/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / main.ts
189 lines · 6.7 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" });
97 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 98 const page = h("div", { className: author ? "page with-author" : "page" }, stage);
99 app.append(page);
101 const piece: Piece = comp.create(view, () => params);
103 // canvases fill the largest square that fits between the header and the transport
104 const fit = () => {
105 const s = Math.floor(Math.min(view.clientWidth, view.clientHeight));
106 for (const c of view.querySelectorAll("canvas")) {
107 c.style.width = `${s}px`;
108 c.style.height = `${s}px`;
109 }
110 };
111 const ro = new ResizeObserver(fit);
112 ro.observe(view);
113 fit();
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 114 const startAt = { value: 0 };
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 116 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 117 const play = async (offset: number) => {
119 try {
120 const audio = await getAudio();
121 await piece.start(audio, offset);
122 } finally {
123 starting = false;
124 }
126 playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0));
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 127 bigPlay.onclick = () => playBtn.click();
129 // author can click the progress line to jump
130 progress.classList.add("seekable");
131 progress.onclick = (ev) => {
132 const r = progress.getBoundingClientRect();
133 const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length());
134 void play(t);
135 };
136 }
138 let panel: ReturnType<typeof createAuthorPanel> | null = null;
139 if (author) {
140 panel = createAuthorPanel({
141 schema: comp.schema,
142 get: () => params,
143 set: (p) => {
144 params = p;
145 saveEdits(comp, p);
146 },
147 defaults: published,
148 readouts: () => piece.readouts(),
149 startAt,
150 });
151 page.append(panel.el);
152 }
154 const onKey = (e: KeyboardEvent) => {
155 const tag = (e.target as HTMLElement).tagName;
156 if (e.code === "Space" && tag !== "INPUT" && tag !== "SELECT" && tag !== "BUTTON") {
157 e.preventDefault();
158 playBtn.click();
159 }
160 };
161 window.addEventListener("keydown", onKey);
163 let raf = 0;
164 let lastReadout = 0;
165 const frame = (ts: number) => {
166 piece.draw();
167 playBtn.textContent = piece.playing ? "stop" : "play";
2913267Fit the composition page to phone screens; add a large play buttonJeremy Magland 168 bigPlay.hidden = piece.playing || starting;
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 169 const note = piece.notice?.() ?? "";
170 if (noticeEl.textContent !== note) noticeEl.textContent = note;
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 171 bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`;
172 if (panel && ts - lastReadout > 200) {
173 panel.updateReadouts();
174 lastReadout = ts;
175 }
176 raf = requestAnimationFrame(frame);
177 };
178 raf = requestAnimationFrame(frame);
180 return () => {
181 cancelAnimationFrame(raf);
182 window.removeEventListener("keydown", onKey);
185 };
188window.addEventListener("hashchange", route);
189route();
↑↓ move↵openescclose