UI Library
Overlaycommandpalettecreatequick addkeyboardradix

Quick add

A create-anything palette: a search box, a rail of section icons, and every kind of record in two grouped columns with an icon and one line each. Opens from a header button or the N key, and works entirely from the keyboard: arrows move by row and column, Enter opens, Esc closes.

Preview

Click the button or press N.

apps/site/blocks/components/QuickAdd.tsx
'use client';

/**
 * A "Quick add" palette — standalone.
 *
 * One place to start creating anything: a search box, a rail of section icons
 * down the left, and every kind of record in two columns, grouped under small
 * headings, each with an icon, a name and one line saying what it is. Opened
 * from a header button or with a single key from anywhere in the app.
 *
 * ── Dependencies ────────────────────────────────────────────────────────────
 *   npm i @radix-ui/react-dialog lucide-react
 *
 * Tailwind is assumed and nothing else: no shadcn, no `cn()`, no cmdk, no
 * animation plugin. Radii are explicit pixels so a host that remaps
 * `rounded-*` from its own `--radius` still renders the same shape.
 *
 * ── Keyboard ────────────────────────────────────────────────────────────────
 *   N            opens it from any page (ignored while typing in a field)
 *   ↑ ↓          move a row up or down
 *   ← →          move between the two columns
 *   Enter        open the highlighted item
 *   Esc          close
 * The search box keeps focus the whole time, so typing always narrows the list.
 *
 * ── Usage ───────────────────────────────────────────────────────────────────
 *   <QuickAdd
 *     groups={GROUPS}
 *     onSelect={(item) => router.push(item.href)}
 *   />
 *
 * `QuickAdd` renders its own trigger button and owns its open state. Pass
 * `open` and `onOpenChange` to control it instead, and `hideTrigger` when the
 * button lives somewhere else.
 */

import * as React from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import {
  BookOpen,
  CalendarClock,
  CircleHelp,
  ClipboardList,
  FileText,
  Flag,
  FolderKanban,
  LayoutGrid,
  ListChecks,
  Megaphone,
  Plus,
  Repeat,
  Search,
  Settings2,
  StickyNote,
  UserPlus,
  Users,
  Workflow,
  X,
  type LucideIcon,
} from 'lucide-react';

// ── Types ───────────────────────────────────────────────────────────────────

export type QuickAddItem = {
  id: string;
  title: string;
  description: string;
  icon: LucideIcon;
  /** Extra words that should find this item, e.g. synonyms. */
  keywords?: string[];
};

export type QuickAddGroup = {
  id: string;
  label: string;
  /** Shown in the left rail. */
  icon: LucideIcon;
  items: QuickAddItem[];
};

const COLUMNS = 2;

// ── The palette ─────────────────────────────────────────────────────────────

