DropdownВыпадающее меню
Dropdown — это кнопка (или любой элемент) с меню в панели рядом, которая открывается наведением, кликом или правым щелчком. Меню — это Menu библиотеки, заданное объектом или разметкой, поэтому пункты, подменю, группы, выбор и клавиатура работают так же.
Когда использовать
- Используйте выпадающее меню, когда действий несколько, а показать все негде: кнопка в строке таблицы, меню пользователя в шапке, действия объекта по правому щелчку.
- Чтобы выбрать значение в форме, используйте
Select; для списка, который всегда на странице (например, навигации), —Menu. - Делайте триггером кнопку или ссылку: до них доходят клавиатура и скринридер. Меню по наведению открывается и по
Enter,Space, стрелкам и касанию.
Примеры
menu as an object: hover the button, or press Enter, Space or an arrow on it. Archive is switched off with disabled: true Nothing chosen yet
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
let chosen = $state('');
</script>
<div class="stack">
<div class="field">
<span class="caption">menu as an object: hover the button, or press Enter, Space or an arrow on it. Archive is switched off with disabled: true</span>
<Dropdown
menu={{
items: [
{ key: 'rename', label: 'Rename' },
{ key: 'duplicate', label: 'Duplicate' },
// disabled: true switches an item off: it is grey and cannot be chosen.
{ key: 'archive', label: 'Archive', disabled: true }
],
onclick: ({ key }) => (chosen = key)
}}
>
<Button>Hover me</Button>
</Dropdown>
<span role="status">{chosen ? `Chosen: ${chosen}` : 'Nothing chosen yet'}</span>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
icon, extra, disabled, a divider, a group and danger: the items of the Menu Nothing chosen yet
<script lang="ts">
import { Button, Dropdown, type MenuItems } from 'svelte-ant-design';
const items: MenuItems = [
{ key: 'open', label: 'Open', icon: '▤', extra: '⌘O' },
{ key: 'save', label: 'Save', icon: '▥', extra: '⌘S' },
{ key: 'print', label: 'Print (disabled)', icon: '▦', disabled: true },
{ type: 'divider' },
{
type: 'group',
label: 'Danger zone',
children: [
{ key: 'move', label: 'Move to trash' },
{ key: 'delete', label: 'Delete forever', danger: true }
]
}
];
let chosen = $state('');
</script>
<div class="stack">
<div class="field">
<span class="caption">icon, extra, disabled, a divider, a group and danger: the items of the Menu</span>
<Dropdown menu={{ items, onclick: ({ key }) => (chosen = key) }} trigger="click">
<Button>File</Button>
</Dropdown>
<span role="status">{chosen ? `Chosen: ${chosen}` : 'Nothing chosen yet'}</span>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
trigger="hover" (the default)
trigger="click": a second click closes it
trigger={['hover', 'click']}: either one opens it
mouseEnterDelay={0.5} and mouseLeaveDelay={0.4}, in seconds
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
const menu = { items: [{ key: 'one', label: 'First action' }, { key: 'two', label: 'Second action' }] };
</script>
<div class="stack">
<div class="field">
<span class="caption">trigger="hover" (the default)</span>
<Dropdown {menu}>
<Button>Hover</Button>
</Dropdown>
</div>
<div class="field">
<span class="caption">trigger="click": a second click closes it</span>
<Dropdown {menu} trigger="click">
<Button>Click</Button>
</Dropdown>
</div>
<div class="field">
<span class="caption">trigger={['hover', 'click']}: either one opens it</span>
<Dropdown {menu} trigger={['hover', 'click']}>
<Button>Hover or click</Button>
</Dropdown>
</div>
<div class="field">
<span class="caption">mouseEnterDelay={0.5} and mouseLeaveDelay={0.4}, in seconds</span>
<Dropdown {menu} mouseEnterDelay={0.5} mouseLeaveDelay={0.4}>
<Button>Slow</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
placement: the side and the alignment; at the edge of the window the panel flips or moves in
autoAdjustOverflow={false}: the panel stays where placement says, also off the screen
<script lang="ts">
import { Button, Dropdown, type DropdownPlacement } from 'svelte-ant-design';
const rows: DropdownPlacement[][] = [
['topLeft', 'top', 'topRight'],
['bottomLeft', 'bottom', 'bottomRight'],
['leftTop', 'left', 'leftBottom'],
['rightTop', 'right', 'rightBottom']
];
const menu = { items: [{ key: 'a', label: 'A longer first entry' }, { key: 'b', label: 'Second' }] };
</script>
<div class="stack">
<div class="field">
<span class="caption">placement: the side and the alignment; at the edge of the window the panel flips or moves in</span>
{#each rows as row (row[0])}
<div class="row">
{#each row as placement (placement)}
<Dropdown {menu} {placement} trigger="click">
<Button class="at">{placement}</Button>
</Dropdown>
{/each}
</div>
{/each}
</div>
<div class="field">
<span class="caption">autoAdjustOverflow={false}: the panel stays where placement says, also off the screen</span>
<Dropdown {menu} placement="top" autoAdjustOverflow={false} trigger="click">
<Button>Stays above</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.row :global(.at) {
min-width: 108px;
}
</style>
arrow
arrow={{ pointAtCenter: true }}: at the middle of the trigger
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
const menu = { items: [{ key: 'a', label: 'First' }, { key: 'b', label: 'Second' }] };
</script>
<div class="stack">
<div class="field">
<span class="caption">arrow</span>
<Dropdown {menu} arrow trigger="click">
<Button>With an arrow</Button>
</Dropdown>
</div>
<div class="field">
<span class="caption">arrow={{ pointAtCenter: true }}: at the middle of the trigger</span>
<Dropdown {menu} arrow={{ pointAtCenter: true }} placement="bottomRight" trigger="click">
<Button>A wider button, pointed at its center</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
trigger="contextMenu": right click in the area, or focus it and press Shift+F10
Right click here
Nothing chosen yet<script lang="ts">
import { Dropdown } from 'svelte-ant-design';
let chosen = $state('');
</script>
<div class="stack">
<div class="field">
<span class="caption">trigger="contextMenu": right click in the area, or focus it and press Shift+F10</span>
<Dropdown
trigger="contextMenu"
menu={{
'aria-label': 'Photo actions',
items: [
{ key: 'copy', label: 'Copy' },
{ key: 'share', label: 'Share' },
{ key: 'remove', label: 'Remove', danger: true }
],
onclick: ({ key }) => (chosen = key)
}}
>
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div class="area" tabindex="0">Right click here</div>
</Dropdown>
<span role="status">{chosen ? `Chosen: ${chosen}` : 'Nothing chosen yet'}</span>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.area {
display: grid;
place-items: center;
width: 100%;
height: 160px;
border: 1px dashed var(--ads-color-border);
border-radius: 8px;
color: var(--ads-color-text-secondary);
}
</style>
menu.onclick gets the item; onopenchange says whether a choice or the trigger changed the panel
Open the menu to see the calls
<script lang="ts">
import { Button, Dropdown, type DropdownOpenChangeInfo } from 'svelte-ant-design';
let log = $state<string[]>([]);
const write = (line: string) => (log = [...log.slice(-3), line]);
const changed = (open: boolean, { source }: DropdownOpenChangeInfo) =>
write(`onopenchange(${open}, { source: '${source}' })`);
</script>
<div class="stack">
<div class="field">
<span class="caption">menu.onclick gets the item; onopenchange says whether a choice or the trigger changed the panel</span>
<Dropdown
trigger="click"
onopenchange={changed}
menu={{
items: [{ key: 'yes', label: 'Yes' }, { key: 'no', label: 'No' }],
onclick: ({ key }) => write(`menu.onclick: ${key}`)
}}
>
<Button>Answer</Button>
</Dropdown>
<div class="log" role="status">
{#each log as line, index (index)}
<div>{line}</div>
{:else}
<div>Open the menu to see the calls</div>
{/each}
</div>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.log {
font-family: ui-monospace, monospace;
font-size: 12px;
}
</style>
menu.selectable: one choice, shown in the menu; the panel closes selected: en
selectable and multiple: the panel stays open while you choose selected: en, zh
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
const languages = [
{ key: 'en', label: 'English' },
{ key: 'ru', label: 'Русский' },
{ key: 'zh', label: '中文' }
];
let language = $state(['en']);
let shown = $state(['en', 'zh']);
</script>
<div class="stack">
<div class="field">
<span class="caption">menu.selectable: one choice, shown in the menu; the panel closes</span>
<Dropdown
trigger="click"
menu={{ items: languages, selectable: true, selectedKeys: language, onselect: ({ selectedKeys }) => (language = selectedKeys) }}
>
<Button>Language</Button>
</Dropdown>
<span role="status">selected: {language.join(', ')}</span>
</div>
<div class="field">
<span class="caption">selectable and multiple: the panel stays open while you choose</span>
<Dropdown
trigger="click"
menu={{
items: languages,
selectable: true,
multiple: true,
selectedKeys: shown,
onselect: ({ selectedKeys }) => (shown = selectedKeys),
ondeselect: ({ selectedKeys }) => (shown = selectedKeys)
}}
>
<Button>Show columns</Button>
</Dropdown>
<span role="status">selected: {shown.join(', ') || '(none)'}</span>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
bind:open with trigger={[]}: another button opens and closes it; a choice and Escape close it too open: false
Keep it open after a choice: with bind:open, set it back when source is 'menu' chosen 0 times
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
let controlled = $state(false);
let staying = $state(false);
let picked = $state(0);
</script>
<div class="stack">
<div class="field">
<span class="caption">bind:open with trigger={[]}: another button opens and closes it; a choice and Escape close it too</span>
<div class="row">
<Dropdown bind:open={controlled} trigger={[]} menu={{ items: [{ key: 'a', label: 'Action' }] }}>
<Button>Controlled</Button>
</Dropdown>
<Button type="primary" onclick={() => (controlled = !controlled)}>{controlled ? 'Close' : 'Open'} it</Button>
</div>
<span role="status">open: {controlled}</span>
</div>
<div class="field">
<span class="caption">Keep it open after a choice: with bind:open, set it back when source is 'menu'</span>
<Dropdown
trigger="click"
bind:open={staying}
onopenchange={(next, { source }) => {
if (source === 'menu') staying = true;
}}
menu={{ items: [{ key: 'more', label: 'Add one more' }], onclick: () => picked++ }}
>
<Button>Stays open</Button>
</Dropdown>
<span role="status">chosen {picked} {picked === 1 ? 'time' : 'times'}</span>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
popupRender: content around the menu; Tab walks from the menu into it Nothing yet
popupRender without a menu
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
let note = $state('');
</script>
{#snippet withFooter({ menu }: { menu: import('svelte').Snippet })}
{@render menu()}
<div class="footer">
<Button type="primary" size="small" onclick={() => (note = 'Saved the view')}>Save the view</Button>
</div>
{/snippet}
{#snippet card()}
<div class="card">Content of your own, without a menu</div>
{/snippet}
<div class="stack">
<div class="field">
<span class="caption">popupRender: content around the menu; Tab walks from the menu into it</span>
<Dropdown
trigger="click"
popupRender={withFooter}
menu={{ items: [{ key: 'list', label: 'List' }, { key: 'grid', label: 'Grid' }], onclick: ({ key }) => (note = `Chose ${key}`) }}
>
<Button>View</Button>
</Dropdown>
<span role="status">{note || 'Nothing yet'}</span>
</div>
<div class="field">
<span class="caption">popupRender without a menu</span>
<Dropdown trigger="click" popupRender={card}>
<Button>About</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.footer {
display: flex;
justify-content: flex-end;
padding: 8px;
border-top: 1px solid var(--ads-color-border-secondary);
}
.card {
padding: 12px 16px;
}
</style>
disabled: nothing opens; the button itself is yours to disable
A menu with no items opens nothing
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
const menu = { items: [{ key: 'a', label: 'Action' }] };
let off = $state(true);
</script>
<div class="stack">
<div class="field">
<span class="caption">disabled: nothing opens; the button itself is yours to disable</span>
<div class="row">
<Dropdown {menu} disabled={off} trigger="click">
<Button disabled={off}>Actions</Button>
</Dropdown>
<label class="check"><input type="checkbox" bind:checked={off} /> disabled</label>
</div>
</div>
<div class="field">
<span class="caption">A menu with no items opens nothing</span>
<Dropdown menu={{ items: [] }} trigger="click">
<Button>Empty</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.check {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>
container: the panel is moved into this box instead of the page body
destroyOnHidden: the panel is removed from the page after closing
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
const menu = { items: [{ key: 'a', label: 'First' }, { key: 'b', label: 'Second' }] };
let box = $state<HTMLElement>();
</script>
<div class="stack">
<div class="field">
<span class="caption">container: the panel is moved into this box instead of the page body</span>
<div class="box" bind:this={box}>
<Dropdown {menu} trigger="click" container={() => box!}>
<Button>In the box</Button>
</Dropdown>
</div>
</div>
<div class="field">
<span class="caption">destroyOnHidden: the panel is removed from the page after closing</span>
<Dropdown {menu} trigger="click" destroyOnHidden>
<Button>Removed on close</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.box {
position: relative;
padding: 12px;
border: 1px dashed var(--ads-color-border);
border-radius: 8px;
}
</style>
classNames and styles: root, menu, item, itemTitle, itemContent, itemIcon
<script lang="ts">
import { Button, Dropdown, type MenuItems } from 'svelte-ant-design';
const items: MenuItems = [
{ key: 'star', label: 'Star', icon: '★' },
{ key: 'sub', label: 'Share', children: [{ key: 'mail', label: 'Mail' }] },
{ type: 'group', label: 'Group', children: [{ key: 'in', label: 'Inside' }] }
];
</script>
<div class="stack">
<div class="field">
<span class="caption">classNames and styles: root, menu, item, itemTitle, itemContent, itemIcon</span>
<Dropdown
trigger="click"
menu={{ items }}
classNames={{ root: 'demo-dropdown', menu: 'demo-menu' }}
styles={{
menu: { 'min-width': '200px' },
item: { 'font-weight': 500 },
itemTitle: { 'text-transform': 'uppercase' },
itemContent: { 'letter-spacing': '0.02em' },
itemIcon: { color: 'var(--ads-color-primary-text)' }
}}
>
<Button>Styled</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
A button with a menu beside it: two buttons side by side, the second one opens the menu Nothing yet
<script lang="ts">
import { Button, Dropdown } from 'svelte-ant-design';
let last = $state('');
</script>
<div class="stack">
<div class="field">
<span class="caption">A button with a menu beside it: two buttons side by side, the second one opens the menu</span>
<div class="split-button">
<Button onclick={() => (last = 'Published')}>Publish</Button>
<Dropdown
placement="bottomRight"
trigger="click"
menu={{
items: [{ key: 'draft', label: 'Save a draft' }, { key: 'later', label: 'Publish later' }],
onclick: ({ key }) => (last = key === 'draft' ? 'Saved a draft' : 'Planned')
}}
>
<Button aria-label="Other ways to publish">▾</Button>
</Dropdown>
</div>
<span role="status">{last || 'Nothing yet'}</span>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.split-button {
display: inline-flex;
}
.split-button :global(.ads-btn:first-of-type) {
border-start-end-radius: 0;
border-end-end-radius: 0;
}
.split-button :global(.ads-dropdown-trigger > .ads-btn) {
margin-inline-start: -1px;
border-start-start-radius: 0;
border-end-start-radius: 0;
}
</style>
menu as a snippet: write the Menu yourself; it behaves as the menu of the panel Nothing chosen yet
<script lang="ts">
import { Button, Dropdown, Menu, MenuDivider, MenuItem, MenuSubMenu } from 'svelte-ant-design';
let chosen = $state('');
let beta = $state(false);
</script>
<div class="stack">
<div class="field">
<span class="caption">menu as a snippet: write the Menu yourself; it behaves as the menu of the panel</span>
<div class="row">
<Dropdown>
<Button>Account</Button>
{#snippet menu()}
<Menu onclick={({ key }) => (chosen = key)}>
<MenuItem key="profile">Profile</MenuItem>
<MenuSubMenu key="theme" label="Theme">
<MenuItem key="light">Light</MenuItem>
<MenuItem key="dark">Dark</MenuItem>
</MenuSubMenu>
{#if beta}
<MenuItem key="labs">Labs</MenuItem>
{/if}
<MenuDivider />
<MenuItem key="logout" danger>Log out</MenuItem>
</Menu>
{/snippet}
</Dropdown>
<label class="check"><input type="checkbox" bind:checked={beta} /> Labs</label>
</div>
<span role="status">{chosen ? `Chosen: ${chosen}` : 'Nothing chosen yet'}</span>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.check {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>
href: an item that is a link; a middle click or Ctrl+click opens it in a new tab
<script lang="ts">
import { Button, Dropdown, type MenuItems } from 'svelte-ant-design';
const items: MenuItems = [
{ key: 'examples', label: 'Examples', href: '#examples' },
{ key: 'api', label: 'API table', href: '#api' },
{ key: 'repo', label: 'Source (new tab)', href: 'https://github.com/prostreyd/ant-design-svelte', target: '_blank', rel: 'noreferrer' }
];
</script>
<div class="stack">
<div class="field">
<span class="caption">href: an item that is a link; a middle click or Ctrl+click opens it in a new tab</span>
<Dropdown menu={{ items }}>
<Button type="link">Go to…</Button>
</Dropdown>
</div>
</div>
<style>
.stack {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 16px;
width: 100%;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
width: 100%;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
API
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| menu | Меню панели: объект с пропсами Menu (без mode, inlineCollapsed, inlineIndent, overflowedIndicator, overflowLabel и tooltip, которые не действуют в вертикальном меню) или snippet, в котором написан Menu. Ведут себя одинаково: вертикальное, не выбирается без selectable, выбор закрывает панель. | DropdownMenuProps | Snippet | — |
| children | Триггер: один элемент. Атрибуты кнопки меню получает то, что в нём принимает фокус. | Snippet | — |
| open | Показана ли панель; bind:open следует за пользователем. Обычное значение — начальное. | boolean | false |
| onopenchange | Изменение, сделанное пользователем: выбор (source: 'menu') либо триггер, Escape, Tab и нажатие снаружи ('trigger'). | (open: boolean, info: { source: 'trigger' | 'menu' }) => void | — |
| trigger | Чем открывается указателем: hover, click, contextMenu или несколько. Пустой массив — только open, и нажатие снаружи не закрывает панель (Escape и выбор закрывают). | 'click' | 'hover' | 'contextMenu' | Array | ['hover'] |
| placement | Сторона и выравнивание; в письме справа налево зеркалится. | 'top' | 'topLeft' | 'topRight' | 'bottom' | 'bottomLeft' | 'bottomRight' | 'left' | 'leftTop' | 'leftBottom' | 'right' | 'rightTop' | 'rightBottom' | 'bottomLeft' |
| arrow | Стрелка к триггеру; pointAtCenter направляет её в центр. | boolean | { pointAtCenter: boolean } | false |
| disabled | Ничего не открывает, открытая панель закрывается. | boolean | false |
| autoAdjustOverflow | У края окна панель переворачивается, меняет выравнивание или сдвигается внутрь. | boolean | true |
| mouseEnterDelay | Наведение: секунды до открытия панели. | number | 0.15 |
| mouseLeaveDelay | Наведение: секунды до закрытия после ухода указателя. | number | 0.1 |
| container | Куда переносится панель; по умолчанию в body. | HTMLElement | ((anchor) => HTMLElement) | — |
| destroyOnHidden | Удаляет панель со страницы после закрытия. Выбор меню, заданного объектом, сохраняется. | boolean | false |
| popupRender | Рисует содержимое панели: menu выводит меню. | Snippet<[{ menu: Snippet }]> | — |
| classNames | Дополнительные классы root, menu, item, itemTitle (заголовки подменю и групп), itemContent и itemIcon. | object | — |
| styles | Встроенные стили тех же частей. | object | — |
Отличия от Ant Design: клавиатура открывает меню при любом триггере, и фокус переходит в него;
menu — объект или snippet с Menu; у пункта есть href; триггер — один элемент и получает ARIA-атрибуты; нет Dropdown.Button (там он устарел) и autoFocus; bind:open и колбэки строчными буквами; classNames и styles — объекты.Аргументы
| Свойство | Описание | Тип |
|---|---|---|
| source | Второй аргумент onopenchange: 'menu' или 'trigger'. | DropdownOpenSource |
| menu | Аргумент popupRender: snippet, который рисует меню, заданное любым способом. | Snippet |
Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-dropdown-z-index | Слой панели (и Select). | 1050 |
| --ads-dropdown-radius | Радиус углов панели. | 8px |
| --ads-dropdown-padding | Отступ вокруг пунктов. | 4px |
| --ads-dropdown-item-height | Высота пункта. | 32px |
| --ads-dropdown-item-padding-inline | Горизонтальные отступы пункта. | 12px |
| --ads-dropdown-item-radius | Радиус углов пункта. | 4px |
| --ads-dropdown-item-hover-bg | Фон пункта при наведении. В тёмной теме страницы rgba(255, 255, 255, 0.08). | rgba(0, 0, 0, 0.04) |
| --ads-dropdown-item-icon-size | Размер иконки. | 12px |
| --ads-dropdown-item-icon-gap | Расстояние между иконкой и подписью. | 8px |
| --ads-dropdown-item-extra-gap | Отступ перед extra. | 16px |
| --ads-dropdown-item-extra-font-size | Размер шрифта extra. | 12px |
| --ads-dropdown-group-item-indent | Где начинается текст пункта группы. | 20px |
Доступность
- Элемент триггера, принимающий фокус, получает
aria-haspopup="menu",aria-expandedи, пока открыто,aria-controls; меню называется по нему (aria-labelменю важнее). Демо Ant Design не ставят ни один из них. Enter,SpaceиArrowDownоткрывают на первом пункте,ArrowUp— на последнем, при любомtrigger(на ссылкеEnterпереходит по ней). Открытие кликом тоже переносит фокус в меню, наведением — нет.Escapeвозвращает на триггер,Tabзакрывает и идёт дальше по странице; сначала проходятся элементы изpopupRender.- Выбранный пункт возвращает фокус на триггер до вызова
menu.onclick, поэтому открытый там диалог вернёт фокус на триггер. Роли, отключённые пункты, выбранное состояние и пункты-ссылки — как вMenu. - Контекстное меню открывается по
Shift+F10и клавише меню на сфокусированной области; дайте менюaria-label.Shift+F10проверено в Chromium и, со скринридером, в Firefox; в Safari — нет. iPad и iPhone не посылают события при долгом нажатии, поэтому там меню не открывается. - В режимах принудительных цветов у панели есть рамка, у выбранного пункта — полоса системного цвета;
tokens-accessible.cssи тёмная тема проходят WCAG AA, как у Menu. Приprefers-reduced-motionничего не движется. - Проверено настоящим скринридером (Orca с Firefox): он читает кнопку как свёрнутую и открывающую меню, меню с именем кнопки, подменю как свёрнутые или развёрнутые, контекстное меню и выбранный пункт, а после
Escapeили выбора снова кнопку. Не проверено: NVDA, JAWS, VoiceOver, телефон и настоящее сенсорное устройство (эмулированное касание проверено в трёх движках браузеров).