Skip to content

Early previewhamur is not on npm yet. The components are being built in the open, follow along on GitHub.

OverlaysReact

Spotlight

A command palette: a dialog holding a search input and a list of commands.

Rendered by React 19.3.1

Loading React…
import * as React from 'react'
import { Autocomplete } from '@hamur/react/autocomplete'
import { getHotkeyKeys } from '@hamur/react/hotkeys'
import { Spotlight } from '@hamur/react/spotlight'

interface Command {
  id: string
  label: string
}

interface CommandGroup {
  value: string
  items: Command[]
}

const commands: CommandGroup[] = [
  {
    value: 'Navigation',
    items: [
      { id: 'go-dashboard', label: 'Go to Dashboard' },
      { id: 'go-projects', label: 'Go to Projects' },
      { id: 'go-settings', label: 'Go to Settings' },
    ],
  },
  {
    value: 'Actions',
    items: [
      { id: 'create-project', label: 'Create project' },
      { id: 'invite', label: 'Invite teammate' },
      { id: 'toggle-theme', label: 'Toggle theme' },
      { id: 'copy-link', label: 'Copy link' },
    ],
  },
]

const glyphs: Record<string, string> = { Meta: '⌘', Control: 'Ctrl' }
const keys = getHotkeyKeys('Mod+K')[0]
const shortcut = keys.map((key) => glyphs[key] ?? key).join(keys.includes('Meta') ? '' : '+')

export default function SpotlightExample() {
  const [query, setQuery] = React.useState('')
  const [lastCommand, setLastCommand] = React.useState<Command | null>(null)
  const { contains } = Autocomplete.useFilter({ sensitivity: 'base' })
  const results = commands.reduce(
    (total, group) => total + group.items.filter((c) => contains(c.label, query.trim())).length,
    0,
  )

  return (
    <Spotlight.Root
      items={commands}
      hotkey="Mod+K"
      value={query}
      onValueChange={(next) => setQuery(next)}
    >
      <div className="stack">
        <div className="row">
          <Spotlight.Trigger className="button">
            Open command palette <kbd aria-hidden="true">{shortcut}</kbd>
          </Spotlight.Trigger>
        </div>
        <p className="muted">Last command: {lastCommand ? lastCommand.label : 'none'}</p>
      </div>

      <Spotlight.Portal>
        <Spotlight.Backdrop className="backdrop" />
        <Spotlight.Popup className="dialog">
          <Spotlight.Title className="dialog-title">
            Command palette
          </Spotlight.Title>
          <Spotlight.Description className="muted">
            Type to filter. Up and Down move through the commands, Enter runs one, Escape closes.
          </Spotlight.Description>
          <label className="field">
            <span className="select-label">Search commands</span>
            <Spotlight.Input className="input" placeholder="Type a command" />
          </label>
          <Spotlight.Empty>
            <div className="combobox-empty">No commands match "{query}".</div>
          </Spotlight.Empty>
          <Spotlight.List className="select-list">
            <Spotlight.Collection>
              {(group: CommandGroup) => (
                <Spotlight.Group
                  key={group.value}
                  items={group.items}
                  className="select-group"
                >
                  <Spotlight.GroupLabel className="select-group-label">
                    {group.value}
                  </Spotlight.GroupLabel>
                  <Spotlight.Collection>
                    {(command: Command) => (
                      <Spotlight.Item
                        key={command.id}
                        value={command}
                        className="select-item plain"
                        onClick={() => setLastCommand(command)}
                      >
                        {command.label}
                      </Spotlight.Item>
                    )}
                  </Spotlight.Collection>
                </Spotlight.Group>
              )}
            </Spotlight.Collection>
          </Spotlight.List>
          <Spotlight.Status>
            <div className="combobox-status">
              {results === 1 ? '1 result' : `${results} results`}
            </div>
          </Spotlight.Status>
          <div className="actions">
            <Spotlight.Close className="button">
              Close
            </Spotlight.Close>
          </div>
        </Spotlight.Popup>
      </Spotlight.Portal>
    </Spotlight.Root>
  )
}
68Tests passing in React · 0 failing
97.3 KiBSize
Not measured yetMemory
Not measured yetSpeed
[N] commits

