Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/ui-inner-html-notify.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': patch
---

Improves `innerHTML` performance by skipping render notifications for nodes built before they are inserted
20 changes: 19 additions & 1 deletion packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ export let createParsedElement: (
namespaceURI: string,
) => Element;

/**
* Runs `build` without change notifications, for nodes built detached. Layout replays only elements it has
* already opened, so marks on new nodes go unused; inserting the result notifies as usual.
*/
export let buildDetached: <T>(document: Document, build: () => T) => T;

const NODE_TYPE_NAMES = [
'ELEMENT_NODE',
'ATTRIBUTE_NODE',
Expand Down Expand Up @@ -356,10 +362,20 @@ export class Document extends Node {

readonly #notify: (nodes: Iterable<Node>) => void;
#factory: (...params: ConstructorParameters<typeof Element>) => Element;
#buildingDetached = false;

static {
createParsedElement = (document, localName, namespaceURI) =>
document.#createElement(localName, { namespaceURI, prefix: null });
buildDetached = (document, build) => {
const previous = document.#buildingDetached;
document.#buildingDetached = true;
try {
return build();
} finally {
document.#buildingDetached = previous;
}
};
}

constructor(
Expand All @@ -373,7 +389,9 @@ export class Document extends Node {
}

override notify(nodes: Iterable<Node>): void {
this.#notify(nodes);
if (!this.#buildingDetached) {
this.#notify(nodes);
}
}

get nodeType(): number {
Expand Down
39 changes: 39 additions & 0 deletions packages/ui/src/layout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { close, createTerm, open, pack, text, type Op } from '@bomb.sh/tty';
import { assert, describe, expect, it, vi } from 'vitest';
import { createHTMLDocument } from './dom.ts';
import { Layout } from './layout.ts';
import { RenderApi } from './render.ts';

describe('Layout', () => {
it('replays unchanged subtrees without reading their children', async () => {
Expand Down Expand Up @@ -52,6 +53,44 @@ describe('Layout', () => {
expect(term.render(ops).errors).toEqual([]);
});

it('lays out content replaced by innerHTML and replays its untouched siblings', async () => {
const controller = new AbortController();
const render = new RenderApi(controller.signal);
const frames = render[Symbol.asyncIterator]();
const document = createHTMLDocument((nodes) => render.request(nodes));
const root = document.createElement('document');
const kept = document.createElement('document');
const host = document.createElement('document');
kept.appendChild(document.createTextNode('kept'));
host.innerHTML = '<document>old</document>';
root.appendChild(kept);
root.appendChild(host);
document.body!.appendChild(root);
const layout = new Layout(root);
const term = await createTerm({ width: 80, height: 24 });
const reference = await createTerm({ width: 80, height: 24 });
await frames.next();
const initial = [...layout.layout()];
let result = term.render(initial);
reference.render(initial);

for (const markup of [
'<document>new <document>nested</document></document><document>sibling</document>',
'<document>again</document>',
]) {
host.innerHTML = markup;
const { value: changes } = await frames.next();
assert(changes);
const ops = [...layout.layout({ changes, info: result.info })];
expect(ops).toContainEqual(result.info.get('DOCUMENT: 1')!.replay);
result = term.render(ops);
const expected = reference.render([...layout.layout()]);
expect(result.errors).toEqual([]);
expect(result.output).toEqual(expected.output);
}
controller.abort();
});

it('lays out uncached elements and falls back when render info is missing', async () => {
const document = createHTMLDocument(() => {});
const root = document.createElement('document');
Expand Down
14 changes: 10 additions & 4 deletions packages/ui/src/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,20 @@ describe('innerHTML setter', () => {
expect(element.attributes[0]).toMatchObject({ name: 'a:b', prefix: null });
});

it('notifies the document so a connected UI re-renders', () => {
it('notifies for the swap only, not for nodes built while detached', () => {
const notify = vi.fn<(nodes: Iterable<Node>) => void>();
const document = createHTMLDocument(notify);
const host = document.body!;
host.innerHTML = '<p>old</p>';
notify.mockClear();
host.innerHTML = '<span>hi</span>';
const notified = notify.mock.calls.flatMap(([nodes]) => [...nodes]);
expect(notified).toContain(host);
host.innerHTML = '<div id="top"><span class="nested">hi</span></div>';
const notified = new Set(notify.mock.calls.flatMap(([nodes]) => [...nodes]));
const top = host.firstChild!;
const nested = top.firstChild!;
expect(notified.has(host)).toBe(true);
expect(notified.has(top)).toBe(true);
expect(notified.has(nested)).toBe(false);
expect(notified.has(nested.firstChild!)).toBe(false);
});

it('treats null as the empty string', () => {
Expand Down
7 changes: 3 additions & 4 deletions packages/ui/src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { asciiLowercase } from './ascii.ts';
import {
Attr,
buildDetached,
createParsedElement,
type Document,
type DocumentFragment,
Expand All @@ -25,10 +26,8 @@ export function parseFragment(context: Element, html: string): DocumentFragment
if (document instanceof XMLDocument) {
throw new DOMException('XML fragment parsing is not supported', 'NotSupportedError');
}
return parseHTMLFragment(html, {
context: fragmentContext(context),
sink: createSink(document),
}) as DocumentFragment;
const options = { context: fragmentContext(context), sink: createSink(document) };
return buildDetached(document, () => parseHTMLFragment(html, options)) as DocumentFragment;
}

function fragmentContext(element: Element): FragmentContext {
Expand Down
Loading