Skip to content

Commit 5eff853

Browse files
committed
Render inline styles in terminal layout
1 parent a5082bb commit 5eff853

6 files changed

Lines changed: 617 additions & 17 deletions

File tree

‎.changeset/dom-style-rendering.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clack/ui': patch
3+
---
4+
5+
Apply element styles to terminal layout, spacing, borders, and colors, including default display modes and inherited foreground colors.

‎packages/ui/src/layout.test.ts‎

Lines changed: 94 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { close, open, text } from '@bomb.sh/tty';
2-
import { describe, expect, it } from 'vitest';
1+
import { close, open, rgba, snapshot, text, type Op } from '@bomb.sh/tty';
2+
import { assert, describe, expect, it } from 'vitest';
33
import { createHTMLDocument } from './dom.ts';
44
import { Layout } from './layout.ts';
55

@@ -34,7 +34,7 @@ describe('Layout', () => {
3434
expect([...layout.layout(child)]).toEqual([open('DOCUMENT: 1'), text('inside'), close()]);
3535
});
3636

37-
it('lays out a deeply nested tree without recursive generator delegation', () => {
37+
it('lays out a deeply nested tree without recursive traversal', () => {
3838
const document = createHTMLDocument(() => {});
3939
const root = document.createElement('document');
4040
document.body!.appendChild(root);
@@ -55,6 +55,9 @@ describe('Layout', () => {
5555
expect(iterator.next().value).toEqual(close());
5656
}
5757
expect(iterator.next().done).toBe(true);
58+
59+
root.style.display = 'inline';
60+
expect([...new Layout(root).layout()]).toEqual([text('leaf')]);
5861
});
5962

6063
it('closes active elements when iteration is returned early', () => {
@@ -74,3 +77,91 @@ describe('Layout', () => {
7477
expect(iterator.next().done).toBe(true);
7578
});
7679
});
80+
describe('sparse layout options', () => {
81+
it('omits default layout options and saves the whole packed layout block', () => {
82+
const document = createHTMLDocument(() => {});
83+
const body = document.body!;
84+
// Explicit defaults have the same packing requirements as undeclared defaults.
85+
body.style.display = 'flex';
86+
body.style.flexDirection = 'row';
87+
body.style.gap = '0px';
88+
body.style.paddingLeft = '0px';
89+
body.style.borderColor = 'blue';
90+
const ops = [...new Layout(body).layout()];
91+
const id = rootId(ops);
92+
const dense = [
93+
open(id, {
94+
layout: {
95+
direction: 'ltr',
96+
gap: 0,
97+
padding: { top: 0, right: 0, bottom: 0, left: 0 },
98+
},
99+
}),
100+
close(),
101+
];
102+
expect(ops).toEqual([open(id), close()]);
103+
expect(packed(dense).byteLength - packed(ops).byteLength).toBe(36);
104+
});
105+
106+
it('packs nondefault layout and border options identically to explicit zero sides', () => {
107+
const document = createHTMLDocument(() => {});
108+
const body = document.body!;
109+
body.style.flexDirection = 'column';
110+
body.style.gap = '2px';
111+
body.style.paddingLeft = '2px';
112+
body.style.borderStyle = 'solid';
113+
body.style.borderColor = 'blue';
114+
body.style.borderTopWidth = '0px';
115+
body.style.borderRightWidth = '0px';
116+
body.style.borderBottomWidth = '0px';
117+
const ops = [...new Layout(body).layout()];
118+
const id = rootId(ops);
119+
expect(ops).toEqual([
120+
open(id, {
121+
layout: { direction: 'ttb', gap: 2, padding: { left: 2 } },
122+
border: { color: rgba(0, 0, 255), left: 1 },
123+
}),
124+
close(),
125+
]);
126+
expect(packed(ops)).toEqual(
127+
packed([
128+
open(id, {
129+
layout: { direction: 'ttb', gap: 2, padding: { top: 0, right: 0, bottom: 0, left: 2 } },
130+
border: { color: rgba(0, 0, 255), top: 0, right: 0, bottom: 0, left: 1 },
131+
}),
132+
close(),
133+
]),
134+
);
135+
});
136+
137+
it('omits terminal-default text color but preserves inherited packed zero', () => {
138+
const document = createHTMLDocument(() => {});
139+
const body = document.body!;
140+
const span = document.createElement('span');
141+
span.appendChild(document.createTextNode('inline'));
142+
body.appendChild(document.createTextNode('direct'));
143+
body.appendChild(span);
144+
const layout = new Layout(body);
145+
const ops = [...layout.layout()];
146+
const id = rootId(ops);
147+
expect(ops).toEqual([open(id), text('direct'), text('inline'), close()]);
148+
body.style.color = 'transparent';
149+
expect([...layout.layout()]).toEqual([
150+
open(id),
151+
text('direct', { color: 0 }),
152+
text('inline', { color: 0 }),
153+
close(),
154+
]);
155+
});
156+
});
157+
158+
function rootId(ops: Op[]): string {
159+
const root = ops[0];
160+
assert(root && 'id' in root);
161+
return root.id;
162+
}
163+
164+
function packed(ops: Op[]): Uint8Array {
165+
const result = snapshot(ops) as { data: Uint8Array };
166+
return result.data;
167+
}

‎packages/ui/src/layout.ts‎

Lines changed: 181 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1-
import { close, open, text, type Op } from '@bomb.sh/tty';
1+
/* oxlint-disable bombshell-dev/max-params -- Layout helpers pass the element and rendering context explicitly. */
2+
import { close, open, rgba, text, type Op } from '@bomb.sh/tty';
3+
import { convert } from 'hueful';
24
import { Element, Text } from './dom.ts';
5+
import type { StyleValues } from './style.ts';
6+
7+
type TTYContainerOptions = NonNullable<Parameters<typeof open>[1]>;
8+
type TTYTextOptions = NonNullable<Parameters<typeof text>[1]>;
39

410
export class Layout {
511
#lastIdNumber = 0;
@@ -11,17 +17,27 @@ export class Layout {
1117
}
1218

1319
/** Serialize an element to TTY Ops. */
14-
*layout(element: Element = this.#root): IterableIterator<Op> {
15-
yield this.#open(element);
20+
*layout(element: Element = this.#root, inheritedColor?: number): IterableIterator<Op> {
21+
const style = computeStyle(element);
22+
const color = resolveColorValue(style.color.value, inheritedColor);
23+
if (style.display.value === 'inline') {
24+
const content = collectInlineText(element);
25+
if (content !== '') {
26+
yield text(content, ttyTextOptions(color));
27+
}
28+
return;
29+
}
1630

17-
const stack = [element.childNodes[Symbol.iterator]()];
31+
const stack = [{ children: element.childNodes[Symbol.iterator](), color }];
1832
try {
33+
yield this.#open(element, style, color);
1934
let content = '';
2035
while (stack.length > 0) {
21-
const next = stack[stack.length - 1]!.next();
36+
const frame = stack[stack.length - 1]!;
37+
const next = frame.children.next();
2238
if (next.done) {
2339
if (content !== '') {
24-
yield text(content);
40+
yield text(content, ttyTextOptions(frame.color));
2541
content = '';
2642
}
2743
stack.pop();
@@ -33,11 +49,20 @@ export class Layout {
3349
content += child.data;
3450
} else if (child instanceof Element) {
3551
if (content !== '') {
36-
yield text(content);
52+
yield text(content, ttyTextOptions(frame.color));
3753
content = '';
3854
}
39-
yield this.#open(child);
40-
stack.push(child.childNodes[Symbol.iterator]());
55+
const childStyle = computeStyle(child);
56+
const childColor = resolveColorValue(childStyle.color.value, frame.color);
57+
if (childStyle.display.value === 'inline') {
58+
const inlineContent = collectInlineText(child);
59+
if (inlineContent !== '') {
60+
yield text(inlineContent, ttyTextOptions(childColor));
61+
}
62+
} else {
63+
stack.push({ children: child.childNodes[Symbol.iterator](), color: childColor });
64+
yield this.#open(child, childStyle, childColor);
65+
}
4166
}
4267
}
4368
} finally {
@@ -48,12 +73,157 @@ export class Layout {
4873
}
4974
}
5075

51-
#open(element: Element): Op {
76+
#open(element: Element, style: StyleValues, color?: number): Op {
5277
let stableId = this.#stableIds.get(element);
5378
if (!stableId) {
5479
stableId = `${element.nodeName}: ${this.#lastIdNumber++}`;
5580
this.#stableIds.set(element, stableId);
5681
}
57-
return open(stableId);
82+
return open(stableId, ttyContainerOptions(style, color));
83+
}
84+
}
85+
86+
/** Inline elements collect descendant text using the outer element's styles. */
87+
function collectInlineText(element: Element): string {
88+
let content = '';
89+
const stack = [element.childNodes[Symbol.iterator]()];
90+
while (stack.length > 0) {
91+
const next = stack[stack.length - 1]!.next();
92+
if (next.done) {
93+
stack.pop();
94+
} else if (next.value instanceof Text) {
95+
content += next.value.data;
96+
} else if (next.value instanceof Element) {
97+
stack.push(next.value.childNodes[Symbol.iterator]());
98+
}
5899
}
100+
return content;
101+
}
102+
103+
/**
104+
* Convert a color which is stored internally as a hueful `ParseResult` into
105+
* an RGB numeric value which is what TTY speaks natively.
106+
*/
107+
function resolveColorValue(
108+
value: StyleValues['color']['value'],
109+
inheritedColor?: number,
110+
): number | undefined {
111+
if (value === 'currentColor') {
112+
return inheritedColor;
113+
}
114+
const [r, g, b, alpha = 1] = convert(value.space, 'rgb', value.value);
115+
const channel = (component: number): number => Math.round(Math.max(0, Math.min(255, component)));
116+
return rgba(channel(r), channel(g), channel(b), channel(alpha * 255));
117+
}
118+
119+
/**
120+
* Map a layout container element's styles to TTY options. The mapping is
121+
* sparse so that even though we have a completely known computed style,
122+
* we only send through to WASM enough information to render.
123+
*/
124+
function ttyContainerOptions(style: StyleValues, color?: number): TTYContainerOptions {
125+
const props: TTYContainerOptions = {};
126+
const layout: NonNullable<typeof props.layout> = {};
127+
if (style.flexDirection.value === 'column') {
128+
layout.direction = 'ttb';
129+
}
130+
if (style.gap.value !== 0) {
131+
layout.gap = style.gap.value;
132+
}
133+
134+
let top = style.paddingTop.value;
135+
let right = style.paddingRight.value;
136+
let bottom = style.paddingBottom.value;
137+
let left = style.paddingLeft.value;
138+
const borderTop = style.borderTopWidth.value;
139+
const borderRight = style.borderRightWidth.value;
140+
const borderBottom = style.borderBottomWidth.value;
141+
const borderLeft = style.borderLeftWidth.value;
142+
if (
143+
style.borderStyle.value === 'solid' &&
144+
(borderTop || borderRight || borderBottom || borderLeft)
145+
) {
146+
const borderColor = resolveColorValue(style.borderColor.value, color);
147+
// TTY requires an explicit border color. Keep the space when it cannot draw the border.
148+
if (borderColor !== undefined) {
149+
props.border = { color: borderColor };
150+
if (borderTop !== 0) {
151+
props.border.top = borderTop;
152+
}
153+
if (borderRight !== 0) {
154+
props.border.right = borderRight;
155+
}
156+
if (borderBottom !== 0) {
157+
props.border.bottom = borderBottom;
158+
}
159+
if (borderLeft !== 0) {
160+
props.border.left = borderLeft;
161+
}
162+
} else {
163+
// TTY cannot draw borders with the terminal-default foreground yet.
164+
// Reserve their space with padding until https://github.com/bombshell-dev/tty/issues/155
165+
// is implemented; then emit the border and remove this fallback.
166+
top += borderTop;
167+
right += borderRight;
168+
bottom += borderBottom;
169+
left += borderLeft;
170+
}
171+
}
172+
173+
if (top || right || bottom || left) {
174+
layout.padding = {};
175+
if (top !== 0) {
176+
layout.padding.top = top;
177+
}
178+
if (right !== 0) {
179+
layout.padding.right = right;
180+
}
181+
if (bottom !== 0) {
182+
layout.padding.bottom = bottom;
183+
}
184+
if (left !== 0) {
185+
layout.padding.left = left;
186+
}
187+
}
188+
// Even an empty layout object makes TTY pack the entire layout block.
189+
if (Object.keys(layout).length > 0) {
190+
props.layout = layout;
191+
}
192+
return props;
193+
}
194+
195+
function ttyTextOptions(color?: number): TTYTextOptions {
196+
return color === undefined ? {} : { color };
197+
}
198+
199+
function computeStyle(element: Element): StyleValues {
200+
const defaults = computeDefaultStyles(element);
201+
return applyInlineStyles(element, defaults);
202+
}
203+
204+
function computeDefaultStyles(element: Element): StyleValues {
205+
const display =
206+
element.namespaceURI === 'http://www.w3.org/1999/xhtml' && element.localName === 'span'
207+
? 'inline'
208+
: 'flex';
209+
return {
210+
color: { value: 'currentColor', representation: 'currentColor' },
211+
display: { value: display, representation: display },
212+
flexDirection: { value: 'row', representation: 'row' },
213+
gap: { value: 0, representation: '0px' },
214+
paddingTop: { value: 0, representation: '0px' },
215+
paddingRight: { value: 0, representation: '0px' },
216+
paddingBottom: { value: 0, representation: '0px' },
217+
paddingLeft: { value: 0, representation: '0px' },
218+
borderStyle: { value: 'none', representation: 'none' },
219+
borderTopWidth: { value: 1, representation: '1px' },
220+
borderRightWidth: { value: 1, representation: '1px' },
221+
borderBottomWidth: { value: 1, representation: '1px' },
222+
borderLeftWidth: { value: 1, representation: '1px' },
223+
borderColor: { value: 'currentColor', representation: 'currentColor' },
224+
};
225+
}
226+
227+
function applyInlineStyles(element: Element, defaults: StyleValues): StyleValues {
228+
return { ...defaults, ...element.style.values };
59229
}

0 commit comments

Comments
 (0)