v2.15.0

Popover

Немодальное всплывающее окно для показа сообщений или сбора данных от пользователя.

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

Поместите в слот по умолчанию Popover Button или любой другой компонент.

Затем слот #content задаёт содержимое, которое показывается при открытии Popover.

<template>
  <B24Popover>
    <B24Button label="Open" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>

Режим

Пропс mode меняет режим Popover. По умолчанию click.

В режиме hover пропс enable-touch позволяет открывать и закрывать Popover касанием по триггеру на сенсорных устройствах. Для триггеров, на которые рассчитано нажатие, используйте режим click.
<template>
  <B24Popover mode="hover" enable-touch>
    <B24Button label="Open" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>
В режиме hover вместо Popover используется компонент HoverCard из Reka UI.

Задержка

В режиме hover пропсы open-delay и close-delay задают задержку перед открытием и закрытием Popover.

<template>
  <B24Popover mode="hover" :open-delay="500" :close-delay="300">
    <B24Button label="Open" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>

Содержимое

Пропс content управляет отрисовкой содержимого Popover: например, align и side задают выравнивание и сторону.

<template>
  <B24Popover
    :content="{
      align: 'center',
      side: 'bottom',
      sideOffset: 8
    }"
  >
    <B24Button label="Open" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>

Стрелка

Пропс arrow показывает стрелку у Popover.

<template>
  <B24Popover arrow>
    <B24Button label="Open" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>

Пропс modal определяет, блокирует ли Popover взаимодействие с остальной страницей. По умолчанию false.

<template>
  <B24Popover modal>
    <B24Button label="Open" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>

Закрытие по действию вне окна

Пропс dismissible определяет, закрывается ли Popover по клику вне его или по Esc. По умолчанию true.

Когда пользователь пытается закрыть Popover, срабатывает событие close:prevent.
<script setup lang="ts">
import Cross50Icon from '@bitrix24/b24icons-vue/actions/Cross50Icon'
</script>

<template>
  <B24Popover :dismissible="false" :b24ui="{ content: 'p-4' }">
    <B24Button label="Открыть" />

    <template #content="{ close }">
      <div class="flex items-center gap-4 mb-4">
        <h2 class="text-legend font-(--ui-font-weight-semi-bold)">
          Popover без закрытия по действию вне окна
        </h2>

        <B24Button color="air-tertiary" :icon="Cross50Icon" @click="close" />
      </div>

      <Placeholder class="size-full min-h-48" />
    </template>
  </B24Popover>
</template>

Примеры

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

Состоянием открытия управляют пропс default-open или директива v-model:open.

<script setup lang="ts">
const open = ref(false)

defineShortcuts({
  o: () => open.value = !open.value
})
</script>

<template>
  <B24Popover v-model:open="open">
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>
<script setup lang="ts">
import { ref } from 'vue'

const open = ref(false)

defineShortcuts({
  o: () => open.value = !open.value
})
</script>

<template>
  <B24Popover v-model:open="open">
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="size-48 m-4 inline-flex" />
    </template>
  </B24Popover>
</template>
В этом примере с помощью defineShortcuts Popover переключается по нажатию O.

С командной палитрой

Внутрь содержимого Popover можно поместить компонент CommandPalette.

<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>

С привязкой к курсору

Чтобы Popover следовал за курсором при наведении на элемент, используйте пропс reference:

<script setup lang="ts">
const open = ref(false)
const anchor = ref({ x: 0, y: 0 })

const reference = computed(() => ({
  getBoundingClientRect: () =>
    ({
      width: 0,
      height: 0,
      left: anchor.value.x,
      right: anchor.value.x,
      top: anchor.value.y,
      bottom: anchor.value.y,
      ...anchor.value
    } as DOMRect)
}))
</script>

<template>
  <B24Popover
    :open="open"
    :reference="reference"
    :content="{ side: 'top', sideOffset: 16, updatePositionStrategy: 'always' }"
  >
    <div
      class="flex items-center justify-center rounded-md border border-dashed border-(--ui-color-accent-main-primary-alt) text-sm aspect-video w-72"
      @pointerenter="open = true"
      @pointerleave="open = false"
      @pointermove="(ev: PointerEvent) => {
        anchor.x = ev.clientX
        anchor.y = ev.clientY
      }"
    >
      Наведите на меня
    </div>

    <template #content>
      <div class="p-4 text-description">
        {{ anchor.x.toFixed(0) }} - {{ anchor.y.toFixed(0) }}
      </div>
    </template>
  </B24Popover>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'

const open = ref(false)
const anchor = ref({ x: 0, y: 0 })

const reference = computed(() => ({
  getBoundingClientRect: () =>
    ({
      width: 0,
      height: 0,
      left: anchor.value.x,
      right: anchor.value.x,
      top: anchor.value.y,
      bottom: anchor.value.y,
      ...anchor.value
    } as DOMRect)
}))
</script>

