Files
planet/frontend/src/admin/components/ui/toast.tsx
T
linkong fbecf30513
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
ci / delivery (push) Has been cancelled
release / images (push) Has been cancelled
release: bump version to 0.73.0
2026-06-29 17:04:05 +08:00

67 lines
2.3 KiB
TypeScript

import * as ToastPrimitive from '@radix-ui/react-toast'
import { X } from 'lucide-react'
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
type ToastTone = 'default' | 'success' | 'error'
interface ToastItem {
id: number
title: string
description?: string
tone: ToastTone
}
interface ToastContextValue {
toast: (item: Omit<ToastItem, 'id' | 'tone'> & { tone?: ToastTone }) => void
}
const ToastContext = createContext<ToastContextValue | null>(null)
export function ToastProvider({ children }: { children: ReactNode }) {
const { t } = useTranslation()
const [items, setItems] = useState<ToastItem[]>([])
const toast = useCallback((item: Omit<ToastItem, 'id' | 'tone'> & { tone?: ToastTone }) => {
const id = Date.now() + Math.random()
setItems((current) => [...current, { id, tone: item.tone || 'default', title: item.title, description: item.description }])
}, [])
const value = useMemo(() => ({ toast }), [toast])
return (
<ToastContext.Provider value={value}>
<ToastPrimitive.Provider swipeDirection="right">
{children}
{items.map((item) => (
<ToastPrimitive.Root
key={item.id}
className={`an-toast an-toast--${item.tone}`}
duration={3000}
onOpenChange={(open) => {
if (!open) setItems((current) => current.filter((candidate) => candidate.id !== item.id))
}}
>
<ToastPrimitive.Title className="an-toast__title">{item.title}</ToastPrimitive.Title>
{item.description ? (
<ToastPrimitive.Description className="an-toast__description">
{item.description}
</ToastPrimitive.Description>
) : null}
<ToastPrimitive.Close className="an-toast__close" aria-label={t('common.close')} title={t('common.close')}>
<X size={14} />
</ToastPrimitive.Close>
</ToastPrimitive.Root>
))}
<ToastPrimitive.Viewport className="an-toast__viewport" />
</ToastPrimitive.Provider>
</ToastContext.Provider>
)
}
export function useToast() {
const context = useContext(ToastContext)
if (!context) throw new Error('useToast must be used within ToastProvider')
return context
}