Files
Spaghet.io/HANDOFF-search-fix.md
T
spaghet 3fef5d378e chore(deps): upgrade tailwind to v4 via vite plugin
Replace @astrojs/tailwind with @tailwindcss/vite in the Astro config and lockfile to adopt Tailwind CSS v4 and simplify the build setup. Also update Markdown site content with current SpaghetAI/MarvinBlade infrastructure details.
2026-11-04 12:31:58 -05:00

148 lines
7.5 KiB
Markdown

# Task Handoff — Search Function Fix (Astro / Spaghet.io)
## TL;DR
The `/search` page had **two** root causes, both now fixed and verified in the
working tree. `astro check` → 0 errors, `npm test` → 11/11 pass,
`astro build` → exit 0. Remaining work is **browser confirmation** and a
**separate production-deploy problem** (see "Not done").
Complexity: **Standard** track. Repo: brownfield Astro 7.3.8 + Solid 1.9.17,
`output: "server"` with `@astrojs/node` SSR adapter.
## Root causes found
1. **`?search=` URL param was never read.** `src/pages/search/index.astro`
used `new URL(typeof window !== 'undefined' ? window.location.href :
'http://localhost')`. Astro frontmatter runs on the **server**, so `window`
is always undefined → it always fell back to a query-less localhost URL.
Refresh, share, and back/forward silently produced an empty search.
Fixed to `Astro.url.searchParams.get("search") ?? ""`.
2. **Zero-match queries rendered nothing at all.** The result block was gated
on `query().length >= 2 && (posts.length > 0 || projects.length > 0)`, so a
search with no hits showed a blank page — indistinguishable from a crash.
Added explicit "No results for '…'" and "Keep typing…" states.
3. (Bonus, real) **Full markdown `body` was serialized into the island's
`props`** — 21,873 chars / 43,572-byte page — while the filter only matched
title/summary/tags. Removed.
## ⚠️ The trap that caused a 500 (read this before touching Search.tsx)
`output: "server"` + `client:load` means the **Solid component body executes on
the server**, and Solid also runs `onCleanup` during **server teardown**. So:
- Top-level `window.addEventListener(...)` in the body → `ReferenceError:
window is not defined` → 500.
- `window.removeEventListener(...)` inside `onCleanup` → **also** throws on the
server. This was my own regression and is why `/search` briefly 500'd.
Rules now encoded in the file:
- Browser API access lives in `onMount` (never runs on server), **or** is
gated by the `popStateBound` flag inside `onCleanup`.
- `syncUrl()` has a `typeof window === "undefined"` guard.
- Also: JSX text is assigned via `textContent`, so HTML entities like
`—` render literally. Use real `—` characters in JSX text.
## Files changed / added
| File | Change |
|---|---|
| `src/lib/search.ts` **(new)** | Fuse.js 7.1.0 wrapper: `createSearcher`, `runSearch`, `partitionByCollection`, `MIN_QUERY_LENGTH = 2`, weighted keys title .4 / tags .35 / summary .25, `threshold: 0.4`, `ignoreLocation: true` |
| `src/lib/content.ts` **(new)** | `toSearchEntry(entry)` — single mapper shared by every page that renders cards |
| `src/lib/types.ts` | Added `SearchEntry` + `CardEntry` union (source of truth for the type) |
| `src/pages/search/index.astro` | `Astro.url.searchParams` fix; emits slim `entries` prop |
| `src/components/Search.tsx` | Uses searcher; `searched` state flag; empty/short-query states; `syncUrl` (replaceState on debounce, pushState on submit); `onPopState` restore; `onMount` + `popStateBound`; `ReturnType<typeof setTimeout>` instead of `NodeJS.Timeout` |
| `src/components/ArrowCard.tsx` | Dropped `any` → `CardEntry`; resolves `collection` from entry **or** prop; `slug` fallback |
| `src/pages/index.astro` | Uses `toSearchEntry` (was emitting legacy `$id` + `Date`) |
| `src/lib/__tests__/search.test.ts` **(new)** | 11 unit tests |
| `vitest.config.ts` **(new)** | node env + `@lib`-style aliases mirroring tsconfig |
| `package.json` | Added `"test": "vitest run"`, `"test:watch": "vitest"` |
| `.clinerules/tool-catalog.md` **(new)** | Records the only real tools here (`editor`, `read_files`, `run_commands`, `search_codebase`, `ask_question`, `skills`, `fetch_web_content`, `searxng-*`). `.clinerules` is gitignored, so this is local-only. |
## Verified evidence
```
search?search=astro -> query prop [0,"astro"] ssr input value="astro" (was [0,""] / "")
island props -> 3,576 chars (was 21,873)
/search page -> 25,304 bytes (was 43,572)
/search / /blog -> HTTP 200, no ReferenceError in server log
homepage card hrefs -> /blog/01-…, /projects/astro-profile (no 404 regression)
astro check -> 0 errors, 0 warnings
npm test -> 11 passed
astro build -> exit 0
bundle Search.DxvATC7F.js contains "No results for", "Keep typing",
pushState, replaceState, popstate, Fuse 7.1.0
```
## How to reproduce the verification
```bash
cd "/home/spaghet/Documents/Spaghet.io"
npx astro build
node -e "import('./dist/server/entry.mjs').then(m=>m.startServer())" &
# fetch /search?search=astro, then parse the <astro-island props="..."> attribute
# (decode &quot; -> " and JSON.parse; keys should be [query, entries])
```
## NOT done — remaining work
1. **Browser-level confirmation (do this first).** No `jsdom`/`happy-dom`/
`playwright` is installed, so hydration and typing behaviour were verified
only indirectly (SSR markup, decoded props, module resolution, bundle
greps) — **not** by executing client JS. Load `/search`, type `astro`,
confirm results render, confirm the URL gains `?search=astro`, press
back/forward, and search `zzzq` to see "No results for 'zzzq'".
2. **Production is a different, stale build — SEPARATE ISSUE.**
`spaghet.io/search` → 307 → `home.spaghet.io/search/`, which serves
`Search.JqbiLQV3.js` (Fuse-based, single `data` prop, **8** docs — including
`02-appwrite-nginx-reverse-proxy-fix` and an `appwrite` project that no
longer exist in this repo). The local build emits `Search.DxvATC7F.js` with
an `entries` prop. Deploying `main` changes live behaviour; review the diff
first. No Dockerfile/CI in-repo — deploy is Gitea → GitHub → self-hosted →
NGINX (see README).
3. **Unrelated pre-existing dirt in the tree.** `src/styles/global.css`,
`tailwind.config.mjs`, `public/js/theme.js` and `astro.config.mjs` already
carried an uncommitted Tailwind v3→v4 migration before this task.
`tailwind.config.mjs` is orphaned under v4 unless `@config` is used.
**Do not bundle that into the search commit** without asking.
4. **Body-content search was deliberately dropped** with the payload trim.
If wanted, add an API route (`src/pages/api/*`) — do not re-inflate island
props.
5. Consider whether `threshold: 0.4` fuzzy matching is too loose for short
queries (it now matches typos, e.g. `websit` → match). Tune in
`src/lib/search.ts`.
## Suggested commit (NOT executed)
```
fix(search): read SSR query param, add empty states, slim island payload
- Use Astro.url.searchParams instead of window (unavailable in SSR) so
?search= deep links, refreshes and back/forward restore results
- Render explicit "No results" / "Keep typing" states instead of blank page
- Move search logic to src/lib/search.ts with Fuse.js fuzzy matching
- Stop serializing markdown bodies into island props (43.5 KB -> 25.3 KB)
- Guard browser APIs behind onMount; onCleanup previously threw during SSR
teardown and 500'd /search
- Add 11 vitest unit tests + test script + vitest.config.ts aliases
```
Delete this file once the handoff is consumed.
Caveats learned the hard way:
- `astro dev` backgrounded from the agent shell gets **reaped between tool
calls**; starting the built server and curling it in the *same* command works.
- `astro dev` may print "Another astro dev server is already running" →
`npx astro dev stop`.
- `node -e "import('./dist/server/entry.mjs')"` alone exits silently — the
adapter only listens if you call `startServer()`.
- `vitest` 5 removed the `basic` reporter; use default or `dot`.