본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

커맨드(Command)

원문 보기 위키 갱신

커맨드 메뉴라고도 불리는 이 컴포넌트는 사용자가 앱 안의 항목을 빠르게 검색하고, 필터링하고, 선택할 수 있게 해줘요. 빠른 내비게이션이나 동작 실행이 필요한 화면에 아주 적합해요.

출처: 문서

본문

<script lang="ts">
  import { Command } from "bits-ui";
  import CalendarBlank from "phosphor-svelte/lib/CalendarBlank";
  import CodeBlock from "phosphor-svelte/lib/CodeBlock";
  import Palette from "phosphor-svelte/lib/Palette";
  import RadioButton from "phosphor-svelte/lib/RadioButton";
  import Sticker from "phosphor-svelte/lib/Sticker";
  import Textbox from "phosphor-svelte/lib/Textbox";
</script>
<Command.Root
  class="divide-border border-muted bg-background flex h-full w-full flex-col divide-y self-start overflow-hidden rounded-xl border"
>
  <Command.Input
    class="focus-override h-input placeholder:text-foreground-alt/50 bg-background focus:outline-hidden inline-flex truncate rounded-tl-xl rounded-tr-xl px-4 text-sm transition-colors focus:ring-0"
    placeholder="Search for something..."
  />
  <Command.List
    class="max-h-[280px] overflow-y-auto overflow-x-hidden px-2 pb-2"
  >
    <Command.Viewport>
      <Command.Empty
        class="text-muted-foreground flex w-full items-center justify-center pb-6 pt-8 text-sm"
      >
        No results found.
      </Command.Empty>
      <Command.Group>
        <Command.GroupHeading
          class="text-muted-foreground px-3 pb-2 pt-4 text-xs"
        >
          Suggestions
        </Command.GroupHeading>
        <Command.GroupItems>
          <Command.Item
            class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
            keywords={["getting started", "tutorial"]}
          >
            <Sticker class="size-4" />
            Introduction
          </Command.Item>
          <Command.Item
            class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
            keywords={["child", "custom element", "snippets"]}
          >
            <CodeBlock class="size-4 " />
            Delegation
          </Command.Item>
          <Command.Item
            class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
            keywords={["css", "theme", "colors", "fonts", "tailwind"]}
          >
            <Palette class="size-4" />
            Styling
          </Command.Item>
        </Command.GroupItems>
      </Command.Group>
      <Command.Separator class="bg-foreground/5 h-px w-full" />
      <Command.Group>
        <Command.GroupHeading
          class="text-muted-foreground px-3 pb-2 pt-4 text-xs"
        >
          Components
        </Command.GroupHeading>
        <Command.GroupItems>
          <Command.Item
            class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
            keywords={["dates", "times"]}
          >
            <CalendarBlank class="size-4" />
            Calendar
          </Command.Item>
          <Command.Item
            class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
            keywords={["buttons", "forms"]}
          >
            <RadioButton class="size-4" />
            Radio Group
          </Command.Item>
          <Command.Item
            class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
            keywords={["inputs", "text", "autocomplete"]}
          >
            <Textbox class="size-4" />
            Combobox
          </Command.Item>
        </Command.GroupItems>
      </Command.Group>
    </Command.Viewport>
  </Command.List>
</Command.Root>

개요(Overview)

Command 컴포넌트, 즉 커맨드 메뉴는 사용자에게 앱 안에서 항목을 빠르고 효율적으로 검색·필터링·선택할 수 있는 방법을 제공하도록 설계됐어요. 검색 입력의 기능과 동적이고 필터링 가능한 명령·옵션 목록을 결합해서, 빠른 내비게이션이나 동작 실행이 필요한 애플리케이션에 이상적이에요.

주요 기능(Key Features)

  • 동적 필터링(Dynamic Filtering): 사용자가 입력 필드에 타이핑하면 명령·항목 목록이 (덮어쓸 수 있는) 스코어링 알고리즘에 따라 즉시 필터링되고 정렬돼요.
  • 키보드 내비게이션(Keyboard Navigation): 키보드 상호작용을 완전히 지원해 마우스 없이도 항목을 빠르게 탐색하고 선택할 수 있어요.
  • 그룹화된 명령(Grouped Commands): 명령을 논리적 그룹으로 정리해 가독성과 구성을 높일 수 있어요.
  • 빈 상태·로딩 상태(Empty and Loading States): 결과가 없거나 결과를 로딩 중일 때를 처리하는 내장 컴포넌트를 제공해요.
  • 접근성(Accessibility): ARIA 속성과 키보드 상호작용으로 화면 낭독기 호환과 접근성 기준을 보장해요.

