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 | 确定按钮的文字。未设置时使用默认值;空字符串则保持为空。 | string | number | Snippet | OK |
| cancelText | 取消按钮的文字。 | string | number | Snippet | Cancel |
| okType | 确定按钮的 type。 | ButtonType | 'primary' |
| okButtonProps | 确定按钮的属性。它的 onclick 先于 onok 执行。 | ComponentProps<typeof Button> | — |
| cancelButtonProps | 取消按钮的属性。它的 onclick 先于 oncancel 执行。 | ComponentProps<typeof Button> | — |
| confirmLoading | 确定按钮处于加载状态。 | boolean | false |
| onok | 点击了确定按钮。只有设置了 closeOnOk 才会关闭。 | (event: MouseEvent) => unknown | — |
| closeOnOk | 在 onok 之后关闭对话框,并等待它返回的 Promise:成功关闭,失败保持打开;event.preventDefault() 也会保持打开。Ant Design 的普通 Modal 没有此选项。 | boolean | false |
| oncancel | 关闭按钮、取消、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 有取消和确定,其余只有确定。此选项可改变这一点。 | boolean | true for confirm |
| footer | 与 Modal 相同。 | string | number | Snippet<[{ origin, ok, cancel }]> | null | the buttons |
| okText | 确定按钮的文字。 | string | number | Snippet | OK |
| cancelText | 取消按钮的文字。 | string | number | Snippet | Cancel |
| okType | 确定按钮的 type。 | ButtonType | 'primary' |
| okButtonProps | 确定按钮的属性。 | ComponentProps<typeof Button> | — |
| cancelButtonProps | 取消按钮的属性。 | ComponentProps<typeof Button> | — |
| onok | 点击了确定。Promise 会使按钮保持加载:成功关闭,失败保持打开。静态对话框总会在 onok 之后关闭(closeOnOk 已开启)。 | (event: MouseEvent) => unknown | — |
| oncancel | 取消、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 | 焦点默认移到确定按钮。 | { 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) | 打开带有取消、确定和警告图标的对话框。 | ModalHandle | — |
| modal.info(options) · success · warning · error | 打开只有确定按钮、带对应类型图标的对话框。 | ModalHandle | — |
| modal.destroyAll() | 关闭所有静态对话框(不会关闭写在模板中的 Modal)。 | void | — |
| handle.destroy() | 关闭对话框并播放离开动画;句柄以 false 完成。关闭后调用无效果。 | void | — |
| handle.update(patch) | 原地更改选项。对象会被合并;函数会收到之前的选项并返回变更。关闭后调用无效果。 | void | — |
| handle.then · await handle | 在对话框开始关闭时完成:确定为 true,其余为 false。await 调用会一直等到关闭。 | 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命名:两者都没有时,开发期间会输出警告。静态对话框是role="alertdialog",并由其文字描述。 - 焦点会移到 Tab 能到达的第一个元素(关闭按钮)并保持在内部:在最后一个元素上按 Tab 会回到第一个,在第一个上按 Shift+Tab 会到最后一个。对话框关闭时,焦点回到打开它的按钮。静态对话框会把焦点放在确定按钮上。
- 对话框后面的页面对键盘、指针和辅助技术不可操作(
inert;在不支持inert的浏览器中使用aria-hidden)。Message 的浮层保持可访问,因此由确定按钮打开的消息会被朗读。 - Escape 会关闭最上层的对话框。其中的 Select 展开时,Escape 先关闭下拉列表。结束 IME 输入的按键不会关闭任何东西。
keyboard: false会关闭 Escape。 - 页面不会滚动,滚动条消失时也不会向侧面跳动。未处理:iOS Safari 16 之前的版本会在手指下滚动被锁定的页面。
- 对比度:标题和文字在卡片上约为 15:1,叉号为 3:1,静态对话框的图标保持 3:1(深色主题中,以及浅色主题配合
tokens-accessible.css时,后者会加深绿色和琥珀色)。在强制颜色模式下,卡片和关闭按钮带有边框,遮罩保持半透明。prefers-reduced-motion下动画关闭,静态对话框的句柄在没有动画时同样能得到结果。 - 已知限制:从弹出层内部(例如 Select 的列表)打开的对话框位于该弹出层之外,因此在其中点击会关闭弹出层并连带关闭对话框。请从外部的按钮打开,或为它设置
container。对话框打开时页面上已有的消息保持可访问,但之后加入同一浮层的消息可能不会被所有读屏软件朗读。 - 未检查:真实的读屏软件(NVDA、JAWS、VoiceOver、手机)、真实的触屏设备和真实的 Safari。已检查:Chromium、Firefox 和 WebKit 中的按键、焦点与背景页面,以及三种引擎受支持的最低版本;Orca 与 Firefox 在 GitHub 上运行。