// The sheet filter: the search box, tag chips and stats block above every
// sheet list (SheetFilter.astro). Rows are all in the HTML, each carrying its
// facets as data attributes; this hides the ones that do not match and
// repaints the panel's counts. With JS off nothing here runs and the list is
// simply complete.
//
// The filter lives in the query string so a narrowed view can be linked.
// It is written with `replaceState` and the router's own `history.state`,
// because Astro's ClientRouter keeps its scroll and index bookkeeping there
// and a bare `{}` would break Back.
export type FilterState = {
/** Free text, as typed. Split on whitespace; every term has to appear. */
q: string;
/** Tags AND together: each one narrows the list further. */
tags: string[];
/** A tool key (lower-cased name). One at a time. */
tool: string;
diff: string;
/** Section key on a shelf, shelf slug on the all-sheets and tag pages. */
sec: string;
};
export type RowFacets = {
/** Lower-cased haystack: title, description, tags and tools. */
text: string;
tags: string[];
tools: string[];
diff: string;
sec: string;
};
const DIFFICULTIES = ['beginner', 'intermediate', 'advanced'];
export function parseState(search: string): FilterState {
const p = new URLSearchParams(search);
const tags = p
.getAll('tag')
.flatMap((v) => v.split(','))
.map((t) => t.trim().toLowerCase())
.filter(Boolean);
const diff = (p.get('diff') ?? '').toLowerCase();
return {
q: p.get('q') ?? '',
tags: [...new Set(tags)],
tool: (p.get('tool') ?? '').trim().toLowerCase(),
diff: DIFFICULTIES.includes(diff) ? diff : '',
sec: p.get('sec') ?? '',
};
}
export function serializeState(s: FilterState): string {
const p = new URLSearchParams();
if (s.q.trim()) p.set('q', s.q);
for (const t of s.tags) p.append('tag', t);
if (s.tool) p.set('tool', s.tool);
if (s.diff) p.set('diff', s.diff);
if (s.sec) p.set('sec', s.sec);
return p.toString();
}
/** `skip` leaves one facet out, so a split bar can count what each of its
* segments *would* show rather than collapsing to the selected one. */
export function rowMatches(row: RowFacets, s: FilterState, skip?: 'diff' | 'sec'): boolean {
if (skip !== 'diff' && s.diff && row.diff !== s.diff) return false;
if (skip !== 'sec' && s.sec && row.sec !== s.sec) return false;
if (s.tool && !row.tools.includes(s.tool)) return false;
for (const t of s.tags) if (!row.tags.includes(t)) return false;
const terms = s.q.toLowerCase().split(/\s+/).filter(Boolean);
for (const term of terms) if (!row.text.includes(term)) return false;
return true;
}
const isActive = (s: FilterState) => serializeState(s) !== '';
const pad = (n: number) => String(n).padStart(2, '0');
const list = (v: string | undefined) => (v ? v.split('|').filter(Boolean) : []);
function bump(map: Map<string, number>, key: string): void {
map.set(key, (map.get(key) ?? 0) + 1);
}
/** Bind the page's filter panel. Idempotent, so it is safe to call on every
* `astro:page-load`; a page without a panel is a no-op. */
export function initSheetFilter(): void {
const root = document.querySelector<HTMLElement>('[data-sheet-filter]');
if (!root || root.dataset.bound) return;
root.dataset.bound = '1';
const rows = [...document.querySelectorAll<HTMLElement>('[data-sf-row]')].map((el) => ({
el,
facets: {
text: el.dataset.text ?? (el.textContent ?? '').toLowerCase(),
tags: list(el.dataset.tags),
tools: list(el.dataset.tools),
diff: el.dataset.diff ?? '',
sec: el.dataset.sec ?? '',
} as RowFacets,
}));
const sections = [...document.querySelectorAll<HTMLElement>('[data-sf-section]')];
const jumps = [...document.querySelectorAll<HTMLElement>('[data-sf-jump]')];
const input = root.querySelector<HTMLInputElement>('[data-sf-q]');
const count = root.querySelector<HTMLElement>('[data-sf-count]');
const chips = root.querySelector<HTMLElement>('[data-sf-chips]');
const empty = root.querySelector<HTMLElement>('[data-sf-empty]');
const more = root.querySelector<HTMLElement>('[data-sf-more]');
const clears = [...root.querySelectorAll<HTMLElement>('[data-sf-clear]')];
// The stats block folds away on a narrow screen, where it would otherwise
// stand between the search field and the results it produces. The summary
// that toggles it is hidden on wide screens (filter.css), so the block has
// to be reopened by hand if the window grows back.
const fold = root.querySelector<HTMLDetailsElement>('[data-sf-fold]');
const narrow = window.matchMedia?.('(max-width: 859px)');
if (fold && narrow) {
fold.open = !narrow.matches;
narrow.addEventListener('change', (e) => { fold.open = !e.matches; });
}
const state = parseState(window.location.search);
if (input) input.value = state.q;
let expanded = false;
/** A filter that arrived by link and has no chip of its own here — a tool
* always, a tag when this list's chip row does not carry it. Without one
* the list would be narrowed by something the reader cannot see or undo. */
const dynamicChip = (kind: 'tag' | 'tool', value: string): HTMLButtonElement => {
const b = document.createElement('button');
b.type = 'button';
b.className = 'sf-chip sf-chip--set';
b.dataset.sfDynamic = '';
if (kind === 'tag') b.dataset.sfTag = value;
else b.dataset.sfTool = value;
b.setAttribute('aria-pressed', 'true');
b.setAttribute('aria-label', `Remove ${kind} filter: ${value}`);
const label = document.createElement('span');
label.className = 'sf-chip__kind';
label.textContent = kind;
const x = document.createElement('span');
x.className = 'sf-chip__x';
x.setAttribute('aria-hidden', 'true');
x.textContent = '×';
b.append(label, document.createTextNode(value), x);
return b;
};
const apply = (): void => {
const tagCounts = new Map<string, number>();
const toolCounts = new Map<string, number>();
const diffCounts = new Map<string, number>();
const secCounts = new Map<string, number>();
const liveSections = new Set<string>();
let shown = 0;
for (const { el, facets } of rows) {
const ok = rowMatches(facets, state);
el.hidden = !ok;
if (ok) {
shown += 1;
liveSections.add(facets.sec);
for (const t of facets.tags) bump(tagCounts, t);
for (const t of facets.tools) bump(toolCounts, t);
}
if (rowMatches(facets, state, 'diff')) bump(diffCounts, facets.diff);
if (rowMatches(facets, state, 'sec')) bump(secCounts, facets.sec);
}
const counts: Record<string, Map<string, number>> = { tag: tagCounts, tool: toolCounts, diff: diffCounts, sec: secCounts };
/** `facet:value`, as the markup writes it. Split on the first colon only. */
const split = (key: string): [string, string] => {
const cut = key.indexOf(':');
return [key.slice(0, cut), key.slice(cut + 1)];
};
const countOf = (key: string): number => {
const [facet, value] = split(key);
return counts[facet]?.get(value) ?? 0;
};
for (const s of sections) s.hidden = !liveSections.has(s.dataset.sfSection ?? '');
for (const j of jumps) j.hidden = !liveSections.has(j.dataset.sfJump ?? '');
// Counts are repainted page-wide, not just inside the panel: the jump
// strip and the section headings quote the same numbers.
document.querySelectorAll<HTMLElement>('[data-sf-n]').forEach((el) => {
el.textContent = pad(countOf(el.dataset.sfN!));
});
// A section heading says how many of its sheets survived the filter.
document.querySelectorAll<HTMLElement>('[data-sf-of]').forEach((el) => {
const total = Number(el.dataset.total) || 0;
const n = Math.min(total, countOf(el.dataset.sfOf!));
el.textContent = n === total ? `${total} ${total === 1 ? 'sheet' : 'sheets'}` : `${n} of ${total} sheets`;
});
root.querySelectorAll<HTMLElement>('[data-sf-grow]').forEach((el) => {
const n = countOf(el.dataset.sfGrow!);
el.style.flexGrow = String(n);
el.toggleAttribute('data-zero', n === 0);
});
root.querySelectorAll<HTMLElement>('[data-sf-fill]').forEach((el) => {
const max = Number(el.dataset.max) || 1;
el.style.width = `${Math.min(100, Math.round((countOf(el.dataset.sfFill!) / max) * 100))}%`;
});
// Chips that arrived by link. Rebuilt each pass so removing one is just
// a state change like any other.
root.querySelectorAll('[data-sf-dynamic]').forEach((el) => el.remove());
if (chips) {
const made: HTMLElement[] = [];
if (state.tool) made.push(dynamicChip('tool', state.tool));
for (const t of state.tags) {
const has = [...chips.querySelectorAll<HTMLElement>('[data-sf-tag]')].some((c) => c.dataset.sfTag === t);
if (!has) made.push(dynamicChip('tag', t));
}
chips.prepend(...made);
}
const toggles: [string, (v: string) => boolean, string][] = [
['sfTag', (v) => state.tags.includes(v), 'tag'],
['sfTool', (v) => state.tool === v, 'tool'],
['sfDiff', (v) => state.diff === v, 'diff'],
['sfSec', (v) => state.sec === v, 'sec'],
];
for (const [key, on, facet] of toggles) {
const attr = `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
root.querySelectorAll<HTMLElement>(`[${attr}]`).forEach((el) => {
const value = el.dataset[key] ?? '';
const pressed = on(value);
el.setAttribute('aria-pressed', String(pressed));
// A chip that would empty the list is dimmed, never disabled: it
// still has to be reachable to be switched back off.
el.toggleAttribute('data-none', !pressed && countOf(`${facet}:${value}`) === 0);
if (el.hasAttribute('data-sf-extra')) el.hidden = !expanded && !pressed;
});
}
// The split bars are drawn from plain marks, not buttons; they follow
// the selection so the bar can grey out everything but the chosen part.
const on: Record<string, string> = { diff: state.diff, sec: state.sec };
root.querySelectorAll<HTMLElement>('[data-sf-mark]').forEach((el) => {
const [facet, value] = split(el.dataset.sfMark!);
el.toggleAttribute('data-on', on[facet] === value);
});
root.toggleAttribute('data-has-diff', !!state.diff);
root.toggleAttribute('data-has-sec', !!state.sec);
if (count) count.textContent = `${shown} shown`;
if (empty) empty.hidden = shown > 0;
const active = isActive(state);
for (const c of clears) if (!c.closest('[data-sf-empty]')) c.hidden = !active;
root.toggleAttribute('data-filtered', active);
const qs = serializeState(state);
const next = `${window.location.pathname}${qs ? `?${qs}` : ''}${window.location.hash}`;
if (next !== `${window.location.pathname}${window.location.search}${window.location.hash}`) {
window.history.replaceState(window.history.state, '', next);
}
};
input?.addEventListener('input', () => { state.q = input.value; apply(); });
input?.addEventListener('keydown', (e) => {
if (e.key !== 'Escape' || !input.value) return;
// Take the first Escape for the field; the second is free to bubble.
e.stopPropagation();
input.value = '';
state.q = '';
apply();
});
root.addEventListener('click', (e) => {
const el = (e.target as Element).closest<HTMLElement>(
'[data-sf-tag],[data-sf-tool],[data-sf-diff],[data-sf-sec],[data-sf-clear],[data-sf-more]',
);
if (!el || !root.contains(el)) return;
const d = el.dataset;
if (d.sfTag !== undefined) {
state.tags = state.tags.includes(d.sfTag) ? state.tags.filter((t) => t !== d.sfTag) : [...state.tags, d.sfTag];
} else if (d.sfTool !== undefined) {
state.tool = state.tool === d.sfTool ? '' : d.sfTool;
} else if (d.sfDiff !== undefined) {
state.diff = state.diff === d.sfDiff ? '' : d.sfDiff;
} else if (d.sfSec !== undefined) {
state.sec = state.sec === d.sfSec ? '' : d.sfSec;
} else if (d.sfClear !== undefined) {
Object.assign(state, parseState(''));
if (input) input.value = '';
} else if (d.sfMore !== undefined) {
expanded = !expanded;
el.setAttribute('aria-expanded', String(expanded));
if (more) {
const label = more.querySelector<HTMLElement>('[data-sf-more-label]');
if (label) label.textContent = expanded ? 'Fewer' : more.dataset.sfMore || 'More';
}
}
apply();
});
apply();
}