구조(Architecture)

Command 컴포넌트는 각각의 역할이 분명한 여러 서브 컴포넌트로 구성돼요.

  • Root: 커맨드 메뉴의 전체 상태와 컨텍스트를 관리하는 메인 컨테이너예요.
  • Input: 사용자가 명령을 검색·필터링하기 위해 타이핑하는 텍스트 입력 필드예요.
  • List: 명령·항목 목록의 컨테이너예요.
  • Viewport: 커맨드 목록의 보이는 영역으로, 목록 높이에 따라 동적 크기 조정/애니메이션을 처리하는 CSS 변수를 적용해요.
  • Empty: 결과가 없을 때 표시하는 컴포넌트예요.
  • Loading: 결과를 가져오거나 처리하는 동안 표시하는 컴포넌트예요.
  • Group: 커맨드 메뉴 안의 항목 그룹 컨테이너예요.
  • GroupHeading: 항목 그룹에 접근 가능한 라벨을 제공하는 헤더 요소예요.
  • GroupItems: 그룹 안의 항목들을 담는 컨테이너예요.
  • Item: 개별적으로 선택 가능한 명령 또는 항목이에요.
  • LinkItem: 링크 기반 동작을 위한 Command.Item의 변형이에요.
  • Separator: 커맨드 목록의 다른 섹션을 나누는 시각적 구분선이에요.

구조(Structure)

Command 컴포넌트가 코드에서 어떤 구조로 이루어져 있는지 한눈에 보여드릴게요.

<script lang="ts">
  import { Command } from "bits-ui";
</script>
<Command.Root>
  <Command.Input />
  <Command.List>
    <Command.Viewport>
      <Command.Empty />
      <Command.Loading />
      <Command.Group>
        <Command.GroupHeading />
        <Command.GroupItems>
          <Command.Item />
          <Command.LinkItem />
        </Command.GroupItems>
      </Command.Group>
      <Command.Separator />
      <Command.Item />
      <Command.LinkItem />
    </Command.Viewport>
  </Command.List>
</Command.Root>

value 상태 관리하기

Bits UI는 Command의 value 상태를 관리하고 동기화하는 여러 접근 방식을 제공해요. 제어 수준과 통합 요구에 따라 골라 쓸 수 있어요.

1. 양방향 바인딩(Two-Way Binding)

완벽한 상태 동기화를 위해 Svelte의 bind:value 지시문을 사용해요. 이 방법은 로컬 상태와 컴포넌트 내부 상태를 자동으로 동기화해 줘요.

<script lang="ts">
  import { Command } from "bits-ui";
  let myValue = $state("");
</script>
<button onclick={() => (myValue = "A")}> Select A </button>
<Command.Root bind:value={myValue}>
  <!-- ... -->
</Command.Root>

주요 이점(Key Benefits)

  • 상태 관리를 단순화해요.
  • 내부 상태가 바뀌면(예: 항목 클릭) myValue를 자동으로 갱신해요.
  • 외부에서 제어할 수 있어요(예: 별도 버튼으로 항목 선택).

2. 변경 핸들러(Change Handler)

상태 변경 시 추가 로직을 수행하려면 onValueChange prop을 사용해요. 값이 바뀔 때 부수 효과를 실행해야 하는 경우에 유용해요.

<script lang="ts">
  import { Command } from "bits-ui";
</script>
<Command.Root
  onValueChange={(value) => {
    // do something with the new value
    console.log(value);
  }}
>
  <!-- ... -->
</Command.Root>

사용 사례(Use Cases)

  • 값 변경 시 커스텀 동작 구현하기
  • 외부 상태 관리 솔루션과 통합하기
  • 부수 효과 트리거(예: 로깅, 데이터 가져오기)

3. 완전 제어(Fully Controlled)

컴포넌트의 상태를 완전히 제어하려면 함수 바인딩(Function Binding)을 사용해 value 상태를 외부에서 관리해요. bind:value 지시문에 getter 함수와 setter 함수를 넘겨서 값이 어떻게 갱신·조회되는지 완전히 통제할 수 있어요.

<script lang="ts">
  import { Command } from "bits-ui";
  let myValue = $state("");
</script>
<Command.Root bind:value={() => myValue, (newValue) => (myValue = newValue)}>
  <!-- ... -->
