Skip to content

Commit 8eb7ffd

Browse files
committed
Brute force reconciliation
1 parent a174bf8 commit 8eb7ffd

File tree

2 files changed

+53
-5
lines changed

2 files changed

+53
-5
lines changed

src/reconciler.js

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,24 @@
1-
export function render(element, parentDom) {
1+
let rootInstance = null;
2+
3+
export function render(element, container) {
4+
const prevInstance = rootInstance;
5+
const nextInstance = reconcile(container, prevInstance, element);
6+
rootInstance = nextInstance;
7+
}
8+
9+
function reconcile(parentDom, instance, element) {
10+
if (instance == null) {
11+
const newInstance = instantiate(element);
12+
parentDom.appendChild(newInstance.dom);
13+
return newInstance;
14+
} else {
15+
const newInstance = instantiate(element);
16+
parentDom.replaceChild(newInstance.dom, instance.dom);
17+
return newInstance;
18+
}
19+
}
20+
21+
function instantiate(element) {
222
const { type, props } = element;
323

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

23-
// Render children
43+
// Instantiate and append children
2444
const childElements = props.children || [];
25-
childElements.forEach(childElement => render(childElement, dom));
45+
const childInstances = childElements.map(instantiate);
46+
const childDoms = childInstances.map(childInstance => childInstance.dom);
47+
childDoms.forEach(childDom => dom.appendChild(childDom));
2648

27-
// Append to parent
28-
parentDom.appendChild(dom);
49+
const instance = { dom, element, childInstances };
50+
return instance;
2951
}

test/02.re-render-element.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import test from "ava";
2+
import browserEnv from "browser-env";
3+
/** @jsx createElement */
4+
import { render, createElement } from "../src/didact";
5+
6+
// Create document global var
7+
browserEnv(["document"]);
8+
9+
test.beforeEach(t => {
10+
let root = document.getElementById("root");
11+
if (!root) {
12+
root = document.createElement("div");
13+
root.id = "root";
14+
document.body.appendChild(root);
15+
}
16+
t.context.root = root;
17+
});
18+
19+
test("render jsx div", t => {
20+
const root = t.context.root;
21+
const element = <div>Foo</div>;
22+
render(element, root);
23+
t.is(root.innerHTML, "<div>Foo</div>");
24+
render(element, root);
25+
t.is(root.innerHTML, "<div>Foo</div>");
26+
});

0 commit comments

Comments
 (0)