Toast gains a pending/update lifecycle so async actions can show a single toast that transitions from in-progress to success/error, instead of firing a new one. Select's floating-menu placement logic is extracted into a shared helper so other dropdown-style components (MultiSelect) can reuse it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
176 lines
6.2 KiB
React
176 lines
6.2 KiB
React
// src/components/ui/Toast.jsx
|
|
// Toast notification system: provider, hook, and renderer.
|
|
//
|
|
// Usage:
|
|
// 1. Wrap your app (or page) with <ToastProvider>
|
|
// 2. In any child component: const { toast } = useToast()
|
|
// 3. Call: toast.success('Saved!', 'Your changes have been saved.')
|
|
// toast.danger('Error', 'Something went wrong.')
|
|
// toast.warning('Warning', 'Disk space is low.')
|
|
// toast.info('Info', 'A new version is available.')
|
|
//
|
|
// Each toast auto-dismisses after `duration` ms (default 4000).
|
|
// ToastProvider renders the stack itself via a portal — no extra component needed.
|
|
|
|
import { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react'
|
|
import { createPortal } from 'react-dom'
|
|
import Spinner from '@/components/ui/Spinner'
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Context
|
|
// ---------------------------------------------------------------------------
|
|
const ToastContext = createContext(null)
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Icons (inline — no external dependency)
|
|
// ---------------------------------------------------------------------------
|
|
function ToastIcon({ variant }) {
|
|
const props = {
|
|
width: 16, height: 16, viewBox: '0 0 16 16',
|
|
fill: 'none', stroke: 'currentColor',
|
|
strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
|
|
'aria-hidden': true,
|
|
}
|
|
|
|
if (variant === 'success') return (
|
|
<svg {...props}><path d="M13 4L6 11l-3-3" /></svg>
|
|
)
|
|
if (variant === 'danger') return (
|
|
<svg {...props}><path d="M12 4L4 12M4 4l8 8" /></svg>
|
|
)
|
|
if (variant === 'warning') return (
|
|
<svg {...props}><path d="M8 3v5M8 11v1" /><path d="M3.5 13.5h9L8 2.5l-4.5 11z" /></svg>
|
|
)
|
|
// info
|
|
return (
|
|
<svg {...props}><circle cx="8" cy="8" r="6" /><path d="M8 7v4M8 5.5v.5" /></svg>
|
|
)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Single Toast item
|
|
// ---------------------------------------------------------------------------
|
|
function ToastItem({ id, variant = 'info', title, message, duration = 4000, pending = false, onDismiss }) {
|
|
const [exiting, setExiting] = useState(false)
|
|
|
|
const dismiss = useCallback(() => {
|
|
setExiting(true)
|
|
setTimeout(() => onDismiss(id), 300)
|
|
}, [id, onDismiss])
|
|
|
|
// Auto-dismiss timer — does not run while `pending` (e.g. waiting on a command reply)
|
|
const timerRef = useRef(null)
|
|
const startTimer = () => {
|
|
if (pending) return
|
|
timerRef.current = setTimeout(dismiss, duration)
|
|
}
|
|
const clearTimer = () => clearTimeout(timerRef.current)
|
|
|
|
// (Re)start the timer whenever `pending` resolves to false, or on mount if already resolved
|
|
useEffect(() => {
|
|
clearTimer()
|
|
startTimer()
|
|
return clearTimer
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [pending, duration])
|
|
|
|
return (
|
|
<div
|
|
className={['toast', `toast-${variant}`, exiting ? 'exiting' : ''].filter(Boolean).join(' ')}
|
|
role="alert"
|
|
aria-live="assertive"
|
|
onMouseEnter={clearTimer}
|
|
onMouseLeave={startTimer}
|
|
>
|
|
<div className="toast-icon">
|
|
{pending ? <Spinner size="sm" /> : <ToastIcon variant={variant} />}
|
|
</div>
|
|
|
|
<div className="toast-content">
|
|
{title && <div className="toast-title">{title}</div>}
|
|
{message && <div className="toast-message">{message}</div>}
|
|
</div>
|
|
|
|
<button
|
|
className="toast-close"
|
|
onClick={dismiss}
|
|
aria-label="Dismiss notification"
|
|
>
|
|
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
|
|
<path d="M2 2l8 8M10 2L2 10" />
|
|
</svg>
|
|
</button>
|
|
|
|
{/* Progress bar — shrinks over duration. Hidden while pending (no timeout running). */}
|
|
{!pending && (
|
|
<div
|
|
className="toast-progress"
|
|
style={{ animationDuration: `${duration}ms` }}
|
|
/>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Provider
|
|
// ---------------------------------------------------------------------------
|
|
let _nextId = 1
|
|
|
|
export function ToastProvider({ children }) {
|
|
const [toasts, setToasts] = useState([])
|
|
|
|
const addToast = useCallback((variant, title, message, duration, pending = false) => {
|
|
const id = _nextId++
|
|
setToasts((prev) => [...prev, { id, variant, title, message, duration, pending }])
|
|
return id
|
|
}, [])
|
|
|
|
const dismiss = useCallback((id) => {
|
|
setToasts((prev) => prev.filter((t) => t.id !== id))
|
|
}, [])
|
|
|
|
// Update an existing toast in place — e.g. flip a `pending` (blue) toast to
|
|
// success/danger/warning once a command reply (or timeout) arrives.
|
|
const update = useCallback((id, patch) => {
|
|
setToasts((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)))
|
|
}, [])
|
|
|
|
const toast = {
|
|
success: (title, message, duration) => addToast('success', title, message, duration),
|
|
danger: (title, message, duration) => addToast('danger', title, message, duration),
|
|
warning: (title, message, duration) => addToast('warning', title, message, duration),
|
|
info: (title, message, duration) => addToast('info', title, message, duration),
|
|
// pending: creates a toast with no auto-dismiss timer until update() clears `pending`
|
|
pending: (title, message) => addToast('info', title, message, 4000, true),
|
|
update,
|
|
dismiss,
|
|
}
|
|
|
|
return (
|
|
<ToastContext.Provider value={toast}>
|
|
{children}
|
|
{createPortal(
|
|
<div className="toast-stack" aria-label="Notifications">
|
|
{toasts.map((t) => (
|
|
<ToastItem key={t.id} {...t} onDismiss={dismiss} />
|
|
))}
|
|
</div>,
|
|
document.body
|
|
)}
|
|
</ToastContext.Provider>
|
|
)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Hook
|
|
// ---------------------------------------------------------------------------
|
|
export function useToast() {
|
|
const ctx = useContext(ToastContext)
|
|
if (!ctx) throw new Error('useToast must be used inside <ToastProvider>')
|
|
return { toast: ctx }
|
|
}
|
|
|
|
// Default export — the provider (hook exported as named)
|
|
export default ToastProvider
|