Refactor components and add tests for improved functionality and coverage

This commit is contained in:
spaghet committed 2026-11-04 22:16:17 -05:00
1 parent bbb76eaa31
commit ab6cd7c162
13 files changed
+253 -54

No files matched your search

+12 -1
View File
@@ -12,6 +12,17 @@ export default defineConfig({
output: "server",
adapter: node({ mode: "ssr" }),
vite: {
plugins: [tailwindcss()]
plugins: [tailwindcss()],
optimizeDeps: {
// Client-island deps that are not reachable from the SSR entry graph are
// discovered mid-session, which makes Vite re-optimize and bump the browserHash.
// Every already-served island module then 504s with "Outdated Optimize Dep",
// hydration aborts, and the Solid lists on /blog, /projects and /search stay
// empty. Pre-declaring them bundles them at startup so the hash never changes
// underneath a page. Keep this list in sync with the imports of every
// src/components/*.tsx island (solid-js, @lib/utils -> clsx + tailwind-merge,
// @lib/search -> fuse.js).
include: ["solid-js", "solid-js/web", "clsx", "tailwind-merge", "fuse.js"],
},
}
})
+14 -19
View File
@@ -1,7 +1,8 @@
import type { BlogPost } from "@lib/types"
import { createEffect, createSignal, For } from "solid-js"
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[]
@@ -10,20 +11,12 @@ type Props = {
export default function Blog({ data, tags }: Props) {
const [filter, setFilter] = createSignal(new Set<string>())
const [posts, setPosts] = createSignal<BlogPost[]>([])
createEffect(() => {
setPosts(data.filter((entry) => {
// Filter by tags
const tagMatch = Array.from(filter()).every((value) =>
entry.tags.some((tag:string) =>
tag.toLowerCase() === String(value).toLowerCase()
)
)
return tagMatch
}))
})
// `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) =>
@@ -66,11 +59,13 @@ export default function Blog({ data, tags }: Props) {
SHOWING {posts().length} OF {data.length} POSTS
</div>
<ul class="flex flex-col gap-3">
{posts().map((post) => (
<li>
<ArrowCard entry={post} collection={'blog'} />
</li>
))}
<For each={posts()}>
{(post) => (
<li>
<ArrowCard entry={post} collection={'blog'} />
</li>
)}
</For>
</ul>
</div>
</div>
+3 -4
View File
@@ -1,15 +1,14 @@
---
import { SITE, LINKS } from "@consts"
import { cn } from "@lib/utils"
import { cn, ACTIVE_NAV_COLORS, isNavActive } from "@lib/utils"
const { pathname } = Astro.url
const subpath = pathname.match(/[^/]+/g)
---
<div id="drawer" class="fixed inset-0 h-0 z-40 overflow-hidden flex flex-col items-center justify-center md:hidden bg-spaghetti-cream dark:bg-black transition-[height] duration-300 ease-in-out">
<nav class="flex flex-col items-center space-y-2">
{
LINKS.map((LINK) => (
<a href={LINK.HREF} class={cn("flex items-center justify-center px-3 py-1 rounded-full", "text-current hover:text-black dark:hover:text-white", "hover:bg-spaghetti-yellow/20 dark:hover:bg-spaghetti-yellow/20", "transition-colors duration-300 ease-in-out", pathname === LINK.HREF || "/" + subpath?.[0] === LINK.HREF ? "pointer-events-none bg-spaghetti-red dark:bg-spaghetti-red text-spaghetti-brown dark:text-spaghetti-brown" : "")}>
<a href={LINK.HREF} class={cn("flex items-center justify-center px-3 py-1 rounded-full", "text-current hover:text-black dark:hover:text-white", "hover:bg-spaghetti-yellow/20 dark:hover:bg-spaghetti-yellow/20", "transition-colors duration-300 ease-in-out", isNavActive(pathname, LINK.HREF) && "pointer-events-none", isNavActive(pathname, LINK.HREF) && ACTIVE_NAV_COLORS)}>
{LINK.TEXT}
</a>
))
@@ -17,7 +16,7 @@ const subpath = pathname.match(/[^/]+/g)
</nav>
<div class="flex gap-1 mt-5">
<a href="/search" aria-label={`Search blog posts and projects on ${SITE.TITLE}`} class={cn("size-9 rounded-full p-2 items-center justify-center bg-transparent hover:bg-spaghetti-yellow/20 dark:hover:bg-spaghetti-yellow/20 stroke-current hover:stroke-black hover:dark:stroke-white border border-spaghetti-yellow/50 dark:border-spaghetti-yellow/50 transition-colors duration-300 ease-in-out", pathname === "/search" || "/" + subpath?.[0] === "search" ? "pointer-events-none bg-spaghetti-red dark:bg-spaghetti-red text-white dark:text-white" : "")}>
<a href="/search" aria-label={`Search blog posts and projects on ${SITE.TITLE}`} class={cn("size-9 rounded-full p-2 items-center justify-center bg-transparent hover:bg-spaghetti-yellow/20 dark:hover:bg-spaghetti-yellow/20 stroke-current hover:stroke-black hover:dark:stroke-white border border-spaghetti-yellow/50 dark:border-spaghetti-yellow/50 transition-colors duration-300 ease-in-out", isNavActive(pathname, "/search") && "pointer-events-none", isNavActive(pathname, "/search") && ACTIVE_NAV_COLORS)}>
<svg class="size-full">
<use href="/ui.svg#search"></use>
</svg>
+5 -6
View File
@@ -1,9 +1,8 @@
---
import { SITE, LINKS } from "@consts"
import { cn } from "@lib/utils"
const { pathname } = Astro.url
const subpath = pathname.match(/[^/]+/g)
import { cn, ACTIVE_NAV_COLORS, isNavActive } from "@lib/utils"
import Container from "@components/Container.astro"
const { pathname } = Astro.url
---
<header id="header" class="fixed top-0 w-full h-16 z-50 ">
@@ -22,7 +21,7 @@ import Container from "@components/Container.astro"
<nav class="hidden md:flex items-center justify-center text-sm gap-1">
{
LINKS.map((LINK) => (
<a href={LINK.HREF} class={cn("h-8 rounded-full px-3 text-current", "flex items-center justify-center", "transition-colors duration-300 ease-in-out", pathname === LINK.HREF || "/" + subpath?.[0] === LINK.HREF ? "bg-spaghetti-red dark:bg-spaghetti-cream text-black dark:text-spaghetti-brown" : "hover:bg-spaghetti-red/5 dark:hover:bg-spaghetti-red/20 hover:text-black dark:hover:text-white")}>
<a href={LINK.HREF} class={cn("h-8 rounded-full px-3 text-current", "flex items-center justify-center", "transition-colors duration-300 ease-in-out", isNavActive(pathname, LINK.HREF) ? ACTIVE_NAV_COLORS : "hover:bg-spaghetti-red/5 dark:hover:bg-spaghetti-red/20 hover:text-black dark:hover:text-white")}>
{LINK.TEXT}
</a>
))
@@ -31,7 +30,7 @@ import Container from "@components/Container.astro"
</div>
<div class="buttons absolute right-0 top-1/2 -translate-y-1/2 flex gap-1">
<a href="/search" aria-label={`Search blog posts and projects on ${SITE.TITLE}`} class={cn("hidden md:flex", "size-9 rounded-full p-2 items-center justify-center", "bg-transparent hover:bg-spaghetti-yellow dark:hover:bg-spaghetti-yellow", "stroke-current hover:stroke-black hover:dark:stroke-white", "border border-black/10 dark:border-white/25", "transition-colors duration-300 ease-in-out", pathname === "/search" || "/" + subpath?.[0] === "/search" ? "pointer-events-none bg-spaghetti-red dark:bg-spaghetti-red text-spaghetti-brown dark:text-spaghetti-brown" : "")}>
<a href="/search" aria-label={`Search blog posts and projects on ${SITE.TITLE}`} class={cn("hidden md:flex", "size-9 rounded-full p-2 items-center justify-center", "bg-transparent hover:bg-spaghetti-yellow dark:hover:bg-spaghetti-yellow", "stroke-current hover:stroke-black hover:dark:stroke-white", "border border-black/10 dark:border-white/25", "transition-colors duration-300 ease-in-out", isNavActive(pathname, "/search") && "pointer-events-none", isNavActive(pathname, "/search") && ACTIVE_NAV_COLORS)}>
<svg class="size-full">
<use href="/ui.svg#search"></use>
</svg>
@@ -52,7 +51,7 @@ import Container from "@components/Container.astro"
</svg>
</button>
<button id="header-drawer-button" aria-label={`Toggle drawer open and closed`} class={cn("flex md:hidden", "size-9 rounded-full p-2 items-center justify-center", "bg-spaghetti-red dark:bg-spaghetti-red", "stroke-current hover:stroke-black hover:dark:stroke-white text-spaghetti-brown dark:text-spaghetti-brown", "border border-black/10 dark:border-white/25", "transition-colors duration-300 ease-in-out")}>
<button id="header-drawer-button" aria-label={`Toggle drawer open and closed`} class={cn("flex md:hidden", "size-9 rounded-full p-2 items-center justify-center", ACTIVE_NAV_COLORS, "stroke-current hover:stroke-black", "border border-black/10 dark:border-white/25", "transition-colors duration-300 ease-in-out")}>
<svg id="drawer-open" class="size-full">
<use href="/ui.svg#menu"></use>
</svg>
+13 -17
View File
@@ -1,26 +1,20 @@
import type { Project } from "@lib/types"
import { createEffect, createSignal, For } from "solid-js"
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[] | any[]
data: Project[]
}
export default function Projects({ data, tags }: Props) {
const [filter, setFilter] = createSignal(new Set<string>())
const [projects, setProjects] = createSignal<Project[]>([])
createEffect(() => {
setProjects(data.filter((entry) =>
Array.from(filter()).every((value) =>
entry.tags.some((tag:string) =>
tag.toLowerCase() === String(value).toLowerCase()
)
)
))
})
// 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) =>
@@ -59,11 +53,13 @@ export default function Projects({ data, tags }: Props) {
SHOWING {projects().length} OF {data.length} PROJECTS
</div>
<ul class="flex flex-col gap-3">
{projects().map((project) => (
<li>
<ArrowCard entry={project} collection={'projects'} />
</li>
))}
<For each={projects()}>
{(project) => (
<li>
<ArrowCard entry={project} collection={'projects'} />
</li>
)}
</For>
</ul>
</div>
</div>
@@ -0,0 +1,83 @@
// 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"
/**
* 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.
*/
function post(id: string, tags: string[]): BlogPost {
return {
id,
title: `Post ${id}`,
summary: `Summary ${id}`,
date: "2026-01-01T00:00:00.000Z",
tags,
draft: false,
content: "",
template: "default",
featured: false,
}
}
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: "",
}
}
describe("Blog island (SSR render)", () => {
const data = [post("a", ["css", "html"]), post("b", ["css"]), post("c", ["html"])]
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}"`)
}
})
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 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>")
})
})
describe("Projects island (SSR render)", () => {
const data = [project("x", ["react"]), project("y", ["react", "rust"])]
it("should render every project in the server HTML", () => {
const html = renderToString(() => Projects({ data, tags: ["react", "rust"] }))
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()
})
})
+33 -1
View File
@@ -1,6 +1,6 @@
// src/lib/__tests__/content.test.ts
import { describe, it, expect } from "vitest"
import { byDateDesc } from "../content"
import { byDateDesc, filterByTags } from "../content"
/**
* Fixture factory rather than inline literals in every test: mirrors the shape
@@ -65,3 +65,35 @@ 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([])
})
})
+29 -1
View File
@@ -1,6 +1,6 @@
// src/lib/__tests__/utils.test.ts
import { describe, it, expect } from "vitest"
import { formatDate, readingTime } from "@lib/utils"
import { formatDate, readingTime, isNavActive } from "@lib/utils"
describe("formatDate", () => {
it("should render a frontmatter date exactly as authored when it is midnight UTC", () => {
@@ -21,3 +21,31 @@ describe("readingTime", () => {
expect(readingTime("<p>one two three</p>")).toBe("1 min read")
})
})
describe("isNavActive", () => {
it("should match an exact pathname", () => {
expect(isNavActive("/blog", "/blog")).toBe(true)
expect(isNavActive("/", "/")).toBe(true)
})
it("should match a nested route by its first path section", () => {
expect(isNavActive("/blog/some-post", "/blog")).toBe(true)
expect(isNavActive("/projects/tool", "/projects")).toBe(true)
})
it("should not match a different section", () => {
expect(isNavActive("/blog/some-post", "/projects")).toBe(false)
expect(isNavActive("/work", "/blog")).toBe(false)
})
it("should activate the search link on /search and its subpaths", () => {
// Regression: the drawer compared "/" + subpath[0] against the bare string
// "search", which could never be true, so the search pill never activated.
expect(isNavActive("/search", "/search")).toBe(true)
expect(isNavActive("/search/anything", "/search")).toBe(true)
})
it("should not treat the root path as a prefix for every link", () => {
expect(isNavActive("/blog", "/")).toBe(false)
})
})
+20
View File
@@ -23,6 +23,26 @@ 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
+3 -2
View File
@@ -18,8 +18,9 @@ export interface Project {
tags: string[];
draft: boolean;
content: string;
demoUrl: string;
repoUrl: string;
/** Optional in the content schema (`z.string().optional()`), so optional here too. */
demoUrl?: string;
repoUrl?: string;
}
/**
+25
View File
@@ -5,6 +5,31 @@ export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Colors for the active (current-page) nav pill, shared by Header.astro and
* Drawer.astro so the four copies cannot drift apart again.
*
* `text-black` is deliberate in both modes: global.css declares unlayered
* `.text-spaghetti-brown` / `.dark .text-spaghetti-brown` overrides, and
* unlayered CSS outranks every Tailwind layer, so a `dark:text-spaghetti-brown`
* class on a `dark:bg-spaghetti-cream` pill resolves to cream-on-cream (1.1:1).
*/
export const ACTIVE_NAV_COLORS = "bg-spaghetti-red dark:bg-spaghetti-cream text-black"
/**
* Whether a nav link is the active one: exact match, or the first path section
* of the current URL (so /blog/some-post highlights the /blog link).
*
* Shared by Header.astro and Drawer.astro. Note the drawer previously compared
* `"/" + subpath?.[0]` against the bare string `"search"`, which can never be
* true; every caller now passes the same href it renders.
*/
export function isNavActive(pathname: string, href: string): boolean {
if (pathname === href) return true
const section = pathname.match(/[^/]+/g)?.[0]
return section !== undefined && `/${section}` === href
}
export function formatDate(date: Date | string) {
if (typeof date === "string") date = new Date(date)
return Intl.DateTimeFormat("en-US", {
+10 -3
View File
@@ -191,9 +191,16 @@ body {
color: var(--spaghetti-dark-cream);
}
.bg-spaghetti-cream {
background-color: var(--spaghetti-cream);
}
/* NOTE: do not re-add an unlayered `.bg-spaghetti-cream` rule here. Unlayered CSS
outranks every Tailwind layer, so it silently beat `dark:bg-black` and left the
mobile drawer cream-on-white in dark mode. The Tailwind utility already resolves
to the same #FEF3C7 via --color-spaghetti-cream.
The `.text-spaghetti-*` rules above are unlayered too, so they must not be paired
with `dark:` variants: `.dark .text-spaghetti-brown` beats Tailwind's
`dark:text-*` utilities, which makes `dark:bg-spaghetti-cream
dark:text-spaghetti-brown` render cream-on-cream (1.1:1). Active nav pills use
plain `text-black` in both modes instead — see ACTIVE_NAV_COLORS in src/lib/utils.ts. */
body {
@apply relative flex flex-col;
+3
View File
@@ -1,11 +1,14 @@
// vitest.config.ts
import { defineConfig } from "vitest/config"
import { fileURLToPath } from "node:url"
import solid from "vite-plugin-solid"
// Mirrors the tsconfig path aliases so modules under test can import via @lib/...
const src = fileURLToPath(new URL("./src", import.meta.url))
export default defineConfig({
// Compiles Solid JSX for the island render tests; Astro uses the same plugin for the app.
plugins: [solid({ ssr: true })],
resolve: {
alias: {
"@lib": `${src}/lib`,