Open History to see the last commit
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 }
44}
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;
53}
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 };
71}
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 }));
102}
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 };
121}
122
123/** A note, but only if it's in the folder (or smart folder) that's open. */
124export function useNoteInFolder(
125 folderId: string,
126 noteId: string,
127): { note: Note | undefined; isReady: boolean } {
128 const { data: note, isReady } = useLiveQuery({
129 query: (q) =>
130 q
131 .from({ note: notesCollection })
132 .where(({ note }) => and(eq(note.id, noteId), inFolder(note, folderId)))
133 .findOne(),
134 });
135 return { note, isReady };
136}
137
138// #region note-counts-query
139/** Notes per folder (Recently Deleted not included). */
140export function noteCountsQuery(q: InitialQueryBuilder) {
141 return q
142 .from({ note: notesCollection })
143 .where(({ note }) => isNull(note.deletedAt))
144 .groupBy(({ note }) => note.folderId)
145 .select(({ note }) => ({ folderId: note.folderId, count: count(note.id) }));
146}
147// #endregion note-counts-query
148
149/** How many notes a (smart) folder shows: one row, or none when it's empty. */
150export function noteCountQuery(folderId: string) {
151 return (q: InitialQueryBuilder) =>
152 q
153 .from({ note: notesCollection })
154 .where(({ note }) => inFolder(note, folderId))
155 .select(({ note }) => ({ count: count(note.id) }));
156}
157
158/** How many notes each folder and smart folder shows, keyed by folder id. */
159export function useNoteCounts(): Record<string, number> {
160 const { data: perFolder } = useLiveQuery({ query: noteCountsQuery });
161 const all = useSmartFolderCount("all");
162 const shared = useSmartFolderCount("shared");
163 const recentlyDeleted = useSmartFolderCount("recently-deleted");
164
165 return {
166 ...Object.fromEntries(perFolder.map((row) => [row.folderId, row.count])),
167 all,
168 shared,
169 "recently-deleted": recentlyDeleted,
170 };
171}
172
173function useSmartFolderCount(folderId: SmartFolderId): number {
174 const { data } = useLiveQuery({ query: noteCountQuery(folderId) });
175 // An aggregate over no rows has no result row.
176 return data[0]?.count ?? 0;
177}
178
179/** The signed-in account (there's exactly one). */
180export function useAccount(): Account | undefined {
181 const { data: account } = useLiveQuery({
182 query: (q) => q.from({ account: accountCollection }).findOne(),
183 });
184 return account;
185}
186
187/* Analytics */
188
189/** The local calendar day of a timestamp, as `YYYY-MM-DD`. */
190export function localDay(timestamp: string): string {
191 const date = new Date(timestamp);
192 const month = String(date.getMonth() + 1).padStart(2, "0");
193 const day = String(date.getDate()).padStart(2, "0");
194 return `${date.getFullYear()}-${month}-${day}`;
195}
196
197// #region note-stats-collection
198/**
199 * One row per note with the numbers the analytics page adds up. The query
200 * builder has no "count words" function, so `fn.select` runs plain
201 * JavaScript, once per note and again only when that note changes. A live
202 * query is a collection too, so the queries below group this one.
203 */
204export const noteStatsCollection = createLiveQueryCollection((q) =>
205 q
206 .from({ note: notesCollection })
207 .where(({ note }) => isNull(note.deletedAt))
208 .fn.select(({ note }) => ({
209 id: note.id,
210 folderId: note.folderId,
211 words: countWords(note),
212 lastEditedOn: localDay(note.updatedAt),
213 })),
214);
215// #endregion note-stats-collection
216
217// #region folder-stats-query
218/** Notes and words per folder (Recently Deleted not included). */
219export function folderStatsQuery(q: InitialQueryBuilder) {
220 return q
221 .from({ stats: noteStatsCollection })
222 .groupBy(({ stats }) => stats.folderId)
223 .select(({ stats }) => ({
224 folderId: stats.folderId,
225 notes: count(stats.id),
226 words: sum(stats.words),
227 }));
228}
229// #endregion folder-stats-query
230
231/** How many notes were last edited on each day, newest day first. */
232export function editsPerDayQuery(q: InitialQueryBuilder) {
233 return q
234 .from({ stats: noteStatsCollection })
235 .groupBy(({ stats }) => stats.lastEditedOn)
236 .select(({ stats }) => ({ day: stats.lastEditedOn, notes: count(stats.id) }))
237 .orderBy(({ $selected }) => $selected.day, "desc");
238}
239
240export function useFolderStats() {
241 return useLiveQuery({ query: folderStatsQuery }).data;
242}
243
244export function useEditsPerDay() {
245 return useLiveQuery({ query: editsPerDayQuery }).data;
246}
247
248/* Loading */
249
250const appCollections = [foldersCollection, notesCollection, accountCollection];
251
252export type AppDataStatus = "loading" | "ready" | "error";
253
254function getAppDataStatus(): AppDataStatus {
255 if (appCollections.some((collection) => collection.status === "error")) return "error";
256 return appCollections.every((collection) => collection.isReady()) ? "ready" : "loading";
257}
258
259function subscribeToAppDataStatus(listener: () => void) {
260 const unsubscribes = appCollections.map((collection) => collection.on("status:change", listener));
261 return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
262}
263
264/**
265 * Loads every collection and reports when all of them are ready. The Notes
266 * app stays mounted for the whole visit, and so do these subscriptions: the
267 * collections are never garbage-collected, so screens that come and go
268 * always find their data (and your edits) in place.
269 */
270export function useAppData(): { status: AppDataStatus; retry: () => void } {
271 useEffect(() => {
272 const subscriptions = [
273 foldersCollection.subscribeChanges(() => {}),
274 notesCollection.subscribeChanges(() => {}),
275 accountCollection.subscribeChanges(() => {}),
276 ];
277 return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
278 }, []);
279 const status = useSyncExternalStore(
280 subscribeToAppDataStatus,
281 getAppDataStatus,
282 (): AppDataStatus => "loading",
283 );
284 return {
285 status,
286 retry: () => {
287 for (const collection of appCollections) void collection.utils.refetch();
288 },
289 };
290}