---
title: "ContentSearch"
description: "Готовая командная палитра для вашей документации."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/content-search"
---
# ContentSearch

> Готовая командная палитра для вашей документации.

> [!WARNING]
> See: /docs/getting-started/integrations/content/
> Компонент доступен, только если установлен модуль `@nuxt/content`.

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

Компонент ContentSearch расширяет [CommandPalette](https://b24-ui.bx-shef.by/raw/docs/components/command-palette.md): к нему добавлены поиск `@nuxt/content`, группировка навигации и команды переключения цветовой схемы. Он поддерживает фильтрацию на клиенте через [Fuse.js](https://www.fusejs.io/) и серверный [полнотекстовый поиск FTS5](https://www.sqlite.org/fts5.html). Можно передать любое свойство CommandPalette: `icon`, `placeholder` и другие.

```vue [ContentSearchExample.vue]
<script setup lang="ts">
import type { ContentNavigationItem } from '@nuxt/content'

const { data: files } = useLazyAsyncData('content-search-example', () => queryCollectionSearchSections('docs', {
  ignoredTags: ['style']
}), {
  server: false
})

const navigation = inject<Ref<ContentNavigationItem[]>>('navigation')

const searchTerm = ref('')
</script>

<template>
  <ClientOnly>
    <LazyB24ContentSearch
      v-model:search-term="searchTerm"
      open
      :autofocus="false"
      :files="files"
      :navigation="navigation"
      :fuse="{ resultLimit: 42 }"
    />
  </ClientOnly>
</template>
```

> [!NOTE]
> Открыть палитру можно сочетанием <kbd value="meta">
> </kbd>
> <kbd value="K" className="ms-px">
> </kbd>
> , компонентом [ContentSearchButton](https://b24-ui.bx-shef.by/raw/docs/components/content-search-button.md) или композаблом `useContentSearch`: `const { open } = useContentSearch()`.

> [!TIP]
> Рекомендуем обернуть `ContentSearch` в компонент [ClientOnly](https://nuxt.com/docs/api/components/client-only), чтобы он не отрисовывался на сервере.

### Навигация

Пропс `navigation` вместе с [`queryCollectionNavigation`](https://content.nuxt.com/docs/utils/query-collection-navigation) группирует результаты поиска по разделам:

```vue [app.vue]
<script setup lang="ts">
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('content'))
</script>

<template>
  <B24App>
    <ClientOnly>
      <LazyB24ContentSearch
        :navigation="navigation"
      />
    </ClientOnly>
  </B24App>
</template>
```

### Файлы

Пропс `files` вместе с [`queryCollectionSearchSections`](https://content.nuxt.com/docs/utils/query-collection-search-sections) сразу загружает все разделы для поиска и включает фильтрацию на клиенте через [Fuse.js](https://www.fusejs.io/):

```vue [app.vue]
<script setup lang="ts">
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('content'))

const { data: files } = useLazyAsyncData('search', () => queryCollectionSearchSections('docs', {
  ignoredTags: ['style']
}), {
  server: false
})
</script>

<template>
  <B24App>
    <ClientOnly>
      <LazyB24ContentSearch
        :navigation="navigation"
        :files="files"
        :fuse="{ resultLimit: 20, fuseOptions: { threshold: 0.2 } }"
      />
    </ClientOnly>
  </B24App>
</template>
```

> [!TIP]
> Пропс `fuse` задаёт параметры [useFuse](https://vueuse.org/integrations/useFuse), которые уходят в базовый [CommandPalette](https://b24-ui.bx-shef.by/raw/docs/components/command-palette.md): например, `resultLimit` (по умолчанию `12`) и `fuseOptions.threshold` (по умолчанию `0.1`).

### Поиск

Пропс `search` вместе с [`useSearchCollection`](https://content.nuxt.com/docs/utils/use-search-collection) вместо фильтрации на клиенте включает серверный [полнотекстовый поиск FTS5](https://www.sqlite.org/fts5.html) с подсвеченными фрагментами:

> [!WARNING]
> Нужен `@nuxt/content` версии 3.14 или выше.

```vue [app.vue]
<script setup lang="ts">
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('content'))

const { search, status, init } = useSearchCollection('content', {
  immediate: false,
  ignoredTags: ['style']
})

const { open } = useContentSearch()

// Откладываем инициализацию индекса до открытия палитры при `immediate: false`
watch(open, (value) => {
  if (value && status.value === 'idle') {
    init()
  }
})
</script>

<template>
  <B24App>
    <ClientOnly>
      <LazyB24ContentSearch
        :navigation="navigation"
        :search="search"
        :search-status="status"
      />
    </ClientOnly>
  </B24App>
</template>
```

> [!TIP]
> Передайте `search-status`, чтобы компонент сам повторял поиск, когда индекс будет готов. Пропс `search-delay` (по умолчанию `100ms`) задаёт, сколько ждать после паузы в наборе, прежде чем запустить поиск. Параметр `fuse.resultLimit` ограничивает общее число результатов по всем группам (результаты поиска, ссылки, тема и т. д.).

> [!NOTE]
> С пропсом `search` передавать `files` не нужно. Вместо Fuse.js компонент вызывает асинхронную функцию поиска при каждом нажатии клавиши. Результаты автоматически сопоставляются и группируются по навигации, фрагменты подсвечиваются. В отличие от подхода с `files`, который сразу загружает все разделы и позволяет просматривать навигацию до ввода, `search` возвращает результаты только после ввода запроса.

### Сочетание клавиш

Пропс `shortcut` меняет сочетание клавиш, которое [defineShortcuts](https://b24-ui.bx-shef.by/raw/docs/composables/define-shortcuts.md) использует для открытия ContentSearch. По умолчанию `meta_k` (<kbd value="meta">

</kbd>

 <kbd value="K">

</kbd>

).

```vue [app.vue]
<template>
  <B24App>
    <ClientOnly>
      <LazyB24ContentSearch
        shortcut="meta_k"
      />
    </ClientOnly>
  </B24App>
</template>
```

### Ссылки

Пропс `links` добавляет вверху палитры группу быстрых ссылок:

```vue [app.vue]
<script setup lang="ts">
const links = [{
  label: 'Документация',
  to: '/docs/getting-started'
}, {
  label: 'Компоненты',
  to: '/docs/components'
}, {
  label: 'Примеры',
  to: '/showcase'
}]
</script>

<template>
  <B24App>
    <ClientOnly>
      <LazyB24ContentSearch
        :links="links"
      />
    </ClientOnly>
  </B24App>
</template>
```

### Цветовая схема

По умолчанию в палитру добавляется группа команд для переключения между светлой и тёмной темой. Это работает, только если `colorMode` не зафиксирован на конкретной странице через `definePageMeta`:

```vue [pages/index.vue]
<script setup lang="ts">
definePageMeta({
  colorMode: 'dark'
})
</script>
```

Отключить эту группу можно пропсом `color-mode` со значением `false`:

```vue [app.vue]
<template>
  <B24App>
    <ClientOnly>
      <LazyB24ContentSearch
        :color-mode="false"
      />
    </ClientOnly>
  </B24App>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the ContentSearch component
 */
interface ContentSearchProps {
  /**
   * @default 'md'
   */
  size?: "sm" | "md" | "xs" | "lg" | "xss" | "xl" | undefined;
  /**
   * Display a close button in the input (useful when inside a Modal for example).
   * `{ size: 'sm', color: 'air-tertiary-no-accent' }`
   * @default true
   */
  close?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * Configure the input or hide it with `false`.
   * `{ fixed: true }`
   * @default true
   */
  input?: boolean | Omit<InputProps<AcceptableValue, ModelModifiers>, "modelValue" | "defaultValue"> | undefined;
  /**
   * Keyboard shortcut to open the search (used by [`defineShortcuts`](https://bitrix24.github.io/b24ui/docs/composables/define-shortcuts/))
   * @default 'meta_k'
   */
  shortcut?: string | undefined;
  /**
   * Links group displayed as the first group in the command palette.
   */
  links?: T[] | undefined;
  navigation?: ContentNavigationItem[] | undefined;
  files?: ContentSearchFile[] | undefined;
  /**
   * Options for [useFuse](https://vueuse.org/integrations/useFuse) passed to the [CommandPalette](https://bitrix24.github.io/b24ui/docs/components/command-palette/).
   * @default {
fuseOptions: {
ignoreLocation: true,
includeMatches: true,
useTokenSearch: true,
threshold: 0.1,
keys: ['label', 'description', 'suffix']
},
resultLimit: 12,
matchAllWhenSearchEmpty: true
}
   */
  fuse?: UseFuseOptions<T> | undefined;
  /**
   * Async search function (e.g. from [`useSearchCollection`](https://content.nuxt.com/docs/utils/use-search-collection)).
   * When provided, ContentSearch calls it on each keystroke and uses the results instead of Fuse.
   * Results are mapped, sanitized, and grouped by navigation internally.
   */
  search?: (query: string, opts?: ContentSearchOptions | undefined): Promise<ContentSearchResult[]> | undefined;
  /**
   * Status of the async search index (e.g. from `useSearchCollection`).
   * When the status transitions to `'ready'`, the search is automatically re-triggered if there's a pending term.
   */
  searchStatus?: "error" | "loading" | "idle" | "ready" | undefined;
  /**
   * Delay (in milliseconds) before the search is triggered (debounced).
   * Keeps the input responsive by only running the search after typing settles.
   * Set to `0` to disable.
   * @default 100
   */
  searchDelay?: number | undefined;
  /**
   * When `true`, the theme command will be added to the groups.
   * @default true
   */
  colorMode?: boolean | undefined;
  b24ui?: { modal?: SlotClass; input?: SlotClass; } & { 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;
  title?: string | undefined;
  description?: string | undefined;
  /**
   * Render an overlay behind the modal.
   * @default true
   */
  overlay?: boolean | undefined;
  /**
   * Animate the modal when opening or closing.
   * @default true
   */
  transition?: boolean | undefined;
  /**
   * The content of the modal.
   */
  content?: Omit<DialogContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<DialogContentImplEmits>> | undefined;
  /**
   * When `false`, the modal will not close when clicking outside or pressing escape.
   * @default false
   */
  dismissible?: boolean | undefined;
  /**
   * When `true`, the modal will take up the full screen.
   * @default false
   */
  fullscreen?: boolean | undefined;
  /**
   * The modality of the dialog When set to `true`, <br>
   * interaction with outside elements will be disabled and only dialog content will be visible to screen readers.
   */
  modal?: boolean | undefined;
  /**
   * Render the modal in a portal.
   * @default true
   */
  portal?: string | false | true | HTMLElement | undefined;
  /**
   * When set to `false`, the dialog content will not be unmounted when closed, but instead hidden with CSS. <br>
   * Useful for SEO or when you want to improve performance by not remounting the component on every open.
   * @default true
   */
  unmountOnHide?: boolean | 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;
  /**
   * When `true`, the loading icon will be displayed.
   */
  loading?: boolean | 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;
  /**
   * When `true`, prevents the user from interacting with listbox
   */
  disabled?: boolean | undefined;
  /**
   * When `true`, hover over item will trigger highlight
   */
  highlightOnHover?: boolean | undefined;
  /**
   * When `true`, keyboard navigation will loop from last item to first, and vice versa.
   */
  loop?: boolean | undefined;
  /**
   * The key used to get the label from the item.
   * @default 'label'
   */
  labelKey?: string | undefined;
  /**
   * The key used to get the description from the item.
   * @default 'description'
   */
  descriptionKey?: string | 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;
  /**
   * 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;
  groups?: CommandPaletteGroup<ContentSearchItem>[] | undefined;
  /**
   * @default ''
   */
  searchTerm?: string | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the ContentSearch component
 */
interface ContentSearchSlots {
  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;
  content(): any;
}
```

### События

```ts
/**
 * Emitted events for the ContentSearch component
 */
interface ContentSearchEmits {
  update:searchTerm: (payload: [value: string]) => void;
}
```

### Доступ через ref

Через ref шаблона доступно:

| Name | Type |
| --- | --- |
| `commandPaletteRef` | `Ref<InstanceType<typeof B24CommandPalette> \| null>` |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    contentSearch: {
      slots: {
        modal: 'p-0 pt-0 pb-[10px]',
        input: ''
      },
      variants: {
        fullscreen: {
          false: {
            modal: 'sm:max-w-[768px] h-full sm:h-[436px]'
          }
        },
        size: {
          xss: {},
          xs: {},
          sm: {},
          md: {},
          lg: {},
          xl: {}
        }
      },
      defaultVariants: {
        size: 'md'
      }
    }
  }
})
```

## Sitemap

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