Skip to content

Open source CapCut alternative.

TypeScript
7.5 KB
Raw Blame
"use client";

/**
 * Synced notes, the desktop half. Notes live in the cloud (/api/cut-cloud/notes)
 * and are written from two places — the iOS app and the Notes tab — so every
 * write carries its own `updatedAt` stamp and the server keeps whichever
 * version is newer (last writer wins). Deletes leave tombstones; the list is
 * filtered here so the UI only ever sees live notes.
 *
 * Notes file into folders, the same way the library's do, and folders file
 * into folders. Folder ids are client-generated so the phone can make one
 * offline, and the one PUT creates, renames and moves.
 */

import { noteReadSchema, noteSaveSchema, parseNoteLink, type NoteLocation } from "@/cut/lib/noteReference";
import { creatorNames } from "./defaultNames";
import { settleParents } from "./folderTree";
import { dropPendingNote, flushNote, sendNoteNow, stageNote, withPendingNotes, type NoteWrite } from "./noteOutbox";
import { backendFor } from "./residency";
import { UserError } from "./userError";

export { folderTrail, folderWithin, subtreeOf } from "./folderTree";

export interface CutNote {
  libraryLocation?: NoteLocation | null;
  id: string;
  title: string;
  body: string;
  colorIndex: number;
  folderId: string | null;
  labelIds: string[];
  updatedAt: number;
  deletedAt: number | null;
  createdAt: number;
}

export interface CutNoteFolder {
  id: string;
  name: string;
  /** The folder this one is filed in; null is the top level. */
  parentId: string | null;
  updatedAt: number;
  createdAt: number;
}

/** A label notes carry. Like folders, ids are client-generated and one PUT
 * both creates and renames. */
export interface CutNoteLabel {
  id: string;
  name: string;
  updatedAt: number;
  createdAt: number;
}

export interface NotesData {
  notes: CutNote[];
  folders: CutNoteFolder[];
  labels: CutNoteLabel[];
}

/** The note paper palette, shared with the iOS app (NoteColor). Index into it
 * with `colorIndex`. */
export const NOTE_COLORS = [
  { name: "Butter", background: "#faefb6", accent: "#f2c94c" },
  { name: "Blush", background: "#fbd8d4", accent: "#ef8b80" },
  { name: "Sky", background: "#d5e8fb", accent: "#7fb2ef" },
  { name: "Mint", background: "#d9f3d6", accent: "#82cf7a" },
  { name: "Lilac", background: "#e6dcf7", accent: "#a988e0" },
] as const;

export const noteColor = (index: number) =>
  NOTE_COLORS[((index % NOTE_COLORS.length) + NOTE_COLORS.length) % NOTE_COLORS.length];

const notesFetch = (path: string, init?: RequestInit) =>
  backendFor("cloud").fetch(path, init);

const json = (body: unknown): RequestInit => ({
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body),
});

/** Every live note, newest first, with the folders they file into. Tombstones
 * are the phone's concern; the desktop just drops them. A folder whose parent
 * the listing does not name reads as top level, so nothing on screen hangs
 * off a folder nobody can open. */
export async function fetchNotes(): Promise<NotesData> {
  const res = await notesFetch("/api/cut/notes");
  if (!res.ok) throw new UserError("notes_load_failed", "Could not load notes.");
  const body = (await res.json()) as Partial<NotesData>;
  return {
    notes: withPendingNotes(body.notes ?? []).filter((n) => n.deletedAt === null),
    folders: settleParents(body.folders ?? []),
    labels: body.labels ?? [],
  };
}

export async function readNote(raw: unknown): Promise<CutNote> {
  const input = noteReadSchema.parse(raw);
  const id = input.id ?? (input.link ? parseNoteLink(input.link) : null);
  if (!id) throw new Error("Provide a note id or a Donkey note link.");
  const res = await notesFetch(`/api/cut/notes/${encodeURIComponent(id)}`);
  if (!res.ok) throw new Error(res.status === 404 ? "This note was deleted or is unavailable." : "Could not read the note.");
  return res.json();
}

