import { useCallback, useEffect } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; interface UseHeaderSearchOptions { initialValue?: string; enableIRIHandling?: boolean; navigateOnEnter?: boolean; navigatePath?: string; onSearchChange?: (value: string) => void; onSearchSubmit?: (value: string) => void; } export const useHeaderSearch = ({ initialValue = '', enableIRIHandling = false, navigateOnEnter = false, navigatePath = '/map', onSearchChange, onSearchSubmit }: UseHeaderSearchOptions = {}) => { const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); // Initialize search term from URL parameters useEffect(() => { const urlSearchTerm = searchParams.get('search'); if (urlSearchTerm && urlSearchTerm !== initialValue && onSearchChange) { onSearchChange(urlSearchTerm); } }, [searchParams, initialValue, onSearchChange]); // IRI handling for Unicode characters in URL useEffect(() => { if (!enableIRIHandling) return; const urlSearchTerm = searchParams.get('search'); if (!urlSearchTerm) return; const currentUrl = window.location.href; const hasEncodedUnicode = /%D[0-9A-F]/i.test(currentUrl); if (hasEncodedUnicode && urlSearchTerm) { const updateUrlForIRI = () => { try { const pathname = window.location.pathname; const origin = window.location.origin; let iriUrl = `${pathname}?search=${urlSearchTerm}`; window.history.replaceState(null, '', iriUrl); const newUrl = window.location.href; if (newUrl.includes('%D')) { try { const url = new URL(origin + pathname); url.search = `?search=${urlSearchTerm}`; window.history.replaceState(null, '', url.pathname + url.search); } catch (e) { const encoded = encodeURI(urlSearchTerm); if (encoded === urlSearchTerm) { window.history.replaceState(null, '', `${pathname}?search=${urlSearchTerm}`); } } } } catch (err) { console.debug('IRI display not supported:', err); } }; updateUrlForIRI(); setTimeout(updateUrlForIRI, 10); setTimeout(updateUrlForIRI, 50); setTimeout(updateUrlForIRI, 100); setTimeout(updateUrlForIRI, 200); setTimeout(updateUrlForIRI, 500); const intervalId = setInterval(() => { const currentHref = window.location.href; if (/%D[0-9A-F]/i.test(currentHref) && urlSearchTerm) { updateUrlForIRI(); } else { clearInterval(intervalId); } }, 100); setTimeout(() => clearInterval(intervalId), 2000); } }, [searchParams, enableIRIHandling]); const handleSearchSubmit = useCallback((value: string) => { if (onSearchSubmit) { onSearchSubmit(value); } else if (navigateOnEnter) { navigate(`${navigatePath}?search=${encodeURIComponent(value)}`); } else { setSearchParams({ search: value }, { replace: true }); } }, [onSearchSubmit, navigateOnEnter, navigate, navigatePath, setSearchParams]); return { handleSearchSubmit }; };