ModalМодальное окно
Modal — это диалог поверх страницы, с которым пользователь должен разобраться, прежде чем идти дальше: форма, подтверждение, сообщение. Он рисуется выше всего на странице; пока он открыт, страница не прокручивается, недоступна клавиатуре и вспомогательным технологиям, фокус остаётся внутри окна и возвращается обратно, а Escape его закрывает. Его можно записать в разметке (<Modal bind:open>) или вызвать готовый диалог из кода (modal.confirm(…)).
Когда использовать
- Используйте, когда пользователь должен ответить или закончить действие, прежде чем идти дальше, не покидая страницу: форма, подтверждение необратимого действия, короткая информация.
- Короткое уведомление без ответа — это Message. Панель у края страницы — Drawer, а небольшой пузырь рядом с элементом — поповер (оба запланированы). Modal прерывает пользователя: используйте его бережно.
- Для подтверждения короче вызвать диалог из кода:
if (await modal.confirm({ … })) ….
Примеры
<script lang="ts">
import { Button, Modal } 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, Cancel, Escape and the mask close it by themselves. OK does not: it is for you to close the Modal once you have checked or saved, so onok closes it here (the other examples set closeOnOk). -->
<div class="stack">
<Button type="primary" onclick={show}>Open Modal</Button>
<Modal
bind:open
title="Basic Modal"
onok={() => {
log = 'OK pressed';
open = false;
}}
oncancel={() => (log = 'cancelled')}
onafterclose={() => (log = `${log}, then closed`)}
>
<p>Some contents...</p>
<p>Some contents...</p>
</Modal>
<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>
confirmLoading: the app closes it
closeOnOk: onok returns a Promise (the first try is rejected)
<script lang="ts">
import { Button, Modal } from 'svelte-ant-design';
// 1. The app closes the Modal: it sets `confirmLoading` while it saves, and `open = false` when it is done.
let manualOpen = $state(false);
let saving = $state(false);
function save() {
saving = true;
setTimeout(() => {
saving = false;
manualOpen = false;
}, 1500);
}
// 2. `closeOnOk`: the Modal waits for the Promise that onok returns, and closes when it is resolved. A reject keeps it open.
let waitOpen = $state(false);
let attempts = $state(0);
const submit = () =>
new Promise<void>((resolve, reject) =>
setTimeout(() => {
attempts += 1;
if (attempts % 2 === 1) reject(new Error('The first try fails'));
else resolve();
}, 1200)
);
</script>
<div class="stack">
<div class="field">
<span class="caption">confirmLoading: the app closes it</span>
<Button type="primary" onclick={() => (manualOpen = true)}>Open (confirmLoading)</Button>
<Modal bind:open={manualOpen} title="Save the file" confirmLoading={saving} onok={save}>
<p>The OK button is loading for 1.5 seconds, then the Modal closes.</p>
</Modal>
</div>
<div class="field">
<span class="caption">closeOnOk: onok returns a Promise (the first try is rejected)</span>
<Button onclick={() => (waitOpen = true)}>Open (closeOnOk)</Button>
<Modal bind:open={waitOpen} title="Send the form" closeOnOk onok={submit}>
<p>Press OK. The first try fails and the Modal stays open; the second succeeds and closes it.</p>
</Modal>
</div>
</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, Modal } from 'svelte-ant-design';
let open = $state(false);
</script>
<!-- okText and cancelText: a text, a number or a snippet. okType is the type of the OK button; okButtonProps and cancelButtonProps are the props of Button itself. -->
<div class="stack">
<Button onclick={() => (open = true)}>Delete…</Button>
<Modal
bind:open
title="Delete the project?"
okText="Delete"
cancelText="Keep it"
okType="primary"
okButtonProps={{ danger: true }}
cancelButtonProps={{ type: 'text' }}
onok={() => (open = false)}
>
<p>The OK button is a danger button, and Cancel is a text button.</p>
</Modal>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
</style>
mask: { closable: false }
mask: false
keyboard: false
<script lang="ts">
import { Button, Modal } from 'svelte-ant-design';
let sticky = $state(false);
let bare = $state(false);
let silent = $state(false);
</script>
<div class="stack">
<div class="field">
<span class="caption">mask: {'{ closable: false }'}</span>
<Button onclick={() => (sticky = true)}>The mask does not close it</Button>
<Modal closeOnOk bind:open={sticky} title="Sticky" mask={{ closable: false }}><p>A press outside does nothing. The close button, Cancel, OK and Escape still close it.</p></Modal>
</div>
<div class="field">
<span class="caption">mask: false</span>
<Button onclick={() => (bare = true)}>No mask</Button>
<Modal closeOnOk bind:open={bare} title="No mask" mask={false}><p>No dim layer is drawn, but the page behind is still out of reach, as in Ant Design.</p></Modal>
</div>
<div class="field">
<span class="caption">keyboard: false</span>
<Button onclick={() => (silent = true)}>Escape does not close it</Button>
<Modal closeOnOk bind:open={silent} title="No Escape" keyboard={false}><p>Escape does nothing here; the close button, Cancel, OK and the mask still close it.</p></Modal>
</div>
</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, Modal } from 'svelte-ant-design';
let centered = $state(false);
let wide = $state(false);
let high = $state(false);
let zoom = $state(false);
</script>
<div class="stack">
<div class="row">
<Button onclick={() => (centered = true)}>Centered</Button>
<Button onclick={() => (wide = true)}>Width 720</Button>
<Button onclick={() => (high = true)}>Style and zIndex</Button>
<Button onclick={() => (zoom = true)}>zoomFromClick</Button>
</div>
<Modal closeOnOk bind:open={centered} title="Centered" centered><p>In the middle of the window.</p></Modal>
<Modal closeOnOk bind:open={wide} title="Width 720" width={720}><p>A number is px; a string such as <code>'60%'</code> is used as it is. On a narrow window it is never wider than the window.</p></Modal>
<Modal closeOnOk bind:open={high} title="Style and zIndex" style="top: 20px" zIndex={1100}><p>20px from the top, above the default layer.</p></Modal>
<Modal closeOnOk bind:open={zoom} title="From the click" zoomFromClick><p>It zooms in and out from the place of the click, as in Ant Design. By default it zooms around its own center.</p></Modal>
</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, Modal } from 'svelte-ant-design';
let plain = $state(false);
let rich = $state(false);
let noClose = $state(false);
let own = $state(false);
</script>
{#snippet richTitle()}<span>Title with <em>emphasis</em></span>{/snippet}
{#snippet crossIcon()}<span aria-hidden="true">✕</span>{/snippet}
<div class="stack">
<div class="row">
<Button onclick={() => (plain = true)}>No title</Button>
<Button onclick={() => (rich = true)}>Snippet title</Button>
<Button onclick={() => (noClose = true)}>closable: false</Button>
<Button onclick={() => (own = true)}>closeIcon and a name</Button>
</div>
<Modal closeOnOk bind:open={plain} aria-label="A dialog with no title"><p>No title, no header: give it a name with <code>aria-label</code>.</p></Modal>
<Modal closeOnOk bind:open={rich} title={richTitle}><p>The title is a string, a number or a snippet.</p></Modal>
<Modal closeOnOk bind:open={noClose} title="No close button" closable={false}><p>Only Cancel, OK, Escape and the mask close it.</p></Modal>
<Modal closeOnOk bind:open={own} title="Own icon" closeIcon={crossIcon} closable={{ 'aria-label': 'Close the dialog' }}><p>The cross is a snippet, and the button has its own name.</p></Modal>
</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, Modal } from 'svelte-ant-design';
let open = $state(false);
let loose = $state(false);
</script>
<div class="stack">
<div class="row">
<Button onclick={() => (open = true)}>Long content</Button>
<Button onclick={() => (loose = true)}>scrollLock: false</Button>
</div>
<Modal closeOnOk bind:open title="Long content">
{#each Array.from({ length: 40 }, (_, index) => index) as index (index)}
<p>Paragraph {index + 1}: the window scrolls, the page behind does not, and it does not jump sideways when its scrollbar goes away.</p>
{/each}
</Modal>
<Modal closeOnOk bind:open={loose} title="The page may scroll" scrollLock={false}>
<p>The page behind keeps scrolling while this is open (the Modal does not hold the scroll).</p>
</Modal>
</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, Modal } from 'svelte-ant-design';
let first = $state(false);
let second = $state(false);
</script>
<!-- Escape and Tab go to the Modal on top; the first one is out of reach until the second is closed. -->
<div class="stack">
<Button onclick={() => (first = true)}>Open the first</Button>
<Modal closeOnOk bind:open={first} title="First">
<p>The second Modal opens above this one.</p>
<Button onclick={() => (second = true)}>Open the second</Button>
</Modal>
<Modal closeOnOk bind:open={second} title="Second"><p>Escape closes this one first, then the first.</p></Modal>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
</style>
default: the content is kept
destroyOnHidden
forceRender, onafteropenchange and onafterclose
<script lang="ts">
import { Button, Modal } from 'svelte-ant-design';
let kept = $state(false);
let fresh = $state(false);
let present = $state(false);
let log = $state<string[]>([]);
</script>
<div class="stack">
<div class="field">
<span class="caption">default: the content is kept</span>
<Button onclick={() => (kept = true)}>Keeps what you typed</Button>
<Modal closeOnOk bind:open={kept} title="Kept"><input aria-label="Draft" placeholder="Type, close, open again" /></Modal>
</div>
<div class="field">
<span class="caption">destroyOnHidden</span>
<Button onclick={() => (fresh = true)}>Starts empty each time</Button>
<Modal closeOnOk bind:open={fresh} title="Fresh" destroyOnHidden><input aria-label="Draft" placeholder="Type, close, open again" /></Modal>
</div>
<div class="field">
<span class="caption">forceRender, onafteropenchange and onafterclose</span>
<Button onclick={() => (present = true)}>Present from the start</Button>
<Modal
bind:open={present}
title="Present"
closeOnOk
forceRender
onafteropenchange={(opened) => (log = [...log, opened ? 'opened' : 'closed'])}
onafterclose={() => (log = [...log, 'afterclose'])}
>
<p>It was in the page, hidden, before this first opening.</p>
</Modal>
<output class="caption">{log.join(' → ')}</output>
</div>
</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>
the Modal goes into this box
<script lang="ts">
import { Button, Modal } from 'svelte-ant-design';
let selected = $state(false);
let inPlace = $state(false);
let box = $state<HTMLElement | null>(null);
let where = $state('');
// `data-demo` is an attribute of the dialog box (the rest of the attributes go there): it lets the example find it.
function report(name: string) {
const dialog = document.querySelector(`[data-demo="${name}"]`);
where = `${name}: the dialog is ${box?.contains(dialog) ? 'inside the box' : 'outside the box'}`;
}
</script>
<!-- container: an element, a function that returns one, a selector, or false to leave it where it is written. The layer still covers the window. -->
<div class="stack">
<div class="row">
<Button onclick={() => (selected = true)}>container="#modal-container"</Button>
<Button onclick={() => (inPlace = true)}>container={'{false}'}</Button>
</div>
<div id="modal-container" class="box" bind:this={box}>the Modal goes into this box</div>
<output class="caption">{where}</output>
<Modal closeOnOk bind:open={selected} title="Into the box" container="#modal-container" data-demo="selector" onafteropenchange={(opened) => opened && report('selector')}>
<p>Its layer is a child of the box in the page.</p>
</Modal>
<Modal closeOnOk bind:open={inPlace} title="In place" container={false} data-demo="false" onafteropenchange={(opened) => opened && report('false')}>
<p>Its layer stays where the component is written.</p>
</Modal>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 12px;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.box {
padding: 12px;
border: 1px dashed var(--ads-color-border);
border-radius: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, Modal } from 'svelte-ant-design';
let open = $state(false);
</script>
<!-- class and style go on the dialog box; wrapClassName on the scroll area; classNames and styles address the parts. -->
<div class="stack">
<Button onclick={() => (open = true)}>Styled</Button>
<Modal
bind:open
title="Styled"
closeOnOk
class="fancy-box"
style="width: 480px"
wrapClassName="fancy-wrap"
classNames={{ header: 'fancy-header' }}
styles={{ title: { 'letter-spacing': '0.04em' }, body: { color: 'var(--ads-color-primary)' } }}
>
<p>The parts: root, mask, wrapper, dialog, content, close, header, title, body and footer.</p>
</Modal>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
/* Classes of this example: they are passed to the Modal, which is drawn in the body, so the rules are global. */
:global(.fancy-box) {
outline: 2px dashed var(--ads-color-primary);
outline-offset: 4px;
}
:global(.fancy-wrap) {
background: rgba(22, 119, 255, 0.06);
}
:global(.fancy-header) {
padding-bottom: 8px;
border-bottom: 1px solid var(--ads-color-border);
}
</style>
focusable: trap false
focusable: focusTriggerAfterClose false
focusable: autoFocusButton ok
<script lang="ts">
import { Button, Modal } from 'svelte-ant-design';
let free = $state(false);
let lost = $state(false);
let primary = $state(false);
</script>
<div class="stack">
<div class="field">
<span class="caption">focusable: trap false</span>
<Button onclick={() => (free = true)}>Tab may leave the dialog</Button>
<Modal closeOnOk bind:open={free} title="No trap" focusable={{ trap: false }}><p>Tab is left to the browser. The page behind is still out of reach.</p></Modal>
</div>
<div class="field">
<span class="caption">focusable: focusTriggerAfterClose false</span>
<Button onclick={() => (lost = true)}>Focus does not come back</Button>
<Modal closeOnOk bind:open={lost} title="No return" focusable={{ focusTriggerAfterClose: false }}><p>After it closes, focus stays where it is.</p></Modal>
</div>
<div class="field">
<span class="caption">focusable: autoFocusButton ok</span>
<Button onclick={() => (primary = true)}>Focus on OK</Button>
<Modal bind:open={primary} title="Focus on OK" focusable={{ autoFocusButton: 'ok' }} onok={() => (primary = false)}><p>The OK button has focus when it opens.</p></Modal>
</div>
</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 type { Snippet } from 'svelte';
import { Button, Modal } from 'svelte-ant-design';
let open = $state(false);
</script>
<!-- modalRender gets the card as a snippet and may wrap it, for example in a draggable box. -->
{#snippet framed(card: Snippet)}
<div class="frame">
<span class="tag">wrapped by modalRender</span>
{@render card()}
</div>
{/snippet}
<div class="stack">
<Button onclick={() => (open = true)}>modalRender</Button>
<Modal closeOnOk bind:open title="Wrapped" modalRender={framed}><p>The card is inside a box of your own.</p></Modal>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.frame {
padding: 8px;
border: 1px dashed var(--ads-color-primary);
border-radius: 12px;
}
.tag {
display: block;
margin-bottom: 4px;
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, Modal, 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 Modal, Escape closes the list first and the Modal on the second press, and the list follows the field when the Modal scrolls. -->
<div class="stack">
<Button onclick={() => (open = true)}>A form with a Select</Button>
<Modal bind:open title="Where to?" onok={() => (open = false)}>
<div class="field">
<span class="caption">City</span>
<Select aria-label="City" options={['lisbon', 'porto', 'faro']} bind:value={city} style="width: 200px" />
</div>
</Modal>
</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, modal } from 'svelte-ant-design';
</script>
<!-- A call opens a dialog from code: no markup, no state. confirm has Cancel and OK; info, success, warning and error have OK only (okCancel changes that). -->
<div class="stack">
<div class="row">
<Button onclick={() => modal.confirm({ title: 'Delete the file?', content: 'This cannot be undone.' })}>confirm</Button>
<Button onclick={() => modal.info({ title: 'Heads up', content: 'The service restarts at midnight.' })}>info</Button>
<Button onclick={() => modal.success({ title: 'Saved', content: 'Your changes are stored.' })}>success</Button>
<Button onclick={() => modal.warning({ title: 'Careful', content: 'The disk is almost full.' })}>warning</Button>
<Button onclick={() => modal.error({ title: 'Failed', content: 'The upload did not finish.', okText: 'Got it' })}>error</Button>
<Button onclick={() => modal.info({ title: 'Update available', content: 'Install it now?', okCancel: true, okText: 'Install', cancelText: 'Later' })}>info + okCancel</Button>
<Button onclick={() => modal.info({ title: 'From the click', content: 'This dialog zooms from the place of the click.', zoomFromClick: true })}>info + zoomFromClick</Button>
</div>
</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, modal } from 'svelte-ant-design';
let answer = $state('');
// The call returns a handle that can be awaited: true for OK, false for Cancel, Escape and destroy.
// The trap: `await modal.confirm(...)` waits until the dialog is closed, and so does returning the handle from an async function.
async function ask() {
const confirmed = await modal.confirm({ title: 'Publish the post?', content: 'It will be visible to everyone.' });
answer = confirmed ? 'You pressed OK' : 'You cancelled';
}
</script>
<div class="stack">
<Button onclick={ask}>Ask</Button>
<output class="caption">{answer}</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, modal } from 'svelte-ant-design';
let tries = $state(0);
// onok may return a Promise: the OK button waits (it is loading), a resolve closes the dialog, a reject keeps it open.
function save() {
modal.confirm({
title: 'Save the changes?',
content: 'The first try always fails.',
onok: () =>
new Promise<void>((resolve, reject) =>
setTimeout(() => {
tries += 1;
return tries % 2 === 1 ? reject(new Error('failed')) : resolve();
}, 1200)
)
});
}
// oncancel may return a Promise too: the Cancel button waits, and the dialog closes when it is resolved.
function leave() {
modal.confirm({ title: 'Discard the draft?', content: 'Cancel takes a moment.', oncancel: () => new Promise((resolve) => setTimeout(resolve, 1000)) });
}
</script>
<div class="stack">
<div class="row">
<Button onclick={save}>OK waits for a Promise</Button>
<Button onclick={leave}>Cancel waits for a Promise</Button>
</div>
</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, modal } from 'svelte-ant-design';
// The handle changes the dialog in place (an object is merged, a function gets the previous options) and closes it.
function countdown() {
let seconds = 5;
const handle = modal.success({ title: 'Done', content: `This closes in ${seconds} seconds.`, okText: 'Close now' });
const timer = setInterval(() => {
seconds -= 1;
if (seconds <= 0) {
clearInterval(timer);
handle.destroy();
} else {
handle.update({ content: `This closes in ${seconds} seconds.` });
}
}, 1000);
void handle.then(() => clearInterval(timer));
}
function several() {
modal.info({ title: 'One' });
modal.warning({ title: 'Two' });
modal.error({ title: 'Three' });
}
</script>
<div class="stack">
<div class="row">
<Button onclick={countdown}>update and destroy</Button>
<Button onclick={several}>Open three</Button>
<Button onclick={() => modal.destroyAll()}>destroyAll</Button>
</div>
</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, ModalHost, modal } from 'svelte-ant-design';
// With no <ModalHost /> the library makes its own layer. A host draws the dialogs where it stands, so they see the context of that place.
let hosted = $state(false);
</script>
{#snippet where()}<span>This dialog was drawn {hosted ? 'by the host' : 'by the layer of the library'}.</span>{/snippet}
<div class="stack">
<div class="field">
<label class="row"><input type="checkbox" bind:checked={hosted} /> <span class="caption">Put a ModalHost in this example</span></label>
<Button onclick={() => modal.info({ title: 'Where am I?', content: where })}>Open a dialog</Button>
</div>
{#if hosted}<ModalHost />{/if}
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
API
Свойства Modal
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| open | Показано ли окно. Работает bind:open: способ закрытия ставит false. | boolean | false |
| title | Заголовок. Нет заголовка — нет шапки. 0 показывается. | string | number | Snippet | null | — |
| children | Тело окна. | Snippet | — |
| footer | null убирает подвал; текст становится подвалом; snippet получает origin (обе кнопки), ok и cancel. | string | number | Snippet<[{ origin, ok, cancel }]> | null | Cancel and OK |
| okText | Текст кнопки OK. Если свойство не задано, берётся значение по умолчанию; пустая строка остаётся пустой. | string | number | Snippet | OK |
| cancelText | Текст кнопки Cancel. | string | number | Snippet | Cancel |
| okType | type кнопки OK. | ButtonType | 'primary' |
| okButtonProps | Свойства кнопки OK. Её onclick вызывается раньше onok. | ComponentProps<typeof Button> | — |
| cancelButtonProps | Свойства кнопки Cancel. Её onclick вызывается раньше oncancel. | ComponentProps<typeof Button> | — |
| confirmLoading | Кнопка OK в состоянии загрузки. | boolean | false |
| onok | Нажата кнопка OK. Окно закрывается только с closeOnOk. | (event: MouseEvent) => unknown | — |
| closeOnOk | Окно закрывается после onok, дожидаясь Promise, который он вернул: resolve закрывает, reject оставляет открытым; event.preventDefault() оставляет открытым. В обычном Modal Ant Design такой опции нет. | boolean | false |
| oncancel | Кнопка закрытия, Cancel, Escape или маска запросили закрытие. Затем окно закрывается, если обработчик не вызвал event.preventDefault(). | (event: MouseEvent | KeyboardEvent) => void | — |
| closable | Показывает кнопку закрытия. Объект задаёт её иконку, отключает её или называет (по умолчанию «Close»). | boolean | { closeIcon?, disabled?, 'aria-label'? } | true |
| closeIcon | Заменяет крестик. Скрыть кнопку можно через closable: false. | Snippet | a cross |
| mask | enabled: false (или false) не рисует маску: окно остаётся модальным. closable: false не даёт нажатию на маску закрыть окно. | boolean | { enabled?, closable? } | true |
| keyboard | Escape закрывает окно. | boolean | true |
| centered | Центрирует окно. | boolean | false |
| width | Число — это px. Не шире окна. | string | number | 520 |
| zIndex | z-index слоя (--ads-modal-z-index), ниже слоёв всплывающих окон. | number | 1000 |
| container | Элемент, в который переносится слой, функция, возвращающая его, селектор или false, чтобы оставить там, где записано. | HTMLElement | (() => HTMLElement) | string | false | document.body |
| destroyOnHidden | Содержимое удаляется при каждом закрытии. | boolean | false |
| forceRender | Окно находится на странице, скрытым, до первого открытия. | boolean | false |
| focusable | trap: Tab остаётся внутри. focusTriggerAfterClose: фокус возвращается туда, где был. autoFocusButton: 'ok', 'cancel' или null (само окно); по умолчанию первый элемент, до которого доходит Tab. | { trap?, focusTriggerAfterClose?, autoFocusButton? } | { trap: true, focusTriggerAfterClose: true } |
| scrollLock | Страница не прокручивается, пока окно открыто. | boolean | true |
| zoomFromClick | Окно увеличивается и уменьшается из места последнего клика, как в Ant Design, а не вокруг своего центра. Открытие с клавиатуры или позже клика по-прежнему идёт из центра. | boolean | false |
| modalRender | Получает карточку как snippet и может её обернуть. | Snippet<[Snippet]> | — |
| class | Дополнительные классы блока окна. | string | — |
| style | Инлайн-стиль блока окна. Ширина сохраняется. | string | — |
| wrapClassName | Дополнительные классы области прокрутки (та же часть, что classNames.wrapper). | string | — |
| classNames | Дополнительные классы для частей окна. | { root?, mask?, wrapper?, dialog?, content?, close?, header?, title?, body?, footer? } | — |
| styles | Инлайн-стили для частей: объект CSS-свойств (kebab-case или пользовательские свойства). | { root?, mask?, wrapper?, dialog?, content?, close?, header?, title?, body?, footer? } | — |
| onafteropenchange | Закончилась анимация появления или ухода. | (open: boolean) => void | — |
| onafterclose | Анимация ухода закончилась, окно скрыто. | () => void | — |
Параметры статического диалога
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| title | Заголовок. | string | number | Snippet | — |
| content | Текст под заголовком. | string | number | Snippet | — |
| icon | Snippet или текст заменяет иконку вида; false убирает её. | Snippet | string | false | the icon of the kind |
| okCancel | У confirm есть Cancel и OK, у остальных только OK. Это меняет умолчание. | boolean | true for confirm |
| footer | Как в Modal. | string | number | Snippet<[{ origin, ok, cancel }]> | null | the buttons |
| okText | Текст кнопки OK. | string | number | Snippet | OK |
| cancelText | Текст кнопки Cancel. | string | number | Snippet | Cancel |
| okType | type кнопки OK. | ButtonType | 'primary' |
| okButtonProps | Свойства кнопки OK. | ComponentProps<typeof Button> | — |
| cancelButtonProps | Свойства кнопки Cancel. | ComponentProps<typeof Button> | — |
| onok | Нажата OK. Promise держит кнопку в загрузке: resolve закрывает диалог, reject оставляет открытым. Статический диалог всегда закрывается после onok (closeOnOk включён). | (event: MouseEvent) => unknown | — |
| oncancel | Cancel, Escape или другой способ отмены. Promise ждётся так же; event.preventDefault() оставляет диалог открытым. | (event: MouseEvent | KeyboardEvent) => unknown | — |
| closable | Показывает кнопку закрытия (по умолчанию её нет). | boolean | { closeIcon?, disabled?, 'aria-label'? } | false |
| closeIcon | Заменяет крестик. | Snippet | a cross |
| mask | Нажатие на маску не закрывает статический диалог, если не задано closable: true. | boolean | { enabled?, closable? } | { closable: false } |
| keyboard | Escape закрывает (это отмена). | boolean | true |
| centered | Центрирует окно. | boolean | false |
| width | Число — это px. | string | number | 416 |
| zIndex | z-index слоя. | number | 1000 |
| container | Куда переносится слой. | HTMLElement | (() => HTMLElement) | string | false | document.body |
| focusable | Фокус по умолчанию уходит на кнопку OK. | { trap?, focusTriggerAfterClose?, autoFocusButton? } | { autoFocusButton: 'ok' } |
| scrollLock | Страница не прокручивается, пока диалог открыт. | boolean | true |
| zoomFromClick | Окно увеличивается и уменьшается из места последнего клика, а не вокруг своего центра. | boolean | false |
| class | Дополнительные классы блока окна. | string | — |
| style | Инлайн-стиль блока окна. | string | — |
| wrapClassName | Дополнительные классы области прокрутки. | string | — |
| classNames | Дополнительные классы для частей, а также для трёх частей статического диалога: confirmBody, icon и description. | { …the parts of the Modal, confirmBody?, icon?, description? } | — |
| styles | Инлайн-стили для тех же частей. | { …the parts of the Modal, confirmBody?, icon?, description? } | — |
| onafteropenchange | Закончилась анимация появления или ухода. | (open: boolean) => void | — |
| onafterclose | Диалог закрыт и скрыт. | () => void | — |
Методы, ручка и ModalHost
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| modal.confirm(options) | Открывает диалог с Cancel и OK и иконкой предупреждения. | ModalHandle | — |
| modal.info(options) · success · warning · error | Открывают диалог только с OK и иконкой своего вида. | ModalHandle | — |
| modal.destroyAll() | Закрывает все статические диалоги (но не Modal, записанный в разметке). | void | — |
| handle.destroy() | Закрывает диалог с анимацией ухода; ручка завершается значением false. После закрытия ничего не делает. | void | — |
| handle.update(patch) | Меняет параметры на месте. Объект объединяется с ними; функция получает предыдущие параметры и возвращает изменения. После закрытия ничего не делает. | void | — |
| handle.then · await handle | Завершается, когда диалог начинает закрываться: true для OK, false для всего остального. Ожидание вызова ждёт закрытия. | PromiseLike<boolean> | — |
| <ModalHost /> | Необязателен. Рисует статические диалоги там, где стоит, поэтому они видят контекст этого места. Активен один хост; без него библиотека создаёт свой слой в body. | component | — |
Отличия от Ant Design: способы отмены закрывают окно, если
oncancel не вызывает event.preventDefault() (в React закрытие остаётся за вами); closeOnOk — новое; maskClosable — это mask.closable, destroyOnClose — destroyOnHidden, а getContainer — container; modal.* и <ModalHost> заменяют Modal.useModal и contextHolder; статические диалоги — alert dialog, и их можно ждать через await. Пока не взято: mask.blur, width по брейкпоинтам, loading (запланировано на v1.1) и перетаскиваемое окно.Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-modal-z-index | Слой окна, ниже слоёв всплывающих окон (у поповера 1030). | 1000 |
| --ads-modal-width | Ширина окна, если не задан width. | 520px |
| --ads-modal-top | Расстояние окна от верха, если оно не по центру. | 100px |
| --ads-modal-mask-bg | Цвет маски. | rgba(0, 0, 0, 0.45) |
| --ads-modal-content-bg | Фон карточки. В тёмной теме #1f1f1f. | #ffffff |
| --ads-modal-radius | Радиус углов карточки. | 8px |
| --ads-modal-shadow | Тень карточки. | 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-modal-padding | Внутренние отступы карточки. | 20px 24px |
| --ads-modal-title-color | Цвет заголовка. В тёмной теме 85% белого. | rgba(0, 0, 0, 0.88) |
| --ads-modal-title-font-size | Размер шрифта заголовка. | 16px |
| --ads-modal-title-line-height | Высота строки заголовка. | 24px |
| --ads-modal-title-font-weight | Насыщенность заголовка. | 600 |
| --ads-modal-header-gap | Промежуток между заголовком и телом (и между заголовком и текстом статического диалога). | 8px |
| --ads-modal-body-color | Цвет текста тела. В тёмной теме 85% белого. | rgba(0, 0, 0, 0.88) |
| --ads-modal-footer-margin-top | Промежуток между телом и подвалом. | 12px |
| --ads-modal-footer-gap | Промежуток между кнопками подвала. | 8px |
| --ads-modal-close-size | Размер кнопки закрытия (цель не меньше 24px, WCAG 2.5.8). | 32px |
| --ads-modal-close-inset | Расстояние кнопки закрытия от угла. | 12px |
| --ads-modal-close-color | Цвет крестика (3:1 на карточке). | rgba(0, 0, 0, 0.45) |
| --ads-modal-close-color-hover | Цвет крестика при наведении. | rgba(0, 0, 0, 0.88) |
| --ads-modal-close-bg-hover | Фон кнопки закрытия при наведении. | rgba(0, 0, 0, 0.06) |
| --ads-modal-motion-ease | Кривая анимации появления. | cubic-bezier(0.08, 0.82, 0.17, 1) |
| --ads-modal-confirm-width | Ширина статического диалога. | 416px |
| --ads-modal-confirm-icon-size | Размер иконки статического диалога. | 22px |
| --ads-modal-confirm-icon-gap | Промежуток между иконкой и текстом статического диалога. | 12px |
| --ads-modal-confirm-icon-info | Цвет иконки info. | #1677ff |
| --ads-modal-confirm-icon-success | Цвет иконки success. tokens-accessible.css затемняет его до #389e0d (3:1 на белой карточке). | #52c41a |
| --ads-modal-confirm-icon-warning | Цвет иконки warning и confirm. tokens-accessible.css затемняет его до #c27c00. | #faad14 |
| --ads-modal-confirm-icon-error | Цвет иконки error. | #ff4d4f |
Доступность
- Окно имеет
role="dialog"иaria-modal="true", его имя — заголовок (aria-labelledby). Без заголовка дайте имя черезaria-label: Modal без того и другого пишет предупреждение при разработке. Статический диалог —role="alertdialog", он описан своим текстом. - Фокус уходит на первый элемент, до которого доходит Tab (кнопка закрытия), и остаётся внутри: Tab на последнем элементе переходит к первому, Shift+Tab на первом — к последнему. Когда окно закрывается, фокус возвращается на кнопку, открывшую его. Статический диалог ставит фокус на кнопку OK.
- Страница позади окна недоступна клавиатуре, указателю и вспомогательным технологиям (
inert;aria-hidden, где браузер не знаетinert). Слой Message остаётся доступным, поэтому сообщение, открытое кнопкой OK, зачитывается. - Escape закрывает верхнее окно. Если внутри открыт Select, сначала закрывается его список. Клавиша, завершающая ввод через IME, ничего не закрывает.
keyboard: falseотключает Escape. - Страница не прокручивается и не прыгает в сторону, когда пропадает её полоса прокрутки. Не обработано: iOS Safari до 16 прокручивает заблокированную страницу под пальцем.
- Контраст: заголовок и текст около 15:1 на карточке, крестик 3:1, а иконки статических диалогов удерживаются на 3:1 (в тёмной теме и в светлой с
tokens-accessible.css, который затемняет зелёный и янтарный). В режимах forced colors у карточки и кнопки закрытия есть рамка, а маска остаётся полупрозрачной. Анимация отключается приprefers-reduced-motion, а ручка статического диалога получает ответ и без неё. - Известное ограничение: окно, открытое изнутри всплывающей панели (например, из списка Select), находится вне этой панели, поэтому нажатие в нём закрывает панель вместе с окном. Открывайте его кнопкой вне панели или задайте
container. Сообщение, которое уже есть на странице, когда открывается окно, остаётся доступным, но сообщение, добавленное позже в тот же слой, может быть прочитано не всеми скринридерами. - Не проверено: настоящий скринридер (NVDA, JAWS, VoiceOver, телефон), настоящее сенсорное устройство и настоящий Safari. Проверено: клавиши, фокус и страница позади в Chromium, Firefox и WebKit, а также на самых старых поддерживаемых версиях трёх движков; Orca с Firefox запускается на GitHub.