Notification
Notificações globais: posições, tempo de exibição, ações, atualização e fila.
Quando usar
notification Mostra o evento com um cabeçalho, detalhes e outras ações. É adequado para exportação em segundo plano, operação de longo prazo ou mensagem do aplicativo. Para uma resposta curta, Message é suficiente; Avisos persistentes importantes também publicam principalmente conteúdo.
CSS Notificação de prefixo Mostrar total ConfigProvider.prefixCls e local prefixCls sem status de reset. NotificationHolder Altera as classes de todos os canais e partes do cartão. App Usa notification.prefixCls. Fila, temporizadores, foco e superfície nativa são preservados.
Instância, conteúdo e posição
Crie createNotification e coloque um NotificationHolder dentro do ConfigProvider desejado. A instância tem uma fila independente para todas as provisões; Áreas individuais precisam de instâncias separadas.
| Tarefa | Oportunidade | Exemplo |
|---|---|---|
| Mostrar evento detalhado | open, title, description |
Notificação básica |
| Selecione Status semântico | success/info/warning/error |
Tipos |
| Mostrar o tempo antes de fechar | duration, showProgress, pauseOnHover |
Mostrar hora |
| Recolher lista em uma posição | stack |
pilha de notificações |
| Selecione a posição e o recipiente | placement, getContainer |
Localização |
| Substitua a expectativa por | Mesmo key, actions |
Atualização |
| Execute uma tarefa em segundo plano | Modelo de aplicativo | Relatório de exportação |
Em title e description você pode transferir texto, número ou trecho. Para botões e links, use actions. Propriedade placement Especifica uma das seis posições em relação às bordas da tela. Se você definir rtl, o texto irá da direita para a esquerda e a borda selecionada permanecerá a mesma.
Atualizar e exibir o tempo
Repetido open com o mesmo key Atualize a entrada, incluindo texto, actions, type e placement. Para salvar a descrição DOM ao alterar o status, defina type ao abrir, por exemplo info: a aparência ou exclusão do ícone pode recriar o wrapper de conteúdo.
Por padrão, a notificação fecha após 4,5 segundos. duration: 0 ou duration: false deixa aberto. Com uma duração positiva showProgress Mostra o tempo restante. A barra pára com o cronômetro quando o usuário passa o ponteiro do ponteiro quando pauseOnHover é ativado ou move o foco dentro do cartão. Em Exemplo de exportação Componente Progress Mostra qual parte do relatório está pronta.
Com closable você pode alterar o ícone, a assinatura ou o botão de fechamento. Se você ocultar o botão na notificação constante, forneça sua própria ação de fechamento. onClose É disparado no início do fechamento da carta e onAllRemoved quando a última carta desaparece do DOM.
Por padrão, a quarta carta em uma posição recolhe a lista. O apontar ou focar dentro da pilha revela todas as cartas. O limite pode ser alterado em stack.threshold e stack: false deixa a lista aberta. Se você deseja fechar as notificações mais antigas, defina maxCount. Esse limite é válido para todas as posições de uma vez.
Contexto, design e limitações
O detentor recebe um tema local e uma direção de ConfigProvider. theme.components.Notification Alterações width, zIndexPopup e fundos de status sem reabrir. Local CSS Variáveis Suporte e registros têm prioridade.
Sem fundos de sobreposição de componentes Use colorBgElevated em vez de total colorInfoBg/colorSuccessBg. A configuração vazia retorna uma largura padrão de 384 px. Explícito width:undefined - um caso separado; Para um determinado tamanho, use o número ou o comprimento CSS sem assumir o modo max-content.
Para botões e links disponíveis, use actions. Através props você pode atribuir um cartão HTML- Atributos, por exemplo data-* ou ária. onClick Obtém um evento de clique no cartão. O botão Fechar possui um manipulador separado.
Por meio de ConfigProvider.notification, você pode definir um ícone de fechamento comum, classes e estilos. Parâmetros classNames e styles Aceite um objeto ou função de { props }. As configurações do provedor, instância e cartão são aplicadas nesta ordem. Exemplo de design.
getContainer Chamado no navegador. Se a função não devolver o nó, a biblioteca usa ConfigProvider.getPopupContainer, então document.body. Se ambas as funções estiverem ausentes, a lista permanecerá ao lado do suporte.
Em vez de um par manual createNotification/NotificationHolder Você pode usar App: App.useApp() Retorna notification da área mais próxima. Seus padrões são herdados por campos, enquanto as filas pai e aninhada são independentes. Alterar App.notification.placement Aplica-se a novas notificações.
Exemplos
Notificação normal
createNotification e um titular.
<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: "A documentação é atualizada",
description: "Novos exemplos de componentes apareceram no catálogo."
}))}>{("Mostrar notificação regular")}</Button>
Ícones Padrão
success, info, warning e 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: `Status: ${type}`,
description: "Ícone de status padrão.",
duration: 0
}))}>{(type)}</Button>
{/each}<Button
onclick={() => notification.destroy()}
>{("Remover notificações de tipo")}</Button></div>
Mostrar hora
A banda mostra quanto tempo resta antes de fechar.
<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={("Notificação de duração")}
min={0}
max={10}
step={0.5}
value={duration}
onValueChange={next => { duration = next ?? 0; }}
/>
<Checkbox bind:checked={permanent}>{("sem fechamento automático")}</Checkbox>
<Checkbox bind:checked={showProgress} disabled={permanent || duration === 0}>
{("Mostrar o tempo restante")}
</Checkbox>
<Checkbox
bind:checked={pauseOnHover}
>{("pausa de notificação ao passar o mouse")}</Checkbox>
<Button onclick={() => notification.info(({
key: 'duration',
title: "Mostrar hora",
description: "Passe o mouse pelo ponteiro ou navegue até o botão Fechar.",
duration: permanent ? false : duration,
pauseOnHover,
showProgress,
onClose: () => { closed++; }
}))}>{("Mostrar com duração selecionada")}</Button>
</div>
<output
aria-label={("Notificação de fechamento")}
>{("Fechado: ")}{closed}</output>
seu fechamento
Texto disponível Nome, disabled e botão oculto.
<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}
>{("Desative o botão Fechar")}</Checkbox>
<Checkbox bind:checked={hidden}>{("Ocultar o botão Fechar")}</Checkbox>
<Button onclick={() => notification.open(({
key: 'close',
title: "seu fechamento",
description: "As configurações se aplicam ao gravar ou atualizar uma entrada.",
duration: 0,
closable: hidden ? false : {
disabled,
closeIcon: "Concluído",
'aria-label': "Notificação completa"
}
}))}>{("Mostre seu fechamento")}</Button>
<Button
onclick={() => notification.destroy('close')}
>{("Remova a notificação manualmente")}</Button></div>
Seu ícone e design
Desenho geral do título e da moldura, ícone de cor própria para um cartão.
<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: ("Desenho próprio"),
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>{("Assinatura de ")}<strong>Svelte Snippet</strong>{(" com design próprio.")}</span>
{/snippet}
<ConfigProvider notification={appearance}>
<NotificationHolder {notification} top={240} id="notification-custom-notices" />
<Button onclick={showNotice}>{("Mostrar seu ícone de notificação")}</Button>
</ConfigProvider>
mantimentos
Seis posições da tela, seleção do contêiner e direção do texto.
<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={("A posição do exemplo de notificação")}
bind:value={placement}
options={(placements)}
/>
<Checkbox bind:checked={rtl}>{("Texto da direita para a esquerda")}</Checkbox>
<div class="actions"><Button onclick={() => notification.info(({
key: placement,
title: `Posição: ${placement}`,
description: "Área da tela física.",
placement,
duration: 0
}))}>{("Mostrar na posição selecionada")}</Button>
<Button
onclick={() => notification.destroy()}
>{("Limpar notificação")}</Button></div></div>
Atualização e ações
Um key Novo botão Result and Accept.
<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');
}}>{("Aceitar o resultado da notificação")}</Button>{/snippet}
<NotificationHolder {notification} top={240} id="notification-update-notices" />
<div class="actions">
<Button onclick={() => notification.info(({
key: 'review',
title: "Verifique o documento",
description: "Aguarde o resultado do teste.",
duration: 0
}))}>{("Iniciar notificação de verificação")}</Button>
<Button onclick={() => notification.success(({
key: 'review',
title: "Documento verificado",
description: "Você pode aceitar o resultado.",
actions,
duration: 0
}))}>{("terminar a notificação")}</Button>
<Button onclick={() => notification.destroy('review')}>
{("Remover verificação de notificação")}
</Button>
</div>
<output
aria-label={("Notificação")}
>{("Recebido: ")}{accepted}</output>
Limite de filas
Quando a quarta notificação é adicionada, a mais antiga fecha.
<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: `Notificação da fila não${++sequence}`,
description: "O limite total é de três entradas."
}))}>{("Adicionar à fila de notificação")}</Button>
<Button
onclick={() => notification.destroy()}
>{("Limpar a fila de notificações")}</Button></div>
pilha de notificações
Adicione quatro relatórios. Aponte o ponteiro ou mova o foco para a pilha.
<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: ("Relatório pronto"),
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}>{("Lista de recolhimento")}</Checkbox>
<label for={thresholdId}>{("Limite de Recolhimento")}</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}>
{("Relatório Concluído Relatório")}
</Button>
<Button disabled={!hasReports} onclick={() => notification.destroy()}>
{("Limpar notificações")}
</Button>
</Flex>
</Flex>
Tema do componente notification
Largura, fundos de status e camadas. Alterar tema salva o comentário em actions, fila e horário de fechamento.
<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(("rascunho de comentários"));
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>{("Comentário\n ")}<Input bind:value={comment} aria-label={("Comentário de notificação")} />
</label>
<Button onclick={() => notification.destroy('theme')}>{("Concluído")}</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}>{("Aplicar tokens de notificação")}</Checkbox>
<Checkbox bind:checked={resetWidth} disabled={!enabled}>
{("Largura da transferência: indefinido")}
</Checkbox>
<div class="status-settings">
<span>{("Status de notificação")}</span>
<RadioGroup
aria-label={("Tópico de notificação de status")}
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: "Tema de notificação",
description: "O tema é atualizado sem redefinir o comentário e ação.", actions, duration: 0
}))}>{("Verifique a notificação")}</Button>
<Button onclick={() => notification.info(({
key: 'timed-theme', title: "Notificação por dois segundos",
description: "A troca de tema não renova a tela.", duration: 2, showProgress: true,
class: 'notification-theme-timed'
}))}>{("Mostrar por 2 segundos")}</Button>
</div>
</div>
</ConfigProvider>
Relatório de exportação
Operação de progresso, sucesso, erro, repetição, cancelamento e CSV real.
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(("Prepare o relatório e faça o download da notificação.")); 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 = ("Relatório pronto para download."); notification.success( ({ key: 'export', title: "Relatório pronto", description: progress, placement, duration: 0, actions: ready, role: 'status' }) ); }, onError() { result = ("Falha ao preparar um relatório. tente novamente."); notification.error( ({ key: 'export', title: "Não foi possível preparar o relatório", 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 = ("Prepare um relatório…"); notification.info( ({ key: 'export', title: "Prepare um relatório", description: progress, actions: pending, placement, duration: 0, role: 'status' }) ); } function cancel() { if (!model.cancel()) { return; } result = ("Exportação cancelada."); notification.info( ({ key: 'export', title: "Exportação cancelada", 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 = ("Relatório baixado."); } function reset() { model.reset(); releaseDownload(); notification.destroy(); result = ("Exportar exemplo de reset."); } 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={("Elaboração do relatório")} />{/snippet} {#snippet pending()}<Button onclick={cancel}>{("Cancelar exportação")}</Button>{/snippet} {#snippet retry()}<Button type="primary" onclick={start} >{("Repetir Export")}</Button>{/snippet} {#snippet ready()} <span class="actions"><Button type="primary" onclick={download}> {("Download Relatório")} </Button><Button onclick={() => notification.destroy('export')} >{("Fechar o resultado da exportação")}</Button></span> {/snippet} <NotificationHolder {notification} id="showcase-notifications" /> <div class="actions" ><Button type="primary" loading={model.status === 'preparing'} onclick={start} >{("Relatório de exportação")}</Button><Checkbox bind:checked={failNext} >{("Próximo erro de exportação")}</Checkbox><div class="placement" ><Select aria-label={("Notificação")} bind:value={placement} options={(placements)} /></div><Button onclick={reset} >{("Exemplo de redefinição de notificação")}</Button></div> <output aria-label={("Resultado da notificação")}>{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: "Prepare um relatório." }); 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: "Após a preparação, o botão de download aparecerá aqui." }; 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: "ícone Coletar dados…" }, { delay: 450, percent: 65, phase: "formulário csv…" }, { delay: 600, percent: 90, phase: "Verifique o arquivo..." } ]) { schedule( stage.delay, () => { state = { status: 'preparing', percent: stage.percent, phase: stage.phase }; } ); } schedule(700, () => { if (failed) { state = { status: 'error', percent: 90, phase: "Dados armazenados. tente exportar novamente." }; callbacks.onError(); } else { state = { status: 'ready', percent: 100, phase: "O arquivo csv contém duas entradas. Ele pode ser baixado agora.", 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: "A preparação do relatório foi cancelada." }; return true; }, reset() { clear(); state = { status: 'idle', percent: 0, phase: "Prepare um relatório." }; }, destroy() { active = false; clear(); } }; }
NotificationHolder Altera as classes de todas as colocações e cartões de peças. O aplicativo usa notificação.prefixCls. Fila, temporizadores, foco e superfície nativa são preservados.
CSS Prefixos notification
namespace geral ConfigProvider e local prefixCls; O estado do componente é salvo ao alterar o nome.
<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}>{("General Prefix Notification Suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Notificação de prefixo local")}</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: "Notificação de prefixo",
description: "Alteração do namespace salva o cartão atual."
}))}>{("Mostrar notificação com o prefixo")}</Button>
<Button onclick={() => notification.destroy()}>
{("Fechar notificação com prefixo")}
</Button>
</div>
</ConfigProvider>
<output
aria-label={("CSS Notificação de prefixo")}
>{("Geral: ")}{prefix}{("; Local: ")}{(localPrefix
|| ("Do provedor"))}</output>
<p>
{("NotificationHolder Altera as classes de todas as colocações e cartões de peças. O aplicativo usa notificação.prefixCls. Fila, temporizadores, foco e superfície nativa são preservados.")}
</p>
</div>
API
| Tema | Exemplo ou restrição |
|---|---|
| Hooks usage (recommended) | Svelte: createNotification e um NotificationHolder no contexto certo. |
| Duration after which the notification box is closed | segundos, false/0 e pausa ao pairar. |
| Notification with icon | Quatro status padrão. |
| Custom close button | Sua assinatura, nome disponível, disabled e ocultar o botão. |
| Customized Icon | Ícone e descrição do snippet. |
| Placement | Todas as seis áreas físicas da tela. |
| Update Message Content | Atualize key e ação dentro da notificação. |
| Stack | Recolher o limite e abertura do teclado ou passar o mouse. |
| Show with progress | O indicador de tempo restante segue o cronômetro de notificação. |
| Customize progress bar color | A cor da banda define progressBg no tópico notification. |
| Custom semantic styles | Classes e estilos gerais do provedor podem ser complementados por um cartão. |
NotificationInstance
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
open | Crie ou atualize a entrada em key. | (config: NotificationConfig) => void | — |
info | Status das informações. | (config) => void | info |
success | Operação bem-sucedida. | (config) => void | success |
warning | Aviso. | (config) => void | warning |
error | Erro. | (config) => void | error |
destroy | Feche uma entrada ou toda a fila. | (key?: string | number) => void | — |
NotificationConfig
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
title | Cabeçalho e nome disponível. | NotificationContent | — |
description | Detalhes da notificação. | NotificationContent | — |
actions | Botões e links para outras ações. | NotificationContent | — |
type | Ícone de status padrão. | success | info | warning | error | — |
icon | Ícone próprio. | NotificationContent | por tipo |
key | ID de renovação sem gravação duplicada. | string | number | gerado |
placement | top/bottom, topLeft/topRight, bottomLeft/bottomRight. | NotificationPlacement | topRight |
duration | segundos; false e 0 desligue o cronômetro. | number | false | 4.5 |
pauseOnHover | Pause o temporizador sob o ponteiro. | boolean | true |
closable | Configurações do botão de fechamento padrão. | boolean | NotificationClosable | true |
closeIcon | assinatura própria; false/null Ocultar o botão. | NotificationContent | Cruze |
role | A urgência do anúncio. | alert | status | alert |
onClose | Início do fechamento. Desmontar o retorno de chamada não. | () => void | — |
class | Registre a classe raiz. | string | — |
style | CSS Raiz do registro. | string | — |
classNames | Classes de peças individuais de cartão. | NotificationSemantic | — |
styles | Estilos de peças individuais de cartão. | NotificationSemantic | — |
showProgress | Mostra quanto tempo resta antes de fechar. | boolean | false |
props | Atributos nativos do cartão, incluindo data-* e Aria. | NotificationRootAttributes | — |
onClick | Clique no cartão. O botão Fechar é pressionado separadamente. | (event: MouseEvent) => void | — |
NotificationClosable
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
disabled | Desative o botão padrão. | boolean | false |
closeIcon | tem prioridade sobre closeIcon configuração. | NotificationContent | Cruze |
aria-label | Nome do botão disponível. | string | locale.closeText |
onClose | é chamado antes de onClose cartão quando fechado por botão ou timer. | () => void | — |
createNotification options
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
placement | Local geral da instância. | NotificationPlacement | topRight |
duration | Duração total. | number | false | 4.5 |
pauseOnHover | Total de pausa. | boolean | true |
maxCount | Limite total para todos os canais. | number | Sem limite |
showProgress | Mostra quanto tempo resta antes de fechar. | boolean | false |
prefixCls | Lista completa de prefixos e seus cartões. | string | ConfigProvider.prefixCls + "-notification" |
top | Recuo superior da superfície. | number | 24 |
bottom | Recuo da superfície inferior. | number | 24 |
stack | Limiar de dobra em cada posição. false Deixa a lista aberta. | boolean | { threshold?: number } | { threshold: 3 } |
rtl | Direção do texto. A posição das cartas na tela define placement. | boolean | ConfigProvider.direction |
getContainer | Seleciona um nó para uma lista de notificações do navegador. | () => HTMLElement | ShadowRoot | null | undefined | — |
closeIcon | Ícone de fechamento próprio para todos os cartões. | NotificationContent | ConfigProvider.notification.closeIcon |
classNames | Listas e classes de cartão para esta instância. | NotificationSemantic | — |
styles | Estilos de lista e cartões para esta instância. | NotificationSemantic | — |
onAllRemoved | Chamado após remover o último cartão do DOM. | () => void | — |
NotificationHolder
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
prefixCls | Lista completa de prefixos e seus cartões. | string | ConfigProvider.prefixCls + "-notification" |
top | Recuo superior da superfície. | number | 24 |
bottom | Recuo da superfície inferior. | number | 24 |
stack | Limiar de dobra em cada posição. false Deixa a lista aberta. | boolean | { threshold?: number } | { threshold: 3 } |
rtl | Direção do texto. A posição das cartas na tela define placement. | boolean | ConfigProvider.direction |
getContainer | Seleciona um nó para uma lista de notificações do navegador. | () => HTMLElement | ShadowRoot | null | undefined | — |
closeIcon | Ícone de fechamento próprio para todos os cartões. | NotificationContent | ConfigProvider.notification.closeIcon |
classNames | Listas e classes de cartão para esta instância. | NotificationSemantic | — |
styles | Estilos de lista e cartões para esta instância. | NotificationSemantic | — |
onAllRemoved | Chamado após remover o último cartão do DOM. | () => void | — |
notification | Cópia da fila; Um suporte conectado. | NotificationInstance | Obrigatório |
id | Surface ID com todos os canais. | string | — |
class | classe de superfície. | string | — |
style | CSS Superfícies. | string | — |
Em vez de gancho de reacção/métodos estáticos, são usados independentes createNotification e NotificationHolder. Os métodos de abertura retornam void; O fechamento executa destroy(key) ou botão padrão.
Semantic DOM
Slots list e listContent Consulte a lista, o restante no cartão.
| Slot | CSS-class | Atribuir |
|---|---|---|
list | .ant-notification-list | Grupo separado placement. |
listContent | .ant-notification-list-content | Lista de registros. |
root | .ant-notification-notice | Entrada com role Nome disponível, class/style. |
wrapper | .ant-notification-notice-wrapper | ícone e texto; Ele é criado somente se houver um ícone. |
section | .ant-notification-notice-section | Pair title/description; Ele é criado apenas se ambos os blocos estiverem presentes. |
icon | .ant-notification-notice-icon | Ícone decorativo. |
title | .ant-notification-notice-title | Cabeçalho. |
description | .ant-notification-notice-description | Descrição. |
actions | .ant-notification-notice-actions | Ações diretamente na raiz do registro, ao lado do wrapper ou texto. |
close | .ant-notification-notice-close | Botão Fechar. |
progress | .ant-notification-notice-progress | Banda de tempo restante. |
Tokens de design
No tema de exemplo, a cor da banda define progressBg. Clique em "Mostrar por 2 segundos".
| Token | Atribuir |
|---|---|
width | Largura do cartão: número em px ou CSS comprimento; é limitado pela viewport. |
zIndexPopup | CSS camada de grupo de canais; Popover nativo permanece na camada top. |
progressBg | Color Band Tempo restante. |
colorInfoBg | Registro de informações de fundo explícito. |
colorSuccessBg | Registro de sucesso de fundo explícito. |
colorWarningBg | Fundo de registro de aviso explícito. |
colorErrorBg | Fundo explícito de registro de erro. |
| Token | Valor |
|---|---|
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
Como obter o contexto ConfigProvider?
Coloque NotificationHolder do seu provedor createNotification interno. Uma instância precisa de um titular.
Qual é a diferença entre notification e mensagem?
notification Projetado para títulos, detalhes e ações. Message Dá uma resposta de curto prazo.
Como atualizar um registro existente?
Repita open com o mesmo key e novas configurações.
Como salvar a descrição DOM ao alterar o status?
Defina type já na abertura. Adicionar ou excluir um ícone pode recriar um wrapper de texto.
Quando o cronômetro para?
Para pairar com pauseOnHover e foque dentro de actions. false/0 Desative o fechamento automático.
Como alterar a cor da banda de tempo?
Defina theme.components.Notification.progressBg e habilite showProgress. Em Amostra Clique em Mostrar por 2 segundos.
Para onde desapareceram as notificações anteriores?
Mova o foco para Stack para abrir as cartas. Se Limite de fila for fornecido, as entradas mais antigas fecham quando novas são adicionadas.
Preciso recriar a notificação depois de alterar o tema?
Não. Tokens de design estão atualizando reativamente, mantendo a fila do tempo e fechando o cronograma.
Por que os planos de fundo de status são iguais?
O padrão é colorBgElevated. Diferentes fundos podem ser definidos com tokens de componentes notification.
Como devolver a largura padrão?
Remova a substituição ou passe uma configuração de componente vazia. Explícito width:undefined difere do campo ausente.