From cb9d025687938ee7b207aefcb02f1d7f73c5fba6 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Mon, 30 Nov 2026 09:49:52 -0500 Subject: [PATCH 1/2] Load the search palette's episodes when it opens, from a slim endpoint The palette fetched /api/episodes/search.json on every page as it hydrated: about 2 MB, most of it show-notes HTML the palette never reads. It now fetches /api/palette.json (only the fields it matches on and shows) the first time it opens, or when a search trigger is pointed at or focused. A query typed before the episodes land is answered once they do, with "Searching..." in place of "Nothing found" meanwhile. The public search.json is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../starpod/src/components/SearchButton.tsx | 10 +++++- .../starpod/src/components/SearchDialog.tsx | 30 +++++++++-------- .../src/components/palette-episodes.ts | 25 +++++++++++++++ packages/starpod/src/index.ts | 3 +- .../starpod/src/pages/api/palette.json.ts | 31 ++++++++++++++++++ tests/e2e/shell.spec.ts | 21 ++++++++++++ tests/unit/SearchDialog.test.tsx | 32 +++++++++++++++++++ 7 files changed, 137 insertions(+), 15 deletions(-) create mode 100644 packages/starpod/src/components/palette-episodes.ts create mode 100644 packages/starpod/src/pages/api/palette.json.ts diff --git a/packages/starpod/src/components/SearchButton.tsx b/packages/starpod/src/components/SearchButton.tsx index 965cb366..1ace3fe0 100644 --- a/packages/starpod/src/components/SearchButton.tsx +++ b/packages/starpod/src/components/SearchButton.tsx @@ -1,10 +1,14 @@ import { SearchIcon } from './icons'; +import { loadPaletteEpisodes } from './palette-episodes'; import { isSearchOpen } from './state'; type Props = { variant?: 'rail' | 'tab' }; // Every trigger is marked so the palette can grow out of whichever is on -// screen, and return to it. +// screen, and return to it. Pointing at one or focusing it fetches the +// palette's episodes, so they are usually there by the time it opens. +const prefetch = () => void loadPaletteEpisodes().catch(() => {}); + export default function SearchButton({ variant = 'rail' }: Props) { if (variant === 'tab') { return ( @@ -12,6 +16,8 @@ export default function SearchButton({ variant = 'rail' }: Props) { aria-label="Search episodes" data-search-trigger onClick={() => (isSearchOpen.value = true)} + onFocus={prefetch} + onPointerEnter={prefetch} type="button" > @@ -26,6 +32,8 @@ export default function SearchButton({ variant = 'rail' }: Props) { class="search-trigger halo flex w-full cursor-pointer items-center gap-[0.6rem] rounded-full border border-line bg-ground px-3 py-[0.6rem] text-md text-muted transition-[color] duration-200 ease-out hover:text-text" data-search-trigger onClick={() => (isSearchOpen.value = true)} + onFocus={prefetch} + onPointerEnter={prefetch} type="button" > diff --git a/packages/starpod/src/components/SearchDialog.tsx b/packages/starpod/src/components/SearchDialog.tsx index b07f4da3..65c92e64 100644 --- a/packages/starpod/src/components/SearchDialog.tsx +++ b/packages/starpod/src/components/SearchDialog.tsx @@ -10,7 +10,7 @@ import { navigate } from 'astro:transitions/client'; import { flipFrom, layoutRect, nudge, reducedMotion } from '../motion/propflip'; import { isSearchOpen, islandAt, islandBack } from './state'; import { personFact } from '../lib/cast'; -import type { Episode } from '../lib/rss'; +import { loadPaletteEpisodes, type PaletteEpisode } from './palette-episodes'; /** A host or guest, as the explorer's With filter lists them. */ export interface PalettePerson { @@ -25,7 +25,7 @@ export interface PalettePerson { type Item = | { kind: 'person'; key: string; person: PalettePerson } - | { kind: 'episode'; key: string; episode: Episode }; + | { kind: 'episode'; key: string; episode: PaletteEpisode }; /** A row's element id, stable across re-filters, for the input's * aria-activedescendant. */ @@ -73,7 +73,7 @@ export default function SearchDialog({ people?: Array; }) { const [query, setQuery] = useState(''); - const [episodes, setEpisodes] = useState([]); + const [episodes, setEpisodes] = useState(); const [selectedIndex, setSelectedIndex] = useState(0); // Mounted from opening until the panel has flown back into its trigger. const [mounted, setMounted] = useState(false); @@ -85,13 +85,13 @@ export default function SearchDialog({ const leaving = useRef(false); const open = isSearchOpen.value; - // Load episodes as the island hydrates (not after a painted frame). + // Load episodes when the palette first opens. Whatever was typed by the + // time they land is matched against them then. useLayoutEffect(() => { - fetch('/api/episodes/search.json') - .then((res) => res.json()) - .then((data) => setEpisodes(data)) - .catch(console.error); - }, []); + if (open) { + loadPaletteEpisodes().then(setEpisodes).catch(console.error); + } + }, [open]); // Before typing: the people most on the show. Typing: up to three people // whose names match, then up to eight episodes. @@ -101,7 +101,7 @@ export default function SearchDialog({ key: `p:${person.value}`, person }); - const asEpisode = (episode: Episode): Item => ({ + const asEpisode = (episode: PaletteEpisode): Item => ({ kind: 'episode', key: `e:${episode.id}`, episode @@ -110,14 +110,14 @@ export default function SearchDialog({ if (!lowerQuery) { return people.length ? people.slice(0, 6).map(asPerson) - : episodes.slice(0, 8).map(asEpisode); + : (episodes ?? []).slice(0, 8).map(asEpisode); } return [ ...people .filter((person) => person.label.toLowerCase().includes(lowerQuery)) .slice(0, 3) .map(asPerson), - ...episodes + ...(episodes ?? []) .filter( (episode) => episode.title.toLowerCase().includes(lowerQuery) || @@ -382,7 +382,11 @@ export default function SearchDialog({ > {items.length === 0 ? (
- {query ? 'Nothing found' : 'Start typing to search episodes...'} + {query + ? episodes + ? 'Nothing found' + : 'Searching...' + : 'Start typing to search episodes...'}
) : ( <> diff --git a/packages/starpod/src/components/palette-episodes.ts b/packages/starpod/src/components/palette-episodes.ts new file mode 100644 index 00000000..c14ef4b9 --- /dev/null +++ b/packages/starpod/src/components/palette-episodes.ts @@ -0,0 +1,25 @@ +import type { Episode } from '../lib/rss'; + +/** What the search palette matches on and shows of an episode. */ +export type PaletteEpisode = Pick< + Episode, + | 'id' + | 'title' + | 'description' + | 'episodeNumber' + | 'episodeSlug' + | 'episodeThumbnail' +>; + +let loading: Promise | undefined; + +/** The palette's episodes, fetched once for the visit when first wanted. */ +export function loadPaletteEpisodes(): Promise { + loading ??= fetch('/api/palette.json') + .then((res) => res.json() as Promise) + .catch((error: unknown) => { + loading = undefined; + throw error; + }); + return loading; +} diff --git a/packages/starpod/src/index.ts b/packages/starpod/src/index.ts index 5dfd308b..8d35c03e 100644 --- a/packages/starpod/src/index.ts +++ b/packages/starpod/src/index.ts @@ -148,7 +148,8 @@ const ROUTES: Array<{ pattern: string; entrypoint: string }> = [ { pattern: '/api/episodes/search.json', entrypoint: 'api/episodes/search.json.ts' - } + }, + { pattern: '/api/palette.json', entrypoint: 'api/palette.json.ts' } ]; const MISSING_CONFIG_MESSAGE = `[starpod] Missing podcast config. diff --git a/packages/starpod/src/pages/api/palette.json.ts b/packages/starpod/src/pages/api/palette.json.ts new file mode 100644 index 00000000..987faaea --- /dev/null +++ b/packages/starpod/src/pages/api/palette.json.ts @@ -0,0 +1,31 @@ +import type { APIRoute } from 'astro'; +import type { PaletteEpisode } from '../../components/palette-episodes'; +import { getAllEpisodes } from '../../lib/rss'; + +export const prerender = true; + +export const GET: APIRoute = async () => { + const episodes: PaletteEpisode[] = (await getAllEpisodes()).map( + ({ + id, + title, + description, + episodeNumber, + episodeSlug, + episodeThumbnail + }) => ({ + id, + title, + description, + episodeNumber, + episodeSlug, + episodeThumbnail + }) + ); + + return new Response(JSON.stringify(episodes), { + headers: { + 'Content-Type': 'application/json' + } + }); +}; diff --git a/tests/e2e/shell.spec.ts b/tests/e2e/shell.spec.ts index 5397ec52..a82d2d4e 100644 --- a/tests/e2e/shell.spec.ts +++ b/tests/e2e/shell.spec.ts @@ -751,6 +751,27 @@ test.describe('skip links', () => { test.describe('search palette', () => { test.use({ viewport: { width: 1440, height: 900 } }); + test('loads its episodes only once it opens', async ({ page }) => { + const asked: Array = []; + page.on('request', (request) => { + if (/\/api\/(palette|episodes\/search)\.json/.test(request.url())) { + asked.push(new URL(request.url()).pathname); + } + }); + for (const path of ['/about', '/']) { + await page.goto(path); + await hydrated(page); + await page.waitForLoadState('networkidle'); + } + expect(asked).toEqual([]); + + await page.keyboard.press('ControlOrMeta+k'); + const input = page.getByPlaceholder('Search episodes...'); + await input.fill('css'); + await expect(page.getByRole('option').first()).toContainText(/css/i); + expect(asked).toEqual(['/api/palette.json']); + }); + test('opens from the rail, filters, and returns focus on close', async ({ page }) => { diff --git a/tests/unit/SearchDialog.test.tsx b/tests/unit/SearchDialog.test.tsx index 9c76111d..b78eaea4 100644 --- a/tests/unit/SearchDialog.test.tsx +++ b/tests/unit/SearchDialog.test.tsx @@ -68,6 +68,38 @@ describe('SearchDialog', () => { vi.mocked(navigate).mockClear(); }); + it('fetches episodes only once opened, and answers what was typed meanwhile', async () => { + // A fresh module graph, so no earlier test has loaded the episodes. + vi.resetModules(); + const { default: FreshDialog } = await import( + 'starpod/src/components/SearchDialog' + ); + const { isSearchOpen: freshOpen } = await import( + 'starpod/src/components/state' + ); + let land = (_episodes: typeof mockEpisodes) => {}; + global.fetch = vi.fn().mockResolvedValue({ + json: () => new Promise((resolve) => (land = resolve)) + }); + freshOpen.value = false; + render(); + expect(global.fetch).not.toHaveBeenCalled(); + + fireEvent.keyDown(document, { key: 'k', metaKey: true }); + const input = await screen.findByPlaceholderText('Search episodes...'); + expect(global.fetch).toHaveBeenCalledTimes(1); + fireEvent.input(input, { target: { value: 'Different' } }); + expect(await screen.findByText('Searching...')).toBeInTheDocument(); + + land(mockEpisodes); + await waitFor(() => + expect( + screen.getAllByRole('option').map((option) => option.textContent) + ).toEqual([expect.stringContaining('Different Title')]) + ); + freshOpen.value = false; + }); + it('renders nothing when search is closed', () => { isSearchOpen.value = false; const { container } = render(); From 7bde971252c6f4ba5d2713c007cf8e9817a9fee1 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Mon, 30 Nov 2026 10:35:07 -0500 Subject: [PATCH 2/2] Treat a failed palette.json response as a failed load An error status with a JSON body would otherwise be stored as the episode list and break the palette on its next render. Throwing clears the cached promise, so the next open asks again. Co-Authored-By: Claude Opus 5.5 --- packages/starpod/src/components/palette-episodes.ts | 7 ++++++- tests/unit/SearchDialog.test.tsx | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/starpod/src/components/palette-episodes.ts b/packages/starpod/src/components/palette-episodes.ts index c14ef4b9..c9fecd1a 100644 --- a/packages/starpod/src/components/palette-episodes.ts +++ b/packages/starpod/src/components/palette-episodes.ts @@ -16,7 +16,12 @@ let loading: Promise | undefined; /** The palette's episodes, fetched once for the visit when first wanted. */ export function loadPaletteEpisodes(): Promise { loading ??= fetch('/api/palette.json') - .then((res) => res.json() as Promise) + .then((res) => { + if (!res.ok) { + throw new Error(`palette.json: ${res.status}`); + } + return res.json() as Promise; + }) .catch((error: unknown) => { loading = undefined; throw error; diff --git a/tests/unit/SearchDialog.test.tsx b/tests/unit/SearchDialog.test.tsx index b78eaea4..158422c8 100644 --- a/tests/unit/SearchDialog.test.tsx +++ b/tests/unit/SearchDialog.test.tsx @@ -59,6 +59,7 @@ describe('SearchDialog', () => { beforeEach(() => { isSearchOpen.value = false; global.fetch = vi.fn().mockResolvedValue({ + ok: true, json: () => Promise.resolve(mockEpisodes) }); }); @@ -79,6 +80,7 @@ describe('SearchDialog', () => { ); let land = (_episodes: typeof mockEpisodes) => {}; global.fetch = vi.fn().mockResolvedValue({ + ok: true, json: () => new Promise((resolve) => (land = resolve)) }); freshOpen.value = false;