Repository Public
1import { useEffect, useId, useRef, useState, useSyncExternalStore, type KeyboardEvent } from 'react';2import { locale, useLang, type Lang } from '@spweb/shared-ui';3import { useT } from '@spweb/shared-ui/i18n/search';45/**6 * Region preference. An explicit choice lives in this browser only (localStorage, same namespace as7 * the theme and language keys) and is sent as `region=` with each search. It is never written to the8 * address bar: a shared link must not carry the sender's region. '' = automatic (no parameter: the9 * server reads the region the browser declares in Accept-Language).10 */11const KEY = 'spweb.region';12export const REGIONS = ['', 'ca', 'ca-qc', 'fr', 'ch', 'be', 'us', 'gb', 'none'] as const;13export type RegionChoice = (typeof REGIONS)[number];1415const listeners = new Set<() => void>();16function read(): RegionChoice {17 try {18 const v = localStorage.getItem(KEY) ?? '';19 return (REGIONS as readonly string[]).includes(v) ? (v as RegionChoice) : '';20 } catch {21 return '';22 }23}24let current: RegionChoice = read();2526export function setRegion(r: RegionChoice): void {27 current = r;28 try {29 if (r === '') localStorage.removeItem(KEY);30 else localStorage.setItem(KEY, r);31 } catch {32 /* preference not persisted */33 }34 listeners.forEach((f) => f());35}3637function subscribe(f: () => void): () => void {38 listeners.add(f);39 return () => listeners.delete(f);40}4142export function useRegion(): RegionChoice {43 return useSyncExternalStore(subscribe, () => current);44}4546/** What the server says it applied (`region` of a search response). */47export interface AppliedRegion {48 value: string | null;49 source: string;50}5152const SUB: Record<string, Record<Lang, string>> = { 'ca-qc': { fr: 'Québec', en: 'Quebec' } };5354/** "Canada", "Canada (Québec)"; an unknown code is shown in capitals rather than guessed. */55export function regionName(code: string, l: Lang): string {56 const c = code.trim().toLowerCase();57 const country = c.split('-')[0] ?? c;58 let name = country.toUpperCase();59 try {60 const n = new Intl.DisplayNames(locale(l), { type: 'region', fallback: 'none' }).of(country.toUpperCase());61 if (n) name = n;62 } catch {63 /* unknown or malformed code */64 }65 const sub = SUB[c]?.[l];66 return sub ? `${name} (${sub})` : name;67}6869function Pin() {70 return (71 <svg className="icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="square" aria-hidden="true" focusable="false">72 <path d="M12 21s-6.5-5.800-6.5-11a6.5 6.5 0 0113 0c0 5.200-6.5 11-6.5 11zM12 7.5a2.5 2.5 0 100 5 2.5 2.5 0 000-5z" />73 </svg>74 );75}7677/**78 * Compact region control: the button states the region in force, the menu lets the reader choose.79 * With a search response at hand (`applied`), the label is what the server reports it applied,80 * never an assumption; without one (home page) only the reader's own setting is stated.81 */82export function RegionControl({ applied, align = 'end', onBeforeChange }: {83 applied?: AppliedRegion | null;84 align?: 'start' | 'end' | 'center';85 /** Called just before the choice changes (the results page returns to its first page: a cursor belongs to one region). */86 onBeforeChange?: () => void;87}) {88 const { t } = useT();89 const lang = useLang();90 const choice = useRegion();91 const [open, setOpen] = useState(false);92 const root = useRef<HTMLDivElement>(null);93 const menu = useRef<HTMLUListElement>(null);94 const id = useId();9596 useEffect(() => {97 if (!open) return;98 const away = (e: PointerEvent) => {99 if (!root.current?.contains(e.target as Node)) setOpen(false);100 };101 document.addEventListener('pointerdown', away);102 // The current choice takes the focus when the menu opens.103 menu.current?.querySelector<HTMLElement>('[aria-checked="true"]')?.focus();104 return () => document.removeEventListener('pointerdown', away);105 }, [open]);106107 const optionLabel = (r: RegionChoice): string => (r === '' ? t('region.auto') : r === 'none' ? t('region.off') : regionName(r, lang));108109 // Button label: the server's report when there is one, otherwise the reader's own setting.110 let label: string;111 let detail = '';112 if (applied && typeof applied.source === 'string') {113 if (applied.source === 'off') label = t('region.off');114 else if (applied.source === 'choice' && applied.value) label = regionName(applied.value, lang);115 else if (applied.source === 'browser' && applied.value) {116 label = t('region.auto.v', { r: regionName(applied.value, lang) });117 detail = t('region.auto.why');118 } else if (applied.value) label = regionName(applied.value, lang);119 else {120 label = t('region.auto.none');121 detail = t('region.auto.none.why');122 }123 } else {124 label = optionLabel(choice);125 }126127 const onKey = (e: KeyboardEvent<HTMLUListElement>) => {128 const items = Array.from(menu.current?.querySelectorAll<HTMLElement>('[role="menuitemradio"]') ?? []);129 const at = items.indexOf(document.activeElement as HTMLElement);130 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {131 e.preventDefault();132 items[(at + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length]?.focus();133 } else if (e.key === 'Home' || e.key === 'End') {134 e.preventDefault();135 items[e.key === 'Home' ? 0 : items.length - 1]?.focus();136 } else if (e.key === 'Escape') {137 e.preventDefault();138 setOpen(false);139 root.current?.querySelector<HTMLElement>('button.region-btn')?.focus();140 } else if (e.key === 'Tab') {141 setOpen(false);142 }143 };144145 return (146 <div className={`region region-${align}${open ? ' region-open' : ''}`} ref={root}>147 <button type="button" className="region-btn" aria-haspopup="menu" aria-expanded={open} aria-controls={`${id}-m`} title={detail || undefined} onClick={() => setOpen((v) => !v)}>148 <Pin />149 <span className="region-k">{t('region.label')}</span>150 <span className="region-v">{label}</span>151 <svg className="region-caret" width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true" focusable="false"><path d="M1.5 3.5L5 7l3.5-3.5" /></svg>152 </button>153 <div className="region-pop" inert={!open}>154 <ul className="region-menu" id={`${id}-m`} role="menu" aria-label={t('region.menu')} ref={menu} onKeyDown={onKey}>155 {REGIONS.map((r) => (156 <li key={r || 'auto'} role="none" className={r === 'none' ? 'region-sep' : undefined}>157 <button158 type="button"159 role="menuitemradio"160 aria-checked={choice === r}161 onClick={() => {162 if (r !== choice) onBeforeChange?.();163 setRegion(r);164 setOpen(false);165 root.current?.querySelector<HTMLElement>('button.region-btn')?.focus();166 }}167 >168 <span className="region-dot" aria-hidden="true" />169 <span>{optionLabel(r)}</span>170 {r === '' && <span className="region-hint">{t('region.auto.hint')}</span>}171 </button>172 </li>173 ))}174 </ul>175 {detail !== '' && <p className="region-note">{detail}</p>}176 <p className="region-note">{t('region.note')}</p>177 </div>178 </div>179 );180}181