Skip to content
Merged
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-detect-terminal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': patch
---

Updates `createUI` to detect terminal color support, so colors render as truecolor where supported and fall back to the 256- or 16-color palette elsewhere
5 changes: 5 additions & 0 deletions .changeset/ui-element-replay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': patch
---

Improves incremental rendering by replaying unchanged element subtrees with TTY 0.12.0. Solid borders without a `border-color` now draw in the terminal's default foreground instead of reserving empty space.
10 changes: 9 additions & 1 deletion examples/basic/src/app.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createTestUI } from '../../../packages/ui/test/ui.ts';
import { createApp } from './app.ts';

Expand All @@ -13,6 +13,14 @@ const panel = [
];

describe('basic example', () => {
beforeEach(() => {
vi.stubEnv('COLORTERM', 'truecolor');
});

afterEach(() => {
vi.unstubAllEnvs();
});

it('renders the original panel with styled labels and inherited value colors', async () => {
await using ui = await createTestUI({ cols: 32, rows: 9 });
const { document, terminal } = ui;
Expand Down
31 changes: 16 additions & 15 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ export abstract class Node implements EventTarget {
}
}

protected notify(): void {
this.ownerDocument?.notify();
protected notify(nodes: Iterable<Node>): void {
this.ownerDocument?.notify(nodes);
}

addEventListener(
Expand Down Expand Up @@ -209,7 +209,7 @@ export abstract class Node implements EventTarget {
this.#childNodes.splice(currentIndex, 1);
node.#parentNode = null;

this.notify();
this.notify([this]);
return node;
}

Expand Down Expand Up @@ -258,7 +258,8 @@ export abstract class Node implements EventTarget {
else this.#childNodes.push(node);

node.#parentNode = this;
this.notify();
// Mark the new parent even if the child was already dirty while detached.
this.notify([this, node]);

return node;
}
Expand Down Expand Up @@ -288,7 +289,7 @@ export class DOMImplementation {
throw new TypeError('createDocument requires a DocumentType or null for its doctype');
}

const document = new XMLDocument(() => this.#document.notify());
const document = new XMLDocument((nodes) => this.#document.notify(nodes));
const element = name === '' ? null : document.createElementNS(namespaceURI, name);
if (doctype !== null) {
document.appendChild(doctype);
Expand All @@ -300,7 +301,7 @@ export class DOMImplementation {
}

createHTMLDocument(title?: string): HTMLDocument {
return createHTMLDocument(() => this.#document.notify(), title);
return createHTMLDocument((nodes) => this.#document.notify(nodes), title);
}

// oxlint-disable-next-line bombshell-dev/max-params -- DOMImplementation.createDocumentType requires three positional arguments.
Expand Down Expand Up @@ -328,11 +329,11 @@ export class Document extends Node {
return null;
}

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

constructor(
notify: () => void,
notify: Node['notify'],
factory?: (...params: ConstructorParameters<typeof Element>) => Element,
) {
super(null);
Expand All @@ -341,8 +342,8 @@ export class Document extends Node {
this.implementation = new DOMImplementation(this);
}

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

get nodeType(): number {
Expand Down Expand Up @@ -571,7 +572,7 @@ export class Element extends Node {
{ namespaceURI = HTML_NS, prefix = null }: Partial<ElementNamespace> = {},
) {
super(owner);
this.style = new StyleDeclaration(() => this.notify());
this.style = new StyleDeclaration(() => this.notify([this]));
this.localName = localName;
this.namespaceURI = namespaceURI;
this.prefix = prefix;
Expand Down Expand Up @@ -730,8 +731,8 @@ export class Attr extends Node {
this.#value = value;
}

protected override notify(): void {
this.ownerElement?.ownerDocument.notify();
protected override notify(nodes: Iterable<Node>): void {
this.ownerElement?.ownerDocument.notify(nodes);
}

get nodeType(): number {
Expand All @@ -755,7 +756,7 @@ export class Attr extends Node {
if (this.#value !== normal) {
this.#value = normal;
attributeChanged(this, normal);
this.notify();
this.notify([this.ownerElement ?? this]);
}
}

Expand Down Expand Up @@ -785,7 +786,7 @@ export abstract class CharacterData extends Node {
const normal = data === null ? '' : String(data);
if (normal !== this.data) {
this.#data = normal;
this.notify();
this.notify([this]);
}
}

Expand Down
149 changes: 138 additions & 11 deletions packages/ui/src/layout.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,137 @@
import { close, open, rgba, snapshot, text, type Op } from '@bomb.sh/tty';
import { assert, describe, expect, it } from 'vitest';
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';

describe('Layout', () => {
it('replays unchanged subtrees without reading their children', async () => {
const document = createHTMLDocument(() => {});
const root = document.createElement('document');
document.body!.appendChild(root);
const unchanged = document.createElement('document');
const changed = document.createElement('document');
const value = document.createTextNode('before');
unchanged.appendChild(document.createTextNode('unchanged'));
changed.appendChild(value);
root.appendChild(unchanged);
root.appendChild(changed);
const layout = new Layout(root);
const term = await createTerm({ width: 80, height: 24 });
const reference = await createTerm({ width: 80, height: 24 });
const initial = [...layout.layout()];
let result = term.render(initial);
reference.render(initial);
const children = vi.spyOn(unchanged.childNodes, Symbol.iterator);

for (const data of ['after', 'again']) {
value.data = data;
const ops = [
...layout.layout({ changes: new Set([value, changed, root]), info: result.info }),
];
expect(children).not.toHaveBeenCalled();
expect(ops).toEqual([
open('DOCUMENT: 0'),
result.info.get('DOCUMENT: 1')!.replay,
open('DOCUMENT: 2'),
text(data),
close(),
close(),
]);
result = term.render(ops);
const expected = reference.render([...layout.layout()]);
expect(result.errors).toEqual([]);
expect(result.output).toEqual(expected.output);
for (const id of ['DOCUMENT: 0', 'DOCUMENT: 1', 'DOCUMENT: 2']) {
expect(result.info.get(id)?.bounds).toEqual(expected.info.get(id)?.bounds);
}
children.mockClear();
}
children.mockRestore();
const ops = [...layout.layout({ changes: new Set(), info: result.info })];
expect(ops).toEqual([result.info.get('DOCUMENT: 0')!.replay]);
expect(term.render(ops).errors).toEqual([]);
});

it('lays out uncached elements and falls back when render info is missing', async () => {
const document = createHTMLDocument(() => {});
const root = document.createElement('document');
document.body!.appendChild(root);
const layout = new Layout(root);
const term = await createTerm({ width: 80, height: 24 });
const first = term.render([...layout.layout()]);
const child = document.createElement('document');
child.appendChild(document.createTextNode('new'));
root.appendChild(child);
const expected = [open('DOCUMENT: 0'), open('DOCUMENT: 1'), text('new'), close(), close()];

expect([...layout.layout({ changes: new Set([root]), info: first.info })]).toEqual(expected);
expect([...layout.layout({ changes: new Set(), info: { get: () => undefined } })]).toEqual(
expected,
);
});

it('replays unchanged subtrees that inherit a changed ancestor color', async () => {
const document = createHTMLDocument(() => {});
const root = document.createElement('document');
document.body!.appendChild(root);
root.style.color = 'red';
const inherited = document.createElement('document');
inherited.style.borderStyle = 'solid';
const span = document.createElement('span');
span.appendChild(document.createTextNode('inherited'));
inherited.appendChild(span);
const explicit = document.createElement('document');
explicit.style.color = 'lime';
explicit.appendChild(document.createTextNode('explicit'));
root.appendChild(inherited);
root.appendChild(explicit);
const layout = new Layout(root);
const term = await createTerm({ width: 80, height: 24 });
const reference = await createTerm({ width: 80, height: 24 });
const initial = [...layout.layout()];
let result = term.render(initial);
reference.render(initial);

for (const color of ['transparent', 'blue'] as const) {
root.style.color = color;
const ops = [...layout.layout({ changes: new Set([root]), info: result.info })];
expect(ops).toEqual([
open('DOCUMENT: 0', { color }),
result.info.get('DOCUMENT: 1')!.replay,
result.info.get('DOCUMENT: 2')!.replay,
close(),
]);
result = term.render(ops);
const expected = reference.render([...layout.layout()]);
expect(result.errors).toEqual([]);
expect(result.output).toEqual(expected.output);
}
});

it('rebuilds elements when switching between flex and inline display', async () => {
const document = createHTMLDocument(() => {});
const root = document.createElement('document');
const child = document.createElement('document');
child.appendChild(document.createTextNode('content'));
root.appendChild(child);
const layout = new Layout(root);
const term = await createTerm({ width: 80, height: 24 });
const flex = [open('DOCUMENT: 0'), open('DOCUMENT: 1'), text('content'), close(), close()];
let result = term.render([...layout.layout()]);

child.style.display = 'inline';
let ops = [...layout.layout({ changes: new Set([root, child]), info: result.info })];
expect(ops).toEqual([open('DOCUMENT: 0'), text('content'), close()]);
result = term.render(ops);
expect(result.errors).toEqual([]);
expect(result.info.get('DOCUMENT: 1')).toBeUndefined();

child.style.display = 'flex';
ops = [...layout.layout({ changes: new Set([root, child]), info: result.info })];
expect(ops).toEqual(flex);
expect(term.render(ops).errors).toEqual([]);
});

it('groups adjacent text around nested and empty elements and keeps IDs stable', () => {
const document = createHTMLDocument(() => {});
const root = document.createElement('document');
Expand Down Expand Up @@ -31,7 +159,6 @@ describe('Layout', () => {

expect([...layout.layout()]).toEqual(expected);
expect([...layout.layout()]).toEqual(expected);
expect([...layout.layout(child)]).toEqual([open('DOCUMENT: 1'), text('inside'), close()]);
});

it('lays out a deeply nested tree without recursive traversal', () => {
Expand Down Expand Up @@ -119,22 +246,22 @@ describe('sparse layout options', () => {
expect(ops).toEqual([
open(id, {
layout: { direction: 'ttb', gap: 2, padding: { left: 2 } },
border: { color: rgba(0, 0, 255), left: 1 },
border: { color: 'blue', left: 1 },
}),
close(),
]);
expect(packed(ops)).toEqual(
packed([
open(id, {
layout: { direction: 'ttb', gap: 2, padding: { top: 0, right: 0, bottom: 0, left: 2 } },
border: { color: rgba(0, 0, 255), top: 0, right: 0, bottom: 0, left: 1 },
border: { color: 'blue', top: 0, right: 0, bottom: 0, left: 1 },
}),
close(),
]),
);
});

it('omits terminal-default text color but preserves inherited packed zero', () => {
it('leaves text color to inheritance from the containing element', () => {
const document = createHTMLDocument(() => {});
const body = document.body!;
const span = document.createElement('span');
Expand All @@ -147,9 +274,9 @@ describe('sparse layout options', () => {
expect(ops).toEqual([open(id), text('direct'), text('inline'), close()]);
body.style.color = 'transparent';
expect([...layout.layout()]).toEqual([
open(id),
text('direct', { color: 0 }),
text('inline', { color: 0 }),
open(id, { color: 'transparent' }),
text('direct'),
text('inline'),
close(),
]);
});
Expand All @@ -162,6 +289,6 @@ function rootId(ops: Op[]): string {
}

function packed(ops: Op[]): Uint8Array {
const result = snapshot(ops) as { data: Uint8Array };
return result.data;
const buffer = new ArrayBuffer(4096);
return new Uint8Array(buffer, 0, pack(ops, buffer, 0) * 4);
}
Loading
Loading