Open History to see the last commit
1import { createLiveQueryCollection, createTransaction } from "@tanstack/react-db";
2import type { Context, InitialQueryBuilder, QueryBuilder } from "@tanstack/react-db";
3import { beforeAll, describe, expect, it } from "vite-plus/test";
4
5import { setNetworkConfig } from "@/api/network-config";
6
7import { accountCollection, foldersCollection, notesCollection } from "./collections";
8import { moveNote, renameFolder, setNotePinned } from "./mutations";
9import {
10 editsPerDayQuery,
11 folderStatsQuery,
12 noteCountQuery,
13 noteCountsQuery,
14 noteListQuery,
15} from "./queries";
16
17beforeAll(async () => {
18 setNetworkConfig({ latencyMs: 0 });
19 await Promise.all([
20 foldersCollection.preload(),
21 notesCollection.preload(),
22 accountCollection.preload(),
23 ]);
24});
25
26async function liveQuery<TContext extends Context>(
27 query: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
28) {
29 const collection = createLiveQueryCollection(query);
30 await collection.preload();
31 return collection;
32}
33
34describe("note list", () => {
35 it("shows a folder's notes, pinned first, then newest edit first", async () => {
36 const list = await liveQuery(noteListQuery("work", "dateEdited"));
37 const notes = list.toArray;
38 expect(notes.length).toBeGreaterThan(1);
39 expect(notes.every((note) => note.folderId === "work")).toBe(true);
40 const firstUnpinned = notes.findIndex((note) => !note.pinned);
41 expect(notes.slice(firstUnpinned).some((note) => note.pinned)).toBe(false);
42 const dates = notes.slice(firstUnpinned).map((note) => note.updatedAt);
43 expect(dates).toEqual([...dates].sort().reverse());
44 });
45
46 it("sorts by title, ignoring case", async () => {
47 const list = await liveQuery(noteListQuery("all", "title"));
48 const titles = list.toArray.filter((note) => !note.pinned).map((note) => note.title);
49 expect(titles).toEqual(
50 [...titles].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())),
51 );
52 });
53
54 it("joins each note with its folder's name", async () => {
55 const list = await liveQuery(noteListQuery("all", "dateEdited"));
56 const folderNames = new Map(
57 foldersCollection.toArray.map((folder) => [folder.id, folder.name]),
58 );
59 for (const note of list.toArray) expect(note.folderName).toBe(folderNames.get(note.folderId));
60 });
61
62 it("smart folders are filters: Shared, and Recently Deleted", async () => {
63 const shared = await liveQuery(noteListQuery("shared", "dateEdited"));
64 expect(shared.toArray.length).toBeGreaterThan(0);
65 expect(shared.toArray.every((note) => note.shared && note.deletedAt === null)).toBe(true);
66
67 const deleted = await liveQuery(noteListQuery("recently-deleted", "dateEdited"));
68 expect(deleted.toArray.length).toBeGreaterThan(0);
69 expect(deleted.toArray.every((note) => note.deletedAt !== null)).toBe(true);
70 });
71});
72
73describe("counts", () => {
74 it("count notes per folder and per smart folder", async () => {
75 const perFolder = await liveQuery(noteCountsQuery);
76 const all = await liveQuery(noteCountQuery("all"));
77 const total = perFolder.toArray.reduce((sum, row) => sum + row.count, 0);
78 expect(all.toArray[0]!.count).toBe(total);
79 const active = notesCollection.toArray.filter((note) => note.deletedAt === null);
80 expect(total).toBe(active.length);
81 });
82
83 it("an empty folder has no count row", async () => {
84 const empty = await liveQuery(noteCountQuery("no-such-folder"));
85 expect(empty.toArray).toEqual([]);
86 });
87});
88
89describe("optimistic changes", () => {
90 it("move a note between folders everywhere at once, then stick", async () => {
91 const counts = await liveQuery(noteCountsQuery);
92 const travel = await liveQuery(noteListQuery("travel", "dateEdited"));
93 const countOf = (folderId: string) =>
94 counts.toArray.find((row) => row.folderId === folderId)?.count ?? 0;
95 const workBefore = countOf("work");
96 const travelBefore = countOf("travel");
97
98 const tx = moveNote("note-01", "travel");
99 // Synchronously, before the server has answered:
100 expect(countOf("work")).toBe(workBefore - 1);
101 expect(countOf("travel")).toBe(travelBefore + 1);
102 expect(travel.toArray.map((note) => note.id)).toContain("note-01");
103
104 await tx.when("settled");
105 expect(notesCollection.get("note-01")?.folderId).toBe("travel");
106 expect(countOf("travel")).toBe(travelBefore + 1);
107 });
108
109 it("pin a note to the top of its list", async () => {
110 const list = await liveQuery(noteListQuery("personal", "dateEdited"));
111 const last = list.toArray.at(-1)!.id;
112 const tx = setNotePinned(last, true);
113 expect(list.toArray[0]!.id).toBe(last);
114 await tx.when("settled");
115 expect(list.toArray[0]!.id).toBe(last);
116 });
117
118 it("roll back a rename the server rejects", async () => {
119 const tx = renameFolder("recipes", "Personal");
120 expect(foldersCollection.get("recipes")?.name).toBe("Personal");
121 await expect(tx.when("settled")).rejects.toMatchObject({ status: 409 });
122 expect(foldersCollection.get("recipes")?.name).toBe("Recipes");
123 expect(tx.state).toBe("failed");
124 });
125});
126
127describe("analytics", () => {
128 it("adds up notes and words per folder", async () => {
129 const perFolder = await liveQuery(folderStatsQuery);
130 const active = notesCollection.toArray.filter((note) => note.deletedAt === null);
131 expect(perFolder.toArray.reduce((sum, row) => sum + row.notes, 0)).toBe(active.length);
132
133 // Notes with known word counts, in a folder of their own. Optimistic
134 // only: the transaction is never committed, so nothing is sent.
135 const now = new Date().toISOString();
136 const note = (id: string, title: string, body: string, deletedAt: string | null = null) => ({
137 id,
138 folderId: "word-count-test",
139 title,
140 body,
141 pinned: false,
142 shared: false,
143 createdAt: now,
144 updatedAt: now,
145 deletedAt,
146 });
147 const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} });
148 tx.mutate(() =>
149 notesCollection.insert([
150 // 2 (title) + Buy, milk, Call, Sam, Plans, Bread = 8
151 note("wc-1", "Weekend shopping", "[ ] Buy milk\n[x] Call Sam\n# Plans\n- Bread"),
152 // 0
153 note("wc-2", "", ""),
154 // Deleted: not counted at all
155 note("wc-3", "Old", "gone for good", now),
156 ]),
157 );
158 expect(perFolder.toArray.find((row) => row.folderId === "word-count-test")).toMatchObject({
159 folderId: "word-count-test",
160 notes: 2,
161 words: 8,
162 });
163 tx.rollback();
164 });
165
166 it("counts notes by the day they were last edited, newest first", async () => {
167 const perDay = await liveQuery(editsPerDayQuery);
168 const days = perDay.toArray.map((row) => row.day);
169 expect(days).toEqual([...days].sort().reverse());
170 const active = notesCollection.toArray.filter((note) => note.deletedAt === null);
171 expect(perDay.toArray.reduce((sum, row) => sum + row.notes, 0)).toBe(active.length);
172 });
173
174 it("updates the word count as a note changes", async () => {
175 const perFolder = await liveQuery(folderStatsQuery);
176 const note = notesCollection.toArray.find(
177 (note) => note.folderId === "recipes" && note.deletedAt === null,
178 )!;
179 const before = perFolder.toArray.find((row) => row.folderId === "recipes")!.words!;
180 // A transaction that's never committed: optimistic only, nothing is sent.
181 const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} });
182 tx.mutate(() =>
183 notesCollection.update(note.id, (draft) => {
184 draft.body = `${draft.body} three more words`;
185 }),
186 );
187 expect(perFolder.toArray.find((row) => row.folderId === "recipes")!.words).toBe(before + 3);
188 tx.rollback();
189 });
190});