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(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 | 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 (
{error() &&
{error()}
} {loading() &&
Searching...⏳
} {!loading() && !error() && !searched() && query().trim().length > 0 && query().trim().length < MIN_QUERY_LENGTH && (
Keep typing — search needs at least {MIN_QUERY_LENGTH} characters
)} {!loading() && !error() && searched() && results().posts.length + results().projects.length === 0 && (
No results for {`'${query()}'`}
Try a shorter or more general keyword — titles, tags and summaries are all searchable.
)} {(searched() && (results().posts.length > 0 || results().projects.length > 0)) && (
Found {results().posts.length + results().projects.length} results for {`'${query()}'`}
{results().posts.length > 0 && (
Blog Posts
    {results().posts.map(result => (
  • ))}
)} {results().projects.length > 0 && (
Projects
    {results().projects.map(result => (
  • ))}
)}
)}
) }