|
| 1 | +/** |
| 2 | + * `<posecode-player>` — a self-contained custom element that renders a Posecode |
| 3 | + * movement as a live 3D figure. Drop it on any page; give it a movement via a |
| 4 | + * `doc` token, a `src` URL, or inline text. |
| 5 | + * |
| 6 | + * Design notes: |
| 7 | + * - **Lazy boot.** three.js is heavy, so the WebGL viewer is created only when |
| 8 | + * the element scrolls into view (IntersectionObserver) — many embeds on one |
| 9 | + * page stay cheap until seen. |
| 10 | + * - **Shadow DOM.** Markup + styles are isolated from the host page. |
| 11 | + * - **Accessible & polite.** Honors `prefers-reduced-motion` (no autoplay, no |
| 12 | + * camera orbit), exposes a labelled play/pause control, and cleans up its |
| 13 | + * render loop on disconnect. |
| 14 | + * - **Never blank.** Parse/load failures render a readable message, not an |
| 15 | + * empty canvas. |
| 16 | + */ |
| 17 | + |
| 18 | +import { parse } from "posecode-parser"; |
| 19 | +import { encodePosecode } from "posecode-share"; |
| 20 | +import type { Viewer } from "posecode-render"; |
| 21 | +import { parseOptions, type PlayerOptions } from "./options.js"; |
| 22 | +import { resolveSource } from "./source.js"; |
| 23 | +import { PLAYER_CSS } from "./styles.js"; |
| 24 | + |
| 25 | +const PLAY = "▶"; |
| 26 | +const PAUSE = "❚❚"; |
| 27 | + |
| 28 | +/** Where the "open in playground" link points; overridable per element. */ |
| 29 | +const DEFAULT_PLAYGROUND = "https://posecode.org/play"; |
| 30 | + |
| 31 | +export class PosecodePlayerElement extends HTMLElement { |
| 32 | + static readonly tagName = "posecode-player"; |
| 33 | + |
| 34 | + #viewer: Viewer | null = null; |
| 35 | + #io: IntersectionObserver | null = null; |
| 36 | + #booted = false; |
| 37 | + #root: ShadowRoot; |
| 38 | + #canvas!: HTMLCanvasElement; |
| 39 | + #playBtn!: HTMLButtonElement; |
| 40 | + #phaseEl!: HTMLElement; |
| 41 | + #source = ""; |
| 42 | + |
| 43 | + constructor() { |
| 44 | + super(); |
| 45 | + this.#root = this.attachShadow({ mode: "open" }); |
| 46 | + } |
| 47 | + |
| 48 | + connectedCallback(): void { |
| 49 | + // Capture inline text BEFORE we replace the light DOM with shadow markup. |
| 50 | + this.#source = this.textContent ?? ""; |
| 51 | + this.#renderChrome(); |
| 52 | + // Boot immediately UNLESS the element is measurably off-screen — in which |
| 53 | + // case defer the heavy renderer until it scrolls into view. The bias is |
| 54 | + // toward booting: an embed must never stay blank because we couldn't |
| 55 | + // measure the viewport (e.g. innerHeight reported as 0) or because the |
| 56 | + // observer never fires. Deferral is a pure optimization, not correctness. |
| 57 | + if (this.#shouldDefer()) { |
| 58 | + this.#io = new IntersectionObserver((entries) => { |
| 59 | + if (entries.some((e) => e.isIntersecting)) void this.#boot(); |
| 60 | + }); |
| 61 | + this.#io.observe(this); |
| 62 | + } else { |
| 63 | + void this.#boot(); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + /** Only defer when we can prove the element is fully outside the viewport. */ |
| 68 | + #shouldDefer(): boolean { |
| 69 | + if (typeof IntersectionObserver !== "function") return false; |
| 70 | + const vh = window.innerHeight || document.documentElement.clientHeight || 0; |
| 71 | + const vw = window.innerWidth || document.documentElement.clientWidth || 0; |
| 72 | + if (!vh || !vw) return false; // can't measure → boot now |
| 73 | + const r = this.getBoundingClientRect(); |
| 74 | + return r.top > vh || r.bottom < 0 || r.left > vw || r.right < 0; |
| 75 | + } |
| 76 | + |
| 77 | + disconnectedCallback(): void { |
| 78 | + this.#io?.disconnect(); |
| 79 | + this.#io = null; |
| 80 | + this.#viewer?.dispose(); |
| 81 | + this.#viewer = null; |
| 82 | + this.#booted = false; |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * The underlying render viewer, or `null` until the element has booted. |
| 87 | + * Exposed for programmatic control (pause/seek all embeds on a page, sync |
| 88 | + * playback, capture a frame) and for testing. |
| 89 | + */ |
| 90 | + get viewer(): Viewer | null { |
| 91 | + return this.#viewer; |
| 92 | + } |
| 93 | + |
| 94 | + /** Toggle playback; no-op until the viewer has booted. */ |
| 95 | + toggle(): void { |
| 96 | + if (!this.#viewer) return; |
| 97 | + const playing = this.#viewer.toggle(); |
| 98 | + this.#reflectPlaying(playing); |
| 99 | + } |
| 100 | + |
| 101 | + #options(): PlayerOptions { |
| 102 | + return parseOptions({ |
| 103 | + autoplay: this.getAttribute("autoplay"), |
| 104 | + loop: this.getAttribute("loop"), |
| 105 | + controls: this.getAttribute("controls"), |
| 106 | + autorotate: this.getAttribute("autorotate"), |
| 107 | + speed: this.getAttribute("speed"), |
| 108 | + }); |
| 109 | + } |
| 110 | + |
| 111 | + #renderChrome(): void { |
| 112 | + const opts = this.#options(); |
| 113 | + const style = document.createElement("style"); |
| 114 | + style.textContent = PLAYER_CSS; |
| 115 | + |
| 116 | + this.#canvas = document.createElement("canvas"); |
| 117 | + |
| 118 | + this.#playBtn = document.createElement("button"); |
| 119 | + this.#playBtn.className = "play"; |
| 120 | + this.#playBtn.textContent = PLAY; |
| 121 | + this.#playBtn.setAttribute("aria-label", "Play or pause"); |
| 122 | + this.#playBtn.addEventListener("click", () => this.toggle()); |
| 123 | + |
| 124 | + this.#phaseEl = document.createElement("span"); |
| 125 | + this.#phaseEl.className = "phase"; |
| 126 | + |
| 127 | + const link = document.createElement("a"); |
| 128 | + link.className = "link"; |
| 129 | + link.target = "_blank"; |
| 130 | + link.rel = "noopener"; |
| 131 | + link.textContent = "Edit ↗"; |
| 132 | + link.href = this.#playgroundUrl(); |
| 133 | + |
| 134 | + const bar = document.createElement("div"); |
| 135 | + bar.className = opts.controls ? "bar" : "bar"; |
| 136 | + if (!opts.controls) bar.style.display = "none"; |
| 137 | + bar.append(this.#playBtn, this.#phaseEl, link); |
| 138 | + |
| 139 | + this.#root.replaceChildren(style, this.#canvas, bar); |
| 140 | + } |
| 141 | + |
| 142 | + #playgroundUrl(): string { |
| 143 | + const base = this.getAttribute("playground") ?? DEFAULT_PLAYGROUND; |
| 144 | + if (!this.#source.trim()) return base; |
| 145 | + try { |
| 146 | + return `${base}#doc=${encodePosecode(this.#source.trim())}`; |
| 147 | + } catch { |
| 148 | + return base; |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + async #boot(): Promise<void> { |
| 153 | + if (this.#booted) return; |
| 154 | + this.#booted = true; |
| 155 | + this.#io?.disconnect(); |
| 156 | + |
| 157 | + const resolved = await resolveSource({ |
| 158 | + doc: this.getAttribute("doc"), |
| 159 | + src: this.getAttribute("src"), |
| 160 | + text: this.#source, |
| 161 | + }); |
| 162 | + if (!resolved.ok) return this.#showMessage(resolved.error, true); |
| 163 | + |
| 164 | + // Keep the resolved source so the "Edit" link matches what's rendered. |
| 165 | + this.#source = resolved.source; |
| 166 | + const { ir, errors } = parse(resolved.source); |
| 167 | + if (!ir || errors.length > 0) { |
| 168 | + const detail = errors[0] ? `${errors[0].message} (line ${errors[0].line})` : ""; |
| 169 | + return this.#showMessage(`Couldn't parse this movement. ${detail}`.trim(), true); |
| 170 | + } |
| 171 | + |
| 172 | + const opts = this.#options(); |
| 173 | + const reduceMotion = |
| 174 | + typeof matchMedia === "function" && |
| 175 | + matchMedia("(prefers-reduced-motion: reduce)").matches; |
| 176 | + |
| 177 | + // Lazy-import the heavy renderer only once we actually have work to show. |
| 178 | + const { createViewer } = await import("posecode-render"); |
| 179 | + const viewer = createViewer(this.#canvas, { |
| 180 | + autoRotate: opts.autoRotate && !reduceMotion, |
| 181 | + }); |
| 182 | + this.#viewer = viewer; |
| 183 | + viewer.onPhase(({ phaseName }) => { |
| 184 | + this.#phaseEl.textContent = phaseName === "reset" ? "" : phaseName; |
| 185 | + }); |
| 186 | + viewer.load(ir); |
| 187 | + viewer.setLoop(opts.loop); |
| 188 | + viewer.setSpeed(opts.speed); |
| 189 | + |
| 190 | + const shouldPlay = opts.autoplay && !reduceMotion; |
| 191 | + if (shouldPlay) viewer.play(); |
| 192 | + this.#reflectPlaying(shouldPlay); |
| 193 | + |
| 194 | + // Update the Edit link now that we know the real source. |
| 195 | + const link = this.#root.querySelector("a.link") as HTMLAnchorElement | null; |
| 196 | + if (link) link.href = this.#playgroundUrl(); |
| 197 | + |
| 198 | + this.dispatchEvent(new CustomEvent("posecode:ready", { bubbles: true })); |
| 199 | + } |
| 200 | + |
| 201 | + #reflectPlaying(playing: boolean): void { |
| 202 | + this.#playBtn.textContent = playing ? PAUSE : PLAY; |
| 203 | + } |
| 204 | + |
| 205 | + #showMessage(text: string, isError: boolean): void { |
| 206 | + const msg = document.createElement("div"); |
| 207 | + msg.className = isError ? "msg error" : "msg"; |
| 208 | + msg.textContent = text; |
| 209 | + this.#root.append(msg); |
| 210 | + if (isError) { |
| 211 | + this.dispatchEvent( |
| 212 | + new CustomEvent("posecode:error", { bubbles: true, detail: { error: text } }), |
| 213 | + ); |
| 214 | + } |
| 215 | + } |
| 216 | +} |
0 commit comments