Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/starpod/src/components/SearchButton.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
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 (
<button
aria-label="Search episodes"
data-search-trigger
onClick={() => (isSearchOpen.value = true)}
onFocus={prefetch}
onPointerEnter={prefetch}
type="button"
>
<SearchIcon />
Expand All @@ -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"
>
<SearchIcon size={18} />
Expand Down
30 changes: 17 additions & 13 deletions packages/starpod/src/components/SearchDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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. */
Expand Down Expand Up @@ -73,7 +73,7 @@ export default function SearchDialog({
people?: Array<PalettePerson>;
}) {
const [query, setQuery] = useState('');
const [episodes, setEpisodes] = useState<Episode[]>([]);
const [episodes, setEpisodes] = useState<PaletteEpisode[]>();
const [selectedIndex, setSelectedIndex] = useState(0);
// Mounted from opening until the panel has flown back into its trigger.
const [mounted, setMounted] = useState(false);
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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) ||
Expand Down Expand Up @@ -382,7 +382,11 @@ export default function SearchDialog({
>
{items.length === 0 ? (
<div class="text-text p-4 text-center">
{query ? 'Nothing found' : 'Start typing to search episodes...'}
{query
? episodes
? 'Nothing found'
: 'Searching...'
: 'Start typing to search episodes...'}
</div>
) : (
<>
Expand Down
30 changes: 30 additions & 0 deletions packages/starpod/src/components/palette-episodes.ts
Original file line number Diff line number Diff line change
@@ -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<PaletteEpisode[]> | undefined;

/** The palette's episodes, fetched once for the visit when first wanted. */
export function loadPaletteEpisodes(): Promise<PaletteEpisode[]> {
loading ??= fetch('/api/palette.json')
.then((res) => {
if (!res.ok) {
throw new Error(`palette.json: ${res.status}`);
}
return res.json() as Promise<PaletteEpisode[]>;
})
.catch((error: unknown) => {
loading = undefined;
throw error;
});
return loading;
}
3 changes: 2 additions & 1 deletion packages/starpod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
31 changes: 31 additions & 0 deletions packages/starpod/src/pages/api/palette.json.ts
Original file line number Diff line number Diff line change
@@ -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'
}
});
};
21 changes: 21 additions & 0 deletions tests/e2e/shell.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = [];
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
}) => {
Expand Down
34 changes: 34 additions & 0 deletions tests/unit/SearchDialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ describe('SearchDialog', () => {
beforeEach(() => {
isSearchOpen.value = false;
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(mockEpisodes)
});
});
Expand All @@ -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(<FreshDialog />);
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(<SearchDialog />);
Expand Down
Loading