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

TodoApp.tsx

260 lines8.1 KB

1import React, { useState } from 'react'
2import { Link } from '@tanstack/react-router'
3import { debounceStrategy, usePacedMutations } from '@tanstack/react-db'
4import type { FormEvent } from 'react'
5import type { Collection, Transaction } from '@tanstack/react-db'
6​
7import type { SelectConfig, SelectTodo } from '@/db/validation'
8import { getComplementaryColor } from '@/lib/color'
9​
10interface TodoAppProps {
11 todos: Array<SelectTodo>
12 configData: Array<SelectConfig>
13 todoCollection: Collection<SelectTodo>
14 configCollection: Collection<SelectConfig>
15 title: string
16 configMutationFn?: (params: { transaction: Transaction }) => Promise<void>
18​
19export function TodoApp({
20 todos,
21 configData,
22 todoCollection,
23 configCollection,
24 title,
25 configMutationFn,
26}: TodoAppProps) {
27 const [newTodo, setNewTodo] = useState(``)
28​
29 // Use paced mutations with debounce strategy for color picker if mutationFn provided
30 // Waits for 2500ms of inactivity before persisting - only the final value is saved
31 const mutateConfig = configMutationFn
32 ? usePacedMutations({
33 mutationFn: configMutationFn,
34 strategy: debounceStrategy({ wait: 2500 }),
35 })
36 : undefined
37​
38 // Define a type-safe helper function to get config values
39 const getConfigValue = (key: string): string | undefined => {
40 for (const config of configData) {
41 if (config.key === key) {
42 return config.value
43 }
44 }
45 return undefined
46 }
47​
48 // Define a helper function to update config values
49 const setConfigValue = (key: string, value: string): void => {
50 if (mutateConfig) {
51 // Use paced mutations for updates (optimistic + batched persistence)
52 mutateConfig(() => {
53 for (const config of configData) {
54 if (config.key === key) {
55 configCollection.update(config.id, (draft) => {
56 draft.value = value
57 })
58 return
59 }
60 }
61​
62 // If the config doesn't exist yet, create it
63 configCollection.insert({
64 id: Math.round(Math.random() * 1000000),
65 key,
66 value,
67 created_at: new Date(),
68 updated_at: new Date(),
69 })
70 })
71 } else {
72 // Use naked collection calls (collection handlers will be invoked)
73 for (const config of configData) {
74 if (config.key === key) {
75 configCollection.update(config.id, (draft) => {
76 draft.value = value
77 })
78 return
79 }
80 }
81​
82 // If the config doesn't exist yet, create it
83 configCollection.insert({
84 id: Math.round(Math.random() * 1000000),
85 key,
86 value,
87 created_at: new Date(),
88 updated_at: new Date(),
89 })
90 }
91 }
92​
93 const backgroundColor = getConfigValue(`backgroundColor`)
94 const titleColor = getComplementaryColor(backgroundColor)
95​
96 const handleColorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
97 const newColor = e.target.value
98 setConfigValue(`backgroundColor`, newColor)
99 }
100​
101 const handleSubmit = (e: FormEvent) => {
102 e.preventDefault()
103 const todo = newTodo.trim()
104 setNewTodo(``)
105​
106 if (todo) {
107 todoCollection.insert({
108 text: todo,
109 completed: false,
110 id: Math.round(Math.random() * 1000000),
111 created_at: new Date(),
112 updated_at: new Date(),
113 })
114 }
115 }
116​
117 const activeTodos = todos.filter((todo) => !todo.completed)
118 const completedTodos = todos.filter((todo) => todo.completed)
119​
120 return (
121 <main
122 className="h-dvh flex justify-center overflow-auto py-8"
123 style={{ backgroundColor }}
124 >
125 <div className="w-[550px]">
126 <h1
127 className="text-center text-[70px] font-bold mb-4"
128 style={{ color: titleColor }}
129 >
130 {title}
131 </h1>
132​
133 <Navigation />
134​
135 <div className="py-4 flex justify-end">
136 <div className="flex items-center">
137 <label
138 htmlFor="colorPicker"
139 className="mr-2 text-sm font-medium text-gray-700"
140 style={{ color: titleColor }}
141 >
142 Background Color:
143 </label>
144 <input
145 type="color"
146 id="colorPicker"
147 value={backgroundColor}
148 onChange={handleColorChange}
149 className="cursor-pointer border border-gray-300 rounded"
150 />
151 </div>
152 </div>
153​
154 <div className="bg-white shadow-[0_2px_4px_0_rgba(0,0,0,0.2),0_25px_50px_0_rgba(0,0,0,0.1)] relative">
155 <form onSubmit={handleSubmit} className="relative">
156 <button
157 type="button"
158 className="absolute w-12 h-full text-[30px] text-[#e6e6e6] hover:text-[#4d4d4d]"
159 disabled={todos.length === 0}
160 onClick={() => {
161 const todosToToggle =
162 activeTodos.length > 0 ? activeTodos : completedTodos
163​
164 todoCollection.update(
165 todosToToggle.map((todo) => todo.id),
166 (drafts) =>
167 drafts.forEach(
168 (draft) => (draft.completed = !draft.completed),
169 ),
170 )
171 }}
172 >
173 ❯
174 </button>
175 <input
176 type="text"
177 value={newTodo}
178 onChange={(e) => setNewTodo(e.target.value)}
179 placeholder="What needs to be done?"
180 className="w-full h-[64px] pl-[60px] pr-4 text-2xl font-light border-none shadow-[inset_0_-2px_1px_rgba(0,0,0,0.03)] box-border"
181 />
182 </form>
183​
184 <ul className="list-none">
185 {todos.map((todo) => (
186 <li
187 key={`todo-${todo.id}`}
188 className="relative border-b border-[#ededed] last:border-none group"
189 >
190 <div className="flex items-center h-[58px] pl-[60px] gap-1.2">
191 <input
192 type="checkbox"
193 checked={todo.completed}
194 onChange={() =>
195 todoCollection.update(todo.id, (draft) => {
196 draft.completed = !draft.completed
197 })
198 }
199 className="absolute left-[12px] size-[40px] cursor-pointer"
200 />
201 <label
202 className={`block p-[15px] text-2xl transition-colors ${todo.completed ? `text-[#d9d9d9] line-through` : ``}`}
203 >
204 {todo.text}
205 </label>
206 <button
207 onClick={() => todoCollection.delete(todo.id)}
208 className="hidden group-hover:block absolute right-[20px] text-[30px] text-[#cc9a9a] hover:text-[#af5b5e] transition-colors"
209 >
210 ×
211 </button>
212 </div>
213 </li>
214 ))}
215 </ul>
216​
217 <footer className="text-[14px] text-[#777] px-[15px] h-[40px] border-t border-[#e6e6e6] flex justify-between items-center">
218 <span>
219 {`${activeTodos.length} ${activeTodos.length === 1 ? `item` : `items`} left`}
220 </span>
221​
222 {completedTodos.length > 0 && (
223 <button
224 onClick={() =>
225 todoCollection.delete(completedTodos.map((todo) => todo.id))
226 }
227 className="hover:underline"
228 >
229 Clear completed
230 </button>
231 )}
232 </footer>
233 </div>
234 </div>
235 </main>
236 )
238​
239function Navigation() {
240 const style = `px-4 py-2 text-white rounded transition-colors`
241 const links = [
242 [`/query`, `Query`, `bg-green-700 hover:bg-green-800`],
243 [`/electric`, `Electric`, `bg-blue-500 hover:bg-blue-600`],
244 [`/trailbase`, `TrailBase`, `bg-purple-600 hover:bg-purple-700`],
245 ]
246​
247 return (
248 <nav className="flex justify-center gap-4 mb-4">
249 <Link to="/" className={`${style} bg-gray-500 hover:bg-gray-600`}>
250 ← Home
251 </Link>
252​
253 {links.map(([href, name, cls]) => (
254 <Link key={href} to={href} className={`${style} ${cls}`}>
255 {name}
256 </Link>
257 ))}
258 </nav>
259 )