@tjakoen/grain 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/PLAN.md CHANGED
@@ -25,3 +25,34 @@
25
25
  `ai-content-retrieval-layer`).
26
26
  5. **Workflow / actions registry.** Named higher-level workflows composed from the atomic verbs, plus a
27
27
  discoverable "what the AI can do" list (memory `actions-workflow-registry-idea`).
28
+
29
+ ## Components
30
+
31
+ Component work does not belong in the numbered list above, which tracks the AI-interaction layer.
32
+
33
+ 1. ~~**Gallery.**~~ **BUILT** (2026-08-12) — `molecules/gallery`, a captioned image grid: the
34
+ companion to `card-grid` for pictures rather than facts, tuned by `--gallery-min` and
35
+ `--gallery-ratio`, wired to `scripts/lightbox.js` by one group per gallery. Written because the
36
+ portfolio's event pages could only carry a hero strip, which hides anything past the fifth tile.
37
+ 2. ~~**Media card.**~~ **BUILT** (2026-08-12) — `molecules/media-card`, a `card` that leads with a
38
+ picture: one image, a title, an optional description, an optional row of buttons, cropped to
39
+ `--media-ratio`. It reuses `card`'s vocabulary rather than a second one, and both optional rows
40
+ collapse to nothing when absent.
41
+
42
+ Both consumers are satisfied. The plain photo that links somewhere is the default stacked
43
+ layout. The video poster that links out is `data-layout="overlay"`, which carries the centred
44
+ play badge and lays the title along the bottom on a scrim, and it keeps the one hard rule that
45
+ made the original worth copying: **it embeds nothing.** No iframe, no platform script, no JS at
46
+ all, so the no-JS case is the only case. `tjakoen.github.io/view/components/molecules/event-video`
47
+ retires into it and `content.ts` `renderVideoCard` composes the molecule instead of owning it.
48
+
49
+ **The open question is answered: one component, layout is an attribute.** The two shapes share
50
+ every rule they have apart from where the text sits, so two molecules would fork the box, the
51
+ crop, the hover, the badge and the pending edge to move one block of text. A beside-the-picture
52
+ layout is deliberately not shipped, because nothing asks for it yet and it is one more attribute
53
+ value when something does.
54
+
55
+ Two new global tokens came with it, `--scrim` and `--on-scrim` in `styles/variables.css`. They
56
+ are the one pair that does **not** invert in the dark block, on purpose: a scrim darkens
57
+ somebody else's photograph so a label survives on top of it, and a photograph does not invert
58
+ with the palette.
package/README.md CHANGED
@@ -232,7 +232,7 @@ every theme, and verify it still reads in dark.
232
232
  (`data-field` / `data-bind-*` / `each` / `<slot-tag>`).
233
233
  2. Register the dir at your **composition root** so the host composes `<mywidget>` and bundles
234
234
  its CSS: add it to the renderer's component roots + the style bundle + the catalog
