It was blank until every module had loaded and the page's examples had been run, a fuzzer's report among them (about a second of work): first paint came 1.3 seconds into a repeat visit and about 3 into a first one. - The assembler draws the home page once, in Node, with the app's own homeView, and puts it inside #app. The browser paints it with the HTML and the stylesheet. - When the app has loaded it draws the page again, with its controls, and puts it in the prerendered one's place; the fuzzer's reports and the proof's counts are copied from the prerendered page, not worked out again. - The prerendered page shows only on the home address: the page's first inline script marks it before the first paint, and without the mark it stays hidden, so an embed or a problem's address never shows it. That script changed, and its hash in docs/Caddyfile with it. Served locally, first paint is at 0.1 to 0.2 seconds and the page with its controls at 0.2 to 0.3; both were at 1.2 to 1.4.
197 lines
12 KiB
TypeScript
197 lines
12 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
/**
|
|
* Entry point: a hash router over three screens (home, app, embed).
|
|
*/
|
|
import { el, clear, add } from './ui/dom.js';
|
|
import { Shell } from './ui/shell.js';
|
|
import { mountEmbed } from './ui/embed.js';
|
|
import { Session, sharedSession } from './core/session.js';
|
|
import { problemById, stateForProblem } from './core/catalog.js';
|
|
import { parseRoute, decodeState, loadLocal, migrateLocal, type PlayState, embedStorageId, clearLocal, editedFrom, applyEmbedParams, resolveSaved, isUnknownRoute, anchorOnly } from './core/state.js';
|
|
import { takeCrashed, settle, setAside, markBusy } from './core/guard.js';
|
|
import { notice, messagePage } from './ui/notice.js';
|
|
import { homeView } from './ui/home.js';
|
|
import { prerenderedHome } from './ui/prerender.js';
|
|
import { siteNav } from './ui/nav.js';
|
|
import { quartoView } from './ui/quarto.js';
|
|
import { libraryView } from './ui/library.js';
|
|
import { libraryState } from './core/library.js';
|
|
import { forceTheme, watchTheme } from './ui/theme.js';
|
|
|
|
/** The home page's title, as index.html has it before the app starts. */
|
|
const HOME_TITLE = 'Programming+: from an idea to Mojo to the machine';
|
|
import { AREAS, isAreaId, paneForArea, type AreaId } from './core/areas.js';
|
|
|
|
migrateLocal();
|
|
watchTheme();
|
|
const app = document.getElementById('app')!;
|
|
let shell: Shell | null = null;
|
|
/** The save whose work was running when the page last died (core/guard.ts): it is set aside, not opened again. */
|
|
let crashed = takeCrashed();
|
|
// a page that closes normally did not die of what it was running (the mark is this tab's: core/guard.ts)
|
|
window.addEventListener('pagehide', () => settle());
|
|
|
|
/** Where the route's work came from, so a failure to open it can offer to put a save aside. */
|
|
interface Opened { area: AreaId; state: PlayState; original?: PlayState; stale?: boolean; savedId?: string; embed?: { view: any; params: URLSearchParams; original: PlayState; storageId: string | null } }
|
|
type Resolved = Opened | { missing: { title: string; text: string } } | null;
|
|
|
|
const noProblem = (id: string) => ({ missing: { title: 'No such problem', text: `Programming+ has no problem called "${id.slice(0, 80)}". It may have been renamed, or the link may be cut short.` } });
|
|
|
|
async function stateForRoute(): Promise<Resolved> {
|
|
const r = parseRoute(location.hash);
|
|
if (r.kind === 'home' || r.kind === 'quarto' || r.kind === 'library') return null;
|
|
if (r.kind === 'problem') {
|
|
const p = problemById(r.id);
|
|
const original = p ? stateForProblem(p) : libraryState(r.id);
|
|
if (!original) return noProblem(r.id);
|
|
let saved = loadLocal(r.id);
|
|
if (saved && crashed === r.id) {
|
|
// this save was running when the page died: keep it as a version and open the problem as written
|
|
crashed = null;
|
|
const name = setAside(r.id, saved, r.area, 'stopped');
|
|
if (name) { saved = null; notice(`The last time this problem was open, the page stopped while it ran your program (it may have used up the browser's memory). Your work is kept as the version "${name}" in the Versions menu, and the problem opens as written.`); }
|
|
}
|
|
const { state, stale } = resolveSaved(original, saved);
|
|
state.lang = paneForArea(AREAS[r.area], state, true);
|
|
return { area: r.area, state, original, stale, savedId: saved ? r.id : undefined };
|
|
}
|
|
// a shared state is the sender's: it is never saved over this browser's own save for its problem
|
|
if (r.kind === 'shared') return { area: r.area, state: await decodeState(r.blob) };
|
|
if (r.kind === 'embed') {
|
|
let state: PlayState | null = null;
|
|
if (r.problem) { const p = problemById(r.problem); if (p) state = stateForProblem(p); else return noProblem(r.problem); }
|
|
else if (r.blob) state = await decodeState(r.blob);
|
|
if (!state) return { missing: { title: 'Nothing to show', text: 'This embed names no program: its address ends where the program should be.' } };
|
|
// the query arranges the example (pane, panel, panes, build, layout) as the page author asked
|
|
const asked = r.params.get('area');
|
|
const area: AreaId = isAreaId(asked) ? asked : r.problem && problemById(r.problem) ? problemById(r.problem)!.area : 'bridge';
|
|
state = applyEmbedParams(state, r.params, area);
|
|
// the reader's edits live in the embed's own save; a read-only embed has none to keep
|
|
const storageId = r.params.get('ro') === '1' ? null : embedStorageId(String(r.view), r.problem, r.blob);
|
|
// a reader's edits that were running when the page died are dropped: the author's example opens
|
|
if (storageId && crashed === storageId) { crashed = null; clearLocal(storageId); }
|
|
const saved = storageId ? loadLocal(storageId) : null;
|
|
// a copy: the session edits its state in place, and the original must stay the author's
|
|
return { area, state: saved ?? state, embed: { view: r.view, params: r.params, original: structuredClone(state), storageId } };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Bring the section the address names to the top. On a page already on screen the move is shown (`built` false).
|
|
* A page built this moment is still waiting for its fonts, and when they arrive the text above the section changes
|
|
* height: a move started before that ends short of the heading or past it. So there the page goes straight to the
|
|
* section, and once more when the fonts are in, unless the reader has gone elsewhere by then.
|
|
*/
|
|
function scrollToAnchor(built = false): void {
|
|
const m = /#(problems|reference|quarto-teaser)$/.exec(location.hash) ?? /^#\/quarto#([\w-]+)$/.exec(location.hash);
|
|
if (!m) return;
|
|
const go = (behavior: ScrollBehavior) => document.getElementById(m[1]!)?.scrollIntoView({ behavior, block: 'start' });
|
|
if (!built) { requestAnimationFrame(() => go(matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth')); return; }
|
|
const hash = location.hash;
|
|
requestAnimationFrame(() => {
|
|
go('auto');
|
|
const at = window.scrollY;
|
|
void document.fonts?.ready.then(() => { if (location.hash === hash && Math.abs(window.scrollY - at) < 200) go('auto'); });
|
|
});
|
|
}
|
|
|
|
/** In a host page (the Quarto extension's pplus.js), follow its light/dark switch: the host posts
|
|
* {type:'pplus:theme', theme} whenever it changes, and answers our 'pplus:ready' with the current one. */
|
|
let following = false;
|
|
function followHostTheme(): void {
|
|
if (following || window.parent === window) return;
|
|
following = true;
|
|
window.addEventListener('message', (ev) => {
|
|
const d = ev.data;
|
|
if (ev.source === window.parent && d && d.type === 'pplus:theme' && (d.theme === 'light' || d.theme === 'dark')) forceTheme(d.theme);
|
|
});
|
|
window.parent.postMessage({ type: 'pplus:ready' }, '*');
|
|
}
|
|
|
|
async function render(): Promise<void> {
|
|
try { await show(); } catch (e: any) {
|
|
// whatever went wrong, the page says so and offers a way on, rather than staying blank
|
|
shell?.destroy(); shell = null;
|
|
clear(app);
|
|
const r = (() => { try { return parseRoute(location.hash); } catch { return null; } })();
|
|
const saved = r?.kind === 'problem' ? loadLocal(r.id) : null;
|
|
const actions: Node[] = [];
|
|
if (r?.kind === 'problem' && saved) actions.push(el('button', { type: 'button', class: 'btn btn-primary', onClick: () => {
|
|
const name = setAside(r.id, saved, r.area, 'failed');
|
|
if (!name && !confirm('This browser would not keep a copy of your saved work as a version. Discard it, and open the problem as written?')) return;
|
|
if (!name) clearLocal(r.id);
|
|
void render();
|
|
} }, 'Keep my work as a version, and open the problem as written'));
|
|
add(app, messagePage('This did not open', `Programming+ could not show this page: ${String(e?.message || e).slice(0, 300)}`, ...actions));
|
|
console.error(e);
|
|
}
|
|
}
|
|
|
|
async function show(): Promise<void> {
|
|
const route = parseRoute(location.hash);
|
|
// the same static page with only the anchor changed: scroll, do not rebuild
|
|
if (!shell && anchorOnly(location.hash, app.firstElementChild ? [...app.firstElementChild.classList] : null)) { scrollToAnchor(); return; }
|
|
shell?.destroy(); shell = null;
|
|
// the home page drawn by the assembler stays on screen until the one with its controls is ready to take its place
|
|
const prerendered = route.kind === 'home' ? prerenderedHome() : null;
|
|
if (!prerendered) clear(app);
|
|
document.body.classList.remove('is-embed');
|
|
let resolved: Resolved;
|
|
try { resolved = await stateForRoute(); } catch (e: any) {
|
|
add(app, messagePage('That link did not open', String(e?.message || e)));
|
|
return;
|
|
}
|
|
if (resolved && 'missing' in resolved) {
|
|
// in the app the page keeps the site's navigation and offers the problem list; an embed is somebody's page, so it says what is missing and no more
|
|
const inApp = route.kind !== 'embed';
|
|
const page = messagePage(resolved.missing.title, resolved.missing.text, ...(inApp ? [el('a', { class: 'btn btn-primary', href: '#/#problems' }, 'Browse the problems')] : []));
|
|
if (inApp) page.insertBefore(siteNav('home'), page.firstChild);
|
|
add(app, page); document.title = `${resolved.missing.title} · Programming+`; return;
|
|
}
|
|
if (!resolved && route.kind === 'library') { add(app, libraryView(route.id)); document.title = `${route.id ? `${route.id} · ` : ''}Library · Programming+`; window.scrollTo(0, 0); return; }
|
|
if (!resolved && route.kind === 'quarto') { add(app, quartoView()); document.title = 'With Quarto · Programming+'; if (route.anchor) scrollToAnchor(true); else window.scrollTo(0, 0); return; }
|
|
if (!resolved) {
|
|
const home = homeView();
|
|
if (prerendered) clear(app);
|
|
add(app, home); document.title = HOME_TITLE; scrollToAnchor(true);
|
|
if (isUnknownRoute(location.hash)) notice('There is no page at that address, so this is the home page. Links from before the three areas open here too.');
|
|
return;
|
|
}
|
|
const embedded = resolved.embed;
|
|
const session = route.kind === 'shared' ? sharedSession(resolved.state, resolved.area) : new Session(resolved.state, embedded
|
|
? { storageId: embedded.storageId, keep: (st) => editedFrom(st, embedded.original), area: resolved.area }
|
|
: { original: resolved.original, stale: resolved.stale, area: resolved.area });
|
|
// saved work runs as the page opens: if it takes the page down, the next load sets it aside (core/guard.ts)
|
|
const busy = resolved.savedId ?? (embedded?.storageId && loadLocal(embedded.storageId) ? embedded.storageId : null);
|
|
if (busy) markBusy(busy);
|
|
document.title = `${resolved.state.title || 'Playground'} · Programming+`;
|
|
if (resolved.embed) {
|
|
document.body.classList.add('is-embed');
|
|
const th = resolved.embed.params.get('theme');
|
|
if (th === 'light' || th === 'dark') forceTheme(th);
|
|
followHostTheme();
|
|
const { original, storageId } = resolved.embed;
|
|
const reset = storageId ? () => { clearLocal(storageId); void render(); } : undefined;
|
|
if (resolved.embed.view === 'playground') {
|
|
// the whole playground in the frame, with the reader's edits in the embed's own save
|
|
document.body.classList.add('is-embed-playground');
|
|
shell = new Shell(session, AREAS[resolved.area], { embed: { reset, edited: () => editedFrom(session.state, original), readOnly: resolved.embed.params.get('ro') === '1' } });
|
|
add(app, shell.root);
|
|
return;
|
|
}
|
|
add(app, mountEmbed(session, resolved.embed.view, resolved.embed.params, {
|
|
original,
|
|
reset,
|
|
}));
|
|
return;
|
|
}
|
|
shell = new Shell(session, AREAS[resolved.area]);
|
|
add(app, shell.root);
|
|
}
|
|
|
|
window.addEventListener('hashchange', () => void render());
|
|
window.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { const btn = document.querySelector<HTMLButtonElement>('.btn-primary'); btn?.click(); e.preventDefault(); } });
|
|
void render();
|