Skip to content

Commit c745fd3

Browse files
authored
feat: currentcolor and open() foreground inheritance (§8.5)
open() gains a color field: the element's own foreground, inherited by descendants via a pack()-time stack pushed on open and popped on close. currentcolor means "inherit" in a color field and "this directive's own resolved color" everywhere else, going through the same field resolution (resolveForField) as any other color. border.color is now optional and defaults to currentcolor. resolveColor() returns a CURRENT_COLOR sentinel for the keyword; ops.ts substitutes the inherited/own color before field resolution via resolveOwn()/colorValue(), both newly threading a `current` parameter through colorWord/sideFg/sideBg. No wire-format change: open()'s own color has no direct rendering, only TS-side inheritance.
1 parent aff632c commit c745fd3

9 files changed

Lines changed: 529 additions & 60 deletions

File tree

‎.changeset/currentcolor.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
"@bomb.sh/tty": minor
3+
---
4+
5+
`open()` accepts a `color` field: the element's own foreground color, inherited
6+
by every descendant that doesn't set its own. `currentcolor` is now a valid
7+
color string everywhere, including `color` itself, where it means "inherit"
8+
(the same as omitting the field). Used in any other color field —
9+
`open({ bg })`, `text({ bg })`, `border.color`, `border.bg`, or a structured
10+
border side's `color`/`bg` — it resolves to the directive's own resolved
11+
color (its explicit `color`, or the color it inherits), then follows the same
12+
field resolution as any other color, so it probes the terminal theme and
13+
transitions normally when that resolved color is an sRGB value. `border.color`
14+
is now optional and defaults to `currentcolor`, matching CSS; a border with no
15+
`color` set anywhere picks up the element's own foreground, same as before
16+
this feature existed.

‎color.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,33 @@ function byte(unit: number): number {
5050
return Math.round(Math.min(Math.max(unit, 0), 1) * 255);
5151
}
5252

