/** * Posecode playground wiring: editor → parser → 3D viewer, plus the how-to * slide-over and playback UX (phase ribbon, scrubber markers, rep counter). * * The text in the editor is the single source of truth. On every (debounced) * change we re-parse; clean docs reload the viewer, errors/warnings surface in * the side panel. The same path works for hand-authored and LLM-authored source. */ import { parse, type AvatarName, type ParseError, type Warning } from "posecode-parser"; import type { ConstraintDiagnostic, Viewer } from "posecode-render"; import { trackUsageEvent, UsageSession, USAGE_EVENT_NAMES, type DocumentKind, type PresetOpenSource, type RenderTrigger, } from "./analytics.js"; import { initializeAnalytics } from "./vercel-analytics.js"; import { buildNicePlayPath, buildNiceShareHash, resolveSharedPath, resolveSharedSource, } from "./nice-share.js"; import type { PosecodeEditor } from "./editor.js"; import { ANIMATION_PROGRESS_MESSAGE, PRESETS } from "./presets.js"; import { prioritizeFeaturedMovement } from "./library-order.js"; import { SHOWCASE_CLIPS } from "./clips.js"; import { previewTimeForLine } from "./direct-manipulation.js"; import { GUIDED_FIRST_EDIT_TARGET, GuidedFirstEditSession, shouldOfferGuidedFirstEdit, } from "./guided-first-edit.js"; // During source-only typechecks the playground resolves posecode-render's last // built declaration bundle. Keep the local extension explicit until the normal // package build regenerates that bundle from the source Viewer interface. type InteractiveViewer = Viewer & { selectBones(boneIds: readonly string[]): void; }; // Open on a deterministic, fully procedural movement. Mocap-backed or // Experimental presets should never be the product's first impression. const DEFAULT_PRESET = PRESETS.find((p) => p.id === "superhero-landing") ?? PRESETS[0]!; // Character appearance is independent of skeleton topology. Documents without // an `avatar` directive use the humanoid default; avatar1 deliberately reuses // XBot instead of committing a duplicate binary. const CHARACTER_URLS: Record = { humanoid: "/models/xbot.glb", avatar1: "/models/xbot.glb", avatar2: "/models/avatar2.glb", avatar3: "/models/avatar3.glb", }; import { renderWarnings } from "./warnings.js"; import llmPrompt from "../../spec/llm-authoring.md?raw"; initializeAnalytics(); const usageSession = new UsageSession(); const $ = (id: string): T => document.getElementById(id) as T; // CodeMirror is heavy too, so the editor is lazy-loaded after first paint (its // own chunk). Until that resolves, `editorApi` is null; recompile() and the // user-action handlers guard on it (a click in that ~tens-of-ms window no-ops). let editorApi: PosecodeEditor | null = null; const warnings = $("warnings"); const canvas = $("canvas"); const playpause = $("playpause"); const scrub = $("scrub"); const markers = $("markers"); const ribbon = $("ribbon"); const reps = $("reps"); const clock = $("clock"); const loop = $("loop"); const speed = $("speed"); const phaseEl = $("phase"); const cueEl = $("cue"); const floorGuideKey = $("floor-guide-key"); const floorGuideTravel = $("floor-guide-travel"); const floorGuideReset = $("floor-guide-reset"); const floorGuideToggle = $("floor-guide-toggle"); const jointSelection = $("joint-selection"); const jointSelectionName = $("joint-selection-name"); const copyBtn = $("copy-prompt"); const shareBtn = $("share"); const exportMenuButton = $("export-menu-button"); const exportMenu = $("export-menu"); const downloadBvhBtn = $("download-bvh"); const downloadGltfBtn = $("download-gltf"); const tabEditor = $("tab-editor"); const tabViewer = $("tab-viewer"); const guidedFirstEditCard = $("guided-first-edit"); const guidedFirstEditTitle = $("guided-first-edit-title"); const guidedFirstEditMessage = $("guided-first-edit-message"); const guidedFirstEditStart = $("guided-first-edit-start"); const guidedFirstEditShare = $("guided-first-edit-share"); const guidedFirstEditDismiss = $("guided-first-edit-dismiss"); // Three.js is heavy (~530 kB). Like the landing page, we load the renderer // *after* the editor shell paints (dynamic import → its own chunk) so first // paint and interactivity aren't blocked by it. Until `boot()` resolves the // import, `viewer` is null and viewer-dependent work is skipped/deferred. let viewer: InteractiveViewer | null = null; let scrubbing = false; let repeat = 1; let rep = 1; // Maps each phase index → the 1-based line range of its `step` block, so the // editor can highlight the lines driving the currently-animating phase. let phaseRanges: Array<{ from: number; to: number }> = []; let lastParseErrors: ParseError[] = []; let lastRomWarnings: Warning[] = []; let lastContactSignature = ""; let lastContactRefresh = 0; let scrubDiagnosticsRefresh = 0; let documentRevision = 1; let pendingRenderTrigger: RenderTrigger = "initial"; let selectedBoneIds: readonly string[] = []; let pendingPreviewLine: number | null = null; let guidedFirstEditSession: GuidedFirstEditSession | null = null; let pendingGuidedAngleFocus = false; /** Keep the source selection and its live 3D joint markers in sync. */ function handleJointSelect( joint: string | null, boneIds: readonly string[], ): void { selectedBoneIds = boneIds; viewer?.selectBones(boneIds); jointSelection.hidden = joint === null; if (joint) { const readable = joint.replaceAll("_", " "); jointSelectionName.textContent = boneIds.length > 1 ? `${readable} · ${boneIds.length} bones` : readable; } else { jointSelectionName.textContent = ""; } } function documentKind(): DocumentKind { if (currentPresetId) return "preset"; return initialDocumentWasShared ? "shared" : "custom"; } /** Merge live solver residuals with source diagnostics without repainting each frame. */ function refreshContactDiagnostics(force = false): void { if (!viewer) return; const contacts = viewer.getReachResiduals(); const constraints = viewer.getConstraintDiagnostics(); const contactSignature = contacts .filter((contact) => contact.weight >= 0.98 && !contact.reached) .map((contact) => `${contact.effector}|${contact.target}|${contact.reason ?? ""}|${ contact.distance === null ? "null" : Math.round(contact.distance * 1000) }`, ) .sort(); const constraintSignature = constraints .filter((diagnostic) => !diagnostic.pass) .map((diagnostic: ConstraintDiagnostic) => `${diagnostic.id}|${Math.round(diagnostic.value * (diagnostic.unit === "m" ? 1000 : 10))}`, ) .sort(); const signature = [...contactSignature, ...constraintSignature].join(";"); if (!force && signature === lastContactSignature) return; lastContactSignature = signature; renderWarnings(warnings, lastParseErrors, lastRomWarnings, contacts, constraints); } /** Read the seeked pose after the viewer's continuously scheduled frame solves it. */ function scheduleScrubDiagnosticsRefresh(): void { cancelAnimationFrame(scrubDiagnosticsRefresh); scrubDiagnosticsRefresh = requestAnimationFrame(() => { scrubDiagnosticsRefresh = 0; refreshContactDiagnostics(true); }); } const playLbl = playpause.querySelector(".lbl"); /** Reflect playback state on the icon-driven play button. */ function setPlaying(isPlaying: boolean): void { playpause.dataset.playing = String(isPlaying); if (playLbl) playLbl.textContent = isPlaying ? "Pause" : "Play"; } /** Paint the custom scrubber fill (0–1000 range → percentage CSS var). */ function paintScrub(): void { scrub.style.setProperty("--pct", `${Number(scrub.value) / 10}%`); } /** Wire the viewer's playback callbacks. Runs once, after the renderer loads. */ function wireViewer(v: Viewer): void { v.onPhase(({ phaseIndex, phaseName, cue }) => { phaseEl.textContent = phaseName === "reset" ? "" : phaseName; cueEl.textContent = cue ?? ""; highlightChip(phaseIndex); // Light up the step block driving this phase (cleared between loops / on reset). const range = phaseIndex < 0 ? undefined : phaseRanges[phaseIndex]; editorApi?.highlightPhase(range ? range.from : null, range?.to); refreshContactDiagnostics(true); }); v.onTick((time, duration) => { if (!scrubbing) { scrub.value = String(Math.round((time / (duration || 1)) * 1000)); paintScrub(); } clock.textContent = `${time.toFixed(1)}s`; const now = performance.now(); if (now - lastContactRefresh >= 200) { lastContactRefresh = now; refreshContactDiagnostics(); } }); v.onLoop(() => { rep = (rep % repeat) + 1; updateReps(); }); } function updateReps(): void { reps.textContent = repeat > 1 ? `rep ${rep} / ${repeat}` : ""; } /** Keep the compact 2D key in sync with the movement-specific 3D floor guide. */ function updateFloorGuideKey(): void { const info = viewer?.getFloorGuideInfo(); floorGuideKey.hidden = !info?.visible; floorGuideTravel.hidden = !info?.hasTravel; floorGuideReset.hidden = !info?.hasLoopReset; floorGuideToggle.classList.toggle("is-active", Boolean(info?.debug)); floorGuideToggle.textContent = info?.debug ? "dense" : "debug"; const describedFeatures = ["load origin", "current facing", "one metre scale", "stage ring"]; if (info?.hasTravel) describedFeatures.push("authored travel path"); if (info?.hasLoopReset) describedFeatures.push("dashed loop reset"); if (info?.debug) describedFeatures.push("debug metre axes"); floorGuideKey.setAttribute( "aria-label", `Floor guide: ${describedFeatures.join(", ")}`, ); } function buildRibbonAndMarkers(): void { const tl = viewer?.getTimeline(); ribbon.innerHTML = ""; markers.innerHTML = ""; if (!tl) return; for (const [index, seg] of tl.segments.entries()) { const chip = document.createElement("button"); chip.type = "button"; chip.className = "chip"; chip.textContent = seg.name; chip.dataset.index = String(index); chip.title = seg.cue ?? ""; chip.addEventListener("click", () => viewer?.seek(seg.start + 1e-3)); ribbon.append(chip); if (seg.start > 0) { const tick = document.createElement("div"); tick.className = "tick"; tick.style.left = `${(seg.start / tl.duration) * 100}%`; markers.append(tick); } } } function highlightChip(index: number): void { let active: HTMLElement | null = null; for (const el of ribbon.querySelectorAll(".chip")) { const selected = Number(el.dataset.index) === index; el.classList.toggle("active", selected); if (selected) el.setAttribute("aria-current", "step"); else el.removeAttribute("aria-current"); if (selected) active = el; } if (active && ribbon.scrollWidth > ribbon.clientWidth) { const gutter = 12; const visibleStart = ribbon.scrollLeft + gutter; const visibleEnd = ribbon.scrollLeft + ribbon.clientWidth - gutter; const chipStart = active.offsetLeft; const chipEnd = chipStart + active.offsetWidth; let left: number | null = null; if (chipStart < visibleStart) left = chipStart - gutter; else if (chipEnd > visibleEnd) left = chipEnd - ribbon.clientWidth + gutter; if (left === null) return; ribbon.scrollTo({ left: Math.max(0, left), behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth", }); } } /** * Map each phase (in timeline order) to the line range of its `step` block, by * scanning the document. Step lines and `repeat` mark block boundaries; trailing * blank lines are trimmed so the highlight hugs the actual phase. */ function computePhaseRanges( text: string, segmentCount: number, ): Array<{ from: number; to: number }> { const lines = text.split(/\r?\n/); const stepLines: number[] = []; const boundaries: number[] = []; for (let i = 0; i < lines.length; i++) { const isStep = /^\s*step\b/.test(lines[i]!); if (isStep) stepLines.push(i + 1); if (isStep || /^\s*repeat\b/.test(lines[i]!)) boundaries.push(i + 1); } const ranges: Array<{ from: number; to: number }> = []; for (let s = 0; s < stepLines.length && s < segmentCount; s++) { const from = stepLines[s]!; const next = boundaries.find((b) => b > from); let to = next ? next - 1 : lines.length; while (to > from && lines[to - 1]!.trim() === "") to--; ranges.push({ from, to }); } return ranges; } let debounce = 0; function scheduleRecompile(previewLine?: number): void { window.clearTimeout(debounce); pendingPreviewLine = previewLine ?? null; debounce = window.setTimeout(recompile, 250); } /** Keep the address bar and library label in sync with editor changes. */ function handleEditorChange( source: string, userInitiated: boolean, context?: { previewLine: number }, ): void { const editedDocumentKind = documentKind(); const preset = PRESETS.find((p) => p.source === source); currentPresetId = preset?.id ?? null; if (userInitiated) { guidedFirstEditSession?.noteUserEdit(source, true); usageSession.trackFirstEdit(editedDocumentKind); initialDocumentWasShared = false; documentRevision++; pendingRenderTrigger = "editor_change"; } setCurrentPresetLabel( preset, source.trim() ? "Custom movement" : "New movement", ); history.replaceState(null, "", buildNicePlayPath(source)); scheduleRecompile(context?.previewLine); } function recompile(): void { window.clearTimeout(debounce); // cancel any pending run; we're compiling now // Captured once so control-flow narrowing survives the calls below; a null // editor (still loading) means there's nothing to compile yet. const ed = editorApi; if (!ed) return; const source = ed.getValue(); if (!source.trim()) { // A deliberately blank editor (the "New" flow): a paste target, not an // error state. Show a hint instead of parse errors and stop the playback. warnings.innerHTML = '
Blank editor. Paste a movement from your AI chat, or pick one from the library.
'; viewer?.pause(); setPlaying(false); return; } const { ir, errors, warnings: warns } = parse(source); lastParseErrors = errors; lastRomWarnings = warns; lastContactSignature = ""; renderWarnings(warnings, errors, warns); // Before the renderer finishes loading, we still parse + surface warnings; // the viewer-dependent work re-runs once `boot()` calls recompile() again. if (ir && viewer) { viewer.load(ir); updateFloorGuideKey(); if ( errors.length === 0 && pendingRenderTrigger === "editor_change" && documentKind() === "custom" ) { usageSession.trackFirstValidCustomMovement(); if (guidedFirstEditSession?.confirmValidCustomRender(source)) { renderGuidedFirstEdit(); } } usageSession.trackSuccessfulRender( documentRevision, pendingRenderTrigger, documentKind(), ); viewer.setLoop(loop.checked); viewer.setSpeed(Number(speed.value)); const tl = viewer.getTimeline(); repeat = tl?.repeat ?? 1; rep = 1; updateReps(); buildRibbonAndMarkers(); phaseRanges = computePhaseRanges( ed.getValue(), tl?.segments.length ?? 0, ); ed.highlightPhase(null); // next onPhase paints the active block const previewTime = pendingPreviewLine !== null && tl ? previewTimeForLine(pendingPreviewLine, phaseRanges, tl.segments) : null; pendingPreviewLine = null; if (previewTime !== null && tl) { // Direct manipulation is a pose inspection workflow: hold the affected // keyframe so even a fast phase visibly responds to a one-degree edit. viewer.seek(previewTime); viewer.pause(); setPlaying(false); scrub.value = String(Math.round((previewTime / (tl.duration || 1)) * 1000)); paintScrub(); clock.textContent = `${previewTime.toFixed(1)}s`; scheduleScrubDiagnosticsRefresh(); } else { viewer.play(); setPlaying(true); } } } // --- Movement library: one panel to search, filter, and pick an example --- // Replaces the old topbar dropdown cluster (area / gear / level / example): a // single button shows the current movement and opens a browsable panel with // one search box and two light chip filters. Picking a movement loads it and // closes the panel, so the topbar stays a one-glance control on any screen. const libOpenBtn = $("lib-open"); const libCurrent = $("lib-current"); const libCurrentStatus = $("lib-current-status"); const library = $("library"); const libSearch = $("lib-search"); const libReadiness = $("lib-readiness"); const libDomains = $("lib-domains"); const libLevels = $("lib-levels"); const libList = $("lib-list"); const libCount = $("lib-count"); let currentPresetId: string | null = null; let libQuery = ""; let libStatus = "ready"; // "" = all; launch-ready is the default first view let libDomain = ""; // "" = all let libLevel = ""; // "" = all function setCurrentPresetLabel( preset: (typeof PRESETS)[number] | undefined, fallback: string, ): void { libCurrent.textContent = preset?.label ?? fallback; const experimental = preset?.status === "experimental"; libCurrentStatus.hidden = !experimental; libCurrentStatus.title = experimental ? ANIMATION_PROGRESS_MESSAGE : ""; } /** Render one chip row ("All" + each distinct value) reflecting the selection. */ function renderChips( host: HTMLDivElement, values: string[], selected: string, allLabel: string, onPick: (value: string) => void, ): void { host.innerHTML = ""; for (const value of ["", ...values]) { const chip = document.createElement("button"); chip.type = "button"; chip.className = "fchip"; chip.textContent = value ? `${value.charAt(0).toUpperCase()}${value.slice(1)}` : allLabel; chip.setAttribute("aria-pressed", String(value === selected)); chip.addEventListener("click", () => onPick(value)); host.append(chip); } } function renderLibraryFilters(): void { const statusPresets = PRESETS.filter((p) => !libStatus || p.status === libStatus); const domainValues = [...new Set(statusPresets.map((p) => p.domain))]; if (libDomain && !domainValues.includes(libDomain)) libDomain = ""; const domainPresets = statusPresets.filter((p) => !libDomain || p.domain === libDomain); const levelOrder = ["Beginner", "Intermediate", "Advanced"]; const levelValues = levelOrder.filter((level) => domainPresets.some((preset) => preset.difficulty === level), ); if (libLevel && !levelValues.includes(libLevel)) libLevel = ""; renderChips(libReadiness, ["ready", "experimental"], libStatus, "All movements", (v) => { libStatus = v; renderLibraryFilters(); renderLibraryList(); }); // Only offer facets that can produce a result under the active readiness // filter. Ready view therefore never exposes experimental-only domains. renderChips(libDomains, domainValues, libDomain, "All", (v) => { libDomain = v; renderLibraryFilters(); renderLibraryList(); }); renderChips(libLevels, levelValues, libLevel, "All levels", (v) => { libLevel = v; renderLibraryFilters(); renderLibraryList(); }); } /** Case- and accent-insensitive ("plie" finds "Demi-plié"). */ function fold(s: string): string { return s .toLowerCase() .normalize("NFD") .replace(/[\u0300-\u036f]/g, ""); } function libraryMatches(): typeof PRESETS { const q = fold(libQuery.trim()); return prioritizeFeaturedMovement( PRESETS.filter( (p) => (!libDomain || p.domain === libDomain) && (!libLevel || p.difficulty === libLevel) && (!libStatus || p.status === libStatus) && (!q || fold(`${p.label} ${p.target} ${p.domain} ${p.bodyPart} ${p.equipment}`).includes(q)), ), ); } function renderLibraryList(): void { const matches = libraryMatches(); libCount.textContent = `(${matches.length})`; libList.innerHTML = ""; if (matches.length === 0) { const empty = document.createElement("div"); empty.className = "lib-empty"; empty.textContent = "No movements match. "; const reset = document.createElement("button"); reset.type = "button"; reset.className = "link"; reset.textContent = "Reset search & filters"; reset.addEventListener("click", () => { libQuery = ""; libSearch.value = ""; libStatus = "ready"; libDomain = ""; libLevel = ""; renderLibraryFilters(); renderLibraryList(); }); empty.append(reset); libList.append(empty); return; } // Group by domain (first-seen order) so each practice gets a single header. const groups = new Map(); for (const p of matches) { const group = groups.get(p.domain); if (group) group.push(p); else groups.set(p.domain, [p]); } for (const [domain, presets] of groups) { const head = document.createElement("div"); head.className = "lib-group"; head.textContent = domain; libList.append(head); for (const p of presets) appendItem(p); } function appendItem(p: (typeof PRESETS)[number]): void { const item = document.createElement("button"); item.type = "button"; item.className = "lib-item"; if (p.id === currentPresetId) item.setAttribute("aria-current", "true"); const name = document.createElement("span"); name.className = "li-name"; const label = document.createElement("span"); label.textContent = p.label; name.append(label); if (p.status === "experimental") { const status = document.createElement("span"); status.className = "li-status"; status.textContent = "Experimental"; status.title = ANIMATION_PROGRESS_MESSAGE; status.setAttribute("aria-label", "Experimental preview"); name.append(status); } const meta = document.createElement("span"); meta.className = "li-meta"; meta.textContent = p.status === "experimental" ? `${p.target} · ${p.equipment} · ${p.difficulty} · Not launch-ready` : `${p.target} · ${p.equipment} · ${p.difficulty}`; item.append(name, meta); item.addEventListener("click", () => { loadPreset(p.id); closePanels(); }); libList.append(item); } } function loadPreset(id: string): void { const preset = PRESETS.find((p) => p.id === id); if (!preset) return; dismissGuidedFirstEdit(); currentPresetId = preset.id; initialDocumentWasShared = false; documentRevision++; pendingRenderTrigger = "preset_open"; trackUsageEvent(USAGE_EVENT_NAMES.presetOpened, { source: "library", preset_id: preset.id, }); setCurrentPresetLabel(preset, preset.label); editorApi?.setValue(preset.source); history.replaceState(null, "", buildNicePlayPath(preset.source)); recompile(); setMobileView("viewer"); // on phones, jump to the figure after picking } libSearch.addEventListener("input", () => { libQuery = libSearch.value; renderLibraryList(); }); renderLibraryFilters(); renderLibraryList(); // --- New movement: clear the editor into a focused source document --- // A human can write directly or paste a draft from another tool without // overwriting a preset by hand-selecting its text first. $("new-doc").addEventListener("click", () => { dismissGuidedFirstEdit(); currentPresetId = null; initialDocumentWasShared = false; setCurrentPresetLabel(undefined, "New movement"); editorApi?.setValue(""); history.replaceState(null, "", "/play"); recompile(); // swaps the status row to the blank-editor hint immediately setMobileView("editor"); // the paste target, front and center on phones editorApi?.focus(); }); // --- Mobile Editor/Viewer toggle (no-op visually on desktop, where both show) --- function setMobileView(view: "editor" | "viewer"): void { document.body.dataset.mview = view; tabEditor.setAttribute("aria-selected", String(view === "editor")); tabViewer.setAttribute("aria-selected", String(view === "viewer")); } tabEditor.addEventListener("click", () => setMobileView("editor")); tabViewer.addEventListener("click", () => setMobileView("viewer")); setMobileView("viewer"); function renderGuidedFirstEdit(): void { const stage = guidedFirstEditSession?.stage ?? "idle"; guidedFirstEditCard.hidden = stage === "idle" || stage === "dismissed"; if (guidedFirstEditCard.hidden) return; guidedFirstEditCard.dataset.stage = stage; const succeeded = stage === "success"; guidedFirstEditTitle.textContent = succeeded ? "Nice — your edit rendered." : "Bend the right knee a little less."; guidedFirstEditMessage.textContent = succeeded ? "The source is valid and the figure updated." : `Change knee_right: flex ${GUIDED_FIRST_EDIT_TARGET.initialDegrees} to ${GUIDED_FIRST_EDIT_TARGET.suggestedDegrees}°.`; guidedFirstEditStart.hidden = succeeded; guidedFirstEditShare.hidden = !succeeded; guidedFirstEditDismiss.setAttribute( "aria-label", succeeded ? "Dismiss edit success" : "Dismiss quick edit", ); } function dismissGuidedFirstEdit(): void { if (guidedFirstEditSession?.dismiss()) renderGuidedFirstEdit(); } function focusGuidedAngleControl(): void { const session = guidedFirstEditSession; if (!session) return; const surface = matchMedia("(max-width: 860px)").matches ? "mobile" : "desktop"; const request = session.begin(surface); if (!request) return; if (request.switchToEditor) setMobileView("editor"); pendingGuidedAngleFocus = true; if (editorApi?.focusAngleControl(request.joint, request.action)) { pendingGuidedAngleFocus = false; } } guidedFirstEditStart.addEventListener("click", focusGuidedAngleControl); guidedFirstEditDismiss.addEventListener("click", dismissGuidedFirstEdit); // --- Transport --- playpause.addEventListener("click", () => { if (viewer) setPlaying(viewer.toggle()); }); scrub.addEventListener("input", () => { if (!viewer) return; scrubbing = true; paintScrub(); viewer.seek((Number(scrub.value) / 1000) * viewer.duration); scheduleScrubDiagnosticsRefresh(); }); scrub.addEventListener("change", () => { scrubbing = false; }); loop.addEventListener("change", () => viewer?.setLoop(loop.checked)); // Playback speed persists across reloads so an author who prefers slow-motion // scrubbing does not have to re-select it every visit. const SPEED_STORAGE_KEY = "posecode.playbackSpeed"; function restoreSpeed() { try { const saved = localStorage.getItem(SPEED_STORAGE_KEY); // Only honour a saved value the current