Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

content.tsx

390 lines16.1 KB

1/**
2 * The guide: one section per idea, each with something to do in the app.
3 * Section ids are stable: phase 4 maps app state to them (`appStates`), and
4 * the dev menu, the mobile header chip and section progress refer to them.
5 *
6 * Code snippets come from `snippets.ts`, which quotes the app's own source.
7 * Copy has to work in both layouts: the app beside the guide (wide screens)
8 * and the app in a sheet opened with "Try it" (phones). Where it can't, use
9 * `ByGuideLayout`.
10 */
11import { Link, linkOptions } from "@tanstack/react-router";
12import type { LinkOptions } from "@tanstack/react-router";
13import type { ReactNode } from "react";
14​
15import { Callout } from "@/components/guide/callout";
16import { SourceSnippet } from "@/components/guide/source-snippet";
17import { ByGuideLayout } from "@/components/guide/try-it";
18import { NOTE_TITLE_MAX_LENGTH } from "@/api/fake-server";
19import type { AppActionMatcher } from "@/lib/app-actions";
20import type { AppState } from "@/lib/app-state";
21​
22import { SNIPPETS } from "./snippets";
23​
24export interface GuideSectionContent {
25 id: string;
26 eyebrow: string;
27 title: string;
28 /** Label for the active-section chip in the mobile header. Keep it short: it's never truncated. */
29 shortTitle: string;
30 /**
31 * The app states this section explains (phase 4 highlights the section
32 * when the app is in one of them). Empty when no app state matches it.
33 */
34 appStates: AppState[];
35 /**
36 * The app screen this section's hands-on step happens on. Sections with one
37 * get a "Try it" button on mobile that opens the app there.
38 */
39 tryIt?: LinkOptions;
40 /**
41 * The app actions that count as doing this section's hands-on step; the
42 * first one that happens marks the section done (see `section-progress.ts`).
43 */
44 doneWhen?: AppActionMatcher[];
45 content: ReactNode;
47​
48export const DOCS = {
49 overview: "https://tanstack.com/db/latest/docs/overview",
50 liveQueries: "https://tanstack.com/db/latest/docs/guides/live-queries",
51 mutations: "https://tanstack.com/db/latest/docs/guides/mutations",
52 concurrentTransactions:
53 "https://tanstack.com/db/latest/docs/guides/mutations#concurrent-optimistic-transactions",
54 queryCollection: "https://tanstack.com/db/latest/docs/collections/query-collection",
55 github: "https://github.com/TanStack/db",
56} as const;
57​
58function External({ href, children }: { href: string; children: ReactNode }) {
59 return (
60 <a href={href} target="_blank" rel="noreferrer">
61 {children}
62 </a>
63 );
65​
66export const GUIDE_SECTIONS: GuideSectionContent[] = [
67 {
68 id: "introduction",
69 eyebrow: "Start here",
70 title: "A notes app where every view is a query",
71 shortTitle: "Intro",
72 appStates: [{ screen: "/" }],
73 tryIt: linkOptions({ to: "/" }),
74 doneWhen: [{ type: "note.opened" }],
75 content: (
76 <>
77 <p>
78 This guide comes with a small copy of Apple Notes, built with <strong>TanStack DB</strong>
79 .{" "}
80 <ByGuideLayout
81 beside="It's in the browser window next to this guide."
82 inSheet="Tap Try it under a section to open it, and close it to come back here."
83 />
84 </p>
85 <p>
86 There's no real server. The app talks to a fake API that runs in your browser: every
87 request takes half a second, and some changes get rejected, like on a real backend. Each
88 section tells you what to do in the app and what to look for.
89 </p>
90 <Callout variant="tip">
91 Look around first: open a folder, pick a note, and open Settings from the account at the
92 bottom of the folder list.
93 </Callout>
94 </>
95 ),
96 },
97 {
98 id: "collections",
99 eyebrow: "Step 1",
100 title: "What are collections?",
101 shortTitle: "Collections",
102 appStates: [
103 { screen: "/folders/$folderId", lastAction: { type: "folder.opened", smart: false } },
104 { screen: "/folders/$folderId/notes/$noteId", lastAction: { type: "note.opened" } },
105 ],
106 tryIt: linkOptions({ to: "/" }),
107 doneWhen: [{ type: "folder.opened", smart: false }],
108 content: (
109 <>
110 <p>
111 A collection is a typed set of records that TanStack DB keeps in memory and in sync with
112 your backend. This app has three: folders, notes and your account.
113 </p>
114 <p>
115 Here's the notes collection. <code>queryFn</code> loads every note from the API, and{" "}
116 <code>getKey</code> tells them apart. The <code>schema</code> checks the notes you create
117 and change in the app, before anything is sent. (Notes loaded by <code>queryFn</code> skip
118 it: this app trusts its own API.) The three handlers send your changes to the server;
119 we'll get to them.
120 </p>
121 <SourceSnippet snippet={SNIPPETS.notesCollection} />
122 <p>
123 The note list, the editor and the folder counts all read from this one collection. There's
124 only one copy of each note, so when it changes, every view that shows it changes with it.
125 </p>
126 <Callout variant="tip">
127 Open a folder and edit a note's title. The note's row in the list shows the new title as
128 you type (in the iPhone layout, go back to the list to see it).
129 </Callout>
130 </>
131 ),
132 },
133 {
134 id: "live-queries",
135 eyebrow: "Step 2",
136 title: "Live queries",
137 shortTitle: "Live queries",
138 appStates: [
139 { screen: "/folders/$folderId", lastAction: { type: "folder.opened", smart: true } },
140 { lastAction: { type: "note.pinned" } },
141 { screen: "/settings", lastAction: { type: "account.updated" } },
142 ],
143 tryIt: linkOptions({ to: "/folders/$folderId", params: { folderId: "all" } }),
144 doneWhen: [{ type: "folder.opened", smart: true }, { type: "note.pinned" }],
145 content: (
146 <>
147 <p>
148 You don't read a collection directly. You ask it questions with live queries, and their
149 results stay up to date on their own.
150 </p>
151 <p>
152 Each folder's list is one live query: the notes in that folder, joined with their folder's
153 name, pinned notes first, then in the order picked in Settings.
154 </p>
155 <SourceSnippet snippet={SNIPPETS.noteListQuery} />
156 <p>
157 Smart folders like All iCloud, Shared and Recently Deleted aren't stored anywhere. Each
158 one is just a different <code>where</code> condition:
159 </p>
160 <SourceSnippet snippet={SNIPPETS.inFolder} />
161 <p>
162 Live queries are fast because they don't run again from scratch when data changes.
163 TanStack DB compiles each query into a pipeline that only processes what changed, so
164 editing one note updates one row of each result, not the whole list.
165 </p>
166 <Callout variant="tip">
167 Open All iCloud and pin a note: right-click it in the list (long-press in the iPhone
168 layout) and choose Pin Note. It moves to Pinned. Then change "Sort notes by" in Settings
169 and save: every list follows.
170 </Callout>
171 </>
172 ),
173 },
174 {
175 id: "optimistic-updates",
176 eyebrow: "Step 3",
177 title: "Optimistic updates",
178 shortTitle: "Optimistic updates",
179 appStates: [
180 { screen: "/folders/$folderId/notes/$noteId", lastAction: { type: "note.edited" } },
181 { lastAction: { type: "note.created" } },
182 { lastAction: { type: "note.moved" } },
183 { lastAction: { type: "note.deleted" } },
184 { lastAction: { type: "note.restored" } },
185 { lastAction: { type: "folder.renamed", status: "applied" } },
186 ],
187 tryIt: linkOptions({ to: "/folders/$folderId", params: { folderId: "work" } }),
188 doneWhen: [{ type: "note.edited" }, { type: "folder.renamed", status: "confirmed" }],
189 content: (
190 <>
191 <p>
192 When you change something, TanStack DB shows the change straight away and sends it to the
193 server in the background. That's an optimistic update: the app assumes the server will say
194 yes.
195 </p>
196 <p>
197 Renaming a folder is the simplest one. It updates the folder in its collection, and the
198 collection's <code>onUpdate</code> handler sends the change to the server. The function
199 returns the transaction, so a caller can wait for the server if it needs to.
200 </p>
201 <SourceSnippet snippet={SNIPPETS.renameFolder} />
202 <p>
203 Every request to the fake API takes half a second, but typing never waits for one. The
204 editor doesn't send a request for each key you press, either. Changes to a note go through
205 a <em>paced mutation</em>: each change shows up at once, and they're saved together when
206 you pause.
207 </p>
208 <SourceSnippet snippet={SNIPPETS.noteChanges} />
209 <h3>Why one paced mutation per note?</h3>
210 <p>
211 TanStack DB lets several changes be in flight at once. Each one that hasn't been saved yet
212 puts its own copy of the whole note on top of what the server last sent. If a newer change
213 finishes first, an older one that's still saving shows its copy again, so an old title can
214 come back for a moment. That's how TanStack DB is designed, not a bug: see{" "}
215 <External href={DOCS.concurrentTransactions}>concurrent optimistic transactions</External>
216 .
217 </p>
218 <p>
219 This app avoids it by sending every change to a note (typing, pinning, moving, deleting)
220 through the same paced mutation, <code>changeNote</code>, built with{" "}
221 <code>pacedPerRecord</code>. Its saves go out one at a time, in order, so a newer change
222 never sits under an older one.
223 </p>
224 <Callout variant="tip">
225 Type in a note: the list keeps up with every key. Then move a note to another folder from
226 its right-click (or long-press) menu: both folders' counts change at once, before the
227 server has answered.
228 </Callout>
229 </>
230 ),
231 },
232 {
233 id: "rollbacks",
234 eyebrow: "Step 4",
235 title: "Rollbacks",
236 shortTitle: "Rollbacks",
237 appStates: [{ lastAction: { status: "rolled-back" } }],
238 tryIt: linkOptions({ to: "/" }),
239 doneWhen: [{ status: "rolled-back" }],
240 content: (
241 <>
242 <p>
243 Sometimes the server says no. The fake API won't let two folders have the same name, just
244 like a real backend would check:
245 </p>
246 <SourceSnippet snippet={SNIPPETS.duplicateName} />
247 <p>
248 By then the new name is already on screen, so TanStack DB has to undo it. It does that
249 when the collection's handler throws. The handlers call the API through a small client
250 that throws for any error response:
251 </p>
252 <SourceSnippet snippet={SNIPPETS.throwOnError} />
253 <p>
254 The error fails the transaction, and TanStack DB drops its optimistic changes: the folder
255 gets its old name back. No component had to remember the old name.
256 </p>
257 <Callout variant="warning">
258 <code>fetch</code> doesn't throw for 4xx or 5xx responses. If your handler doesn't check{" "}
259 <code>response.ok</code> and throw, TanStack DB treats a failed save as a success.
260 </Callout>
261 <Callout variant="tip">
262 Rename the Work folder to "Personal". In the sidebar, double-click Work or right-click it
263 and choose Rename Folder. In the iPhone layout, tap Edit on the Folders screen, then tap
264 Work. The new name shows up, then switches back, and a message tells you why. A note title
265 longer than {NOTE_TITLE_MAX_LENGTH} characters gets rejected too.
266 </Callout>
267 </>
268 ),
269 },
270 {
271 id: "sync",
272 eyebrow: "Step 5",
273 title: "How collections sync",
274 shortTitle: "Syncing",
275 appStates: [{ lastAction: { status: "confirmed" } }],
276 content: (
277 <>
278 <p>
279 Data in this app flows one way: from the server into collections, from collections into
280 live queries, and from live queries into components. Components never change what they
281 show. They change a collection, and the change flows down from there, on top of the
282 server's data until the server answers.
283 </p>
284 <p>
285 The collections here are <em>query collections</em>, from{" "}
286 <code>@tanstack/query-db-collection</code>. They load data with a TanStack Query{" "}
287 <code>queryFn</code>. Saving doesn't refetch anything: each handler writes the record the
288 server sent back into the collection, so the collection holds exactly what the server
289 saved.
290 </p>
291 <SourceSnippet snippet={SNIPPETS.saveNoteUpdates} />
292 <p>
293 <code>inOrder</code> sends one note's requests one at a time, so an older save can't
294 arrive after a newer one. <code>saveEach</code> saves every record in the transaction,
295 even if one of them fails.
296 </p>
297 <p>
298 Query collections work with any REST or RPC API. Other collection types change how data
299 syncs, and keep the rest (live queries, optimistic updates, rollbacks) the same:
300 </p>
301 <ul>
302 <li>
303 Electric (<code>electricCollectionOptions</code>): real-time sync from Postgres
304 </li>
305 <li>PowerSync, RxDB and TrailBase, for offline-first and streaming backends</li>
306 <li>
307 Local-only, localStorage and IndexedDB collections, for data that stays in the browser
308 </li>
309 </ul>
310 <Callout variant="note">
311 The <Link to="/deep-dives/query-driven-sync">query-driven sync</Link> deep dive goes
312 further: it loads only the notes a query needs.
313 </Callout>
314 </>
315 ),
316 },
317 {
318 id: "aggregations",
319 eyebrow: "Step 6",
320 title: "Aggregations",
321 shortTitle: "Aggregations",
322 appStates: [{ screen: "/analytics" }],
323 tryIt: linkOptions({ to: "/analytics" }),
324 content: (
325 <>
326 <p>
327 Live queries can group and count, too. The folder counts in the sidebar come from a{" "}
328 <code>groupBy</code> with <code>count</code>:
329 </p>
330 <SourceSnippet snippet={SNIPPETS.noteCountsQuery} />
331 <p>
332 The Analytics page, at the bottom of the folder list, also adds up the words in each
333 folder. The query builder has no function that counts words, so a first live query works
334 out each note's numbers with <code>fn.select</code>, which runs plain JavaScript:
335 </p>
336 <SourceSnippet snippet={SNIPPETS.noteStatsCollection} />
337 <p>A live query is a collection itself, so a second query can group the first one:</p>
338 <SourceSnippet snippet={SNIPPETS.folderStatsQuery} />
339 <p>
340 Like every live query, these update step by step. When you type in a note, only that
341 note's numbers are worked out again, and only its folder's total changes.
342 </p>
343 <Callout variant="tip">
344 Open Analytics and note a folder's word count. Add a few words to one of its notes, then
345 go back to Analytics: the count has gone up.
346 </Callout>
347 </>
348 ),
349 },
350 {
351 id: "whats-next",
352 eyebrow: "Wrap-up",
353 title: "What's next",
354 shortTitle: "What's next",
355 appStates: [],
356 content: (
357 <>
358 <p>
359 That's the core of TanStack DB: collections hold your data, live queries read it,
360 optimistic mutations change it, and rejected changes roll back on their own.
361 </p>
362 <h3>Deep dives</h3>
363 <ul>
364 <li>
365 <Link to="/deep-dives/query-driven-sync">Query-driven sync</Link>: load only the notes a
366 live query asks for, with <code>syncMode: "on-demand"</code>.
367 </li>
368 </ul>
369 <h3>Docs</h3>
370 <ul>
371 <li>
372 <External href={DOCS.overview}>TanStack DB overview</External>
373 </li>
374 <li>
375 <External href={DOCS.liveQueries}>Live queries</External>
376 </li>
377 <li>
378 <External href={DOCS.mutations}>Mutations</External>
379 </li>
380 <li>
381 <External href={DOCS.queryCollection}>Query collections</External>
382 </li>
383 <li>
384 <External href={DOCS.github}>TanStack DB on GitHub</External>
385 </li>
386 </ul>
387 </>
388 ),
389 },
390];