Installation

npm i @hamur/react

Not on npm yet. The package goes out under the chosen name.

Anatomy

Import the component and assemble its parts:

<Spotlight.Root>
  <Spotlight.Trigger />
  <Spotlight.Portal>
    <Spotlight.Backdrop />
    <Spotlight.Popup>
      <Spotlight.Title />
      <Spotlight.Description />
      <Spotlight.Input />
      <Spotlight.Empty />
      <Spotlight.List>
        <Spotlight.Collection>
          <Spotlight.Group>
            <Spotlight.GroupLabel>
              <Spotlight.Item />
            </Spotlight.GroupLabel>
          </Spotlight.Group>
        </Spotlight.Collection>
      </Spotlight.List>
      <Spotlight.Status />
      <Spotlight.Close />
    </Spotlight.Popup>
  </Spotlight.Portal>
</Spotlight.Root>

// Not in this example: Spotlight.Separator, Spotlight.Viewport

Examples

The demo at the top is the one example this component has so far.

API reference

48 props across 18 parts, in React syntax. className, style, render are listed once, under Shared props.

BackdropSpotlight.Backdrop

An overlay displayed beneath the popup. Renders a <div>.

Backdrop props
PropTypeDefault
forceRenderWhether the backdrop is forced to render even when nested.booleanfalse
Backdrop data attributes
Data attributeDescription
data-openPresent when the spotlight is open.
data-closedPresent when the spotlight is closed.
data-starting-stylePresent when the spotlight begins animating in.
data-ending-stylePresent when the spotlight is animating out.
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

CloseSpotlight.Close

A button that closes the spotlight. Renders a <button>.

Close props
PropTypeDefault
nativeButtonWhether the component renders a native <button> element when replacing itbooleantrue
Close data attributes
Data attributeDescription
data-disabledPresent when the button is disabled.
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

CollectionSpotlight.Collection

Renders the filtered commands, or the commands of its Spotlight.Group. If rendering a flat list, pass a function child to the List component instead, which implicitly wraps it. Doesn’t render its own element.

Collection props
PropTypeDefault
childrenrequired(item: any, index: number) => React.ReactNode—

DescriptionSpotlight.Description

A paragraph with additional information about the spotlight. Renders a <p>.

Description data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

EmptySpotlight.Empty

Renders its children only when no command matches the query. Announces changes politely to screen readers. Keep it mounted and outside Spotlight.List. Renders a <div>.

Empty data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

GroupSpotlight.Group

Groups related commands with the corresponding label. Renders a <div>.

Group props
PropTypeDefault
itemsItems to be rendered within this group.readonly any[]—
Group data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

GroupLabelSpotlight.GroupLabel

An accessible label that is automatically associated with its parent group. Renders a <div>.

GroupLabel data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

InputSpotlight.Input

A text input to search the commands. It is a combobox that controls the list, and the popup's initial focus. Renders an <input>.

Input props
PropTypeDefault
disabledWhether the component should ignore user interaction.booleanfalse
Input data attributes
Data attributeDescription
data-popup-openPresent when the corresponding popup is open.
data-pressedPresent when the input is pressed.
data-disabledPresent when the component is disabled.
data-readonlyPresent when the component is readonly.
data-popup-sideIndicates which side the corresponding popup is positioned relative to its anchor.
data-requiredPresent when the component is required.
data-validPresent when the component is in a valid state (when wrapped in Field.Root).
data-invalidPresent when the component is in an invalid state (when wrapped in Field.Root).
data-touchedPresent when the component has been touched (when wrapped in Field.Root).
data-dirtyPresent when the component's value has changed (when wrapped in Field.Root).
data-filledPresent when the component has a value (when wrapped in Field.Root).
data-focusedPresent when the input is focused (when wrapped in Field.Root).
data-list-emptyPresent when the corresponding items list is empty.
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

