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

mutations.ts

139 lines4.6 KB

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 };
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// #region note-changes
52/**
53 * Every change to an existing note (typing, pinning, moving, deleting) goes
54 * through one paced mutation per note. Each change shows up at once; they're
55 * sent together, in order, when things go quiet for a moment. With a single
56 * path per note, a newer change can't be hidden behind an older unsaved one.
57 */
58const noteChanges = pacedPerRecord((noteId) =>
59 createPacedMutations<NoteChange, Note>({
60 onMutate: (change) => {
61 notesCollection.update(noteId, (draft) => {
62 Object.assign(draft, change);
63 if (change.title !== undefined || change.body !== undefined) {
64 draft.updatedAt = new Date().toISOString();
65 }
66 });
67 },
68 mutationFn: ({ transaction }) => saveNoteUpdates(transaction),
69 strategy: debounceStrategy({ wait: editorSaveDelayMs }),
70 }),
71);
72​
73function changeNote(action: AppAction, noteId: string, change: NoteChange) {
74 const tx = noteChanges.mutate(noteId, change);
75 reportMutation(action, tx);
76 return tx;
78​
79/** Typing in the title or body, from any editor (or layout) that shows the note. */
80export function editNote(noteId: string, edit: NoteEdit) {
81 return changeNote({ type: "note.edited", noteId }, noteId, edit);
83// #endregion note-changes
84​
85export function setNotePinned(noteId: string, pinned: boolean) {
86 return changeNote({ type: "note.pinned", noteId, pinned }, noteId, { pinned });
88​
89/** Moves a note to another folder (out of Recently Deleted, too). */
90export function moveNote(noteId: string, folderId: string) {
91 return changeNote({ type: "note.moved", noteId, folderId }, noteId, {
92 folderId,
93 deletedAt: null,
94 });
96​
97/** Moves a note to Recently Deleted. */
98export function deleteNote(noteId: string) {
99 return changeNote({ type: "note.deleted", noteId, permanently: false }, noteId, {
100 deletedAt: new Date().toISOString(),
101 });
103​
104/** Takes a note out of Recently Deleted, back into its folder. */
105export function restoreNote(noteId: string) {
106 return changeNote({ type: "note.restored", noteId }, noteId, { deletedAt: null });
108​
109/** Deletes a note for good (from Recently Deleted). */
110export function deleteNotePermanently(noteId: string) {
111 // The note is going away: drop its changes that haven't been sent yet.
112 noteChanges.cancelPending(noteId);
113 const tx = notesCollection.delete(noteId);
114 reportMutation({ type: "note.deleted", noteId, permanently: true }, tx);
115 return tx;
117​
118// #region rename-folder
119export function renameFolder(folderId: string, name: string) {
120 const tx = foldersCollection.update(folderId, (draft) => {
121 draft.name = name;
122 });
123 reportMutation({ type: "folder.renamed", folderId, name }, tx);
124 return tx;
126// #endregion rename-folder
127​
128export type AccountSettings = Pick<
129 Account,
130 "name" | "email" | "defaultFolderId" | "sortNotesBy" | "newNotesStartWith" | "groupNotesByDate"
131>;
132​
133export function updateAccount(accountId: string, settings: AccountSettings) {
134 const tx = accountCollection.update(accountId, (draft) => {
135 Object.assign(draft, settings);
136 });
137 reportMutation({ type: "account.updated" }, tx);
138 return tx;