(() => { const root = document.querySelector('[data-home-search-suggest]'); if (!root) return; const form = root.querySelector('form'); const input = form.querySelector('input[name="q"]'); const list = root.querySelector('[role="listbox"]'); const labels = { page: root.dataset.pageLabel, file: root.dataset.fileLabel, quartier: root.dataset.quartierLabel, street: root.dataset.streetLabel, spot: root.dataset.spotLabel, }; const cache = new Map(); let controller; let timer; let sequence = 0; let active = -1; let candidates = []; const rows = () => [...list.querySelectorAll('[role="option"]')]; const close = () => { list.hidden = true; active = -1; input.setAttribute('aria-expanded', 'false'); input.removeAttribute('aria-activedescendant'); }; const activate = index => { const options = rows(); if (!options.length) return; active = (index + options.length) % options.length; options.forEach((option, position) => option.setAttribute('aria-selected', String(position === active))); input.setAttribute('aria-activedescendant', options[active].id); options[active].scrollIntoView({block:'nearest'}); }; const resultHref = query => { const url = new URL(form.action, location.href); url.searchParams.set('q', query); url.searchParams.set('scope', '/'); return url.pathname + url.search; }; const makeRow = (item, index) => { const link = document.createElement('a'); link.id = `home-search-option-${index}`; link.className = 'home-search-suggestion'; link.href = item.href; link.role = 'option'; link.setAttribute('aria-selected', 'false'); link.dataset.suggestionIndex = String(index); if (item.exact) link.dataset.exact = 'true'; const kind = document.createElement('span'); kind.className = 'home-search-suggestion-kind'; kind.textContent = labels[item.kind] || item.kind; const main = document.createElement('span'); main.className = 'home-search-suggestion-main'; const title = document.createElement('strong'); title.textContent = item.label; const detail = document.createElement('small'); detail.textContent = [item.context, item.path].filter(Boolean).join(' · '); main.append(title, detail); const open = document.createElement('span'); open.className = 'home-search-suggestion-open'; open.textContent = item.exact ? root.dataset.directLabel : '↵'; link.append(kind, main, open); link.addEventListener('pointerenter', () => activate(index)); link.addEventListener('click', close); return link; }; const render = (query, data) => { if (input.value.trim() !== query) return; candidates = Array.isArray(data.items) ? data.items : []; const fragment = document.createDocumentFragment(); candidates.forEach((item, index) => fragment.append(makeRow(item, index))); const search = makeRow({kind:'search', label:`${root.dataset.allLabel}: “${query}”`, path:'', href:resultHref(query)}, candidates.length); search.classList.add('home-search-suggestion-search'); search.querySelector('.home-search-suggestion-kind').textContent = '⌕'; fragment.append(search); list.replaceChildren(fragment); active = -1; list.hidden = false; input.setAttribute('aria-expanded', 'true'); }; const request = async query => { if (cache.has(query)) { render(query, cache.get(query)); return; } controller?.abort(); controller = new AbortController(); const current = ++sequence; try { const url = new URL(root.dataset.endpoint, location.href); url.searchParams.set('q', query); const response = await fetch(url, {headers:{Accept:'application/json'}, credentials:'same-origin', cache:'no-store', signal:controller.signal}); if (!response.ok) throw new Error(`HTTP ${response.status}`); const data = await response.json(); if (current !== sequence) return; cache.set(query, data); if (cache.size > 24) cache.delete(cache.keys().next().value); render(query, data); } catch (error) { if (error.name !== 'AbortError' && current === sequence) close(); } }; input.addEventListener('input', () => { clearTimeout(timer); controller?.abort(); candidates = []; close(); const query = input.value.trim(); if (/^add\s+(task|cal)\b/i.test(query)) return; if ([...query].length < 2) return; timer = setTimeout(() => request(query), 140); }); input.addEventListener('keydown', event => { if (event.key === 'ArrowDown' && !list.hidden) { event.preventDefault(); activate(active + 1); } else if (event.key === 'ArrowUp' && !list.hidden) { event.preventDefault(); activate(active < 0 ? rows().length - 1 : active - 1); } else if (event.key === 'Escape') { event.preventDefault(); close(); } }); form.addEventListener('submit', event => { if (/^add\s+(task|cal)\b/i.test(input.value.trim())) return; if (event.ctrlKey || event.metaKey) return; const options = rows(); let selected = active >= 0 ? options[active] : null; if (!selected) { const exact = candidates.findIndex(item => item.exact); if (exact >= 0) selected = options[exact]; } if (!selected || selected.classList.contains('home-search-suggestion-search')) return; event.preventDefault(); location.assign(selected.href); }); document.addEventListener('pointerdown', event => { if (!root.contains(event.target)) close(); }); root.addEventListener('focusout', () => setTimeout(() => { if (!root.contains(document.activeElement)) close(); }, 100)); })();