Modal

A Modal is a dialog over the page that the user has to deal with before going on: a form, a confirmation, a piece of information. It is drawn above everything on the page, and while it is open the page does not scroll, the page behind it is out of reach of the keyboard and assistive technology, focus stays inside it and comes back, and Escape closes it. Write it into the markup (<Modal bind:open>) or call a ready-made dialog from code (modal.confirm(…)).

Import
import { Modal, modal, ModalHost } from 'svelte-ant-design';
Links
src/lib/Modal Report an issue Component README

When to use

  • Use it when the user has to answer or finish something before going on, without leaving the page: a form, a confirmation of a destructive action, a short piece of information.
  • A short notice that needs no answer is a Message. A panel at the edge of the page is a Drawer, and a small bubble next to an element a popover (both are planned). A Modal interrupts the user: use it sparingly.
  • For a confirmation, a dialog from code is the shorter way: if (await modal.confirm({ … })) ….

Examples

Basic

A Modal written into the markup with bind:open. The close button, Cancel, Escape and a press on the mask close it by themselves; OK does not: it is for you to close the Modal once you have checked or saved, so here onok closes it and says so. The other examples set closeOnOk, so that OK closes them. oncancel is called first.

confirmLoading: the app closes it
closeOnOk: onok returns a Promise (the first try is rejected)

Asynchronous close

confirmLoading puts the OK button into its loading state while the app saves; the app then sets open = false. With closeOnOk the Modal does it itself: it waits for the Promise that onok returns, closes on a resolve and stays open on a reject.

Texts and props of the buttons

okText and cancelText are a text, a number or a snippet (an empty text and 0 are shown). okType is the type of the OK button, and okButtonProps and cancelButtonProps are the props of Button itself. Their onclick runs first.

mask: { closable: false }
mask: false
keyboard: false

Mask and keyboard

mask is a boolean or { enabled, closable }. mask: false draws no mask, and the Modal is still modal (the page behind is out of reach), as in Ant Design. A press that starts inside the dialog and ends on the mask (selecting text) never closes it. keyboard: false turns Escape off.

Position and width

centered puts the dialog in the middle of the window; by default it is 100px from the top. width is a number (px) or a string, 520 by default, and never wider than the window. style and zIndex adjust the box and the layer (1000, under the popup layers). By default the dialog zooms in and out around its own center; zoomFromClick makes it zoom from the place of the last click, as in Ant Design.

Title and close button

No title means no header: give the dialog a name with aria-label. title is a string, a number or a snippet. closable is false or an object with closeIcon, disabled and aria-label (the default name is “Close”); closeIcon replaces the cross.

Long content and the scroll

A tall dialog scrolls inside the window, not the page. While it is open the page does not scroll and does not jump sideways when its scrollbar goes away; scrollLock: false leaves the page scrolling. iOS Safari before 16 scrolls a locked page under a finger.

Nested Modals

A Modal opened later is above the first one; Escape and Tab go to the Modal on top, and the first is out of reach until the second is closed. Only the first one dims the page: the second adds no second mask.

default: the content is kept
destroyOnHidden
forceRender, onafteropenchange and onafterclose

Keeping and destroying the content

By default the content stays after a close, so what you typed is still there. destroyOnHidden removes it on every close. forceRender puts the Modal into the page before the first opening. onafteropenchange and onafterclose report the end of the animations.

Container

container is an element, a function that returns one, a selector, or false (leave it where it is written). The layer still covers the whole window. Custom properties set on a subtree reach the Modal only through a container inside that subtree.

Classes and styles

class and style go on the dialog box and wrapClassName on the scroll area. classNames and styles address the parts: root, mask, wrapper, dialog, content, close, header, title, body and footer. The Modal is drawn in the body, so the rules for these classes have to be global.

focusable: trap false
focusable: focusTriggerAfterClose false
focusable: autoFocusButton ok

Focus and the scroll lock

focusable is { trap, focusTriggerAfterClose, autoFocusButton }. Focus goes to the first element Tab reaches (the close button) and comes back to the button that opened the Modal; trap: false lets Tab leave, focusTriggerAfterClose: false does not give focus back, and autoFocusButton picks 'ok' or 'cancel'.

Custom render

modalRender is a snippet that gets the card as a snippet and may wrap it, for example in a box that can be dragged. The library has no draggable Modal of its own.

A Select inside

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.

Static dialogs

