v2.15.0

Drawer

Выдвижная шторка с плавными анимациями появления и скрытия.

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

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

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

<template>
  <B24Drawer>
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>

Слоты #header, #body и #footer настраивают содержимое Drawer.

Заголовок

Пропс title задаёт заголовок в шапке Drawer.

<template>
  <B24Drawer title="Drawer с заголовком">
    <B24Button label="Открыть" />

    <template #body>
      <Placeholder class="h-48" />
    </template>
  </B24Drawer>
</template>

Описание

Пропс description задаёт описание в шапке Drawer.

<template>
  <B24Drawer
    title="Drawer с описанием"
    description="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
  >
    <B24Button label="Открыть" />

    <template #body>
      <Placeholder class="h-48" />
    </template>
  </B24Drawer>
</template>

Направление

Пропс direction задаёт направление Drawer. По умолчанию bottom.

<template>
  <B24Drawer direction="right">
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="min-w-96 min-h-96 size-full m-4" />
    </template>
  </B24Drawer>
</template>

Отступ от краёв

Пропс inset отодвигает Drawer от краёв.

<template>
  <B24Drawer direction="right" inset>
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="min-w-96 min-h-96 size-full m-4" />
    </template>
  </B24Drawer>
</template>

Ручка

Пропс handle определяет, есть ли у Drawer ручка. По умолчанию true.

<template>
  <B24Drawer :handle="false">
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>

Только ручка

Пропс handle-only разрешает перетаскивать Drawer только за ручку.

<template>
  <B24Drawer handle-only>
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>

Оверлей

Пропс overlay определяет, есть ли у Drawer оверлей. По умолчанию true.

<template>
  <B24Drawer :overlay="false">
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>

Пропс modal определяет, блокирует ли Drawer взаимодействие с контентом вне него. По умолчанию true.

Если modal равен false, оверлей отключается автоматически, и контент вне Drawer остаётся доступным.
<template>
  <B24Drawer :modal="false">
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>

Закрытие вне Drawer

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

Когда пользователь пытается закрыть Drawer, срабатывает событие close:prevent.
Чтобы фон при открытом Drawer оставался доступным и Drawer не закрывался, объедините modal: false и dismissible: false.
<script setup lang="ts">
import Cross50Icon from '@bitrix24/b24icons-vue/actions/Cross50Icon'

const open = ref(false)
</script>

<template>
  <B24Drawer v-model:open="open" :dismissible="false" :modal="false" :handle="false">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #body>
      <div class="flex items-center justify-between gap-4 mb-4">
        <ProseH2 class="mb-0"> Drawer без закрытия по действию вне окна </ProseH2>

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

      <Placeholder class="size-full min-h-48" />
    </template>
  </B24Drawer>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import Cross50Icon from '@bitrix24/b24icons-vue/actions/Cross50Icon'

const open = ref(false)
</script>

<template>
  <B24Drawer v-model:open="open" :dismissible="false" :modal="false" :handle="false">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #body>
      <div class="flex items-center justify-between gap-4 mb-4">
        <ProseH2 class="mb-0"> Drawer без закрытия по действию вне окна </ProseH2>

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

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

Масштабирование фона

Пропс should-scale-background масштабирует фон при открытом Drawer и создаёт эффект глубины. Пропс set-background-color-on-scale со значением false запрещает менять цвет фона.

<template>
  <B24Drawer should-scale-background set-background-color-on-scale>
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>
Чтобы это работало, добавьте директиву data-vaul-drawer-wrapper родительскому элементу приложения.
app.vue
<template>
  <B24App>
    <div class="bg-default" data-vaul-drawer-wrapper>
      <NuxtLayout>
        <NuxtPage />
      </NuxtLayout>
    </div>
  </B24App>
</template>
nuxt.config.ts
export default defineNuxtConfig({
  app: {
    rootAttrs: {
      'data-vaul-drawer-wrapper': '',
      'class': 'bg-default'
    }
  }
})

Без стилей для body 2.15+

Пропс no-body-styles запрещает Drawer применять стили к элементу <body>: например, pointer-events: none, который блокирует взаимодействие со страницей, пока Drawer открыт.

При включённом overlay прокрутка body всё равно блокируется. Чтобы страница оставалась интерактивной, объедините no-body-styles и overlay: false.
<template>
  <B24Drawer no-body-styles :overlay="false">
    <B24Button label="Открыть" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>

Примеры

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

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

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

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

<template>
  <B24Drawer v-model:open="open">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

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

const open = ref(false)

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

<template>
  <B24Drawer v-model:open="open">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>
В этом примере с помощью defineShortcuts Drawer открывается и закрывается клавишей O.
Так триггер можно вынести за пределы Drawer или убрать совсем.

Адаптивный Drawer

Например, на десктопе можно показывать компонент Modal, а на мобильных устройствах — Drawer.

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

const { screen } = useDevice()

const [DefineFormTemplate, ReuseFormTemplate] = createReusableTemplate()
const open = ref(false)

const state = reactive({
  email: undefined
})

