---
title: "CommandPalette"
description: "Командная палитра с поиском на базе Fuse.js: быстрый нечёткий поиск по тексту."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/command-palette"
---
# CommandPalette

> Командная палитра с поиском на базе Fuse.js: быстрый нечёткий поиск по тексту.

## Использование

Директива `v-model` управляет значением CommandPalette, а пропс `default-value` задаёт начальное значение, если состоянием управлять не нужно.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'users',
    label: 'Пользователи',
    items: [
      {
        label: 'Assistant Name',
        suffix: 'assistant',
        avatar: {
          src: '/b24ui/avatar/assistant.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Bitrix24',
        suffix: 'bitrix24',
        avatar: {
          src: 'https://github.com/bitrix24.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Employee Name',
        suffix: 'employee',
        avatar: {
          src: '/b24ui/avatar/employee.png',
          loading: 'lazy'
        }
      }
    ]
  }
])
const value = ref({})
</script>

<template>
  <B24CommandPalette v-model="value" :groups="groups" class="flex-1" />
</template>
```

> [!TIP]
> See: #control-selected-items
> Выбранные элементы можно отслеживать и через событие `@update:model-value`.

### Группы

CommandPalette фильтрует группы и ранжирует подходящие команды по релевантности по мере ввода. Поиск мгновенный и динамический, что упрощает поиск команд. Пропс `groups` — массив объектов со свойствами:

- `id: string`
- `label?: string`
- `slot?: string`
- `items?: CommandPaletteItem[]`
- [`ignoreFilter?: boolean`](#with-ignore-filter)
- [`postFilter?: (searchTerm: string, items: T[]) => T[]`](#with-post-filtered-items)
- `highlightedIcon?: IconComponent`

> [!CAUTION]
> У каждой группы должен быть `id`, иначе группа игнорируется.

В каждой группе есть массив `items` — объекты, описывающие команды. У элемента могут быть свойства:

- `prefix?: string`
- `label?: string`
- `suffix?: string`
- `icon?: IconComponent`
- `avatar?: AvatarProps`
- `chip?: ChipProps`
- `kbds?: string[] | KbdProps[]`
- `active?: boolean`
- `loading?: boolean`
- `disabled?: boolean`
- [`slot?: string`](#with-custom-slot)
- `placeholder?: string`
- `children?: CommandPaletteItem[]`
- `labelHtml?: string`
- `suffixHtml?: string`
- `descriptionHtml?: string`
- `onSelect?: (e: Event) => void`
- `class?: any`
- `b24ui?: { item?: ClassNameValue, itemLeadingIcon?: ClassNameValue, itemLeadingAvatarSize?: ClassNameValue, itemLeadingAvatar?: ClassNameValue, itemLeadingChipSize?: ClassNameValue, itemLeadingChip?: ClassNameValue, itemLabel?: ClassNameValue, itemLabelPrefix?: ClassNameValue, itemLabelBase?: ClassNameValue, itemLabelSuffix?: ClassNameValue, itemTrailing?: ClassNameValue, itemTrailingKbds?: ClassNameValue, itemTrailingKbdsSize?: ClassNameValue, itemTrailingHighlightedIcon?: ClassNameValue, itemTrailingIcon?: ClassNameValue }`

Можно передать любое свойство компонента [Link](https://b24-ui.bx-shef.by/raw/docs/components/link.md#props): `to`, `target` и другие.

> [!CAUTION]
> `labelHtml`, `suffixHtml` и `descriptionHtml` вставляются через `v-html`. Обычно палитра сама вычисляет их по совпадению с поиском: всё экранируется, найденный фрагмент оборачивается в `<mark>`. Значение, заданное вручную, этот шаг пропускает и отрисовывается как сырой HTML. Очищайте всё, что приходит из CMS, API или от пользователей, прежде чем передавать сюда.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'users',
    label: 'Пользователи',
    items: [
      {
        label: 'Assistant Name',
        suffix: 'assistant',
        avatar: {
          src: '/b24ui/avatar/assistant.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Bitrix24',
        suffix: 'bitrix24',
        avatar: {
          src: 'https://github.com/bitrix24.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Employee Name',
        suffix: 'employee',
        avatar: {
          src: '/b24ui/avatar/employee.png',
          loading: 'lazy'
        }
      }
    ]
  }
])
const value = ref({})
</script>

<template>
  <B24CommandPalette v-model="value" :groups="groups" class="flex-1" />
</template>
```

> [!TIP]
> See: #with-children-in-items
> Чтобы создать подменю, элемент может содержать массив `children` с такими же свойствами:

### Множественный выбор

Пропс `multiple` разрешает выбрать несколько элементов.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'users',
    label: 'Пользователи',
    items: [
      {
        label: 'Assistant Name',
        suffix: 'assistant',
        avatar: {
          src: '/b24ui/avatar/assistant.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Bitrix24',
        suffix: 'bitrix24',
        avatar: {
          src: 'https://github.com/bitrix24.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Employee Name',
        suffix: 'employee',
        avatar: {
          src: '/b24ui/avatar/employee.png',
          loading: 'lazy'
        }
      }
    ]
  }
])
const value = ref([])
</script>

<template>
  <B24CommandPalette multiple v-model="value" :groups="groups" class="flex-1" />
</template>
```

> [!CAUTION]
> Передавайте в пропс `default-value` или в директиву `v-model` массив.

### Плейсхолдер

Пропс `placeholder` меняет текст плейсхолдера.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette placeholder="Найти приложение..." :groups="groups" class="flex-1" />
</template>
```

### Размер

Пропс `size` меняет размер CommandPalette.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette size="xl" :groups="groups" class="flex-1" />
</template>
```

### Иконка

Пропс `icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) в поле ввода.

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette :icon="RocketIcon" :groups="groups" class="flex-1" />
</template>
```

### Иконка выбранного элемента

Пропс `selected-icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) выбранного элемента.

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'users',
    label: 'Пользователи',
    items: [
      {
        label: 'Assistant Name',
        suffix: 'assistant',
        avatar: {
          src: '/b24ui/avatar/assistant.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Bitrix24',
        suffix: 'bitrix24',
        avatar: {
          src: 'https://github.com/bitrix24.png',
          loading: 'lazy'
        }
      },
      {
        label: 'Employee Name',
        suffix: 'employee',
        avatar: {
          src: '/b24ui/avatar/employee.png',
          loading: 'lazy'
        }
      }
    ]
  }
])
const value = ref([
  {
    label: 'Bitrix24',
    suffix: 'bitrix24',
    avatar: {
      src: 'https://github.com/bitrix24.png',
      loading: 'lazy'
    }
  }
])
</script>

