v2.15.0

EditorMentionMenu

Меню упоминаний, которое показывает подсказки пользователей, когда в редакторе вводят символ-триггер.

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

Компонент EditorMentionMenu показывает меню подсказок пользователей, когда в редакторе вводят символ-триггер (по умолчанию @), и вставляет выбранное упоминание через пакет @tiptap/extension-mention. Символ-триггер также служит префиксом вставленного упоминания.

Он использует композабл useEditorMenu на основе утилиты Suggestion из TipTap: элементы фильтруются по мере ввода, а по меню можно перемещаться с клавиатуры (стрелки, Enter для выбора, Escape для закрытия).
Компонент нужно использовать в слоте по умолчанию компонента Editor, чтобы получить доступ к экземпляру редактора.
<script setup lang="ts">
import type { EditorMentionMenuItem } from '@bxshefby/b24ui-nuxt'

const value = ref(`# Меню упоминаний

Введите @, чтобы упомянуть пользователя, и выберите его из списка.`)

const items: EditorMentionMenuItem[] = [
  {
    label: 'bitrix24',
    avatar: {
      src: 'https://github.com/bitrix24.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Сотрудник',
    avatar: {
      src: '/b24ui/avatar/employee.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Ассистент',
    avatar: {
      src: '/b24ui/avatar/assistant.png',
      loading: 'lazy' as const
    }
  }
]

// Безопасная для SSR функция, добавляющая меню в body (чтобы не было проблем с z-index в документации)
const appendToBody = import.meta.client ? () => document.body : undefined
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите @, чтобы упомянуть пользователя..."
    class="w-full min-h-21"
  >
    <B24EditorMentionMenu :editor="editor" :items="items" :append-to="appendToBody" />
  </B24Editor>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { EditorMentionMenuItem } from '@bxshefby/b24ui-nuxt'

const value = ref(`# Меню упоминаний

Введите @, чтобы упомянуть пользователя, и выберите его из списка.`)

const items: EditorMentionMenuItem[] = [
  {
    label: 'bitrix24',
    avatar: {
      src: 'https://github.com/bitrix24.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Сотрудник',
    avatar: {
      src: '/b24ui/avatar/employee.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Ассистент',
    avatar: {
      src: '/b24ui/avatar/assistant.png',
      loading: 'lazy' as const
    }
  }
]

// Безопасная для SSR функция, добавляющая меню в body (чтобы не было проблем с z-index в документации)
const appendToBody = import.meta.client ? () => document.body : undefined
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите @, чтобы упомянуть пользователя..."
    class="w-full min-h-21"
  >
    <B24EditorMentionMenu :editor="editor" :items="items" :append-to="appendToBody" />
  </B24Editor>
</template>
Подробнее о расширении Mention — в документации TipTap.

Элементы

Пропс items — массив объектов со свойствами:

  • label: string
  • avatar?: AvatarProps
  • icon?: IconComponent
  • description?: string
  • disabled?: boolean
<script setup lang="ts">
import type { EditorMentionMenuItem } from '@bxshefby/b24ui-nuxt'

const value = ref(`Введите @, чтобы упомянуть пользователя.

Элементы можно настроить: добавить аватары, иконки и описания.`)

const items: EditorMentionMenuItem[] = [
  {
    label: 'bitrix24',
    avatar: { src: 'https://github.com/bitrix24.png', loading: 'lazy' as const },
    description: 'Профиль Bitrix24'
  },
  {
    label: 'Сотрудник',
    avatar: { src: '/b24ui/avatar/employee.png', loading: 'lazy' as const }
  },
  {
    label: 'Ассистент',
    avatar: { src: '/b24ui/avatar/assistant.png', loading: 'lazy' as const },
    disabled: true
  }
]
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите @ для упоминания..."
    class="w-full min-h-19"
  >
    <B24EditorMentionMenu :editor="editor" :items="items" />
  </B24Editor>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { EditorMentionMenuItem } from '@bxshefby/b24ui-nuxt'

const value = ref(`Введите @, чтобы упомянуть пользователя.

Элементы можно настроить: добавить аватары, иконки и описания.`)

const items: EditorMentionMenuItem[] = [
  {
    label: 'bitrix24',
    avatar: { src: 'https://github.com/bitrix24.png', loading: 'lazy' as const },
    description: 'Профиль Bitrix24'
  },
  {
    label: 'Сотрудник',
    avatar: { src: '/b24ui/avatar/employee.png', loading: 'lazy' as const }
  },
  {
    label: 'Ассистент',
    avatar: { src: '/b24ui/avatar/assistant.png', loading: 'lazy' as const },
    disabled: true
  }
]
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите @ для упоминания..."
    class="w-full min-h-19"
  >
    <B24EditorMentionMenu :editor="editor" :items="items" />
  </B24Editor>
</template>
Чтобы получить отдельные группы элементов, передайте в items массив массивов.

Символ

Пропс char меняет символ-триггер. По умолчанию @. Символ-триггер также служит префиксом вставленного упоминания (например, #channel вместо @channel).

<template>
  <B24Editor v-slot="{ editor }">
    <B24EditorMentionMenu :editor="editor" :items="channels" char="#" />
  </B24Editor>
</template>
В одном редакторе можно использовать несколько компонентов EditorMentionMenu с разными пропсами char и plugin-key, чтобы поддержать разные типы упоминаний.
<template>
  <B24Editor v-slot="{ editor }">
    <B24EditorMentionMenu :editor="editor" :items="users" plugin-key="mentionMenu" />
    <B24EditorMentionMenu :editor="editor" :items="tags" char="#" plugin-key="tagMenu" />
  </B24Editor>
</template>

Подсказка

Пропс suggestion настраивает поведение сопоставления Suggestion из TipTap.

Это нужно, если меню должно открываться сразу после других символов, а не только после пробела, как по умолчанию.

<template>
  <B24Editor v-slot="{ editor }">
    <B24EditorMentionMenu
      :editor="editor"
      :items="items"
      char="#"
      :suggestion="{
        allowedPrefixes: null
      }"
    />
  </B24Editor>
</template>

Параметры

Пропс options настраивает позиционирование с помощью параметров Floating UI.

<template>
  <B24Editor v-slot="{ editor }">
    <B24EditorMentionMenu
      :editor="editor"
      :items="items"
      :options="{
        placement: 'bottom-start',
        offset: 4
      }"
    />
  </B24Editor>
</template>

Примеры

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

Пропс ignore-filter со значением true отключает встроенный поиск, и вы используете свою логику поиска. Директива v-model:search-term даёт доступ к текущему запросу, по которому можно получать элементы из API.

<script setup lang="ts">
import { refDebounced } from '@vueuse/core'

const value = ref(`# Асинхронное меню упоминаний

Введите @, чтобы упомянуть пользователя. Результаты загружаются из API по мере набора.`)

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

const { data: items } = useLazyFetch('https://dummyjson.com/users/search?limit=10', {
  key: 'editor-mention-users-search',
  query: { q: searchTermDebounced },
  transform: (data: { users: { id: number, firstName: string, lastName: string, image: string }[] }) => {
    return data.users?.map(user => ({ id: user.id, label: `${user.firstName} ${user.lastName}`, avatar: { src: user.image, loading: 'lazy' as const } })) || []
  },
  server: false
})

// Безопасная для SSR функция, добавляющая меню в body (чтобы не было проблем с z-index в документации)
const appendToBody = import.meta.client ? () => document.body : undefined
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите @ для упоминания..."
    class="w-full min-h-21"
  >
    <B24EditorMentionMenu
      v-model:search-term="searchTerm"
      :editor="editor"
      :items="items"
      :append-to="appendToBody"
      ignore-filter
    />
  </B24Editor>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { refDebounced } from '@vueuse/core'

const value = ref(`# Асинхронное меню упоминаний

Введите @, чтобы упомянуть пользователя. Результаты загружаются из API по мере набора.`)

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

const { data: items } = useLazyFetch('https://dummyjson.com/users/search?limit=10', {
  key: 'editor-mention-users-search',
  query: { q: searchTermDebounced },
  transform: (data: { users: { id: number, firstName: string, lastName: string, image: string }[] }) => {
    return data.users?.map(user => ({ id: user.id, label: `${user.firstName} ${user.lastName}`, avatar: { src: user.image, loading: 'lazy' as const } })) || []
  },
  server: false
})

// Безопасная для SSR функция, добавляющая меню в body (чтобы не было проблем с z-index в документации)
const appendToBody = import.meta.client ? () => document.body : undefined
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите @ для упоминания..."
    class="w-full min-h-21"
  >
    <B24EditorMentionMenu
      v-model:search-term="searchTerm"
      :editor="editor"
      :items="items"
      :append-to="appendToBody"
      ignore-filter
    />
  </B24Editor>
</template>
В этом примере refDebounced откладывает вызовы API.

API

Пропсы

Prop Default Type
size'md' "xs" | "md" | "xss" | "sm" | "lg" | "xl"
items T[] | T[][]
editorEditor
char'@' string

The trigger character (e.g., '/', '@', ':')

pluginKey'mentionMenu' string

Plugin key to identify this menu

filterFields['label'] string[]

Fields to filter items by.

limit42 number

Maximum number of items to display

options{ strategy: 'absolute', placement: 'bottom-start', offset: 8, shift: { padding: 8 } } FloatingUIOptions

The options for positioning the menu. Those are passed to Floating UI and include options for the placement, offset, flip, shift, size, autoPlacement, hide, and inline middleware.

suggestion Omit<Partial<SuggestionOptions<any, any>>, "editor" | "char" | "pluginKey" | "items" | "command" | "render">

Optional TipTap Suggestion matching options.

appendTo HTMLElement | (): HTMLElement

The DOM element to append the menu to. Default is the editor's parent element.

Sometimes the menu needs to be appended to a different DOM context due to accessibility, clipping, or z-index issues.

b24ui { content?: SlotClass; viewport?: SlotClass; group?: SlotClass; label?: SlotClass; separator?: SlotClass; item?: SlotClass; itemLeadingIcon?: SlotClass; itemLeadingAvatar?: SlotClass; itemLeadingAvatarSize?: SlotClass; itemWrapper?: SlotClass; itemLabel?: SlotClass; itemDescription?: SlotClass; itemLabelExternalIcon?: SlotClass; }

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/editor-mention-menu.ts
export default {
  slots: {
    content: 'base-mode bg-(--ui-color-bg-content-primary) shadow-(--popup-window-box-shadow) rounded-(--ui-border-radius-xl) will-change-[opacity] motion-safe:data-[state=open]:animate-[scale-in_100ms_var(--ease-out)] motion-safe:data-[state=closed]:animate-[scale-out_100ms_var(--ease-out)] origin-top font-[family-name:var(--ui-font-family-primary)] relative isolate px-0 py-(--menu-popup-padding) pointer-events-auto',
    viewport: 'relative w-full max-h-[min(var(--max-height-popup-menu),100vh)] min-w-48 max-w-60 overflow-x-hidden overflow-y-auto scrollbar-thin',
    group: 'grid',
    label: 'w-full h-(--popup-window-delimiter-section-height) mt-(--menu-item-block-stack-space) flex flex-row rtl:flex-row-reverse items-center select-none outline-none whitespace-nowrap text-start text-legend font-(--ui-font-weight-normal) after:ms-[10px] after:block after:flex-1 after:min-w-[15px] after:h-px after:bg-(--ui-color-divider-vibrant-default)',
    separator: 'my-2 mx-4.5 h-px bg-(--ui-color-divider-vibrant-default)',
    item: 'group w-full  mt-(--menu-item-block-stack-space) relative flex flex-row rtl:flex-row-reverse items-center select-none outline-none whitespace-nowrap cursor-pointer data-disabled:cursor-not-allowed data-disabled:opacity-30 text-start text-legend hover:text-label data-highlighted:text-label data-[state=open]:text-label hover:bg-(--ui-color-base-black-fixed)/3 dark:hover:bg-(--ui-color-base-black-fixed) active:bg-(--ui-color-base-black-fixed)/6 dark:active:bg-(--ui-color-base-black-fixed) data-highlighted:not-active:bg-(--ui-color-base-black-fixed)/3 dark:data-highlighted:not-active:bg-(--ui-color-base-black-fixed) data-[state=open]:bg-(--ui-color-base-black-fixed)/6 dark:data-[state=open]:bg-(--ui-color-base-black-fixed) transition-colors',
    itemLeadingIcon: 'size-[25px] shrink-0 text-(--ui-color-base-5)',
    itemLeadingAvatar: 'shrink-0',
    itemLeadingAvatarSize: '',
    itemWrapper: 'ms-[4px] flex-1 flex flex-col text-start min-w-0',
    itemLabel: 'max-w-60 truncate -mt-px',
    itemDescription: 'max-w-60 truncate -mt-[6px] text-description text-(length:--ui-font-size-sm)',
    itemLabelExternalIcon: 'inline-block size-[25px] text-(--ui-color-base-5)'
  },
  variants: {
    size: {
      xss: {
        label: 'px-[14px] text-(length:--ui-font-size-4xs)/[normal] gap-[14px]',
        item: 'px-[14px] text-(length:--ui-font-size-4xs)/[normal] gap-[14px]',
        itemLeadingIcon: 'size-4 text-(length:--ui-font-size-sm)/[normal]',
        itemLeadingAvatarSize: '3xs'
      },
      xs: {
        label: 'px-[14px] text-(length:--ui-font-size-4xs)/[normal] gap-[14px]',
        item: 'px-[14px] text-(length:--ui-font-size-xs)/[normal] gap-[14px]',
        itemLeadingIcon: 'size-4 text-(length:--ui-font-size-sm)/[normal]',
        itemLeadingAvatarSize: '3xs'
      },
      sm: {
        label: 'px-4.5 text-(length:--ui-font-size-xs)/[normal] gap-4.5',
        item: 'px-4.5 text-(length:--ui-font-size-xs)/[normal] gap-4.5',
        itemLeadingIcon: 'size-4 text-(length:--ui-font-size-sm)/[normal]',
        itemLeadingAvatarSize: '3xs'
      },
      md: {
        label: 'px-4.5 text-(length:--ui-font-size-sm)/[normal] gap-4.5',
        item: 'h-[36px] px-4.5 text-(length:--ui-font-size-sm)/[normal] gap-4.5',
        itemLeadingIcon: 'size-4.5 text-(length:--ui-font-size-lg)/[normal]',
        itemLeadingAvatar: 'size-[16px] me-2',
        itemLeadingAvatarSize: '2xs'
      },
      lg: {
        label: 'px-[20px] text-(length:--ui-font-size-sm)/[normal] gap-[20px]',
        item: 'px-[20px] text-(length:--ui-font-size-sm)/[normal] gap-[20px]',
        itemLeadingIcon: 'size-4.5 text-(length:--ui-font-size-lg)/[normal]',
        itemLeadingAvatar: 'size-[16px] me-2',
        itemLeadingAvatarSize: '2xs'
      },
      xl: {
        label: 'px-[20px] text-(length:--ui-font-size-sm)/[normal] gap-[20px]',
        item: 'px-[20px] text-(length:--ui-font-size-lg)/[normal] gap-[20px]',
        itemLeadingIcon: 'size-[20px] text-(length:--ui-font-size-2xl)/[normal]',
        itemLeadingAvatar: 'size-[16px] me-2',
        itemLeadingAvatarSize: 'xs'
      }
    },
    active: {
      true: {
        item: '',
        itemLeadingIcon: 'text-(--ui-color-accent-main-primary) hover:text-(--ui-color-accent-main-primary) group-data-[state=open]:text-(--ui-color-accent-main-primary)'
      },
      false: {}
    }
  },
  defaultVariants: {
    size: 'md'
  }
}