/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / main.ts
168 lines · 5.7 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 stage = h("main", { className: "stage" }, header, view, h("div", { className: "transport" }, playBtn, progress, editLink));
79 const page = h("div", { className: author ? "page with-author" : "page" }, stage);
80 app.append(page);
82 const piece: Piece = comp.create(view, () => params);
83 view.append(bigPlay);
84 // canvases fill the largest square that fits between the header and the transport
85 const fit = () => {
86 const s = Math.floor(Math.min(view.clientWidth, view.clientHeight));
87 for (const c of view.querySelectorAll("canvas")) {
88 c.style.width = `${s}px`;
89 c.style.height = `${s}px`;
90 }
91 };
92 const ro = new ResizeObserver(fit);
93 ro.observe(view);
94 fit();
95 const startAt = { value: 0 };
97 let starting = false; // instruments can take a moment to load; don't offer play twice
98 const play = async (offset: number) => {
99 starting = true;
100 try {
101 const audio = await getAudio();
102 await piece.start(audio, offset);
103 } finally {
104 starting = false;
105 }
106 };
107 playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0));
108 bigPlay.onclick = () => playBtn.click();
109 if (author) {
110 // author can click the progress line to jump
111 progress.classList.add("seekable");
112 progress.onclick = (ev) => {
113 const r = progress.getBoundingClientRect();
114 const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length());
115 void play(t);
116 };
117 }
119 let panel: ReturnType<typeof createAuthorPanel> | null = null;
120 if (author) {
121 panel = createAuthorPanel({
122 schema: comp.schema,
123 get: () => params,
124 set: (p) => {
125 params = p;
126 saveEdits(comp, p);
127 },
128 defaults: published,
129 readouts: () => piece.readouts(),
130 startAt,
131 });
132 page.append(panel.el);
133 }
135 const onKey = (e: KeyboardEvent) => {
136 const tag = (e.target as HTMLElement).tagName;
137 if (e.code === "Space" && tag !== "INPUT" && tag !== "SELECT" && tag !== "BUTTON") {
138 e.preventDefault();
139 playBtn.click();
140 }
141 };
142 window.addEventListener("keydown", onKey);
144 let raf = 0;
145 let lastReadout = 0;
146 const frame = (ts: number) => {
147 piece.draw();
148 playBtn.textContent = piece.playing ? "stop" : "play";
149 bigPlay.hidden = piece.playing || starting;
150 bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`;
151 if (panel && ts - lastReadout > 200) {
152 panel.updateReadouts();
153 lastReadout = ts;
154 }
155 raf = requestAnimationFrame(frame);
156 };
157 raf = requestAnimationFrame(frame);
159 return () => {
160 cancelAnimationFrame(raf);
161 window.removeEventListener("keydown", onKey);
162 ro.disconnect();
163 piece.dispose();
164 };
167window.addEventListener("hashchange", route);
168route();
↑↓ move↵openescclose