@tjakoen/grain 0.1.12 → 0.1.14

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.
@@ -0,0 +1,113 @@
1
+ // grain/scripts/drawer.js — the drawer organism's behavior: open, close, and the modal
2
+ // obligations that come with covering the page.
3
+ //
4
+ // A drawer is a MODAL overlay, and the three things that make one usable are the three every
5
+ // hand-rolled implementation skips: focus goes INTO it on open, Tab stays inside while it's up,
6
+ // and focus comes BACK to the control that opened it on close. Ship those here so no consumer has
7
+ // to remember them — the drawer that scrolls a form under a scrim while the page behind it still
8
+ // takes Tab is the failure mode this file exists to prevent.
9
+ //
10
+ // The visible state is the plain `hidden` attribute, so a server can render an open drawer and a
11
+ // page with no JS renders a closed one (never an overlay stranded across the screen). Delegated
12
+ // off document, so markup swapped in later — a fragment loaded into the body, a re-rendered
13
+ // list — is wired with no re-init. Pure UI chrome: it knows nothing about the AI door.
14
+ //
15
+ // OPT-IN markup:
16
+ // <button data-drawer-open="my-drawer">New</button> // value = the drawer's id
17
+ // <aside class="drawer" id="my-drawer" data-drawer hidden>
18
+ // <div class="drawer__backdrop" data-drawer-close></div>
19
+ // <div class="drawer__panel" role="dialog" aria-modal="true" aria-labelledby="my-drawer-t">
20
+ // <header class="drawer__head"><h2 id="my-drawer-t">New</h2>
21
+ // <button class="icon-btn" data-drawer-close aria-label="Close">✕</button></header>
22
+ // <div class="drawer__body">…</div>
23
+ // </div>
24
+ // </aside>
25
+ // A `data-drawer-open` with no value opens the page's only `[data-drawer]`.
26
+ (() => {
27
+ "use strict";
28
+ if (window.grain && window.grain.drawer) return; // idempotent
29
+
30
+ // what can hold focus inside the panel — the Tab cycle's endpoints come from this list
31
+ const FOCUSABLE = [
32
+ "a[href]", "button:not([disabled])", "input:not([disabled])", "select:not([disabled])",
33
+ "textarea:not([disabled])", "[tabindex]:not([tabindex='-1'])",
34
+ ].join(",");
35
+
36
+ let openEl = null; // the drawer currently up (only ever one)
37
+ let opener = null; // the control that opened it, to hand focus back to
38
+ let inerted = []; // the body children we made inert, to undo exactly
39
+
40
+ const panelOf = (d) => d.querySelector(".drawer__panel") || d;
41
+ const focusables = (d) => [...panelOf(d).querySelectorAll(FOCUSABLE)]
42
+ .filter((el) => el.offsetParent !== null || el === document.activeElement);
43
+
44
+ const find = (id) => (id ? document.getElementById(id) : document.querySelector("[data-drawer]"));
45
+
46
+ function open(target, from) {
47
+ const d = typeof target === "string" ? find(target) : target;
48
+ if (!d || d === openEl) return null;
49
+ if (openEl) close(); // never stack drawers
50
+ openEl = d;
51
+ opener = from || (document.activeElement instanceof HTMLElement ? document.activeElement : null);
52
+ d.removeAttribute("hidden");
53
+
54
+ // everything else on the page stops taking focus, pointer events and AT attention. `inert`
55
+ // is one attribute that does all three — the aria-hidden + tabindex dance it replaces was
56
+ // always partial (it never stopped a click reaching what it hid).
57
+ inerted = [...document.body.children].filter((c) => c !== d && !c.hasAttribute("inert"));
58
+ for (const c of inerted) c.setAttribute("inert", "");
59
+
60
+ // focus the first real control, else the panel itself (a body of prose still needs to
61
+ // receive Escape and be where the screen reader lands).
62
+ const first = focusables(d)[0];
63
+ if (first) first.focus();
64
+ else {
65
+ const p = panelOf(d);
66
+ if (!p.hasAttribute("tabindex")) p.setAttribute("tabindex", "-1");
67
+ p.focus();
68
+ }
69
+ d.dispatchEvent(new CustomEvent("grain:drawer-open", { bubbles: true }));
70
+ return d;
71
+ }
72
+
73
+ function close() {
74
+ const d = openEl;
75
+ if (!d) return null;
76
+ openEl = null;
77
+ d.setAttribute("hidden", "");
78
+ for (const c of inerted) c.removeAttribute("inert");
79
+ inerted = [];
80
+ // hand focus back to whatever opened it — losing it to <body> drops a keyboard user at the
81
+ // top of the page with no idea where they were.
82
+ if (opener && opener.isConnected) opener.focus();
83
+ opener = null;
84
+ d.dispatchEvent(new CustomEvent("grain:drawer-close", { bubbles: true }));
85
+ return d;
86
+ }
87
+
88
+ document.addEventListener("click", (e) => {
89
+ const t = e.target instanceof Element ? e.target : null;
90
+ if (!t) return;
91
+ const closer = t.closest("[data-drawer-close]");
92
+ if (closer) { e.preventDefault(); close(); return; }
93
+ const btn = t.closest("[data-drawer-open]");
94
+ if (btn) { e.preventDefault(); open(btn.getAttribute("data-drawer-open"), btn); }
95
+ });
96
+
97
+ document.addEventListener("keydown", (e) => {
98
+ if (!openEl) return;
99
+ if (e.key === "Escape") { e.preventDefault(); close(); return; }
100
+ if (e.key !== "Tab") return;
101
+ // the trap: wrap at the ends rather than letting Tab walk out behind the scrim. `inert` above
102
+ // already blocks the page, but the browser chrome/address bar is still in the cycle without
103
+ // this, and Shift+Tab off the first control would leave the panel entirely.
104
+ const items = focusables(openEl);
105
+ if (!items.length) { e.preventDefault(); return; }
106
+ const first = items[0], last = items[items.length - 1];
107
+ if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
108
+ else if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
109
+ });
110
+
111
+ window.grain = window.grain || {};
112
+ window.grain.drawer = { open, close, current: () => openEl };
113
+ })();
@@ -0,0 +1,70 @@
1
+ // grain/scripts/drawer.test.ts — DRIFT GUARD for the drawer island.
2
+ //
3
+ // Scope, stated honestly: this package has no DOM in test (zero runtime deps, and a hand-rolled
4
+ // fake would test the fake). So these are grep-style contract guards in the tabs.test.ts mould —
5
+ // they catch a modal obligation being DELETED, which is the realistic regression, not one being
6
+ // subtly wrong. The behavior itself (focus lands in the panel, Tab wraps, focus returns to the
7
+ // opener) is asserted in a browser against a consumer — see plans/0007 in STEWARD. Lesson 9 cuts
8
+ // both ways: don't claim a behavior a mechanism can't render, and don't claim a test proves more
9
+ // than it does.
10
+ import { test, expect } from "bun:test";
11
+ import { readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+
14
+ const js = readFileSync(join(import.meta.dir, "drawer.js"), "utf8");
15
+ const md = readFileSync(join(import.meta.dir, "..", "components/organisms/drawer/drawer.md"), "utf8");
16
+
17
+ test("idempotent, like every grain island", () => {
18
+ expect(js).toMatch(/if \(window\.grain && window\.grain\.drawer\) return/);
19
+ });
20
+
21
+ test("state is the `hidden` attribute, not a class — SSR ships it, no-JS renders it closed", () => {
22
+ expect(js).toMatch(/removeAttribute\("hidden"\)/);
23
+ expect(js).toMatch(/setAttribute\("hidden", ""\)/);
24
+ expect(js).not.toMatch(/classList\.(add|remove)\("(is-)?open"\)/);
25
+ });
26
+
27
+ test("focus moves INTO the panel on open", () => {
28
+ expect(js).toMatch(/focusables\(d\)\[0\]/);
29
+ expect(js).toMatch(/first\.focus\(\)/);
30
+ });
31
+
32
+ test("focus RETURNS to the opener on close — never dropped to <body>", () => {
33
+ expect(js).toMatch(/opener = from \|\| /);
34
+ expect(js).toMatch(/if \(opener && opener\.isConnected\) opener\.focus\(\)/);
35
+ });
36
+
37
+ test("Tab is trapped inside the panel, wrapping at BOTH ends", () => {
38
+ expect(js).toMatch(/e\.key !== "Tab"/);
39
+ expect(js).toMatch(/!e\.shiftKey && document\.activeElement === last/);
40
+ expect(js).toMatch(/e\.shiftKey && document\.activeElement === first/);
41
+ });
42
+
43
+ test("the rest of the page goes inert while open, and is restored exactly", () => {
44
+ expect(js).toMatch(/setAttribute\("inert", ""\)/);
45
+ expect(js).toMatch(/removeAttribute\("inert"\)/);
46
+ // only the children WE inerted are un-inerted — a page that inerts something itself keeps it.
47
+ expect(js).toMatch(/!c\.hasAttribute\("inert"\)/);
48
+ });
49
+
50
+ test("Escape and the scrim both close", () => {
51
+ expect(js).toMatch(/e\.key === "Escape"/);
52
+ expect(js).toMatch(/\[data-drawer-close\]/);
53
+ });
54
+
55
+ test("never stacks: opening a second drawer closes the first", () => {
56
+ expect(js).toMatch(/if \(openEl\) close\(\)/);
57
+ });
58
+
59
+ test("delegated off document, so swapped-in markup needs no re-init", () => {
60
+ expect(js).toMatch(/document\.addEventListener\("click"/);
61
+ expect(js).toMatch(/document\.addEventListener\("keydown"/);
62
+ });
63
+
64
+ test("exposes the window.grain.drawer seam and the open/close events the .md promises", () => {
65
+ expect(js).toMatch(/window\.grain\.drawer\s*=\s*\{[\s\S]*\bopen\b[\s\S]*\bclose\b/);
66
+ expect(js).toMatch(/grain:drawer-open/);
67
+ expect(js).toMatch(/grain:drawer-close/);
68
+ expect(md).toMatch(/grain:drawer-open/);
69
+ expect(md).toMatch(/window\.grain\.drawer/);
70
+ });
@@ -0,0 +1,315 @@
1
+ // grain/scripts/presentation.js: the PRESENTATION island, the behaviour half of the
2
+ // organisms/presentation surface.
3
+ //
4
+ // It owns the deck and nothing else: which slide is current, which fragments have landed, the
5
+ // fit-to-box pass, the dot matrix, the overview grid, present mode, the notes strip, the presenter
6
+ // window, and print. It knows nothing about any particular talk.
7
+ //
8
+ // THE SEAM. A consuming app hooks its own per-slide behaviour by listening on the deck element:
9
+ //
10
+ // deck.addEventListener("presentation:slide", (e) => {
11
+ // const { index, step, slide, title, entered } = e.detail;
12
+ // });
13
+ //
14
+ // `entered` is true on the first event for a slide (the arrival) and false on later steps within
15
+ // it, so an app can start an animation once and advance figures per step. That is the whole
16
+ // contract: no registry, no per-slide config, no framework.
17
+ //
18
+ // OPT-IN: mark the root `.presentation` with `data-deck`. Zero-JS the markup still renders the
19
+ // first slide (author it with `data-current`), which is what the static export and a print run get.
20
+ (() => {
21
+ "use strict";
22
+ if (window.grain && window.grain.presentation) return; // idempotent, like the other islands
23
+
24
+ const SETTLE_MS = 420; // how long a slide reads as "in transit" before its type commits to clean
25
+
26
+ function init() {
27
+ for (const deck of document.querySelectorAll(".presentation[data-deck]")) mount(deck);
28
+ }
29
+
30
+ function mount(deck) {
31
+ const slides = [...deck.querySelectorAll(".presentation__slide")];
32
+ if (!slides.length) return;
33
+ const dotsEl = deck.querySelector("[data-dots]");
34
+ const posEl = deck.querySelector("[data-pos]");
35
+ const gridEl = deck.querySelector("[data-grid]");
36
+ const stripEl = deck.querySelector("[data-inline-notes]");
37
+ const total = slides.length;
38
+ const channel = "BroadcastChannel" in window
39
+ ? new BroadcastChannel(deck.dataset.channel || "grain.presentation") : null;
40
+ const isPresenter = new URLSearchParams(location.search).get("presenter") === "1";
41
+
42
+ let at = 0, step = 0, settleTimer = null;
43
+
44
+ const frags = (s) => [...s.querySelectorAll(".frag")];
45
+ const steps = (s) => frags(s).length + (Number(s.dataset.steps) || 0);
46
+ const notesOf = (s) => [...(s.querySelector(".slide-notes")?.children || [])].map((li) => li.innerHTML);
47
+
48
+ /* ---- fit: shrink a dense slide until it fits its own box -------------------
49
+ Fragments only change opacity and transform, never layout, so one measurement per slide
50
+ holds for every step. Any [aria-expanded] card is measured OPEN, so clicking one on stage
51
+ can never overflow. */
52
+ slides.forEach((s) => {
53
+ if (s.querySelector(".presentation__body")) return;
54
+ const body = document.createElement("div");
55
+ body.className = "presentation__body";
56
+ [...s.children].forEach((c) => { if (!c.classList.contains("slide-notes")) body.append(c); });
57
+ s.prepend(body);
58
+ });
59
+
60
+ function fit(s) {
61
+ const body = s.querySelector(".presentation__body");
62
+ if (!body) return;
63
+ const shown = s.hasAttribute("data-current");
64
+ if (!shown) { s.style.display = "flex"; s.style.visibility = "hidden"; }
65
+ const collapsed = [...s.querySelectorAll('[aria-expanded="false"]')];
66
+ collapsed.forEach((c) => c.setAttribute("aria-expanded", "true"));
67
+ // measure the WORST case, which is the slide mid-settle: the grain face and its extra
68
+ // letter-spacing are wider than the clean one, so a slide that fits when settled can still
69
+ // overflow on the way in. Measuring settled would ship exactly that silent overflow.
70
+ const wasSettling = s.hasAttribute("data-settling");
71
+ s.setAttribute("data-settling", "");
72
+ s.style.setProperty("--fit", "1");
73
+ const cs = getComputedStyle(s);
74
+ const room = () => s.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom);
75
+ let f = 1;
76
+ while (f > 0.5 && body.scrollHeight > room()) {
77
+ f = Math.round((f - 0.04) * 100) / 100;
78
+ s.style.setProperty("--fit", String(f));
79
+ }
80
+ collapsed.forEach((c) => c.setAttribute("aria-expanded", "false"));
81
+ if (!wasSettling) s.removeAttribute("data-settling");
82
+ if (!shown) { s.style.display = ""; s.style.visibility = ""; }
83
+ }
84
+ const fitAll = () => slides.forEach(fit);
85
+
86
+ /* ---- paint ------------------------------------------------------------- */
87
+ function paint(entered) {
88
+ slides.forEach((s, i) => s.toggleAttribute("data-current", i === at));
89
+ const now = slides[at];
90
+ frags(now).forEach((f, i) => f.classList.toggle("is-on", i < step));
91
+ // a figure draws itself in once its slide has arrived, or once its own fragment lands
92
+ now.querySelectorAll("[data-draw], [data-lit]").forEach((el) => {
93
+ const own = el.closest(".frag");
94
+ el.classList.toggle("is-drawn", !own || own.classList.contains("is-on"));
95
+ });
96
+
97
+ if (entered) {
98
+ now.setAttribute("data-settling", "");
99
+ clearTimeout(settleTimer);
100
+ settleTimer = setTimeout(() => now.removeAttribute("data-settling"), SETTLE_MS);
101
+ }
102
+
103
+ dotsEl?.querySelectorAll(".presentation__dot").forEach((d, i) => {
104
+ d.toggleAttribute("data-seen", i <= at);
105
+ d.toggleAttribute("data-now", i === at);
106
+ });
107
+ gridEl?.querySelectorAll(".presentation__cell").forEach((c, i) => c.toggleAttribute("data-now", i === at));
108
+ if (posEl) posEl.textContent = `${at + 1} / ${total}`;
109
+ if (stripEl) stripEl.innerHTML = `<ul>${notesOf(now).map((n) => `<li>${n}</li>`).join("")}</ul>`;
110
+
111
+ syncControls();
112
+ deck.dispatchEvent(new CustomEvent("presentation:slide", {
113
+ detail: { index: at, step, slide: now, title: now.dataset.title || "", entered, total },
114
+ }));
115
+ channel?.postMessage({ type: "state", at, step });
116
+ if (deck.hasAttribute("data-hash")) history.replaceState(null, "", `#${at + 1}`);
117
+ }
118
+
119
+ function go(i, s = 0) {
120
+ const next = Math.max(0, Math.min(total - 1, i));
121
+ deck.dataset.dir = next < at ? "back" : "fwd";
122
+ const entered = next !== at || !slides[at].hasAttribute("data-current");
123
+ at = next; step = s;
124
+ paint(entered);
125
+ }
126
+ function next() {
127
+ if (step < steps(slides[at])) { step += 1; paint(false); return; }
128
+ if (at < total - 1) go(at + 1, 0);
129
+ }
130
+ function prev() {
131
+ if (step > 0) { step -= 1; paint(false); return; }
132
+ if (at > 0) go(at - 1, steps(slides[at - 1]));
133
+ }
134
+
135
+ /* ---- chrome ------------------------------------------------------------ */
136
+ if (dotsEl) {
137
+ dotsEl.innerHTML = slides.map((s, i) =>
138
+ `<button class="presentation__dot" type="button" data-to="${i}" title="${s.dataset.title || i + 1}">` +
139
+ `<span class="sr-only">${i + 1}</span></button>`).join("");
140
+ }
141
+ if (gridEl) {
142
+ gridEl.innerHTML = slides.map((s, i) =>
143
+ `<button class="presentation__cell" type="button" data-to="${i}">` +
144
+ `<span class="presentation__n">${String(i + 1).padStart(2, "0")}</span>` +
145
+ `<p class="presentation__t">${s.dataset.title || ""}</p></button>`).join("");
146
+ }
147
+ /* the control cluster: the same moves the keys make, for a presenter whose hands are on a
148
+ laptop, a reader at a desk, and a touch screen with no arrow keys at all */
149
+ deck.addEventListener("click", (e) => {
150
+ const to = e.target.closest("[data-to]");
151
+ if (to) { deck.dataset.view = "slides"; go(Number(to.dataset.to), 0); return; }
152
+ const ctl = e.target.closest("[data-ctl]");
153
+ if (ctl) {
154
+ switch (ctl.dataset.ctl) {
155
+ case "prev": prev(); break;
156
+ case "next": next(); break;
157
+ case "notes": deck.toggleAttribute("data-notes"); requestAnimationFrame(fitAll); break;
158
+ case "grid": deck.dataset.view = deck.dataset.view === "grid" ? "slides" : "grid"; break;
159
+ case "presenter": window.open(`${location.pathname}?presenter=1`, "grain-presenter", "width=1100,height=760"); break;
160
+ default: break;
161
+ }
162
+ syncControls();
163
+ return;
164
+ }
165
+ if (e.target.closest("[data-present-toggle]")) togglePresent();
166
+ });
167
+
168
+ function syncControls() {
169
+ const first = at === 0 && step === 0;
170
+ const last = at === total - 1 && step >= steps(slides[at]);
171
+ deck.querySelector('[data-ctl="prev"]')?.toggleAttribute("disabled", first);
172
+ deck.querySelector('[data-ctl="next"]')?.toggleAttribute("disabled", last);
173
+ deck.querySelector('[data-ctl="notes"]')
174
+ ?.setAttribute("aria-pressed", String(deck.hasAttribute("data-notes")));
175
+ deck.querySelector('[data-ctl="grid"]')
176
+ ?.setAttribute("aria-pressed", String(deck.dataset.view === "grid"));
177
+ }
178
+
179
+ /* ---- keys -------------------------------------------------------------- */
180
+ const typing = (e) => /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName) || e.target.isContentEditable;
181
+ addEventListener("keydown", (e) => {
182
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
183
+ // a deck that is not presenting only claims the arrow keys; letters stay the app's
184
+ const owns = deck.hasAttribute("data-present") || deck.contains(document.activeElement) || deck.hasAttribute("data-solo");
185
+ switch (e.key) {
186
+ case "ArrowRight": case "PageDown": case " ":
187
+ if (typing(e)) return;
188
+ e.preventDefault(); next(); break;
189
+ case "ArrowLeft": case "PageUp":
190
+ if (typing(e)) return;
191
+ e.preventDefault(); prev(); break;
192
+ case "ArrowUp": if (typing(e) || cedes(deck, "ArrowUp")) return; e.preventDefault(); go(at - 1, 0); break;
193
+ case "ArrowDown": if (typing(e) || cedes(deck, "ArrowDown")) return; e.preventDefault(); go(at + 1, 0); break;
194
+ case "Home": if (typing(e)) return; e.preventDefault(); go(0, 0); break;
195
+ case "End": if (typing(e)) return; e.preventDefault(); go(total - 1, 0); break;
196
+ case "Escape": deck.dataset.view = "slides"; if (deck.hasAttribute("data-present")) togglePresent(); break;
197
+ default: break;
198
+ }
199
+ if (!owns || typing(e)) return;
200
+ switch (e.key.toLowerCase()) {
201
+ case "o": deck.dataset.view = deck.dataset.view === "grid" ? "slides" : "grid"; break;
202
+ case "n": deck.toggleAttribute("data-notes"); requestAnimationFrame(fitAll); break;
203
+ case "p": window.open(`${location.pathname}?presenter=1`, "grain-presenter", "width=1100,height=760"); break;
204
+ case "f": togglePresent(); break;
205
+ case "d": {
206
+ const root = document.documentElement;
207
+ const dark = root.dataset.colorScheme
208
+ ? root.dataset.colorScheme === "dark"
209
+ : matchMedia("(prefers-color-scheme: dark)").matches;
210
+ root.dataset.colorScheme = dark ? "light" : "dark";
211
+ break;
212
+ }
213
+ case ".": deck.style.visibility = deck.style.visibility === "hidden" ? "" : "hidden"; break;
214
+ default: break;
215
+ }
216
+ });
217
+
218
+ /* An app can claim a key for a slide's own control (the arrows on a guess marker, say) by
219
+ setting data-cede="ArrowUp ArrowDown" on the current slide. The deck yields, nothing more. */
220
+ function cedes(d, key) {
221
+ const s = d.querySelector(".presentation__slide[data-current]");
222
+ return !!s && (s.dataset.cede || "").split(/\s+/).includes(key);
223
+ }
224
+
225
+ function togglePresent() {
226
+ const on = deck.toggleAttribute("data-present");
227
+ if (on) document.documentElement.requestFullscreen?.().catch(() => { /* the deck is still full-bleed */ });
228
+ else if (document.fullscreenElement) document.exitFullscreen();
229
+ requestAnimationFrame(fitAll);
230
+ }
231
+ document.addEventListener("fullscreenchange", () => {
232
+ if (!document.fullscreenElement && deck.hasAttribute("data-present")) {
233
+ deck.removeAttribute("data-present");
234
+ requestAnimationFrame(fitAll);
235
+ }
236
+ });
237
+
238
+ // touch: a swipe is an arrow key
239
+ let x0 = null;
240
+ deck.addEventListener("touchstart", (e) => { x0 = e.changedTouches[0].clientX; }, { passive: true });
241
+ deck.addEventListener("touchend", (e) => {
242
+ if (x0 === null) return;
243
+ const dx = e.changedTouches[0].clientX - x0;
244
+ if (Math.abs(dx) > 45) (dx < 0 ? next : prev)();
245
+ x0 = null;
246
+ }, { passive: true });
247
+
248
+ /* ---- print: land everything first, so Cmd+P is the real deck ----------- */
249
+ addEventListener("beforeprint", () => {
250
+ // print swaps --u's source to viewport units (see the component's @media print block), so
251
+ // the fit pass has to run again under those rules or every slide prints at the screen's --fit
252
+ fitAll();
253
+ slides.forEach((s) => {
254
+ frags(s).forEach((f) => f.classList.add("is-on"));
255
+ s.querySelectorAll("[data-draw], [data-lit]").forEach((el) => el.classList.add("is-drawn"));
256
+ s.removeAttribute("data-settling");
257
+ });
258
+ deck.dispatchEvent(new CustomEvent("presentation:print"));
259
+ });
260
+
261
+ /* ---- the presenter window ---------------------------------------------- */
262
+ if (isPresenter) {
263
+ document.body.dataset.mode = "presenter";
264
+ const p = (sel) => document.querySelector(sel);
265
+ let t0 = Date.now();
266
+ const show = (i) => {
267
+ const s = slides[i];
268
+ if (p("[data-p-pos]")) p("[data-p-pos]").textContent = `${i + 1} / ${total}`;
269
+ if (p("[data-p-title]")) p("[data-p-title]").textContent = s.dataset.title || "";
270
+ if (p("[data-p-notes]")) p("[data-p-notes]").innerHTML = notesOf(s).map((n) => `<li>${n}</li>`).join("");
271
+ if (p("[data-p-next]")) p("[data-p-next]").textContent = slides[i + 1]?.dataset.title || "End of deck";
272
+ };
273
+ channel?.addEventListener("message", (e) => { if (e.data?.type === "state") show(e.data.at); });
274
+ addEventListener("keydown", (e) => {
275
+ if (e.key === "t" || e.key === "T") t0 = Date.now();
276
+ if (["ArrowRight", "ArrowLeft", "ArrowUp", "ArrowDown", " ", "Home", "End"].includes(e.key)) {
277
+ channel?.postMessage({ type: "key", key: e.key });
278
+ }
279
+ });
280
+ setInterval(() => {
281
+ const s = Math.floor((Date.now() - t0) / 1000);
282
+ const el = p("[data-p-clock]");
283
+ if (!el) return;
284
+ el.textContent = `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
285
+ el.toggleAttribute("data-over", s > Number(deck.dataset.minutes || 20) * 60);
286
+ }, 500);
287
+ show(0);
288
+ } else {
289
+ channel?.addEventListener("message", (e) => {
290
+ if (e.data?.type !== "key") return;
291
+ const k = e.data.key;
292
+ if (k === "ArrowRight" || k === " ") next();
293
+ else if (k === "ArrowLeft") prev();
294
+ else if (k === "ArrowUp") go(at - 1, 0);
295
+ else if (k === "ArrowDown") go(at + 1, 0);
296
+ else if (k === "Home") go(0, 0);
297
+ else if (k === "End") go(total - 1, 0);
298
+ });
299
+ }
300
+
301
+ /* ---- boot -------------------------------------------------------------- */
302
+ addEventListener("resize", fitAll);
303
+ if (document.fonts) document.fonts.ready.then(fitAll);
304
+ // the deck may live in a pane that resizes without the window (a rail collapsing, say)
305
+ if ("ResizeObserver" in window) new ResizeObserver(() => fitAll()).observe(deck);
306
+ fitAll();
307
+ const fromHash = Number(location.hash.slice(1));
308
+ go(deck.hasAttribute("data-hash") && Number.isFinite(fromHash) && fromHash >= 1 ? fromHash - 1 : 0, 0);
309
+
310
+ (window.grain ||= {}).presentation = { go, next, prev, fitAll, deck };
311
+ }
312
+
313
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
314
+ else init();
315
+ })();
@@ -0,0 +1,77 @@
1
+ // grain/scripts/presentation.test.ts — DRIFT GUARD for the presentation island.
2
+ //
3
+ // Scope, stated honestly: this package has no DOM in test (zero runtime deps, and a hand-rolled
4
+ // fake would test the fake), so these are grep-style contract guards in the drawer.test.ts mould.
5
+ // They catch an obligation being DELETED, which is the realistic regression. Whether the fit pass
6
+ // actually stops a slide overflowing on a projector is measured in a browser against a consumer,
7
+ // and nothing in this file claims otherwise.
8
+ import { test, expect } from "bun:test";
9
+ import { readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+
12
+ const here = new URL(".", import.meta.url).pathname;
13
+ const js = readFileSync(join(here, "presentation.js"), "utf8");
14
+
15
+ test("mounting is opt-in on [data-deck], so decks in a page don't get claimed by accident", () => {
16
+ expect(js).toMatch(/querySelectorAll\("\.presentation\[data-deck\]"\)/);
17
+ });
18
+
19
+ test("it is idempotent, like the other islands: a second load is a no-op", () => {
20
+ expect(js).toMatch(/if \(window\.grain && window\.grain\.presentation\) return/);
21
+ });
22
+
23
+ test("the seam is one event carrying enough for an app to drive its own figures", () => {
24
+ expect(js).toMatch(/new CustomEvent\("presentation:slide"/);
25
+ for (const key of ["index", "step", "slide", "title", "entered", "total"]) {
26
+ expect(js).toMatch(new RegExp(`\\b${key}\\b`));
27
+ }
28
+ });
29
+
30
+ test("the fit pass measures the WORST case: expandable cards open", () => {
31
+ // clicking a card on stage must never overflow a slide that fit a moment ago
32
+ expect(js).toMatch(/aria-expanded="false"/);
33
+ expect(js).toMatch(/setAttribute\("aria-expanded", "true"\)/);
34
+ });
35
+
36
+ test("the fit pass has a floor, so a runaway slide cannot loop forever", () => {
37
+ expect(js).toMatch(/while \(f > 0\.\d+ && body\.scrollHeight > room\(\)\)/);
38
+ });
39
+
40
+ test("print lands every fragment and figure first, then tells the app to do the same", () => {
41
+ const printBlock = js.slice(js.indexOf('addEventListener("beforeprint"'));
42
+ expect(printBlock).toMatch(/classList\.add\("is-on"\)/);
43
+ expect(printBlock).toMatch(/classList\.add\("is-drawn"\)/);
44
+ expect(printBlock).toMatch(/new CustomEvent\("presentation:print"\)/);
45
+ // print swaps the unit's source, so the fit pass has to run again under those rules
46
+ expect(printBlock).toMatch(/fitAll\(\)/);
47
+ });
48
+
49
+ test("a slide can claim a key back from the deck with data-cede", () => {
50
+ expect(js).toMatch(/dataset\.cede/);
51
+ expect(js).toMatch(/function cedes/);
52
+ });
53
+
54
+ test("the presenter window is the same page, synced, and never shown to the room", () => {
55
+ expect(js).toMatch(/presenter=1/);
56
+ expect(js).toMatch(/BroadcastChannel/);
57
+ expect(js).toMatch(/postMessage\(\{ type: "key"/);
58
+ });
59
+
60
+ test("typing in a field never moves the deck", () => {
61
+ expect(js).toMatch(/INPUT\|TEXTAREA\|SELECT/);
62
+ expect(js).toMatch(/isContentEditable/);
63
+ });
64
+
65
+ test("the fit pass re-runs on resize and on fonts loading, not once at boot", () => {
66
+ expect(js).toMatch(/addEventListener\("resize", fitAll\)/);
67
+ expect(js).toMatch(/document\.fonts.*fitAll/s);
68
+ expect(js).toMatch(/ResizeObserver/);
69
+ });
70
+
71
+ test("the public seam is small and named, and there is no back channel into the deck", () => {
72
+ expect(js).toMatch(/\(window\.grain \|\|= \{\}\)\.presentation = \{ go, next, prev, fitAll, deck \}/);
73
+ });
74
+
75
+ test("no em-dashes, per the standards this package follows", () => {
76
+ expect(js).not.toContain("—");
77
+ });