Files
Spaghet.io/src/lib/filters.ts
T
spaghet fb8e42f632 refactor: consolidate blog and project filtering into shared component
The /blog and /projects listings previously used byte-identical copies of the same
filtering island, which meant bugs like inconsistent AND-vs-OR tag semantics,
duplicate-case tags, and a missing empty state were duplicated across both.

This commit introduces `FilteredList`, a single shared Solid component that:

- Unifies tag, keyword, and sort filtering for both collections
- Seeds initial filter state from the SSR request URL to avoid hydration mismatches
- Syncs active filters into the address bar via `history.replaceState` so filtered
  views survive refreshes and can be shared
- Restores filters on browser back/forward navigation (`popstate`)
- Case-folds and dedupes tags when parsing URL params

Filter logic (collectTags, filterEntries, sortKeys, URL param encoding) is extracted
into `src/lib/filters.ts` with full unit test coverage.
2026-11-12 22:38:58 -05:00

185 lines
5.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// src/lib/filters.ts
import type { ListEntry } from "@lib/types"
export type { ListEntry }
export type SortKey = "newest" | "oldest" | "az"
export const DEFAULT_SORT: SortKey = "newest"
export const SORT_KEYS: SortKey[] = ["newest", "oldest", "az"]
export const SORT_LABELS: Record<SortKey, string> = {
newest: "Newest first",
oldest: "Oldest first",
az: "Title A–Z",
}
export interface TagOption {
/** Case-folded identity, what gets stored in state and in the URL. */
key: string
/** The spelling shown to humans. */
label: string
}
export interface FilterState {
tags: string[]
query: string
sort: SortKey
}
export const TAGS_PARAM = "tags"
export const QUERY_PARAM = "q"
export const SORT_PARAM = "sort"
export function normalizeTag(tag: string): string {
return tag.trim().toLowerCase()
}
/**
* Dedupe tags case-insensitively and pick one canonical spelling per tag.
*
* Frontmatter is hand-written, so the same tag appears as both `Astro` and
* `astro` across the projects collection. Matching has always been
* case-insensitive, which meant the filter sidebar rendered two visually
* different checkboxes that did exactly the same thing. The label with the
* most occurrences wins; ties fall back to first-seen order, so the result is
* stable across builds.
*/
export function collectTags(entries: ListEntry[]): TagOption[] {
const spellings = new Map<string, Map<string, number>>()
for (const entry of entries) {
for (const raw of entry.tags ?? []) {
const label = raw.trim()
if (!label) continue
const key = normalizeTag(label)
const counts = spellings.get(key) ?? new Map<string, number>()
counts.set(label, (counts.get(label) ?? 0) + 1)
spellings.set(key, counts)
}
}
return Array.from(spellings, ([key, counts]) => ({
key,
label: mostFrequent(counts),
})).sort((a, b) => a.label.localeCompare(b.label))
}
/** Highest count wins; `Map` iteration order breaks ties by first insertion. */
function mostFrequent(counts: Map<string, number>): string {
let best = ""
let bestCount = -1
for (const [label, count] of counts) {
if (count > bestCount) {
best = label
bestCount = count
}
}
return best
}
/**
* Keyword match over the fields the card shows: title, summary and tags. Body
* text is intentionally out of scope — full-text search lives on /search.
*/
export function matchesQuery(entry: ListEntry, query: string): boolean {
const needle = query.trim().toLowerCase()
if (!needle) return true
return (
entry.title.toLowerCase().includes(needle) ||
entry.summary.toLowerCase().includes(needle) ||
(entry.tags ?? []).some((tag) => tag.toLowerCase().includes(needle))
)
}
/**
* OR semantics: an entry is kept when it carries *any* selected tag.
*
* The old filter AND-ed the selection, so picking a second tag almost always
* emptied the list with no explanation. Broadening on click is what the
* checkboxes look like they do.
*/
export function filterEntries<T extends ListEntry>(
entries: T[],
state: FilterState
): T[] {
const selected = state.tags.map(normalizeTag).filter(Boolean)
const matched = entries.filter(
(entry) =>
matchesQuery(entry, state.query) &&
(selected.length === 0 ||
(entry.tags ?? []).some((tag) => selected.includes(normalizeTag(tag))))
)
return sortEntries(matched, state.sort)
}
function timestamp(entry: ListEntry): number {
const ms = new Date(entry.date).getTime()
// A malformed frontmatter date must not sort the whole list to NaN.
return Number.isFinite(ms) ? ms : 0
}
export function sortEntries<T extends ListEntry>(entries: T[], sort: SortKey): T[] {
const copy = [...entries]
if (sort === "az") return copy.sort((a, b) => a.title.localeCompare(b.title))
if (sort === "oldest") return copy.sort((a, b) => timestamp(a) - timestamp(b))
return copy.sort((a, b) => timestamp(b) - timestamp(a))
}
/**
* How many entries each tag would contribute *within the current keyword
* filter*, keyed by tag. Tags are not counted against each other: under OR
* semantics every selected tag is contributing, and a count that collapsed as
* soon as you clicked something would read like the filter was broken.
*/
export function tagCounts(entries: ListEntry[], state: FilterState): Map<string, number> {
const counts = new Map<string, number>()
for (const entry of entries) {
if (!matchesQuery(entry, state.query)) continue
for (const key of new Set((entry.tags ?? []).map(normalizeTag))) {
if (!key) continue
counts.set(key, (counts.get(key) ?? 0) + 1)
}
}
return counts
}
export function hasActiveFilters(state: FilterState): boolean {
return state.tags.length > 0 || state.query.trim().length > 0 || state.sort !== DEFAULT_SORT
}
/**
* Read filter state out of a URL query string. Anything unparseable falls back
* to the default rather than throwing: these values come from a hand-edited
* address bar and have no contract to honour.
*/
export function parseFilterParams(params: URLSearchParams): FilterState {
const rawSort = params.get(SORT_PARAM)
return {
tags: Array.from(
new Set(
(params.get(TAGS_PARAM) ?? "")
.split(",")
.map(normalizeTag)
.filter(Boolean)
)
),
query: params.get(QUERY_PARAM) ?? "",
sort: SORT_KEYS.includes(rawSort as SortKey) ? (rawSort as SortKey) : DEFAULT_SORT,
}
}
/**
* Write filter state back into a URLSearchParams, omitting defaults so a plain
* /blog stays a clean, shareable /blog.
*/
export function writeFilterParams(params: URLSearchParams, state: FilterState): void {
if (state.tags.length > 0) params.set(TAGS_PARAM, state.tags.join(","))
else params.delete(TAGS_PARAM)
if (state.query.trim().length > 0) params.set(QUERY_PARAM, state.query.trim())
else params.delete(QUERY_PARAM)
if (state.sort !== DEFAULT_SORT) params.set(SORT_PARAM, state.sort)
else params.delete(SORT_PARAM)
}