export function QuickAdd({
  groups,
  onSelect,
  open: openProp,
  onOpenChange,
  hideTrigger = false,
  shortcut = 'n',
  triggerLabel = 'Quick add',
  placeholder = 'What do you want to create?',
  allLabel = 'Everything',
}: {
  groups: QuickAddGroup[];
  onSelect: (item: QuickAddItem, group: QuickAddGroup) => void;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  hideTrigger?: boolean;
  /** A single key that opens the palette from anywhere; '' turns it off. */
  shortcut?: string;
  triggerLabel?: string;
  placeholder?: string;
  allLabel?: string;
}) {
  const [openState, setOpenState] = React.useState(false);
  const open = openProp ?? openState;
  const setOpen = React.useCallback(
    (next: boolean) => {
      if (openProp === undefined) setOpenState(next);
      onOpenChange?.(next);
    },
    [openProp, onOpenChange],
  );

  const [query, setQuery] = React.useState('');
  const [section, setSection] = React.useState<string>('all');
  const [active, setActive] = React.useState(0);
  const listRef = React.useRef<HTMLDivElement>(null);

  // Global key: open from any page, but never while the user is typing.
  React.useEffect(() => {
    if (!shortcut) return;
    function onKey(e: KeyboardEvent) {
      if (e.key.toLowerCase() !== shortcut.toLowerCase()) return;
      if (e.metaKey || e.ctrlKey || e.altKey) return;
      const t = e.target as HTMLElement | null;
      if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
      e.preventDefault();
      setOpen(true);
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [shortcut, setOpen]);

  // A fresh start every time it opens.
  React.useEffect(() => {
    if (open) {
      setQuery('');
      setSection('all');
      setActive(0);
    }
  }, [open]);

  const q = query.trim().toLowerCase();
  const visible = React.useMemo(
    () =>
      groups
        .filter((g) => section === 'all' || g.id === section)
        .map((g) => ({
          ...g,
          items: g.items.filter((item) => {
            if (!q) return true;
            const hay = [item.title, item.description, g.label, ...(item.keywords ?? [])]
              .join(' ')
              .toLowerCase();
            return q.split(/\s+/).every((word) => hay.includes(word));
          }),
        }))
        .filter((g) => g.items.length > 0),
    [groups, section, q],
  );

  // One flat list in reading order: each group's items fill two columns, row
  // by row. Arrow keys move inside that grid, crossing into the next group.
  const flat = React.useMemo(
    () => visible.flatMap((g) => g.items.map((item, i) => ({ item, group: g, col: i % COLUMNS }))),
    [visible],
  );

  React.useEffect(() => setActive(0), [q, section]);

  React.useEffect(() => {
    listRef.current
      ?.querySelector<HTMLElement>(`[data-qa-index="${active}"]`)
      ?.scrollIntoView({ block: 'nearest' });
  }, [active]);

  function move(e: React.KeyboardEvent) {
    if (flat.length === 0) return;
    const cur = flat[active];
    let next = active;
    if (e.key === 'ArrowRight' && cur.col < COLUMNS - 1 && flat[active + 1]?.group.id === cur.group.id) {
      next = active + 1;
    } else if (e.key === 'ArrowLeft' && cur.col > 0) {
      next = active - 1;
    } else if (e.key === 'ArrowDown') {
      // Same column one row down; at the end of a group, the first row of the next.
      const below = flat.findIndex(
        (x, i) => i > active && (x.group.id !== cur.group.id || x.col === cur.col),
      );
      next = below === -1 ? active : below;
      if (flat[next].group.id !== cur.group.id) {
        const firstOfNext = flat.findIndex((x) => x.group.id === flat[next].group.id);
        next = Math.min(firstOfNext + cur.col, flat.findLastIndex((x) => x.group.id === flat[next].group.id));
      }
    } else if (e.key === 'ArrowUp') {
      let above = -1;
      for (let i = active - 1; i >= 0; i--) {
        if (flat[i].group.id !== cur.group.id || flat[i].col === cur.col) {
          above = i;
          break;
        }
      }
      next = above === -1 ? active : above;
      if (above !== -1 && flat[above].group.id !== cur.group.id) {
        // Land on the same column in the previous group's last row.
        const g = flat[above].group.id;
        const lastRowStart = flat.findLastIndex((x) => x.group.id === g && x.col === 0);
        next = Math.min(lastRowStart + cur.col, above);
      }
    } else if (e.key === 'Enter') {
      e.preventDefault();
      choose(active);
      return;
    } else {
      return;
    }
    e.preventDefault();
    setActive(next);
  }

  function choose(index: number) {
    const hit = flat[index];
    if (!hit) return;
    setOpen(false);
    onSelect(hit.item, hit.group);
  }

  const kbd =
    'inline-flex h-5 min-w-5 items-center justify-center rounded-[5px] border border-slate-200 bg-white px-1 text-[10px] font-semibold text-slate-600';

  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      {hideTrigger ? null : (
        <Dialog.Trigger asChild>
          <button
            type="button"
            className="inline-flex h-10 items-center gap-2 rounded-full bg-slate-900 pl-4 pr-2 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800"
          >
            <Plus className="h-4 w-4" aria-hidden />
            {triggerLabel}
            {shortcut ? (
              <kbd className="ml-1 inline-flex h-6 min-w-6 items-center justify-center rounded-full bg-white/15 px-1.5 text-[11px] font-semibold uppercase">
                {shortcut}
              </kbd>
            ) : null}
          </button>
        </Dialog.Trigger>
      )}
      <Dialog.Portal>
        <style>{PALETTE_KEYFRAMES}</style>
        <Dialog.Overlay
          className="fixed inset-0 z-50 bg-slate-900/30 backdrop-blur-[2px]"
          style={{ animation: 'quickAddFade 160ms ease-out' }}
        />
        <Dialog.Content
          aria-describedby={undefined}
          onOpenAutoFocus={(e) => {
            // Focus the search box, not the first button.
            e.preventDefault();
            (e.currentTarget as HTMLElement).querySelector('input')?.focus();
          }}
          className={
            'fixed left-1/2 top-[10vh] z-50 flex max-h-[80vh] w-[calc(100%-2rem)] max-w-[620px] -translate-x-1/2 flex-col ' +
            'overflow-hidden rounded-[18px] border border-slate-200 bg-white shadow-2xl outline-none'
          }
          style={{ animation: 'quickAddIn 200ms cubic-bezier(0.32, 0.72, 0, 1)' }}
        >
          <Dialog.Title className="sr-only">{triggerLabel}</Dialog.Title>

          <div className="flex items-center gap-3 border-b border-slate-200 px-4 py-3">
            <Search className="h-5 w-5 shrink-0 text-slate-500" aria-hidden />
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={move}
              placeholder={placeholder}
              aria-label={placeholder}
              role="combobox"
              aria-expanded
              aria-controls="quick-add-list"
              aria-activedescendant={flat[active] ? `qa-${flat[active].group.id}-${flat[active].item.id}` : undefined}
              className="h-8 min-w-0 flex-1 bg-transparent text-base text-slate-900 outline-none placeholder:text-slate-400"
            />
            <Dialog.Close
              aria-label="Close"
              className="rounded-[8px] p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-slate-900"
            >
              <X className="h-4 w-4" aria-hidden />
            </Dialog.Close>
          </div>

          <div className="flex min-h-0 flex-1">
            <nav aria-label="Sections" className="flex shrink-0 flex-col items-center gap-1 border-r border-slate-200 p-2">
              <RailButton label={allLabel} icon={LayoutGrid} active={section === 'all'} onClick={() => setSection('all')} />
              {groups.map((g) => (
                <RailButton
                  key={g.id}
                  label={g.label}
                  icon={g.icon}
                  active={section === g.id}
                  onClick={() => setSection(g.id)}
                />
              ))}
            </nav>

            <div ref={listRef} id="quick-add-list" role="listbox" aria-label={triggerLabel} className="min-h-0 flex-1 overflow-y-auto px-3 pb-3 pt-2">
              {visible.length === 0 ? (
                <p className="px-2 py-12 text-center text-sm text-slate-500">
                  Nothing called &ldquo;{query}&rdquo;.
                </p>
              ) : (
                visible.map((g) => (
                  <div key={g.id} role="group" aria-label={g.label}>
                    <p className="px-2 pb-1.5 pt-3 text-[11px] font-bold uppercase tracking-[0.06em] text-slate-500">
                      {g.label}
                    </p>
                    <div className="grid grid-cols-1 gap-1 sm:grid-cols-2">
                      {g.items.map((item) => {
                        const index = flat.findIndex((x) => x.item.id === item.id && x.group.id === g.id);
                        const on = index === active;
                        const Icon = item.icon;
                        return (
                          <div
                            key={item.id}
                            id={`qa-${g.id}-${item.id}`}
                            role="option"
                            aria-selected={on}
                            data-qa-index={index}
                            onMouseMove={() => setActive(index)}
                            onClick={() => choose(index)}
                            className={
                              'flex cursor-pointer items-start gap-3 rounded-[12px] border px-2.5 py-2 ' +
                              (on ? 'border-lime-300 bg-lime-50' : 'border-transparent hover:bg-slate-50')
                            }
                          >
                            <span
                              className={
                                'mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-[9px] ' +
                                (on ? 'bg-lime-100 text-lime-800' : 'bg-slate-100 text-slate-600')
                              }
                            >
                              <Icon className="h-4 w-4" aria-hidden />
                            </span>
                            <span className="min-w-0">
                              <span className="block text-sm font-semibold text-slate-900">{item.title}</span>
                              <span className="block text-xs leading-snug text-slate-500">{item.description}</span>
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          <div className="hidden items-center gap-4 border-t border-slate-200 bg-slate-50 px-4 py-2.5 text-xs text-slate-600 sm:flex">
            <span className="flex items-center gap-1.5 whitespace-nowrap">
              <kbd className={kbd}>↑</kbd>
              <kbd className={kbd}>↓</kbd>
              Navigate
            </span>
            <span className="flex items-center gap-1.5 whitespace-nowrap">
              <kbd className={kbd}>←</kbd>
              <kbd className={kbd}>→</kbd>
              Columns
            </span>
            <span className="flex items-center gap-1.5 whitespace-nowrap">
              <kbd className={kbd}>↵</kbd>
              Open
            </span>
            <span className="flex items-center gap-1.5 whitespace-nowrap">
              <kbd className={kbd}>Esc</kbd>
              Close
            </span>
            {shortcut ? (
              <span className="ml-auto flex items-center gap-1.5 whitespace-nowrap">
                <kbd className={kbd}>{shortcut.toUpperCase()}</kbd>
                opens it from any page
              </span>
            ) : null}
          </div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}

function RailButton({
  label,
  icon: Icon,
  active,
  onClick,
}: {
  label: string;
  icon: LucideIcon;
  active: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-pressed={active}
      aria-label={label}
      title={label}
      className={
        'flex h-9 w-9 items-center justify-center rounded-[10px] border transition ' +
        (active
          ? 'border-lime-300 bg-lime-100 text-lime-800'
          : 'border-transparent text-slate-500 hover:bg-slate-100 hover:text-slate-900')
      }
    >
      <Icon className="h-4 w-4" aria-hidden />
    </button>
  );
}

const PALETTE_KEYFRAMES = `
@keyframes quickAddIn {
  from { opacity: 0; transform: translate(-50%, 8px) scale(0.98); }
  to   { opacity: 1; transform: translate(-50%, 0) scale(1); }
}
@keyframes quickAddFade {
  from { opacity: 0; }
  to   { opacity: 1; }
}
@media (prefers-reduced-motion: reduce) {
  @keyframes quickAddIn { from { opacity: 1; transform: translate(-50%, 0); } to { opacity: 1; transform: translate(-50%, 0); } }
  @keyframes quickAddFade { from { opacity: 1; } to { opacity: 1; } }
}
`;

// ── Demo ────────────────────────────────────────────────────────────────────

const DEMO_GROUPS: QuickAddGroup[] = [
  {
    id: 'work',
    label: 'Work',
    icon: ClipboardList,
    items: [
      { id: 'task', title: 'Task', description: 'Something to do, with a due date and an owner', icon: ListChecks, keywords: ['todo', 'issue'] },
      { id: 'sprint', title: 'Sprint', description: 'A time box of tasks with a goal', icon: Repeat },
      { id: 'milestone', title: 'Milestone', description: 'A date the team is working toward', icon: Flag },
      { id: 'meeting', title: 'Meeting notes', description: 'Notes from a call, with action items', icon: CalendarClock },
    ],
  },
  {
    id: 'docs',
    label: 'Docs & diagrams',
    icon: FileText,
    items: [
      { id: 'note', title: 'Note', description: 'A page of writing only your team sees', icon: StickyNote },
      { id: 'flow', title: 'Flow', description: 'A flowchart or a user journey', icon: Workflow, keywords: ['diagram'] },
      { id: 'checklist', title: 'Checklist', description: 'Steps to tick off, reusable next time', icon: ListChecks },
      { id: 'guide', title: 'Help article', description: 'A question and answer for the help centre', icon: CircleHelp, keywords: ['faq'] },
    ],
  },
  {
    id: 'projects',
    label: 'Projects',
    icon: FolderKanban,
    items: [
      { id: 'project', title: 'Project', description: 'A home for related tasks, notes and flows', icon: FolderKanban },
      { id: 'handbook', title: 'Handbook', description: 'Group guides into one reading order', icon: BookOpen },
    ],
  },
  {
    id: 'people',
    label: 'People',
    icon: Users,
    items: [
      { id: 'invite', title: 'Invite a teammate', description: 'Send a link to join this workspace', icon: UserPlus },
      { id: 'announcement', title: 'Announcement', description: 'A message everyone sees when they sign in', icon: Megaphone },
    ],
  },
  {
    id: 'setup',
    label: 'Setup',
    icon: Settings2,
    items: [{ id: 'field', title: 'Custom field', description: 'Track one more thing on every task', icon: Settings2 }],
  },
];

/** What /ui renders: a header button that opens the palette and says what was picked. */
export function QuickAddDemo() {
  const [picked, setPicked] = React.useState<string | null>(null);
  return (
    <div className="flex flex-col items-center gap-3">
      <QuickAdd groups={DEMO_GROUPS} onSelect={(item) => setPicked(item.title)} />
      <p className="text-sm text-slate-500" aria-live="polite">
        {picked ? (
          <>
            Would open the new <span className="font-semibold text-slate-900">{picked}</span> form.
          </>
        ) : (
          <>Click the button or press N.</>
        )}
      </p>
    </div>
  );
}

Dependencies

  • @radix-ui/react-dialog — npm package
  • lucide-react — npm package

Colours

Colours come from CSS variables (--background, --primary, --border) using the shadcn/ui token names, so the block adopts your palette rather than importing ours.

21 more blocks.

Headers, footers, dialogs, pickers and toasts, all in the same style.