25 lines
1.3 KiB
TypeScript
25 lines
1.3 KiB
TypeScript
const levels = ['province_id', 'district_id', 'admin_post_id', 'locality_id'];
|
|
const searchRoutes = ['/carteira', '/oportunidades', '/zonas', '/educacao'];
|
|
|
|
/** URL-scoped search context, never a saved investment or another browser tab. */
|
|
export function searchTerritoryHref(href: string, pageUrl: string): string {
|
|
const base = 'https://portal.invalid';
|
|
const source = new URL(pageUrl, base);
|
|
const target = new URL(href, base);
|
|
const supported = (path: string) => searchRoutes.some((route) => path === route || path.startsWith(`${route}/`));
|
|
if (target.origin !== base || !supported(source.pathname) || !supported(target.pathname)) return href;
|
|
const inherited = source.searchParams.has('catalogue_query')
|
|
? new URLSearchParams(source.searchParams.get('catalogue_query')!)
|
|
: source.searchParams;
|
|
// An explicit ancestor, including an explicit empty value, overrides its descendants.
|
|
let changed = false;
|
|
for (const field of levels) {
|
|
if (target.searchParams.has(field)) {
|
|
changed ||= target.searchParams.get(field) !== inherited.get(field);
|
|
} else if (!changed && inherited.get(field)) {
|
|
target.searchParams.set(field, inherited.get(field)!);
|
|
}
|
|
}
|
|
return target.pathname + target.search + target.hash;
|
|
}
|