/** * ELEMENT RESOLVER * * Central, schema-aware logic to: * - Resolve a logical path (e.g. ["elements", 0, "elements", 1]) to a stable element id. * - Enumerate all element paths for a slide (for engine.elements(slideIndex) and path-based element()). * * Supports: explicit `id` on objects, `ids` on the slide for named fields, and fallback to * elemId(slideIndex, ...path). Works for all built-in layouts; extend PATH_GENERATORS for new types. * * @see resolveId * @see getElementPaths * @see getElementIds * @see Lumina.element * @see Lumina.elements */ import { getByPath } from '../utils/deep'; import { elemId } from './elementId'; import type { BaseSlideData } from './types'; /** * Logical path into slide data: property names and array indices. Used by resolveId and * engine.element(slideIndex, path). String form: "tag", "features.0", "elements.0.elements.1". */ export type ElementPath = (string | number)[]; /** * Converts an ElementPath to a dot-notation key for getByPath (e.g. ["features", 0] → "features.0"). */ export function pathToKey(path: ElementPath): string { return path.join('.'); } /** * Reads the value at `path` in the slide object. Uses dot-notation traversal; indices are * stringified (e.g. "features.0"). * * @param slide - Slide data (BaseSlideData). Can be any object for generic traversal. * @param path - Path segments (e.g. ['features', 0] or ['elements', 0, 'elements', 1]). * @returns The value at that path, or undefined if missing. */ export function getValueAt(slide: Readonly, path: ElementPath): unknown { if (!slide || !path.length) return undefined; return getByPath(slide, pathToKey(path)); } /** * Parses a path from string or array. Use for engine.element(slideIndex, path) when * path is a string like "features.0" or "elements.0.elements.1". * * Rules: split by "."; numeric segments become numbers, rest stay strings. * * @param input - String ("features.0") or already-parsed ElementPath. * @returns Normalized ElementPath. Empty array if input is not string or array. * * @example * parsePath("tag") // ['tag'] * parsePath("features.0") // ['features', 0] * parsePath("elements.0.elements.1") // ['elements', 0, 'elements', 1] */ export function parsePath(input: string | ElementPath): ElementPath { if (Array.isArray(input)) return input; if (typeof input !== 'string') return []; return input.split('.').map((p) => (/^\d+$/.test(p) ? parseInt(p, 10) : p)); } /** * Resolves the stable element id for a (slide, slideIndex, path). This id is used in * data-lumina-id, engine.element(id), and meta.initialElementState. Resolution order: * 1. Path [] or ['slide'] → slide.id or elemId(slideIndex, 'slide'). * 2. If the value at path is an object with string `id` → use it (e.g. feature.id, node.id). * 3. If slide.ids[pathToKey(path)] exists → use it (supports compound keys: 'tag', 'features.0', 'elements.0.elements.1'). * 4. Otherwise → if slide.id is set, "{slide.id}-{path}"; else elemId(slideIndex, ...path) * (e.g. "intro-tag" with slide.id "intro", or "s0-tag" when no slide.id). * * @param slide - The slide data. * @param slideIndex - Zero-based slide index (for elemId fallback). * @param path - Logical path (from getElementPaths or parsePath). * @returns Element id string. Use in engine.element(id) or meta.initialElementState. * * @see getElementPaths * @see getElementIds * @see elemId */ export function resolveId( slide: Readonly, slideIndex: number, path: ElementPath ): string { const slideAny = slide as { id?: string; ids?: Record }; if (path.length === 0 || (path.length === 1 && path[0] === 'slide')) { return slideAny?.id || elemId(slideIndex, 'slide'); } const obj = getValueAt(slide, path); if (obj != null && typeof obj === 'object' && typeof (obj as { id?: string }).id === 'string') { return (obj as { id: string }).id; } const key = pathToKey(path); if (key && slideAny?.ids?.[key]) { return slideAny.ids[key]; } // Fallback: use slide.id as namespace when present, so IDs stay stable when slides are // inserted, removed or reordered. Otherwise s{N}-{path} (same as before). if (slideAny?.id != null && slideAny.id !== '') { return `${slideAny.id}-${path.map(String).join('-')}`; } return elemId(slideIndex, ...path); } /** Function that returns all logical element paths for a given slide. One per layout type. */ export type PathGenerator = (slide: Readonly) => ElementPath[]; /** Map of slide.type → path generator. Extend to support new layouts. */ const PATH_GENERATORS: Record = { statement: (s) => { const paths: ElementPath[] = [['title']]; if (getValueAt(s, ['tag'])) paths.unshift(['tag']); if (getValueAt(s, ['subtitle'])) paths.push(['subtitle']); return paths; }, features: (s) => { const arr = getValueAt(s, ['features']); const list = Array.isArray(arr) ? arr : []; // Omit header (parent of title/description) to avoid animating container + children = jump const paths: ElementPath[] = [['title']]; if (getValueAt(s, ['description'])) paths.push(['description']); return [...paths, ...list.map((_: unknown, i: number) => ['features', i] as ElementPath)]; }, half: (s) => { const paths: ElementPath[] = [['media'], ['title'], ['paragraphs']]; if (getValueAt(s, ['tag'])) paths.splice(1, 0, ['tag']); // after media, before title if (getValueAt(s, ['cta'])) paths.push(['cta']); return paths; }, timeline: (s) => { const arr = getValueAt(s, ['timeline']); const list = Array.isArray(arr) ? arr : []; const paths: ElementPath[] = [['title']]; if (getValueAt(s, ['subtitle'])) paths.push(['subtitle']); return [...paths, ...list.map((_: unknown, i: number) => ['timeline', i] as ElementPath)]; }, steps: (s) => { const arr = getValueAt(s, ['steps']); const list = Array.isArray(arr) ? arr : []; // Omit header (parent of title/subtitle) to avoid animating container + children = jump const paths: ElementPath[] = [['title']]; if (getValueAt(s, ['subtitle'])) paths.push(['subtitle']); return [...paths, ...list.map((_: unknown, i: number) => ['steps', i] as ElementPath)]; }, flex: (s) => { const paths: ElementPath[] = []; const els = getValueAt(s, ['elements']); const list = Array.isArray(els) ? els : []; list.forEach((e: unknown, i: number) => { paths.push(['elements', i]); const ob = e && typeof e === 'object' ? (e as { type?: string; elements?: unknown[] }) : null; if (ob?.type === 'content' && Array.isArray(ob.elements)) { ob.elements.forEach((_: unknown, j: number) => paths.push(['elements', i, 'elements', j])); } }); return paths; }, chart: (s) => { const paths: ElementPath[] = []; if (getValueAt(s, ['title'])) paths.push(['title']); if (getValueAt(s, ['subtitle'])) paths.push(['subtitle']); paths.push(['chart']); return paths; }, diagram: (s) => { const p: ElementPath[] = []; const nodes = getValueAt(s, ['nodes']); const edges = getValueAt(s, ['edges']); (Array.isArray(nodes) ? nodes : []).forEach((_: unknown, i: number) => p.push(['nodes', i])); (Array.isArray(edges) ? edges : []).forEach((_: unknown, i: number) => p.push(['edges', i])); return p; }, custom: () => [], video: (s) => { const paths: ElementPath[] = [['video']]; if (getValueAt(s, ['title'])) paths.push(['title']); return paths; }, free: (s) => { const arr = getValueAt(s, ['elements']); const list = Array.isArray(arr) ? arr : []; return list.map((_: unknown, i: number) => ['elements', i] as ElementPath); }, }; /** * Registers or overrides the path generator for a slide type. Use to support custom layouts * or to change how elements are enumerated for engine.elements(slideIndex) and path-based * engine.element(slideIndex, path). * * @param type - Slide type (e.g. 'statement', 'features', or a custom type like 'diagram-v2'). * @param fn - Generator that returns ElementPath[] for a slide of that type. * * @example * import { registerElementPaths, getElementPaths } from 'lumina-slides'; * registerElementPaths('my-layout', (slide) => [['title'], ['blocks', 0], ['blocks', 1]]); */ export function registerElementPaths(type: string, fn: PathGenerator): void { PATH_GENERATORS[type] = fn; } /** * Returns all logical element paths for a slide. Used by {@link getElementIds} and thus * engine.elements(slideIndex). Always includes the slide root ['slide']; the rest come from * PATH_GENERATORS for the slide's type. Add new layout types by extending PATH_GENERATORS. * * @param slide - The slide data (must have `type`). * @returns Array of paths, e.g. [['slide'], ['tag'], ['title'], ['subtitle']] for statement. * * @see getElementIds * @see resolveId * @see Lumina.elements */ export function getElementPaths(slide: BaseSlideData): ElementPath[] { const t = (slide?.type as string) || 'unknown'; const gen = PATH_GENERATORS[t] || (() => []); return [['slide'], ...gen(slide)]; } /** * Returns all element ids for a slide. Used by engine.elements(slideIndex) and useful to * know which ids can be passed to engine.element(id) or to meta.initialElementState. * * @param slide - The slide data. * @param slideIndex - Zero-based slide index (for resolveId). * @returns Array of id strings, e.g. ["s0-slide","s0-tag","s0-title","s0-subtitle"]. * * @see getElementPaths * @see resolveId * @see Lumina.elements * @see DeckMeta.initialElementState */ export function getElementIds(slide: Readonly, slideIndex: number): string[] { return getElementPaths(slide).map((p) => resolveId(slide, slideIndex, p)); }