export async function writeNoteFromTool(raw: unknown): Promise<CutNote> {
  const input = noteSaveSchema.parse(raw);
  const { id, ...changes } = input;
  const prior = id ? await readNote({ id }) : null;
  if (!prior && !input.title?.trim() && !input.body?.trim()) throw new Error("A new note needs a title or body.");
  return saveNote({ id: prior?.id ?? crypto.randomUUID(), title: prior?.title ?? creatorNames().untitled, body: prior?.body ?? "",
    colorIndex: prior?.colorIndex ?? 0, folderId: prior?.folderId ?? null, labelIds: prior?.labelIds ?? [],
    ...(prior ? {} : { libraryLocation: null }), ...changes });
}

/** Write one note: saved in this browser at once, then sent. The answer is
 * the winning version — this write, or a newer one from the phone — or this
 * write itself while it waits to sync. With no account bound there is no
 * outbox, and the write goes straight to the server. */
export async function saveNote(note: NoteWrite): Promise<CutNote> {
  if (!stageNote(note)) {
    return sendNoteNow(note);
  }
  const saved = await flushNote(note.id);
  if (!saved) throw new UserError("note_save_failed", "Could not save the note.");
  return saved;
}

export async function deleteNote(id: string): Promise<void> {
  dropPendingNote(id);
  const res = await notesFetch(`/api/cut/notes/${encodeURIComponent(id)}`, {
    method: "DELETE",
  });
  if (!res.ok) throw new UserError("note_delete_failed", "Could not delete the note.");
}

/** Create, rename or move a folder under `id`. A create mints the id here so
 * the new folder is on screen before the write returns. The server answers
 * with the folder as stored: a parent it could not honor reads back as the
 * top level. */
export async function saveNoteFolder(
  id: string,
  folder: { name: string; parentId: string | null },
): Promise<CutNoteFolder> {
  const res = await notesFetch(
    `/api/cut/notes/folders/${encodeURIComponent(id)}`,
    json(folder),
  );
  if (!res.ok) throw new UserError("note_folder_save_failed", "Could not save the folder.");
  return (await res.json()) as CutNoteFolder;
}

/** Delete the notes filed in Library folders on a shelf that keeps no notes
 * of its own — what deleting those folders takes. */
export async function deleteLibraryFolderNotes(residency: "browser" | "local", folderIds: string[]): Promise<void> {
  const res = await notesFetch("/api/cut/notes/library-folders/delete", {
    ...json({ residency, folderIds }),
    method: "POST",
  });
  if (!res.ok) throw new UserError("note_folder_notes_delete_failed", "Could not delete the folder’s notes.");
}

/** Delete a folder and everything under it: its folders and their notes. */
export async function deleteNoteFolder(id: string): Promise<void> {
  const res = await notesFetch(`/api/cut/notes/folders/${encodeURIComponent(id)}`, {
    method: "DELETE",
  });
  if (!res.ok) throw new UserError("note_folder_delete_failed", "Could not delete the folder.");
}

/** Create or rename a label under `id`. A create mints the id here so the
 * new label is on the note before the write returns. */
export async function saveNoteLabel(id: string, name: string): Promise<CutNoteLabel> {
  const res = await notesFetch(
    `/api/cut/notes/labels/${encodeURIComponent(id)}`,
    json({ name }),
  );
  if (!res.ok) throw new UserError("label_save_failed", "Could not save the label.");
  return (await res.json()) as CutNoteLabel;
}

/** Delete a label. Every note carrying it lets it go. */
export async function deleteNoteLabel(id: string): Promise<void> {
  const res = await notesFetch(`/api/cut/notes/labels/${encodeURIComponent(id)}`, {
    method: "DELETE",
  });
  if (!res.ok) throw new UserError("label_delete_failed", "Could not delete the label.");
}