53+
/**
54+
* A §8.5 `currentcolor` sentinel. In a `color` field it means "inherit"; in
55+
* any other field it means "this directive's own resolved color." Both
56+
* substitutions happen in `pack()`'s inheritance stack (ops.ts), not here.
57+
*/
58+
export const CURRENT_COLOR: { readonly current: true } = { current: true };
59+
export type CurrentColor = typeof CURRENT_COLOR;
60+
61+
/** Narrows a `resolveColor()` result to the `currentcolor` sentinel. */
62+
export function isCurrentColor(
63+
value: number | TerminalColor | CurrentColor,
64+
): value is CurrentColor {
65+
return typeof value === "object" && "current" in value;
66+
}
67+
5368
/**
5469
* Resolves a §8.5 CSS color string to the packed ARGB number the transfer
55-
* encoding carries, a terminal-themed color for a system color keyword, or
56-
* `undefined` when the string is not a supported color. Channels clamp to
57-
* the sRGB range, so out-of-gamut colors clip per channel.
70+
* encoding carries, a terminal-themed color for a system color keyword, the
71+
* `currentcolor` sentinel, or `undefined` when the string is not a supported
72+
* color. Channels clamp to the sRGB range, so out-of-gamut colors clip per
73+
* channel.
5874
*/
5975
export function resolveColor(
6076
input: string,
61-
): number | TerminalColor | undefined {
77+
): number | TerminalColor | CurrentColor | undefined {
6278
let lower = input.toLowerCase();
79+
if (lower === "currentcolor") return CURRENT_COLOR;
6380
if (Object.hasOwn(systemColors, lower)) {
6481
return { ansi: systemColors[lower as keyof typeof systemColors] };
6582
}

‎ops.ts‎

Lines changed: 75 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { names } from "hueful";
22
import {
3+
isCurrentColor,
34
resolveColor,
45
resolveForField,
56
type systemColors,
@@ -104,20 +105,22 @@ function sideFg(
104105
side: BorderSide | undefined,
105106
shared: Color,
106107
theme: ThemeColors | undefined,
108+
current: number | TerminalColor,
107109
): number {
108110
let color = typeof side === "object" && side.color !== undefined
109111
? side.color
110112
: shared;
111-
return colorWord(color, "fg", theme);
113+
return colorWord(color, "fg", theme, current);
112114
}
113115

114116
function sideBg(
115117
side: BorderSide | undefined,
116118
shared: Color | undefined,
117119
theme: ThemeColors | undefined,
120+
current: number | TerminalColor,
118121
): number {
119122
let bg = typeof side === "object" && side.bg !== undefined ? side.bg : shared;
120-
return bg === undefined ? BG_KEEP : colorWord(bg, "bg", theme);
123+
return bg === undefined ? BG_KEEP : colorWord(bg, "bg", theme, current);
121124
}
122125

123126
function packString(
@@ -155,11 +158,16 @@ export function pack(
155158
let end = limit ?? mem.byteLength;
156159
let o = offset;
157160

161+
// §8.5 foreground inheritance: pushed on open (the element's own resolved
162+
// color), popped on the matching close. Scoped to this single pass.
163+
let colorStack: (number | TerminalColor)[] = [DEFAULT_FG];
164+
158165
for (let op of ops) {
159166
switch (op.directive) {
160167
case OP_CLOSE_ELEMENT:
161168
view.setUint32(o, op.directive, true);
162169
o += 4;
170+
if (colorStack.length > 1) colorStack.pop();
163171
break;
164172

165173
case OP_OPEN_ELEMENT: {
@@ -169,9 +177,15 @@ export function pack(
169177
let bytes = encoder.encode(op.id);
170178
o = packString(view, bytes, o, end, "element id");
171179

180+
let ownColor = resolveOwn(
181+
op.color,
182+
colorStack[colorStack.length - 1],
183+
);
184+
colorStack.push(ownColor);
185+
172186
let bg = op.bg === undefined
173187
? undefined
174-
: colorValue(op.bg, "bg", theme);
188+
: colorValue(op.bg, "bg", theme, ownColor);
175189
let mask = 0;
176190
if (op.layout) mask |= PROP_LAYOUT;
177191
if (typeof bg === "number") mask |= PROP_BG_COLOR;
@@ -254,10 +268,11 @@ export function pack(
254268
// attribute words: fg/bg pairs in top, right, bottom, left order.
255269
// C treats the presence and order of these words as a wire-format
256270
// invariant and only consumes the explicit values.
271+
let sharedColor: Color = b.color ?? "currentcolor";
257272
for (let side of [b.top, b.right, b.bottom, b.left]) {
258-
view.setUint32(o, sideFg(side, b.color, theme), true);
273+
view.setUint32(o, sideFg(side, sharedColor, theme, ownColor), true);
259274
o += 4;
260-
view.setUint32(o, sideBg(side, b.bg, theme), true);
275+
view.setUint32(o, sideBg(side, b.bg, theme, ownColor), true);
261276
o += 4;
262277
}
263278
}
@@ -332,11 +347,15 @@ export function pack(
332347
view.setUint32(o, OP_TEXT, true);
333348
o += 4;
334349
// The fg word's bit 31 travels in the attrs byte (0x80); the C path
335-
// ORs the attrs byte back over the high byte. No color is the
336-
// terminal default.
337-
let color = op.color === undefined
338-
? { ansi: "fg-default" as const }
339-
: colorValue(op.color, "fg", theme);
350+
// ORs the attrs byte back over the high byte. No color inherits the
351+
// nearest ancestor open()'s color (§8.5), terminal default at root.
352+
let ownColor = resolveOwn(
353+
op.color,
354+
colorStack[colorStack.length - 1],
355+
);
356+
let color = typeof ownColor === "number"
357+
? ownColor
358+
: resolveForField(ownColor, "fg", theme);
340359
let terminal = typeof color === "object";
341360
view.setUint32(
342361
o,
@@ -347,7 +366,9 @@ export function pack(
347366

348367
view.setUint32(
349368
o,
350-
op.bg === undefined ? BG_KEEP : colorWord(op.bg, "bg", theme),
369+
op.bg === undefined
370+
? BG_KEEP
371+
: colorWord(op.bg, "bg", theme, ownColor),
351372
true,
352373
);
353374
o += 4;
@@ -398,21 +419,45 @@ export type Color = number | string;
398419
/**
399420
* Resolves a color value to a packed ARGB number or a terminal-themed color
400421
* (§8.5), for the field it's packed into. Numbers pass through; strings
401-
* resolve through the CSS color grammar. A cross-field default keyword
402-
* resolves against `theme` to a packed ARGB number, falling back to the
403-
* field's own terminal default when `theme` lacks that color. Invalid
404-
* strings throw rather than decoding to a garbage color.
422+
* resolve through the CSS color grammar. `currentcolor` substitutes `current`
423+
* — the directive's own resolved color — before field resolution runs, same
424+
* as any other color. A cross-field default keyword resolves against `theme`
425+
* to a packed ARGB number, falling back to the field's own terminal default
426+
* when `theme` lacks that color. Invalid strings throw rather than decoding
427+
* to a garbage color.
405428
*/
406429
function colorValue(
407430
color: Color,
408431
field: "fg" | "bg",
409432
theme: ThemeColors | undefined,
433+
current: number | TerminalColor,
410434
): number | TerminalColor {
411435
if (typeof color === "number") return color;
412436
let value = resolveColor(color);
413437
if (value === undefined) throw new TypeError(`invalid color: "${color}"`);
414-
if (typeof value === "number") return value;
415-
return resolveForField(value, field, theme);
438+
let resolved = isCurrentColor(value) ? current : value;
439+
if (typeof resolved === "number") return resolved;
440+
return resolveForField(resolved, field, theme);
441+
}
442+
443+
/**
444+
* Resolves the canonical (pre field-resolution) color a directive's own
445+
* `color` property names — its inheritance value for §8.5's foreground
446+
* inheritance. `undefined` or `currentcolor` inherits `parent`; any other
447+
* value resolves through the CSS color grammar, same as `colorValue`, but
448+
* without field resolution — that happens where the value is later consumed.
449+
*/
450+
function resolveOwn(
451+
explicit: Color | undefined,
452+
parent: number | TerminalColor,
453+
): number | TerminalColor {
454+
if (explicit === undefined) return parent;
455+
if (typeof explicit === "number") return explicit;
456+
let value = resolveColor(explicit);
457+
if (value === undefined) {
458+
throw new TypeError(`invalid color: "${explicit}"`);
459+
}
460+
return isCurrentColor(value) ? parent : value;
416461
}
417462

418463
function terminalWord(color: TerminalColor): number {
@@ -426,11 +471,15 @@ function colorWord(
426471
color: Color,
427472
field: "fg" | "bg",
428473
theme: ThemeColors | undefined,
474+
current: number | TerminalColor,
429475
): number {
430-
let value = colorValue(color, field, theme);
476+
let value = colorValue(color, field, theme, current);
431477
return typeof value === "number" ? value & 0x00FFFFFF : terminalWord(value);
432478
}
433479

480+
/* The directive-chain default when no ancestor `open()` sets `color`. */
481+
const DEFAULT_FG: TerminalColor = { ansi: "fg-default" };
482+
434483
export type SizingAxis =
435484
| { type: "fit"; min?: number; max?: number }
436485
| { type: "grow"; min?: number; max?: number }
@@ -468,6 +517,10 @@ export type BorderSide =
468517
export interface OpenElement {
469518
directive: typeof OP_OPEN_ELEMENT;
470519
id: string;
520+
/** The element's own foreground color (§8.5). Inherited by descendants
521+
* that do not override it; `currentcolor` means "inherit," same as
522+
* omitting this field. */
523+
color?: Color;
471524
layout?: {
472525
width?: SizingAxis;
473526
height?: SizingAxis;
@@ -480,7 +533,8 @@ export interface OpenElement {
480533
bg?: Color;
481534
cornerRadius?: { tl?: number; tr?: number; bl?: number; br?: number };
482535
border?: {
483-
color: Color;
536+
/** Defaults to `currentcolor` (§8.5): the element's own resolved color. */
537+
color?: Color;
484538
bg?: Color;
485539
left?: BorderSide;
486540
right?: BorderSide;
@@ -640,7 +694,8 @@ type ColorFunction =
640694
type NamedColor =
641695
| keyof typeof names
642696
| keyof typeof systemColors
643-
| "transparent";
697+
| "transparent"
698+
| "currentcolor";
644699

645700
type CheckedColor<T> = T extends number ? T
646701
: T extends string ? string extends T ? T

‎specs/renderer-spec.md‎

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -881,31 +881,31 @@ clipped per channel; no perceptual gamut mapping is performed. Alpha defaults to
881881
255 when a form does not supply it. A hex string and the equivalent `rgba()`
882882
call produce bit-identical packed values.
883883

884-
**Foreground inheritance and `currentcolor`.** `open()` accepts a `color`
885-
field: the element's own foreground color. `color` is inherited: an element
886-
with no explicit `color` (or with `color: "currentcolor"`) uses the nearest
887-
ancestor `open()`'s resolved color; an explicit `color` other than
888-
`currentcolor` overrides it for that element and, by the same inheritance
889-
rule, every descendant that does not itself override it. `text()` resolves its
890-
own `color` field (and, when absent, inherits) the same way; a `text()` has no
891-
descendants, so its resolved color only affects itself. With no `color`
892-
anywhere in the enclosing chain, the inherited color is the terminal default
893-
foreground — the same color a directive gets today when `color` is omitted.
884+
**Foreground inheritance and `currentcolor`.** `open()` accepts a `color` field:
885+
the element's own foreground color. `color` is inherited: an element with no
886+
explicit `color` (or with `color: "currentcolor"`) uses the nearest ancestor
887+
`open()`'s resolved color; an explicit `color` other than `currentcolor`
888+
overrides it for that element and, by the same inheritance rule, every
889+
descendant that does not itself override it. `text()` resolves its own `color`
890+
field (and, when absent, inherits) the same way; a `text()` has no descendants,
891+
so its resolved color only affects itself. With no `color` anywhere in the
892+
enclosing chain, the inherited color is the terminal default foreground — the
893+
same color a directive gets today when `color` is omitted.
894894

895895
`currentcolor` used in any field other than `color` — `open({ bg })`,
896896
`text({ bg })`, `border.color`, `border.bg`, or a structured border side's
897-
`color` or `bg` — resolves to that directive's own resolved color (its
898-
explicit `color`, or the color it inherits). That resolved color is then
899-
subject to the same field resolution as any other color value: a same-field
900-
default keyword or palette entry stays terminal-themed, a cross-field default
901-
keyword resolves against the probed theme (falling back to the field's own
902-
default when unprobed), and an sRGB color passes through unchanged. For
903-
example, an element with no `color` set anywhere above it has an inherited
904-
color of the terminal default foreground; `bg: "currentcolor"` on that element
905-
resolves exactly like `bg: "CanvasText"` — the probed foreground when
906-
available, the default background otherwise — while `border.color` left at its
907-
default resolves like `border.color: "CanvasText"` used in a foreground field,
908-
which stays terminal-themed (SGR `39`).
897+
`color` or `bg` — resolves to that directive's own resolved color (its explicit
898+
`color`, or the color it inherits). That resolved color is then subject to the
899+
same field resolution as any other color value: a same-field default keyword or
900+
palette entry stays terminal-themed, a cross-field default keyword resolves
901+
against the probed theme (falling back to the field's own default when
902+
unprobed), and an sRGB color passes through unchanged. For example, an element
903+
with no `color` set anywhere above it has an inherited color of the terminal
904+
default foreground; `bg: "currentcolor"` on that element resolves exactly like
905+
`bg: "CanvasText"` — the probed foreground when available, the default
906+
background otherwise — while `border.color` left at its default resolves like
907+
`border.color: "CanvasText"` used in a foreground field, which stays
908+
terminal-themed (SGR `39`).
909909

910910
`border.color` is optional and defaults to `currentcolor`, matching CSS. A
911911
structured border side without its own `color` falls back to the shared
@@ -915,8 +915,8 @@ structured border side without its own `color` falls back to the shared
915915
Foreground inheritance is resolved by `pack()` with a stack: pushed on each
916916
element open (the newly resolved color), popped on the matching close. It is
917917
scoped to the single pass over one frame's directive array — a sibling that
918-
follows a closed element does not see that element's color, and no
919-
inheritance state carries across frames (§6, §10.4).
918+
follows a closed element does not see that element's color, and no inheritance
919+
state carries across frames (§6, §10.4).
920920

921921
**Invalid color strings.** A string that does not match the color string grammar
922922
is invalid directive input (§9.1). `validate()` reports it as an invalid field
@@ -929,10 +929,10 @@ The directive constructors check string literals at compile time: a literal
929929
beginning with `#` must match the hex form (the type-level equivalent of
930930
`#${string{3,4,6,8}}`); a literal containing `(` must begin with a supported
931931
function name; any other literal must be a named color keyword, `transparent`,
932-
`currentcolor`, or a system color keyword. Function arguments are not checked statically.
933-
Strings whose value is only known at runtime (colors read from a theme or
934-
configuration, for example) pass the type check as `string` and are checked by
935-
`validate()` and the packer at render time.
932+
`currentcolor`, or a system color keyword. Function arguments are not checked
933+
statically. Strings whose value is only known at runtime (colors read from a
934+
theme or configuration, for example) pass the type check as `string` and are
935+
checked by `validate()` and the packer at render time.
936936

937937
### 8.6 Term update
938938

‎test/border.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -748,3 +748,52 @@ describe("system colors", () => {
748748
expect(at(parsed, 3, 0).fg).toBe("\x1b[38;2;200;210;220");
749749
});
750750
});
751+
752+
describe("currentcolor", () => {
753+
it("defaults border.color to currentcolor, inherited from an ancestor open", async () => {
754+
let term = await createTerm({ width: 12, height: 5 });
755+
let ansi = decode(
756+
term.render([
757+
open("outer", { color: RED }),
758+
open("box", {
759+
layout: { width: fixed(8), height: fixed(4) },
760+
border: { top: 1, right: 1, bottom: 1, left: 1 },
761+
}),
762+
close(),
763+
close(),
764+
], { mode: "line" }).output,
765+
);
766+
let parsed = cells(ansi);
767+
768+
for (let cell of glyphs(parsed, "┌┐└┘─│")) {
769+
expect(cell.fg).toBe(FG.red);
770+
}
771+
});
772+
773+
it("resolves border.color: currentcolor to the element's own explicit color", async () => {
774+
let parsed = await renderBox({
775+
color: GREEN,
776+
border: { color: "currentcolor", top: 1 },
777+
});
778+
779+
expect(at(parsed, 3, 0).fg).toBe(FG.green);
780+
});
781+
782+
it("resolves border.bg: currentcolor to the element's own resolved color", async () => {
783+
let parsed = await renderBox({
784+
color: BLUE,
785+
border: { color: WHITE, bg: "currentcolor", top: 1 },
786+
});
787+
788+
expect(at(parsed, 3, 0).bg).toBe(BG.blue);
789+
});
790+
791+
it("resolves a structured side's color: currentcolor to the element's own color", async () => {
792+
let parsed = await renderBox({
793+
color: YELLOW,
794+
border: { color: WHITE, top: { width: 1, color: "currentcolor" } },
795+
});
796+
797+
expect(at(parsed, 3, 0).fg).toBe(FG.yellow);
798+
});
799+
});

0 commit comments

Comments
 (0)