<template>
  <B24CommandPalette multiple v-model="value" :selected-icon="RocketIcon" :groups="groups" class="flex-1" />
</template>
```

### Иконка справа

Пропс `trailing-icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) справа у элементов с подменю.

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'actions',
    items: [
      {
        label: 'Поделиться',
        children: [
          {
            label: 'Почта'
          },
          {
            label: 'Копировать'
          },
          {
            label: 'Ссылка'
          }
        ]
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette :trailing-icon="RocketIcon" :groups="groups" class="flex-1" />
</template>
```

### Загрузка

Пропс `loading` показывает в CommandPalette иконку загрузки.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette loading :groups="groups" class="flex-1" />
</template>
```

### Закрытие

Пропс `close` показывает кнопку [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md), которая закрывает CommandPalette.

> [!TIP]
> По нажатию на кнопку закрытия срабатывает событие `update:open`.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette close :groups="groups" class="flex-1" />
</template>
```

Кнопку можно настроить любым свойством компонента [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md).

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette :close="{color:'air-primary',rounded:true,size:'md'}" :groups="groups" class="flex-1" />
</template>
```

### Иконка закрытия

Пропс `close-icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) кнопки закрытия.

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette close :close-icon="RocketIcon" :groups="groups" class="flex-1" />
</template>
```

### Кнопка «Назад»

Пропс `back` настраивает кнопку «Назад», которая показывается при переходе в подменю, или скрывает её (значение `false`).

Кнопку можно настроить любым свойством компонента [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md).

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'actions',
    items: [
      {
        label: 'Поделиться',
        children: [
          {
            label: 'Почта'
          },
          {
            label: 'Копировать'
          },
          {
            label: 'Ссылка'
          }
        ]
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette :back="{color:'air-primary'}" :groups="groups" class="flex-1" />
</template>
```

### Иконка кнопки «Назад»

Пропс `back-icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) кнопки «Назад».

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'actions',
    items: [
      {
        label: 'Поделиться',
        children: [
          {
            label: 'Почта'
          },
          {
            label: 'Копировать'
          },
          {
            label: 'Ссылка'
          }
        ]
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette :back-icon="RocketIcon" :groups="groups" class="flex-1" />
</template>
```

### Отключение

Пропс `disabled` отключает CommandPalette.

```vue
<script setup lang="ts">
import type { CommandPaletteGroup } from '@bxshefby/b24ui-nuxt'

const groups = ref<CommandPaletteGroup[]>([
  {
    id: 'apps',
    items: [
      {
        label: 'Календарь'
      },
      {
        label: 'Музыка'
      },
      {
        label: 'Карты'
      }
    ]
  }
])
</script>

<template>
  <B24CommandPalette disabled :groups="groups" class="flex-1" />
</template>
```

## Примеры

### Управление выбранными элементами

Выбранными элементами можно управлять через пропс `default-value` или директиву `v-model`, через поле `onSelect` у каждого элемента или через событие `@update:model-value`.

```vue [CommandPaletteSelectExample.vue]
<script setup lang="ts">
import FileUploadIcon from '@bitrix24/b24icons-vue/main/FileUploadIcon'
import FolderPlusIcon from '@bitrix24/b24icons-vue/outline/FolderPlusIcon'
import TagIcon from '@bitrix24/b24icons-vue/outline/TagIcon'
import StageIcon from '@bitrix24/b24icons-vue/outline/StageIcon'

const toast = useToast()

const groups = ref([
  {
    id: 'users',
    label: 'Пользователи',
    items: [
      {
        label: 'Имя ассистента',
        suffix: 'assistant',
        to: 'https://github.com/bitrix24',
        target: '_blank',
        avatar: {
          src: '/b24ui/avatar/assistant.png',
          loading: 'lazy' as const
        }
      },
      {
        label: 'Bitrix24',
        suffix: 'bitrix24',
        to: 'https://github.com/bitrix24',
        target: '_blank',
        avatar: {
          src: 'https://github.com/bitrix24.png',
          loading: 'lazy' as const
        }
      },
      {
        label: 'Имя сотрудника',
        suffix: 'employee',
        to: 'https://github.com/bitrix24',
        target: '_blank',
        avatar: {
          src: '/b24ui/avatar/employee.png',
          loading: 'lazy' as const
        }
      }
    ]
  },
  {
    id: 'actions',
    items: [
      {
        label: 'Добавить новый файл',
        suffix: 'Создать новый файл в текущей папке или рабочем пространстве.',
        icon: FileUploadIcon,
        kbds: [
          'meta',
          'I'
        ],
        onSelect() {
          toast.add({ title: 'Добавить новый файл' })
        }
      },
      {
        label: 'Добавить новую папку',
        suffix: 'Создать новую папку в текущей папке или рабочем пространстве.',
        icon: FolderPlusIcon,
        kbds: [
          'meta',
          'F'
        ],
        onSelect() {
          toast.add({ title: 'Добавить новую папку' })
        }
      },
      {
        label: 'Добавить хештег',
        suffix: 'Добавить хештег к текущему элементу.',
        icon: TagIcon,
        kbds: [
          'meta',
          'H'
        ],
        onSelect() {
          toast.add({ title: 'Добавить хештег' })
        }
      },
      {
        label: 'Добавить метку',
        suffix: 'Добавить метку к текущему элементу.',
        icon: StageIcon,
        kbds: [
          'meta',
          'L'
        ],
        onSelect() {
          toast.add({ title: 'Добавить метку' })
        }
      }
    ]
  }
])

function onSelect(item: any) {
  console.log(item)
}
</script>

<template>
  <B24CommandPalette
    :groups="groups"
    class="flex-1 h-80"
    @update:model-value="onSelect"
  />
</template>
```

> [!TIP]
> Пропс `value-key` выбирает поле элемента, которое используется как значение вместо самого объекта. Пропс `by` сравнивает объекты по полю, а не по ссылке.

### Управление поисковым запросом

Директива `v-model:search-term` управляет поисковым запросом.

```vue [CommandPaletteSearchTermExample.vue]
<script setup lang="ts">
const users = [
  {
    label: 'Имя ассистента',
    suffix: 'assistant',
    to: 'https://github.com/bitrix24',
    target: '_blank',
    avatar: {
      src: '/b24ui/avatar/assistant.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Bitrix24',
    suffix: 'bitrix24',
    to: 'https://github.com/bitrix24',
    target: '_blank',
    avatar: {
      src: 'https://github.com/bitrix24.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Имя сотрудника',
    suffix: 'employee',
    to: 'https://github.com/bitrix24',
    target: '_blank',
    avatar: {
      src: '/b24ui/avatar/employee.png',
      loading: 'lazy' as const
    }
  }
]

const searchTerm = ref('B')

function onSelect() {
  searchTerm.value = ''
}
</script>

<template>
  <B24CommandPalette
    v-model:search-term="searchTerm"
    :groups="[{ id: 'users', items: users }]"
    class="flex-1"
    @update:model-value="onSelect"
  />
</template>
```

> [!NOTE]
> В этом примере событие `@update:model-value` сбрасывает поисковый запрос при выборе элемента.

### Вложенные элементы

Иерархические меню создаются свойством `children` у элементов. Если у элемента есть `children`, он автоматически показывает шеврон, и по нему можно перейти в подменю.

```vue [CommandPaletteItemsChildrenExample.vue]
<script setup lang="ts">
import CirclePlusIcon from '@bitrix24/b24icons-vue/outline/CirclePlusIcon'
import FileUploadIcon from '@bitrix24/b24icons-vue/main/FileUploadIcon'
import FolderPlusIcon from '@bitrix24/b24icons-vue/outline/FolderPlusIcon'
import AddProductIcon from '@bitrix24/b24icons-vue/outline/AddProductIcon'
import ShareIcon from '@bitrix24/b24icons-vue/button/ShareIcon'
import LinkIcon from '@bitrix24/b24icons-vue/outline/LinkIcon'
import MailSendIcon from '@bitrix24/b24icons-vue/outline/MailSendIcon'
import Share2Icon from '@bitrix24/b24icons-vue/main/Share2Icon'
import TwitterIcon from '@bitrix24/b24icons-vue/common-service/TwitterIcon'
import TelegramIcon from '@bitrix24/b24icons-vue/social/TelegramIcon'
import SettingsLIcon from '@bitrix24/b24icons-vue/outline/SettingsLIcon'
import Filter1Icon from '@bitrix24/b24icons-vue/main/Filter1Icon'
import PaletteIcon from '@bitrix24/b24icons-vue/outline/PaletteIcon'
import ShieldIcon from '@bitrix24/b24icons-vue/outline/ShieldIcon'

const toast = useToast()

const groups = [{
  id: 'actions',
  label: 'Действия',
  items: [
    {
      label: 'Создать',
      icon: CirclePlusIcon,
      children: [
        {
          label: 'Новый файл',
          icon: FileUploadIcon,
          suffix: 'Создать новый файл в текущей папке',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Новый файл создан!' })
          },
          kbds: ['meta', 'I']
        },
        {
          label: 'Новая папка',
          icon: FolderPlusIcon,
          suffix: 'Создать новую папку в текущей папке',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Новая папка создана!' })
          },
          kbds: ['meta', 'F']
        },
        {
          label: 'Новый проект',
          icon: AddProductIcon,
          suffix: 'Создать новый проект из шаблона',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Новый проект создан!' })
          },
          kbds: ['meta', 'P']
        }
      ]
    },
    {
      label: 'Поделиться',
      icon: ShareIcon,
      children: [
        {
          label: 'Копировать ссылку',
          icon: LinkIcon,
          suffix: 'Скопировать ссылку на текущий элемент',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Ссылка скопирована в буфер обмена!' })
          },
          kbds: ['meta', 'L']
        },
        {
          label: 'Поделиться по email',
          icon: MailSendIcon,
          suffix: 'Поделиться текущим элементом по email',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Диалог отправки по email открыт!' })
          }
        },
        {
          label: 'Поделиться в соцсетях',
          icon: Share2Icon,
          suffix: 'Поделиться текущим элементом в соцсетях',
          children: [
            {
              label: 'Twitter',
              icon: TwitterIcon,
              onSelect(e: Event) {
                e.preventDefault()
                toast.add({ title: 'Отправлено в Twitter!' })
              }
            },
            {
              label: 'Telegram',
              icon: TelegramIcon,
              onSelect(e: Event) {
                e.preventDefault()
                toast.add({ title: 'Отправлено в Telegram!' })
              }
            }
          ]
        }
      ]
    },
    {
      label: 'Настройки',
      icon: SettingsLIcon,
      children: [
        {
          label: 'Общие',
          icon: Filter1Icon,
          suffix: 'Настроить общие параметры',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Общие настройки открыты!' })
          }
        },
        {
          label: 'Внешний вид',
          icon: PaletteIcon,
          suffix: 'Настроить внешний вид',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Настройки внешнего вида открыты!' })
          }
        },
        {
          label: 'Безопасность',
          icon: ShieldIcon,
          suffix: 'Управление настройками безопасности',
          onSelect(e: Event) {
            e.preventDefault()
            toast.add({ title: 'Настройки безопасности открыты!' })
          }
        }
      ]
    }
  ]
}]
</script>

