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..c9fecd1a --- /dev/null +++ b/packages/starpod/src/components/palette-episodes.ts @@ -0,0 +1,30 @@ +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) => { + if (!res.ok) { + throw new Error(`palette.json: ${res.status}`); + } + return 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..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) }); }); @@ -68,6 +69,39 @@ 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({ + ok: true, + 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();