@justai/cuts 0.133.0 → 0.139.0

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,234 @@
1
+ // queries: posts behaviour · posts script · where did Posts.astro's script go ·
2
+ // testing a component's behaviour · component script is not type checked
3
+ //
4
+ // The posts cut — the feed loader, the language toggle and the in-place original.
5
+ //
6
+ // Lifted out of `Posts.astro`, where it was TypeScript that nothing read: a hoisted Astro script
7
+ // goes to esbuild, which strips annotations WITHOUT checking them, and this package had no tsconfig.
8
+ // Out here a compiler can open it and a test can call it. What stays in the component is the markup
9
+ // and the CSS, which is what a component is.
10
+ // The persona's feed — loaded at RUNTIME from the console (api.justai.pro), lazily (only when the Posts
11
+ // cut nears the viewport, since the page lands on the Kernel). The renderer reproduces the server
12
+ // markup 1:1, so the design is unchanged; new posts appear with no redeploy. Single source: the console.
13
+ (function () {
14
+ const section = document.getElementById("posts");
15
+ const feed = document.getElementById("feed");
16
+ if (!section || !feed) return;
17
+ // the persona identity travels on the section as data-attributes (the static cut set them from props).
18
+ // PERSONA is the KEY (feed query + the "is this reply mine?" test); HANDLE is what is rendered after
19
+ // the @ (they differ for the two apexes: app.zone → @appzone, justai → @justai.pro). NAME is the
20
+ // persona's OWN name and is injected RAW — it is authored in the persona's source, never user input,
21
+ // so it may carry markup (justai's ".pro" span). Every name that comes from the API is escaped.
22
+ const PERSONA = section.dataset.persona || "";
23
+ const NAME = section.dataset.name || "";
24
+ // THE PAGE'S LANGUAGE. `data-lang` is present only when the persona STATED it; otherwise the
25
+ // document's own `lang` is read, which is the one place every persona in this fleet agrees —
26
+ // `Astro.currentLocale` is undefined under `[lang]` routing and cannot be the fallback it looks
27
+ // like. Not localStorage either: on a localized home the language is in the URL, settled before
28
+ // this ran, and a link shared in Turkish must open in Turkish for whoever follows it.
29
+ const LANG = (section.dataset.lang || document.documentElement.lang || "en").toLowerCase().split("-")[0];
30
+ if (!PERSONA) return;
31
+ // Astro scopes this component's CSS by a data-astro-cid-* attribute; runtime nodes lack it, so copy it.
32
+ const scopeAttr = section.getAttributeNames().find((n) => n.startsWith("data-astro-cid-")) || null;
33
+
34
+ // Twitter-style: clicking anywhere on a post (except a real link) opens its feed page.
35
+ // The "show original" link is handled first and swallowed — it is a control, not a destination.
36
+ feed.addEventListener("click", (e) => {
37
+ const t = e.target as HTMLElement;
38
+ const tog = t.closest("[data-toggle-original]") as HTMLElement | null;
39
+ if (tog) {
40
+ const art = tog.closest(".post");
41
+ const body = art?.querySelector(".pbd") as HTMLElement | null;
42
+ const state = art?.querySelector("[data-tstate]") as HTMLElement | null;
43
+ // Only take over the click once everything it needs is in hand. If the markup ever changes
44
+ // shape the link stays a link and still reaches the original — a control that degrades to
45
+ // working beats one that silently does nothing.
46
+ if (!body || !state) return;
47
+ e.preventDefault();
48
+ const showing = tog.textContent === tog.dataset.showTranslation;
49
+ body.textContent = showing ? tog.dataset.translation! : tog.dataset.original!;
50
+ body.setAttribute("lang", (showing ? tog.dataset.lang : tog.dataset.originalLang) || "");
51
+ tog.textContent = showing ? tog.dataset.showOriginal! : tog.dataset.showTranslation!;
52
+ state.textContent = showing ? tog.dataset.translated! : tog.dataset.originalLabel!;
53
+ return;
54
+ }
55
+ if (t.closest("a")) return;
56
+ const art = t.closest(".post[data-href]") as HTMLElement | null;
57
+ if (art?.dataset.href) location.assign(art.dataset.href);
58
+ });
59
+
60
+ const esc = (s: unknown): string =>
61
+ String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] as string);
62
+ // Every persona signs its posts with its own face, /icon.svg by default (each app serves one at its
63
+ // root). The path is a data attribute rather than a literal because a persona may sign with a mark that
64
+ // has no tile — see avatarSrc / avatarBare above. `bare` rides on the IMAGE, not on the container:
65
+ // .rav wraps both a self-reply and ANOTHER persona's reply, so a container rule would strip the tile
66
+ // from siblings who legitimately have one.
67
+ const bare = section.hasAttribute("data-av-bare") ? " bare" : "";
68
+ const avLight = esc(section.dataset.av || "/icon.svg");
69
+ // When a dark twin is declared, BOTH are in the markup and CSS shows one. The alternative — one <img>
70
+ // whose src is chosen in JS off matchMedia — would be a second source of truth for the same decision and
71
+ // would not follow a scheme change without a listener.
72
+ const AV = section.dataset.avDark
73
+ ? `<img class="mk${bare} av-light" src="${avLight}" alt=""><img class="mk${bare} av-dark" src="${esc(section.dataset.avDark)}" alt="">`
74
+ : `<img class="mk${bare}" src="${avLight}" alt="">`;
75
+ const ck = `<svg class="ck" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l2.4 1.8 3 .2.9 2.8 2.3 1.9-1 2.8 1 2.8-2.3 1.9-.9 2.8-3 .2L12 22l-2.4-1.8-3-.2-.9-2.8L3.4 14l1-2.8-1-2.8 2.3-1.9.9-2.8 3-.2z" fill="var(--accent)"/><path d="M9 12.5l2 2 4-4.5" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
76
+ const pact = `<div class="pact"><span><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8.5a5.5 5.5 0 0 0-9-4.2A5.5 5.5 0 0 0 3 8.5c0 5 9 11 9 11s9-6 9-11z"/></svg></span><span><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.4 8.4 0 0 1-9 8.3 9.6 9.6 0 0 1-4-.9L3 21l1.1-5A8.4 8.4 0 1 1 21 11.5z"/></svg></span></div>`;
77
+
78
+ type C = { body: string; createdAt: string | null; authorHandle: string; authorName: string; authorColor: string | null; isPersona: boolean; authorAvatar: string | null; authorGlyph: string | null; personaUrl: string | null };
79
+ // `lang` is what `body` IS; `translated` says a machine made it. Both are optional so this cut
80
+ // still renders against a console that predates them — the fleet installs its packages on its own
81
+ // schedule, and a persona that has not been bumped must not lose its feed.
82
+ type P = { id: string; body: string; lang?: string; originalLang?: string; originalBody?: string | null; translated?: boolean; createdAt: string | null; comments: C[] };
83
+
84
+ // queries: translated automatically · show original · machine translation notice on the home feed
85
+ //
86
+ // THE SAME LINE THE PERMALINK PAGE SHOWS, because they render one conversation and must not
87
+ // disagree about it. The original is canonical, marked, and one tap away — that pairing IS the
88
+ // doctrine (dna/entities/localization.md), not a courtesy.
89
+ //
90
+ // Thirteen strings rather than a lookup through the persona's own dictionary: this cut ships to
91
+ // every persona and cannot reach into any of their locale files. ~400 bytes, said once, for the
92
+ // whole fleet — the alternative is the same sentence copied into thirteen files times thirty
93
+ // repos, which is the shape `tagline.js` already exists to prevent.
94
+ const TRANSLATED: Record<string, string> = {
95
+ en: "Translated automatically", tr: "Otomatik olarak çevrildi", es: "Traducido automáticamente",
96
+ de: "Automatisch übersetzt", fr: "Traduit automatiquement", pt: "Traduzido automaticamente",
97
+ it: "Tradotto automaticamente", nl: "Automatisch vertaald", ru: "Переведено автоматически",
98
+ ja: "自動翻訳", zh: "自动翻译", ar: "تُرجم آليًا", hi: "स्वचालित रूप से अनूदित",
99
+ };
100
+ const SHOW_ORIGINAL: Record<string, string> = {
101
+ en: "Show original", tr: "Orijinali göster", es: "Ver original", de: "Original anzeigen",
102
+ fr: "Afficher l'original", pt: "Ver original", it: "Mostra originale", nl: "Origineel weergeven",
103
+ ru: "Показать оригинал", ja: "原文を表示", zh: "显示原文", ar: "عرض النص الأصلي", hi: "मूल दिखाएँ",
104
+ };
105
+ // The way BACK. It is a toggle, not a door: swapping in place keeps the reader on the feed they
106
+ // were reading, in the language they set — the alternative walks them to the permalink and hands
107
+ // them the whole page in English for the sake of one paragraph.
108
+ const SHOW_TRANSLATION: Record<string, string> = {
109
+ en: "Show translation", tr: "Çeviriyi göster", es: "Ver traducción", de: "Übersetzung anzeigen",
110
+ fr: "Afficher la traduction", pt: "Ver tradução", it: "Mostra traduzione", nl: "Vertaling weergeven",
111
+ ru: "Показать перевод", ja: "翻訳を表示", zh: "显示翻译", ar: "عرض الترجمة", hi: "अनुवाद दिखाएँ",
112
+ };
113
+
114
+ // Relative timestamps are DERIVED from each post/comment's real createdAt (never a stored string),
115
+ // localized to the visitor's language and recomputed at read time — so they age honestly.
116
+ const agoLang = (() => { try { return localStorage.getItem("lang") || document.documentElement.lang || "en"; } catch { return "en"; } })();
117
+ const agoRtf = (() => { try { return new Intl.RelativeTimeFormat(agoLang, { numeric: "auto", style: "narrow" }); } catch { return new Intl.RelativeTimeFormat("en", { numeric: "auto", style: "narrow" }); } })();
118
+ const timeAgo = (iso: string | null): string => {
119
+ if (!iso) return "";
120
+ const t = Date.parse(iso);
121
+ if (Number.isNaN(t)) return "";
122
+ let s = Math.round((Date.now() - t) / 1000);
123
+ if (s < 0) s = 0;
124
+ if (s < 60) return agoRtf.format(-s, "second");
125
+ const m = Math.floor(s / 60); if (m < 60) return agoRtf.format(-m, "minute");
126
+ const h = Math.floor(m / 60); if (h < 24) return agoRtf.format(-h, "hour");
127
+ const d = Math.floor(h / 24); if (d < 7) return agoRtf.format(-d, "day");
128
+ const w = Math.floor(d / 7); if (w < 5) return agoRtf.format(-w, "week");
129
+ const mo = Math.floor(d / 30); if (mo < 12) return agoRtf.format(-mo, "month");
130
+ return agoRtf.format(-Math.floor(d / 365), "year");
131
+ };
132
+ // queries: a persona's name links to the wrong place · a comment links to a host that does not
133
+ // exist · pin.games persona linked to app.zone · where does a commenter's name go
134
+ //
135
+ // WHERE A PERSONA LIVES IS A FACT WE ARE TOLD, NOT ONE WE DERIVE. The API sends `personaUrl`,
136
+ // built from the registry's own `home`, for every persona that has one — and `home` is required
137
+ // by the manifest, so in practice that is all of them.
138
+ //
139
+ // There used to be a fallback here that guessed: justai → justai.pro, app.zone → app.zone, and
140
+ // everything else → `${handle}.app.zone`. It was correct for exactly as long as one apex existed.
141
+ // The day a game persona comments on a feed, that guess sends the reader to a host that has never
142
+ // existed — and it does it silently, in a link, on somebody else's page.
143
+ //
144
+ // So there is no fallback now. If we were not told where a persona lives, its name is rendered
145
+ // WITHOUT a link: a name that goes nowhere is a small disappointment, and a name that goes
146
+ // somewhere wrong is a broken ecosystem seen by a stranger.
147
+ const comment = (c: C, last: boolean): string => {
148
+ const ln = last ? "" : `<span class="ln"></span>`;
149
+ if (c.isPersona) {
150
+ // THE SOCIAL LAYER: personas reply on each other's feeds. A self-reply wears this persona's own
151
+ // face and name; ANOTHER persona wears ITS canonical icon (glyph fallback), its own name, its
152
+ // @handle, and its name links to its own profile. The verified check stays for both.
153
+ const own = c.authorHandle === PERSONA;
154
+ const av = own
155
+ ? AV
156
+ : c.authorAvatar
157
+ ? `<img class="mk" src="${esc(c.authorAvatar)}" alt="">`
158
+ : `<span style="font-size:16px">${esc(c.authorGlyph || "✦")}</span>`;
159
+ const nm = own ? NAME : esc(c.authorName); // own name is authored markup; an API name is escaped
160
+ const purl = own ? "#profile" : c.personaUrl ? `${c.personaUrl}/#profile` : null;
161
+ const at = own ? PERSONA : c.authorHandle;
162
+ const meta = `${at ? `@${esc(at)} ` : ""}· ${timeAgo(c.createdAt)}`;
163
+ const nameEl = purl ? `<a class="pn" href="${esc(purl)}"><b>${nm}</b></a>` : `<span class="pn"><b>${nm}</b></span>`;
164
+ return `<div class="trow${last ? " last" : ""}"><div class="avc"><span class="rav">${av}</span>${ln}</div><div class="cc"><div class="ch">${nameEl}${ck}<span class="muted">${meta}</span></div><p class="cb">${esc(c.body)}</p></div></div>`;
165
+ }
166
+ const initial = esc(String(c.authorName || "?").slice(0, 1));
167
+ // A person needs the handle MORE than a persona does — display names collide constantly among
168
+ // people. Guarded on the value: a principal with none shows a gap, never a bare "@".
169
+ const uat = c.authorHandle ? `@${esc(c.authorHandle)} ` : "";
170
+ return `<div class="trow${last ? " last" : ""}"><div class="avc"><span class="uav" style="--c:${esc(c.authorColor || "#888")}">${initial}</span>${ln}</div><div class="cc"><div class="ch"><b>${esc(c.authorName)}</b><span class="muted">${uat}· ${timeAgo(c.createdAt)}</span></div><p class="cb">${esc(c.body)}</p></div></div>`;
171
+ };
172
+ const post = (p: P): string => {
173
+ const cs = p.comments || [];
174
+ const inner = cs.map((c, i) => comment(c, i === cs.length - 1)).join("");
175
+ // Twitter-style permalink: the timestamp links to the post's feed page, and the whole post is
176
+ // clickable (the delegated handler above). n = the post id's last segment ("post:qr:7" → 7).
177
+ const n = String(p.id || "").split(":").pop() || "";
178
+ // queries: clicking a post loses my language · the permalink is English · navigation language
179
+ //
180
+ // EVERY NAVIGATION STAYS IN THE READER'S LANGUAGE — the founder's rule, and it is stronger than
181
+ // "link to the translation when there is one". Set a persona to Italian and EVERY page of it is
182
+ // Italian; a post with no Italian gives the original words with Italian chrome around them, and
183
+ // `/feed/{n}/it` renders exactly that rather than 404ing.
184
+ //
185
+ // The one URL that carries no segment is the post read in the language it was written in: there
186
+ // is no "translation into the original", so the permalink is already that page.
187
+ const orig = p.originalLang || "en";
188
+ const tr = !!p.translated && !!p.originalBody;
189
+ const base = n ? `/feed/${n}` : "";
190
+ const perma = base && LANG !== orig ? `${base}/${LANG}` : base;
191
+ const pt = perma ? `<a class="pt" href="${perma}">${timeAgo(p.createdAt)}</a>` : `<span class="pt">${timeAgo(p.createdAt)}</span>`;
192
+ // The way back, in the language of the person reading it. A real <a> so the delegated
193
+ // click-anywhere handler above lets it through — it returns early on any link.
194
+ // Both texts ride in the markup so the swap is instant and needs no second request. The link
195
+ // keeps a real href — without scripts it still reaches the original's own page.
196
+ const note = tr
197
+ ? `<p class="tnote" dir="auto"><span data-tstate>${esc(TRANSLATED[LANG] ?? TRANSLATED.en)}</span><span class="dot">·</span>` +
198
+ `<a href="${base}" data-toggle-original data-original="${esc(p.originalBody)}" data-translation="${esc(p.body)}"` +
199
+ ` data-show-original="${esc(SHOW_ORIGINAL[LANG] ?? SHOW_ORIGINAL.en)}" data-show-translation="${esc(SHOW_TRANSLATION[LANG] ?? SHOW_TRANSLATION.en)}"` +
200
+ ` data-translated="${esc(TRANSLATED[LANG] ?? TRANSLATED.en)}" data-original-label="${esc(orig.toUpperCase())} · ${esc(NAME).replace(/<[^>]*>/g, "")}"` +
201
+ ` data-original-lang="${esc(orig)}" data-lang="${esc(p.lang || LANG)}">${esc(SHOW_ORIGINAL[LANG] ?? SHOW_ORIGINAL.en)}</a></p>`
202
+ : "";
203
+ // `dir="auto"` on the body: an Arabic post inside an LTR page — and the reverse — must lay
204
+ // itself out from its own first strong character, not from the page around it.
205
+ return `<article class="post"${perma ? ` data-href="${perma}"` : ""}><div class="trow"><div class="avc"><span class="pa">${AV}</span>${cs.length ? '<span class="ln"></span>' : ""}</div><div class="cc"><div class="ph"><a class="pn" href="#profile"><b>${NAME}</b></a>${ck}${PERSONA ? `<span class="phandle">@${esc(PERSONA)}</span>` : ""}<span class="dot">·</span>${pt}</div><p class="pbd" dir="auto"${tr ? ` lang="${esc(p.lang)}"` : ""}>${esc(p.body)}</p>${note}${pact}</div></div>${inner}</article>`;
206
+ };
207
+
208
+ let done = false;
209
+ const load = async (): Promise<void> => {
210
+ if (done) return;
211
+ done = true;
212
+ try {
213
+ // `lang` rides in the query because it IS the content here — api.justai.pro is CDN'd with the
214
+ // query string in the cache key, so this is one more entry rather than one more origin hit.
215
+ const res = await fetch(
216
+ "https://api.justai.pro/api/feed?persona=" + encodeURIComponent(PERSONA) + "&lang=" + encodeURIComponent(LANG));
217
+ if (!res.ok) return;
218
+ const data = await res.json();
219
+ feed.innerHTML = ((data.posts as P[]) || []).map(post).join("");
220
+ if (scopeAttr) feed.querySelectorAll("*").forEach((el) => el.setAttribute(scopeAttr, ""));
221
+ } catch {
222
+ /* offline → the feed simply stays empty; the rest of the page is unaffected */
223
+ }
224
+ };
225
+
226
+ if ("IntersectionObserver" in window) {
227
+ const io = new IntersectionObserver((es, obs) => {
228
+ if (es.some((e) => e.isIntersecting)) { obs.disconnect(); load(); }
229
+ }, { rootMargin: "400px" });
230
+ io.observe(section);
231
+ } else {
232
+ load();
233
+ }
234
+ })();
@@ -0,0 +1,298 @@
1
+ // queries: preroll behaviour · preroll script · where did Preroll.astro's script go ·
2
+ // testing a component's behaviour · component script is not type checked
3
+ //
4
+ // The preroll — the persona's opening frame, its mark and its timing.
5
+ //
6
+ // Lifted out of `Preroll.astro`, where it was TypeScript that nothing read: a hoisted Astro script
7
+ // goes to esbuild, which strips annotations WITHOUT checking them, and this package had no tsconfig.
8
+ // Out here a compiler can open it and a test can call it. What stays in the component is the markup
9
+ // and the CSS, which is what a component is.
10
+ // queries: preroll script · the game never connects · atrium router game · boot · curtain
11
+ //
12
+ // THE SHELL IS THE ROUTER, AND IT IS ONE BEFORE THE FRAME EXISTS. atrium's rule is that a guest
13
+ // discovers UPWARD, so the room has to be standing before anybody can walk into it. `mount` names
14
+ // the guest by its WINDOW — never by what it calls itself, because a guest that announces its own
15
+ // name lets any frame on the page claim to be the game.
16
+ import atrium from "@justai/atrium";
17
+
18
+ const root = document.getElementById("pr");
19
+ if (root) {
20
+ const door = document.getElementById("prDoor") as HTMLElement;
21
+ const stage = document.getElementById("prStage") as HTMLElement;
22
+ const fill = document.getElementById("prFill") as HTMLElement;
23
+ const playBtn = document.getElementById("prPlay") as HTMLButtonElement;
24
+ const label = document.getElementById("prLabel") as HTMLElement;
25
+
26
+ const src = root.dataset.src as string;
27
+ const atriumId = root.dataset.atrium as string;
28
+
29
+ let started = false;
30
+
31
+ // The stage is never switched — it is underneath the whole time, and the door is a cover over
32
+ // it. `open()` is the handover: the cover leaves and what was already drawing there is visible.
33
+ const open = () => { door.hidden = true; };
34
+
35
+ // ── PATIENCE IS MEASURED IN SILENCE, NOT IN SECONDS ──────────────────────────────────────
36
+ //
37
+ // queries: the game was cut off while it was still loading · the preroll gave up too early ·
38
+ // how long does the shell wait · slow connection · the bar vanished mid-load
39
+ //
40
+ // A total time limit is the wrong instrument and it fails in both directions: 20s abandons a
41
+ // real game on a real 3G connection, and 120s leaves a player staring at a dead frame. What
42
+ // separates the two cases is not how long it has taken — it is whether the game is still
43
+ // TALKING. So the clock is reset by every progress report, and only silence runs it down.
44
+ //
45
+ // A game that never speaks at all gets one window's worth from the moment the frame is created,
46
+ // which is the same promise made to a player whose game is simply broken.
47
+ const PATIENCE = 20000;
48
+ let watchdog: ReturnType<typeof setTimeout> | null = null;
49
+ // Assigned where the promise it resolves is created — a no-op until then, because a progress
50
+ // report cannot arrive before the frame exists and a `bump` that throws would take the bar
51
+ // down with it.
52
+ let bump = () => {};
53
+
54
+ // THE BUTTON IS THE BAR. Its fill layer grows and its word changes; nothing moves and nothing is
55
+ // replaced. A player who pressed something and watches that same thing work never has to ask
56
+ // where their press went.
57
+ const setProgress = (v: unknown) => {
58
+ bump();
59
+ const n = typeof v === "number" ? v : (v as any)?.value;
60
+ if (typeof n !== "number" || !isFinite(n)) return;
61
+ playBtn.removeAttribute("data-indeterminate");
62
+ fill.style.width = Math.max(0, Math.min(1, n)) * 100 + "%";
63
+ };
64
+
65
+ const start = async () => {
66
+ if (started) return;
67
+ started = true;
68
+ // Indeterminate until the game says otherwise, and `disabled` is deliberately NOT used: a
69
+ // disabled button greys out and reads as broken, when what is true is that it is working.
70
+ playBtn.setAttribute("data-busy", "");
71
+ playBtn.setAttribute("data-indeterminate", "");
72
+ playBtn.setAttribute("aria-busy", "true");
73
+ label.textContent = playBtn.dataset.loading || label.textContent;
74
+
75
+ const frame = document.createElement("iframe");
76
+ frame.title = stage.dataset.title || "";
77
+ // `allow` carries the gesture forward: the tap that opened this frame is what lets the game
78
+ // play sound at all, and a frame without it starts muted for reasons nobody can see.
79
+ frame.setAttribute("allow", "autoplay; fullscreen");
80
+ frame.setAttribute("referrerpolicy", "same-origin");
81
+
82
+ let bus: any = null;
83
+ try {
84
+ bus = await atrium({
85
+ id: atriumId,
86
+ router: true,
87
+ mount: ({ source }: any) => (source === frame.contentWindow ? "game" : null),
88
+ });
89
+ } catch {
90
+ // atrium failing must not cost the player the game: mount the frame and hand over blind.
91
+ // A game that cannot speak still runs; it simply gets no progress and no early curtain.
92
+ }
93
+
94
+ // ── THE STAGE — v2 of the protocol: who owns attention, and who owns the chrome ─────────
95
+ //
96
+ // queries: stage playing · pause the game from the shell · mood accent · theater mode ·
97
+ // the cuts stay reachable while playing · focus protocol · oyun basladi
98
+ //
99
+ // The game declares STATE and the shell decides what it means — a game never asks for a
100
+ // toolbar to be hidden, it says what the player is doing. Three messages: `stage` and `mood`
101
+ // travel up (the same direction every progress report already travels), `pause` comes back.
102
+ //
103
+ // THE RETURN DIRECTION IS THE SAFETY OF THE WHOLE DESIGN. Whoever grants exclusive attention
104
+ // must be able to take it back — the player reached for the way out, the tab went to the
105
+ // background. A focus handover with no way back does not trap the shell, it traps the PLAYER,
106
+ // and on a phone the only escape from that is closing the tab. So: a game that has not
107
+ // declared protocol 2 in its boot answer is never given the stage. The declaration IS the
108
+ // promise that `pause` is registered, and the shell holds it to that.
109
+ // The declaration is the boot ANSWER, and a game may announce `playing` in the same breath
110
+ // as resolving boot — airdrop does, and its announcement beats its own answer onto the wire.
111
+ // So the stage handler never reads a variable; it AWAITS the declaration, and a message that
112
+ // arrives early is simply held until the shell knows who it is talking to. The watchdog path
113
+ // declares protocol 1, so a silent game's early announcement resolves to a refusal, not a hang.
114
+ let declareProtocol: (v: number) => void = () => {};
115
+ const declared: Promise<number> = new Promise((r) => { declareProtocol = r; });
116
+ if (bus) {
117
+ // Whatever theme the page carried before the stage took it — restored on pause, so a manual
118
+ // data-theme set by anything else survives a round trip through a game.
119
+ let priorTheme: string | undefined;
120
+
121
+ const setStage = (mode: string) => {
122
+ const playing = mode === "playing";
123
+ if (playing) {
124
+ document.documentElement.dataset.stage = "playing";
125
+ // The theater: the persona's own dark theme, switched on. See the style block above.
126
+ if (document.documentElement.dataset.theme !== "dark") {
127
+ priorTheme = document.documentElement.dataset.theme;
128
+ document.documentElement.dataset.theme = "dark";
129
+ }
130
+ } else {
131
+ delete document.documentElement.dataset.stage;
132
+ if (priorTheme === undefined) delete document.documentElement.dataset.theme;
133
+ else document.documentElement.dataset.theme = priorTheme;
134
+ priorTheme = undefined;
135
+ }
136
+ // The other cuts go INERT rather than display:none — the page must not reflow, and the
137
+ // player's scroll position has to survive a pause. inert takes them out of tab order and
138
+ // the accessibility tree both; a screen reader must not keep walking a page the player
139
+ // has left.
140
+ for (const id of ["profile", "posts"]) {
141
+ const el = document.getElementById(id);
142
+ if (el) el.toggleAttribute("inert", playing);
143
+ }
144
+ // The page is locked, so make sure what it is locked ON is the stage.
145
+ if (playing) stage.scrollIntoView({ block: "nearest" });
146
+ // queries: space does nothing · keyboard not reaching the game · input bind · focus
147
+ //
148
+ // AND THE KEYBOARD GOES WITH THE STAGE. The play press happened in THIS document, so this
149
+ // document holds the focus — and every key the player presses lands in the shell while
150
+ // the game hears nothing. The founder, on the space bar: *"bu haldeyken klavyeden space
151
+ // tusunu bile almiyor. tum input game frame'e bind olmali."* Granting the stage IS the
152
+ // input handover, so the frame is focused with it — and again on pause's reversal, so a
153
+ // resumed game does not come back deaf.
154
+ if (playing) frame.focus();
155
+ // The toolbar swaps its icons for the handle on this event — it owns its own row.
156
+ document.dispatchEvent(new CustomEvent("justai:stage", { detail: { mode } }));
157
+ };
158
+
159
+ // ── the mood: meaning, not pixels ─────────────────────────────────────────────────────
160
+ // A few calls a second at most, eased here over ~600ms — never sampled from a framebuffer.
161
+ // It leans on the ONE variable the whole ground is already built from, so the persona's
162
+ // page re-tints without anything being painted: the door's washes, the buttons, the links
163
+ // all read --accent already.
164
+ const moodHost = (document.getElementById("infinite") ?? document.documentElement) as HTMLElement;
165
+ const hex = (c: string) => {
166
+ const m = /^#([0-9a-f]{6})$/i.exec(c.trim());
167
+ return m ? [parseInt(m[1].slice(0, 2), 16), parseInt(m[1].slice(2, 4), 16), parseInt(m[1].slice(4, 6), 16)] : null;
168
+ };
169
+ let moodRaf = 0;
170
+ const moodTo = (args: any) => {
171
+ if (typeof args?.energy === "number")
172
+ moodHost.style.setProperty("--stage-energy", String(Math.max(0, Math.min(1, args.energy))));
173
+ const to = typeof args?.accent === "string" ? hex(args.accent) : null;
174
+ if (!to) return;
175
+ const from = hex(getComputedStyle(moodHost).getPropertyValue("--accent")) ?? to;
176
+ cancelAnimationFrame(moodRaf);
177
+ const t0 = performance.now();
178
+ const step = (now: number) => {
179
+ const k = Math.min(1, (now - t0) / 600);
180
+ const e = k * k * (3 - 2 * k);
181
+ const c = from.map((f, i) => Math.round(f + (to[i] - f) * e));
182
+ moodHost.style.setProperty("--accent", `rgb(${c[0]}, ${c[1]}, ${c[2]})`);
183
+ if (k < 1) moodRaf = requestAnimationFrame(step);
184
+ };
185
+ moodRaf = requestAnimationFrame(step);
186
+ };
187
+
188
+ bus.register({
189
+ method: "stage",
190
+ handler: async (a: any) => {
191
+ // No protocol 2, no stage — the rule, not a courtesy. Awaited, not read: see above.
192
+ if ((await declared) < 2) return { granted: false };
193
+ setStage(a?.mode === "playing" ? "playing" : "paused");
194
+ return { granted: true };
195
+ },
196
+ });
197
+ bus.register({ method: "mood", handler: (a: any) => { moodTo(a); return {}; } });
198
+
199
+ // The shell's asks, all funnelled through one line so every reason travels the same path.
200
+ const askPause = (reason: string) =>
201
+ bus.proxy({ method: "pause", service: "game", args: { reason }, options: { timeout: 3000 } })
202
+ .catch(() => {});
203
+ // The pause handle and the fullscreen control live in the toolbar's own row; it dispatches,
204
+ // this listens. The shell restores its chrome only when the GAME announces `paused` — one
205
+ // source of truth for state, which is the game, always.
206
+ document.addEventListener("justai:pause-request", () => askPause("chrome"));
207
+ document.addEventListener("justai:fullscreen-request", () =>
208
+ (stage as any).requestFullscreen?.().catch(() => {}));
209
+ document.addEventListener("visibilitychange", () => {
210
+ if (document.hidden && document.documentElement.dataset.stage === "playing") askPause("hidden");
211
+ });
212
+ document.addEventListener("keydown", (e) => {
213
+ if (e.key === "Escape" && document.documentElement.dataset.stage === "playing") askPause("chrome");
214
+ });
215
+ }
216
+
217
+ const arrived = bus
218
+ ? new Promise<void>((resolve) => bus.on("connected", (e: any) => { if (e?.name === "game") resolve(); }))
219
+ : Promise.resolve();
220
+
221
+ stage.appendChild(frame);
222
+ // ── WHAT CROSSES INTO THE FRAME: AN ALLOWLIST, AND A SHORT ONE ──────────────────────────
223
+ //
224
+ // Forwarding the persona's whole query string would be the obvious convenience and it is a
225
+ // privacy hole: a `?data=` envelope, a campaign's utm tags and anything else a person arrived
226
+ // carrying would be handed to a frame that will one day be a third party's deployment. So the
227
+ // shell passes exactly two flags, both of them DEBUG instruments that belong to whoever is
228
+ // looking at the page rather than to whoever built the game: `xray`, the framework's design
229
+ // grid, and `slow`, which asks a game to spread its own loading out far enough to watch.
230
+ // A game that does not understand either simply ignores them.
231
+ const here = new URLSearchParams(location.search);
232
+ const url = new URL(src, location.href);
233
+ for (const flag of ["xray", "slow"]) if (here.has(flag)) url.searchParams.set(flag, here.get(flag) ?? "");
234
+ frame.src = url.pathname + url.search;
235
+
236
+ // ── THE HANDOVER ─────────────────────────────────────────────────────────────────────────
237
+ //
238
+ // ONE CALL CARRIES BOTH. atrium's `proxy` takes a progress callback and resolves when the
239
+ // method returns, so `boot` is the whole protocol: the game reports as it loads and answers
240
+ // when it can draw. No second channel, no polling, and nothing to keep in sync.
241
+ //
242
+ // ** THE EXPLICIT `timeout` IS LOAD-BEARING. ** atrium's default transaction timeout is ONE
243
+ // SECOND — right for a `pick` or an `echo`, and catastrophic here: every game on earth takes
244
+ // longer than a second to load, so `boot` rejected at 1.000s, the catch below swallowed it,
245
+ // and the shell handed over an empty frame while the game was still fetching. It failed the
246
+ // same way every time and said nothing, which is the whole silent-failure genre in one line.
247
+ // Caught by the spec in harness/tests/behavior.spec.mjs, which asked the bar what it read.
248
+ //
249
+ // The number is deliberately far beyond any real load: the POLICY is the watchdog above, and
250
+ // two clocks racing to enforce one promise means the promise is whichever one you forgot.
251
+ const boot = (async () => {
252
+ if (!bus) return {};
253
+ await arrived;
254
+ return await bus.proxy({
255
+ method: "boot",
256
+ service: "game",
257
+ options: { timeout: 600000, callback: (e: any) => setProgress(e?.progress ?? e?.value ?? e) },
258
+ });
259
+ })();
260
+
261
+ // The watchdog is the other half of the promise made to the player: whatever is wrong in
262
+ // there, they are better off seeing it than seeing us wait for it.
263
+ const giveUp = new Promise<any>((resolve) => {
264
+ bump = () => {
265
+ if (watchdog) clearTimeout(watchdog);
266
+ watchdog = setTimeout(() => resolve({ lateBy: "silence" }), PATIENCE);
267
+ };
268
+ bump();
269
+ });
270
+
271
+ // A SWALLOWED REASON IS THE FAILURE ITSELF. The frame is handed over either way — a player must
272
+ // not lose the game to a broken handshake — but the catch SAYS what went wrong, because the
273
+ // symptom on the other side of it is "the wait ended early" and nothing else. This cut's own
274
+ // one-second bug lived inside an empty catch and was invisible until a spec read the bar.
275
+ const answer: any = await Promise.race([
276
+ boot.catch((e: any) => {
277
+ console.warn("[preroll] the game's boot did not complete:", e?.message || e);
278
+ return {};
279
+ }),
280
+ giveUp,
281
+ ]);
282
+ if (watchdog) clearTimeout(watchdog);
283
+
284
+ // The boot answer carries the game's protocol version, and version 2 is the declaration
285
+ // that `pause` is registered and will be honoured. Resolved before open(), so a game
286
+ // announcing `playing` in its very first frame — or a breath before its own answer — is
287
+ // already trusted by the time the door goes up.
288
+ declareProtocol(typeof answer?.protocol === "number" ? answer.protocol : 1);
289
+
290
+ open();
291
+ // `curtain: true` is the game saying "hand over early, I will cover the rest myself" — which
292
+ // is what a console does, where the logo animation IS the loading screen. Nothing else here
293
+ // changes; the difference is only how long this cut keeps the door shut.
294
+ if (answer?.curtain) root.dataset.curtain = "";
295
+ };
296
+
297
+ playBtn.addEventListener("click", start, { once: true });
298
+ }
@@ -0,0 +1,64 @@
1
+ // queries: segmented behaviour · segmented script · where did Segmented.astro's script go ·
2
+ // testing a component's behaviour · component script is not type checked
3
+ //
4
+ // The segmented control — one choice out of a few, iOS-grammar.
5
+ //
6
+ // Lifted out of `Segmented.astro`, where it was TypeScript that nothing read: a hoisted Astro script
7
+ // goes to esbuild, which strips annotations WITHOUT checking them, and this package had no tsconfig.
8
+ // Out here a compiler can open it and a test can call it. What stays in the component is the markup
9
+ // and the CSS, which is what a component is.
10
+ // queries: segmented control keyboard · arrow keys · roving tabindex · aria-checked · change event
11
+ //
12
+ // ROVING TABINDEX IS THE WHOLE OF THE KEYBOARD. A radiogroup is ONE tab stop: Tab reaches the
13
+ // chosen option and the arrows move within the group. Leaving every option at `tabIndex 0` is the
14
+ // common mistake and it is invisible to anyone using a mouse — a person on a keyboard suddenly has
15
+ // to press Tab three times to get past a control they were not using.
16
+ //
17
+ // Lifted from qr, which had it right and had it alone.
18
+ const wire = (root: HTMLElement) => {
19
+ const items = () => Array.from(root.querySelectorAll<HTMLElement>('[role="radio"]'));
20
+
21
+ const set = (el: HTMLElement, focus?: boolean, quiet?: boolean) => {
22
+ if (el.getAttribute("aria-disabled") === "true") return;
23
+ const next = el.dataset.value!;
24
+ if (root.dataset.value === next) { if (focus) el.focus(); return; }
25
+ for (const r of items()) {
26
+ const chosen = r === el;
27
+ r.setAttribute("aria-checked", String(chosen));
28
+ r.tabIndex = chosen ? 0 : -1;
29
+ }
30
+ root.dataset.value = next;
31
+ if (focus) el.focus();
32
+ // Setting `.value` from code does NOT re-announce — a caller that just said what it wants does
33
+ // not need to be told, and a listener that reacts by setting the value would loop.
34
+ if (!quiet) root.dispatchEvent(new CustomEvent("change", { detail: { value: next }, bubbles: true }));
35
+ };
36
+
37
+ for (const el of items()) el.addEventListener("click", () => set(el, true));
38
+
39
+ root.addEventListener("keydown", (e) => {
40
+ const key = (e as KeyboardEvent).key;
41
+ const all = items().filter((r) => r.getAttribute("aria-disabled") !== "true");
42
+ const at = all.findIndex((r) => r.getAttribute("aria-checked") === "true");
43
+ let to = -1;
44
+ if (key === "ArrowRight" || key === "ArrowDown") to = (at + 1) % all.length;
45
+ else if (key === "ArrowLeft" || key === "ArrowUp") to = (at - 1 + all.length) % all.length;
46
+ else if (key === "Home") to = 0;
47
+ else if (key === "End") to = all.length - 1;
48
+ if (to < 0 || !all[to]) return;
49
+ e.preventDefault();
50
+ set(all[to], true);
51
+ });
52
+
53
+ // The one thing a caller needs beyond listening: saying what it wants.
54
+ Object.defineProperty(root, "value", {
55
+ get: () => root.dataset.value,
56
+ set: (v: string) => {
57
+ const el = items().find((r) => r.dataset.value === v);
58
+ if (el) set(el, false, true);
59
+ },
60
+ configurable: true,
61
+ });
62
+ };
63
+
64
+ for (const root of document.querySelectorAll<HTMLElement>(".jseg")) wire(root);