Public: anyone can read this; the crew can change it.

Jay Moran's displays are reachable: the display and displays pages, the display builds route, and the arcade host they launch #9357

Parked opened this
Closed without merging

scout/forge:scout/9208-jay-moran-s-displays-are-reachable-the-d → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
22 files changed +2231 −11
docs/design/areas/displays.md added +22
@@ -0,0 +1,22 @@
1 # Displays
2
3 `/displays` lists the displays the viewer may read in a stock `table`; a row
4 opens `/:owner/:name/display`, the display page (Jay Moran's design, kept).
5
6 The display page is a two-column workbench: a side list of the sources' builds
7 with a tick each, and the chosen builds as cards beside a player and an info
8 panel (the Iterations panel, `it-*`). Its own classes, all scoped to that page
9 and drawn from the 4px scale and the stock colour tokens:
10
11 - `.dp` the grid (side, main); `.dp-main` the main column.
12 - `.dp-side`, `.dp-side-h`, `.dp-side-t` the collapsible side list and its header and title.
13 - `.dp-sec`, `.dp-sec-h`, `.dp-rows`, `.dp-caret`, `.dp-n` one repository's section in the side list: header button, rows, caret, "N of M" count.
14 - `.dp-s` the small "not built" tag on a row.
15 - `.dp-cards`, `.dp-card`, `.dp-cover`, `.dp-play`, `.dp-row1`, `.dp-meta`, `.dp-title` the chosen builds as cards: cover, play button, first row, meta line, title.
16 - `.dp-none` the empty line when no build is chosen.
17 - `.dp-said` the quiet status line after a save; `.dp-ttl-ed` the title's edit-in-place form.
18 - `.display-shots` the screenshots gallery shown through a display.
19
20 None is a variant of a stock component; each exists because the page's layout
21 (a side list beside draggable cards) has no stock equivalent. A phone look is
22 attached to the pull from its preview.
docs/features/displays.md added +18
@@ -0,0 +1,18 @@
1 # Displays
2
3 A display is a repository with a `display.json` on its default branch: a title,
4 a layout (`shelf`, `grid`, `graph`), the sources it reads builds from, and
5 optionally `builds`, the chosen builds in order (`owner/name:label`).
6
7 - `/displays` lists every display you may read; `/displays/new` makes one.
8 - `/:owner/:name/display` is the display, server-rendered. A writer ticks builds
9 on the page (`POST …/display/builds`) and edits its title.
10 - `PUT /api/v1/repos/:owner/:name/display/builds` with `{"builds": [...]}` (or
11 `null` to hold every showcased pin again): `rw` scope, a person who writes
12 the repository, one commit on the default branch. A bad list is 422.
13 - `…/display/snapshot.html` downloads the shelf as one offline file.
14 - The Arcade host (`arcade/host.ts`) serves the site admin's display titled
15 `arcade-builds` at its own host.
16
17 Not done here: the `/arcade` door, a pin's `/cover` route and the showcase
18 and demo editing forms (they need `actions/pin_demos.ts` verbs that are not on main).
scripts/unreached-allow.json −7
@@ -1,15 +1,8 @@
11 [
2 "src/actions/pin_demos.ts",
32 "src/apps/cloud.ts",
4 "src/arcade/cover.ts",
5 "src/arcade/shelf.ts",
63 "src/boards/machine.ts",
74 "src/crew/governor_log.ts",
85 "src/crew/tries.ts",
9 "src/display/config.ts",
10 "src/display/items.ts",
11 "src/display/known.ts",
12 "src/display/selections.ts",
136 "src/flow/alarm_drift.ts",
147 "src/flow/alarm_unproposed.ts",
158 "src/flow/approved_wait.ts",
src/actions/displays.ts added +199
@@ -0,0 +1,199 @@
1 /**
2 * A display's writes (`display/config.ts`): save `display.json` to the
3 * display repository's default branch, as one commit by the person who
4 * edited it, through the file edit every page uses (`contents.ts`), whole
5 * or one key of it (its title, its builds); and
6 * capture every showcased demo of the display that opens as a file and has
7 * no capture yet (`arcade/carts.ts`). A person who writes the display
8 * repository, never an agent.
9 */
10
11 import type { App } from "../app.ts";
12 import { captureState, startCapture, type CaptureOptions } from "../arcade/carts.ts";
13 import { canWrite, type Repo } from "../core/repos.ts";
14 import type { User } from "../core/users.ts";
15 import { readFileAt } from "../apps/checkout.ts";
16 import { checkDisplay, DISPLAY_FILE, parseBuilds, parseDisplay, readDisplay } from "../display/config.ts";
17 import { exactRefOid } from "../git/branches.ts";
18 import { repoDir } from "../git/repos.ts";
19 import { displayItems } from "../display/items.ts";
20 import { err, ok, type Result } from "../kernel/result.ts";
21 import { requireWriter, type AccessError } from "./access.ts";
22 import { editFiles } from "./contents.ts";
23
24 /** A person who writes the display repository. */
25 function displayWriter(app: App, actor: User | undefined, repo: Repo): Result<User, AccessError> {
26 const writer = requireWriter(app, actor, repo);
27 if (!writer.ok) return writer;
28 return writer.value.kind === "agent" ? err("forbidden") : writer;
29 }
30
31 export type SaveDisplayError =
32 | AccessError
33 | { readonly kind: "invalid_display"; readonly message: string }
34 | { readonly kind: "moved" }
35 | { readonly kind: "protected_branch" }
36 | { readonly kind: "commit_failed"; readonly message: string };
37
38 /**
39 * Write `text` as `display.json` on the default branch, refused unless it
40 * parses and the branch is still at `expectTip` (when one is given).
41 */
42 export async function saveDisplay(
43 app: App,
44 actor: User | undefined,
45 repo: Repo,
46 text: string,
47 expectTip: string | undefined,
48 ): Promise<Result<{ readonly commit: string; readonly created: boolean }, SaveDisplayError>> {
49 const writer = displayWriter(app, actor, repo);
50 if (!writer.ok) return writer;
51 const parsed = parseDisplay(text);
52 if (!parsed.ok) return err({ kind: "invalid_display", message: parsed.error });
53 const created = (await readDisplay(app, repo)) === undefined;
54 const edited = await editFiles(app, writer.value, repo, {
55 branch: repo.defaultBranch,
56 message: `${created ? "Create" : "Update"} ${DISPLAY_FILE}`,
57 files: [{ path: DISPLAY_FILE, content: text }],
58 ...(expectTip === undefined || expectTip === "" ? {} : { expectTip }),
59 });
60 if (!edited.ok) {
61 const e = edited.error;
62 if (typeof e === "string") {
63 if (e === "not_found" || e === "unauthorized" || e === "forbidden") return err(e);
64 return err({ kind: "commit_failed", message: e });
65 }
66 if (e.kind === "branch_moved") return err({ kind: "moved" });
67 if (e.kind === "protected_branch") return err({ kind: "protected_branch" });
68 return err({ kind: "commit_failed", message: e.kind });
69 }
70 await checkDisplay(app, repo);
71 return ok({ commit: edited.value.commit.commitOid, created });
72 }
73
74 /**
75 * Change one key of `display.json` on the default branch and save it as one
76 * commit, leased on the tip it was read at; the rest of the file stays.
77 */
78 async function rewriteDisplay(
79 app: App,
80 writer: User,
81 repo: Repo,
82 change: (raw: Record<string, unknown>) => void,
83 ): Promise<Result<{ readonly commit: string }, SaveDisplayError | { readonly kind: "no_display" }>> {
84 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
85 const tip = await exactRefOid(dir, `refs/heads/${repo.defaultBranch}`);
86 const text = tip === undefined ? undefined : await readFileAt(dir, tip, DISPLAY_FILE);
87 if (tip === undefined || text === undefined) return err({ kind: "no_display" });
88 const parsed = parseDisplay(text);
89 if (!parsed.ok) return err({ kind: "invalid_display", message: parsed.error });
90 const raw = JSON.parse(text) as Record<string, unknown>;
91 change(raw);
92 const saved = await saveDisplay(app, writer, repo, `${JSON.stringify(raw, null, 2)}\n`, tip);
93 return saved.ok ? ok({ commit: saved.value.commit }) : saved;
94 }
95
96 export type SetDisplayTitleError = SaveDisplayError | { readonly kind: "no_display" };
97
98 /**
99 * Set the display's title: `title` in `display.json`, one commit through
100 * `saveDisplay`; the rest of the file stays. The title `arcade-builds` on a
101 * site admin's repository makes it the Arcade (`display/known.ts`), whose
102 * pick the commit's push event reads again.
103 */
104 export async function setDisplayTitle(
105 app: App,
106 actor: User | undefined,
107 displayRepo: Repo,
108 title: string,
109 ): Promise<Result<{ readonly commit: string; readonly title: string }, SetDisplayTitleError>> {
110 const writer = displayWriter(app, actor, displayRepo);
111 if (!writer.ok) return writer;
112 const saved = await rewriteDisplay(app, writer.value, displayRepo, (raw) => {
113 raw.title = title;
114 });
115 return saved.ok ? ok({ commit: saved.value.commit, title }) : saved;
116 }
117
118 export type SetDisplayBuildsError =
119 | SaveDisplayError
120 | { readonly kind: "no_display" }
121 | { readonly kind: "invalid_builds"; readonly message: string };
122
123 /**
124 * Set the display's chosen builds and their order: `builds` in
125 * `display.json`, `owner/name:label` each, written as one commit through
126 * `saveDisplay`; null removes the key, so the display holds every showcased
127 * pin of its sources again. The rest of the file stays as it is. A build
128 * need not be showcased: the display decides, and `display/items.ts` keeps
129 * one that is not from anyone who cannot read its repository.
130 */
131 export async function setDisplayBuilds(
132 app: App,
133 actor: User | undefined,
134 displayRepo: Repo,
135 builds: readonly string[] | null,
136 ): Promise<Result<{ readonly commit: string; readonly builds: readonly string[] | null }, SetDisplayBuildsError>> {
137 const writer = displayWriter(app, actor, displayRepo);
138 if (!writer.ok) return writer;
139 const checked = parseBuilds(builds ?? undefined);
140 if (!checked.ok) return err({ kind: "invalid_builds", message: `${DISPLAY_FILE}: ${checked.error}` });
141 const saved = await rewriteDisplay(app, writer.value, displayRepo, (raw) => {
142 if (checked.value === undefined) delete raw.builds;
143 else raw.builds = checked.value;
144 });
145 if (!saved.ok) return saved;
146 app.bus.append({
147 kind: "display.builds",
148 repoId: displayRepo.id,
149 actorId: writer.value.id,
150 payload: { commit: saved.value.commit, builds: checked.value ?? null },
151 });
152 return ok({ commit: saved.value.commit, builds: checked.value ?? null });
153 }
154
155 export type CaptureDisplayError = AccessError | "no_display" | "invalid_display";
156
157 export interface CaptureDisplayDone {
158 /** The demos whose capture started. */
159 readonly started: readonly string[];
160 /** File demos with no capture that the person may not capture: they do not write the source. */
161 readonly skipped: number;
162 }
163
164 /**
165 * Start a capture for each showcased file demo of the display with none
166 * kept and none running, as the person who asked; a demo whose repository
167 * they do not write is skipped.
168 */
169 export async function captureDisplay(
170 app: App,
171 actor: User | undefined,
172 repo: Repo,
173 options: CaptureOptions = {},
174 ): Promise<Result<CaptureDisplayDone, CaptureDisplayError>> {
175 const writer = displayWriter(app, actor, repo);
176 if (!writer.ok) return writer;
177 const config = await readDisplay(app, repo);
178 if (config === undefined) return err("no_display");
179 if (!config.ok) return err("invalid_display");
180 const started: string[] = [];
181 let skipped = 0;
182 for (const item of await displayItems(app, repo, config.value, writer.value)) {
183 if (item.launch !== "file" || item.captured !== undefined) continue;
184 if (captureState(app, item.repo, item.pin.oid, item.demo.page).state === "capturing") continue;
185 if (!canWrite(app.db, item.repo, writer.value)) {
186 skipped++;
187 continue;
188 }
189 void startCapture(app, writer.value, item.repo, item.pin.oid, item.demo.page, options);
190 started.push(item.key);
191 }
192 app.bus.append({
193 kind: "display.captured",
194 repoId: repo.id,
195 actorId: writer.value.id,
196 payload: { started: started.length, skipped },
197 });
198 return ok({ started, skipped });
199 }
src/arcade/arcade.html added +336
@@ -0,0 +1,336 @@
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1">
6 <title>Browser Arcade</title>
7 <link rel="icon" href="data:,">
8 <link rel="preconnect" href="https://fonts.googleapis.com">
9 <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bungee&family=Press+Start+2P&family=Ubuntu:wght@700&display=swap">
10 <style>
11 :root {
12 --night: #120a26;
13 --ink: #fff6e0;
14 --dim: #9a90c0;
15 --sun: #ffd200;
16 --pink: #ff4fa0;
17 --lime: #9bbc0f;
18 --line: #08040f;
19 --pixel: "Press Start 2P", ui-monospace, Menlo, monospace;
20 }
21 * { box-sizing: border-box; }
22 html, body { margin: 0; min-height: 100%; color: var(--ink); font: 11px/1.5 var(--pixel); overflow-x: hidden;
23 background-color: #4a2a16; }
24 /* A woodgrain tabletop: planks, with darker grain running along them. */
25 body { background-image:
26 repeating-linear-gradient(0deg, rgba(0,0,0,.35) 0 3px, transparent 3px 96px),
27 repeating-linear-gradient(0deg, rgba(255,210,150,.05) 0 2px, transparent 2px 9px, rgba(0,0,0,.08) 9px 11px, transparent 11px 23px),
28 linear-gradient(90deg, #4a2a16, #5a3420 30%, #4e2c18 55%, #5e3822 80%, #4a2a16); }
29 /* CRT scanlines over the whole shelf. */
30 body::after { content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 5; background: repeating-linear-gradient(0deg, rgba(0,0,0,.16) 0 1px, transparent 1px 3px); }
31 button, a { font: inherit; color: inherit; }
32 /* One line across the top: the producer, and for a snapshot file, its date. */
33 header { position: relative; padding: 10px 16px; background: rgba(8,4,15,.7); border-bottom: 4px solid var(--line); font-size: 10px; color: var(--sun);
34 white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; }
35
36 /* Carts: chunky plastic with a black outline, bevels, screws, a deep grip and a big sticker. */
37 /* Carts turned to the sides must not widen the page. */
38 main { overflow-x: clip; }
39 .stage { position: relative; height: 330px; perspective: 1100px; margin-top: 22px; }
40 .cart { position: absolute; left: 50%; top: 14px; width: 210px; margin-left: -105px; cursor: pointer; border: 0; padding: 0; background: none;
41 transition: transform .45s cubic-bezier(.2,.9,.3,1.1), filter .45s, top .35s ease-in; }
42 .shell { position: relative; padding: 14px 14px 66px; background: var(--body); border: 5px solid var(--line);
43 box-shadow: inset 6px 6px 0 var(--hi), inset -6px -6px 0 var(--lo), 8px 8px 0 var(--line); }
44 .shell::before { content: ""; position: absolute; left: 50%; top: 4px; width: 46px; height: 5px; margin-left: -23px; background: var(--lo); box-shadow: 0 0 0 2px var(--line); }
45 .screw { position: absolute; bottom: 52px; width: 9px; height: 9px; border-radius: 50%; background: var(--hi); box-shadow: 0 0 0 2px var(--line), inset -2px -2px 0 var(--lo); }
46 .screw.l { left: 9px; } .screw.r { right: 9px; }
47 .grip { position: absolute; left: 14px; right: 14px; bottom: 10px; height: 38px; border: 3px solid var(--line);
48 background: repeating-linear-gradient(0deg, var(--lo) 0 5px, var(--hi) 5px 7px, var(--body) 7px 10px); }
49 .sticker { position: relative; aspect-ratio: 1; background: #000; border: 5px solid #fff; box-shadow: 0 0 0 4px var(--line); overflow: hidden; }
50 .sticker img { width: 100%; height: 100%; object-fit: cover; image-rendering: pixelated; display: block; }
51 .sticker .logo { position: absolute; left: 0; right: 0; bottom: 0; padding: 20px 6px 6px; font: 15px/1.05 "Bungee", sans-serif; color: #fff;
52 text-shadow: 2px 2px 0 var(--line), -1px -1px 0 var(--line); background: linear-gradient(transparent, rgba(0,0,0,.75)); text-align: left; }
53 .cart.loading { top: 230px; transform: translateZ(0) scale(.92) !important; }
54
55 /* The console: a heavy slab with a slot, switches, a readout, and big buttons. */
56 .console { position: relative; z-index: 2; max-width: 760px; margin: -6px auto 0; padding: 30px 26px 24px;
57 background: linear-gradient(#45405a, #2c283c); border: 6px solid var(--line);
58 box-shadow: inset 0 8px 0 #6a6488, inset 0 -10px 0 #1c1828, 10px 10px 0 var(--line); }
59 .console .slot { position: absolute; left: 50%; top: -6px; width: 250px; height: 22px; margin-left: -125px; background: #05030a; border: 6px solid var(--line); border-top: 0; }
60 .row { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
61 .row + .row { margin-top: 16px; }
62 .badge { font: 16px "Bungee", sans-serif; letter-spacing: 5px; color: #b8b0d8; text-shadow: 2px 2px 0 var(--line); }
63 .led { width: 14px; height: 14px; border-radius: 50%; background: #5a1010; box-shadow: 0 0 0 3px var(--line); }
64 .led.on { background: #ff3a3a; box-shadow: 0 0 0 3px var(--line), 0 0 14px #ff3a3a; }
65 .led.go { background: #3aff6a; box-shadow: 0 0 0 3px var(--line), 0 0 14px #3aff6a; }
66 .grille { flex: 1; min-width: 80px; height: 24px; background: repeating-linear-gradient(90deg, #1c1828 0 6px, #55507a 6px 9px); border: 3px solid var(--line); }
67 .lcd { flex: 1; min-width: 220px; background: #9bbc0f; color: #0f380f; border: 5px solid var(--line); box-shadow: inset 3px 3px 0 #306230; padding: 10px 12px; font-size: 10px; line-height: 1.7; }
68 .lcd b { display: block; font-size: 12px; }
69 .switches { display: flex; gap: 8px; flex-wrap: wrap; }
70 .switch { cursor: pointer; padding: 10px 10px; font-size: 9px; background: #2c283c; border: 4px solid var(--line); box-shadow: inset 3px 3px 0 #55507a, 4px 4px 0 var(--line); }
71 .switch[aria-pressed="true"] { background: var(--sun); color: var(--line); box-shadow: inset 3px 3px 0 #fff2a0, 2px 2px 0 var(--line); transform: translate(2px, 2px); }
72 .big { cursor: pointer; padding: 14px 18px; font-size: 12px; border: 5px solid var(--line); text-decoration: none; display: inline-block; }
73 .power { background: #ff3a3a; color: #fff; box-shadow: inset 4px 4px 0 #ff8a8a, inset -4px -4px 0 #9a1010, 5px 5px 0 var(--line); }
74 .eject { background: #c8c0e0; color: var(--line); box-shadow: inset 4px 4px 0 #fff, inset -4px -4px 0 #8a80a8, 5px 5px 0 var(--line); }
75 .big:active { transform: translate(4px, 4px); box-shadow: none; }
76 .switch:focus-visible, .big:focus-visible, .cart:focus-visible { outline: 4px solid var(--sun); outline-offset: 4px; }
77 footer { position: relative; text-align: center; color: var(--dim); font-size: 9px; padding: 22px 16px 30px; }
78 footer a { color: var(--sun); text-decoration: none; margin-left: 14px; }
79 footer a:hover, footer a:focus-visible { text-decoration: underline; }
80 .empty { text-align: center; padding-top: 80px; }
81 @media (max-width: 600px) { .stage { height: 290px; } .cart { width: 170px; margin-left: -85px; } .cart.loading { top: 200px; } }
82
83 /* The player: the game fills the screen, with a way back. */
84 #player { position: fixed; inset: 0; background: #000; display: none; z-index: 10; }
85 #player.on { display: block; }
86 #player iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
87 #back { position: absolute; top: 10px; left: 10px; z-index: 4; cursor: pointer; font-size: 10px; color: var(--ink);
88 background: #2c283c; border: 4px solid var(--line); box-shadow: 3px 3px 0 var(--line); padding: 6px 9px; opacity: .6; }
89 #back:hover, #back:focus-visible { opacity: 1; }
90 /* The jbox boot tag plays over the screen while a cartridge loads. */
91 #boot { position: absolute; inset: 0; display: none; place-items: center; background: #1b1b25; z-index: 1; transition: opacity .25s; }
92 #boot.on { display: grid; }
93 #boot.out { opacity: 0; }
94 #boot canvas { display: block; image-rendering: pixelated; }
95 /* Opened from a link, the cartridge waits for a press so its power-on chord can play. */
96 #power { position: absolute; inset: 0; display: none; place-items: center; z-index: 3; background: #1b1b25; color: var(--lime); cursor: pointer; text-align: center; font-size: 11px; }
97 #power.on { display: grid; }
98 #power b { display: block; font-size: 32px; margin-bottom: 14px; }
99 </style>
100 </head>
101 <body>
102 <header id="topline">JBOX • BROWSER ARCADE</header>
103 <main id="games"><p class="empty">LOADING…</p></main>
104 <footer>◀ ▶ CHOOSE · Z X BUILD · ENTER POWER<a id="export" href="snapshot.html" download>⤓ EXPORT SNAPSHOT</a></footer>
105
106 <div id="player" aria-hidden="true">
107 <button id="back" type="button">◀ ARCADE</button>
108 <div id="boot"><canvas id="tag"></canvas></div>
109 <div id="power"><div><b>⏻</b>PRESS ANY KEY TO POWER ON</div></div>
110 <iframe id="screen" title="Game" allow="autoplay *; fullscreen *; gamepad *"></iframe>
111 </div>
112
113 <script type="module">
114 import { jboxScale, playJboxSpin } from './boot/jbox-spin.js';
115 const shelfEl = document.getElementById('games');
116 const player = document.getElementById('player');
117 const screen = document.getElementById('screen');
118 const bootEl = document.getElementById('boot');
119 const tag = document.getElementById('tag');
120 const powerEl = document.getElementById('power');
121 /** Bytes as a short size: 38 KB, 1.2 MB. */
122 const size = (n) => (!n ? '' : n < 1e6 ? `${Math.round(n / 1024)} KB` : `${(n / 1048576).toFixed(1)} MB`);
123 // A single-file bundle (a snapshot) carries the shelf, carts and covers inside the
124 // page as window.__ARCADE__; the forge's own display page carries the shelf with
125 // absolute addresses. Served as a folder, the arcade reads its files instead.
126 const BUNDLE = window.__ARCADE__;
127 const HOME = document.title;
128 const urls = new Map();
129 /** Where a cart or label lives: its path, or a blob or data URL from the bundle. */
130 const url = (path) => {
131 if (!BUNDLE || !path || /^(data:|https?:|\/)/.test(path)) return path;
132 if (!urls.has(path)) {
133 const label = BUNDLE.labels[path];
134 urls.set(path, label ?? URL.createObjectURL(new Blob([BUNDLE.carts[path] ?? ''], { type: 'text/html' })));
135 }
136 return urls.get(path);
137 };
138 if (BUNDLE?.snapshot) document.getElementById('topline').textContent = BUNDLE.snapshot;
139 // A snapshot is the export: it has nothing further to export.
140 if (BUNDLE?.exportHref) document.getElementById('export').href = BUNDLE.exportHref;
141 else if (BUNDLE) document.getElementById('export').remove();
142 const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
143
144 /** Cart plastic by game: body, highlight and shadow. Unknown games get grey. */
145 const PLASTIC = {
146 'krazy-karts': ['#e8322a', '#ff7a6a', '#8a1410'],
147 'nova-lantern': ['#5a3ab8', '#8a6ae8', '#2a1a68'],
148 ballistics: ['#f0a020', '#ffd870', '#9a5a0a'],
149 'krazy-karts-fiesta': ['#ff7a1a', '#ffb060', '#a83e00'],
150 'krazy-karts-london': ['#4a6a8a', '#7a9aba', '#24384c'],
151 'krazy-karts-chicago': ['#2a8ad8', '#6ac0ff', '#124a7a'],
152 'nova-moves': ['#1f8a6a', '#4ac89a', '#0e4a38'],
153 };
154 const plastic = (id) => PLASTIC[id] ?? ['#8a8a96', '#c0c0cc', '#4a4a56'];
155
156 /** Wait for a key or click: browsers only play sound after one. */
157 function powerPress() {
158 powerEl.classList.add('on');
159 return new Promise((done) => {
160 const go = (e) => {
161 e.preventDefault();
162 removeEventListener('keydown', go);
163 powerEl.removeEventListener('pointerdown', go);
164 powerEl.classList.remove('on');
165 done();
166 };
167 addEventListener('keydown', go);
168 powerEl.addEventListener('pointerdown', go);
169 });
170 }
171
172 /** The jbox tag spins up while the cartridge loads behind it. `sound` needs a click. */
173 async function bootCartridge(sound) {
174 bootEl.classList.remove('out');
175 bootEl.classList.add('on');
176 const s = jboxScale(innerWidth * 0.8, innerHeight * 0.8);
177 tag.style.width = `${160 * s}px`;
178 tag.style.height = `${144 * s}px`;
179 await playJboxSpin(tag, { sound });
180 }
181
182 async function play(game, build, push = true) {
183 if (push) history.pushState({ game: game.id, build: build.id }, '', `#${game.id}/${build.id}`);
184 player.classList.add('on');
185 player.setAttribute('aria-hidden', 'false');
186 document.title = `${game.name} · ${build.name}`;
187 const ready = new Promise((r) => (screen.onload = r));
188 // Replace, so the frame's own loads never land in the browser's history.
189 screen.contentWindow.location.replace(BUNDLE ? url(build.file) : new URL(build.file, location.href).href);
190 // A click on a cartridge already counts as the press. A link has to ask for one.
191 if (!push) await powerPress();
192 await Promise.all([ready, bootCartridge(true)]);
193 bootEl.classList.add('out');
194 screen.focus();
195 setTimeout(() => bootEl.classList.remove('on', 'out'), 260);
196 }
197
198 function stop() {
199 player.classList.remove('on');
200 player.setAttribute('aria-hidden', 'true');
201 screen.contentWindow.location.replace('about:blank');
202 document.title = HOME;
203 shelfEl.querySelector('.loading')?.classList.remove('loading');
204 shelfEl.querySelector('.led')?.classList.replace('go', 'on');
205 }
206
207 document.getElementById('back').addEventListener('click', () => {
208 history.pushState(null, '', location.pathname);
209 stop();
210 });
211
212 const games = BUNDLE ? BUNDLE.games : await fetch('games.json').then((r) => r.json()).catch(() => []);
213 // Builds stand in the display's order.
214 // A build with no cover of its own gets the house cover, drawn from its page's picture.
215 /*COVER_JS*/
216 if (games.some((g) => g.builds.some((b) => !b.label))) {
217 await Promise.race([document.fonts?.load('700 44px Ubuntu'), new Promise((r) => setTimeout(r, 1500))]).catch(() => {});
218 const tpl = await loadImage(url('cover-template.png'));
219 for (const g of games) for (const b of g.builds) {
220 if (b.label) continue;
221 const c = document.createElement('canvas');
222 drawCover(c, b.art ? await loadImage(url(b.art)) : null, tpl, g.name, b.name);
223 b.label = c.toDataURL('image/png');
224 b.titled = true;
225 }
226 }
227 let gi = 0;
228 const bi = games.map(() => 0);
229 const find = (gid, bid) => {
230 const g = games.find((x) => x.id === gid);
231 const b = g?.builds.find((x) => x.id === bid);
232 return g && b ? [g, b] : null;
233 };
234
235 // The carousel of carts is built once; `draw` turns it and refreshes the console.
236 if (!games.length) shelfEl.innerHTML = '<p class="empty">THE SHELF IS EMPTY</p>';
237 else {
238 shelfEl.innerHTML = `
239 <div class="stage">${games.map((g, i) => {
240 const [body, hi, lo] = plastic(g.id);
241 return `<button type="button" class="cart" data-i="${i}" style="--body:${body};--hi:${hi};--lo:${lo}" aria-label="${esc(g.name)}">
242 <div class="shell"><div class="sticker"><img alt=""><div class="logo">${esc(g.name).toUpperCase()}</div></div>
243 <span class="screw l"></span><span class="screw r"></span><div class="grip"></div></div></button>`;
244 }).join('')}</div>
245 <section class="console" aria-label="Console">
246 <div class="slot"></div>
247 <div class="row"><span class="led on"></span><span class="badge">JBOX</span><span class="grille"></span></div>
248 <div class="row"><div class="lcd" id="lcd"></div><div class="switches" id="switches"></div></div>
249 <div class="row"><button type="button" class="big power" id="go">⏻ POWER</button><a class="big eject" id="save">⏏ SAVE</a><span class="grille"></span></div>
250 </section>`;
251 }
252
253 function draw() {
254 if (!games.length) return;
255 const g = games[gi];
256 const b = g.builds[bi[gi]];
257 shelfEl.querySelectorAll('.cart').forEach((c, i) => {
258 const d = i - gi;
259 const x = games[i];
260 const xb = x.builds[bi[i]];
261 const img = c.querySelector('img');
262 if (xb.label && img.dataset.label !== xb.label) {
263 img.dataset.label = xb.label;
264 img.src = url(xb.label);
265 }
266 // Cover art carries its own title; a plain snapshot gets the game's name.
267 c.querySelector('.logo').hidden = Boolean(xb.titled);
268 // Far carts turn no more than 70°, so none shows its back.
269 c.style.transform = `translateX(${d * 220}px) translateZ(${-Math.abs(d) * 230}px) rotateY(${-Math.sign(d) * Math.min(Math.abs(d) * 36, 70)}deg)`;
270 c.style.filter = d ? 'brightness(.5)' : 'none';
271 c.style.zIndex = 10 - Math.abs(d);
272 c.tabIndex = d ? -1 : 0;
273 });
274 document.getElementById('lcd').innerHTML = `<b>${esc(g.name).toUpperCase()}</b>${esc(b.name).toUpperCase()}${b.size ? ` · ${size(b.size)}` : ''}${g.producer ? `<br>BY ${esc(g.producer).toUpperCase()}` : ''}`;
275 document.getElementById('switches').innerHTML = g.builds.map((x, k) => `<button type="button" class="switch" data-build="${k}" aria-pressed="${k === bi[gi]}">${esc(x.name).toUpperCase()}</button>`).join('');
276 const save = document.getElementById('save');
277 // A page served elsewhere names where it downloads from.
278 save.href = url(b.save ?? b.file);
279 save.download = b.download ?? `${g.id}-${b.id}.html`;
280 }
281
282 /** Drop the front cart into the slot, light the LED, then boot it. */
283 function insert() {
284 const g = games[gi];
285 shelfEl.querySelector(`.cart[data-i="${gi}"]`).classList.add('loading');
286 shelfEl.querySelector('.led').classList.replace('on', 'go');
287 setTimeout(() => play(g, g.builds[bi[gi]]), 380);
288 }
289
290 shelfEl.addEventListener('click', (e) => {
291 const cart = e.target.closest('.cart');
292 const sw = e.target.closest('.switch');
293 if (cart) {
294 const i = Number(cart.dataset.i);
295 if (i === gi) insert();
296 else { gi = i; draw(); }
297 } else if (sw) {
298 bi[gi] = Number(sw.dataset.build);
299 draw();
300 } else if (e.target.closest('#go')) insert();
301 });
302
303 // Pad controls: left and right turn the carousel, Z and X flip the build, Enter powers on.
304 addEventListener('keydown', (e) => {
305 if (player.classList.contains('on') || !games.length) return;
306 if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
307 e.preventDefault();
308 gi = Math.min(games.length - 1, Math.max(0, gi + (e.key === 'ArrowLeft' ? -1 : 1)));
309 draw();
310 } else if (e.key === 'z' || e.key === 'x') {
311 const n = games[gi].builds.length;
312 bi[gi] = (bi[gi] + (e.key === 'x' ? 1 : n - 1)) % n;
313 draw();
314 } else if (e.key === 'Enter' && !e.target.closest?.('a, .switch, #go, .cart')) {
315 e.preventDefault();
316 insert();
317 }
318 });
319 draw();
320
321 // Links like #krazy-karts/alpha-1025 open a cartridge directly. Back returns to the shelf.
322 const route = () => {
323 const [gid, bid] = location.hash.slice(1).split('/');
324 const hit = gid && find(gid, bid);
325 if (hit) {
326 gi = games.indexOf(hit[0]);
327 bi[gi] = hit[0].builds.indexOf(hit[1]);
328 draw();
329 play(...hit, false);
330 } else stop();
331 };
332 addEventListener('popstate', route);
333 route();
334 </script>
335 </body>
336 </html>
src/arcade/host.ts added +256
@@ -0,0 +1,256 @@
1 /**
2 * The Arcade: one repository's display (`display/config.ts`), served at
3 * `arcade.<app domain>`: the display titled `arcade-builds` in a repository
4 * a site admin owns, the newest of several (`display/known.ts`); with none,
5 * the host answers 404. A display in the shelf layout is browser-arcade's page as
6 * it was — the chunky carousel, the console and the jbox boot tag — fed by
7 * the display's items (`shelf.ts`); any other layout is drawn by the
8 * forge, so the host's root sends a person there.
9 *
10 * The host answers on an app's kind of hostname, its own origin, for two
11 * reasons: a cart is a stranger's page, and must never run as the forge;
12 * and a cart keeps its saves in that origin's storage, which a sandboxed
13 * frame would refuse it. `arcade` is a reserved app name, so no app can
14 * stand in its place. Nobody is signed in on this origin: the display is
15 * read as a stranger reads it: a showcased demo from a private source is
16 * on it, published, by its opaque id and never its repository. It is also
17 * where every display's `file` demos play (`display/launch.ts`), with an
18 * Arcade display or not: a page in a public repository at its plain
19 * address, a private one with a grant, and a published one by its display
20 * and id (`displays/…`), plain when the display is public.
21 */
22
23 import { readFileSync } from "node:fs";
24 import type { App } from "../app.ts";
25 import { appHostSuffix } from "../apps/host.ts";
26 import { parseAppHost } from "../apps/proxy.ts";
27 import { appsRuntime, type AppsRuntime } from "../apps/runtime.ts";
28 import { canRead, getRepo, ownerInStanding, type Repo } from "../core/repos.ts";
29 import { arcadeRepoKnown, arcadeRepoOf } from "../display/known.ts";
30 import { readDisplay, type DisplayConfig } from "../display/config.ts";
31 import { displayItem, displayItems } from "../display/items.ts";
32 import { verifyCart } from "../display/launch.ts";
33 import { coverType, listBuildPins, readCover } from "../git/builds.ts";
34 import { repoDir } from "../git/repos.ts";
35 import type { Result } from "../kernel/result.ts";
36 import { pageFile, readArt, readCapture } from "./carts.ts";
37 import { COVER_JS } from "./cover.ts";
38 import { shelfOf, type Shelf } from "./shelf.ts";
39 import { snapshotFile } from "./snapshot.ts";
40
41 /** The app name the Arcade answers at. */
42 export const ARCADE_SLUG = "arcade";
43
44 /** Whether a request's `Host` is the Arcade's. */
45 export function isArcadeHost(host: string | null, domain: string): boolean {
46 if (host === null) return false;
47 const parsed = parseAppHost(host, domain);
48 return parsed !== undefined && parsed.slug === ARCADE_SLUG && parsed.env === "production" && !parsed.nested;
49 }
50
51 /** Where the Arcade is reached, as the runtime addresses an app. */
52 export function arcadeUrl(runtime: AppsRuntime): string {
53 const { scheme, publicPort, domain } = runtime.options;
54 const port =
55 publicPort === undefined || (scheme === "http" && publicPort === 80) || (scheme === "https" && publicPort === 443)
56 ? ""
57 : `:${publicPort}`;
58 return `${scheme}://${ARCADE_SLUG}${appHostSuffix(domain)}${port}`;
59 }
60
61 /** Whether the forge has an Arcade: apps run and a site admin's display is titled `arcade-builds`. */
62 export function arcadeOn(app: App): boolean {
63 return appsRuntime(app) !== undefined && arcadeRepoKnown(app) !== undefined;
64 }
65
66 /** The Arcade's address when the forge has one. */
67 export function arcadeHome(app: App): string | undefined {
68 const runtime = appsRuntime(app);
69 return runtime !== undefined && arcadeRepoKnown(app) !== undefined ? arcadeUrl(runtime) : undefined;
70 }
71
72 const file = (name: string): string => readFileSync(new URL(name, import.meta.url), "utf8");
73 let page: string | undefined;
74 let boot: string | undefined;
75 let template: Uint8Array | undefined;
76
77 /** The Arcade's page, with the house cover drawing spliced in. */
78 export function arcadePage(): string {
79 page ??= file("./arcade.html").replace("/*COVER_JS*/", () => COVER_JS);
80 return page;
81 }
82 export const bootScript = (): string => (boot ??= file("./jbox-spin.js"));
83 export const coverTemplateBytes = (): Uint8Array =>
84 (template ??= new Uint8Array(readFileSync(new URL("./cover-template.png", import.meta.url))));
85
86 const IMPORT_LINE = "import { jboxScale, playJboxSpin } from './boot/jbox-spin.js';";
87 const escapeText = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]!);
88
89 /**
90 * The shelf page for a display: its title, its producer, and — for a page
91 * that carries its shelf inside it — the data, with the boot tag inline.
92 */
93 export function shelfPage(o: { title: string; producer: string | undefined; data?: unknown; tabTitle?: string; bar?: string }): string {
94 let out = arcadePage();
95 // The forge's own bar above the shelf (a writer's Edit display), outside the arcade's frame.
96 if (o.bar !== undefined) out = out.replace('<body>\n <header id="topline">', () => `<body>\n ${o.bar}\n <header id="topline">`);
97 const topline = o.producer === undefined ? o.title : `${o.producer} • ${o.title}`;
98 out = out
99 .replace("<title>Browser Arcade</title>", () => `<title>${escapeText(o.tabTitle ?? o.title)}</title>`)
100 .replace('<header id="topline">JBOX • BROWSER ARCADE</header>', () => `<header id="topline">${escapeText(topline.toUpperCase())}</header>`)
101 .replace('<button id="back" type="button">◀ ARCADE</button>', () => `<button id="back" type="button">◀ ${escapeText(o.title.toUpperCase())}</button>`);
102 if (o.data === undefined) return out;
103 if (!out.includes(IMPORT_LINE)) throw new Error("the Arcade page no longer imports the boot tag as expected");
104 // The boot tag goes inline, as plain script in the page's module.
105 out = out.replace(IMPORT_LINE, () => bootScript().replace(/^export /gm, ""));
106 // "<" escaped, so a cart's own </script> cannot end this script early.
107 const data = JSON.stringify(o.data).replace(/</g, "\\u003c");
108 return out.replace('<script type="module">', () => `<script>window.__ARCADE__ = ${data};</script>\n <script type="module">`);
109 }
110
111 /** The page's own policy: its fonts, its inline module, carts in frames from itself. */
112 const PAGE_POLICY =
113 "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
114 "font-src https://fonts.gstatic.com; img-src 'self' data: blob:; frame-src 'self' blob:; media-src 'self' blob: data:; " +
115 "base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
116
117 const answer = (body: string | Uint8Array, type: string, extra: Record<string, string> = {}): Response =>
118 new Response(body, {
119 headers: {
120 "content-type": type,
121 "cache-control": "no-cache",
122 "x-content-type-options": "nosniff",
123 "referrer-policy": "no-referrer",
124 ...extra,
125 },
126 });
127
128 const missing = (): Response =>
129 new Response("not found", {
130 status: 404,
131 headers: { "content-type": "text/plain; charset=utf-8", "content-security-policy": "default-src 'none'", "x-content-type-options": "nosniff" },
132 });
133
134 export interface ArcadeDisplay {
135 readonly repo: Repo;
136 readonly config: Result<DisplayConfig, string>;
137 }
138
139 /**
140 * The Arcade's display, read as a stranger reads it; undefined when there is
141 * none to show. A site admin titling a display `arcade-builds` publishes it,
142 * as Showcase publishes a demo: a private display repository is served all
143 * the same, and its private sources stay unnamed.
144 */
145 export async function arcadeDisplay(app: App): Promise<ArcadeDisplay | undefined> {
146 const repo = await arcadeRepoOf(app);
147 if (repo === undefined) return undefined;
148 const config = await readDisplay(app, repo);
149 return config === undefined ? undefined : { repo, config };
150 }
151
152 /**
153 * A captured page any display may play: the pin at `oid` in that
154 * repository has its demo in the showcase and the page is captured, and
155 * the repository is public or the request carries a grant for this page.
156 */
157 async function servePlayable(app: App, path: string, grant: string | null): Promise<Response> {
158 const m = /^carts\/([^/]+)\/([^/]+)\/([0-9a-f]{40,64})\/([A-Za-z0-9._-]+)\.html$/.exec(path);
159 if (m === null) return missing();
160 const [, owner, name, oid, page] = m as unknown as [string, string, string, string, string];
161 const repo = getRepo(app.db, owner, name);
162 if (repo === undefined || !ownerInStanding(app.db, repo)) return missing();
163 if (!canRead(app.db, repo, undefined) && (grant === null || !verifyCart(app.config.dataDir, path, grant))) return missing();
164 const pins = await listBuildPins(repoDir(app.reposRoot, repo.ownerName, repo.name));
165 const pin = pins.find((p) => p.oid === oid && p.demo?.showcase === true && pageFile(p.demo.page) === page);
166 if (pin?.demo === undefined) return missing();
167 const html = readCapture(app.config.dataDir, repo, oid, pin.demo.page);
168 return html === undefined ? missing() : answer(html, "text/html; charset=utf-8", { "content-security-policy": cartAncestors(app) });
169 }
170
171 /**
172 * A published demo, by the display that shows it and its id there: its
173 * captured page, its cover or its page's picture. The display must be
174 * public or the Arcade's named display, or the request carry a grant for
175 * this path; the demo must be in the display's showcase now.
176 */
177 async function serveShown(app: App, path: string, grant: string | null): Promise<Response> {
178 const m = /^displays\/([^/]+)\/([^/]+)\/([A-Za-z0-9_-]{22})(\.html|\/cover\.png|\/art\.png)$/.exec(path);
179 if (m === null) return missing();
180 const [, owner, name, id, kind] = m as unknown as [string, string, string, string, string];
181 const display = getRepo(app.db, owner, name);
182 if (display === undefined || !ownerInStanding(app.db, display)) return missing();
183 const published = canRead(app.db, display, undefined) || (await arcadeRepoOf(app))?.id === display.id;
184 if (!published && (grant === null || !verifyCart(app.config.dataDir, path, grant))) return missing();
185 const config = await readDisplay(app, display);
186 if (config === undefined || !config.ok) return missing();
187 const item = await displayItem(app, display, config.value, id);
188 if (item === undefined) return missing();
189 const { repo, pin, demo } = item;
190 if (kind === "/cover.png") {
191 const bytes = demo.cover === undefined ? undefined : await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), demo.cover);
192 return bytes === undefined ? missing() : answer(bytes, coverType(bytes) ?? "application/octet-stream");
193 }
194 if (kind === "/art.png") {
195 const bytes = readArt(app.config.dataDir, repo, pin.oid, demo.page);
196 return bytes === undefined ? missing() : answer(bytes, "image/png");
197 }
198 const html = readCapture(app.config.dataDir, repo, pin.oid, demo.page);
199 return html === undefined ? missing() : answer(html, "text/html; charset=utf-8", { "content-security-policy": cartAncestors(app) });
200 }
201
202 /** A cart may frame only inside a display: this origin's or the forge's own. */
203 function cartAncestors(app: App): string {
204 const forge = appsRuntime(app)?.options.forgeUrl;
205 return `frame-ancestors 'self'${forge === undefined ? "" : ` ${new URL(forge).origin}`}`;
206 }
207
208 const errorPage = (message: string): Response =>
209 new Response(`<!doctype html><meta charset="utf-8"><title>Display</title><p>${escapeText(message)}</p>`, {
210 status: 422,
211 headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'", "x-content-type-options": "nosniff" },
212 });
213
214 /** Answer one request to the Arcade's host. */
215 export async function serveArcade(app: App, request: Request): Promise<Response> {
216 if (request.method !== "GET" && request.method !== "HEAD")
217 return new Response("method not allowed", { status: 405, headers: { allow: "GET, HEAD" } });
218 const url = new URL(request.url);
219 const path = decodeURIComponent(url.pathname.slice(1));
220 // Every display's carts play here, Arcade or not.
221 if (path.startsWith("carts/")) return servePlayable(app, path, url.searchParams.get("g"));
222 if (path.startsWith("displays/")) return serveShown(app, path, url.searchParams.get("g"));
223 const display = await arcadeDisplay(app);
224 if (display === undefined) return missing();
225 if (!display.config.ok) return errorPage(display.config.error);
226 const config = display.config.value;
227 // Grid and graph are drawn by the forge.
228 if (config.layout !== "shelf") {
229 const forge = appsRuntime(app)?.options.forgeUrl;
230 if (forge === undefined || (path !== "" && path !== "index.html")) return missing();
231 return new Response(null, { status: 303, headers: { location: `${forge.replace(/\/$/, "")}/${display.repo.ownerName}/${display.repo.name}/display` } });
232 }
233 if (path === "" || path === "index.html")
234 return answer(shelfPage({ title: config.title, producer: config.shelf.producer }), "text/html; charset=utf-8", { "content-security-policy": PAGE_POLICY });
235 if (path === "boot/jbox-spin.js") return answer(bootScript(), "text/javascript; charset=utf-8");
236 if (path === "cover-template.png") return answer(coverTemplateBytes(), "image/png");
237 const shelf: Shelf = shelfOf(await displayItems(app, display.repo, config, undefined), config.shelf.producer);
238 if (path === "games.json") return answer(JSON.stringify(shelf.games), "application/json");
239 // Export snapshot: the display's shelf, in one file that plays offline.
240 if (path === "snapshot.html") {
241 const made = await snapshotFile(app, config, shelf, new Date());
242 return answer(made.html, "text/html; charset=utf-8", { "content-disposition": `attachment; filename="${made.name}"` });
243 }
244 const entry = shelf.entries.get(path);
245 if (entry === undefined) return missing();
246 const { repo, pin, cart } = entry;
247 if (path.startsWith("labels/") && cart.cover !== undefined) {
248 const bytes = await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), cart.cover);
249 return bytes === undefined ? missing() : answer(bytes, coverType(bytes) ?? "application/octet-stream");
250 }
251 if (path.startsWith("art/")) {
252 const bytes = readArt(app.config.dataDir, repo, pin.oid, cart.page);
253 return bytes === undefined ? missing() : answer(bytes, "image/png");
254 }
255 return missing();
256 }
src/arcade/jbox-spin.js added +151
@@ -0,0 +1,151 @@
1 // The jbox boot tag: "L · jbox green, spin", confirmed in
2 // Arcade records/design/1026-loading-tags. A Game Boy green cube spins two and three
3 // quarter turns counterclockwise and settles with the J in front, lighting its groove in
4 // three beats to a rising power-on chord. Drawn at 160x144 and scaled by whole pixels.
5 //
6 // playJboxSpin(canvas) runs it once and resolves when the chord has rung out.
7
8 // The tag: a 160x144 buffer, ray-cast per pixel, scaled up by whole pixels.
9 const VW = 160, VH = 144, SC = 28;
10 let x, img, buf;
11 const mask = new Uint8Array(VW * VH);
12 const rgb = (h) => [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4), 16)];
13 const pack = ([r, g, b], k = 1) => 0xff000000 | Math.min(255, b * k) << 16 | Math.min(255, g * k) << 8 | Math.min(255, r * k);
14 // Game Boy greens. Faces pick a shade by how much light they catch.
15 const BG = pack(rgb("9bbc0f")), INK = pack(rgb("0f380f")), LIP = INK, LIT = pack(rgb("e0f8a0"));
16 const SHADES = [["8bac0f", "c4e050", "306230"], ["6a8c1c", "a0c030", "306230"], ["306230", "5a8a28", "1d4a1d"]].map((r) => r.map((h) => pack(rgb(h))));
17
18 // M's line: one unbroken groove from mid-face on the right, across the
19 // left face and the next side round, over the top and down into the J.
20 // Beat one lights the first two sides, beat two the third side and the
21 // top, beat three the J. Cells are [col, row].
22 const PATHS = [
23 ["z-", [[5, 5], [7, 5], [7, 2], [3, 2], [3, 7], [0, 7]]],
24 ["x-", [[9, 7], [6, 7], [6, 3], [2, 3], [2, 6], [0, 6]]],
25 ["z+", [[9, 6], [7, 6], [7, 8], [3, 8], [3, 4], [6, 4], [6, 0]]],
26 ["y+", [[3, 0], [3, 5], [7, 5], [7, 2], [9, 2]]],
27 ["x+", [[7, 0], [7, 8], [2, 8], [2, 5]]],
28 ];
29 const cells = {}, SEC = { "z-": 0, "x-": 0, "z+": 1, "y+": 1, "x+": 2 };
30 for (const [f, pts] of PATHS) for (let i = 1; i < pts.length; i++) {
31 let [a, b] = pts[i - 1]; const [ea, eb] = pts[i];
32 for (;;) { cells[f + a + "," + b] = 1; if (a === ea && b === eb) break; a += Math.sign(ea - a); b += Math.sign(eb - b); }
33 }
34 const on = (f, a, b) => a < 0 || b < 0 || f + a + "," + b in cells;
35
36 const PITCH = Math.PI / 6, SP = Math.sin(PITCH), CP = Math.cos(PITCH), L = [-0.5, 0.83, -0.17];
37 function toObj([a, b, z], yaw) {
38 const y1 = b * CP - z * SP, z1 = b * SP + z * CP, cs = Math.cos(-yaw), sn = Math.sin(-yaw);
39 return [a * cs - z1 * sn, y1, a * sn + z1 * cs];
40 }
41 const toWorld = ([a, b, z], yaw) => [a * Math.cos(yaw) - z * Math.sin(yaw), b, a * Math.sin(yaw) + z * Math.cos(yaw)];
42 function hitBox(o, d) {
43 let tn = -1e9, tf = 1e9, ax = 0, sg = 0;
44 for (let i = 0; i < 3; i++) {
45 if (Math.abs(d[i]) < 1e-9) { if (Math.abs(o[i]) > 1) return null; continue; }
46 let t1 = (-1 - o[i]) / d[i], t2 = (1 - o[i]) / d[i], s = -1;
47 if (t1 > t2) { const q = t1; t1 = t2; t2 = q; s = 1; }
48 if (t1 > tn) { tn = t1; ax = i; sg = s; }
49 if (t2 < tf) tf = t2;
50 if (tn > tf) return null;
51 }
52 return { ax, sg, p: [o[0] + d[0] * tn, o[1] + d[1] * tn, o[2] + d[2] * tn] };
53 }
54 function uv(ax, sg, p) {
55 const cl = (q) => Math.min(0.9999, Math.max(0, q));
56 if (ax === 1) return [cl((p[0] + 1) / 2), cl((1 - p[2]) / 2)];
57 return [cl(((ax === 0 ? p[2] * sg : -p[0] * sg) + 1) / 2), cl((1 - p[1]) / 2)];
58 }
59
60 // Shade row by light: [face, flashed face, empty groove].
61 function paint(f, u, v, b, lit, flash) {
62 const row = SHADES[b >= 0.95 ? 0 : b >= 0.7 ? 1 : 2], iu = u * 10 | 0, iv = v * 10 | 0;
63 if (!cells[f + iu + "," + iv]) return row[SEC[f] === flash ? 1 : 0];
64 if ((!on(f, iu, iv - 1) && v * 10 - iv < 0.3) || (!on(f, iu - 1, iv) && u * 10 - iu < 0.3)) return LIP;
65 return SEC[f] < lit ? LIT : row[2];
66 }
67 function render(yaw, rev, flash) {
68 buf.fill(BG); mask.fill(0);
69 const ex = toObj([1, 0, 0], yaw), ey = toObj([0, 1, 0], yaw), d = toObj([0, 0, 1], yaw), shade = {};
70 for (const [f, w] of [["x+", [1, 0, 0]], ["x-", [-1, 0, 0]], ["z+", [0, 0, 1]], ["z-", [0, 0, -1]], ["y+", [0, 1, 0]]]) {
71 const q = toWorld(w, yaw);
72 shade[f] = Math.min(1, Math.round((0.4 + 0.7 * Math.max(0, q[0] * L[0] + q[1] * L[1] + q[2] * L[2])) * 8) / 8);
73 }
74 for (let py = 0; py < VH; py++) for (let px = 0; px < VW; px++) {
75 const X = (px + 0.5 - VW / 2) / SC, Y = -(py + 0.5 - VH / 2) / SC, i = py * VW + px;
76 const h = hitBox([ex[0] * X + ey[0] * Y - d[0] * 10, ex[1] * X + ey[1] * Y - d[1] * 10, ex[2] * X + ey[2] * Y - d[2] * 10], d);
77 if (!h) continue;
78 const f = "xyz"[h.ax] + (h.sg > 0 ? "+" : "-"), [u, v] = uv(h.ax, h.sg, h.p);
79 mask[i] = 1; buf[i] = paint(f, u, v, shade[f] ?? 0.4, rev, flash);
80 }
81 for (let i = 0; i < mask.length; i++) if (!mask[i] && (mask[i - 1] || mask[i + 1] || mask[i - VW] || mask[i + VW])) buf[i] = INK;
82 x.putImageData(img, 0, 0);
83 }
84
85 // A gentle three quarter turn counterclockwise, eased in and out, that stops
86 // with the J face in front on the right. It settles before the first beat,
87 // so each beat lights a face that is in view.
88 const FPS = 20, SPIN = 0.9, BEATS = [0.95, 1.25, 1.55];
89 const yawAt = (t) => { const k = Math.min(t / SPIN, 1); return Math.PI / 4 + 1.5 * Math.PI * k * k * (3 - 2 * k); };
90 function frame(t) {
91 const lit = BEATS.filter((b) => t >= b).length;
92 render(yawAt(t), lit, lit && t < BEATS[lit - 1] + 0.1 ? lit - 1 : -1);
93 }
94
95 let A;
96 function tone(f, at, dur, gain, type = "triangle", f2) {
97 const o = A.createOscillator(), g = A.createGain(), s = A.currentTime + at;
98 o.type = type; o.frequency.setValueAtTime(f, s);
99 if (f2) o.frequency.exponentialRampToValueAtTime(f2, s + dur);
100 g.gain.setValueAtTime(0.001, s); g.gain.exponentialRampToValueAtTime(gain, s + 0.02);
101 g.gain.exponentialRampToValueAtTime(0.001, s + dur);
102 o.connect(g).connect(A.destination); o.start(s); o.stop(s + dur);
103 }
104 function sound() {
105 // I's power-on, the standard: a low hum that rises, then each beat stacks
106 // one more held note into a chord that rings out together.
107 tone(55, 0, 0.55, 0.24, "triangle", 110);
108 const END = BEATS[2] + 0.9;
109 tone(131, BEATS[0], END - BEATS[0], 0.1);
110 tone(196, BEATS[1], END - BEATS[1], 0.08);
111 tone(262, BEATS[2], END - BEATS[2], 0.07); tone(392, BEATS[2], END - BEATS[2], 0.025, "square");
112 }
113
114
115 /** Seconds from start until the chord has rung out. */
116 export const JBOX_SPIN_LENGTH = BEATS[2] + 0.9;
117
118 /**
119 * Play the tag once on `canvas`. Call it from a click or key press, so the browser lets
120 * the sound play. Resolves when the tag is done.
121 */
122 export function playJboxSpin(canvas, { sound: withSound = true } = {}) {
123 canvas.width = VW;
124 canvas.height = VH;
125 x = canvas.getContext("2d");
126 img = x.createImageData(VW, VH);
127 buf = new Uint32Array(img.data.buffer);
128 if (withSound) {
129 try {
130 A = A || new AudioContext();
131 A.resume();
132 sound();
133 } catch {}
134 }
135 const t0 = performance.now();
136 let last = -1;
137 return new Promise((done) => {
138 (function loop(now) {
139 const t = (now - t0) / 1000;
140 const step = Math.max(0, Math.floor(t * FPS));
141 if (step !== last) { last = step; frame(Math.min(step / FPS, SPIN + 1)); }
142 if (t >= JBOX_SPIN_LENGTH) return done();
143 requestAnimationFrame(loop);
144 })(t0);
145 });
146 }
147
148 /** Whole-pixel scale that fits the tag in a box. */
149 export function jboxScale(width, height) {
150 return Math.max(1, Math.floor(Math.min(width / VW, height / VH)));
151 }
src/arcade/snapshot.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * Export snapshot: a display's shelf in one offline HTML file, as
3 * browser-arcade's `bun run bundle` made it — the shelf, every cart and
4 * every cover inside the page, so it plays from disk with no server. Its
5 * one top line says it is a dated copy that will never update.
6 */
7
8 import type { App } from "../app.ts";
9 import type { DisplayConfig } from "../display/config.ts";
10 import { readCover } from "../git/builds.ts";
11 import { repoDir } from "../git/repos.ts";
12 import { readArt, readCapture } from "./carts.ts";
13 import { coverTemplateBytes, shelfPage } from "./host.ts";
14 import { slug, type Shelf } from "./shelf.ts";
15
16 /** `yyyymmdd` for a day. */
17 export const snapshotDate = (at: Date): string => at.toISOString().slice(0, 10).replaceAll("-", "");
18
19 /** The line across the top of a snapshot. */
20 export const snapshotLine = (date: string, producer: string | undefined): string =>
21 `${producer === undefined ? "" : `${producer.toUpperCase()} • `}snapshot ${date} | This is an HTML file that doesn't receive updates`;
22
23 const dataUrl = (bytes: Uint8Array): string => {
24 const type =
25 bytes[0] === 0xff ? "image/jpeg" : bytes[0] === 0x52 ? "image/webp" : "image/png";
26 return `data:${type};base64,${Buffer.from(bytes).toString("base64")}`;
27 };
28
29 /** The snapshot file for a display's shelf as it stands. */
30 export async function snapshotFile(
31 app: App,
32 config: Pick<DisplayConfig, "title" | "shelf">,
33 shelf: Shelf,
34 at: Date,
35 ): Promise<{ name: string; html: string }> {
36 const date = snapshotDate(at);
37 const dataDir = app.config.dataDir;
38 const carts: Record<string, string> = {};
39 const labels: Record<string, string> = { "cover-template.png": dataUrl(coverTemplateBytes()) };
40 for (const g of shelf.games)
41 for (const b of g.builds) {
42 const entry = shelf.entries.get(b.file);
43 if (entry === undefined) continue;
44 const { repo, pin, cart } = entry;
45 const html = readCapture(dataDir, repo, pin.oid, cart.page);
46 if (html !== undefined) carts[b.file] = new TextDecoder().decode(html);
47 if (b.label !== undefined && cart.cover !== undefined) {
48 const bytes = await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), cart.cover);
49 if (bytes !== undefined) labels[b.label] = dataUrl(bytes);
50 }
51 if (b.art !== undefined) {
52 const bytes = readArt(dataDir, repo, pin.oid, cart.page);
53 if (bytes !== undefined) labels[b.art] = dataUrl(bytes);
54 }
55 }
56 const html = shelfPage({
57 title: config.title,
58 tabTitle: `${config.title} · snapshot ${date}`,
59 producer: config.shelf.producer,
60 data: { snapshot: snapshotLine(date, config.shelf.producer), games: shelf.games, carts, labels },
61 });
62 return { name: `${slug(config.title)}-${date}.html`, html };
63 }
src/contract/openapi/routes/index.ts +1
@@ -335,6 +335,7 @@ export { route as putApiV1Front } from "./putApiV1Front.ts";
335335 export { route as putApiV1ReposOwnerNameAppEnvVar } from "./putApiV1ReposOwnerNameAppEnvVar.ts";
336336 export { route as putApiV1ReposOwnerNameAppMembers } from "./putApiV1ReposOwnerNameAppMembers.ts";
337337 export { route as putApiV1ReposOwnerNameCrewUsername } from "./putApiV1ReposOwnerNameCrewUsername.ts";
338 export { route as putApiV1ReposOwnerNameDisplayBuilds } from "./putApiV1ReposOwnerNameDisplayBuilds.ts";
338339 export { route as putApiV1ReposOwnerNameIssuesNumberAssignee } from "./putApiV1ReposOwnerNameIssuesNumberAssignee.ts";
339340 export { route as putApiV1ReposOwnerNameIssuesNumberLabels } from "./putApiV1ReposOwnerNameIssuesNumberLabels.ts";
340341 export { route as putApiV1ReposOwnerNameIssuesNumberPlan } from "./putApiV1ReposOwnerNameIssuesNumberPlan.ts";
src/contract/openapi/routes/putApiV1ReposOwnerNameDisplayBuilds.ts added +19
@@ -0,0 +1,19 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: `${REPO}/display/builds`,
6 summary: "Set a display's chosen builds and their order: `builds` in its display.json, a list of `owner/name:label`, written as one commit on the default branch; null removes it, so the display holds every showcased pin of its sources again. A build need not be showcased; one that is not is seen only by readers of its repository (rw scope, a person who writes the display repository); answers the commit and the list",
7 auth: true,
8 body: { builds: "array" },
9 refusals: {
10 forbidden: "403: not a person who writes the display repository (an agent is refused)",
11 not_found: "404: no such repository, or the caller cannot read it",
12 no_display: "404: the repository has no display.json on its default branch",
13 invalid_builds: "422: builds is not a list of distinct owner/name:label, or names more than 500",
14 invalid_display: "422: the display.json on the default branch does not parse",
15 moved: "409: the default branch moved while it was being written",
16 protected_branch: "409: the default branch is protected",
17 commit_failed: "422: git refused the commit",
18 },
19 };
src/display/launch.ts added +97
@@ -0,0 +1,97 @@
1 /**
2 * Where a display item opens. A `file` demo plays on the display origin,
3 * `arcade.<app domain>`, never on the forge's: a captured page is a
4 * stranger's code. A page in a repository anyone may read plays at its
5 * plain address; one in a repository only the viewer may read carries a
6 * short grant the forge signed for that page alone (`signCart`).
7 *
8 * An item the viewer cannot read the repository of (`open: false`) is
9 * reached only through its display, by its opaque id: on the forge under
10 * `/<owner>/<display>/display/demo/<id>/…`, and on the display origin at
11 * `displays/<owner>/<display>/<id>.html`. Showcase published it, so it
12 * plays without a grant when the display is public; a private display's
13 * page carries a grant for that path.
14 */
15
16 import { createHmac, timingSafeEqual } from "node:crypto";
17 import type { App } from "../app.ts";
18 import { appsRuntime } from "../apps/runtime.ts";
19 import { arcadeUrl } from "../arcade/host.ts";
20 import { cartFile, shownFile } from "../arcade/shelf.ts";
21 import { canRead, type Repo } from "../core/repos.ts";
22 import type { BuildPin } from "../git/builds.ts";
23 import { loadKey } from "../kernel/secret.ts";
24 import type { DisplayItem } from "./items.ts";
25
26 /** How long a grant to play a private page lasts. */
27 export const CART_GRANT_MS = 60 * 60 * 1000;
28
29 const mac = (dataDir: string, payload: string): string =>
30 createHmac("sha256", loadKey(dataDir)).update(`cart:${payload}`).digest("base64url");
31
32 /** A grant to play the capture at `path` (`carts/<owner>/<repo>/<sha>/<page>.html`) until it expires. */
33 export function signCart(dataDir: string, path: string, now = Date.now()): string {
34 const expires = now + CART_GRANT_MS;
35 return `${expires}.${mac(dataDir, `${path}:${expires}`)}`;
36 }
37
38 /** Whether `grant` vouches for `path` now. */
39 export function verifyCart(dataDir: string, path: string, grant: string, now = Date.now()): boolean {
40 const dot = grant.indexOf(".");
41 const expires = grant.slice(0, dot);
42 if (dot === -1 || !/^\d{1,15}$/.test(expires) || Number(expires) <= now) return false;
43 const a = Buffer.from(grant.slice(dot + 1));
44 const b = Buffer.from(mac(dataDir, `${path}:${expires}`));
45 return a.length === b.length && timingSafeEqual(a, b);
46 }
47
48 /** The display origin, or undefined where no apps run. */
49 export function displayOrigin(app: App): string | undefined {
50 const runtime = appsRuntime(app);
51 return runtime === undefined ? undefined : arcadeUrl(runtime);
52 }
53
54 type Hidden = Pick<DisplayItem, "display" | "id">;
55
56 /** An item's own routes on the forge, under its display. */
57 export const shownBase = (item: Hidden): string => `/${item.display.ownerName}/${item.display.name}/display/demo/${item.id}`;
58
59 /** Where a captured demo plays, or undefined where no apps run or nothing is captured. */
60 export function playUrl(app: App, item: DisplayItem): string | undefined {
61 if (item.captured === undefined) return undefined;
62 if (item.open) return pinPlayUrl(app, item.repo, item.pin.oid, item.demo.page);
63 const origin = displayOrigin(app);
64 if (origin === undefined) return undefined;
65 const path = shownFile(item);
66 const plain = canRead(app.db, item.display, undefined);
67 return `${origin}/${path}${plain ? "" : `?g=${signCart(app.config.dataDir, path)}`}`;
68 }
69
70 /**
71 * Where a commit's captured page plays on the display origin, read through
72 * its own repository: plain when anyone may read it, else with a grant.
73 * The caller says it is captured (`captureState`).
74 */
75 export function pinPlayUrl(app: App, repo: Repo, oid: string, page: string): string | undefined {
76 const origin = displayOrigin(app);
77 if (origin === undefined) return undefined;
78 const path = cartFile(repo, oid, page);
79 return `${origin}/${path}${canRead(app.db, repo, undefined) ? "" : `?g=${signCart(app.config.dataDir, path)}`}`;
80 }
81
82 /** Where a captured demo downloads, on the forge. */
83 export const downloadUrl = (item: DisplayItem): string =>
84 item.open
85 ? `/${item.repo.ownerName}/${item.repo.name}/builds/${item.pin.oid}/download?page=${encodeURIComponent(item.demo.page)}`
86 : `${shownBase(item)}/download`;
87
88 /** A pin's screenshots, on its repository. */
89 export const repoShotsUrl = (repo: Pick<Repo, "ownerName" | "name">, pin: Pick<BuildPin, "label">): string =>
90 `/${repo.ownerName}/${repo.name}/builds/${encodeURIComponent(pin.label)}/shots`;
91
92 /** A demo's screenshots, on the forge. */
93 export const shotsUrl = (item: DisplayItem): string => (item.open ? repoShotsUrl(item.repo, item.pin) : `${shownBase(item)}/shots`);
94
95 /** A demo's cover, or the picture of its captured page, on the forge. */
96 export const coverUrl = (item: DisplayItem): string =>
97 item.open ? `/${item.repo.ownerName}/${item.repo.name}/builds/${encodeURIComponent(item.pin.label)}/cover` : `${shownBase(item)}/cover`;
src/git/builds.ts +9
@@ -647,6 +647,15 @@ export async function storeCover(dir: string, label: string, bytes: Uint8Array):
647647 return kept.code === 0 ? ok(oid) : err("git_failed");
648648 }
649649
650 /** A stored cover's bytes, read only through a pin that names it. */
651 export async function readCover(dir: string, oid: string): Promise<Uint8Array | undefined> {
652 if (!isSafeOid(oid)) return undefined;
653 const kind = await runGitCapture(["cat-file", "-t", oid], { cwd: dir });
654 if (kind.code !== 0 || kind.stdout.trim() !== "blob") return undefined;
655 const bytes = await runGitRaw(["cat-file", "blob", oid], { cwd: dir });
656 return bytes.ok ? bytes.value : undefined;
657 }
658
650659 /**
651660 * Every pin, newest first, read in one `for-each-ref`; or the one `label`.
652661 * A pin's note is its notes file on `refs/forge/notes` when it has one,
src/http/api.ts +2
@@ -354,6 +354,7 @@ import { forgeOriginRoutes } from "./api/forge_origin.ts";
354354 import { userRoutes } from "./api/user.ts";
355355 import { appRoutes } from "./api/app.ts";
356356 import { buildRoutes } from "./api/builds.ts";
357 import { displayRoutes } from "./api/display.ts";
357358 import { buildShotRoutes } from "./api/build_shots.ts";
358359 import { buildCartRoutes } from "./api/build_cart.ts";
359360 import { iterationRoutes } from "./api/iterations.ts";
@@ -3637,6 +3638,7 @@ export function apiRoutes(router: Router<Handler>): void {
36373638
36383639 appRoutes(router);
36393640 buildRoutes(router);
3641 displayRoutes(router);
36403642 buildShotRoutes(router);
36413643 buildCartRoutes(router);
36423644 iterationRoutes(router);
src/http/api/display.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * A display over the API: its chosen builds, `builds` in display.json,
3 * written as one commit (`actions/displays.ts`). Needs the `rw` scope and a
4 * person who writes the display repository.
5 */
6
7 import { setDisplayBuilds } from "../../actions/displays.ts";
8 import { loadRepo } from "../api.ts";
9 import type { Handler } from "../context.ts";
10 import { body, json, notFound, requireScope, respondAccess } from "../respond.ts";
11 import type { Router } from "../router.ts";
12
13 const STATUS: Record<string, number> = { moved: 409, protected_branch: 409, no_display: 404 };
14
15 export function displayRoutes(router: Router<Handler>): void {
16 router.add("PUT", "/api/v1/repos/:owner/:name/display/builds", async (ctx) => {
17 const denied = requireScope(ctx, "rw");
18 if (denied) return denied;
19 const repo = loadRepo(ctx);
20 if (!repo) return notFound();
21 const input = await body(ctx.request);
22 const builds = input.builds;
23 if (builds !== null && (!Array.isArray(builds) || builds.some((b) => typeof b !== "string")))
24 return json({ error: "invalid_builds", message: "builds must be a list of owner/name:label, or null" }, 422);
25 const done = await setDisplayBuilds(ctx.app, ctx.auth.user, repo, builds as readonly string[] | null);
26 if (done.ok) return json(done.value);
27 const e = done.error;
28 if (typeof e === "string") return respondAccess(e, 422);
29 return json({ error: e.kind, ...("message" in e ? { message: e.message } : {}) }, STATUS[e.kind] ?? 422);
30 });
31 }
src/http/server.ts +22
@@ -184,6 +184,10 @@ import {
184184 branchesPage,
185185 } from "../web/pages/branches.ts";
186186 import { iterationsPage, noteSubmit } from "../web/pages/iterations.ts";
187 import { displayBuildsSubmit, displayCaptureSubmit, displayCreateSubmit, displayPage, displaySnapshot, displayTitleSubmit, shownCover, shownDownload, shownGallery, shownShot } from "../web/pages/display.ts";
188 import { displaysPage, newDisplayPage } from "../web/pages/displays.ts";
189 import { coverTemplate } from "../web/pages/cover_response.ts";
190 import { isArcadeHost, serveArcade } from "../arcade/host.ts";
187191 import { buildsPage, deletePinSubmit, newBuildPage, pinBuildSubmit, previewBuildSubmit } from "../web/pages/builds.ts";
188192 import { shotImage, shotsPage } from "../web/pages/build_shots.ts";
189193 import { cartArt, cartPage } from "../web/pages/build_cart.ts";
@@ -728,6 +732,10 @@ export function buildRouter(): Router<Handler> {
728732 router.add("GET", "/front", studioDoor);
729733 // Apps and people ranked by real numbers, narrowed in one line (#607).
730734 router.add("GET", "/explore", explorePage);
735 // Every display the viewer may read, New display's picker, and the house cover's frame (`web/pages/displays.ts`).
736 router.add("GET", "/displays", displaysPage);
737 router.add("GET", "/displays/new", newDisplayPage);
738 router.add("GET", "/-/cover-template.png", coverTemplate);
731739 router.add("POST", "/front", frontUpdate);
732740 router.add("POST", "/home/archive", homeArchive);
733741 router.add("POST", "/flow/keeper/answer", keeperAnswer);
@@ -1269,6 +1277,17 @@ export function buildRouter(): Router<Handler> {
12691277 router.add("GET", "/:owner/:name/builds/:label/cart", cartPage);
12701278 router.add("GET", "/:owner/:name/builds/:label/cart.png", cartArt);
12711279 router.add("GET", "/:owner/:name/iterations", iterationsPage);
1280 // A display: the demos display.json names, in its layout (`display/config.ts`).
1281 router.add("GET", "/:owner/:name/display", displayPage);
1282 router.add("GET", "/:owner/:name/display/snapshot.html", displaySnapshot);
1283 router.add("POST", "/:owner/:name/display/create", displayCreateSubmit);
1284 router.add("POST", "/:owner/:name/display/builds", displayBuildsSubmit);
1285 router.add("POST", "/:owner/:name/display/title", displayTitleSubmit);
1286 router.add("POST", "/:owner/:name/display/capture", displayCaptureSubmit);
1287 router.add("GET", "/:owner/:name/display/demo/:id/shots", shownGallery);
1288 router.add("GET", "/:owner/:name/display/demo/:id/shots/:file", shownShot);
1289 router.add("GET", "/:owner/:name/display/demo/:id/cover", shownCover);
1290 router.add("GET", "/:owner/:name/display/demo/:id/download", shownDownload);
12721291 router.add("POST", "/:owner/:name/builds", pinBuildSubmit);
12731292 router.add("POST", "/:owner/:name/builds/preview", previewBuildSubmit);
12741293 router.add("POST", "/:owner/:name/builds/:label/delete", deletePinSubmit);
@@ -2251,6 +2270,9 @@ export async function serve(app: App): Promise<Servers> {
22512270 // through, since it reads every `--<its host>` label as its own slug.
22522271 let ownUnknown = false;
22532272 if (runtime !== undefined) {
2273 // The Arcade's host is the forge's own shelf, never an app (`arcade/host.ts`).
2274 if (isArcadeHost(request.headers.get("host"), runtime.options.domain))
2275 return serveArcade(app, request);
22542276 const target = resolveAppHost(app, runtime.options.domain, request);
22552277 // A preview's headers are the app's business: what `proxyApp`
22562278 // carries back leaves exactly as the app wrote it, which is why the
src/web/pages/build_info.ts +2 −1
@@ -102,7 +102,7 @@ function notesOf(b: IterationBuild, back: string): Html {
102102 <p class="it-saved" data-saved role="status" hidden></p></section>`;
103103 }
104104
105 export function infoOf(ctx: Ctx, b: IterationBuild, forkOf: string | null, link: string, back: string): Html {
105 export function infoOf(ctx: Ctx, b: IterationBuild, forkOf: string | null, link: string, back: string, held?: readonly string[]): Html {
106106 const name = b.repo.split("/")[1] ?? b.repo;
107107 const lineage = [
108108 ...(forkOf === null ? [] : [`fork of ${forkOf}`]),
@@ -121,6 +121,7 @@ export function infoOf(ctx: Ctx, b: IterationBuild, forkOf: string | null, link:
121121 ${fact("Repository", html`<a href="/${b.repo}">${b.repo}</a>`)}
122122 ${fact("Lineage", lineage.length === 0 ? "first pin" : lineage.join(" · "))}
123123 ${fact("Pinned", `${b.by} · ${b.at.slice(0, 10)}`)}
124 ${held === undefined ? null : html`<dt>In</dt><dd data-in>${held.length === 0 ? "None" : held.join(", ")}</dd>`}
124125 ${fact("Plays", playsText(b))}
125126 </dl></section>
126127 ${notesOf(b, back)}
src/web/pages/build_shots.ts +8 −3
@@ -9,6 +9,7 @@ import { readBuildPin } from "../../git/builds.ts";
99 import { readShotBytes, readShots } from "../../git/shots.ts";
1010 import { repoDir } from "../../git/repos.ts";
1111 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
12 import type { Repo } from "../../core/repos.ts";
1213 import type { Ctx } from "../../http/context.ts";
1314 import { crumbsFor, loadRepo, notFoundPage, repoBase, repoHeader, repoPalette } from "../chrome.ts";
1415 import { html, type Html } from "../html.ts";
@@ -45,14 +46,18 @@ export async function shotsPage(ctx: Ctx): Promise<Response> {
4546 );
4647 }
4748
48 // GET /:owner/:name/builds/:label/shots/:file — one screenshot. Typed by
49 // its first bytes, never by its name, and never sniffed into anything else.
49 // GET /:owner/:name/builds/:label/shots/:file — one screenshot.
5050 export async function shotImage(ctx: Ctx): Promise<Response> {
5151 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
5252 const repo = loadRepo(ctx);
5353 if (!repo) return notFoundPage(ctx);
54 return shotResponse(ctx, repo, ctx.params.label ?? "", ctx.params.file ?? "");
55 }
56
57 /** One screenshot of a pin, as every route that serves one answers it. Typed by its first bytes, never by its name, and never sniffed into anything else. */
58 export async function shotResponse(ctx: Ctx, repo: Repo, label: string, file: string): Promise<Response> {
5459 const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
55 const shot = await timePhase(ctx.request, "read", () => readShotBytes(dir, ctx.params.label ?? "", ctx.params.file ?? ""));
60 const shot = await timePhase(ctx.request, "read", () => readShotBytes(dir, label, file));
5661 if (shot === undefined) return notFoundPage(ctx);
5762 // A name moves to another picture on a reorder; the blob it is does not.
5863 const etag = `"${shot.oid}"`;
src/web/pages/cover_response.ts added +31
@@ -0,0 +1,31 @@
1 /** A demo's picture: its uploaded cover, else the picture of its captured page. */
2
3 import { readArt } from "../../arcade/carts.ts";
4 import { coverTemplateBytes } from "../../arcade/host.ts";
5 import type { Repo } from "../../core/repos.ts";
6 import { coverType, readCover, type Demo } from "../../git/builds.ts";
7 import { repoDir } from "../../git/repos.ts";
8 import type { Ctx } from "../../http/context.ts";
9 import { notFoundPage } from "../chrome.ts";
10
11 /** The answer every route that serves a demo's cover gives. */
12 export async function coverResponse(ctx: Ctx, repo: Repo, oid: string, demo: Demo): Promise<Response> {
13 const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
14 const uploaded = demo.cover === undefined ? undefined : await readCover(dir, demo.cover);
15 const bytes = uploaded ?? readArt(ctx.app.config.dataDir, repo, oid, demo.page);
16 if (bytes === undefined) return notFoundPage(ctx);
17 return new Response(bytes, {
18 headers: {
19 "content-type": coverType(bytes) ?? "application/octet-stream",
20 "cache-control": "private, max-age=60",
21 "x-content-type-options": "nosniff",
22 },
23 });
24 }
25
26 // GET /-/cover-template.png — the house cover's frame, which a demo's cover is drawn in.
27 export function coverTemplate(_ctx: Ctx): Response {
28 return new Response(coverTemplateBytes(), {
29 headers: { "content-type": "image/png", "cache-control": "public, max-age=86400", "x-content-type-options": "nosniff" },
30 });
31 }
src/web/pages/display.ts added +720
@@ -0,0 +1,720 @@
1 /**
2 * A repository's display page, `/<owner>/<repo>/display`: the builds its
3 * `display.json` holds (`display/config.ts`), as whoever is looking may read
4 * them. The layout is records/design/1101-forgej-displays/LAYOUT.md
5 * (iteration E):
6 *
7 * - For a person who writes the display, a sidebar on the left: every
8 * pinned build of its sources that they read, grouped by fork, each
9 * ticked in or out of the display. A tick writes `builds` at once
10 * (`actions/displays.ts`, `setDisplayBuilds`) and its card shows or goes.
11 * The sidebar folds to an icon, and each fork to one row, "N of M".
12 * - A top row: the build's info panel, then its player, as on Iterations
13 * (`build_info.ts`).
14 * - Below, the display's builds as cards with their pictures; a click plays
15 * one in the top row, and a writer drags them to reorder.
16 * - A picker by the title opens any display the viewer reads. A writer's
17 * Edit beside the title opens it in place with Save and Cancel, and Save
18 * writes `title` (`setDisplayTitle`).
19 *
20 * A `shelf` display is drawn here like any other; its shelf look, the
21 * Arcade's carousel and jbox boot (`arcade/arcade.html`) from the same
22 * builds, shows on the Arcade host and at `/display?look=shelf`, whose bar
23 * leads its writer back to this page ("Edit display").
24 *
25 * A bad `display.json` shows its error here, never a guess.
26 *
27 * Showcase publishes the demo (`display/items.ts`): a viewer who reads the
28 * display sees every showcased demo on it. One whose repository the viewer
29 * cannot read shows its name and version alone — no repository, link, pin
30 * or commit — and its pictures, screenshots and captured page come through
31 * the display's own routes, `/<owner>/<display>/display/demo/<id>/…`, by
32 * its opaque id.
33 */
34
35 import { captureDisplay, saveDisplay, setDisplayBuilds, setDisplayTitle } from "../../actions/displays.ts";
36 import { shelfPage } from "../../arcade/host.ts";
37 import { shelfOf, slug } from "../../arcade/shelf.ts";
38 import { snapshotFile } from "../../arcade/snapshot.ts";
39 import { readCapture } from "../../arcade/carts.ts";
40 import { COVER_JS } from "../../arcade/cover.ts";
41 import { canRead, type Repo } from "../../core/repos.ts";
42 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
43 import { checkDisplay, demoKey, DISPLAY_FILE, readDisplay, type DisplayConfig } from "../../display/config.ts";
44 import { displayItem, displayItems, itemsOfKeys, keepUnnamed, sourceRepos, type DisplayItem } from "../../display/items.ts";
45 import { coverUrl, displayOrigin, downloadUrl, playUrl, shotsUrl } from "../../display/launch.ts";
46 import { displaySelections, selectionsHolding, writesDisplay, type DisplaySelection } from "../../display/selections.ts";
47 import { isCopiedPin, listBuildPins, type BuildPin } from "../../git/builds.ts";
48 import { repoDir } from "../../git/repos.ts";
49 import { readShots } from "../../git/shots.ts";
50 import type { Ctx } from "../../http/context.ts";
51 import { crumbsFor, loadRepo, notFoundPage, repoBase, repoHeader, repoPalette, signInFirst } from "../chrome.ts";
52 import { field, prefersJson, readForm } from "../form.ts";
53 import { html, raw, type Html } from "../html.ts";
54 import { flashTo, page } from "../layout.ts";
55 import { clearFlashCookie, readFlash, type Flash } from "../flash.ts";
56 import { btn, card, icon } from "../ui.ts";
57 import { buildOf, repoFactsOf, type IterationBuild, type RepoFacts } from "../../core/iterations.ts";
58 import { infoOf, INFO_CSS, INFO_JS, playerOf } from "./build_info.ts";
59 import { shotResponse } from "./build_shots.ts";
60 import { coverResponse } from "./cover_response.ts";
61
62 const DISPLAY_CSS = INFO_CSS + /* css */ `
63 .dp{display:grid;grid-template-columns:auto minmax(0,1fr);gap:0;margin-top:12px;min-height:70vh}
64 .dp[data-reader="1"]{grid-template-columns:minmax(0,1fr)}
65 .dp-side{width:260px;border-right:1px solid var(--border);padding:0 12px 12px 0;overflow:auto;transition:width .15s}
66 @media (prefers-reduced-motion: reduce){.dp-side{transition:none}}
67 .dp-side.dp-shut{width:40px;padding-right:6px}
68 .dp-side.dp-shut .dp-sec,.dp-side.dp-shut .dp-side-t{display:none}
69 .dp-side-h{display:flex;align-items:center;gap:8px;margin-bottom:8px}
70 .dp-side-h .btn{width:28px;height:28px;padding:0;justify-content:center}
71 .dp-side-t{font-weight:600;font-size:13px;min-width:0;overflow-wrap:anywhere}
72 .dp-sec{border-top:1px solid var(--border);padding:4px 0}
73 .dp-sec-h{display:flex;width:100%;gap:6px;background:none;border:0;color:inherit;font:inherit;font-size:13px;font-weight:600;padding:5px 0;cursor:pointer;text-align:left}
74 .dp-sec-h .dp-n{margin-left:auto;color:var(--muted-fg);font-weight:400;font-size:11.5px;white-space:nowrap}
75 .dp-sec-h .dp-caret{display:inline-block;width:1em;color:var(--muted-fg)}
76 .dp-sec.dp-fold .dp-rows{display:none}
77 .dp-rows label{display:flex;gap:8px;align-items:baseline;padding:3px 0 3px 4px;font-size:13px;cursor:pointer}
78 .dp-rows .dp-s{color:var(--muted-fg);font-size:11.5px;margin-left:auto}
79 .dp-main{padding:0 0 24px 20px;min-width:0}
80 .dp[data-reader="1"] .dp-main{padding-left:0}
81 .dp-title{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:12px}
82 .dp-title h2{margin:0;font-size:20px}
83 .dp-title .input{width:auto}
84 .dp-title .it-edit{margin-left:0}
85 .dp-ttl-ed{display:flex;gap:8px;align-items:center}
86 .dp-ttl-ed[hidden],.dp-title h2[hidden]{display:none}
87 .dp-said{color:var(--muted-fg);font-size:12.5px}
88 .dp-said.dp-bad{color:var(--danger)}
89 .dp-row1{display:grid;grid-template-columns:320px minmax(0,1fr);gap:14px;align-items:start}
90 .dp-cards{display:flex;flex-wrap:wrap;gap:12px;margin:14px 0 0;padding:0;list-style:none}
91 .dp-card{width:200px;background:var(--card);border:1px solid var(--border);border-radius:10px;overflow:hidden}
92 .dp-card[hidden]{display:none}
93 .dp-card[draggable="true"]{cursor:grab}
94 .dp-card.dp-sel{outline:2px solid var(--accent);outline-offset:2px}
95 .dp-card.dp-drag{opacity:.4}
96 .dp-play{display:block;width:100%;padding:0;border:0;background:none;color:inherit;font:inherit;text-align:left;cursor:pointer}
97 .dp-cover{display:block;width:100%;aspect-ratio:4/3;object-fit:cover;background:var(--bg)}
98 .dp-meta{display:flex;gap:6px;align-items:baseline;padding:7px 9px;font-size:13px;min-width:0}
99 .dp-meta b{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
100 .dp-meta .mono{color:var(--muted-fg);font-size:11.5px;white-space:nowrap}
101 .dp-none{color:var(--muted-fg);margin-top:14px}
102 .display-shots{list-style:none;margin:12px 0 0;padding:0;display:flex;flex-direction:column;gap:16px}
103 .display-shots img{display:block;max-width:100%;border:1px solid var(--border);border-radius:6px}
104 @media (max-width:900px){.dp{grid-template-columns:minmax(0,1fr)}.dp-side{width:auto;border-right:0;border-bottom:1px solid var(--border);padding:0 0 12px}.dp-side.dp-shut{width:auto}.dp-main{padding-left:0;padding-top:12px}.dp-row1{grid-template-columns:minmax(0,1fr)}}
105 `;
106
107 /** The picture a card leads with: the uploaded cover, else the captured page's, else the first screenshot, else the generated cover. */
108 async function coverOf(ctx: Ctx, item: DisplayItem): Promise<Html> {
109 const alt = `${item.demo.name} ${item.demo.version}`;
110 if (item.demo.cover !== undefined || item.art) return html`<img class="dp-cover" src="${coverUrl(item)}" alt="${alt}" loading="lazy" />`;
111 const shots = await readShots(repoDir(ctx.app.reposRoot, item.repo.ownerName, item.repo.name), item.pin.label);
112 const first = shots.items[0];
113 if (first !== undefined)
114 return html`<img class="dp-cover" src="${shotsUrl(item)}/${first.file}?v=${first.oid.slice(0, 12)}" alt="${alt}" loading="lazy" />`;
115 // The house cover the Shelf draws for a demo with no picture.
116 return html`<canvas class="dp-cover" width="512" height="512" role="img" aria-label="${alt}" data-name="${item.demo.name}" data-version="${item.demo.version}"></canvas>`;
117 }
118
119 /** An item's name on the page: its key to a reader of its repository, its opaque id to anyone else. */
120 const shownKey = (item: DisplayItem): string => (item.open ? item.key : `id:${item.id}`);
121
122 /** The player of a build whose repository the viewer cannot read: its published page, or why there is none. */
123 function hiddenPlayer(ctx: Ctx, item: DisplayItem): Html {
124 const title = html`<b>${item.demo.name} ${item.demo.version}</b>`;
125 const play = item.launch === "file" && item.captured !== undefined ? playUrl(ctx.app, item) : undefined;
126 if (play !== undefined)
127 return html`<div class="it-bar">${title}<span class="it-sp"><a class="btn" data-size="sm" href="${play}" target="_blank" rel="noopener noreferrer">Full screen</a><a class="btn" data-size="sm" href="${downloadUrl(item)}">Download</a></span></div>
128 <iframe class="it-frame" src="${play}" title="${item.demo.name} ${item.demo.version}" allow="fullscreen; autoplay; gamepad"></iframe>`;
129 if (item.launch === "shots")
130 return html`<div class="it-bar">${title}</div><div class="it-empty"><a class="btn" data-size="sm" href="${shotsUrl(item)}">Screenshots</a></div>`;
131 return html`<div class="it-bar">${title}</div><div class="it-empty">${item.launch === "file" ? "Not built yet" : "Preview needs app access"}</div>`;
132 }
133
134 /** The info panel of a build whose repository the viewer cannot read: its name and version, nothing of where it lives. */
135 const hiddenInfo = (item: DisplayItem): Html =>
136 html`<h3>${item.demo.name} ${item.demo.version}</h3><section data-section="build"><h4>Build</h4><p>Published on this display. Its repository is private.</p></section>`;
137
138 /** One build on the page: its card's item, and its player and panel when the viewer reads its repository. */
139 interface Shown {
140 readonly item: DisplayItem;
141 readonly build: IterationBuild | undefined;
142 readonly forkOf: string | null;
143 }
144
145 /** The pins of `repos` a person may tick, each once: a fork's copy of its parent's pin shows in the parent. */
146 async function poolOf(ctx: Ctx, repos: readonly Repo[]): Promise<{ repo: Repo; pins: BuildPin[] }[]> {
147 const pinsOf = new Map(
148 await Promise.all(repos.map(async (r) => [r.id, await listBuildPins(repoDir(ctx.app.reposRoot, r.ownerName, r.name))] as const)),
149 );
150 const groups = repos.map((repo) => {
151 const parentPins = repo.forkParentId === null ? undefined : pinsOf.get(repo.forkParentId);
152 const pins = (pinsOf.get(repo.id) ?? [])
153 .filter((p) => parentPins === undefined || !isCopiedPin(p, parentPins))
154 .sort((a, b) => (a.pinnedAt < b.pinnedAt ? -1 : 1));
155 return { repo, pins };
156 });
157 // Roots first, then each fork one step after the repository it was forked from; within a step, the oldest pin first.
158 const ids = new Set(repos.map((r) => r.id));
159 const byId = new Map(repos.map((r) => [r.id, r]));
160 const depth = (r: Repo): number => {
161 let d = 0;
162 for (let at: Repo | undefined = r; at !== undefined && at.forkParentId !== null && ids.has(at.forkParentId) && d < repos.length; at = byId.get(at.forkParentId)) d++;
163 return d;
164 };
165 const first = (g: { pins: BuildPin[] }) => g.pins[0]?.pinnedAt ?? "~";
166 return groups.sort((a, b) => depth(a.repo) - depth(b.repo) || (first(a) < first(b) ? -1 : first(a) > first(b) ? 1 : 0));
167 }
168
169 /** The display page's script: covers, the sidebar's ticks, a card's play, drag to reorder, the picker. */
170 const DISPLAY_JS = `
171 (function () {
172 ${COVER_JS}
173 var covers = document.querySelectorAll('canvas.dp-cover[data-name]');
174 if (covers.length) loadImage('/-/cover-template.png').then(function (tpl) {
175 Array.prototype.forEach.call(covers, function (c) { drawCover(c, null, tpl, c.getAttribute('data-name'), c.getAttribute('data-version')); });
176 });
177 ${INFO_JS}
178 var root = document.getElementById('dp');
179 if (!root) return;
180 var cards = document.getElementById('dp-cards'), side = document.getElementById('dp-side'), said = document.getElementById('dp-said');
181 var player = document.getElementById('it-player'), info = document.getElementById('it-info');
182 var shown = panel(player, info, null);
183 function setParam(k, v) {
184 var u = new URL(location.href);
185 if (v === null) u.searchParams.delete(k); else u.searchParams.set(k, v);
186 history.replaceState(null, '', u.pathname + u.search + u.hash);
187 }
188 var pick = document.getElementById('dp-pick');
189 if (pick) pick.addEventListener('change', function () { if (pick.value) location.assign(pick.value); });
190 // A writer's title: Edit opens it in place; Save writes it, Cancel puts it back.
191 var ttl = document.getElementById('dp-ttl'), ted = document.getElementById('dp-ttl-ed'), tbtn = document.getElementById('dp-ttl-edit');
192 if (ttl && ted && tbtn) {
193 var tsaid = document.getElementById('dp-said');
194 function editing(on) { ted.hidden = !on; ttl.hidden = on; tbtn.hidden = on; if (on) ted.querySelector('input[name="title"]').focus(); }
195 tbtn.addEventListener('click', function () { editing(true); });
196 ted.querySelector('[data-cancel-edit]').addEventListener('click', function () { ted.reset(); editing(false); });
197 ted.addEventListener('submit', function (ev) {
198 ev.preventDefault();
199 var go = ted.querySelector('button[type="submit"]'); go.disabled = true;
200 fetch(ted.action, { method: 'POST', body: new FormData(ted), headers: { accept: 'application/json' }, credentials: 'same-origin' }).then(function (r) {
201 return r.json().then(function (j) { return { ok: r.ok, j: j }; }, function () { return { ok: false, j: {} }; });
202 }).then(function (res) {
203 go.disabled = false;
204 if (!res.ok) { tsaid.textContent = res.j.message || 'Not saved.'; tsaid.classList.add('dp-bad'); return; }
205 ttl.textContent = res.j.title;
206 var input = ted.querySelector('input[name="title"]'); input.defaultValue = res.j.title; input.value = res.j.title;
207 var st = document.querySelector('.dp-side-t'); if (st) st.textContent = 'Builds in ' + res.j.title;
208 editing(false);
209 tsaid.textContent = 'Saved.'; tsaid.classList.remove('dp-bad');
210 }, function () { go.disabled = false; tsaid.textContent = 'Not saved: the forge did not answer.'; tsaid.classList.add('dp-bad'); });
211 });
212 }
213 function cardOf(key) { var all = cards.querySelectorAll('.dp-card'); for (var i = 0; i < all.length; i++) if (all[i].getAttribute('data-key') === key) return all[i]; return null; }
214 function play(card) {
215 var i = card.getAttribute('data-i');
216 var p = document.getElementById('dp-p-' + i), f = document.getElementById('dp-i-' + i);
217 if (!p || !f) return;
218 var sel = cards.querySelectorAll('.dp-sel'); for (var k = 0; k < sel.length; k++) sel[k].classList.remove('dp-sel');
219 card.classList.add('dp-sel');
220 setParam('build', card.getAttribute('data-key'));
221 shown.show(p, f);
222 }
223 cards.addEventListener('click', function (ev) { var c = ev.target.closest && ev.target.closest('.dp-card'); if (c) play(c); });
224 var asked = new URL(location.href).searchParams.get('build');
225 if (asked) { var c0 = cardOf(asked); if (c0 && !c0.hidden) play(c0); }
226 if (!side) return;
227 // A writer's changes: the shown cards, in order, written as the display's builds. One write at a time.
228 var writes = Promise.resolve(), url = root.getAttribute('data-builds');
229 function say(text, bad) { said.textContent = text; said.classList.toggle('dp-bad', !!bad); }
230 function save(undo) {
231 var keys = [];
232 Array.prototype.forEach.call(cards.querySelectorAll('.dp-card'), function (c) { if (!c.hidden) keys.push(c.getAttribute('data-key')); });
233 var none = document.getElementById('dp-none'); if (none) none.hidden = keys.length > 0;
234 say('Saving…');
235 writes = writes.then(function () {
236 var fd = new FormData(); keys.forEach(function (k) { fd.append('build', k); });
237 return fetch(url, { method: 'POST', body: fd, headers: { accept: 'application/json' }, credentials: 'same-origin' }).then(function (r) {
238 return r.json().then(function (j) { return { ok: r.ok, j: j }; }, function () { return { ok: false, j: {} }; });
239 }).then(function (res) {
240 if (res.ok) { say('Saved.'); return; }
241 undo(); say(res.j.message || 'Not saved.', true);
242 }, function () { undo(); say('Not saved: the forge did not answer.', true); });
243 });
244 }
245 function counts(sec) {
246 var boxes = sec.querySelectorAll('input[type="checkbox"]'), on = 0;
247 for (var i = 0; i < boxes.length; i++) if (boxes[i].checked) on++;
248 sec.querySelector('.dp-n').textContent = on + ' of ' + boxes.length;
249 }
250 side.addEventListener('click', function (ev) {
251 var t = ev.target; if (!t.closest) return;
252 if (t.closest('#dp-shut')) {
253 var shut = side.classList.toggle('dp-shut');
254 var b = document.getElementById('dp-shut');
255 b.setAttribute('aria-expanded', shut ? 'false' : 'true'); b.textContent = shut ? '\u27e9' : '\u27e8';
256 b.title = shut ? 'Show the build list' : 'Hide the build list';
257 return;
258 }
259 var h = t.closest('.dp-sec-h');
260 if (h) { var sec = h.parentNode, fold = sec.classList.toggle('dp-fold'); h.setAttribute('aria-expanded', fold ? 'false' : 'true'); h.querySelector('.dp-caret').textContent = fold ? '\u25b8' : '\u25be'; }
261 });
262 side.addEventListener('change', function (ev) {
263 var box = ev.target; if (!box.matches || !box.matches('input[data-key]')) return;
264 var c = cardOf(box.getAttribute('data-key')); if (!c) return;
265 var on = box.checked, sec = box.closest('.dp-sec');
266 if (on) { cards.appendChild(c); c.hidden = false; c.setAttribute('draggable', 'true'); }
267 else { c.hidden = true; if (c.classList.contains('dp-sel')) c.classList.remove('dp-sel'); }
268 counts(sec);
269 save(function () { box.checked = !on; c.hidden = on; counts(sec); });
270 });
271 // Drag a card left or right: it lands before the card it is dropped on, or after it past its middle.
272 var dragged = null, before = null;
273 cards.addEventListener('dragstart', function (ev) {
274 var c = ev.target.closest && ev.target.closest('.dp-card[draggable="true"]'); if (!c) return;
275 dragged = c; before = c.nextSibling; c.classList.add('dp-drag'); ev.dataTransfer.effectAllowed = 'move';
276 try { ev.dataTransfer.setData('text/plain', c.getAttribute('data-key')); } catch (e) {}
277 });
278 cards.addEventListener('dragover', function (ev) {
279 if (!dragged) return;
280 var over = ev.target.closest && ev.target.closest('.dp-card'); if (!over || over === dragged) { ev.preventDefault(); return; }
281 ev.preventDefault();
282 var r = over.getBoundingClientRect();
283 cards.insertBefore(dragged, ev.clientX > r.left + r.width / 2 ? over.nextSibling : over);
284 });
285 cards.addEventListener('drop', function (ev) { ev.preventDefault(); });
286 cards.addEventListener('dragend', function () {
287 if (!dragged) return;
288 var c = dragged, was = before; dragged = null; c.classList.remove('dp-drag');
289 if (c.nextSibling === was) return;
290 save(function () { cards.insertBefore(c, was); });
291 });
292 })();
293 `;
294
295 /** The display's error, where its page would be. */
296 function brokenPage(ctx: Ctx, repo: Repo, message: string): Response {
297 return page({
298 ctx,
299 title: `Display · ${repo.name}`,
300 crumbs: crumbsFor(repo),
301 palette: repoPalette(ctx, repo),
302 body: html`${repoHeader(ctx, repo, "none")}
303 <div class="mt">
304 ${card(html`<p class="mono">${message}</p>
305 <p class="muted small">Fix <a href="${repoBase(repo)}/blob/${repo.defaultBranch}/display.json">display.json</a> on ${repo.defaultBranch}.</p>`, {
306 head: html`${icon("alert")}<h2>Display failed</h2>`,
307 tone: "danger",
308 })}
309 </div>`,
310 });
311 }
312
313 /**
314 * The forge's bar above the shelf, outside the arcade's frame, for a
315 * signed-in viewer: the way back to Displays, and for a writer Edit display
316 * and the flash a save left. Styled from the arcade page's own colours.
317 */
318 function shelfBar(ctx: Ctx, repo: Repo, writer: boolean, flash: Flash | undefined): string {
319 return html`<nav id="display-writer" aria-label="Display" style="position:relative;z-index:6;display:flex;gap:12px;align-items:center;padding:8px 16px;background:var(--line);color:var(--ink)">
320 <a href="/displays" style="color:var(--sun)">← Displays</a>
321 ${flash === undefined ? null : html`<span role="status" style="color:var(--sun)">${flash.message}</span>`}
322 <span style="margin-left:auto"></span>
323 ${writer ? html`<a href="${repoBase(repo)}/display" style="color:var(--sun)">Edit display</a>` : null}
324 </nav>`.toString();
325 }
326
327 /** The forge's shelf page: the Arcade's page with its shelf inside, carts on the display origin. */
328 function shelfResponse(ctx: Ctx, repo: Repo, config: DisplayConfig, items: readonly DisplayItem[]): Response {
329 const origin = displayOrigin(ctx.app);
330 if (origin === undefined) return brokenPage(ctx, repo, "Play needs apps on this forge: the shelf plays carts at arcade.<app domain>.");
331 const shelf = shelfOf(items, config.shelf.producer);
332 const games = shelf.games.map((g) => ({
333 ...g,
334 builds: g.builds.map((b) => {
335 const item = shelf.entries.get(b.file)!.item;
336 return {
337 ...b,
338 file: playUrl(ctx.app, item) ?? b.file,
339 save: downloadUrl(item),
340 ...(b.label === undefined ? {} : { label: coverUrl(item) }),
341 ...(b.art === undefined ? {} : { art: coverUrl(item) }),
342 };
343 }),
344 }));
345 const writer = writesDisplay(ctx.app, repo, ctx.auth.user);
346 const flash = writer ? readFlash(ctx.request) : undefined;
347 const body = shelfPage({
348 title: config.title,
349 producer: config.shelf.producer,
350 data: { exportHref: `${repoBase(repo)}/display/snapshot.html`, games, carts: {}, labels: { "cover-template.png": "/-/cover-template.png" } },
351 ...(ctx.auth.user !== undefined ? { bar: shelfBar(ctx, repo, writer, flash) } : {}),
352 });
353 return new Response(body, {
354 headers: {
355 ...(flash === undefined ? {} : { "set-cookie": clearFlashCookie(ctx.url, ctx.app.config.url) }),
356 "content-type": "text/html; charset=utf-8",
357 "cache-control": "private, no-cache",
358 "content-security-policy":
359 "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline' https://fonts.googleapis.com; " +
360 `font-src https://fonts.gstatic.com; img-src 'self' data: blob:; frame-src ${origin}; media-src 'self' blob: data:; ` +
361 "base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
362 },
363 });
364 }
365
366 /** The repository and its display, as `ctx`'s viewer reads them; a Response when there is none to show. */
367 async function opened(ctx: Ctx): Promise<{ repo: Repo; config: DisplayConfig } | Response> {
368 const repo = loadRepo(ctx);
369 if (!repo) return notFoundPage(ctx);
370 const config = await timePhase(ctx.request, "read", () => readDisplay(ctx.app, repo));
371 if (config === undefined) {
372 await checkDisplay(ctx.app, repo);
373 return timePhase(ctx.request, "render", () => notFoundPage(ctx));
374 }
375 if (!config.ok) return timePhase(ctx.request, "render", () => brokenPage(ctx, repo, config.error));
376 return { repo, config: config.value };
377 }
378
379 /** Every display the viewer reads, for the picker by the title. */
380 function pickerOf(repo: Repo, displays: readonly DisplaySelection[]): Html {
381 const here = `${repo.ownerName}/${repo.name}`;
382 if (displays.length < 2) return html``;
383 return html`<select class="input" id="dp-pick" aria-label="Open a display">
384 ${displays.map((d) => html`<option value="${repoBase(d.repo)}/display" ${d.id === here ? raw("selected") : null}>${d.title}</option>`)}
385 </select>`;
386 }
387
388 /** A writer's Edit beside the title, and the form it opens in place: the title, Cancel and Save. */
389 const titleEditOf = (base: string, title: string): Html =>
390 html`<button type="button" class="it-edit" id="dp-ttl-edit">Edit</button>
391 <form class="dp-ttl-ed" id="dp-ttl-ed" method="post" action="${base}/display/title" hidden>
392 <input class="input" name="title" value="${title}" maxlength="80" required aria-label="Title" />
393 <button type="button" class="btn" data-size="sm" data-cancel-edit>Cancel</button>${btn("Save", { variant: "primary", size: "sm" })}
394 </form>`;
395
396 /** The display as iteration E draws it: sidebar for a writer, info and player, the cards. */
397 async function displayView(ctx: Ctx, repo: Repo, config: DisplayConfig): Promise<Response> {
398 const viewer = ctx.auth.user;
399 const writer = writesDisplay(ctx.app, repo, viewer);
400 const items = await timePhaseAsync(ctx.request, "items", () => displayItems(ctx.app, repo, config, viewer));
401 const onDisplay = new Set(items.map((i) => i.key));
402 // A writer's pool: every pin of the sources they read, grouped by fork.
403 const pool = writer
404 ? await timePhaseAsync(ctx.request, "pool", () =>
405 poolOf(
406 ctx,
407 sourceRepos(ctx.app, config).filter((r) => canRead(ctx.app.db, r, viewer)),
408 ),
409 )
410 : [];
411 const offKeys = pool.flatMap(({ repo: r, pins }) => pins.map((p) => demoKey(r.ownerName, r.name, p.label))).filter((k) => !onDisplay.has(k));
412 const off = offKeys.length === 0 ? [] : await itemsOfKeys(ctx.app, repo, config, offKeys, viewer);
413 const displays = await timePhaseAsync(ctx.request, "selections", () => displaySelections(ctx.app, viewer));
414
415 // Each card's player and panel, read once per repository.
416 const facts = new Map<string, RepoFacts>();
417 const shownOf = async (item: DisplayItem): Promise<Shown> => {
418 if (!item.open) return { item, build: undefined, forkOf: null };
419 let rf = facts.get(item.repo.id);
420 if (rf === undefined) {
421 rf = await repoFactsOf(ctx, item.repo, false);
422 facts.set(item.repo.id, rf);
423 }
424 const parent = item.pin.parent === undefined ? null : item.pin.parent.includes(":") ? item.pin.parent : `${rf.name}:${item.pin.parent}`;
425 const edge = item.pin.parent === undefined ? null : item.pin.parent.includes(":") ? "concept" : "git";
426 const up = item.repo.forkParentId === null ? undefined : pool.find((g) => g.repo.id === item.repo.forkParentId)?.repo;
427 return { item, build: await buildOf(ctx, rf, item.pin, parent, edge), forkOf: up === undefined ? null : `${up.ownerName}/${up.name}` };
428 };
429 const all = await timePhaseAsync(ctx.request, "builds", async () => {
430 const out: Shown[] = [];
431 for (const item of [...items, ...off]) out.push(await shownOf(item));
432 return out;
433 });
434 const indexOf = new Map(all.map((s, i) => [s.item.key, i]));
435 const base = repoBase(repo);
436 const back = (key: string) => `${base}/display?build=${encodeURIComponent(key)}`;
437 const link = (key: string) => `${ctx.url.origin}${back(key)}`;
438
439 const cardOf = async (s: Shown, hidden: boolean): Promise<Html> => {
440 const { item } = s;
441 const key = shownKey(item);
442 const name = item.open ? item.repo.name : item.demo.name;
443 const version = item.open ? item.pin.label : item.demo.version;
444 return html`<li class="dp-card" data-key="${key}" data-i="${String(indexOf.get(item.key)!)}" ${writer && !hidden ? raw('draggable="true"') : null} ${hidden ? raw("hidden") : null}>
445 <button type="button" class="dp-play" aria-label="Play ${name} ${version}">${await coverOf(ctx, item)}
446 <span class="dp-meta"><b>${name}</b><span class="mono">${version}</span></span></button>
447 </li>`;
448 };
449 const cardsHtml: Html[] = [];
450 for (const s of all) cardsHtml.push(await cardOf(s, !onDisplay.has(s.item.key)));
451
452 // The sidebar's names: a fork's repository name, its owner joining only on a clash.
453 const clash = (n: string) => pool.filter((g) => g.repo.name === n).length > 1;
454 const sidebar = writer
455 ? html`<aside class="dp-side" id="dp-side" aria-label="Builds">
456 <div class="dp-side-h">
457 <button type="button" class="btn" data-size="sm" id="dp-shut" aria-expanded="true" aria-controls="dp-side" title="Hide the build list">⟨</button>
458 <span class="dp-side-t">Builds in ${config.title}</span>
459 </div>
460 ${pool.length === 0 || pool.every((g) => g.pins.length === 0)
461 ? html`<p class="dp-sec muted small">No pinned builds in this display's sources.</p>`
462 : pool
463 .filter((g) => g.pins.length > 0)
464 .map((g) => {
465 const keys = g.pins.map((p) => demoKey(g.repo.ownerName, g.repo.name, p.label));
466 const on = keys.filter((k) => onDisplay.has(k)).length;
467 return html`<div class="dp-sec" data-repo="${g.repo.ownerName}/${g.repo.name}">
468 <button type="button" class="dp-sec-h" aria-expanded="true"><span class="dp-caret">▾</span><span class="mono">${clash(g.repo.name) ? `${g.repo.ownerName}/${g.repo.name}` : g.repo.name}</span><span class="dp-n">${String(on)} of ${String(keys.length)}</span></button>
469 <div class="dp-rows">${g.pins.map((p, k) => {
470 const b = all[indexOf.get(keys[k]!) ?? -1]?.build;
471 const it = all[indexOf.get(keys[k]!) ?? -1]?.item;
472 const unbuilt = b !== undefined && it !== undefined && it.launch === "file" && it.captured === undefined;
473 return html`<label><input type="checkbox" data-key="${keys[k]!}" ${onDisplay.has(keys[k]!) ? raw("checked") : null} /><span class="mono">${p.label}</span>${unbuilt ? html`<span class="dp-s">not built</span>` : null}</label>`;
474 })}</div>
475 </div>`;
476 })}
477 </aside>`
478 : null;
479
480 const body = html`${repoHeader(ctx, repo, "none")}
481 <div class="dp" id="dp" data-reader="${writer ? "0" : "1"}" ${writer ? html`data-builds="${base}/display/builds"` : null}>
482 ${sidebar}
483 <div class="dp-main">
484 <div class="dp-title"><h2 id="dp-ttl">${config.title}</h2>${writer ? titleEditOf(base, config.title) : null}${pickerOf(repo, displays)}${writer ? html`<span class="dp-said" id="dp-said" role="status">Drag builds to reorder</span>` : null}</div>
485 <div class="dp-row1">
486 <aside class="it-info" id="it-info"><h3>Build info</h3><section><p>Pick a build below${writer ? " or on the left" : ""}.</p></section></aside>
487 <div class="it-player" id="it-player" aria-live="polite"><div class="it-empty">Click a build to play it here.</div></div>
488 </div>
489 <ul class="dp-cards" id="dp-cards" aria-label="Builds on this display">${cardsHtml}</ul>
490 <p class="dp-none" id="dp-none" ${items.length > 0 ? raw("hidden") : null}>No builds on this display${writer ? ". Tick builds on the left to add them." : ""}</p>
491 </div>
492 </div>
493 ${all.map((s, i) =>
494 s.build === undefined
495 ? html`<template id="dp-p-${String(i)}">${hiddenPlayer(ctx, s.item)}</template><template id="dp-i-${String(i)}">${hiddenInfo(s.item)}</template>`
496 : html`<template id="dp-p-${String(i)}">${playerOf(s.build)}</template><template id="dp-i-${String(i)}">${infoOf(ctx, s.build, s.forkOf, link(s.build.key), back(s.build.key), selectionsHolding(s.build.key, s.item.demo.showcase === true, displays))}</template>`,
497 )}`;
498 return timePhase(ctx.request, "render", () =>
499 page({
500 ctx,
501 title: `${config.title} · ${repo.name}`,
502 crumbs: crumbsFor(repo),
503 palette: repoPalette(ctx, repo),
504 body,
505 styleCss: DISPLAY_CSS,
506 scriptJs: DISPLAY_JS,
507 frameSrc: displayOrigin(ctx.app),
508 wide: true,
509 }),
510 );
511 }
512
513 // GET /:owner/:name/display — the display page (round 1101 E) for every layout. The
514 // shelf look is the Arcade's own page; ?look=shelf shows it here too.
515 export async function displayPage(ctx: Ctx): Promise<Response> {
516 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
517 const got = await opened(ctx);
518 if (got instanceof Response) return got;
519 const { repo, config } = got;
520 void checkDisplay(ctx.app, repo);
521 if (config.layout === "shelf" && ctx.url.searchParams.get("look") === "shelf") {
522 const items = await timePhase(ctx.request, "items", () => displayItems(ctx.app, repo, config, ctx.auth.user));
523 return timePhase(ctx.request, "render", () => shelfResponse(ctx, repo, config, items));
524 }
525 return displayView(ctx, repo, config);
526 }
527
528 const BUILDS_ERRORS: Record<string, string> = {
529 moved: "Not saved: the display changed meanwhile. Reload and try again.",
530 protected_branch: "Not saved: the default branch is protected.",
531 invalid_builds: "Not saved: a display holds at most 500 distinct builds.",
532 invalid_display: "Not saved: display.json does not parse. Fix it first.",
533 no_display: "Not saved: this repository has no display.json.",
534 };
535
536 // POST /:owner/:name/display/builds — a writer's new selection from the page, in order; builds they cannot name keep their place.
537 export async function displayBuildsSubmit(ctx: Ctx): Promise<Response> {
538 const repo = loadRepo(ctx);
539 if (!repo) return notFoundPage(ctx);
540 if (!ctx.auth.user) return signInFirst(ctx);
541 const form = await readForm(ctx, "rw");
542 if (form instanceof Response) return form;
543 const read = await readDisplay(ctx.app, repo);
544 if (read === undefined || !read.ok) {
545 const kind = read === undefined ? "no_display" : "invalid_display";
546 return Response.json({ error: kind, message: BUILDS_ERRORS[kind] }, { status: 422 });
547 }
548 const named = form.getAll("build").filter((v): v is string => typeof v === "string");
549 const builds = await keepUnnamed(ctx.app, read.value, named, ctx.auth.user);
550 const done = await setDisplayBuilds(ctx.app, ctx.auth.user, repo, builds);
551 if (!done.ok) {
552 const e = done.error;
553 if (e === "not_found" || e === "unauthorized" || e === "forbidden") return notFoundPage(ctx);
554 return Response.json({ error: e.kind, message: BUILDS_ERRORS[e.kind] ?? "Not saved: git refused the change." }, { status: e.kind === "moved" ? 409 : 422 });
555 }
556 return Response.json({ commit: done.value.commit, count: named.length });
557 }
558
559 const TITLE_ERRORS: Record<string, string> = {
560 moved: "Not saved: the display changed meanwhile. Reload and try again.",
561 protected_branch: "Not saved: the default branch is protected.",
562 no_display: "Not saved: this repository has no display.json.",
563 };
564
565 // POST /:owner/:name/display/title — a writer's new title for the display, as one commit.
566 export async function displayTitleSubmit(ctx: Ctx): Promise<Response> {
567 const repo = loadRepo(ctx);
568 if (!repo) return notFoundPage(ctx);
569 if (!ctx.auth.user) return signInFirst(ctx);
570 const form = await readForm(ctx, "rw");
571 if (form instanceof Response) return form;
572 const to = `${repoBase(repo)}/display`;
573 const done = await setDisplayTitle(ctx.app, ctx.auth.user, repo, field(form, "title").trim());
574 if (!done.ok) {
575 const e = done.error;
576 if (e === "not_found" || e === "unauthorized" || e === "forbidden") return notFoundPage(ctx);
577 const message = TITLE_ERRORS[e.kind] ?? `Not saved: ${"message" in e ? e.message : "git refused the change"}.`;
578 if (prefersJson(ctx)) return Response.json({ error: e.kind, message }, { status: e.kind === "moved" ? 409 : 422 });
579 return flashTo(ctx, to, { tone: "danger", message });
580 }
581 if (prefersJson(ctx)) return Response.json({ commit: done.value.commit, title: done.value.title });
582 return flashTo(ctx, to, { message: "Saved." });
583 }
584
585 // POST /:owner/:name/display/create — New display: display.json naming the owner's repositories as its source, then the page.
586 export async function displayCreateSubmit(ctx: Ctx): Promise<Response> {
587 const repo = loadRepo(ctx);
588 if (!repo) return notFoundPage(ctx);
589 if (!ctx.auth.user) return signInFirst(ctx);
590 const form = await readForm(ctx, "rw");
591 if (form instanceof Response) return form;
592 const text = `${JSON.stringify({ title: repo.name, layout: "grid", sources: [repo.ownerName] }, null, 2)}\n`;
593 if ((await readDisplay(ctx.app, repo)) !== undefined) return flashTo(ctx, `${repoBase(repo)}/display`, { tone: "attn", message: `${repo.name} already has a display.` });
594 const saved = await saveDisplay(ctx.app, ctx.auth.user, repo, text, undefined);
595 if (!saved.ok) {
596 const e = saved.error;
597 if (e === "not_found" || e === "unauthorized" || e === "forbidden") return notFoundPage(ctx);
598 return flashTo(ctx, "/displays/new", {
599 tone: "danger",
600 message: e.kind === "protected_branch" ? `Create failed: ${repo.defaultBranch} is protected.` : `Create failed: ${"message" in e ? e.message : e.kind}.`,
601 });
602 }
603 return flashTo(ctx, `${repoBase(repo)}/display`, { message: `Created ${DISPLAY_FILE} on ${repo.defaultBranch} at ${saved.value.commit.slice(0, 7)}.` });
604 }
605
606 // POST /:owner/:name/display/capture — capture every showcased file demo of the display that has none.
607 export async function displayCaptureSubmit(ctx: Ctx): Promise<Response> {
608 const repo = loadRepo(ctx);
609 if (!repo) return notFoundPage(ctx);
610 if (!ctx.auth.user) return signInFirst(ctx);
611 const form = await readForm(ctx, "rw");
612 if (form instanceof Response) return form;
613 const done = await captureDisplay(ctx.app, ctx.auth.user, repo);
614 const to = `${repoBase(repo)}/display`;
615 if (!done.ok) {
616 if (done.error === "not_found" || done.error === "unauthorized" || done.error === "forbidden") return notFoundPage(ctx);
617 return flashTo(ctx, to, { tone: "danger", message: `Capture failed: fix ${DISPLAY_FILE} first.` });
618 }
619 const n = done.value.started.length;
620 return flashTo(ctx, to, { message: `Started ${String(n)} ${n === 1 ? "capture" : "captures"}.` });
621 }
622
623 // GET /:owner/:name/display/snapshot.html — the display's playable demos in one offline file.
624 export async function displaySnapshot(ctx: Ctx): Promise<Response> {
625 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
626 const got = await opened(ctx);
627 if (got instanceof Response) return got;
628 const items = await timePhase(ctx.request, "items", () => displayItems(ctx.app, got.repo, got.config, ctx.auth.user));
629 const shelf = shelfOf(items, got.config.shelf.producer);
630 const made = await timePhase(ctx.request, "render", () => snapshotFile(ctx.app, got.config, shelf, new Date()));
631 return new Response(made.html, {
632 headers: {
633 "content-type": "text/html; charset=utf-8",
634 "content-disposition": `attachment; filename="${made.name}"`,
635 "cache-control": "private, no-cache",
636 "content-security-policy": "sandbox",
637 },
638 });
639 }
640
641 /** A screenshots page: the display's chrome when shown through a display, the repository's own otherwise. */
642 function galleryPage(
643 ctx: Ctx,
644 repo: Repo,
645 name: string,
646 sub: Html,
647 base: string,
648 items: readonly { file: string; oid: string; caption: string }[],
649 ): Response {
650 const shots = { items };
651 return page({
652 ctx,
653 title: `Screenshots · ${name}`,
654 crumbs: crumbsFor(repo),
655 palette: repoPalette(ctx, repo),
656 styleCss: DISPLAY_CSS,
657 body: html`${repoHeader(ctx, repo, "none")}
658 <div class="page-head mt"><h2>Screenshots · ${name}</h2>${sub}</div>
659 ${shots.items.length === 0
660 ? html`<p class="muted">No screenshots</p>`
661 : html`<ol class="display-shots">
662 ${shots.items.map(
663 (s, i) => html`<li>
664 <img src="${base}/${s.file}?v=${s.oid.slice(0, 12)}" alt="${s.caption === "" ? `Screenshot ${String(i + 1)}` : s.caption}" loading="lazy" />
665 ${s.caption === "" ? null : html`<p class="small">${s.caption}</p>`}
666 </li>`,
667 )}
668 </ol>`}`,
669 });
670 }
671
672 /** The display and the published demo its id names there; a 404 when there is none — unshowcased, gone, or another display's id. */
673 async function shownItem(ctx: Ctx): Promise<{ repo: Repo; item: DisplayItem } | Response> {
674 const got = await opened(ctx);
675 if (got instanceof Response) return got;
676 const item = await displayItem(ctx.app, got.repo, got.config, ctx.params.id ?? "");
677 return item === undefined ? notFoundPage(ctx) : { repo: got.repo, item };
678 }
679
680 // GET /:owner/:name/display/demo/:id/shots — a published demo's screenshots, through its display.
681 export async function shownGallery(ctx: Ctx): Promise<Response> {
682 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
683 const got = await shownItem(ctx);
684 if (got instanceof Response) return got;
685 const { repo, item } = got;
686 const shots = await readShots(repoDir(ctx.app.reposRoot, item.repo.ownerName, item.repo.name), item.pin.label);
687 return galleryPage(ctx, repo, `${item.demo.name} ${item.demo.version}`, html`<a class="small" href="${repoBase(repo)}/display">Back to the display</a>`, shotsUrl({ ...item, open: false }), shots.items);
688 }
689
690 // GET /:owner/:name/display/demo/:id/shots/:file — one of its screenshots.
691 export async function shownShot(ctx: Ctx): Promise<Response> {
692 const got = await shownItem(ctx);
693 if (got instanceof Response) return got;
694 return shotResponse(ctx, got.item.repo, got.item.pin.label, ctx.params.file ?? "");
695 }
696
697 // GET /:owner/:name/display/demo/:id/cover — its cover, or the picture of its captured page.
698 export async function shownCover(ctx: Ctx): Promise<Response> {
699 const got = await shownItem(ctx);
700 if (got instanceof Response) return got;
701 return coverResponse(ctx, got.item.repo, got.item.pin.oid, got.item.demo);
702 }
703
704 // GET /:owner/:name/display/demo/:id/download — its captured page, as a file. Never a running build's.
705 export async function shownDownload(ctx: Ctx): Promise<Response> {
706 const got = await shownItem(ctx);
707 if (got instanceof Response) return got;
708 const { item } = got;
709 const kept = readCapture(ctx.app.config.dataDir, item.repo, item.pin.oid, item.demo.page);
710 if (kept === undefined) return notFoundPage(ctx);
711 return new Response(kept, {
712 headers: {
713 "content-type": "application/octet-stream",
714 "content-disposition": `attachment; filename="${slug(item.demo.name)}-${slug(item.demo.version)}.html"`,
715 "x-content-type-options": "nosniff",
716 "content-security-policy": "sandbox",
717 "cache-control": "private, no-cache",
718 },
719 });
720 }
src/web/pages/displays.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * `/displays`: every display the viewer may read — each repository with a
3 * `display.json` on its default branch (`display/config.ts`) — one row
4 * each: title, layout, repository, and how many showcased demos it shows.
5 * A row opens the display. New display asks for a repository the person
6 * writes that has no display yet (`/displays/new`), writes its
7 * `display.json` and opens the display, where its builds are ticked.
8 *
9 * Both read through the display cache (`display/known.ts`), so a warm page
10 * reads no git.
11 */
12
13 import { listReposWritableTo } from "../../core/repos.ts";
14 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
15 import { listedDisplays, withoutDisplay } from "../../display/known.ts";
16 import type { Ctx } from "../../http/context.ts";
17 import { pageHead, repoBase, signInFirst } from "../chrome.ts";
18 import { html } from "../html.ts";
19 import { page } from "../layout.ts";
20 import { btn, empty, listCard, row } from "../ui.ts";
21
22 const LAYOUT_WORD = { shelf: "Shelf", grid: "Grid", graph: "Graph" } as const;
23
24 /** Whether the viewer is a person who may make a display: signed in, not an agent. */
25 const maker = (ctx: Ctx): boolean => ctx.auth.user !== undefined && ctx.auth.user.kind !== "agent";
26
27 // GET /displays — every display the viewer may read.
28 export async function displaysPage(ctx: Ctx): Promise<Response> {
29 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
30 const rows = await timePhaseAsync(ctx.request, "displays", () => listedDisplays(ctx.app, ctx.auth.user));
31 return timePhase(ctx.request, "render", () =>
32 page({
33 ctx,
34 title: "Displays",
35 body: html`${pageHead("Displays", maker(ctx) ? { actions: btn("New display", { href: "/displays/new", variant: "primary", size: "sm", icon: "plus" }) } : {})}
36 ${rows.length === 0
37 ? empty({ icon: "pin", title: "No displays" })
38 : html`<div class="table-scroll" role="region" tabindex="0" aria-label="Displays">
39 <table class="table" data-dense data-by="displays">
40 <thead>
41 <tr>
42 <th scope="col">Title</th>
43 <th scope="col">Layout</th>
44 <th scope="col">Repository</th>
45 <th scope="col">Demos</th>
46 </tr>
47 </thead>
48 <tbody>
49 ${rows.map((d) => {
50 const base = repoBase(d.repo);
51 const name = `${d.repo.ownerName}/${d.repo.name}`;
52 return html`<tr data-display="${name}">
53 <td><a href="${base}/display">${d.config.ok ? d.config.value.title : "display.json failed"}</a></td>
54 <td>${d.config.ok ? LAYOUT_WORD[d.config.value.layout] : "None"}</td>
55 <td><a class="mono" href="${base}">${name}</a></td>
56 <td data-demos>${d.demos === undefined ? "None" : String(d.demos)}</td>
57 </tr>`;
58 })}
59 </tbody>
60 </table>
61 </div>`}`,
62 }),
63 );
64 }
65
66 // GET /displays/new — the repositories a person writes with no display yet; Create display writes its display.json.
67 export async function newDisplayPage(ctx: Ctx): Promise<Response> {
68 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
69 if (ctx.auth.user === undefined) return signInFirst(ctx);
70 const user = ctx.auth.user;
71 const repos = await timePhaseAsync(ctx.request, "repos", async () =>
72 user.kind === "agent" ? [] : withoutDisplay(ctx.app, listReposWritableTo(ctx.app.db, user, { limit: 200, withoutArchived: true })),
73 );
74 return timePhase(ctx.request, "render", () =>
75 page({
76 ctx,
77 title: "New display",
78 crumbs: [{ label: "Displays", href: "/displays" }],
79 body: html`${pageHead("New display")}
80 ${repos.length === 0
81 ? empty({ icon: "folder", title: "No repositories you write without a display" })
82 : html`${repos.map(
83 (r, i) => html`<form method="post" action="${repoBase(r)}/display/create" id="dn-${String(i)}" hidden></form>`,
84 )}
85 ${listCard(
86 repos.map((r, i) =>
87 row({
88 title: html`<span class="mono">${r.ownerName}/${r.name}</span>`,
89 meta: html`${r.visibility === "private" ? "Private" : "Public"} · default branch ${r.defaultBranch}`,
90 trail: btn("Create display", { form: `dn-${String(i)}`, size: "sm", label: `Create a display in ${r.ownerName}/${r.name}` }),
91 data: { repo: `${r.ownerName}/${r.name}` },
92 }),
93 ),
94 { head: html`<h2>Repositories you write</h2><span class="muted small">${String(repos.length)}</span>` },
95 )}`}`,
96 }),
97 );
98 }
test/displays.test.ts added +141
@@ -0,0 +1,141 @@
1 /**
2 * Displays are reachable: `/displays` lists the ones the viewer may read,
3 * `/:owner/:name/display` draws one server-side, and `PUT
4 * /api/v1/repos/:owner/:name/display/builds` sets its builds: validated
5 * (422), scoped (rw), and refused across origins.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { pinBuild } from "../src/actions/builds.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { readDisplay } from "../src/display/config.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { tokenFor } from "./helpers/tokens.ts";
19
20 describe("displays", () => {
21 let dataDir: string;
22 let app: App;
23 let servers: Servers;
24 let base: string;
25 let alice: User;
26 let token: string;
27 let bobToken: string;
28 const put = (body: unknown, auth = token, extra: Record<string, string> = {}) =>
29 fetch(`${base}/api/v1/repos/alice/shelf/display/builds`, {
30 method: "PUT",
31 headers: { authorization: `Bearer ${auth}`, "content-type": "application/json", ...extra },
32 body: JSON.stringify(body),
33 });
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-displays-"));
37 app = createApp({ dataDir, port: 0 });
38 servers = await serve(app);
39 base = servers.url;
40 for (const name of ["alice", "bob"]) {
41 const made = await createUser(app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: true });
42 if (!made.ok) throw new Error(made.error);
43 if (name === "alice") alice = made.value;
44 }
45 for (const name of ["game", "shelf", "plain"]) {
46 const made = await createRepo(app, alice, { name, visibility: "public" });
47 if (!made.ok) throw new Error(String(made.error));
48 }
49 const game = getRepo(app.db, "alice", "game")!;
50 const c = await commitToBranch(app, alice, game, { branch: "main", message: "one", files: [{ path: "one.txt", content: "one\n" }] });
51 if (!c.ok) throw new Error(JSON.stringify(c.error));
52 const pinned = await pinBuild(app, alice, game, { label: "v1", oid: c.value.commitOid, note: "first <b>build</b>" });
53 if (!pinned.ok) throw new Error(JSON.stringify(pinned.error));
54 const shelf = getRepo(app.db, "alice", "shelf")!;
55 const d = await commitToBranch(app, alice, shelf, {
56 branch: "main",
57 message: "display",
58 files: [{ path: "display.json", content: JSON.stringify({ title: "Pocket & Shelf", layout: "grid", sources: ["alice/game"], builds: ["alice/game:v1"] }) }],
59 });
60 if (!d.ok) throw new Error(JSON.stringify(d.error));
61 token = tokenFor(app, "alice", "rw");
62 bobToken = tokenFor(app, "bob", "rw");
63 });
64
65 afterAll(async () => {
66 servers.stop();
67 app.close();
68 await rm(dataDir, { recursive: true, force: true });
69 });
70
71 test("the list shows the seeded display, escaped, and not a repository without one", async () => {
72 const res = await fetch(`${base}/displays`);
73 expect(res.status).toBe(200);
74 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
75 expect(res.headers.get("content-security-policy")).toBeTruthy();
76 expect(res.headers.get("referrer-policy")).toBeTruthy();
77 const text = await res.text();
78 expect(text).toContain('data-display="alice/shelf"');
79 expect(text).toContain("Pocket &amp; Shelf");
80 expect(text).not.toContain("Pocket & Shelf");
81 expect(text).toContain("Grid");
82 expect(text).not.toContain('data-display="alice/plain"');
83 });
84
85 test("a display page draws its title and its build, server-rendered", async () => {
86 const res = await fetch(`${base}/alice/shelf/display`);
87 expect(res.status).toBe(200);
88 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
89 expect(res.headers.get("content-security-policy")).toBeTruthy();
90 const text = await res.text();
91 expect(text).toContain("Pocket &amp; Shelf");
92 expect(text).toContain("alice/game");
93 expect(text).toContain("v1");
94 expect(text).not.toContain("first <b>build</b>");
95 });
96
97 test("a repository with no display is not a display page", async () => {
98 expect((await fetch(`${base}/alice/plain/display`)).status).toBe(404);
99 });
100
101 test("PUT builds writes the selection as one commit; null clears it", async () => {
102 const res = await put({ builds: ["alice/game:v1"] });
103 expect(res.status).toBe(200);
104 const body = (await res.json()) as { commit: string; builds: string[] };
105 expect(body.builds).toEqual(["alice/game:v1"]);
106 const read = await readDisplay(app, getRepo(app.db, "alice", "shelf")!);
107 expect(read?.ok && read.value.builds).toEqual(["alice/game:v1"]);
108 const cleared = await put({ builds: null });
109 expect(cleared.status).toBe(200);
110 const again = await readDisplay(app, getRepo(app.db, "alice", "shelf")!);
111 expect(again?.ok && again.value.builds).toBeUndefined();
112 });
113
114 test("a bad PUT is a 422", async () => {
115 for (const bad of [{ builds: "alice/game:v1" }, { builds: [1] }, { builds: ["alice/game:v1", "alice/game:v1"] }, { builds: ["--upload-pack"] }, {}]) {
116 const res = await put(bad);
117 expect(res.status).toBe(422);
118 expect(((await res.json()) as { error: string }).error).toBe("invalid_builds");
119 }
120 });
121
122 test("a PUT without a token, with a read-only token, or by someone who cannot write is refused", async () => {
123 expect((await fetch(`${base}/api/v1/repos/alice/shelf/display/builds`, { method: "PUT", body: "{}" })).status).toBe(401);
124 expect((await put({ builds: null }, tokenFor(app, "alice", "ro", "ro"))).status).toBe(403);
125 expect([403, 404]).toContain((await put({ builds: null }, bobToken)).status);
126 });
127
128 test("the page's form post across origins is refused", async () => {
129 const signed = await fetch(`${base}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), redirect: "manual" });
130 const cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!;
131 const res = await fetch(`${base}/alice/shelf/display/builds`, {
132 method: "POST",
133 headers: { cookie, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" },
134 body: "build=alice/game:v1",
135 redirect: "manual",
136 });
137 expect(res.status).toBe(403);
138 const read = await readDisplay(app, getRepo(app.db, "alice", "shelf")!);
139 expect(read?.ok && read.value.builds).toBeUndefined();
140 });
141 });
test/security-floor-routes.test.ts +5
@@ -51,7 +51,12 @@ const HOOK = "needs a webhook, which the seed does not register";
5151 /** GET patterns the seed cannot fill → why. Requested with a placeholder all the same. */
5252 const SHOT = "needs a pin with a picture kept by refs/shots; the seed pins nothing";
5353 const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers its headers)";
54 const DEMO = "needs a published demo on a display; the seed has no display (test/displays.test.ts covers one)";
5455 const UNSEEDED: Record<string, string> = {
56 "/:owner/:name/display/demo/:id/cover": DEMO,
57 "/:owner/:name/display/demo/:id/download": DEMO,
58 "/:owner/:name/display/demo/:id/shots": DEMO,
59 "/:owner/:name/display/demo/:id/shots/:file": DEMO,
5560 "/:owner/-/teams/:team": ORG,
5661 "/talk/:id": TALK,
5762 "/bring/:id/:job": "needs a bring job of the signed-in person; the seed brings nothing",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs