();
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();