235
- (this repo: `componentRoots` / `styleRoots` in `tjakoen.github.io/config.ts`; a standalone consumer
235
+ (this repo: `componentRoots` / `styleRoots` in `tjakoen.github.io/src/config.ts`; a standalone consumer
236
236
  passes its dir to `createRenderer` / the style bundle / `createCatalog`). It then appears
237
237
  in `/catalog` automatically.
238
238
 
@@ -1,8 +1,8 @@
1
1
  // grain/ai/accepts.test.ts — UNIT: component affordance harvester in isolation.
2
2
  // Uses tmp files to simulate component HTML so no real fs state is needed.
3
3
  import { test, expect } from "bun:test";
4
- import { mkdirSync, writeFileSync, rmSync } from "fs";
5
- import { join } from "path";
4
+ import { mkdirSync, writeFileSync, rmSync } from "node:fs";
5
+ import { join } from "node:path";
6
6
  import { createAccepts } from "./accepts.ts";
7
7
 
8
8
  const TMP = join(import.meta.dir, "__accepts_test_tmp__");
package/ai/accepts.ts CHANGED
@@ -1,11 +1,11 @@
1
- // /framework/render/accepts.ts — harvest component-declared affordances.
1
+ // grain/ai/accepts.ts — harvest component-declared affordances.
2
2
  //
3
3
  // Scans each component's .html for `data-kind` + `data-accepts` and returns a
4
4
  // kind → action-names map. This is the single source the AI manifest reads, so it
5
5
  // can't drift from what the components actually expose (https://tjakoen.github.io/grain/docs/ai-interface §4).
6
6
  // Generic: it knows nothing about the app's specific verbs or surfaces.
7
- import { readdirSync, readFileSync } from "fs";
8
- import { join } from "path";
7
+ import { readdirSync, readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
9
 
10
10
  const KIND = /\bdata-kind=["']([^"']+)["']/;
11
11
  const ACCEPTS = /\bdata-accepts=["']([^"']+)["']/;
package/ai/contract.ts CHANGED
@@ -1,4 +1,4 @@
1
- // /app/ai/contract.ts — the action vocabulary contract (see https://tjakoen.github.io/grain/docs/ai-interface).
1
+ // grain/ai/contract.ts — the action vocabulary contract (see https://tjakoen.github.io/grain/docs/ai-interface).
2
2
  //
3
3
  // Two closed registries + three envelopes. Both a human interaction and an AI
4
4
  // decision become the SAME Intent, flow through the SAME door, and come back as
@@ -224,6 +224,7 @@ export const isSafeNavigateHref = (href: unknown): href is string =>
224
224
  /** Cap on a field.set value — a prefill is a message draft, not a document. */
225
225
  export const FIELD_VALUE_CAP = 2000;
226
226
  /** Plain text only: no C0 control chars except \n and \t (a textarea needs both). */
227
+ // eslint-disable-next-line no-control-regex
227
228
  const FIELD_VALUE_BAD_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f]/;
228
229
  export const isSafeFieldValue = (v: unknown): v is string =>
229
230
  typeof v === "string" && v.length <= FIELD_VALUE_CAP && !FIELD_VALUE_BAD_CHARS.test(v);
@@ -1,4 +1,4 @@
1
- // /app/ai/interaction-layer.ts — THE ONE DOOR (the single internal AI interaction
1
+ // grain/ai/interaction-layer.ts — THE ONE DOOR (the single internal AI interaction
2
2
  // layer; MVP §"One interface, one path"). Every Intent — from a human click or an
3
3
  // AI decision — enters here, is validated against the closed vocabulary, handed to
4
4
  // the reasoner (the single writer), and the resulting RenderOps are PUSHED back to
package/ai/manifest.ts CHANGED
@@ -1,4 +1,4 @@
1
- // /app/ai/manifest.ts — the AI's instruction manual, per screen.
1
+ // grain/ai/manifest.ts — the AI's instruction manual, per screen.
2
2
  //
3
3
  // A machine-readable projection of what's addressable (targets) and invokable
4
4
  // (actions) on a screen, plus the in-view state the reasoner needs (MVP steps 2–4).
package/ai/markdown.ts CHANGED
@@ -36,6 +36,7 @@ const LIST_ITEM_RE = /^[-*]\s+/;
36
36
  const BLOCK_SPLIT_RE = /\n{2,}/;
37
37
  // Placeholder delimiter for pulled-out code spans (below) — \x00 can't occur in real chat text
38
38
  // (it was already esc()'d as ordinary text upstream), so it never collides.
39
+ // eslint-disable-next-line no-control-regex
39
40
  const CODE_PLACEHOLDER_RE = /\x00(\d+)\x00/g;
40
41
 
41
42
  function inline(escaped: string): string {
@@ -135,7 +135,7 @@ test("say.set → the reply streams straight into the reflection surface (no cha
135
135
  const d = await r.decide(intent({ action: "say.set", surface: "reflection", payload: { text: "clear thursday" } }), tools);
136
136
 
137
137
  expect(d.ok).toBe(true);
138
- expect(targetsOf(ops.filter((o) => o.op === "type"))).toEqual(new Array([...("Noted: clear Thursday.")].length + 1).fill("reflection"));
138
+ expect(targetsOf(ops.filter((o) => o.op === "type"))).toEqual(Array.from<string>({ length: [...("Noted: clear Thursday.")].length + 1 }).fill("reflection"));
139
139
  expect(ops.every((o) => o.target === "reflection")).toBe(true); // no chat-log bubble machinery
140
140
  });
141
141
 
@@ -49,7 +49,7 @@ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
49
49
 
50
50
  /** Stream text into a surface one code point at a time (kit ops), then settle it clean. */
51
51
  async function stream(surface: string, text: string, tools: ReasonTools): Promise<void> {
52
- for (const ch of [...text]) {
52
+ for (const ch of text) {
53
53
  if (tools.cancelled()) break;
54
54
  if (thinkMs > 0) await tools.delay(TYPE_MS);
55
55
  tools.emit(typeToken(surface, ch));
package/ai/reasoner.ts CHANGED
@@ -1,4 +1,4 @@
1
- // /app/ai/reasoner.ts — the reasoner boundary (the PROJECT-PLAN §10c `Model` seam)
1
+ // grain/ai/reasoner.ts — the reasoner boundary (the PROJECT-PLAN §10c `Model` seam)
2
2
  // plus a stub standing in for the real cloud/local model during frontend work.
3
3
  //
4
4
  // The reasoner is the SINGLE WRITER: it decides, then writes + renders through
@@ -69,7 +69,7 @@ export function makeStubReasoner(opts: StubOptions = {}): Reasoner {
69
69
  // arrives at grain with a caret; `done` settles it to clean (DESIGN-SYSTEM §3).
70
70
  // Shared by both text verbs so the input and the button feel the same.
71
71
  const stream = async (surface: string, line: string, done = true): Promise<Decision> => {
72
- for (const ch of [...line]) { // spread = per code point (handles "—")
72
+ for (const ch of line) { // for-of on a string already iterates per code point (handles "—")
73
73
  if (tools.cancelled()) break; // stop promptly at a clean boundary…
74
74
  await tools.delay(thinkMs > 0 ? TYPE_MS : 0);
75
75
  tools.emit({ target: surface, op: "type", text: ch, provenance: "ai", commit: "pending" });
@@ -7,8 +7,8 @@
7
7
  // dropdowns, with a live search filter. Dependency-free: a tiny line parser, no
8
8
  // markdown library, no CDN. It reads the filesystem directly (like ai/accepts.ts) and
9
9
  // imports nothing from batch — the composition root passes the page-nav routes in.
10
- import { readdirSync, readFileSync } from "fs";
11
- import { join } from "path";
10
+ import { readdirSync, readFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
12
 
13
13
  interface Panel { label: string; code: string; flat?: boolean; }
14
14
  interface Group { label: string; panels: Panel[]; }
@@ -1,17 +1,9 @@
1
1
  /* atoms/b-button — the button, ONE class: .btn. Variants are ATTRIBUTES, not
2
2
  extra classes (vanilla CSS, no utility soup). The component owns its styling.
3
- Accent is three CSS vars scoped to .btn; a status attribute repoints them, so
4
- every variant inherits the new color for free.
5
3
  Each pseudo-state has a parallel data-force value so the catalog can show it
6
4
  statically (e.g. .btn:hover AND .btn[data-force~="hover"]). */
7
5
 
8
6
  .btn {
9
- /* accent token set — [data-status] overrides these */
10
- --btn-accent: var(--color-primary);
11
- --btn-accent-hover: var(--color-primary-hover);
12
- --btn-accent-contrast: var(--color-primary-contrast);
13
- --btn-accent-soft: var(--color-primary-soft);
14
-
15
7
  display: inline-flex; align-items: center; justify-content: center;
16
8
  gap: var(--space-2);
17
9
  font-family: var(--type-font);
@@ -24,7 +16,7 @@
24
16
  border: var(--border); /* ink hairline — no fill, no shadow */
25
17
  border-radius: var(--radius-sm);
26
18
  cursor: pointer;
27
- transition: background-color 0.15s, color 0.15s;
19
+ transition: background-color 0.15s, color 0.15s, border-color 0.15s;
28
20
 
29
21
  /* default = transparent fill, ink border + label (DESIGN-SYSTEM §5 Buttons) */
30
22
  background: transparent;
@@ -43,21 +35,35 @@
43
35
  .btn[data-variant="soft"] { background: var(--paper-2); }
44
36
  .btn[data-variant="outline"] { background: transparent; } /* already the default look */
45
37
 
46
- /* ---- status (attribute): repoint the accent token set ---- */
47
- .btn[data-status="success"] {
48
- --btn-accent: var(--color-success); --btn-accent-hover: var(--color-success-hover);
49
- --btn-accent-contrast: var(--color-success-contrast); --btn-accent-soft: var(--color-success-soft);
50
- }
51
- .btn[data-status="danger"] {
52
- --btn-accent: var(--color-danger); --btn-accent-hover: var(--color-danger-hover);
53
- --btn-accent-contrast: var(--color-danger-contrast); --btn-accent-soft: var(--color-danger-soft);
54
- }
38
+ /* ---- status (attribute): a doubled rule on the irreversible one, and nothing else ----
39
+ Settled 2026-08-11 by a walked review, not by a reading: plans/grain-token-debt.md in the
40
+ portfolio, tour review-grain-status, candidate B with the fill kept for the hover.
41
+ Four --btn-accent* tokens used to be declared above and repointed here. They are DELETED
42
+ rather than wired up, because wiring them would have rendered nothing: --color-success and
43
+ --color-danger both resolve to var(--ink), with the same --paper and --paper-2 partners as
44
+ every other button. There is no hue to spend and that is the design (DESIGN-SYSTEM §2), so
45
+ the honest fix is to stop declaring a colour the palette does not have.
46
+ success gets NO visual rule, on purpose. It keeps its meaning for assistive tech and for the
47
+ AI layer while visual ranking stays data-variant's job, which is the axis that already works
48
+ in a monochrome palette. Only the action you cannot undo is marked. */
49
+ .btn[data-status="danger"] { border-width: 2px; }
55
50
 
56
51
  /* ---- pseudo-states. Hover = a quiet ink WASH (DESIGN-SYSTEM §5), never an invert and
57
52
  never a new hue — the full ink-fill invert read as a loud accent block and revealed the
58
53
  corner radius on otherwise-flat buttons (regression, 2026-07-04). ---- */
59
54
  .btn:hover, .btn[data-force~="hover"] { background: color-mix(in srgb, var(--ink) 8%, transparent); }
60
55
 
56
+ /* The one exception to "hover is a wash", and the one place a solid fill is spent: the
57
+ destructive control. At rest it is only a doubled rule, so the row stays quiet; the moment the
58
+ pointer is on the button that cannot be undone it goes solid ink with a paper label, which is
59
+ the loudest thing GRAIN can say without a hue. Reads at (0,3,0) so it beats the wash above on
60
+ specificity, not on source order. border-color is set explicitly for a flavor that repoints
61
+ --hairline away from --ink; in the stock themes the two are the same value. */
62
+ .btn[data-status="danger"]:hover,
63
+ .btn[data-status="danger"][data-force~="hover"] {
64
+ background: var(--ink); color: var(--paper); border-color: var(--ink);
65
+ }
66
+
61
67
  .btn:focus-visible, .btn[data-force~="focus"] { outline: 2px solid var(--color-accent); outline-offset: 2px; }
62
68
  .btn:active, .btn[data-force~="active"] { transform: translateY(1px); }
63
69
 
@@ -0,0 +1,47 @@
1
+ /* molecules/gallery — a captioned image grid. CSS-only (CONVENTIONS §4): composed by hand, nothing
2
+ data-binds it. The companion to card-grid, for pictures rather than facts: every tile is equal
3
+ weight, cropped to one ratio, and carries its caption under it.
4
+
5
+ Deliberately NOT a hero strip. A strip runs one photo big to carry a post; a gallery is the roll
6
+ that hero was picked from, so a reader can scan it and move on. Tile width tunes with
7
+ --gallery-min (default 15rem, same idiom as --card-min), the crop with --gallery-ratio.
8
+
9
+ Lightbox: wrap the grid in [data-lightbox-group] and mark each tile [data-lightbox] (scripts/
10
+ lightbox.js). One group per gallery, so prev/next never walks out of it into another strip on the
11
+ same page. Keep the trigger an <a href> pointing at the full image: that is the no-JS fallback. */
12
+ .gallery {
13
+ display: grid;
14
+ gap: var(--space-4);
15
+ grid-template-columns: repeat(auto-fit, minmax(var(--gallery-min, 15rem), 1fr));
16
+ }
17
+
18
+ .gallery__item { margin: 0; display: flex; flex-direction: column; gap: var(--space-2); }
19
+
20
+ /* fixed box per tile: a real roll mixes portrait and landscape, and a ragged grid reads like a
21
+ mistake. object-fit crops to the box; the box reserves the space, so a lazily-loaded photo cannot
22
+ shift the page under someone mid-scroll. */
23
+ .gallery__link {
24
+ display: block;
25
+ overflow: hidden;
26
+ border: 1px solid var(--color-line);
27
+ border-radius: var(--radius-md);
28
+ background: var(--paper-2);
29
+ }
30
+ .gallery__link img {
31
+ display: block; width: 100%; height: 100%;
32
+ aspect-ratio: var(--gallery-ratio, 3 / 2);
33
+ object-fit: cover;
34
+ }
35
+ a.gallery__link { transition: border-color 0.15s; }
36
+ a.gallery__link:hover { border-color: var(--ink); }
37
+
38
+ .gallery__caption {
39
+ color: var(--color-muted);
40
+ font-size: var(--text-xs);
41
+ line-height: var(--leading-normal);
42
+ }
43
+
44
+ /* ---- AI / in-transit: a gallery the AI is still filling wears the dashed "terminal" edge on its
45
+ tiles, the same vocabulary card + badge + field use. */
46
+ .gallery[data-commit="pending"] .gallery__link,
47
+ [data-grade="grain"] .gallery__link { border-style: dashed; border-color: var(--ink); }
@@ -0,0 +1,53 @@
1
+ # Gallery
2
+
3
+ A captioned image grid: the companion to `card-grid`, for pictures rather than facts. Every tile is
4
+ equal weight, cropped to one ratio, caption underneath. Composed by hand, so nothing data-binds it.
5
+
6
+ It is not a hero strip. A strip runs one photo big to carry a post; a gallery is the roll that hero
7
+ was picked from, and it belongs where a reader can scan it and move on. Tile width tunes with
8
+ `--gallery-min` (default `15rem`, the same idiom as `--card-min`), the crop with `--gallery-ratio`.
9
+
10
+ ## Gallery
11
+ ```html
12
+ <div class="gallery">
13
+ <figure class="gallery__item">
14
+ <span class="gallery__link"><img src="/assets/figure-sample.svg" alt="An abstract field of grain strokes"></span>
15
+ <figcaption class="gallery__caption">The caption is the alt text: it has to work read aloud and read on the page.</figcaption>
16
+ </figure>
17
+ <figure class="gallery__item">
18
+ <span class="gallery__link"><img src="/assets/figure-sample.svg" alt="The same field, second frame"></span>
19
+ <figcaption class="gallery__caption">One sentence, what is actually in the frame.</figcaption>
20
+ </figure>
21
+ </div>
22
+ ```
23
+
24
+ ## Wired to the lightbox
25
+
26
+ Wrap the grid in `data-lightbox-group` and mark each tile `data-lightbox` (`scripts/lightbox.js`).
27
+ **One group per gallery**, so prev/next never walks out of it into another strip on the same page.
28
+ Keep the trigger an `<a href>` pointing at the full image: with no JS, or a modified click, it
29
+ degrades to a plain navigation, which is the no-JS-safe fallback.
30
+
31
+ ```html
32
+ <div class="gallery" data-lightbox-group>
33
+ <figure class="gallery__item">
34
+ <a class="gallery__link" data-lightbox href="/assets/figure-sample.svg">
35
+ <img src="/assets/figure-sample.svg" alt="An abstract field of grain strokes" loading="lazy" decoding="async">
36
+ </a>
37
+ <figcaption class="gallery__caption">Clicking any tile opens the viewer and walks the whole group.</figcaption>
38
+ </figure>
39
+ </div>
40
+ ```
41
+
42
+ ## Wider tiles, square crop
43
+ ```html
44
+ <div class="gallery" style="--gallery-min: 20rem; --gallery-ratio: 1 / 1;">
45
+ <figure class="gallery__item">
46
+ <span class="gallery__link"><img src="/assets/figure-sample.svg" alt="A square crop of the same field"></span>
47
+ <figcaption class="gallery__caption">Both knobs are custom properties, set them on the grid.</figcaption>
48
+ </figure>
49
+ </div>
50
+ ```
51
+
52
+ **Alt text is the caption here**, so write one that carries both jobs: read aloud, and read on the
53
+ page under the picture.
@@ -0,0 +1,90 @@
1
+ /* molecules/media-card — a card that leads with a picture. CSS-only (CONVENTIONS §4): composed by
2
+ hand, nothing data-binds it. Card's vocabulary, not a second one: hairline box, no fill, no
3
+ shadow (DESIGN-SYSTEM §2), data-pad for padding, and the whole tile navigable when the root is
4
+ an <a>. Description and action row are both optional and both collapse to nothing when absent.
5
+
6
+ Layout is an attribute, not a second component. The default stacks the text under the picture;
7
+ [data-layout="overlay"] lays it over the bottom of the picture on a scrim. Those are the two
8
+ shapes with a real consumer today, and they share every other rule they have: the box, the
9
+ crop, the hover, the badge, the pending edge. Splitting them into two molecules would fork all
10
+ five to move one block of text. A beside-the-picture layout is the same decision again and is
11
+ deliberately not shipped until something asks for it: it is one more attribute value here, not
12
+ a new component.
13
+
14
+ It embeds nothing. The video poster consumer is one anchor over a still we host ourselves, so
15
+ there is no iframe, no platform script, and no JS in this component at all, which makes the
16
+ no-JS case the only case. The play badge is decorative (mark it aria-hidden); the title carries
17
+ the meaning for a screen reader.
18
+
19
+ Crop tunes with --media-ratio (default 16 / 9, the same idiom as --gallery-ratio). */
20
+ .media-card {
21
+ position: relative;
22
+ display: block;
23
+ overflow: hidden;
24
+ border: 1px solid var(--color-line);
25
+ border-radius: var(--radius-md);
26
+ }
27
+
28
+ /* fixed box for the picture: the ratio reserves the space, so a lazily-loaded still cannot shift
29
+ the page under someone mid-scroll, and object-fit crops whatever it is handed to that box. */
30
+ .media-card__media { display: block; position: relative; background: var(--paper-2); }
31
+ .media-card__image {
32
+ display: block; width: 100%; height: 100%;
33
+ aspect-ratio: var(--media-ratio, 16 / 9);
34
+ object-fit: cover;
35
+ }
36
+
37
+ .media-card__body { padding: var(--space-5); }
38
+ .media-card[data-pad="sm"] .media-card__body { padding: var(--space-4); }
39
+
40
+ /* both rows are display: block because the navigable form composes them as <span>. Inside an <a>
41
+ the whole tile is the link, and a <span> is the neutral element to reach for there; left inline
42
+ it would run the title and the description together on one line, which is what happens the first
43
+ time anyone copies the example. Declaring it here means the markup can be spans or an <h3> and a
44
+ <p>, and both stack. */
45
+ .media-card__title { display: block; font-size: var(--text-base); margin: 0; }
46
+ .media-card__text { display: block; color: var(--color-muted); font-size: var(--text-sm);
47
+ line-height: var(--leading-normal); margin: var(--space-2) 0 0; }
48
+
49
+ /* the action row: buttons composed by hand, wrapping rather than overflowing on a narrow tile */
50
+ .media-card__actions { display: flex; flex-wrap: wrap; gap: var(--space-2);
51
+ margin: var(--space-4) 0 0; }
52
+
53
+ /* a navigable tile: the whole card is the link, so the tap target is the picture. Quiet at rest,
54
+ the edge picks up ink on hover, the way a gallery tile does. */
55
+ a.media-card { text-decoration: none; color: var(--color-fg); }
56
+ a.media-card:hover { border-color: var(--ink); }
57
+ a.media-card[aria-disabled="true"] { pointer-events: none; opacity: 0.6; }
58
+
59
+ /* the play badge sits centred over the picture, carrying its own scrim disc so it survives a
60
+ bright frame. Decorative: the title is what a screen reader gets. */
61
+ .media-card__play {
62
+ position: absolute; inset: 0; margin: auto;
63
+ width: 4rem; height: 4rem;
64
+ display: grid; place-items: center;
65
+ border-radius: 50%;
66
+ background: var(--scrim); color: var(--on-scrim);
67
+ font-size: var(--text-2xl); line-height: 1; padding-left: .15em;
68
+ }
69
+ a.media-card:hover .media-card__play { background: var(--ink); }
70
+
71
+ /* ---- overlay: the text sits on the picture rather than under it. The gradient is the readability
72
+ device, not decoration: a label over an arbitrary photograph has no contrast guarantee without
73
+ it. Both scrim tokens hold their value across color schemes on purpose (variables.css). */
74
+ .media-card[data-layout="overlay"] .media-card__body {
75
+ position: absolute; left: 0; right: 0; bottom: 0;
76
+ padding: var(--space-4);
77
+ color: var(--on-scrim);
78
+ background: linear-gradient(to top, var(--scrim), transparent);
79
+ }
80
+ .media-card[data-layout="overlay"] .media-card__text { color: var(--on-scrim); opacity: 0.85; }
81
+
82
+ @media (prefers-reduced-motion: no-preference) {
83
+ a.media-card { transition: border-color 0.15s; }
84
+ .media-card__play { transition: background 0.15s; }
85
+ }
86
+
87
+ /* ---- AI / in-transit: a media card the AI is still composing wears the dashed "terminal" edge,
88
+ the same vocabulary card + gallery + badge + field use. */
89
+ .media-card[data-commit="pending"],
90
+ [data-grade="grain"] .media-card { border-style: dashed; border-color: var(--ink); }
@@ -0,0 +1,97 @@
1
+ # Media card
2
+
3
+ A card that leads with a picture: one image, a title, an optional description, an optional row of
4
+ buttons. It borrows `card`'s vocabulary rather than inventing a second one, so the box is a
5
+ hairline with no fill, `data-pad` tunes the padding, and the whole tile is the link when the root
6
+ is an `<a>`. Composed by hand, so nothing data-binds it. The crop tunes with `--media-ratio`
7
+ (default `16 / 9`, the same idiom as `--gallery-ratio`).
8
+
9
+ **It embeds nothing.** The reason lives in the second example below, but it applies to the whole
10
+ component: there is no iframe, no third-party script and no JS of any kind in it, which makes the
11
+ no-JS case the only case there is.
12
+
13
+ ## A picture that links somewhere
14
+
15
+ The plain case. The root is the anchor, so the picture is the tap target, and the description
16
+ collapses to nothing when you leave it out.
17
+
18
+ ```html
19
+ <a class="media-card" href="#media-card">
20
+ <span class="media-card__media">
21
+ <img class="media-card__image" src="/assets/figure-sample.svg"
22
+ alt="An abstract field of grain strokes" loading="lazy" decoding="async">
23
+ </span>
24
+ <span class="media-card__body">
25
+ <span class="media-card__title">The field, in one frame</span>
26
+ <span class="media-card__text">One sentence about where this goes, written like a link and not
27
+ like a button.</span>
28
+ </span>
29
+ </a>
30
+ ```
31
+
32
+ ## A video poster that links out
33
+
34
+ `data-layout="overlay"` moves the text onto the bottom of the picture, on a scrim, and the play
35
+ badge sits centred over it. The badge is decorative, so it is `aria-hidden` and the title is what a
36
+ screen reader is given.
37
+
38
+ This is the shape to reach for when a video lives on somebody else's platform. Embedding it would
39
+ put a third-party iframe and its scripts on the page to play something that lives over there
40
+ regardless: the visitor lands on that platform the moment they press play either way. So the tile
41
+ is one anchor over a still you host yourself, and the title says where the tap goes and whose
42
+ platform it lands on, because the picture cannot.
43
+
44
+ ```html
45
+ <a class="media-card" data-layout="overlay" href="https://example.com/reel/1" rel="noopener">
46
+ <span class="media-card__media">
47
+ <img class="media-card__image" src="/assets/figure-sample.svg" width="1600" height="900"
48
+ alt="A still from the recap, the room mid-session" loading="lazy" decoding="async">
49
+ <span class="media-card__play" aria-hidden="true">▶</span>
50
+ </span>
51
+ <span class="media-card__body">
52
+ <span class="media-card__title">Watch the recap on the platform it lives on</span>
53
+ </span>
54
+ </a>
55
+ ```
56
+
57
+ Both scrim colors hold their value in light and dark. A scrim darkens somebody else's photograph so
58
+ a label survives on top of it, and a photograph does not invert with the palette.
59
+
60
+ ## With an action row
61
+
62
+ **When there are buttons, the root is a `<div>`, never an `<a>`.** A link inside a link is invalid
63
+ markup and browsers recover from it in their own ways, so the two are mutually exclusive: either
64
+ the whole tile navigates, or the buttons do.
65
+
66
+ ```html
67
+ <div class="media-card" data-pad="sm">
68
+ <span class="media-card__media">
69
+ <img class="media-card__image" src="/assets/figure-sample.svg" style="--media-ratio: 3 / 2;"
70
+ alt="The same field, second frame" loading="lazy" decoding="async">
71
+ </span>
72
+ <div class="media-card__body">
73
+ <h3 class="media-card__title">Two ways out of one tile</h3>
74
+ <p class="media-card__text">The description is optional and so is this row. Both collapse to
75
+ nothing when they are absent.</p>
76
+ <div class="media-card__actions">
77
+ <a class="btn" data-size="sm" href="#media-card">Read the write-up</a>
78
+ <a class="btn" data-size="sm" data-variant="soft" href="#media-card">See the photos</a>
79
+ </div>
80
+ </div>
81
+ </div>
82
+ ```
83
+
84
+ ## Layouts
85
+
86
+ `data-layout` carries the layout, because the two shapes share every rule they have apart from
87
+ where the text sits: the box, the crop, the hover, the badge and the pending edge. Two components
88
+ would fork all five of those to move one block of text.
89
+
90
+ | Value | What it does |
91
+ | --- | --- |
92
+ | *(omitted)* | Stacked. The text sits under the picture. |
93
+ | `overlay` | The text sits over the bottom of the picture, on a scrim. |
94
+
95
+ A beside-the-picture layout is the same decision one more time, and it is deliberately not shipped
96
+ until something asks for it. When something does, it is one more value in that table rather than a
97
+ new molecule.
@@ -20,7 +20,7 @@
20
20
  /* the backdrop: the page behind the window, a shade darker than the paper */
21
21
  .app-window-backdrop {
22
22
  background: color-mix(in srgb, var(--ink) 12%, var(--paper));
23
- padding: clamp(0.5rem, 2vh, 1.5rem);
23
+ padding: clamp(var(--space-2), 2vh, var(--space-6));
24
24
  height: 100dvh;
25
25
  box-sizing: border-box;
26
26
  }
@@ -44,7 +44,11 @@
44
44
  .notepad__entry { min-width: 0; overflow-wrap: anywhere; }
45
45
  /* a code block is the one thing that shouldn't hard-wrap — let it scroll on its own, capped to width */
46
46
  .notepad__entry pre { max-width: 100%; overflow-x: auto; }
47
- .notepad__entry[data-grade="grain"] { color: var(--color-grain, var(--color-muted)); }
47
+ /* --color-grain was referenced here and defined nowhere, in this one line and no other in the
48
+ estate, so the fallback was the only thing that ever rendered. There is no "grain colour" to
49
+ point it at either: the grade vocabulary is carried by the FONT (--font-grain / --type-font),
50
+ not by a hue. So the phantom goes and the fallback becomes the rule it always was. */
51
+ .notepad__entry[data-grade="grain"] { color: var(--color-muted); }
48
52
  .notepad__entry > :first-child { margin-top: 0; }
49
53
  .notepad__entry > :last-child { margin-bottom: 0; }
50
54
  .notepad__entry a { color: var(--color-accent); text-decoration: none; }
@@ -229,18 +229,18 @@
229
229
  .presenter { display: none; }
230
230
  [data-mode="presenter"] .presenter {
231
231
  display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: auto 1fr;
232
- align-content: start; gap: 1.5rem; padding: 1.5rem; min-height: 100dvh;
232
+ align-content: start; gap: var(--space-6); padding: var(--space-6); min-height: 100dvh;
233
233
  box-sizing: border-box; font-size: 1rem;
234
234
  }
235
235
  .presenter__now { grid-column: 1 / -1; display: flex; justify-content: space-between;
236
- align-items: baseline; border-bottom: var(--rule); padding-bottom: 0.75rem; }
236
+ align-items: baseline; border-bottom: var(--rule); padding-bottom: var(--space-3); }
237
237
  .presenter__clock { font-family: var(--font-mono); font-size: 2.6rem; }
238
238
  .presenter__clock[data-over] { color: var(--color-accent); }
239
239
  .presenter__pos { font-family: var(--font-mono); color: var(--color-muted); }
240
- .presenter__title { font-size: 1.8rem; margin: 0 0 0.75rem; }
240
+ .presenter__title { font-size: 1.8rem; margin: 0 0 var(--space-3); }
241
241
  .presenter__notes li { font-size: 1.15rem; line-height: 1.55; margin-bottom: 0.55rem; }
242
242
  .presenter__next h3 { font-size: 0.95rem; letter-spacing: 0.12em; text-transform: uppercase;
243
- color: var(--color-muted); margin: 0 0 0.5rem; }
243
+ color: var(--color-muted); margin: 0 0 var(--space-2); }
244
244
  .presenter__next p { color: var(--color-muted); }
245
245
  .presenter__hint { grid-column: 1 / -1; margin: 0; font-size: 0.85rem; color: var(--ink-faint);
246
246
  letter-spacing: 0.08em; text-transform: uppercase; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tjakoen/grain",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "description": "GRAIN — an AI-interaction design system where every surface is operable by both a human and an AI through one shared vocabulary.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -1,4 +1,4 @@
1
- // /frontend/scripts/ai-dispatch.js — the dispatcher island (docs/AI-INTERFACE.md §3).
1
+ // grain/scripts/ai-dispatch.js — the dispatcher island (docs/AI-INTERFACE.md §3).
2
2
  //
3
3
  // The ONE accepted bit of client JS. Two jobs:
4
4
  // 1. Turn [data-action] interactions (click, or Enter in an input) into POST /intent
@@ -53,6 +53,7 @@ import { createSpotlight } from "/scripts/ai-spotlight.js";
53
53
  // dispatcher is the LAST line of defense before a value lands in a real form field, so it
54
54
  // re-checks even though the reasoner already validated.
55
55
  const FIELD_VALUE_CAP = 2000;
56
+ // eslint-disable-next-line no-control-regex
56
57
  const FIELD_VALUE_BAD_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f]/;
57
58
  const SAFE_FIELD_VALUE = (v) => typeof v === "string" && v.length <= FIELD_VALUE_CAP && !FIELD_VALUE_BAD_CHARS.test(v);
58
59
  // A `navigate` op tears the page down — irreversible, so give any in-flight settle (the
@@ -77,6 +78,7 @@ import { createSpotlight } from "/scripts/ai-spotlight.js";
77
78
  const MD_LIST_ITEM_RE = /^[-*]\s+/;
78
79
  const MD_BLOCK_SPLIT_RE = /\n{2,}/;
79
80
  // Placeholder delimiter for pulled-out code spans (below) — \x00 can't occur in real chat text.
81
+ // eslint-disable-next-line no-control-regex
80
82
  const MD_CODE_PLACEHOLDER_RE = /\x00(\d+)\x00/g;
81
83
  function mdInline(escaped) {
82
84
  // Code spans are pulled OUT first (placeholdered), so their literal contents can never be
@@ -188,6 +190,7 @@ import { createSpotlight } from "/scripts/ai-spotlight.js";
188
190
  const sh = document.querySelector(".app-shell");
189
191
  if (sh) { sh.removeAttribute("data-acting"); sh.removeAttribute("data-chat-open"); sh.removeAttribute("data-console-open"); } // hand back: everything resets
190
192
  clearActing(spotlit); spotlit = null;
193
+ // eslint-disable-next-line unicorn/no-useless-spread -- the copy IS load-bearing: clearTrigger deletes from pendingTriggers while we iterate it
191
194
  for (const t of [...pendingTriggers.keys()]) clearTrigger(t); // backstop: turn over → nothing stays "working"
192
195
  }
193
196
 
@@ -253,6 +256,7 @@ import { createSpotlight } from "/scripts/ai-spotlight.js";
253
256
  if (pendingTriggers.size) watchdogTimer = setTimeout(watchdogFire, WATCHDOG_MS);
254
257
  }
255
258
  function watchdogFire() {
259
+ // eslint-disable-next-line unicorn/no-useless-spread -- the copy IS load-bearing: clearTrigger deletes from pendingTriggers while we iterate it
256
260
  for (const [target, trg] of [...pendingTriggers.entries()]) {
257
261
  trg.removeAttribute("data-state"); void trg.offsetWidth; // restart the flash
258
262
  trg.setAttribute("data-state", "error");
@@ -299,7 +303,7 @@ import { createSpotlight } from "/scripts/ai-spotlight.js";
299
303
  applyType(el, op);
300
304
  return;
301
305
  case "spotlight": // the AI as actor: dim + light the target
302
- op.active ? spotlightOn(op.target, op.click) : spotlightOff();
306
+ if (op.active) spotlightOn(op.target, op.click); else spotlightOff();
303
307
  return;
304
308
  case "navigate": // AI-directed browser navigation (contract.ts's `navigate` op)
305
309
  if (typeof op.href !== "string" || !SAFE_NAV_HREF.test(op.href)) {
@@ -353,7 +357,7 @@ import { createSpotlight } from "/scripts/ai-spotlight.js";
353
357
  el.setAttribute("data-commit", "pending");
354
358
  body = el.querySelector(".stream-body");
355
359
  // OVERWRITE (op.back) re-enters an already-written surface → keep its text so the
356
- // the AI can backspace it. A fresh write (text, no back) starts empty (wipes any placeholder).
360
+ // AI can backspace it. A fresh write (text, no back) starts empty (wipes any placeholder).
357
361
  if (typeof op.back === "number") body.textContent = prev;
358
362
  }
359
363
  if (typeof op.back === "number" && op.back > 0) // the AI revising: delete trailing chars
@@ -484,7 +488,7 @@ import { createSpotlight } from "/scripts/ai-spotlight.js";
484
488
  if (trigger) { clearTrigger(target); trigger.setAttribute("data-commit", "pending"); pendingTriggers.set(target, trigger); armWatchdog(); }
485
489
  const send = () => sendIntent({ source: "user", session, screen, surface: target, action, payload })
486
490
  .catch(() => { clearTrigger(target); markOnline(false); }); // couldn't reach the door (timeout/network) → undo + honest offline
487
- sseIsOpen ? send() : sseReady.then(send); // wait for the stream so no early ops are lost
491
+ if (sseIsOpen) send(); else sseReady.then(send); // wait for the stream so no early ops are lost
488
492
  }
489
493
 
490
494
  // fire a [data-action] trigger (a button/link with a verb) through the ONE door. Shared by page
package/scripts/cmdk.js CHANGED
@@ -139,7 +139,7 @@
139
139
  function init() {
140
140
  build();
141
141
  document.addEventListener("keydown", (ev) => {
142
- if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === "k") { ev.preventDefault(); isOpen() ? close() : open(); }
142
+ if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === "k") { ev.preventDefault(); if (isOpen()) close(); else open(); }
143
143
  });
144
144
  // declarative trigger: any [data-cmdk-open] element opens the palette (e.g. the title
145
145
  // bar's search field — a button drawn as an input)
@@ -30,7 +30,7 @@
30
30
  const DRAFT_KEY = "grain.notepad.draft"; // the human's uncommitted textarea text (kept across reload)
31
31
 
32
32
  const read = (k) => { try { return localStorage.getItem(k); } catch { return null; } };
33
- const write = (k, v) => { try { v == null ? localStorage.removeItem(k) : localStorage.setItem(k, v); } catch { /* private mode */ } };
33
+ const write = (k, v) => { try { if (v == null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* private mode */ } };
34
34
 
35
35
  // Join every entry's markdown source, in order — the whole pad's canonical markdown.
36
36
  const deriveSource = (body) =>
package/scripts/shell.js CHANGED
@@ -48,7 +48,7 @@
48
48
  for (const b of shell.querySelectorAll(`[data-shell="${name}"]`))
49
49
  b.addEventListener("click", () => {
50
50
  const on = shell.getAttribute(attr) !== "true";
51
- on ? shell.setAttribute(attr, "true") : shell.removeAttribute(attr);
51
+ if (on) shell.setAttribute(attr, "true"); else shell.removeAttribute(attr);
52
52
  try { localStorage.setItem(key, on ? "1" : "0"); } catch { /* ignore */ }
53
53
  });
54
54
  }
package/scripts/tabs.js CHANGED
@@ -103,7 +103,7 @@
103
103
  if (path !== here) return render();
104
104
  // closing the page you're ON: go to the neighbor tab, else the first pinned tab, else home
105
105
  const next = list[Math.min(i, list.length - 1)]
106
- || (strip.querySelector("a[data-pinned]") || {}).getAttribute?.("href") || "/";
106
+ || strip.querySelector("a[data-pinned]")?.getAttribute("href") || "/";
107
107
  location.assign(next);
108
108
  };
109
109
 
@@ -112,7 +112,7 @@
112
112
  list = [];
113
113
  save(list);
114
114
  if (!wasHere) return render();
115
- location.assign((strip.querySelector("a[data-pinned]") || {}).getAttribute?.("href") || "/");
115
+ location.assign(strip.querySelector("a[data-pinned]")?.getAttribute("href") || "/");
116
116
  };
117
117
 
118
118
  const allBtns = document.querySelectorAll('[data-shell="tabs-close-all"]');
@@ -19,7 +19,7 @@
19
19
  "use strict";
20
20
  if (window.grain && window.grain.terminal) return; // idempotent
21
21
 
22
- const PROMPT = "❯"; // ❯
22
+ const PROMPT = "❯";
23
23
  const HISTORY_KEY = "grain.terminal.history";
24
24
  const HISTORY_CAP = 50;
25
25
  const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -11,5 +11,5 @@
11
11
  if (s) html.setAttribute("data-color-scheme", s);
12
12
  var t = localStorage.getItem("grain-theme");
13
13
  if (t) html.setAttribute("data-theme", t);
14
- } catch (e) { /* no storage (privacy mode) → defaults render, theme.js stays the fallback */ }
14
+ } catch { /* no storage (privacy mode) → defaults render, theme.js stays the fallback */ }
15
15
  })();
package/scripts/theme.js CHANGED
@@ -27,7 +27,7 @@
27
27
  const html = document.documentElement;
28
28
  const store = (() => { try { return window.localStorage; } catch { return null; } })();
29
29
  const get = (k) => { try { return store && store.getItem(k); } catch { return null; } };
30
- const put = (k, v) => { try { if (store) v == null ? store.removeItem(k) : store.setItem(k, v); } catch {} };
30
+ const put = (k, v) => { try { if (store) { if (v == null) store.removeItem(k); else store.setItem(k, v); } } catch { /* private mode — the pref just doesn't persist */ } };
31
31
 
32
32
  // ---- color scheme (light | dark | auto; auto drops the attr → follow the OS) --------------
33
33
  function setScheme(s) {
@@ -18,21 +18,30 @@
18
18
  .lightbox::backdrop { background: color-mix(in srgb, var(--ink) 82%, transparent); }
19
19
  @media (prefers-reduced-motion: reduce) { .lightbox { transition: none; } }
20
20
 
21
- /* the figure: the centre column, holds the image + its caption */
21
+ /* the figure: the centre column, holds the image + its caption. `align-items: center` is load-bearing:
22
+ without it the column stretches its children, so a long caption widens the figure and the image box
23
+ with it — the picture then letterboxes inside a too-wide box and the img's own background paints
24
+ paper-coloured bars beside it. Centred, the image shrink-wraps to its real aspect. */
22
25
  .lightbox__figure {
23
26
  grid-column: 2; justify-self: center; align-self: center;
24
- display: flex; flex-direction: column; gap: var(--space-2);
27
+ display: flex; flex-direction: column; align-items: center; gap: var(--space-2);
25
28
  max-width: 100%; max-height: 100dvh; margin: 0; padding: var(--space-3);
26
29
  box-sizing: border-box;
27
30
  }
31
+ /* the height budget: the viewport minus the bottom chrome the figure must not collide with (the dot
32
+ rail + counter) and minus room for a caption line or two. Without it a tall image pushes its own
33
+ caption down into the dots. */
28
34
  .lightbox__img {
29
- display: block; max-width: 100%; max-height: calc(100dvh - 6rem);
35
+ display: block; max-width: 100%; max-height: calc(100dvh - 12rem);
30
36
  width: auto; height: auto; object-fit: contain;
31
37
  border-radius: var(--radius-md); background: var(--color-bg);
32
38
  box-shadow: 0 8px 32px color-mix(in srgb, var(--ink) 55%, transparent);
33
39
  }
40
+ /* the caption WRAPS: centring the column stopped it from stretching, so an unbounded line would run
41
+ straight off both edges of the viewport. It reads under the image, never wider than the gutter. */
34
42
  .lightbox__caption {
35
- text-align: center; font-size: .85rem; color: var(--color-bg);
43
+ align-self: stretch; max-width: min(100%, 60ch); margin: 0 auto;
44
+ text-align: center; font-size: .85rem; line-height: 1.4; color: var(--color-bg);
36
45
  text-shadow: 0 1px 3px color-mix(in srgb, var(--ink) 85%, transparent);
37
46
  }
38
47
 
@@ -47,6 +47,14 @@
47
47
  --hairline: #1C1B17; /* solid rules (under headlines) */
48
48
  --line-soft: rgba(28, 27, 23, .14); /* translucent border for quiet grouping */
49
49
 
50
+ /* the photo scrim, and the text that sits on it. Deliberately NOT part of the paper/ink pair
51
+ and deliberately NOT overridden in the dark block below: a scrim darkens somebody else's
52
+ photograph so a label survives on top of it, and a photograph does not invert with the
53
+ palette. Flip these with the color scheme and the light mode gets a dark scrim, the dark
54
+ mode a pale one, and the same picture reads two different ways for no reason. */
55
+ --scrim: rgba(20, 19, 15, .72); /* over a still, so a label on it holds in both modes */
56
+ --on-scrim: #F4F2EA; /* the only text color legible on that scrim */
57
+
50
58
  /* grade font families (clean = human, grain = AI / in-transit). Grain is grade 50 —
51
59
  one step up from the 35 working grade for more visible texture. */
52
60
  --font-smooth: "Redaction", "Times New Roman", Georgia, serif;
@@ -170,6 +178,18 @@
170
178
  /* AI takeover STACKING — one source of truth so the AI module (grain/ai/ai.css) and any
171
179
  consumer chrome (e.g. the app's portfolio-frame console/chat) agree without duplicating
172
180
  magic z-index numbers. veil < spotlit surface < the AI surfaces that stay above the veil. */
181
+ /* Shared chrome heights. The one-line head that the drawer, the app-shell topbar and the
182
+ sidebar-panel all have to agree on: all three read `var(--editor-header-h, 2.9rem)` and none
183
+ of them defined it, so three organisms were agreeing by repeating a magic number rather than
184
+ by sharing a token. 2.9rem is the value that already rendered; declaring it here is what makes
185
+ the agreement real, and what makes it possible to change the row height in one place. */
186
+ --editor-header-h: 2.9rem;
187
+
188
+ /* Presentation sits BELOW the AI ladder on purpose: the lamp has to be able to dim a slide.
189
+ It was already reading `var(--z-presentation, 8000)` in presentation.css with nothing
190
+ defining it, so 8000 is the value that has always rendered — this declares it rather than
191
+ changing it, and puts it on the ladder where the next person can see the ordering. */
192
+ --z-presentation: 8000;
173
193
  --z-ai-veil: 9000; /* the dimming backdrop */
174
194
  --z-ai-spot: 9001; /* the spotlit surface, lifted out of the dim */
175
195
  --z-ai-surface: 9002; /* AI surfaces kept above the veil (acting label, console, chat) */
@@ -0,0 +1,96 @@
1
+ // grain/styles/vars-defined.test.ts — the guard that plans/grain-token-debt.md G3 asks for: every
2
+ // custom property a stylesheet READS has to be one some stylesheet DEFINES.
3
+ //
4
+ // Why this exists, concretely. crumb.css shipped five references that were defined nowhere in grain
5
+ // or crumb: --accent, --font-ui, --ink-soft, --ok and --warn. Nothing failed, nothing warned, and
6
+ // two of them rendered — `var(--ok, green)` and `var(--warn, orange)` put a literal green and a
7
+ // literal orange on screen inside a palette that collapses every status to ink on purpose. They
8
+ // survived an audit and a release because CSS has no undefined-variable error: it takes the
9
+ // fallback and says nothing.
10
+ //
11
+ // So the fallback is NOT an excuse here, it is the aggravating factor. `var(--nope)` renders as
12
+ // nothing and someone notices within the hour; `var(--nope, green)` renders as green and ships. A
13
+ // reference with a fallback is held to exactly the same bar as one without, which is the only rule
14
+ // that would have caught the five.
15
+ //
16
+ // Scope is the whole package set rather than one package, because the vocabulary is shared: grain
17
+ // defines the tokens and crumb, mill and proof spend them. A per-package check would have called
18
+ // crumb's references "external" and passed.
19
+ import { test, expect } from "bun:test";
20
+ import { readdirSync, readFileSync } from "node:fs";
21
+ import { join, relative } from "node:path";
22
+
23
+ const PACKAGES = join(import.meta.dir, "..", "..");
24
+
25
+ // Directories that hold no shipped styling: dependencies, build output, and anything a package
26
+ // generates. A stylesheet under any of these is not ours to hold to the vocabulary.
27
+ const SKIP = new Set(["node_modules", "dist", "build", ".git", "coverage"]);
28
+
29
+ function cssFiles(dir: string, out: string[] = []): string[] {
30
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
31
+ if (SKIP.has(e.name)) continue;
32
+ const full = join(dir, e.name);
33
+ if (e.isDirectory()) cssFiles(full, out);
34
+ else if (e.name.endsWith(".css")) out.push(full);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ // A DEFINITION is `--name:` in declaration position. A reference inside a value never matches,
40
+ // because `var(--x)` and `var(--x, y)` put a `)` or a `,` after the name, never a `:`.
41
+ const DEFINE = /(?:^|[;{\s])(--[a-zA-Z0-9_-]+)\s*:/g;
42
+ const REFERENCE = /var\(\s*(--[a-zA-Z0-9_-]+)/g;
43
+
44
+ // The two honest reasons a reference has no declaration, each with the receipt that makes it
45
+ // checkable. Adding a name here without one turns this guard back into the thing it replaced.
46
+ //
47
+ // 1. WRITTEN AT RUNTIME — a script sets it with style.setProperty, so no stylesheet can declare it.
48
+ // 2. AN INSTANCE KNOB — the component publishes it as a per-use parameter the CALLER supplies
49
+ // inline (`style="--seg: 70%"`), documented in that component's .md. The fallback in the
50
+ // stylesheet is the documented default, which is the one case where a fallback is the design
51
+ // rather than a cover for a missing token.
52
+ const EXTERNALLY_SET = new Map<string, string>([
53
+ ["--cmdk-top", "runtime: grain/scripts/cmdk.js:116,130 setProperty"],
54
+ ["--cmdk-left", "runtime: grain/scripts/cmdk.js setProperty"],
55
+ ["--cmdk-width", "runtime: grain/scripts/cmdk.js setProperty"],
56
+ ["--seg", "instance knob: components/atoms/b-meter/b-meter.md:5,16"],
57
+ ["--card-min", "instance knob: components/molecules/card/card.md:4"],
58
+ ["--gallery-min", "instance knob: components/molecules/gallery/gallery.md:8,48"],
59
+ ["--gallery-ratio", "instance knob: components/molecules/gallery/gallery.md:8,48"],
60
+ ["--media-ratio", "instance knob: components/molecules/media-card/media-card.md:6,76"],
61
+ ["--rail-icon-col", "instance knob: components/molecules/nav-item/nav-item.md:4"],
62
+ ["--draw-len", "instance knob: components/organisms/presentation/presentation.md:82"],
63
+ ]);
64
+ const SET_IN_JS = new Set<string>(EXTERNALLY_SET.keys());
65
+
66
+ // Comments are blanked, not deleted, so line numbers survive for the report. This is not a nicety:
67
+ // the first run of this check reported --ok and --warn as still-undefined in crumb.css, and they
68
+ // were, in a comment explaining that they had just been removed. A checker that reads prose finds
69
+ // defects that are not there, which costs more trust than the ones it catches.
70
+ const decomment = (src: string) =>
71
+ src.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "));
72
+
73
+ function scan(re: RegExp, src: string): string[] {
74
+ const found: string[] = [];
75
+ for (const m of src.matchAll(re)) found.push(m[1]);
76
+ return found;
77
+ }
78
+
79
+ test("every var(--token) a stylesheet reads is defined by some stylesheet", () => {
80
+ const files = cssFiles(PACKAGES);
81
+ expect(files.length).toBeGreaterThan(0); // a silent empty sweep would pass forever
82
+
83
+ const defined = new Set<string>(SET_IN_JS);
84
+ for (const f of files) for (const name of scan(DEFINE, decomment(readFileSync(f, "utf8")))) defined.add(name);
85
+
86
+ const undefinedRefs: string[] = [];
87
+ for (const f of files) {
88
+ const src = decomment(readFileSync(f, "utf8"));
89
+ src.split("\n").forEach((line, i) => {
90
+ for (const name of scan(REFERENCE, line)) {
91
+ if (!defined.has(name)) undefinedRefs.push(`${relative(PACKAGES, f)}:${i + 1}: ${name}`);
92
+ }
93
+ });
94
+ }
95
+ expect([...new Set(undefinedRefs)]).toEqual([]);
96
+ });