Open History to see the last commit
1import React, { useEffect, useMemo, useState } from 'react'
2import { useLiveQuery } from '@tanstack/react-db'
3import { createTodoActions, todoCollection } from '~/db/todos'
4
5interface TodoDemoProps {
6 title: string
7 description: string
8 storageType: `indexeddb` | `localstorage`
9 offline: any
10}
11
12export function TodoDemo({
13 title,
14 description,
15 storageType,
16 offline,
17}: TodoDemoProps) {
18 const [newTodoText, setNewTodoText] = useState(``)
19 const [error, setError] = useState<string | null>(null)
20 const [isOnline, setIsOnline] = useState(navigator.onLine)
21 const [pendingCount, setPendingCount] = useState(0)
22
23 // Create actions based on offline executor
24 const actions = useMemo(() => createTodoActions(offline), [offline])
25 console.log({ offline, actions })
26
27 // Use live query to get todos
28 const { data: todoList = [], isLoading } = useLiveQuery((q) =>
29 q
30 .from({ todo: todoCollection })
31 .orderBy(({ todo }) => todo.createdAt, `desc`),
32 )
33
34 // Monitor online status
35 useEffect(() => {
36 const handleOnline = () => {
37 setIsOnline(true)
38 if (offline) {
39 offline.notifyOnline()
40 }
41 }
42 const handleOffline = () => setIsOnline(false)
43
44 window.addEventListener(`online`, handleOnline)
45 window.addEventListener(`offline`, handleOffline)
46
47 return () => {
48 window.removeEventListener(`online`, handleOnline)
49 window.removeEventListener(`offline`, handleOffline)
50 }
51 }, [offline])
52
53 // Monitor pending transactions
54 useEffect(() => {
55 if (!offline) return
56
57 const interval = setInterval(() => {
58 setPendingCount(offline.getPendingCount())
59 }, 100)
60
61 return () => clearInterval(interval)
62 }, [offline])
63
64 const handleAddTodo = async () => {
65 if (!newTodoText.trim()) return
66
67 try {
68 setError(null)
69 if (typeof actions.addTodo === `function`) {
70 await actions.addTodo(newTodoText)
71 } else {
72 actions.addTodo(newTodoText)
73 }
74 setNewTodoText(``)
75 } catch (err) {
76 setError(err instanceof Error ? err.message : `Failed to add todo`)
77 }
78 }
79
80 const handleToggleTodo = async (id: string) => {
81 try {
82 setError(null)
83 if (typeof actions.toggleTodo === `function`) {
84 await actions.toggleTodo(id)
85 } else {
86 actions.toggleTodo(id)
87 }
88 } catch (err) {
89 setError(err instanceof Error ? err.message : `Failed to toggle todo`)
90 }
91 }
92
93 const handleDeleteTodo = async (id: string) => {
94 try {
95 setError(null)
96 if (typeof actions.deleteTodo === `function`) {
97 await actions.deleteTodo(id)
98 } else {
99 actions.deleteTodo(id)
100 }
101 } catch (err) {
102 setError(err instanceof Error ? err.message : `Failed to delete todo`)
103 }
104 }
105
106 const handleKeyPress = (e: React.KeyboardEvent) => {
107 if (e.key === `Enter`) {
108 handleAddTodo()
109 }
110 }
111
112 const getStorageIcon = () => {
113 switch (storageType) {
114 case `indexeddb`:
115 return `🗄️`
116 case `localstorage`:
117 return `💾`
118 default:
119 return `💿`
120 }
121 }
122
123 return (
124 <div className="max-w-2xl mx-auto p-6">
125 <div className="bg-white rounded-lg shadow-lg p-6">
126 <div className="flex items-center gap-3 mb-4">
127 <span className="text-2xl">{getStorageIcon()}</span>
128 <div>
129 <h2 className="text-2xl font-bold text-gray-900">{title}</h2>
130 <p className="text-gray-600">{description}</p>
131 </div>
132 </div>
133
134 {/* Status indicators */}
135 <div className="flex flex-wrap gap-4 mb-6 text-sm">
136 <div
137 className={`flex items-center gap-2 px-3 py-1 rounded-full ${
138 isOnline
139 ? `bg-green-100 text-green-800`
140 : `bg-red-100 text-red-800`
141 }`}
142 >
143 <div
144 className={`w-2 h-2 rounded-full ${
145 isOnline ? `bg-green-500` : `bg-red-500`
146 }`}
147 />
148 {isOnline ? `Online` : `Offline`}
149 </div>
150
151 <div
152 className={`flex items-center gap-2 px-3 py-1 rounded-full ${
153 offline?.isOfflineEnabled
154 ? `bg-blue-100 text-blue-800`
155 : `bg-gray-100 text-gray-800`
156 }`}
157 >
158 <div
159 className={`w-2 h-2 rounded-full ${
160 offline?.isOfflineEnabled ? `bg-blue-500` : `bg-gray-500`
161 }`}
162 />
163 {offline?.isOfflineEnabled ? `Offline Mode Enabled` : `Online Only`}
164 </div>
165
166 {pendingCount > 0 && (
167 <div className="flex items-center gap-2 px-3 py-1 rounded-full bg-yellow-100 text-yellow-800">
168 <div className="w-2 h-2 rounded-full bg-yellow-500 animate-pulse" />
169 {pendingCount} pending sync{pendingCount !== 1 ? `s` : ``}
170 </div>
171 )}
172 </div>
173
174 {/* Error display */}
175 {error && (
176 <div className="mb-4 p-3 bg-red-100 border border-red-300 rounded-md">
177 <p className="text-red-700 text-sm">{error}</p>
178 </div>
179 )}
180
181 {/* Add new todo */}
182 <div className="flex gap-2 mb-6">
183 <input
184 type="text"
185 value={newTodoText}
186 onChange={(e) => setNewTodoText(e.target.value)}
187 onKeyPress={handleKeyPress}
188 placeholder="Add a new todo..."
189 className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
190 disabled={isLoading}
191 />
192 <button
193 onClick={handleAddTodo}
194 disabled={isLoading || !newTodoText.trim()}
195 className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
196 >
197 Add
198 </button>
199 </div>
200
201 {/* Todo list */}
202 <div className="space-y-2">
203 {isLoading && todoList.length === 0 ? (
204 <div className="text-center py-8 text-gray-500">
205 <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2" />
206 Loading todos...
207 </div>
208 ) : todoList.length === 0 ? (
209 <div className="text-center py-8 text-gray-500">
210 No todos yet. Add one above to get started!
211 <br />
212 <span className="text-xs">
213 Try going offline to see how it works
214 </span>
215 </div>
216 ) : (
217 todoList.map((todo) => {
218 return (
219 <div
220 key={todo.id}
221 className="flex items-center gap-3 p-3 border border-gray-200 rounded-md hover:bg-gray-50"
222 >
223 <button
224 onClick={() => handleToggleTodo(todo.id)}
225 className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
226 todo.completed
227 ? `bg-green-500 border-green-500 text-white`
228 : `border-gray-300 hover:border-green-400`
229 }`}
230 >
231 {todo.completed && <span className="text-xs">✓</span>}
232 </button>
233 <span
234 className={`flex-1 ${
235 todo.completed
236 ? `line-through text-gray-500`
237 : `text-gray-900`
238 }`}
239 >
240 {todo.text}
241 </span>
242 <span className="text-xs text-gray-400">
243 {new Date(todo.createdAt).toLocaleDateString()}
244 </span>
245 <button
246 onClick={() => handleDeleteTodo(todo.id)}
247 className="px-2 py-1 text-red-600 hover:bg-red-50 rounded text-sm"
248 >
249 Delete
250 </button>
251 </div>
252 )
253 })
254 )}
255 </div>
256
257 {/* Instructions */}
258 <div className="mt-6 p-4 bg-gray-50 rounded-md">
259 <h3 className="font-medium text-gray-900 mb-2">Try this:</h3>
260 <ol className="text-sm text-gray-600 space-y-1">
261 <li>1. Add some todos while online</li>
262 <li>3. Add more todos (they'll be stored locally)</li>
263 <li>4. Go back online to see them sync</li>
264 <li>
265 5. Open this page in another tab to test multi-tab coordination
266 </li>
267 </ol>
268 </div>
269 </div>
270 </div>
271 )
272}