Notification
Глобальные уведомления: положения, время показа, действия, обновление и очередь.
Когда использовать
notification показывает событие с заголовком, подробностями и дальнейшими действиями. Он подходит для фонового экспорта, завершения длительной операции или сообщения приложения. Для короткого отклика достаточно Message; важное постоянное предупреждение размещайте также в основном содержимом.
CSS-префиксы notification показывают общий ConfigProvider.prefixCls и локальный prefixCls без сброса состояния. NotificationHolder меняет классы всех placements и частей карточки. У App используется notification.prefixCls. Очередь, таймеры, фокус и нативная поверхность сохраняются.
Экземпляр, содержимое и положение
Создайте createNotification и разместите один NotificationHolder внутри нужного ConfigProvider. Экземпляр имеет независимую очередь для всех положений; отдельным областям нужны отдельные экземпляры.
| Задача | Возможность | Пример |
|---|---|---|
| Показать подробное событие | open, title, description |
Основное уведомление |
| Выбрать смысловой статус | success/info/warning/error |
Типы |
| Показать время до закрытия | duration, showProgress, pauseOnHover |
Время показа |
| Свернуть список в одном положении | stack |
Стек уведомлений |
| Выбрать положение и контейнер | placement, getContainer |
Размещение |
| Заменить ожидание результатом | одинаковый key, actions |
Обновление |
| Выполнить фоновую задачу | модель приложения | Экспорт отчёта |
В title и description можно передать текст, число или сниппет. Для кнопок и ссылок используйте actions. Свойство placement задаёт одно из шести положений относительно краёв экрана. Если задать rtl, текст пойдёт справа налево, а выбранный край останется прежним.
Обновление и время показа
Повторный open с тем же key обновляет запись, включая текст, actions, type и placement. Чтобы сохранить DOM описания при смене статуса, задавайте type уже при открытии, например info: появление либо удаление значка может пересоздать обёртку содержимого.
По умолчанию уведомление закрывается через 4,5 секунды. duration: 0 или duration: false оставляет его открытым. При положительной длительности showProgress показывает оставшееся время. Полоса останавливается вместе с таймером, когда пользователь наводит указатель при включённом pauseOnHover или переводит фокус внутрь карточки. В примере экспорта компонент Progress показывает, какая часть отчёта готова.
С помощью closable можно изменить значок, подпись или доступность кнопки закрытия. Если скрываете кнопку у постоянного уведомления, предусмотрите собственное действие закрытия. onClose срабатывает в начале закрытия карточки, а onAllRemoved — когда последняя карточка исчезнет из DOM.
По умолчанию четвёртая карточка в одном положении сворачивает список. Наведение или фокус внутри стека раскрывают все карточки. Порог можно изменить через stack.threshold, а stack: false оставляет список раскрытым. Если нужно закрывать самые старые уведомления, задайте maxCount. Этот лимит действует сразу для всех положений экземпляра.
Контекст, оформление и ограничения
Holder получает локальную тему и направление из ConfigProvider. theme.components.Notification меняет width, zIndexPopup и фоны статусов без повторного открытия. Локальные CSS-переменные holder и записи имеют приоритет.
Без компонентного override фоны статусов используют colorBgElevated, а не общий colorInfoBg/colorSuccessBg. Пустая конфигурация возвращает стандартную ширину 384px. Явный width:undefined — отдельный случай; для заданного размера используйте число либо CSS-длину, не предполагая режим max-content.
Для доступных кнопок и ссылок используйте actions. Через props можно назначить карточке HTML-атрибуты, например data-* или ARIA. onClick получает событие нажатия на карточку. У кнопки закрытия отдельный обработчик.
Через ConfigProvider.notification можно задать общую иконку закрытия, классы и стили. Параметры classNames и styles принимают объект или функцию от { props }. Настройки провайдера, экземпляра и карточки применяются в этом порядке. Пример оформления.
getContainer вызывается в браузере. Если функция не вернула узел, библиотека использует ConfigProvider.getPopupContainer, затем document.body. Если обе функции отсутствуют, список остаётся рядом с держателем.
Вместо ручной пары createNotification/NotificationHolder можно использовать App: App.useApp() возвращает notification из ближайшей области. Её defaults наследуются по полям, а родительские и вложенные очереди независимы. Смена App.notification.placement применяется к новым уведомлениям.
Примеры
Обычное уведомление
createNotification и один holder.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
</script>
<NotificationHolder {notification} top={240} id="notification-basic-notices" />
<Button onclick={() => notification.open(({
title: 'Документация обновлена',
description: 'В каталоге появились новые примеры компонентов.'
}))}>{("Показать обычное уведомление")}</Button>
Стандартные значки
success, info, warning и error.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
const types = ['success', 'info', 'warning', 'error'] as const;
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-types-notices" />
<div class="actions">{#each types as type (type)}
<Button onclick={() => notification[type](({
key: type,
title: `Статус: ${type}`,
description: 'Стандартный значок состояния.',
duration: 0
}))}>{(type)}</Button>
{/each}<Button
onclick={() => notification.destroy()}
>{("Убрать уведомления типов")}</Button></div>
Время показа
Полоса показывает, сколько времени осталось до закрытия.
<script lang="ts">
import {
Button,
Checkbox,
InputNumber,
NotificationHolder,
createNotification
} from '@woodger/antd';
const notification = createNotification();
let duration = $state(4.5);
let permanent = $state(false);
let pauseOnHover = $state(true);
let showProgress = $state(true);
let closed = $state(0);
</script>
<style>
.settings {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
}
output {
display: block;
margin-top: 16px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-duration-notices" />
<div class="settings">
<InputNumber
aria-label={("Длительность Notification")}
min={0}
max={10}
step={0.5}
value={duration}
onValueChange={next => { duration = next ?? 0; }}
/>
<Checkbox bind:checked={permanent}>{("Без автоматического закрытия")}</Checkbox>
<Checkbox bind:checked={showProgress} disabled={permanent || duration === 0}>
{('Показывать оставшееся время')}
</Checkbox>
<Checkbox
bind:checked={pauseOnHover}
>{("Пауза Notification при наведении")}</Checkbox>
<Button onclick={() => notification.info(({
key: 'duration',
title: 'Время показа',
description: 'Наведите указатель или перейдите к кнопке закрытия.',
duration: permanent ? false : duration,
pauseOnHover,
showProgress,
onClose: () => { closed++; }
}))}>{("Показать с выбранной длительностью")}</Button>
</div>
<output
aria-label={("Закрытия Notification")}
>{("Закрыто: ")}{closed}</output>
Своё закрытие
Текст, доступное имя, disabled и скрытая кнопка.
<script lang="ts">
import { Button, Checkbox, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification({ placement: 'bottomLeft' });
let disabled = $state(false);
let hidden = $state(false);
</script>
<style>
.settings {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-close-notices" />
<div
class="settings"
><Checkbox
bind:checked={disabled}
>{("Отключить кнопку закрытия")}</Checkbox>
<Checkbox bind:checked={hidden}>{("Скрыть кнопку закрытия")}</Checkbox>
<Button onclick={() => notification.open(({
key: 'close',
title: 'Своё закрытие',
description: 'Настройки применяются при показе или обновлении записи.',
duration: 0,
closable: hidden ? false : {
disabled,
closeIcon: 'Готово',
'aria-label': 'Завершить уведомление'
}
}))}>{("Показать своё закрытие")}</Button>
<Button
onclick={() => notification.destroy('close')}
>{("Убрать уведомление вручную")}</Button></div>
Свой значок и оформление
Общее оформление заголовка и рамки, свой цвет значка для одной карточки.
<script lang="ts">
import { Button, ConfigProvider, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
const appearance = {
classNames: { title: 'notification-custom-title' },
styles: { root: 'border: 1px dashed var(--ant-color-warning)' }
};
function showNotice() {
notification.open({
title: ('Собственное оформление'),
description,
icon,
duration: 5,
class: 'notification-custom',
styles: {
root: 'border-radius: 12px',
icon: 'color: var(--ant-color-warning)'
}
});
}
</script>
<style>
:global(.notification-custom-title) { font-weight: 600; }
</style>
{#snippet icon()}<span aria-hidden="true">★</span>{/snippet}
{#snippet description()}
<span>{('Подпись из ')}<strong>Svelte Snippet</strong>{(' с собственным оформлением.')}</span>
{/snippet}
<ConfigProvider notification={appearance}>
<NotificationHolder {notification} top={240} id="notification-custom-notices" />
<Button onclick={showNotice}>{('Показать свой значок Notification')}</Button>
</ConfigProvider>
Положения
Шесть положений на экране, выбор контейнера и направление текста.
<script lang="ts">
import {
Button,
Checkbox,
NotificationHolder,
RadioGroup,
createNotification,
type NotificationPlacement
} from '@woodger/antd';
const notification = createNotification();
const placements: NotificationPlacement[] = [
'top', 'topLeft', 'topRight', 'bottom', 'bottomLeft', 'bottomRight'
];
let placement = $state<NotificationPlacement>('topRight');
let container = $state<HTMLDivElement>();
let rtl = $state(false);
</script>
<style>
.settings {
display: grid;
gap: 20px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
<NotificationHolder {notification} rtl={rtl || undefined} getContainer={() => container}
top={240} bottom={24} id="notification-placement-notices" />
<div bind:this={container} class="settings">
<RadioGroup
aria-label={("Положение примера Notification")}
bind:value={placement}
options={(placements)}
/>
<Checkbox bind:checked={rtl}>{('Текст справа налево')}</Checkbox>
<div class="actions"><Button onclick={() => notification.info(({
key: placement,
title: `Положение: ${placement}`,
description: 'Физическая область экрана.',
placement,
duration: 0
}))}>{("Показать в выбранном положении")}</Button>
<Button
onclick={() => notification.destroy()}
>{("Очистить положения Notification")}</Button></div></div>
Обновление и действия
Один key, новый результат и кнопка принятия.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
let accepted = $state(0);
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
}
</style>
{#snippet actions()}<Button type="primary" onclick={() => {
accepted++;
notification.destroy('review');
}}>{("Принять результат уведомления")}</Button>{/snippet}
<NotificationHolder {notification} top={240} id="notification-update-notices" />
<div class="actions">
<Button onclick={() => notification.info(({
key: 'review',
title: 'Проверяем документ',
description: 'Ожидаем результат проверки.',
duration: 0
}))}>{("Начать проверку Notification")}</Button>
<Button onclick={() => notification.success(({
key: 'review',
title: 'Документ проверен',
description: 'Можно принять результат.',
actions,
duration: 0
}))}>{("Завершить проверку Notification")}</Button>
<Button onclick={() => notification.destroy('review')}>
{("Убрать проверку Notification")}
</Button>
</div>
<output
aria-label={("Действия Notification")}
>{("Принято: ")}{accepted}</output>
Ограничение очереди
При добавлении четвёртого уведомления самое старое закрывается.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification({ maxCount: 3, duration: 0, placement: 'bottomLeft' });
let sequence = $state(0);
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-queue-notices" />
<div class="actions"><Button onclick={() => notification.info(({
title: `Уведомление очереди №${++sequence}`,
description: 'Общий лимит — три записи.'
}))}>{("Добавить в очередь Notification")}</Button>
<Button
onclick={() => notification.destroy()}
>{("Очистить очередь Notification")}</Button></div>
Стек уведомлений
Добавьте четыре отчёта. Наведите указатель или переведите фокус в стек.
<script lang="ts">
import {
Button, Checkbox, Flex, InputNumber, NotificationHolder, createNotification
} from '@woodger/antd';
const thresholdId = $props.id();
const notification = createNotification({ duration: 0, placement: 'bottomRight' });
let enabled = $state(true);
let threshold = $state(3);
let hasReports = $state(false);
let sequence = 0;
function reportReady() {
sequence += 1;
notification.success({
title: ('Отчёт готов'),
description: `report-${sequence}.csv`
});
hasReports = true;
}
</script>
<NotificationHolder {notification} stack={enabled ? { threshold } : false}
onAllRemoved={() => { hasReports = false; }} />
<Flex vertical align="start" gap="medium">
<Flex align="center" wrap gap="small">
<Checkbox bind:checked={enabled}>{('Сворачивать список')}</Checkbox>
<label for={thresholdId}>{('Порог сворачивания')}</label>
<InputNumber id={thresholdId} value={threshold} min={1} max={10} step={1} precision={0}
disabled={!enabled} onValueChange={value => { threshold = value ?? 1; }} />
</Flex>
<Flex wrap gap="small">
<Button type="primary" onclick={reportReady}>
{('Сообщить о готовом отчёте')}
</Button>
<Button disabled={!hasReports} onclick={() => notification.destroy()}>
{('Очистить уведомления')}
</Button>
</Flex>
</Flex>
Компонентная тема notification
Ширина, фоны статусов и слой. Смена темы сохраняет комментарий в actions, очередь и срок закрытия.
<script lang="ts">
import {
Button,
Checkbox,
ConfigProvider,
Input,
NotificationHolder,
RadioGroup,
createNotification
} from '@woodger/antd';
import type { NotificationType } from '@woodger/antd';
const notification = createNotification({ pauseOnHover: false });
let enabled = $state(true);
let resetWidth = $state(false);
let status = $state<NotificationType>('info');
let comment = $state(('Черновик комментария'));
const types = ['info', 'success', 'warning', 'error'] as const;
const tokens = {
zIndexPopup: 2400,
progressBg: '#d48806',
colorInfoBg: '#fffbe6',
colorSuccessBg: '#f6ffed',
colorWarningBg: '#fff7e6',
colorErrorBg: '#fff1f0'
};
</script>
<style>
.settings {
display: grid;
gap: 24px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.status-settings, .notice-actions {
display: grid;
gap: 12px;
min-width: 0;
max-width: 100%;
}
label {
display: grid;
gap: 8px;
}
</style>
{#snippet actions()}
<div class="notice-actions">
<label>{("Комментарий\n ")}<Input bind:value={comment} aria-label={("Комментарий темы Notification")} />
</label>
<Button onclick={() => notification.destroy('theme')}>{("Готово")}</Button>
</div>
{/snippet}
<ConfigProvider direction="rtl" theme={{
cssVar: { prefix: 'notification-demo' },
token: { colorInfoBg: '#fffbe6' },
components: { Notification: enabled ? { ...tokens, width: resetWidth ? undefined : 480 } : {} }
}}>
<NotificationHolder {notification} top={240} bottom={24} id="notification-theme-notices" />
<div class="settings">
<Checkbox bind:checked={enabled}>{("Применить токены Notification")}</Checkbox>
<Checkbox bind:checked={resetWidth} disabled={!enabled}>
{("Передать width: undefined")}
</Checkbox>
<div class="status-settings">
<span>{("Статус уведомления")}</span>
<RadioGroup
aria-label={("Статус темы Notification")}
bind:value={status}
options={(types)}
style="
display: flex;
flex-wrap: wrap;
gap: 8px;
"
/>
</div>
<div class="actions">
<Button onclick={() => notification.open(({
key: 'theme', type: status, title: 'Тема Notification',
description: 'Тема обновляется без сброса комментария и действий.', actions, duration: 0
}))}>{("Проверить тему Notification")}</Button>
<Button onclick={() => notification.info(({
key: 'timed-theme', title: 'Уведомление на две секунды',
description: 'Переключение темы не продлевает показ.', duration: 2, showProgress: true,
class: 'notification-theme-timed'
}))}>{("Показать на 2 секунды")}</Button>
</div>
</div>
</ConfigProvider>
Экспорт отчёта
Прогресс операции, успех, ошибка, повтор, отмена и настоящий CSV.
NotificationExample.svelte<script lang="ts"> import { onDestroy } from 'svelte'; import { Button, Checkbox, NotificationHolder, Progress, Select, createNotification, type NotificationPlacement } from '@woodger/antd'; import { createNotificationExport } from './notification-export.model.svelte'; const notification = createNotification({ maxCount: 3 }); let failNext = $state(false); let placement = $state<NotificationPlacement>('topRight'); let result = $state(('Подготовьте отчёт и скачайте его из уведомления.')); let downloadUrl: string | undefined; const placements = ['top', 'topLeft', 'topRight', 'bottom', 'bottomLeft', 'bottomRight'].map( (value) => ({ value: value as NotificationPlacement, label: value }) ); const model = createNotificationExport({ onReady() { result = ('Отчёт готов к скачиванию.'); notification.success( ({ key: 'export', title: 'Отчёт готов', description: progress, placement, duration: 0, actions: ready, role: 'status' }) ); }, onError() { result = ('Не удалось подготовить отчёт. Повторите попытку.'); notification.error( ({ key: 'export', title: 'Не удалось подготовить отчёт', description: progress, placement, duration: 0, actions: retry }) ); } }); function releaseDownload() { if (downloadUrl) URL.revokeObjectURL(downloadUrl); downloadUrl = undefined; } function start() { const failed = failNext; if (!model.start(failed)) { return; } failNext = false; releaseDownload(); result = ('Готовим отчёт…'); notification.info( ({ key: 'export', title: 'Готовим отчёт', description: progress, actions: pending, placement, duration: 0, role: 'status' }) ); } function cancel() { if (!model.cancel()) { return; } result = ('Экспорт отменён.'); notification.info( ({ key: 'export', title: 'Экспорт отменён', description: progress, placement, duration: 0, actions: retry, role: 'status' }) ); } function download() { const report = model.report; if (!report) { return; } releaseDownload(); downloadUrl = URL.createObjectURL(new Blob([report], { type: 'text/csv;charset=utf-8' })); const link = document.createElement('a'); link.href = downloadUrl; link.download = 'report.csv'; document.body.append(link); link.click(); link.remove(); result = ('Отчёт скачан.'); } function reset() { model.reset(); releaseDownload(); notification.destroy(); result = ('Пример экспорта сброшен.'); } onDestroy(() => { model.destroy(); releaseDownload(); }); </script> <style> .actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; } .placement { width: 180px; } output { display: block; margin-top: 20px; color: var(--ant-color-text-secondary); } .phase { margin-block: 0 var(--ant-margin-sm); } </style> {#snippet progress()}<p class="phase">{(model.phase)}</p><Progress percent={model.percent} status={model.status === 'preparing' ? 'active' : model.status === 'error' ? 'exception' : undefined} aria-label={("Подготовка отчёта")} />{/snippet} {#snippet pending()}<Button onclick={cancel}>{("Отменить экспорт")}</Button>{/snippet} {#snippet retry()}<Button type="primary" onclick={start} >{("Повторить экспорт")}</Button>{/snippet} {#snippet ready()} <span class="actions"><Button type="primary" onclick={download}> {("Скачать отчёт")} </Button><Button onclick={() => notification.destroy('export')} >{("Закрыть результат экспорта")}</Button></span> {/snippet} <NotificationHolder {notification} id="showcase-notifications" /> <div class="actions" ><Button type="primary" loading={model.status === 'preparing'} onclick={start} >{("Экспортировать отчёт")}</Button><Checkbox bind:checked={failNext} >{("Ошибка следующего экспорта")}</Checkbox><div class="placement" ><Select aria-label={("Положение Notification")} bind:value={placement} options={(placements)} /></div><Button onclick={reset} >{("Сбросить пример Notification")}</Button></div> <output aria-label={("Результат примера Notification")}>{result}</output>notification-export.model.svelte.tstype ExportState = | { status: 'idle'; percent: 0; phase: string } | { status: 'preparing'; percent: number; phase: string } | { status: 'ready'; percent: 100; phase: string; report: string } | { status: 'error' | 'cancelled'; percent: number; phase: string }; export function createNotificationExport(callbacks: { onReady: () => void; onError: () => void }) { let state = $state.raw<ExportState>({ status: 'idle', percent: 0, phase: "Подготовьте отчёт." }); let generation = 0; let active = true; const timers = new Set<ReturnType<typeof setTimeout>>(); function clear() { generation++; for (const timer of timers) clearTimeout(timer); timers.clear(); } function start(failed = false): boolean { if (!active || state.status === 'preparing') { return false; } clear(); const current = generation; state = { status: 'preparing', percent: 0, phase: "После подготовки здесь появится кнопка скачивания." }; function schedule(delay: number, update: () => void) { const timer = setTimeout( () => { timers.delete(timer); if (active && current === generation && state.status === 'preparing') update(); }, delay ); timers.add(timer); } for (const stage of [ { delay: 200, percent: 25, phase: "Собираем данные…" }, { delay: 450, percent: 65, phase: "Формируем CSV…" }, { delay: 600, percent: 90, phase: "Проверяем файл…" } ]) { schedule( stage.delay, () => { state = { status: 'preparing', percent: stage.percent, phase: stage.phase }; } ); } schedule(700, () => { if (failed) { state = { status: 'error', percent: 90, phase: "Данные сохранены. Попробуйте выполнить экспорт ещё раз." }; callbacks.onError(); } else { state = { status: 'ready', percent: 100, phase: "CSV-файл содержит две записи. Его можно скачать сейчас.", report: '\uFEFFname,framework\r\nAnna,Svelte\r\nBoris,TypeScript\r\n' }; callbacks.onReady(); } }); return true; } return { get status() { return state.status; }, get percent() { return state.percent; }, get phase() { return state.phase; }, get report() { return state.status === 'ready' ? state.report : undefined; }, start, cancel() { if (state.status !== 'preparing') { return false; } clear(); state = { status: 'cancelled', percent: state.percent, phase: "Подготовка отчёта отменена." }; return true; }, reset() { clear(); state = { status: 'idle', percent: 0, phase: "Подготовьте отчёт." }; }, destroy() { active = false; clear(); } }; }
NotificationHolder меняет классы всех placements и частей карточки. У App используется notification.prefixCls. Очередь, таймеры, фокус и нативная поверхность сохраняются.
CSS-префиксы notification
Общий namespace ConfigProvider и локальный prefixCls; состояние компонента сохраняется при смене имени.
<script lang="ts">
import {
Checkbox,
ConfigProvider,
NotificationHolder,
createNotification,
Button
} from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-notification' : '');
const notification = createNotification({ duration: 0 });
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("Общий префикс Notification suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Локальный префикс Notification")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'notification-theme' } }}>
<div class="prefix-stage">
<NotificationHolder {notification} prefixCls={localPrefix} top={240} />
<Button onclick={() => notification.success(({
key: 'prefix',
title: 'Уведомление с префиксом',
description: 'Смена namespace сохраняет текущую карточку.'
}))}>{("Показать Notification с префиксом")}</Button>
<Button onclick={() => notification.destroy()}>
{("Закрыть Notification с префиксом")}
</Button>
</div>
</ConfigProvider>
<output
aria-label={("CSS-префикс Notification")}
>{("Общий: ")}{prefix}{("; локальный: ")}{(localPrefix
|| ('из провайдера'))}</output>
<p>
{("NotificationHolder меняет классы всех placements и частей карточки. У App используется notification.prefixCls. Очередь, таймеры, фокус и нативная поверхность сохраняются.")}
</p>
</div>
API
| Тема | Пример или ограничение |
|---|---|
| Hooks usage (recommended) | Svelte: createNotification и один NotificationHolder в нужном контексте. |
| Duration after which the notification box is closed | Секунды, false/0 и пауза при наведении. |
| Notification with icon | Четыре стандартных статуса. |
| Custom close button | Своя подпись, доступное имя, disabled и скрытие кнопки. |
| Customized Icon | Snippet значка и описания. |
| Placement | Все шесть физических областей экрана. |
| Update Message Content | Обновление по key и действие внутри уведомления. |
| Stack | Порог сворачивания списка и раскрытие с клавиатуры или при наведении. |
| Show with progress | Индикатор оставшегося времени следует за таймером уведомления. |
| Customize progress bar color | Цвет полосы задаёт progressBg в теме notification. |
| Custom semantic styles | Общие классы и стили провайдера можно дополнить для одной карточки. |
NotificationInstance
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
open | Создать или обновить запись по key. | (config: NotificationConfig) => void | — |
info | Информационный статус. | (config) => void | info |
success | Успешная операция. | (config) => void | success |
warning | Предупреждение. | (config) => void | warning |
error | Ошибка. | (config) => void | error |
destroy | Закрыть одну запись или всю очередь. | (key?: string | number) => void | — |
NotificationConfig
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
title | Заголовок и доступное имя. | NotificationContent | — |
description | Подробности уведомления. | NotificationContent | — |
actions | Кнопки и ссылки дальнейших действий. | NotificationContent | — |
type | Стандартный значок состояния. | success | info | warning | error | — |
icon | Собственный значок. | NotificationContent | по type |
key | Идентификатор обновления без дублирования записи. | string | number | генерируется |
placement | top/bottom, topLeft/topRight, bottomLeft/bottomRight. | NotificationPlacement | topRight |
duration | Секунды; false и 0 отключают таймер. | number | false | 4.5 |
pauseOnHover | Пауза таймера под указателем. | boolean | true |
closable | Настройки стандартной кнопки закрытия. | boolean | NotificationClosable | true |
closeIcon | Своя подпись; false/null скрывают кнопку. | NotificationContent | крестик |
role | Срочность объявления. | alert | status | alert |
onClose | Начало закрытия. Unmount holder callback не вызывает. | () => void | — |
class | Класс корня записи. | string | — |
style | CSS корня записи. | string | — |
classNames | Классы отдельных частей карточки. | NotificationSemantic | — |
styles | Стили отдельных частей карточки. | NotificationSemantic | — |
showProgress | Показывает, сколько времени осталось до закрытия. | boolean | false |
props | Нативные атрибуты карточки, включая data-* и ARIA. | NotificationRootAttributes | — |
onClick | Нажатие на карточку. Кнопка закрытия обрабатывает нажатие отдельно. | (event: MouseEvent) => void | — |
NotificationClosable
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
disabled | Отключить стандартную кнопку. | boolean | false |
closeIcon | Имеет приоритет над closeIcon конфигурации. | NotificationContent | крестик |
aria-label | Доступное имя кнопки. | string | locale.closeText |
onClose | Вызывается перед onClose карточки при закрытии кнопкой или по таймеру. | () => void | — |
createNotification options
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
placement | Общее положение экземпляра. | NotificationPlacement | topRight |
duration | Общая длительность. | number | false | 4.5 |
pauseOnHover | Общая пауза таймера. | boolean | true |
maxCount | Общий лимит для всех placements. | number | без лимита |
showProgress | Показывает, сколько времени осталось до закрытия. | boolean | false |
prefixCls | Полный префикс списка и его карточек. | string | ConfigProvider.prefixCls + "-notification" |
top | Верхний отступ поверхности. | number | 24 |
bottom | Нижний отступ поверхности. | number | 24 |
stack | Порог сворачивания в каждом положении. false оставляет список раскрытым. | boolean | { threshold?: number } | { threshold: 3 } |
rtl | Направление текста. Положение карточек на экране задаёт placement. | boolean | ConfigProvider.direction |
getContainer | Выбирает узел для списка уведомлений в браузере. | () => HTMLElement | ShadowRoot | null | undefined | — |
closeIcon | Своя иконка закрытия для всех карточек. | NotificationContent | ConfigProvider.notification.closeIcon |
classNames | Классы списка и карточек для этого экземпляра. | NotificationSemantic | — |
styles | Стили списка и карточек для этого экземпляра. | NotificationSemantic | — |
onAllRemoved | Вызывается после удаления последней карточки из DOM. | () => void | — |
NotificationHolder
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
prefixCls | Полный префикс списка и его карточек. | string | ConfigProvider.prefixCls + "-notification" |
top | Верхний отступ поверхности. | number | 24 |
bottom | Нижний отступ поверхности. | number | 24 |
stack | Порог сворачивания в каждом положении. false оставляет список раскрытым. | boolean | { threshold?: number } | { threshold: 3 } |
rtl | Направление текста. Положение карточек на экране задаёт placement. | boolean | ConfigProvider.direction |
getContainer | Выбирает узел для списка уведомлений в браузере. | () => HTMLElement | ShadowRoot | null | undefined | — |
closeIcon | Своя иконка закрытия для всех карточек. | NotificationContent | ConfigProvider.notification.closeIcon |
classNames | Классы списка и карточек для этого экземпляра. | NotificationSemantic | — |
styles | Стили списка и карточек для этого экземпляра. | NotificationSemantic | — |
onAllRemoved | Вызывается после удаления последней карточки из DOM. | () => void | — |
notification | Экземпляр очереди; один подключённый holder. | NotificationInstance | обязателен |
id | Идентификатор поверхности со всеми placements. | string | — |
class | Класс поверхности. | string | — |
style | CSS поверхности. | string | — |
Вместо React hook/static methods используются независимый createNotification и NotificationHolder. Методы открытия возвращают void; закрытие выполняет destroy(key) или стандартная кнопка.
Semantic DOM
Слоты list и listContent относятся к списку, остальные — к карточке.
| Слот | CSS-класс | Назначение |
|---|---|---|
list | .ant-notification-list | Группа отдельного placement. |
listContent | .ant-notification-list-content | Список записей. |
root | .ant-notification-notice | Запись с role, доступным именем, class/style. |
wrapper | .ant-notification-notice-wrapper | Значок и текст; создаётся только при наличии значка. |
section | .ant-notification-notice-section | Пара title/description; создаётся только при наличии обоих блоков. |
icon | .ant-notification-notice-icon | Декоративный значок. |
title | .ant-notification-notice-title | Заголовок. |
description | .ant-notification-notice-description | Описание. |
actions | .ant-notification-notice-actions | Действия непосредственно в корне записи, рядом с wrapper или текстом. |
close | .ant-notification-notice-close | Кнопка закрытия. |
progress | .ant-notification-notice-progress | Полоса оставшегося времени. |
Токены оформления
В примере темы цвет полосы задаёт progressBg. Нажмите «Показать на 2 секунды».
| Токен | Назначение |
|---|---|
width | Ширина карточки: число в px или CSS-длина; ограничивается viewport. |
zIndexPopup | CSS-слой групп placements; native popover остаётся в top layer. |
progressBg | Цвет полосы оставшегося времени. |
colorInfoBg | Явный фон info-записи. |
colorSuccessBg | Явный фон success-записи. |
colorWarningBg | Явный фон warning-записи. |
colorErrorBg | Явный фон error-записи. |
| Токен | Значение |
|---|---|
colorBgElevated | #ffffff |
colorText | rgba(0,0,0,0.88) |
colorTextHeading | rgba(0,0,0,0.88) |
colorSuccess | #52c41a |
colorError | #ff4d4f |
colorInfo | #1677ff |
colorWarning | #faad14 |
borderRadiusLG | 8 |
FAQ
Как получить контекст ConfigProvider?
Поместите NotificationHolder своего createNotification внутрь provider. Для экземпляра нужен один holder.
Чем отличается notification от Message?
notification рассчитан на заголовок, подробности и действия. Message даёт короткий временный отклик.
Как обновить существующую запись?
Повторите open с тем же key и новыми настройками.
Как сохранить DOM описания при смене статуса?
Задайте type уже при открытии. Добавление или удаление значка может пересоздать текстовую обёртку.
Когда таймер приостанавливается?
При hover с pauseOnHover и при фокусе внутри actions. false/0 отключают автозакрытие.
Как изменить цвет полосы времени?
Задайте theme.components.Notification.progressBg и включите showProgress. В примере темы нажмите «Показать на 2 секунды».
Куда исчезли предыдущие уведомления?
Переведите фокус в стек, чтобы раскрыть карточки. Если задан лимит очереди, самые старые записи закрываются при добавлении новых.
Нужно ли пересоздавать уведомление после смены темы?
Нет. Токены оформления (design tokens) обновляются реактивно, сохраняя очередь и сроки закрытия.
Почему фоны статусов одинаковые?
По умолчанию используется colorBgElevated. Разные фоны можно задать компонентными токенами notification.
Как вернуть стандартную ширину?
Уберите override либо передайте пустую компонентную конфигурацию. Явный width:undefined отличается от отсутствующего поля.