<template>
  <B24CommandPalette :groups="groups" class="flex-1" />
</template>
```

> [!NOTE]
> При переходе в подменю:
> - поисковый запрос сбрасывается;
> - в поле ввода появляется кнопка «Назад»;
> - к предыдущей группе можно вернуться клавишей <kbd value="backspace">
> </kbd>
> .

### Элементы из API

Элементы можно получать из API и использовать в CommandPalette.

```vue [CommandPaletteFetchExample.vue]
<script setup lang="ts">
const searchTerm = ref('')

const { data: users, status } = useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'command-palette-users',
  transform: (data: { id: number, name: string, email: string }[]) => {
    return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
  },
  server: false
})

const groups = computed(() => [{
  id: 'users',
  label: searchTerm.value ? `Пользователи по запросу «${searchTerm.value}»...` : 'Пользователи',
  items: users.value || []
}])
</script>

<template>
  <B24CommandPalette
    v-model:search-term="searchTerm"
    :loading="status === 'pending' || status === 'idle'"
    :groups="groups"
    class="flex-1 h-80"
  />
</template>
```

> [!NOTE]
> В этом примере `useLazyFetch` с `server: false` загружает данные на клиенте и не блокирует первую отрисовку. Состояние загрузки проверяет и `pending`, и `idle`, чтобы индикатор загрузки показывался до запроса и во время него.

### Игнорирование фильтра

Поле `ignoreFilter` со значением `true` у группы отключает встроенный поиск, и вы используете свою логику поиска.

```vue [CommandPaletteIgnoreFilterExample.vue]
<script setup lang="ts">
import { refDebounced } from '@vueuse/core'

