Skip to content

Commit

Permalink
Brute force reconciliation
Browse files Browse the repository at this point in the history
  • Loading branch information
pomber committed May 21, 2017
1 parent a174bf8 commit 8eb7ffd
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/reconciler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,24 @@
export function render(element, parentDom) {
let rootInstance = null;

export function render(element, container) {
const prevInstance = rootInstance;
const nextInstance = reconcile(container, prevInstance, element);
rootInstance = nextInstance;
}

function reconcile(parentDom, instance, element) {
if (instance == null) {
const newInstance = instantiate(element);
parentDom.appendChild(newInstance.dom);
return newInstance;
} else {
const newInstance = instantiate(element);
parentDom.replaceChild(newInstance.dom, instance.dom);
return newInstance;
}
}

function instantiate(element) {
const { type, props } = element;

// Create DOM element
Expand All @@ -20,10 +40,12 @@ export function render(element, parentDom) {
dom[name] = props[name];
});

// Render children
// Instantiate and append children
const childElements = props.children || [];
childElements.forEach(childElement => render(childElement, dom));
const childInstances = childElements.map(instantiate);
const childDoms = childInstances.map(childInstance => childInstance.dom);
childDoms.forEach(childDom => dom.appendChild(childDom));

// Append to parent
parentDom.appendChild(dom);
const instance = { dom, element, childInstances };
return instance;
}
26 changes: 26 additions & 0 deletions test/02.re-render-element.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import test from "ava";
import browserEnv from "browser-env";
/** @jsx createElement */
import { render, createElement } from "../src/didact";

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

test.beforeEach(t => {
let root = document.getElementById("root");
if (!root) {
root = document.createElement("div");
root.id = "root";
document.body.appendChild(root);
}
t.context.root = root;
});

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

0 comments on commit 8eb7ffd

Please sign in to comment.