/** * Thin typed wrapper over the slice of `wp.customize()` this theme uses. * * Only the Customizer host goes through here (see settings-transport.ts); the * standalone theme options page has no `wp.customize` at all and round-trips * over REST instead. * * Every id this addresses was registered PHP-side in * `Aureon\Customizer\Customizer` (one setting per `design.*` leaf, one per * other top-level key) — see `settingIds` in `window.aureonAdmin`, built * from that exact same path list via `Customizer::setting_ids()`, so this * file never reimplements the bracket-syntax option-name construction. */ // `wp.customize` ships no first-party types (same situation as `wp.media` — // see media-image-field.tsx); this is the narrow slice this bridge actually // uses. interface CustomizeSetting { ( newValue?: unknown ): unknown; set: ( value: unknown ) => void; // Every `wp.customize()` setting is a `Value` instance under the hood, so // it also carries `.bind()` — undeclared above because nothing needed it // until getRawValue()'s subscribeRawValue() below. bind?: ( callback: ( value: unknown ) => void ) => void; } interface CustomizeSection { expanded: { (): boolean; bind: ( callback: ( expanded: boolean ) => void ) => void; unbind: ( callback: ( expanded: boolean ) => void ) => void; }; active: { set: ( active: boolean ) => void; }; focus: () => void; } interface CustomizeValue { get: () => unknown; bind: ( callback: ( value: unknown ) => void ) => void; unbind: ( callback: ( value: unknown ) => void ) => void; } interface CustomizeControl { deferred: { embedded: { done: ( callback: () => void ) => void } }; } interface CustomizeAPI { ( id: string ): CustomizeSetting; section: ( id: string ) => CustomizeSection | undefined; state: ( id: string ) => CustomizeValue & { set: ( value: unknown ) => void; }; control: ( id: string, callback: ( control: CustomizeControl ) => void ) => void; bind: ( event: string, callback: () => void ) => void; // Core's preview device ('desktop' | 'tablet' | 'mobile'), driven by the // footer's device buttons. previewedDevice: CustomizeValue & { set: ( value: string ) => void }; settings: { url: { home: string } }; previewer: { previewUrl: CustomizeSetting; refresh: () => void; send: ( event: string, data?: unknown ) => void; bind: ( event: string, callback: () => void ) => void; unbind: ( event: string, callback: () => void ) => void; }; // Core's own notification collection, rendered in the controls pane's // `#customize-notifications-area` — see `notify()` below. notifications: { add: ( notification: unknown ) => void; remove: ( code: string ) => void; }; Notification: new ( code: string, params: { message: string; type?: string; dismissible?: boolean; } ) => unknown; } const customize = (): CustomizeAPI | undefined => ( window as unknown as { wp?: { customize?: CustomizeAPI }; } ).wp?.customize; const idFor = ( path: string ): string | undefined => window.aureonAdmin?.settingIds?.[ path ]; /** * Whether `wp.customize` is actually present — true on the Customizer host, * false on the standalone admin page. Lets a component shared between both * (see `CatalogDisplayFields` in `sections/woocommerce/shop/fields.tsx`) skip * rendering the raw-id fields it has no way to read or write outside the * Customizer. */ export function isCustomizerHost(): boolean { return !! customize(); } /** * Read one settings-tree path's current value straight from its * `wp.customize` setting. * * @param path Dotted `design.*` leaf, or a bare top-level key. */ export function getValue( path: string ): unknown { const id = idFor( path ); const api = customize(); if ( ! id || ! api ) { return undefined; } return api( id )(); } /** * Write one settings-tree path's value into its `wp.customize` setting — * marks the Customizer dirty and updates the live preview immediately, * same as editing a native control would. * * @param path Dotted `design.*` leaf, or a bare top-level key. * @param value New value. */ export function setValue( path: string, value: unknown ): void { const id = idFor( path ); const api = customize(); if ( ! id || ! api ) { return; } api( id ).set( value ); } /** * Read one `wp.customize` setting by its literal registered id, for a * setting outside the Aureon tree entirely — a core one (`show_on_front`, * say), which `idFor()` above has no dotted path to resolve since it was * never one of `Customizer::DESIGN_PATHS`/`STRUCTURAL_LABELS`. See * `StaticFrontPageSection`. * * @param id Registered `wp.customize` setting id. */ export function getRawValue( id: string ): unknown { return customize()?.( id )?.(); } /** * Write one `wp.customize` setting by its literal id — the raw-id * counterpart to {@see setValue}. * * @param id Registered `wp.customize` setting id. * @param value New value. */ export function setRawValue( id: string, value: unknown ): void { customize()?.( id )?.set( value ); } /** * Subscribe to a raw setting's changes — e.g. another browser tab's edit to * the same changeset arriving via core's own sync. See {@see getRawValue}. * * @param id Registered `wp.customize` setting id. * @param callback Invoked with the new value on every change. */ export function subscribeRawValue( id: string, callback: ( value: unknown ) => void ): void { customize()?.( id )?.bind?.( callback ); } /** * Fires once a control's markup actually exists in the DOM. * * A section nested inside a panel (every one of ours is) is embedded * *lazily* — its control content only enters the DOM once the user * actually navigates into the panel/section, not at page load. `admin.js` * runs once, at page load, well before that — mounting straight into * `document.getElementById(mountId)` at that point would silently find * nothing, since the node doesn't exist yet. `deferred.embedded` is core's * own promise for exactly this: it resolves the moment this control's * container is actually in the DOM, regardless of when that happens to be. * * @param controlId Control id. * @param callback Invoked once, when the mount node first exists. */ export function onControlEmbedded( controlId: string, callback: () => void ): void { customize()?.control( controlId, ( control ) => { control.deferred.embedded.done( callback ); } ); } // core's own save request has no fixed upper bound, but a hung Customizer // save (network drop, a validation error core's own UI didn't surface some // other way) shouldn't leave the app's Save button spinning forever. const PUBLISH_TIMEOUT_MS = 20000; /** * Trigger the Customizer's own native save (Publish) — the app's existing * Save button awaits this instead of POSTing to REST, so persistence now * goes through core's `customize_save` exactly like a native control's * change would. Resolves once core's own `saved` state observable reports * the save actually completed, not merely that the button was clicked. */ export function publish(): Promise< void > { return new Promise( ( resolve, reject ) => { const api = customize(); const saveButton = document.querySelector< HTMLButtonElement >( '#save' ); if ( ! api || ! saveButton || saveButton.disabled ) { reject( new Error( 'Customizer save control is unavailable.' ) ); return; } const savedState = api.state( 'saved' ); const timeout = setTimeout( () => { savedState.unbind( onSaved ); reject( new Error( 'Timed out waiting for the Customizer to save.' ) ); }, PUBLISH_TIMEOUT_MS ); function onSaved( isSaved: unknown ) { if ( ! isSaved ) { return; } clearTimeout( timeout ); savedState.unbind( onSaved ); resolve(); } savedState.bind( onSaved ); saveButton.click(); } ); } /** * Show or hide one native section without re-registering anything — core's * own `active` observable, the same thing an `active_callback` drives * server-side. Used for module gating: a section configuring a module that's * switched off shouldn't be in the panel's list, and the toggle that switches * it lives in the Customizer itself, so a server-side callback (evaluated * once, at page load) could never keep up. * * @param sectionId Section id. * @param active Whether the section should be listed. */ /** * Whether a section with this id is registered on the current screen — a * WooCommerce row only exists while WooCommerce is active, and two of ours * exist under core's own id rather than an `aureon_` one when it is (see * `Customizer::WOOCOMMERCE_CORE_SECTION_MERGE`). * * @param sectionId Section id. */ export function hasSection( sectionId: string ): boolean { return !! customize()?.section( sectionId ); } export function setSectionActive( sectionId: string, active: boolean ): void { customize()?.section( sectionId )?.active.set( active ); } /** * Fires whenever a section is opened in the accordion — core's own * `section.expanded` observable, which flips true on *every* route into the * section (a click in the panel list, a `focus()` from one of our own * "Configure" links, or a deep link landing straight on it). * * `onControlEmbedded` above can't stand in for this: it resolves once, the * first time the section's markup enters the DOM, so anything that has to * happen on each visit — pointing the preview at the view being edited — * needs this instead. * * @param sectionId Section id. * @param callback Invoked with the new expanded state on every change. */ export function onSectionExpanded( sectionId: string, callback: ( expanded: boolean ) => void ): void { customize()?.section( sectionId )?.expanded.bind( callback ); } /** * Subscribe to a section's expanded state, returning an unsubscribe — the * teardown-able counterpart to {@see onSectionExpanded}, for a component that * only needs to know while it's mounted. Calls back once immediately with the * current state. A no-op (never calls back) off the Customizer host. * * @param sectionId Section id. * @param callback Invoked with the expanded state now and on every change. */ export function watchSectionExpanded( sectionId: string, callback: ( expanded: boolean ) => void ): () => void { const section = customize()?.section( sectionId ); if ( ! section ) { return () => undefined; } callback( section.expanded() ); section.expanded.bind( callback ); return () => section.expanded.unbind( callback ); } /** * Subscribe to core's preview device, returning an unsubscribe. Calls back * once immediately with the current device. A no-op off the Customizer host. * * @param callback Invoked with 'desktop' | 'tablet' | 'mobile'. */ export function watchPreviewedDevice( callback: ( device: string ) => void ): () => void { const device = customize()?.previewedDevice; if ( ! device ) { return () => undefined; } const handler = ( value: unknown ) => callback( String( value ) ); handler( device.get() ); device.bind( handler ); return () => device.unbind( handler ); } /** * Switch core's preview device — the same thing the footer's device buttons * do, so the preview resizes to match. A no-op off the Customizer host. * * @param device 'desktop' | 'tablet' | 'mobile'. */ export function setPreviewedDevice( device: string ): void { customize()?.previewedDevice?.set( device ); } /** * Mark the Customizer as having unsaved changes, so Publish is enabled. * * Core only flips this for its own settings. A plugin-owned value (see * `setPanelValue()` in customizer/store.ts) is invisible to the changeset, so * without this an edit to one left Publish reading "Published" and disabled — * nothing to click to save it. A no-op off the Customizer host. */ export function markUnsaved(): void { customize()?.state( 'saved' ).set( false ); } /** * Fires when the Customizer starts a save (Publish). Core triggers this on * the `wp.customize` bus itself as the request goes out, which is what lets * plugin-owned values — invisible to core's changeset — ride along with the * same click. See `flushPanelValues()` in customizer/store.ts. * * @param callback Invoked on each save. */ export function onSave( callback: () => void ): void { customize()?.bind( 'save', callback ); } /** * While a section is open, keep the preview scrolled to the part of the page * it edits — the Footer section to the site footer, the Header back to the * top. Sent when the section expands and again each time the preview frame * finishes (re)loading, since an edit that refreshes the frame, or opening * the section before the frame is ready, would otherwise lose it. Handled by * `aureon-scroll-to` in src/frontend/customize-preview.js. Returns an * unsubscribe; a no-op off the Customizer host. * * @param sectionId Section id. * @param target Where to scroll: the footer, or the top of the page. */ export function followSectionInPreview( sectionId: string, target: 'footer' | 'top' ): () => void { const api = customize(); const section = api?.section( sectionId ); if ( ! api || ! section ) { return () => undefined; } const scroll = () => { if ( section.expanded() ) { api.previewer.send( 'aureon-scroll-to', target ); } }; const onExpanded = ( expanded: boolean ) => { if ( expanded ) { scroll(); } }; section.expanded.bind( onExpanded ); api.previewer.bind( 'ready', scroll ); scroll(); return () => { section.expanded.unbind( onExpanded ); api.previewer.unbind( 'ready', scroll ); }; } /** * Navigate to a section, expanding its panel on the way — core's own * `focus()`. Backs the Modules section's "Configure" buttons, which used to * switch the single-page app's own nav and now have real sections to jump to. * * @param sectionId Section id. */ export function focusSection( sectionId: string ): void { customize()?.section( sectionId )?.focus(); } /** * An edit shortcut's request: open this section and, for a header or footer * element, that element's settings. See src/frontend/edit-shortcuts.js. */ export interface EditRequest { section: string; element?: string; } const EDIT_EVENT = 'aureon-edit-request'; // A section's screen mounts only once the section is first opened, which is // after the shortcut has already asked for it — so the request waits here // until a screen for that section claims it. let pendingEdit: EditRequest | null = null; /** * Hand an edit shortcut's request to the screen of the section it names. * * @param request The section and, optionally, the element to edit. */ export function requestEdit( request: EditRequest ): void { pendingEdit = request; window.dispatchEvent( new window.CustomEvent( EDIT_EVENT ) ); } /** * Run `callback` with the element id each time an edit shortcut asks for an * element in this section — including one that asked before this screen * mounted. Returns an unsubscribe. * * @param sectionId Section the calling screen renders. * @param callback Opens that element's settings. */ export function onEditRequest( sectionId: string, callback: ( element: string ) => void ): () => void { const claim = () => { if ( ! pendingEdit || pendingEdit.section !== sectionId ) { return; } const { element } = pendingEdit; pendingEdit = null; if ( element ) { callback( element ); } }; claim(); window.addEventListener( EDIT_EVENT, claim ); return () => window.removeEventListener( EDIT_EVENT, claim ); } /** * Point the Customizer's own native preview iframe at a real example of the * view being edited (Content Templates' Post Feed/Article/Page/Search, * WooCommerce's Shop/Single Product/Cart/Checkout) — core's own * `previewer.previewUrl`. * * `window.aureonAdmin.previewUrls[context]` carries a `aureon_preview` * token meant for that standalone page's *separate*, non-Customizer iframe * (see Preview_Bridge on the PHP side) — stripped here since the native * preview updates live through bound `wp.customize` settings already and * doesn't need it. * * @param context One of the keys in `window.aureonAdmin.previewUrls` * ('archive' | 'post' | 'page' | 'search' | 'shop' | …). */ export function previewViewUrl( context: string ): void { const raw = window.aureonAdmin?.previewUrls?.[ context ]; const api = customize(); if ( ! raw || ! api ) { return; } let url = raw; try { const parsed = new URL( raw, window.location.href ); parsed.searchParams.delete( 'aureon_preview' ); url = parsed.toString(); } catch ( error ) { // Malformed URL — fall back to the raw value rather than blocking nav. } api.previewer.previewUrl.set( url ); } /** * Point the preview at an arbitrary same-site URL — for a page no * `previewUrls` context covers, such as a plugin surface's own `previewUrl`. * * @param url Absolute URL to load. */ export function setPreviewUrl( url: string ): void { customize()?.previewer.previewUrl.set( url ); } /** * The URL the preview is currently showing, or '' off the Customizer host. */ export function getPreviewUrl(): string { return String( customize()?.previewer.previewUrl() ?? '' ); } /** * Send the site's home back to the preview — where a section that pointed it * at a page of its own returns it on close. */ export function resetPreviewUrl(): void { const api = customize(); if ( api?.settings.url.home ) { api.previewer.previewUrl.set( api.settings.url.home ); } } /** * Post a message into the preview frame, for a page listening with * `wp.customize.preview.bind( event, … )`. * * @param event Message id. * @param data Payload. */ export function sendToPreview( event: string, data: unknown ): void { customize()?.previewer.send( event, data ); } /** * Run a callback each time a preview page finishes loading and handshakes * with the controls pane — the earliest point a message sent to it lands. * * @param callback Invoked on every preview load. */ export function onPreviewReady( callback: () => void ): void { customize()?.previewer.bind( 'ready', callback ); } /** * Listen for a message the preview frame sends (`wp.customize.preview.send()` * there). A no-op off the Customizer host. * * @param event Message name. * @param callback Receives the message's data. */ export function onPreviewMessage< T >( event: string, callback: ( data: T ) => void ): void { customize()?.previewer.bind( event, callback as () => void ); } /** * Reload the Customizer's preview iframe. * * Every *setting* live-updates the preview by itself — either through its * `postMessage` transport or core's own refresh on a `refresh`-transport * change — so this is not for settings. It's for a change made outside the * changeset entirely: a plugin action that rewrote a WooCommerce page's * content (Nexus's classic cart/checkout switch is the first), where the * preview is now showing markup the server would no longer produce and no * setting changed to tell core that. * * A no-op off the Customizer host. */ export function refreshPreview(): void { customize()?.previewer.refresh(); } /** * Show a message in the Customizer's own notification area — the banner strip * at the top of the controls pane, below the Publish header. * * Core's place for this, and the reason it's used rather than the Snackbar the * standalone page shows: in `customize.php` the reader is looking at the * narrow pane on the left, at the control they just operated. A toast in the * far bottom-right corner of a wide screen, four seconds long, is genuinely * easy to miss — and a plugin action that quietly rewrote a page is exactly * the case where silence reads as "nothing happened". * * A no-op off the Customizer host. * * @param code Stable id — re-notifying with the same code replaces the * previous message rather than stacking a second one. * @param message Text to show. * @param type Core's notification type: 'success' | 'error' | 'warning' | * 'info'. Drives the banner's colour. */ export function notify( code: string, message: string, type: string ): void { const api = customize(); if ( ! api ) { return; } api.notifications.remove( code ); api.notifications.add( new api.Notification( code, { message, type, dismissible: true } ) ); } /** * Remove a message added by {@see notify}. Safe to call for a code that isn't * currently showing. * * @param code The same code the message was added under. */ export function dismissNotification( code: string ): void { customize()?.notifications.remove( code ); } /** * Run a callback once the Customizer is fully bootstrapped. * * Load order matters here and isn't obvious: core creates every * `WP_Customize_Setting`'s JS counterpart inside its own jQuery-ready handler * and fires `ready` at the end of it (see `api.trigger( 'ready' )` in * `wp-admin/js/customize-controls.js`). This bundle, enqueued in the footer, * executes at parse time — *before* that handler runs — so at module scope * `wp.customize( id )` is still undefined for every one of them, and reading a * value would throw. Anything that touches settings has to wait for this. * * @param callback Invoked once, when the Customizer is ready. */ export function onReady( callback: () => void ): void { const api = customize(); if ( ! api ) { return; } api.bind( 'ready', callback ); }