Skip to content

Commit

Permalink
Render dom elements
Browse files Browse the repository at this point in the history
  • Loading branch information
pomber committed May 21, 2017
1 parent 551e350 commit fc4d360
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/reconciler.js
Original file line number Diff line number Diff line change
@@ -1 +1,29 @@
export function render(element, container) {}
export function render(element, parentDom) {
const { type, props } = element;

// Create DOM element
const isTextElement = type === "TEXT ELEMENT";
const dom = isTextElement
? document.createTextNode("")
: document.createElement(type);

// Add event listeners
const isListener = name => name.startsWith("on");
Object.keys(props).filter(isListener).forEach(name => {
const eventType = name.toLowerCase().substring(2);
dom.addEventListener(eventType, props[name]);
});

// Set properties
const isAttribute = name => !isListener(name) && name != "children";
Object.keys(props).filter(isAttribute).forEach(name => {
dom[name] = props[name];
});

// Render children
const childElements = props.children || [];
childElements.forEach(childElement => render(childElement, dom));

// Append to parent
parentDom.appendChild(dom);
}
70 changes: 70 additions & 0 deletions test/00.render-dom-elements.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import test from "ava";
import browserEnv from "browser-env";
import { render } from "../src/didact";

// Create document global var
browserEnv(["document"]);

test.beforeEach(t => {
const root = document.createElement("div");
document.body.appendChild(root);
t.context.root = root;
});

test.afterEach.always(t => {
const root = t.context.root;
root.innerHTML = "";
document.body.removeChild(root);
});

test("render div", t => {
const root = t.context.root;
const element = {
type: "div",
props: {}
};
render(element, root);
t.is(root.innerHTML, "<div></div>");
});

test("render div with children", t => {
const root = t.context.root;
const element = {
type: "div",
props: {
children: [
{ type: "b", props: {} },
{ type: "a", props: { href: "foo" } }
]
}
};
render(element, root);
t.is(root.innerHTML, '<div><b></b><a href="foo"></a></div>');
});

test("render div with props", t => {
const root = t.context.root;
const element = {
type: "div",
props: { id: "foo" }
};
render(element, root);
t.is(root.innerHTML, '<div id="foo"></div>');
});

test("render span with text child", t => {
const root = t.context.root;
const element = {
type: "span",
props: {
children: [
{
type: "TEXT ELEMENT",
props: { nodeValue: "Foo" }
}
]
}
};
render(element, root);
t.is(root.innerHTML, "<span>Foo</span>");
});

0 comments on commit fc4d360

Please sign in to comment.