</Command.Root>

언제 사용할까(When to Use)

  • 복잡한 값 변경 로직 구현하기
  • 여러 UI 요소 조율하기
  • 상태 관련 문제 디버깅하기
참고(Note)

완전 제어 상태는 강력하지만 복잡도를 높이고, 주의 깊게 다루지 않으면 예상치 못한 동작을 일으킬 수 있어요. 신중하게 사용하세요.

제어 컴포넌트와 고급 상태 관리 기법에 대한 더 자세한 내용은 State Management 문서를 참고하세요.

모달 안에서 사용하기(In a Modal)

Command 컴포넌트를 Dialog 컴포넌트와 결합하면 모달 안에 커맨드 메뉴를 표시할 수 있어요.

코드 펼치기(Expand Code)

<script lang="ts">
  import { Command, Dialog } from "bits-ui";
  import CalendarBlank from "phosphor-svelte/lib/CalendarBlank";
  import CodeBlock from "phosphor-svelte/lib/CodeBlock";
  import Palette from "phosphor-svelte/lib/Palette";
  import RadioButton from "phosphor-svelte/lib/RadioButton";
  import Sticker from "phosphor-svelte/lib/Sticker";
  import Textbox from "phosphor-svelte/lib/Textbox";
  let dialogOpen = $state(false);
  function handleKeydown(e: KeyboardEvent) {
    if (e.key === "j" && (e.metaKey || e.ctrlKey)) {
      e.preventDefault();
      dialogOpen = true;
    }
  }
</script>
<svelte:document onkeydown={handleKeydown} />
<Dialog.Root bind:open={dialogOpen}>
  <Dialog.Trigger
    class="rounded-input bg-dark text-background
	shadow-mini hover:bg-dark/95 focus-visible:ring-foreground focus-visible:ring-offset-background focus-visible:outline-hidden inline-flex
	h-12 select-none items-center justify-center whitespace-nowrap px-[21px] text-[15px] font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
  >
    Open Command Menu ⌘J
  </Dialog.Trigger>
  <Dialog.Portal>
    <Dialog.Overlay
      class="data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80"
    />
    <Dialog.Content
      class="rounded-card-lg bg-background shadow-popover data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95  data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] outline-hidden fixed left-[50%] top-[50%] z-50 w-full max-w-[94%] translate-x-[-50%] translate-y-[-50%] sm:max-w-[490px] md:w-full"
    >
      <Dialog.Title class="sr-only">Command Menu</Dialog.Title>
      <Dialog.Description class="sr-only">
        This is the command menu. Use the arrow keys to navigate and press ⌘K to
        open the search bar.
      </Dialog.Description>
      <Command.Root
        class="divide-border border-muted bg-background flex h-full w-full flex-col divide-y self-start overflow-hidden rounded-xl border"
      >
        <Command.Input
          class="focus-override h-input bg-background placeholder:text-foreground-alt/50 focus:outline-hidden inline-flex truncate rounded-xl px-4 text-sm transition-colors focus:ring-0"
          placeholder="Search for something..."
        />
        <Command.List
          class="max-h-[280px] overflow-y-auto overflow-x-hidden px-2 pb-2"
        >
          <Command.Viewport>
            <Command.Empty
              class="text-muted-foreground flex w-full items-center justify-center pb-6 pt-8 text-sm"
            >
              No results found.
            </Command.Empty>
            <Command.Group>
              <Command.GroupHeading
                class="text-muted-foreground px-3 pb-2 pt-4 text-xs"
              >
                Suggestions
              </Command.GroupHeading>
              <Command.GroupItems>
                <Command.Item
                  class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
                  keywords={["getting started", "tutorial"]}
                >
                  <Sticker class="size-4" />
                  Introduction
                </Command.Item>
                <Command.Item
                  class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
                  keywords={["child", "custom element", "snippets"]}
                >
                  <CodeBlock class="size-4 " />
                  Delegation
                </Command.Item>
                <Command.Item
                  class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
                  keywords={["css", "theme", "colors", "fonts", "tailwind"]}
                >
                  <Palette class="size-4" />
                  Styling
                </Command.Item>
              </Command.GroupItems>
            </Command.Group>
            <Command.Separator />
            <Command.Group>
              <Command.GroupHeading
                class="text-muted-foreground px-3 pb-2 pt-4 text-xs"
              >
                Components
              </Command.GroupHeading>
              <Command.GroupItems>
                <Command.Item
                  class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
                  keywords={["dates", "times"]}
                >
                  <CalendarBlank class="size-4" />
                  Calendar
                </Command.Item>
                <Command.Item
                  class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
                  keywords={["buttons", "forms"]}
                >
                  <RadioButton class="size-4" />
                  Radio Group
                </Command.Item>
                <Command.Item
                  class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
                  keywords={["inputs", "text", "autocomplete"]}
                >
                  <Textbox class="size-4" />
                  Combobox
                </Command.Item>
              </Command.GroupItems>
            </Command.Group>
          </Command.Viewport>
        </Command.List>
      </Command.Root>
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>