modal.confirm, info, success, warning and error open a ready-made dialog from code: an icon, a title, a text and buttons. No markup and no state. It is an alert dialog, 416px wide, with focus on OK; there is no close button, a press outside does not close it, and Escape does.

The answer

The call returns a handle that can be awaited: true for OK, false for Cancel, Escape and destroy(). Note: await modal.confirm(…) waits until the dialog is closed, and so does returning the handle from an async function.

OK and Cancel that wait

onok and oncancel of a static dialog may return a Promise. The button is loading while it is pending; a resolve closes the dialog, and a reject (or event.preventDefault()) keeps it open. An unanswered dialog has not resolved its handle.

update, destroy and destroyAll

handle.update(patch) changes the dialog in place (an object is merged; a function gets the previous options) and keeps focus. handle.destroy() closes it. modal.destroyAll() closes every static dialog and never a Modal written in the markup, for example on a route change.

ModalHost

With no host the library draws the static dialogs itself, in the body. <ModalHost> draws them where you put it, so they see the context of that place. Only one host is active at a time; one that unmounts hands the open dialogs back.

API

Props of Modal

PropertyDescriptionTypeDefault
openWhether the Modal is shown. bind:open works: a way to close sets it to false.booleanfalse
titleThe title. No title, no header. 0 is shown.string | number | Snippet | null—
childrenThe body.Snippet—
footernull removes the footer; a text is the footer; a snippet gets origin (both buttons), ok and cancel.string | number | Snippet<[{ origin, ok, cancel }]> | nullCancel and OK
okTextText of the OK button. When it is left out the default is used; an empty string stays empty.string | number | SnippetOK
cancelTextText of the Cancel button.string | number | SnippetCancel
okTypeThe type of the OK button.ButtonType'primary'
okButtonPropsProps of the OK button. Its onclick runs before onok.ComponentProps<typeof Button>—
cancelButtonPropsProps of the Cancel button. Its onclick runs before oncancel.ComponentProps<typeof Button>—
confirmLoadingThe OK button is loading.booleanfalse
onokThe OK button was pressed. The Modal closes only with closeOnOk.(event: MouseEvent) => unknown—
closeOnOkThe Modal closes after onok, waiting for a Promise it returned: a resolve closes it, a reject keeps it open; event.preventDefault() keeps it open. Ant Design has no such option on the plain Modal.booleanfalse
oncancelThe close button, Cancel, Escape or the mask asked to close. The Modal then closes unless the handler calls event.preventDefault().(event: MouseEvent | KeyboardEvent) => void—
closableShows the close button. An object sets its icon, disables it, or names it (default “Close”).boolean | { closeIcon?, disabled?, 'aria-label'? }true
closeIconReplaces the cross. Hide the button with closable: false.Snippeta cross
maskenabled: false (or false) draws no mask: the Modal is modal all the same. closable: false stops a press on the mask from closing it.boolean | { enabled?, closable? }true
keyboardEscape closes.booleantrue
centeredCenters the dialog in the window.booleanfalse
widthA number is px. Never wider than the window.string | number520
zIndexThe z-index of the layer (--ads-modal-z-index), under the popup layers.number1000
containerThe element the layer is moved into, a function that returns it, a selector, or false to leave it where it is written.HTMLElement | (() => HTMLElement) | string | falsedocument.body
destroyOnHiddenThe content is removed on every close.booleanfalse
forceRenderThe Modal is in the page, hidden, before the first opening.booleanfalse
focusabletrap: Tab stays inside. focusTriggerAfterClose: focus goes back to what had it. autoFocusButton: 'ok', 'cancel' or null (the dialog); by default the first element Tab reaches.{ trap?, focusTriggerAfterClose?, autoFocusButton? }{ trap: true, focusTriggerAfterClose: true }
scrollLockThe page does not scroll while the Modal is open.booleantrue
zoomFromClickThe dialog zooms in and out from the place of the last click, as in Ant Design, instead of around its own center. A keyboard open, or one that comes later than the click, still starts at the center.booleanfalse
modalRenderGets the card as a snippet and may wrap it.Snippet<[Snippet]>—
classExtra classes of the dialog box.string—
styleInline style of the dialog box. The width is kept.string—
wrapClassNameExtra classes of the scroll area (the same part as classNames.wrapper).string—
classNamesExtra classes for the parts of the Modal.{ root?, mask?, wrapper?, dialog?, content?, close?, header?, title?, body?, footer? }—
stylesInline styles for the parts: an object of CSS properties (kebab-case or custom properties).{ root?, mask?, wrapper?, dialog?, content?, close?, header?, title?, body?, footer? }—
onafteropenchangeThe enter or the leave animation has ended.(open: boolean) => void—
onaftercloseThe leave animation has ended and the Modal is gone.() => void—