const searchTerm = ref('')
const searchTermDebounced = refDebounced(searchTerm, 200)

const { data: users, status } = useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'command-palette-users-search',
  query: { q: searchTermDebounced },
  transform: (data: { id: number, name: string, email: string }[]) => {
    return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
  },
  server: false
})

const groups = computed(() => [{
  id: 'users',
  label: searchTerm.value ? `Пользователи по запросу «${searchTerm.value}»...` : 'Пользователи',
  items: users.value || [],
  ignoreFilter: true
}])
</script>

<template>
  <B24CommandPalette
    v-model:search-term="searchTerm"
    :loading="status === 'pending' || status === 'idle'"
    :groups="groups"
    class="flex-1 h-80"
  />
</template>
```

> [!NOTE]
> В этом примере [`refDebounced`](https://vueuse.org/shared/refDebounced/#refdebounced) откладывает вызовы API. Состояние загрузки проверяет и `pending`, и `idle`, чтобы индикатор загрузки показывался до запроса и во время него.

> [!TIP]
> Пропс `ignore-filter` со значением `true` отключает встроенный поиск сразу для всех групп. Группа может вернуть его, указав `ignoreFilter: false`.

### Фильтрация после поиска

Поле `postFilter` у группы фильтрует элементы после поиска.

```vue [CommandPalettePostFilterExample.vue]
<script setup lang="ts">
const items = [
  {
    id: '/',
    label: 'Введение',
    level: 1
  },
  {
    id: '/docs/getting-started/#whats-new-in-v3',
    label: 'Что нового в v3?',
    level: 2
  },
  {
    id: '/docs/getting-started/#reka-ui',
    label: 'Reka UI',
    level: 3
  },
  {
    id: '/docs/getting-started/',
    label: 'Tailwind CSS',
    level: 3
  },
  {
    id: '/docs/getting-started/#tailwind-variants',
    label: 'Tailwind Variants',
    level: 3
  },
  {
    id: '/docs/getting-started/installation/',
    label: 'Установка',
    level: 1
  }
]

function postFilter(searchTerm: string, items: any[]) {
  // Без searchTerm фильтруем только элементы первого уровня
  if (!searchTerm) {
    return items?.filter(item => item.level === 1)
  }

  return items
}
</script>

<template>
  <B24CommandPalette :groups="[{ id: 'files', items, postFilter }]" class="flex-1" />
</template>
```

> [!NOTE]
> Начните вводить текст, и появятся элементы более высокого уровня.

### Свои настройки Fuse

Пропс `fuse` переопределяет параметры [useFuse](https://vueuse.org/integrations/useFuse). По умолчанию они такие:

```ts
{
  fuseOptions: {
    ignoreLocation: true,
    threshold: 0.1,
    keys: ['label', 'description', 'suffix']
  },
  resultLimit: 12,
  matchAllWhenSearchEmpty: true
}
```

> [!TIP]
> `fuseOptions` — параметры [Fuse.js](https://www.fusejs.io/), `resultLimit` — максимальное число результатов, а `matchAllWhenSearchEmpty` — булево значение: показывать все элементы, если поисковый запрос пуст.

Например, `{ fuseOptions: { includeMatches: true } }` подсвечивает искомый текст в элементах.

```vue [CommandPaletteFuseExample.vue]
<script setup lang="ts">
const { data: users } = useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'command-palette-users',
  transform: (data: { id: number, name: string, email: string }[]) => {
    return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
  },
  server: false
})
</script>

<template>
  <B24CommandPalette
    :groups="[{ id: 'users', items: users || [] }]"
    :fuse="{ fuseOptions: { includeMatches: true } }"
    class="flex-1 h-80"
  />
</template>
```

### Виртуализация

Пропс `virtualize` включает виртуализацию для больших списков: булево значение или объект с параметрами вроде `{ estimateSize: 32, overscan: 12 }`.

> [!WARNING]
> See: https://github.com/unovue/reka-ui/issues/1885
> При включении все группы сводятся в один список из-за ограничения Reka UI.

```vue [CommandPaletteVirtualizeExample.vue]
<script setup lang="ts">
import type { CommandPaletteItem } from '@bxshefby/b24ui-nuxt'

const items: CommandPaletteItem[] = Array(1000)
  .fill(0)
  .map((_, value) => ({
    label: `item-${value}`,
    value
  }))

const groups = [
  {
    id: 'items',
    items
  }
]
</script>

<template>
  <B24CommandPalette
    virtualize
    :fuse="{ resultLimit: 1000 }"
    :groups="groups"
    class="flex-1 h-80"
  />
</template>
```

### Внутри Popover

CommandPalette можно использовать внутри содержимого [Popover](https://b24-ui.bx-shef.by/raw/docs/components/popover.md).

```vue [PopoverCommandPaletteExample.vue]
<script setup lang="ts">
import type { CommandPaletteItem } from '@bxshefby/b24ui-nuxt'
import TagIcon from '@bitrix24/b24icons-vue/outline/TagIcon'

