// Album shell: hash routes // #/ track list // #/ a composition (visitor: published defaults only) // #//edit the same composition with the author panel import "./style.css"; import { getAudio } from "./core/audio.ts"; import { createAuthorPanel } from "./core/authorPanel.ts"; import type { Composition, Piece } from "./core/composition.ts"; import { resolveParams } from "./core/params.ts"; import type { Params } from "./core/params.ts"; import { ALBUM_TITLE, COMPOSITIONS } from "./compositions/index.ts"; const app = document.getElementById("app")!; let teardown: (() => void) | null = null; function h(tag: K, props: Record = {}, ...kids: (Node | string)[]): HTMLElementTagNameMap[K] { const e = Object.assign(document.createElement(tag), props) as HTMLElementTagNameMap[K]; e.append(...kids); return e; } /** Old composition ids → current ones (so old links keep working). */ const RENAMED: Record = { "04-crash": "04-descent", ensemble: "05-ensemble" }; // carry saved author edits over to renamed compositions (once) for (const [from, to] of Object.entries(RENAMED)) { try { const old = localStorage.getItem(`double-pendulum:author:${from}`); if (old !== null && localStorage.getItem(`double-pendulum:author:${to}`) === null) localStorage.setItem(`double-pendulum:author:${to}`, old); localStorage.removeItem(`double-pendulum:author:${from}`); } catch { /* no storage */ } } function route() { teardown?.(); teardown = null; app.replaceChildren(); const parts = location.hash.replace(/^#\/?/, "").split("/").filter(Boolean); if (parts[0] && RENAMED[parts[0]]) { location.replace(`#/${[RENAMED[parts[0]], ...parts.slice(1)].join("/")}`); return; } const comp = COMPOSITIONS.find((c) => c.id === parts[0]); if (!comp) return showAlbum(); teardown = showComposition(comp, parts[1] === "edit"); } function showAlbum() { document.title = ALBUM_TITLE; const list = h("ol", { className: "tracks" }); for (const c of COMPOSITIONS) if (!c.hidden) list.append(h("li", {}, h("a", { href: `#/${c.id}`, textContent: c.title }))); app.append(h("main", { className: "album" }, h("h1", { textContent: ALBUM_TITLE }), list)); } const storageKey = (c: Composition) => `double-pendulum:author:${c.id}`; function loadEdits(c: Composition): Partial | null { try { const s = localStorage.getItem(storageKey(c)); return s ? JSON.parse(s) : null; } catch { return null; } } function saveEdits(c: Composition, p: Params) { try { localStorage.setItem(storageKey(c), JSON.stringify(p)); } catch { /* storage unavailable: edits last for this page view only */ } } function showComposition(comp: Composition, author: boolean): () => void { const index = COMPOSITIONS.filter((c) => !c.hidden).indexOf(comp) + 1; document.title = `${comp.title} · ${ALBUM_TITLE}`; const published = () => resolveParams(comp.schema, comp.defaults); let params = author ? resolveParams(comp.schema, comp.defaults, loadEdits(comp)) : published(); const view = h("div", { className: "view" }); const bigPlay = h("button", { className: "big-play", textContent: "▶", title: "play" }); bigPlay.setAttribute("aria-label", "play"); const playBtn = h("button", { className: "play", textContent: "play" }); const bar = h("div", { className: "bar" }); const progress = h("div", { className: "progress" }, bar); const editLink = h("a", { className: "edit", href: author ? `#/${comp.id}` : `#/${comp.id}/edit`, textContent: author ? "done" : "edit" }); const header = h( "header", {}, h("a", { href: "#/", textContent: ALBUM_TITLE }), h("span", { className: "sep", textContent: " / " }), h("span", { textContent: comp.hidden ? comp.title : `${index}. ${comp.title}` }), ); const noticeEl = h("div", { className: "notice" }); const stage = h("main", { className: "stage" }, header, noticeEl, view, h("div", { className: "transport" }, playBtn, progress, editLink)); const page = h("div", { className: author ? "page with-author" : "page" }, stage); app.append(page); const piece: Piece = comp.create(view, () => params); view.append(bigPlay); // canvases fill the largest square that fits between the header and the transport const fit = () => { const s = Math.floor(Math.min(view.clientWidth, view.clientHeight)); for (const c of view.querySelectorAll("canvas")) { c.style.width = `${s}px`; c.style.height = `${s}px`; } }; const ro = new ResizeObserver(fit); ro.observe(view); fit(); const startAt = { value: 0 }; let starting = false; // instruments can take a moment to load; don't offer play twice const play = async (offset: number) => { starting = true; try { const audio = await getAudio(); await piece.start(audio, offset); } finally { starting = false; } }; playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0)); bigPlay.onclick = () => playBtn.click(); if (author) { // author can click the progress line to jump progress.classList.add("seekable"); progress.onclick = (ev) => { const r = progress.getBoundingClientRect(); const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length()); void play(t); }; } let panel: ReturnType | null = null; if (author) { panel = createAuthorPanel({ schema: comp.schema, get: () => params, set: (p) => { params = p; saveEdits(comp, p); }, defaults: published, readouts: () => piece.readouts(), startAt, }); page.append(panel.el); } const onKey = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (e.code === "Space" && tag !== "INPUT" && tag !== "SELECT" && tag !== "BUTTON") { e.preventDefault(); playBtn.click(); } }; window.addEventListener("keydown", onKey); let raf = 0; let lastReadout = 0; const frame = (ts: number) => { piece.draw(); playBtn.textContent = piece.playing ? "stop" : "play"; bigPlay.hidden = piece.playing || starting; const note = piece.notice?.() ?? ""; if (noticeEl.textContent !== note) noticeEl.textContent = note; bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`; if (panel && ts - lastReadout > 200) { panel.updateReadouts(); lastReadout = ts; } raf = requestAnimationFrame(frame); }; raf = requestAnimationFrame(frame); return () => { cancelAnimationFrame(raf); window.removeEventListener("keydown", onKey); ro.disconnect(); piece.dispose(); }; } window.addEventListener("hashchange", route); route();