/** * Template interpolation for Lumina slide content. * * Replaces `{{key}}` placeholders in strings with values from a key-value store * (e.g. engine.data / store.userData). When the store changes, any component * that uses the interpolated result will reactively update. * * @example * interpolateString('Hello {{name}}', { name: 'World' }) // 'Hello World' * interpolateObject({ title: '{{product}}', subtitle: 'v{{version}}' }, { product: 'Lumina', version: 1 }) * // { title: 'Lumina', subtitle: 'v1' } */ /** Matches {{key}} or {{ key }}. Key: alphanumeric, underscore. */ const TAG_RE = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g; /** * Replaces all {{key}} placeholders in a string with values from `data`. * Missing keys render as empty string. Non-string values are coerced with String(). * * @param str - Raw string possibly containing `{{key}}` tags. * @param data - Key-value map (e.g. engine.data / store.state.userData). * @returns Interpolated string. */ export function interpolateString(str: string, data: Record): string { if (typeof str !== 'string') return str; return str.replace(TAG_RE, (_, key: string) => { const v = data[key]; return v == null ? '' : String(v); }); } /** * Recursively interpolates all string values in an object/array with `{{key}}` * placeholders. Other types (number, boolean, null, etc.) are returned unchanged. * Does not mutate the input; returns a new structure. * * @param obj - Object, array, or primitive (strings are interpolated). * @param data - Key-value map (e.g. engine.data / store.state.userData). * @returns New structure with all strings interpolated. */ export function interpolateObject(obj: T, data: Record): T { if (obj == null) return obj; if (typeof obj === 'string') return interpolateString(obj, data) as T; if (Array.isArray(obj)) return obj.map((item) => interpolateObject(item, data)) as T; if (typeof obj === 'object' && obj.constructor === Object) { return Object.fromEntries( Object.entries(obj).map(([k, v]) => [k, interpolateObject(v, data)]) ) as T; } return obj; }