# Spotlight (/docs/spotlight)





<SpotlightDemoProvider />

`Spotlight` is a ⌘K menu that searches several domains at once (users, events, projects…) and runs commands. The kit owns the menu, the keyboard, the async plumbing and the layout. Each team owns its data: a **source** is a plain `search` function, so nothing assumes REST, GraphQL, a search engine or a caching library.

Open it with the bar below, or with <kbd>⌘J</kbd> (<kbd>Ctrl J</kbd> off macOS). ⌘K is taken by the docs' own search on this page. Type `mar`, `exam` or `room`:

* **Users** stream: the people you've worked with land at once, then the rest arrive two at a time.
* **Events** take 900 ms and show skeleton rows while they load.
* **Projects** stream in one by one, too.
* **Modules** and **Rooms** come from a single federated source.
* **Evaluations** fail on any query matching their name (`eval`), with a Retry row. `zzz` finds nothing at all.

Press <kbd>Tab</kbd> on a user to search within them (their projects and events), then on a project for its attempts; on any other row, Tab searches only its group. Start the query with `@ ` (users), `# ` (projects) or `> ` (commands) to do the same by typing: the "Search in" rows on an empty query list every prefix. See [Scoping](#scoping).

<Preview align="center" code="null">
  <SpotlightTrigger />
</Preview>

## Setup [#setup]

`createSpotlight(config)` returns a bound `spotlight` object, a `<SpotlightProvider />`, and the hooks. They all share one store. Call it once in a `"use client"` module:

```tsx title="app/spotlight.tsx"
'use client';
import { createSpotlight, staticSource } from '@42-central/ui-react/spotlight';
import { usersSource, eventsSource } from './sources';

const commands = staticSource({
  id: 'commands',
  label: 'Commands',
  minQueryLength: 0, // also shown on an empty query
  items: [{ id: 'theme', title: 'Toggle theme', shortcut: ['⌘', 'T'], onSelect: toggleTheme }],
});

export const {
  spotlight,
  SpotlightProvider,
  useSpotlight,
  useSpotlightSource,
  SpotlightSources,
  useSpotlightPath,
  SpotlightPath,
} =
  createSpotlight({
    sources: [usersSource, eventsSource, commands],
    hotkey: 'mod+k', // ⌘K on macOS, Ctrl+K elsewhere; false binds none
    recents: { limit: 5, storageKey: '42-spotlight-recents' }, // false to disable
    placeholder: 'Search 42…',
  });
```

Mount `<SpotlightProvider />` once near the root, inside your `LinkComponentProvider`. It binds the hotkey and renders the menu, and nothing is rendered until the menu opens:

```tsx title="app/layout.tsx"
<LinkComponentProvider component={Link}>
  <SpotlightProvider />
  {children}
</LinkComponentProvider>
```

## Sources [#sources]

A source is an id, a label and a `search(query, context)` function. `context.signal` is aborted on the next keystroke and on close, so pass it to `fetch`. `context.limit` is how many items to return (5 per group by default, 20 per page when [scoped](#scoping)).

```tsx
const usersSource: SpotlightSource<'users'> = {
  id: 'users',
  label: 'Users', // or () => t('spotlight.users'), read at render
  icon: <UsersIcon />,
  search: async (query, { signal, limit }) => {
    const res = await fetch(`/api/users?q=${encodeURIComponent(query)}&limit=${limit}`, { signal });
    if (!res.ok) throw new Error(`users search failed: ${res.status}`);
    const users: User[] = await res.json();
    return users.map((user) => ({
      id: user.login,
      title: user.displayName,
      description: `@${user.login}`,
      icon: <Avatar src={user.image} name={user.displayName} size="sm" />,
      link: { href: `/users/${user.login}` },
    }));
  },
};
```

Throwing on a non-2xx status matters: it turns a 500 into an error row with **Retry** instead of an empty group.

### Streaming [#streaming]

`search` can be an `async function*`. Each `yield` (one item or a list) is appended to the group as soon as it arrives. When the query changes, the kit aborts the signal and calls the iterator's `return()`, so the generator's `finally` runs and nothing from the old query lands afterwards.

The demo's users source works this way: type `a` in the bar at the top. The people you've worked with come from a local cache and land at once, then the rest stream in from the server, and the group ends with three skeleton rows until the stream is done.

```tsx
const usersSource: SpotlightSource<'users'> = {
  id: 'users',
  label: 'Users',
  async *search(query, { signal, limit }) {
    // Local first: the people you've worked with, by login or prefix.
    const known = teammates.match(query).slice(0, limit);
    yield known.map(toItem);
    // Then the server's stream, without the ones already shown.
    const hits = ndjson(await fetch(`/api/users?q=${query}&limit=${limit}`, { signal }));
    try {
      for await (const hit of hits) {
        if (!known.some(({ login }) => login === hit.login)) yield toItem(hit);
      }
    } finally {
      // Also runs on the next keystroke, once the kit aborts `signal` and calls `return()`.
      hits.cancel();
    }
  },
};
```

### One service, several groups [#one-service-several-groups]

A federated search service is registered once. Each item names its group with a stable `group` key, and the source's `groups` map gives each key its label, icon and order:

```tsx
const catalogSource: SpotlightSource<'catalog'> = {
  id: 'catalog',
  label: 'Catalog',
  groups: {
    modules: { label: 'Modules', icon: <BookOpenIcon />, order: 0 },
    rooms: { label: 'Rooms', icon: <DoorOpenIcon />, order: 1 },
  },
  search: async (query, { signal }) =>
    (await searchCatalog(query, signal)).map((hit) => ({ ...toItem(hit), group: hit.index })),
};
```

### Loading, streaming and errors [#loading-streaming-and-errors]

Every group renders as soon as its source answers. The other groups are never held back, and they never move once shown.

* **Loading.** Skeleton rows appear once a source has been searching for `skeletonDelay` ms (120 by default). The debounce before the search doesn't count, so a fast source never flashes them over rows already shown. When nothing else would be on screen (no rows, recents or "Search in" rows, as on the first key, after an empty state or over the prompt), they show at once instead, so the list never collapses while it waits.
* **Re-running.** As you type, a source that already shows results keeps the previous query's rows, slightly dimmed, until its new answer lands. No skeleton rows come and go, and the list grows but doesn't shrink until every source has settled, so it doesn't bob between keystrokes. Whatever space that held height leaves under the rows fills with skeleton rows (after the same `skeletonDelay`), so it reads as loading rather than as a gap. They're not options: ↑ and ↓ skip them, and screen readers don't announce them. Once everything has settled they go, and the list eases down to its rows.
* **Streaming.** Three skeleton rows end the group while more is coming, after the same `skeletonDelay`. They're laid out like the rows they stand for, so nothing moves when the results land. A scoped list with a next page ends the same way.
* **Error.** The group keeps whatever it received and ends with a Retry row, which ↵ or a click runs again (`spotlight.refresh(sourceId)`). The demo's Evaluations fail on `eval`.
* **Empty.** "No results", with an icon and a hint to try other words (or, while scoped, to press ⌫ to widen the search), shows only once every source has settled. `Spotlight.Empty`'s `children` replace all three.

The highlight follows an item, not a position, so a group arriving above the highlighted row doesn't move it.

<story.Playground />

## Items [#items]

The default row shows `icon` (an icon, an `<Avatar>`, an image), `title`, `description`, `badge`, and `shortcut` as `Kbd` keys. The query's words are marked in the title with `Mark`, ignoring case and diacritics (`desi` marks *Désiato*). When a search engine knows better (stemming, typos), pass its match positions as `highlights` and they're marked instead:

```tsx
{ id, title: hit.title, highlights: hit._matchesPosition.title.map(({ start, length }) => [start, start + length]) }
```

A source's `render(item, { highlighted, query })` replaces the row's content. The kit still owns the row element, its ARIA and its keyboard handling.

## Links and the keyboard [#links-and-the-keyboard]

| Key               | Action                                                                                                            |
| ----------------- | ----------------------------------------------------------------------------------------------------------------- |
| ⌘K / Ctrl+K       | Open; toggles closed when open (`hotkey`)                                                                         |
| ↑ / ↓, Home / End | Move the highlight (wraps)                                                                                        |
| ↵                 | Run the row: its `onSelect`, then `navigate(link)`, then close (unless `closeOnSelect: false`)                    |
| ⌘↵ / Ctrl+↵       | Open the row's link in a new tab, and stay open                                                                   |
| Tab               | Search within the highlighted item when its source has `within`, else only in its group (see [Scoping](#scoping)) |
| ⌫ (empty input)   | Drop the last chip                                                                                                |
| Esc               | Drop the last chip; with none left, close                                                                         |

An item with a `link` renders as your `LinkComponentProvider`'s `Link`, with the link object spread on it (a plain `<a>` without a provider). So middle-click, ⌘-click and your router's hover preloading all work natively. ↵ and a plain click go through `navigate`, and ⌘↵ opens the `href` the row's anchor rendered. After a navigation, focus isn't pulled back to the button that opened the menu, so your router keeps control of focus on the new page.

Items with only `onSelect` (commands) render as plain options. `onSelect` receives `{ close, query }`.

## Scoping [#scoping]

Scoping narrows the search, and scopes compose into a **path**: the chips before the input, read left to right. `[Users: Marvin] [Projects: libft]` searches libft's attempts by Marvin. Each chip is a **frame**:

* a **category** `{ source, group? }` narrows the search to one source, or one group of a federated source. That source is asked for a page instead of a few rows, and the list loads more as you scroll.
* an **item** `{ source, item }` searches *within* that item: the menu then searches the sources its source's `within(item)` returns.

```tsx
const usersSource: SpotlightSource<'users'> = {
  id: 'users',
  label: 'Users',
  prefix: '@', // "@ mar" narrows to users
  search: async (query, { signal, limit }) => searchUsers(query, limit, signal),
  // Searched within a user: the closure carries them, so nested sources need nothing else.
  within: (user) => [projectsOf(user), eventsOf(user)],
};

const projectsOf = (user: SpotlightItem): SpotlightSource => ({
  id: 'projects',
  label: 'Projects',
  prefix: '#',
  search: (query, { signal }) => searchProjects({ user: user.id, query }, signal),
  within: (project) => [attemptsOf(user, project)], // and one level deeper
});
```

The menu searches one **level** at a time. With no chips, it's every root source (global and contextual). After an item chip, it's what that item's `within` returned. A category chip narrows the level it sits on. Every level works the same way, so depth is unlimited.

Commands with sub-actions use the same mechanism: a settings source whose `within(setting)` returns its actions.

* **Every row of a source with `within` can be entered**, and shows a `›` button. That is the rule to follow: put commands with sub-actions in a source of their own, apart from plain commands, as this page's demo does with Settings and Commands.
* **An item replaces the category it was found in.** `@ mar` then Tab on Marvin gives one chip, `[Users: Marvin]`, not `[Users] [Users: Marvin]`, and ⌫ from there goes back to the root. This holds however the path is built: Tab, `›`, `push`, `setPath`, `open({ path })` or `useSpotlightPath`. A category of another source stays.
* **One label per source.** A source's `label` names its group and its chips. An item chip reads "Users: Marvin" by default; reword it with the `itemLabel` translation, e.g. `(source, title) => title` or a singular of your own.

**Ways in:**

* **Tab** on a highlighted row. If its source has `within`, Tab enters the item and clears the query. Otherwise it narrows to the row's group and keeps the query (`Modules` and `Rooms` are separate groups of one catalog source). Tab is only taken when it adds a chip, so Shift+Tab, or Tab again on a group that is already the last chip, moves focus as usual and the keyboard is never trapped.
* **The `›` button** that rows of a source with `within` show, for the mouse. ↵ and a click on the row still select it.
* **A prefix and a space.** A source's `prefix` followed by a space, at the very start of the query, narrows to that source and is removed from the input: `@ mar` searches users for `mar`. Prefixes belong to the current level (`# ` means "this user's projects" inside a user), and only apply while the last chip isn't already a category. The space is required, so `#42` stays literal text.
* **A "Search in" row** (see [Discovering prefixes](#discovering-prefixes)): ↵, Tab or a click narrows to its source and clears the query.
* **See all in X**, the last row of a group that has more: its source returned a `nextCursor`, or the group is as long as the unscoped `limit`.
* **From code:** `spotlight.open({ path })`, `spotlight.setPath(path)`, `spotlight.push(frame)`, or a contextual source's `open()`. A path's first frame is typed against the global source ids; deeper ones only exist at runtime, so they are plain strings. A frame that doesn't fit its level ends the path there.

**Ways out:** ⌫ on an empty input and Esc drop the last chip; Esc closes only once there are none. A chip's × removes it and every chip after it. From code, `spotlight.pop()` or `spotlight.setPath([])`. Any change aborts the running searches, like a keystroke. Screen readers hear the whole path ("Searching in Users: Marvin, Projects") and "Searching everywhere" once it's empty.

A narrowed search gets `scoped: true` and the larger `limit` (`limit: { unscoped: 5, scoped: 20 }` by default). Narrowed to one group, it also gets `group` (the group's key), so a federated service can be asked for just that slice. A source that ignores it still works: the kit only shows the items whose `group` matches.

### Discovering prefixes [#discovering-prefixes]

A prefix only helps once people know it. On an empty query, after the recents, a **Search in** group lists every source of the current level with its icon, its label and its `prefix` as a key: `@` Users, `#` Projects, `>` Commands. Inside an item chip, it lists what that item's `within` returned, with their own prefixes.

Once something is typed, only the sources the query names stay, and they move to the top, highlighted: the prefix itself (`@`), or the start of a word of the label (`use`, ignoring case and diacritics). The normal search still runs underneath, and `@ ` with its space still narrows straight away. Running a row (↵, Tab or a click) narrows to its source and clears the query, since the text only served to find it.

While a prefix works, each group's heading also shows it after the label, so the prefix is learned from results too.

The rows are hidden while the last chip is a category (the search is already narrowed) and on a level with fewer than two sources. Turn them off with `scopes: false` on `createSpotlight`, or on `<SpotlightProvider scopes={false} />`, which overrides the factory's.

### An empty query in a scope [#an-empty-query-in-a-scope]

A chip with nothing typed after it shows, in order: the recents of that chip's source (or group), headed "Recent in Users"; then the suggestions of its sources with `minQueryLength: 0`; and, when there are neither, a **prompt**: the chip's icon, "Search Users" ("Search in Marvin Paranoid" on an item chip), a hint, and ⌫ to go back. The prompt waits until every source has settled, so a source about to suggest never flashes it. In the demo, `@ ` suggests a few people you've worked with, and **In Rooms** shows the prompt with the catalog's own hint. Item chips show no recents: a recent names its source, not the level it was found on.

Two source fields reword a scope. `hint` replaces the prompt's "Type to search" while the path ends on the source or one of its groups, and `placeholder` replaces the input's "Search Users…" there. Both take a function, read at render, to follow the locale. At the root, the input keeps the factory's or the provider's `placeholder`.

```tsx
const usersSource: SpotlightSource<'users'> = {
  id: 'users',
  label: 'Users',
  hint: () => t('spotlight.users.hint'), // "Type a login or a name"
  placeholder: () => t('spotlight.users.placeholder'), // "Login or name…"
  search,
};
```

`Spotlight.Prompt` is the part. The default list renders it after `Spotlight.Empty`, and its `children` replace its content.

### Opening at a path [#opening-at-a-path]

A page can say where the menu opens: `useSpotlightPath(path)`, or the component form `<SpotlightPath path={…} />`, sets it while mounted. On a user's profile, ⌘K then opens within that user. Its chips are removable like any other, unmounting clears it, and an explicit `spotlight.open({ path })` wins. Pass a stable path (module scope, or memoised).

```tsx
function ProfilePage({ user }: { user: User }) {
  const path = useMemo(() => [{ source: 'users', item: { id: user.login, title: user.displayName } }] as const, [user]);
  useSpotlightPath(path);
  return <Profile user={user} />;
}
```

Visit Marvin's profile, then open the menu:

<Preview align="center" code="null">
  <ProfileDemo />
</Preview>

### Pagination [#pagination]

While scoped, return `{ items, nextCursor }` to say there is more. When the list nears its end, the kit calls `search` again with the same query and `cursor: nextCursor`, appends the page, and ends the list with three skeleton rows while there is more to load. One page loads at a time, the highlight doesn't move as pages land, and a page without `nextCursor` is the last. The cursor is an opaque string: an offset, a page number or a search engine's token all fit.

```tsx
search: async (query, { signal, limit, cursor }) => {
  const page = Number(cursor ?? 1);
  const res = await fetch(`/api/students?q=${query}&page=${page}&per_page=${limit}`, { signal });
  const { data, meta } = await res.json();
  return {
    items: data.map(toItem),
    nextCursor: page < meta.lastPage ? String(page + 1) : undefined,
  };
},
```

This demo's source holds 1,000 students and answers in 500 ms per page. Browse them all, then scroll:

<Preview align="center" code="null">
  <PaginationDemo />
</Preview>

## Recents [#recents]

On an empty query, the menu shows the items last selected, most recent first. They're stored with [`useLocalStorage`](/docs/hooks/use-local-storage), so they survive reloads and sync across tabs. Two kinds of item are recorded: items with a `link` (replayed by navigating to it), and items of a `staticSource` (rebuilt by id, so a command's `onSelect` still runs). Sources with `minQueryLength: 0` show next to them as suggestions. On a category's chip, only that category's recents show (see [An empty query in a scope](#an-empty-query-in-a-scope)). Pass `recents: false` to turn them off.

## Open from code [#open-from-code]

The `spotlight` object works anywhere, outside React too: event handlers, utils, router guards.

<Preview align="center" code="&#x22;spotlight.open({ query: 'mar' })\nspotlight.open({ path: [{ source: 'users' }], query: 'ma' }) // narrowed to a source\nspotlight.setPath([{ source: 'users', item: marvin }, { source: 'projects', item: libft }])\nspotlight.push({ source: 'catalog', group: 'rooms' }) // one chip more\nspotlight.pop()                                       // one chip less; setPath([]) clears\nspotlight.close()\nspotlight.toggle()\nspotlight.setQuery('exam')\nspotlight.refresh('events')            // re-run one source, or all\nconst unregister = spotlight.register(source)\nspotlight.subscribe(listener)\nspotlight.getState()                   // { open, query, path, trail, sources, groups }&#x22;">
  <OpenFromCode />
</Preview>

## Contextual sources [#contextual-sources]

A source can live with a route. `useSpotlightSource(source)` registers it while the calling component is mounted, so calling it in a route layout makes it route-mounted. It returns `{ open(query?) }`, which opens the menu narrowed to that source, with its chip. Contextual sources live at the root level; deeper levels come from `within`. Pass a stable source (module scope, or memoised): a new object registers it again, which restarts its search.

```tsx
function ProjectLayout() {
  const files = useSpotlightSource(projectFilesSource);
  return <Button onClick={() => files.open()}>Search this project</Button>;
}
```

Route-config routers that can't call hooks use the component form:

```tsx
{ path: 'projects/:slug', element: <><SpotlightSources sources={[projectFiles, projectMembers]} /><ProjectPage /></> }
```

## Routers [#routers]

**TanStack Router.** The router is a module-level object, so `navigate` goes on the factory. Annotate its parameter: it becomes the link type every item's `link` is checked against, so a typo in a route is a compile error.

```tsx title="app/spotlight.tsx"
import { Link, type NavigateOptions } from '@tanstack/react-router';
import { router } from '~/router';

const usersSource: SpotlightSource<'users', NavigateOptions> = {
  id: 'users',
  label: 'Users',
  search: async (query, { signal }) =>
    (await searchUsers(query, signal)).map((user) => ({
      id: user.login,
      title: user.displayName,
      link: { to: '/users/$login', params: { login: user.login } },
    })),
};

export const { spotlight, SpotlightProvider } = createSpotlight({
  sources: [usersSource],
  navigate: (link: NavigateOptions) => router.navigate(link),
});

// app root
<LinkComponentProvider component={Link}>
  <SpotlightProvider />
  <Outlet />
</LinkComponentProvider>
```

**Next.js (App Router).** `useRouter()` only exists inside React, so `navigate` goes on the provider, which overrides the factory's. Links are plain `{ href }`. This page's demo is wired this way:

```tsx title="app/app-spotlight.tsx"
'use client';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

export function AppSpotlight() {
  const router = useRouter();
  return (
    <LinkComponentProvider component={Link}>
      <SpotlightProvider navigate={({ href }) => router.push(href)} />
    </LinkComponentProvider>
  );
}
```

**No router.** Leave `navigate` out: ↵ calls `window.location.assign(link.href)`, and rows render plain anchors.

## Custom layout [#custom-layout]

`<SpotlightProvider>` with children replaces the default layout with the parts: `Spotlight.Root` (the modal), `Spotlight.Input`, `Spotlight.Path` (the chips) and `Spotlight.Scope` (one chip), `Spotlight.List` (whose children can render the groups themselves), `Spotlight.Group`, `Spotlight.Item`, `Spotlight.Empty`, `Spotlight.Prompt` and `Spotlight.Footer`. Each takes `className` and `testId`, and the ones with inner pieces take `classNames`.

`Spotlight.Input` renders `<Spotlight.Path />` in its `startSlot`, before the input. Pass your own there to style it (`classNames.scope` reaches every chip), lay out `<Spotlight.Scope index={…} />` chips yourself, or pass `startSlot={null}` to leave them out. A chip takes `asChild`, and its `children` replace the label.

<Preview align="center" code="&#x22;<SpotlightProvider>\n  <Spotlight.Root>\n    <Spotlight.Input>\n      <Kbd size=\&#x22;sm\&#x22;>Esc</Kbd>\n    </Spotlight.Input>\n    <Spotlight.List>\n      {(groups) => groups.map((group) => <Spotlight.Group key={group.key} group={group} />)}\n    </Spotlight.List>\n    <Spotlight.Empty className=\&#x22;py-10\&#x22; />\n    <Spotlight.Prompt className=\&#x22;py-10\&#x22; />\n  </Spotlight.Root>\n</SpotlightProvider>&#x22;">
  <CustomLayoutDemo />
</Preview>

## Icons [#icons]

`icons` replaces the menu's own icons, set on the factory and overridden per key on `<SpotlightProvider icons>`, like `translations`: `search` leads the search row, `enter` is a row's › button (search within the item), `seeAll` leads a group's "See all" row, and `empty` tops the empty state. `search: null`, `seeAll: null` and `empty: null` drop theirs. The kit's chevrons mirror on a right-to-left page; yours are drawn as given, so add `rtl:-scale-x-100` to an arrow. A source's, group's or item's own `icon` is data, not part of this map. Add `className={iconStroke}` (from `@42/ui-react`) for the kit's 1.5px line.

<Preview align="center" code="&#x22;const { spotlight, SpotlightProvider } = createSpotlight({\n  sources: [users, commands],\n  icons: {\n    search: <TextSearchIcon className={iconStroke} />,\n    enter: <CornerDownRightIcon className={cn(iconStroke, \&#x22;rtl:-scale-x-100\&#x22;)} />,\n    seeAll: <ArrowRightIcon className={cn(iconStroke, \&#x22;rtl:-scale-x-100\&#x22;)} />,\n  },\n})&#x22;">
  <IconsDemo />
</Preview>

## Translations [#translations]

All of the menu's own wording comes from `translations`, set on the factory and overridden per key on `<SpotlightProvider translations>` (where a runtime locale switch lands). Source and group labels are yours: write them as `() => t('…')` to follow the locale.

The footer's keys are [`<Kbd hotkey>`](/docs/kbd#translations) caps, so their words come from `translations.kbd`, a partial set of Kbd's own translations that Spotlight forwards to each of them. Translate both the words a cap shows and the names it is spoken by, or a French menu still reads "Up Arrow":

```tsx
const { SpotlightProvider } = createSpotlight({
  sources,
  translations: {
    hintNavigate: 'naviguer',
    hintSelect: 'choisir',
    hintClose: 'fermer',
    kbd: { escape: 'Échap', enter: 'Entrée', return: 'Retour', up: 'Flèche haut', down: 'Flèche bas' },
  },
});
```

<Preview align="center" code="null">
  <TranslationsDemo />
</Preview>

`keyCtrl` and `keyEsc` came first and still work, as `kbd.ctrl` and `kbd.escape`; move them into `kbd`.

<TypeTable
  type="{
  inputLabel: { type: 'string', default: '&#x22;Search&#x22;', description: &#x22;The input's and the dialog's accessible name.&#x22; },
  recents: { type: 'string', default: '&#x22;Recent&#x22;', description: 'The heading of the recents.' },
  recentsIn: { type: '(label: string) => string', default: '`Recent in ${label}`', description: &#x22;Their heading on a category's chip, which shows only that category's.&#x22; },
  noResults: { type: '(query: string) => string', default: '`No results for “${query}”`', description: 'The empty state.' },
  noResultsHint: { type: 'string', default: '&#x22;Try fewer or different words&#x22;', description: 'The line under it.' },
  noResultsScopedHint: { type: 'string', default: '&#x22;to widen the search&#x22;', description: &#x22;The line under it while the path isn't empty, after the ⌫ key.&#x22; },
  promptTitle: { type: '(label: string, title?: string) => string', default: '`Search ${label}`, or `Search in ${title}` on an item chip', description: &#x22;The prompt's heading, on a chip with nothing typed and nothing to show.&#x22; },
  promptHint: { type: 'string', default: '&#x22;Type to search&#x22;', description: &#x22;The line under it, unless the source has its own `hint`.&#x22; },
  promptBack: { type: 'string', default: '&#x22;to go back&#x22;', description: &#x22;The prompt's last line, after the ⌫ key.&#x22; },
  searchPlaceholder: { type: '(label: string, title?: string) => string', default: '`Search ${label}…`, or `Search in ${title}…` on an item chip', description: &#x22;The input's placeholder on a chip, unless the source has its own `placeholder`.&#x22; },
  error: { type: '(group: string) => string', default: &#x22;`Couldn't load ${group}`&#x22;, description: &#x22;A failed source's row.&#x22; },
  retry: { type: 'string', default: '&#x22;Retry&#x22;', description: 'The action on that row.' },
  results: { type: '(count: number) => string', default: '`${count} results`', description: 'Announced once every source has settled.' },
  scopes: { type: 'string', default: '&#x22;Search in&#x22;', description: 'The heading of the rows that scope to a source.' },
  searchIn: { type: '(label: string) => string', default: '`Search in ${label}`', description: &#x22;A \&#x22;Search in\&#x22; row's accessible name.&#x22; },
  seeAll: { type: '(group: string) => string', default: '`See all in ${group}`', description: 'The row that scopes to a group with more.' },
  scopeLabel: { type: '(path: readonly string[]) => string', default: '`Searching in ${path.join(&#x22;, &#x22;)}`', description: &#x22;Announced when the path changes, with every chip's label.&#x22; },
  scopeCleared: { type: 'string', default: '&#x22;Searching everywhere&#x22;', description: 'Announced when the path empties.' },
  itemLabel: { type: '(source: string, title: string) => string', default: '`${source}: ${title}`', description: &#x22;An item chip's label.&#x22; },
  enter: { type: '(title: string) => string', default: '`Search in ${title}`', description: &#x22;A row's › button.&#x22; },
  leaveScope: { type: '(chip: string) => string', default: '`Leave ${chip}`', description: &#x22;A chip's remove button (it removes the chips after it too).&#x22; },
  hintNavigate: { type: 'string', default: '&#x22;navigate&#x22;', description: 'Footer hint after ↑↓.' },
  hintSelect: { type: 'string', default: '&#x22;select&#x22;', description: 'Footer hint after ↵.' },
  hintNewTab: { type: 'string', default: '&#x22;new tab&#x22;', description: 'Footer hint after ⌘↵, while the highlighted row has a link.' },
  hintScope: { type: 'string', default: '&#x22;search within&#x22;', description: 'Footer hint after Tab, while Tab would add a chip.' },
  hintLeaveScope: { type: 'string', default: '&#x22;back&#x22;', description: 'Footer hint after ⌫ / Esc, while there are chips.' },
  hintClose: { type: 'string', default: '&#x22;close&#x22;', description: 'Footer hint after Esc.' },
  kbd: { type: 'Partial<KbdTranslations>', default: '{}', description: 'The footer\'s key words, forwarded to every key cap it draws and merged per key onto Kbd\'s English defaults: the words shown (ctrl &#x22;Ctrl&#x22;, escape &#x22;Esc&#x22;, backspace &#x22;Backspace&#x22;) and the names spoken (up, down, return / enter, command, tab, delete). The provider\'s add to the factory\'s, key by key. Kbd\'s Translations section lists every key.' },
  keyCtrl: { type: 'string', default: '&#x22;Ctrl&#x22;', description: 'Deprecated, use kbd.ctrl (it wins when both are set); removed in the next minor. The Ctrl keycap of the new-tab hint, off Apple platforms.' },
  keyTab: { type: 'string', default: '&#x22;Tab&#x22;', description: 'Deprecated and unused: the footer draws Tab as an icon, spoken kbd.tab.' },
  keyEsc: { type: 'string', default: '&#x22;Esc&#x22;', description: 'Deprecated, use kbd.escape (it wins when both are set); removed in the next minor. The Esc keycap.' },
}"
/>

## Testing [#testing]

Every part takes a `testId`. `<SpotlightProvider testId="spotlight" />` names the modal and derives `spotlight-input`, `spotlight-path` (its chips `spotlight-path-${index}`, with `-remove` on their buttons), `spotlight-list` and `spotlight-footer`. Each row renders its item's `testId`, or `spotlight-item-${sourceId}-${itemId}` (`spotlight-recent-…` for a recent), its `›` button that id plus `-enter`, a "See all" row is `spotlight-see-all-${groupKey}`, and a "Search in" row is `spotlight-scope-${sourceId}`.

## API [#api]

<TypeTable
  type="{
  sources: { type: 'SpotlightSource[]', description: &#x22;The global sources. Their ids type a path's first frame.&#x22; },
  navigate: { type: '(link: L) => void', description: &#x22;Called with a selected item's `link`. Its parameter types every item's `link`. Without it, `window.location.assign(link.href)`.&#x22; },
  hotkey: { type: 'string | false', default: '&#x22;mod+k&#x22;', description: 'The toggle shortcut; `mod` is ⌘ on macOS and Ctrl elsewhere.' },
  recents: { type: '{ limit?: number; storageKey?: string } | false', default: '{ limit: 5, storageKey: &#x22;42-spotlight-recents&#x22; }', description: 'Recently selected items on an empty query.' },
  scopes: { type: 'boolean', default: 'true', description: 'The &#x22;Search in&#x22; rows, one per source of the current level with its prefix. See Discovering prefixes.' },
  limit: { type: '{ unscoped?: number; scoped?: number }', default: '{ unscoped: 5, scoped: 20 }', description: 'How many items sources are asked for, unless a source sets its own.' },
  skeletonDelay: { type: 'number', default: '120', description: 'How long a source may search before its group shows skeleton rows, in ms.' },
  placeholder: { type: 'string', default: '&#x22;Search…&#x22;', description: &#x22;The input's placeholder at the root. A chip shows its own; see An empty query in a scope.&#x22; },
  translations: { type: 'Partial<SpotlightTranslations>', description: 'See Translations.' },
  icons: { type: '{ search?, enter?, seeAll?, empty? }', description: 'Replaces the menu\'s icons; a missing key keeps its default. See Icons.' },
  modalProps: { type: 'Partial<ModalProps>', description: 'Merged onto the modal (size, radius, classNames…).' },
}"
/>

A source (`SpotlightSource`):

<TypeTable
  type="{
  id: { type: 'string', description: 'Unique among its level. Global ids type the first frame of a path.' },
  label: { type: 'string | (() => string)', description: 'The heading of its own group, and its chip. A function is read at render.' },
  icon: { type: 'ReactNode', description: 'Its group, chip, &#x22;Search in&#x22; row and prompt.' },
  groups: { type: 'Record<string, { label, icon?, order? }>', description: 'The groups its items can name with `group`. See One service, several groups.' },
  prefix: { type: 'string', description: 'Typed with a space at the start of the query, narrows to the source: `&#x22;@&#x22;`.' },
  order: { type: 'number', default: '0', description: 'Groups are ordered by it, then by registration.' },
  minQueryLength: { type: 'number', default: '1', description: 'The shortest trimmed query it runs for; `0` also runs it on an empty one (suggestions).' },
  hint: { type: 'string | (() => string)', default: 'translations.promptHint', description: &#x22;The prompt's line on its chip, or one of its groups'.&#x22; },
  placeholder: { type: 'string | (() => string)', default: 'translations.searchPlaceholder(label)', description: &#x22;The input's placeholder on its chip, or one of its groups'.&#x22; },
  limit: { type: 'number | { unscoped?: number; scoped?: number }', description: &#x22;How many items to ask for, over `createSpotlight`'s.&#x22; },
  debounce: { type: 'number', default: '150', description: 'Milliseconds after a keystroke before it searches; `0` for local sources.' },
  search: { type: '(query, context) => page | Promise<page> | AsyncIterable<chunk>', description: 'Its results. See Sources and Streaming.' },
  items: { type: 'SpotlightItem[]', description: &#x22;The whole fixed list (`staticSource` sets it), which recents rebuild items from.&#x22; },
  render: { type: '(item, state) => ReactNode', description: &#x22;Replaces its rows' content.&#x22; },
  within: { type: '(item) => SpotlightSource[]', description: 'The sources searched within one of its items. See Scoping.' },
}"
/>

`<SpotlightProvider>` takes `navigate`, `scopes`, `translations`, `icons` and `placeholder` (each overriding the factory's), `classNames` (`root`, `input`, `scope`, `list`, `footer`) and `testId` for the default layout, and `children` for a custom one.