const title = 'Изменить профиль'
const description = 'Здесь можно изменить данные профиля. Нажмите «Сохранить», когда закончите.'
</script>

<template>
  <DefineFormTemplate>
    <B24Form :state="state" class="space-y-4">
      <B24FormField label="Email" name="email" required>
        <B24Input v-model="state.email" placeholder="you@example.com" required />
      </B24FormField>

      <B24Button label="Сохранить изменения" color="air-primary-success" type="submit" />
    </B24Form>
  </DefineFormTemplate>

  <B24Modal v-if="!screen.isMobile" v-model:open="open" :title="title" :description="description">
    <B24Button label="Изменить профиль" />

    <template #body>
      <ReuseFormTemplate />
    </template>
  </B24Modal>

  <B24Drawer v-else v-model:open="open" :title="title" :description="description">
    <B24Button label="Изменить профиль" />

    <template #body>
      <ReuseFormTemplate />
    </template>
  </B24Drawer>
</template>

Вложенные Drawer

Drawer можно вкладывать друг в друга пропсом nested.

<template>
  <B24Drawer :b24ui="{ content: 'h-full' }">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #footer>
      <B24Drawer nested :b24ui="{ content: 'h-full' }">
        <B24Button label="Открыть вложенное" />

        <template #content>
          <Placeholder class="flex-1 m-4" />
        </template>
      </B24Drawer>
    </template>
  </B24Drawer>
</template>

Слот #footer добавляет контент после тела Drawer.

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

<template>
  <B24Drawer
    v-model:open="open"
    title="Drawer с подвалом"
    description="Пригодится, когда в Drawer нужна форма."
    :b24ui="{ container: 'max-w-xl mx-auto' }"
  >
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #body>
      <Placeholder class="h-48" />
    </template>

    <template #footer>
      <B24Button label="Отправить" color="air-primary-success" />
      <B24Button label="Отмена" @click="open = false" />
    </template>
  </B24Drawer>
</template>
<script setup lang="ts">
import { ref } from 'vue'

const open = ref(false)
</script>

<template>
  <B24Drawer
    v-model:open="open"
    title="Drawer с подвалом"
    description="Пригодится, когда в Drawer нужна форма."
    :b24ui="{ container: 'max-w-xl mx-auto' }"
  >
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #body>
      <Placeholder class="h-48" />
    </template>

    <template #footer>
      <B24Button label="Отправить" color="air-primary-success" />
      <B24Button label="Отмена" @click="open = false" />
    </template>
  </B24Drawer>
</template>

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

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

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

API

Пропсы

Prop Default Type
as'div'any

The element or component this component should render as.

title string
description string
insetfalseboolean

Whether to inset the drawer from the edges.

content DialogContentProps & Partial<EmitsToProps<DialogContentImplEmits>>

The content of the drawer.

overlaytrueboolean

Render an overlay behind the drawer.

overlayBlur'auto' "auto" | "on" | "off"

Render an overlay blur behind the modal. auto use motion-safe.

handletrueboolean

Render a handle on the drawer.

portaltrue string | false | true | HTMLElement

Render the drawer in a portal.

nestedfalseboolean

Whether the drawer is nested in another drawer.

scrollbarThintrueboolean
closefalseboolean | Omit<ButtonProps, LinkPropsKeys>

Display a close button to dismiss the drawer. { size: 'md', color: 'air-tertiary-no-accent' }

closeIconicons.closeIconComponent

The icon displayed in the close button.

activeSnapPoint null | string | number
closeThreshold number

Number between 0 and 1 that determines when the drawer should be closed. Example: threshold of 0.5 would close the drawer if the user swiped for 50% of the height of the drawer or more.

shouldScaleBackgroundboolean
setBackgroundColorOnScaleboolean

When false we don't change body's background color when the drawer is open.

scrollLockTimeout number

Duration for which the drawer is not draggable after scrolling content inside of the drawer.

fixedboolean

When true, don't move the drawer upwards if there's space, but rather only change it's height so it's fully scrollable when the keyboard is open

dismissibletrueboolean

When false dragging, clicking outside, pressing esc, etc. will not close the drawer. Use this in combination with the open prop, otherwise you won't be able to open/close the drawer.

modaltrueboolean

When false it allows to interact with elements outside of the drawer without closing it.

openboolean
defaultOpenboolean

Opened by default, skips initial enter animation. Still reacts to open state changes

direction'bottom' "bottom" | "top" | "left" | "right"

Direction of the drawer. Can be top or bottom, left, right.

noBodyStylesboolean

When true the body doesn't get any styles assigned from Vaul

handleOnlyboolean

When true only allows the drawer to be dragged by the <Drawer.Handle /> component.

preventScrollRestorationboolean
snapPoints (string | number)[]

Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up. Should go from least visible. Example [0.2, 0.5, 0.8]. You can also use px values, which doesn't take screen height into account.

