/** * Dotted-path get/set helpers for a `WorkingSettings`-shaped object — * used by `customizer/store.ts`, which assembles its working tree from * `customize-bridge.ts`'s `getValue()`. */ /** * Read a dotted path out of an arbitrary nested object. * * @param source Object to read from. * @param path Dotted path, e.g. `design.colors.primary`. */ export function getPath( source: unknown, path: string ): unknown { return path .split( '.' ) .reduce< unknown >( ( ref, segment ) => ref && 'object' === typeof ref ? ( ref as Record< string, unknown > )[ segment ] : undefined, source ); } /** * Inverse of `getPath()` — writes a value at a dotted path, building up * intermediate objects along the way. For assembling a tree from scratch * (e.g. hydrating from a flat id → value map) where every intermediate is * guaranteed empty going in — see `writePath()` below for mutating an * *existing*, possibly PHP-JSON-sourced tree instead. * * @param target Object to write into (mutated in place). * @param path Dotted path, e.g. `design.colors.primary`. * @param value Value to write. */ export function setPathValue( target: Record< string, unknown >, path: string, value: unknown ): void { const segments = path.split( '.' ); const last = segments.pop() as string; let ref = target; segments.forEach( ( segment ) => { if ( 'object' !== typeof ref[ segment ] || null === ref[ segment ] ) { ref[ segment ] = {}; } ref = ref[ segment ] as Record< string, unknown >; } ); ref[ last ] = value; } /** * Deep-clones `source` and writes `value` at a dotted path in the clone, * returning the clone. Unlike `setPathValue()`, this walks through * *existing* intermediate values rather than assuming they're empty — * safe to use on a tree just loaded from PHP/JSON. * * @param source Object to clone and write into (not mutated). * @param path Dotted path, e.g. `design.colors.primary`. * @param value Value to write. */ export function writePath< T >( source: T, path: string, value: unknown ): T { const next = structuredClone( source ) as Record< string, unknown >; const segments = path.split( '.' ); let ref = next; for ( let i = 0; i < segments.length - 1; i++ ) { const child = ref[ segments[ i ] ]; // PHP serializes an empty map as `[]`, not `{}`. Descending into one // and assigning a string key would set a property on an Array, which // JSON.stringify drops — silently losing the write. Only an *empty* // array is ambiguous; a populated one is a real list, left alone. ref[ segments[ i ] ] = null === child || undefined === child || ( Array.isArray( child ) && 0 === child.length ) ? {} : child; ref = ref[ segments[ i ] ] as Record< string, unknown >; } ref[ segments[ segments.length - 1 ] ] = value; return next as T; }