Command palette

A palette that opens with ⌘K and unmounts when closed. The shortcut still works, because it lives in the graft.

or press ⌘K / Ctrl K

Mounted

A provider, a trigger and the palette. The palette leaves the tree when it closes.

tsx
// react-graft-command-palette-demo.tsx
export const ReactGraftCommandPaletteDemo = () => (
  <ReactGraftCommandPaletteGraft.Provider>
    <ReactGraftCommandPaletteTrigger />
    <ReactGraftCommandPaletteLayer />
  </ReactGraftCommandPaletteGraft.Provider>
);

The graft

The graft keeps the query and matching commands available, whether the palette is open or closed.

tsx
// react-graft-command-palette.graft.ts
export const ReactGraftCommandPaletteGraft = createGraft({
  name: "ReactGraftCommandPaletteGraft",
  graft: useGraft,
  inject: [useInjectShortcut],
});

function useGraft() {
  const [isOpen, setIsOpen] = useState(false);
  const [query, setQuery] = useState("");

  const open = useCallback(() => {
    setQuery("");
    setIsOpen(true);
  }, []);

  const close = useCallback(() => setIsOpen(false), []);

  const results = useMemo(() => {
    const term = query.trim().toLowerCase();
    if (!term) return COMMAND_LIST;

    return COMMAND_LIST.filter((command) => command.toLowerCase().includes(term));
  }, [query]);

  return { isOpen, query, results, close, open, setQuery };
}

The shortcut

It is injected, so it belongs to the provider and keeps listening while the palette is closed.

tsx
function useInjectShortcut({ close, isOpen, open }: { close: () => void; isOpen: boolean; open: () => void }) {
  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "k" || !(event.metaKey || event.ctrlKey)) return;

      event.preventDefault();

      if (isOpen) return close();

      open();
    };

    window.addEventListener("keydown", onKeyDown);

    return () => window.removeEventListener("keydown", onKeyDown);
  }, [close, isOpen, open]);
}
tsx
// the same listener, written inside the palette
export const ReactGraftCommandPaletteLayer = () => {
  const { close, isOpen, open } = ReactGraftCommandPaletteGraft.use();

  useShortcut(isOpen, open, close);   // only runs while the palette is mounted

  return (
    <Layer open={isOpen} onClose={close}>
      …
    </Layer>
  );
};