Options of a static dialog

PropertyDescriptionTypeDefault
titleThe title.string | number | Snippet—
contentThe text under the title.string | number | Snippet—
iconA snippet or a text replaces the icon of the kind; false removes it.Snippet | string | falsethe icon of the kind
okCancelconfirm has Cancel and OK; the others OK only. This changes that.booleantrue for confirm
footerAs in Modal.string | number | Snippet<[{ origin, ok, cancel }]> | nullthe buttons
okTextText of the OK button.string | number | SnippetOK
cancelTextText of the Cancel button.string | number | SnippetCancel
okTypeThe type of the OK button.ButtonType'primary'
okButtonPropsProps of the OK button.ComponentProps<typeof Button>—
cancelButtonPropsProps of the Cancel button.ComponentProps<typeof Button>—
onokOK was pressed. A Promise keeps the button loading: a resolve closes the dialog, a reject keeps it open. A static dialog always closes after onok (closeOnOk is on).(event: MouseEvent) => unknown—
oncancelCancel, Escape or another way to cancel. A Promise is waited for in the same way; event.preventDefault() keeps the dialog open.(event: MouseEvent | KeyboardEvent) => unknown—
closableShows the close button (there is none by default).boolean | { closeIcon?, disabled?, 'aria-label'? }false
closeIconReplaces the cross.Snippeta cross
maskA press on the mask does not close a static dialog unless closable is true.boolean | { enabled?, closable? }{ closable: false }
keyboardEscape closes (it is a cancel).booleantrue
centeredCenters the dialog.booleanfalse
widthA number is px.string | number416
zIndexThe z-index of the layer.number1000
containerWhere the layer is moved to.HTMLElement | (() => HTMLElement) | string | falsedocument.body
focusableFocus goes to the OK button by default.{ trap?, focusTriggerAfterClose?, autoFocusButton? }{ autoFocusButton: 'ok' }
scrollLockThe page does not scroll while the dialog is open.booleantrue
zoomFromClickThe dialog zooms in and out from the place of the last click instead of around its own center.booleanfalse
classExtra classes of the dialog box.string—
styleInline style of the dialog box.string—
wrapClassNameExtra classes of the scroll area.string—
classNamesExtra classes for the parts, and for the three parts of a static dialog: confirmBody, icon and description.{ …the parts of the Modal, confirmBody?, icon?, description? }—
stylesInline styles for the same parts.{ …the parts of the Modal, confirmBody?, icon?, description? }—
onafteropenchangeThe enter or the leave animation has ended.(open: boolean) => void—
onaftercloseThe dialog is gone.() => void—

Methods, the handle and ModalHost

PropertyDescriptionTypeDefault
modal.confirm(options)Opens a dialog with Cancel and OK and the warning icon.ModalHandle—
modal.info(options) · success · warning · errorOpen a dialog with OK only and the icon of the kind.ModalHandle—
modal.destroyAll()Closes every static dialog (never a Modal written in the markup).void—
handle.destroy()Closes the dialog with the leave animation; the handle resolves false. Does nothing once it is closed.void—
handle.update(patch)Changes the options in place. An object is merged into them; a function gets the previous options and returns the changes. Does nothing after a close.void—
handle.then · await handleResolves when the dialog starts to close: true for OK, false for everything else. Awaiting a call waits for the close.PromiseLike<boolean>—
<ModalHost />Optional. Draws the static dialogs where it stands, so they see the context of that place. One host is active; with none, the library makes its own layer in the body.component—
Differences from Ant Design: the cancel ways close the Modal unless oncancel calls event.preventDefault() (React leaves closing to you); closeOnOk is new; maskClosable is mask.closable, destroyOnClose is destroyOnHidden and getContainer is container; modal.* and <ModalHost> replace Modal.useModal and contextHolder; static dialogs are alert dialogs and can be awaited. Not taken yet: mask.blur, width by breakpoint, loading (planned for v1.1), and a draggable Modal.

Design tokens

