// A collection page's finder: the scoped search, the tag row, the breakdown
// panel and the A–Z index, all narrowing the same grid of tools. Progressive —
// the page is a complete static list without it. State lives in the URL with
// the catalog's own parameter names, so a narrowed deck is shareable and
// "Full catalog" can carry the same filters across.
import { EMPTY_FILTERS, FACET_KEYS, filtersFromSearch, filtersToSearch, type CatalogFilters, type FacetKey } from '../lib/techniques';
import { DECK_ALPHABET, sigMatches } from '../lib/deck';
import { url } from '../lib/url';
function boot() {
const found = document.querySelector<HTMLElement>('[data-deck]');
if (!found || found.dataset.booted) return;
const root: HTMLElement = found;
root.dataset.booted = '1';
const $ = <T extends HTMLElement = HTMLElement>(s: string) => root.querySelector<T>(s)!;
const search = $<HTMLInputElement>('[data-deck-search]');
const shown = $('[data-deck-shown]'), empty = $('[data-deck-empty]');
const tiles = [...root.querySelectorAll<HTMLAnchorElement>('.src__tool')].map((el) => ({
el, name: el.dataset.name || '', letter: el.dataset.letter || '#', sigs: (el.dataset.sig || '').split(' '),
}));
const marks = [...root.querySelectorAll<HTMLButtonElement>('button[data-facet]')];
const letters = [...root.querySelectorAll<HTMLAnchorElement>('[data-az]')];
const total = tiles.length;
// `key\tvalue` → the character that stands for it in a tile's signatures.
const vocab: string[] = JSON.parse(root.dataset.vocab || '[]');
const code = new Map(vocab.map((v, i) => [v, DECK_ALPHABET[i]]));
const known = (key: FacetKey, values: string[] = []) => values.filter((v) => code.has(`${key}\t${v}`));
let filters: CatalogFilters = { ...EMPTY_FILTERS };
function readURL() {
const f = filtersFromSearch(location.search);
// A parameter this deck has no tag for (a hand-edited or carried-over URL)
// is dropped rather than silently hiding everything.
filters = { ...EMPTY_FILTERS, query: f.query };
for (const key of FACET_KEYS) { const v = known(key, f[key]); if (v.length) filters[key] = v; }
search.value = filters.query;
}
const active = () => FACET_KEYS.some((k) => filters[k]?.length) || !!filters.query.trim();
function render() {
const words = filters.query.toLowerCase().trim().split(/\s+/).filter(Boolean);
const groups = FACET_KEYS.map((k) => (filters[k] || []).map((v) => code.get(`${k}\t${v}`)).join('')).filter(Boolean);
const live = new Set<string>();
let n = 0;
for (const t of tiles) {
const hit = words.every((w) => t.name.includes(w)) && sigMatches(t.sigs, groups);
t.el.hidden = !hit;
if (hit) { n++; live.add(t.letter); }
}
shown.textContent = n === total ? `${total} shown` : `${n} of ${total} shown`;
empty.hidden = n > 0;
root.querySelectorAll<HTMLElement>('[data-deck-clear]').forEach((b) => { if (!b.closest('[data-deck-empty]')) b.hidden = !active(); });
for (const b of marks) b.setAttribute('aria-pressed', String(filters[b.dataset.facet as FacetKey]?.includes(b.dataset.value!) || false));
root.querySelectorAll<HTMLElement>('.bd-block').forEach((block) => block.toggleAttribute('data-narrowed', !!block.querySelector('[aria-pressed="true"]')));
for (const a of letters) { if (live.has(a.dataset.az!)) a.removeAttribute('aria-disabled'); else a.setAttribute('aria-disabled', 'true'); }
const qs = filtersToSearch(filters);
const next = location.pathname + (qs ? `?${qs}` : '') + location.hash;
if (next !== location.pathname + location.search + location.hash) history.replaceState(history.state, '', next);
// The same question, asked of every collection at once.
const across = url('catalog') + (qs ? `?${qs}` : '');
$<HTMLAnchorElement>('[data-deck-catalog]').href = across;
$<HTMLAnchorElement>('[data-deck-catalog]').textContent = qs ? '← Same filters in the full catalog' : '← Full catalog';
$<HTMLAnchorElement>('[data-deck-elsewhere]').href = across;
}
root.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
const mark = target.closest<HTMLButtonElement>('button[data-facet]');
if (mark) {
const key = mark.dataset.facet as FacetKey, value = mark.dataset.value!;
const values = new Set(filters[key] || []);
values.has(value) ? values.delete(value) : values.add(value);
filters = { ...filters, [key]: [...values] };
render();
return;
}
if (target.closest('[data-deck-clear]')) { filters = { ...EMPTY_FILTERS }; search.value = ''; render(); search.focus(); return; }
// A letter goes to the first tool under it that is still showing, which
// the static #anchor cannot know once the grid is narrowed.
const letter = target.closest<HTMLAnchorElement>('[data-az]');
if (letter) {
e.preventDefault();
const first = tiles.find((t) => t.letter === letter.dataset.az && !t.el.hidden);
if (!first) return;
const calm = matchMedia('(prefers-reduced-motion: reduce)').matches || document.documentElement.dataset.motion === 'reduce';
first.el.scrollIntoView({ block: 'start', behavior: calm ? 'auto' : 'smooth' });
first.el.focus({ preventScroll: true });
}
});
let debounce: ReturnType<typeof setTimeout>;
search.addEventListener('input', () => { clearTimeout(debounce); debounce = setTimeout(() => { filters = { ...filters, query: search.value }; render(); }, 90); });
search.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && search.value) { e.stopPropagation(); search.value = ''; filters = { ...filters, query: '' }; render(); }
// Enter opens the top match: type a few letters, press Enter, be there.
else if (e.key === 'Enter') { clearTimeout(debounce); filters = { ...filters, query: search.value }; render(); tiles.find((t) => !t.el.hidden)?.el.click(); }
});
const onPop = () => { readURL(); render(); };
window.addEventListener('popstate', onPop);
document.addEventListener('astro:before-swap', () => { clearTimeout(debounce); window.removeEventListener('popstate', onPop); }, { once: true });
readURL(); render();
}
boot();
document.addEventListener('astro:page-load', boot);