v2.15.0

CommandPalette

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

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

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

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
Выбранные элементы можно отслеживать и через событие @update:model-value.

Группы

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

У каждой группы должен быть 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
  • 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: to, target и другие.

labelHtml, suffixHtml и descriptionHtml вставляются через v-html. Обычно палитра сама вычисляет их по совпадению с поиском: всё экранируется, найденный фрагмент оборачивается в <mark>. Значение, заданное вручную, этот шаг пропускает и отрисовывается как сырой HTML. Очищайте всё, что приходит из CMS, API или от пользователей, прежде чем передавать сюда.
<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
Чтобы создать подменю, элемент может содержать массив children с такими же свойствами:

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

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

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
Передавайте в пропс default-value или в директиву v-model массив.

Плейсхолдер

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

<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>
<script setup lang="ts">
import { ref } from 'vue'
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.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 задаёт иконку в поле ввода.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 задаёт иконку выбранного элемента.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 задаёт иконку справа у элементов с подменю.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 иконку загрузки.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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, которая закрывает CommandPalette.

По нажатию на кнопку закрытия срабатывает событие update:open.
<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>
<script setup lang="ts">
import { ref } from 'vue'
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.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 задаёт иконку кнопки закрытия.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 задаёт иконку кнопки «Назад».

<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>
<script setup lang="ts">
import { ref } from 'vue'
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.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
Пропс value-key выбирает поле элемента, которое используется как значение вместо самого объекта. Пропс by сравнивает объекты по полю, а не по ссылке.

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

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

<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>
<script setup lang="ts">
import { ref } from 'vue'

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>
В этом примере событие @update:model-value сбрасывает поисковый запрос при выборе элемента.

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

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

<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>
При переходе в подменю:
  • поисковый запрос сбрасывается;
  • в поле ввода появляется кнопка «Назад»;
  • к предыдущей группе можно вернуться клавишей ⌫.

Элементы из API

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

Нет данных
<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>
<script setup lang="ts">
import { ref, computed } from 'vue'

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>
В этом примере useLazyFetch с server: false загружает данные на клиенте и не блокирует первую отрисовку. Состояние загрузки проверяет и pending, и idle, чтобы индикатор загрузки показывался до запроса и во время него.

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

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

Нет данных
<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>
<script setup lang="ts">
import { ref, computed } from 'vue'
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>
В этом примере refDebounced откладывает вызовы API. Состояние загрузки проверяет и pending, и idle, чтобы индикатор загрузки показывался до запроса и во время него.
Пропс ignore-filter со значением true отключает встроенный поиск сразу для всех групп. Группа может вернуть его, указав ignoreFilter: false.

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

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

<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>
Начните вводить текст, и появятся элементы более высокого уровня.

Пропс fuse переопределяет параметры useFuse. По умолчанию они такие:

{
  fuseOptions: {
    ignoreLocation: true,
    threshold: 0.1,
    keys: ['label', 'description', 'suffix']
  },
  resultLimit: 12,
  matchAllWhenSearchEmpty: true
}
fuseOptions — параметры Fuse.js, resultLimit — максимальное число результатов, а matchAllWhenSearchEmpty — булево значение: показывать все элементы, если поисковый запрос пуст.

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

Нет данных
<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 }.

При включении все группы сводятся в один список из-за ограничения Reka UI.
<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.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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.

<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>
<script setup lang="ts">
import { ref, computed } from 'vue'
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>
В этом примере useLazyFetch с immediate: false загружает данные только при открытии Modal.

Внутри Drawer

CommandPalette можно использовать внутри содержимого Drawer.

<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>
<script setup lang="ts">
import { ref, computed } from 'vue'
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>
В этом примере useLazyFetch с immediate: false загружает данные только при открытии Drawer.

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

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

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
Это удобно, например, когда CommandPalette находится внутри Modal.

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