const items = ref([
  {
    label: 'Ошибка',
    value: 'bug',
    chip: {
      color: 'air-primary-alert'
    }
  },
  {
    label: 'Функция',
    value: 'feature',
    chip: {
      color: 'air-primary-success'
    }
  },
  {
    label: 'Улучшение',
    value: 'enhancement',
    chip: {
      color: 'air-primary'
    }
  }
] satisfies CommandPaletteItem[])

const label = ref([])
</script>

<template>
  <B24Popover :content="{ side: 'right', align: 'start' }">
    <B24Button
      :icon="TagIcon"
      label="Выберите метки"
    />

    <template #content>
      <B24CommandPalette
        v-model="label"
        :multiple="true"
        placeholder="Найдите метки..."
        :groups="[{ id: 'labels', items }]"
        :b24ui="{ input: '[&>input]:h-8 [&>input]:text-sm' }"
      />
    </template>
  </B24Popover>
</template>
```

### Внутри Modal

CommandPalette можно использовать внутри содержимого [Modal](https://b24-ui.bx-shef.by/raw/docs/components/modal.md).

```vue [ModalCommandPaletteExample.vue]
<script setup lang="ts">
import PersonSearchIcon from '@bitrix24/b24icons-vue/outline/PersonSearchIcon'

const searchTerm = ref('')

const { data: users, status, execute } = await useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'modal-command-palette-users',
  query: { q: searchTerm },
  transform: (data: { id: number, name: string, email: string }[]) => {
    return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
  },
  immediate: false
})

const groups = computed(() => [{
  id: 'users',
  label: searchTerm.value ? `Пользователи по запросу «${searchTerm.value}»...` : 'Пользователи',
  items: users.value || [],
  ignoreFilter: true
}])

function onOpen() {
  if (!users.value?.length) {
    execute()
  }
}
</script>

<template>
  <B24Modal
    :b24ui="{ content: 'p-0 pt-0 pb-2.5' }"
    @update:open="onOpen"
  >
    <B24Button
      label="Найдите пользователей..."
      :icon="PersonSearchIcon"
    />

    <template #content>
      <B24CommandPalette
        v-model:search-term="searchTerm"
        :loading="status === 'pending'"
        :groups="groups"
        placeholder="Найдите пользователей..."
        class="h-80"
      />
    </template>
  </B24Modal>
</template>
```

> [!NOTE]
> В этом примере `useLazyFetch` с `immediate: false` загружает данные только при открытии Modal.

### Внутри Drawer

CommandPalette можно использовать внутри содержимого [Drawer](https://b24-ui.bx-shef.by/raw/docs/components/drawer.md).

```vue [DrawerCommandPaletteExample.vue]
<script setup lang="ts">
import PersonSearchIcon from '@bitrix24/b24icons-vue/outline/PersonSearchIcon'

const searchTerm = ref('')

const { data: users, status, execute } = await useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'drawer-command-palette-users',
  query: { q: searchTerm },
  transform: (data: { id: number, name: string, email: string }[]) => {
    return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
  },
  immediate: false
})

const groups = computed(() => [{
  id: 'users',
  label: searchTerm.value ? `Пользователи по запросу «${searchTerm.value}»...` : 'Пользователи',
  items: users.value || [],
  ignoreFilter: true
}])

function onOpen() {
  if (!users.value?.length) {
    execute()
  }
}
</script>

<template>
  <B24Drawer :handle="false" @update:open="onOpen">
    <B24Button
      label="Найдите пользователей..."
      :icon="PersonSearchIcon"
      use-dropdown
      :b24ui="{ trailingIcon: 'rotate-180' }"
    />

    <template #content>
      <B24CommandPalette
        v-model:search-term="searchTerm"
        :loading="status === 'pending'"
        :groups="groups"
        placeholder="Найдите пользователей..."
        class="h-80"
      />
    </template>
  </B24Drawer>
</template>
```

> [!NOTE]
> В этом примере `useLazyFetch` с `immediate: false` загружает данные только при открытии Drawer.

### Отслеживание состояния открытия

Если задан пропс `close`, на нажатие кнопки можно реагировать событием `update:open`.

```vue [CommandPaletteOpenExample.vue]
<script setup lang="ts">
import SearchIcon from '@bitrix24/b24icons-vue/outline/SearchIcon'

const open = ref(false)

