NotificationУведомление
Уведомление — блок с заголовком, текстом и, если нужно, кнопками. Оно стоит в углу или у верхнего или нижнего края окна, закрывается само через время и не забирает фокус. Оно весомее сообщения: говорит больше и стоит у края окна, а не над содержимым. Его открывают вызовом из кода, откуда угодно, а не элементом в шаблоне.
Когда использовать
- Используйте для обратной связи, которой нужны заголовок и текст: завершённая загрузка, неудавшаяся синхронизация, новая версия, сообщение от кого-то.
- Короткая обратная связь в одну фразу — это
Message. Для решения, которое должен принять пользователь, нужен диалог (Modal). - Уведомление уходит само, поэтому не кладите в него то, что пользователь должен суметь найти снова, либо задайте
duration: 0и дайте пользователю закрыть его.
Примеры
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
</script>
<!-- A call from anywhere shows a notification at the top right: no setup and no markup. It goes after 4.5 s. -->
<Button
type="primary"
onclick={() =>
notification.open({
title: 'Notification title',
description: 'This is the content of the notification. A title, and a text under it.'
})}
>
Open the notification
</Button>
open: no type icon
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
const text = 'The type gives the icon, and a screen reader the type word before the title.';
</script>
<!-- Four kinds with an icon, and `open`, which has none. `error` and `warning` are read out at once, the others wait. -->
<div class="stack">
<div class="row">
<Button onclick={() => notification.success({ title: 'Saved', description: text })}>success</Button>
<Button onclick={() => notification.info({ title: 'New version', description: text })}>info</Button>
<Button onclick={() => notification.warning({ title: 'Almost full', description: text })}>warning</Button>
<Button onclick={() => notification.error({ title: 'Upload failed', description: text })}>error</Button>
</div>
<div class="field">
<span class="caption">open: no type icon</span>
<Button onclick={() => notification.open({ title: 'No icon', description: text })}>open</Button>
</div>
</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>
<script lang="ts">
import { Button, notification, type NotificationPlacement } from 'svelte-ant-design';
const top: NotificationPlacement[] = ['topLeft', 'top', 'topRight'];
const bottom: NotificationPlacement[] = ['bottomLeft', 'bottom', 'bottomRight'];
const show = (placement: NotificationPlacement) =>
notification.info({ title: placement, description: 'The newest stands nearest the window edge.', placement, duration: 6 });
</script>
<!-- Six places. Each is its own list: the newest notification is nearest the edge, the older ones are pushed away from it. -->
<div class="stack">
<div class="row">
{#each top as placement (placement)}
<Button onclick={() => show(placement)}>{placement}</Button>
{/each}
</div>
<div class="row">
{#each bottom as placement (placement)}
<Button onclick={() => show(placement)}>{placement}</Button>
{/each}
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
duration 10
duration 0: until it is closed
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
let close: (() => void) | undefined;
</script>
<!-- `duration` is in seconds (default 4.5). `0` or `false` keeps the notification until it is closed. -->
<div class="stack">
<div class="field">
<span class="caption">duration 10</span>
<Button onclick={() => notification.info({ title: 'Ten seconds', description: 'It waits longer than usual.', duration: 10 })}>10 s</Button>
</div>
<div class="field">
<span class="caption">duration 0: until it is closed</span>
<div class="row">
<Button onclick={() => (close = notification.warning({ title: 'Stays', description: 'Close it with the cross, or with the other button.', duration: 0 }))}>
Open
</Button>
<Button onclick={() => close?.()}>Close it by code</Button>
</div>
</div>
</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>
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
// The same key updates the notification in place: the box stays where it is, and a screen reader reads the new text.
function run() {
notification.info({ title: 'Uploading', description: 'The file is on its way.', key: 'upload', duration: 0 });
setTimeout(() => notification.success({ title: 'Uploaded', description: 'The file is on the server.', key: 'upload', duration: 4 }), 1800);
}
</script>
<Button onclick={run}>Upload</Button>
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
const key = 'actions';
const undo = () => notification.destroy(key);
</script>
<!-- `actions` is content under the text, at the end: usually buttons. They are your elements, so the keyboard reaches them
after the text and before the close button. -->
{#snippet actions()}
<Button size="small" onclick={undo}>Undo</Button>
<Button size="small" type="primary" onclick={undo}>Keep</Button>
{/snippet}
<Button onclick={() => notification.info({ title: 'Message moved', description: 'It is in the archive now.', actions, key, duration: 0 })}>
With actions
</Button>
icon: a string
icon: a snippet
icon: false
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
</script>
{#snippet star()}<span style="color: gold; font-size: 24px">★</span>{/snippet}
<!-- `icon` replaces the icon of the type: a string (an emoji), a snippet, or `false` for none. -->
<div class="stack">
<div class="field">
<span class="caption">icon: a string</span>
<Button onclick={() => notification.success({ title: 'Launched', description: 'The icon is an emoji.', icon: '🚀' })}>string</Button>
</div>
<div class="field">
<span class="caption">icon: a snippet</span>
<Button onclick={() => notification.open({ title: 'Starred', description: 'The icon is a snippet.', icon: star })}>snippet</Button>
</div>
<div class="field">
<span class="caption">icon: false</span>
<Button onclick={() => notification.error({ title: 'Without icon', description: 'The type word is still read by a screen reader.', icon: false })}>false</Button>
</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>
closable: false
closeIcon: a string
closeIcon: a snippet
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
</script>
{#snippet word()}Close{/snippet}
<!-- The close button is there by default. `closable: false` or `closeIcon: false` removes it; `closeIcon` replaces the cross. -->
<div class="stack">
<div class="field">
<span class="caption">closable: false</span>
<Button onclick={() => notification.info({ title: 'No close button', description: 'It goes by itself.', closable: false })}>closable false</Button>
</div>
<div class="field">
<span class="caption">closeIcon: a string</span>
<Button onclick={() => notification.info({ title: 'A text button', description: 'The name of the button stays "Close".', closeIcon: '✕', duration: 8 })}>string</Button>
</div>
<div class="field">
<span class="caption">closeIcon: a snippet</span>
<Button onclick={() => notification.info({ title: 'A snippet button', description: 'Any content is the icon.', closeIcon: word, duration: 8 })}>snippet</Button>
</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>
showProgress, duration 8: hold the pointer over it
showProgress, pauseOnHover: false
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
</script>
<!-- `showProgress` draws a strip that runs down with the time left. It is drawn from the timer that closes the notification, so it
stands still while the pointer or the focus holds it. It is decorative: it is not announced. -->
<div class="stack">
<div class="field">
<span class="caption">showProgress, duration 8: hold the pointer over it</span>
<Button onclick={() => notification.info({ title: 'Progress', description: 'The strip waits when the timer waits.', showProgress: true, duration: 8 })}>
with a strip
</Button>
</div>
<div class="field">
<span class="caption">showProgress, pauseOnHover: false</span>
<Button onclick={() => notification.info({ title: 'No pause', description: 'It goes on while you hold the pointer.', showProgress: true, pauseOnHover: false, duration: 8 })}>
does not pause
</Button>
</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>
pauseOnHover (the default), duration 5: keep the pointer over it
pauseOnHover: false
duration 5: Tab to the close button, and it waits for you
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
</script>
<!-- Hover (a mouse or a pen, not a touch) and focus inside stop the timer; it goes on with the time that was left. The timer also
waits while the page is hidden. -->
<div class="stack">
<div class="field">
<span class="caption">pauseOnHover (the default), duration 5: keep the pointer over it</span>
<Button onclick={() => notification.info({ title: 'Hover me', description: 'I stay while you do.', duration: 5 })}>pauses</Button>
</div>
<div class="field">
<span class="caption">pauseOnHover: false</span>
<Button onclick={() => notification.info({ title: 'I go on', description: 'Whatever you do.', duration: 5, pauseOnHover: false })}>does not pause</Button>
</div>
<div class="field">
<span class="caption">duration 5: Tab to the close button, and it waits for you</span>
<Button onclick={() => notification.warning({ title: 'Focus holds it', description: 'Focus inside the box stops the timer.', duration: 5 })}>holds on focus</Button>
</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>
stack on (the default), threshold 3
<script lang="ts">
import { Button, Switch, notification } from 'svelte-ant-design';
let stacked = $state(true);
let opened = $state(0);
// `stack` is a setting of notification.config(): on by default, `{ threshold }` sets the number, `false` turns it off.
$effect(() => {
notification.config({ stack: stacked ? undefined : false });
return () => notification.config({ stack: undefined });
});
</script>
<!-- Past the threshold (3) the older notifications of a place lie behind the newest one; the pointer or the focus opens the pile,
and every timer waits while it is open. -->
<div class="stack">
<div class="row">
<Switch bind:checked={stacked} aria-label="stack" />
<span>stack {stacked ? 'on (the default), threshold 3' : 'off'}</span>
</div>
<div class="row">
<Button onclick={() => notification.info({ title: `Notification ${++opened}`, description: 'This is a stacked notification.', duration: 12 })}>Open</Button>
<Button onclick={() => notification.destroy()}>Destroy all</Button>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
maxCount not set
<script lang="ts">
import { Button, Switch, notification } from 'svelte-ant-design';
let limited = $state(false);
let opened = $state(0);
let pushed = $state(0);
// maxCount is a setting of notification.config(): it counts the notifications of all places together. undefined takes it back
// to the default (no limit), so the other examples of the page are not limited.
$effect(() => {
notification.config({ maxCount: limited ? 3 : undefined });
return () => notification.config({ maxCount: undefined });
});
</script>
<div class="stack">
<div class="row">
<Switch bind:checked={limited} aria-label="maxCount 3" />
<span>maxCount {limited ? 3 : 'not set'}</span>
</div>
<div class="field">
<div class="row">
<Button
onclick={() =>
notification.info({
title: `Notification ${++opened}`,
description: 'The oldest closes to make room.',
duration: 0,
onclose: (reason) => reason === 'replaced' && pushed++
})}
>
Open one
</Button>
<Button onclick={() => notification.destroy()}>Close all</Button>
</div>
<span role="status">{opened} opened, pushed out by the limit: {pushed}</span>
</div>
</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;
}
</style>
class, style: on the box
classNames, styles: the parts (root, icon, section, title, description, actions, close, progress)
props: data-* and aria-* on the box
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
</script>
<div class="stack">
<div class="field">
<span class="caption">class, style: on the box</span>
<Button onclick={() => notification.info({ title: 'Styled box', description: 'A class and a style.', class: 'fancy', style: { 'border-radius': '24px' } })}>
class and style
</Button>
</div>
<div class="field">
<span class="caption">classNames, styles: the parts (root, icon, section, title, description, actions, close, progress)</span>
<Button
onclick={() =>
notification.success({
title: 'Styled parts',
description: 'The box, the title and the strip.',
showProgress: true,
classNames: { title: 'fancy-title' },
styles: { root: { background: 'var(--ads-color-primary-solid)', color: '#fff' }, icon: { color: '#fff' }, close: { color: '#fff' } }
})}
>
classNames and styles
</Button>
</div>
<div class="field">
<span class="caption">props: data-* and aria-* on the box</span>
<Button onclick={() => notification.info({ title: 'With attributes', props: { 'data-testid': 'my-note', 'aria-label': 'Custom label' } })}>props</Button>
</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;
}
/* The notification is drawn outside this component, so a class that styles it is global here. */
:global(.fancy) {
outline: 2px dashed var(--ads-color-primary);
}
:global(.fancy-title) {
font-weight: 600;
letter-spacing: 0.02em;
}
</style>
box clicks: 0; closed by: —
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
let clicked = $state(0);
let reason = $state('');
</script>
<!-- `onclick` is called when the box is clicked (not the close button). `onclose` is called once, when the notification starts to
close, with the reason: 'timeout', 'user' (the close button, Escape), 'replaced' (the limit) or 'destroy' (code). -->
<div class="stack">
<div class="field">
<Button
onclick={() =>
notification.info({
title: 'Click me, or close me',
description: 'Wait, close it, or press Escape inside it.',
duration: 6,
onclick: () => clicked++,
onclose: (why) => (reason = why)
})}
>
Open
</Button>
<span role="status">box clicks: {clicked}; closed by: {reason || '—'}</span>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
</style>
<script lang="ts">
import { Button, notification } from 'svelte-ant-design';
</script>
<!-- Title, description and actions are a string, a number or a snippet. A snippet is drawn in the layer, so it sees the context of the
place where the host is, not of the component that wrote it. -->
{#snippet title()}<strong>Rich</strong> <em>title</em>{/snippet}
{#snippet description()}A link to <a href="#content">the docs</a> and <code>code</code>.{/snippet}
<Button onclick={() => notification.info({ title, description, duration: 10 })}>Snippets</Button>
<NotificationHost placement="bottomLeft" bottom={72} ... /> not mounted
<script lang="ts">
import { Button, NotificationHost, Switch, notification } from 'svelte-ant-design';
let mounted = $state(false);
</script>
<!-- <NotificationHost> draws the notifications where you put it. Its props are the settings and win over notification.config(). Without one the library
makes its own layer. Only one host is active at a time. -->
{#if mounted}
<NotificationHost placement="bottomLeft" bottom={72} duration={8} labels={{ close: 'Dismiss', success: 'Done', error: 'Failed' }} />
{/if}
<div class="stack">
<div class="row">
<Switch bind:checked={mounted} aria-label="NotificationHost" />
<span><NotificationHost placement="bottomLeft" bottom={72} ... /> {mounted ? 'mounted' : 'not mounted'}</span>
</div>
<div class="row">
<Button onclick={() => notification.success({ title: 'Saved' })}>success</Button>
<Button onclick={() => notification.error({ title: 'Upload' })}>error</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, notification } from 'svelte-ant-design';
let opened = $state(0);
</script>
<!-- `notification.destroy(key)` closes one, `notification.destroy()` closes every notification. -->
<div class="stack">
<div class="row">
<Button onclick={() => notification.info({ title: `Notification ${++opened}`, key: `n${opened}`, duration: 0 })}>Open</Button>
<Button onclick={() => notification.destroy(`n${opened}`)}>Close the last</Button>
<Button onclick={() => notification.destroy()}>Destroy all</Button>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
a modal dialog
<script lang="ts">
import { tick } from 'svelte';
import { Button, notification } from 'svelte-ant-design';
const KEY = 'container-dialog';
let dialog = $state<HTMLDialogElement | null>(null);
// Null before the first press; then where the layer was found: in the body or in the dialog.
let placed = $state<'body' | 'dialog' | null>(null);
// `container` is a setting of notification.config(): the element that the layer is put in (the body by default). A native modal
// <dialog> is shown in the top layer of the browser, over everything that is outside of it, and nothing outside it can be reached.
// So a layer in the body is covered by the dialog, and a layer in the dialog stands above it and can be used. The setting is
// given back (and the notification closed) when the dialog closes, and when the example is left, so that the page is not touched.
async function show(inDialog: boolean) {
if (!dialog) return;
notification.config({ container: inDialog ? dialog : undefined });
notification.info({
key: KEY,
title: inDialog ? 'In the dialog' : 'In the body',
description: inDialog ? 'Above the dialog, and it can be closed.' : 'Behind the dialog.',
duration: 8,
props: { 'data-demo': 'container' }
});
await tick();
placed = dialog.contains(document.querySelector('[data-demo="container"]')) ? 'dialog' : 'body';
}
function release() {
notification.destroy(KEY);
notification.config({ container: undefined });
placed = null;
}
$effect(() => {
return () => notification.config({ container: undefined });
});
</script>
<div class="stack">
<div class="field">
<span class="caption">a modal dialog</span>
<div class="row">
<Button onclick={() => dialog?.showModal()}>Open the dialog</Button>
</div>
</div>
</div>
<dialog bind:this={dialog} aria-label="The container example" onclose={release}>
<div class="stack">
<div class="field">
<span class="caption">container: not set (the body)</span>
<Button onclick={() => show(false)}>Show a notification</Button>
<span class="out" role="status">
{#if placed === 'body'}
The layer is in the body. The dialog covers it, and the notification cannot be reached.
{:else}
Press to see where the layer goes.
{/if}
</span>
</div>
<div class="field">
<span class="caption">container: the dialog</span>
<Button onclick={() => show(true)}>Show a notification</Button>
<span class="out" role="status">
{#if placed === 'dialog'}
The layer is in the dialog. The notification stands above it and can be closed.
{:else}
Press to see where the layer goes.
{/if}
</span>
</div>
<div class="row">
<Button onclick={() => dialog?.close()}>Close the dialog</Button>
</div>
</div>
</dialog>
<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;
}
.out {
min-height: 36px;
color: var(--ads-color-text-secondary);
font-size: 12px;
line-height: 18px;
}
dialog {
box-sizing: border-box;
width: min(420px, calc(100vw - 32px));
padding: 20px 24px;
border: 1px solid var(--ads-color-border);
border-radius: var(--ads-radius-lg);
background: var(--ads-color-bg-container);
color: var(--ads-color-text);
}
/* Dark enough to show that what stands under it is covered. */
dialog::backdrop {
background: rgb(0 0 0 / 55%);
}
</style>
API
Параметры уведомления
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| title | Первая строка: строка, число (0 показывается) или snippet. Обязателен. Это имя title из Ant Design React 6 (message там устарел). | NotificationContent | — |
| description | Текст под заголовком. Необязателен: одного заголовка достаточно. | NotificationContent | — |
| actions | Содержимое под текстом, у конца строки: обычно кнопки. Элементы отсюда — те, до которых добирается клавиатура (actions в React, btn в Vue). | NotificationContent | — |
| icon | Заменяет иконку вида; false убирает её. У open иконки нет, пока её не передали. | string | Snippet | false | the icon of the type |
| duration | Секунды до ухода уведомления. 0 или false оставляет его, пока не закроют. Отрицательное или нечисловое значение заменяется значением по умолчанию (с предупреждением при разработке). Angular считает в миллисекундах; мы нет. | number | false | 4.5 |
| key | Вызов с ключом открытого уведомления обновляет его на месте (новые вид, тексты и параметры; таймер запускается заново). Без ключа он создаётся сам. | string | number | generated |
| placement | Где оно стоит: своё место или значение по умолчанию хоста и notification.config(). | 'top' | 'topLeft' | 'topRight' | 'bottom' | 'bottomLeft' | 'bottomRight' | 'topRight' |
| closable | Показывает кнопку закрытия. Если не задано, действует значение по умолчанию хоста и notification.config(). | boolean | true |
| closeIcon | Заменяет крестик кнопки закрытия; false убирает кнопку. Имя кнопки для скринридера остаётся labels.close. Объектная форма closable из React не взята: это closeIcon и onclose. | string | Snippet | false | the cross |
| showProgress | Показывает полосу внизу блока, которая убывает с оставшимся временем. Она стоит, когда стоит таймер, и её нет при duration: 0. | boolean | false |
| pauseOnHover | Удерживает таймер, пока курсор (мышь или перо) над блоком. Фокус внутри, раскрытая стопка и скрытая страница удерживают его независимо от этого значения. | boolean | true |
| role | Переопределяет роль. По умолчанию у error и warning alert (зачитывается сразу), у остальных status. | 'alert' | 'status' | by type |
| class | Дополнительные классы блока. | string | — |
| style | Инлайн-стиль блока: строка или объект CSS-свойств (kebab-case или custom properties; числа записываются как есть). | string | Record<string, string | number> | — |
| classNames | Дополнительные классы для частей. Значение здесь важнее значения хоста и notification.config(). | { root?, icon?, section?, title?, description?, actions?, close?, progress? } | — |
| styles | То же для инлайн-стилей, объектами. | { root?, icon?, section?, title?, description?, actions?, close?, progress? } | — |
| props | Атрибуты блока (props из React): data-* и aria-*. | Record<`data-${string}` | `aria-${string}`, string> | — |
| onclick | Вызывается с событием при клике по блоку, не по кнопке закрытия. Клик не закрывает уведомление. | (event: MouseEvent) => void | — |
| onclose | Вызывается один раз, когда уведомление начинает закрываться, с причиной: вышло время, закрыл пользователь (кнопка или Escape), вытеснил лимит или закрыл код (destroy или возвращённая функция). Angular сообщает лишь, закрыл ли пользователь; React и Vue ничего не передают. | (reason: 'timeout' | 'user' | 'replaced' | 'destroy') => void | — |
Методы
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| notification.open(options) | Открывает уведомление без иконки вида или обновляет открытое с тем же key. Возвращает функцию, закрывающую его. Она не thenable (у Message — thenable). | () => void | — |
| notification.info | success | error | warning(options) | По методу на каждый вид, с теми же параметрами. Без окна (на сервере) любой вызов ничего не делает и возвращает функцию, которая ничего не делает. | () => void | — |
| notification.destroy(key?) | Закрывает уведомление с этим ключом или все уведомления. Каждое проходит обычный уход и вызывает свой onclose с причиной 'destroy'. | void | — |
| notification.config(options) | Задаёт значения по умолчанию для всех уведомлений с этого момента (таблица настроек ниже). Настройка, переданная как { top: undefined }, возвращается к значению по умолчанию. | void | — |
Настройки: notification.config() и пропсы NotificationHost
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| top | Расстояние верхних мест от верха окна. Число — пиксели. | number | string | 24 |
| bottom | Расстояние нижних мест от низа окна. Число — пиксели. | number | string | 24 |
| placement | Место каждого уведомления, которое своё не указало. | 'top' | 'topLeft' | 'topRight' | 'bottom' | 'bottomLeft' | 'bottomRight' | 'topRight' |
| duration | Длительность по умолчанию в секундах. 0 и false не закрывают. | number | false | 4.5 |
| maxCount | Не больше стольких открытых уведомлений во всех местах вместе; старейшее закрывается (причина 'replaced'). React и Angular считают так же, Vue — отдельно для каждого места. | number | — |
| container | Элемент, в который кладётся слой. Это только место в странице: слой остаётся position: fixed и рисуется у окна (getContainer в Ant Design). Нужен, например, для нативного модального <dialog>, который закрывает всё, что вне его. | HTMLElement | (() => HTMLElement) | document.body |
| closable | Значение closable по умолчанию. | boolean | true |
| closeIcon | Значение closeIcon по умолчанию. | string | Snippet | false | the cross |
| showProgress | Значение showProgress по умолчанию. | boolean | false |
| pauseOnHover | Значение pauseOnHover по умолчанию. | boolean | true |
| labels | Слово вида, которое читают перед заголовком (пустое слово — без слова, так по умолчанию у open), и имя кнопки закрытия. Переводы передавайте здесь: системы локалей в библиотеке пока нет. | { open?, info?, success?, error?, warning?, close? } | { info: "Info", success: "Success", error: "Error", warning: "Warning", close: "Close" } |
| classNames | Значения по умолчанию для частей каждого уведомления и две части места: list (прокручиваемая колонка) и listContent (строки). | { root?, icon?, section?, title?, description?, actions?, close?, progress?, list?, listContent? } | — |
| styles | То же для инлайн-стилей, объектами. | { root?, icon?, section?, title?, description?, actions?, close?, progress?, list?, listContent? } | — |
| stack | Включена по умолчанию (как в Ant Design React): после порога (3) старые уведомления места ложатся за самым новым, а курсор или фокус раскрывают стопку. false отключает, { threshold } меняет число. | boolean | { threshold?: number } | true |
Отличия от Ant Design: слой создаёт сама библиотека (
useNotification и contextHolder из React заменяет <NotificationHost>); title и actions — актуальные имена из React (message и btn там устарели); stack включён по умолчанию, как в React; самое новое уведомление стоит ближе всего к краю окна в любом месте, как в React; роль по виду и скрытое слово вида (React: role="alert" у всех); таймер ждёт ещё и фокус, раскрытую стопку и скрытую страницу; onclose передаёт причину, а вызов возвращает функцию, закрывающую уведомление; duration в секундах, как в React и Vue (Angular: миллисекунды). Не взяты: алиас warn из Vue, prefixCls, rtl (направление наследуется) и объектная форма closable. API вдохновлён Ant Design (MIT); реализация оригинальная для Svelte.Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-notification-z-index | Слой уведомлений, выше сообщений (2010) и любого всплывающего окна (у подсказки 1070). | 2050 |
| --ads-notification-width | Ширина блока. Он никогда не шире окна. | 384px |
| --ads-notification-top | Расстояние верхних мест от верха окна, если top не задан. | 24px |
| --ads-notification-bottom | Расстояние нижних мест от низа окна, если bottom не задан. | 24px |
| --ads-notification-margin | Свободное место по бокам окна и на дальнем конце места (оставляет также место для тени). | 24px |
| --ads-notification-gap | Промежуток между двумя уведомлениями. | 16px |
| --ads-notification-bg | Фон блока. В тёмной теме #1f1f1f. | #ffffff |
| --ads-notification-color | Цвет текста. В тёмной теме 85% белого. | rgba(0, 0, 0, 0.88) |
| --ads-notification-padding-block | Внутренний отступ блока сверху и снизу. | 20px |
| --ads-notification-padding-inline | Внутренний отступ блока по бокам. На этом расстоянии от края стоит кнопка закрытия. | 24px |
| --ads-notification-padding | Внутренние отступы блока (два предыдущих). | var(--ads-notification-padding-block) var(--ads-notification-padding-inline) |
| --ads-notification-line-height | Высота строки описания. | 22px |
| --ads-notification-radius | Радиус углов блока. | 8px |
| --ads-notification-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-notification-title-size | Размер шрифта заголовка. | 16px |
| --ads-notification-title-line-height | Высота строки заголовка; иконка и кнопка закрытия центрируются по ней. | 24px |
| --ads-notification-description-gap | Промежуток между заголовком и описанием. | 8px |
| --ads-notification-actions-gap | Промежуток между текстом и действиями. | 12px |
| --ads-notification-icon-size | Размер иконки. | 24px |
| --ads-notification-icon-gap | Промежуток между иконкой и текстом. | 12px |
| --ads-notification-icon-info | Цвет иконки info. | #1677ff |
| --ads-notification-icon-success | Цвет иконки success. tokens-accessible.css затемняет её до #389e0d (3:1 на белом блоке). | #52c41a |
| --ads-notification-icon-error | Цвет иконки error. | #ff4d4f |
| --ads-notification-icon-warning | Цвет иконки warning. tokens-accessible.css затемняет её до #c27c00. | #faad14 |
| --ads-notification-close-size | Размер кнопки закрытия: 24px, минимальная цель по WCAG 2.5.8 (в Ant Design 22px). | 24px |
| --ads-notification-close-icon-size | Размер крестика в кнопке закрытия. | 14px |
| --ads-notification-close-room | Место, которое остаётся свободным в конце первой строки заголовка под кнопку закрытия. | 26px |
| --ads-notification-close-padding | Отступ с обоих концов кнопки закрытия, в которой больше, чем крестик (например, слово); крестик остаётся квадратом 24 px. | 4px |
| --ads-notification-close-color | Цвет кнопки закрытия. tokens-accessible.css делает его rgba(0, 0, 0, 0.65) (4.5:1 на блоке). | rgba(0, 0, 0, 0.45) |
| --ads-notification-close-color-hover | Цвет кнопки закрытия при наведении. | rgba(0, 0, 0, 0.88) |
| --ads-notification-close-bg | Фон кнопки закрытия в покое. | transparent |
| --ads-notification-close-bg-hover | Фон кнопки закрытия при наведении. | rgba(0, 0, 0, 0.06) |
| --ads-notification-progress-bg | Заливка полосы времени. | linear-gradient(90deg, #69b1ff, #1677ff) |
| --ads-notification-progress-track | Дорожка полосы времени. | rgba(0, 0, 0, 0.04) |
| --ads-notification-progress-height | Высота полосы времени. | 2px |
| --ads-notification-progress-inset | Расстояние полосы времени от боков блока. | 8px |
| --ads-notification-progress-radius | Радиус углов полосы времени. | 8px |
| --ads-notification-motion-offset | На сколько от своего места уведомление начинает появляться и заканчивает уходить (со своей стороны: правые места справа, top сверху). | 64px |
| --ads-notification-stack-offset | Шаг между строками стопки. | 8px |
| --ads-notification-stack-scale-step | Насколько каждая строка стопки меньше предыдущей (масштаб останавливается на втором шаге). | 0.06 |
Доступность
errorиwarning— этоrole="alert", их зачитывают сразу;info,successиopen—role="status", они ждут, пока скринридер закончит. В Ant Design Reactrole="alert"у всех, и скринридер прерывается даже на простое «Сохранено»; опцияroleзадаёт роль для каждого уведомления.- Иконка декоративна. Скрытое слово перед заголовком называет вид («Error: Upload failed»), так что вид передаётся не только цветом и формой. Переводы передавайте в
labels: системы локалей в библиотеке пока нет, по умолчанию английский. - Уведомление никогда не забирает фокус. Сфокусировать в нём можно кнопку закрытия и элементы, которые вы положили в
actions; кнопка закрытия 24px, размер цели по WCAG 2.5.8.Escapeзакрывает уведомление, в котором стоит фокус. - Таймер ждёт, пока курсор над уведомлением, пока фокус внутри, пока стопка раскрыта и пока страница скрыта. Уведомлению, которое должно остаться, нужен
duration: 0, а кнопка закрытия позволяет пользователю его убрать (WCAG 2.2.1, ограничения времени). - Слой — последний элемент своего контейнера, поэтому с клавиатуры до кнопок уведомления добираются только после остальной страницы, а сочетания клавиш для перехода к уведомлениям нет. В стопке старые уведомления
inertи скрыты от скринридера; стопка раскрывается, когда в неё приходит фокус, так что пользователь клавиатуры до них добирается. - Контраст: текст — около 15:1 на блоке; иконки видов держатся не ниже 3:1, а кнопка закрытия — 4,5:1 (в тёмной теме и в светлой с
tokens-accessible.css, который затемняет зелёный, жёлтый и кнопку закрытия). - В режимах forced-colors, например Windows High Contrast, блок, кнопка закрытия и полоса времени рисуются с рамкой. Анимация (блок выезжает со стороны своего места и проявляется) отключена при
prefers-reduced-motion; таймер и полоса те же. Касание не удерживает таймер и не раскрывает стопку. - Проверено настоящим скринридером (Orca с Firefox): он читает роль, слово вида, заголовок, описание, новый текст после обновления по ключу и имя кнопки закрытия. Не проверено: объявляет ли скринридер уведомление при его появлении (в нашей настройке Orca не озвучивает даже обычный
role="alert"), NVDA, JAWS, VoiceOver, скринридер телефона, настоящее сенсорное устройство (касание эмулируется в Chromium) и настоящий Safari.