Public: anyone can read this; the crew can change it.
Tab forge: serve the forge as the tab's own page in the hosted shell, no frame #18306
Merged 4h 51m ago, live in production
mason/forge:mason/18305-tab-forge-serve-the-forge-as-the-tab-s-o → main 0 commits fork 4 threads · 4 unresolved
14 files
changed +398
−97
docs/design/areas/tab.md +10 −4
| @@ -1,7 +1,13 @@ | ||
| 1 | 1 | # Tab (a forge in this tab) |
| 2 | 2 | |
| 3 | The page at `/tab` (`src/web/pages/tab.ts`): three plain facts, a button and, once started, the tab's own forge shown in | |
| 4 | a frame under them. Styled in `style/content.ts`. | |
| 3 | The page at `/tab` (`src/web/pages/tab.ts`): three plain facts, a button and, once started, the tab's own forge drawn in | |
| 4 | the page under them (no frame). Styled in `style/content.ts`. | |
| 5 | 5 | |
| 6 | - `.tab-frame` — the frame the forge in the tab is shown in: full width, 60% of the window tall (at least 320px), no | |
| 7 | border: space above it sets it apart. Hidden until the forge runs. | |
| 6 | - `.tab-view` — where the forge in the tab is drawn (and the preview of an app being made): in the page's own flow, at | |
| 7 | most 36rem wide, space above it sets it apart. Hidden until the forge runs. Its links, forms, lists and boards are | |
| 8 | styled under it (the same few rules `/tab/f.css` holds for a standalone page), so nothing leaks to the forge's own | |
| 9 | chrome. | |
| 10 | ||
| 11 | The forge in the tab brings its own few classes, styled only under `.tab-view`: `.block`, `.items`, `.pair`, `.add`, | |
| 12 | `.quiet`, `.tick`, `.big`, `.note`, `.field`, `.act`, `.lanes`, `.lane`, `.spec`, `.remove` and `button.danger`. They | |
| 13 | are the ones the renderers in `src/tab/render.ts` write. |
docs/features/tab.md +14 −4
| @@ -5,7 +5,12 @@ row: Run a forge in a browser tab | ||
| 5 | 5 | # A forge in a browser tab (#16861) |
| 6 | 6 | |
| 7 | 7 | Open `/tab` and press *Start it*: the page starts SQLite as wasm on the browser's private file system (OPFS) in a |
| 8 | worker, registers a service worker as the server of `/tab/f/`, and shows that forge in a frame. Home, an issue list, | |
| 8 | worker, registers a service worker as the server of `/tab/f/`, and draws that forge in the page | |
| 9 | itself, under the forge's own topbar and navigation: there is no frame. A click on a `/tab/f/` link | |
| 10 | or a form post in it is sent to the database worker and the reply's `main` replaces the view | |
| 11 | (`src/tab/view.ts`), because a real navigation would unload the page that holds the worker. The | |
| 12 | place is kept in the address fragment (`/tab#/issues`), so Back works and a reload stays on /tab. | |
| 13 | Home, an issue list, | |
| 9 | 14 | one issue and opening an issue work (`src/tab/forge.ts`). |
| 10 | 15 | |
| 11 | 16 | The page says three things, and the terminal's palette entry *A forge in a browser tab* says the same words |
| @@ -25,7 +30,7 @@ SQLite, loaded as the browser loads it, and over `bun:sqlite`. | ||
| 25 | 30 | |
| 26 | 31 | The box on `/tab`, *Make an app*, turns a sentence into an app, with no login and no model. The sentence compiles on |
| 27 | 32 | every keystroke (`src/tab/compile.ts`, deterministic: the same sentence, the same app) and the preview under the box is the |
| 28 | app's real page (`src/tab/render.ts`) in a frame that runs no script. The compiler is a separate file, `/tab/make.js`, | |
| 33 | app's real page (`src/tab/render.ts`) drawn under the box (the renderer escapes every field, and nothing in it runs). The compiler is a separate file, `/tab/make.js`, | |
| 29 | 34 | fetched the first time the box is used. *Make it* starts the forge if it is not running and keeps the app. |
| 30 | 35 | |
| 31 | 36 | An app is a row in the tab's own SQLite (`app`: its spec as JSON; `rec`: its entries). It is data, never code: each spec |
| @@ -72,7 +77,7 @@ Every change in the tab forge (new app, edit, issue, settings) is a form post th | ||
| 72 | 77 | |
| 73 | 78 | ## The whole tab (#18259) |
| 74 | 79 | |
| 75 | Once started, the forge is the tab: its frame covers the viewport (`html[data-running]`, `src/web/style/content.ts`), with no page around it. Its shell carries one quiet line, *This forge lives in this browser… Export*, and the pages below (`src/tab/whole.ts`, `src/tab/coverage.ts`, words in `TAB_WHOLE`, said again by the terminal's entry, `src/tui/screens/tab.ts`): | |
| 80 | Once started, the forge is drawn in the /tab page itself, under the hosted forge's topbar and navigation (`src/tab/view.ts`). Its shell carries one quiet line, *This forge lives in this browser… Export*, and the pages below (`src/tab/whole.ts`, `src/tab/coverage.ts`, words in `TAB_WHOLE`, said again by the terminal's entry, `src/tui/screens/tab.ts`): | |
| 76 | 81 | |
| 77 | 82 | - **What works** (`/tab/f/pages`): every page of the hosted forge (`GO_PAGES`), as works, works differently, or cannot work in a tab (with why and the way to get it: "use your hosted forge"); there is no fourth outcome. The terminal lists the same in *What works in a forge in a tab* (`src/tui/screens/tabworks.ts`), with the runner words. Search, Waiting and Archive are cannot; Board and Notes work differently (an app made from a sentence). `test/tab-whole.test.ts` fails if the hosted list gains a page this one does not name, and if a page that claims to work does not answer. |
| 78 | 83 | - **Runners** (`/tab/f/runners`, in the menu; the What works list does not link it, because no *cannot* page is linked there): says what a tab can run (JavaScript and WebAssembly in a worker) and cannot (git, a shell, native programs, listening, surviving a closed tab). It has **no switch**: the tab runner is #18257's spike, and a switch that did nothing would be dead. Until it lands this tab is not a runner. |
| @@ -80,4 +85,9 @@ Once started, the forge is the tab: its frame covers the viewport (`html[data-ru | ||
| 80 | 85 | |
| 81 | 86 | It survives a reload and a reopened tab: the page remembers (`localStorage`) that the forge was started and the last page of it that was read, and starts it again on load. Every decision a reload makes is in `src/tab/restore.ts` and tested in `test/tab-whole.test.ts`: `startsItself` (starts only when this browser started it before), `openOn` (only a `/tab/f/` path is ever opened), `keepStorage` (asks only on the first Start). When the browser cleared the store but kept `localStorage`, the worker reports the store empty (`unmade`, no tables before the migration): every page of it carries *The browser cleared this forge since it last ran: Import an export to bring it back.* When the browser cleared both, the page is a first visit again: Start. A second tab cannot open the store while the first holds it; it says so and names the way out. If the browser clears the site's data the forge is gone: export first. |
| 82 | 87 | |
| 83 | Not done: a topbar identical to the hosted forge's, an export of the whole database file (the export is the app and its issues), a hosted forge reading the file, and the runner switch. The forge is still shown in a frame over /tab, not served as the tab's own page in the hosted shell: the database needs a dedicated worker (OPFS sync handles), which a page under `/tab/f/` loses on every navigation. The cold read by a no-context agent was not run. | |
| 88 | Not done: an export of the whole database file (the export is the app and its issues), a hosted | |
| 89 | forge reading the file, and the runner switch. The forge's pages are drawn into /tab rather than | |
| 90 | served as documents under `/tab/f/`, because the database's dedicated worker (OPFS sync handles) | |
| 91 | would be lost on a navigation. The service worker stays only for a `/tab/f/` link opened outside the | |
| 92 | page (a new tab, a bookmark): it asks the /tab window that holds the forge and answers it as a | |
| 93 | document. The cold read by a no-context agent was not run. |
src/tab/boot.ts +14 −24
| @@ -1,11 +1,11 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The /tab page's script: starts the database worker, registers the service worker, and shows the |
| 3 | * forge in a frame. The page is the host: its requests from the worker are relayed from the | |
| 4 | * service worker, so closing the tab stops the forge. | |
| 3 | * forge in the page itself (`view.ts`). The page is the host: its requests from the worker are | |
| 4 | * relayed from the service worker, so closing the tab stops the forge. | |
| 5 | 5 | */ |
| 6 | 6 | import { activated, type Registration } from "./active.ts"; |
| 7 | 7 | import type { Runtime } from "./fill.ts"; |
| 8 | import type { TabRequest } from "./forge.ts"; | |
| 8 | import type { TabReply, TabRequest } from "./forge.ts"; | |
| 9 | 9 | import { keepStorage, openOn, startsItself } from "./restore.ts"; |
| 10 | 10 | |
| 11 | 11 | // The few browser globals this file touches, named here rather than pulling in the DOM library. |
| @@ -14,10 +14,9 @@ interface Box { | ||
| 14 | 14 | textContent: string | null; |
| 15 | 15 | disabled: boolean; |
| 16 | 16 | hidden: boolean; |
| 17 | src: string; | |
| 17 | innerHTML: string; | |
| 18 | 18 | value: string; |
| 19 | srcdoc: string; | |
| 20 | addEventListener(type: "click" | "input" | "load", listener: () => void): void; | |
| 19 | addEventListener(type: "click" | "input", listener: () => void): void; | |
| 21 | 20 | addEventListener(type: "submit", listener: (e: { preventDefault(): void }) => void): void; |
| 22 | 21 | } |
| 23 | 22 | interface Registrations { |
| @@ -27,9 +26,6 @@ interface Registrations { | ||
| 27 | 26 | } |
| 28 | 27 | declare const document: { getElementById(id: string): Box | null; readonly documentElement: { readonly dataset: Record<string, string> } }; |
| 29 | 28 | declare const navigator: { readonly serviceWorker?: Registrations; readonly storage?: { getDirectory?: unknown; persist?(): Promise<boolean>; persisted?(): Promise<boolean> } }; |
| 30 | interface Frame extends Box { | |
| 31 | readonly contentWindow: { readonly location: { readonly pathname: string } } | null; | |
| 32 | } | |
| 33 | 29 | declare const localStorage: { getItem(key: string): string | null; setItem(key: string, value: string): void }; |
| 34 | 30 | const ON = "tf:on"; |
| 35 | 31 | const WHERE = "tf:at"; |
| @@ -44,6 +40,7 @@ const say = (text: string): void => { | ||
| 44 | 40 | // The worker of the forge this page started; null on a page that never did, which then stays |
| 45 | 41 | // silent. |
| 46 | 42 | let holder: Worker | null = null; |
| 43 | let view: { go(target: string): Promise<void> } | null = null; | |
| 47 | 44 | // Whether the browser promised to keep the storage, asked once at start; the forge's pages say it. |
| 48 | 45 | let kept: "persistent" | "best-effort" | null = null; |
| 49 | 46 | // Whether a forge that ran here before opened on an empty store; its pages say so. |
| @@ -95,17 +92,10 @@ async function start(button: Box): Promise<boolean> { | ||
| 95 | 92 | const ranBefore = startsItself(localStorage.getItem(ON)); |
| 96 | 93 | // Asked to keep the storage on the first Start only; the forge's pages say whether it agreed. |
| 97 | 94 | kept = await keepStorage(navigator.storage, !ranBefore); |
| 98 | const frame = document.getElementById("tab-frame") as unknown as Frame; | |
| 99 | // Back where the person was. | |
| 100 | frame.src = openOn(localStorage.getItem(WHERE)); | |
| 101 | frame.addEventListener("load", () => { | |
| 102 | const at = frame.contentWindow?.location.pathname; | |
| 103 | if (at !== undefined && openOn(at) === at) localStorage.setItem(WHERE, at); | |
| 104 | }); | |
| 105 | frame.hidden = false; | |
| 95 | const root = document.getElementById("tab-view")!; | |
| 96 | // Back where the person was, unless the address names a page. | |
| 97 | view = (await import(/* @vite-ignore */ root.dataset.code!)).mount(root, ask, openOn(localStorage.getItem(WHERE)), (at: string) => localStorage.setItem(WHERE, at)); | |
| 106 | 98 | localStorage.setItem(ON, "1"); |
| 107 | // The forge is the whole tab: the page's own chrome steps back (CSS on `data-running`). | |
| 108 | document.documentElement.dataset.running = "1"; | |
| 109 | 99 | // Its pages say so: the page's own status is hidden while the forge fills the tab. |
| 110 | 100 | cleared = ranBefore && empty; |
| 111 | 101 | say("Running."); |
| @@ -113,7 +103,7 @@ async function start(button: Box): Promise<boolean> { | ||
| 113 | 103 | } |
| 114 | 104 | |
| 115 | 105 | /** One request to the database worker, answered on its own port. */ |
| 116 | function ask(req: TabRequest): Promise<{ status: number; location?: string }> { | |
| 106 | function ask(req: TabRequest): Promise<TabReply> { | |
| 117 | 107 | return new Promise((resolve) => { |
| 118 | 108 | const channel = new MessageChannel(); |
| 119 | 109 | channel.port1.onmessage = (e) => resolve(e.data); |
| @@ -182,8 +172,8 @@ if (button !== null && go !== null) { | ||
| 182 | 172 | } |
| 183 | 173 | |
| 184 | 174 | // "Make an app": the compiler is a separate file, fetched the first time the box is used, so the |
| 185 | // page stays small for a person who only reads it. The preview is the compiled app's own page in a | |
| 186 | // frame that runs no script. | |
| 175 | // page stays small for a person who only reads it. The preview is the compiled app's own markup, | |
| 176 | // escaped by the renderer, drawn under the box. | |
| 187 | 177 | const make = document.getElementById("tab-make"); |
| 188 | 178 | const sayBox = document.getElementById("tab-say"); |
| 189 | 179 | const previewFrame = document.getElementById("tab-preview"); |
| @@ -193,7 +183,7 @@ if (make !== null && sayBox !== null && previewFrame !== null && button !== null | ||
| 193 | 183 | const show = async (): Promise<void> => { |
| 194 | 184 | compiler ??= import(/* @vite-ignore */ make.dataset.make!); |
| 195 | 185 | const loaded = await compiler; |
| 196 | previewFrame.srcdoc = loaded.preview(sayBox.value); | |
| 186 | previewFrame.innerHTML = loaded.preview(sayBox.value); | |
| 197 | 187 | previewFrame.hidden = false; |
| 198 | 188 | }; |
| 199 | 189 | sayBox.addEventListener("input", () => void show()); |
| @@ -210,7 +200,7 @@ if (make !== null && sayBox !== null && previewFrame !== null && button !== null | ||
| 210 | 200 | } |
| 211 | 201 | const done = await ask({ method: "POST", path: "/apps", form: answer === null ? { say: sentence } : { say: sentence, answer } }); |
| 212 | 202 | if (done.location !== undefined) { |
| 213 | document.getElementById("tab-frame")!.src = done.location; | |
| 203 | void view!.go(done.location); | |
| 214 | 204 | previewFrame.hidden = true; |
| 215 | 205 | sayBox.value = ""; |
| 216 | 206 | say("Made, kept in this browser."); |
src/tab/make.ts +3 −3
| @@ -1,8 +1,8 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The compiler's browser entry, loaded by `boot.ts` only when the "Make an app" box is used |
| 3 | * (#18043): a sentence in, the real app's page out, with no network and no model. | |
| 3 | * (#18043): a sentence in, the real app's markup out, with no network and no model. | |
| 4 | 4 | */ |
| 5 | 5 | import { compile } from "./compile.ts"; |
| 6 | import { previewDocument } from "./render.ts"; | |
| 6 | import { previewMarkup } from "./render.ts"; | |
| 7 | 7 | |
| 8 | export const preview = (sentence: string): string => previewDocument(compile(sentence).app); | |
| 8 | export const preview = (sentence: string): string => previewMarkup(compile(sentence).app); |
src/tab/render.ts +4 −2
| @@ -103,5 +103,7 @@ export function renderApp(app: BlockApp, v: View): string { | ||
| 103 | 103 | return `<h1>${app.glyph === undefined ? "" : `<span aria-hidden="true">${esc(app.glyph)}</span> `}${esc(app.title)}</h1>${app.blocks.map((b, i) => one(v, i, b)).join("")}`; |
| 104 | 104 | } |
| 105 | 105 | |
| 106 | /** The preview the box shows: the same app, empty, with no forms. */ | |
| 107 | export const previewDocument = (app: BlockApp): string => pageOf(app.title, renderApp(app, { appId: null, records: [], today: "" })); | |
| 106 | /** | |
| 107 | * The app as it will look, with no forms: the markup of a page's `main`, for the host page to draw. | |
| 108 | */ | |
| 109 | export const previewMarkup = (app: BlockApp): string => renderApp(app, { appId: null, records: [], today: "" }); |
src/tab/shell.ts +1 −1
| @@ -8,5 +8,5 @@ export const KEPT_MARK = "<!--kept-->"; | ||
| 8 | 8 | |
| 9 | 9 | export function shell(title: string, body: string, status = 200, heading = true): TabReply { |
| 10 | 10 | const nav = `<nav><a href="${ROOT}/">Home</a> <a href="${ROOT}/issues">Issues</a> <a href="${ROOT}/runners">Runners</a> <a href="${ROOT}/pages">What works</a></nav>`; |
| 11 | return { status, html: pageOf(title, `${heading ? `<h1>${esc(title)}</h1>` : ""}${body}<footer class="kept muted">${KEPT_MARK}</footer>`, nav) }; | |
| 11 | return { status, html: pageOf(title, `${heading ? `<h1>${esc(title)}</h1>` : ""}${body}<footer class="muted">${KEPT_MARK}</footer>`, nav) }; | |
| 12 | 12 | } |
src/tab/view.ts added +126
| @@ -0,0 +1,126 @@ | ||
| 1 | /** | |
| 2 | * The forge in the tab, shown in the /tab page itself (#18305): the hosted forge's pages are drawn | |
| 3 | * into one element of the page, so its topbar and navigation stay, and a link or form under | |
| 4 | * `/tab/f/` is answered by the database worker instead of loading a new document (a navigation | |
| 5 | * would unload the page that holds the worker). The address keeps the place in its fragment, so a | |
| 6 | * reload or Back stays on /tab. Loaded by `boot.ts` once the forge runs. | |
| 7 | */ | |
| 8 | import type { TabReply, TabRequest } from "./forge.ts"; | |
| 9 | import { PREFIX } from "./wire.ts"; | |
| 10 | ||
| 11 | interface Node { | |
| 12 | getAttribute(name: string): string | null; | |
| 13 | closest(selector: string): Node | null; | |
| 14 | readonly method?: string; | |
| 15 | } | |
| 16 | interface Root { | |
| 17 | innerHTML: string; | |
| 18 | hidden: boolean; | |
| 19 | focus(): void; | |
| 20 | querySelector(selector: string): { setAttribute(name: string, value: string): void; focus(): void } | null; | |
| 21 | addEventListener(type: "click", listener: (e: { target: Node | null; button: number; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; preventDefault(): void }) => void): void; | |
| 22 | addEventListener(type: "submit", listener: (e: { target: Node; preventDefault(): void }) => void): void; | |
| 23 | } | |
| 24 | declare const document: { title: string; createElement(tag: "a"): { href: string; download: string; click(): void } }; | |
| 25 | declare const location: { readonly hash: string; readonly origin: string }; | |
| 26 | declare const history: { pushState(state: null, title: string, url: string): void }; | |
| 27 | declare const addEventListener: (type: "popstate", listener: () => void) => void; | |
| 28 | declare class DOMParser { | |
| 29 | parseFromString(text: string, type: "text/html"): { title: string; querySelector(selector: string): { innerHTML: string } | null }; | |
| 30 | } | |
| 31 | declare class FormData { | |
| 32 | constructor(form: Node); | |
| 33 | entries(): Iterable<[string, string | { text(): Promise<string> }]>; | |
| 34 | } | |
| 35 | ||
| 36 | /** Where a link or form action points when it is the forge in the tab's, else null. */ | |
| 37 | function inside(href: string | null): URL | null { | |
| 38 | if (href === null) return null; | |
| 39 | const url = new URL(href, `${location.origin}${PREFIX}/`); | |
| 40 | const own = url.origin === location.origin && (url.pathname === PREFIX || url.pathname.startsWith(`${PREFIX}/`)); | |
| 41 | return own ? url : null; | |
| 42 | } | |
| 43 | ||
| 44 | const FAILED = `<h1>That did not work</h1><p>The forge in this tab could not answer. <a href="${PREFIX}/">Go to the forge's home</a>, or open /tab again.</p>`; | |
| 45 | ||
| 46 | export type Ask = (req: TabRequest) => Promise<TabReply>; | |
| 47 | ||
| 48 | /** | |
| 49 | * Draws the forge into `root` and keeps its links and forms there; returns how to go to a page. It | |
| 50 | * opens on the address's fragment, else on `open`; `remember` hears each page it draws. | |
| 51 | */ | |
| 52 | export function mount(root: Root, ask: Ask, open: string, remember: (at: string) => void): { go(target: string, push?: boolean): Promise<void> } { | |
| 53 | const parser = new DOMParser(); | |
| 54 | ||
| 55 | /** | |
| 56 | * Draws a reply; false when it was an error (no page to show), which gets a sentence and a way | |
| 57 | * out. | |
| 58 | */ | |
| 59 | function keep(reply: TabReply): boolean { | |
| 60 | const doc = parser.parseFromString(reply.html, "text/html"); | |
| 61 | const main = doc.querySelector("main"); | |
| 62 | const failed = reply.status >= 400 && main === null; | |
| 63 | root.innerHTML = failed ? FAILED : (main?.innerHTML ?? ""); | |
| 64 | if (!failed && doc.title !== "") document.title = doc.title; | |
| 65 | root.hidden = false; | |
| 66 | return !failed; | |
| 67 | } | |
| 68 | ||
| 69 | async function answer(req: TabRequest, push: boolean): Promise<void> { | |
| 70 | const reply = await ask(req); | |
| 71 | if (reply.location !== undefined) return go(reply.location, true); | |
| 72 | if (reply.file !== undefined) { | |
| 73 | const a = document.createElement("a"); | |
| 74 | a.href = URL.createObjectURL(new Blob([reply.html], { type: reply.file.type })); | |
| 75 | a.download = reply.file.name; | |
| 76 | a.click(); | |
| 77 | URL.revokeObjectURL(a.href); | |
| 78 | return; | |
| 79 | } | |
| 80 | keep(reply); | |
| 81 | const at = `${req.path}${req.query ? `?${req.query}` : ""}`; | |
| 82 | // Only a page that was read and found is a place to reopen: a failed or posted path is not. | |
| 83 | if (req.method === "GET" && reply.status === 200) { | |
| 84 | remember(`${PREFIX}${at}`); | |
| 85 | if (push) history.pushState(null, "", `#${at}`); | |
| 86 | } | |
| 87 | // Focus the new view's first heading, so a screen reader reads that and not the whole page. | |
| 88 | const heading = root.querySelector("h1, h2"); | |
| 89 | if (heading === null) root.focus(); | |
| 90 | else { | |
| 91 | heading.setAttribute("tabindex", "-1"); | |
| 92 | heading.focus(); | |
| 93 | } | |
| 94 | } | |
| 95 | ||
| 96 | const go = (target: string, push = true): Promise<void> => { | |
| 97 | const url = inside(target) ?? inside(`${PREFIX}/`)!; | |
| 98 | return answer({ method: "GET", path: url.pathname.slice(PREFIX.length) || "/", query: url.search.slice(1), form: {} }, push); | |
| 99 | }; | |
| 100 | ||
| 101 | root.addEventListener("click", (e) => { | |
| 102 | const a = e.target?.closest("a") ?? null; | |
| 103 | const url = a === null || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey ? null : inside(a.getAttribute("href")); | |
| 104 | if (url === null || a?.getAttribute("download") != null) return; | |
| 105 | e.preventDefault(); | |
| 106 | void go(url.pathname + url.search); | |
| 107 | }); | |
| 108 | ||
| 109 | root.addEventListener("submit", (e) => { | |
| 110 | const url = inside(e.target.getAttribute("action") ?? `${PREFIX}/`); | |
| 111 | if (url === null) return; | |
| 112 | e.preventDefault(); | |
| 113 | void (async () => { | |
| 114 | const form: Record<string, string> = {}; | |
| 115 | for (const [name, value] of new FormData(e.target).entries()) form[name] = typeof value === "string" ? value : await value.text(); | |
| 116 | const path = url.pathname.slice(PREFIX.length) || "/"; | |
| 117 | if ((e.target.method ?? "get").toLowerCase() === "post") await answer({ method: "POST", path, query: url.search.slice(1), form }, false); | |
| 118 | else await answer({ method: "GET", path, query: new URLSearchParams(form).toString(), form: {} }, true); | |
| 119 | })(); | |
| 120 | }); | |
| 121 | ||
| 122 | const here = (): string => (location.hash.length > 1 ? `${PREFIX}${location.hash.slice(1)}` : open); | |
| 123 | addEventListener("popstate", () => void go(here(), false)); | |
| 124 | void go(here(), false); | |
| 125 | return { go }; | |
| 126 | } |
src/web/pages/tab.ts +5 −5
| @@ -1,8 +1,8 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * /tab: starts a forge in this browser tab. The page is server-rendered and says plainly what that |
| 3 | 3 | * means (`tab/words.ts`, which the terminal says too); the button starts the database worker and |
| 4 | * the service worker (`tab/boot.ts`). Every file is static: serving it costs this forge a file | |
| 5 | * read. | |
| 4 | * the service worker (`tab/boot.ts`), and the forge is drawn into the page (`tab/view.ts`). Every | |
| 5 | * file is static: serving it costs this forge a file read. | |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import type { Ctx } from "../../http/context.ts"; |
| @@ -21,7 +21,7 @@ export async function tabPage(ctx: Ctx): Promise<Response> { | ||
| 21 | 21 | <label for="tab-say"><strong>Make an app</strong></label> |
| 22 | 22 | <input id="tab-say" name="say" maxlength="300" autocomplete="off" placeholder="Track my water, a shopping list, a board for my bugs…"> |
| 23 | 23 | <button class="btn" type="submit">Make it</button> |
| 24 | <iframe id="tab-preview" class="tab-frame" title="Preview of your app" sandbox="" src="about:blank" hidden></iframe> | |
| 24 | <div id="tab-preview" class="tab-view" role="region" aria-live="polite" aria-label="Preview of your app" hidden></div> | |
| 25 | 25 | </form> |
| 26 | 26 | <noscript><p>A forge in a tab needs JavaScript: it runs in this page's scripts.</p></noscript> |
| 27 | 27 | <p id="tab-go" hidden> |
| @@ -36,6 +36,6 @@ export async function tabPage(ctx: Ctx): Promise<Response> { | ||
| 36 | 36 | <p id="tab-model-status" class="muted" role="status"></p> |
| 37 | 37 | </section> |
| 38 | 38 | <p id="tab-status" class="muted" role="status">${boot === null ? "The tab forge could not be built here." : ""}</p> |
| 39 | <iframe id="tab-frame" class="tab-frame" title="The forge in this tab" src="about:blank" hidden></iframe>`; | |
| 40 | return page({ ctx, title: TAB_TITLE, description: "A forge that runs in this browser tab, on this device.", frameSelf: true, ...(boot === null ? {} : { scriptJs: boot.code }), body }); | |
| 39 | <section id="tab-view" class="tab-view" aria-label="The forge in this tab" tabindex="-1" data-code="/tab/view.js" hidden></section>`; | |
| 40 | return page({ ctx, title: TAB_TITLE, description: "A forge that runs in this browser tab, on this device.", ...(boot === null ? {} : { scriptJs: boot.code }), body }); | |
| 41 | 41 | } |
src/web/style/content.ts +28 −7
| @@ -26,13 +26,34 @@ a[data-waves-link] { display: inline-flex; align-items: center; min-height: 44px | ||
| 26 | 26 | .repo-head p.muted.small { margin-top: 4px; text-wrap: pretty; } |
| 27 | 27 | /* A description: two lines, then "more" opens it in place. */ |
| 28 | 28 | .clamp { margin: 0; } |
| 29 | .tab-frame { display: block; width: 100%; height: 60vh; min-height: 320px; margin-top: 24px; } | |
| 30 | .tab-frame[hidden] { display: none; } | |
| 31 | /* A forge running in the tab is the whole tab: the page's chrome steps aside and the frame takes the width and the height (#18259). */ | |
| 32 | html[data-running="1"] .skip, html[data-running="1"] .topbar, html[data-running="1"] .foot, html[data-running="1"] body > a[data-palette], | |
| 33 | html[data-running="1"] #main > :not(#tab-frame) { display: none; } | |
| 34 | html[data-running="1"] #main { max-width: none; padding: 0; margin: 0; } | |
| 35 | html[data-running="1"] #tab-frame { height: max(100dvh, 320px); margin: 0; border: 0; } | |
| 29 | .tab-view { margin-top: 24px; max-width: 36rem; overflow-wrap: anywhere; } | |
| 30 | .tab-view[hidden] { display: none; } | |
| 31 | .tab-view nav { display: flex; gap: 12px; } | |
| 32 | .tab-view nav a { display: inline-flex; align-items: center; min-height: 44px; } | |
| 33 | .tab-view form { display: grid; gap: 8px; margin-top: 16px; } | |
| 34 | .tab-view label { display: grid; gap: 4px; } | |
| 35 | .tab-view input, .tab-view textarea, .tab-view button { font: inherit; font-size: 16px; padding: 6px 12px; min-height: 44px; box-sizing: border-box; color: inherit; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); } | |
| 36 | .tab-view input, .tab-view textarea { width: 100%; } | |
| 37 | .tab-view textarea { min-height: 5rem; } | |
| 38 | .tab-view button { cursor: pointer; } | |
| 39 | .tab-view .block { border-top: 1px solid var(--border); margin-top: 24px; padding-top: 4px; } | |
| 40 | .tab-view .items { list-style: none; margin: 8px 0 0; padding: 0; } | |
| 41 | .tab-view .items li { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; justify-content: space-between; padding: 4px 0; } | |
| 42 | .tab-view .items li.done span { text-decoration: line-through; color: var(--muted-fg); } | |
| 43 | .tab-view .items form, .tab-view .pair form { display: block; margin: 0; } | |
| 44 | .tab-view .pair { display: flex; gap: 8px; } | |
| 45 | .tab-view .add { grid-template-columns: 1fr auto; } | |
| 46 | .tab-view .quiet { background: none; border-color: transparent; color: var(--muted-fg); } | |
| 47 | .tab-view .tick { margin: 0; } | |
| 48 | .tab-view .big { font-size: 20px; font-weight: 700; margin: 4px 0; } | |
| 49 | .tab-view .note { white-space: pre-wrap; margin: 12px 0; } | |
| 50 | .tab-view .field, .tab-view .act { display: inline-block; color: var(--muted-fg); } | |
| 51 | .tab-view .lanes { display: grid; gap: 16px; margin-top: 12px; } | |
| 52 | .tab-view .lane h3 { font-size: 14px; margin: 0; } | |
| 53 | .tab-view .spec { overflow: auto; font-size: 13px; } | |
| 54 | .tab-view footer { margin-top: 32px; font-size: 13px; color: var(--muted-fg); } | |
| 55 | .tab-view .remove { margin-top: 32px; } | |
| 56 | .tab-view button.danger { background: var(--danger); border-color: var(--danger); color: var(--bg); } | |
| 36 | 57 | .clamp-l { display: block; cursor: pointer; } |
| 37 | 58 | .clamp-t { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; overflow-wrap: anywhere; } |
| 38 | 59 | .clamp-x:checked ~ .clamp-t { display: block; } |
src/web/tab-asset.ts +9 −7
| @@ -4,9 +4,10 @@ | ||
| 4 | 4 | * |
| 5 | 5 | * - `/tab/worker.js`, `/tab/sw.js` and `/tab/make.js` (the compiler, fetched only when the "Make an |
| 6 | 6 | * app" box is used) and `/tab/model.js` (the optional model's code, fetched only where the |
| 7 | * browser has one): `src/tab/worker.ts`, `sw.ts`, `make.ts` and `model.ts`, bundled by | |
| 8 | * `Bun.build` at first use. Fixed paths (a service worker's scope comes from its path), answered | |
| 9 | * with a validator and `no-cache`. | |
| 7 | * browser has one) and `/tab/view.js` (draws the forge into /tab once it runs): | |
| 8 | * `src/tab/worker.ts`, `sw.ts`, `make.ts` and `model.ts`, bundled by `Bun.build` at first use. | |
| 9 | * Fixed paths (a service worker's scope comes from its path), answered with a validator and | |
| 10 | * `no-cache`. | |
| 10 | 11 | * - `/tab/v/<hash>/sqlite3.mjs` and `sqlite3.wasm`: the vendored SQLite wasm |
| 11 | 12 | * (`vendor/sqlite-wasm`), the hash of the wasm in the path so both are immutable; the module |
| 12 | 13 | * finds the wasm beside it. |
| @@ -68,7 +69,7 @@ export function sqliteVendor(): Vendor { | ||
| 68 | 69 | |
| 69 | 70 | export const sqliteModulePath = (): string => `/tab/v/${sqliteVendor().hash}/sqlite3.mjs`; |
| 70 | 71 | |
| 71 | type Name = "boot" | "worker" | "sw" | "make" | "model"; | |
| 72 | type Name = "boot" | "worker" | "sw" | "make" | "model" | "view"; | |
| 72 | 73 | let building: Promise<Record<Name, BuiltAsset | null>> | null = null; |
| 73 | 74 | /** |
| 74 | 75 | * One of the tab's scripts, all three built once per process (the paths are literal so the tree |
| @@ -77,14 +78,15 @@ let building: Promise<Record<Name, BuiltAsset | null>> | null = null; | ||
| 77 | 78 | export async function tabScript(name: Name): Promise<BuiltAsset | null> { |
| 78 | 79 | building ??= (async () => { |
| 79 | 80 | const at = (url: URL) => Bun.fileURLToPath(url); |
| 80 | const [boot, worker, sw, make, model] = await Promise.all([ | |
| 81 | const [boot, worker, sw, make, model, view] = await Promise.all([ | |
| 81 | 82 | bundleEntry(at(new URL("../tab/boot.ts", import.meta.url)), "tab-boot", "web.tab_asset_failed"), |
| 82 | 83 | bundleEntry(at(new URL("../tab/worker.ts", import.meta.url)), "tab-worker", "web.tab_asset_failed"), |
| 83 | 84 | bundleEntry(at(new URL("../tab/sw.ts", import.meta.url)), "tab-sw", "web.tab_asset_failed"), |
| 84 | 85 | bundleEntry(at(new URL("../tab/make.ts", import.meta.url)), "tab-make", "web.tab_asset_failed"), |
| 85 | 86 | bundleEntry(at(new URL("../tab/model.ts", import.meta.url)), "tab-model", "web.tab_asset_failed"), |
| 87 | bundleEntry(at(new URL("../tab/view.ts", import.meta.url)), "tab-view", "web.tab_asset_failed"), | |
| 86 | 88 | ]); |
| 87 | return { boot, worker, sw, make, model }; | |
| 89 | return { boot, worker, sw, make, model, view }; | |
| 88 | 90 | })(); |
| 89 | 91 | return (await building)[name]; |
| 90 | 92 | } |
| @@ -101,7 +103,7 @@ function validated(request: Request, body: string, type: string, csp: string): R | ||
| 101 | 103 | /** GET /tab/:name: the worker, the service worker or the stylesheet. */ |
| 102 | 104 | export async function tabFile(request: Request, name: string): Promise<Response> { |
| 103 | 105 | if (name === "f.css") return validated(request, STYLE, "text/css; charset=utf-8", PLAIN_CSP); |
| 104 | const scripts: Record<string, Name> = { "worker.js": "worker", "sw.js": "sw", "make.js": "make", "model.js": "model" }; | |
| 106 | const scripts: Record<string, Name> = { "worker.js": "worker", "sw.js": "sw", "make.js": "make", "model.js": "model", "view.js": "view" }; | |
| 105 | 107 | const script = Object.hasOwn(scripts, name) ? scripts[name] : undefined; |
| 106 | 108 | if (script === undefined) return missing(); |
| 107 | 109 | const built = await tabScript(script); |
test/helpers/chrome.ts +8 −6
| @@ -85,9 +85,9 @@ class Cdp { | ||
| 85 | 85 | this.listeners.set(method, [...(this.listeners.get(method) ?? []), listen]); |
| 86 | 86 | } |
| 87 | 87 | |
| 88 | send(method: string, params: object = {}): Promise<any> { | |
| 88 | send(method: string, params: object = {}, ms: number = SEND_MS): Promise<any> { | |
| 89 | 89 | const id = this.nextId++; |
| 90 | return within(SEND_MS, method, new Promise((resolve, reject) => { | |
| 90 | return within(ms, method, new Promise((resolve, reject) => { | |
| 91 | 91 | this.pending.set(id, (msg) => { |
| 92 | 92 | if (msg.error !== undefined) reject(new Error(msg.error.message)); |
| 93 | 93 | else resolve(msg.result); |
| @@ -748,8 +748,10 @@ export async function walkWithWorker( | ||
| 748 | 748 | })); |
| 749 | 749 | return new Cdp(ws); |
| 750 | 750 | }; |
| 751 | const run = async (cdp: Cdp, expression: string, what: string): Promise<unknown> => { | |
| 752 | const { result, exceptionDetails } = await cdp.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }); | |
| 751 | // A script that waits on the page (the forge starting, the walk's five posts) is bounded by its | |
| 752 | // own limit, not by the 20 s a single CDP command gets: that cut the walk off under load. | |
| 753 | const run = async (cdp: Cdp, expression: string, what: string, ms: number = SEND_MS): Promise<unknown> => { | |
| 754 | const { result, exceptionDetails } = await cdp.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }, ms); | |
| 753 | 755 | if (exceptionDetails !== undefined) throw new Error(`${what}: ${exceptionDetails.exception?.description ?? exceptionDetails.text}`); |
| 754 | 756 | return result.value; |
| 755 | 757 | }; |
| @@ -769,7 +771,7 @@ export async function walkWithWorker( | ||
| 769 | 771 | const loaded = page.once("Page.loadEventFired"); |
| 770 | 772 | await page.send("Page.navigate", { url }); |
| 771 | 773 | await within(15_000, `loading ${url}`, loaded); |
| 772 | await within(30_000, "starting", run(page, steps.start, "start")); | |
| 774 | await within(35_000, "starting", run(page, steps.start, "start", 35_000)); | |
| 773 | 775 | const httpBase = browserWsUrl.replace(/^ws:/, "http:").replace(/\/devtools\/browser\/.*$/, ""); |
| 774 | 776 | let at: string | undefined; |
| 775 | 777 | await pollUntil(async () => { |
| @@ -778,7 +780,7 @@ export async function walkWithWorker( | ||
| 778 | 780 | return at !== undefined; |
| 779 | 781 | }, "the tab forge's service worker in the devtools list", 10_000); |
| 780 | 782 | const worker = await open(at!); |
| 781 | const value = String(await within(60_000, "the walk", run(page, steps.walk, "walk"))); | |
| 783 | const value = String(await within(75_000, "the walk", run(page, steps.walk, "walk", 75_000))); | |
| 782 | 784 | return { value, worker: String(await run(worker, steps.read, "read")), posts }; |
| 783 | 785 | } finally { |
| 784 | 786 | for (const ws of sockets) ws.close(); |
test/tab-browser.test.ts +25 −33
| @@ -23,13 +23,12 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 23 | 23 | import { serve, type Servers } from "../src/http/server.ts"; |
| 24 | 24 | import { findChromium } from "../src/looks/capture.ts"; |
| 25 | 25 | import { makeSpec } from "../src/tab/spec.ts"; |
| 26 | import { fromOwnPage } from "../src/tab/wire.ts"; | |
| 27 | 26 | import { chromiumRuns, walkWithWorker, type WorkerWalk } from "./helpers/chrome.ts"; |
| 28 | 27 | |
| 29 | 28 | const START = `(async () => { |
| 30 | 29 | document.getElementById("tab-start").click(); |
| 31 | 30 | const end = Date.now() + 25000; |
| 32 | while (document.documentElement.dataset.running !== "1") { | |
| 31 | while (document.getElementById("tab-view").hidden) { | |
| 33 | 32 | if (Date.now() > end) throw new Error("the forge never started: " + document.getElementById("tab-status").textContent); |
| 34 | 33 | await new Promise((r) => requestAnimationFrame(r)); |
| 35 | 34 | } |
| @@ -48,42 +47,43 @@ const READ = `(async () => { | ||
| 48 | 47 | })()`; |
| 49 | 48 | |
| 50 | 49 | const walkScript = (): string => `(async () => { |
| 51 | const frame = document.getElementById("tab-frame"); | |
| 52 | const doc = () => frame.contentDocument; | |
| 53 | const frameDrawn = () => new Promise((r) => requestAnimationFrame(r)); | |
| 50 | const root = document.getElementById("tab-view"); | |
| 51 | const drawn = () => new Promise((r) => requestAnimationFrame(r)); | |
| 54 | 52 | const holds = async (ok, what) => { |
| 55 | 53 | const end = Date.now() + 15000; |
| 56 | 54 | for (;;) { |
| 57 | 55 | try { const v = ok(); if (v) return v; } catch {} |
| 58 | if (Date.now() > end) throw new Error("waited for " + what + " at " + frame.contentWindow.location.pathname); | |
| 59 | await frameDrawn(); | |
| 56 | if (Date.now() > end) throw new Error("waited for " + what + " at " + location.hash); | |
| 57 | await drawn(); | |
| 60 | 58 | } |
| 61 | 59 | }; |
| 62 | const landed = (path) => holds(() => doc().readyState === "complete" && path.test(frame.contentWindow.location.pathname) && doc().querySelector("main, body > *"), "a page at " + path); | |
| 60 | // The forge's place is the address fragment (view.ts): "#/apps/3" is /tab/f/apps/3. | |
| 61 | const at = () => location.hash.slice(1) || "/"; | |
| 62 | const landed = (path) => holds(() => !root.hidden && path.test(at()) && root.querySelector("main, h1, h2, form, p"), "a page at " + path); | |
| 63 | 63 | const out = []; |
| 64 | const note = (step) => out.push({ step, path: frame.contentWindow.location.pathname, text: doc().body.innerText.slice(0, 400) }); | |
| 65 | const go = async (path) => { frame.src = path; await landed(new RegExp("^" + path + "$")); }; | |
| 64 | const note = (step) => out.push({ step, path: at(), text: root.innerText.slice(0, 400) }); | |
| 65 | const go = async (path) => { location.hash = "#" + path; await landed(new RegExp("^" + path + "$")); }; | |
| 66 | 66 | const post = async (step, action, fill, lands) => { |
| 67 | const form = await holds(() => [...doc().querySelectorAll("form")].find((f) => action.test(new URL(f.action).pathname)), "a form for " + step); | |
| 67 | const form = await holds(() => [...root.querySelectorAll("form")].find((f) => action.test(new URL(f.action).pathname)), "a form for " + step); | |
| 68 | 68 | fill(form); |
| 69 | const before = doc(); | |
| 69 | const before = root.innerHTML; | |
| 70 | 70 | form.requestSubmit(); |
| 71 | await holds(() => doc() !== before, step + " to load a page"); | |
| 71 | await holds(() => root.innerHTML !== before, step + " to draw a page"); | |
| 72 | 72 | await landed(lands); |
| 73 | 73 | note(step); |
| 74 | 74 | }; |
| 75 | await landed(/^\\/tab\\/f\\/$/); | |
| 76 | await post("make", /^\\/tab\\/f\\/apps$/, (f) => { f.elements.say.value = "Track my water"; }, /^\\/tab\\/f\\/apps\\/\\d+$/); | |
| 77 | const app = frame.contentWindow.location.pathname; | |
| 75 | await landed(/^\\/$/); | |
| 76 | await post("make", /^\\/tab\\/f\\/apps$/, (f) => { f.elements.say.value = "Track my water"; }, /^\\/apps\\/\\d+$/); | |
| 77 | const app = at(); | |
| 78 | 78 | await post("edit", /^\\/tab\\/f\\/apps\\/\\d+\\/\\d+\\/[a-z]+$/, (f) => { |
| 79 | 79 | for (const i of f.querySelectorAll("input:not([type=hidden])")) if (i.value === "") i.value = i.type === "number" ? "1" : "a glass"; |
| 80 | 80 | }, new RegExp("^" + app + "$")); |
| 81 | await go("/tab/f/issues"); | |
| 82 | await post("issue", /^\\/tab\\/f\\/issues$/, (f) => { f.elements.title.value = "Filed from a real form"; f.elements.body.value = "by the browser test"; }, /^\\/tab\\/f\\/issues\\/\\d+$/); | |
| 83 | await go("/tab/f/"); | |
| 84 | await post("import", /^\\/tab\\/f\\/import$/, (f) => { f.elements.spec.value = ${JSON.stringify(makeSpec("Imported back", undefined))}; }, /^\\/tab\\/f\\/$/); | |
| 81 | await go("/issues"); | |
| 82 | await post("issue", /^\\/tab\\/f\\/issues$/, (f) => { f.elements.title.value = "Filed from a real form"; f.elements.body.value = "by the browser test"; }, /^\\/issues\\/\\d+$/); | |
| 83 | await go("/"); | |
| 84 | await post("import", /^\\/tab\\/f\\/import$/, (f) => { f.elements.spec.value = ${JSON.stringify(makeSpec("Imported back", undefined))}; }, /^\\/$/); | |
| 85 | 85 | await go(app); |
| 86 | await post("remove", /\\/delete$/, (f) => { f.elements.confirm.value = /“(.*)”/.exec(f.textContent)[1]; }, /^\\/tab\\/f\\/$/); | |
| 86 | await post("remove", /\\/delete$/, (f) => { f.elements.confirm.value = /“(.*)”/.exec(f.textContent)[1]; }, /^\\/$/); | |
| 87 | 87 | return JSON.stringify(out); |
| 88 | 88 | })()`; |
| 89 | 89 | |
| @@ -148,18 +148,10 @@ describe.skipIf(chromium === undefined)("the tab forge in a real browser (#18258 | ||
| 148 | 148 | expect(JSON.parse(file.json).format).toBe(JSON.parse(makeSpec("x", undefined)).format); |
| 149 | 149 | }); |
| 150 | 150 | |
| 151 | test("each post left the tab's own page, as the worker's guard reads it", () => { | |
| 152 | const origin = new URL(servers.url).origin; | |
| 153 | const header = (h: Record<string, string>, name: string): string | null => | |
| 154 | Object.entries(h).find(([k]) => k.toLowerCase() === name)?.[1] ?? null; | |
| 155 | const seen = walked.posts.map((p) => ({ path: new URL(p.url).pathname, origin: header(p.headers, "origin"), referer: header(p.headers, "referer") ?? "" })); | |
| 156 | const shapes = [/^\/tab\/f\/apps$/, /^\/tab\/f\/apps\/\d+\/\d+\/[a-z]+$/, /^\/tab\/f\/issues$/, /^\/tab\/f\/import$/, /^\/tab\/f\/apps\/\d+\/delete$/]; | |
| 157 | expect(seen.length).toBe(shapes.length); | |
| 158 | shapes.forEach((shape, i) => expect(seen[i]!.path).toMatch(shape)); | |
| 159 | for (const s of seen) { | |
| 160 | expect(fromOwnPage(s.origin, s.referer, origin)).toBe(true); | |
| 161 | expect(s.referer).toStartWith(`${origin}/tab/f/`); | |
| 162 | } | |
| 151 | test("the writes go to the database worker from the page: none is a request to the network", () => { | |
| 152 | // The page draws the forge itself (#18305), so a form post is a message, not a document | |
| 153 | // request: nothing for DevTools to record, and no frame for a guard to read headers from. | |
| 154 | expect(walked.posts).toEqual([]); | |
| 163 | 155 | }); |
| 164 | 156 | }); |
| 165 | 157 |
test/tab-view.test.ts added +147
| @@ -0,0 +1,147 @@ | ||
| 1 | /** | |
| 2 | * The forge in the tab is drawn in the /tab page, not a frame (#18305): links and forms stay there. | |
| 3 | */ | |
| 4 | import { afterEach, expect, test } from "bun:test"; | |
| 5 | import type { TabReply, TabRequest } from "../src/tab/forge.ts"; | |
| 6 | ||
| 7 | const NAMES = ["document", "location", "history", "addEventListener", "DOMParser", "FormData"] as const; | |
| 8 | const saved = new Map(NAMES.map((n) => [n, (globalThis as any)[n]])); | |
| 9 | // The fakes below stand in for browser globals: put the real ones back for the other files. | |
| 10 | afterEach(() => { | |
| 11 | for (const [n, v] of saved) (globalThis as any)[n] = v; | |
| 12 | }); | |
| 13 | ||
| 14 | // A fresh copy per test: the module keeps nothing, but each mount adds its own listeners. | |
| 15 | const fresh = async (tag: string): Promise<typeof import("../src/tab/view.ts")> => { | |
| 16 | const at: string = `../src/tab/view.ts?${tag}`; | |
| 17 | return import(at); | |
| 18 | }; | |
| 19 | ||
| 20 | type Listener = (e: any) => void; | |
| 21 | function setup(hash = "") { | |
| 22 | const listeners: Record<string, Listener> = {}; | |
| 23 | const pushed: string[] = []; | |
| 24 | const doc = { title: "", createElement: () => ({}) }; | |
| 25 | const root = { | |
| 26 | innerHTML: "", hidden: true, focused: 0, | |
| 27 | focus() { this.focused++; }, | |
| 28 | querySelector: () => null, | |
| 29 | addEventListener(type: string, l: Listener) { listeners[type] = l; }, | |
| 30 | }; | |
| 31 | const g = globalThis as any; | |
| 32 | g.document = doc; | |
| 33 | g.location = { hash, origin: "https://forge.test" }; | |
| 34 | g.history = { pushState: (_s: null, _t: string, url: string) => pushed.push(url) }; | |
| 35 | g.addEventListener = () => {}; | |
| 36 | g.DOMParser = class { | |
| 37 | parseFromString(text: string) { | |
| 38 | const title = /<title>(.*?)<\/title>/.exec(text)?.[1] ?? ""; | |
| 39 | const main = /<main>(.*)<\/main>/s.exec(text)?.[1]; | |
| 40 | return { title, querySelector: () => (main === undefined ? null : { innerHTML: main }) }; | |
| 41 | } | |
| 42 | }; | |
| 43 | g.FormData = class { | |
| 44 | constructor(private form: { fields: [string, string][] }) {} | |
| 45 | entries() { return this.form.fields; } | |
| 46 | }; | |
| 47 | return { listeners, pushed, root, doc }; | |
| 48 | } | |
| 49 | ||
| 50 | // Lets the awaited worker replies land: each step is a microtask. | |
| 51 | const settle = async (): Promise<void> => { | |
| 52 | for (let i = 0; i < 30; i++) await Promise.resolve(); | |
| 53 | }; | |
| 54 | ||
| 55 | const page = (title: string, main: string): TabReply => ({ status: 200, html: `<!doctype html><title>${title}</title><main>${main}</main>` }); | |
| 56 | const link = (href: string) => ({ getAttribute: (n: string) => (n === "href" ? href : null), closest: function () { return this; } }); | |
| 57 | const click = (href: string, extra = {}) => ({ target: link(href), button: 0, ctrlKey: false, metaKey: false, shiftKey: false, preventDefault() { this.stopped = true; }, stopped: false, ...extra }); | |
| 58 | ||
| 59 | test("the forge's first page is drawn into the host element, from the address fragment", async () => { | |
| 60 | const { mount } = await fresh("first"); | |
| 61 | const s = setup("#/issues"); | |
| 62 | const asked: TabRequest[] = []; | |
| 63 | mount(s.root as any, async (r) => (asked.push(r), page("Issues", "<h1>Issues</h1>")), "/tab/f/", () => {}); | |
| 64 | await Promise.resolve(); await Promise.resolve(); | |
| 65 | expect(asked[0]).toMatchObject({ method: "GET", path: "/issues" }); | |
| 66 | expect(s.root.innerHTML).toBe("<h1>Issues</h1>"); | |
| 67 | expect(s.root.hidden).toBe(false); | |
| 68 | expect(s.doc.title).toBe("Issues"); | |
| 69 | }); | |
| 70 | ||
| 71 | test("a /tab/f/ link is answered in place and the place goes in the fragment; other links are left alone", async () => { | |
| 72 | const { mount } = await fresh("link"); | |
| 73 | const s = setup(); | |
| 74 | const asked: TabRequest[] = []; | |
| 75 | const kept: string[] = []; | |
| 76 | mount(s.root as any, async (r) => (asked.push(r), page("T", `<p>${r.path}${r.query ?? ""}</p>`)), "/tab/f/", (at) => void kept.push(at)); | |
| 77 | const e = click("/tab/f/issues/3?x=1"); | |
| 78 | s.listeners.click!(e); | |
| 79 | await settle(); | |
| 80 | expect(e.stopped).toBe(true); | |
| 81 | expect(asked.at(-1)).toMatchObject({ method: "GET", path: "/issues/3", query: "x=1" }); | |
| 82 | expect(s.pushed).toEqual(["#/issues/3?x=1"]); | |
| 83 | expect(kept.at(-1)).toBe("/tab/f/issues/3?x=1"); | |
| 84 | const other = click("https://elsewhere.test/tab/f/x"); | |
| 85 | s.listeners.click!(other); | |
| 86 | const outside = click("/issues"); | |
| 87 | s.listeners.click!(outside); | |
| 88 | const modified = click("/tab/f/issues", { ctrlKey: true }); | |
| 89 | s.listeners.click!(modified); | |
| 90 | expect([other.stopped, outside.stopped, modified.stopped]).toEqual([false, false, false]); | |
| 91 | }); | |
| 92 | ||
| 93 | test("a form post is sent to the worker, and its redirect is followed in place", async () => { | |
| 94 | const { mount } = await fresh("form"); | |
| 95 | const s = setup(); | |
| 96 | const asked: TabRequest[] = []; | |
| 97 | mount(s.root as any, async (r) => { | |
| 98 | asked.push(r); | |
| 99 | return r.method === "POST" ? { status: 303, html: "", location: "/tab/f/issues/9" } : page("One", "<h1>nine</h1>"); | |
| 100 | }, "/tab/f/", () => {}); | |
| 101 | const form = { method: "post", fields: [["title", "hello"]] as [string, string][], getAttribute: () => "/tab/f/new", closest: () => form }; | |
| 102 | let stopped = false; | |
| 103 | s.listeners.submit!({ target: form, preventDefault: () => (stopped = true) }); | |
| 104 | await settle(); | |
| 105 | expect(stopped).toBe(true); | |
| 106 | expect(asked.some((r) => r.method === "POST" && r.path === "/new" && r.form.title === "hello")).toBe(true); | |
| 107 | expect(asked.at(-1)).toMatchObject({ method: "GET", path: "/issues/9" }); | |
| 108 | expect(s.root.innerHTML).toBe("<h1>nine</h1>"); | |
| 109 | expect(s.pushed).toEqual(["#/issues/9"]); | |
| 110 | }); | |
| 111 | ||
| 112 | test("a form that posts elsewhere is not taken", async () => { | |
| 113 | const { mount } = await fresh("away"); | |
| 114 | const s = setup(); | |
| 115 | mount(s.root as any, async () => page("T", "x"), "/tab/f/", () => {}); | |
| 116 | const form = { method: "post", fields: [], getAttribute: () => "https://evil.test/tab/f/new", closest: () => form }; | |
| 117 | let stopped = false; | |
| 118 | s.listeners.submit!({ target: form, preventDefault: () => (stopped = true) }); | |
| 119 | expect(stopped).toBe(false); | |
| 120 | }); | |
| 121 | ||
| 122 | test("with no fragment it opens on the page it was told to, and remembers it", async () => { | |
| 123 | const { mount } = await fresh("open"); | |
| 124 | const s = setup(); | |
| 125 | const asked: TabRequest[] = []; | |
| 126 | const kept: string[] = []; | |
| 127 | mount(s.root as any, async (r) => (asked.push(r), page("T", "x")), "/tab/f/issues", (at) => void kept.push(at)); | |
| 128 | await settle(); | |
| 129 | expect(asked[0]).toMatchObject({ path: "/issues" }); | |
| 130 | expect(kept).toEqual(["/tab/f/issues"]); | |
| 131 | }); | |
| 132 | ||
| 133 | test("a failed post is not remembered, and says so in a sentence with a way out", async () => { | |
| 134 | const { mount } = await fresh("failed"); | |
| 135 | const s = setup(""); | |
| 136 | const heard: string[] = []; | |
| 137 | const ask = async (req: TabRequest): Promise<TabReply> => (req.method === "POST" ? { status: 503, html: "<!doctype html><title>Stopped</title><p>stopped</p>" } : page("Home", "<h1>Home</h1>")); | |
| 138 | mount(s.root, ask, "/tab/f/", (at) => heard.push(at)); | |
| 139 | await settle(); | |
| 140 | expect(heard).toEqual(["/tab/f/"]); | |
| 141 | const form = { getAttribute: (n: string) => (n === "action" ? "/tab/f/new" : null), method: "post", fields: [["title", "x"]], preventDefault() {} }; | |
| 142 | s.listeners.submit!({ target: form, preventDefault() {} }); | |
| 143 | await settle(); | |
| 144 | expect(heard).toEqual(["/tab/f/"]); | |
| 145 | expect(s.root.innerHTML).toContain("did not work"); | |
| 146 | expect(s.root.innerHTML).toContain('href="/tab/f/"'); | |
| 147 | }); |
test/tab.test.ts +4 −1
| @@ -196,7 +196,10 @@ describe("what the server holds of it", () => { | ||
| 196 | 196 | expect(text).toContain('<p id="tab-go" hidden>'); |
| 197 | 197 | expect(text).toContain("<noscript><p>A forge in a tab needs JavaScript"); |
| 198 | 198 | expect(text).not.toContain("Not started."); |
| 199 | expect(res.headers.get("content-security-policy")).toContain("frame-src 'self'"); | |
| 199 | // The forge is drawn in the page: no frame, so none is allowed and none is in the markup. | |
| 200 | expect(res.headers.get("content-security-policy")).not.toContain("frame-src 'self'"); | |
| 201 | expect(text).not.toContain("<iframe"); | |
| 202 | expect(text).toContain('id="tab-view"'); | |
| 200 | 203 | const said: string[] = []; |
| 201 | 204 | entry.run(new Session(app, { sshUsername: "guest", remoteAddress: "127.0.0.1" }), { ...quietCtx(), toast: (m: string) => void said.push(m) }); |
| 202 | 205 | expect(said).toEqual([tabLine()]); |
new above
offline
Two doc comments are stacked on previewMarkup. Delete the old one-liner.