@tjakoen/grain 0.1.12

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.
Files changed (181) hide show
  1. package/LICENSE +202 -0
  2. package/PLAN.md +27 -0
  3. package/README.md +243 -0
  4. package/ai/accepts.test.ts +69 -0
  5. package/ai/accepts.ts +57 -0
  6. package/ai/ai.css +127 -0
  7. package/ai/client-door.test.ts +70 -0
  8. package/ai/client-door.ts +56 -0
  9. package/ai/contract.test.ts +158 -0
  10. package/ai/contract.ts +285 -0
  11. package/ai/interaction-layer.test.ts +270 -0
  12. package/ai/interaction-layer.ts +138 -0
  13. package/ai/manifest-dom.test.ts +176 -0
  14. package/ai/manifest-dom.ts +187 -0
  15. package/ai/manifest.test.ts +71 -0
  16. package/ai/manifest.ts +57 -0
  17. package/ai/markdown.test.ts +68 -0
  18. package/ai/markdown.ts +74 -0
  19. package/ai/model-chat.test.ts +131 -0
  20. package/ai/model-chat.ts +151 -0
  21. package/ai/model-reasoner.test.ts +152 -0
  22. package/ai/model-reasoner.ts +146 -0
  23. package/ai/model.test.ts +148 -0
  24. package/ai/model.ts +200 -0
  25. package/ai/reasoner-kit.test.ts +142 -0
  26. package/ai/reasoner-kit.ts +159 -0
  27. package/ai/reasoner.test.ts +227 -0
  28. package/ai/reasoner.ts +446 -0
  29. package/ai/timeline-log.test.ts +55 -0
  30. package/ai/timeline-log.ts +50 -0
  31. package/ai/vocab-reference.test.ts +43 -0
  32. package/ai/vocab-reference.ts +107 -0
  33. package/ai/webllm.test.ts +79 -0
  34. package/ai/webllm.ts +125 -0
  35. package/assets/figure-sample.svg +14 -0
  36. package/assets/sprite.svg +22 -0
  37. package/catalog/catalog.test.ts +37 -0
  38. package/catalog/catalog.ts +424 -0
  39. package/components/atoms/action-badge/action-badge.css +17 -0
  40. package/components/atoms/action-badge/action-badge.html +6 -0
  41. package/components/atoms/action-badge/action-badge.md +23 -0
  42. package/components/atoms/b-badge/b-badge.css +15 -0
  43. package/components/atoms/b-badge/b-badge.html +2 -0
  44. package/components/atoms/b-badge/b-badge.md +16 -0
  45. package/components/atoms/b-button/b-button.ai.md +22 -0
  46. package/components/atoms/b-button/b-button.css +87 -0
  47. package/components/atoms/b-button/b-button.html +5 -0
  48. package/components/atoms/b-button/b-button.md +77 -0
  49. package/components/atoms/b-icon/b-icon.css +10 -0
  50. package/components/atoms/b-icon/b-icon.html +5 -0
  51. package/components/atoms/b-icon/b-icon.md +36 -0
  52. package/components/atoms/b-icon-button/b-icon-button.ai.md +11 -0
  53. package/components/atoms/b-icon-button/b-icon-button.css +43 -0
  54. package/components/atoms/b-icon-button/b-icon-button.html +8 -0
  55. package/components/atoms/b-icon-button/b-icon-button.md +33 -0
  56. package/components/atoms/b-input/b-input.css +36 -0
  57. package/components/atoms/b-input/b-input.html +8 -0
  58. package/components/atoms/b-input/b-input.md +59 -0
  59. package/components/atoms/b-kbd/b-kbd.css +11 -0
  60. package/components/atoms/b-kbd/b-kbd.html +3 -0
  61. package/components/atoms/b-kbd/b-kbd.md +13 -0
  62. package/components/atoms/b-list/b-list.css +21 -0
  63. package/components/atoms/b-list/b-list.html +6 -0
  64. package/components/atoms/b-list/b-list.md +24 -0
  65. package/components/atoms/b-meter/b-meter.css +39 -0
  66. package/components/atoms/b-meter/b-meter.md +44 -0
  67. package/components/atoms/b-select/b-select.css +35 -0
  68. package/components/atoms/b-select/b-select.md +75 -0
  69. package/components/atoms/b-switch/b-switch.css +61 -0
  70. package/components/atoms/b-switch/b-switch.html +6 -0
  71. package/components/atoms/b-switch/b-switch.md +40 -0
  72. package/components/atoms/b-text/b-text.ai.md +29 -0
  73. package/components/atoms/b-text/b-text.css +2 -0
  74. package/components/atoms/b-text/b-text.html +3 -0
  75. package/components/atoms/b-text/b-text.md +23 -0
  76. package/components/atoms/code-block/code-block.css +42 -0
  77. package/components/atoms/code-block/code-block.md +23 -0
  78. package/components/examples.test.ts +23 -0
  79. package/components/molecules/callout/callout.css +19 -0
  80. package/components/molecules/callout/callout.md +15 -0
  81. package/components/molecules/card/card.css +28 -0
  82. package/components/molecules/card/card.md +30 -0
  83. package/components/molecules/chat-message/chat-message.css +83 -0
  84. package/components/molecules/chat-message/chat-message.md +52 -0
  85. package/components/molecules/chip-group/chip-group.css +35 -0
  86. package/components/molecules/chip-group/chip-group.md +42 -0
  87. package/components/molecules/content-index/content-index.css +87 -0
  88. package/components/molecules/content-index/content-index.md +27 -0
  89. package/components/molecules/content-source/content-source.css +6 -0
  90. package/components/molecules/content-source/content-source.md +13 -0
  91. package/components/molecules/figure/figure.css +19 -0
  92. package/components/molecules/figure/figure.md +20 -0
  93. package/components/molecules/lede/lede.css +17 -0
  94. package/components/molecules/lede/lede.md +17 -0
  95. package/components/molecules/made-with/made-with.css +25 -0
  96. package/components/molecules/made-with/made-with.md +35 -0
  97. package/components/molecules/nav-item/nav-item.css +19 -0
  98. package/components/molecules/nav-item/nav-item.md +21 -0
  99. package/components/molecules/stat-tile/stat-tile.css +34 -0
  100. package/components/molecules/stat-tile/stat-tile.md +50 -0
  101. package/components/molecules/status-list/status-list.css +47 -0
  102. package/components/molecules/status-list/status-list.md +62 -0
  103. package/components/molecules/tab/tab.css +32 -0
  104. package/components/molecules/tab/tab.md +27 -0
  105. package/components/molecules/table/table.css +23 -0
  106. package/components/molecules/table/table.md +18 -0
  107. package/components/organisms/activity-bar/activity-bar.css +36 -0
  108. package/components/organisms/activity-bar/activity-bar.md +43 -0
  109. package/components/organisms/app-shell/app-shell.css +193 -0
  110. package/components/organisms/app-shell/app-shell.md +58 -0
  111. package/components/organisms/app-shell/app-shell.test.ts +74 -0
  112. package/components/organisms/app-window/app-window.css +111 -0
  113. package/components/organisms/app-window/app-window.md +53 -0
  114. package/components/organisms/chat-log/chat-log.css +5 -0
  115. package/components/organisms/chat-log/chat-log.md +14 -0
  116. package/components/organisms/code-editor/code-editor.ai.md +31 -0
  117. package/components/organisms/code-editor/code-editor.css +111 -0
  118. package/components/organisms/code-editor/code-editor.md +122 -0
  119. package/components/organisms/console/console.css +112 -0
  120. package/components/organisms/console/console.md +66 -0
  121. package/components/organisms/file-tree/file-tree.css +85 -0
  122. package/components/organisms/file-tree/file-tree.md +49 -0
  123. package/components/organisms/note/note.css +19 -0
  124. package/components/organisms/note/note.md +20 -0
  125. package/components/organisms/notepad/notepad.css +60 -0
  126. package/components/organisms/notepad/notepad.md +40 -0
  127. package/components/organisms/side-rail/side-rail.css +55 -0
  128. package/components/organisms/side-rail/side-rail.md +24 -0
  129. package/components/organisms/sidebar-panel/sidebar-panel.css +69 -0
  130. package/components/organisms/sidebar-panel/sidebar-panel.md +47 -0
  131. package/components/organisms/status-bar/status-bar.css +33 -0
  132. package/components/organisms/status-bar/status-bar.md +28 -0
  133. package/components/organisms/tab-bar/tab-bar.css +48 -0
  134. package/components/organisms/tab-bar/tab-bar.md +26 -0
  135. package/components/organisms/timeline/timeline.css +51 -0
  136. package/components/organisms/timeline/timeline.md +42 -0
  137. package/components/organisms/topbar/topbar.css +8 -0
  138. package/components/organisms/topbar/topbar.md +26 -0
  139. package/components/responsive-polish.test.ts +43 -0
  140. package/components/tokens.test.ts +39 -0
  141. package/fonts/redaction-35-400.woff2 +0 -0
  142. package/fonts/redaction-400.woff2 +0 -0
  143. package/fonts/redaction-50-400.woff2 +0 -0
  144. package/fonts/redaction-70-400.woff2 +0 -0
  145. package/package.json +46 -0
  146. package/scripts/ai-dispatch.js +583 -0
  147. package/scripts/ai-dispatch.test.ts +85 -0
  148. package/scripts/ai-spotlight.d.ts +23 -0
  149. package/scripts/ai-spotlight.js +139 -0
  150. package/scripts/ai-spotlight.test.ts +31 -0
  151. package/scripts/catalog-peek.js +156 -0
  152. package/scripts/catalog-peek.test.ts +31 -0
  153. package/scripts/cmdk.js +159 -0
  154. package/scripts/demo-box.js +53 -0
  155. package/scripts/handoff.js +64 -0
  156. package/scripts/handoff.test.ts +36 -0
  157. package/scripts/lightbox.js +144 -0
  158. package/scripts/lightbox.test.ts +23 -0
  159. package/scripts/made-with.d.ts +2 -0
  160. package/scripts/made-with.js +22 -0
  161. package/scripts/made-with.test.ts +25 -0
  162. package/scripts/notepad.js +100 -0
  163. package/scripts/shell.js +204 -0
  164. package/scripts/shell.test.ts +50 -0
  165. package/scripts/tabs.js +127 -0
  166. package/scripts/tabs.test.ts +40 -0
  167. package/scripts/terminal.js +271 -0
  168. package/scripts/terminal.test.ts +36 -0
  169. package/scripts/theme-boot.js +15 -0
  170. package/scripts/theme.js +87 -0
  171. package/scripts/type-effect.js +25 -0
  172. package/scripts/xray.js +79 -0
  173. package/scripts/xray.test.ts +43 -0
  174. package/styles/cmdk.css +65 -0
  175. package/styles/global.css +80 -0
  176. package/styles/grain.css +47 -0
  177. package/styles/lightbox.css +78 -0
  178. package/styles/themes/_template.css +48 -0
  179. package/styles/themes/baguette.css +30 -0
  180. package/styles/themes/brioche.css +30 -0
  181. package/styles/variables.css +217 -0
@@ -0,0 +1,85 @@
1
+ // grain/scripts/ai-dispatch.test.ts — ai-dispatch.js is a browser-native IIFE (DOM globals,
2
+ // EventSource, crypto.randomUUID at load time) that can't be imported into a bun test — see its
3
+ // own file header, "the ONE accepted bit of client JS". What CAN be verified without a browser:
4
+ // that its two intentional, self-contained COPIES of grain rules (the navigate href guard, the
5
+ // settle-time markdown renderer) stay byte-identical to their canonical, unit-tested sources.
6
+ //
7
+ // DRIFT GUARD, same technique as ai/vocab-reference.test.ts's RENDER_OP_KINDS check: read both
8
+ // files as text and compare the regex LITERALS verbatim. CLAUDE.md lesson #5 — a contract that can
9
+ // silently drift needs a test that catches it, not just a patched instance.
10
+ import { test, expect } from "bun:test";
11
+
12
+ const read = (rel: string) => Bun.file(new URL(rel, import.meta.url)).text();
13
+
14
+ test("ai-dispatch.js registers a case for every RenderOpKind contract.ts declares", async () => {
15
+ const [dispatch, contract] = await Promise.all([read("./ai-dispatch.js"), read("../ai/contract.ts")]);
16
+ const m = contract.match(/export type RenderOpKind\s*=\s*([^;]+);/);
17
+ expect(m).not.toBeNull();
18
+ const kinds = [...m![1].matchAll(/"([a-z]+)"/g)].map((x) => x[1]);
19
+ expect(kinds).toContain("navigate"); // sanity: this test would be vacuous if contract.ts regressed
20
+ for (const kind of kinds) expect(dispatch).toContain(`case "${kind}":`);
21
+ });
22
+
23
+ test("SAFE_NAV_HREF in ai-dispatch.js matches contract.ts's isSafeNavigateHref regex verbatim", async () => {
24
+ const [dispatch, contract] = await Promise.all([read("./ai-dispatch.js"), read("../ai/contract.ts")]);
25
+ const dispatchRe = dispatch.match(/const SAFE_NAV_HREF = (\/.*\/);/)?.[1];
26
+ const contractRe = contract.match(/const SAFE_NAV_HREF = (\/.*\/);/)?.[1];
27
+ expect(dispatchRe).toBeTruthy();
28
+ expect(contractRe).toBeTruthy();
29
+ expect(dispatchRe).toBe(contractRe);
30
+ });
31
+
32
+ test("ai-dispatch.js's markdown regex rules match ai/markdown.ts's verbatim", async () => {
33
+ const [dispatch, markdown] = await Promise.all([read("./ai-dispatch.js"), read("../ai/markdown.ts")]);
34
+ const rules = ["CODE_RE", "LINK_RE", "STRONG_RE", "EM_RE", "LIST_ITEM_RE", "BLOCK_SPLIT_RE"];
35
+ for (const name of rules) {
36
+ const dRe = dispatch.match(new RegExp(`const MD_${name} = (\\/.*\\/[a-z]*);`))?.[1];
37
+ const mRe = markdown.match(new RegExp(`const ${name} = (\\/.*\\/[a-z]*);`))?.[1];
38
+ expect(dRe, `MD_${name} missing or reformatted in ai-dispatch.js`).toBeTruthy();
39
+ expect(mRe, `${name} missing or reformatted in markdown.ts`).toBeTruthy();
40
+ expect(dRe).toBe(mRe);
41
+ }
42
+ });
43
+
44
+ test("the fill value guard in ai-dispatch.js matches contract.ts's isSafeFieldValue verbatim (cap + regex)", async () => {
45
+ const [dispatch, contract] = await Promise.all([read("./ai-dispatch.js"), read("../ai/contract.ts")]);
46
+ const dispatchCap = dispatch.match(/const FIELD_VALUE_CAP = (\d+);/)?.[1];
47
+ const contractCap = contract.match(/const FIELD_VALUE_CAP = (\d+);/)?.[1];
48
+ expect(dispatchCap).toBeTruthy();
49
+ expect(contractCap).toBeTruthy();
50
+ expect(dispatchCap).toBe(contractCap);
51
+ const dispatchRe = dispatch.match(/const FIELD_VALUE_BAD_CHARS = (\/.*\/);/)?.[1];
52
+ const contractRe = contract.match(/const FIELD_VALUE_BAD_CHARS = (\/.*\/);/)?.[1];
53
+ expect(dispatchRe).toBeTruthy();
54
+ expect(contractRe).toBeTruthy();
55
+ expect(dispatchRe).toBe(contractRe);
56
+ });
57
+
58
+ test("fill sets .value + a grain grade and dispatches a bubbling input event; a trusted input settles the grade", async () => {
59
+ // The IIFE can't be imported (file header) — assert the fill case's contract-critical moves as
60
+ // source text, the same bar the other guards here hold: value assignment (not innerHTML), the
61
+ // grain grade, the bubbling input event, and the isTrusted-only settle listener.
62
+ const dispatch = await read("./ai-dispatch.js");
63
+ const fillCase = dispatch.match(/case "fill":([\s\S]*?)return;/)?.[1] ?? "";
64
+ expect(fillCase).toContain('"value" in el'); // inert on a non-field element
65
+ expect(fillCase).toContain("SAFE_FIELD_VALUE(op.text)"); // last-line-of-defense re-check
66
+ expect(fillCase).toContain("el.value = op.text"); // state, not markup
67
+ expect(fillCase).toContain('el.setAttribute("data-grade", "grain")');
68
+ expect(fillCase).toContain('new Event("input", { bubbles: true })');
69
+ expect(dispatch).toContain("ev.isTrusted"); // human touch settles AI ink…
70
+ expect(dispatch).toMatch(/isTrusted\)\s*return/); // …synthetic events never do
71
+ });
72
+
73
+ test("a navigate op with an unsafe href is never assigned to location — asserted on the shared regex", async () => {
74
+ const contract = await read("../ai/contract.ts");
75
+ const src = contract.match(/const SAFE_NAV_HREF = (\/.*\/);/)?.[1];
76
+ expect(src).toBeTruthy();
77
+ // eslint-disable-next-line no-eval -- reconstructing the SAME literal ai-dispatch.js guards with
78
+ const re = new Function(`return ${src};`)() as RegExp;
79
+ expect(re.test("/notes")).toBe(true);
80
+ expect(re.test("/")).toBe(true);
81
+ expect(re.test("javascript:alert(1)")).toBe(false);
82
+ expect(re.test("https://evil.example")).toBe(false);
83
+ expect(re.test("//evil.example")).toBe(false);
84
+ expect(re.test("/\\evil.example")).toBe(false);
85
+ });
@@ -0,0 +1,23 @@
1
+ // Types for the hand-authored browser module ai-spotlight.js (THE TRAVELING LAMP). Lets TS
2
+ // consumers (the colocated test; CRUMB's tour client) import it without `any`. Keep in sync with
3
+ // the module's exports — the .js stays the SSOT (no build step).
4
+
5
+ /** A client rect the passthrough hole is cut from (the lamp's on-screen geometry). */
6
+ export interface LampRect { left: number; top: number; width: number; height: number; }
7
+
8
+ /**
9
+ * The backdrop's click-catch clip: "the whole viewport EXCEPT `hole`", as a slit polygon, so the
10
+ * lit target stays clickable in passthrough mode. `null`/`undefined` → "" (full-cover backdrop).
11
+ */
12
+ export function backdropClip(hole: LampRect | null | undefined): string;
13
+
14
+ export interface Spotlight {
15
+ on(text?: string): void;
16
+ move(el: Element | null, opts?: { click?: boolean }): void;
17
+ pulse(el: Element | null): void;
18
+ off(): void;
19
+ isOn(): boolean;
20
+ }
21
+
22
+ /** The one traveling lamp. `passthrough` cuts a click-through hole at the lit target (CRUMB). */
23
+ export function createSpotlight(opts?: { onInterrupt?: () => void; passthrough?: boolean }): Spotlight;
@@ -0,0 +1,139 @@
1
+ // grain/scripts/ai-spotlight.js — GRAIN's reusable "AI is acting" spotlight: THE TRAVELING LAMP.
2
+ // One fixed-position frame (.ai-lamp) whose rect GLIDES between surfaces — the dim is the lamp's
3
+ // own cutout shadow, so hole and veil move together (styled by grain/ai/ai.css; the glide speed
4
+ // is the --ai-focus-move / --ai-focus-ease tokens). The lit element is never restyled: a rect is
5
+ // a rect, so every surface kind gets the same treatment by construction. Both the real dispatcher
6
+ // and client-side demos drive this ONE factory (AI-INTERFACE §5c) — never re-implement it.
7
+ // Native ES module, no build. Reduced-motion is handled by ai.css (the glide transition is off).
8
+ //
9
+ // PASSTHROUGH MODE (added for CRUMB, the guided-tour layer). Normally the backdrop is a solid
10
+ // click-catcher: any click while the lamp is on → `onInterrupt` (the "ask the AI to stop"
11
+ // gesture). A guided TOUR needs the opposite for the LIT target — the human must be able to
12
+ // click the highlighted surface to inspect/verify it. Passthrough cuts a hole in the backdrop's
13
+ // click-catch area AT THE LAMP'S GEOMETRY (never per-surface — grain lesson 8), so the pointer
14
+ // falls straight through to the target while everything else still blocks (guarding the tour
15
+ // from stray page clicks). The visual is untouched: the dim is the LAMP's own cutout shadow
16
+ // (a separate, pointer-events:none element), so cutting the transparent backdrop changes only
17
+ // what's clickable, never what's lit.
18
+
19
+ // The backdrop is a full-viewport fixed element; to make ONE rectangular region click-through
20
+ // we clip it to "everything except that rect" via a polygon with a slit bridging out to the
21
+ // hole and back (the standard overlay-hole technique). Pure geometry → unit-testable without a
22
+ // browser (grain tests DOM behavior with structural fakes; lesson 9: test the motion, not
23
+ // presence). `hole` is the lamp's client rect {left,top,width,height}; returns a clip-path
24
+ // string, or "" for no hole (full-cover backdrop).
25
+ export function backdropClip(hole) {
26
+ if (!hole) return "";
27
+ const { left: x, top: y, width: w, height: h } = hole;
28
+ return `polygon(0px 0px, 100% 0px, 100% 100%, 0px 100%, 0px 0px, ` +
29
+ `${x}px ${y}px, ${x}px ${y + h}px, ${x + w}px ${y + h}px, ${x + w}px ${y}px, ${x}px ${y}px)`;
30
+ }
31
+
32
+ export function createSpotlight({ onInterrupt, passthrough = false } = {}) {
33
+ let backdrop = null, lamp = null, labelEl = null, lit = null;
34
+ const PAD = 6; // breathing room between the surface and the lamp's frame
35
+
36
+ function ensure() {
37
+ if (backdrop) return;
38
+ backdrop = document.createElement("div"); // invisible click-catcher: the interrupt gesture
39
+ backdrop.className = "ai-backdrop";
40
+ if (onInterrupt) backdrop.addEventListener("click", onInterrupt);
41
+ // The backdrop catches CLICKS (the interrupt gesture) but must NOT lock scrolling — the user
42
+ // still wants to read/adjust the page while the AI works. Forward wheel + touch drags to the
43
+ // page's own scroll region (the app-shell's main pane, else the document). A tap still fires
44
+ // `click` → interrupt; a wheel or drag just scrolls (owner 2026-07-17).
45
+ const scrollRegion = () => document.querySelector(".app-shell__main") || document.scrollingElement || document.documentElement;
46
+ backdrop.addEventListener("wheel", (e) => { scrollRegion().scrollTop += e.deltaY; e.preventDefault(); }, { passive: false });
47
+ let touchY = null;
48
+ backdrop.addEventListener("touchstart", (e) => { touchY = e.touches[0] ? e.touches[0].clientY : null; }, { passive: true });
49
+ backdrop.addEventListener("touchmove", (e) => {
50
+ if (touchY == null || !e.touches[0]) return;
51
+ const y = e.touches[0].clientY;
52
+ scrollRegion().scrollTop += touchY - y; touchY = y; e.preventDefault();
53
+ }, { passive: false });
54
+ document.body.appendChild(backdrop);
55
+ lamp = document.createElement("div"); // the one traveling frame (+ its shadow = the dim)
56
+ lamp.className = "ai-lamp";
57
+ document.body.appendChild(lamp);
58
+ labelEl = document.createElement("div");
59
+ labelEl.className = "ai-acting-label";
60
+ document.body.appendChild(labelEl);
61
+ // the lamp FOLLOWS its surface through scroll/resize (it is position:fixed, the page isn't).
62
+ // While the page scrolls, the long focus-glide would FIGHT the scroll (every scroll frame
63
+ // re-targets the transition → visible stutter), so following swaps to a short linear chase
64
+ // and the glide is restored once the scroll settles.
65
+ let followTimer = null;
66
+ const follow = () => {
67
+ if (!(lit && lamp.classList.contains("is-on"))) return;
68
+ lamp.style.transitionDuration = "0.12s"; lamp.style.transitionTimingFunction = "linear";
69
+ place(lit);
70
+ clearTimeout(followTimer);
71
+ followTimer = setTimeout(() => { lamp.style.transitionDuration = ""; lamp.style.transitionTimingFunction = ""; }, 140);
72
+ };
73
+ addEventListener("scroll", follow, { capture: true, passive: true });
74
+ addEventListener("resize", follow, { passive: true });
75
+ }
76
+
77
+ // A form control's lit surface is its whole labeled FIELD (grain lesson 8, designed out here:
78
+ // the rule lives in WHERE the lamp points, not in per-kind CSS).
79
+ const frameTarget = (el) => el.closest?.(".field") || el;
80
+
81
+ function place(el) {
82
+ const r = frameTarget(el).getBoundingClientRect();
83
+ // travel via transform (composited — stays smooth even while the page lays out under it)
84
+ lamp.style.transform = `translate3d(${r.left - PAD}px, ${r.top - PAD}px, 0)`;
85
+ lamp.style.width = `${r.width + PAD * 2}px`;
86
+ lamp.style.height = `${r.height + PAD * 2}px`;
87
+ // passthrough: the backdrop's click-catch hole tracks the lamp (same rect), so the lit
88
+ // target stays clickable as it glides. The hole rides `follow` too — it never lags a scroll.
89
+ if (passthrough) backdrop.style.clipPath = backdropClip(
90
+ { left: r.left - PAD, top: r.top - PAD, width: r.width + PAD * 2, height: r.height + PAD * 2 });
91
+ }
92
+
93
+ return {
94
+ // raise the veil; `text` names what the AI is doing (empty → no label)
95
+ on(text) {
96
+ ensure();
97
+ labelEl.textContent = text || "";
98
+ labelEl.hidden = !text;
99
+ if (!lit) {
100
+ // no surface yet: the lamp wakes as a closed iris and the first move blooms it open.
101
+ // A page may declare WHERE the light lives ([data-lamp-origin] — e.g. a drawn
102
+ // lamp's head): the iris then opens from that spot, so the object and the light read
103
+ // as one thing. Default: viewport center.
104
+ const origin = document.querySelector("[data-lamp-origin]");
105
+ let ox = innerWidth / 2, oy = innerHeight / 2;
106
+ if (origin) { const r = origin.getBoundingClientRect(); ox = r.left + r.width / 2; oy = r.top + r.height / 2; }
107
+ lamp.style.transitionProperty = "opacity"; // wake AT the origin — never glide there
108
+ lamp.style.transform = `translate3d(${ox}px, ${oy}px, 0)`;
109
+ lamp.style.width = "0px"; lamp.style.height = "0px";
110
+ void lamp.offsetWidth; // commit the position before restoring the glide
111
+ lamp.style.transitionProperty = "";
112
+ }
113
+ void lamp.offsetWidth; // reflow so the opacity fade runs
114
+ backdrop.classList.add("is-on");
115
+ lamp.classList.add("is-on");
116
+ },
117
+ // glide the lamp onto ONE surface (off the previous one); click = pulse it
118
+ move(el, { click = false } = {}) {
119
+ ensure();
120
+ if (lit && lit !== el) lit.classList.remove("ai-spotlit", "is-click");
121
+ lit = el || null;
122
+ if (el) {
123
+ el.classList.add("ai-spotlit"); // semantic marker only — the visual is the lamp
124
+ place(el);
125
+ if (click) this.pulse(el);
126
+ }
127
+ },
128
+ // a click ripple; remove→reflow→add restarts the animation if the same element is re-pulsed
129
+ pulse(el) { if (!el) return; el.classList.remove("is-click"); void el.offsetWidth; el.classList.add("is-click"); setTimeout(() => el.classList.remove("is-click"), 500); },
130
+ // drop the veil and release the lit surface (the lamp fades out in place)
131
+ off() {
132
+ if (backdrop) { backdrop.classList.remove("is-on"); backdrop.style.clipPath = ""; }
133
+ if (lamp) lamp.classList.remove("is-on");
134
+ if (labelEl) labelEl.hidden = true;
135
+ if (lit) { lit.classList.remove("ai-spotlit", "is-click"); lit = null; }
136
+ },
137
+ isOn() { return !!backdrop && backdrop.classList.contains("is-on"); },
138
+ };
139
+ }
@@ -0,0 +1,31 @@
1
+ // grain/scripts/ai-spotlight.test.ts — UNIT: the traveling lamp's PASSTHROUGH geometry.
2
+ // The lamp's DOM motion is covered by the consumer e2e (a real browser); here we pin the pure
3
+ // geometry the passthrough hole is built from — lesson 9: a knob (passthrough) must be
4
+ // MECHANICALLY CONSUMED. `backdropClip` is the mechanism that turns the lamp's rect into a
5
+ // click-through hole in the backdrop; if it stops emitting the hole coords, passthrough is a
6
+ // disconnected knob and the tour can't click its target. So we assert the hole is really cut.
7
+ import { test, expect } from "bun:test";
8
+ import { backdropClip } from "./ai-spotlight.js";
9
+
10
+ test("no hole → empty clip (backdrop stays a full click-catcher)", () => {
11
+ expect(backdropClip(null)).toBe("");
12
+ expect(backdropClip(undefined)).toBe("");
13
+ });
14
+
15
+ test("a hole rect is cut into the backdrop as a slit polygon (all four inner corners present)", () => {
16
+ const clip = backdropClip({ left: 100, top: 50, width: 200, height: 80 });
17
+ expect(clip.startsWith("polygon(")).toBe(true);
18
+ // the outer ring reaches the viewport edges…
19
+ expect(clip).toContain("100% 100%");
20
+ // …then bridges in to the exact target rect corners (left/top .. left+width/top+height)
21
+ expect(clip).toContain("100px 50px"); // top-left
22
+ expect(clip).toContain("100px 130px"); // bottom-left (top + height)
23
+ expect(clip).toContain("300px 130px"); // bottom-right (left + width, top + height)
24
+ expect(clip).toContain("300px 50px"); // top-right (left + width)
25
+ });
26
+
27
+ test("the hole tracks the rect — different geometry yields a different clip", () => {
28
+ const a = backdropClip({ left: 0, top: 0, width: 10, height: 10 });
29
+ const b = backdropClip({ left: 40, top: 40, width: 10, height: 10 });
30
+ expect(a).not.toBe(b);
31
+ });
@@ -0,0 +1,156 @@
1
+ // grain/scripts/catalog-peek.js — the sidebar-panel's CATALOG pane. Its BASE job runs on ANY page
2
+ // that has the pane: embed /catalog in the pane's <iframe> the first time it's shown, so "Catalog"
3
+ // is always a real, working reference browser — never an empty pane. Its ENHANCED job (this file's
4
+ // original scope) is grain's OWN reference app: bridging usage → specimen, where hovering a
5
+ // component in the demo REVEALS that component's entry in the embedded catalog (one at a time,
6
+ // cross-fading — no scrolling). That bridge needs a demo root ([data-peek-root]) to hover WITHIN,
7
+ // which only grain's own pages declare — everywhere else it's simply not there, and this file
8
+ // degrades to the base job with no crash and no empty pane. The pane itself is a sidebar-panel MODE
9
+ // (shell.js owns the Chat⇄Catalog switch); this island adds the catalog behaviours: [data-peek]
10
+ // open/close hooks, the lazy iframe load (base, unconditional), and the hover/tap bridge (enhanced,
11
+ // gated on the demo root existing).
12
+ //
13
+ // It maps each rendered CSS class to its catalog section slug (the .md title slug — stable for
14
+ // grain's components). The catalog exposes a "single" mode (data-peek-single + .is-peek-active,
15
+ // driven here via window.__catSetActive). The bridge adapts to the pointer: with a HOVERING
16
+ // pointer it's a hover-reveal in single mode (one entry at a time, cross-fading). On a COARSE
17
+ // pointer (touch, no hover) a finger can't hover, so the same usage→specimen link becomes a TAP:
18
+ // tapping a component opens the pane and scrolls that entry into view in the full, scrollable
19
+ // catalog (single mode stays off — a finger needs the surrounding list to scroll back through).
20
+ (() => {
21
+ "use strict";
22
+ const shell = document.querySelector(".app-shell");
23
+ const pane = document.querySelector('.assistant__pane[data-pane="catalog"]');
24
+ const frame = pane && pane.querySelector("iframe");
25
+ // BASE requirement: the pane + its iframe. Without these there's nothing to embed the catalog
26
+ // into at all, so there's genuinely nothing this island can do.
27
+ if (!shell || !pane || !frame) return;
28
+ // ENHANCED requirement, OPTIONAL: the demo root the hover/tap bridge reveals FROM. Every branch
29
+ // below that touches `demo` is gated on this — every page without one still gets a fully working
30
+ // catalog pane (this was previously an all-or-nothing early return that left non-grain pages with
31
+ // a permanently empty pane).
32
+ const demo = document.querySelector("[data-peek-root]");
33
+ // the hover-to-reveal mechanic only makes sense with a hovering pointer (desktop mouse) —
34
+ // on touch it would be undrivable, so there we leave the full scrollable catalog.
35
+ const canHover = matchMedia("(hover: hover) and (pointer: fine)").matches;
36
+
37
+ // rendered CSS class → catalog slug. A hand-maintained BRIDGE (the rendered class often differs
38
+ // from the slug: "icon-btn" → "icon-button", "field" → "input"), so keep it in sync when a
39
+ // component's class or title changes. A drift test (catalog-peek.test.ts) fails if a slug here
40
+ // stops matching a real component. Innermost match wins (hover the glyph → Icon; the row → Nav item).
41
+ const MAP = {
42
+ "action-badge": "action-badge", "icon-btn": "icon-button", "nav-item": "nav-item",
43
+ "tab-bar": "tab-bar", "side-rail": "side-rail", "app-shell": "app-shell",
44
+ "chat-message": "chat-message", "field": "input", "badge": "badge",
45
+ "kbd": "keyboard-hint", "list": "list", "tab": "tab", "btn": "button",
46
+ "icon": "icon", "t": "typography",
47
+ };
48
+
49
+ const isOpen = () => !pane.hidden;
50
+ // open/close = switch the sidebar-panel's mode — REUSE the shell's one mechanic (click its mode
51
+ // tab; shell.js flips data-mode/hidden/aria-selected), never a parallel show/hide path. On the
52
+ // mobile sheet, opening also raises the sheet so the switch is visible.
53
+ const modeTab = (m) => shell.querySelector(`.assistant__modes [data-shell-mode="${m}"]`);
54
+ const setOpen = (v) => {
55
+ modeTab(v ? "catalog" : "chat")?.click();
56
+ if (v && matchMedia("(max-width: 768px)").matches) shell.setAttribute("data-aside-open", "");
57
+ };
58
+ // [data-peek] hooks: "open" forces open, "close" forces closed, "toggle" (default) flips.
59
+ // preventDefault so a hook can be a real <a> (the Catalog tab is href="/grain" for no-JS nav /
60
+ // for pages without the pane, e.g. /loop) yet switch the panel in place where this island runs.
61
+ for (const t of document.querySelectorAll("[data-peek]")) {
62
+ const mode = t.getAttribute("data-peek");
63
+ t.addEventListener("click", (e) => { e.preventDefault(); setOpen(mode === "open" ? true : mode === "close" ? false : !isOpen()); });
64
+ }
65
+
66
+ // lazy-load /catalog the first time the pane becomes visible — whichever way it opened (a
67
+ // [data-peek] hook or the panel's own Catalog mode tab).
68
+ const ensureSrc = () => { if (isOpen() && !frame.getAttribute("src")) frame.setAttribute("src", "/catalog"); };
69
+ new MutationObserver(ensureSrc).observe(pane, { attributes: true, attributeFilter: ["hidden"] });
70
+ ensureSrc();
71
+
72
+ // once the embedded catalog loads, put it in "single" mode (show one entry at a time) and
73
+ // default to the first entry so the pane isn't blank before the first hover. Pointer-only:
74
+ // on touch we skip single mode and leave the full scrollable catalog.
75
+ frame.addEventListener("load", () => {
76
+ // touch: no single mode — honour a tap that fired before the frame finished loading.
77
+ if (!canHover) { if (pendingTouch) { scrollToInFrame(pendingTouch); pendingTouch = null; } return; }
78
+ try {
79
+ const doc = frame.contentDocument;
80
+ const cat = doc && doc.querySelector(".cat");
81
+ if (!cat) return;
82
+ cat.setAttribute("data-peek-single", "");
83
+ // honour a hover that happened before load finished, else default to the first entry
84
+ if (last && doc.getElementById(last)) showInFrame(last);
85
+ else if (!doc.querySelector(".cat-doc.is-peek-active")) doc.querySelector(".cat-doc")?.classList.add("is-peek-active");
86
+ } catch { /* cross-origin / not ready — ignore */ }
87
+ });
88
+
89
+ let last = null, showTimer = 0, pendingTouch = null;
90
+ // Reveal one entry (cross-fading), debounced so sweeping the pointer doesn't strobe the fade.
91
+ function showInFrame(slug) {
92
+ clearTimeout(showTimer);
93
+ showTimer = setTimeout(() => {
94
+ try {
95
+ const win = frame.contentWindow, doc = frame.contentDocument;
96
+ if (win && typeof win.__catSetActive === "function") { win.__catSetActive(slug); return; }
97
+ // fallback before the catalog's own script has attached
98
+ const target = doc && doc.getElementById(slug);
99
+ if (target && !target.classList.contains("is-peek-active")) {
100
+ doc.querySelectorAll(".cat-doc.is-peek-active").forEach((d) => d.classList.remove("is-peek-active"));
101
+ target.classList.add("is-peek-active");
102
+ }
103
+ } catch { /* iframe not ready / cross-origin — ignore */ }
104
+ }, 70);
105
+ }
106
+
107
+ function peek(slug) {
108
+ if (slug === last) return;
109
+ last = slug;
110
+ pane.setAttribute("data-peek-slug", slug); // observable state (e2e + reference)
111
+ showInFrame(slug); // reveal-one: the pane shows just this entry, cross-fading — no scrolling
112
+ }
113
+
114
+ // Everything below is the ENHANCED hover/tap bridge — a PROGRESSIVE ENHANCEMENT gated on `demo`
115
+ // existing. A page with no [data-peek-root] (every non-grain consumer) still got a fully working
116
+ // catalog pane above; it just has nothing to hover/tap INTO the pane from, which is correct — it
117
+ // has no grain component demo on the page to bridge from in the first place.
118
+ if (demo) demo.addEventListener("mouseover", (e) => {
119
+ if (!canHover || !isOpen()) return;
120
+ let el = e.target;
121
+ while (el && el !== demo) {
122
+ if (el.classList) for (const cls in MAP) if (el.classList.contains(cls)) { peek(MAP[cls]); return; }
123
+ el = el.parentElement;
124
+ }
125
+ // No component under the pointer → HOLD the current reveal (don't switch on prose/gaps). This
126
+ // lets you move the pointer across the page to the sidebar and scroll the revealed entry
127
+ // without it changing out from under you.
128
+ });
129
+
130
+ // TOUCH bridge (coarse pointer / no hover): scroll a component's entry into view in the full
131
+ // catalog — the reveal a mouse gets for free by hovering, driven by a finger.
132
+ function scrollToInFrame(slug) {
133
+ try {
134
+ const el = frame.contentDocument?.getElementById(slug);
135
+ if (!el) return;
136
+ const smooth = !matchMedia("(prefers-reduced-motion: reduce)").matches;
137
+ el.scrollIntoView({ block: "start", behavior: smooth ? "smooth" : "auto" });
138
+ } catch { /* iframe not ready / cross-origin — ignore */ }
139
+ }
140
+ // A TAP on a catalogued component opens the Catalog pane (raises the sheet on mobile) and brings
141
+ // that entry into view. Only fires on touch; leaves operable controls alone so a real press isn't
142
+ // swallowed (links/buttons/inputs, and the door clients [data-action] / peek hooks [data-peek]).
143
+ if (demo && !canHover) demo.addEventListener("click", (e) => {
144
+ if (e.target.closest("a,button,input,textarea,select,label,[data-action],[data-peek]")) return;
145
+ let el = e.target, slug = null;
146
+ while (el && el !== demo && !slug) {
147
+ if (el.classList) for (const cls in MAP) if (el.classList.contains(cls)) { slug = MAP[cls]; break; }
148
+ el = el.parentElement;
149
+ }
150
+ if (!slug) return;
151
+ pendingTouch = slug;
152
+ pane.setAttribute("data-peek-slug", slug); // observable state (e2e + reference), as on hover
153
+ setOpen(true); // open + raise the Catalog sheet
154
+ if (frame.getAttribute("src")) { scrollToInFrame(slug); pendingTouch = null; } // loaded → now; else on load
155
+ });
156
+ })();
@@ -0,0 +1,31 @@
1
+ // grain/scripts/catalog-peek.test.ts — the peek island bridges a rendered CSS class → a catalog
2
+ // slug via a hand-maintained MAP. If a component's title (and thus its slug) drifts, the MAP
3
+ // silently stops revealing that component on hover. This guards the slug side: every slug the MAP
4
+ // targets must be a real grain component slug.
5
+ import { test, expect } from "bun:test";
6
+ import { readdirSync, readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+
9
+ const slugify = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
10
+
11
+ function componentSlugs(dir: string, out: Set<string> = new Set<string>()): Set<string> {
12
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
13
+ const full = join(dir, e.name);
14
+ if (e.isDirectory()) componentSlugs(full, out);
15
+ else if (e.name.endsWith(".md") && !e.name.endsWith(".ai.md")) {
16
+ const title = (readFileSync(full, "utf8").match(/^#\s+(.+)$/m) || [])[1];
17
+ if (title) out.add(slugify(title.trim()));
18
+ }
19
+ }
20
+ return out;
21
+ }
22
+
23
+ test("every catalog-peek MAP slug resolves to a real grain component", () => {
24
+ const js = readFileSync(join(import.meta.dir, "catalog-peek.js"), "utf8");
25
+ const mapBody = js.match(/const MAP = \{([\s\S]*?)\};/)?.[1] ?? "";
26
+ const slugs = [...mapBody.matchAll(/:\s*"([^"]+)"/g)].map((m) => m[1]);
27
+ expect(slugs.length).toBeGreaterThan(5); // sanity: the MAP was actually parsed
28
+ const known = componentSlugs(join(import.meta.dir, "..", "components"));
29
+ const orphans = slugs.filter((s) => !known.has(s));
30
+ expect(orphans).toEqual([]);
31
+ });
@@ -0,0 +1,159 @@
1
+ // grain/scripts/cmdk.js — global command palette (Spotlight / Notion ⌘K style).
2
+ //
3
+ // Self-contained: one <script> tag drops it onto any page. A <link> to cmdk.css
4
+ // must precede it. Injects a native <dialog>, binds ⌘K / Ctrl+K, fetches
5
+ // the search index once, filters, and navigates. Monochrome e-ink look via the
6
+ // page's design tokens. Today it indexes pages + components; live sources plug in
7
+ // through window.cmdk.register (the seam below made real): a provider is a sync
8
+ // (query) => item[] the host app registers, its items pre-filtered by the app,
9
+ // and an item may carry an action() instead of a url — Enter runs it (palette as
10
+ // another action-vocabulary client).
11
+ //
12
+ // Host config (optional, via <html data-*>; defaults keep old pages working):
13
+ // data-cmdk-src URL of the static index (default "/search.json"; set EMPTY
14
+ // to skip the fetch entirely — provider-only palettes, or
15
+ // project pages served under a subpath where "/" is wrong)
16
+ // data-cmdk-sprite base path of the icon sprite (default "/assets/sprite.svg")
17
+ (() => {
18
+ "use strict";
19
+ let data = null, items = [], sel = 0, root, input, list;
20
+ const providers = [];
21
+ const CFG = document.documentElement.dataset;
22
+ const SRC = CFG.cmdkSrc !== undefined ? CFG.cmdkSrc : "/search.json";
23
+ const SPRITE = CFG.cmdkSprite || "/assets/sprite.svg";
24
+
25
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
26
+ const isOpen = () => !!(root && root.open);
27
+
28
+ function build() {
29
+ // native modal <dialog>: focus-trap + focus-restore + Escape + ::backdrop + top-layer
30
+ // for free — no backdrop div, no manual Escape handling, no z-index races.
31
+ root = document.createElement("dialog");
32
+ root.className = "cmdk";
33
+ root.setAttribute("aria-label", "Search");
34
+ root.innerHTML = `
35
+ <div class="cmdk__row">
36
+ <svg class="icon cmdk__icon" aria-hidden="true"><use href="${SPRITE}#search"></use></svg>
37
+ <input class="cmdk__input" type="text" placeholder="Search pages and components…" aria-label="Search">
38
+ </div>
39
+ <ul class="cmdk__list" role="listbox"></ul>
40
+ <div class="cmdk__hint">↑↓ navigate · ↵ open · esc close</div>`;
41
+ document.body.appendChild(root);
42
+ input = root.querySelector(".cmdk__input");
43
+ list = root.querySelector(".cmdk__list");
44
+ root.addEventListener("click", (e) => { if (e.target === root) close(); }); // light-dismiss: click the backdrop
45
+ input.addEventListener("input", render);
46
+ input.addEventListener("keydown", onKey);
47
+ list.addEventListener("click", (e) => { const li = e.target.closest(".cmdk__item"); if (li) { sel = +li.dataset.i; activate(); } });
48
+ list.addEventListener("mousemove", (e) => { const li = e.target.closest(".cmdk__item"); if (li && +li.dataset.i !== sel) { sel = +li.dataset.i; paint(); } });
49
+ }
50
+
51
+ async function load() {
52
+ if (data) return;
53
+ if (!SRC) { data = { pages: [], components: [] }; return; } // provider-only palette
54
+ try { data = await (await fetch(SRC)).json(); }
55
+ catch { data = { pages: [], components: [] }; }
56
+ }
57
+
58
+ const corpus = () => [
59
+ ...(data.pages || []).map((p) => ({ ...p, kind: "Page" })),
60
+ ...(data.components || []).map((c) => ({ ...c, kind: "Component" })),
61
+ ];
62
+
63
+ // Registered live sources (the seam, made real): each provider returns its own
64
+ // already-filtered items for the query. A throwing provider yields nothing —
65
+ // the palette never breaks on a bad source.
66
+ const fromProviders = (q) => providers.flatMap((p) => { try { return p(q) || []; } catch { return []; } });
67
+
68
+ function paint() {
69
+ [...list.children].forEach((el, i) => el.classList && el.classList.toggle("is-sel", i === sel));
70
+ if (list.children[sel]) list.children[sel].scrollIntoView({ block: "nearest" });
71
+ }
72
+
73
+ function render() {
74
+ const q = input.value.trim().toLowerCase();
75
+ // match on the URL too — Quick Open by path ("notes/ten", "grain/docs") like an editor's ⌘P
76
+ items = [
77
+ ...fromProviders(q),
78
+ ...corpus().filter((e) => !q || (e.title + " " + (e.subtitle || "") + " " + (e.url || "")).toLowerCase().includes(q)),
79
+ ].slice(0, 30);
80
+ sel = 0;
81
+ list.innerHTML = items.length
82
+ ? items.map((e, i) => `<li class="cmdk__item${i === 0 ? " is-sel" : ""}" role="option" data-i="${i}">
83
+ <span class="cmdk__title">${esc(e.title)}</span>
84
+ ${e.subtitle ? `<span class="cmdk__sub">${esc(e.subtitle)}</span>` : ""}
85
+ <span class="cmdk__kind">${esc(e.kind)}</span></li>`).join("")
86
+ : `<li class="cmdk__empty">No matches</li>`;
87
+ }
88
+
89
+ function move(d) { if (!items.length) return; sel = (sel + d + items.length) % items.length; paint(); }
90
+ function activate() {
91
+ const e = items[sel];
92
+ if (!e) return;
93
+ if (e.action) { close(); e.action(); } // command entry: run it (door stays the app's)
94
+ else if (e.url) location.assign(e.url);
95
+ }
96
+
97
+ function onKey(ev) {
98
+ if (ev.key === "ArrowDown") { ev.preventDefault(); move(1); }
99
+ else if (ev.key === "ArrowUp") { ev.preventDefault(); move(-1); }
100
+ else if (ev.key === "Enter") { ev.preventDefault(); activate(); }
101
+ // Escape is handled natively by <dialog> (cancel → close)
102
+ }
103
+
104
+ // Anchor the palette directly beneath the title bar's search field (measured, not guessed —
105
+ // grain/CLAUDE.md lesson 9: a positioning token must be mechanically consumed). Falls back to
106
+ // the CSS-only centered position (cmdk.css defaults) if no field is on the page.
107
+ function reposition() {
108
+ const anchor = document.querySelector(".window-bar__search");
109
+ if (!anchor || anchor.offsetParent === null) { root.classList.remove("cmdk--anchored"); return; }
110
+ const r = anchor.getBoundingClientRect();
111
+ const vw = document.documentElement.clientWidth;
112
+ const MARGIN = 8;
113
+ // Narrow viewport: a full-width sheet dropping from just under the field. A
114
+ // compact trigger button must not squeeze the palette to its own width.
115
+ if (vw <= 768) {
116
+ root.style.setProperty("--cmdk-top", `${r.bottom + 4}px`);
117
+ root.style.setProperty("--cmdk-left", `${MARGIN}px`);
118
+ root.style.setProperty("--cmdk-width", `${vw - MARGIN * 2}px`);
119
+ root.classList.add("cmdk--anchored");
120
+ return;
121
+ }
122
+ // Wide: at least 24rem, and never narrower than the trigger. When the clamp
123
+ // makes it wider than the trigger, grow LEFTWARD so the right edges align
124
+ // (the search field sits at the top-right), then clamp to the viewport so it
125
+ // can never overflow the right edge.
126
+ const minW = 24 * 16;
127
+ const w = Math.min(vw - MARGIN * 2, Math.max(r.width, minW));
128
+ let left = w > r.width ? r.right - w : r.left;
129
+ left = Math.max(MARGIN, Math.min(left, vw - MARGIN - w));
130
+ root.style.setProperty("--cmdk-top", `${r.bottom + 4}px`);
131
+ root.style.setProperty("--cmdk-left", `${left}px`);
132
+ root.style.setProperty("--cmdk-width", `${w}px`);
133
+ root.classList.add("cmdk--anchored");
134
+ }
135
+
136
+ function open() { root.showModal(); reposition(); input.value = ""; load().then(render); input.focus(); }
137
+ function close() { if (root.open) root.close(); }
138
+
139
+ function init() {
140
+ build();
141
+ document.addEventListener("keydown", (ev) => {
142
+ if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === "k") { ev.preventDefault(); isOpen() ? close() : open(); }
143
+ });
144
+ // declarative trigger: any [data-cmdk-open] element opens the palette (e.g. the title
145
+ // bar's search field — a button drawn as an input)
146
+ document.addEventListener("click", (ev) => {
147
+ if (ev.target.closest && ev.target.closest("[data-cmdk-open]")) { ev.preventDefault(); open(); }
148
+ });
149
+ window.addEventListener("resize", () => { if (isOpen()) reposition(); });
150
+ }
151
+ // Public surface: hosts register live sources and can drive the palette.
152
+ window.cmdk = {
153
+ register(provider) { if (typeof provider === "function") providers.push(provider); },
154
+ open: () => open(),
155
+ close: () => close(),
156
+ };
157
+
158
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
159
+ })();