ItemSpotlight.Item

A command in the list. A press (a click, a tap, or <kbd>Enter</kbd> while it is highlighted) runs its onClick, then closes the spotlight. Renders a <div>.

Item props
PropTypeDefault
nativeButtonWhether the component renders a native <button> element when replacing itbooleanfalse
childrenReact.ReactNode—
onClickA click handler that runs the command.((event: BaseUIEvent<React.MouseEvent<HTMLDivElement, MouseEvent>>) => void)—
closeOnClickWhether pressing the item closes the spotlight, with the reason 'item-press'.booleantrue
indexThe index of the item in the list.number—
valueA unique value that identifies this item.anynull
disabledWhether the component should ignore user interaction.booleanfalse
Item data attributes
Data attributeDescription
data-highlightedPresent when the item is highlighted.
data-disabledPresent when the item is disabled.
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

ListSpotlight.List

The list of commands, always shown: a listbox the input controls. Keep Spotlight.Empty and Spotlight.Status outside it. Renders a <div>.

List props
PropTypeDefault
childrenReact.ReactNode | ((item: any, index: number) => React.ReactNode)—
List data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

PopupSpotlight.Popup

A container for the spotlight contents: the dialog, which holds the search input and the list. Renders a <div>.

Popup props
PropTypeDefault
initialFocusDetermines the element to focus when the spotlight is opened.boolean | React.RefObject<HTMLElement | null> | ((openType: InteractionType) => boolean | void | HTMLElement | null)—
finalFocusDetermines the element to focus when the spotlight is closed.boolean | React.RefObject<HTMLElement | null> | ((closeType: InteractionType) => boolean | void | HTMLElement | null)—
Popup data attributes
Data attributeDescription
data-openPresent when the spotlight is open.
data-closedPresent when the spotlight is closed.
data-starting-stylePresent when the spotlight begins animating in.
data-ending-stylePresent when the spotlight is animating out.
data-nestedPresent when the spotlight is nested within another dialog.
data-nested-dialog-openPresent when the spotlight has other open dialogs nested within it.
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.
Popup CSS variables
CSS variableDescription
--nested-dialogsIndicates how many dialogs are nested within.

PortalSpotlight.Portal

A portal element that moves the popup to a different part of the DOM. By default, the portal element is appended to <body>. Renders a <div>.

Portal props
PropTypeDefault
keepMountedWhether to keep the portal mounted in the DOM while the popup is hidden.booleanfalse
containerA parent element to render the portal element into.HTMLElement | ShadowRoot | React.RefObject<HTMLElement | ShadowRoot | null> | null—
Portal data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

RootSpotlight.Root

Groups all parts of the spotlight: a command palette, a modal dialog holding a search input and an inline list of commands. Doesn’t render its own element.