b24ui { overlay?: SlotClass; content?: SlotClass; handle?: SlotClass; container?: SlotClass; header?: SlotClass; wrapper?: SlotClass; title?: SlotClass; description?: SlotClass; actions?: SlotClass; body?: SlotClass; footer?: SlotClass; close?: SlotClass; }

Слоты

Slot Type
default{}
content{}
header{}
title{}
description{}
actions{}
close{ b24ui: object; }
body{}
footer{}

События

Event Type
close[]
drag[percentageDragged: number]
after:leave[]
after:enter[]
close:prevent[]
release[open: boolean]
update:open[open: boolean]
update:activeSnapPoint[val: string | number]
animationEnd[open: boolean]

Доступность 2.14+

При открытии фокус на один такт уходит с триггера, и только потом его перехватывает ловушка фокуса диалога. Так обходится ошибка тайминга в reka-ui, из-за которой браузер отказывается применять aria-hidden и пишет в консоль «Blocked aria-hidden on an element because its descendant retained focus».

Фокус возвращается туда, где он был до открытия, в том числе когда компонент открывают программно, а не через слот триггера. Скринридеры, которые сразу озвучивают смену фокуса (прежде всего VoiceOver), могут ненадолго озвучить заголовок страницы раньше заголовка диалога.

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/drawer.ts
export default {
  slots: {
    overlay: 'fixed inset-0',
    content: 'fixed base-mode bg-(--ui-color-bg-content-primary) flex focus:outline-none ring ring-(--ui-color-divider-default)',
    handle: 'shrink-0 !bg-(--ui-color-divider-default) transition-opacity',
    container: 'w-full flex flex-col gap-4 p-4 overflow-y-auto',
    header: 'flex items-center gap-1.5 min-h-8',
    wrapper: 'min-w-0 flex-1',
    title: 'font-[family-name:var(--ui-font-family-primary)] text-label font-(--ui-font-weight-medium) mb-0 text-[calc(var(--ui-font-size-2xl)+2px)]/(--ui-font-size-2xl)',
    description: 'mt-1 text-description text-(length:--ui-font-size-sm)',
    actions: 'flex items-center gap-1.5 shrink-0 ms-auto',
    body: 'flex-1',
    footer: 'flex flex-col gap-1.5',
    close: ''
  },
  variants: {
    overlayBlur: {
      auto: {
        overlay: 'motion-safe:backdrop-blur-sm'
      },
      on: {
        overlay: 'backdrop-blur-sm'
      },
      off: {
        overlay: ''
      }
    },
    scrollbarThin: {
      true: {
        body: 'scrollbar-thin'
      }
    },
    overlay: {
      true: {
        overlay: 'bg-[#003366]/20'
      }
    },
    direction: {
      top: {
        content: 'mb-24 flex-col-reverse',
        handle: 'mb-4'
      },
      right: {
        content: 'flex-row rtl:flex-row-reverse',
        handle: '!ml-4'
      },
      bottom: {
        content: 'mt-24 flex-col',
        handle: 'mt-4'
      },
      left: {
        content: 'flex-row-reverse rtl:flex-row',
        handle: '!mr-4'
      }
    },
    inset: {
      true: {
        content: 'rounded-lg after:hidden overflow-hidden [--initial-transform:calc(100%+1.5rem)]'
      }
    },
    snapPoints: {
      true: ''
    }
  },
  compoundVariants: [
    {
      direction: [
        'top',
        'bottom'
      ],
      class: {
        content: 'h-auto max-h-[96%]',
        handle: '!w-12 !h-1.5 mx-auto'
      }
    },
    {
      direction: [
        'top',
        'bottom'
      ],
      snapPoints: true,
      class: {
        content: 'h-full'
      }
    },
    {
      direction: [
        'right',
        'left'
      ],
      class: {
        content: 'w-auto max-w-[calc(100%-2rem)]',
        handle: '!h-12 !w-1.5 mt-auto mb-auto'
      }
    },
    {
      direction: [
        'right',
        'left'
      ],
      snapPoints: true,
      class: {
        content: 'w-full'
      }
    },
    {
      direction: 'top',
      inset: true,
      class: {
        content: 'inset-x-4 top-4'
      }
    },
    {
      direction: 'top',
      inset: false,
      class: {
        content: 'inset-x-0 top-0 rounded-b-lg'
      }
    },
    {
      direction: 'bottom',
      inset: true,
      class: {
        content: 'inset-x-4 bottom-4'
      }
    },
    {
      direction: 'bottom',
      inset: false,
      class: {
        content: 'inset-x-0 bottom-0 rounded-t-lg'
      }
    },
    {
      direction: 'left',
      inset: true,
      class: {
        content: 'inset-y-4 left-4'
      }
    },
    {
      direction: 'left',
      inset: false,
      class: {
        content: 'inset-y-0 left-0 rounded-r-lg'
      }
    },
    {
      direction: 'right',
      inset: true,
      class: {
        content: 'inset-y-4 right-4'
      }
    },
    {
      direction: 'right',
      inset: false,
      class: {
        content: 'inset-y-0 right-0 rounded-l-lg'
      }
    }
  ]
}