From 385c24244bad990ddf292dee27ab1954e643dc46 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Fri, 9 Oct 2026 13:59:04 -0500 Subject: [PATCH 1/9] feat: color-encoding tiers derived from capability evidence The renderer resolves an emission tier (truecolor / 256 / 16) from its capability snapshot instead of hardcoding 24-bit truecolor, per specs/color-encoding-spec.md. Capability state is authoritative in the WASM instance; the host pushes it at creation and after capability folds, and a tier change forces a complete redraw. Standard palette colors keep their classic indices when downmapped. Terminal-themed colors from the system-color work bypass downmapping: -ansi-* palette colors are already 4-bit and emit unchanged in every tier, while a cross-field Canvas/CanvasText resolved from the probed theme is ordinary sRGB and is encoded for the active tier. Closes #60 --- .changeset/color-encoding-tiers.md | 20 ++ specs/color-encoding-spec.md | 355 ++++++++++++++++++++++++++++ specs/renderer-spec.md | 28 ++- src/clayterm.c | 205 +++++++++++++++-- src/clayterm.h | 3 +- term-native.ts | 10 +- term.ts | 10 +- test/border.test.ts | 79 +++++-- test/caps.ts | 26 ++- test/color-encoding-modes.test.ts | 356 +++++++++++++++++++++++++++++ test/color.test.ts | 169 +++++++++++--- test/pack.test.ts | 2 + test/term.test.ts | 13 +- test/transitions.test.ts | 7 +- test/width.test.ts | 2 + 15 files changed, 1206 insertions(+), 79 deletions(-) create mode 100644 .changeset/color-encoding-tiers.md create mode 100644 specs/color-encoding-spec.md create mode 100644 test/color-encoding-modes.test.ts diff --git a/.changeset/color-encoding-tiers.md b/.changeset/color-encoding-tiers.md new file mode 100644 index 00000000..e00138e0 --- /dev/null +++ b/.changeset/color-encoding-tiers.md @@ -0,0 +1,20 @@ +--- +"@bomb.sh/tty": minor +--- + +The renderer now derives its SGR color encoding from the terminal's capability evidence instead of always emitting 24-bit truecolor. Truecolor evidence (`RGB`/`Tc` terminfo extension, `COLORTERM`, direct-color entries with `max_colors ≥ 2²⁴`, or a `colordepth` probe response folded through `term.update()`) keeps the historical byte-identical truecolor output. Without truecolor evidence, cells emit 256-color SGR (`\x1b[38;5;Nm`) when the resolved palette exceeds 16 colors, or 4-bit SGR (`\x1b[31m`) at or below 16. + +Colors are downmapped deterministically: standard palette colors keep their classic indices (`rgba(255,0,0)` → `\x1b[31m` / `\x1b[38;5;1m`), grays use the 240-step grayscale ramp, and everything else rounds to the 6×6×6 cube. System palette colors (`-ansi-red`, …) are already 4-bit and emit unchanged in every tier. A tier change between frames forces a complete redraw so no stale encoding survives on screen. + +**Breaking:** rendering without color evidence now produces 256-color bytes where it previously produced truecolor. Run `detectTerminal()` and pass its `TerminalInfo` to `createTerm` (or fold probe responses with `term.update()`) to keep truecolor output — terminals that support truecolor report it. + +#### Migration + +```diff + import { createTerm } from "@bomb.sh/tty"; ++ import { detectTerminal } from "@bomb.sh/tty"; + +- const term = await createTerm({ width, height }); ++ const terminfo = await detectTerminal(); ++ const term = await createTerm({ width, height, terminfo }); +``` diff --git a/specs/color-encoding-spec.md b/specs/color-encoding-spec.md new file mode 100644 index 00000000..48d42e59 --- /dev/null +++ b/specs/color-encoding-spec.md @@ -0,0 +1,355 @@ +# Clayterm Color Encoding Specification + +**Version:** 0.1 (draft) **Status:** Design specification for a work-in-progress +feature. Normative where it establishes invariants and contract. Descriptive +where surfaces may settle during implementation. + +--- + +## 1. Purpose + +The renderer emits one SGR color encoding for every cell it paints. Historically +that encoding was hardcoded to 24-bit truecolor (`\x1b[38;2;R;G;Bm`), regardless +of what the destination terminal supports. A 16-color terminal, a CI log, or a +pipe receives sequences its destination renders poorly — or not at all — when +`\x1b[31m` would have been both smaller and more faithful. + +This specification defines how the renderer derives its color encoding from the +capability snapshot it already maintains, and how it downmaps truecolor values +into narrower palettes when the evidence calls for it. It resolves the deferred +"color encoding" item in [renderer-spec.md](renderer-spec.md) §7.8 and the open +question from the capability-foundation work about where the renderer's +authoritative capability state lives. + +There is deliberately no caller-facing override. Capability evidence is the +single lever (TINV-3); an override would create a second source of truth that +could contradict probe responses. + +--- + +## 2. Scope + +### In scope (normative) + +- The color tier resolution rule: how `trueColor` and `colors` in the capability + snapshot determine the emitted encoding tier +- Ownership of the renderer's color-capability state inside the WASM module +- Per-tier SGR emission formats for foreground and background colors +- The downmapping algorithms from 24-bit RGB to the 256-color and 16-color + palettes, including the normative nominal palette +- Output invalidation when the resolved tier changes between transactions + +### In scope (non-normative, descriptive) + +- Implementation notes for the C-side emission path +- The relationship between this specification and the failing-test reproduction + that motivated it + +### Out of scope + +- **Terminal palette definition.** The renderer maps to palette _indices_; how a + terminal renders index N is the terminal's business. OSC 4 palette queries + remain deferred (terminfo-spec). +- **An `"8"`-color tier.** The 16-color tier already emits the base + `30–37`/`40–47` codes for indices 0–7. A dedicated 8-color tier would need + bright-index elision for marginal benefit; deferred. +- **88-color precision.** Terminals reporting `17 ≤ colors ≤ 255` resolve to the + 256 tier (§6.1); indices above 87 are the terminal's problem. +- **Per-render or per-call overrides.** Recorded as rejected in §7. +- **Other capability-driven emission** (synchronized output, pointer shape, + Kitty protocols) — each has its own focused specification path. + +--- + +## 3. Terminology + +**Color tier.** One of `"truecolor" | "256" | "16"` — the same three-value +`ColorDepth` type defined in [terminfo-spec.md](terminfo-spec.md) §6.2. The tier +names the _emission encoding_, not the terminal's full capability set. + +**Downmapping.** Producing the narrowest SGR sequence that faithfully represents +a 24-bit RGB color under the active tier. + +**Nominal palette.** The 16-entry RGB table defined in §6.3. It is the +renderer's canonical model of what each 4-bit index _means_ for mapping +purposes. It is not a claim about any terminal's actual palette, which varies +and may be user-configured. + +--- + +## 4. Architectural Model + +### 4.1 Evidence flows one way + +``` +detectTerminal() probe responses update() + terminfo entry → (input.scan) → CapabilityEvents + ↓ ↓ + Capabilities ──────────── fold ────────→ RuntimeCapabilities + │ + push (on change) │ + ↓ + WASM Clayterm instance (authoritative) + │ resolve tier + ↓ + emit_attr formatting +``` + +Static evidence (terminfo entry, `COLORTERM`) and dynamic evidence (`colordepth` +CapabilityEvents) meet in the capability snapshot exactly as terminfo-spec +defines. The renderer consumes that snapshot; it never consults the environment +or the raw terminfo entry itself. + +### 4.2 Capability state ownership + +The renderer's authoritative color-capability state — the `colors` value and the +truecolor flag — resides inside the WASM module, on the Clayterm instance +struct. The host pushes values across the boundary: + +- once at Term creation, seeding from `terminfo.capabilities` or the §7.1 + baseline of [terminfo-spec.md](terminfo-spec.md); +- after each `update()` whose folded events changed either value. + +Render transactions read the in-module state directly; the host does not copy +capability values per render. State belongs to the instance struct — there is no +module-level mutable state. + +A resize update rebuilds dimension-dependent renderer storage but MUST NOT reset +color capabilities to baseline: the tier is a property of the terminal, not of +the frame geometry. The instance retains the values across the update, and they +MUST survive intact. + +`term.capabilities` (the frozen `RuntimeCapabilities` snapshot) remains the +host-readable mirror. Its shape is unchanged by this specification. + +### 4.3 The renderer is still a pure formatter + +Nothing here changes the renderer's invariants: it performs no IO, manages no +terminal state, and produces bytes only. Tier resolution and downmapping are +pure functions of (capability state, packed cell color). + +--- + +## 5. Core Invariants + +- **CI-1 — Total, deterministic resolution.** Every capability snapshot state + resolves to exactly one tier, by the rule in §6.1. The same state always + yields the same tier. +- **CI-2 — Truecolor byte-identity.** Under the `"truecolor"` tier, output MUST + be byte-identical to the renderer's historical (pre-this-specification) + output. +- **CI-3 — Deterministic downmapping.** Every downmapping decision in §6.3 is a + pure function of the RGB value and the tier. Ties always resolve to the lowest + index. +- **CI-4 — Palette round-trip by color.** Under the `"256"` tier, every RGB + value that is itself an entry of the 256-color palette maps to an index that + represents that same RGB value. Where the nominal palette and the cube or + grayscale ramp define the same color (eight cube corners plus `#808080`), the + nominal index wins — the emitted index differs, the color does not. Under the + `"16"` tier, every nominal palette entry maps to its own index. +- **CI-5 — Tier change forces full redraw.** If the resolved tier differs from + the previous transaction's tier, the next transaction MUST emit the frame as a + complete redraw. Diff state is cell-based; stale cells from the previous + encoding must not survive. +- **CI-6 — Defaults stay default.** A cell with the default foreground or + background emits no color SGR for that attribute, in every tier. Style + attributes (bold, dim, italic, underline, blink, reverse, strikeout) and the + SGR reset pattern are unchanged in every tier. + +--- + +## 6. Rendering Contract Additions + +### 6.1 Tier resolution + +The renderer resolves the emission tier from the capability snapshot: + +``` +tier = + trueColor ? "truecolor" + : colors <= 16 ? "16" + : "256" +``` + +The `colors ≤ 16` boundary intentionally matches the denial mapping in +terminfo-spec §6.3 (`"16"` when `colors ≤ 16`, `"256"` otherwise), so the +renderer's derived tier and a `colordepth` denial event agree for every static +`colors` value. A `colordepth` probe event folds into `trueColor` (and is the +authoritative evidence for it per TINV-3); no other fold changes the tier. + +Notes: + +- `colors` values below 16 (including a missing `max_colors`, i.e. 0) clamp to + the `"16"` tier. The 16-color tier emits base codes for indices 0–7 and + aixterm bright codes for 8–15; a strictly 8-color destination's handling of + bright codes is the destination's concern. +- Truecolor requires positive evidence (terminfo-spec §7.1): the `RGB`/`Tc` + terminfo extension, `COLORTERM`, a direct-color entry (`max_colors ≥ 2²⁴`), or + a `colordepth` probe response. The baseline — no evidence at all — resolves to + `"256"`. + +**Default-behavior change.** A Term created without any color evidence now emits +256-color SGR, where it previously emitted truecolor. This is the baseline +evidence model applied to emission, not a regression: the renderer's hardcoded +truecolor contradicted terminfo-spec §7.1 ("Truecolor is not assumed at +baseline"). Callers who require truecolor bytes without running +`detectTerminal()` must supply capability evidence themselves. + +### 6.2 Emission formats + +For a non-default foreground/background under each tier: + +| Tier | Foreground | Background | +| ------------- | --------------------------------------------- | ---------------------------------------------- | +| `"truecolor"` | `\x1b[38;2;R;G;Bm` | `\x1b[48;2;R;G;Bm` | +| `"256"` | `\x1b[38;5;Nm`, N ∈ 0–255 | `\x1b[48;5;Nm`, N ∈ 0–255 | +| `"16"` | index 0–7: `\x1b[3Nm`; index 8–15: `\x1b[9Nm` | index 0–7: `\x1b[4Nm`; index 8–15: `\x1b[10Nm` | + +In the `"16"` tier, `N` is the resolved palette index for indices 0–7 and +`index − 8` for indices 8–15. Standard red (index 1) emits `\x1b[31m` foreground +and `\x1b[41m` background. + +### 6.3 Downmapping + +#### 6.3.1 Nominal palette + +The nominal palette defines what each 4-bit index means to the renderer: + +| Index | RGB | Name | Index | RGB | Name | +| ----- | --------- | ------- | ----- | --------- | -------------- | +| 0 | `#000000` | black | 8 | `#808080` | bright black | +| 1 | `#ff0000` | red | 9 | `#ff5555` | bright red | +| 2 | `#00ff00` | green | 10 | `#55ff55` | bright green | +| 3 | `#ffff00` | yellow | 11 | `#ffff55` | bright yellow | +| 4 | `#0000ff` | blue | 12 | `#5555ff` | bright blue | +| 5 | `#ff00ff` | magenta | 13 | `#ff55ff` | bright magenta | +| 6 | `#00ffff` | cyan | 14 | `#55ffff` | bright cyan | +| 7 | `#c0c0c0` | white | 15 | `#ffffff` | bright white | + +The primaries (1–6) are the pure hues; the bright variants are their pastel +counterparts. This choice is what makes "standard red" (`rgba(255, 0, 0)`) +resolve to index 1 — the behavior the motivating issue pins. + +#### 6.3.2 `"16"` tier + +Map the RGB value to the nearest entry of the nominal palette by squared +Euclidean distance over the three channels; on a tie, choose the lowest index. +Exact palette matches are distance zero, so they subsume themselves. + +#### 6.3.3 `"256"` tier + +Resolved in order; the first matching rule wins: + +1. **Exact nominal match.** If the RGB value equals a nominal palette entry, + emit that index (0–15). This is why standard red emits `\x1b[38;5;1m` rather + than the cube corner `\x1b[38;5;196m`: the terminal's index 1 _is_ its red, + and consistency with the `"16"` tier is worth more than exact chroma here. +2. **Exact cube match.** If every channel is one of the six cube values + `{0, 95, 135, 175, 215, 255}`, emit `16 + 36r + 6g + b` for the channel's + cube step. (Exact grayscale cube values such as `#5f5f5f` resolve here.) +3. **Grayscale.** If `r == g == b`, choose the nearest value among the grayscale + ramp `{8 + 10i : 0 ≤ i ≤ 23}` extended by the endpoints `0` (index 16) and + `255` (index 231); on a tie, choose the lower index. Emit `232 + i` for ramp + value `8 + 10i`, `16` for the low endpoint, `231` for the high endpoint. +4. **Cube nearest.** Otherwise, map each channel independently to the nearest + cube value (ties to the smaller value) and emit `16 + 36r + 6g + b`. + +Rules 1–3 are the exact-match tiers: nominal entries match in rule 1, cube +values in rule 2, and every grayscale ramp value matches itself in rule 3 +(distance zero). Eight RGB values are defined by both the nominal palette and +the cube (the pure primaries, black, and white) — for those, rule 1 outranks and +the nominal index is emitted, which still satisfies CI-4 because the emitted +index represents the identical color. + +#### 6.3.4 Default and attribute bytes + +Default foreground/background emit no color SGR (CI-6). The high byte of a +packed color carries style attributes; downmapping consumes only the low 24 bits +and never alters attribute emission. + +#### 6.3.5 Terminal-themed colors + +Terminal-themed colors (renderer-spec §8.5 system colors) are not downmapped. A +palette color is already a 4-bit index and emits as SGR `30`–`37` / `90`–`97` +(foreground) or `40`–`47` / `100`–`107` (background) in every tier; a terminal +default emits as in §6.3.4. A `Canvas` or `CanvasText` keyword that resolves to +a probed theme color is an ordinary sRGB value and is encoded for the active +tier like any other. + +### 6.4 Invalidation on tier change + +The update transaction itself still returns no bytes for capability events +(renderer-spec §7.7). This specification defines the consumer behavior the +foundation reserved: when the resolved tier changes, the _next_ render +transaction MUST emit a complete redraw (CI-5). No immediate bytes are required +— the redraw's own output re-encodes every visible cell. + +### 6.5 What does not change + +- The diff model: cells are compared on packed color values, exactly as before. + The tier affects only how a changed cell's colors are _encoded_. +- The SGR reset + attribute prefix pattern in `emit_attr`. +- The output buffer budget; 256-color and 16-color sequences are strictly + shorter than truecolor. + +--- + +## 7. Public API impact + +None. `createTerm`, `render`, `update`, and `RuntimeCapabilities` are unchanged. +This is deliberate. + +**Rejected alternative — a `colorMode` option on `createTerm`.** The motivating +issue sketched `createTerm({ colorMode: "16" })` as an explicit override. It was +rejected: capability evidence is the single lever for renderer output (TINV-3), +and an override creates a second source of truth that can contradict probe +responses — a denial event would silently fight the override. Callers control +the encoding the same way they control every other capability: by supplying +evidence (a terminfo entry, or folding probe responses through `update()`). + +--- + +## 8. Test plan + +One test file (`test/color-encoding-modes.test.ts`) covers exactly this +specification: + +- **16-color tier.** Standard red foreground → `\x1b[31m`; background → + `\x1b[41m`; the 24-bit sequence must not survive; bright index mapping (e.g. + `#ff5555` → `\x1b[91m`). +- **256-color tier.** Standard red foreground → `\x1b[38;5;1m`; background → + `\x1b[48;5;1m`; exact cube round-trip (e.g. `#5f5f5f` → `\x1b[38;5;59m`); + grayscale ramp mapping; nearest-cube mapping for non-palette colors. +- **Truecolor tier.** Byte-identity with the historical output (CI-2), including + background and attribute combinations. +- **Tier resolution.** Baseline (no evidence) → `"256"`; `colors: 8` and + `colors: 16` → `"16"`; `colors: 17` → `"256"`; a granted truecolor flag → + truecolor. (How entries grant the flag — `RGB`/`Tc`, `COLORTERM`, direct-color + `max_colors ≥ 2²⁴` — is terminfo-spec evidence territory, covered by its + tests.) +- **Dynamic evidence.** A `colordepth` CapabilityEvent folded through `update()` + changes the tier of the next render; the render after a tier change is a + complete redraw in the new encoding (CI-5). +- **Defaults.** Default foreground/background emit no color SGR in every tier + (CI-6). +- **Palette round-trip.** Every 256-palette RGB value maps to an index that + represents the identical color under the `"256"` tier (CI-4, exhaustive sweep + over a rendered 16×16 grid). + +Existing test files that pin truecolor byte sequences (`term.test.ts`, +`border.test.ts`, `color.test.ts`, `transitions.test.ts`) inject truecolor +capability evidence at creation so they continue to exercise the `"truecolor"` +tier explicitly; the default-tier change is pinned once, in the new file. + +--- + +## 9. Deferred / Future Areas + +- **OSC 4 palette queries.** The mapping assumes the nominal palette and + standard 256 cube. Querying the terminal's actual palette would permit exact + nearest-color downmapping against reality; deferred (terminfo-spec). +- **Perceptual distance.** Squared Euclidean RGB is deterministic and cheap. A + perceptually weighted metric (e.g. OKLab) could improve downmapping fidelity + for photography-like content; deferred until a use case demands it. +- **Dithering.** Adjacent-cell error diffusion to approximate out-of-palette + colors; out of scope indefinitely. diff --git a/specs/renderer-spec.md b/specs/renderer-spec.md index 97925e19..8944225a 100644 --- a/specs/renderer-spec.md +++ b/specs/renderer-spec.md @@ -474,9 +474,10 @@ capability, output, and invalidation rules in its own section of this specification. Synchronized output (§7.9) and pointer shape (§7.10) are specified so far. -Color encoding, Kitty keyboard mode setup, and Kitty graphics emission are -deferred to their respective follow-up PRs. The renderer continues to emit its -existing hardcoded ANSI output until each is specified. +Color encoding is specified in the +[Color Encoding Specification](color-encoding-spec.md). Kitty keyboard mode +setup and Kitty graphics emission are deferred to their respective follow-up +PRs. ### 7.9 Synchronized output (DEC mode 2026) @@ -601,7 +602,9 @@ parameters specify the terminal dimensions in character cells. The optional `terminfo` value (from `detectTerminal()`; see [Terminfo Specification](terminfo-spec.md) §10.1) initializes the Term's private `RuntimeCapabilities` from the static `Capabilities` it carries. When omitted, -the Term uses the §7.1 baseline. +the Term uses the §7.1 baseline. The renderer resolves its color encoding from +this capability snapshot; the derivation rule and downmapping behavior are +specified in the [Color Encoding Specification](color-encoding-spec.md). ### 8.2 Render invocation @@ -855,16 +858,17 @@ The renderer reads this from the OSC 10/11 theme probe, surfaced as `RuntimeCapabilities.theme.foreground` / `.background` (terminfo-spec §6.4), using the theme in effect when the frame renders. The result is an ordinary opaque sRGB color (alpha 255): it renders exactly like the equivalent `rgba()` -value, as truecolor. When the theme has not yet reported that color, the keyword -falls back to its field's own terminal default instead (the same-field behavior -above). A theme report that `update()` folds in after a frame renders takes -effect starting with the next render. +value, encoded for the active color tier +([Color Encoding Specification](color-encoding-spec.md) §6). When the theme has +not yet reported that color, the keyword falls back to its field's own terminal +default instead (the same-field behavior above). A theme report that `update()` +folds in after a frame renders takes effect starting with the next render. For example, once the terminal has reported its default foreground color, -`text({ bg: "CanvasText" })` paints that color as an opaque truecolor -background. Until then it falls back to the default background: a terminal -offers no way to paint its default foreground color as a cell background without -knowing its RGB value, and the renderer never guesses one. +`text({ bg: "CanvasText" })` paints that color as an opaque background. Until +then it falls back to the default background: a terminal offers no way to paint +its default foreground color as a cell background without knowing its RGB value, +and the renderer never guesses one. A terminal-themed color (a same-field default, or a palette entry) is opaque. A palette color in a foreground field is emitted as SGR `30`–`37` for palette 0–7 diff --git a/src/clayterm.c b/src/clayterm.c index d9cc79f0..53b2e91e 100644 --- a/src/clayterm.c +++ b/src/clayterm.c @@ -44,6 +44,12 @@ struct Clayterm { * CLAYTERM_THEME_KNOWN | 0xRRGGBB, or 0 until reported. Retained across * resize updates. */ uint32_t theme_fg, theme_bg; + /* max_colors evidence (color-encoding-spec §4.2); §7.1 baseline is 256. */ + uint32_t colors; + /* Emission tier, resolved once per reduce. last_tier detects tier + * changes, which force a complete redraw (color-encoding-spec CI-5). */ + int tier; + int last_tier; }; /* 128 bytes per cell: ~84 bytes worst-case for CUP + SGR sequences, plus up @@ -148,6 +154,136 @@ static void append_combining(struct Clayterm *ct, int x, int y, uint32_t cp) { report_combining_exceeded(ct); } +/* ── Color tiers and downmapping ──────────────────────────────────── */ + +/* Emission tiers (color-encoding-spec §6.1). */ +#define TIER_TRUECOLOR 0 +#define TIER_256 1 +#define TIER_16 2 + +/* Nominal 16-color palette (color-encoding-spec §6.3.1): the renderer's + * canonical model of what each 4-bit index means for downmapping. Pure + * primaries for 0-7, pastel brights for 8-15. Not a claim about any + * terminal's actual palette. */ +static const uint32_t NOMINAL_PALETTE[16] = { + 0x000000, 0xff0000, 0x00ff00, 0xffff00, 0x0000ff, 0xff00ff, + 0x00ffff, 0xc0c0c0, 0x808080, 0xff5555, 0x55ff55, 0xffff55, + 0x5555ff, 0xff55ff, 0x55ffff, 0xffffff, +}; + +/* 6x6x6 color cube channel values (indices 16-231). */ +static const int CUBE_STEPS[6] = {0, 95, 135, 175, 215, 255}; + +/* Resolve the emission tier from the capability evidence pushed by the + * host (color-encoding-spec §6.1). The colors <= 16 boundary matches the + * colordepth denial mapping in terminfo-spec §6.3. */ +static int resolve_tier(const struct Clayterm *ct) { + if (ct->caps & RENDER_CAP_TRUE_COLOR) + return TIER_TRUECOLOR; + if (ct->colors <= 16) + return TIER_16; + return TIER_256; +} + +/* Nearest nominal palette entry by squared Euclidean distance; ties + * resolve to the lowest index (color-encoding-spec §6.3.2). */ +static int map_16(uint32_t rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + int best = 0; + int best_dist = -1; + for (int i = 0; i < 16; i++) { + uint32_t c = NOMINAL_PALETTE[i]; + int dr = r - (int)((c >> 16) & 0xff); + int dg = g - (int)((c >> 8) & 0xff); + int db = b - (int)(c & 0xff); + int dist = dr * dr + dg * dg + db * db; + if (best_dist < 0 || dist < best_dist) { + best_dist = dist; + best = i; + } + } + return best; +} + +/* The cube step for an exact cube value, or -1 when the value is not a + * cube channel value. */ +static int cube_exact(int v) { + for (int i = 0; i < 6; i++) { + if (CUBE_STEPS[i] == v) + return i; + } + return -1; +} + +/* Nearest cube step for an arbitrary channel value; ties resolve to the + * smaller value (color-encoding-spec §6.3.3 rule 4). */ +static int cube_step(int v) { + int best = 0; + int best_dist = -1; + for (int i = 0; i < 6; i++) { + int d = v - CUBE_STEPS[i]; + if (d < 0) + d = -d; + if (best_dist < 0 || d < best_dist) { + best_dist = d; + best = i; + } + } + return best; +} + +/* Downmap a 24-bit RGB value to a 256-palette index. Ordered rules; + * the first match wins (color-encoding-spec §6.3.3). Rules 1-3 make + * every 256-palette entry resolve to an index of the identical color + * (CI-4; the nominal index wins where the palettes overlap). */ +static int map_256(uint32_t rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + + /* 1. exact nominal match: standard colors keep their 4-bit indices */ + for (int i = 0; i < 16; i++) { + if (NOMINAL_PALETTE[i] == rgb) + return i; + } + + /* 2. exact cube match */ + int cr = cube_exact(r); + int cg = cube_exact(g); + int cb = cube_exact(b); + if (cr >= 0 && cg >= 0 && cb >= 0) + return 16 + 36 * cr + 6 * cg + cb; + + /* 3. grayscale: nearest of the ramp extended by both endpoints. + * Candidates run in ascending index order (16, 231, 232..255), so a + * strict comparison resolves ties to the lowest index. */ + if (r == g && g == b) { + int best = 16; + int best_dist = r; /* value 0 at index 16 */ + int d = 255 - r; /* value 255 at index 231 */ + if (d < best_dist) { + best = 231; + best_dist = d; + } + for (int i = 0; i < 24; i++) { + int val = 8 + 10 * i; + d = r - val; + if (d < 0) + d = -d; + if (d < best_dist) { + best = 232 + i; + best_dist = d; + } + } + return best; + } + + /* 4. nearest cube value per channel */ + return 16 + 36 * cube_step(r) + 6 * cube_step(g) + cube_step(b); +} + /* ── Escape sequence generation ───────────────────────────────────── */ static void emit_palette(Buffer *out, int index, int base, int bright) { @@ -156,6 +292,38 @@ static void emit_palette(Buffer *out, int index, int base, int bright) { buf_put(out, "m", 1); } +/* Emit the SGR color sequence for one packed RGB value under the active + * tier (color-encoding-spec §6.2). `is_fg` selects the foreground + * (38, 3x/9x) or background (48, 4x/10x) code family. */ +static void emit_sgr_color(struct Clayterm *ct, uint32_t rgb, int is_fg) { + Buffer *out = &ct->frames.current->context->output; + switch (ct->tier) { + case TIER_16: { + int idx = map_16(rgb); + int base = is_fg ? 30 : 40; + if (idx >= 8) + base += 60; /* aixterm bright codes: 90-97 / 100-107 */ + buf_str(out, "\x1b["); + buf_num(out, base + (idx & 7)); + buf_put(out, "m", 1); + break; + } + case TIER_256: + buf_str(out, is_fg ? "\x1b[38;5;" : "\x1b[48;5;"); + buf_num(out, map_256(rgb)); + buf_put(out, "m", 1); + break; + default: /* TIER_TRUECOLOR */ + buf_str(out, is_fg ? "\x1b[38;2;" : "\x1b[48;2;"); + buf_num(out, (rgb >> 16) & 0xff); + buf_put(out, ";", 1); + buf_num(out, (rgb >> 8) & 0xff); + buf_put(out, ";", 1); + buf_num(out, rgb & 0xff); + buf_put(out, "m", 1); + } +} + static void emit_attr(struct Clayterm *ct, uint32_t fg, uint32_t bg) { Frame *frame = ct->frames.current; Buffer *out = &frame->context->output; @@ -181,18 +349,12 @@ static void emit_attr(struct Clayterm *ct, uint32_t fg, uint32_t bg) { if (fg & ATTR_STRIKEOUT) buf_str(out, "\x1b[9m"); - /* foreground: palette, truecolor, or default (left by the reset) */ + /* foreground: palette, tiered RGB, or default (left by the reset) */ if (fg & ATTR_DEFAULT) { if (fg & ATTR_PALETTE) emit_palette(out, (int)(fg & 0xff), 30, 90); } else { - buf_str(out, "\x1b[38;2;"); - buf_num(out, (fg >> 16) & 0xff); - buf_put(out, ";", 1); - buf_num(out, (fg >> 8) & 0xff); - buf_put(out, ";", 1); - buf_num(out, fg & 0xff); - buf_put(out, "m", 1); + emit_sgr_color(ct, fg & COLOR_MASK, 1); } /* background: same */ @@ -200,13 +362,7 @@ static void emit_attr(struct Clayterm *ct, uint32_t fg, uint32_t bg) { if (bg & ATTR_PALETTE) emit_palette(out, (int)(bg & 0xff), 40, 100); } else { - buf_str(out, "\x1b[48;2;"); - buf_num(out, (bg >> 16) & 0xff); - buf_put(out, ";", 1); - buf_num(out, (bg >> 8) & 0xff); - buf_put(out, ";", 1); - buf_num(out, bg & 0xff); - buf_put(out, "m", 1); + emit_sgr_color(ct, bg & COLOR_MASK, 0); } frame->emission.lastfg = fg; @@ -812,6 +968,8 @@ struct Clayterm *clayterm_init(void *mem, int w, int h, int runlist_capacity) { struct Clayterm *ct = (struct Clayterm *)mem; *ct = (struct Clayterm){0}; ct->runlist_capacity = (uint32_t)runlist_capacity; + ct->colors = 256; /* §7.1 baseline until the host pushes evidence */ + ct->last_tier = -1; char *base = (char *)ct + align8(sizeof(struct Clayterm)); frame_context_init(&ct->frames, base, ct->runlist_capacity); clayterm_resize(ct, w, h); @@ -866,7 +1024,10 @@ void clayterm_resize(struct Clayterm *ct, int w, int h) { cells_fill(ct->frames.previous->cells, w, h, 0, 0, 0); } -void set_capabilities(struct Clayterm *ct, uint32_t caps) { ct->caps = caps; } +void set_capabilities(struct Clayterm *ct, uint32_t caps, uint32_t colors) { + ct->caps = caps; + ct->colors = colors; +} void set_theme(struct Clayterm *ct, uint32_t fg, uint32_t bg) { ct->theme_fg = fg; @@ -1413,6 +1574,18 @@ static void draw_current_frame(struct Clayterm *ct, static void write_current_frame(struct Clayterm *ct, int mode, int row) { Frame *frame = ct->frames.current; Buffer *out = &frame->context->output; + + /* Resolve the emission tier for this frame and force a complete + * redraw when it changed (color-encoding-spec CI-5): diff state is + * cell-based, so unchanged cells would otherwise keep bytes from the + * previous encoding on screen. Zeroing the previous frame's cells makes + * every cell diff as changed. */ + ct->tier = resolve_tier(ct); + if (ct->tier != ct->last_tier) { + cells_fill(ct->frames.previous->cells, ct->w, ct->h, 0, 0, 0); + ct->last_tier = ct->tier; + } + if (mode == 1) { present_lines(ct); } else { diff --git a/src/clayterm.h b/src/clayterm.h index 9af51619..fd302d9d 100644 --- a/src/clayterm.h +++ b/src/clayterm.h @@ -12,6 +12,7 @@ struct Clayterm; /* Capability bits for set_capabilities(). */ #define RENDER_CAP_SYNC_OUTPUT (1u << 0) #define RENDER_CAP_POINTER_SHAPE (1u << 1) +#define RENDER_CAP_TRUE_COLOR (1u << 2) /* Packed directives and their property-group masks. */ #define CLAYTERM_OP_OPEN_ELEMENT 0x02 @@ -50,7 +51,7 @@ struct Clayterm; int clayterm_size(int w, int h, int runlist_capacity); struct Clayterm *clayterm_init(void *mem, int w, int h, int runlist_capacity); void clayterm_resize(struct Clayterm *ct, int w, int h); -void set_capabilities(struct Clayterm *ct, uint32_t caps); +void set_capabilities(struct Clayterm *ct, uint32_t caps, uint32_t colors); void set_theme(struct Clayterm *ct, uint32_t fg, uint32_t bg); int reduce(struct Clayterm *ct, uint32_t *buf, int len, int mode, int row, float deltaTime, float px, float py, int pointer); diff --git a/term-native.ts b/term-native.ts index 057a789f..631801d7 100644 --- a/term-native.ts +++ b/term-native.ts @@ -53,10 +53,13 @@ function themeWord(rgb: RenderRgb | undefined): number { export interface RenderCapabilities { syncOutput: boolean; pointerShape: boolean; + colors: number; + trueColor: boolean; } const RENDER_CAP_SYNC_OUTPUT = 1 << 0; const RENDER_CAP_POINTER_SHAPE = 1 << 1; +const RENDER_CAP_TRUE_COLOR = 1 << 2; /** Pointer passed to reduce(): absent, up, or down. */ export const POINTER_ABSENT = 0; @@ -164,7 +167,7 @@ export async function createTermNative( ): number; output(ct: number): number; length(ct: number): number; - set_capabilities(ct: number, caps: number): void; + set_capabilities(ct: number, caps: number, colors: number): void; set_theme(ct: number, fg: number, bg: number): void; pointer_over_count(ct: number): number; pointer_over_id_string_length(ct: number, index: number): number; @@ -192,8 +195,9 @@ export async function createTermNative( let opsBuf = 0; function setCaps(next: RenderCapabilities): void { let flags = (next.syncOutput ? RENDER_CAP_SYNC_OUTPUT : 0) | - (next.pointerShape ? RENDER_CAP_POINTER_SHAPE : 0); - ct.set_capabilities(statePtr!, flags); + (next.pointerShape ? RENDER_CAP_POINTER_SHAPE : 0) | + (next.trueColor ? RENDER_CAP_TRUE_COLOR : 0); + ct.set_capabilities(statePtr!, flags, next.colors); } // Native storage keeps both frames' runlists and metadata before the cells, diff --git a/term.ts b/term.ts index 6defecd6..85eb30e0 100644 --- a/term.ts +++ b/term.ts @@ -189,6 +189,8 @@ export async function createTerm(options: TermOptions): Promise { let native = await createTermNative(width, height, { syncOutput: currentCaps.syncOutput, pointerShape: currentCaps.pointerShape, + colors: currentCaps.colors, + trueColor: currentCaps.trueColor, }); let { memory } = native; @@ -330,13 +332,19 @@ export async function createTerm(options: TermOptions): Promise { } } + // A color change resolves a new tier on the next render, which + // forces a complete redraw (color-encoding-spec §4.2, §6.4). if ( next.syncOutput !== currentCaps.syncOutput || - next.pointerShape !== currentCaps.pointerShape + next.pointerShape !== currentCaps.pointerShape || + next.colors !== currentCaps.colors || + next.trueColor !== currentCaps.trueColor ) { native.setCapabilities({ syncOutput: next.syncOutput, pointerShape: next.pointerShape, + colors: next.colors, + trueColor: next.trueColor, }); } if ( diff --git a/test/border.test.ts b/test/border.test.ts index 79c083e5..b134462b 100644 --- a/test/border.test.ts +++ b/test/border.test.ts @@ -8,6 +8,7 @@ import { text, } from "../ops.ts"; import { createTerm } from "../term.ts"; +import { TRUECOLOR_INFO } from "./caps.ts"; import { describe, expect, it } from "./suite.ts"; import { print } from "./print.ts"; @@ -120,7 +121,11 @@ type OpenProps = Omit; * mode and parses the full-frame output into cells. Box corners are at * (0,0), (7,0), (0,3), (7,3). */ async function renderBox(props: OpenProps): Promise { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("box", { @@ -269,7 +274,11 @@ describe("structured sides", () => { }); it("does not retain a prior frame's side bg", async () => { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let frame = (bg?: number) => [ open("box", { layout: { width: fixed(8), height: fixed(4) }, @@ -455,8 +464,16 @@ describe("directive model", () => { describe("instances", () => { it("does not share side attributes between Term instances", async () => { - let a = await createTerm({ width: 12, height: 5 }); - let b = await createTerm({ width: 12, height: 5 }); + let a = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); + let b = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let frame = (top: number, bottom: number) => [ open("box", { @@ -495,7 +512,11 @@ const trim = (s: string) => s.split("\n").map((l) => l.trimEnd()).join("\n"); describe("box model", () => { it("full border with no padding reserves space: children visible, box is 3 rows", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -514,7 +535,11 @@ describe("box model", () => { }); it("partial borders (top+left) reserve only their sides", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -534,7 +559,11 @@ describe("box model", () => { }); it("padding is additive: border=1 alone gives height 3; border=1 plus padding=1 gives height 5", async () => { - let nopad = await createTerm({ width: 20, height: 10 }); + let nopad = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let r1 = nopad.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -548,7 +577,11 @@ describe("box model", () => { close(), ]); - let withpad = await createTerm({ width: 20, height: 10 }); + let withpad = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let r2 = withpad.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -573,7 +606,11 @@ describe("box model", () => { }); it("explicit padding > border width adds breathing room inside the border", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -597,7 +634,11 @@ describe("box model", () => { }); it("nested two-tone bevel lays out without manual padding compensation", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -623,7 +664,11 @@ describe("box model", () => { }); it("visual: full border renders border glyphs around content", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let out = trim( print( decode( @@ -725,7 +770,11 @@ describe("system colors", () => { }); it("renders a probed default background as a truecolor border side fg once the theme reports it", async () => { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -751,7 +800,11 @@ describe("system colors", () => { describe("currentcolor", () => { it("defaults border.color to currentcolor, inherited from an ancestor open", async () => { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: RED }), diff --git a/test/caps.ts b/test/caps.ts index ef816818..62105f24 100644 --- a/test/caps.ts +++ b/test/caps.ts @@ -1,4 +1,8 @@ -import { type DetectOptions, detectTerminal } from "../terminfo.ts"; +import { + type DetectOptions, + detectTerminal, + type TerminalInfo, +} from "../terminfo.ts"; export function offlineDetect(options: Partial = {}) { return detectTerminal({ env: {}, ...options }); @@ -8,3 +12,23 @@ export function offlineDetect(options: Partial = {}) { export function trueColorDetect() { return offlineDetect({ env: { COLORTERM: "truecolor" } }); } + +/** Static truecolor evidence with no probe or key payload. Tests that pin + * truecolor byte sequences pass this at createTerm to select the truecolor + * tier (color-encoding-spec §8): without evidence the renderer resolves the + * 256-color baseline tier. */ +export const TRUECOLOR_INFO: TerminalInfo = Object.freeze({ + capabilities: Object.freeze({ + colors: 256, + trueColor: true, + bce: true, + autoMargin: true, + xenl: true, + altScreen: true, + styledUnderline: false, + syncOutput: false, + pointerShape: false, + }), + probe: new Uint8Array(0), + keys: new Uint8Array(0), +}); diff --git a/test/color-encoding-modes.test.ts b/test/color-encoding-modes.test.ts new file mode 100644 index 00000000..07d5a566 --- /dev/null +++ b/test/color-encoding-modes.test.ts @@ -0,0 +1,356 @@ +// deno-lint-ignore-file no-control-regex +import { describe, expect, it } from "./suite.ts"; +import { createTerm } from "../term.ts"; +import type { TerminalInfo } from "../terminfo.ts"; +import { close, fixed, grow, type Op, open, rgba, text } from "../ops.ts"; + +const decode = (b: Uint8Array) => new TextDecoder().decode(b); + +/** Static capability evidence with a chosen `colors` value and optional + * truecolor grant. The renderer resolves its emission tier from these + * fields alone (color-encoding-spec §6.1). */ +function info(colors: number, trueColor = false): TerminalInfo { + return Object.freeze({ + capabilities: Object.freeze({ + colors, + trueColor, + bce: true, + autoMargin: true, + xenl: true, + altScreen: true, + styledUnderline: false, + syncOutput: false, + pointerShape: false, + }), + probe: new Uint8Array(0), + keys: new Uint8Array(0), + }); +} + +/** Frame: one full-screen text node carrying the given color/bg. */ +function coloredText( + color?: number, + bg?: number, +): Op[] { + return [ + open("root", { layout: { width: grow(), height: grow() } }), + text("X", { color, bg }), + close(), + ]; +} + +/** The SGR bytes emitted before the glyph. */ +function beforeGlyph(ansi: string): string { + return ansi.slice(0, ansi.indexOf("X")); +} + +describe("color encoding modes", () => { + describe("16-color tier", () => { + it("downgrades standard red foreground to the 4-bit code", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + let before = beforeGlyph(ansi); + // pins: standard-palette red maps to 4-bit \x1b[31m + expect(before).toContain("\x1b[31m"); + // pins: the 24-bit sequence must not survive the downgrade + expect(before).not.toContain("\x1b[38;2;255;0;0"); + }); + + it("downgrades standard red background to the 4-bit code", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode( + term.render(coloredText(undefined, rgba(255, 0, 0))).output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[41m"); + expect(before).not.toContain("\x1b[48;2;255;0;0"); + }); + + it("maps bright palette colors to aixterm codes", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode(term.render(coloredText(rgba(255, 85, 85))).output); + + // #ff5555 is nominal index 9 → bright red foreground + expect(beforeGlyph(ansi)).toContain("\x1b[91m"); + }); + + it("maps non-palette colors to the nearest nominal entry", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + // #aa0000 is nearer nominal red (index 1) than any other entry + let ansi = decode(term.render(coloredText(rgba(170, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[31m"); + }); + }); + + describe("256-color tier", () => { + it("downgrades standard red foreground to its palette index", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + // pins: standard-palette red maps to index 1 + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;1m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[38;2;255;0;0"); + }); + + it("downgrades standard red background to its palette index", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + let ansi = decode( + term.render(coloredText(undefined, rgba(255, 0, 0))).output, + ); + + expect(beforeGlyph(ansi)).toContain("\x1b[48;5;1m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[48;2;255;0;0"); + }); + + it("round-trips exact cube colors", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + // #5f5f5f is cube (1,1,1) → index 16 + 36 + 6 + 1 = 59 + let ansi = decode(term.render(coloredText(rgba(95, 95, 95))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;59m"); + }); + + it("maps equal-channel grays onto the grayscale ramp", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + // (100,100,100): nearest ramp value is 98 (i=9) → index 241 + let ansi = decode(term.render(coloredText(rgba(100, 100, 100))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;241m"); + }); + + it("maps non-palette colors to the nearest cube value per channel", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + // (250,10,10) → cube steps (5,0,0) → index 196 + let ansi = decode(term.render(coloredText(rgba(250, 10, 10))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); + }); + }); + + describe("truecolor tier", () => { + it("emits byte-identical historical sequences", async () => { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(256, true), + }); + let ansi = decode( + term.render(coloredText(rgba(255, 0, 0), rgba(0, 0, 255))).output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[38;2;255;0;0m"); + expect(before).toContain("\x1b[48;2;0;0;255m"); + expect(before).not.toContain("38;5;"); + }); + }); + + describe("tier resolution", () => { + it("resolves the 256-color baseline without evidence", async () => { + let term = await createTerm({ width: 4, height: 1 }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;1m"); + }); + + it("resolves the 16-color tier at and below 16 colors", async () => { + for (let colors of [8, 16]) { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(colors), + }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + expect(beforeGlyph(ansi)).toContain("\x1b[31m"); + } + }); + + it("resolves the 256-color tier above 16 colors", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(17) }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;1m"); + }); + + it("resolves the truecolor tier on a granted truecolor flag", async () => { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(16, true), + }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;2;255;0;0m"); + }); + }); + + describe("dynamic evidence", () => { + it("applies a colordepth event from the next render", async () => { + let term = await createTerm({ width: 4, height: 1 }); + let ops = coloredText(rgba(255, 0, 0)); + + expect(decode(term.render(ops).output)).toContain("\x1b[38;5;1m"); + + term.update([ + { type: "capability", key: "colordepth", value: "truecolor" }, + ]); + + // The next render encodes in the new tier + expect(decode(term.render(ops).output)).toContain("\x1b[38;2;255;0;0m"); + }); + + it("redraws the complete frame after a tier change", async () => { + let term = await createTerm({ width: 4, height: 1 }); + let ops = coloredText(rgba(255, 0, 0)); + + term.render(ops); + // no redraw while the tier is stable + expect(term.render(ops).output.length).toBe(0); + + term.update([ + { type: "capability", key: "colordepth", value: "truecolor" }, + ]); + let out = term.render(ops).output; + // CI-5: the frame after a tier change is a complete redraw + expect(out.length).toBeGreaterThan(0); + expect(decode(out)).toContain("X"); + + // the tier has settled: diffing resumes + expect(term.render(ops).output.length).toBe(0); + }); + + it("downgrades on a colordepth denial event", async () => { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(256, true), + }); + let ops = coloredText(rgba(255, 0, 0)); + + expect(decode(term.render(ops).output)).toContain("\x1b[38;2;255;0;0m"); + + term.update([{ type: "capability", key: "colordepth", value: "256" }]); + expect(decode(term.render(ops).output)).toContain("\x1b[38;5;1m"); + }); + }); + + describe("default colors", () => { + it("emits no color SGR for default fg/bg in any tier", async () => { + for (let caps of [info(16), info(256), info(256, true)]) { + let term = await createTerm({ width: 4, height: 1, terminfo: caps }); + let ansi = decode(term.render(coloredText()).output); + + expect(ansi).toContain("X"); + expect(ansi).not.toMatch(/\x1b\[(3\d|4\d|9\d|10\d|38|48)/); + } + }); + }); + + describe("terminal-themed colors", () => { + it("emits palette colors as 4-bit codes in every tier", async () => { + for (let caps of [info(16), info(256), info(256, true)]) { + let term = await createTerm({ width: 4, height: 1, terminfo: caps }); + let ansi = decode( + term.render([ + text("X", { color: "-ansi-red", bg: "-ansi-bright-blue" }), + ]) + .output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[31m"); + expect(before).toContain("\x1b[104m"); + expect(before).not.toMatch(/\x1b\[(38|48);/); + } + }); + + it("encodes a probed theme color for the active tier", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + term.update([ + { + type: "capability", + key: "foreground-color", + value: { r: 255, g: 0, b: 0 }, + }, + ]); + let ansi = decode( + term.render([text("X", { bg: "CanvasText" })]).output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[48;5;1m"); + expect(before).not.toContain("\x1b[48;2;"); + }); + }); + + describe("palette round-trip", () => { + it("maps every 256-palette entry to an index of the same color", async () => { + let NOMINAL = [ + 0x000000, + 0xff0000, + 0x00ff00, + 0xffff00, + 0x0000ff, + 0xff00ff, + 0x00ffff, + 0xc0c0c0, + 0x808080, + 0xff5555, + 0x55ff55, + 0xffff55, + 0x5555ff, + 0xff55ff, + 0x55ffff, + 0xffffff, + ]; + let CUBE = [0, 95, 135, 175, 215, 255]; + let rgbOf = (i: number): number => { + if (i < 16) return NOMINAL[i]; + if (i < 232) { + let n = i - 16; + return (CUBE[Math.floor(n / 36)] << 16) | + (CUBE[Math.floor(n / 6) % 6] << 8) | + CUBE[n % 6]; + } + let v = 8 + 10 * (i - 232); + return (v << 16) | (v << 8) | v; + }; + + // A 16x16 grid whose cell k carries palette color k. + let term = await createTerm({ width: 16, height: 16 }); + let ops: Op[] = [ + open("root", { + layout: { width: grow(), height: grow(), direction: "ttb" }, + }), + ]; + for (let row = 0; row < 16; row++) { + ops.push( + open(`row${row}`, { + layout: { width: grow(), height: fixed(1), direction: "ltr" }, + }), + ); + for (let col = 0; col < 16; col++) { + let rgb = rgbOf(row * 16 + col); + ops.push(text(".", { + bg: rgba((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff), + })); + } + ops.push(close()); + } + ops.push(close()); + + let ansi = decode(term.render(ops).output); + let indices = [...ansi.matchAll(/\x1b\[48;5;(\d+)m/g)].map((m) => + Number(m[1]) + ); + expect(indices.length).toBe(256); + for (let k = 0; k < 256; k++) { + // The emitted index must represent the identical color (CI-4). + expect(rgbOf(indices[k])).toBe(rgbOf(k)); + } + }); + }); +}); diff --git a/test/color.test.ts b/test/color.test.ts index 404b5117..c9ad3485 100644 --- a/test/color.test.ts +++ b/test/color.test.ts @@ -1,5 +1,6 @@ import { close, fixed, grow, type Op, open, rgba, text } from "../ops.ts"; import { createTerm } from "../term.ts"; +import { TRUECOLOR_INFO } from "./caps.ts"; import { describe, expect, it } from "./suite.ts"; const decode = (b: Uint8Array) => new TextDecoder().decode(b); @@ -72,7 +73,11 @@ function firstCell(cells: Cell[], ch: string): Cell { describe("foreground", () => { it("emits uncolored text with no foreground", async () => { - let term = await createTerm({ width: 12, height: 1 }); + let term = await createTerm({ + width: 12, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode(term.render([text("hi")]).output); expect(ansi).toContain("hi"); @@ -82,7 +87,11 @@ describe("foreground", () => { describe("background", () => { it("fills border cells with the requested border-level bg", async () => { - let term = await createTerm({ width: 12, height: 4 }); + let term = await createTerm({ + width: 12, + height: 4, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -112,7 +121,11 @@ describe("background", () => { }); it("leaves existing border-cell bg unchanged when border bg is omitted", async () => { - let term = await createTerm({ width: 12, height: 4 }); + let term = await createTerm({ + width: 12, + height: 4, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -140,7 +153,11 @@ describe("background", () => { }); it("fills glyph cells with the requested text-level bg", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -155,7 +172,11 @@ describe("background", () => { }); it("resets border bg on subsequent frames without border bg", async () => { - let term = await createTerm({ width: 12, height: 4 }); + let term = await createTerm({ + width: 12, + height: 4, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); // Frame 1: border with bg @@ -198,7 +219,11 @@ describe("background", () => { }); it("resets the background before writing trailing cells", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -222,7 +247,11 @@ describe("background", () => { describe("hex color strings", () => { it("renders text bg from a 3-digit hex string", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -235,7 +264,11 @@ describe("hex color strings", () => { }); it("renders text fg from a 6-digit hex string", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -248,7 +281,11 @@ describe("hex color strings", () => { }); it("matches hex case-insensitively", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -262,7 +299,11 @@ describe("hex color strings", () => { }); it("expands 4- and 8-digit hex with doubled digits", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -276,7 +317,11 @@ describe("hex color strings", () => { }); it("fills element bg from a hex string", async () => { - let term = await createTerm({ width: 8, height: 2 }); + let term = await createTerm({ + width: 8, + height: 2, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { @@ -307,7 +352,11 @@ describe("hex color strings", () => { describe("CSS color strings", () => { it("renders fg and bg from CSS color functions and names", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -450,7 +499,11 @@ describe("system colors", () => { }); it("overwrites an enclosing bg with an explicit Canvas element bg", async () => { - let term = await createTerm({ width: 8, height: 1 }); + let term = await createTerm({ + width: 8, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { @@ -490,7 +543,11 @@ describe("system colors", () => { }); it("re-emits cells whose color changes between palette, default, and sRGB", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let frame = (color: number | string) => decode(term.render([text("Hi", { color })]).output); @@ -505,7 +562,11 @@ describe("system colors", () => { }); it("re-emits cells whose bg changes between palette, default, and sRGB", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let frame = (bg: number | string) => decode( term.render([ @@ -528,7 +589,11 @@ describe("system colors", () => { }); it("paints a probed default foreground as a truecolor text bg once the theme reports it", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let before = decode( term.render([text("Hi", { bg: "CanvasText" })]).output, ); @@ -548,7 +613,11 @@ describe("system colors", () => { }); it("paints a probed default foreground as a truecolor element bg once the theme reports it", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -569,7 +638,11 @@ describe("system colors", () => { }); it("paints a probed default background as a truecolor border side fg", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -612,7 +685,11 @@ describe("system colors", () => { }); it("keeps the probed theme across a resize", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -628,7 +705,11 @@ describe("system colors", () => { }); it("resolves a replayed cross-field keyword against a theme reported after its source render", async () => { - let term = await createTerm({ width: 8, height: 1 }); + let term = await createTerm({ + width: 8, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("wrap", { layout: { padding: { left: 2 } } }), open("box"), @@ -670,7 +751,11 @@ describe("system colors", () => { describe("foreground inheritance and currentcolor", () => { it("inherits an ancestor open's color through nested opens to text", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -685,7 +770,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("overrides the inherited color for itself and its descendants", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -746,7 +835,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves text bg currentcolor to the inherited color", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -759,7 +852,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves text bg currentcolor to the element's own explicit color over an ancestor's", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -772,7 +869,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves open bg currentcolor to its own color", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("box", { @@ -803,7 +904,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves text bg currentcolor to the probed theme foreground once reported", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -842,8 +947,16 @@ describe("foreground inheritance and currentcolor", () => { ...children, close(), ]; - let replayed = await createTerm({ width: 10, height: 1 }); - let direct = await createTerm({ width: 10, height: 1 }); + let replayed = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); + let direct = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let result = replayed.render(frame("#ff0000", ...child)); direct.render(frame("#ff0000", ...child)); diff --git a/test/pack.test.ts b/test/pack.test.ts index d41aa869..8677f503 100644 --- a/test/pack.test.ts +++ b/test/pack.test.ts @@ -86,6 +86,8 @@ describe("pack", () => { let native = await createTermNative(8, 1, { syncOutput: false, pointerShape: false, + colors: 256, + trueColor: false, }); let overhead = pack([open(""), close()], new ArrayBuffer(64), 0) * 4; let id = "x".repeat(native.opsCapacity - overhead); diff --git a/test/term.test.ts b/test/term.test.ts index db44aa22..86cb664b 100644 --- a/test/term.test.ts +++ b/test/term.test.ts @@ -4,7 +4,7 @@ import { createTerm, type Term } from "../term.ts"; import type { InputEvent } from "../input.ts"; import { close, fixed, grow, type Op, open, rgba, text } from "../ops.ts"; import { print } from "./print.ts"; -import { trueColorDetect } from "./caps.ts"; +import { TRUECOLOR_INFO, trueColorDetect } from "./caps.ts"; const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes); const trim = (s: string) => s.split("\n").map((l) => l.trimEnd()).join("\n"); @@ -34,9 +34,16 @@ describe("term", () => { expect(out).toContain("Hello, World!"); }); - it("text inherits parent background", () => { + it("text inherits parent background", async () => { + // Truecolor evidence selects the truecolor tier (color-encoding-spec + // §6.1); this test pins truecolor background bytes. + let local = await createTerm({ + width: 40, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( - term.render([ + local.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, bg: rgba(255, 0, 0), diff --git a/test/transitions.test.ts b/test/transitions.test.ts index 0ae41df8..55f816d5 100644 --- a/test/transitions.test.ts +++ b/test/transitions.test.ts @@ -9,6 +9,7 @@ import { rgba, text, } from "../mod.ts"; +import { TRUECOLOR_INFO } from "./caps.ts"; import { print } from "./print.ts"; const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes); @@ -121,7 +122,11 @@ describe("transitions", () => { describe("system colors", () => { it("switches between sRGB and a system color at half progress", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let frame = (bg: number | string, deltaTime: number) => new TextDecoder().decode( term.render([ diff --git a/test/width.test.ts b/test/width.test.ts index 85477ac6..ce42f83a 100644 --- a/test/width.test.ts +++ b/test/width.test.ts @@ -141,6 +141,8 @@ describe("width", () => { let native = await createTermNative(10, 3, { syncOutput: false, pointerShape: false, + colors: 256, + trueColor: false, }); // TextEncoder never produces surrogate bytes, so pack a placeholder From 2264f656a05eaf18c7105568ad1729e0e69bbab2 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 08:49:51 -0500 Subject: [PATCH 2/9] Delete .changeset/color-encoding-tiers.md --- .changeset/color-encoding-tiers.md | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 .changeset/color-encoding-tiers.md diff --git a/.changeset/color-encoding-tiers.md b/.changeset/color-encoding-tiers.md deleted file mode 100644 index e00138e0..00000000 --- a/.changeset/color-encoding-tiers.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -"@bomb.sh/tty": minor ---- - -The renderer now derives its SGR color encoding from the terminal's capability evidence instead of always emitting 24-bit truecolor. Truecolor evidence (`RGB`/`Tc` terminfo extension, `COLORTERM`, direct-color entries with `max_colors ≥ 2²⁴`, or a `colordepth` probe response folded through `term.update()`) keeps the historical byte-identical truecolor output. Without truecolor evidence, cells emit 256-color SGR (`\x1b[38;5;Nm`) when the resolved palette exceeds 16 colors, or 4-bit SGR (`\x1b[31m`) at or below 16. - -Colors are downmapped deterministically: standard palette colors keep their classic indices (`rgba(255,0,0)` → `\x1b[31m` / `\x1b[38;5;1m`), grays use the 240-step grayscale ramp, and everything else rounds to the 6×6×6 cube. System palette colors (`-ansi-red`, …) are already 4-bit and emit unchanged in every tier. A tier change between frames forces a complete redraw so no stale encoding survives on screen. - -**Breaking:** rendering without color evidence now produces 256-color bytes where it previously produced truecolor. Run `detectTerminal()` and pass its `TerminalInfo` to `createTerm` (or fold probe responses with `term.update()`) to keep truecolor output — terminals that support truecolor report it. - -#### Migration - -```diff - import { createTerm } from "@bomb.sh/tty"; -+ import { detectTerminal } from "@bomb.sh/tty"; - -- const term = await createTerm({ width, height }); -+ const terminfo = await detectTerminal(); -+ const term = await createTerm({ width, height, terminfo }); -``` From 91d76382a951eed45532d5317ca25c8afc554900 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 09:00:37 -0500 Subject: [PATCH 3/9] chore: add changeset for color-encoding tiers --- .changeset/color-encoding-tiers.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/color-encoding-tiers.md diff --git a/.changeset/color-encoding-tiers.md b/.changeset/color-encoding-tiers.md new file mode 100644 index 00000000..94705948 --- /dev/null +++ b/.changeset/color-encoding-tiers.md @@ -0,0 +1,20 @@ +--- +'@bomb.sh/tty': minor +--- + +Adds capability-aware SGR color encoding to the renderer. + +The renderer now derives its color encoding from terminal capability evidence instead of always emitting 24-bit truecolor. Terminals with truecolor evidence (`RGB`/`Tc`, `COLORTERM`, direct-color `max_colors`, or a `colordepth` probe folded through `term.update()`) continue to receive byte-identical truecolor output. Without truecolor evidence, cells emit 256-color SGR (`\x1b[38;5;Nm`) when `colors > 16`, or 4-bit SGR (`\x1b[31m`) at or below 16. Colors are downmapped deterministically: nominal palette entries keep their classic indices, grays use the grayscale ramp, and everything else rounds to the 6×6×6 cube. A tier change between frames forces a complete redraw. + +The baseline — no capability evidence — now resolves to 256-color rather than truecolor. Pass `detectTerminal()` output to `createTerm` to restore truecolor output on terminals that support it. + +#### Migration + +```diff + import { createTerm } from "@bomb.sh/tty"; ++ import { detectTerminal } from "@bomb.sh/tty"; + +- const term = await createTerm({ width, height }); ++ const terminfo = await detectTerminal(); ++ const term = await createTerm({ width, height, terminfo }); +``` From 5489c326968e1750d415fd4baadca3609c3e2021 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 12:03:50 -0500 Subject: [PATCH 4/9] docs: trim color-encoding spec to end-user behavior MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop the architecture diagram, WASM state-ownership notes, test plan, rejected-alternative discussion, and deferred-work list; keep tier resolution, emission formats, downmapping, and tier-change output. Sections renumber accordingly (resolution §5, formats §6, downmapping §7, tier changes §8). renderer-spec §7.8 no longer references follow-up PR sequencing. --- specs/color-encoding-spec.md | 360 +++++++++-------------------------- specs/renderer-spec.md | 12 +- 2 files changed, 97 insertions(+), 275 deletions(-) diff --git a/specs/color-encoding-spec.md b/specs/color-encoding-spec.md index 48d42e59..3146a8b7 100644 --- a/specs/color-encoding-spec.md +++ b/specs/color-encoding-spec.md @@ -1,168 +1,87 @@ # Clayterm Color Encoding Specification -**Version:** 0.1 (draft) **Status:** Design specification for a work-in-progress -feature. Normative where it establishes invariants and contract. Descriptive -where surfaces may settle during implementation. +**Version:** 0.1 (draft) **Status:** Proposed. Normative for the SGR color +encoding of rendered cells. --- ## 1. Purpose -The renderer emits one SGR color encoding for every cell it paints. Historically -that encoding was hardcoded to 24-bit truecolor (`\x1b[38;2;R;G;Bm`), regardless -of what the destination terminal supports. A 16-color terminal, a CI log, or a -pipe receives sequences its destination renders poorly — or not at all — when -`\x1b[31m` would have been both smaller and more faithful. +The renderer encodes every non-default cell color as an SGR sequence. This +specification defines which encoding the renderer emits for a given capability +snapshot, and how 24-bit colors map into the 256-color and 16-color palettes +when the terminal lacks truecolor support. -This specification defines how the renderer derives its color encoding from the -capability snapshot it already maintains, and how it downmaps truecolor values -into narrower palettes when the evidence calls for it. It resolves the deferred -"color encoding" item in [renderer-spec.md](renderer-spec.md) §7.8 and the open -question from the capability-foundation work about where the renderer's -authoritative capability state lives. - -There is deliberately no caller-facing override. Capability evidence is the -single lever (TINV-3); an override would create a second source of truth that -could contradict probe responses. +The capability snapshot ([terminfo-spec.md](terminfo-spec.md)) is the only input +that selects the encoding. There is no caller-facing override: callers control +the encoding by supplying capability evidence, either a terminfo entry at +creation or probe responses folded through `update()`. --- ## 2. Scope -### In scope (normative) - -- The color tier resolution rule: how `trueColor` and `colors` in the capability - snapshot determine the emitted encoding tier -- Ownership of the renderer's color-capability state inside the WASM module -- Per-tier SGR emission formats for foreground and background colors -- The downmapping algorithms from 24-bit RGB to the 256-color and 16-color - palettes, including the normative nominal palette -- Output invalidation when the resolved tier changes between transactions - -### In scope (non-normative, descriptive) +### In scope -- Implementation notes for the C-side emission path -- The relationship between this specification and the failing-test reproduction - that motivated it +- How `trueColor` and `colors` in the capability snapshot select the encoding + tier +- The SGR format for foreground and background colors in each tier +- The mapping from 24-bit RGB to the 256-color and 16-color palettes +- Output when the tier changes between renders ### Out of scope -- **Terminal palette definition.** The renderer maps to palette _indices_; how a - terminal renders index N is the terminal's business. OSC 4 palette queries - remain deferred (terminfo-spec). -- **An `"8"`-color tier.** The 16-color tier already emits the base - `30–37`/`40–47` codes for indices 0–7. A dedicated 8-color tier would need - bright-index elision for marginal benefit; deferred. -- **88-color precision.** Terminals reporting `17 ≤ colors ≤ 255` resolve to the - 256 tier (§6.1); indices above 87 are the terminal's problem. -- **Per-render or per-call overrides.** Recorded as rejected in §7. -- **Other capability-driven emission** (synchronized output, pointer shape, - Kitty protocols) — each has its own focused specification path. +- **The terminal's palette.** The renderer emits palette _indices_. How a + terminal renders index N is the terminal's concern. +- **An 8-color tier.** Terminals reporting fewer than 16 colors use the 16-color + tier (§5). +- **88-color precision.** Terminals reporting `17 ≤ colors ≤ 255` use the + 256-color tier (§5). --- ## 3. Terminology -**Color tier.** One of `"truecolor" | "256" | "16"` — the same three-value -`ColorDepth` type defined in [terminfo-spec.md](terminfo-spec.md) §6.2. The tier -names the _emission encoding_, not the terminal's full capability set. +**Color tier.** One of `"truecolor" | "256" | "16"`, the `ColorDepth` type +defined in [terminfo-spec.md](terminfo-spec.md) §6.2. The tier names the +emission encoding, not the terminal's full capability set. -**Downmapping.** Producing the narrowest SGR sequence that faithfully represents -a 24-bit RGB color under the active tier. +**Downmapping.** Producing the SGR sequence that represents a 24-bit RGB color +under a narrower tier. -**Nominal palette.** The 16-entry RGB table defined in §6.3. It is the -renderer's canonical model of what each 4-bit index _means_ for mapping -purposes. It is not a claim about any terminal's actual palette, which varies -and may be user-configured. +**Nominal palette.** The 16-entry RGB table defined in §7.1. It is the +renderer's model of what each 4-bit index means for mapping purposes. It is not +a claim about any terminal's actual palette. --- -## 4. Architectural Model - -### 4.1 Evidence flows one way - -``` -detectTerminal() probe responses update() - terminfo entry → (input.scan) → CapabilityEvents - ↓ ↓ - Capabilities ──────────── fold ────────→ RuntimeCapabilities - │ - push (on change) │ - ↓ - WASM Clayterm instance (authoritative) - │ resolve tier - ↓ - emit_attr formatting -``` - -Static evidence (terminfo entry, `COLORTERM`) and dynamic evidence (`colordepth` -CapabilityEvents) meet in the capability snapshot exactly as terminfo-spec -defines. The renderer consumes that snapshot; it never consults the environment -or the raw terminfo entry itself. - -### 4.2 Capability state ownership - -The renderer's authoritative color-capability state — the `colors` value and the -truecolor flag — resides inside the WASM module, on the Clayterm instance -struct. The host pushes values across the boundary: - -- once at Term creation, seeding from `terminfo.capabilities` or the §7.1 - baseline of [terminfo-spec.md](terminfo-spec.md); -- after each `update()` whose folded events changed either value. - -Render transactions read the in-module state directly; the host does not copy -capability values per render. State belongs to the instance struct — there is no -module-level mutable state. - -A resize update rebuilds dimension-dependent renderer storage but MUST NOT reset -color capabilities to baseline: the tier is a property of the terminal, not of -the frame geometry. The instance retains the values across the update, and they -MUST survive intact. - -`term.capabilities` (the frozen `RuntimeCapabilities` snapshot) remains the -host-readable mirror. Its shape is unchanged by this specification. - -### 4.3 The renderer is still a pure formatter - -Nothing here changes the renderer's invariants: it performs no IO, manages no -terminal state, and produces bytes only. Tier resolution and downmapping are -pure functions of (capability state, packed cell color). - ---- +## 4. Invariants -## 5. Core Invariants - -- **CI-1 — Total, deterministic resolution.** Every capability snapshot state - resolves to exactly one tier, by the rule in §6.1. The same state always - yields the same tier. -- **CI-2 — Truecolor byte-identity.** Under the `"truecolor"` tier, output MUST - be byte-identical to the renderer's historical (pre-this-specification) - output. -- **CI-3 — Deterministic downmapping.** Every downmapping decision in §6.3 is a - pure function of the RGB value and the tier. Ties always resolve to the lowest - index. +- **CI-1 — Total, deterministic resolution.** Every capability snapshot resolves + to exactly one tier by the rule in §5. The tier depends only on the capability + snapshot; resizing the Term does not change it. +- **CI-2 — Truecolor is exact.** Under the `"truecolor"` tier, every RGB color + is emitted with its exact channel values. +- **CI-3 — Deterministic downmapping.** Every downmapping decision in §7 is a + pure function of the RGB value and the tier. Ties resolve to the lowest index. - **CI-4 — Palette round-trip by color.** Under the `"256"` tier, every RGB - value that is itself an entry of the 256-color palette maps to an index that - represents that same RGB value. Where the nominal palette and the cube or + value that is an entry of the 256-color palette maps to an index that + represents the same RGB value. Where the nominal palette and the cube or grayscale ramp define the same color (eight cube corners plus `#808080`), the - nominal index wins — the emitted index differs, the color does not. Under the - `"16"` tier, every nominal palette entry maps to its own index. -- **CI-5 — Tier change forces full redraw.** If the resolved tier differs from - the previous transaction's tier, the next transaction MUST emit the frame as a - complete redraw. Diff state is cell-based; stale cells from the previous - encoding must not survive. + nominal index wins. Under the `"16"` tier, every nominal palette entry maps to + its own index. +- **CI-5 — Tier change redraws.** When the tier differs from the previous + render's tier, the next render emits every cell, encoded in the new tier. - **CI-6 — Defaults stay default.** A cell with the default foreground or - background emits no color SGR for that attribute, in every tier. Style - attributes (bold, dim, italic, underline, blink, reverse, strikeout) and the - SGR reset pattern are unchanged in every tier. + background emits no color SGR for that attribute in any tier. Style attributes + (bold, dim, italic, underline, blink, reverse, strikeout) emit identically in + every tier. --- -## 6. Rendering Contract Additions +## 5. Tier resolution -### 6.1 Tier resolution - -The renderer resolves the emission tier from the capability snapshot: +The renderer resolves the tier from the capability snapshot: ``` tier = @@ -171,33 +90,23 @@ tier = : "256" ``` -The `colors ≤ 16` boundary intentionally matches the denial mapping in -terminfo-spec §6.3 (`"16"` when `colors ≤ 16`, `"256"` otherwise), so the -renderer's derived tier and a `colordepth` denial event agree for every static -`colors` value. A `colordepth` probe event folds into `trueColor` (and is the -authoritative evidence for it per TINV-3); no other fold changes the tier. - -Notes: +The `colors ≤ 16` boundary matches the denial mapping in terminfo-spec §6.3, so +the tier agrees with a `colordepth` denial event for every static `colors` +value. A `colordepth` probe event folds into `trueColor`; no other fold changes +the tier. -- `colors` values below 16 (including a missing `max_colors`, i.e. 0) clamp to - the `"16"` tier. The 16-color tier emits base codes for indices 0–7 and - aixterm bright codes for 8–15; a strictly 8-color destination's handling of - bright codes is the destination's concern. +- `colors` values below 16, including a missing `max_colors` (0), resolve to the + `"16"` tier. - Truecolor requires positive evidence (terminfo-spec §7.1): the `RGB`/`Tc` terminfo extension, `COLORTERM`, a direct-color entry (`max_colors ≥ 2²⁴`), or - a `colordepth` probe response. The baseline — no evidence at all — resolves to - `"256"`. + a `colordepth` probe response. +- With no evidence (the terminfo-spec §7.1 baseline), the tier is `"256"`. -**Default-behavior change.** A Term created without any color evidence now emits -256-color SGR, where it previously emitted truecolor. This is the baseline -evidence model applied to emission, not a regression: the renderer's hardcoded -truecolor contradicted terminfo-spec §7.1 ("Truecolor is not assumed at -baseline"). Callers who require truecolor bytes without running -`detectTerminal()` must supply capability evidence themselves. +--- -### 6.2 Emission formats +## 6. Emission formats -For a non-default foreground/background under each tier: +For a non-default foreground or background under each tier: | Tier | Foreground | Background | | ------------- | --------------------------------------------- | ---------------------------------------------- | @@ -205,15 +114,15 @@ For a non-default foreground/background under each tier: | `"256"` | `\x1b[38;5;Nm`, N ∈ 0–255 | `\x1b[48;5;Nm`, N ∈ 0–255 | | `"16"` | index 0–7: `\x1b[3Nm`; index 8–15: `\x1b[9Nm` | index 0–7: `\x1b[4Nm`; index 8–15: `\x1b[10Nm` | -In the `"16"` tier, `N` is the resolved palette index for indices 0–7 and -`index − 8` for indices 8–15. Standard red (index 1) emits `\x1b[31m` foreground -and `\x1b[41m` background. +In the `"16"` tier, `N` is the palette index for indices 0–7 and `index − 8` for +indices 8–15. Standard red (index 1) emits `\x1b[31m` foreground and `\x1b[41m` +background. -### 6.3 Downmapping +--- -#### 6.3.1 Nominal palette +## 7. Downmapping -The nominal palette defines what each 4-bit index means to the renderer: +### 7.1 Nominal palette | Index | RGB | Name | Index | RGB | Name | | ----- | --------- | ------- | ----- | --------- | -------------- | @@ -226,130 +135,47 @@ The nominal palette defines what each 4-bit index means to the renderer: | 6 | `#00ffff` | cyan | 14 | `#55ffff` | bright cyan | | 7 | `#c0c0c0` | white | 15 | `#ffffff` | bright white | -The primaries (1–6) are the pure hues; the bright variants are their pastel -counterparts. This choice is what makes "standard red" (`rgba(255, 0, 0)`) -resolve to index 1 — the behavior the motivating issue pins. +The primaries (1–6) are the pure hues, so `rgba(255, 0, 0)` resolves to index 1. +The bright variants are their pastel counterparts. -#### 6.3.2 `"16"` tier +### 7.2 `"16"` tier -Map the RGB value to the nearest entry of the nominal palette by squared -Euclidean distance over the three channels; on a tie, choose the lowest index. -Exact palette matches are distance zero, so they subsume themselves. +Map the RGB value to the nearest nominal palette entry by squared Euclidean +distance over the three channels. On a tie, choose the lowest index. -#### 6.3.3 `"256"` tier +### 7.3 `"256"` tier -Resolved in order; the first matching rule wins: +The first matching rule wins: 1. **Exact nominal match.** If the RGB value equals a nominal palette entry, - emit that index (0–15). This is why standard red emits `\x1b[38;5;1m` rather - than the cube corner `\x1b[38;5;196m`: the terminal's index 1 _is_ its red, - and consistency with the `"16"` tier is worth more than exact chroma here. + emit that index (0–15). Standard red emits `\x1b[38;5;1m`, not the cube + corner `\x1b[38;5;196m`, so it matches the `"16"` tier. 2. **Exact cube match.** If every channel is one of the six cube values - `{0, 95, 135, 175, 215, 255}`, emit `16 + 36r + 6g + b` for the channel's - cube step. (Exact grayscale cube values such as `#5f5f5f` resolve here.) + `{0, 95, 135, 175, 215, 255}`, emit `16 + 36r + 6g + b` for the channels' + cube steps. Gray cube values such as `#5f5f5f` resolve here. 3. **Grayscale.** If `r == g == b`, choose the nearest value among the grayscale ramp `{8 + 10i : 0 ≤ i ≤ 23}` extended by the endpoints `0` (index 16) and - `255` (index 231); on a tie, choose the lower index. Emit `232 + i` for ramp - value `8 + 10i`, `16` for the low endpoint, `231` for the high endpoint. -4. **Cube nearest.** Otherwise, map each channel independently to the nearest - cube value (ties to the smaller value) and emit `16 + 36r + 6g + b`. - -Rules 1–3 are the exact-match tiers: nominal entries match in rule 1, cube -values in rule 2, and every grayscale ramp value matches itself in rule 3 -(distance zero). Eight RGB values are defined by both the nominal palette and -the cube (the pure primaries, black, and white) — for those, rule 1 outranks and -the nominal index is emitted, which still satisfies CI-4 because the emitted -index represents the identical color. - -#### 6.3.4 Default and attribute bytes - -Default foreground/background emit no color SGR (CI-6). The high byte of a -packed color carries style attributes; downmapping consumes only the low 24 bits -and never alters attribute emission. - -#### 6.3.5 Terminal-themed colors - -Terminal-themed colors (renderer-spec §8.5 system colors) are not downmapped. A -palette color is already a 4-bit index and emits as SGR `30`–`37` / `90`–`97` -(foreground) or `40`–`47` / `100`–`107` (background) in every tier; a terminal -default emits as in §6.3.4. A `Canvas` or `CanvasText` keyword that resolves to -a probed theme color is an ordinary sRGB value and is encoded for the active -tier like any other. + `255` (index 231). On a tie, choose the lower index. Emit `232 + i` for ramp + value `8 + 10i`, `16` for the low endpoint, and `231` for the high endpoint. +4. **Cube nearest.** Otherwise, map each channel to the nearest cube value (ties + to the smaller value) and emit `16 + 36r + 6g + b`. -### 6.4 Invalidation on tier change +### 7.4 Default colors and style attributes -The update transaction itself still returns no bytes for capability events -(renderer-spec §7.7). This specification defines the consumer behavior the -foundation reserved: when the resolved tier changes, the _next_ render -transaction MUST emit a complete redraw (CI-5). No immediate bytes are required -— the redraw's own output re-encodes every visible cell. +Default foreground and background emit no color SGR (CI-6). Downmapping reads +only a color's RGB channels and never alters style attribute emission. -### 6.5 What does not change - -- The diff model: cells are compared on packed color values, exactly as before. - The tier affects only how a changed cell's colors are _encoded_. -- The SGR reset + attribute prefix pattern in `emit_attr`. -- The output buffer budget; 256-color and 16-color sequences are strictly - shorter than truecolor. - ---- - -## 7. Public API impact - -None. `createTerm`, `render`, `update`, and `RuntimeCapabilities` are unchanged. -This is deliberate. - -**Rejected alternative — a `colorMode` option on `createTerm`.** The motivating -issue sketched `createTerm({ colorMode: "16" })` as an explicit override. It was -rejected: capability evidence is the single lever for renderer output (TINV-3), -and an override creates a second source of truth that can contradict probe -responses — a denial event would silently fight the override. Callers control -the encoding the same way they control every other capability: by supplying -evidence (a terminfo entry, or folding probe responses through `update()`). - ---- +### 7.5 Terminal-themed colors -## 8. Test plan - -One test file (`test/color-encoding-modes.test.ts`) covers exactly this -specification: - -- **16-color tier.** Standard red foreground → `\x1b[31m`; background → - `\x1b[41m`; the 24-bit sequence must not survive; bright index mapping (e.g. - `#ff5555` → `\x1b[91m`). -- **256-color tier.** Standard red foreground → `\x1b[38;5;1m`; background → - `\x1b[48;5;1m`; exact cube round-trip (e.g. `#5f5f5f` → `\x1b[38;5;59m`); - grayscale ramp mapping; nearest-cube mapping for non-palette colors. -- **Truecolor tier.** Byte-identity with the historical output (CI-2), including - background and attribute combinations. -- **Tier resolution.** Baseline (no evidence) → `"256"`; `colors: 8` and - `colors: 16` → `"16"`; `colors: 17` → `"256"`; a granted truecolor flag → - truecolor. (How entries grant the flag — `RGB`/`Tc`, `COLORTERM`, direct-color - `max_colors ≥ 2²⁴` — is terminfo-spec evidence territory, covered by its - tests.) -- **Dynamic evidence.** A `colordepth` CapabilityEvent folded through `update()` - changes the tier of the next render; the render after a tier change is a - complete redraw in the new encoding (CI-5). -- **Defaults.** Default foreground/background emit no color SGR in every tier - (CI-6). -- **Palette round-trip.** Every 256-palette RGB value maps to an index that - represents the identical color under the `"256"` tier (CI-4, exhaustive sweep - over a rendered 16×16 grid). - -Existing test files that pin truecolor byte sequences (`term.test.ts`, -`border.test.ts`, `color.test.ts`, `transitions.test.ts`) inject truecolor -capability evidence at creation so they continue to exercise the `"truecolor"` -tier explicitly; the default-tier change is pinned once, in the new file. +Terminal-themed colors (renderer-spec §8.5) are not downmapped. A palette color +is already a 4-bit index and emits as SGR `30`–`37` / `90`–`97` (foreground) or +`40`–`47` / `100`–`107` (background) in every tier. A terminal default emits as +in §7.4. A `Canvas` or `CanvasText` keyword that resolves to a probed theme +color is an ordinary sRGB value and is encoded for the active tier. --- -## 9. Deferred / Future Areas +## 8. Tier changes -- **OSC 4 palette queries.** The mapping assumes the nominal palette and - standard 256 cube. Querying the terminal's actual palette would permit exact - nearest-color downmapping against reality; deferred (terminfo-spec). -- **Perceptual distance.** Squared Euclidean RGB is deterministic and cheap. A - perceptually weighted metric (e.g. OKLab) could improve downmapping fidelity - for photography-like content; deferred until a use case demands it. -- **Dithering.** Adjacent-cell error diffusion to approximate out-of-palette - colors; out of scope indefinitely. +An `update()` that changes the tier returns no bytes (renderer-spec §7.7). The +next render emits a complete redraw in the new tier (CI-5). diff --git a/specs/renderer-spec.md b/specs/renderer-spec.md index 8944225a..c3408945 100644 --- a/specs/renderer-spec.md +++ b/specs/renderer-spec.md @@ -471,13 +471,9 @@ is valid until the next `render()` **or** `update()` call). The renderer consumes the read-only capability snapshot maintained by `Term.update()`. A protocol that changes emitted bytes MUST define its gating capability, output, and invalidation rules in its own section of this -specification. Synchronized output (§7.9) and pointer shape (§7.10) are -specified so far. - -Color encoding is specified in the -[Color Encoding Specification](color-encoding-spec.md). Kitty keyboard mode -setup and Kitty graphics emission are deferred to their respective follow-up -PRs. +specification or a companion specification: synchronized output (§7.9), pointer +shape (§7.10), and color encoding +([Color Encoding Specification](color-encoding-spec.md)). ### 7.9 Synchronized output (DEC mode 2026) @@ -859,7 +855,7 @@ The renderer reads this from the OSC 10/11 theme probe, surfaced as using the theme in effect when the frame renders. The result is an ordinary opaque sRGB color (alpha 255): it renders exactly like the equivalent `rgba()` value, encoded for the active color tier -([Color Encoding Specification](color-encoding-spec.md) §6). When the theme has +([Color Encoding Specification](color-encoding-spec.md) §5). When the theme has not yet reported that color, the keyword falls back to its field's own terminal default instead (the same-field behavior above). A theme report that `update()` folds in after a frame renders takes effect starting with the next render. From 7f7fbebb3e4a6270bbf92059e6f8e15798557a7f Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 12:03:50 -0500 Subject: [PATCH 5/9] refactor: track color tier in frame state The emitted tier is per-frame output state, like pointer_shape, so it lives on Frame instead of the Clayterm instance. write_current_frame resolves current->color_tier and compares it against previous's to decide on a full redraw; the frame swap carries it forward, so the separate last_tier sentinel goes away. Also repoints code comments at the renumbered spec sections. --- src/clayterm.c | 39 ++++++++++++------------------- src/frame.h | 5 ++++ term.ts | 2 +- test/caps.ts | 2 +- test/color-encoding-modes.test.ts | 2 +- test/term.test.ts | 2 +- 6 files changed, 24 insertions(+), 28 deletions(-) diff --git a/src/clayterm.c b/src/clayterm.c index 53b2e91e..e41555b4 100644 --- a/src/clayterm.c +++ b/src/clayterm.c @@ -44,12 +44,8 @@ struct Clayterm { * CLAYTERM_THEME_KNOWN | 0xRRGGBB, or 0 until reported. Retained across * resize updates. */ uint32_t theme_fg, theme_bg; - /* max_colors evidence (color-encoding-spec §4.2); §7.1 baseline is 256. */ + /* max_colors evidence; the terminfo-spec §7.1 baseline is 256. */ uint32_t colors; - /* Emission tier, resolved once per reduce. last_tier detects tier - * changes, which force a complete redraw (color-encoding-spec CI-5). */ - int tier; - int last_tier; }; /* 128 bytes per cell: ~84 bytes worst-case for CUP + SGR sequences, plus up @@ -156,12 +152,12 @@ static void append_combining(struct Clayterm *ct, int x, int y, uint32_t cp) { /* ── Color tiers and downmapping ──────────────────────────────────── */ -/* Emission tiers (color-encoding-spec §6.1). */ +/* Emission tiers (color-encoding-spec §5). */ #define TIER_TRUECOLOR 0 #define TIER_256 1 #define TIER_16 2 -/* Nominal 16-color palette (color-encoding-spec §6.3.1): the renderer's +/* Nominal 16-color palette (color-encoding-spec §7.1): the renderer's * canonical model of what each 4-bit index means for downmapping. Pure * primaries for 0-7, pastel brights for 8-15. Not a claim about any * terminal's actual palette. */ @@ -175,7 +171,7 @@ static const uint32_t NOMINAL_PALETTE[16] = { static const int CUBE_STEPS[6] = {0, 95, 135, 175, 215, 255}; /* Resolve the emission tier from the capability evidence pushed by the - * host (color-encoding-spec §6.1). The colors <= 16 boundary matches the + * host (color-encoding-spec §5). The colors <= 16 boundary matches the * colordepth denial mapping in terminfo-spec §6.3. */ static int resolve_tier(const struct Clayterm *ct) { if (ct->caps & RENDER_CAP_TRUE_COLOR) @@ -186,7 +182,7 @@ static int resolve_tier(const struct Clayterm *ct) { } /* Nearest nominal palette entry by squared Euclidean distance; ties - * resolve to the lowest index (color-encoding-spec §6.3.2). */ + * resolve to the lowest index (color-encoding-spec §7.2). */ static int map_16(uint32_t rgb) { int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; @@ -218,7 +214,7 @@ static int cube_exact(int v) { } /* Nearest cube step for an arbitrary channel value; ties resolve to the - * smaller value (color-encoding-spec §6.3.3 rule 4). */ + * smaller value (color-encoding-spec §7.3 rule 4). */ static int cube_step(int v) { int best = 0; int best_dist = -1; @@ -235,7 +231,7 @@ static int cube_step(int v) { } /* Downmap a 24-bit RGB value to a 256-palette index. Ordered rules; - * the first match wins (color-encoding-spec §6.3.3). Rules 1-3 make + * the first match wins (color-encoding-spec §7.3). Rules 1-3 make * every 256-palette entry resolve to an index of the identical color * (CI-4; the nominal index wins where the palettes overlap). */ static int map_256(uint32_t rgb) { @@ -293,11 +289,12 @@ static void emit_palette(Buffer *out, int index, int base, int bright) { } /* Emit the SGR color sequence for one packed RGB value under the active - * tier (color-encoding-spec §6.2). `is_fg` selects the foreground + * tier (color-encoding-spec §6). `is_fg` selects the foreground * (38, 3x/9x) or background (48, 4x/10x) code family. */ static void emit_sgr_color(struct Clayterm *ct, uint32_t rgb, int is_fg) { - Buffer *out = &ct->frames.current->context->output; - switch (ct->tier) { + Frame *frame = ct->frames.current; + Buffer *out = &frame->context->output; + switch (frame->color_tier) { case TIER_16: { int idx = map_16(rgb); int base = is_fg ? 30 : 40; @@ -969,7 +966,6 @@ struct Clayterm *clayterm_init(void *mem, int w, int h, int runlist_capacity) { *ct = (struct Clayterm){0}; ct->runlist_capacity = (uint32_t)runlist_capacity; ct->colors = 256; /* §7.1 baseline until the host pushes evidence */ - ct->last_tier = -1; char *base = (char *)ct + align8(sizeof(struct Clayterm)); frame_context_init(&ct->frames, base, ct->runlist_capacity); clayterm_resize(ct, w, h); @@ -1575,16 +1571,11 @@ static void write_current_frame(struct Clayterm *ct, int mode, int row) { Frame *frame = ct->frames.current; Buffer *out = &frame->context->output; - /* Resolve the emission tier for this frame and force a complete - * redraw when it changed (color-encoding-spec CI-5): diff state is - * cell-based, so unchanged cells would otherwise keep bytes from the - * previous encoding on screen. Zeroing the previous frame's cells makes - * every cell diff as changed. */ - ct->tier = resolve_tier(ct); - if (ct->tier != ct->last_tier) { + /* A tier change forces a complete redraw (color-encoding-spec CI-5): + * zeroing the diff baseline makes every cell diff as changed. */ + frame->color_tier = resolve_tier(ct); + if (frame->color_tier != ct->frames.previous->color_tier) cells_fill(ct->frames.previous->cells, ct->w, ct->h, 0, 0, 0); - ct->last_tier = ct->tier; - } if (mode == 1) { present_lines(ct); diff --git a/src/frame.h b/src/frame.h index 40b727e2..462f847e 100644 --- a/src/frame.h +++ b/src/frame.h @@ -176,6 +176,11 @@ typedef struct { * (default). Inherited from previous until a shape change is emitted. */ uint8_t pointer_shape; + /* Color encoding tier this frame's output was emitted in, resolved from + * the capability snapshot before presentation. A tier that differs from + * previous forces a complete redraw. */ + uint8_t color_tier; + /* Caret declaration and placement state, reset on frame reuse or resize. */ CaretState caret; diff --git a/term.ts b/term.ts index 85eb30e0..9d7cd89e 100644 --- a/term.ts +++ b/term.ts @@ -333,7 +333,7 @@ export async function createTerm(options: TermOptions): Promise { } // A color change resolves a new tier on the next render, which - // forces a complete redraw (color-encoding-spec §4.2, §6.4). + // forces a complete redraw (color-encoding-spec §8). if ( next.syncOutput !== currentCaps.syncOutput || next.pointerShape !== currentCaps.pointerShape || diff --git a/test/caps.ts b/test/caps.ts index 62105f24..bef3d057 100644 --- a/test/caps.ts +++ b/test/caps.ts @@ -15,7 +15,7 @@ export function trueColorDetect() { /** Static truecolor evidence with no probe or key payload. Tests that pin * truecolor byte sequences pass this at createTerm to select the truecolor - * tier (color-encoding-spec §8): without evidence the renderer resolves the + * tier (color-encoding-spec §5): without evidence the renderer resolves the * 256-color baseline tier. */ export const TRUECOLOR_INFO: TerminalInfo = Object.freeze({ capabilities: Object.freeze({ diff --git a/test/color-encoding-modes.test.ts b/test/color-encoding-modes.test.ts index 07d5a566..33487ca2 100644 --- a/test/color-encoding-modes.test.ts +++ b/test/color-encoding-modes.test.ts @@ -8,7 +8,7 @@ const decode = (b: Uint8Array) => new TextDecoder().decode(b); /** Static capability evidence with a chosen `colors` value and optional * truecolor grant. The renderer resolves its emission tier from these - * fields alone (color-encoding-spec §6.1). */ + * fields alone (color-encoding-spec §5). */ function info(colors: number, trueColor = false): TerminalInfo { return Object.freeze({ capabilities: Object.freeze({ diff --git a/test/term.test.ts b/test/term.test.ts index 86cb664b..88b6c5cb 100644 --- a/test/term.test.ts +++ b/test/term.test.ts @@ -36,7 +36,7 @@ describe("term", () => { it("text inherits parent background", async () => { // Truecolor evidence selects the truecolor tier (color-encoding-spec - // §6.1); this test pins truecolor background bytes. + // §5); this test pins truecolor background bytes. let local = await createTerm({ width: 40, height: 10, From fa231488d7c7736ad7f8789f711d82c34cec9895 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 12:15:26 -0500 Subject: [PATCH 6/9] docs: align color-encoding spec with resolved-color rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since #157/#158, a cell's color is known only after render-time field resolution (inheritance, currentcolor, system colors). The tier now applies explicitly to that resolved color; terminal default and palette colors defer to renderer-spec §8.5 instead of restating it, which also drops a "no color SGR" rule that contradicted §8.5's allowance of SGR 39/49. renderer-spec's "unchanged cell MUST NOT be re-emitted" gains the CI-5 tier-change exception, and §7.1 notes that `red` downmaps while `-ansi-red` is palette 1 in every tier. --- specs/color-encoding-spec.md | 34 +++++++++++++++++++--------------- specs/renderer-spec.md | 5 +++-- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/specs/color-encoding-spec.md b/specs/color-encoding-spec.md index 3146a8b7..858e2dce 100644 --- a/specs/color-encoding-spec.md +++ b/specs/color-encoding-spec.md @@ -72,10 +72,10 @@ a claim about any terminal's actual palette. its own index. - **CI-5 — Tier change redraws.** When the tier differs from the previous render's tier, the next render emits every cell, encoded in the new tier. -- **CI-6 — Defaults stay default.** A cell with the default foreground or - background emits no color SGR for that attribute in any tier. Style attributes - (bold, dim, italic, underline, blink, reverse, strikeout) emit identically in - every tier. +- **CI-6 — Terminal-themed colors are tier-independent.** Terminal default and + palette colors emit as renderer-spec §8.5 specifies, identically in every + tier. Style attributes (bold, dim, italic, underline, blink, reverse, + strikeout) also emit identically in every tier. --- @@ -135,8 +135,10 @@ background. | 6 | `#00ffff` | cyan | 14 | `#55ffff` | bright cyan | | 7 | `#c0c0c0` | white | 15 | `#ffffff` | bright white | -The primaries (1–6) are the pure hues, so `rgba(255, 0, 0)` resolves to index 1. -The bright variants are their pastel counterparts. +The primaries (1–6) are the pure hues, so `rgba(255, 0, 0)` and the named color +`red` resolve to index 1. The bright variants are their pastel counterparts. +This mapping applies only to sRGB colors: `red` emits `\x1b[38;2;255;0;0m` in +the `"truecolor"` tier, while `-ansi-red` is palette 1 in every tier (§7.4). ### 7.2 `"16"` tier @@ -160,18 +162,20 @@ The first matching rule wins: 4. **Cube nearest.** Otherwise, map each channel to the nearest cube value (ties to the smaller value) and emit `16 + 36r + 6g + b`. -### 7.4 Default colors and style attributes +### 7.4 Resolved colors -Default foreground and background emit no color SGR (CI-6). Downmapping reads -only a color's RGB channels and never alters style attribute emission. +The tier applies to a cell's resolved color, after the render-time field +resolution of renderer-spec §8.5 (foreground inheritance, `currentcolor`, and +system colors). A resolved color is one of: -### 7.5 Terminal-themed colors +- **sRGB.** Encoded for the active tier by §6 and §7. This includes a + cross-field `Canvas` or `CanvasText` resolved to a probed theme color, and a + `currentcolor` or inherited color that resolves to sRGB. +- **Terminal default or palette entry.** Not downmapped. It emits as + renderer-spec §8.5 specifies, in every tier (CI-6). -Terminal-themed colors (renderer-spec §8.5) are not downmapped. A palette color -is already a 4-bit index and emits as SGR `30`–`37` / `90`–`97` (foreground) or -`40`–`47` / `100`–`107` (background) in every tier. A terminal default emits as -in §7.4. A `Canvas` or `CanvasText` keyword that resolves to a probed theme -color is an ordinary sRGB value and is encoded for the active tier. +Downmapping reads only a color's RGB channels and never alters style attribute +emission. --- diff --git a/specs/renderer-spec.md b/specs/renderer-spec.md index c3408945..92e31984 100644 --- a/specs/renderer-spec.md +++ b/specs/renderer-spec.md @@ -881,8 +881,9 @@ including cells an enclosing element painted. This is distinct from an omitted Cell diffing treats terminal-themed colors like any other attribute: a cell whose color changes between a palette color, a terminal default, and an sRGB color in consecutive frames MUST be re-emitted, and an unchanged cell MUST NOT -be. The renderer does not resolve a palette color to RGB to compare it with an -sRGB color. +be, except after a color tier change +([Color Encoding Specification](color-encoding-spec.md) CI-5). The renderer does +not resolve a palette color to RGB to compare it with an sRGB color. Transitions have special considerations for terminal-themed colors; see Transitions Specification §7.4. From 07cc9f73b5e92b6714ab82bce2a15f89b5218cfd Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 12:15:26 -0500 Subject: [PATCH 7/9] test: cover tiering of inherited and currentcolor sRGB An inherited open() color and a currentcolor background that resolve to sRGB downmap like any other sRGB color. The default-color test now asserts tier-independent bytes rather than the absence of any color SGR, matching CI-6. --- test/color-encoding-modes.test.ts | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/test/color-encoding-modes.test.ts b/test/color-encoding-modes.test.ts index 33487ca2..e4dbbeec 100644 --- a/test/color-encoding-modes.test.ts +++ b/test/color-encoding-modes.test.ts @@ -238,14 +238,18 @@ describe("color encoding modes", () => { }); describe("default colors", () => { - it("emits no color SGR for default fg/bg in any tier", async () => { + it("emits default fg/bg identically in every tier", async () => { + let outputs: string[] = []; for (let caps of [info(16), info(256), info(256, true)]) { let term = await createTerm({ width: 4, height: 1, terminfo: caps }); let ansi = decode(term.render(coloredText()).output); expect(ansi).toContain("X"); - expect(ansi).not.toMatch(/\x1b\[(3\d|4\d|9\d|10\d|38|48)/); + expect(ansi).not.toMatch(/\x1b\[(38|48);/); + outputs.push(ansi); } + expect(outputs[1]).toEqual(outputs[0]); + expect(outputs[2]).toEqual(outputs[0]); }); }); @@ -286,6 +290,28 @@ describe("color encoding modes", () => { }); }); + describe("resolved colors", () => { + it("encodes inherited and currentcolor sRGB for the active tier", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode( + term.render([ + open("root", { + color: rgba(255, 0, 0), + layout: { width: grow(), height: grow() }, + }), + text("X", { bg: "currentcolor" }), + close(), + ]).output, + ); + + let before = beforeGlyph(ansi); + // inherited red foreground and currentcolor red background + expect(before).toContain("\x1b[31m"); + expect(before).toContain("\x1b[41m"); + expect(before).not.toMatch(/\x1b\[(38|48);/); + }); + }); + describe("palette round-trip", () => { it("maps every 256-palette entry to an index of the same color", async () => { let NOMINAL = [ From 3e880dbc51757a0fc5ff2c1a8f05ec5f113f37a7 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 12:19:35 -0500 Subject: [PATCH 8/9] docs: keep sRGB off the themed 0-15 indices in the 256 tier An sRGB color is a fixed color, but mapping #ff0000 to palette index 1 made its appearance depend on the user's theme: a terminal that sets index 1 to pink rendered `red` pink in 256-color output and red in truecolor. #60 asked for `\x1b[38;5;1m` before the `-ansi-*` keywords existed; now that they do, they are the way to ask for the theme's colors. The 256 tier maps only onto the cube and grayscale ramp (16-255), so standard red emits 196. CI-4 becomes "every cube and ramp color maps to its own index". The 16 tier keeps nearest-nominal mapping, since it has no fixed alternative; the spec says so directly. --- specs/color-encoding-spec.md | 44 +++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/specs/color-encoding-spec.md b/specs/color-encoding-spec.md index 858e2dce..4b1b8d92 100644 --- a/specs/color-encoding-spec.md +++ b/specs/color-encoding-spec.md @@ -50,8 +50,11 @@ emission encoding, not the terminal's full capability set. under a narrower tier. **Nominal palette.** The 16-entry RGB table defined in §7.1. It is the -renderer's model of what each 4-bit index means for mapping purposes. It is not -a claim about any terminal's actual palette. +renderer's model of what each 4-bit index means when the `"16"` tier picks the +nearest index. It is not a claim about any terminal's actual palette. + +**Fixed color.** An sRGB value. Its intended appearance does not depend on the +terminal's theme, unlike a terminal-themed color (renderer-spec §8.5). --- @@ -64,12 +67,12 @@ a claim about any terminal's actual palette. is emitted with its exact channel values. - **CI-3 — Deterministic downmapping.** Every downmapping decision in §7 is a pure function of the RGB value and the tier. Ties resolve to the lowest index. -- **CI-4 — Palette round-trip by color.** Under the `"256"` tier, every RGB - value that is an entry of the 256-color palette maps to an index that - represents the same RGB value. Where the nominal palette and the cube or - grayscale ramp define the same color (eight cube corners plus `#808080`), the - nominal index wins. Under the `"16"` tier, every nominal palette entry maps to - its own index. +- **CI-4 — Fixed colors stay off the themed palette where possible.** Under the + `"256"` tier, an sRGB color never maps to indices 0–15, which the terminal's + theme controls. Every color of the cube or grayscale ramp (indices 16–255) + maps to its own index. Under the `"16"` tier no fixed alternative exists, so + an sRGB color maps to the nearest nominal palette entry, and every nominal + palette entry maps to its own index. - **CI-5 — Tier change redraws.** When the tier differs from the previous render's tier, the next render emits every cell, encoded in the new tier. - **CI-6 — Terminal-themed colors are tier-independent.** Terminal default and @@ -135,10 +138,14 @@ background. | 6 | `#00ffff` | cyan | 14 | `#55ffff` | bright cyan | | 7 | `#c0c0c0` | white | 15 | `#ffffff` | bright white | -The primaries (1–6) are the pure hues, so `rgba(255, 0, 0)` and the named color -`red` resolve to index 1. The bright variants are their pastel counterparts. -This mapping applies only to sRGB colors: `red` emits `\x1b[38;2;255;0;0m` in -the `"truecolor"` tier, while `-ansi-red` is palette 1 in every tier (§7.4). +The primaries (1–6) are the pure hues and the bright variants are their pastel +counterparts. The `"16"` tier uses this table to choose the nearest index +(§7.2); the `"256"` tier does not use it. + +In the `"16"` tier, the named color `red` and `-ansi-red` both emit palette 1, +because the tier has no other way to show red. The terminal's theme decides what +palette 1 looks like. In the `"256"` and `"truecolor"` tiers, `red` is a fixed +color, while `-ansi-red` is palette 1 in every tier (§7.4). ### 7.2 `"16"` tier @@ -147,19 +154,20 @@ distance over the three channels. On a tie, choose the lowest index. ### 7.3 `"256"` tier +The tier maps sRGB colors only onto the 6×6×6 cube (indices 16–231) and the +grayscale ramp (indices 232–255). It never emits indices 0–15, because the +terminal's theme controls them. Standard red emits `\x1b[38;5;196m`. + The first matching rule wins: -1. **Exact nominal match.** If the RGB value equals a nominal palette entry, - emit that index (0–15). Standard red emits `\x1b[38;5;1m`, not the cube - corner `\x1b[38;5;196m`, so it matches the `"16"` tier. -2. **Exact cube match.** If every channel is one of the six cube values +1. **Exact cube match.** If every channel is one of the six cube values `{0, 95, 135, 175, 215, 255}`, emit `16 + 36r + 6g + b` for the channels' cube steps. Gray cube values such as `#5f5f5f` resolve here. -3. **Grayscale.** If `r == g == b`, choose the nearest value among the grayscale +2. **Grayscale.** If `r == g == b`, choose the nearest value among the grayscale ramp `{8 + 10i : 0 ≤ i ≤ 23}` extended by the endpoints `0` (index 16) and `255` (index 231). On a tie, choose the lower index. Emit `232 + i` for ramp value `8 + 10i`, `16` for the low endpoint, and `231` for the high endpoint. -4. **Cube nearest.** Otherwise, map each channel to the nearest cube value (ties +3. **Cube nearest.** Otherwise, map each channel to the nearest cube value (ties to the smaller value) and emit `16 + 36r + 6g + b`. ### 7.4 Resolved colors From 9bd1f6750854193c5c53a3ff599e387e15987b73 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 12:19:35 -0500 Subject: [PATCH 9/9] fix: map 256-tier sRGB onto the cube and ramp only Drop the exact-nominal rule from map_256 so sRGB never lands on the theme-controlled indices 0-15. Standard red now emits 38;5;196, and the 256 round-trip sweep asserts that nominal colors stay at 16 or above while every cube and ramp color maps to its own index. --- .changeset/color-encoding-tiers.md | 2 +- src/clayterm.c | 26 +++++++++----------------- test/color-encoding-modes.test.ts | 30 +++++++++++++++++------------- 3 files changed, 27 insertions(+), 31 deletions(-) diff --git a/.changeset/color-encoding-tiers.md b/.changeset/color-encoding-tiers.md index 94705948..97b1ed82 100644 --- a/.changeset/color-encoding-tiers.md +++ b/.changeset/color-encoding-tiers.md @@ -4,7 +4,7 @@ Adds capability-aware SGR color encoding to the renderer. -The renderer now derives its color encoding from terminal capability evidence instead of always emitting 24-bit truecolor. Terminals with truecolor evidence (`RGB`/`Tc`, `COLORTERM`, direct-color `max_colors`, or a `colordepth` probe folded through `term.update()`) continue to receive byte-identical truecolor output. Without truecolor evidence, cells emit 256-color SGR (`\x1b[38;5;Nm`) when `colors > 16`, or 4-bit SGR (`\x1b[31m`) at or below 16. Colors are downmapped deterministically: nominal palette entries keep their classic indices, grays use the grayscale ramp, and everything else rounds to the 6×6×6 cube. A tier change between frames forces a complete redraw. +The renderer now derives its color encoding from terminal capability evidence instead of always emitting 24-bit truecolor. Terminals with truecolor evidence (`RGB`/`Tc`, `COLORTERM`, direct-color `max_colors`, or a `colordepth` probe folded through `term.update()`) continue to receive byte-identical truecolor output. Without truecolor evidence, cells emit 256-color SGR (`\x1b[38;5;Nm`) when `colors > 16`, or 4-bit SGR (`\x1b[31m`) at or below 16. Colors are downmapped deterministically. In 256-color output, RGB colors map onto the 6×6×6 cube and grayscale ramp (`rgba(255, 0, 0)` → `\x1b[38;5;196m`), never onto indices 0–15, which follow the terminal's theme. In 16-color output, they map to the nearest standard palette entry. Use the `-ansi-*` keywords when you want the terminal's own palette colors. A tier change between frames forces a complete redraw. The baseline — no capability evidence — now resolves to 256-color rather than truecolor. Pass `detectTerminal()` output to `createTerm` to restore truecolor output on terminals that support it. diff --git a/src/clayterm.c b/src/clayterm.c index e41555b4..d5bb115c 100644 --- a/src/clayterm.c +++ b/src/clayterm.c @@ -157,10 +157,9 @@ static void append_combining(struct Clayterm *ct, int x, int y, uint32_t cp) { #define TIER_256 1 #define TIER_16 2 -/* Nominal 16-color palette (color-encoding-spec §7.1): the renderer's - * canonical model of what each 4-bit index means for downmapping. Pure - * primaries for 0-7, pastel brights for 8-15. Not a claim about any - * terminal's actual palette. */ +/* Nominal 16-color palette (color-encoding-spec §7.1): the "16" tier's + * model of what each 4-bit index means when choosing the nearest one. + * Not a claim about any terminal's actual palette. */ static const uint32_t NOMINAL_PALETTE[16] = { 0x000000, 0xff0000, 0x00ff00, 0xffff00, 0x0000ff, 0xff00ff, 0x00ffff, 0xc0c0c0, 0x808080, 0xff5555, 0x55ff55, 0xffff55, @@ -230,29 +229,22 @@ static int cube_step(int v) { return best; } -/* Downmap a 24-bit RGB value to a 256-palette index. Ordered rules; - * the first match wins (color-encoding-spec §7.3). Rules 1-3 make - * every 256-palette entry resolve to an index of the identical color - * (CI-4; the nominal index wins where the palettes overlap). */ +/* Downmap a 24-bit RGB value to a 256-palette index in 16-255, leaving + * the theme-controlled 0-15 alone. Ordered rules; the first match wins + * (color-encoding-spec §7.3). */ static int map_256(uint32_t rgb) { int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; int b = rgb & 0xff; - /* 1. exact nominal match: standard colors keep their 4-bit indices */ - for (int i = 0; i < 16; i++) { - if (NOMINAL_PALETTE[i] == rgb) - return i; - } - - /* 2. exact cube match */ + /* 1. exact cube match */ int cr = cube_exact(r); int cg = cube_exact(g); int cb = cube_exact(b); if (cr >= 0 && cg >= 0 && cb >= 0) return 16 + 36 * cr + 6 * cg + cb; - /* 3. grayscale: nearest of the ramp extended by both endpoints. + /* 2. grayscale: nearest of the ramp extended by both endpoints. * Candidates run in ascending index order (16, 231, 232..255), so a * strict comparison resolves ties to the lowest index. */ if (r == g && g == b) { @@ -276,7 +268,7 @@ static int map_256(uint32_t rgb) { return best; } - /* 4. nearest cube value per channel */ + /* 3. nearest cube value per channel */ return 16 + 36 * cube_step(r) + 6 * cube_step(g) + cube_step(b); } diff --git a/test/color-encoding-modes.test.ts b/test/color-encoding-modes.test.ts index e4dbbeec..c4f232a8 100644 --- a/test/color-encoding-modes.test.ts +++ b/test/color-encoding-modes.test.ts @@ -86,22 +86,24 @@ describe("color encoding modes", () => { }); describe("256-color tier", () => { - it("downgrades standard red foreground to its palette index", async () => { + it("maps sRGB red foreground to the fixed cube red", async () => { let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); - // pins: standard-palette red maps to index 1 - expect(beforeGlyph(ansi)).toContain("\x1b[38;5;1m"); + // pins: cube (5,0,0), not the theme-controlled palette index 1 + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[38;5;1m"); expect(beforeGlyph(ansi)).not.toContain("\x1b[38;2;255;0;0"); }); - it("downgrades standard red background to its palette index", async () => { + it("maps sRGB red background to the fixed cube red", async () => { let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); let ansi = decode( term.render(coloredText(undefined, rgba(255, 0, 0))).output, ); - expect(beforeGlyph(ansi)).toContain("\x1b[48;5;1m"); + expect(beforeGlyph(ansi)).toContain("\x1b[48;5;196m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[48;5;1m"); expect(beforeGlyph(ansi)).not.toContain("\x1b[48;2;255;0;0"); }); @@ -153,7 +155,7 @@ describe("color encoding modes", () => { let term = await createTerm({ width: 4, height: 1 }); let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); - expect(beforeGlyph(ansi)).toContain("\x1b[38;5;1m"); + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); }); it("resolves the 16-color tier at and below 16 colors", async () => { @@ -172,7 +174,7 @@ describe("color encoding modes", () => { let term = await createTerm({ width: 4, height: 1, terminfo: info(17) }); let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); - expect(beforeGlyph(ansi)).toContain("\x1b[38;5;1m"); + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); }); it("resolves the truecolor tier on a granted truecolor flag", async () => { @@ -192,7 +194,7 @@ describe("color encoding modes", () => { let term = await createTerm({ width: 4, height: 1 }); let ops = coloredText(rgba(255, 0, 0)); - expect(decode(term.render(ops).output)).toContain("\x1b[38;5;1m"); + expect(decode(term.render(ops).output)).toContain("\x1b[38;5;196m"); term.update([ { type: "capability", key: "colordepth", value: "truecolor" }, @@ -233,7 +235,7 @@ describe("color encoding modes", () => { expect(decode(term.render(ops).output)).toContain("\x1b[38;2;255;0;0m"); term.update([{ type: "capability", key: "colordepth", value: "256" }]); - expect(decode(term.render(ops).output)).toContain("\x1b[38;5;1m"); + expect(decode(term.render(ops).output)).toContain("\x1b[38;5;196m"); }); }); @@ -285,7 +287,7 @@ describe("color encoding modes", () => { ); let before = beforeGlyph(ansi); - expect(before).toContain("\x1b[48;5;1m"); + expect(before).toContain("\x1b[48;5;196m"); expect(before).not.toContain("\x1b[48;2;"); }); }); @@ -313,7 +315,7 @@ describe("color encoding modes", () => { }); describe("palette round-trip", () => { - it("maps every 256-palette entry to an index of the same color", async () => { + it("never emits themed indices and round-trips cube and ramp colors", async () => { let NOMINAL = [ 0x000000, 0xff0000, @@ -374,8 +376,10 @@ describe("color encoding modes", () => { ); expect(indices.length).toBe(256); for (let k = 0; k < 256; k++) { - // The emitted index must represent the identical color (CI-4). - expect(rgbOf(indices[k])).toBe(rgbOf(k)); + // Nominal colors stay off the themed 0-15; cube and ramp colors + // round-trip to their own index (CI-4). + if (k < 16) expect(indices[k]).toBeGreaterThanOrEqual(16); + else expect(indices[k]).toBe(k); } }); });