kbar

repository·main·Indexed 26 days ago

https://github.com/timc1/kbar

A plug-and-play React component library for implementing a fast, extensible command palette (Cmd+K) interface, similar to macOS Spotlight or Linear. Version 0.1.0-beta.47 provides a suite of components like KBarProvider, KBarPortal, KBarSearch, and KBarResults, along with hooks such as useMatches and useKBar to manage search queries, action registration, and visual states.

Tokens
3.1K
Snippets
9
Records
16
Agent score
90%

What's inside kbar

  1. Set up the kbar UI components

    main

    To render the command palette UI, use the provided component hierarchy inside KBarProvider. This structure ensures the menu is rendered outside the root node and handles animations and positioning.

    Required components:

    • KBarPortal: Renders the content outside the root node.
    • KBarPositioner: Centers the content.
    • KBarAnimator: Handles show/hide and height animations.
    • KBarSearch: The search input field.
    import {
      KBarProvider,
      KBarPortal,
      KBarPositioner,
      KBarAnimator,
      KBarSearch
    } from "kbar";
    
    // Inside your component return:
    <KBarProvider actions={actions}>
      <KBarPortal>
        <KBarPositioner>
          <KBarAnimator>
            <KBarSearch />
          </KBarAnimator>
        </KBarPositioner>
      </KBarPortal>
      <MyApp />
    </KBarProvider>
  2. Render search results with useMatches and KBarResults

    main

    Use the useMatches hook to get a flattened list of results (including group names) and the KBarResults component to render them efficiently using virtualization.

    The onRender prop in KBarResults provides the item and its active state, allowing you to customize the appearance of both group headers (strings) and action items (objects).

    import {
      KBarResults,
      useMatches,
      NO_GROUP,
    } from "kbar";
    
    function RenderResults() {
      const { results } = useMatches();
    
      return (
        <KBarResults
          items={results}
          onRender={({ item, active }) =>
            typeof item === "string" ? (
              <div>{item}</div>
            ) : (
              <div
                style={{
                  background: active ? "#eee" : "transparent",
                }}
              >
                {item.name}
              </div>
            )
          }
        />
      );
    }
  3. Define and provide actions to KBarProvider

    main

    Actions are the core of kbar; they define what executes when a user selects an item. Wrap your application (or a specific part of it) with KBarProvider and pass an array of action objects.

    Each action object should include:

    • id: A unique identifier.
    • name: The display name of the action.
    • shortcut: An array of strings representing keyboard shortcuts.
    • keywords: A string of searchable terms.
    • perform: A function that executes when the action is triggered.
    import { KBarProvider } from "kbar";
    
    const actions = [
      {
        id: "blog",
        name: "Blog",
        shortcut: ["b"],
        keywords: "writing words",
        perform: () => (window.location.pathname = "blog"),
      },
      {
        id: "contact",
        name: "Contact",
        shortcut: ["c"],
        keywords: "email",
        perform: () => (window.location.pathname = "contact"),
      },
    ];
    
    function MyApp() {
      return (
        <KBarProvider actions={actions}>
          {/* Your app content */}
        </KBarProvider>
      );
    }
  4. Configure KBarOptions

    main

    Use the KBarOptions interface to customize the behavior and appearance of the kbar instance. Key configuration options include:

    • animations: Control entry and exit durations using enterMs and exitMs.
    • callbacks: Hook into lifecycle events like onOpen, onClose, onQueryChange, and onSelectAction.
    • disableScrollbarManagement: If true, kbar won't manipulate the document's margin-right to prevent layout shifts.
    • disableDocumentLock: If true, kbar won't hide the body scrollbar or disable pointer events when open.
    • enableHistory: Enables/disables command history.
    • toggleShortcut: Customizes the keyboard shortcut to trigger kbar (defaults to "$mod+k").
    export interface KBarOptions {
      animations?: {
        enterMs?: number;
        exitMs?: number;
      };
      callbacks?: {
        onOpen?: () => void;
        onClose?: () => void;
        onQueryChange?: (searchQuery: string) => void;
        onSelectAction?: (action: ActionImpl) => void;
      };
      disableScrollbarManagement?: boolean;
      disableDocumentLock?: boolean;
      enableHistory?: boolean;
      toggleShortcut?: string;
    }
  5. KBar Hooks Reference

    main

    The following hooks are available for interacting with the command palette state:

    • useMatches: Returns a flattened list of results and group names based on the current search query. The returned array format is ["Section name", Action, Action, "Another section name", Action, Action].
  6. KBar UI Components Reference

    main

    The following components are used to build the command palette interface:

    • KBarProvider: The context provider that holds actions and state.
    • KBarPortal: Renders the menu outside the main application DOM tree.
    • KBarPositioner: Handles the positioning/centering of the menu.
    • KBarAnimator: Manages entry/exit and height animations.
    • KBarSearch: The input field for user queries.
    • KBarResults: A virtualized list component for rendering search results.
  7. Access KBar State and Context

    main

    The IKBarContext provides access to the internal state and configuration of kbar. It includes:

    • getState(): Returns the current KBarState (including searchQuery, activeIndex, and visualState).
    • query: Provides the KBarQuery methods for interaction.
    • subscribe(collector, cb): Allows subscribing to state changes.
    • options: Returns the current KBarOptions.
    export interface IKBarContext {
      getState: () => KBarState;
      query: KBarQuery;
      subscribe: (
        collector: <C>(state: KBarState) => C,
        cb: <C>(collected: C) => void
      ) => void;
      options: KBarOptions;
    }
  8. Use kbar components and hooks

    main

    The kbar package provides a suite of components and hooks to build a command palette interface. Key exports include:

    • Hooks: useKBar for accessing the kbar state, useMatches for finding matching actions, and useRegisterActions for registering your command list.
    • Components: KBarContextProvider to wrap your application, KBarSearch for the input field, KBarResults for displaying matches, KBarPortal and KBarPositioner for layout and rendering, and KBarAnimator for transitions.
    • Core: action for action definitions and types for TypeScript definitions.
  9. Use the KBarSearch component

    main

    The KBarSearch component provides a controlled input field for the kbar interface. It integrates with the useKBar hook to manage search queries, handle focus, and manage accessibility attributes like aria-controls and aria-activedescendant.

    Key features:

    • Automatically manages the search query via query.setSearch.
    • Automatically focuses the input when the root action changes.
    • Dynamically updates the placeholder: it shows the name of the currentRootAction if one is active, otherwise it falls back to defaultPlaceholder or the default string "Type a command or search…".
    • Supports standard HTMLInputElement props (e.g., onChange, onKeyDown).
    • Clears the search query when the component unmounts or when the root action changes.
  10. Import Action types and implementations from kbar/action

    main
    The src/action/index.tsx entrypoint exports the core interfaces and implementations for actions in kbar. Use this module to access ActionInterface for type definitions and ActionImpl for the underlying action logic.