|Kit

Spotlight

A ⌘K omni search over sources your teams own. Each group streams in on its own, with skeletons, retries, recents, commands, scoping with infinite scroll, and router-aware links.

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 ⌘J (Ctrl J 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 Tab 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.

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:

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:

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

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).

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

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.

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

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:

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

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.

Spotlight

Loading preview

Props

Code

<Spotlight
  placeholder="Search…"
  skeletonDelay={120}
  latency={900}
  failing
/>

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:

{ 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.

KeyAction
⌘K / Ctrl+KOpen; toggles closed when open (hotkey)
↑ / ↓, Home / EndMove 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
TabSearch within the highlighted item when its source has within, else only in its group (see Scoping)
⌫ (empty input)Drop the last chip
EscDrop 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 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.
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): ↵, 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

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

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.

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

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).

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:

Marvin Paranoid@marvin · Heart of Gold

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.

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:

Recents

On an empty query, the menu shows the items last selected, most recent first. They're stored with useLocalStorage, 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). Pass recents: false to turn them off.

Open from code

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

Code

spotlight.open({ query: 'mar' })
spotlight.open({ path: [{ source: 'users' }], query: 'ma' }) // narrowed to a source
spotlight.setPath([{ source: 'users', item: marvin }, { source: 'projects', item: libft }])
spotlight.push({ source: 'catalog', group: 'rooms' }) // one chip more
spotlight.pop()                                       // one chip less; setPath([]) clears
spotlight.close()
spotlight.toggle()
spotlight.setQuery('exam')
spotlight.refresh('events')            // re-run one source, or all
const unregister = spotlight.register(source)
spotlight.subscribe(listener)
spotlight.getState()                   // { open, query, path, trail, sources, groups }

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.

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:

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

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.

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:

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

<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.

Code

<SpotlightProvider>
  <Spotlight.Root>
    <Spotlight.Input>
      <Kbd size="sm">Esc</Kbd>
    </Spotlight.Input>
    <Spotlight.List>
      {(groups) => groups.map((group) => <Spotlight.Group key={group.key} group={group} />)}
    </Spotlight.List>
    <Spotlight.Empty className="py-10" />
    <Spotlight.Prompt className="py-10" />
  </Spotlight.Root>
</SpotlightProvider>

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.

Code

const { spotlight, SpotlightProvider } = createSpotlight({
  sources: [users, commands],
  icons: {
    search: <TextSearchIcon className={iconStroke} />,
    enter: <CornerDownRightIcon className={cn(iconStroke, "rtl:-scale-x-100")} />,
    seeAll: <ArrowRightIcon className={cn(iconStroke, "rtl:-scale-x-100")} />,
  },
})

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> 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":

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' },
  },
});

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

Prop

Type

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

Prop

Type

A source (SpotlightSource):

Prop

Type

<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.

Changelog

v0.30.0
  • Option lists scroll with the kit's thin scrollbars on every OS; Select's focus ring moves to the list's frame

    #494
  • On a short screen, Spotlight's list shrinks so its footer stays in view

    #494
v0.20.0
  • New Spotlight ⌘K omni search: createSpotlight({ sources, navigate }) returns a controller (open, close, toggle, setQuery, refresh, loadMore) plus <SpotlightProvider />, useSpotlight, useSpotlightSource and <SpotlightSources>; sources search in parallel with their own debounce, can stream from an async function*, and fail alone with a retry row

    #340
  • Items take a typed link checked against your router's navigate parameter, or an onSelect; ↵ navigates, ⌘↵ opens a new tab, and staticSource({ id, label, items }) filters commands client-side ignoring case and diacritics

    #340
  • The default menu opens on hotkey (mod+k), keeps recents (recents: { limit, storageKey } or false), highlights matches and supports RTL; Spotlight.Root/Input/List/Group/Item/Empty/Footer compose a custom layout, and translations, placeholder and icons reword and restyle it

    #343
  • Drill-down: a source's within(item) returns the sources to search inside an item; Tab or › pushes a chip, Backspace or Esc pops one, and spotlight.open({ path }), setPath, push, pop, useSpotlightPath and <SpotlightPath> set the path from code

    #346
  • Scope a search by typing a source's prefix (@ , # …) or picking a "Search in" row (scopes: false hides them); scoped sources page in as you scroll by following nextCursor

    #352
  • Loading never flashes: pending and streaming groups end in skeleton rows, stale rows dim, the list height eases; an empty scope shows Spotlight.Prompt with the source's hint and recents, and no results shows icons.empty and a hint

    #414
  • The footer draws its hints as <Kbd hotkey> caps with terse labels, translated through translations.kbd

    #410

On this page