/** * URL-backed UI state. * * The panel already keeps the active settings section in the query string * (`?page=aureon§ion=colors`), so a reload — or a bookmark, or the browser * back button — lands where the user left off. Everything else was component * state, which meant a refresh dropped the Modules area and the Content * Templates / WooCommerce workspaces back to their first tab. * * This hook gives that behaviour to any single-value chooser: it reads the * initial value from a query parameter (falling back to a default when the * parameter is missing or names something that no longer exists), and rewrites * the URL with `replaceState` on every change — no navigation, no history entry * per click, so Back still leaves the panel rather than stepping through tabs. */ import { useState, useCallback } from '@wordpress/element'; /** * Read a query parameter, accepting it only when it's one of the values the * caller knows how to render. * * @param {string} param Query-parameter name. * @param {string} fallback Value to use when the parameter is absent or unknown. * @param {string[]} allowed Values the caller can render. * @return {string} The resolved initial value. */ const readParam = ( param: string, fallback: string, allowed: readonly string[] ): string => { const requested = new URLSearchParams( window.location.search ).get( param ); return requested && allowed.includes( requested ) ? requested : fallback; }; /** * State whose current value lives in the URL. * * @param {string} param Query-parameter name to store the value under. * @param {string} fallback Default value. * @param {string[]} allowed Values accepted from the URL. * @return {[string, (next: string) => void]} Current value and its setter. */ export default function useUrlState< T extends string >( param: string, fallback: T, allowed: readonly T[] ): [ T, ( next: T ) => void ] { const [ value, setValue ] = useState< T >( () => readParam( param, fallback, allowed ) as T ); const set = useCallback( ( next: T ) => { setValue( next ); const url = new URL( window.location.href ); // An empty value means "nothing chosen" — the state a sub-navigation // starts in (see `SubNav`). Dropping the parameter rather than // storing it empty keeps a reloaded URL landing on the list, the way // a fresh one does. if ( next ) { url.searchParams.set( param, next ); } else { url.searchParams.delete( param ); } window.history.replaceState( {}, '', url ); }, [ param ] ); return [ value, set ]; }