그리드(Grid)

columns prop을 추가하면 커맨드를 그리드 형태로 사용할 수 있어요.

코드 펼치기(Expand Code)

<script lang="ts">
  import { Command } from "bits-ui";
  import Sticker from "phosphor-svelte/lib/Sticker";
  import Smiley from "phosphor-svelte/lib/Smiley";
  import ArrowLeft from "phosphor-svelte/lib/ArrowLeft";
  import { Button } from "../ui/button/index.js";
  import { cn } from "$lib/utils/index.js";
  type Item = {
    icon?: typeof Sticker;
    content: string;
    keywords: string[];
    disabled?: boolean;
    action?: () => void;
  };
  type Group = {
    name: string;
    items: Item[];
  };
  type View = {
    columns: number | undefined;
    empty: string;
    placeholder: string;
    groups: Group[];
  };
  const defaultView: View = {
    columns: undefined,
    placeholder: "Search for something...",
    empty: "No results found.",
    groups: [
      {
        name: "Suggestions",
        items: [
          {
            content: "Search Emojis and Symbols",
            keywords: ["emoji", "symbols"],
            icon: Smiley,
            action: () => {
              search = "";
              views.push(emojiView);
            }
          }
        ]
      }
    ]
  };
  const emojiView: View = {
    columns: 8,
    placeholder: "Search Emoji and Symbols...",
    empty: "No emojis or symbols found.",
    groups: [
      {
        name: "Pinned",
        items: [
          { content: "🤷‍♂️", keywords: ["shrug"] },
          { content: "✅", keywords: ["check", "mark"] },
          { content: "🎉", keywords: ["party"] }
        ]
      },
      {
        name: "Frequently Used",
        items: [
          { content: "¢", keywords: ["cent", "currency"] },
          { content: "📦", keywords: ["box", "cardboard", "shipping"] },
          { content: "🛜", keywords: ["wifi"] },
          { content: "🔥", keywords: ["fire", "hot"] },
          { content: "⭐", keywords: ["star", "favorite"] },
          { content: "👍", keywords: ["thumbs up", "like", "approve"] },
          { content: "🚀", keywords: ["rocket", "launch"] },
          { content: "👏", keywords: ["clap", "applause"] }
        ]
      },
      {
        name: "All Emojis",
        items: [
          { content: "😊", keywords: ["smile", "happy", "face"] },
          { content: "❤️", keywords: ["heart", "love"] },
          { content: "👀", keywords: ["eyes", "look", "see"] },
          { content: "💡", keywords: ["lightbulb", "idea"] },
          { content: "☕", keywords: ["coffee", "drink", "break"] },
          { content: "💻", keywords: ["computer", "laptop", "work"] },
          { content: "✏️", keywords: ["pencil", "edit", "write"] },
          { content: "📅", keywords: ["calendar", "date", "schedule"] },
          { content: "📱", keywords: ["phone", "call", "mobile"] },
          { content: "🎵", keywords: ["music", "note", "song"] },
          { content: "📷", keywords: ["camera", "photo", "picture"] },
          { content: "🎁", keywords: ["gift", "present", "surprise"] },
          { content: "🌙", keywords: ["moon", "night", "sleep"] },
          { content: "☀️", keywords: ["sun", "day", "weather"] },
          { content: "🌈", keywords: ["rainbow", "color", "pride"] },
          { content: "🌍", keywords: ["earth", "world", "globe"] },
          { content: "🌳", keywords: ["tree", "nature", "plant"] },
          { content: "🌸", keywords: ["flower", "nature", "spring"] },
          { content: "🎆", keywords: ["fireworks", "celebration", "festival"] },
          { content: "🎈", keywords: ["balloon", "party", "birthday"] },
          { content: "🍪", keywords: ["cookie", "snack", "dessert"] },
          { content: "🍕", keywords: ["pizza", "food", "slice"] },
          { content: "🍦", keywords: ["ice cream", "dessert", "sweet"] },
          { content: "🍎", keywords: ["apple", "fruit", "food"] },
          { content: "🍌", keywords: ["banana", "fruit", "yellow"] },
          { content: "🚗", keywords: ["car", "vehicle", "drive"] },
          { content: "🚲", keywords: ["bicycle", "bike", "ride"] },
          { content: "🚆", keywords: ["train", "travel", "transport"] },
          { content: "✈️", keywords: ["airplane", "flight", "travel"] },
          { content: "⚓", keywords: ["anchor", "boat", "sea"] },
          { content: "🏅", keywords: ["medal", "award", "winner"] },
          { content: "⚽", keywords: ["soccer", "football", "sport"] },
          { content: "🏀", keywords: ["basketball", "sport", "game"] },
          { content: "🏆", keywords: ["trophy", "award", "win"] },
          { content: "📚", keywords: ["book", "read", "study"] },
          { content: "✉️", keywords: ["mail", "envelope", "letter"] },
          { content: "🤩", keywords: ["star eyes", "excited", "wow"] },
          { content: "🤔", keywords: ["thinking", "hmm", "question"] },
          { content: "😴", keywords: ["sleepy", "tired", "zzz"] },
          { content: "😢", keywords: ["cry", "sad", "tears"] },
          { content: "😂", keywords: ["laugh", "joy", "funny"] },
          { content: "😉", keywords: ["wink", "flirt", "smile"] },
          { content: "🤓", keywords: ["nerd", "geek", "glasses"] },
          { content: "🤖", keywords: ["robot", "ai", "machine"] },
          { content: "👻", keywords: ["ghost", "spooky", "halloween"] },
          { content: "👽", keywords: ["alien", "space", "ufo"] }
        ]
      }
    ]
  };
  const views: View[] = $state([defaultView, emojiView]);
  const currentView = $derived(views[views.length - 1]);
  let search = $state("");
  function popView() {
    if (views.length > 1) {
      views.pop();
    }
  }