const users = [
  {
    label: 'Имя ассистента',
    suffix: 'assistant',
    to: 'https://github.com/bitrix24',
    target: '_blank',
    avatar: {
      src: '/b24ui/avatar/assistant.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Bitrix24',
    suffix: 'bitrix24',
    to: 'https://github.com/bitrix24',
    target: '_blank',
    avatar: {
      src: 'https://github.com/bitrix24.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Имя сотрудника',
    suffix: 'employee',
    to: 'https://github.com/bitrix24',
    target: '_blank',
    avatar: {
      src: '/b24ui/avatar/employee.png',
      loading: 'lazy' as const
    }
  }
]
</script>

<template>
  <B24Modal v-model:open="open" :b24ui="{ content: 'p-0 pt-0 pb-2.5' }">
    <B24Button
      label="Найдите пользователей..."
      :icon="SearchIcon"
    />

    <template #content>
      <B24CommandPalette close :groups="[{ id: 'users', items: users }]" @update:open="open = $event" />
    </template>
  </B24Modal>
</template>
```

> [!NOTE]
> Это удобно, например, когда CommandPalette находится внутри [`Modal`](https://b24-ui.bx-shef.by/raw/docs/components/modal.md).

### Слот footer

Слот `#footer` добавляет свой контент внизу CommandPalette: например, подсказку по горячим клавишам или дополнительные действия.

```vue [CommandPaletteFooterSlotExample.vue]
<script setup lang="ts">
import Bitrix24Icon from '@bitrix24/b24icons-vue/common-service/Bitrix24Icon'
import VueIcon from '@bitrix24/b24icons-vue/file-type/VueIcon'
import MarkdownIcon from '@bitrix24/b24icons-vue/file-type/MarkdownIcon'
import NodeIcon from '@bitrix24/b24icons-vue/file-type/NodeIcon'
import FileUploadIcon from '@bitrix24/b24icons-vue/main/FileUploadIcon'
import FolderPlusIcon from '@bitrix24/b24icons-vue/outline/FolderPlusIcon'
import CrmSearchIcon from '@bitrix24/b24icons-vue/crm/CrmSearchIcon'
import SettingsLIcon from '@bitrix24/b24icons-vue/outline/SettingsLIcon'

const groups = [
  {
    id: 'actions',
    items: [
      {
        label: 'Добавить новый файл',
        suffix: 'Создать новый файл в текущей папке',
        icon: FileUploadIcon,
        kbds: ['meta', 'I']
      },
      {
        label: 'Добавить новую папку',
        suffix: 'Создать новую папку в текущей папке',
        icon: FolderPlusIcon,
        kbds: ['meta', 'F']
      },
      {
        label: 'Найти файлы',
        suffix: 'Поиск по всем файлам проекта',
        icon: CrmSearchIcon,
        kbds: ['meta', 'P']
      },
      {
        label: 'Настройки',
        suffix: 'Открыть настройки приложения',
        icon: SettingsLIcon,
        kbds: ['meta', ',']
      }
    ]
  },
  {
    id: 'recent',
    label: 'Недавние',
    items: [
      {
        label: 'project.vue',
        suffix: 'components/',
        icon: VueIcon
      },
      {
        label: 'readme.md',
        suffix: 'docs/',
        icon: MarkdownIcon
      },
      {
        label: 'package.json',
        suffix: 'root/',
        icon: NodeIcon
      }
    ]
  }
]
</script>

<template>
  <B24CommandPalette :groups="groups" class="flex-1 h-80">
    <template #footer>
      <div class="flex items-center justify-between gap-2">
        <Bitrix24Icon class="size-5 text-label ms-1" />
        <div class="flex items-center gap-1">
          <B24Button label="Открыть команды" size="sm">
            <template #trailing>
              <B24Kbd value="enter" size="sm" />
            </template>
          </B24Button>
          <B24Separator orientation="vertical" class="h-4" />
          <B24Button label="Действия" size="sm">
            <template #trailing>
              <B24Kbd value="meta" size="sm" />
              <B24Kbd value="k" size="sm" />
            </template>
          </B24Button>
        </div>
      </div>
    </template>
  </B24CommandPalette>
</template>
```

### Свой слот

Свойство `slot` настраивает отдельный элемент или группу.

Вам будут доступны слоты:

- `#{{ item.slot }}`
- `#{{ item.slot }}-leading`
- `#{{ item.slot }}-label`
- `#{{ item.slot }}-trailing`
- `#{{ group.slot }}`
- `#{{ group.slot }}-leading`
- `#{{ group.slot }}-label`
- `#{{ group.slot }}-trailing`

```vue [CommandPaletteCustomSlotExample.vue]
<script setup lang="ts">
import UserMaskIcon from '@bitrix24/b24icons-vue/outline/UserMaskIcon'
import CreditDebitCardIcon from '@bitrix24/b24icons-vue/main/CreditDebitCardIcon'
import NotificationIcon from '@bitrix24/b24icons-vue/outline/NotificationIcon'
import LockLIcon from '@bitrix24/b24icons-vue/outline/LockLIcon'

const groups = [
  {
    id: 'settings',
    items: [
      {
        label: 'Профиль',
        icon: UserMaskIcon,
        kbds: ['meta', 'P']
      },
      {
        label: 'Оплата',
        icon: CreditDebitCardIcon,
        kbds: ['meta', 'B'],
        slot: 'billing' as const
      },
      {
        label: 'Уведомления',
        icon: NotificationIcon
      },
      {
        label: 'Безопасность',
        icon: LockLIcon
      }
    ]
  },
  {
    id: 'users',
    label: 'Пользователи',
    slot: 'users' as const,
    items: [
      {
        label: 'Имя ассистента',
        suffix: 'assistant',
        to: 'https://github.com/bitrix24',
        avatarSrc: '/b24ui/avatar/assistant.png',
        target: '_blank'
      },
      {
        label: 'Bitrix24',
        suffix: 'bitrix24',
        to: 'https://github.com/bitrix24',
        avatarSrc: 'https://github.com/bitrix24.png',
        target: '_blank'
      },
      {
        label: 'Имя сотрудника',
        suffix: 'employee',
        to: 'https://github.com/bitrix24',
        avatarSrc: '/b24ui/avatar/employee.png',
        target: '_blank'
      }
    ]
  }
]
</script>

<template>
  <B24CommandPalette :groups="groups" class="flex-1 h-80">
    <template #users-leading="{ item }">
      <B24Avatar :src="item?.avatarSrc" size="2xs" loading="lazy" />
    </template>

    <template #billing-label="{ item }">
      <span class="font-(--ui-font-weight-medium) text-(--ui-color-accent-main-primary)">{{ item.label }}</span>

      <B24Badge size="sm">
        Скидка 50%
      </B24Badge>
    </template>
  </B24CommandPalette>
</template>
```

> [!TIP]
> See: #slots
> Слоты `#item`, `#item-leading`, `#item-label` и `#item-trailing` настраивают сразу все элементы.

## API

### Пропсы

```ts
/**
 * Props for the CommandPalette component
 */
interface CommandPaletteProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  /**
   * @default 'md'
   */
  size?: "sm" | "md" | "xs" | "lg" | "xss" | "xl" | undefined;
  /**
   * The icon displayed in the input. Set to `false` to hide the icon.
   * @default icons.search
   */
  icon?: false | (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * The icon displayed on the right side of the input.
   * @default icons.search
   */
  trailingIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * The icon displayed when an item is selected.
   * @default icons.check
   */
  selectedIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * The icon displayed when an item has children.
   * @default icons.chevronRight
   */
  childrenIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * The placeholder text for the input.
   * @default t('commandPalette.placeholder')
   */
  placeholder?: string | undefined;
  /**
   * Automatically focus the input when component is mounted.
   * @default true
   */
  autofocus?: boolean | undefined;
  /**
   * Display a close button in the input (useful when inside a Modal for example).
   * `{ color: 'air-tertiary-no-accent' }`
   * @default false
   */
  close?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the close button.
   * @default icons.close
   */
  closeIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * Display a button to navigate back in history.
   * `{ color: 'air-tertiary-accent' }`
   * @default true
   */
  back?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the back button.
   * @default icons.arrowLeft
   */
  backIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * Configure the input or hide it with `false`.
   * @default true
   */
  input?: boolean | Omit<InputProps<AcceptableValue, ModelModifiers>, "modelValue" | "defaultValue"> | undefined;
  groups?: G[] | undefined;
  /**
   * Options for [useFuse](https://vueuse.org/integrations/useFuse).
   * @default {
fuseOptions: {
ignoreLocation: true,
threshold: 0.1,
keys: ['label', 'description', 'suffix']
},
resultLimit: 12,
matchAllWhenSearchEmpty: true
}
   */
  fuse?: UseFuseOptions<T> | undefined;
  /**
   * Enable virtualization for large lists.
   * Note: when enabled, all groups are flattened into a single list due to a limitation of Reka UI (https://github.com/unovue/reka-ui/issues/1885).
   * @default false
   */
  virtualize?: boolean | { overscan?: number | undefined; estimateSize?: number | ((index: number) => number) | undefined; } | undefined;
  /**
   * When `items` is an array of objects, select the field to use as the value instead of the object itself.
   * @default undefined
   */
  valueKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  /**
   * The key used to get the label from the item.
   * @default 'label'
   */
  labelKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  /**
   * The key used to get the description from the item.
   * @default 'description'
   */
  descriptionKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  /**
   * Whether to preserve the order of groups as defined in the `groups` prop when filtering.
   * When `false`, groups will appear based on item matches.
   * @default false
   */
  preserveGroupOrder?: boolean | undefined;
  /**
   * When `true`, items will not be filtered which is useful for custom filtering (useAsyncData, useFetch, etc.).
   * Applies to every group, unless the group sets its own `ignoreFilter` field.
   * @default false
   */
  ignoreFilter?: boolean | undefined;
  /**
   * Delay (in milliseconds) before the search term is passed to Fuse (debounced).
   * Useful when indexing large datasets where fuzzy search becomes the bottleneck — the input stays responsive while Fuse and the result pipeline only re-run after typing settles.
   * Set to `0` (the default) to disable.
   * @default 0
   */
  searchDelay?: number | undefined;
  b24ui?: { root?: SlotClass; input?: SlotClass; close?: SlotClass; back?: SlotClass; content?: SlotClass; footer?: SlotClass; viewport?: SlotClass; group?: SlotClass; empty?: SlotClass; label?: SlotClass; item?: SlotClass; itemLeadingIcon?: SlotClass; itemLeadingAvatar?: SlotClass; itemLeadingAvatarSize?: SlotClass; itemLeadingChip?: SlotClass; itemLeadingChipSize?: SlotClass; itemTrailing?: SlotClass; itemTrailingIcon?: SlotClass; itemTrailingHighlightedIcon?: SlotClass; itemTrailingKbds?: SlotClass; itemTrailingKbdsSize?: SlotClass; itemWrapper?: SlotClass; itemLabel?: SlotClass; itemLabelBase?: SlotClass; itemLabelPrefix?: SlotClass; itemLabelSuffix?: SlotClass; itemDescription?: SlotClass; } | undefined;
  /**
   * Whether multiple options can be selected or not.
   */
  multiple?: boolean | undefined;
  /**
   * When `true`, prevents the user from interacting with listbox
   */
  disabled?: boolean | undefined;
  /**
   * The controlled value of the listbox. Can be binded with `v-model`.
   */
  modelValue?: null | string | number | bigint | Record<string, any> | AcceptableValue[] | undefined;
  /**
   * The value of the listbox when initially rendered. Use when you do not need to control the state of the Listbox
   */
  defaultValue?: null | string | number | bigint | Record<string, any> | AcceptableValue[] | undefined;
  /**
   * When `true`, hover over item will trigger highlight
   * @default true
   */
  highlightOnHover?: boolean | undefined;
  /**
   * When `true`, keyboard navigation will loop from last item to first, and vice versa.
   */
  loop?: boolean | undefined;
  /**
   * How multiple selection should behave in the collection.
   * @default 'toggle'
   */
  selectionBehavior?: "replace" | "toggle" | undefined;
  /**
   * Use this to compare objects by a particular field, or pass your own comparison function for complete control over how objects are compared.
   */
  by?: string | (a: AcceptableValue, b: AcceptableValue): boolean | undefined;
  /**
   * When `true`, the loading icon will be displayed.
   */
  loading?: boolean | undefined;
  /**
   * @default ''
   */
  searchTerm?: string | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the CommandPalette component
 */
interface CommandPaletteSlots {
  empty(): any;
  footer(): any;
  back(): any;
  close(): any;
  item(): any;
  item-leading(): any;
  item-label(): any;
  item-description(): any;
  item-trailing(): any;
  group-label(): any;
}
```

### События

```ts
/**
 * Emitted events for the CommandPalette component
 */
interface CommandPaletteEmits {
  update:modelValue: (payload: [value: T]) => void;
  highlight: (payload: [payload: { ref: HTMLElement; value: T; } | undefined]) => void;
  entryFocus: (payload: [event: CustomEvent<any>]) => void;
  leave: (payload: [event: Event]) => void;
  update:open: (payload: [value: boolean]) => void;
  update:searchTerm: (payload: [value: string]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    commandPalette: {
      slots: {
        root: 'flex flex-col min-h-0 min-w-0 divide-y divide-(--ui-color-divider-default)',
        input: '',
        close: '',
        back: 'p-0 -ms-1.5 me-1',
        content: 'relative overflow-hidden flex flex-col focus:outline-none',
        footer: 'p-1',
        viewport: 'relative scroll-py-1 overflow-y-auto scrollbar-thin flex-1 focus:outline-none',
        group: 'p-1 isolate',
        empty: 'text-center text-description',
        label: 'text-label',
        item: 'group relative w-full flex items-center select-none outline-none before:absolute before:z-[-1] before:inset-px before:rounded-(--ui-border-radius-sm) data-disabled:cursor-not-allowed data-disabled:opacity-30',
        itemLeadingIcon: 'shrink-0',
        itemLeadingAvatar: 'shrink-0',
        itemLeadingAvatarSize: '',
        itemLeadingChip: 'shrink-0',
        itemLeadingChipSize: '',
        itemTrailing: 'ms-auto inline-flex items-center',
        itemTrailingIcon: 'shrink-0 text-(--ui-color-accent-main-primary)',
        itemTrailingHighlightedIcon: 'shrink-0 text-label hidden group-data-highlighted:inline-flex',
        itemTrailingKbds: 'hidden lg:inline-flex items-center shrink-0',
        itemTrailingKbdsSize: '',
        itemWrapper: 'flex-1 flex flex-col text-start min-w-0 overflow-hidden',
        itemLabel: 'truncate space-x-1 text-label',
        itemLabelBase: 'text-label [&>mark]:text-(--ui-color-black-base) [&>mark]:bg-(--ui-color-collab-accent-less-1)',
        itemLabelPrefix: 'text-legend',
        itemLabelSuffix: 'truncate text-description [&>mark]:text-(--ui-color-black-base) [&>mark]:bg-(--ui-color-collab-accent-less-1)',
        itemDescription: 'truncate -mt-[6px] text-description text-(length:--ui-font-size-sm) [&>mark]:text-(--ui-color-black-base) [&>mark]:bg-(--ui-color-collab-accent-less-1)'
      },
      variants: {
        virtualize: {
          true: {
            viewport: 'p-1 isolate'
          },
          false: {
            viewport: ''
          }
        },
        size: {
          xss: {
            input: 'ps-[20px] pe-[20px]',
            empty: 'py-3 text-(length:--ui-font-size-4xs)',
            label: 'p-1 text-[10px]/3 gap-1',
            item: 'p-1 text-(length:--ui-font-size-4xs) gap-1',
            itemLeadingIcon: 'size-4',
            itemLeadingAvatarSize: '3xs',
            itemLeadingChip: 'size-4',
            itemLeadingChipSize: 'sm',
            itemTrailing: 'gap-1',
            itemTrailingIcon: 'size-4',
            itemTrailingHighlightedIcon: 'size-4',
            itemTrailingKbds: 'gap-0.5',
            itemTrailingKbdsSize: 'sm'
          },
          xs: {
            input: 'ps-[22px] pe-[22px]',
            empty: 'py-3 text-(length:--ui-font-size-xs)',
            label: 'p-1 text-[10px]/3 gap-1',
            item: 'p-1 text-(length:--ui-font-size-xs) gap-1',
            itemLeadingIcon: 'size-4',
            itemLeadingAvatarSize: '3xs',
            itemLeadingChip: 'size-4',
            itemLeadingChipSize: 'sm',
            itemTrailing: 'gap-1',
            itemTrailingIcon: 'size-4',
            itemTrailingHighlightedIcon: 'size-4',
            itemTrailingKbds: 'gap-0.5',
            itemTrailingKbdsSize: 'sm'
          },
          sm: {
            input: 'ps-[28px] pe-[28px]',
            empty: 'py-4 text-(length:--ui-font-size-sm)',
            label: 'p-1.5 text-[10px]/3 gap-1.5',
            item: 'p-1.5 text-(length:--ui-font-size-sm) gap-1.5',
            itemLeadingIcon: 'size-4',
            itemLeadingAvatarSize: '3xs',
            itemLeadingChip: 'size-4',
            itemLeadingChipSize: 'sm',
            itemTrailing: 'gap-1.5',
            itemTrailingIcon: 'size-4',
            itemTrailingHighlightedIcon: 'size-4',
            itemTrailingKbds: 'gap-0.5',
            itemTrailingKbdsSize: 'sm'
          },
          md: {
            input: 'ps-[40px] pe-[44px]',
            empty: 'py-6 text-(length:--ui-font-size-sm)',
            label: 'p-[6px] text-(length:--ui-font-size-xs) gap-[6px]',
            item: 'p-[6px] text-(length:--ui-font-size-md) gap-[6px]',
            itemLeadingIcon: 'size-[20px]',
            itemLeadingAvatarSize: '2xs',
            itemLeadingChip: 'size-[20px]',
            itemLeadingChipSize: 'md',
            itemTrailing: 'gap-[6px]',
            itemTrailingIcon: 'size-[20px]',
            itemTrailingHighlightedIcon: 'size-[20px]',
            itemTrailingKbds: 'gap-0.5',
            itemTrailingKbdsSize: 'md'
          },
          lg: {
            input: 'ps-[40px] pe-[44px]',
            empty: 'py-7 text-(length:--ui-font-size-sm)',
            label: 'p-2 text-(length:--ui-font-size-lg) gap-2',
            item: 'p-2 text-(length:--ui-font-size-lg) gap-2',
            itemLeadingIcon: 'size-5',
            itemLeadingAvatarSize: '2xs',
            itemLeadingChip: 'size-5',
            itemLeadingChipSize: 'md',
            itemTrailing: 'gap-2',
            itemTrailingIcon: 'size-5',
            itemTrailingHighlightedIcon: 'size-5',
            itemTrailingKbds: 'gap-0.5',
            itemTrailingKbdsSize: 'md'
          },
          xl: {
            input: 'ps-[40px] pe-[44px]',
            empty: 'py-8 text-(length:--ui-font-size-lg)',
            label: 'p-2 text-(length:--ui-font-size-2xl) gap-2',
            item: 'p-2 text-(length:--ui-font-size-2xl) gap-2',
            itemLeadingIcon: 'size-6',
            itemLeadingAvatarSize: 'xs',
            itemLeadingChip: 'size-6',
            itemLeadingChipSize: 'lg',
            itemTrailing: 'gap-2',
            itemTrailingIcon: 'size-6',
            itemTrailingHighlightedIcon: 'size-6',
            itemTrailingKbds: 'gap-0.5',
            itemTrailingKbdsSize: 'lg'
          }
        },
        active: {
          true: {
            item: 'text-label before:bg-(--ui-color-base-8)',
            itemLeadingIcon: 'text-legend'
          },
          false: {
            item: 'text-legend data-highlighted:not-data-disabled:text-legend data-highlighted:not-data-disabled:before:bg-(--ui-color-bg-content-secondary) transition-colors before:transition-colors',
            itemLeadingIcon: 'text-legend group-data-highlighted:not-group-data-disabled:text-legend transition-colors'
          }
        },
        loading: {
          true: {
            itemLeadingIcon: 'animate-spin'
          }
        }
      },
      defaultVariants: {
        size: 'md'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
