Skip to content

Commit

Permalink
layout: basic layout caching and invalidation
Browse files Browse the repository at this point in the history
  • Loading branch information
CanadaHonk committed Oct 25, 2023
1 parent b1b8324 commit da99259
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
11 changes: 11 additions & 0 deletions engine/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ export class Node {
}
}

allChildren() {
let o = [];

for (const x of this.children) {
o.push(x);
o = o.concat(x.allChildren());
}

return o;
}

get id() {
return this.attrs.id;
}
Expand Down
25 changes: 19 additions & 6 deletions engine/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ const defaultFontSize = 16; // px
const byPtr = {};
export class LayoutNode extends Node {
renderer = null;

cache = {};
constructor(node, renderer) {
super();
Object.assign(this, { ...node, renderer });
Expand All @@ -59,15 +61,14 @@ export class LayoutNode extends Node {

const cache = k => {
const f = this[k].bind(this);
let cached;

this[k] = function() {
if (cached) return cached;
return cached = f.apply(this, arguments);
if (this.cache[k]) return this.cache[k];
return this.cache[k] = f.apply(this, arguments);
}.bind(this);
};

// cache('x'); cache('y'); cache('width'); cache('height');

cache('x'); cache('y'); cache('width'); cache('height');
if (this.tagName === 'img') this.image();
}

Expand Down Expand Up @@ -559,6 +560,8 @@ export class LayoutNode extends Node {
this._image.style.display = 'none';
document.body.appendChild(this._image);

this._image.onload = () => this.invalidateCaches();

return this._image;
}

Expand Down Expand Up @@ -626,10 +629,20 @@ export class LayoutNode extends Node {
this.appendChild(text);
}

invalidateCaches() {
invalidateCaches(sub = false) {
super.invalidateCaches();

// just invalidate the entire document
// todo: not do this
if (!sub) {
this.document.invalidateCaches(true);
for (const x of this.document.allChildren()) x.invalidateCaches(true);
}

// if (this.parent) this.parent.invalidateCaches();

this._cssCache = null;
this.cache = {};
}
}

Expand Down

0 comments on commit da99259

Please sign in to comment.