Back

0% Statements 0/98
0% Branches 0/40
0% Functions 0/15
0% Lines 0/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * External dependencies
 */
import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
import { useSearch, useNavigate } from '@wordpress/route';
/**
 * Internal dependencies
 */
import {
	DashboardSearchParamsProvider,
	type DashboardSearchParamsTuple,
	type SetDashboardSearchParams,
} from './dashboard-search-params-context';
import { isExternalAdminContext, DASHBOARD_URL_CHANGE_EVENT } from './utils';
/**
 * Types
 */
import type { PropsWithChildren } from 'react';
 
type Props = PropsWithChildren< {
	/**
	 * Route id to bind `useSearch` / `useNavigate` to.
	 *
	 * Required because ciab-admin doesn't provide a
	 * "nearest match" for `useSearch()` to infer.
	 */
	from: string;
} >;
 
/**
 * Parse search params from the URL for external admin contexts.
 * In these contexts, params may be embedded inside the ?p= value.
 *
 * @return URLSearchParams parsed from the current URL.
 */
function parseExternalAdminSearchParams(): URLSearchParams {
	const url = new URL( window.location.href );
	const result = new URLSearchParams();
 
	// First, check direct URL params
	let rawResponseIds = url.searchParams.getAll( 'responseIds' );
	let search = url.searchParams.get( 'search' );
 
	// If not found, check inside the p parameter (external admin context)
	if ( rawResponseIds.length === 0 ) {
		const pValue = url.searchParams.get( 'p' );
		if ( pValue && pValue.includes( '?' ) ) {
			try {
				const pUrl = new URL( pValue, window.location.origin );
				rawResponseIds = pUrl.searchParams.getAll( 'responseIds' );
				if ( ! search ) {
					search = pUrl.searchParams.get( 'search' );
				}
			} catch {
				// Ignore malformed p values that cannot be parsed as URLs.
			}
		}
	}
 
	// Parse responseIds, handling JSON-encoded arrays from TanStack Router
	for ( const raw of rawResponseIds ) {
		if ( raw.startsWith( '[' ) ) {
			try {
				const parsed = JSON.parse( raw );
				if ( Array.isArray( parsed ) ) {
					for ( const id of parsed ) {
						result.append( 'responseIds', String( id ) );
					}
					continue;
				}
			} catch {
				// Not valid JSON, treat as regular value
			}
		}
		result.append( 'responseIds', raw );
	}
 
	if ( search ) {
		result.set( 'search', search );
	}
 
	return result;
}
 
/**
 * Convert `@wordpress/route` `search` record shape into `URLSearchParams`.
 *
 * @param search - Search record to convert.
 * @return       - URL search params.
 */
function searchRecordToUrlSearchParams( search: Record< string, unknown > ): URLSearchParams {
	const params = new URLSearchParams();
 
	for ( const [ key, value ] of Object.entries( search || {} ) ) {
		if ( value === undefined || value === null ) {
			continue;
		}
 
		if ( Array.isArray( value ) ) {
			for ( const v of value ) {
				if ( v === undefined || v === null ) {
					continue;
				}
 
				params.append( key, String( v ) );
			}
 
			continue;
		}
 
		params.set( key, String( value ) );
	}
 
	return params;
}
 
/**
 * Convert `URLSearchParams` into the router `search` record shape.
 *
 * Note: some keys (e.g. `responseIds`) are treated as arrays even when only one value is present.
 *
 * @param params            - URL search params to convert.
 * @param options           - Options.
 * @param options.arrayKeys - Keys that should always be represented as arrays.
 * @return                  - Record suitable for `@wordpress/route` `search`.
 */
function urlSearchParamsToSearchRecord(
	params: URLSearchParams,
	options: {
		/**
		 * Keys that should always be represented as arrays.
		 * For example: `responseIds` is treated as `string[]` by routes that use selection.
		 */
		arrayKeys?: ReadonlySet< string >;
	} = {}
): Record< string, string | string[] > {
	const { arrayKeys = new Set< string >() } = options;
	const out: Record< string, string | string[] > = {};
 
	for ( const key of params.keys() ) {
		const values = params.getAll( key );
 
		if ( values.length < 1 ) {
			continue;
		}
 
		if ( arrayKeys.has( key ) ) {
			out[ key ] = values;
			continue;
		}
 
		// For non-array keys, always coerce to a scalar string.
		// If multiple values exist for a key, preserve the last one.
		out[ key ] = values[ values.length - 1 ];
	}
 
	return out;
}
 
/**
 * Provider for external admin contexts (no router hooks).
 * Uses direct URL parsing and history API for navigation.
 *
 * @param props          - Props.
 * @param props.children - Children.
 * @return               - JSX element.
 */
