/** * Aureon admin app — the standalone Appearance → Aureon theme options page. * * `customize.php` no longer mounts this app, and neither does this page mount * its own copy of the design sections anymore: every one of them is a real * native `WP_Customize_Section` now, mounted independently through * `customizer/sections.tsx` (see `Customizer::SECTIONS`) — that file already * reimplements this page's old plugin-surface/extras wiring for its own host, * so nothing here needs to duplicate it. What's left is only what has nowhere * else to live because it isn't a live-preview customization: Modules * (feature toggles), Import/Export (whole-tree data), and whatever a * companion plugin contributes as its own top-level area — License, Account * Hub, and Social Login, from Aureon Nexus Pro — see `PANEL_AREAS`/`AREAS` * below and `NON_CUSTOMIZER_SURFACE_KEYS` in `Customizer.php`. * * Saves via a single explicit Save button over REST (see * settings-transport.ts), writing the same `aureon_settings` option the * Customizer's native Publish writes, so a value set from either surface is * indistinguishable to the rest of the theme. * * Plugin-contributed areas (licensing, …) load/save over their own REST * routes — a separate, plugin-owned mechanism this doesn't touch. */ import { useState, useEffect, useCallback } from '@wordpress/element'; import apiFetch from '@wordpress/api-fetch'; import { getPath, writePath } from './tree-utils'; import { loadSchema, loadSettings, saveSettings } from './settings-transport'; import { __ } from '@wordpress/i18n'; import { Spinner, Notice as WPNotice, Snackbar } from '@wordpress/components'; import ActionBar from './action-bar'; import Sidebar from './sidebar'; import ToolsSection from './sections/tools'; import ModulesArea from './areas/modules'; import CustomCodeSection from './sections/custom-code'; import useUrlState from './use-url-state'; import PanelSection from './sections/panel-section'; import type { Area, AreaKey, FeatureModule, Notice, PanelArea as PanelAreaType, PanelSection as PanelSectionType, PanelValues, SettingsSchema, WorkingSettings, } from './types'; // Surface keys whose plugin-contributed values differ from what was loaded, so // Save only POSTs to the routes that actually changed. Surfaces that declared // `saves: false` are skipped — their writes happen through action buttons, and // counting their fields would leave the panel permanently dirty. const panelDirtyKeys = ( values: PanelValues, savedValues: PanelValues ): string[] => PLUGIN_SURFACES.filter( ( surface ) => surface.saves && JSON.stringify( values[ surface.key ] ?? {} ) !== JSON.stringify( savedValues[ surface.key ] ?? {} ) ).map( ( surface ) => surface.key ); // Every registered feature module, for the Modules area's cards. const MODULES: FeatureModule[] = window.aureonAdmin?.modules ?? []; /** * A Customizer URL that opens straight into one section, `return`-ing back * to this admin page — the target for the Modules page's "Configure" links * now that every section's actual fields live in the Customizer (see * `Aureon\Customizer\Customizer::SECTIONS`) rather than this page's own * (now-removed) Settings tab. * * @param sectionKey Section key, e.g. 'wishlist' — becomes `aureon_wishlist`. */ const customizeSectionUrl = ( sectionKey: string ): string => { const base = window.aureonAdmin?.customizeUrl ?? '/wp-admin/customize.php'; const url = new URL( base, window.location.href ); url.searchParams.set( 'autofocus[section]', `aureon_${ sectionKey }` ); url.searchParams.set( 'return', window.location.href ); return url.toString(); }; // Areas contributed by plugins — currently just License, from Aureon Nexus // Pro. Each owns its storage behind `restPath`, loaded/saved alongside but // separately from the theme's settings tree, and rendered full-width by // PanelSection exactly like Modules and Import/Export are (see the JSX below). const PANEL_AREAS: PanelAreaType[] = window.aureonAdmin?.areas ?? []; // Every plugin-contributed *section* descriptor (window.aureonAdmin.sections), // the same list customizer/sections.tsx reads — but here only its `target`ed // surfaces matter: fields a plugin aimed at an existing section (e.g. Aureon // Nexus's raw code injection, targeted at 'custom_code') rather than asking // for a nav entry of its own. See extrasFor() and CustomCodeSection below. const ALL_PANEL_SECTIONS: PanelSectionType[] = window.aureonAdmin?.sections ?? []; const SECTION_EXTRAS = ALL_PANEL_SECTIONS.filter( ( s ) => !! s.target ); // Every plugin surface this page loads/saves values for — areas with their own // nav entry, plus extras targeted at a built-in section. Kept separate from // AREAS (nav) below, since an extra doesn't get a row of its own. const PLUGIN_SURFACES: PanelAreaType[] = [ ...PANEL_AREAS, ...SECTION_EXTRAS ]; // Top-level areas shown in the left sidebar nav: Modules (feature // toggles), Custom Code (CSS plus any plugin code slots, moved out of the Customizer — raw CSS gets no benefit // from its `refresh` transport, a full iframe reload per keystroke rather than // a real live patch), Import/Export (whole-tree data), and whatever a // companion plugin contributes — everything else is a native Customizer // section now (see the class docblock above), so this list stays exactly as // short as what has no other home. const BASE_AREAS: Area[] = [ { key: 'modules', label: __( 'Modules', 'aureon' ), enabled: true, icon: 'LayoutGrid', // Leads the nav: which modules are on decides which of the other // screens exist at all. group: 'setup', }, { key: 'custom_code', label: __( 'Custom Code', 'aureon' ), enabled: true, icon: 'Code', group: 'advanced', }, { key: 'tools', label: __( 'Backup & Reset', 'aureon' ), enabled: true, icon: 'ArrowDownUp', group: 'tools', }, ]; // Also the values `?area=` is validated against, so a plugin area survives a // reload instead of falling back to Modules — gated areas included, so a // link to one that's since been switched off still round-trips through the // URL rather than silently landing on Modules. const AREA_KEYS: readonly AreaKey[] = [ ...BASE_AREAS.map( ( area ) => area.key ), ...PANEL_AREAS.map( ( area ) => area.key ), ]; export default function App() { const [ loading, setLoading ] = useState( true ); const [ saving, setSaving ] = useState( false ); const [ error, setError ] = useState< string | null >( null ); const [ notice, setNotice ] = useState< Notice | null >( null ); const [ schema, setSchema ] = useState< SettingsSchema >( {} ); const [ saved, setSaved ] = useState< WorkingSettings | null >( null ); const [ working, setWorking ] = useState< WorkingSettings | null >( null ); // Plugin-contributed sections keep their values in their own slice — they // live in plugin-owned storage, not the theme's settings option, so they must // never be folded into `working` (which is POSTed wholesale to /settings). const [ panelSaved, setPanelSaved ] = useState< PanelValues >( {} ); const [ panelValues, setPanelValues ] = useState< PanelValues >( {} ); // The plugin action currently running, as `:`, so the // button that started it can show progress and the rest stay inert. const [ pendingAction, setPendingAction ] = useState< string | null >( null ); // The area rides the URL, so a reload keeps whichever area (Modules, // Import/Export, a plugin's) the user had open instead of resetting. const [ activeArea, setActiveArea ] = useUrlState< AreaKey >( 'area', 'modules', AREA_KEYS ); useEffect( () => { // Where this comes from is the transport's business: a REST round trip // on the page host, the config blob plus wp.customize() (synchronously) // in the Customizer. See settings-transport.ts. loadSettings() .then( ( res ) => { setSchema( res.schema ); setSaved( res.settings ); setWorking( res.settings ); } ) .catch( ( e: Error ) => setError( e.message || __( 'Failed to load settings.', 'aureon' ) ) ) .finally( () => setLoading( false ) ); }, [] ); // Each plugin-contributed surface's values, from its own route — a // top-level area and a section extra alike. A surface whose endpoint fails // is skipped rather than blocking the panel — the theme's own settings // don't depend on it. useEffect( () => { PLUGIN_SURFACES.forEach( ( surface ) => { apiFetch< { settings?: Record< string, unknown > } >( { path: surface.restPath, } ) .then( ( res ) => { const values = res?.settings ?? res ?? {}; setPanelSaved( ( prev ) => ( { ...prev, [ surface.key ]: values, } ) ); setPanelValues( ( prev ) => ( { ...prev, [ surface.key ]: values, } ) ); } ) .catch( () => { // Leave the slice empty; the surface renders its defaults-free // state and a save still writes whatever the user sets. } ); } ); }, [] ); // Toast notices auto-dismiss after 4s; manual close still works via // the Snackbar's onRemove. useEffect( () => { if ( ! notice ) { return; } const timeout = setTimeout( () => setNotice( null ), 4000 ); return () => clearTimeout( timeout ); }, [ notice ] ); const dirtyPanelKeys = panelDirtyKeys( panelValues, panelSaved ); const dirty = Boolean( working && saved && JSON.stringify( working ) !== JSON.stringify( saved ) ) || dirtyPanelKeys.length > 0; const setPath = useCallback( ( path: string, value: unknown ) => { setWorking( ( prev ) => prev ? writePath( prev, path, value ) : prev ); }, [] ); // Writes one field of one plugin-contributed section. Flat keys only — the // descriptors don't nest, so there's no dotted-path walk to do here. const setPanelValue = useCallback( ( sectionKey: string, field: string, value: unknown ) => { setPanelValues( ( prev ) => ( { ...prev, [ sectionKey ]: { ...( prev[ sectionKey ] ?? {} ), [ field ]: value, }, } ) ); }, [] ); // Runs an `action` field on a plugin area: POST { action, values } to the // area's own route, then adopt the state it returns. Deliberately outside the // Save cycle — an action does work (activating a license, say) rather than // persisting the form, and the route decides what the values become afterwards. const runPanelAction = useCallback( ( surfaceKey: string, action: string ) => { const surface = PLUGIN_SURFACES.find( ( s ) => s.key === surfaceKey ); if ( ! surface ) { return; } setPendingAction( `${ surfaceKey }:${ action }` ); setNotice( null ); apiFetch< { settings?: Record< string, unknown >; message?: Notice; refresh?: boolean; } >( { path: surface.restPath, method: 'POST', data: { action, values: panelValues[ surfaceKey ] ?? {} }, } ) .then( ( res ) => { const values = res?.settings ?? panelValues[ surfaceKey ] ?? {}; setPanelSaved( ( prev ) => ( { ...prev, [ surfaceKey ]: values, } ) ); setPanelValues( ( prev ) => ( { ...prev, [ surfaceKey ]: values, } ) ); // The route reports its own outcome, since only it knows whether // "activated" means success here. if ( res?.message?.text && ( 'success' === res.message.status || 'error' === res.message.status ) ) { setNotice( { status: res.message.status, text: res.message.text, } ); } // `refresh` means the action changed state the theme reads // from outside its settings tree, so the schema this page // loaded no longer describes the site — see the flag's // contract in Admin_Panel::panel_sections(). Re-read it; // a failure just leaves the stale copy in place, which is // where it already was. if ( res?.refresh ) { loadSchema() .then( setSchema ) .catch( () => {} ); } } ) .catch( ( e: Error ) => setNotice( { status: 'error', text: e.message || __( 'That didn’t work.', 'aureon' ), } ) ) .finally( () => setPendingAction( null ) ); }, [ panelValues ] ); const save = useCallback( () => { if ( ! working ) { return; } setSaving( true ); setNotice( null ); // Each dirty plugin surface saves to its own route, in parallel with the // theme's settings. Failures surface through the same notice, and a surface // that rejects keeps its edits so the user can retry. const panelSaves = panelDirtyKeys( panelValues, panelSaved ).map( ( key ) => { const surface = PLUGIN_SURFACES.find( ( s ) => s.key === key ); if ( ! surface ) { return Promise.resolve(); } return apiFetch< { settings?: Record< string, unknown > } >( { path: surface.restPath, method: 'POST', data: panelValues[ key ] ?? {}, } ).then( ( res ) => { // The route returns its sanitized state, which becomes both the // new baseline and the displayed value. const values = res?.settings ?? panelValues[ key ] ?? {}; setPanelSaved( ( prev ) => ( { ...prev, [ key ]: values, } ) ); setPanelValues( ( prev ) => ( { ...prev, [ key ]: values, } ) ); } ); } ); // The theme's own tree goes through whichever transport this host uses — // a POST, or wp.customize() writes plus a native Publish. Either way it // resolves with the authoritative post-sanitize state, which becomes both // the new baseline and the displayed value. const settingsSave = saveSettings( working, saved ).then( ( tree ) => { setSaved( tree ); setWorking( tree ); } ); Promise.all( [ settingsSave, ...panelSaves ] ) .then( () => { setNotice( { status: 'success', text: __( 'Settings saved.', 'aureon' ), } ); } ) .catch( ( e: Error ) => setNotice( { status: 'error', text: e.message || __( 'Save failed.', 'aureon' ), } ) ) .finally( () => setSaving( false ) ); }, [ working, saved, panelValues, panelSaved ] ); if ( loading || ! working ) { return (
); } if ( error ) { return ( { error } ); } // Plugin areas currently visible — the same `gatePath` gating the // Customizer applies to its own nav (see `SECTION_GATE`/`applyGates` in // customizer/sections.tsx); empty `gatePath` means always visible. A // gated-off area still round-trips through `?area=` (see `AREA_KEYS` // above) — it just renders nothing here and drops off the sidebar below // until its module is back on. const visiblePanelAreas = PANEL_AREAS.filter( ( area ) => ! area.gatePath || !! getPath( working, area.gatePath ) ); const AREAS: Area[] = [ ...BASE_AREAS, // A plugin names its own group in its descriptor, so a licensing screen // can sit under Tools while a feature screen sits under Features, // rather than every plugin surface landing in one bucket together. ...visiblePanelAreas.map( ( area ) => ( { key: area.key, label: area.label, enabled: true, badge: area.badge, icon: area.icon, group: area.areaGroup, } ) ), ]; // The plugin area taking over the whole body, if the active one is one. const activePanelArea = visiblePanelAreas.find( ( area ) => area.key === activeArea ); // The action running on a given surface, as PanelSection expects it (the action // name alone, without the surface prefix the shared state carries). const surfacePendingAction = ( key: string ): string | undefined => pendingAction && pendingAction.startsWith( `${ key }:` ) ? pendingAction.slice( key.length + 1 ) : undefined; // Field groups a plugin aimed at a built-in section, ready to render inline // — same contract as extrasFor() in customizer/sections.tsx, just backed by // this host's own panelValues/setPanelValue instead of the Customizer store. const extrasFor = ( key: string ) => SECTION_EXTRAS.filter( ( surface ) => surface.target === key ).map( ( surface ) => ( { key: surface.key, fields: surface.fields, values: panelValues[ surface.key ] ?? {}, setValue: ( field: string, value: unknown ) => setPanelValue( surface.key, field, value ), runAction: ( action: string ) => runPanelAction( surface.key, action ), pendingAction: surfacePendingAction( surface.key ), } ) ); return (
area.key === activeArea ) ?.label ?? '' } dirty={ dirty } saving={ saving } onSave={ save } /> { 'modules' === activeArea && (
{ if ( AREA_KEYS.includes( sectionKey ) ) { setActiveArea( sectionKey ); return; } window.open( customizeSectionUrl( sectionKey ), '_blank', 'noopener,noreferrer' ); } } />
) } { 'custom_code' === activeArea && (
) } { activePanelArea && (
setPanelValue( activePanelArea.key, field, value ) } runAction={ ( action ) => runPanelAction( activePanelArea.key, action ) } pendingAction={ surfacePendingAction( activePanelArea.key ) } />
) } { 'tools' === activeArea && (
) }
{ notice && ( setNotice( null ) } > { notice.text } ) }
); }