/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / main.ts
145 lines · 4.9 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;
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 playBtn = h("button", { className: "play", textContent: "play" });
66 const bar = h("div", { className: "bar" });
67 const progress = h("div", { className: "progress" }, bar);
68 const editLink = h("a", { className: "edit", href: author ? `#/${comp.id}` : `#/${comp.id}/edit`, textContent: author ? "done" : "edit" });
69 const header = h(
70 "header",
71 {},
72 h("a", { href: "#/", textContent: ALBUM_TITLE }),
73 h("span", { className: "sep", textContent: " / " }),
74 h("span", { textContent: `${index}. ${comp.title}` }),
75 );
76 const stage = h("main", { className: "stage" }, header, view, h("div", { className: "transport" }, playBtn, progress, editLink));
77 const page = h("div", { className: author ? "page with-author" : "page" }, stage);
78 app.append(page);
80 const piece: Piece = comp.create(view, () => params);
81 const startAt = { value: 0 };
83 const play = async (offset: number) => {
84 const audio = await getAudio();
85 await piece.start(audio, offset);
86 };
87 playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0));
88 if (author) {
89 // author can click the progress line to jump
90 progress.classList.add("seekable");
91 progress.onclick = (ev) => {
92 const r = progress.getBoundingClientRect();
93 const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length());
94 void play(t);
95 };
96 }
98 let panel: ReturnType<typeof createAuthorPanel> | null = null;
99 if (author) {
100 panel = createAuthorPanel({
101 schema: comp.schema,
102 get: () => params,
103 set: (p) => {
104 params = p;
105 saveEdits(comp, p);
106 },
107 defaults: published,
108 readouts: () => piece.readouts(),
109 startAt,
110 });
111 page.append(panel.el);
112 }
114 const onKey = (e: KeyboardEvent) => {
115 const tag = (e.target as HTMLElement).tagName;
116 if (e.code === "Space" && tag !== "INPUT" && tag !== "SELECT" && tag !== "BUTTON") {
117 e.preventDefault();
118 playBtn.click();
119 }
120 };
121 window.addEventListener("keydown", onKey);
123 let raf = 0;
124 let lastReadout = 0;
125 const frame = (ts: number) => {
126 piece.draw();
127 playBtn.textContent = piece.playing ? "stop" : "play";
128 bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`;
129 if (panel && ts - lastReadout > 200) {
130 panel.updateReadouts();
131 lastReadout = ts;
132 }
133 raf = requestAnimationFrame(frame);
134 };
135 raf = requestAnimationFrame(frame);
137 return () => {
138 cancelAnimationFrame(raf);
139 window.removeEventListener("keydown", onKey);
140 piece.dispose();
141 };
144window.addEventListener("hashchange", route);
145route();
↑↓ move↵openescclose