AncrelDocumentationv0.3.0

Search documentation

    Documentation / frontend

    Toast · 状态通知

    在会产生通知的区域外放一个 ToastProvider,并在其内部挂一个 ToastViewport。通过 useToast().push({ message, tone }) 添加消息。普通消息通过 polite 区域播报,tone="danger" 使用 assertive 区域。通知出现时,用户可继续操作当前控件。

    Live example

    Open playground ↗

    App.tsx

    'use client'
    
    import { Button, ToastProvider, ToastViewport, useToast } from '@ancrel/ui'
    import '@ancrel/tokens/css'
    import '@ancrel/ui/styles.css'
    
    function SaveAction() {
      const { push } = useToast()
      return <Button onClick={() => push({ message: 'Draft saved', tone: 'success' })}>Save draft</Button>
    }
    
    export default function App() {
      return <ToastProvider durationMs={4500}><SaveAction /><ToastViewport /></ToastProvider>
    }
    

    Expected behavior

    Expected behavior

    Click Save draft twice. Both confirmations appear in the polite region. Dismissing one leaves the other visible until its own 4.5-second deadline.

    控制消息的生命周期

    push 返回此条消息的 ID。两次推入相同文字会得到不同 ID,各自按照自己的期限关闭。调用 dismiss(id) 或点击消息旁的关闭按钮可提前移除对应消息。Provider 卸载时会清理所有待执行的计时器。

    默认显示 4500 毫秒。Provider 的 durationMs 设置区域默认值,单条消息的同名选项可覆盖它。传入 durationMs: 0 让消息保留到手动关闭。重要且需要用户采取行动的信息也应在相关页面持续可见。

    Exports

    • ToastProvider
    • ToastViewport
    • ToastItem
    • useToast

    Constraints

    • Mount a single ToastViewport within the ToastProvider that owns the notifications.
    • Retain the ID returned by push to dismiss a particular notification.

    Anti-patterns

    • Using message text as a timer or dismissal key.
    • Moving keyboard focus to transient notifications.