/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / main.ts
171 lines · 5.9 KBBlameHistoryRaw
1// Album shell: hash routes
2// #/ track list
3// #/<id> a composition (visitor: published defaults only)
4// #/<id>/edit the same composition with the author panel
5import "./style.css";
6import { getAudio } from "./core/audio.ts";
7import { createAuthorPanel } from "./core/authorPanel.ts";
8import type { Composition, Piece } from "./core/composition.ts";
9import { resolveParams } from "./core/params.ts";
10import type { Params } from "./core/params.ts";
11import { ALBUM_TITLE, COMPOSITIONS } from "./compositions/index.ts";
13const app = document.getElementById("app")!;
14let teardown: (() => void) | null = null;
16function h<K extends keyof HTMLElementTagNameMap>(tag: K, props: Record<string, unknown> = {}, ...kids: (Node | string)[]): HTMLElementTagNameMap[K] {
17 const e = Object.assign(document.createElement(tag), props) as HTMLElementTagNameMap[K];
18 e.append(...kids);
19 return e;
22function route() {
23 teardown?.();
24 teardown = null;
25 app.replaceChildren();
26 const parts = location.hash.replace(/^#\/?/, "").split("/").filter(Boolean);
27 const comp = COMPOSITIONS.find((c) => c.id === parts[0]);
28 if (!comp) return showAlbum();
29 teardown = showComposition(comp, parts[1] === "edit");
32function showAlbum() {
33 document.title = ALBUM_TITLE;
34 const list = h("ol", { className: "tracks" });
35 for (const c of COMPOSITIONS) list.append(h("li", {}, h("a", { href: `#/${c.id}`, textContent: c.title })));
36 app.append(h("main", { className: "album" }, h("h1", { textContent: ALBUM_TITLE }), list));
39const storageKey = (c: Composition) => `double-pendulum:author:${c.id}`;
41function loadEdits(c: Composition): Partial<Params> | null {
42 try {
43 const s = localStorage.getItem(storageKey(c));
44 return s ? JSON.parse(s) : null;
45 } catch {
46 return null;
47 }
50function saveEdits(c: Composition, p: Params) {
51 try {
52 localStorage.setItem(storageKey(c), JSON.stringify(p));
53 } catch {
54 /* storage unavailable: edits last for this page view only */
55 }
58function showComposition(comp: Composition, author: boolean): () => void {
59 const index = COMPOSITIONS.indexOf(comp) + 1;
60 document.title = `${comp.title} · ${ALBUM_TITLE}`;
61 const published = () => resolveParams(comp.schema, comp.defaults);
62 let params = author ? resolveParams(comp.schema, comp.defaults, loadEdits(comp)) : published();
64 const view = h("div", { className: "view" });
65 const bigPlay = h("button", { className: "big-play", textContent: "▶", title: "play" });
66 bigPlay.setAttribute("aria-label", "play");
67 const playBtn = h("button", { className: "play", textContent: "play" });
68 const bar = h("div", { className: "bar" });
69 const progress = h("div", { className: "progress" }, bar);
70 const editLink = h("a", { className: "edit", href: author ? `#/${comp.id}` : `#/${comp.id}/edit`, textContent: author ? "done" : "edit" });
71 const header = h(
72 "header",
73 {},
74 h("a", { href: "#/", textContent: ALBUM_TITLE }),
75 h("span", { className: "sep", textContent: " / " }),
76 h("span", { textContent: `${index}. ${comp.title}` }),
77 );
78 const noticeEl = h("div", { className: "notice" });
79 const stage = h("main", { className: "stage" }, header, noticeEl, view, h("div", { className: "transport" }, playBtn, progress, editLink));
80 const page = h("div", { className: author ? "page with-author" : "page" }, stage);
81 app.append(page);
83 const piece: Piece = comp.create(view, () => params);
84 view.append(bigPlay);
85 // canvases fill the largest square that fits between the header and the transport
86 const fit = () => {
87 const s = Math.floor(Math.min(view.clientWidth, view.clientHeight));
88 for (const c of view.querySelectorAll("canvas")) {
89 c.style.width = `${s}px`;
90 c.style.height = `${s}px`;
91 }
92 };
93 const ro = new ResizeObserver(fit);
94 ro.observe(view);
95 fit();
96 const startAt = { value: 0 };
98 let starting = false; // instruments can take a moment to load; don't offer play twice
99 const play = async (offset: number) => {
100 starting = true;
101 try {
102 const audio = await getAudio();
103 await piece.start(audio, offset);
104 } finally {
105 starting = false;
106 }
107 };
108 playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0));
109 bigPlay.onclick = () => playBtn.click();
110 if (author) {
111 // author can click the progress line to jump
112 progress.classList.add("seekable");
113 progress.onclick = (ev) => {
114 const r = progress.getBoundingClientRect();
115 const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length());
116 void play(t);
117 };
118 }
120 let panel: ReturnType<typeof createAuthorPanel> | null = null;
121 if (author) {
122 panel = createAuthorPanel({
123 schema: comp.schema,
124 get: () => params,
125 set: (p) => {
126 params = p;
127 saveEdits(comp, p);
128 },
129 defaults: published,
130 readouts: () => piece.readouts(),
131 startAt,
132 });
133 page.append(panel.el);
134 }
136 const onKey = (e: KeyboardEvent) => {
137 const tag = (e.target as HTMLElement).tagName;
138 if (e.code === "Space" && tag !== "INPUT" && tag !== "SELECT" && tag !== "BUTTON") {
139 e.preventDefault();
140 playBtn.click();
141 }
142 };
143 window.addEventListener("keydown", onKey);
145 let raf = 0;
146 let lastReadout = 0;
147 const frame = (ts: number) => {
148 piece.draw();
149 playBtn.textContent = piece.playing ? "stop" : "play";
150 bigPlay.hidden = piece.playing || starting;
151 const note = piece.notice?.() ?? "";
152 if (noticeEl.textContent !== note) noticeEl.textContent = note;
153 bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`;
154 if (panel && ts - lastReadout > 200) {
155 panel.updateReadouts();
156 lastReadout = ts;
157 }
158 raf = requestAnimationFrame(frame);
159 };
160 raf = requestAnimationFrame(frame);
162 return () => {
163 cancelAnimationFrame(raf);
164 window.removeEventListener("keydown", onKey);
165 ro.disconnect();
166 piece.dispose();
167 };
170window.addEventListener("hashchange", route);
171route();
↑↓ move↵openescclose