-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvoluMultitenantExample.tsx
More file actions
347 lines (304 loc) · 10.4 KB
/
EvoluMultitenantExample.tsx
File metadata and controls
347 lines (304 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"use client";
import * as Evolu from "@evolu/common";
import { createUseEvolu, EvoluProvider, useQuery } from "@evolu/react";
import { createEvoluDeps } from "@evolu/react-web";
import { IconEdit, IconTrash } from "@tabler/icons-react";
import clsx from "clsx";
import { type FC, Suspense, use, useState } from "react";
const TodoId = Evolu.id("Todo");
// biome-ignore lint/correctness/noUnusedVariables: Context
type TodoId = typeof TodoId.Type;
const Schema = {
todo: {
id: TodoId,
// Branded type ensuring titles are non-empty and ≤100 chars.
title: Evolu.NonEmptyString100,
// SQLite doesn't support the boolean type; it uses 0 and 1 instead.
isCompleted: Evolu.nullOr(Evolu.SqliteBoolean),
},
};
const deps = createEvoluDeps();
// Create a typed query builder from the schema
const createQuery = Evolu.createQueryBuilder(Schema);
deps.evoluError.subscribe(() => {
const error = deps.evoluError.get();
if (!error) return;
alert("Evolu error occurred. Check the console.");
// eslint-disable-next-line no-console
console.error(error);
});
// const syncStats = createSyncStats(deps)
const evolu = Evolu.createEvolu(deps)(Schema, {
name: Evolu.SimpleName.orThrow("minimal-example"),
...(process.env.NODE_ENV === "development" && {
transports: [{ type: "WebSocket", url: "ws://localhost:4000" }],
}),
});
const useEvolu = createUseEvolu(evolu);
evolu.subscribeError(() => {
const error = evolu.getError();
if (!error) return;
alert("🚨 Evolu error occurred! Check the console.");
// eslint-disable-next-line no-console
console.error(error);
});
export const EvoluMultitenantExample: FC = () => (
<div className="min-h-screen px-8 py-8">
<div className="mx-auto max-w-md">
<div className="mb-2 flex items-center justify-between pb-4">
<h1 className="w-full text-center text-xl font-semibold text-gray-900">
Minimal Todo App
</h1>
</div>
<EvoluProvider value={evolu}>
<Suspense>
<Todos />
<OwnerActions />
</Suspense>
</EvoluProvider>
</div>
</div>
);
// Evolu uses Kysely for type-safe SQL (https://kysely.dev/).
const todosQuery = createQuery((db) =>
db
// Type-safe SQL: try autocomplete for table and column names.
.selectFrom("todo")
.select(["id", "title", "isCompleted"])
// Soft delete: filter out deleted rows.
.where("isDeleted", "is not", Evolu.sqliteTrue)
// Like with GraphQL, all columns except id are nullable in queries
// (even if defined without nullOr in the schema) to allow schema
// evolution without migrations. Filter nulls with where + $narrowType.
.where("title", "is not", null)
.$narrowType<{ title: Evolu.kysely.NotNull }>()
// Columns createdAt, updatedAt, isDeleted are auto-added to all tables.
.orderBy("createdAt"),
);
// Extract the row type from the query for type-safe component props.
type TodosRow = typeof todosQuery.Row;
const Todos: FC = () => {
// useQuery returns live data - component re-renders when data changes.
const todos = useQuery(todosQuery);
const { insert } = useEvolu();
const [newTodoTitle, setNewTodoTitle] = useState("");
const addTodo = () => {
const result = insert(
"todo",
{
title: newTodoTitle.trim(),
},
{
onComplete: () => {
setNewTodoTitle("");
},
},
);
if (!result.ok) {
alert(formatTypeError(result.error));
}
};
return (
<div className="rounded-lg bg-white p-6 shadow-sm ring-1 ring-gray-200">
<ol className="mb-6 space-y-2">
{todos.map((todo) => (
<TodoItem key={todo.id} row={todo} />
))}
</ol>
<div className="flex gap-2">
<input
type="text"
value={newTodoTitle}
onChange={(e) => {
setNewTodoTitle(e.target.value);
}}
onKeyDown={(e) => {
if (e.key === "Enter") addTodo();
}}
placeholder="Add a new todo..."
className="block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 sm:text-sm/6"
/>
<Button title="Add" onClick={addTodo} variant="primary" />
</div>
</div>
);
};
const TodoItem: FC<{
row: TodosRow;
}> = ({ row: { id, title, isCompleted } }) => {
const { update } = useEvolu();
const handleToggleCompletedClick = () => {
update("todo", {
id,
isCompleted: Evolu.booleanToSqliteBoolean(!isCompleted),
});
};
const handleRenameClick = () => {
const newTitle = window.prompt("Edit todo", title);
if (newTitle == null) return;
const result = update("todo", { id, title: newTitle });
if (!result.ok) {
alert(formatTypeError(result.error));
}
};
const handleDeleteClick = () => {
update("todo", {
id,
// Soft delete with isDeleted flag (CRDT-friendly, preserves sync history).
isDeleted: Evolu.sqliteTrue,
});
};
return (
<li className="-mx-2 flex items-center gap-3 px-2 py-2 hover:bg-gray-50">
<label className="flex flex-1 cursor-pointer items-center gap-3">
<input
type="checkbox"
checked={!!isCompleted}
onChange={handleToggleCompletedClick}
className="col-start-1 row-start-1 appearance-none rounded-sm border border-gray-300 bg-white checked:border-blue-600 checked:bg-blue-600 indeterminate:border-blue-600 indeterminate:bg-blue-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:border-gray-300 disabled:bg-gray-100 disabled:checked:bg-gray-100 forced-colors:appearance-auto"
/>
<span
className={clsx(
"flex-1 text-sm",
isCompleted ? "text-gray-500 line-through" : "text-gray-900",
)}
>
{title}
</span>
</label>
<div className="flex gap-1">
<button
onClick={handleRenameClick}
className="p-1 text-gray-400 transition-colors hover:text-blue-600"
title="Edit"
>
<IconEdit className="size-4" />
</button>
<button
onClick={handleDeleteClick}
className="p-1 text-gray-400 transition-colors hover:text-red-600"
title="Delete"
>
<IconTrash className="size-4" />
</button>
</div>
</li>
);
};
const OwnerActions: FC = () => {
const evolu = useEvolu();
const appOwner = use(evolu.appOwner);
const [showMnemonic, setShowMnemonic] = useState(false);
const handleRestoreAppOwnerClick = () => {
const mnemonic = window.prompt("Enter your mnemonic to restore your data:");
if (mnemonic == null) return;
const result = Evolu.Mnemonic.from(mnemonic.trim());
if (!result.ok) {
alert(formatTypeError(result.error));
return;
}
// void evolu.restoreAppOwner(result.value);
};
const handleResetAppOwnerClick = () => {
if (confirm("Are you sure? This will delete all your local data.")) {
// void evolu.resetAppOwner();
}
};
const handleDownloadDatabaseClick = () => {
void evolu.exportDatabase().then((data) => {
using objectUrl = Evolu.createObjectURL(
new Blob([data], { type: "application/x-sqlite3" }),
);
const link = document.createElement("a");
link.href = objectUrl.url;
link.download = `${evolu.name}.sqlite3`;
link.click();
});
};
return (
<div className="mt-8 rounded-lg bg-white p-6 shadow-sm ring-1 ring-gray-200">
<h2 className="mb-4 text-lg font-medium text-gray-900">Account</h2>
<p className="mb-4 text-sm text-gray-600">
Todos are stored in local SQLite. When you sync across devices, your
data is end-to-end encrypted using your mnemonic.
</p>
<div className="space-y-3">
<Button
title={`${showMnemonic ? "Hide" : "Show"} Mnemonic`}
onClick={() => {
setShowMnemonic(!showMnemonic);
}}
className="w-full"
/>
{showMnemonic && appOwner.mnemonic && (
<div className="bg-gray-50 p-3">
<label className="mb-2 block text-xs font-medium text-gray-700">
Your Mnemonic (keep this safe!)
</label>
<textarea
value={appOwner.mnemonic}
readOnly
rows={3}
className="w-full border-b border-gray-300 bg-white px-2 py-1 font-mono text-xs focus:border-blue-500 focus:outline-none"
/>
</div>
)}
<div className="flex gap-2">
<Button
title="Restore from Mnemonic"
onClick={handleRestoreAppOwnerClick}
/>
<Button title="Reset All Data" onClick={handleResetAppOwnerClick} />
<Button
title="Download Backup"
onClick={handleDownloadDatabaseClick}
/>
</div>
</div>
</div>
);
};
const Button: FC<{
title: string;
className?: string;
onClick: () => void;
variant?: "primary" | "secondary";
}> = ({ title, className, onClick, variant = "secondary" }) => {
const baseClasses =
"px-3 py-2 text-sm font-medium rounded-lg transition-colors";
const variantClasses =
variant === "primary"
? "bg-blue-600 text-white hover:bg-blue-700"
: "bg-gray-100 text-gray-700 hover:bg-gray-200";
return (
<button
className={clsx(baseClasses, variantClasses, className)}
onClick={onClick}
>
{title}
</button>
);
};
/**
* Formats Evolu Type errors into user-friendly messages.
*
* Evolu Type typed errors ensure every error type used in schema must have a
* formatter. TypeScript enforces this at compile-time, preventing unhandled
* validation errors from reaching users.
*
* The `createFormatTypeError` function handles both built-in and custom errors,
* and lets us override default formatting for specific errors.
*
* Click on `createFormatTypeError` below to see how to write your own
* formatter.
*/
const formatTypeError = Evolu.createFormatTypeError<
Evolu.MinLengthError | Evolu.MaxLengthError
>((error): string => {
switch (error.type) {
case "MinLength":
return `Text must be at least ${error.min} character${error.min === 1 ? "" : "s"} long`;
case "MaxLength":
return `Text is too long (maximum ${error.max} characters)`;
}
});