Files
Spaghet.io/src/components/Search.tsx
T
spaghet 9e157a4fa3 feat(theme): implement dual light/dark colour token system with WCAG AA contrast
Replace hard-coded hex values and ad-hoc `dark:` variants with a single
semantic token layer in `src/styles/global.css` (`@theme` + `html.dark`
re-declaration), so every component uses the same Tailwind class list in
both modes.

Key changes:
- Define semantic tokens (page, surface, ink, accent, edge, etc.) and raw
  ingredient palette (--color-spaghetti-*, --color-marinara*, etc.)
- Configure dual Shiki themes (light-plus / everforest-dark) with
  `defaultColor: false` for proper per-mode code block colours, replacing
  the old `.prose pre { #1f2937 !important }` hack
- Tint background particles to match the warm cream/espresso palette
  instead of pure black dots
- Document theme rules: add tokens not `dark:` variants, keep colour rules
  inside `@layer`, never target Tailwind utility classes with unlayered
  overrides, route prose colours through `--tw-prose-*` only

All text and interactive elements meet WCAG AA contrast (4.5:1 body, 3:1
large/interactive). Light mode is a warm cream plate with white cards; dark
mode is espresso (#140C08) with raised cards.
2026-11-12 20:48:10 -05:00

196 lines
6.9 KiB
TypeScript

import { createEffect, createSignal, onCleanup, onMount } from "solid-js"
import ArrowCard from "@components/ArrowCard"
import {
createSearcher,
partitionByCollection,
runSearch,
MIN_QUERY_LENGTH,
type SearchEntry,
} from "@lib/search"
type Props = {
query?: string
/** Slim searchable entries serialized by src/pages/search/index.astro */
entries?: SearchEntry[]
}
const QUERY_PARAM = "search"
const DEBOUNCE_MS = 300
export default function Search(props: Props) {
const [query, setQuery] = createSignal(props.query || "")
const [results, setResults] = createSignal<{ posts: SearchEntry[]; projects: SearchEntry[] }>({ posts: [], projects: [] })
const [searched, setSearched] = createSignal(false)
const [loading, setLoading] = createSignal(false)
const [error, setError] = createSignal<string | null>(null)
// Build the fuzzy index once per hydration; keystrokes reuse it.
const searcher = createSearcher(props.entries || [])
// Debounce timer reference (browser-safe type; `NodeJS.Timeout` leaks
// Node types into a client component).
let debounceTimer: ReturnType<typeof setTimeout> | null = null
/**
* Mirror the active query into the URL so refresh, back/forward and sharing
* all restore the same result set. `replaceState` keeps history tidy while
* typing; explicit submits push a real entry.
*/
const syncUrl = (q: string, push = false) => {
// Guard: this component is SSR'd, and history APIs are unavailable there.
if (typeof window === "undefined") return
const url = new URL(window.location.href)
if (q.trim().length >= MIN_QUERY_LENGTH) {
url.searchParams.set(QUERY_PARAM, q)
} else {
url.searchParams.delete(QUERY_PARAM)
}
if (push) {
window.history.pushState({}, "", url.toString())
} else {
window.history.replaceState({}, "", url.toString())
}
}
createEffect(() => {
const q = query()
if (q.trim().length < MIN_QUERY_LENGTH) {
if (debounceTimer) clearTimeout(debounceTimer)
setResults({ posts: [], projects: [] })
setSearched(false)
setLoading(false)
setError(null)
return
}
if (debounceTimer) clearTimeout(debounceTimer)
setLoading(true)
debounceTimer = setTimeout(() => {
try {
const matched = runSearch(searcher, q)
setResults(partitionByCollection(matched))
setSearched(true)
setError(null)
// Keep the address bar in sync so the current results are shareable
// and survive a refresh.
syncUrl(q)
} catch (err) {
console.error("Search error:", err)
setResults({ posts: [], projects: [] })
setSearched(true)
setError("Search failed. Please try again.")
} finally {
setLoading(false)
}
}, DEBOUNCE_MS)
})
// Restore the query when the user navigates with browser back/forward.
const onPopState = () => {
setQuery(new URL(window.location.href).searchParams.get(QUERY_PARAM) || "")
}
// IMPORTANT: this component is SSR'd (output: "server" + client:load). The
// component body runs on the server AND Solid runs onCleanup during server
// teardown, while onMount never runs on the server. So every browser-API
// touchpoint must either live in onMount or be gated by `popStateBound`.
let popStateBound = false
onMount(() => {
window.addEventListener("popstate", onPopState)
popStateBound = true
})
const onInput = (e: Event) => {
const target = e.target as HTMLInputElement
setQuery(target.value)
}
const handleSubmit = (e: Event) => {
e.preventDefault()
// Never let the browser do a full page reload; the createEffect re-runs
// the search and syncUrl keeps the address bar shareable.
if (query().trim().length >= MIN_QUERY_LENGTH) {
syncUrl(query(), true)
}
}
// Cleanup the debounce timer (safe on server) and the history listener,
// which is only ever bound in the browser.
onCleanup(() => {
if (debounceTimer) clearTimeout(debounceTimer)
if (popStateBound) window.removeEventListener("popstate", onPopState)
})
return (
<div class="flex flex-col">
<form onSubmit={handleSubmit} class="relative" classList={{ "animate-pulse": loading() }}>
<input
name="search"
type="text"
value={query()}
onInput={onInput}
autocomplete="off"
spellcheck={false}
placeholder="What are you looking for?"
class="w-full px-2.5 py-1.5 pl-10 rounded outline-none text-ink bg-chip border border-edge focus:border-link"
/>
<svg class="absolute size-6 left-1.5 top-1/2 -translate-y-1/2 stroke-current">
<use href={`/ui.svg#search`}/>
</svg>
</form>
{error() && <div class="mt-4 text-status-down">{error()}</div>}
{loading() && <div class="mt-4">Searching...<span class="ml-2 animate-spin">⏳</span></div>}
{!loading() && !error() && !searched() && query().trim().length > 0 && query().trim().length < MIN_QUERY_LENGTH && (
<div class="mt-4 text-sm uppercase text-ink-muted">
Keep typing — search needs at least {MIN_QUERY_LENGTH} characters
</div>
)}
{!loading() && !error() && searched() && results().posts.length + results().projects.length === 0 && (
<div class="mt-12">
<div class="text-sm uppercase mb-2">
No results for {`'${query()}'`}
</div>
<div class="text-sm text-ink-muted">
Try a shorter or more general keyword — titles, tags and summaries are all searchable.
</div>
</div>
)}
{(searched() && (results().posts.length > 0 || results().projects.length > 0)) && (
<div class="mt-12">
<div class="text-sm uppercase mb-2">
Found {results().posts.length + results().projects.length} results for {`'${query()}'`}
</div>
<div class="flex flex-col gap-6 mt-4">
{results().posts.length > 0 && (
<div class="border-t border-line pt-4">
<div class="text-sm font-bold mb-2">Blog Posts</div>
<ul class="flex flex-col gap-3">
{results().posts.map(result => (
<li>
<ArrowCard entry={result} pill={true} collection={'blog'} />
</li>
))}
</ul>
</div>
)}
{results().projects.length > 0 && (
<div class="border-t border-line pt-4">
<div class="text-sm font-bold mb-2">Projects</div>
<ul class="flex flex-col gap-3">
{results().projects.map(result => (
<li>
<ArrowCard entry={result} pill={true} collection={'projects'} />
</li>
))}
</ul>
</div>
)}
</div>
</div>
)}
</div>
)
}