<template>
  <B24Popover
    :open="open"
    :reference="reference"
    :content="{ side: 'top', sideOffset: 16, updatePositionStrategy: 'always' }"
  >
    <div
      class="flex items-center justify-center rounded-md border border-dashed border-(--ui-color-accent-main-primary-alt) text-sm aspect-video w-72"
      @pointerenter="open = true"
      @pointerleave="open = false"
      @pointermove="(ev: PointerEvent) => {
        anchor.x = ev.clientX
        anchor.y = ev.clientY
      }"
    >
      Наведите на меня
    </div>

    <template #content>
      <div class="p-4 text-description">
        {{ anchor.x.toFixed(0) }} - {{ anchor.y.toFixed(0) }}
      </div>
    </template>
  </B24Popover>
</template>

Со слотом anchor

Слот #anchor позиционирует Popover относительно произвольного элемента.

Слот работает только при mode, равном click.
<script lang="ts" setup>
const open = ref(false)
</script>

<template>
  <B24Popover
    v-model:open="open"
    :dismissible="false"
    :b24ui="{ content: 'w-(--reka-popover-trigger-width) p-4' }"
  >
    <template #anchor>
      <B24Input placeholder="Фокус открывает список" @focus="open = true" @blur="open = false" />
    </template>

    <template #content>
      <Placeholder class="w-full aspect-square" />
    </template>
  </B24Popover>
</template>

Карточка сведений о сущности

Пример из практики: сводка по аккаунту или сделке во всплывающем окне при наведении. Собрана из Card, Avatar, Separator, Button, Link и DescriptionList — без своих стилей, кроме акцента аватара.

<script setup lang="ts">
import UserGroupIcon from '@bitrix24/b24icons-vue/common-b24/UserGroupIcon'
import type { DescriptionListItem } from '@bxshefby/b24ui-nuxt'

const items = [
  { label: 'Менеджер аккаунта', description: 'Пример владельца', slot: 'owner' as const },
  { label: 'Создано', description: '6 октября 2024 08:37' },
  { label: 'Сегмент', description: 'Корпоративный' }
] satisfies DescriptionListItem[]
</script>

<template>
  <B24Popover mode="hover" :content="{ side: 'bottom', sideOffset: 8 }" :b24ui="{ content: 'p-0' }">
    <B24Link is-action>
      ООО «Акме»
    </B24Link>

    <template #content>
      <div class="w-65 p-6 flex flex-col gap-4.5">
        <div class="flex items-center gap-3">
          <B24Avatar
            size="lg"
            color="air-secondary-alert"
            :icon="UserGroupIcon"
          />
          <div class="min-w-0">
            <div class="text-label font-(--ui-font-weight-semi-bold) truncate">
              ООО «Акме»
            </div>
            <div class="text-sm text-description truncate">
              12 контактов
            </div>
          </div>
        </div>

        <B24Button block size="sm" color="air-secondary-accent-2" label="Открыть аккаунт" />

        <B24Separator />

        <B24DescriptionList
          size="sm"
          :items="items"
          :b24ui="{
            container: 'mt-0 sm:grid-cols-1',
            labelWrapper: 'border-t-0 sm:border-t-0 py-0 sm:py-0',
            descriptionWrapper: 'sm:border-t-0 py-0 pb-2.5 sm:py-0 sm:pb-2.5 last:pb-0 sm:last:pb-0'
          }"
        >
          <template #description="{ item }">
            <B24Link v-if="item.slot === 'owner'">{{ item.description }}</B24Link>
            <template v-else>{{ item.description }}</template>
          </template>
        </B24DescriptionList>
      </div>
    </template>
  </B24Popover>
</template>

Собрать всплывающее окно со сведениями о сущности для любой записи или объекта.

Виджет динамики продаж

Пример из практики: Popover со статистической карточкой. Сам виджет описан на странице Card; здесь он лежит внутри B24Popover, и кнопка-триггер показывает его по требованию.

<script setup lang="ts">
import RepeatIcon from '@bitrix24/b24icons-vue/outline/RepeatIcon'
import SettingsIcon from '@bitrix24/b24icons-vue/outline/SettingsIcon'
import FeedbackIcon from '@bitrix24/b24icons-vue/outline/FeedbackIcon'
import Info1Icon from '@bitrix24/b24icons-vue/main/Info1Icon'

const rows = [
  { label: 'Активные сделки', count: 10, amount: '$46,500' },
  { label: 'Выигранные сделки', count: 1, amount: '$10,000' }
]

const highlight = {
  label: 'Конверсия',
  count: '10%',
  amount: '17.7%',
  info: 'Сегодня и последние 30 дней'
}
</script>

