diff --git a/.changeset/ui-detect-terminal.md b/.changeset/ui-detect-terminal.md new file mode 100644 index 00000000..e4d23cba --- /dev/null +++ b/.changeset/ui-detect-terminal.md @@ -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 diff --git a/.changeset/ui-element-replay.md b/.changeset/ui-element-replay.md new file mode 100644 index 00000000..ef8489c9 --- /dev/null +++ b/.changeset/ui-element-replay.md @@ -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. diff --git a/examples/basic/src/app.test.ts b/examples/basic/src/app.test.ts index 5ded942f..72190e93 100644 --- a/examples/basic/src/app.test.ts +++ b/examples/basic/src/app.test.ts @@ -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'; @@ -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; diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 512f198c..7d1c19c2 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -77,8 +77,8 @@ export abstract class Node implements EventTarget { } } - protected notify(): void { - this.ownerDocument?.notify(); + protected notify(nodes: Iterable): void { + this.ownerDocument?.notify(nodes); } addEventListener( @@ -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; } @@ -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; } @@ -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); @@ -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. @@ -328,11 +329,11 @@ export class Document extends Node { return null; } - readonly #notify: () => void; + readonly #notify: (nodes: Iterable) => void; #factory: (...params: ConstructorParameters) => Element; constructor( - notify: () => void, + notify: Node['notify'], factory?: (...params: ConstructorParameters) => Element, ) { super(null); @@ -341,8 +342,8 @@ export class Document extends Node { this.implementation = new DOMImplementation(this); } - override notify(): void { - this.#notify(); + override notify(nodes: Iterable): void { + this.#notify(nodes); } get nodeType(): number { @@ -571,7 +572,7 @@ export class Element extends Node { { namespaceURI = HTML_NS, prefix = null }: Partial = {}, ) { super(owner); - this.style = new StyleDeclaration(() => this.notify()); + this.style = new StyleDeclaration(() => this.notify([this])); this.localName = localName; this.namespaceURI = namespaceURI; this.prefix = prefix; @@ -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): void { + this.ownerElement?.ownerDocument.notify(nodes); } get nodeType(): number { @@ -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]); } } @@ -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]); } } diff --git a/packages/ui/src/layout.test.ts b/packages/ui/src/layout.test.ts index d365e326..25e67b2b 100644 --- a/packages/ui/src/layout.test.ts +++ b/packages/ui/src/layout.test.ts @@ -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'); @@ -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', () => { @@ -119,7 +246,7 @@ 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(), ]); @@ -127,14 +254,14 @@ describe('sparse layout options', () => { 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'); @@ -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(), ]); }); @@ -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); } diff --git a/packages/ui/src/layout.ts b/packages/ui/src/layout.ts index 533e0494..30ab49aa 100644 --- a/packages/ui/src/layout.ts +++ b/packages/ui/src/layout.ts @@ -1,12 +1,16 @@ /* oxlint-disable bombshell-dev/max-params -- Layout helpers pass the element and rendering context explicitly. */ -import { close, open, rgba, text, type Op } from '@bomb.sh/tty'; -import { convert } from 'hueful'; -import { Element, Text } from './dom.ts'; +import { close, open, text, type Op, type RenderInfo } from '@bomb.sh/tty'; +import { Element, Text, type Node } from './dom.ts'; import type { StyleValues } from './style.ts'; type TTYContainerOptions = NonNullable[1]>; type TTYTextOptions = NonNullable[1]>; +interface LayoutOptions { + changes?: ReadonlySet; + info?: RenderInfo; +} + export class Layout { #lastIdNumber = 0; #stableIds = new WeakMap(); @@ -16,28 +20,33 @@ export class Layout { this.#root = root; } - /** Serialize an element to TTY Ops. */ - *layout(element: Element = this.#root, inheritedColor?: number): IterableIterator { + /** Serialize the root to TTY Ops, replaying subtrees absent from changes. */ + *layout(options: LayoutOptions = {}): IterableIterator { + const element = this.#root; const style = computeStyle(element); - const color = resolveColorValue(style.color.value, inheritedColor); if (style.display.value === 'inline') { const content = collectInlineText(element); if (content !== '') { - yield text(content, ttyTextOptions(color)); + yield text(content, ttyTextOptions(style)); } return; } - const stack = [{ children: element.childNodes[Symbol.iterator](), color }]; + const replay = this.#replay(element, options); + if (replay) { + yield replay; + return; + } + + const stack = [element.childNodes[Symbol.iterator]()]; try { - yield this.#open(element, style, color); + yield this.#open(element, style); let content = ''; while (stack.length > 0) { - const frame = stack[stack.length - 1]!; - const next = frame.children.next(); + const next = stack[stack.length - 1]!.next(); if (next.done) { if (content !== '') { - yield text(content, ttyTextOptions(frame.color)); + yield text(content); content = ''; } stack.pop(); @@ -49,19 +58,23 @@ export class Layout { content += child.data; } else if (child instanceof Element) { if (content !== '') { - yield text(content, ttyTextOptions(frame.color)); + yield text(content); content = ''; } const childStyle = computeStyle(child); - const childColor = resolveColorValue(childStyle.color.value, frame.color); if (childStyle.display.value === 'inline') { const inlineContent = collectInlineText(child); if (inlineContent !== '') { - yield text(inlineContent, ttyTextOptions(childColor)); + yield text(inlineContent, ttyTextOptions(childStyle)); } } else { - stack.push({ children: child.childNodes[Symbol.iterator](), color: childColor }); - yield this.#open(child, childStyle, childColor); + const childReplay = this.#replay(child, options); + if (childReplay) { + yield childReplay; + } else { + stack.push(child.childNodes[Symbol.iterator]()); + yield this.#open(child, childStyle); + } } } } @@ -73,13 +86,19 @@ export class Layout { } } - #open(element: Element, style: StyleValues, color?: number): Op { + #replay(element: Element, { changes, info }: LayoutOptions): Op | undefined { + if (!changes || changes.has(element) || !info) return; + const id = this.#stableIds.get(element); + return id ? info.get(id)?.replay : undefined; + } + + #open(element: Element, style: StyleValues): Op { let stableId = this.#stableIds.get(element); if (!stableId) { stableId = `${element.nodeName}: ${this.#lastIdNumber++}`; this.#stableIds.set(element, stableId); } - return open(stableId, ttyContainerOptions(style, color)); + return open(stableId, ttyContainerOptions(style)); } } @@ -100,29 +119,16 @@ function collectInlineText(element: Element): string { return content; } -/** - * Convert a color which is stored internally as a hueful `ParseResult` into - * an RGB numeric value which is what TTY speaks natively. - */ -function resolveColorValue( - value: StyleValues['color']['value'], - inheritedColor?: number, -): number | undefined { - if (value === 'currentColor') { - return inheritedColor; - } - const [r, g, b, alpha = 1] = convert(value.space, 'rgb', value.value); - const channel = (component: number): number => Math.round(Math.max(0, Math.min(255, component))); - return rgba(channel(r), channel(g), channel(b), channel(alpha * 255)); -} - /** * Map a layout container element's styles to TTY options. The mapping is * sparse so that even though we have a completely known computed style, * we only send through to WASM enough information to render. */ -function ttyContainerOptions(style: StyleValues, color?: number): TTYContainerOptions { +function ttyContainerOptions(style: StyleValues): TTYContainerOptions { const props: TTYContainerOptions = {}; + if (style.color.value !== 'currentColor') { + props.color = style.color.representation; + } const layout: NonNullable = {}; if (style.flexDirection.value === 'column') { layout.direction = 'ttb'; @@ -131,10 +137,10 @@ function ttyContainerOptions(style: StyleValues, color?: number): TTYContainerOp layout.gap = style.gap.value; } - let top = style.paddingTop.value; - let right = style.paddingRight.value; - let bottom = style.paddingBottom.value; - let left = style.paddingLeft.value; + const top = style.paddingTop.value; + const right = style.paddingRight.value; + const bottom = style.paddingBottom.value; + const left = style.paddingLeft.value; const borderTop = style.borderTopWidth.value; const borderRight = style.borderRightWidth.value; const borderBottom = style.borderBottomWidth.value; @@ -143,30 +149,21 @@ function ttyContainerOptions(style: StyleValues, color?: number): TTYContainerOp style.borderStyle.value === 'solid' && (borderTop || borderRight || borderBottom || borderLeft) ) { - const borderColor = resolveColorValue(style.borderColor.value, color); - // TTY requires an explicit border color. Keep the space when it cannot draw the border. - if (borderColor !== undefined) { - props.border = { color: borderColor }; - if (borderTop !== 0) { - props.border.top = borderTop; - } - if (borderRight !== 0) { - props.border.right = borderRight; - } - if (borderBottom !== 0) { - props.border.bottom = borderBottom; - } - if (borderLeft !== 0) { - props.border.left = borderLeft; - } - } else { - // TTY cannot draw borders with the terminal-default foreground yet. - // Reserve their space with padding until https://github.com/bombshell-dev/tty/issues/155 - // is implemented; then emit the border and remove this fallback. - top += borderTop; - right += borderRight; - bottom += borderBottom; - left += borderLeft; + props.border = {}; + if (style.borderColor.value !== 'currentColor') { + props.border.color = style.borderColor.representation; + } + if (borderTop !== 0) { + props.border.top = borderTop; + } + if (borderRight !== 0) { + props.border.right = borderRight; + } + if (borderBottom !== 0) { + props.border.bottom = borderBottom; + } + if (borderLeft !== 0) { + props.border.left = borderLeft; } } @@ -192,8 +189,8 @@ function ttyContainerOptions(style: StyleValues, color?: number): TTYContainerOp return props; } -function ttyTextOptions(color?: number): TTYTextOptions { - return color === undefined ? {} : { color }; +function ttyTextOptions(style: StyleValues): TTYTextOptions { + return style.color.value === 'currentColor' ? {} : { color: style.color.representation }; } function computeStyle(element: Element): StyleValues { diff --git a/packages/ui/src/named-node-map.ts b/packages/ui/src/named-node-map.ts index 7730f459..87185690 100644 --- a/packages/ui/src/named-node-map.ts +++ b/packages/ui/src/named-node-map.ts @@ -197,7 +197,7 @@ export class NamedNodeMap { #changed(): void { if (this.#exposed) this.#reflect(); - this.#ownerElement.ownerDocument.notify(); + this.#ownerElement.ownerDocument.notify([this.#ownerElement]); } /** Rebuilds the indexed and named views from the ordered list. */ diff --git a/packages/ui/src/render.test.ts b/packages/ui/src/render.test.ts index d071a611..424b1534 100644 --- a/packages/ui/src/render.test.ts +++ b/packages/ui/src/render.test.ts @@ -1,8 +1,110 @@ import { describe, expect, test } from 'vitest'; +import { createHTMLDocument, type Element, type Node } from './dom.ts'; import { RenderApi } from './render.ts'; describe('RenderApi', () => { - test('waits while clean and yields void when requested', async () => { + test('coalesces changed nodes and their ancestors into a fresh set for each frame', async () => { + using fixture = setup(); + const { renderer, iterator } = fixture; + const document = createHTMLDocument((nodes) => renderer.request(nodes)); + const root = document.body!; + const ancestors = [root, document.documentElement!, document]; + await iterator.next(); + const branch = document.createElement('div'); + const text = document.createTextNode('before'); + branch.appendChild(text); + root.appendChild(branch); + text.data = 'after'; + + const first = await iterator.next(); + expect(first.value).toEqual(new Set([text, branch, ...ancestors])); + const next = iterator.next(); + await expectPending(next); + text.data = 'again'; + expect((await next).value).toEqual(new Set([text, branch, ...ancestors])); + const sibling = document.createElement('div'); + root.appendChild(sibling); + expect((await iterator.next()).value).toEqual(new Set([sibling, ...ancestors])); + expect(first.value).toEqual(new Set([text, branch, ...ancestors])); + }); + + test('invalidates both ancestor chains when an element moves and its old parent on removal', async () => { + using fixture = setup(); + const { renderer, iterator } = fixture; + const document = createHTMLDocument((nodes) => renderer.request(nodes)); + const root = document.body!; + const ancestors = [root, document.documentElement!, document]; + const left = document.createElement('div'); + const right = document.createElement('div'); + const child = document.createElement('span'); + root.appendChild(left); + root.appendChild(right); + left.appendChild(child); + await iterator.next(); + + right.appendChild(child); + expect((await iterator.next()).value).toEqual(new Set([left, right, child, ...ancestors])); + expect(left.childNodes).toEqual([]); + expect(child.parentNode).toBe(right); + + right.removeChild(child); + expect((await iterator.next()).value).toEqual(new Set([right, ...ancestors])); + expect(child.parentNode).toBeNull(); + }); + + test('invalidates the new ancestry when inserting a fragment with already-dirty children', async () => { + using fixture = setup(); + const { renderer, iterator } = fixture; + const document = createHTMLDocument((nodes) => renderer.request(nodes)); + await iterator.next(); + const fragment = document.createDocumentFragment(); + const child = document.createElement('div'); + const text = document.createTextNode('added'); + child.appendChild(text); + fragment.appendChild(child); + document.body!.appendChild(fragment); + + expect((await iterator.next()).value).toEqual( + new Set([text, child, fragment, document.body!, document.documentElement!, document]), + ); + expect(fragment.childNodes).toEqual([]); + expect(child.parentNode).toBe(document.body); + }); + + test.each([ + ['attribute update', (element: Element) => element.setAttribute('title', 'after')], + [ + 'attribute value update', + (element: Element) => { + element.getAttributeNode('title')!.value = 'after'; + }, + ], + ['attribute removal', (element: Element) => element.removeAttribute('title')], + [ + 'style property update', + (element: Element) => { + element.style.color = 'blue'; + }, + ], + ['style attribute update', (element: Element) => element.setAttribute('style', 'color: blue')], + ['style attribute removal', (element: Element) => element.removeAttribute('style')], + ])('invalidates the owning element and its ancestors after %s', async (_, mutate) => { + using fixture = setup(); + const { renderer, iterator } = fixture; + const document = createHTMLDocument((nodes) => renderer.request(nodes)); + const element = document.createElement('div'); + document.body!.appendChild(element); + element.setAttribute('title', 'before'); + element.setAttribute('style', 'color: red'); + await iterator.next(); + + mutate(element); + expect((await iterator.next()).value).toEqual( + new Set([element, document.body!, document.documentElement!, document]), + ); + }); + + test('waits while clean and yields a change set when requested', async () => { using fixture = setup(); const { renderer, iterator } = fixture; const pending = iterator.next(); @@ -10,7 +112,7 @@ describe('RenderApi', () => { await expectPending(pending); renderer.request(); - await expect(pending).resolves.toEqual({ done: false, value: undefined }); + await expect(pending).resolves.toEqual({ done: false, value: new Set() }); }); test('coalesces requests made before delivery without leaving an extra iteration', async () => { @@ -20,7 +122,7 @@ describe('RenderApi', () => { renderer.request(); renderer.request(); - await expect(iterator.next()).resolves.toEqual({ done: false, value: undefined }); + await expect(iterator.next()).resolves.toEqual({ done: false, value: new Set() }); const pending = iterator.next(); await expectPending(pending); controller.abort(); @@ -104,7 +206,7 @@ describe('RenderApi', () => { function setup(): { controller: AbortController; renderer: RenderApi; - iterator: AsyncGenerator; + iterator: AsyncGenerator, void, void>; [Symbol.dispose](): void; } { const controller = new AbortController(); diff --git a/packages/ui/src/render.ts b/packages/ui/src/render.ts index 479f173e..b02e20d0 100644 --- a/packages/ui/src/render.ts +++ b/packages/ui/src/render.ts @@ -1,8 +1,11 @@ +import type { Node } from './dom.ts'; + /** * Drives a single `for await` rendering loop. * * `request()` asks the loop to run. Multiple requests before the iterator - * yields are combined into one pass through the loop. + * yields are combined into one pass through the loop, including all changed + * nodes and their ancestors. Each pass receives its own change-set snapshot. * * The caller renders and awaits its output write inside the loop. Any requests * made during that work cause one more pass after it finishes. @@ -12,6 +15,7 @@ export class RenderApi { #signal: AbortSignal; #requested = Promise.withResolvers(); + #changes = new Set(); constructor(signal: AbortSignal) { this.#signal = signal; @@ -21,20 +25,31 @@ export class RenderApi { } /** Ask the rendering loop to run; repeated pending requests count as one. */ - request(): void { + request(nodes: Iterable = []): void { + for (const node of nodes) { + for (let current: Node | null = node; current; current = current.parentNode) { + if (this.#changes.has(current)) break; + this.#changes.add(current); + } + } this.#requested.resolve(); } - async *[Symbol.asyncIterator](): AsyncGenerator { + async *[Symbol.asyncIterator](): AsyncGenerator, void, void> { while (!this.#signal.aborted) { await this.#requested.promise; if (this.#signal.aborted) { break; } + // Capture the changes that will be part of this frame + const changes = this.#changes; + this.#changes = new Set(); + // Collect requests for the next pass before handing control to the loop. this.#requested = Promise.withResolvers(); - yield; + + yield changes; } } } diff --git a/packages/ui/src/style-rendering.test.ts b/packages/ui/src/style-rendering.test.ts index ee3e06eb..09a40b65 100644 --- a/packages/ui/src/style-rendering.test.ts +++ b/packages/ui/src/style-rendering.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createTestUI } from '../test/ui.ts'; import type { UI } from './ui.ts'; import type { Element } from './dom.ts'; @@ -7,6 +7,14 @@ const green = { r: 0, g: 205, b: 0 }; const blue = { r: 0, g: 0, b: 238 }; describe('style rendering', () => { + beforeEach(() => { + vi.stubEnv('COLORTERM', 'truecolor'); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + it('defaults div to a row with no gap or padding, and repaints when direction changes', async () => { await using ui = await createTestUI({ cols: 12, rows: 4 }); const { document, terminal } = ui; @@ -286,7 +294,7 @@ describe('style rendering', () => { }, ); - it('preserves border space and keeps rendering when the border color is terminal-default', async () => { + it('draws borders in the terminal-default foreground when no color is set', async () => { await using ui = await createTestUI({ cols: 8, rows: 4 }); const { document, terminal } = ui; const box = document.createElement('div'); @@ -294,8 +302,8 @@ describe('style rendering', () => { box.appendChild(document.createTextNode('X')); document.body!.appendChild(box); - await expect.poll(() => terminal.screen.getLines()).toEqual(['', ' X', '', '']); - expect(terminal.getCell(1, 1).fg).toBeNull(); + await expect.poll(() => terminal.screen.getLines()).toEqual(['┌─┐', '│X│', '└─┘', '']); + expect(terminal.getCell(0, 0).fg).toBeNull(); box.style.borderColor = 'rgb(0 0 238)'; await expect.poll(() => terminal.screen.getLines()).toEqual(['┌─┐', '│X│', '└─┘', '']); @@ -303,7 +311,8 @@ describe('style rendering', () => { box.style.borderColor = ''; document.body!.appendChild(label(document, '!')); - await expect.poll(() => terminal.screen.getLines()).toEqual([' !', ' X', '', '']); + await expect.poll(() => terminal.screen.getLines()).toEqual(['┌─┐!', '│X│', '└─┘', '']); + expect(terminal.getCell(0, 0).fg).toBeNull(); }); it('allows terminal-default foreground when every border side has zero width', async () => { diff --git a/packages/ui/src/ui.test.ts b/packages/ui/src/ui.test.ts index 543ce471..008143fc 100644 --- a/packages/ui/src/ui.test.ts +++ b/packages/ui/src/ui.test.ts @@ -3,6 +3,28 @@ import { createTestUI } from '../test/ui.ts'; import { Document } from './dom.ts'; describe('UI', () => { + it('preserves unchanged siblings across updates and attachment of a dirty subtree', async () => { + await using ui = await createTestUI({ cols: 20, rows: 4 }); + const { document, terminal } = ui; + const left = document.createElement('div'); + const right = document.createElement('div'); + const value = document.createTextNode('before'); + left.appendChild(value); + right.appendChild(document.createTextNode('stable')); + document.body!.appendChild(left); + document.body!.appendChild(right); + await expect.poll(() => terminal.screen).toHaveText('beforestable'); + + for (const data of ['after', 'again']) { + value.data = data; + await expect.poll(() => terminal.screen).toHaveText(`${data}stable`); + } + const added = document.createElement('div'); + added.appendChild(document.createTextNode('new')); + document.body!.appendChild(added); + await expect.poll(() => terminal.screen).toHaveText('againstablenew'); + }); + it('renders hello world in the terminal', async () => { await using ui = await createTestUI({ cols: 80, rows: 24 }); const { terminal, document } = ui; diff --git a/packages/ui/src/ui.ts b/packages/ui/src/ui.ts index 04dc8856..8a75bd02 100644 --- a/packages/ui/src/ui.ts +++ b/packages/ui/src/ui.ts @@ -1,4 +1,11 @@ -import { alternateBuffer, createTerm, cursor, settings } from '@bomb.sh/tty'; +import { + alternateBuffer, + createTerm, + cursor, + detectTerminal, + settings, + type RenderInfo, +} from '@bomb.sh/tty'; import type { Readable, Writable } from 'node:stream'; import { createHTMLDocument, type HTMLDocument } from './dom.ts'; import { RenderApi } from './render.ts'; @@ -22,10 +29,11 @@ export async function createUI(options: UIOptions): Promise { const setup = settings(cursor(false), alternateBuffer()); - const term = await createTerm({ width, height }); + const terminfo = await detectTerminal({ signal }); + const term = await createTerm({ width, height, terminfo }); const render = new RenderApi(signal); - const document = createHTMLDocument(() => render.request()); + const document = createHTMLDocument((nodes) => render.request(nodes)); const layout = new Layout(document.documentElement!); @@ -35,9 +43,11 @@ export async function createUI(options: UIOptions): Promise { await write(output, setup.apply); try { - for await (const _ of render) { - const ops = [...layout.layout()]; + let info: RenderInfo | undefined; + for await (const changes of render) { + const ops = [...layout.layout({ changes, info })]; const result = term.render(ops); + info = result.info; await write(output, result.output); } } finally { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f87543b0..676cc3db 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -196,8 +196,8 @@ settings: catalogs: default: '@bomb.sh/tty': - specifier: ^0.10.0 - version: 0.10.0 + specifier: ^0.12.0 + version: 0.12.0 importers: @@ -274,7 +274,7 @@ importers: dependencies: '@bomb.sh/tty': specifier: 'catalog:' - version: 0.10.0 + version: 0.12.0 '@standard-schema/spec': specifier: ^1.1.0 version: 1.1.0 @@ -344,8 +344,8 @@ packages: resolution: {integrity: sha512-iaWws8S5kMuS6zImKXPSguUoQYA5M8XlK4ObVJI5jvubNeSlCI6feGPwex9GHyO+eIsi6izv/swO1ceO2MWEvw==} hasBin: true - '@bomb.sh/tty@0.10.0': - resolution: {integrity: sha512-ZOfMnVMhlik9CtSv5NJV4409T6SitS9GC93YZrbq1Be1nmbv83gf5wQHdOc+ic9QOb2kgpgAXKrMV6WiHLSTPA==} + '@bomb.sh/tty@0.12.0': + resolution: {integrity: sha512-hXNa4b3/9WNxAgNRE98Ctp/OAIVeAFy2opMkjC5LfgYrc26Putxv1cZHoRGoLhLKixlpNlklAXLqgdzEYm724g==} engines: {node: '>= 22'} '@changesets/apply-release-plan@8.1.1': @@ -2557,7 +2557,9 @@ snapshots: - vite-plus - vue-tsc - '@bomb.sh/tty@0.10.0': {} + '@bomb.sh/tty@0.12.0': + dependencies: + hueful: 0.8.1 '@changesets/apply-release-plan@8.1.1': dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 8e70bd01..0d8ff441 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -2,7 +2,7 @@ packages: - packages/* - examples/* catalog: - '@bomb.sh/tty': ^0.10.0 + '@bomb.sh/tty': ^0.12.0 allowBuilds: node-pty: true publicHoistPattern: @@ -15,3 +15,5 @@ tasks: .wpt: dependsOn: - ^build +minimumReleaseAgeExclude: + - '@bomb.sh/tty@0.12.0'