Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

ReportRuntimeProvider.tsx

94 lines2.3 KB

1'use client'
2​
3import {
4 createContext,
5 useCallback,
6 useContext,
7 useMemo,
8 useState,
9} from 'react'
10import type { UIUpdate } from '@/lib/reports/types'
11​
12type ToastVariant = 'default' | 'success' | 'error'
13​
14interface ToastItem {
15 id: string
16 message: string
17 variant: ToastVariant
19​
20interface ReportRuntimeContextValue {
21 reportId: string
22 applyUIUpdates: (updates: UIUpdate[]) => void
23 pushToast: (message: string, variant?: ToastVariant) => void
25​
26const ReportRuntimeContext = createContext<ReportRuntimeContextValue | null>(
27 null,
29​
30export function ReportRuntimeProvider({
31 reportId,
32 applyUIUpdates,
33 children,
34}: {
35 reportId: string
36 applyUIUpdates: (updates: UIUpdate[]) => void
37 children: React.ReactNode
38}) {
39 const [toasts, setToasts] = useState<ToastItem[]>([])
40​
41 const pushToast = useCallback(
42 (message: string, variant: ToastVariant = 'default') => {
43 const id = `toast-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
44 setToasts((prev) => [...prev, { id, message, variant }])
45 setTimeout(() => {
46 setToasts((prev) => prev.filter((toast) => toast.id !== id))
47 }, 3000)
48 },
49 [],
50 )
51​
52 const value = useMemo(
53 () => ({
54 reportId,
55 applyUIUpdates,
56 pushToast,
57 }),
58 [reportId, applyUIUpdates, pushToast],
59 )
60​
61 return (
62 <ReportRuntimeContext.Provider value={value}>
63 {children}
64 {toasts.length > 0 && (
65 <div className="fixed top-4 right-4 z-50 space-y-2">
66 {toasts.map((toast) => (
67 <div
68 key={toast.id}
69 className={`rounded-lg px-4 py-2 text-sm shadow-lg border ${
70 toast.variant === 'success'
71 ? 'bg-emerald-600/90 text-white border-emerald-400/50'
72 : toast.variant === 'error'
73 ? 'bg-red-600/90 text-white border-red-400/50'
74 : 'bg-gray-900/90 text-white border-gray-600/60'
75 }`}
76 >
77 {toast.message}
78 </div>
79 ))}
80 </div>
81 )}
82 </ReportRuntimeContext.Provider>
83 )
85​
86export function useReportRuntime() {
87 const context = useContext(ReportRuntimeContext)
88 if (!context) {
89 throw new Error(
90 'useReportRuntime must be used within ReportRuntimeProvider',
91 )
92 }
93 return context