Skip to content

Commit

Permalink
Returning and Unmounting
Browse files Browse the repository at this point in the history
  • Loading branch information
brainkim committed Oct 12, 2020
1 parent ce8a6b8 commit 274b914
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion crank.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,23 @@ function updateChildren(renderer, host, el, newChildren) {
const oldChild = oldChildren[i];
let newChild = narrow(newChildren[i]);
const [child, value] = diff(renderer, host, oldChild, newChild);
if (oldChild instanceof Element && child !== oldChild) {
unmount(renderer, oldChild);
}

children.push(child);
if (value) {
values.push(value);
}
}

el._children = unwrap(children);
for (const oldChild of oldChildren.slice(length)) {
if (oldChild instanceof Element) {
unmount(renderer, oldChild);
}
}

return commit(renderer, el, normalize(values));
}

Expand All @@ -261,6 +271,18 @@ function commit(renderer, el, values) {
return el._node;
}

function unmount(renderer, el) {
if (typeof el.tag === "function") {
unmountCtx(el._ctx);
}

for (const child of wrap(el._children)) {
if (child instanceof Element) {
unmount(renderer, child);
}
}
}

class Context {
constructor(renderer, host, el) {
this._renderer = renderer;
Expand All @@ -270,6 +292,7 @@ class Context {

// flags
this._isUpdating = false;
this._isDone = false;
}

refresh() {
Expand All @@ -278,7 +301,9 @@ class Context {
}

function stepCtx(ctx) {
if (!ctx._iter) {
if (ctx._isDone) {
return getValue(ctx._el);
} else if (!ctx._iter) {
const value = ctx._el.tag.call(ctx, ctx._el.props);
if (isIteratorLike(value)) {
ctx._iter = value;
Expand All @@ -288,6 +313,10 @@ function stepCtx(ctx) {
}

const iteration = ctx._iter.next();
if (iteration.done) {
ctx._isDone = true;
}

return updateCtxChildren(ctx, iteration.value);
}

Expand All @@ -312,3 +341,12 @@ function commitCtx(ctx, values) {
ctx._isUpdating = false;
return unwrap(values);
}

function unmountCtx(ctx) {
if (!ctx._isDone) {
ctx._isDone = true;
if (ctx._iterator && typeof ctx._iterator.return === "function") {
ctx._iterator.return();
}
}
}

0 comments on commit 274b914

Please # to comment.