<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
<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>
Слоты #item, #item-leading, #item-label и #item-trailing настраивают сразу все элементы.

API

Пропсы

Prop Default Type
as'div'any

The element or component this component should render as.

size'md' "sm" | "md" | "xs" | "lg" | "xss" | "xl"
iconicons.searchIconComponent

The icon displayed in the input. Set to false to hide the icon.

trailingIconicons.searchIconComponent

The icon displayed on the right side of the input.

selectedIconicons.checkIconComponent

The icon displayed when an item is selected.

childrenIconicons.chevronRightIconComponent

The icon displayed when an item has children.

placeholdert('commandPalette.placeholder') string

The placeholder text for the input.

autofocustrueboolean

Automatically focus the input when component is mounted.

closefalseboolean | Omit<ButtonProps, LinkPropsKeys>

Display a close button in the input (useful when inside a Modal for example). { color: 'air-tertiary-no-accent' }

closeIconicons.closeIconComponent

The icon displayed in the close button.

backtrueboolean | Omit<ButtonProps, LinkPropsKeys>

Display a button to navigate back in history. { color: 'air-tertiary-accent' }

backIconicons.arrowLeftIconComponent

The icon displayed in the back button.

inputtrueboolean | Omit<InputProps<AcceptableValue, ModelModifiers>, "modelValue" | "defaultValue">

Configure the input or hide it with false.

groups G[]
fuse{ fuseOptions: { ignoreLocation: true, threshold: 0.1, keys: ['label', 'description', 'suffix'] }, resultLimit: 12, matchAllWhenSearchEmpty: true } UseFuseOptions<T>

Options for useFuse.

virtualizefalseboolean | { overscan?: number ; estimateSize?: number | ((index: number) => number) | undefined; } | 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).

valueKeyundefined keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>>

When items is an array of objects, select the field to use as the value instead of the object itself.

labelKey'label' keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>>

The key used to get the label from the item.

descriptionKey'description' keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>>

The key used to get the description from the item.

preserveGroupOrderfalseboolean

Whether to preserve the order of groups as defined in the groups prop when filtering. When false, groups will appear based on item matches.

ignoreFilterfalseboolean

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.

searchDelay0 number

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.

multipleboolean

Whether multiple options can be selected or not.

disabledboolean

When true, prevents the user from interacting with listbox

modelValue null | string | number | bigint | Record<string, any> | AcceptableValue[]

The controlled value of the listbox. Can be binded with v-model.

defaultValue null | string | number | bigint | Record<string, any> | AcceptableValue[]

The value of the listbox when initially rendered. Use when you do not need to control the state of the Listbox

highlightOnHovertrueboolean

When true, hover over item will trigger highlight

loopboolean

When true, keyboard navigation will loop from last item to first, and vice versa.

selectionBehavior'toggle' "replace" | "toggle"

How multiple selection should behave in the collection.

by string | (a: AcceptableValue, b: AcceptableValue): boolean

Use this to compare objects by a particular field, or pass your own comparison function for complete control over how objects are compared.

loadingboolean

When true, the loading icon will be displayed.

searchTerm'' string
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; }

Слоты

Slot Type
empty{ searchTerm?: string | undefined; }
footer{ b24ui: object; }
back{ b24ui: object; }
close{ b24ui: object; }
item{ item: T; index: number; b24ui: object; }
item-leading{ item: T; index: number; b24ui: object; }
item-label{ item: T; index: number; b24ui: object; }
item-description{ item: T; index: number; b24ui: object; }
item-trailing{ item: T; index: number; b24ui: object; }
group-label{ group: G; label: string; b24ui: object; }

События

Event Type
update:modelValue[value: T]
highlight[payload: { ref: HTMLElement; value: T; } | undefined]
entryFocus[event: CustomEvent<any>]
leave[event: Event]
update:open[value: boolean]
update:searchTerm[value: string]

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/command-palette.ts
export default {
  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'
  }
}