import '@hyperframes/player' import { HyperframesSlideshow } from '@hyperframes/player/slideshow' // --------------------------------------------------------------------------- // Animated navigation // // The slideshow controller moves between hold points by seeking the deck // timeline, which jumps. Every slide's exit and entrance is authored in that // timeline, so instead of jumping we scrub forward to the next hold point, // a little faster than real time. Backward moves and long jumps still cut. type Player = HTMLElement & { currentTime: number; seek(t: number): void } type Frame = { sequenceId: string; slideIndex: number; fragmentIndex: number } type Controller = { player: Player playTo(t: number): void frame: Frame show: { slides: Array<{ sceneId: string; fragments?: number[] }> } resumeSlide(slideIndex: number, fragmentIndex: number): void next(): void prev(): void stopSlideMedia?(): void onChange(cb: () => void): () => void __kody?: true } let jumpNext = false // the next playTo cuts instead of scrubbing const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)') const SPEED = 1.8 // timeline seconds per wall-clock second const MAX_SCRUB = 6 // longer forward jumps (presenter skipping ahead) cut function animateNavigation(controller: Controller) { if (controller.__kody) return controller.__kody = true // Back steps through reveals one at a time, the mirror of Next: within a // slide go to the previous reveal; from a slide's first reveal go to the // previous slide fully revealed (its last hold), not its first. const prev = controller.prev.bind(controller) controller.prev = () => { const { sequenceId, slideIndex, fragmentIndex } = controller.frame if (sequenceId !== 'main') return prev() if (fragmentIndex > 0) return controller.resumeSlide(slideIndex, fragmentIndex - 1) const before = controller.show.slides[slideIndex - 1] if (!before) return prev() controller.stopSlideMedia?.() controller.resumeSlide(slideIndex - 1, Math.max(0, (before.fragments?.length ?? 1) - 1)) } let frame = 0 controller.playTo = (target: number) => { cancelAnimationFrame(frame) const player = controller.player const from = player.currentTime ?? 0 const distance = target - from const jump = jumpNext jumpNext = false if (jump || reducedMotion.matches || distance <= 0 || distance > MAX_SCRUB) { player.seek(target) return } const duration = (distance / SPEED) * 1000 const start = performance.now() const step = (now: number) => { const p = Math.min(1, (now - start) / duration) player.seek(from + distance * p) if (p < 1) frame = requestAnimationFrame(step) } frame = requestAnimationFrame(step) } } const proto = HyperframesSlideshow.prototype as unknown as { bindController(this: unknown, c: Controller): void } const bind = proto.bindController // --------------------------------------------------------------------------- // Settle every stop // // A stop (a slide's rest frame or a reveal step) is a fixed timeline time, and // the deck parks exactly there. If an entrance is still running at that moment // it would freeze half-blurred. So measure the real timeline once and push any // stop that lands mid-animation to just after that animation ends. type Tween = { startTime(): number; endTime(): number; duration(): number } type Timeline = { getChildren(nested: boolean, tweens: boolean, timelines: boolean): Tween[] } function settleStops(c: Controller) { const el = document.querySelector('hyperframes-player') as (HTMLElement & { iframeElement?: HTMLIFrameElement }) | null const frame = el?.iframeElement ?? el?.shadowRoot?.querySelector('iframe') const tl = (frame?.contentWindow as { __timelines?: Record } | null)?.__timelines?.deck if (!tl) return const spans = tl .getChildren(true, true, false) .filter((t) => t.duration() > 0.02) .map((t) => [t.startTime(), t.endTime()] as const) for (const slide of c.show.slides as Array<{ sceneId: string; fragments?: number[]; end?: number; authored?: number[] }>) { const stops = slide.fragments if (!stops?.length) continue slide.authored ??= stops.slice() const limit = (slide.end ?? Infinity) - 0.52 // never run into the slide's exit for (let i = 0; i < stops.length; i++) { const stop = slide.authored[i]! stops[i] = stop // wait for what's already moving at the stop... const busyUntil = Math.max(0, ...spans.filter(([s, e]) => s < stop - 1e-3 && e > stop + 1e-3).map(([, e]) => e)) if (!busyUntil) continue // ...but never into what comes next (the next reveal, or the exit) const nextStart = Math.min(limit, ...spans.filter(([s]) => s >= stop - 1e-3).map(([s]) => s)) const at = Math.max(stop, Math.min(busyUntil + 0.02, nextStart - 0.01)) if (busyUntil + 0.02 > nextStart - 0.01) console.warn(`Stop ${i + 1} on "${slide.sceneId}" overlaps the next animation`) stops[i] = at } } } proto.bindController = function (c) { animateNavigation(c) // The iframe's timeline can register a beat after the controller binds; the // settle is idempotent, so try now and again shortly after. for (const ms of [0, 300, 1000, 2500]) { setTimeout(() => { try { settleStops(c) } catch (error) { console.warn('Could not settle slide stops', error) } }, ms) } const result = bind.call(this, c) syncUrl(c) return result } // --------------------------------------------------------------------------- // URL ⇄ slide // // The hash names the current slide and reveal step (#/search-problem/2), so a // refresh lands where you were. Scene ids rather than numbers, so adding a // slide doesn't send old links somewhere else. function hashFor(c: Controller) { const { slideIndex, fragmentIndex } = c.frame const id = c.show.slides[slideIndex]?.sceneId if (!id) return '' return fragmentIndex > 0 ? `#/${id}/${fragmentIndex + 1}` : `#/${id}` } function resumeFromHash(c: Controller) { const [, id, step] = location.hash.match(/^#\/([^/]+)(?:\/(\d+))?$/) ?? [] if (!id) return const index = c.show.slides.findIndex((s) => s.sceneId === id) if (index < 0) return const fragment = step ? Math.max(0, Number(step) - 1) : 0 if (index === c.frame.slideIndex && fragment === c.frame.fragmentIndex) return jumpNext = true c.resumeSlide(index, fragment) } function syncUrl(c: Controller) { resumeFromHash(c) c.onChange(() => { const hash = hashFor(c) if (hash && hash !== location.hash) history.replaceState(null, '', `${location.pathname}${location.search}${hash}`) }) window.addEventListener('hashchange', () => resumeFromHash(c)) } // --------------------------------------------------------------------------- // Presentation clickers // // Most remotes send Page Down / Page Up; some send Down / Up. Handle these // before the browser scrolls, including when focus is inside the composition. const CLICKER_KEYS: Record = { PageDown: 'next', ArrowDown: 'next', PageUp: 'prev', ArrowUp: 'prev', } function onClickerKey(event: KeyboardEvent) { const action = CLICKER_KEYS[event.key] if (!action || event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return // Use the event path rather than instanceof: iframe elements belong to a // different window, and shadow DOM can retarget an editable control. if (event.composedPath().some((target) => { const element = target as Element return element.closest?.('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"]') })) return const controller = (document.querySelector('hyperframes-slideshow') as (HTMLElement & { controller?: Controller }) | null)?.controller if (!controller) return event.preventDefault() event.stopImmediatePropagation() if (!event.repeat) controller[action]() } window.addEventListener('keydown', onClickerKey, true) const clickerDocuments = new WeakSet() function hookClicker(doc: Document) { if (doc === document || clickerDocuments.has(doc)) return // Track Documents, since navigating an iframe replaces its document while // retaining the same contentWindow. Reloaded frames need a fresh listener. doc.addEventListener('keydown', onClickerKey, true) doc.addEventListener('pointermove', wake, true) doc.addEventListener('pointerdown', wake, true) hookTouch(doc) clickerDocuments.add(doc) } // --------------------------------------------------------------------------- // Phones: swipe and tap // // The deck renders inside the player's iframe, so touches on a slide never // reach the slideshow's own touch handlers. Listen in every deck document // (and the page around it): a horizontal swipe of 40px or more moves, a tap on // the left third goes back, anywhere else goes forward. Taps on links, buttons // and widgets (agent logos) are left alone. touch-action: none keeps Chrome // from scrolling, zooming or swiping back through history mid-gesture. const SWIPE_PX = 40 const TAP_PX = 10 const INTERACTIVE = 'a, button, input, select, textarea, label, summary, [role="button"], [role="link"], [contenteditable]:not([contenteditable="false"]), [data-hf-nav-cluster], .theme-toggle, .agent-logo[data-agent-group], [data-interactive]' function onDeckSurface(event: Event) { return event.composedPath().some((target) => { const element = target as Element return element.matches?.('hyperframes-slideshow') }) } function hookTouch(doc: Document) { const win = doc.defaultView if (!win) return doc.documentElement.style.touchAction = 'none' let start: { id: number; x: number; y: number; t: number; interactive: boolean } | null = null // Screen px per document px (the deck iframe is scaled down to fit). const scale = () => { const frame = win.frameElement as HTMLElement | null return frame ? frame.getBoundingClientRect().width / (win.innerWidth || 1) : 1 } doc.addEventListener( 'pointerdown', (event) => { if (event.pointerType === 'mouse' || !event.isPrimary) return if (doc === document && !onDeckSurface(event)) return const interactive = event.composedPath().some((t) => (t as Element).matches?.(INTERACTIVE)) start = { id: event.pointerId, x: event.clientX, y: event.clientY, t: event.timeStamp, interactive } }, true, ) doc.addEventListener('pointercancel', () => (start = null), true) doc.addEventListener( 'pointerup', (event) => { const s = start start = null if (!s || s.id !== event.pointerId) return const controller = (document.querySelector('hyperframes-slideshow') as (HTMLElement & { controller?: Controller }) | null)?.controller if (!controller) return const k = scale() const dx = (event.clientX - s.x) * k const dy = (event.clientY - s.y) * k if (Math.abs(dx) >= SWIPE_PX && Math.abs(dx) > Math.abs(dy)) { if (dx < 0) controller.next() else controller.prev() return } if (s.interactive || Math.abs(dx) > TAP_PX || Math.abs(dy) > TAP_PX || event.timeStamp - s.t > 600) return const host = doc === document ? document.querySelector('hyperframes-slideshow')?.getBoundingClientRect() : null const left = host ? host.left : 0 const width = host ? host.width : win.innerWidth if (event.clientX - left < width / 3) controller.prev() else controller.next() }, true, ) } hookTouch(document) // The slideshow's own touch handler would double up on the swipes above. window.addEventListener( 'touchend', (event) => { if (onDeckSurface(event)) event.stopPropagation() }, true, ) // --------------------------------------------------------------------------- // Light / dark / system // // The choice lives in localStorage, so the presenter and audience tabs (and // the deck iframes inside them) all follow it, including live changes. type Theme = 'light' | 'dark' | 'system' const KEY = 'kody-deck-theme' function readTheme(): Theme { try { const t = localStorage.getItem(KEY) return t === 'light' || t === 'dark' ? t : 'system' } catch { return 'system' } } function applyTheme(theme: Theme) { const docs = [document, ...Array.from(document.querySelectorAll('hyperframes-player'), frameDoc)] for (const doc of docs) { if (!doc) continue hookClicker(doc) if (theme === 'system') delete doc.documentElement.dataset.theme else doc.documentElement.dataset.theme = theme } for (const b of document.querySelectorAll('[data-theme-choice]')) { b.setAttribute('aria-checked', String(b.dataset.themeChoice === theme)) } } function frameDoc(player: Element): Document | null { const frame = (player as { iframeElement?: HTMLIFrameElement }).iframeElement ?? player.shadowRoot?.querySelector('iframe') try { return frame?.contentDocument ?? null } catch { return null } } function setTheme(theme: Theme) { try { if (theme === 'system') localStorage.removeItem(KEY) else localStorage.setItem(KEY, theme) } catch {} applyTheme(theme) } for (const b of document.querySelectorAll('[data-theme-choice]')) { b.addEventListener('click', () => setTheme(b.dataset.themeChoice as Theme)) } // keep the slideshow's arrow keys working after a click on the toggle document.querySelector('.theme-toggle')?.addEventListener('click', () => { document.querySelector('hyperframes-slideshow')?.focus() }) window.addEventListener('storage', (e) => { if (e.key === KEY || e.key === null) applyTheme(readTheme()) }) // Players (the main one, presenter previews) load their iframes on their own // schedule; keep every deck document in step with the current choice. setInterval(() => applyTheme(readTheme()), 500) applyTheme(readTheme()) // Hide slide controls while idle. Keep this on the root so HyperFrames can // rebuild its navigation after every reveal without making it visible again. const toggle = document.querySelector('.theme-toggle') let idleTimer = 0 function wake() { toggle?.classList.remove('idle') document.documentElement.classList.remove('controls-idle') clearTimeout(idleTimer) idleTimer = window.setTimeout(() => { toggle?.classList.add('idle') document.documentElement.classList.add('controls-idle') }, 2200) } window.addEventListener('pointermove', wake) window.addEventListener('pointerdown', wake) document.addEventListener('fullscreenchange', wake) wake()