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

App.tsx

343 lines10.5 KB

1import React, { useState } from "react"
2import { createElectricSync, useCollection } from "@tanstack/react-optimistic"
3import { DevTools } from "./DevTools"
4import { updateConfigSchema, updateTodoSchema } from "./db/validation"
5import type { UpdateConfig, UpdateTodo } from "./db/validation"
6import type { Collection } from "@tanstack/react-optimistic"
7import type { FormEvent } from "react"
8​
9export default function App() {
10 const [newTodo, setNewTodo] = useState(``)
11​
12 const {
13 data: todos,
14 insert,
15 update,
16 delete: deleteTodo,
17 } = useCollection<UpdateTodo>({
18 id: `todos`,
19 sync: createElectricSync(
20 {
21 url: `http://localhost:3000/v1/shape`,
22 params: {
23 table: `todos`,
24 },
25 parser: {
26 // Parse timestamp columns into JavaScript Date objects
27 timestamptz: (date: string) => new Date(date),
28 },
29 },
30 { primaryKey: [`id`] }
31 ),
32 schema: updateTodoSchema,
33 mutationFn: {
34 persist: async ({ transaction }) => {
35 const response = await fetch(`http://localhost:3001/api/mutations`, {
36 method: `POST`,
37 headers: {
38 "Content-Type": `application/json`,
39 },
40 body: JSON.stringify(transaction.mutations),
41 })
42 if (!response.ok) {
43 throw new Error(`HTTP error! Status: ${response.status}`)
44 }
45​
46 const result = await response.json()
47 return {
48 txid: result.txid,
49 }
50 },
51 awaitSync: async ({
52 persistResult,
53 collection,
54 }: {
55 persistResult: { txid: number }
56 collection: Collection
57 }) => {
58 // Start waiting for the txid
59 await collection.config.sync.awaitTxid(persistResult.txid)
60 },
61 },
62 })
63​
64 const {
65 data: configData,
66 update: updateConfig,
67 insert: insertConfig,
68 } = useCollection<UpdateConfig>({
69 id: `config`,
70 sync: createElectricSync(
71 {
72 url: `http://localhost:3000/v1/shape`,
73 params: {
74 table: `config`,
75 },
76 parser: {
77 // Parse timestamp columns into JavaScript Date objects
78 timestamptz: (date: string) => {
79 return new Date(date)
80 },
81 },
82 },
83 { primaryKey: [`id`] }
84 ),
85 schema: updateConfigSchema,
86 mutationFn: {
87 persist: async ({ transaction }) => {
88 const response = await fetch(`http://localhost:3001/api/mutations`, {
89 method: `POST`,
90 headers: {
91 "Content-Type": `application/json`,
92 },
93 body: JSON.stringify(transaction.mutations),
94 })
95 if (!response.ok) {
96 throw new Error(`HTTP error! Status: ${response.status}`)
97 }
98​
99 const result = await response.json()
100 return {
101 txid: result.txid,
102 }
103 },
104 awaitSync: async ({
105 persistResult,
106 collection,
107 }: {
108 persistResult: { txid: number }
109 collection: Collection
110 }) => {
111 // Start waiting for the txid
112 await collection.config.sync.awaitTxid(persistResult.txid)
113 },
114 },
115 })
116​
117 // Define a more robust type-safe helper function to get config values
118 const getConfigValue = (key: string): string => {
119 for (const config of configData) {
120 if (config.key === key) {
121 return config.value!
122 }
123 }
124 return ``
125 }
126​
127 // Define a helper function to update config values
128 const setConfigValue = (key: string, value: string): void => {
129 for (const config of configData) {
130 if (config.key === key) {
131 updateConfig(config, (draft) => {
132 draft.value = value
133 })
134​
135 return
136 }
137 }
138​
139 // If the config doesn't exist yet, create it
140 insertConfig({
141 key,
142 value,
143 })
144 }
145​
146 const backgroundColor = getConfigValue(`backgroundColor`)
147​
148 // Function to generate a complementary color
149 const getComplementaryColor = (hexColor: string): string => {
150 // Default to a nice blue if no color is provided
151 if (!hexColor) return `#3498db`
152​
153 // Remove the hash if it exists
154 const color = hexColor.replace(`#`, ``)
155​
156 // Convert hex to RGB
157 const r = parseInt(color.substr(0, 2), 16)
158 const g = parseInt(color.substr(2, 2), 16)
159 const b = parseInt(color.substr(4, 2), 16)
160​
161 // Calculate complementary color (inverting the RGB values)
162 const compR = 255 - r
163 const compG = 255 - g
164 const compB = 255 - b
165​
166 // Convert back to hex
167 const compHex =
168 `#` +
169 ((1 << 24) + (compR << 16) + (compG << 8) + compB).toString(16).slice(1)
170​
171 // Calculate brightness of the background
172 const brightness = r * 0.299 + g * 0.587 + b * 0.114
173​
174 // If the complementary color doesn't have enough contrast, adjust it
175 const compBrightness = compR * 0.299 + compG * 0.587 + compB * 0.114
176 const brightnessDiff = Math.abs(brightness - compBrightness)
177​
178 if (brightnessDiff < 128) {
179 // Not enough contrast, use a more vibrant alternative
180 if (brightness > 128) {
181 // Dark color for light background
182 return `#8e44ad` // Purple
183 } else {
184 // Light color for dark background
185 return `#f1c40f` // Yellow
186 }
187 }
188​
189 return compHex
190 }
191​
192 const titleColor = getComplementaryColor(backgroundColor)
193​
194 const handleColorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
195 const newColor = e.target.value
196 setConfigValue(`backgroundColor`, newColor)
197 }
198​
199 const handleSubmit = (e: FormEvent) => {
200 e.preventDefault()
201 if (!newTodo.trim()) return
202​
203 insert({
204 text: newTodo,
205 completed: false,
206 })
207 setNewTodo(``)
208 }
209​
210 const toggleTodo = (todo: UpdateTodo) => {
211 update(todo, (draft) => {
212 draft.completed = !draft.completed
213 })
214 }
215​
216 const activeTodos = todos.filter((todo) => !todo.completed)
217 const completedTodos = todos.filter((todo) => todo.completed)
218​
219 return (
220 <>
221 <div
222 className="min-h-screen flex items-start justify-center overflow-auto py-8"
223 style={{ backgroundColor }}
224 >
225 <div style={{ width: 550 }} className="mx-auto relative">
226 <h1
227 className="text-[100px] font-bold text-center mb-8"
228 style={{ color: titleColor }}
229 >
230 todos
231 </h1>
232​
233 <div className="mb-4 flex justify-end">
234 <div className="flex items-center">
235 <label
236 htmlFor="colorPicker"
237 className="mr-2 text-sm font-medium text-gray-700"
238 style={{ color: titleColor }}
239 >
240 Background Color:
241 </label>
242 <input
243 type="color"
244 id="colorPicker"
245 value={backgroundColor}
246 onChange={handleColorChange}
247 className="cursor-pointer border border-gray-300 rounded"
248 />
249 </div>
250 </div>
251​
252 <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">
253 <form onSubmit={handleSubmit} className="relative">
254 {todos.length > 0 && (
255 <button
256 type="button"
257 className="absolute left-0 w-12 h-full text-[30px] text-[#e6e6e6] hover:text-[#4d4d4d]"
258 onClick={() => {
259 const allCompleted = completedTodos.length === todos.length
260 update(
261 allCompleted ? completedTodos : activeTodos,
262 (drafts) => {
263 drafts.forEach(
264 (draft) => (draft.completed = !allCompleted)
265 )
266 }
267 )
268 }}
269 >
270 ❯
271 </button>
272 )}
273 <input
274 type="text"
275 value={newTodo}
276 onChange={(e) => setNewTodo(e.target.value)}
277 placeholder="What needs to be done?"
278 className="w-full py-4 pl-[60px] pr-4 text-2xl font-light border-none shadow-[inset_0_-2px_1px_rgba(0,0,0,0.03)] box-border"
279 style={{
280 background: `rgba(0, 0, 0, 0.003)`,
281 }}
282 />
283 </form>
284​
285 {todos.length > 0 && (
286 <>
287 <ul className="my-0 mx-0 p-0 list-none">
288 {todos.map((todo) => (
289 <li
290 key={`todo-${todo.id}`}
291 className="relative border-b border-[#ededed] last:border-none group"
292 >
293 <div className="flex items-center h-[58px] pl-[60px]">
294 <input
295 type="checkbox"
296 checked={todo.completed}
297 onChange={() => toggleTodo(todo)}
298 className="absolute left-[12px] top-0 bottom-0 my-auto h-[40px] w-[40px] cursor-pointer"
299 />
300 <label
301 className={`block leading-[1.2] py-[15px] px-[15px] text-2xl transition-colors ${
302 todo.completed ? `text-[#d9d9d9] line-through` : ``
303 }`}
304 >
305 {todo.text}
306 </label>
307 <button
308 onClick={() => deleteTodo(todo)}
309 className="hidden group-hover:block absolute right-[10px] w-[40px] h-[40px] my-auto top-0 bottom-0 text-[30px] text-[#cc9a9a] hover:text-[#af5b5e] transition-colors"
310 >
311 ×
312 </button>
313 </div>
314 </li>
315 ))}
316 </ul>
317​
318 <footer className="text-[14px] text-[#777] py-[10px] px-[15px] h-[40px] relative border-t border-[#e6e6e6] flex justify-between items-center">
319 <span className="text-[inherit]">
320 {activeTodos.length}
321 {` `}
322 {activeTodos.length === 1 ? `item` : `items`} left
323 </span>
324 {completedTodos.length > 0 && (
325 <button
326 onClick={() => {
327 deleteTodo(completedTodos)
328 }}
329 className="text-inherit hover:underline"
330 >
331 Clear completed
332 </button>
333 )}
334 </footer>
335 </>
336 )}
337 </div>
338 </div>
339 </div>
340 <DevTools />
341 </>
342 )