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.
This commit is contained in:
spaghet committed 2026-11-12 22:38:58 -05:00
1 parent 9e157a4fa3
commit fb8e42f632
11 files changed
+811 -266

No files matched your search

-74
View File
@@ -1,74 +0,0 @@
import type { BlogPost } from "@lib/types"
import { createMemo, createSignal, For } from "solid-js"
import ArrowCard from "@components/ArrowCard"
import { cn } from "@lib/utils"
import { filterByTags } from "@lib/content"
type Props = {
tags: string[]
data: BlogPost[]
}
export default function Blog({ data, tags }: Props) {
const [filter, setFilter] = createSignal(new Set<string>())
// `createMemo`, not `createEffect` + a signal: effects never run during SSR, so the
// signal stayed at its initial `[]` and the server emitted "SHOWING 0 OF 3" with an
// empty <ul>. The list was only ever filled by client hydration, which meant any
// island load failure hid every post.
const posts = createMemo<BlogPost[]>(() => filterByTags(data, filter()))
function toggleTag(tag: string) {
setFilter((prev) =>
new Set(prev.has(tag)
? [...prev].filter((t) => t !== tag)
: [...prev, tag]
)
)
}
return (
<div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
<div class="col-span-3 sm:col-span-1">
<div class="sticky top-24">
<div class="text-sm font-semibold uppercase mb-2 text-ink">Filter</div>
{/* Tag Filter */}
<div class="mb-2">
<div class="text-xs uppercase mb-1 text-ink-muted">Tags</div>
<ul class="flex flex-wrap sm:flex-col gap-1.5">
<For each={tags}>
{(tag) => (
<li>
<button onClick={() => toggleTag(tag)} class={cn("w-full px-2 py-1 rounded text-ink", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "border border-transparent hover:border-edge hover:bg-wash", "transition-colors duration-300 ease-in-out", filter().has(tag) && "bg-chip text-chip-ink border-chip")}>
<svg class={cn("size-5 fill-current opacity-60", "transition-colors duration-300 ease-in-out", filter().has(tag) && "opacity-100")}>
<use href={`/ui.svg#square`} class={cn(!filter().has(tag) ? "block" : "hidden")} />
<use href={`/ui.svg#square-check`} class={cn(filter().has(tag) ? "block" : "hidden")} />
</svg>
{tag}
</button>
</li>
)}
</For>
</ul>
</div>
</div>
</div>
<div class="col-span-3 sm:col-span-2">
<div class="flex flex-col">
<div class="text-sm uppercase mb-2">
SHOWING {posts().length} OF {data.length} POSTS
</div>
<ul class="flex flex-col gap-3">
<For each={posts()}>
{(post) => (
<li>
<ArrowCard entry={post} collection={'blog'} />
</li>
)}
</For>
</ul>
</div>
</div>
</div>
)
}
+210
View File
@@ -0,0 +1,210 @@
import { createEffect, createMemo, createSignal, onCleanup, onMount, For } from "solid-js"
import ArrowCard from "@components/ArrowCard"
import { cn } from "@lib/utils"
import {
collectTags,
filterEntries,
hasActiveFilters,
parseFilterParams,
tagCounts,
writeFilterParams,
DEFAULT_SORT,
SORT_KEYS,
SORT_LABELS,
type FilterState,
type ListEntry,
type SortKey,
} from "@lib/filters"
type Props = {
entries: ListEntry[]
collection: "blog" | "projects"
/**
* Filter state read from the incoming request URL. The island is SSR'd, so
* seeding from `window.location` would render one list on the server and a
* different one on hydration; the page passes the parsed request URL instead.
*/
initial?: FilterState
}
/**
* Shared tag + keyword + sort filter for the /blog and /projects listings.
*
* Both islands used to be byte-identical copies of each other, which is how
* the AND-vs-OR semantics, the duplicate-case tags and the missing empty state
* ended up duplicated too. One component, one place to fix.
*/
export default function FilteredList({ entries, collection, initial }: Props) {
const [filter, setFilter] = createSignal<FilterState>(
initial ?? { tags: [], query: "", sort: DEFAULT_SORT }
)
const tags = createMemo(() => collectTags(entries))
const counts = createMemo(() => tagCounts(entries, filter()))
const visible = createMemo(() => filterEntries(entries, filter()))
const filtered = createMemo(() => hasActiveFilters(filter()))
function toggleTag(key: string) {
setFilter((prev) => ({
...prev,
tags: prev.tags.includes(key)
? prev.tags.filter((tag) => tag !== key)
: [...prev.tags, key],
}))
}
function reset() {
setFilter({ tags: [], query: "", sort: DEFAULT_SORT })
}
// Mirror state into the address bar so a filtered view survives a refresh and
// can be shared, matching what the search island already does.
const syncUrl = () => {
if (typeof window === "undefined") return
const url = new URL(window.location.href)
writeFilterParams(url.searchParams, filter())
window.history.replaceState({}, "", url.toString())
}
createEffect(syncUrl)
// Restore filters when the user navigates with browser back/forward. Bound
// only in onMount: this component is SSR'd, and `window` does not exist there.
const onPopState = () =>
setFilter(parseFilterParams(new URL(window.location.href).searchParams))
let popStateBound = false
onMount(() => {
window.addEventListener("popstate", onPopState)
popStateBound = true
})
onCleanup(() => {
if (popStateBound) window.removeEventListener("popstate", onPopState)
})
const noun = collection === "blog" ? "post" : "project"
const plural = `${noun}s`
return (
<div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
<div class="col-span-3 sm:col-span-1">
<div class="sticky top-24">
<div class="flex items-center justify-between gap-2">
<div class="text-sm font-semibold uppercase mb-2 text-ink">Filter</div>
{filtered() && (
<button
onClick={reset}
class="text-xs uppercase text-link hover:text-link-hover underline underline-offset-2 mb-2 transition-colors duration-300 ease-in-out"
>
Clear all
</button>
)}
</div>
<label class="block text-xs uppercase mb-1 text-ink-muted" htmlFor="filter-q">
Keyword
</label>
<input
id="filter-q"
type="search"
value={filter().query}
onInput={(e) => setFilter((prev) => ({ ...prev, query: e.currentTarget.value }))}
placeholder={`Search ${plural}…`}
autocomplete="off"
spellcheck={false}
class="w-full px-2.5 py-1.5 rounded outline-none text-ink bg-chip border border-edge focus:border-edge transition-colors duration-300 ease-in-out"
/>
<label class="block text-xs uppercase mt-3 mb-1 text-ink-muted" htmlFor="filter-sort">
Sort
</label>
<select
id="filter-sort"
value={filter().sort}
onChange={(e) => setFilter((prev) => ({ ...prev, sort: e.currentTarget.value as SortKey }))}
class="w-full px-2 py-1.5 rounded text-ink bg-chip border border-edge outline-none transition-colors duration-300 ease-in-out"
>
<For each={SORT_KEYS}>
{/* `selected` is set explicitly because `<select value>` has no
content attribute: SSR writes it as one, which browsers ignore,
so a deep link like ?sort=az would render the wrong option
selected until hydration. */}
{(key) => <option value={key} selected={filter().sort === key}>{SORT_LABELS[key]}</option>}
</For>
</select>
<div class="mt-3">
<div class="text-xs uppercase mb-1 text-ink-muted">Tags</div>
<ul role="group" aria-label="Filter by tag" class="flex flex-wrap sm:flex-col gap-1.5">
<For each={tags()}>
{(tag) => {
const selected = () => filter().tags.includes(tag.key)
const count = () => counts().get(tag.key) ?? 0
return (
<li>
<button
onClick={() => toggleTag(tag.key)}
aria-pressed={selected()}
class={cn(
"w-full px-2 py-1 rounded text-ink",
"whitespace-nowrap overflow-hidden overflow-ellipsis",
"flex gap-2 items-center",
"border border-transparent hover:border-edge hover:bg-wash",
"transition-colors duration-300 ease-in-out",
selected() && "bg-chip text-chip-ink border-chip",
count() === 0 && !selected() && "opacity-50"
)}
>
<svg class={cn("size-5 shrink-0 fill-current opacity-60", "transition-colors duration-300 ease-in-out", selected() && "opacity-100")}>
<use href={`/ui.svg#square`} class={cn(selected() ? "hidden" : "block")} />
<use href={`/ui.svg#square-check`} class={cn(selected() ? "block" : "hidden")} />
</svg>
<span class="flex-1 text-left truncate">{tag.label}</span>
<span class="text-xs tabular-nums opacity-70">{count()}</span>
</button>
</li>
)
}}
</For>
</ul>
</div>
</div>
</div>
<div class="col-span-3 sm:col-span-2">
<div class="flex flex-col">
<div class="text-sm uppercase mb-2" aria-live="polite">
SHOWING {visible().length} OF {entries.length} {plural.toUpperCase()}
</div>
{visible().length === 0 ? (
<div class="p-4 border border-edge rounded-lg bg-surface">
<div class="font-semibold text-ink">No {plural} match these filters.</div>
<div class="text-sm text-ink-muted mt-1">
Tags are combined with OR, so a keyword that excludes everything is the usual
culprit. Try shortening the keyword or clearing the filters.
</div>
<button
onClick={reset}
class="mt-3 px-2 py-1 rounded text-ink border border-edge hover:bg-wash transition-colors duration-300 ease-in-out"
>
Clear filters
</button>
</div>
) : (
<ul class="flex flex-col gap-3">
<For each={visible()}>
{(entry) => (
<li>
<ArrowCard entry={entry} collection={collection} />
</li>
)}
</For>
</ul>
)}
</div>
</div>
</div>
)
}
-68
View File
@@ -1,68 +0,0 @@
import type { Project } from "@lib/types"
import { createMemo, createSignal, For } from "solid-js"
import ArrowCard from "@components/ArrowCard"
import { cn } from "@lib/utils"
import { filterByTags } from "@lib/content"
type Props = {
tags: string[]
data: Project[]
}
export default function Projects({ data, tags }: Props) {
const [filter, setFilter] = createSignal(new Set<string>())
// See Blog.tsx: a memo (not an effect writing a signal) so the list is populated
// in the server-rendered HTML and survives a failed hydration.
const projects = createMemo<Project[]>(() => filterByTags(data, filter()))
function toggleTag(tag: string) {
setFilter((prev) =>
new Set(prev.has(tag)
? [...prev].filter((t) => t !== tag)
: [...prev, tag]
)
)
}
return (
<div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
<div class="col-span-3 sm:col-span-1">
<div class="sticky top-24">
<div class="text-sm font-semibold uppercase mb-2 text-ink">Filter</div>
<ul class="flex flex-wrap sm:flex-col gap-1.5">
<For each={tags}>
{(tag) => (
<li>
<button onClick={() => toggleTag(tag)} class={cn("w-full px-2 py-1 rounded text-ink", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "border border-transparent hover:border-edge hover:bg-wash", "transition-colors duration-300 ease-in-out", filter().has(tag) && "bg-chip text-chip-ink border-chip")}>
<svg class={cn("size-5 fill-current opacity-60", "transition-colors duration-300 ease-in-out", filter().has(tag) && "opacity-100")}>
<use href={`/ui.svg#square`} class={cn(!filter().has(tag) ? "block" : "hidden")} />
<use href={`/ui.svg#square-check`} class={cn(filter().has(tag) ? "block" : "hidden")} />
</svg>
{tag}
</button>
</li>
)}
</For>
</ul>
</div>
</div>
<div class="col-span-3 sm:col-span-2">
<div class="flex flex-col">
<div class="text-sm uppercase mb-2">
SHOWING {projects().length} OF {data.length} PROJECTS
</div>
<ul class="flex flex-col gap-3">
<For each={projects()}>
{(project) => (
<li>
<ArrowCard entry={project} collection={'projects'} />
</li>
)}
</For>
</ul>
</div>
</div>
</div>
)
}
+120 -50
View File
@@ -1,83 +1,153 @@
// src/components/__tests__/list-islands.test.ts
import { describe, it, expect } from "vitest"
import { renderToString } from "solid-js/web"
import Blog from "@components/Blog"
import Projects from "@components/Projects"
import type { BlogPost, Project } from "@lib/types"
import FilteredList from "@components/FilteredList"
import type { FilterState, ListEntry } from "@lib/filters"
/**
* These render the islands through solid-js/web's server renderer, which is
* the same path Astro takes for `output: "server"` + `client:load`. That is
* the point: the regression being locked in here is that the filtered list
* must exist in the SERVER HTML. The old `createEffect` + signal version
* rendered "SHOWING 0 OF 3" with an empty <ul> because effects never run
* during SSR, so any island/hydration failure hid every post.
* Renders the shared listing island through solid-js/web's server renderer,
* which is the same path Astro takes for `output: "server"` + `client:load`.
*
* The regression locked in here is that the list must exist in the SERVER HTML:
* the original `createEffect` + signal version rendered "SHOWING 0 OF 3" with an
* empty <ul>, so any hydration failure hid every entry. The second regression is
* the case-duplicated tag list, which made /blog and /projects render two
* checkboxes that did exactly the same thing.
*/
function post(id: string, tags: string[]): BlogPost {
function entry(id: string, tags: string[], overrides: Partial<ListEntry> = {}): ListEntry {
return {
id,
title: `Post ${id}`,
title: `Entry ${id}`,
summary: `Summary ${id}`,
date: "2026-01-01T00:00:00.000Z",
tags,
draft: false,
content: "",
template: "default",
featured: false,
...overrides,
}
}
function project(id: string, tags: string[]): Project {
return {
id,
title: `Project ${id}`,
summary: `Summary ${id}`,
date: "2026-01-01T00:00:00.000Z",
tags,
draft: false,
content: "",
}
const posts: ListEntry[] = [
entry("a", ["CSS", "Html"], { title: "Alpha", date: "2025-01-01T00:00:00.000Z" }),
entry("b", ["CSS", "css"], { title: "Bravo", date: "2026-01-01T00:00:00.000Z" }),
entry("c", ["html"], { title: "Charlie", date: "2025-06-01T00:00:00.000Z" }),
]
/**
* Solid's SSR output interleaves hydration markers around every dynamic value
* (`SHOWING <!--$-->3<!--/--> OF …`). Stripping comments keeps the assertions
* about real content instead of about marker placement.
*/
function render(props: {
entries?: ListEntry[]
collection?: "blog" | "projects"
initial?: FilterState
}): string {
const html = renderToString(() =>
FilteredList({
entries: props.entries ?? posts,
collection: props.collection ?? "blog",
initial: props.initial,
})
)
return html.replace(/<!--.*?-->/g, "")
}
describe("Blog island (SSR render)", () => {
const data = [post("a", ["css", "html"]), post("b", ["css"]), post("c", ["html"])]
describe("FilteredList island (SSR render)", () => {
it("should render every entry in the server HTML with no filter applied", () => {
const html = render({})
it("should render every post in the server HTML with no filter applied", () => {
const html = renderToString(() => Blog({ data, tags: ["css", "html"] }))
expect(html).toContain("SHOWING <!--$-->3<!--/--> OF <!--$-->3<!--/--> POSTS")
for (const entry of data) {
expect(html).toContain(`href="/blog/${entry.id}"`)
expect(html).toContain("SHOWING 3 OF 3 POSTS")
for (const item of posts) {
expect(html).toContain(`href="/blog/${item.id}"`)
}
})
it("should not regress to an empty list when the filter signal is untouched", () => {
// Guards the createEffect bug specifically: an empty filter must still show all.
const html = renderToString(() => Blog({ data, tags: [] }))
expect(html).not.toContain("SHOWING <!--$-->0")
it("should not regress to an empty list when no initial state is passed", () => {
// Guards the createEffect bug specifically: an untouched filter must show all.
expect(render({})).not.toContain("SHOWING 0")
})
it("should render the tag filter buttons server-side", () => {
const html = renderToString(() => Blog({ data, tags: ["css", "html"] }))
expect(html).toContain(">css<!--/--></button>")
expect(html).toContain(">html<!--/--></button>")
it("should apply initial state server-side so a filtered deep link renders filtered", () => {
const html = render({ initial: { tags: ["css"], query: "", sort: "newest" } })
expect(html).toContain("SHOWING 2 OF 3 POSTS")
expect(html).toContain('href="/blog/a"')
expect(html).toContain('href="/blog/b"')
expect(html).not.toContain('href="/blog/c"')
})
})
describe("Projects island (SSR render)", () => {
const data = [project("x", ["react"]), project("y", ["react", "rust"])]
it("should render one checkbox per tag, deduped across spellings", () => {
// `CSS`/`css` and `html`/`Html` collapse to two options, not four.
const html = render({})
it("should render every project in the server HTML", () => {
const html = renderToString(() => Projects({ data, tags: ["react", "rust"] }))
expect(html).toContain(">CSS</span>")
expect(html).toContain(">Html</span>")
expect(html.match(/aria-pressed/g)).toHaveLength(2)
})
expect(html).toContain("SHOWING <!--$-->2<!--/--> OF <!--$-->2<!--/--> PROJECTS")
it("should show a per-tag count next to each option", () => {
// css -> a, b; html -> a, c. Assert on the rendered counts rather than on
// the exact class string so the test survives a restyle.
const html = render({})
const counts = [...html.matchAll(/<\/span><span[^>]*>(\d+)<\/span>/g)].map((m) => m[1])
expect(counts).toHaveLength(2)
expect(counts.every((count) => count === "2")).toBe(true)
})
it("should render the keyword input, sort select and live count region", () => {
const html = render({})
expect(html).toContain('id="filter-q"')
expect(html).toContain('id="filter-sort"')
expect(html).toContain('aria-live="polite"')
expect(html).toContain('role="group"')
expect(html).toContain("Newest first")
})
it("should sort by the requested key in the server HTML", () => {
const html = render({ initial: { tags: [], query: "", sort: "az" } })
expect(html.indexOf('href="/blog/a"')).toBeLessThan(html.indexOf('href="/blog/b"'))
})
it("should render an empty state instead of a blank list when nothing matches", () => {
const html = render({ initial: { tags: [], query: "zzzz", sort: "newest" } })
expect(html).toContain("SHOWING 0 OF 3 POSTS")
expect(html).toContain("No posts match these filters.")
expect(html).toContain("Clear filters")
})
it("should offer Clear all only once a filter is active", () => {
expect(render({})).not.toContain("Clear all")
expect(render({ initial: { tags: ["css"], query: "", sort: "newest" } })).toContain("Clear all")
})
it("should label the count PROJECTS for the projects collection", () => {
const html = render({
entries: [entry("x", ["react"]), entry("y", ["react", "rust"])],
collection: "projects",
})
expect(html).toContain("SHOWING 2 OF 2 PROJECTS")
expect(html).toContain('href="/projects/x"')
expect(html).toContain('href="/projects/y"')
})
it("should tolerate entries without optional demoUrl/repoUrl", () => {
// The content schema marks both optional; the memo must not throw on SSR.
expect(() => renderToString(() => Projects({ data, tags: [] }))).not.toThrow()
it("should render an empty collection without throwing", () => {
// A collection where every entry is still a draft: no tags to list, nothing
// to show, and the empty state must carry the panel.
const html = render({ entries: [] })
expect(html).toContain("SHOWING 0 OF 0 POSTS")
expect(html).toContain("No posts match these filters.")
expect(html.match(/aria-pressed/g)).toBeNull()
})
it("should render entries that carry no tags at all", () => {
const html = render({ entries: [entry("solo", [])] })
expect(html).toContain("SHOWING 1 OF 1 POSTS")
expect(html).toContain('href="/blog/solo"')
})
})
+1 -33
View File
@@ -1,6 +1,6 @@
// src/lib/__tests__/content.test.ts
import { describe, it, expect } from "vitest"
import { byDateDesc, filterByTags } from "../content"
import { byDateDesc } from "../content"
/**
* Fixture factory rather than inline literals in every test: mirrors the shape
@@ -65,35 +65,3 @@ describe("byDateDesc", () => {
expect(([] as ReturnType<typeof dated>[]).sort(byDateDesc)).toEqual([])
})
})
describe("filterByTags", () => {
const tagged = (id: string, tags: string[]) => ({ id, tags })
const entries = [
tagged("css-html", ["CSS", "html"]),
tagged("css-only", ["css"]),
tagged("html-only", ["Html"]),
]
it("should return everything when no tags are selected", () => {
expect(filterByTags(entries, []).map((e) => e.id)).toEqual([
"css-html",
"css-only",
"html-only",
])
})
it("should match tags case-insensitively on both sides", () => {
expect(filterByTags(entries, ["CSS"]).map((e) => e.id)).toEqual(["css-html", "css-only"])
expect(filterByTags(entries, ["hTmL"]).map((e) => e.id)).toEqual(["css-html", "html-only"])
})
it("should AND selected tags, narrowing rather than unioning", () => {
// Deliberate behavior, not an accident: selecting two tags keeps only entries
// carrying both, which is why most multi-tag selections return few results.
expect(filterByTags(entries, ["css", "html"]).map((e) => e.id)).toEqual(["css-html"])
})
it("should return nothing for an unselected tag", () => {
expect(filterByTags(entries, ["rust"])).toEqual([])
})
})
+257
View File
@@ -0,0 +1,257 @@
// src/lib/__tests__/filters.test.ts
import { describe, it, expect } from "vitest"
import {
collectTags,
filterEntries,
hasActiveFilters,
matchesQuery,
normalizeTag,
parseFilterParams,
sortEntries,
tagCounts,
writeFilterParams,
DEFAULT_SORT,
type FilterState,
type ListEntry,
} from "../filters"
/** Mirrors the fields the listing island receives, without Astro's virtual module. */
function entry(
id: string,
tags: string[],
overrides: Partial<ListEntry> = {}
): ListEntry {
return {
id,
title: `Entry ${id}`,
summary: `Summary ${id}`,
date: "2026-01-01T00:00:00.000Z",
tags,
...overrides,
}
}
function state(overrides: Partial<FilterState> = {}): FilterState {
return { tags: [], query: "", sort: DEFAULT_SORT, ...overrides }
}
describe("normalizeTag", () => {
it("should case-fold and trim", () => {
expect(normalizeTag(" Tailwind CSS ")).toBe("tailwind css")
})
})
describe("collectTags", () => {
it("should collapse tags that differ only by case into one option", () => {
// The real bug: /projects carries both `Astro` and `astro` in frontmatter,
// so the sidebar rendered two checkboxes that did the same thing.
const tags = collectTags([
entry("a", ["Astro", "React"]),
entry("b", ["astro", "Tailwind CSS"]),
])
expect(tags.map((tag) => tag.key)).toEqual(["astro", "react", "tailwind css"])
})
it("should pick the most frequent spelling as the label", () => {
const tags = collectTags([
entry("a", ["astro"]),
entry("b", ["Astro"]),
entry("c", ["Astro"]),
])
expect(tags).toEqual([{ key: "astro", label: "Astro" }])
})
it("should keep the first-seen spelling when the counts tie", () => {
const first = collectTags([entry("a", ["Docker"]), entry("b", ["docker"])])
const second = collectTags([entry("a", ["docker"]), entry("b", ["Docker"])])
expect(first).toEqual([{ key: "docker", label: "Docker" }])
expect(second).toEqual([{ key: "docker", label: "docker" }])
})
it("should sort options alphabetically and drop blanks", () => {
const tags = collectTags([entry("a", ["zeta", "", " ", "alpha"])])
expect(tags.map((tag) => tag.label)).toEqual(["alpha", "zeta"])
})
it("should return nothing for an empty collection", () => {
expect(collectTags([])).toEqual([])
})
})
describe("matchesQuery", () => {
const post = entry("k", ["Docker"], {
title: "Home Server",
summary: "Unraid and backups",
})
it("should match everything on an empty or whitespace query", () => {
expect(matchesQuery(post, "")).toBe(true)
expect(matchesQuery(post, " ")).toBe(true)
})
it("should match title, summary and tags case-insensitively", () => {
expect(matchesQuery(post, "SERVER")).toBe(true)
expect(matchesQuery(post, "backups")).toBe(true)
expect(matchesQuery(post, "docKer")).toBe(true)
})
it("should not match the body, which is not part of the shape", () => {
expect(matchesQuery(post, "nope")).toBe(false)
})
})
describe("filterEntries", () => {
const entries = [
entry("css-html", ["CSS", "html"]),
entry("css-only", ["css"]),
entry("html-only", ["Html"]),
entry("rust-only", ["rust"]),
]
it("should return everything when nothing is selected", () => {
expect(filterEntries(entries, state()).map((e) => e.id)).toEqual([
"css-html",
"css-only",
"html-only",
"rust-only",
])
})
it("should OR selected tags, broadening rather than narrowing", () => {
// Deliberate change from the old AND behavior: clicking a second tag adds
// results, which is what a checkbox list looks like it does.
expect(filterEntries(entries, state({ tags: ["css", "html"] })).map((e) => e.id)).toEqual([
"css-html",
"css-only",
"html-only",
])
})
it("should match selected tags case-insensitively on both sides", () => {
expect(filterEntries(entries, state({ tags: ["CsS"] })).map((e) => e.id)).toEqual([
"css-html",
"css-only",
])
})
it("should intersect the keyword filter with the tag filter", () => {
const result = filterEntries(entries, state({ tags: ["css", "rust"], query: "html" }))
expect(result.map((e) => e.id)).toEqual(["css-html"])
})
it("should return nothing for a tag nobody carries", () => {
expect(filterEntries(entries, state({ tags: ["go"] }))).toEqual([])
})
it("should not throw when an entry is missing tags", () => {
const loose = [{ ...entry("a", []), tags: undefined }] as unknown as ListEntry[]
expect(() => filterEntries(loose, state({ tags: ["css"] }))).not.toThrow()
expect(collectTags(loose)).toEqual([])
})
})
describe("sortEntries", () => {
const entries = [
entry("old", [], { date: "2025-01-01T00:00:00.000Z", title: "Bravo" }),
entry("new", [], { date: "2026-01-01T00:00:00.000Z", title: "alpha" }),
entry("mid", [], { date: "2025-06-01T00:00:00.000Z", title: "Charlie" }),
]
it("should sort newest first by default", () => {
expect(sortEntries(entries, "newest").map((e) => e.id)).toEqual(["new", "mid", "old"])
})
it("should sort oldest first", () => {
expect(sortEntries(entries, "oldest").map((e) => e.id)).toEqual(["old", "mid", "new"])
})
it("should sort by title case-insensitively", () => {
expect(sortEntries(entries, "az").map((e) => e.title)).toEqual(["alpha", "Bravo", "Charlie"])
})
it("should not mutate the caller's array", () => {
const original = entries.map((e) => e.id)
sortEntries(entries, "oldest")
expect(entries.map((e) => e.id)).toEqual(original)
})
it("should tolerate an unparseable date without throwing", () => {
const broken = [entry("a", [], { date: "not-a-date" }), entry("b", [], { date: "2026-01-01T00:00:00.000Z" })]
expect(() => sortEntries(broken, "newest")).not.toThrow()
expect(sortEntries(broken, "newest").map((e) => e.id)).toEqual(["b", "a"])
})
})
describe("tagCounts", () => {
const entries = [
entry("a", ["Docker", "Astro"]),
entry("b", ["docker"]),
entry("c", ["Rust"]),
]
it("should count each tag once per entry", () => {
expect(tagCounts(entries, state()).get("docker")).toBe(2)
expect(tagCounts(entries, state()).get("astro")).toBe(1)
})
it("should count within the keyword filter", () => {
const counts = tagCounts(entries, state({ query: "Entry c" }))
expect(counts.get("rust")).toBe(1)
expect(counts.get("docker")).toBeUndefined()
})
it("should not count a tag twice when an entry spells it two ways", () => {
const counts = tagCounts([entry("a", ["Astro", "astro"])], state())
expect(counts.get("astro")).toBe(1)
})
})
describe("hasActiveFilters", () => {
it("should be false for the default state", () => {
expect(hasActiveFilters(state())).toBe(false)
})
it("should be true for tags, a keyword, or a non-default sort", () => {
expect(hasActiveFilters(state({ tags: ["css"] }))).toBe(true)
expect(hasActiveFilters(state({ query: " hi " }))).toBe(true)
expect(hasActiveFilters(state({ sort: "az" }))).toBe(true)
expect(hasActiveFilters(state({ query: " " }))).toBe(false)
})
})
describe("URL params", () => {
it("should round-trip tags, keyword and sort", () => {
const params = new URLSearchParams()
writeFilterParams(params, state({ tags: ["docker", "astro"], query: "home lab", sort: "oldest" }))
expect(parseFilterParams(params)).toEqual({
tags: ["docker", "astro"],
query: "home lab",
sort: "oldest",
})
})
it("should omit defaults so /blog stays clean", () => {
const params = new URLSearchParams()
writeFilterParams(params, state())
expect(params.toString()).toBe("")
})
it("should case-fold and dedupe tags when parsing", () => {
const parsed = parseFilterParams(new URLSearchParams("tags=Docker,docker,,astro"))
expect(parsed.tags).toEqual(["docker", "astro"])
})
it("should fall back to defaults for junk values", () => {
const parsed = parseFilterParams(new URLSearchParams("sort=random&tags=%20%20"))
expect(parsed.sort).toBe(DEFAULT_SORT)
expect(parsed.tags).toEqual([])
})
it("should ignore a missing sort entirely", () => {
expect(parseFilterParams(new URLSearchParams("q=x")).query).toBe("x")
})
})
-20
View File
@@ -23,26 +23,6 @@ export function byDateDesc(a: DatedEntry, b: DatedEntry): number {
return diff !== 0 ? diff : a.id.localeCompare(b.id)
}
/**
* Tag filter shared by the Blog and Projects islands (their logic was
* byte-identical duplicates of each other).
*
* AND semantics: an entry must carry *every* selected tag, so adding a second
* tag narrows the result set rather than unioning it. Case-insensitive on both
* sides. Lives here (not in the islands) because the memo now runs during SSR,
* so a throw on a malformed entry would be a 500 rather than an empty list —
* and because this is the behavior worth asserting directly.
*/
export function filterByTags<T extends { tags: string[] }>(
entries: T[],
selected: Iterable<string>
): T[] {
const wanted = Array.from(selected, (value) => String(value).toLowerCase())
return entries.filter((entry) =>
wanted.every((tag) => entry.tags.some((entryTag) => entryTag.toLowerCase() === tag))
)
}
/**
* Map a blog or project content entry down to the slim, serializable shape
* used by ArrowCard and the search index. Centralising this keeps every page
+184
View File
@@ -0,0 +1,184 @@
// 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)
}
+20 -4
View File
@@ -41,11 +41,27 @@ export interface SearchEntry {
}
/**
* Shape accepted by ArrowCard. A union so the cards on the blog/projects
* listing pages (flat BlogPost/Project) and search results (SearchEntry,
* which carries `collection` + `slug`) both type-check.
* The fields a listing card and its filters actually read.
*
* Deliberately excludes the markdown `content`: the /blog and /projects islands
* serialized every entry's full body into the island's props on each request and
* never matched against it. `BlogPost`, `Project` and `SearchEntry` all satisfy
* this shape structurally, so cards and filters accept any of them.
*/
export type CardEntry = BlogPost | Project | SearchEntry
export interface ListEntry {
id: string;
title: string;
summary: string;
date: string;
tags: string[];
}
/**
* Shape accepted by ArrowCard. A union so the cards on the blog/projects
* listing pages (flat ListEntry) and search results (SearchEntry, which
* carries `collection` + `slug`) both type-check.
*/
export type CardEntry = ListEntry | SearchEntry
export interface WorkExperience {
id: string;
+10 -8
View File
@@ -3,26 +3,28 @@ import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro"
import Blog from "@components/Blog"
import FilteredList from "@components/FilteredList"
import { BLOG } from "@consts"
import { byDateDesc } from "@lib/content"
import { parseFilterParams } from "@lib/filters"
const entries = await getCollection("blog", ({ data }) => !data.draft)
// Only the fields the cards and the filters read. `content` was serialized into
// the island's props on every request and never matched against — the markdown
// body is the single largest thing on this page.
const posts = entries
.sort(byDateDesc)
.map((entry) => ({
id: entry.id,
slug: entry.id,
title: entry.data.title,
summary: entry.data.summary,
date: entry.data.date.toISOString(),
tags: entry.data.tags,
draft: entry.data.draft,
content: entry.body ?? "",
template: entry.data.template,
featured: entry.data.featured,
}))
const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
// Frontmatter runs on the server, so the initial filter state has to come from
// the request URL rather than `window.location` (see src/pages/search/index.astro).
const initial = parseFilterParams(Astro.url.searchParams)
---
<PageLayout title={BLOG.TITLE} description={BLOG.DESCRIPTION}>
@@ -33,7 +35,7 @@ const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
</TopLayout>
<BottomLayout>
<div class="animate">
<Blog client:load tags={tags} data={posts} />
<FilteredList client:load collection="blog" entries={posts} initial={initial} />
</div>
</BottomLayout>
</PageLayout>
+9 -9
View File
@@ -3,26 +3,26 @@ import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro"
import Projects from "@components/Projects"
import FilteredList from "@components/FilteredList"
import { PROJECTS } from "@consts"
import { byDateDesc } from "@lib/content"
import { parseFilterParams } from "@lib/filters"
const entries = await getCollection("projects", ({ data }) => !data.draft)
const posts = entries
// Only the fields the cards and the filters read; see src/pages/blog/index.astro.
const projects = entries
.sort(byDateDesc)
.map((entry) => ({
id: entry.id,
slug: entry.id,
title: entry.data.title,
summary: entry.data.summary,
date: entry.data.date.toISOString(),
tags: entry.data.tags,
draft: entry.data.draft,
content: entry.body ?? "",
demoUrl: entry.data.demoUrl,
repoUrl: entry.data.repoUrl,
}))
const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
// Frontmatter runs on the server, so the initial filter state has to come from
// the request URL rather than `window.location` (see src/pages/search/index.astro).
const initial = parseFilterParams(Astro.url.searchParams)
---
<PageLayout title={PROJECTS.TITLE} description={PROJECTS.DESCRIPTION}>
@@ -33,7 +33,7 @@ const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
</TopLayout>
<BottomLayout>
<div class="animate">
<Projects client:load tags={tags} data={posts} />
<FilteredList client:load collection="projects" entries={projects} initial={initial} />
</div>
</BottomLayout>
</PageLayout>