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

queries.ts

212 lines7.4 KB

1import { and, count, eq, isNull, lower, not, useLiveQuery } from "@tanstack/react-db";
2import type { InitialQueryBuilder, Ref } from "@tanstack/react-db";
3import { useEffect, useSyncExternalStore } from "react";
4​
5import { isSmartFolderId, resolveFolderView } from "@/lib/notes/folder-views";
6import type { FolderView, SmartFolderId } from "@/lib/notes/folder-views";
7import type { NoteListOptions } from "@/lib/notes/note-list";
8​
9import { accountCollection, foldersCollection, notesCollection } from "./collections";
10import type { Account, Folder, Note, SortNotesBy } from "./schema";
11​
12/**
13 * Every screen of the Notes app reads its data through these hooks, and each
14 * one is a live query. When a note changes (an edit, an optimistic update, a
15 * rollback, a refetch), every query that includes it updates at once: the
16 * list, the editor, the folder counts and the tab title.
17 */
18​
19/** Which notes a folder shows. Smart folders aren't stored anywhere: they're just filters. */
20export function inFolder(note: Ref<Note>, folderId: string) {
21 const notDeleted = isNull(note.deletedAt);
22 switch (folderId) {
23 case "all":
24 return notDeleted;
25 case "shared":
26 return and(notDeleted, eq(note.shared, true));
27 case "recently-deleted":
28 return not(notDeleted);
29 default:
30 return and(notDeleted, eq(note.folderId, folderId));
31 }
33​
34export function useFolders(): Folder[] {
35 const { data: folders } = useLiveQuery({
36 query: (q) =>
37 q.from({ folder: foldersCollection }).orderBy(({ folder }) => folder.position, "asc"),
38 });
39 return folders;
41​
42/** A folder or smart folder by id; `undefined` once loaded means it doesn't exist. */
43export function useFolderView(folderId: string): {
44 view: FolderView | undefined;
45 isReady: boolean;
46} {
47 const { data: folder, isReady } = useLiveQuery({
48 query: (q) =>
49 isSmartFolderId(folderId)
50 ? undefined
51 : q
52 .from({ folder: foldersCollection })
53 .where(({ folder }) => eq(folder.id, folderId))
54 .findOne(),
55 });
56 if (isSmartFolderId(folderId)) return { view: resolveFolderView(folderId, []), isReady: true };
57 return { view: folder ? resolveFolderView(folderId, [folder]) : undefined, isReady };
59​
60/** A note in a list, with the name of the folder it's in (cross-folder views show it). */
61export type NoteListItem = Note & { folderName: string | undefined };
62​
63/** The date a sort order is about; the list groups notes by it. */
64export const SORT_DATE_FIELD = {
65 dateEdited: "updatedAt",
66 dateCreated: "createdAt",
67 title: null,
68} as const satisfies Record<SortNotesBy, keyof Note | null>;
69​
70/** A folder's notes: pinned first, then in the order picked in Settings. */
71export function noteListQuery(folderId: string, sortNotesBy: SortNotesBy) {
72 return (q: InitialQueryBuilder) =>
73 q
74 .from({ note: notesCollection })
75 .leftJoin({ folder: foldersCollection }, ({ note, folder }) => eq(note.folderId, folder.id))
76 .where(({ note }) => inFolder(note, folderId))
77 .orderBy(({ note }) => note.pinned, "desc")
78 .orderBy(
79 ({ note }) =>
80 sortNotesBy === "title"
81 ? lower(note.title)
82 : sortNotesBy === "dateCreated"
83 ? note.createdAt
84 : note.updatedAt,
85 sortNotesBy === "title" ? "asc" : "desc",
86 )
87 .select(({ note, folder }) => ({ ...note, folderName: folder?.name }));
89​
90export function useNoteList(folderId: string): {
91 notes: NoteListItem[];
92 isReady: boolean;
93 listOptions: NoteListOptions;
94} {
95 const account = useAccount();
96 const sortNotesBy = account?.sortNotesBy ?? "dateEdited";
97​
98 const { data: notes, isReady } = useLiveQuery({
99 query: noteListQuery(folderId, sortNotesBy),
100 });
101 const listOptions = {
102 dateField: SORT_DATE_FIELD[sortNotesBy],
103 groupByDate: account?.groupNotesByDate ?? true,
104 };
105 return { notes, isReady, listOptions };
107​
108/** A note, but only if it's in the folder (or smart folder) that's open. */
109export function useNoteInFolder(
110 folderId: string,
111 noteId: string,
112): { note: Note | undefined; isReady: boolean } {
113 const { data: note, isReady } = useLiveQuery({
114 query: (q) =>
115 q
116 .from({ note: notesCollection })
117 .where(({ note }) => and(eq(note.id, noteId), inFolder(note, folderId)))
118 .findOne(),
119 });
120 return { note, isReady };
122​
123/** Notes per folder (Recently Deleted not included). */
124export function noteCountsQuery(q: InitialQueryBuilder) {
125 return q
126 .from({ note: notesCollection })
127 .where(({ note }) => isNull(note.deletedAt))
128 .groupBy(({ note }) => note.folderId)
129 .select(({ note }) => ({ folderId: note.folderId, count: count(note.id) }));
131​
132/** How many notes a (smart) folder shows: one row, or none when it's empty. */
133export function noteCountQuery(folderId: string) {
134 return (q: InitialQueryBuilder) =>
135 q
136 .from({ note: notesCollection })
137 .where(({ note }) => inFolder(note, folderId))
138 .select(({ note }) => ({ count: count(note.id) }));
140​
141/** How many notes each folder and smart folder shows, keyed by folder id. */
142export function useNoteCounts(): Record<string, number> {
143 const { data: perFolder } = useLiveQuery({ query: noteCountsQuery });
144 const all = useSmartFolderCount("all");
145 const shared = useSmartFolderCount("shared");
146 const recentlyDeleted = useSmartFolderCount("recently-deleted");
147​
148 return {
149 ...Object.fromEntries(perFolder.map((row) => [row.folderId, row.count])),
150 all,
151 shared,
152 "recently-deleted": recentlyDeleted,
153 };
155​
156function useSmartFolderCount(folderId: SmartFolderId): number {
157 const { data } = useLiveQuery({ query: noteCountQuery(folderId) });
158 // An aggregate over no rows has no result row.
159 return data[0]?.count ?? 0;
161​
162/** The signed-in account (there's exactly one). */
163export function useAccount(): Account | undefined {
164 const { data: account } = useLiveQuery({
165 query: (q) => q.from({ account: accountCollection }).findOne(),
166 });
167 return account;
169​
170/* Loading */
171​
172const appCollections = [foldersCollection, notesCollection, accountCollection];
173​
174export type AppDataStatus = "loading" | "ready" | "error";
175​
176function getAppDataStatus(): AppDataStatus {
177 if (appCollections.some((collection) => collection.status === "error")) return "error";
178 return appCollections.every((collection) => collection.isReady()) ? "ready" : "loading";
180​
181function subscribeToAppDataStatus(listener: () => void) {
182 const unsubscribes = appCollections.map((collection) => collection.on("status:change", listener));
183 return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
185​
186/**
187 * Loads every collection and reports when all of them are ready. The Notes
188 * app stays mounted for the whole visit, and so do these subscriptions: the
189 * collections are never garbage-collected, so screens that come and go
190 * always find their data (and your edits) in place.
191 */
192export function useAppData(): { status: AppDataStatus; retry: () => void } {
193 useEffect(() => {
194 const subscriptions = [
195 foldersCollection.subscribeChanges(() => {}),
196 notesCollection.subscribeChanges(() => {}),
197 accountCollection.subscribeChanges(() => {}),
198 ];
199 return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
200 }, []);
201 const status = useSyncExternalStore(
202 subscribeToAppDataStatus,
203 getAppDataStatus,
204 (): AppDataStatus => "loading",
205 );
206 return {
207 status,
208 retry: () => {
209 for (const collection of appCollections) void collection.utils.refetch();
210 },
211 };