Open History to see the last commit
1import { createPacedMutations, debounceStrategy, safeRandomUUID } from "@tanstack/react-db";
2
3import { reportMutation } from "@/lib/app-actions";
4import type { AppAction } from "@/lib/app-actions";
5import { editorSaveDelayMs } from "@/lib/dev-config";
6
7import {
8 accountCollection,
9 foldersCollection,
10 notesCollection,
11 saveNoteUpdates,
12} from "./collections";
13import { pacedPerRecord } from "./paced-per-record";
14import type { Account, Note } from "./schema";
15
16/**
17 * Every change the app makes to its data. Each one is an optimistic write to
18 * a collection: it shows up everywhere immediately, the collection's handler
19 * sends it to the server, and if the server rejects it, it rolls back.
20 *
21 * They return the transaction, so callers can wait for the server with
22 * `await tx.when("settled")` (it throws if the change was rolled back).
23 * Each one changes a single record, so transactions never span records.
24 */
25
26export function createNote(folderId: string) {
27 const now = new Date().toISOString();
28 const note: Note = {
29 // Works on plain-HTTP origins too, where `crypto.randomUUID` is missing.
30 id: safeRandomUUID(),
31 folderId,
32 title: "",
33 body: "",
34 pinned: false,
35 shared: false,
36 createdAt: now,
37 updatedAt: now,
38 deletedAt: null,
39 };
40 const tx = notesCollection.insert(note);
41 reportMutation({ type: "note.created", noteId: note.id, folderId }, tx);
42 return { note, tx };
43}
44
45/** What can change on an existing note. */
46export type NoteChange = Partial<
47 Pick<Note, "title" | "body" | "pinned" | "folderId" | "deletedAt">
48>;
49export type NoteEdit = Pick<NoteChange, "title" | "body">;
50
51/**
52 * Every change to an existing note (typing, pinning, moving, deleting) goes
53 * through one paced mutation per note. Each change shows up at once; they're
54 * sent together, in order, when things go quiet for a moment. With a single
55 * path per note, a newer change can't be hidden behind an older unsaved one.
56 */
57const noteChanges = pacedPerRecord((noteId) =>
58 createPacedMutations<NoteChange, Note>({
59 onMutate: (change) => {
60 notesCollection.update(noteId, (draft) => {
61 Object.assign(draft, change);
62 if (change.title !== undefined || change.body !== undefined) {
63 draft.updatedAt = new Date().toISOString();
64 }
65 });
66 },
67 mutationFn: ({ transaction }) => saveNoteUpdates(transaction),
68 strategy: debounceStrategy({ wait: editorSaveDelayMs }),
69 }),
70);
71
72function changeNote(action: AppAction, noteId: string, change: NoteChange) {
73 const tx = noteChanges.mutate(noteId, change);
74 reportMutation(action, tx);
75 return tx;
76}
77
78/** Typing in the title or body, from any editor (or layout) that shows the note. */
79export function editNote(noteId: string, edit: NoteEdit) {
80 return changeNote({ type: "note.edited", noteId }, noteId, edit);
81}
82
83export function setNotePinned(noteId: string, pinned: boolean) {
84 return changeNote({ type: "note.pinned", noteId, pinned }, noteId, { pinned });
85}
86
87/** Moves a note to another folder (out of Recently Deleted, too). */
88export function moveNote(noteId: string, folderId: string) {
89 return changeNote({ type: "note.moved", noteId, folderId }, noteId, {
90 folderId,
91 deletedAt: null,
92 });
93}
94
95/** Moves a note to Recently Deleted. */
96export function deleteNote(noteId: string) {
97 return changeNote({ type: "note.deleted", noteId, permanently: false }, noteId, {
98 deletedAt: new Date().toISOString(),
99 });
100}
101
102/** Takes a note out of Recently Deleted, back into its folder. */
103export function restoreNote(noteId: string) {
104 return changeNote({ type: "note.restored", noteId }, noteId, { deletedAt: null });
105}
106
107/** Deletes a note for good (from Recently Deleted). */
108export function deleteNotePermanently(noteId: string) {
109 // The note is going away: drop its changes that haven't been sent yet.
110 noteChanges.cancelPending(noteId);
111 const tx = notesCollection.delete(noteId);
112 reportMutation({ type: "note.deleted", noteId, permanently: true }, tx);
113 return tx;
114}
115
116export function renameFolder(folderId: string, name: string) {
117 const tx = foldersCollection.update(folderId, (draft) => {
118 draft.name = name;
119 });
120 reportMutation({ type: "folder.renamed", folderId, name }, tx);
121 return tx;
122}
123
124export type AccountSettings = Pick<
125 Account,
126 "name" | "email" | "defaultFolderId" | "sortNotesBy" | "newNotesStartWith" | "groupNotesByDate"
127>;
128
129export function updateAccount(accountId: string, settings: AccountSettings) {
130 const tx = accountCollection.update(accountId, (draft) => {
131 Object.assign(draft, settings);
132 });
133 reportMutation({ type: "account.updated" }, tx);
134 return tx;
135}