/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / main.ts
196 lines · 7.2 KBCodeBlameHistory
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 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;
e8001dcRename composition 4: crash → descentJeremy Magland 22/** Old composition ids → current ones (so old links keep working). */
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 23const RENAMED: Record<string, string> = { "04-crash": "04-descent", ensemble: "05-ensemble" };
25// carry saved author edits over to renamed compositions (once)
26for (const [from, to] of Object.entries(RENAMED)) {
27 try {
28 const old = localStorage.getItem(`double-pendulum:author:${from}`);
29 if (old !== null && localStorage.getItem(`double-pendulum:author:${to}`) === null) localStorage.setItem(`double-pendulum:author:${to}`, old);
30 localStorage.removeItem(`double-pendulum:author:${from}`);
31 } catch {
32 /* no storage */
33 }
37 teardown?.();
38 teardown = null;
39 app.replaceChildren();
40 const parts = location.hash.replace(/^#\/?/, "").split("/").filter(Boolean);
e8001dcRename composition 4: crash → descentJeremy Magland 41 if (parts[0] && RENAMED[parts[0]]) {
42 location.replace(`#/${[RENAMED[parts[0]], ...parts.slice(1)].join("/")}`);
43 return;
44 }
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 45 const comp = COMPOSITIONS.find((c) => c.id === parts[0]);
46 if (!comp) return showAlbum();
47 teardown = showComposition(comp, parts[1] === "edit");
50function showAlbum() {
51 document.title = ALBUM_TITLE;
52 const list = h("ol", { className: "tracks" });
d8370f3Lab: the double pendulum as an instrument (#/lab/edit)Jeremy Magland 53 for (const c of COMPOSITIONS) if (!c.hidden) list.append(h("li", {}, h("a", { href: `#/${c.id}`, textContent: c.title })));
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 54 app.append(h("main", { className: "album" }, h("h1", { textContent: ALBUM_TITLE }), list));
57const storageKey = (c: Composition) => `double-pendulum:author:${c.id}`;
59function loadEdits(c: Composition): Partial<Params> | null {
60 try {
61 const s = localStorage.getItem(storageKey(c));
62 return s ? JSON.parse(s) : null;
63 } catch {
64 return null;
65 }
68function saveEdits(c: Composition, p: Params) {
69 try {
70 localStorage.setItem(storageKey(c), JSON.stringify(p));
71 } catch {
72 /* storage unavailable: edits last for this page view only */
73 }
76function showComposition(comp: Composition, author: boolean): () => void {
d8370f3Lab: the double pendulum as an instrument (#/lab/edit)Jeremy Magland 77 const index = COMPOSITIONS.filter((c) => !c.hidden).indexOf(comp) + 1;
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 78 document.title = `${comp.title} · ${ALBUM_TITLE}`;
79 const published = () => resolveParams(comp.schema, comp.defaults);
80 let params = author ? resolveParams(comp.schema, comp.defaults, loadEdits(comp)) : published();
82 const view = h("div", { className: "view" });
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 83 const bigPlay = h("button", { className: "big-play", textContent: "▶", title: "play" });
84 bigPlay.setAttribute("aria-label", "play");
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 85 const playBtn = h("button", { className: "play", textContent: "play" });
86 const bar = h("div", { className: "bar" });
87 const progress = h("div", { className: "progress" }, bar);
88 const editLink = h("a", { className: "edit", href: author ? `#/${comp.id}` : `#/${comp.id}/edit`, textContent: author ? "done" : "edit" });
89 const header = h(
90 "header",
91 {},
92 h("a", { href: "#/", textContent: ALBUM_TITLE }),
93 h("span", { className: "sep", textContent: " / " }),
d8370f3Lab: the double pendulum as an instrument (#/lab/edit)Jeremy Magland 94 h("span", { textContent: comp.hidden ? comp.title : `${index}. ${comp.title}` }),
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 96 const noticeEl = h("div", { className: "notice" });
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 97 // shown while the performance is computing ahead (at the start, or if it has to catch up)
98 const bufferingEl = h("div", { className: "buffering", hidden: true }, h("div", { className: "spinner" }), h("div", { className: "fill" }));
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 99 const stage = h("main", { className: "stage" }, header, noticeEl, view, h("div", { className: "transport" }, playBtn, progress, editLink));
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 100 const page = h("div", { className: author ? "page with-author" : "page" }, stage);
101 app.append(page);
103 const piece: Piece = comp.create(view, () => params);
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 104 view.append(bigPlay, bufferingEl);
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 105 // canvases fill the largest square that fits between the header and the transport
106 const fit = () => {
107 const s = Math.floor(Math.min(view.clientWidth, view.clientHeight));
108 for (const c of view.querySelectorAll("canvas")) {
109 c.style.width = `${s}px`;
110 c.style.height = `${s}px`;
111 }
112 };
113 const ro = new ResizeObserver(fit);
114 ro.observe(view);
115 fit();
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 116 const startAt = { value: 0 };
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 118 let starting = false; // instruments can take a moment to load; don't offer play twice
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 119 const play = async (offset: number) => {
121 try {
122 const audio = await getAudio();
123 await piece.start(audio, offset);
124 } finally {
125 starting = false;
126 }
128 playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0));
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 129 bigPlay.onclick = () => playBtn.click();
131 // author can click the progress line to jump
132 progress.classList.add("seekable");
133 progress.onclick = (ev) => {
134 const r = progress.getBoundingClientRect();
135 const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length());
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 136 if (piece.playing && piece.seek) piece.seek(t);
137 else void play(t);
139 }
141 let panel: ReturnType<typeof createAuthorPanel> | null = null;
142 if (author) {
143 panel = createAuthorPanel({
144 schema: comp.schema,
145 get: () => params,
146 set: (p) => {
147 params = p;
148 saveEdits(comp, p);
149 },
150 defaults: published,
151 readouts: () => piece.readouts(),
152 startAt,
153 });
154 page.append(panel.el);
155 }
157 const onKey = (e: KeyboardEvent) => {
158 const tag = (e.target as HTMLElement).tagName;
159 if (e.code === "Space" && tag !== "INPUT" && tag !== "SELECT" && tag !== "BUTTON") {
160 e.preventDefault();
161 playBtn.click();
162 }
163 };
164 window.addEventListener("keydown", onKey);
166 let raf = 0;
167 let lastReadout = 0;
168 const frame = (ts: number) => {
169 piece.draw();
170 playBtn.textContent = piece.playing ? "stop" : "play";
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 171 bigPlay.hidden = piece.playing || starting;
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 172 const st = piece.playing ? piece.status?.() : undefined;
173 const buffering = !!st?.buffering || starting;
174 bufferingEl.hidden = !buffering;
175 if (buffering) (bufferingEl.lastChild as HTMLElement).textContent = `${Math.round(100 * (st?.fill ?? 0))}%`;
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 176 const note = piece.notice?.() ?? "";
177 if (noticeEl.textContent !== note) noticeEl.textContent = note;
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 178 bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`;
179 if (panel && ts - lastReadout > 200) {
180 panel.updateReadouts();
181 lastReadout = ts;
182 }
183 raf = requestAnimationFrame(frame);
184 };
185 raf = requestAnimationFrame(frame);
187 return () => {
188 cancelAnimationFrame(raf);
189 window.removeEventListener("keydown", onKey);
192 };
195window.addEventListener("hashchange", route);
196route();
↑↓ move↵openescclose