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

queries.ts

301 lines10.0 KB

1import {
2 and,
3 count,
4 createLiveQueryCollection,
5 eq,
6 isNull,
7 lower,
8 not,
9 sum,
10 useLiveQuery,
11} from "@tanstack/react-db";
12import type { InitialQueryBuilder, Ref } from "@tanstack/react-db";
13import { useEffect, useSyncExternalStore } from "react";
14​
15import { isSmartFolderId, resolveFolderView } from "@/lib/notes/folder-views";
16import type { FolderView, SmartFolderId } from "@/lib/notes/folder-views";
17import { countWords } from "@/lib/notes/note-body";
18import type { NoteListOptions } from "@/lib/notes/note-list";
19​
20import { accountCollection, foldersCollection, notesCollection } from "./collections";
21import type { Account, Folder, Note, SortNotesBy } from "./schema";
22​
23/**
24 * Every screen of the Notes app reads its data through these hooks, and each
25 * one is a live query. When a note changes (an edit, an optimistic update, a
26 * rollback, a refetch), every query that includes it updates at once: the
27 * list, the editor, the folder counts and the tab title.
28 */
29​
30// #region in-folder
31/** Which notes a folder shows. Smart folders aren't stored anywhere: they're just filters. */
32export function inFolder(note: Ref<Note>, folderId: string) {
33 const notDeleted = isNull(note.deletedAt);
34 switch (folderId) {
35 case "all":
36 return notDeleted;
37 case "shared":
38 return and(notDeleted, eq(note.shared, true));
39 case "recently-deleted":
40 return not(notDeleted);
41 default:
42 return and(notDeleted, eq(note.folderId, folderId));
43 }
45// #endregion in-folder
46​
47export function useFolders(): Folder[] {
48 const { data: folders } = useLiveQuery({
49 query: (q) =>
50 q.from({ folder: foldersCollection }).orderBy(({ folder }) => folder.position, "asc"),
51 });
52 return folders;
54​
55/** A folder or smart folder by id; `undefined` once loaded means it doesn't exist. */
56export function useFolderView(folderId: string): {
57 view: FolderView | undefined;
58 isReady: boolean;
59} {
60 const { data: folder, isReady } = useLiveQuery({
61 query: (q) =>
62 isSmartFolderId(folderId)
63 ? undefined
64 : q
65 .from({ folder: foldersCollection })
66 .where(({ folder }) => eq(folder.id, folderId))
67 .findOne(),
68 });
69 if (isSmartFolderId(folderId)) return { view: resolveFolderView(folderId, []), isReady: true };
70 return { view: folder ? resolveFolderView(folderId, [folder]) : undefined, isReady };
72​
73/** A note in a list, with the name of the folder it's in (cross-folder views show it). */
74export type NoteListItem = Note & { folderName: string | undefined };
75​
76/** The date a sort order is about; the list groups notes by it. */
77export const SORT_DATE_FIELD = {
78 dateEdited: "updatedAt",
79 dateCreated: "createdAt",
80 title: null,
81} as const satisfies Record<SortNotesBy, keyof Note | null>;
82​
83// #region note-list-query
84/** A folder's notes: pinned first, then in the order picked in Settings. */
85export function noteListQuery(folderId: string, sortNotesBy: SortNotesBy) {
86 return (q: InitialQueryBuilder) =>
87 q
88 .from({ note: notesCollection })
89 .leftJoin({ folder: foldersCollection }, ({ note, folder }) => eq(note.folderId, folder.id))
90 .where(({ note }) => inFolder(note, folderId))
91 .orderBy(({ note }) => note.pinned, "desc")
92 .orderBy(
93 ({ note }) =>
94 sortNotesBy === "title"
95 ? lower(note.title)
96 : sortNotesBy === "dateCreated"
97 ? note.createdAt
98 : note.updatedAt,
99 sortNotesBy === "title" ? "asc" : "desc",
100 )
101 .select(({ note, folder }) => ({ ...note, folderName: folder?.name }));
103// #endregion note-list-query
104​
105export function useNoteList(folderId: string): {
106 notes: NoteListItem[];
107 isReady: boolean;
108 listOptions: NoteListOptions;
109} {
110 const account = useAccount();
111 const sortNotesBy = account?.sortNotesBy ?? "dateEdited";
112​
113 const { data: notes, isReady } = useLiveQuery({
114 query: noteListQuery(folderId, sortNotesBy),
115 });
116 const listOptions = {
117 dateField: SORT_DATE_FIELD[sortNotesBy],
118 groupByDate: account?.groupNotesByDate ?? true,
119 };
120 return { notes, isReady, listOptions };
122​
123/** The most recently edited note a (smart) folder shows: one row, or none. */
124export function newestNoteQuery(folderId: string) {
125 return (q: InitialQueryBuilder) =>
126 q
127 .from({ note: notesCollection })
128 .where(({ note }) => inFolder(note, folderId))
129 .orderBy(({ note }) => note.updatedAt, "desc")
130 .limit(1)
131 .select(({ note }) => ({ id: note.id }));
133​
134/** A note, but only if it's in the folder (or smart folder) that's open. */
135export function useNoteInFolder(
136 folderId: string,
137 noteId: string,
138): { note: Note | undefined; isReady: boolean } {
139 const { data: note, isReady } = useLiveQuery({
140 query: (q) =>
141 q
142 .from({ note: notesCollection })
143 .where(({ note }) => and(eq(note.id, noteId), inFolder(note, folderId)))
144 .findOne(),
145 });
146 return { note, isReady };
148​
149// #region note-counts-query
150/** Notes per folder (Recently Deleted not included). */
151export function noteCountsQuery(q: InitialQueryBuilder) {
152 return q
153 .from({ note: notesCollection })
154 .where(({ note }) => isNull(note.deletedAt))
155 .groupBy(({ note }) => note.folderId)
156 .select(({ note }) => ({ folderId: note.folderId, count: count(note.id) }));
158// #endregion note-counts-query
159​
160/** How many notes a (smart) folder shows: one row, or none when it's empty. */
161export function noteCountQuery(folderId: string) {
162 return (q: InitialQueryBuilder) =>
163 q
164 .from({ note: notesCollection })
165 .where(({ note }) => inFolder(note, folderId))
166 .select(({ note }) => ({ count: count(note.id) }));
168​
169/** How many notes each folder and smart folder shows, keyed by folder id. */
170export function useNoteCounts(): Record<string, number> {
171 const { data: perFolder } = useLiveQuery({ query: noteCountsQuery });
172 const all = useSmartFolderCount("all");
173 const shared = useSmartFolderCount("shared");
174 const recentlyDeleted = useSmartFolderCount("recently-deleted");
175​
176 return {
177 ...Object.fromEntries(perFolder.map((row) => [row.folderId, row.count])),
178 all,
179 shared,
180 "recently-deleted": recentlyDeleted,
181 };
183​
184function useSmartFolderCount(folderId: SmartFolderId): number {
185 const { data } = useLiveQuery({ query: noteCountQuery(folderId) });
186 // An aggregate over no rows has no result row.
187 return data[0]?.count ?? 0;
189​
190/** The signed-in account (there's exactly one). */
191export function useAccount(): Account | undefined {
192 const { data: account } = useLiveQuery({
193 query: (q) => q.from({ account: accountCollection }).findOne(),
194 });
195 return account;
197​
198/* Analytics */
199​
200/** The local calendar day of a timestamp, as `YYYY-MM-DD`. */
201export function localDay(timestamp: string): string {
202 const date = new Date(timestamp);
203 const month = String(date.getMonth() + 1).padStart(2, "0");
204 const day = String(date.getDate()).padStart(2, "0");
205 return `${date.getFullYear()}-${month}-${day}`;
207​
208// #region note-stats-collection
209/**
210 * One row per note with the numbers the analytics page adds up. The query
211 * builder has no "count words" function, so `fn.select` runs plain
212 * JavaScript, once per note and again only when that note changes. A live
213 * query is a collection too, so the queries below group this one.
214 */
215export const noteStatsCollection = createLiveQueryCollection((q) =>
216 q
217 .from({ note: notesCollection })
218 .where(({ note }) => isNull(note.deletedAt))
219 .fn.select(({ note }) => ({
220 id: note.id,
221 folderId: note.folderId,
222 words: countWords(note),
223 lastEditedOn: localDay(note.updatedAt),
224 })),
225);
226// #endregion note-stats-collection
227​
228// #region folder-stats-query
229/** Notes and words per folder (Recently Deleted not included). */
230export function folderStatsQuery(q: InitialQueryBuilder) {
231 return q
232 .from({ stats: noteStatsCollection })
233 .groupBy(({ stats }) => stats.folderId)
234 .select(({ stats }) => ({
235 folderId: stats.folderId,
236 notes: count(stats.id),
237 words: sum(stats.words),
238 }));
240// #endregion folder-stats-query
241​
242/** How many notes were last edited on each day, newest day first. */
243export function editsPerDayQuery(q: InitialQueryBuilder) {
244 return q
245 .from({ stats: noteStatsCollection })
246 .groupBy(({ stats }) => stats.lastEditedOn)
247 .select(({ stats }) => ({ day: stats.lastEditedOn, notes: count(stats.id) }))
248 .orderBy(({ $selected }) => $selected.day, "desc");
250​
251export function useFolderStats() {
252 return useLiveQuery({ query: folderStatsQuery }).data;
254​
255export function useEditsPerDay() {
256 return useLiveQuery({ query: editsPerDayQuery }).data;
258​
259/* Loading */
260​
261const appCollections = [foldersCollection, notesCollection, accountCollection];
262​
263export type AppDataStatus = "loading" | "ready" | "error";
264​
265function getAppDataStatus(): AppDataStatus {
266 if (appCollections.some((collection) => collection.status === "error")) return "error";
267 return appCollections.every((collection) => collection.isReady()) ? "ready" : "loading";
269​
270function subscribeToAppDataStatus(listener: () => void) {
271 const unsubscribes = appCollections.map((collection) => collection.on("status:change", listener));
272 return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
274​
275/**
276 * Loads every collection and reports when all of them are ready. The Notes
277 * app stays mounted for the whole visit, and so do these subscriptions: the
278 * collections are never garbage-collected, so screens that come and go
279 * always find their data (and your edits) in place.
280 */
281export function useAppData(): { status: AppDataStatus; retry: () => void } {
282 useEffect(() => {
283 const subscriptions = [
284 foldersCollection.subscribeChanges(() => {}),
285 notesCollection.subscribeChanges(() => {}),
286 accountCollection.subscribeChanges(() => {}),
287 ];
288 return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
289 }, []);
290 const status = useSyncExternalStore(
291 subscribeToAppDataStatus,
292 getAppDataStatus,
293 (): AppDataStatus => "loading",
294 );
295 return {
296 status,
297 retry: () => {
298 for (const collection of appCollections) void collection.utils.refetch();
299 },
300 };