</script>
<Command.Root
  disableInitialScroll={true}
  columns={currentView.columns}
  class="divide-border border-muted bg-background flex h-full w-full flex-col divide-y self-start overflow-hidden rounded-xl border"
>
  <div class="flex items-center">
    {#if views.length > 1}
      <Button variant="ghost" onclick={() => views.pop()}>
        <ArrowLeft />
      </Button>
    {/if}
    <Command.Input
      autofocus={false}
      class={cn(
        "focus-override h-input placeholder:text-foreground-alt/50 bg-background focus:outline-hidden inline-flex flex-1 truncate rounded-tl-xl rounded-tr-xl pr-4 text-sm transition-colors focus:ring-0",
        { "pl-4": views.length === 1 }
      )}
      bind:value={search}
      onkeydown={(e) => {
        if (e.key === "Backspace" && search.length === 0) {
          e.preventDefault();
          popView();
        }
      }}
      placeholder={currentView.placeholder}
    />
  </div>
  {#if currentView.columns !== undefined}
    <Command.List
      class="max-h-[280px] overflow-y-auto overflow-x-hidden px-2 pb-2"
    >
      <Command.Viewport>
        <Command.Empty
          class="text-muted-foreground flex w-full items-center justify-center pb-6 pt-8 text-sm"
        >
          {currentView.empty}
        </Command.Empty>
        {#each currentView.groups as group (group)}
          <Command.Group>
            <Command.GroupHeading
              class="text-muted-foreground px-2 pb-2 pt-4 text-xs"
            >
              {group.name}
            </Command.GroupHeading>
            <Command.GroupItems class="grid grid-cols-8 gap-2 px-2">
              {#each group.items as groupItem (groupItem)}
                <Command.Item
                  class="rounded-button bg-muted data-selected:ring-foreground outline-hidden flex aspect-square size-full cursor-pointer select-none items-center justify-center text-2xl ring-2 ring-transparent aria-disabled:cursor-not-allowed aria-disabled:opacity-50"
                  keywords={groupItem.keywords}
                  disabled={groupItem.disabled}
                >
                  {#if groupItem.icon}
                    <groupItem.icon class="size-4" />
                  {:else}
                    {groupItem.content}
                  {/if}
                </Command.Item>
              {/each}
            </Command.GroupItems>
          </Command.Group>
        {/each}
      </Command.Viewport>
    </Command.List>
  {:else}
    <Command.List
      class="max-h-[280px] overflow-y-auto overflow-x-hidden px-2 pb-2"
    >
      <Command.Viewport>
        <Command.Empty
          class="text-muted-foreground flex w-full items-center justify-center pb-6 pt-8 text-sm"
        >
          {currentView.empty}
        </Command.Empty>
        {#each currentView.groups as group (group)}
          <Command.Group>
            <Command.GroupHeading
              class="text-muted-foreground px-3 pb-2 pt-4 text-xs"
            >
              {group.name}
            </Command.GroupHeading>
            <Command.GroupItems>
              {#each group.items as groupItem (groupItem)}
                <Command.Item
                  class="rounded-button data-selected:bg-muted outline-hidden flex h-10 cursor-pointer select-none items-center gap-2 px-3 py-2.5 text-sm capitalize"
                  keywords={groupItem.keywords}
                  disabled={groupItem.disabled}
                  onSelect={groupItem.action}
                >
                  {#if groupItem.icon}
                    <groupItem.icon class="size-4" />
                  {/if}
                  {groupItem.content}
                </Command.Item>
              {/each}
            </Command.GroupItems>
          </Command.Group>
        {/each}
      </Command.Viewport>
    </Command.List>
  {/if}
</Command.Root>

필터링(Filtering)

커스텀 필터(Custom Filter)

기본적으로 Command 컴포넌트는 항목을 어떻게 정렬·필터링할지 결정하는 스코어링 알고리즘을 사용해요. 커스텀 필터 함수를 제공하면 이 동작을 덮어쓸 수 있어요.

함수는 0과 1 사이의 숫자를 반환해야 해요. 1은 완벽한 매치, 0은 매치 없음(항목이 완전히 숨겨짐)을 의미해요.

다음 예시는 엄격한 부분 문자열 매치 필터를 구현하는 방법을 보여줘요.

<script lang="ts">
  import { Command } from "bits-ui";
  function customFilter(
    commandValue: string,
    search: string,
    commandKeywords?: string[]
  ): number {
    return commandValue.includes(search) ? 1 : 0;
  }
</script>
<Command.Root filter={customFilter}>
  <!-- ... -->
</Command.Root>

기본 필터 확장(Extend Default Filter)

기본적으로 Command 컴포넌트는 computeCommandScore 함수를 사용해 각 항목의 점수를 결정하고 그에 따라 필터·정렬해요. 이 함수는 필요에 따라 사용하고 확장할 수 있도록 export되어 있어요.

<script lang="ts">
  import { Command, computeCommandScore } from "bits-ui";
  function customFilter(
    commandValue: string,
    search: string,
    commandKeywords?: string[]
  ): number {
    const score = computeCommandScore(commandValue, search, commandKeywords);
    // Add custom logic here
    return score;
  }
</script>
<Command.Root filter={customFilter}>
  <!-- ... -->
</Command.Root>

필터링 비활성화(Disable Filtering)

shouldFilter prop을 false로 설정하면 필터링을 꺼둘 수 있어요.

<Command.Root shouldFilter={false}>
  <!-- ... -->
</Command.Root>

커스텀 로직이 많거나, 항목을 비동기로 가져와야 하거나, 필터링을 직접 처리하고 싶은 경우에 유용해요. 항목을 순회하며 어떤 항목을 보여줄지 직접 결정해야 해요.

항목 선택(Item Selection)

onSelect prop을 사용해 항목 선택을 처리할 수 있어요.

<Command.Item onSelect={() => console.log("selected something!")} />

항목 중 하나가 링크의 모든 이점(프리페칭 등)을 누리길 원한다면 Command.Item 대신 Command.LinkItem 컴포넌트를 사용해야 해요. 유일한 차이는 Command.LinkItem이 div 대신 a 요소를 렌더링한다는 점이에요.

<Command.LinkItem href="/some/path">
  <!-- ... -->
</Command.LinkItem>

명령형 API(Imperative API)

커스텀 키바인딩 같은 더 고급 사용 사례를 위해 Command.Root 컴포넌트는 프로그래밍 방식 제어를 위한 여러 메서드를 노출해요.

이 메서드들은 컴포넌트에 바인딩해서 접근할 수 있어요.

<script lang="ts">
  import { Command } from "bits-ui";
  let command: typeof Command.Root;
</script>
<Command.Root bind:this={command}>
  <!-- ... -->
</Command.Root>

메서드(Methods)

getValidItems()

유효한(비활성화되지 않고 보이는) 커맨드 항목의 배열을 반환해요. 작업 전에 경계를 확인할 때 유용해요.

const items = command.getValidItems();
console.log(items.length); // number of selectable items

updateSelectedToIndex(index: number)

지정한 인덱스의 항목으로 선택을 설정해요. 인덱스가 유효하지 않으면 아무 일도 하지 않아요.

// select third item (if it exists)
command.updateSelectedToIndex(2);
// with bounds check
const items = command.getValidItems();
if (index < items.length) {
  command.updateSelectedToIndex(index);
}

updateSelectedByGroup(change: 1 | -1)

다음/이전 그룹의 첫 번째 항목으로 선택을 이동해요. 그룹이 없으면 다음/이전 항목으로 대체돼요.

command.updateSelectedByGroup(1); // move to next group
command.updateSelectedByGroup(-1); // move to previous group

updateSelectedByItem(change: 1 | -1)

현재 항목을 기준으로 위/아래로 선택을 이동해요. loop 옵션이 켜져 있으면 끝에서 다시 돌아와요.

command.updateSelectedByItem(1); // next item
command.updateSelectedByItem(-1); // previous item

사용 예시(Usage Example)

<script lang="ts">
  import { Command } from "bits-ui";
  let command: typeof Command.Root;
  function jumpToLastItem() {
    if (!command) return;
    const items = command.getValidItems();
    if (!items.length) return;
    command.updateSelectedToIndex(items.length - 1);
  }
</script>
<svelte:window
  onkeydown={(e) => {
    if (e.key === "o") {
      jumpToLastItem();
    }
  }}
/>
<Command.Root bind:this={command}>
  <!-- Command content -->
</Command.Root>

흔한 실수(Common Mistakes)

중복 value

각 Command.Item의 value는 반드시 고유해야 해요. 같은 값을 가진 항목이 두 개 있으면 컴포넌트가 어느 것을 선택해야 할지 결정할 수 없어서, 키보드 탐색이나 마우스 호버 시 예상치 못한 동작이 생겨요.

어떤 이유로 두 항목의 텍스트 내용이 같다면 value prop으로 각 항목에 고유한 값을 설정해야 해요. value를 설정하면 텍스트 내용은 표시 용도로만 쓰이고, 필터링과 선택에는 value prop이 사용돼요.

흔한 패턴은 value 뒤에 ID나 숫자 같은 고유한 값을 붙여서 필터링이 여전히 value와 매치되게 하는 거예요.

<Command.Item value="my item 1">My Item</Command.Item>
<Command.Item value="my item 2">My Item</Command.Item>

API 참조(API Reference)

Command.Root

컴포넌트의 전체 상태와 컨텍스트를 관리하는 메인 컨테이너예요.

Property Type Description Details
value $bindable string The value of the command.Default:
onValueChange function - (value: string) => void A callback that is fired when the command value changes.Default:  —— undefined
label string An accessible label for the command menu. This is not visible and is only used for screen readers.Default:  —— undefined
filter function - (value: string, search: string, keywords?: string[]) => number; A custom filter function used to filter items. This function should return a number between 0 and 1, with 1 being a perfect match, and 0 being no match, resulting in the item being hidden entirely. The items are sorted/filtered based on this score.Default:  —— undefined
shouldFilter boolean Whether or not the command menu should filter items. This is useful when you want to apply custom filtering logic outside of the Command component.Default: true
columns number The number of columns in the grid layout ifDefault:  —— undefined
onStateChange function - type CommandState = { /** The value of the search query */ search: string /** The value of the selected command menu item */ value: string /** The filtered items */ filtered: { /** The count of all visible items. */ count: number /** Map from visible item id to its search store. */ items: Map<string, number> /** Set of groups with at least one visible item. */ groups: Set<string> } } type onStateChange = (state: Readonly<CommandState>) => void A callback that fires when the command's internal state changes. This callback receives a readonly snapshot of the current state. The callback is debounced and only fires once per batch of related updates (e.g., when typing triggers filtering and selection changes).Default:  —— undefined
loop boolean Whether or not the command menu should loop through items when navigating with the keyboard.Default: false
disablePointerSelection boolean Set this to true to prevent items from being selected when the users pointer moves over them.Default: false
vimBindings boolean Whether VIM bindings should be enabled or not, which allow the user to navigate using ctrl+n/j/p/kDefault: true
disableInitialScroll boolean Whether to disable scrolling the selected item into view on initial mount. When true, prevents automatic scrolling when the command menu first renders and selects its first item, but still allows scrolling on subsequent selections.Default: false
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-root '' Present on the root element.

Command.Input

사용자가 명령을 검색·필터링하기 위해 타이핑하는 텍스트 입력 필드예요.

Property Type Description Details
value $bindable string The value of the search query. This is used to filter items and to search for items.Default:  —— undefined
ref $bindable HTMLInputElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-input '' Present on the input element.

Command.List

커맨드 메뉴의 뷰포트, 항목, 기타 요소들의 컨테이너예요.

Property Type Description Details
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-list '' Present on the list element.
CSS Variable Description Details
--bits-command-list-height The height of the command list element, which is computed by the Command.Viewport component.

Command.Viewport

커맨드 목록의 보이는 영역으로, 목록 높이에 따라 동적 크기 조정/애니메이션을 처리하는 CSS 변수를 적용해요.

Property Type Description Details
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-viewport '' Present on the viewport element.

Command.Group

커맨드 메뉴 안의 항목 그룹 컨테이너예요.

Property Type Description Details
value string If a Command.GroupHeading is used within this group, the contents of the heading will be used as the value. If the content is dynamic or you wish to have a more specific value, you can provide a unique value for the group here.Default:  —— undefined
forceMount boolean Whether or not the group should always be mounted to the DOM, regardless of the internal filtering logicDefault: false
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-group '' Present on the group element.

Command.GroupHeading

항목 그룹에 접근 가능한 라벨을 제공하는 헤더 요소예요.

Property Type Description Details
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-group-heading '' Present on the group heading element.

Command.GroupItems

그룹 안의 항목들을 담는 컨테이너예요.

Property Type Description Details
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-group-items '' Present on the group items element.

Command.Item

커맨드 메뉴 안의 개별 항목을 나타내요. 페이지로 연결하는 앵커 요소를 렌더링하고 싶다면 Command.LinkItem 컴포넌트를 사용하세요.

Property Type Description Details
value required string The value of the item.Default:  —— undefined
keywords string[] An array of additional keywords or aliases that will be used to filter the item.Default:  —— undefined
forceMount boolean Whether or not the item should always be mounted to the DOM, regardless of the internal filtering logicDefault: false
onSelect function - () => void A callback that is fired when the item is selected.Default:  —— undefined
disabled boolean Whether or not the combobox item is disabled. This will prevent interaction/selection.Default: false
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-disabled '' Present when the item is disabled.
data-selected '' Present when the item is selected.
data-command-item '' Present on the item element.

Command.LinkItem

Command.Item 컴포넌트와 비슷하지만, 내비게이션 전에 프리로딩을 활용할 수 있도록 앵커 요소를 렌더링해요.

Property Type Description Details
value required string The value of the item.Default:  —— undefined
keywords string[] An array of additional keywords or aliases that will be used to filter the item.Default:  —— undefined
forceMount boolean Whether or not the item should always be mounted to the DOM, regardless of the internal filtering logicDefault: false
onSelect function - () => void A callback that is fired when the item is selected.Default:  —— undefined
disabled boolean Whether or not the combobox item is disabled. This will prevent interaction/selection.Default: false
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-disabled '' Present when the item is disabled.
data-selected '' Present when the item is selected.
data-command-item '' Present on the item element.

Command.Empty

결과가 없을 때 표시하는 컴포넌트예요.

Property Type Description Details
forceMount boolean Whether or not to forcefully mount the empty state, regardless of the internal filtering logic. Useful when you want to handle filtering yourself.Default: false
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-empty '' Present on the empty element.

Command.Loading

결과를 가져오거나 처리하는 동안 표시하는 컴포넌트예요.

Property Type Description Details
progress number The progress of the loading state.Default: 0
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-loading '' Present on the loading element.

Command.Separator

커맨드 목록의 다른 섹션을 나누는 시각적 구분선이에요. 검색어가 비어 있거나 forceMount prop이 true일 때 보여요.

Property Type Description Details
forceMount boolean Whether or not the separator should always be mounted to the DOM, regardless of the internal filtering logicDefault: false
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-command-separator '' Present on the separator element.

더 알아보기 (Learn more)

커맨드 메뉴는 빠른 검색·선택에 특화되어 있어 콤보박스(Combobox)와 많은 아이디어를 공유해요. 모달 안에 넣어 쓰고 싶다면 다이얼로그(Dialog) 컴포넌트와의 조합도 살펴보면 좋아요.