TokenDescriptionDefault
--ads-modal-z-indexLayer of the Modal, under the popup layers (the popover is 1030).1000
--ads-modal-widthWidth of a dialog when width is not set.520px
--ads-modal-topDistance of the dialog from the top, when it is not centered.100px
--ads-modal-mask-bgColor of the mask.rgba(0, 0, 0, 0.45)
--ads-modal-content-bgBackground of the card. In the dark theme #1f1f1f.#ffffff
--ads-modal-radiusCorner radius of the card.8px
--ads-modal-shadowShadow of the card.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-paddingPadding of the card.20px 24px
--ads-modal-title-colorColor of the title. In the dark theme 85% white.rgba(0, 0, 0, 0.88)
--ads-modal-title-font-sizeFont size of the title.16px
--ads-modal-title-line-heightLine height of the title.24px
--ads-modal-title-font-weightWeight of the title.600
--ads-modal-header-gapGap between the title and the body (and between the title and the text of a static dialog).8px
--ads-modal-body-colorColor of the body text. In the dark theme 85% white.rgba(0, 0, 0, 0.88)
--ads-modal-footer-margin-topGap between the body and the footer.12px
--ads-modal-footer-gapGap between the buttons of the footer.8px
--ads-modal-close-sizeSize of the close button (a target of at least 24px, WCAG 2.5.8).32px
--ads-modal-close-insetDistance of the close button from the corner.12px
--ads-modal-close-colorColor of the cross (3:1 on the card).rgba(0, 0, 0, 0.45)
--ads-modal-close-color-hoverColor of the cross on hover.rgba(0, 0, 0, 0.88)
--ads-modal-close-bg-hoverBackground of the close button on hover.rgba(0, 0, 0, 0.06)
--ads-modal-motion-easeEasing of the zoom-in.cubic-bezier(0.08, 0.82, 0.17, 1)
--ads-modal-confirm-widthWidth of a static dialog.416px
--ads-modal-confirm-icon-sizeSize of the icon of a static dialog.22px
--ads-modal-confirm-icon-gapGap between the icon and the text of a static dialog.12px
--ads-modal-confirm-icon-infoColor of the info icon.#1677ff
--ads-modal-confirm-icon-successColor of the success icon. tokens-accessible.css darkens it to #389e0d (3:1 on the white card).#52c41a
--ads-modal-confirm-icon-warningColor of the warning icon and of confirm. tokens-accessible.css darkens it to #c27c00.#faad14
--ads-modal-confirm-icon-errorColor of the error icon.#ff4d4f

Accessibility

  • The dialog is role="dialog" with aria-modal="true", named by its title (aria-labelledby). With no title give it a name with aria-label: a Modal with neither logs a warning while developing. A static dialog is role="alertdialog" and is described by its text.
  • Focus moves to the first element Tab reaches (the close button) and stays inside: Tab on the last element goes to the first, Shift+Tab on the first to the last. When the Modal closes, focus goes back to the button that opened it. A static dialog puts focus on the OK button.
  • The page behind the Modal is out of reach of the keyboard, the pointer and assistive technology (inert; aria-hidden where a browser does not know inert). The Message layer is kept reachable, so a message opened by the OK button is read.
  • Escape closes the Modal that is on top. With a Select open inside it, Escape closes the list first. A key that ends an IME composition does not close anything. keyboard: false turns Escape off.
  • The page does not scroll and does not jump sideways when its scrollbar goes away. Not handled: iOS Safari before 16 scrolls a locked page under a finger.
  • Contrast: the title and the text are about 15:1 on the card, the cross 3:1, and the icons of static dialogs are held to 3:1 (in the dark theme, and in the light theme with tokens-accessible.css, which darkens the green and the amber). In forced-colors modes the card and the close button have a border, and the mask stays translucent. The animation is off under prefers-reduced-motion, and the handle of a static dialog is answered without it.
  • Known limit: a Modal opened from inside a popup (for example from the list of a Select) is outside that popup, so a press in it closes the popup and takes the Modal with it. Open it from a button outside, or give it a container. A message that is already on the page when a Modal opens is kept reachable, but a message added later to the same layer may not be read by every screen reader.
  • Not checked: a real screen reader (NVDA, JAWS, VoiceOver, a phone), a real touch device, and a real Safari. Checked: the keys, focus and the page behind in Chromium, Firefox and WebKit, and on the lowest supported versions of the three engines; Orca with Firefox is run on GitHub.