import { createApp, App as VueApp, watch, computed, type Ref, type ComputedRef } from 'vue'; import LuminaDeck from '../components/LuminaDeck.vue'; import LuminaStudio from '../components/studio/LuminaStudio.vue'; import StudioEmbedRoot from '../components/studio/StudioEmbedRoot.vue'; import LuminaSpeakerNotes from '../components/LuminaSpeakerNotes.vue'; import LayoutStatement from '../components/layouts/LayoutStatement.vue'; import LayoutHalf from '../components/layouts/LayoutHalf.vue'; import LayoutFeatures from '../components/layouts/LayoutFeatures.vue'; import LayoutTimeline from '../components/layouts/LayoutTimeline.vue'; import LayoutSteps from '../components/layouts/LayoutSteps.vue'; import LayoutFlex from '../components/layouts/LayoutFlex.vue'; import LayoutAuto from '../components/layouts/LayoutAuto.vue'; import LayoutCustom from '../components/layouts/LayoutCustom.vue'; import LayoutChart from '../components/layouts/LayoutChart.vue'; import LayoutVideo from '../components/layouts/LayoutVideo.vue'; import LayoutDiagram from '../components/layouts/LayoutDiagram.vue'; import LayoutFree from '../components/layouts/LayoutFree.vue'; import LuminaElement from '../components/base/LuminaElement.vue'; import { createStore, StoreKey, LuminaStore } from './store'; import { resolveTransitionConfig } from './animationConfig'; import { computeStagger, resolveAnimationFromInput } from '../animation'; import { createElementController, createNoopElementController } from './elementController'; import { parsePath, resolveId, getElementIds } from './elementResolver'; import { elemId } from './elementId'; import type { ElementPath } from './elementResolver'; import { bus } from './events'; import { ThemeManager, deepMerge } from './theme'; import { SpeakerChannel } from './speaker-channel'; import type { Deck, LuminaOptions, LuminaEventMap, LuminaDataStore, SpeakerSyncPayload, BaseSlideData, ElementController, RevealInSequenceOptions, ThemeConfig } from './types'; import { i18n } from '../i18n'; import '../style/main.css'; /** * Lumina Engine — presentation renderer from declarative JSON. Main entry point for the library. * * @description * Mount a slide deck into a DOM element, load/patch deck data, subscribe to events (slideChange, action), * and export state for LLM context. Vanilla JS: use `engine.load(deck)`, `engine.element(id)`, `engine.on(...)`. * Elements start hidden by default and cascade-reveal on slide enter. Set `elementControl.defaultVisible: true` * to show all, or `slide.reveal: false` for manual control. Use `engine.element(id).show()` or `revealInSequence`. * `engine.element(id).animate()` and `getElementById` require the element's slide to be mounted (no-op/null otherwise). * * @example * ```ts * import { Lumina } from "lumina-slides"; * import "lumina-slides/style.css"; * * const engine = new Lumina("#app", { theme: "ocean", loop: true }); * engine.load({ meta: { title: "Demo" }, slides: [ * { type: "statement", title: "Hello", subtitle: "World" } * ]}); * engine.on("action", (p) => console.log("clicked", p)); * ``` * * @see Deck * @see LuminaOptions * @see ElementController * @see resolveTransitionConfig * @see IMPLEMENTATION.md * @see AGENTS.md */ const DEFAULT_EMBED_DECK: Deck = { meta: { title: 'Untitled' }, slides: [{ type: 'statement', title: 'New Slide', subtitle: '' }] }; export class Lumina { private app: VueApp; private store: LuminaStore | null = null; /** When studioEmbed is true, deck is synced from store.state.deck (computed). */ private _embedDeckRef: Ref | ComputedRef | null = null; /** Key-value store: `engine.data.get/set/has/delete/clear/keys`. Persists across deck loads. */ public readonly data: LuminaDataStore; // Speaker Notes state private speakerWindow: Window | null = null; private speakerChannel: SpeakerChannel | null = null; private speakerChannelId: string; private speakerUnsubscribe: (() => void) | null = null; // Timeline (Remotion-style) state private _timelineProgress = 0; private _timelineCancel: (() => void) | null = null; /** * Creates a new Lumina instance and mounts the presentation UI. * * @param selector - CSS selector for the mount target (e.g. `"#app"`, `".deck"`). * @param options - Optional: theme, loop, navigation, touch, studio, etc. See {@link LuminaOptions}. */ constructor(public selector: string, options: LuminaOptions = {}) { // Generate unique channel ID for this instance this.speakerChannelId = `lumina-speaker-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const isStudioEmbed = !!options.studioEmbed; if (isStudioEmbed) { this.store = createStore({ studio: true, elementControl: { defaultVisible: true } }); const initialDeck = options.initialDeck && Array.isArray(options.initialDeck.slides) ? options.initialDeck : DEFAULT_EMBED_DECK; this.store.loadDeck(initialDeck); this._embedDeckRef = computed(() => this.store!.state.deck ?? null) as ComputedRef; this.data = { get: (k) => this.store!.getUserData(k) as string, set: (k, v) => { this.store!.setUserData(k, v); return this.data!; }, has: (k) => this.store!.hasUserData(k), delete: (k) => this.store!.deleteUserData(k), clear: () => this.store!.clearUserData(), keys: () => Object.keys(this.store!.state.userData) } as LuminaDataStore; if (options.theme) ThemeManager.inject(options.theme); this.app = createApp(StudioEmbedRoot, { deckRef: this._embedDeckRef, initialPreviewMode: !!options.studioPreviewMode }); if (options.locale === 'en' || options.locale === 'es') { i18n.global.locale = options.locale; } this.app.use(i18n); this.app.provide(StoreKey, this.store); this.app.provide('LuminaEngine', this); watch( () => this.store!.state.currentIndex, (newIndex) => { this.store!.resetElementStateForSlide(newIndex); } ); } else { this.store = createStore(options); const dataApi: LuminaDataStore = { get: (k) => this.store!.getUserData(k), set: (k, v) => { this.store!.setUserData(k, v); return dataApi; }, has: (k) => this.store!.hasUserData(k), delete: (k) => this.store!.deleteUserData(k), clear: () => this.store!.clearUserData(), keys: () => Object.keys(this.store!.state.userData) }; this.data = dataApi; if (options.theme) ThemeManager.inject(options.theme); this.app = options.studio ? createApp(LuminaStudio, { initialPreviewMode: !!options.studioPreviewMode }) : createApp(LuminaDeck); if (options.studio && (options.locale === 'en' || options.locale === 'es')) { i18n.global.locale = options.locale; } this.app.use(i18n); this.app.provide(StoreKey, this.store); this.app.provide('LuminaEngine', this); watch(() => this.store!.state.currentIndex, (newIndex, oldIndex) => { this.store!.resetElementStateForSlide(newIndex); const deck = this.store!.state.deck; const currentSlide = deck?.slides?.[newIndex]; if (currentSlide) { bus.emit('slideChange', { index: newIndex, previousIndex: oldIndex ?? 0, slide: currentSlide }); // Reveal runs from Deck onEnter when the slide has mounted (elements in DOM). } }); watch(() => this.store!.state.deck?.meta, (newMeta) => { if (newMeta) { const fromThemeConfig = newMeta.themeConfig || {}; const direct: Partial = { colors: newMeta.colors, typography: newMeta.typography, spacing: newMeta.spacing, borderRadius: newMeta.borderRadius, effects: newMeta.effects, components: newMeta.components }; const base = (fromThemeConfig && typeof fromThemeConfig === 'object' && !Array.isArray(fromThemeConfig) ? fromThemeConfig : {}); const overrides = deepMerge(base as ThemeConfig, direct); const deck = this.store!.state.deck; const themeOrName = deck?.theme ?? newMeta.theme ?? this.store!.state.options?.theme ?? 'default'; ThemeManager.inject(themeOrName, overrides); if (newMeta.orbColor) { document.documentElement.style.setProperty('--lumina-colors-primary', newMeta.orbColor); } bus.emit('themeChange', { theme: typeof themeOrName === 'string' ? themeOrName : 'custom' }); } }, { deep: true }); bus.on('action', (payload) => { if (payload.type === 'slide-update' && typeof payload.slideIndex === 'number') { const { slideIndex, patch } = payload; if (patch && typeof patch === 'object') { if ('nodes' in patch) this.store!.updateNode(`slides.${slideIndex}.nodes`, patch.nodes); if ('edges' in patch) this.store!.updateNode(`slides.${slideIndex}.edges`, patch.edges); } } this.store!.recordAction(payload); }); } this.app.component('layout-statement', LayoutStatement); this.app.component('layout-half', LayoutHalf); this.app.component('layout-features', LayoutFeatures); this.app.component('layout-timeline', LayoutTimeline); this.app.component('layout-steps', LayoutSteps); this.app.component('layout-flex', LayoutFlex); this.app.component('layout-auto', LayoutAuto); this.app.component('layout-custom', LayoutCustom); this.app.component('layout-chart', LayoutChart); this.app.component('layout-video', LayoutVideo); this.app.component('layout-diagram', LayoutDiagram); this.app.component('layout-free', LayoutFree); this.app.component('LuminaElement', LuminaElement); this.app.mount(this.selector); if (!isStudioEmbed) this.syncSpeakerNotes(); } /** * Loads a full deck, replacing any existing content. * Use this for initial load or when swapping to a different deck. * Emits `error` if the deck is invalid; `ready` on success. * * @param deckData - Full deck: `{ meta: { title }, slides: [...] }`. See {@link Deck}. * @example * engine.load({ meta: { title: "Q4 Review" }, slides: [ { type: "statement", title: "Intro" } ] }); */ public load(deckData: Deck) { if (!deckData || !Array.isArray(deckData.slides)) { bus.emit('error', new Error('Invalid deck: expected { meta?, slides: [] }')); return; } try { if (this.store) { this.store.loadDeck(deckData); this.syncSpeakerNotes(); } bus.emit('ready', deckData); } catch (e) { bus.emit('error', e instanceof Error ? e : new Error(String(e))); } } /** * Merges partial changes into the current deck without full reload. * Use for incremental updates (e.g. from streaming or edits). * Emits `patch` with the diff. * * @param diff - Partial deck: `meta` and/or `slides`. Deep-merged; `slides` array is replaced if provided. * @example * engine.patch({ meta: { title: "Updated Title" } }); */ public patch(diff: Partial) { if (!this.store) return; this.store.patchDeck(diff); bus.emit('patch', { diff: diff ?? {} }); this.syncSpeakerNotes(); } /** * Exports current slide index, type, and interaction history for LLM context. * Use when feeding "where the user is" back into an agent. * * @returns Frozen object: `{ status, currentSlide: { index, id, type, title }, narrative, engagementLevel, history }`. * @example * const state = engine.exportState(); * // "User is on slide 3 (features). Session: clicked 'Learn More' -> navigated next." */ public exportState() { if (!this.store) return Object.freeze({ status: 'active' as const, currentSlide: null, narrative: '', engagementLevel: 'Low Engagement', history: [] }); const { currentIndex, deck, actionHistory } = this.store.state; const slide = deck?.slides[currentIndex]; const context = actionHistory.map(a => `User ${a.type}ed on ${a.label || a.value}`).join(' -> '); const interest = actionHistory.length > 5 ? "High Engagement" : "Low Engagement"; return Object.freeze({ status: "active", currentSlide: { index: currentIndex, id: slide?.id || currentIndex, type: slide?.type, title: (typeof slide?.title === 'string' ? slide.title : null) || "(No Title)" }, narrative: `User is currently on slide ${currentIndex + 1}. Session Flow: ${context || "Just started"}.`, engagementLevel: interest, history: [...actionHistory] }); } /** * Subscribes to an engine event. Use for slide changes, button clicks, errors, and lifecycle. * * @param event - Event name. See {@link LuminaEventMap}: `ready`, `slideChange`, `action`, `error`, * `patch`, `destroy`, `navigate`, `themeChange`, `speakerNotesOpen`, `speakerNotesClose`, * `timelineSeek`, `timelineComplete`, `revealStart`, `revealComplete`, `revealElement`. * @param handler - Callback with typed payload for the event. * @example * engine.on("slideChange", ({ index, slide }) => console.log(`Slide ${index}: ${slide.type}`)); * engine.on("action", (p) => { if (p.type === "button") sendToAgent(`Clicked: ${p.label}`); }); * engine.on("patch", ({ diff }) => console.log("Deck patched", diff)); */ public on(event: K, handler: (e: LuminaEventMap[K]) => void) { bus.on(event, handler); } /** * Unsubscribes a previously added handler for an event. * * @param event - Event name. * @param handler - The same function reference passed to `on`. */ public off(event: K, handler: (e: LuminaEventMap[K]) => void) { bus.off(event, handler); } /** * Emits an error to subscribers of the `error` event. Use to forward errors from your app (e.g. load failures, API errors). * * @param err - Error instance to emit. */ public emitError(err: Error) { bus.emit('error', err); } /** * Unmounts the app, clears events, and closes speaker notes. Call when removing the presentation from the page. * Emits `destroy` before clearing handlers. */ public destroy() { bus.emit('destroy', {}); this.closeSpeakerNotes(); if (this.app) { this.app.unmount(); } bus.clear(); } /** Zero-based index of the currently visible slide. In studioEmbed mode returns 0. */ public get currentSlideIndex() { return this.store ? this.store.state.currentIndex : 0; } /** * Jumps to a slide by index. * @param index - Zero-based slide index. Clamped to [0, slides.length - 1]. */ public goTo(index: number) { if (!this.store) return; const from = this.store.state.currentIndex; this.store.goto(index); if (this.store.state.currentIndex !== from) { bus.emit('navigate', { direction: 'goto', fromIndex: from, toIndex: this.store.state.currentIndex }); } this.syncSpeakerNotes(); } /** Advances to the next slide (or first if loop and at end). */ public next() { if (!this.store) return; const from = this.store.state.currentIndex; this.store.next(); if (this.store.state.currentIndex !== from) { bus.emit('navigate', { direction: 'next', fromIndex: from, toIndex: this.store.state.currentIndex }); } this.syncSpeakerNotes(); } /** Goes to the previous slide (or last if loop and at start). */ public prev() { if (!this.store) return; const from = this.store.state.currentIndex; this.store.prev(); if (this.store.state.currentIndex !== from) { bus.emit('navigate', { direction: 'prev', fromIndex: from, toIndex: this.store.state.currentIndex }); } this.syncSpeakerNotes(); } /** * Returns the DOM node with data-lumina-id equal to `id`. Used by ElementController.animate * and for direct DOM access. The element exists only when its slide is mounted (e.g. switching * slides unmounts the previous slide’s content). * * @param id - Element id (from resolveId, elemId, or explicit id in the slide JSON). * @returns The HTMLElement or null if not found or not yet mounted. * * @see element * @see resolveId * @see elemId */ public getElementById(id: string): HTMLElement | null { const container = document.querySelector(this.selector); if (!container) return null; const root = container.querySelector('[data-lumina-root]') || container; const escaped = id.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); const el = root.querySelector(`[data-lumina-id="${escaped}"]`); return el instanceof HTMLElement ? el : null; } /** * Returns an {@link ElementController} to change one slide element’s state in real time * (visibility, opacity, transform, classes, style, GSAP animation). Use for: starting with * a blank slide and revealing items in order (via meta.initialElementState + .show()), hiding * highlights, or syncing with voice/agent. * * Overloads: * - **element(id: string)** — by resolved or explicit id (e.g. "s0-title", "intro-tag", or a * diagram node id). Use when you already have the id (from elements(), getElementIds, or * meta.initialElementState). * - **element(slideIndex: number, path: string | ElementPath)** — by logical path. path can be * a string ("tag", "features.0", "elements.0.elements.1") or an array (['elements', 0, 'elements', 1]). * The id is resolved via resolveId; then the same controller is returned as element(id). * * The target element must be wrapped with LuminaElement or have data-lumina-id (layouts do this * via resolveId). If the element is not in the DOM (e.g. another slide), show/hide/opacity/etc. * still update the store and apply when the slide is shown; animate() is a no-op until mounted. * * @param idOrSlide - Element id string, or (when using path) zero-based slide index. * @param path - When idOrSlide is a number: path string or ElementPath. Ignored when idOrSlide is string. * @returns ElementController (chainable: .show(), .hide(), .opacity(n), .animate({...}), etc.). * * @example * engine.element('s0-title').hide(); * engine.element(0, 'tag').show(); * engine.element(1, 'features.0').opacity(0.5).animate({ to: { opacity: 1 }, duration: 0.6 }); * engine.element(2, ['elements', 0, 'elements', 1]).show(); * // With meta.initialElementState hiding s0-tag, s0-title, s0-subtitle: * engine.element(0, 'tag').show(); * await delay(400); * engine.element(0, 'title').show().animate({ from: { y: 20, opacity: 0 }, to: { y: 0, opacity: 1 }, duration: 0.5 }); * * @see elements * @see getElementById * @see resolveId * @see getElementIds * @see ElementController * @see DeckMeta.initialElementState */ public element(id: string): ElementController; public element(slideIndex: number, path: string | ElementPath): ElementController; public element(idOrSlide: string | number, path?: string | ElementPath): ElementController { if (!this.store) return createNoopElementController(this, typeof idOrSlide === 'string' ? idOrSlide : ''); if (typeof idOrSlide === 'number') { const slide = this.store.state.deck?.slides[idOrSlide]; const p = parsePath(path!); const id = slide ? resolveId(slide, idOrSlide, p) : elemId(idOrSlide, ...p); return createElementController(this.store, this, id); } return createElementController(this.store, this, idOrSlide); } /** * Returns the element at the given path on the current slide. Shorthand for * engine.element(engine.currentSlideIndex, path). Use when you don't need the slide index. * * @param path - Logical path (e.g. "title", "features.0", ["elements", 0, "elements", 1]). * @returns ElementController for that element. * * @example * engine.elementInCurrent("title").show(); * engine.elementInCurrent("features.0").animate({ from: { opacity: 0 }, to: { opacity: 1 }, duration: 0.5 }); * * @see element * @see elements */ public elementInCurrent(path: string | ElementPath): ElementController { const i = this.store ? this.store.state.currentIndex ?? 0 : 0; return this.element(i, path); } /** * Returns all element ids for a slide. Use to discover which ids exist (e.g. for * meta.initialElementState, or to iterate and control elements). Each id can be passed to * engine.element(id). Uses the same path→id logic as element(slideIndex, path); ids follow * resolveId (explicit id, slide.ids, or slide.id / elemId(slideIndex, ...path) as fallback). * * @param slideIndex - Zero-based slide index. Omit to use the current slide. If out of range or deck not loaded, returns []. * @returns Array of id strings (e.g. ["s0-slide","s0-tag","s0-title","s0-subtitle"] or ["intro-slide","intro-tag",...] when slide.id is set). * * @example * engine.elements(); // current slide * engine.elements(0); * engine.elements().forEach(id => { if (id.endsWith('-title')) engine.element(id).hide(); }); * * @see element * @see elementInCurrent * @see getElementIds * @see resolveId * @see DeckMeta.initialElementState */ public elements(slideIndex?: number): string[] { if (!this.store) return []; const i = slideIndex ?? this.store.state.currentIndex ?? 0; const slide = this.store.state.deck?.slides[i]; if (!slide) return []; return getElementIds(slide, i); } /** * Hides all controlled elements of a slide. Use for blank-slide or reset-before-reveal flows. * * @param slideIndex - Zero-based slide index. Omit to use the current slide. * @returns this (chainable). * * @example * engine.hideAll(); // current slide * engine.hideAll(2); await engine.delay(300); engine.revealInSequence(2); */ public hideAll(slideIndex?: number): this { const i = slideIndex ?? this.currentSlideIndex; this.elements(i).forEach((id) => this.element(id).hide()); return this; } /** * Shows all controlled elements of a slide. * * @param slideIndex - Zero-based slide index. Omit to use the current slide. * @returns this (chainable). */ public showAll(slideIndex?: number): this { const i = slideIndex ?? this.currentSlideIndex; this.elements(i).forEach((id) => this.element(id).show()); return this; } /** * Hides all elements of the slide, then shows only the given ids. Use for focus mode or * spotlight effects. * * @param ids - Element ids to keep visible. * @param slideIndex - Zero-based slide index. Omit to use the current slide. * @returns this (chainable). * * @example * engine.showOnly(['s1-title', 's1-tag'], 1); */ public showOnly(ids: string[], slideIndex?: number): this { const i = slideIndex ?? this.currentSlideIndex; this.hideAll(i); ids.forEach((id) => this.element(id).show()); return this; } /** * Hides all elements except the given ids (convenience for hideAll + show on exceptIds). * * @param exceptIds - Element ids to keep visible. * @param slideIndex - Zero-based slide index. Omit to use the current slide. * @returns this (chainable). */ public hideAllExcept(exceptIds: string[], slideIndex?: number): this { return this.showOnly(exceptIds, slideIndex); } /** * Resets element state for a slide to the initial values (as when entering the slide). * Respects meta.initialElementState and meta.elementControl.defaultVisible. Use before * running a reveal sequence again. * * @param slideIndex - Zero-based slide index. Omit to use the current slide. * @returns this (chainable). */ public resetSlide(slideIndex?: number): this { if (!this.store) return this; this.store.resetElementStateForSlide(slideIndex ?? this.currentSlideIndex); return this; } /** * Returns a Promise that resolves after the given milliseconds. Useful for chaining * with async/await between reveal steps or after hideAll. * * @param ms - Delay in milliseconds. * * @example * engine.hideAll(0); await engine.delay(500); engine.revealInSequence(0); */ public delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } /** * Merges meta.reveal and slide.reveal into options for revealInSequence. slide overrides meta. * Used when auto-running reveal from declarative slide.reveal or meta.reveal in the deck JSON. */ private getRevealOptionsFromDeck( deck: { meta?: { reveal?: RevealInSequenceOptions }; slides?: ReadonlyArray<{ reveal?: RevealInSequenceOptions }> }, index: number ): RevealInSequenceOptions { const meta = deck.meta; const slide = deck.slides?.[index]; const a = (meta?.reveal && typeof meta.reveal === 'object') ? meta.reveal : {}; const b = (slide?.reveal && typeof slide.reveal === 'object') ? slide.reveal : {}; return { ...a, ...b }; } /** * Options for the default cascade when no meta.reveal or slide.reveal is configured. * Uses defaultCascadeDelayMs and defaultCascadeDuration from config; excludes the slide root. */ private getDefaultCascadeOptions(index: number): RevealInSequenceOptions { if (!this.store) return {}; const deck = this.store.state.deck; const slide = deck?.slides?.[index] as BaseSlideData | undefined; const cfg = resolveTransitionConfig(this.store, slide ?? undefined); const slideRootId = slide ? resolveId(slide, index, ['slide']) : undefined; return { delayMs: cfg.defaultCascadeDelayMs, duration: cfg.defaultCascadeDuration, ...(slideRootId ? { exclude: [slideRootId] as readonly string[] } : {}), }; } /** * Runs reveal for a slide if configured (default cascade, meta.reveal, or slide.reveal). * Call when the slide has mounted (e.g. from Deck's onEnter) so elements exist in the DOM. * Returns the reveal promise or undefined if no reveal runs. */ public runRevealForSlideIfNeeded(slideIndex?: number): Promise | undefined { if (!this.store) return undefined; const i = slideIndex ?? this.currentSlideIndex; const opts = this.getRevealDecision(i); if (opts === null) return undefined; return this.revealInSequence(i, opts); } /** * Decides whether and how to run reveal for a slide. Returns options to pass to revealInSequence, * or null if no reveal should run. */ private getRevealDecision(index: number): RevealInSequenceOptions | null { const deck = this.store?.state.deck; const slide = deck?.slides?.[index]; if (!slide) return null; const rev = deck?.meta?.reveal ?? (slide as { reveal?: unknown }).reveal; // Explicit opt-out: no reveal if (rev === false) return null; // Timeline-driven: no cascade if ((slide as { timelineTracks?: unknown }).timelineTracks != null) return null; // Explicit reveal config: use it if (rev && typeof rev === 'object') { return this.getRevealOptionsFromDeck(deck!, index); } // Default: fast cascade return this.getDefaultCascadeOptions(index); } /** * Reveals slide elements one by one with optional stagger and animation. Optionally * hides all first (hideFirst: true). Resolves when the sequence has been scheduled * (does not wait for the last animation to finish). * * @param slideIndex - Zero-based slide index. Omit to use the current slide. * @param options - Stagger delay, animation from/to, and filters (only, exclude). Or from slide.reveal / meta.reveal when auto-run. * @returns Promise that resolves after the last element's scheduled reveal time. * * @example * engine.on('slideChange', (e) => { engine.revealInSequence(e.index, { delayMs: 500 }); }); * await engine.revealInSequence(0, { only: ['s0-tag', 's0-title'], hideFirst: true }); */ public revealInSequence(slideIndex?: number, options?: RevealInSequenceOptions): Promise { if (!this.store) return Promise.resolve(); const i = slideIndex ?? this.currentSlideIndex; let ids = this.elements(i); const opts = options ?? {}; if (opts.only?.length) ids = ids.filter((id) => opts.only!.includes(id)); if (opts.exclude?.length) ids = ids.filter((id) => !opts.exclude!.includes(id)); const slide = this.store.state.deck?.slides[i]; const cfg = resolveTransitionConfig(this.store, slide ?? undefined); const delayMs = opts.delayMs ?? cfg.revealDelayMs; const animate = opts.animate !== false; const motions = this.store.state.deck?.meta?.motions; const resolved = resolveAnimationFromInput( { preset: opts.preset, motion: opts.motion, from: opts.from, to: opts.to, ease: opts.ease, duration: opts.duration, }, { from: { opacity: 0, y: 16 }, to: { opacity: 1, y: 0 }, ease: cfg.revealEase, duration: cfg.revealDuration }, motions ); const steps = computeStagger({ ids, delayMs, mode: opts.staggerMode ?? 'sequential', randomSeed: opts.randomSeed ?? i, }); if (opts.hideFirst !== false) this.hideAll(i); return new Promise((resolve) => { bus.emit('revealStart', { slideIndex: i, elementIds: steps.map((s) => s.id) }); if (steps.length === 0) { bus.emit('revealComplete', { slideIndex: i }); resolve(); return; } steps.forEach((step, idx) => { setTimeout(() => { bus.emit('revealElement', { slideIndex: i, elementId: step.id, index: idx }); this.element(step.id).show(); if (animate) { this.element(step.id).animate({ from: resolved.from, to: resolved.to, duration: resolved.duration, ease: resolved.ease, }); } }, step.delayMs); }); const mode = opts.staggerMode ?? 'sequential'; const totalDelay = mode === 'sequential' ? steps.length * delayMs : (steps.length ? Math.max(...steps.map((s) => s.delayMs)) : 0); setTimeout(() => { bus.emit('revealComplete', { slideIndex: i }); resolve(); }, totalDelay); }); } /** * Current timeline progress 0–1. Set by {@link seekTo} and {@link playTimeline}. */ public get timelineProgress(): number { return this._timelineProgress; } /** * Seek the slide's timeline to a progress 0–1. Applies keyframes from `slide.timelineTracks` to each * element via `element(id).animateToProgress(progress, keyframes)`. No-op if the slide has no * `timelineTracks`. Remotion-style: scrub the composition. * * @param progress - 0–1. Interpolation between keyframes is linear. * @param slideIndex - Omit to use the current slide. * * @example * engine.seekTo(0); // reset to first keyframes * engine.seekTo(0.5); // halfway * slider.oninput = () => engine.seekTo(parseFloat(slider.value)); */ public seekTo(progress: number, slideIndex?: number): this { if (!this.store) return this; const i = slideIndex ?? this.currentSlideIndex; const slide = this.store.state.deck?.slides[i]; const timeline = slide?.timelineTracks; this._timelineProgress = Math.max(0, Math.min(1, progress)); bus.emit('timelineSeek', { progress: this._timelineProgress, slideIndex: i }); if (!timeline || typeof timeline !== 'object') return this; for (const id of Object.keys(timeline)) { this.element(id).animateToProgress(this._timelineProgress, timeline[id]); } return this; } /** * Play the current slide's timeline from 0 to 1 over the given duration. Uses requestAnimationFrame. * Resolves when done. Call the returned cancel to stop early. If the slide has no `timelineTracks`, resolves immediately. * * @param durationSeconds - Time to go from 0 to 1. Default 5. * @param slideIndex - Omit to use the current slide. * @returns Promise that resolves when finished, and a cancel function. * * @example * const [promise, cancel] = engine.playTimeline(6); * promise.then(() => console.log('done')); * // cancel() to stop */ public playTimeline(durationSeconds = 5, slideIndex?: number): [Promise, () => void] { if (!this.store) return [Promise.resolve(), () => {}]; const i = slideIndex ?? this.currentSlideIndex; const slide = this.store.state.deck?.slides[i]; if (!slide?.timelineTracks || typeof slide.timelineTracks !== 'object') { return [Promise.resolve(), () => {}]; } if (this._timelineCancel) this._timelineCancel(); let rafId = 0; let start = 0; const cancel = () => { if (rafId) cancelAnimationFrame(rafId); rafId = 0; this._timelineCancel = null; }; this._timelineCancel = cancel; const run = (t: number) => { if (!start) start = t; const elapsed = (t - start) / 1000; const p = Math.min(1, elapsed / durationSeconds); this.seekTo(p, i); if (p < 1) rafId = requestAnimationFrame(run); else { rafId = 0; this._timelineCancel = null; bus.emit('timelineComplete', { slideIndex: i }); resolvePlay(); } }; let resolvePlay: () => void; const promise = new Promise((r) => { resolvePlay = r; }); rafId = requestAnimationFrame(run); return [promise, cancel]; } public openSpeakerNotes(): Window | null { if (this.speakerWindow && !this.speakerWindow.closed) { this.speakerWindow.focus(); return this.speakerWindow; } if (!SpeakerChannel.isSupported()) { console.error('[Lumina] BroadcastChannel not supported.'); return null; } const width = 600; const height = 800; const left = window.screenX + window.outerWidth; const top = window.screenY; this.speakerWindow = window.open( 'about:blank', `lumina-speaker-notes-${this.speakerChannelId}`, `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes` ); if (!this.speakerWindow) { console.warn('[Lumina] Popup blocked.'); return null; } const win = this.speakerWindow; win.document.open(); win.document.write(` Speaker Notes - Lumina
`); win.document.close(); setTimeout(() => { if (win.closed) return; Array.from(document.querySelectorAll('style, link[rel="stylesheet"]')).forEach(node => { win.document.head.appendChild(node.cloneNode(true)); }); const container = win.document.getElementById('speaker-notes-root'); if (container) { const notesApp = createApp(LuminaSpeakerNotes, { channelId: this.speakerChannelId }); notesApp.mount(container); win.addEventListener('unload', () => notesApp.unmount()); } }, 0); this.initSpeakerChannel(); bus.emit('speakerNotesOpen', {}); return this.speakerWindow; } public closeSpeakerNotes(): void { bus.emit('speakerNotesClose', {}); if (this.speakerUnsubscribe) { this.speakerUnsubscribe(); this.speakerUnsubscribe = null; } if (this.speakerChannel) { this.speakerChannel.notifyClose(); this.speakerChannel.destroy(); this.speakerChannel = null; } if (this.speakerWindow && !this.speakerWindow.closed) { this.speakerWindow.close(); } this.speakerWindow = null; } public get isSpeakerNotesOpen(): boolean { return this.speakerWindow !== null && !this.speakerWindow.closed; } private initSpeakerChannel(): void { this.speakerChannel = SpeakerChannel.getInstance(this.speakerChannelId); this.speakerUnsubscribe = this.speakerChannel.subscribe((msg: SpeakerSyncPayload) => { switch (msg.action) { case 'next': this.next(); break; case 'prev': this.prev(); break; case 'goto': if (msg.index !== undefined) this.goTo(msg.index); break; case 'ping': this.syncSpeakerNotes(); break; } }); this.syncSpeakerNotes(); const checkWindow = setInterval(() => { if (this.speakerWindow?.closed) { clearInterval(checkWindow); this.closeSpeakerNotes(); } }, 1000); } private syncSpeakerNotes(): void { if (!this.speakerChannel || !this.store) return; const { currentIndex, deck } = this.store.state; if (!deck) return; const currentSlide = deck.slides[currentIndex]; const nextSlide = deck.slides[currentIndex + 1]; const getSlideTitle = (slide: BaseSlideData | undefined): string | undefined => (slide && typeof slide.title === 'string' ? slide.title : undefined); this.speakerChannel.send({ action: 'state', index: currentIndex, totalSlides: deck.slides.length, currentNotes: currentSlide?.notes, nextSlidePreview: nextSlide ? { title: getSlideTitle(nextSlide), type: nextSlide.type } : undefined }); } }