Skip to content

Command

Command as Dialog

⌘J to open dialog

import { Command, FlexRow, Text } from '@ronin-nexus/atomic';
import { Calculator, Calendar, Receipt, Settings, Smile, User } from 'lucide-react';
import { useEffect, useState } from 'react';
 
const commandList = {
  Suggestions: [
    { value: 'calendar', label: 'Calendar', icon: Calendar },
    { value: 'emoji', label: 'Emoji', icon: Smile },
    { value: 'calculator', label: 'Calculator', icon: Calculator },
  ],
  Settings: [
    { value: 'profile', label: 'Profile', icon: User },
    { value: 'billing', label: 'Billing', icon: Receipt },
    { value: 'settings', label: 'Settings', icon: Settings },
  ],
};
export function CommandMenu() {
  const [open, setOpen] = useState(false);
 
  useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key === 'j' && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setOpen(open => !open);
      }
    };
    document.addEventListener('keydown', down);
    return () => document.removeEventListener('keydown', down);
  }, []);
 
  const handleSelectItem = (value: string) => {
    console.log(value);
    setOpen(false);
  };
 
  return (
    <Command.Dialog className="w-[500px]" open={open} onOpenChange={setOpen}>
      <Command.Input placeholder="Type a command or search..." />
      <Command.List>
        <Command.Empty>No results found.</Command.Empty>
        {Object.entries(commandList).map(([key, value]) => {
          return (
            <Command.Group key={key} heading={key}>
              {value.map(item => {
                const Icon = item.icon;
                return (
                  <Command.Item key={item.value} value={item.value} onSelect={handleSelectItem}>
                    <FlexRow className="items-center space-x-2">
                      <Icon className="text-text" size={22} />
                      <Text>{item.label}</Text>
                    </FlexRow>
                  </Command.Item>
                );
              })}
            </Command.Group>
          );
        })}
      </Command.List>
    </Command.Dialog>
  );
}

Command as List