<template>
  <B24Popover :b24ui="{ content: 'p-0 bg-transparent border-0 shadow-none' }">
    <B24Button label="Открыть виджет продаж" />

    <template #content>
      <B24Card
        variant="filled-copilot"
        class="max-w-md"
        :b24ui="{
          root: 'edge-dark rounded-2xl bg-[radial-gradient(110.42%_110.42%_at_-10.42%_31.25%,var(--ui-color-copilot-bg-content-3)_0%,var(--ui-color-copilot-bg-content-2)_58.65%,var(--ui-color-copilot-bg-content-1)_100%)]'
        }"
      >
        <template #header>
          <div class="flex items-start justify-between gap-4">
            <div class="min-w-0">
              <div class="text-(length:--ui-font-size-2xl)/[normal] font-(--ui-font-weight-semi-bold)">
                Динамика повторных продаж
              </div>
              <div class="text-(length:--ui-font-size-md) opacity-90">
                Всего создано сделок: 10
              </div>
              <div class="text-(length:--ui-font-size-md) opacity-90">
                Сегодня: 10 сделок
              </div>
            </div>

            <B24Button
              rounded
              color="air-secondary-accent"
              label="Последние 30 дней"
              :trailing-icon="RepeatIcon"
            />
          </div>
        </template>

        <div class="flex flex-col gap-2">
          <div class="grid grid-cols-[1fr_auto_auto] gap-x-6 px-3 py-1 text-(length:--ui-font-size-sm) opacity-80">
            <span />
            <span class="text-end min-w-20">Количество</span>
            <span class="text-end min-w-24">Сумма</span>
          </div>

          <div
            v-for="row in rows"
            :key="row.label"
            class="grid grid-cols-[1fr_auto_auto] gap-x-6 items-center px-3 py-3 rounded-xl bg-white/5"
          >
            <span class="font-(--ui-font-weight-medium)">{{ row.label }}</span>
            <span class="text-end min-w-20">{{ row.count }}</span>
            <span class="text-end min-w-24">{{ row.amount }}</span>
          </div>

          <div class="style-filled-boost grid grid-cols-[1fr_auto_auto] gap-x-6 items-center px-3 py-3 rounded-xl text-(--ui-color-design-filled-boost-content)">
            <span class="font-(--ui-font-weight-medium) inline-flex items-center gap-1">
              {{ highlight.label }}
              <B24Tooltip :text="highlight.info">
                <Info1Icon class="size-4 opacity-80" />
              </B24Tooltip>
            </span>
            <span class="text-end min-w-20">{{ highlight.count }}</span>
            <span class="text-end min-w-24 font-(--ui-font-weight-semi-bold)">{{ highlight.amount }}</span>
          </div>
        </div>

        <template #footer>
          <div class="flex items-center justify-between gap-4">
            <B24Button color="air-secondary-accent" :icon="SettingsIcon" label="Настроить" />
            <B24Button color="air-secondary-accent" :icon="FeedbackIcon" label="Обратная связь" />
          </div>
        </template>
      </B24Card>
    </template>
  </B24Popover>
</template>

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

API

Пропсы

Prop Default Type
mode'click' M

The display mode of the popover.

content{ side: 'bottom', sideOffset: 8, collisionPadding: 8 } PopoverContentProps & Partial<EmitsToProps<PopoverContentImplEmits>>

The content of the popover.

arrowfalseboolean | PopoverArrowProps

Display an arrow alongside the popover.

portaltrue string | false | true | HTMLElement

Render the popover in a portal.

reference Element | VirtualElement

The reference (or anchor) element that is being referred to for positioning.

Accepts an element or a virtual element (anything with getBoundingClientRect), and can be changed reactively to re-anchor the popover (e.g. for a guided tour). If not provided will use the current component as anchor.

dismissibletrueboolean

When false, the popover will not close when clicking outside or pressing escape.

defaultOpenboolean

The open state of the popover when it is initially rendered. Use when you do not need to control its open state.

openboolean

The controlled open state of the popover.

modalfalseboolean

The modality of the popover. When set to true, interaction with outside elements will be disabled and only popover content will be visible to screen readers.

openDelay0 number

The duration from when the mouse enters the trigger until the hover card opens.

closeDelay0 number

The duration from when the mouse leaves the trigger or content until the hover card closes.

enableTouchboolean

When true, tapping the trigger on touch devices toggles the hover card open/closed. By default touch interactions are ignored to match pointer hover semantics.

b24ui { content?: SlotClass; arrow?: SlotClass; }

Слоты

Slot Type
default{ open: boolean; }
contentSlotProps<M>
anchorSlotProps<M>
Функция close доступна только при mode, равном click: Reka UI даёт её для Popover, но не для HoverCard.

События

Event Type
close:prevent[]
update:open[value: boolean]

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/popover.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-(--reka-popover-content-transform-origin) focus:outline-none pointer-events-auto',
    arrow: 'fill-(--ui-color-bg-content-primary)'
  }
}