DrawerВыдвижная панель
Drawer — панель, которая выезжает с края экрана поверх страницы. В ней форма, подробности элемента или набор действий: задача, слишком тяжёлая для всплывающей подсказки, которую пользователь должен выполнить, не уходя со страницы. Она рисуется поверх страницы и, с маской, делает страницу позади недоступной.
Когда использовать
- Используйте его, чтобы создавать или править набор данных формой, показывать подробности строки или карточки, или для подзадачи, слишком тяжёлой для всплывающей панели и относящейся к задаче на странице.
- Диалог, который просит ответа посреди экрана, — это Modal. Короткое уведомление без ответа — Message. Панель рядом со страницей, которая не мешает ей работать, — Drawer с
mask: false. - Drawer внутри другого Drawer вложенный: родитель сдвигается, пока открыт потомок. Не делайте больше двух уровней.
Примеры
<script lang="ts">
import { Button, Drawer } from 'svelte-ant-design';
let open = $state(false);
let log = $state('');
// Every opening starts with an empty log, so that the last way to close is the only thing it says.
function show() {
log = '';
open = true;
}
</script>
<!-- bind:open: the close button, the mask and Escape close it by themselves; onclose hears each of them first. -->
<div class="stack">
<Button type="primary" onclick={show}>Open Drawer</Button>
<Drawer
bind:open
title="Basic Drawer"
onclose={() => (log = 'asked to close')}
onafteropenchange={(opened) => {
if (!opened) log = `${log}, then gone`;
}}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Drawer>
<output class="caption">{log}</output>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, Drawer, type DrawerPlacement } from 'svelte-ant-design';
const sides: DrawerPlacement[] = ['top', 'right', 'bottom', 'left'];
let open = $state(false);
let placement = $state<DrawerPlacement>('right');
function show(side: DrawerPlacement) {
placement = side;
open = true;
}
</script>
<!-- placement: the side the panel comes from. The sides are physical (left stays on the left in right-to-left); a top or a bottom panel is sized by its height. -->
<div class="stack">
<div class="row">
{#each sides as side (side)}
<Button onclick={() => show(side)}>{side}</Button>
{/each}
</div>
<Drawer bind:open {placement} title="Placement: {placement}">
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
<script lang="ts">
import { Button, Drawer, type DrawerSize } from 'svelte-ant-design';
const sizes: { label: string; size: DrawerSize }[] = [
{ label: 'default (378 px)', size: 'default' },
{ label: 'large (736 px)', size: 'large' },
{ label: '500', size: 500 },
{ label: "'50%'", size: '50%' },
{ label: "'20vw'", size: '20vw' }
];
let open = $state(false);
let chosen = $state<DrawerSize>('default');
let label = $state('');
function show(entry: (typeof sizes)[number]) {
chosen = entry.size;
label = entry.label;
open = true;
}
</script>
<!-- size: the width of a left or right panel and the height of a top or bottom one. A number is px, a string is any CSS length; the panel is never larger than the page. -->
<div class="stack">
<div class="row">
{#each sizes as entry (entry.label)}
<Button onclick={() => show(entry)}>{entry.label}</Button>
{/each}
</div>
<Drawer bind:open size={chosen} title="size: {label}">
<p>Some contents...</p>
<p>Some contents...</p>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
<script lang="ts">
import { Button, Drawer } from 'svelte-ant-design';
type Variant = 'extra' | 'end' | 'disabled' | 'none' | 'icon';
const variants: { id: Variant; label: string }[] = [
{ id: 'extra', label: 'extra' },
{ id: 'end', label: "closable.placement: 'end'" },
{ id: 'disabled', label: 'closable.disabled' },
{ id: 'none', label: 'closable: false' },
{ id: 'icon', label: 'closeIcon' }
];
let open = $state(false);
let variant = $state<Variant>('extra');
let log = $state('');
const closable = $derived(variant === 'end' ? { placement: 'end' as const } : variant === 'disabled' ? { disabled: true } : variant === 'none' ? false : true);
function show(id: Variant) {
variant = id;
log = '';
open = true;
}
</script>
{#snippet actions()}
<div class="row">
<Button
size="small"
onclick={() => {
log = 'Cancel pressed';
open = false;
}}>Cancel</Button
>
<Button
size="small"
type="primary"
onclick={() => {
log = 'OK pressed';
open = false;
}}>OK</Button
>
</div>
{/snippet}
{#snippet heart()}
<span aria-hidden="true">♥</span>
{/snippet}
<!-- The header has the close button (at the start by default), the title, and the extra actions at the end. -->
<div class="stack">
<div class="row">
{#each variants as entry (entry.id)}
<Button onclick={() => show(entry.id)}>{entry.label}</Button>
{/each}
</div>
<Drawer
bind:open
title="Drawer with a header"
extra={variant === 'extra' ? actions : undefined}
{closable}
closeIcon={variant === 'icon' ? heart : undefined}
>
<p>Some contents...</p>
<p>{variant === 'disabled' ? 'The close button is shown but does nothing; the mask and Escape still close it.' : 'Some contents...'}</p>
</Drawer>
<output class="caption">{log}</output>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, Drawer, Form, FormItem, Input, createForm } from 'svelte-ant-design';
interface Account {
name: string;
email: string;
}
const form = createForm<Account>();
let open = $state(false);
let result = $state('');
// The footer is outside the <Form> in the page, so it asks the form to validate and reads the values from it.
async function save() {
try {
const values = await form.validateFields();
result = `Saved: ${JSON.stringify(values)}`;
open = false;
} catch {
result = '';
}
}
</script>
{#snippet actions()}
<div class="actions">
<Button onclick={() => (open = false)}>Cancel</Button>
<Button type="primary" onclick={save}>Submit</Button>
</div>
{/snippet}
<!-- A form in a Drawer: the task stays in the context of the page. Validation keeps the Drawer open while a field is wrong. -->
<div class="stack">
<Button type="primary" onclick={() => (open = true)}>New account</Button>
<Drawer bind:open title="Create a new account" size="large" footer={actions}>
<Form {form} layout="vertical" initialValues={{ name: '', email: '' }}>
<FormItem name="name" label="Name" rules={[{ required: true, message: 'Please enter a name' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} placeholder="Please enter a name" {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="email" label="Email" rules={[{ required: true, message: 'Please enter an email' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} placeholder="Please enter an email" {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</Drawer>
{#if result}<output class="caption">{result}</output>{/if}
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
a control of the page
<script lang="ts">
import { Button, Drawer } from 'svelte-ant-design';
type Kind = 'dimmed' | 'fixed' | 'none' | 'keys';
const kinds: { id: Kind; label: string }[] = [
{ id: 'dimmed', label: 'Dimmed mask' },
{ id: 'fixed', label: 'mask.closable: false' },
{ id: 'none', label: 'No mask' },
{ id: 'keys', label: 'keyboard: false' }
];
let open = $state(false);
let kind = $state<Kind>('dimmed');
let clicks = $state(0);
const mask = $derived(kind === 'fixed' ? { closable: false } : kind === 'none' ? false : true);
function show(id: Kind) {
kind = id;
open = true;
}
</script>
<!-- A mask dims the page and makes the Drawer modal (the page is locked and out of reach). With no mask it is a panel beside the page: the page works, scrolls, and Escape closes it only while focus is inside. -->
<div class="stack">
<div class="row">
{#each kinds as entry (entry.id)}
<Button onclick={() => show(entry.id)}>{entry.label}</Button>
{/each}
</div>
<div class="field">
<span class="caption">a control of the page</span>
<Button onclick={() => clicks++}>Count a click</Button>
<output class="caption">clicks: {clicks}</output>
</div>
<Drawer bind:open title="Drawer: {kinds.find((entry) => entry.id === kind)?.label}" {mask} keyboard={kind !== 'keys'}>
<p>{kind === 'none' ? 'The page behind is not dimmed: press "Count a click" while this panel is open.' : 'Press the mask, or Escape.'}</p>
<p>{kind === 'fixed' ? 'The mask does not close it; the close button and Escape do.' : ''}</p>
<p>{kind === 'keys' ? 'Escape does nothing here; the mask and the close button close it.' : ''}</p>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
push of the parent
<script lang="ts">
import { Button, Drawer, type DrawerPlacement } from 'svelte-ant-design';
let open = $state(false);
let inner = $state(false);
let side = $state<DrawerPlacement>('right');
let pushed = $state<'default' | 'off' | 'near'>('default');
const push = $derived(pushed === 'off' ? false : pushed === 'near' ? { distance: 60 } : true);
const labels = { default: 'push: true (180 px)', off: 'push: false', near: 'push: { distance: 60 }' };
function show(next: DrawerPlacement) {
side = next;
inner = true;
}
</script>
<!-- A Drawer written inside another one is nested: while it is open the parent moves aside by its own push distance (only for a child of the same side). Only the lowest layer dims the page: the child keeps a clear mask that still takes the press outside it. -->
<div class="stack">
<div class="field">
<span class="caption">push of the parent</span>
<div class="row">
{#each Object.entries(labels) as [id, label] (id)}
<Button type={pushed === id ? 'primary' : 'default'} onclick={() => (pushed = id as typeof pushed)}>{label}</Button>
{/each}
</div>
</div>
<Button type="primary" onclick={() => (open = true)}>Open drawer</Button>
<Drawer bind:open title="Parent Drawer" size={520} {push}>
<div class="stack">
<div class="row">
<Button type="primary" onclick={() => show('right')}>Two-level drawer</Button>
<Button onclick={() => show('left')}>From the other side</Button>
</div>
<p>The child comes from the {side}. The parent moves only when it is of the same side.</p>
</div>
<Drawer bind:open={inner} title="Child Drawer" size={320} placement={side}>
<p>This is the second level.</p>
</Drawer>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
container={false}
Render in current DOM
a control of the page, outside the region
<script lang="ts">
import { Button, Drawer } from 'svelte-ant-design';
let open = $state(false);
let clicks = $state(0);
</script>
<!-- container={false} leaves the Drawer where it is written: it covers its nearest positioned parent only and is a panel of that region, not a modal. The rest of the page works. -->
<div class="stack">
<div class="field">
<span class="caption">container={'{false}'}</span>
<div class="region">
<Button type="primary" onclick={() => (open = true)}>Open in this region</Button>
<p>Render in current DOM</p>
<Drawer bind:open container={false} title="Basic Drawer" size={240}>
<p>Its layer covers the region only.</p>
</Drawer>
</div>
</div>
<div class="field">
<span class="caption">a control of the page, outside the region</span>
<Button onclick={() => clicks++}>Count a click</Button>
<output class="caption">clicks while the panel is open: {clicks}</output>
</div>
</div>
<style>
.stack {
display: grid;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.region {
position: relative;
box-sizing: border-box;
justify-self: stretch;
min-height: 260px;
padding: 16px;
border: 1px dashed var(--ads-color-border);
border-radius: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
default: the content stays after a close
destroyOnHidden
forceRender
<script lang="ts">
import { onMount } from 'svelte';
import { Button, Drawer } from 'svelte-ant-design';
let kept = $state(false);
let destroyed = $state(false);
let forced = $state(false);
let present = $state('');
// forceRender: the content is in the page, hidden, before the first opening.
onMount(() => {
present = document.querySelector('[data-forced-content]') ? 'yes' : 'no';
});
</script>
<!-- destroyOnHidden removes the content on every close (what was typed is gone); forceRender puts it in the page before the first opening. -->
<div class="stack">
<div class="field">
<span class="caption">default: the content stays after a close</span>
<Button onclick={() => (kept = true)}>Keep the content</Button>
</div>
<div class="field">
<span class="caption">destroyOnHidden</span>
<Button onclick={() => (destroyed = true)}>Remove the content</Button>
</div>
<div class="field">
<span class="caption">forceRender</span>
<Button onclick={() => (forced = true)}>Pre-rendered</Button>
<output class="caption">its content is in the page before the first opening: {present}</output>
</div>
<Drawer bind:open={kept} title="Keeps its content">
<input aria-label="Note" placeholder="Type, close, open again" />
</Drawer>
<Drawer bind:open={destroyed} destroyOnHidden title="Removes its content">
<input aria-label="Note" placeholder="Type, close, open again" />
</Drawer>
<Drawer bind:open={forced} forceRender title="Pre-rendered">
<p data-forced-content>This paragraph was in the page from the start.</p>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, Drawer } from 'svelte-ant-design';
let open = $state(false);
</script>
<!-- class and style go on the panel, rootClassName and rootStyle on the layer; classNames and styles reach each part (root, mask, wrapper, section, header, title, close, extra, body, footer, dragger). zIndex sets the level of the layer. -->
<div class="stack">
<Button onclick={() => (open = true)}>Open a styled Drawer</Button>
<Drawer
bind:open
title="Custom semantic styling"
footer="Footer"
class="styled-panel"
style="border-radius: 12px 0 0 12px"
rootClassName="styled-root"
rootStyle="--demo-accent: #722ed1"
zIndex={1010}
classNames={{ title: 'styled-title', body: 'styled-body' }}
styles={{
header: { background: 'var(--demo-accent)' },
mask: { 'background-color': 'rgba(114, 46, 209, 0.25)' },
footer: { 'text-align': 'center' }
}}
>
<p>A class on the panel, a style on the layer, a class and a style on three parts.</p>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
:global(.styled-title) {
color: #ffffff;
}
:global(.styled-body) {
font-style: italic;
}
</style>
<script lang="ts">
import type { Snippet } from 'svelte';
import { Button, Drawer } from 'svelte-ant-design';
let open = $state(false);
</script>
{#snippet frame(content: Snippet)}
<div class="frame">{@render content()}</div>
{/snippet}
<!-- drawerRender gets the content of the panel (header, body, footer) as a snippet and may wrap it. -->
<div class="stack">
<Button onclick={() => (open = true)}>Open Drawer</Button>
<Drawer bind:open title="Custom drawer content" footer="Footer" drawerRender={frame}>
<p>The whole content of the panel sits inside a framed box.</p>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.frame {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
border-inline-start: 4px solid var(--ads-color-primary);
}
</style>
<script lang="ts">
import { Button, Drawer } from 'svelte-ant-design';
type Kind = 'default' | 'free' | 'stay';
let open = $state(false);
let kind = $state<Kind>('default');
const focusable = $derived(kind === 'free' ? { trap: false } : kind === 'stay' ? { focusTriggerAfterClose: false } : undefined);
function show(next: Kind) {
kind = next;
open = true;
}
</script>
<!-- By default focus goes to the panel, Tab stays inside and focus goes back to the button that opened it. focusable turns the trap or the return off. -->
<div class="stack">
<div class="row">
<Button onclick={() => show('default')}>Default</Button>
<Button onclick={() => show('free')}>trap: false</Button>
<Button onclick={() => show('stay')}>focusTriggerAfterClose: false</Button>
</div>
<Drawer bind:open title="focusable: {kind}" {focusable}>
<p>Press Tab: {kind === 'free' ? 'it leaves the Drawer for the page.' : 'it goes around inside.'}</p>
<input aria-label="A field" placeholder="A field" />
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
<script lang="ts">
import { Button, Drawer, Select, type SelectValue } from 'svelte-ant-design';
let open = $state(false);
let city = $state<SelectValue | undefined>('lisbon');
</script>
<!-- The list of a Select opens above the Drawer and takes typing, Escape closes the list first and the Drawer on the second press. -->
<div class="stack">
<Button onclick={() => (open = true)}>A Drawer with a Select</Button>
<Drawer bind:open title="Where to?">
<div class="field">
<span class="caption">City</span>
<Select aria-label="City" showSearch options={['lisbon', 'porto', 'faro']} bind:value={city} style="width: 200px" />
</div>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, Drawer } from 'svelte-ant-design';
let open = $state(false);
const lines = Array.from({ length: 40 }, (_, index) => index + 1);
</script>
<!-- A long body scrolls on its own: the header and the footer stay in place, and the page behind does not scroll. -->
<div class="stack">
<Button onclick={() => (open = true)}>Open a long Drawer</Button>
<Drawer bind:open title="A long body" footer="The footer stays at the bottom">
{#each lines as line (line)}
<p>Line {line}</p>
{/each}
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
</style>
<script lang="ts">
import { Button, Drawer, type DrawerPlacement } from 'svelte-ant-design';
let open = $state(false);
let placement = $state<DrawerPlacement>('right');
let log = $state('');
function show(side: DrawerPlacement) {
placement = side;
log = '';
open = true;
}
</script>
<!-- resizable draws a strip on the inner edge. Drag it, or focus it and press the arrow keys (10 px, Shift 50 px), Home and End. minSize and maxSize (px) set the stops; the size stays after a close. -->
<div class="stack">
<div class="row">
<Button onclick={() => show('right')}>right</Button>
<Button onclick={() => show('bottom')}>bottom</Button>
</div>
<Drawer
bind:open
{placement}
title="Resizable Drawer"
size={320}
minSize={240}
maxSize={640}
resizable={{
onresizestart: () => (log = 'resizing...'),
onresize: (size) => (log = `size: ${size} px`),
onresizeend: () => (log = `${log} (done)`)
}}
>
<p>Drag the strip on the inner edge, or press the arrow keys when it has focus.</p>
<output class="caption">{log}</output>
</Drawer>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
API
Свойства Drawer
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| open | Показан ли Drawer. Работает bind:open: способ закрытия ставит false. | boolean | false |
| title | Заголовок; он задаёт имя панели. 0 показывается. Без заголовка задайте Drawer aria-label. | string | number | Snippet | none |
| extra | Действия в конце шапки. Шапка рисуется и при одном extra. | string | number | Snippet | none |
| children | Тело. Прокручивается само. | Snippet | none |
| footer | Подвал внизу панели. Без него подвала нет. | string | number | Snippet | none |
| placement | Сторона, с которой выезжает панель. Стороны физические. | 'top' | 'right' | 'bottom' | 'left' | 'right' |
| size | Ширина левой или правой панели, высота верхней или нижней. default — 378 px, large — 736 px; число — px; строка — CSS-длина. Заменяет устаревшие width и height. | 'default' | 'large' | number | string | 'default' |
| closable | Кнопка закрытия. false убирает её; disabled показывает, но она ничего не делает; placement логическое и зеркалится справа налево; aria-label — её имя (по умолчанию Close). | boolean | { closeIcon?: Snippet; disabled?: boolean; placement?: 'start' | 'end'; 'aria-label'?: string } | true |
| closeIcon | Заменяет крестик. Чтобы скрыть кнопку, используйте closable: false. | Snippet | a cross |
| mask | Затемнённая подложка. Страницу затемняет только нижний из открытых слоёв (Drawer и Modal); слой выше сохраняет прозрачную маску, которая принимает нажатие. closable (по умолчанию true): нажатие на неё просит закрыть. Без маски Drawer не модальный: страница не блокируется и доступна, Tab не запирается, aria-modal — false. | boolean | { enabled?: boolean; closable?: boolean } | true |
| keyboard | Escape закрывает Drawer. Модальный берёт Escape, когда он верхний слой; немодальный — только пока фокус внутри него. | boolean | true |
| push | Как этот Drawer сдвигается, когда открывается вложенный с той же стороны. false — не двигать; число — px, строка — CSS-длина. | boolean | { distance?: string | number } | { distance: 180 } |
| zIndex | z-index слоя (токен --ads-drawer-z-index): уровень Modal, ниже слоёв всплывающих панелей. | number | 1000 |
| container | Куда помещается слой: элемент, функция, селектор. false оставляет Drawer там, где он записан: он закрывает только ближайшего позиционированного родителя и не модальный. | HTMLElement | (() => HTMLElement) | string | false | document.body |
| destroyOnHidden | Убирать содержимое при каждом закрытии. | boolean | false |
| forceRender | Положить Drawer в страницу скрытым до первого открытия. | boolean | false |
| focusable | Фокус. trap: Tab и Shift+Tab остаются внутри (модальный Drawer). focusTriggerAfterClose: фокус возвращается туда, где был. При открытии фокус уходит на саму панель. | { trap?: boolean; focusTriggerAfterClose?: boolean } | { trap: true, focusTriggerAfterClose: true } |
| resizable | Полоса на внутреннем краю, которую двигают указатель или стрелки (separator с фокусом). Колбэки сообщают размер в px; нажатие клавиши — один жест. Размер сохраняется после закрытия и сбрасывается при смене size или placement. | boolean | { onresizestart?: () => void; onresize?: (size: number) => void; onresizeend?: () => void; 'aria-label'?: string } | false |
| maxSize | Наибольший размер в px при изменении. Не больше контейнера. | number | the container |
| minSize | Наименьший размер в px при изменении. Наше: в React его нет, и панель там сжималась до 7 px. | number | 100 |
| drawerRender | Получает содержимое панели (шапку, тело, подвал) как snippet и может обернуть его. | Snippet<[Snippet]> | none |
| class | Класс панели (section). | string | none |
| style | Стиль панели. | string | none |
| rootClassName | Класс слоя, в котором маска и панель. | string | none |
| rootStyle | Стиль слоя. | string | none |
| classNames | Классы частей: root, mask, wrapper, section, header, title, close, extra, body, footer, dragger. | { root?: string; mask?: string; wrapper?: string; section?: string; header?: string; title?: string; close?: string; extra?: string; body?: string; footer?: string; dragger?: string } | none |
| styles | Инлайн-стили тех же частей. | { root?: SemanticStyle; mask?: SemanticStyle; wrapper?: SemanticStyle; section?: SemanticStyle; header?: SemanticStyle; title?: SemanticStyle; close?: SemanticStyle; extra?: SemanticStyle; body?: SemanticStyle; footer?: SemanticStyle; dragger?: SemanticStyle } | none |
| onclose | Кнопка закрытия, маска или Escape просят закрыть. После вызова Drawer закрывается, если не вызван event.preventDefault(). | (event: MouseEvent | KeyboardEvent) => void | none |
| onafteropenchange | После окончания анимации появления (true) или ухода (false); сразу при prefers-reduced-motion. | (open: boolean) => void | none |
Отличия от Ant Design: кнопка закрытия, маска и Escape закрывают Drawer, если
onclose не вызывает event.preventDefault() (в React закрытие остаётся вам); фокус уходит на панель, у которой роль и имя; Drawer без маски или рисуемый на месте не модальный; у resizable есть клавиатура и минимум (minSize); size заменяет устаревшие width и height. Пока нет: loading и mask.blur. Не берём: сервис, открывающий Drawer из кода (он есть только в Angular).Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-drawer-z-index | Уровень слоя. | 1000 |
| --ads-drawer-mask-bg | Цвет маски. | rgba(0, 0, 0, 0.45) |
| --ads-drawer-bg | Фон панели. | #ffffff |
| --ads-drawer-size | Размер default. | 378px |
| --ads-drawer-size-large | Размер large. | 736px |
| --ads-drawer-shadow-right | Тень правой панели (падает влево). | -6px 0 16px 0 rgba(0, 0, 0, 0.08), -3px 0 6px -4px rgba(0, 0, 0, 0.12), -9px 0 28px 8px rgba(0, 0, 0, 0.05) |
| --ads-drawer-shadow-left | Тень левой панели. | 6px 0 16px 0 rgba(0, 0, 0, 0.08), 3px 0 6px -4px rgba(0, 0, 0, 0.12), 9px 0 28px 8px rgba(0, 0, 0, 0.05) |
| --ads-drawer-shadow-top | Тень верхней панели. | 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 9px 28px 8px rgba(0, 0, 0, 0.05) |
| --ads-drawer-shadow-bottom | Тень нижней панели. | 0 -6px 16px 0 rgba(0, 0, 0, 0.08), 0 -3px 6px -4px rgba(0, 0, 0, 0.12), 0 -9px 28px 8px rgba(0, 0, 0, 0.05) |
| --ads-drawer-header-padding | Внутренний отступ шапки. | 16px 24px |
| --ads-drawer-header-border | Линия под шапкой. | rgba(5, 5, 5, 0.06) |
| --ads-drawer-title-color | Цвет заголовка. | rgba(0, 0, 0, 0.88) |
| --ads-drawer-title-font-size | Размер шрифта заголовка. | 16px |
| --ads-drawer-title-line-height | Высота строки заголовка. | 24px |
| --ads-drawer-title-font-weight | Насыщенность заголовка. | 600 |
| --ads-drawer-close-size | Размер кнопки закрытия. | 24px |
| --ads-drawer-close-gap | Промежуток между кнопкой закрытия и заголовком. | 8px |
| --ads-drawer-close-color | Цвет кнопки закрытия. | rgba(0, 0, 0, 0.45) |
| --ads-drawer-close-color-hover | Цвет кнопки закрытия при наведении. | rgba(0, 0, 0, 0.88) |
| --ads-drawer-close-bg-hover | Заливка кнопки закрытия при наведении. | rgba(0, 0, 0, 0.06) |
| --ads-drawer-body-color | Цвет текста. | rgba(0, 0, 0, 0.88) |
| --ads-drawer-body-padding | Внутренний отступ тела. | 24px |
| --ads-drawer-footer-padding | Внутренний отступ подвала. | 8px 16px |
| --ads-drawer-footer-border | Линия над подвалом. | rgba(5, 5, 5, 0.06) |
| --ads-drawer-motion-duration | Длительность выезда и появления маски. | 0.3s |
| --ads-drawer-motion-ease | Кривая выезда и появления маски. | ease |
| --ads-drawer-dragger-size | Ширина видимой линии полосы изменения размера. | 4px |
| --ads-drawer-dragger-hit | Ширина области, принимающей нажатие; половина — за пределами панели. | 8px |
| --ads-drawer-dragger-hover-bg | Цвет полосы при наведении, фокусе и перетаскивании. | var(--ads-color-primary) |
Доступность
- Панель —
role="dialog"и получает имя от заголовка (aria-labelledby). Без заголовка задайтеaria-label(в разработке предупреждение напомнит). У модального Draweraria-modal="true"; у Drawer без маски или рисуемого на месте —aria-modal="false". - Фокус уходит на саму панель (не на кнопку закрытия, поэтому сначала произносится заголовок). В модальном Drawer Tab и Shift+Tab остаются внутри: Tab на последнем элементе ведёт к первому. После закрытия фокус возвращается на кнопку, которая его открыла.
- Страница позади модального Drawer недоступна клавиатуре, указателю и вспомогательным технологиям (
inert;aria-hidden, где браузер не знаетinert). Drawer без маски или рисуемый на месте оставляет страницу доступной и не запирает Tab. - Escape закрывает верхний Drawer; если внутри открыт Select, Escape сначала закрывает список. Drawer без маски принимает Escape, только пока фокус внутри него. Клавиша, завершающая IME-композицию, ничего не закрывает.
keyboard: falseотключает Escape. - Модальный Drawer не даёт странице прокручиваться и прыгать вбок, когда исчезает её полоса прокрутки, до конца анимации ухода. Не обработано: iOS Safari до 16 прокручивает заблокированную страницу под пальцем.
- Полоса изменения размера —
separatorс фокусом (шаблон «разделитель окон») со значением, границами и именем (Resize); её двигают стрелки, Home и End. У полосы в React нет роли и клавиатуры, и панель сжимается до нескольких пикселей; здесьminSizeпо умолчанию 100 px. - Контраст: заголовок и текст около 15:1 на панели, значок закрытия 3:1 (контраст не-текста). Полоса получает основной цвет при наведении и фокусе. В режиме принудительных цветов у панели есть рамка на внутреннем краю, кнопка закрытия и полоса остаются видимыми. Выезд отключается при
prefers-reduced-motion. - Известное ограничение: Drawer, открытый изнутри всплывающей панели (например, из списка Select), находится вне неё, поэтому нажатие в нём закрывает панель и уносит Drawer. Открывайте его со страницы или выделите ему место через
container. - Не проверено: настоящий скринридер, кроме Orca (NVDA, JAWS, VoiceOver, телефон), настоящее сенсорное устройство и настоящий Safari. Проверено: Orca с Firefox (документ начинается внутри модального Drawer, Tab ходит по кругу внутри, полоса читается как разделитель со значением), а также клавиши, фокус и страница позади в Chromium, Firefox и WebKit, перетаскивание пальцем в эмулируемом Chromium и самые старые поддерживаемые версии браузеров.