/** * One shared settings store for the Customizer host. * * Inside `customize.php` every Aureon surface is its own native * `WP_Customize_Section`, each mounting its own small React root (see * sections.tsx). Those roots are siblings, not one tree, so they can't share * React state — but they very much edit the same settings: Colors' preset * "bundle apply" writes into Buttons' `design.radius` and Typography's * `font_pairings`; the Modules section's toggles gate whether other sections * are even shown. This module is the single source of truth they all read * from and write through, so a write in one root is immediately visible in * every other. * * Two kinds of value live here, with different destinations: * * - The theme's own tree (`working`) — every path is a registered * `WP_Customize_Setting`, so a write goes straight to `wp.customize()`. * That marks the Customizer dirty and live-updates the preview exactly as * editing a native control would, and core's own Publish persists it. There * is deliberately no Save button of our own here. * - Plugin-contributed surfaces (`panelValues`) — these live in plugin-owned * storage behind their own REST routes, which core's changeset knows * nothing about. They're held locally and flushed on Publish; see * {@link flushPanelValues}. */ import apiFetch from '@wordpress/api-fetch'; import { getPath, writePath } from '../tree-utils'; import { getValue, setValue, onSave, refreshPreview, markUnsaved, } from '../customize-bridge'; import { loadSchema } from '../settings-transport'; import type { Notice, PanelSurface, PanelValues, SettingsSchema, WorkingSettings, } from '../types'; /** Every plugin-contributed surface, targeted or not — all load and save the same way. */ const PANEL_SURFACES: PanelSurface[] = [ ...( window.aureonAdmin?.sections ?? [] ), ...( window.aureonAdmin?.areas ?? [] ), ]; export interface StoreState { working: WorkingSettings; schema: SettingsSchema; defaults: Partial< WorkingSettings >; panelValues: PanelValues; /** `:` while a plugin action button is in flight. */ pendingAction: string | null; /** Transient feedback from a plugin action; the section that owns it renders it. */ notice: Notice | null; } type Listener = ( state: StoreState ) => void; const listeners = new Set< Listener >(); let state: StoreState = { working: {} as WorkingSettings, schema: window.aureonAdmin?.schema ?? {}, defaults: window.aureonAdmin?.defaults ?? {}, panelValues: {}, pendingAction: null, notice: null, }; const emit = ( next: Partial< StoreState > ): void => { state = { ...state, ...next }; listeners.forEach( ( listener ) => listener( state ) ); }; export const getState = (): StoreState => state; /** * Subscribe to every change. Returns its own unsubscribe, so a React root can * hand it straight to `useEffect`'s cleanup. * * @param listener Called with the whole new state after each change. */ export function subscribe( listener: Listener ): () => void { listeners.add( listener ); return () => { listeners.delete( listener ); }; } /** * Re-assemble the whole tree from `wp.customize()` — the authoritative * post-sanitize source both at load and after a Publish. */ function readTree(): WorkingSettings { const ids = window.aureonAdmin?.settingIds ?? {}; const tree: Record< string, unknown > = {}; Object.keys( ids ).forEach( ( path ) => { writeInto( tree, path, getValue( path ) ); } ); return tree as WorkingSettings; } /** * Assign at a dotted path, creating plain objects along the way. (Local to * this module so `readTree` doesn't have to clone the whole tree per leaf the * way the immutable `writePath` does.) * * @param target Object to write into, mutated in place. * @param path Dotted path. * @param value Value to assign. */ function writeInto( target: Record< string, unknown >, path: string, value: unknown ): void { const segments = path.split( '.' ); let ref = target; for ( let i = 0; i < segments.length - 1; i++ ) { const child = ref[ segments[ i ] ]; ref[ segments[ i ] ] = child && 'object' === typeof child && ! Array.isArray( child ) ? child : {}; ref = ref[ segments[ i ] ] as Record< string, unknown >; } ref[ segments[ segments.length - 1 ] ] = value; } /** * Push a write out to `wp.customize()`. Three cases, since a write doesn't * always land exactly on one registered setting: * * - `path` itself is a registered id (a `design.*` leaf) — push it directly. * - `path`'s top-level segment is a registered whole-tree id (`layout`, * `header`, …) — push that entire updated subtree, since only the top-level * key is a registered setting. * - `path` is itself the *parent* of individually-registered leaves (a preset * applying all of `design.colors` at once) — push every matching leaf. * * @param path Dotted settings path that was written. * @param tree The tree, already updated with that write. */ function push( path: string, tree: WorkingSettings ): void { const ids = window.aureonAdmin?.settingIds ?? {}; if ( path in ids ) { setValue( path, getPath( tree, path ) ); return; } const rootKey = path.split( '.' )[ 0 ]; if ( rootKey in ids ) { setValue( rootKey, getPath( tree, rootKey ) ); return; } const prefix = `${ path }.`; Object.keys( ids ) .filter( ( id ) => id.startsWith( prefix ) ) .forEach( ( leaf ) => setValue( leaf, getPath( tree, leaf ) ) ); } /** * Write one settings-tree path — locally and straight through to its * `wp.customize` setting, which is what makes it dirty, previewed and * Publishable. * * @param path Dotted settings path. * @param value New value. */ export function setPath( path: string, value: unknown ): void { const working = writePath( state.working, path, value ); push( path, working ); emit( { working } ); } /** * Write one field of one plugin-contributed surface. Flat keys only — the * descriptors don't nest. * * @param surfaceKey Surface key. * @param field Field key. * @param value New value. */ export function setPanelValue( surfaceKey: string, field: string, value: unknown ): void { emit( { panelValues: { ...state.panelValues, [ surfaceKey ]: { ...( state.panelValues[ surfaceKey ] ?? {} ), [ field ]: value, }, }, } ); dirtyPanelKeys.add( surfaceKey ); markUnsaved(); } /** Surfaces edited since the last flush, so Publish only posts what changed. */ const dirtyPanelKeys = new Set< string >(); export const clearNotice = (): void => emit( { notice: null } ); /** * Run an `action` field on a plugin surface: POST `{ action, values }` to its * own route, then adopt the state it returns. Deliberately outside the * Publish cycle — an action does work (activating a license, say) rather than * persisting a form. * * A response may also set `refresh` to say the action changed something the * theme reads from outside its own settings tree, so neither the schema in * this store nor the preview iframe reflects the site any more. Both are then * re-read: the schema over REST (it's what gates, for one, Cart's and * Checkout's "this store uses the block design" notice — the very thing a * switch action has just made untrue), and the preview through core's own * `previewer.refresh()`, since no setting changed to trigger that itself. * * @param surfaceKey Surface key. * @param action Action name from the field descriptor. */ export function runPanelAction( surfaceKey: string, action: string ): void { const surface = PANEL_SURFACES.find( ( s ) => s.key === surfaceKey ); if ( ! surface ) { return; } emit( { pendingAction: `${ surfaceKey }:${ action }`, notice: null } ); apiFetch< { settings?: Record< string, unknown >; message?: Notice; refresh?: boolean; } >( { path: surface.restPath, method: 'POST', data: { action, values: state.panelValues[ surfaceKey ] ?? {} }, } ) .then( ( res ) => { const values = res?.settings ?? state.panelValues[ surfaceKey ] ?? {}; dirtyPanelKeys.delete( surfaceKey ); emit( { panelValues: { ...state.panelValues, [ surfaceKey ]: values }, notice: res?.message?.text && ( 'success' === res.message.status || 'error' === res.message.status ) ? { status: res.message.status, text: res.message.text } : null, } ); if ( ! res?.refresh ) { return; } refreshPreview(); // Failing to re-read leaves the stale schema in place — the // section carries on showing a notice that's now out of date, // which is where it already was, so there's nothing to report. loadSchema() .then( ( schema ) => emit( { schema } ) ) .catch( () => {} ); } ) .catch( ( e: Error ) => emit( { notice: { status: 'error', text: e.message || 'That didn’t work.', }, } ) ) .finally( () => emit( { pendingAction: null } ) ); } /** * POST every edited plugin surface to its own route. * * Core's changeset only persists registered `WP_Customize_Setting`s, and these * values aren't any — the plugin owns their storage and sanitization. Bound to * the Customizer's own save below, so Publish saves everything on screen * rather than silently dropping the plugin-contributed half. */ function flushPanelValues(): void { Array.from( dirtyPanelKeys ).forEach( ( key ) => { const surface = PANEL_SURFACES.find( ( s ) => s.key === key ); if ( ! surface || ! surface.saves ) { dirtyPanelKeys.delete( key ); return; } apiFetch< { settings?: Record< string, unknown > } >( { path: surface.restPath, method: 'POST', data: state.panelValues[ key ] ?? {}, } ) .then( ( res ) => { const values = res?.settings ?? state.panelValues[ key ] ?? {}; emit( { panelValues: { ...state.panelValues, [ key ]: values }, } ); } ) .catch( () => { // Keep the edits and the dirty mark so the next Publish retries. } ) .finally( () => dirtyPanelKeys.delete( key ) ); } ); } /** * Hydrate the store and wire it to the Customizer's lifecycle. Safe to call * once, at bundle load, before any section has been navigated into. */ export function initStore(): void { emit( { working: readTree() } ); // Each plugin surface loads from its own route, in parallel — one that // fails is skipped rather than blocking anything, the theme's own // settings don't depend on it. That used to mean one `emit()` per surface, // the moment its own request landed; the browser doesn't run a dozen // fetches in lockstep, so they straggle in independently over the page's // first few seconds. Every `emit()` re-renders every mounted section — // this store has no per-section selectors — so a dozen sections each // repainting once, staggered across those few seconds, is what read as // several of them blinking on open: whichever happened to be mounted // while the remaining fetches were still trickling in. `Promise.allSettled` // still lets one surface's failure skip only that surface, but folds the // population of `panelValues` into a single emit instead of up to eleven. Promise.allSettled( PANEL_SURFACES.map( ( surface ) => apiFetch< { settings?: Record< string, unknown > } >( { path: surface.restPath, } ).then( ( res ) => [ surface.key, res?.settings ?? res ?? {} ] as const ) ) ).then( ( results ) => { const panelValues: PanelValues = { ...state.panelValues }; results.forEach( ( result ) => { if ( 'fulfilled' === result.status ) { const [ key, settings ] = result.value; panelValues[ key ] = settings; } } ); emit( { panelValues } ); } ); onSave( () => { flushPanelValues(); // Re-read once core has written: the stored values are post-sanitize // and can differ from what was pushed. window.setTimeout( () => emit( { working: readTree() } ), 0 ); } ); }