Files
CatoandClaude c59cd1dc11 refactor(palette): search as you type through searchkit's useSearchAsYouType (#380)
The command palette hand-rolled its own debounce, abort and stale-answer
drop. @bitbaum/searchkit/react's useSearchAsYouType does exactly that, and
the org rule is that a package capability is used, not re-implemented. The
local useSearch is gone; the palette keeps its cache (an earlier query
answers without a request), its keyboard behaviour and its rows.

What the reader sees: the last research results stay on screen while a
newer query loads instead of blanking out, the "All N results" count only
shows for the query actually answered, and a failed research search now
says so on the last row instead of failing silently.

package-plan.json binds CommandPalette.tsx to useSearchAsYouType under the
search block; README describes the new behaviour.

Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 08:40:56 +01:00

188 lines
6.4 KiB
TypeScript

'use client';
/**
* ⌘K: jump to any page, bottleneck, company, country or note.
*
* The shape is Loki's palette (components/shell/CommandPalette.tsx there):
* one input, one list, ↑↓ to move, Enter to open, Esc or a click outside to
* close. Pages match instantly from `palette.ts`; the research answers from
* /api/search, the same index behind /search, and the last row always opens
* the full results page for the query.
*/
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSearchAsYouType } from '@bitbaum/searchkit/react';
import { SEARCH_TYPE_LABEL, segments, type SearchResult } from '@/lib/search-types';
import { Highlight } from '@/components/portal/Highlight';
import { SearchIcon } from '@/components/portal/Mark';
import { searchHref } from '@/components/portal/search/shared';
import { searchEntries, type PaletteEntry } from './palette';
import { useDialog } from './use-dialog';
const DEBOUNCE_MS = 120;
const PAGE_LIMIT = 6;
/** The index's strongest groups; the last row opens every one of them. */
const GROUP_LIMIT = 6;
interface Row {
key: string;
href: string;
group: string;
title: React.ReactNode;
sub: React.ReactNode;
}
function pageRow(e: PaletteEntry): Row {
return { key: e.key, href: e.href, group: e.group, title: e.label, sub: e.hint };
}
/**
* Search as you type is searchkit's: each keystroke aborts the request before
* it and a late answer to an older query is dropped. While a newer query
* loads, the last answer stays on screen. What stays here is the cache, so
* backspacing to an earlier query costs no request.
*/
function useResearch(query: string) {
const cache = useRef(new Map<string, SearchResult>());
const search = useCallback(async (text: string, signal: AbortSignal) => {
const hit = cache.current.get(text);
if (hit) return hit;
const r = await fetch(`/api/search?q=${encodeURIComponent(text)}`, { signal });
if (!r.ok) throw new Error(`Search answered ${r.status}`);
const data = (await r.json()) as SearchResult;
cache.current.set(text, data);
return data;
}, []);
return useSearchAsYouType(query, search, { debounceMs: DEBOUNCE_MS, minLength: 2 });
}
export function CommandPalette({
entries,
onClose,
}: {
entries: readonly PaletteEntry[];
onClose: () => void;
}) {
const router = useRouter();
const id = useId();
const panel = useRef<HTMLDivElement>(null);
const input = useRef<HTMLInputElement>(null);
const [q, setQ] = useState('');
const [active, setActive] = useState(0);
const query = q.trim();
const { results: result, error } = useResearch(query);
/** The answer on screen may be for an earlier query while this one loads. */
const fresh = result?.query === query;
useDialog(panel, onClose, input);
const rows = useMemo<Row[]>(() => {
if (!query) return entries.map(pageRow);
const pages = searchEntries(entries, query).map((hit) => ({
...pageRow(hit.item),
title: <Highlight segments={segments(hit.item.label, hit.matches.label)} />,
}));
const research =
result?.groups.slice(0, GROUP_LIMIT).flatMap((g) =>
g.hits.map((hit) => ({
key: hit.id,
href: hit.href,
group: SEARCH_TYPE_LABEL[g.type].one,
title: <Highlight segments={hit.title} />,
sub: <Highlight segments={hit.snippet} />,
})),
) ?? [];
const all: Row = {
key: '__all',
href: searchHref(query),
group: 'Search',
title:
result && fresh ? `All ${result.total} results for “${query}”` : `Search for “${query}”`,
sub: error
? 'The research search did not answer. Open the full results page to try again.'
: 'Every bottleneck, company, country, policy, note and event.',
};
return [...pages.slice(0, PAGE_LIMIT), ...research, all];
}, [entries, query, result, fresh, error]);
const current = Math.min(active, rows.length - 1);
const go = (href: string) => {
onClose();
router.push(href);
};
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
setActive(Math.min(rows.length - 1, current + 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActive(Math.max(0, current - 1));
} else if (e.key === 'Enter') {
e.preventDefault();
const row = rows[current];
if (row) go(row.href);
}
};
useEffect(() => {
document.getElementById(`${id}-${current}`)?.scrollIntoView({ block: 'nearest' });
}, [id, current]);
return (
<div className="shell-overlay shell-palette-wrap">
<div className="shell-backdrop" aria-hidden onClick={onClose} />
<div
ref={panel}
role="dialog"
aria-modal="true"
aria-label="Search and jump"
className="shell-palette"
>
<div className="shell-palette-input">
<SearchIcon className="h-5 w-5 shrink-0 text-fg-tertiary" />
<input
ref={input}
value={q}
onChange={(e) => {
setQ(e.target.value);
setActive(0);
}}
onKeyDown={onKeyDown}
role="combobox"
aria-expanded="true"
aria-controls={`${id}-list`}
aria-activedescendant={rows.length ? `${id}-${current}` : undefined}
aria-label="Search pages and research"
placeholder="Jump to a page, or search ASML, EUV, quartz"
maxLength={200}
autoComplete="off"
spellCheck={false}
/>
<button type="button" className="shell-palette-close" onClick={onClose}>
Esc
</button>
</div>
<ul id={`${id}-list`} role="listbox" className="shell-palette-list">
{rows.map((row, i) => (
<li
key={row.key}
id={`${id}-${i}`}
role="option"
aria-selected={i === current}
className="shell-palette-row"
onMouseMove={() => setActive(i)}
onClick={() => go(row.href)}
>
<span className="shell-palette-row-title">{row.title}</span>
<span className="shell-palette-row-group">{row.group}</span>
<span className="shell-palette-row-sub">{row.sub}</span>
</li>
))}
</ul>
</div>
</div>
);
}