MessageСообщение
Сообщение — короткое лёгкое уведомление, которое появляется вверху страницы после действия («Сохранено», «Не удалось загрузить», «Загрузка…») и уходит само. Оно не забирает фокус и не останавливает пользователя. Его открывают вызовом из кода, откуда угодно, а не элементом в шаблоне.
Когда использовать
- Используйте для обратной связи по действию: успех, ошибка, предупреждение или работа в процессе.
- Сообщение — для короткой обратной связи, которая ничего не блокирует. Для решения, которое должен принять пользователь, нужен диалог, а для длинного текста с заголовком — уведомление (оба в плане).
- Сообщение уходит само, поэтому не кладите в него то, что пользователь должен суметь найти снова.
Примеры
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
</script>
<!-- A call from anywhere in the code: no setup, no markup. The library makes a layer on the page by itself. -->
<Button onclick={() => message.info('This is a normal message')}>Show message</Button>
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
</script>
<!-- Five kinds. error and warning are read out at once by a screen reader; the others wait for it to finish. -->
<div class="row">
<Button onclick={() => message.info('This is an information message')}>info</Button>
<Button onclick={() => message.success('This is a success message')}>success</Button>
<Button onclick={() => message.error('This is an error message')}>error</Button>
<Button onclick={() => message.warning('This is a warning message')}>warning</Button>
<Button onclick={() => message.loading('Action in progress..')}>loading</Button>
</div>
<style>
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
duration 1 (seconds; the default is 3)
duration 6
duration 0: until it is closed from code
<script lang="ts">
import { Button, message, type MessageHandle } from 'svelte-ant-design';
// The function that a call returns closes the message.
let hide: MessageHandle | undefined;
</script>
<div class="stack">
<div class="field">
<span class="caption">duration 1 (seconds; the default is 3)</span>
<Button onclick={() => message.info('Gone in a second', 1)}>1 second</Button>
</div>
<div class="field">
<span class="caption">duration 6</span>
<Button onclick={() => message.info('Stays for six seconds', 6)}>6 seconds</Button>
</div>
<div class="field">
<span class="caption">duration 0: until it is closed from code</span>
<div class="row">
<Button onclick={() => (hide = message.loading('Stays until you close it', 0))}>Open</Button>
<Button onclick={() => hide?.()}>Close it</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, message } from 'svelte-ant-design';
// The same key updates the message in place: the box stays where it is, and a screen reader reads the new text.
function run() {
message.loading({ content: 'Loading...', key: 'updatable', duration: 0 });
setTimeout(() => message.success({ content: 'Loaded!', key: 'updatable', duration: 2 }), 1500);
}
</script>
<Button onclick={run}>Load</Button>
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
// The handle is thenable: the promise resolves when the message starts to close, so the next one comes in as
// the first one goes. (For the same reason `await message.info(...)` waits for the message to close.)
function run() {
message
.loading('Action in progress..', 2.5)
.then(() => message.success('Loading finished', 2.5))
.then(() => message.info('Loading finished is finished', 2.5));
}
</script>
<Button onclick={run}>Display sequential messages</Button>
content: string, number, snippet
content: a snippet with a button Undo pressed 0 times
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
let undone = $state(0);
</script>
<!-- A snippet can hold a link or a button. It is drawn in the layer, so it sees the context of the place where the
MessageHost is, not of this component. -->
{#snippet saved()}
Saved
<Button size="small" type="link" onclick={() => undone++}>Undo</Button>
{/snippet}
<div class="stack">
<div class="field">
<span class="caption">content: string, number, snippet</span>
<div class="row">
<Button onclick={() => message.info('A string')}>string</Button>
<Button onclick={() => message.info(0)}>number 0</Button>
</div>
</div>
<div class="field">
<span class="caption">content: a snippet with a button</span>
<Button onclick={() => message.success({ content: saved, duration: 6 })}>snippet</Button>
<span role="status">Undo pressed {undone} times</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;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
</script>
<!-- A string is shown as text (an emoji, for example), a snippet is drawn as it is, false removes the icon. -->
{#snippet star()}
<svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden="true">
<path d="M8 1l2.1 4.6 5 .5-3.8 3.4 1.1 4.9L8 11.8 3.6 14.4l1.1-4.9L.9 6.1l5-.5z" />
</svg>
{/snippet}
<div class="row">
<Button onclick={() => message.info({ content: 'A string icon', icon: '🎉' })}>string</Button>
<Button onclick={() => message.warning({ content: 'A snippet icon', icon: star })}>snippet</Button>
<Button onclick={() => message.success({ content: 'No icon', icon: false })}>false</Button>
</div>
<style>
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
</style>
class, style: on the box
classNames, styles: the parts (root, wrapper, icon, title, close)
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
</script>
<div class="stack">
<div class="field">
<span class="caption">class, style: on the box</span>
<Button
onclick={() => message.info({ content: 'Styled box', class: 'fancy', style: { 'border-radius': '24px' } })}
>
class and style
</Button>
</div>
<div class="field">
<span class="caption">classNames, styles: the parts (root, wrapper, icon, title, close)</span>
<Button
onclick={() =>
message.success({
content: 'Styled parts',
closable: 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>
<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 message 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>
pauseOnHover (the default), duration 3: keep the pointer over it
pauseOnHover: false
closable, duration 3: Tab into it, and it waits for you
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
</script>
<!-- Hover (a mouse or a pen, not a touch) and focus inside the message 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 3: keep the pointer over it</span>
<Button onclick={() => message.info('Hover me: I stay while you do')}>pauses</Button>
</div>
<div class="field">
<span class="caption">pauseOnHover: false</span>
<Button onclick={() => message.info({ content: 'I go on, whatever you do', pauseOnHover: false })}>does not pause</Button>
</div>
<div class="field">
<span class="caption">closable, duration 3: Tab into it, and it waits for you</span>
<Button onclick={() => message.warning({ content: 'Focus inside holds the timer', closable: true })}>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>
clicked 0, closed 0
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
let clicks = $state(0);
let closes = $state(0);
</script>
<!-- onclick is for a mouse or a finger only: a box cannot be reached with the keyboard. Put a button in the content
(see Content) for an action. onclose is called once, when the message starts to close, however it was closed. -->
<div class="field">
<Button onclick={() => message.info({ content: 'Click me', onclick: () => clicks++, onclose: () => closes++ })}>Open</Button>
<span role="status">clicked {clicks}, closed {closes}</span>
</div>
<style>
.field {
display: grid;
justify-items: start;
gap: 8px;
}
</style>
closable, duration 0: stays until the button is pressed
closable, duration 3
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
</script>
<!-- closable adds a button. Enter and Space press it, and Escape closes the message that has focus inside it. -->
<div class="stack">
<div class="field">
<span class="caption">closable, duration 0: stays until the button is pressed</span>
<Button onclick={() => message.info({ content: 'A message that stays', closable: true, duration: 0 })}>stays</Button>
</div>
<div class="field">
<span class="caption">closable, duration 3</span>
<Button onclick={() => message.error({ content: 'Upload failed', closable: true })}>can be closed</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>
maxCount not set
<script lang="ts">
import { Button, Switch, message } from 'svelte-ant-design';
let limited = $state(false);
let opened = $state(0);
// maxCount is a setting of message.config(); undefined takes it back to the default.
$effect(() => {
message.config({ maxCount: limited ? 3 : undefined });
return () => message.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={() => message.info({ content: `Message ${++opened}`, duration: 0 })}>Open one</Button>
<Button onclick={() => message.destroy()}>Close all</Button>
</div>
<span role="status">The oldest closes to make room: {opened} opened</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>
top: 8 (px)
<script lang="ts">
import { Button, message } from 'svelte-ant-design';
let top = $state<number | string>(8);
$effect(() => {
message.config({ top });
return () => message.config({ top: undefined });
});
</script>
<!-- top is a number (pixels) or any CSS length. -->
<div class="stack">
<div class="field">
<span class="caption">top: {typeof top === 'number' ? `${top} (px)` : `'${top}'`}</span>
<div class="row">
<Button onclick={() => (top = 8)}>8</Button>
<Button onclick={() => (top = 80)}>80</Button>
<Button onclick={() => (top = '30vh')}>'30vh'</Button>
</div>
</div>
<Button onclick={() => message.info({ content: 'Where am I?', duration: 5 })}>Show message</Button>
</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>
stack off
<script lang="ts">
import { Button, Switch, message } from 'svelte-ant-design';
let stacked = $state(false);
let opened = $state(0);
// stack is a setting of message.config(): true collapses the messages into a pile after 3 of them (or { threshold }).
$effect(() => {
message.config({ stack: stacked ? { threshold: 3 } : undefined });
return () => message.config({ stack: undefined });
});
</script>
<!-- The newest message is the first row. Past the threshold the others lie behind it; the pointer or 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, threshold 3' : 'off'}</span>
</div>
<div class="row">
<Button onclick={() => message.info({ content: `Message ${++opened}: This is a stacked message.`, closable: true, duration: 10 })}>Open</Button>
<Button onclick={() => message.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>
<MessageHost top={72} closable labels={...} /> not mounted
<script lang="ts">
import { Button, MessageHost, Switch, message } from 'svelte-ant-design';
let mounted = $state(false);
</script>
<!-- <MessageHost> draws the messages where you put it. Its props are the settings and win over message.config().
Without one the library makes its own layer. Only one host is active at a time. -->
{#if mounted}
<MessageHost top={72} closable labels={{ close: 'Dismiss', success: 'Done', error: 'Failed' }} />
{/if}
<div class="stack">
<div class="row">
<Switch bind:checked={mounted} aria-label="MessageHost" />
<span><MessageHost top={72} closable labels={...} /> {mounted ? 'mounted' : 'not mounted'}</span>
</div>
<div class="row">
<Button onclick={() => message.success('Saved')}>success</Button>
<Button onclick={() => message.error('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>
a modal dialog
<script lang="ts">
import { tick } from 'svelte';
import { Button, message } 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 message.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 message 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;
message.config({ container: inDialog ? dialog : undefined });
message.info({
key: KEY,
content: inDialog ? 'In the dialog' : 'In the body',
duration: 8,
closable: true,
class: 'container-demo'
});
await tick();
placed = dialog.contains(document.querySelector('.container-demo')) ? 'dialog' : 'body';
}
function release() {
message.destroy(KEY);
message.config({ container: undefined });
placed = null;
}
$effect(() => {
return () => message.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 message</Button>
<span class="out" role="status">
{#if placed === 'body'}
The layer is in the body. The dialog covers it, and the message 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 message</Button>
<span class="out" role="status">
{#if placed === 'dialog'}
The layer is in the dialog. The message 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
Параметры сообщения
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| type | Вид сообщения. Только для message.open; у типизированных методов он задан. | 'info' | 'success' | 'error' | 'warning' | 'loading' | 'info' |
| content | Текст или содержимое: строка, число (0 показывается) или snippet. | string | number | Snippet | — |
| duration | Секунды до ухода сообщения. 0 оставляет его, пока не закроют. Отрицательное или не конечное значение заменяется значением по умолчанию, при разработке с предупреждением. | number | 3 |
| icon | Заменяет иконку вида: строка (показывается как текст), snippet или false, чтобы убрать. | string | Snippet | false | the icon of the type |
| key | Вызов с ключом открытого сообщения обновляет его на месте (новые вид, содержимое и параметры, таймер запускается заново). Без ключа он создаётся сам. | string | number | generated |
| pauseOnHover | Удерживает таймер, пока курсор (мышь или перо) над блоком. Фокус внутри и скрытая страница удерживают его независимо от этого значения. | boolean | true |
| closable | Показывает кнопку закрытия. В Ant Design такой опции нет. | boolean | false |
| class | Дополнительные классы блока. | string | — |
| style | Инлайн-стиль блока: строка или объект CSS-свойств (kebab-case или custom properties; числа записываются как есть). | string | Record<string, string | number> | — |
| classNames | Дополнительные классы для частей root, wrapper, icon, title и close. Значение здесь важнее значения хоста и message.config(). | { root?, wrapper?, icon?, title?, close? } | — |
| styles | Инлайн-стили для тех же частей, объектами. | { root?, wrapper?, icon?, title?, close? } | — |
| onclick | Вызывается с событием при клике по блоку, но не по его кнопке закрытия. До блока нельзя добраться с клавиатуры: для действия положите кнопку в содержимое. | (event: MouseEvent) => void | — |
| onclose | Вызывается один раз, когда сообщение начинает закрываться, как бы его ни закрыли (таймер, возвращённая функция, destroy, maxCount, кнопка закрытия, Escape). | () => void | — |
Методы
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| message.open(options) | Открывает сообщение вида options.type (по умолчанию info) или обновляет открытое с тем же key. | MessageHandle | — |
| message.info | success | error | warning | loading(content, duration?, onclose?) | По методу на каждый вид. Без окна (на сервере) любой вызов ничего не делает и возвращает неактивный handle. | MessageHandle | — |
| message.info | success | error | warning | loading(options) | То же с объектом параметров (без type). | MessageHandle | — |
| message.destroy(key?) | Закрывает сообщение с этим ключом или все сообщения. Каждое проходит обычный уход и вызывает свой onclose. | void | — |
| message.config(options) | Задаёт значения по умолчанию для всех сообщений с этого момента (таблица настроек ниже). Настройка, переданная как { top: undefined }, возвращается к значению по умолчанию. | void | — |
| handle() | Что возвращает вызов: функция, закрывающая сообщение. Закрытие сообщения, которое уже закрывается или закрыто, ничего не делает. | () => void | — |
| handle.then(onfulfilled) | Handle — thenable: промис выполняется, когда сообщение начинает закрываться. Поэтому await handle ждёт закрытия. | PromiseLike<void> | — |
Настройки: message.config() и пропсы MessageHost
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| top | Расстояние от верха окна до первого сообщения. Число — пиксели. Без него — токен --ads-message-top (8px). | number | string | 8 |
| duration | duration по умолчанию для каждого сообщения, в секундах. | number | 3 |
| maxCount | Не больше стольких открытых сообщений: самое старое закрывается, чтобы освободить место. Значение меньше 1 или не конечное игнорируется. | number | — |
| container | Куда переносится слой: элемент или функция, которая его возвращает. По умолчанию document.body. | HTMLElement | (() => HTMLElement) | document.body |
| closable | Значение closable по умолчанию для каждого сообщения. | boolean | false |
| labels | Слово, которое слышит скринридер перед текстом (info, success, error, warning, loading: «Error: Upload failed») и имя кнопки закрытия (close). Передайте перевод; пустая строка убирает слово вида. | Partial<Record<'info' | 'success' | 'error' | 'warning' | 'loading' | 'close', string>> | 'Info', 'Success', 'Error', 'Warning', 'Loading', 'Close' |
| classNames | Значения по умолчанию для частей каждого сообщения и две части слоя: list (фиксированный слой) и listContent (колонка строк). | { root?, wrapper?, icon?, title?, close?, list?, listContent? } | — |
| styles | То же для инлайн-стилей, объектами. | { root?, wrapper?, icon?, title?, close?, list?, listContent? } | — |
| stack | true или { threshold }: самое новое сообщение — первая строка, а после порога (3) остальные ложатся за ним стопкой, которую раскрывают курсор или фокус. Есть в React 6.4.0, нет в Vue и Angular. | boolean | { threshold?: number } | false |
Отличия от Ant Design: слой создаёт сама библиотека (
useMessage и contextHolder из React заменяет <MessageHost>); роль по виду и скрытое слово вида (React: role="alert" у всех, Vue и Angular: нет); closable новый, а таймер ждёт ещё и фокус со скрытой страницей; duration в секундах, как в React и Vue (Angular: миллисекунды); stack есть только в React 6.4.0. Не взяты: алиас warn из Vue, prefixCls и rtl (направление наследуется). API вдохновлён Ant Design (MIT); реализация оригинальная для Svelte.Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-message-z-index | Слой сообщений, выше любого всплывающего окна (у подсказки 1070). | 2010 |
| --ads-message-top | Расстояние от верха до первого сообщения, если top не задан. | 8px |
| --ads-message-gap | Промежуток между двумя сообщениями. | 16px |
| --ads-message-margin-inline | Свободное место у левого и правого края окна. | 24px |
| --ads-message-bg | Фон блока. В тёмной теме #1f1f1f. | #ffffff |
| --ads-message-color | Цвет текста. В тёмной теме 85% белого. | rgba(0, 0, 0, 0.88) |
| --ads-message-padding | Внутренние отступы блока. | 9px 12px |
| --ads-message-line-height | Высота строки текста и иконки, поэтому блок высотой 40px с иконкой и без неё. | 22px |
| --ads-message-radius | Радиус углов блока. | 8px |
| --ads-message-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-message-icon-size | Размер иконки. | 16px |
| --ads-message-icon-gap | Промежуток между иконкой, текстом и кнопкой закрытия. | 8px |
| --ads-message-icon-info | Цвет иконок info и loading. | #1677ff |
| --ads-message-icon-success | Цвет иконки success. tokens-accessible.css затемняет её до #389e0d (3:1 на белом блоке). | #52c41a |
| --ads-message-icon-error | Цвет иконки error. | #ff4d4f |
| --ads-message-icon-warning | Цвет иконки warning. tokens-accessible.css затемняет её до #c27c00. | #faad14 |
| --ads-message-close-size | Размер кнопки закрытия: 24px, минимальная цель по WCAG 2.5.8. | 24px |
| --ads-message-close-color | Цвет кнопки закрытия (4.5:1 на блоке). | rgba(0, 0, 0, 0.65) |
| --ads-message-close-color-hover | Цвет кнопки закрытия при наведении. | rgba(0, 0, 0, 0.88) |
| --ads-message-close-bg | Фон кнопки закрытия в покое: он показывает, где кнопка. | rgba(0, 0, 0, 0.04) |
| --ads-message-close-bg-hover | Фон кнопки закрытия при наведении. | rgba(0, 0, 0, 0.1) |
| --ads-message-motion-offset | На сколько выше своего места сообщение начинает появляться и заканчивает уходить. | 64px |
| --ads-message-stack-offset | Шаг между строками стопки. | 8px |
| --ads-message-stack-scale-step | Насколько каждая строка стопки меньше предыдущей. | 0.06 |
Доступность
errorиwarning— этоrole="alert", их зачитывают сразу;info,successиloading—role="status", они ждут, пока скринридер закончит. В Ant Design Reactrole="alert"у всех пяти, в Vue и Angular нет ни одной.- Иконка декоративна. Скрытое слово перед текстом называет вид («Error: Upload failed»), так что вид передаётся не только цветом и формой. Переводы передавайте в
labels: системы локалей в библиотеке пока нет, по умолчанию английский. - Сообщение никогда не забирает фокус. Без
closableв нём нечего фокусировать; с ним — только кнопку закрытия (24px, размер цели по WCAG 2.5.8).Escapeзакрывает сообщение, в котором стоит фокус. - Таймер ждёт, пока курсор над сообщением, пока фокус внутри и пока страница скрыта. Сообщению, которое должно остаться, нужен
duration: 0, аclosableпозволяет пользователю его убрать. - Слой — последний элемент своего контейнера, поэтому с клавиатуры до кнопки закрытия добираются только после остальной страницы, а сочетания клавиш для перехода к сообщениям нет. Скринридер зачитывает сообщение, когда оно открывается.
- Контраст: текст — около 15:1 на блоке, а иконки видов держатся не ниже 3:1 (в тёмной теме и в светлой с
tokens-accessible.css, который затемняет зелёный и жёлтый). - В режимах forced-colors, например Windows High Contrast, блок и кнопка закрытия рисуются с рамкой. Анимация (блок появляется сверху и проявляется) отключена при
prefers-reduced-motion; таймер тот же. - Проверено настоящим скринридером (Orca с Firefox): он читает роль, слово вида, текст, новый текст после обновления и имя кнопки закрытия. Не проверено: объявляет ли скринридер сообщение при его появлении (в нашей настройке Orca не озвучивает даже обычный
role="alert"), NVDA, JAWS, VoiceOver, скринридер телефона, настоящее сенсорное устройство и настоящий Safari.