Root props
PropTypeDefault
openWhether the spotlight is currently open.boolean—
defaultOpenWhether the spotlight is initially open.booleanfalse
onOpenChangeEvent handler called when the spotlight is opened or closed.((open: boolean, eventDetails: SpotlightRootChangeEventDetails) => void)—
onOpenChangeCompleteEvent handler called after any animations complete when the spotlight is opened or closed.((open: boolean) => void)—
modalDetermines if the spotlight enters a modal state when open.boolean | "trap-focus"true
disablePointerDismissalWhether to prevent the spotlight from closing on outside presses.booleanfalse
actionsRefA ref to imperative actions.React.RefObject<SpotlightRootActions | null>—
handleA handle to associate the spotlight with a trigger.SpotlightHandle<Payload>—
triggerIdID of the trigger that the spotlight is associated with.string | null—
defaultTriggerIdID of the trigger that the spotlight is associated with.string | null—
hotkeyA hotkey that opens the spotlight, and closes it while open, such as 'Mod+K'.string—
itemsThe commands to be displayed in the list.readonly ItemValue[] | readonly Group<ItemValue>[]—
filteredItemsFiltered commands to display in the list.readonly ItemValue[] | readonly Group<ItemValue>[]—
filterFilter function used to match items against the query.((item: ItemValue, query: string, itemToString?: ((item: ItemValue) => string) | undefined) => boolean) | null—
limitThe maximum number of items to display in the list.number-1
localeThe locale to use for string comparison.Intl.LocalesArgument—
valueThe query typed in the input.string—
defaultValueThe uncontrolled query when the spotlight is initially rendered.string—
onValueChangeEvent handler called when the query changes.((value: string, eventDetails: AutocompleteRootChangeEventDetails) => void)—
itemToStringValueWhen the item values are objects, this function converts the object value to a string((itemValue: ItemValue) => string)—
onItemHighlightedCallback fired when an item is highlighted or unhighlighted.((highlightedValue: ItemValue | undefined, eventDetails: AriaCombobox.HighlightEventDetails) => void)—
highlightItemOnHoverWhether moving the pointer over items should highlight them.booleantrue
loopFocusWhether to loop keyboard focus back to the input when the end of the list is reached while using the arrow keys.booleantrue
virtualizedWhether the items are being externally virtualized.booleanfalse
childrenThe content of the spotlight.React.ReactNode | PayloadChildRenderFunction<Payload>—

SeparatorSpotlight.Separator

A visual separator between commands or groups. Renders a <div>.

Separator props
PropTypeDefault
orientationThe orientation of the separator.Orientation'horizontal'
Separator data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

StatusSpotlight.Status

Announces the result count politely to screen readers once the query has settled. Renders its children only while the query is not empty, at least one command matches, and the query has not changed for delay milliseconds. Keep it mounted and outside Spotlight.List. Renders a <div>.

Status props
PropTypeDefault
delayHow long the query must stay unchanged before the children are rendered, in milliseconds.number1000
Status data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

TitleSpotlight.Title

A heading that labels the spotlight. Renders a <h2>.

Title data attributes
Data attributeDescription
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

TriggerSpotlight.Trigger

A button that opens the spotlight. Renders a <button>.

Trigger props
PropTypeDefault
nativeButtonWhether the component renders a native <button> element when replacing itbooleantrue
handleA handle to associate the trigger with a spotlight.SpotlightHandle<Payload>—
payloadA payload to pass to the spotlight when it is opened.Payload—
idID of the trigger.string—
Trigger data attributes
Data attributeDescription
data-disabledPresent when the trigger is disabled.
data-popup-openPresent when the corresponding dialog is open.
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

ViewportSpotlight.Viewport

A positioning container for the spotlight popup that can be made scrollable. Renders a <div>.

Viewport data attributes
Data attributeDescription
data-openPresent when the spotlight is open.
data-closedPresent when the spotlight is closed.
data-starting-stylePresent when the spotlight begins animating in.
data-ending-stylePresent when the spotlight is animating out.
data-nestedPresent when the spotlight is nested within another dialog.
data-nested-dialog-openPresent when the spotlight has other open dialogs nested within it.
data-slotNames the part for styling: the component's id on its root (switch), <component>-<part> on the others (popover-popup). A value you set on the part wins.

Shared props

Every part that renders an element takes these.

Shared props
PropType
classNameCSS class applied to the element, or a function that returns a class based on the component's state.string | ((state: State) => string | undefined)
styleStyle applied to the element, or a function that returns a style object based on the component's state.React.CSSProperties | ((state: State) => React.CSSProperties | undefined)
renderAllows you to replace the component's HTML element with a different tag, or compose it with another component.React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, State>

Keyboard and accessibility

Keyboard

Keyboard
KeysDoesPart
Mod+KOpens and closes the palette
↑ ↓Moves between the commands
EnterRuns the highlighted command
EscCloses the palette

Accessibility

Not written yet.