function ExternalAdminSearchParamsProvider( {
	children,
}: {
	children: React.ReactNode;
} ): JSX.Element {
	const [ searchParams, setSearchParamsState ] = useState( parseExternalAdminSearchParams );
 
	useEffect( () => {
		/**
		 * Updates params state when URL changes via browser navigation.
		 */
		function handleUrlChange() {
			setSearchParamsState( parseExternalAdminSearchParams() );
		}
 
		// Listen for both browser navigation and custom dashboard URL changes
		window.addEventListener( 'popstate', handleUrlChange );
		window.addEventListener( DASHBOARD_URL_CHANGE_EVENT, handleUrlChange );
		return () => {
			window.removeEventListener( 'popstate', handleUrlChange );
			window.removeEventListener( DASHBOARD_URL_CHANGE_EVENT, handleUrlChange );
		};
	}, [] );
 
	const setSearchParams: SetDashboardSearchParams = useCallback(
		next => {
			const resolved = typeof next === 'function' ? next( searchParams ) : next;
 
			// Update URL via history API
			const url = new URL( window.location.href );
			const pValue = url.searchParams.get( 'p' );
 
			if ( pValue ) {
				try {
					// Update params inside the p parameter
					const pUrl = new URL( pValue, window.location.origin );
					// Clear existing params we manage
					pUrl.searchParams.delete( 'responseIds' );
					pUrl.searchParams.delete( 'search' );
					// Set new params
					for ( const [ key, value ] of resolved.entries() ) {
						pUrl.searchParams.append( key, value );
					}
					url.searchParams.set( 'p', pUrl.pathname + pUrl.search );
				} catch {
					// Fallback: Update direct URL params if pValue is malformed
					url.searchParams.delete( 'responseIds' );
					url.searchParams.delete( 'search' );
					for ( const [ key, value ] of resolved.entries() ) {
						url.searchParams.append( key, value );
					}
				}
			} else {
				// Update direct URL params
				url.searchParams.delete( 'responseIds' );
				url.searchParams.delete( 'search' );
				for ( const [ key, value ] of resolved.entries() ) {
					url.searchParams.append( key, value );
				}
			}
 
			window.history.pushState( {}, '', url.toString() );
			setSearchParamsState( resolved );
			// Dispatch custom event so other provider instances can update
			window.dispatchEvent( new CustomEvent( DASHBOARD_URL_CHANGE_EVENT ) );
		},
		[ searchParams ]
	);
 
	const value = useMemo(
		() => [ searchParams, setSearchParams ] as DashboardSearchParamsTuple,
		[ searchParams, setSearchParams ]
	);
 
	return (
		<DashboardSearchParamsProvider value={ value }>{ children }</DashboardSearchParamsProvider>
	);
}
 
/**
 * Provider for standard wp-route contexts (uses router hooks).
 *
 * @param props          - Props.
 * @param props.from     - Route id to bind `useSearch` / `useNavigate` to.
 * @param props.children - Children.
 * @return               - JSX element.
 */
function WpRouteSearchParamsProvider( { from, children }: Props ): JSX.Element {
	// `useSearch()` re-renders when the router search changes. We'll adapt it to URLSearchParams
	// so shared dashboard code can keep using the URLSearchParams API.
	const search = useSearch( {
		// In this build, the router type isn't registered, so `@wordpress/route` models `from` as `never`.
		// We still want to pass the runtime route id through.
		from: from as unknown as never,
		strict: false,
	} );
	const navigate = useNavigate();
	const searchParams = useMemo( () => searchRecordToUrlSearchParams( search ), [ search ] );
 
	const setSearchParams: SetDashboardSearchParams = useCallback(
		next => {
			const resolved = typeof next === 'function' ? next( searchParams ) : next;
			const nextSearch = urlSearchParamsToSearchRecord( resolved, {
				arrayKeys: new Set( [ 'responseIds' ] ),
			} );
 
			type NavigateArg = Parameters< typeof navigate >[ 0 ];
			type SearchOption = NavigateArg extends { search?: infer S } ? S : never;
			type SearchReducer = Exclude< SearchOption, true | undefined >;
 
			// In `@wordpress/route`, `search` is modeled as a reducer function, but without a registered
			// router type it ends up as a very "loose" signature. We still pass a fully-formed object.
			const replaceSearch = ( () => nextSearch ) as unknown as SearchReducer;
 
			navigate( { search: replaceSearch } );
		},
		[ navigate, searchParams ]
	);
 
	const value = useMemo(
		() => [ searchParams, setSearchParams ] as DashboardSearchParamsTuple,
		[ searchParams, setSearchParams ]
	);
 
	return (
		<DashboardSearchParamsProvider value={ value }>{ children }</DashboardSearchParamsProvider>
	);
}
 
/**
 * Provider for the dashboard search params.
 * Automatically detects context and uses appropriate implementation.
 *
 * @param props          - Props.
 * @param props.from     - Route id to bind `useSearch` / `useNavigate` to.
 * @param props.children - Children.
 * @return               - JSX element.
 */
export default function WpRouteDashboardSearchParamsProvider( {
	from,
	children,
}: Props ): JSX.Element {
	// Check context once at mount - this determines which provider to use
	const [ isExternal ] = useState( isExternalAdminContext );
 
	if ( isExternal ) {
		return <ExternalAdminSearchParamsProvider>{ children }</ExternalAdminSearchParamsProvider>;
	}
 
	return <WpRouteSearchParamsProvider from={ from }>{ children }</WpRouteSearchParamsProvider>;
}