import { reactive, readonly, InjectionKey } from 'vue'; import type { Deck, LuminaOptions, ActionPayload, ElementState } from './types'; import { expandValue } from './compression'; import { normalizeAliases } from './schema'; import { setByPath, insertByPath, removeByPath, moveByPath, getByPath } from '../utils/deep'; import { getElementIds } from './elementResolver'; /** * LUMINA STORE FACTORY * Refactored to support multiple instances via Dependency Injection. */ export interface LuminaState { deck: Deck | null; currentIndex: number; options: LuminaOptions; isReady: boolean; // Feature: Feedback Loop (Context Window) actionHistory: ActionPayload[]; /** * Per-element state for {@link ElementController}: visibility, opacity, transform, class, style. * Keys = element ids (e.g. "s0-title", "s1-features-0"). Initialized from * {@link DeckMeta.initialElementState} on load; updated by engine.element(id).show/hide/opacity/etc. * loadDeck applies initialElementState before assigning deck so the first paint sees the correct state. * @see loadDeck */ elementState: Record; /** * Key-value store for arbitrary user data. Access via engine.data or store.getUserData/setUserData. * Persists across deck loads; not serialized. */ userData: Record; } export type LuminaStore = ReturnType; export const StoreKey: InjectionKey = Symbol('LuminaStore'); const DEFAULT_OPTIONS: LuminaOptions = { loop: false, navigation: true, keyboard: true, touch: true, debug: false, theme: 'default', ui: { visible: true, showProgressBar: true, showSlideCount: true, showControls: true }, keys: { next: ['ArrowRight', ' ', 'Enter'], prev: ['ArrowLeft', 'Backspace'] }, animation: { enabled: true, type: 'cascade', durationIn: 1.0, durationOut: 0.5, stagger: 0.1, ease: 'power3.out' } }; /** * Deeply expands compressed values in an object. */ function deepExpand(obj: any): any { if (typeof obj === 'string') return expandValue(obj); if (Array.isArray(obj)) return obj.map(deepExpand); if (obj && typeof obj === 'object') { const newObj: any = {}; for (const key in obj) { newObj[key] = deepExpand(obj[key]); } return newObj; } return obj; } /** * Simple deep merge for patching. */ function deepMerge(target: any, source: any) { if (typeof target !== 'object' || target === null) return source; if (typeof source !== 'object' || source === null) return source; if (Array.isArray(source)) { // Arrays are replaced, not merged, to avoid duplication issues in lists return source.map(deepExpand); } const output = { ...target }; for (const key in source) { if (source[key] === Object(source[key])) { if (!(key in target)) { Object.assign(output, { [key]: deepExpand(source[key]) }); } else { output[key] = deepMerge(target[key], source[key]); } } else { Object.assign(output, { [key]: deepExpand(source[key]) }); } } return output; } /** * Creates a new isolated Lumina Store instance. * Uses the Factory pattern to support multiple engine instances on the same page. * * @param initialOptions - Optional configuration overrides. * @returns A store object containing the reactive state and methods. */ export function createStore(initialOptions: LuminaOptions = {}) { const baseOptions = { ...DEFAULT_OPTIONS, ...initialOptions }; if (initialOptions && typeof initialOptions.keys === 'object') { baseOptions.keys = { ...DEFAULT_OPTIONS.keys!, ...initialOptions.keys }; } const state = reactive({ deck: null, currentIndex: 0, options: baseOptions, isReady: false, actionHistory: [], elementState: {}, userData: {} }); // --- Getters --- /** * Returns the complete data object for the currently active slide. */ const currentSlide = () => { const slides = state.deck?.slides; if (!state.deck || !Array.isArray(slides) || slides.length === 0) return null; return slides[state.currentIndex] || null; }; /** Checks if there is a next slide available (respects loop). */ const hasNext = () => { const slides = state.deck?.slides; if (!state.deck || !Array.isArray(slides)) return false; return state.options.loop ? true : state.currentIndex < slides.length - 1; }; /** Checks if there is a previous slide available (respects loop). */ const hasPrev = () => { if (!state.deck) return false; return state.options.loop ? true : state.currentIndex > 0; }; /** Returns the current progress as a normalized value between 0 and 1. */ const progress = () => { const slides = state.deck?.slides; if (!state.deck || !Array.isArray(slides) || slides.length <= 1) return 0; return state.currentIndex / (slides.length - 1); }; // --- Actions --- /** * Updates the engine options at runtime. * Merges provided options with existing ones. * * @param options - Partial options object to merge. */ function setOptions(options: LuminaOptions) { state.options = { ...state.options, ...options }; // Theme Merging Logic if (options.theme) { if (typeof options.theme === 'string') { // Completely replace if string preset state.options.theme = options.theme; } else { // Allow fine-grained object overrides state.options.theme = options.theme; } } if (options.ui) state.options.ui = { ...state.options.ui, ...options.ui }; if (options.keys) state.options.keys = { ...state.options.keys, ...options.keys }; if (options.animation) state.options.animation = { ...state.options.animation, ...options.animation }; if (options.elementControl) state.options.elementControl = { ...(state.options.elementControl || {}), ...options.elementControl }; } /** * Ensures all elements in flex layouts have unique dragKeys for vuedraggable. */ function ensureDragKeys(obj: any): any { if (!obj || typeof obj !== 'object') return obj; if (Array.isArray(obj)) return obj.map(ensureDragKeys); const newObj = { ...obj }; if (newObj.type === 'flex' && Array.isArray(newObj.elements)) { newObj.elements = newObj.elements.map((el: any) => ({ dragKey: el.dragKey || Date.now() + Math.random(), ...ensureDragKeys(el) })); } else if (newObj.type === 'content' && Array.isArray(newObj.elements)) { newObj.elements = newObj.elements.map((el: any) => ({ dragKey: el.dragKey || Date.now() + Math.random() + 1, ...ensureDragKeys(el) })); } else { for (const key in newObj) { newObj[key] = ensureDragKeys(newObj[key]); } } return newObj; } /** * Loads a new deck into the engine and resets state. * * **Critical order (element control):** Apply `meta.initialElementState` to * `state.elementState` *before* assigning `state.deck`. Assigning `state.deck` triggers * Vue's re-render; on that first paint, LuminaElements and useTransition read * `elementState` to decide initial opacity and whether to exclude `.reveal-*` containers. * If `elementState` were applied after `state.deck`, on that first frame they would see * empty or stale state (e.g. `visible: true` from a previous load), and elements that * should start hidden would appear visible until the next tick. * * @param deck - Full deck: `{ meta: { initialElementState?, ... }, slides: [...] }`. */ function loadDeck(deck: Deck) { if (!deck || !Array.isArray(deck.slides)) { console.error('[LuminaStore] Invalid deck format'); return; } const normalizedDeck = normalizeAliases(deck); const keyedDeck = ensureDragKeys(normalizedDeck); const initial = keyedDeck.meta?.initialElementState; const initialObj = initial && typeof initial === 'object' && !Array.isArray(initial) ? initial : {}; state.elementState = Object.fromEntries( Object.entries(initialObj).map(([k, v]) => [k, { ...(v && typeof v === 'object' ? v : {}) }]) ); state.deck = deepExpand(keyedDeck); state.currentIndex = 0; state.isReady = true; state.actionHistory = []; // Elements are hidden by default. Set elementControl.defaultVisible: true (options or meta) to show all. const hideByDefault = state.options.elementControl?.defaultVisible !== true && keyedDeck.meta?.elementControl?.defaultVisible !== true; if (hideByDefault) { const inInitial = new Set(Object.keys(initialObj)); (state.deck?.slides ?? []).forEach((slide, i) => { getElementIds(slide, i).forEach((id) => { if (!inInitial.has(id)) { const cur = state.elementState[id] || {}; state.elementState[id] = { ...cur, visible: false }; } }); }); } } /** * Feature: Diff Updates * Patches the current deck with partial data. */ function patchDeck(partial: Partial) { if (!state.deck) return; const merged = deepMerge(state.deck, partial); state.deck = ensureDragKeys(merged); } /** * Records a user action for the Feedback Loop. */ function recordAction(action: ActionPayload) { state.actionHistory.push(action); if (state.actionHistory.length > 50) state.actionHistory.shift(); // Keep buffer small } /** Advances to the next slide if possible. */ function next() { if (!hasNext()) return; const count = state.deck?.slides.length || 0; let newIndex = state.currentIndex; if (state.options.loop) { newIndex = (state.currentIndex + 1) % count; } else { newIndex++; } if (newIndex !== state.currentIndex) { state.currentIndex = newIndex; // Emit event via bus (imported from events.ts, need to update imports) // Ideally store shouldn't know about bus, but for now this is the direct fix } } /** Returns to the previous slide if possible. */ function prev() { if (!hasPrev()) return; const count = state.deck?.slides.length || 0; let newIndex = state.currentIndex; if (state.options.loop) { newIndex = (state.currentIndex - 1 + count) % count; } else { newIndex--; } if (newIndex !== state.currentIndex) { state.currentIndex = newIndex; } } /** * Jumps immediately to a specific slide index. * @param index - Zero-based index of the target slide. */ function goto(index: number) { const slides = state.deck?.slides; if (!state.deck || !Array.isArray(slides)) return; if (index >= 0 && index < slides.length) { if (state.currentIndex !== index) { state.currentIndex = index; } } } // --- Editor Actions (Immutable) --- function updateNode(path: string, value: any) { if (!state.deck) return; const updated = setByPath(state.deck, path, value); state.deck = ensureDragKeys(updated); } function addNode(arrayPath: string, item: any, index?: number) { if (!state.deck) return; const target = getByPath(state.deck, arrayPath); // Default to end of array if index not provided const actualIndex = (index !== undefined) ? index : (Array.isArray(target) ? target.length : 0); // Ensure item has keys const keyedItem = ensureDragKeys(item); state.deck = insertByPath(state.deck, arrayPath, actualIndex, keyedItem); } function removeNode(arrayPath: string, index: number) { if (!state.deck) return; state.deck = removeByPath(state.deck, arrayPath, index); } function moveNode(arrayPath: string, from: number, to: number) { if (!state.deck) return; state.deck = moveByPath(state.deck, arrayPath, from, to); } /** * Merges a partial {@link ElementState} into the stored state for an element. Used by * {@link ElementController} (engine.element(id)). style and class are merged; visible, opacity, transform * are replaced when present in `patch`. * * @param id - Element id (from resolveId, elemId, or explicit id in JSON). * @param patch - Partial ElementState. Only provided keys are applied. */ function setElementState(id: string, patch: Partial) { const prev = state.elementState[id] || {}; const next: ElementState = { ...prev }; if (patch.visible !== undefined) next.visible = patch.visible; if (patch.opacity !== undefined) next.opacity = patch.opacity; if (patch.transform !== undefined) next.transform = patch.transform; if (patch.class !== undefined) next.class = patch.class; if (patch.style !== undefined) next.style = { ...(prev.style || {}), ...patch.style }; state.elementState[id] = next; } /** * Resets elementState for all ids of the given slide to their initial values. * Used when navigating to a slide so that controlled entrance animations * (e.g. engine.element(id).show()) can run again. Respects * meta.initialElementState and meta.elementControl.defaultVisible (or * options.elementControl.defaultVisible). * * @param slideIndex - Zero-based index of the slide to reset. */ function resetElementStateForSlide(slideIndex: number) { const deck = state.deck; if (!deck?.slides) return; const slide = deck.slides[slideIndex]; if (!slide) return; const initial = deck.meta?.initialElementState; const initialObj = initial && typeof initial === 'object' && !Array.isArray(initial) ? initial : {}; const hideByDefault = state.options.elementControl?.defaultVisible !== true && deck.meta?.elementControl?.defaultVisible !== true; const inInitial = new Set(Object.keys(initialObj)); getElementIds(slide, slideIndex).forEach((id) => { if (inInitial.has(id)) { const v = initialObj[id]; state.elementState[id] = { ...(v && typeof v === 'object' ? v : {}) }; } else if (hideByDefault) { state.elementState[id] = { visible: false }; } else { state.elementState[id] = {}; } }); } // --- Key-Value Store (engine.data) --- function getUserData(key: string): unknown { return state.userData[key]; } function setUserData(key: string, value: unknown): void { state.userData[key] = value; } function hasUserData(key: string): boolean { return Object.prototype.hasOwnProperty.call(state.userData, key); } function deleteUserData(key: string): boolean { if (!Object.prototype.hasOwnProperty.call(state.userData, key)) return false; delete state.userData[key]; return true; } function clearUserData(): void { state.userData = {}; } return { state: readonly(state), currentSlide, hasNext, hasPrev, progress, setOptions, loadDeck, patchDeck, updateNode, addNode, removeNode, moveNode, setElementState, resetElementStateForSlide, recordAction, next, prev, goto, getUserData, setUserData, hasUserData, deleteUserData, clearUserData }; }