Open source CapCut alternative.
TypeScript
feat(site): rich text notes that save as they are typed
David Le9b952f002a8f
diff --git a/site/src/cut/components/NoteBodyEditor.tsx b/site/src/cut/components/NoteBodyEditor.tsxnew file mode 100644index 00000000..14ba692b--- /dev/null+++ b/site/src/cut/components/NoteBodyEditor.tsx@@ -0,0 +1,221 @@+"use client";++import { useEffect, useRef, useState, type ReactNode } from "react";+import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react";+import { BubbleMenu } from "@tiptap/react/menus";+import StarterKit from "@tiptap/starter-kit";+import { TaskItem, TaskList } from "@tiptap/extension-list";+import { Placeholder } from "@tiptap/extensions";+import { Bold, Check, ChevronDown, Italic, Strikethrough, Underline } from "lucide-react";+import { NOTE_TEXT_COLORS, parseNoteBody, serializeNoteBody, type NoteTextColor } from "@/cut/lib/noteMarkdown";+import { blocksOf, docOf, TextColor } from "@/cut/lib/noteDoc";+import { cn } from "@/lib/utils";++/** What a selection can turn its lines into, the way the toolbar names it. */+const TURN_INTO: { id: string; label: string; active: (e: Editor) => boolean; run: (e: Editor) => void }[] = [+ { id: "text", label: "Text", active: (e) => e.isActive("paragraph") && !e.isActive("bulletList") && !e.isActive("orderedList") && !e.isActive("taskList") && !e.isActive("blockquote"), run: (e) => toText(e).setParagraph().run() },+ ...([1, 2, 3] as const).map((level) => ({+ id: `h${level}`,+ label: `Heading ${level}`,+ active: (e: Editor) => e.isActive("heading", { level }),+ run: (e: Editor) => toText(e).setHeading({ level }).run(),+ })),+ { id: "bullet", label: "Bulleted list", active: (e) => e.isActive("bulletList"), run: (e) => toText(e).toggleBulletList().run() },+ { id: "number", label: "Numbered list", active: (e) => e.isActive("orderedList"), run: (e) => toText(e).toggleOrderedList().run() },+ { id: "todo", label: "To-do list", active: (e) => e.isActive("taskList"), run: (e) => toText(e).toggleTaskList().run() },+ { id: "quote", label: "Quote", active: (e) => e.isActive("blockquote"), run: (e) => toText(e).setParagraph().toggleBlockquote().run() },+];+/** Lift the selected lines out of any list or quote first, so every turn+ * starts from plain lines. */+function toText(e: Editor) {+ let chain = e.chain().focus();+ if (e.isActive("bulletList")) chain = chain.toggleBulletList();+ else if (e.isActive("orderedList")) chain = chain.toggleOrderedList();+ else if (e.isActive("taskList")) chain = chain.toggleTaskList();+ if (e.isActive("blockquote")) chain = chain.lift("blockquote");+ return chain;+}++/** The note's body: rich text on the paper, written out as the note's+ * Markdown on every change. Selecting words brings up the toolbar — turn the+ * lines into a heading or a list, bold, italic, underline, strikethrough and+ * color — and the Markdown shortcuts work as they are typed. */+export default function NoteBodyEditor({+ body,+ ink,+ onChange,+ onEditor,+}: {+ /** The body the editor opens on. Later changes to it are ignored: the+ * editor is the source of the body while it is open. */+ body: string;+ ink: string;+ onChange: (body: string) => void;+ onEditor?: (editor: Editor | null) => void;+}) {+ const [initial] = useState(() => docOf(parseNoteBody(body)));+ // The handlers as of the last render; the editor holds the ones it was+ // made with.+ const handlers = useRef({ onChange, onEditor });+ useEffect(() => {+ handlers.current = { onChange, onEditor };+ });+ const editor = useEditor({+ immediatelyRender: false,+ extensions: [+ StarterKit.configure({+ code: false,+ codeBlock: false,+ horizontalRule: false,+ link: false,+ hardBreak: false,+ trailingNode: false,+ heading: { levels: [1, 2, 3] },+ }),+ TaskList,+ TaskItem.configure({ nested: true }),+ TextColor,+ Placeholder.configure({ placeholder: "Write your note…" }),+ ],+ content: initial,+ editorProps: { attributes: { class: "outline-none min-h-[50vh]" } },+ onCreate: ({ editor }) => handlers.current.onEditor?.(editor),+ onDestroy: () => handlers.current.onEditor?.(null),+ onUpdate: ({ editor }) => handlers.current.onChange(serializeNoteBody(blocksOf(editor.getJSON()))),+ });++ return (+ <div+ className={cn(+ "text-lg leading-8",+ "[&_h1]:mt-4 [&_h1]:text-3xl [&_h1]:leading-tight [&_h1]:font-semibold",+ "[&_h2]:mt-3 [&_h2]:text-2xl [&_h2]:leading-tight [&_h2]:font-semibold",+ "[&_h3]:mt-2 [&_h3]:text-xl [&_h3]:font-semibold",+ "[&_ul]:list-disc [&_ul]:pl-6 [&_ol]:list-decimal [&_ol]:pl-6 [&_ul_ul]:list-[circle] [&_ul_ul_ul]:list-[square]",+ "[&_ul[data-type=taskList]]:list-none [&_ul[data-type=taskList]]:pl-0.5",+ "[&_li[data-checked]]:flex [&_li[data-checked]]:gap-2.5 [&_li[data-checked]>label]:mt-0.5 [&_li[data-checked]>div]:flex-1",+ "[&_li[data-checked=true]>div]:line-through [&_li[data-checked=true]>div]:opacity-50",+ "[&_input[type=checkbox]]:size-4 [&_input[type=checkbox]]:cursor-pointer [&_input[type=checkbox]]:accent-current",+ "[&_blockquote]:border-l-[3px] [&_blockquote]:border-current [&_blockquote]:pl-4",+ "[&_.is-editor-empty:first-child]:before:pointer-events-none [&_.is-editor-empty:first-child]:before:float-left [&_.is-editor-empty:first-child]:before:h-0 [&_.is-editor-empty:first-child]:before:opacity-40 [&_.is-editor-empty:first-child]:before:content-[attr(data-placeholder)]",+ )}+ style={{ color: ink }}+ >+ {editor && <Toolbar editor={editor} />}+ <EditorContent editor={editor} />+ </div>+ );+}++/** The selection's toolbar. Every press keeps the editor's focus, so the+ * selection it acts on stays put. */+function Toolbar({ editor }: { editor: Editor }) {+ const [panel, setPanel] = useState<"turn" | "color" | null>(null);+ const state = useEditorState({+ editor,+ selector: ({ editor: e }) => ({+ turn: TURN_INTO.find((t) => t.active(e))?.label ?? "Text",+ bold: e.isActive("bold"),+ italic: e.isActive("italic"),+ underline: e.isActive("underline"),+ strike: e.isActive("strike"),+ color: (e.getAttributes("textColor").color as NoteTextColor | undefined) ?? null,+ }),+ });+ const keep = (e: React.MouseEvent) => e.preventDefault();+ const color = NOTE_TEXT_COLORS.find((c) => c.id === state.color);++ return (+ <BubbleMenu+ editor={editor}+ options={{ placement: "top-start", offset: 8, onHide: () => setPanel(null) }}+ className="z-[60] flex items-center gap-0.5 rounded-lg border border-black/10 bg-white p-1 text-sm text-neutral-800 shadow-lg"+ onMouseDown={keep}+ >+ <Menu+ open={panel === "turn"}+ onToggle={() => setPanel(panel === "turn" ? null : "turn")}+ trigger={<>{state.turn}<ChevronDown className="size-3.5 opacity-50" /></>}+ >+ {TURN_INTO.map((t) => (+ <MenuItem key={t.id} checked={t.label === state.turn} onPick={() => { t.run(editor); setPanel(null); }}>+ {t.label}+ </MenuItem>+ ))}+ </Menu>+ <Divider />+ <Toggle label="Bold" on={state.bold} onPress={() => editor.chain().focus().toggleBold().run()}><Bold className="size-4" /></Toggle>+ <Toggle label="Italic" on={state.italic} onPress={() => editor.chain().focus().toggleItalic().run()}><Italic className="size-4" /></Toggle>+ <Toggle label="Underline" on={state.underline} onPress={() => editor.chain().focus().toggleUnderline().run()}><Underline className="size-4" /></Toggle>+ <Toggle label="Strikethrough" on={state.strike} onPress={() => editor.chain().focus().toggleStrike().run()}><Strikethrough className="size-4" /></Toggle>+ <Divider />+ <Menu+ open={panel === "color"}+ onToggle={() => setPanel(panel === "color" ? null : "color")}+ label="Text color"+ trigger={<><span className="font-semibold" style={{ color: color?.paper }}>A</span><ChevronDown className="size-3.5 opacity-50" /></>}+ >+ <MenuItem checked={!color} onPick={() => { editor.chain().focus().unsetMark("textColor").run(); setPanel(null); }}>+ <span className="w-4 text-center font-semibold">A</span> Default+ </MenuItem>+ {NOTE_TEXT_COLORS.map((c) => (+ <MenuItem key={c.id} checked={c.id === state.color} onPick={() => { editor.chain().focus().setMark("textColor", { color: c.id }).run(); setPanel(null); }}>+ <span className="w-4 text-center font-semibold" style={{ color: c.paper }}>A</span> {c.name}+ </MenuItem>+ ))}+ </Menu>+ </BubbleMenu>+ );+}++const Divider = () => <div className="mx-0.5 h-5 w-px bg-black/10" />;++function Toggle({ label, on, onPress, children }: { label: string; on: boolean; onPress: () => void; children: ReactNode }) {+ return (+ <button+ type="button"+ aria-label={label}+ aria-pressed={on}+ className={cn("grid size-7 cursor-pointer place-items-center rounded-md hover:bg-black/5", on && "bg-black/10 hover:bg-black/10")}+ onClick={onPress}+ >+ {children}+ </button>+ );+}++function Menu({ open, onToggle, label, trigger, children }: { open: boolean; onToggle: () => void; label?: string; trigger: ReactNode; children: ReactNode }) {+ return (+ <div className="relative">+ <button+ type="button"+ aria-label={label}+ aria-expanded={open}+ className={cn("flex h-7 cursor-pointer items-center gap-1 rounded-md px-2 hover:bg-black/5", open && "bg-black/5")}+ onClick={onToggle}+ >+ {trigger}+ </button>+ {open && (+ <div role="menu" className="absolute top-full left-0 mt-1.5 w-44 rounded-lg border border-black/10 bg-white p-1 shadow-lg">+ {children}+ </div>+ )}+ </div>+ );+}++function MenuItem({ checked, onPick, children }: { checked: boolean; onPick: () => void; children: ReactNode }) {+ return (+ <button+ type="button"+ role="menuitemradio"+ aria-checked={checked}+ className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-black/5"+ onClick={onPick}+ >+ <span className="flex min-w-0 flex-1 items-center gap-2">{children}</span>+ {checked && <Check className="size-4 shrink-0 opacity-70" />}+ </button>+ );+}diff --git a/site/src/cut/components/NoteBodyPreview.tsx b/site/src/cut/components/NoteBodyPreview.tsxnew file mode 100644index 00000000..5f977ff9--- /dev/null+++ b/site/src/cut/components/NoteBodyPreview.tsx@@ -0,0 +1,58 @@+import { Fragment } from "react";+import { NOTE_TEXT_COLORS, parseNoteBody, type NoteBlock, type NoteRun } from "@/cut/lib/noteMarkdown";+import { cn } from "@/lib/utils";++/** The opening lines of a note body as they read on the paper: headings,+ * list markers and styled words, for a note's card. Long lines wrap, and the+ * card shows `lines` lines of it. */+export function NoteBodyPreview({ body, lines, className }: { body: string; lines: number; className?: string }) {+ const blocks = parseNoteBody(body).slice(0, lines);+ // Numbered lines count within their run, the way the editor numbers them.+ const numbers: number[] = [];+ return (+ <div className={cn("overflow-hidden break-words", className)} style={{ maxHeight: `${lines}lh` }}>+ {blocks.map((b, i) => {+ if (b.kind === "number") numbers[b.indent] = (numbers[b.indent] ?? 0) + 1;+ numbers.length = b.kind === "number" ? b.indent + 1 : b.kind === "bullet" || b.kind === "todo" ? b.indent : 0;+ const marker =+ b.kind === "bullet" ? "•" : b.kind === "number" ? `${numbers[b.indent]}.` : b.kind === "todo" ? (b.checked ? "☑" : "☐") : null;+ return (+ <div+ key={i}+ className={cn(+ "min-h-[1lh]",+ b.kind === "heading" && "font-semibold",+ b.kind === "quote" && "border-l-2 border-current pl-1.5",+ b.kind === "todo" && b.checked && "line-through opacity-60",+ )}+ style={{ paddingLeft: b.indent ? `${b.indent * 0.75}rem` : undefined }}+ >+ {marker && <span className="mr-1">{marker}</span>}+ <Runs block={b} />+ </div>+ );+ })}+ </div>+ );+}++function Runs({ block }: { block: NoteBlock }) {+ return block.runs.map((r: NoteRun, i) => {+ const color = r.marks.color ? NOTE_TEXT_COLORS.find((c) => c.id === r.marks.color)?.paper : undefined;+ const styled = r.marks.bold || r.marks.italic || r.marks.underline || r.marks.strike || color;+ if (!styled) return <Fragment key={i}>{r.text}</Fragment>;+ return (+ <span+ key={i}+ className={cn(+ r.marks.bold && "font-semibold",+ r.marks.italic && "italic",+ r.marks.underline && r.marks.strike ? "[text-decoration-line:underline_line-through]" : r.marks.underline ? "underline" : r.marks.strike && "line-through",+ )}+ style={color ? { color } : undefined}+ >+ {r.text}+ </span>+ );+ });+}diff --git a/site/src/cut/components/NoteComposer.tsx b/site/src/cut/components/NoteComposer.tsxindex a500ee74..611ce086 100644--- a/site/src/cut/components/NoteComposer.tsx+++ b/site/src/cut/components/NoteComposer.tsx@@ -4,6 +4,8 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react";import type React from "react";import type { NoteLocation } from "@/cut/lib/noteReference";import { createPortal } from "react-dom";+import dynamic from "next/dynamic";+import type { Editor } from "@tiptap/react";import { ArrowLeft, Check, ChevronDown, Pencil, Plus, Tag, Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";import {@@ -20,6 +22,10 @@ import { cn } from "@/lib/utils";// The note paper's ink, matching the iOS app.const NOTE_INK = "#201a0d";+// The rich text editor loads with the first note opened, off the list's own+// bundle.+const NoteBodyEditor = dynamic(() => import("./NoteBodyEditor"), { ssr: false });+export interface NoteDraft {libraryLocation?: NoteLocation | null;id: string;@@ -28,9 +34,8 @@ export interface NoteDraft {colorIndex: number;folderId: string | null;labelIds: string[];- isNew: boolean;- /** What the note held when it opened. A draft that still matches closes- * without a write, so opening a note to read it leaves the list alone. */+ /** What the server last took from this draft. A draft that still matches+ * writes nothing, so opening a note to read it leaves the list alone. */saved: { title: string; body: string; colorIndex: number; labelIds: string[] };}@@ -44,10 +49,30 @@ const labelKey = (ids: string[]) => [...new Set(ids)].sort().join("\n");/** True when the draft holds something the stored note does not. */export const noteChanged = (d: NoteDraft) =>d.title.trim() !== d.saved.title ||- d.body.trim() !== d.saved.body ||+ d.body.trimEnd() !== d.saved.body ||d.colorIndex !== d.saved.colorIndex ||labelKey(d.labelIds) !== labelKey(d.saved.labelIds);+const stop = (e: React.SyntheticEvent) => e.stopPropagation();+// A file let go over the paper lands nowhere; left to the browser, it would+// open the file in place of the app.+const stopFile = (e: React.DragEvent) => {+ e.stopPropagation();+ if (Array.from(e.dataTransfer.types).includes("Files")) e.preventDefault();+};+/** The events the page behind the sheet listens for. */+const KEEP_EVENTS = {+ onContextMenu: stop,+ onPointerDown: stop,+ onMouseDown: stop,+ onClick: stop,+ onKeyDown: stop,+ onDragEnter: stop,+ onDragOver: stopFile,+ onDragLeave: stop,+ onDrop: stopFile,+};+/** The box that scrolls around `node`: the app shell gives each page a main* column with its own scrollbar, and the document itself scrolls only where* nothing else claims it. */@@ -82,8 +107,9 @@ function useAutoGrow(value: string) {/** The note itself, over the whole window: a sheet of paper with a title, a* body that runs as long as it needs to, and the paper's color on a menu. It* covers the app — sidebar and all — so writing a note is the only thing on- * screen, and the page behind it holds still while it is open. Closing it —- * the back arrow, Done, or Escape — hands the draft back to be saved. */+ * screen, and the page behind it holds still while it is open. Every edit+ * saves on its own; closing it — the back arrow or Escape — saves it once+ * more. */export function NoteComposer({draft,back,@@ -116,7 +142,12 @@ export function NoteComposer({}) {const paper = noteColor(draft.colorIndex);const titleRef = useAutoGrow(draft.title);- const bodyRef = useAutoGrow(draft.body);+ const body = useRef<Editor | null>(null);+ // The draft as of the last render, for the editor's change handler.+ const draftRef = useRef(draft);+ useEffect(() => {+ draftRef.current = draft;+ });// While the label picker is up, Escape is its to close.const [picking, setPicking] = useState(false);@@ -159,14 +190,16 @@ export function NoteComposer({};}, [from]);- // Portaled to the body so the sheet covers the app: a press on the paper is- // a press on the note, and it never reaches the list's rubber-band selection- // underneath.+ // Portaled to the body so the sheet covers the app. React still bubbles a+ // portal's events up to the page that rendered it, so the sheet stops them+ // here: a right-click, a press or a file dropped on the paper belongs to the+ // note, never to the page's menu, rubber-band selection or import.return createPortal(<divrole="dialog"aria-modal="true"aria-label={draft.title.trim() || "Untitled note"}+ {...KEEP_EVENTS}className="fixed inset-0 z-50 flex flex-col font-system antialiased"style={{ backgroundColor: paper.background, color: NOTE_INK }}>@@ -219,24 +252,19 @@ export function NoteComposer({))}</DropdownMenuContent></DropdownMenu>- {!draft.isNew && (- <Button- variant="ghost"- aria-label="Delete note"- className="text-destructive hover:bg-black/5 hover:text-destructive"- onClick={onDelete}- >- <Trash2 data-icon="inline-start" /> Delete- </Button>- )}- <Button className="bg-black/80 text-white hover:bg-black" onClick={onClose}>- Done+ <Button+ variant="ghost"+ aria-label="Delete note"+ className="text-destructive hover:bg-black/5 hover:text-destructive"+ onClick={onDelete}+ >+ <Trash2 data-icon="inline-start" /> Delete</Button></header>- {/* The paper scrolls, the header does not. Both text boxes grow with what- is written and never scroll on their own, so a wheel anywhere over- the sheet moves the sheet. */}+ {/* The paper scrolls, the header does not. The title and the body grow+ with what is written and never scroll on their own, so a wheel+ anywhere over the sheet moves the sheet. */}<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain"><div className="mx-auto flex w-full max-w-3xl flex-col gap-4 px-8 pt-6 pb-32"><textarea@@ -251,7 +279,7 @@ export function NoteComposer({onKeyDown={(e) => {if (e.key === "Enter") {e.preventDefault();- bodyRef.current?.focus();+ body.current?.commands.focus("start");}}}/>@@ -293,14 +321,11 @@ export function NoteComposer({</PopoverContent></Popover></div>- <textarea- ref={bodyRef}- rows={1}- value={draft.body}- placeholder="Write your note…"- className="min-h-[50vh] resize-none overflow-hidden bg-transparent text-lg leading-8 outline-none placeholder:opacity-40"- style={{ color: NOTE_INK }}- onChange={(e) => onChange({ ...draft, body: e.target.value })}+ <NoteBodyEditor+ body={draft.body}+ ink={NOTE_INK}+ onChange={(text) => onChange({ ...draftRef.current, body: text })}+ onEditor={(editor) => (body.current = editor)}/></div></div>diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsxindex 67c3213c..53b3fd53 100644--- a/site/src/cut/components/NotesView.tsx+++ b/site/src/cut/components/NotesView.tsx@@ -24,6 +24,7 @@ import {type CutNoteFolder,} from "@/cut/lib/notes";import { homeHref, useCutBase } from "@/cut/lib/nav";+import { cutNotes } from "@/cut/lib/chatRuntime";import { notesKey, patchNotes, useNotes } from "@/cut/lib/queries";import { cn } from "@/lib/utils";import { setObjectDragImage } from "@/cut/lib/assetDrag";@@ -32,6 +33,7 @@ import { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";import { DeleteConfirm, foldersGoNote } from "./selectionMenu";import { LIBRARY_SQUARE } from "./LibraryCard";import { NoteComposer, noteChanged, type NoteDraft } from "./NoteComposer";+import { NoteBodyPreview } from "./NoteBodyPreview";// The note paper's ink, matching the iOS app.const NOTE_INK = "#201a0d";@@ -45,8 +47,8 @@ const NOTE_FOLDERS_MOVE_MIME = "application/x-donkey-note-folders";/** Write a note out. The list shows it the moment it is written, and the* server's answer — this write, or a newer one from the phone — replaces it.* False means the write was lost and the list has to be read again. A note- * with nothing in it, or one that comes back untouched, is left alone, so- * opening a note to read it keeps the list in the order it had.+ * that comes back untouched is left alone, so opening a note to read it keeps+ * the list in the order it had.** `settleFolder` waits on a folder's own write, so the server knows the folder* by the time a note names it. */@@ -57,13 +59,12 @@ async function writeNote(settleLabels: (labelIds: string[]) => Promise<string[]>,): Promise<boolean> {const { id, title, body, colorIndex, folderId, labelIds, libraryLocation } = d;- if (!title.trim() && !body.trim()) return true;if (!noteChanged(d)) return true;const now = Date.now();const optimistic: CutNote = {id,- title: title.trim() || "Untitled",- body: body.trim(),+ title: title.trim(),+ body: body.trimEnd(),colorIndex,folderId,labelIds,@@ -92,7 +93,6 @@ async function writeNote(colorIndex,folderId,labelIds: live,- ...(d.isNew ? { libraryLocation } : {}),}).catch(() => null);if (!saved) return false;patchNotes(client, (prev) => ({@@ -110,6 +110,20 @@ const mintLabel = (name: string) => ({createdAt: Date.now(),});+/** A new note with nothing in it yet, stamped now. */+const blankNote = (folderId: string | null, libraryLocation: NoteLocation | null): CutNote => ({+ id: crypto.randomUUID(),+ title: "",+ body: "",+ colorIndex: 0,+ folderId,+ libraryLocation,+ labelIds: [],+ updatedAt: Date.now(),+ deletedAt: null,+ createdAt: Date.now(),+});+/** A stored note, opened for editing. */const draftOf = (n: CutNote): NoteDraft => ({id: n.id,@@ -119,7 +133,6 @@ const draftOf = (n: CutNote): NoteDraft => ({folderId: n.folderId ?? null,labelIds: n.labelIds,libraryLocation: n.libraryLocation,- isNew: false,saved: { title: n.title, body: n.body, colorIndex: n.colorIndex, labelIds: n.labelIds },});@@ -148,6 +161,22 @@ export function NotesView({ library, ref }: Props = {}) {buffer.current = d;setEditing(d);};+ // A folder tile is on screen the moment it is made, so a note can be filed+ // into it while its own write is still in flight. The write is held here+ // and awaited before any note names that folder, so the server knows the+ // folder by the time it has to resolve the id.+ const folderWrites = useRef(new Map<string, Promise<unknown>>());+ const settleFolder = async (folderId: string | null) => {+ if (folderId) await folderWrites.current.get(folderId);+ };+ // Every note write runs after the one before it, so the server and the list+ // take them in the order they were made.+ const writes = useRef<Promise<unknown>>(Promise.resolve());+ const queue = <T,>(job: () => Promise<T>): Promise<T> => {+ const run = writes.current.then(job);+ writes.current = run;+ return run;+ };const [selected, setSelected] = useState<Set<string>>(new Set());const [folderCreating, setFolderCreating] = useState(false);const [deletingFolder, setDeletingFolder] = useState<string | null>(null);@@ -230,33 +259,36 @@ export function NotesView({ library, ref }: Props = {}) {pushedNote.current = true;};+ /** Make a blank note and open it. It is written at once, so it is a note+ * from the moment it is asked for, and every save after this one edits it. */const openNew = () => {- const id = crypto.randomUUID();- edit({- id,- title: "",- body: "",- colorIndex: 0,- // A note written inside a folder is filed there.- folderId: openFolder,- ...(library ? { libraryLocation: { folderId: library.folderId, residency: library.residency } satisfies NoteLocation } : {}),- labelIds: [],- isNew: true,- saved: { title: "", body: "", colorIndex: 0, labelIds: [] },+ // A note written inside a folder is filed there.+ const note = blankNote(openFolder, library ? { folderId: library.folderId, residency: library.residency } : null);+ patchNotes(client, (prev) => ({ ...prev, notes: [note, ...prev.notes] }));+ edit(draftOf(note));+ openAt(note.id);+ const folderId = openFolder;+ void queue(async () => {+ await settleFolder(folderId);+ const saved = await saveNote({+ id: note.id,+ title: "",+ body: "",+ colorIndex: 0,+ folderId,+ labelIds: [],+ ...(library ? { libraryLocation: note.libraryLocation } : {}),+ }).catch(() => null);+ if (!saved) return reload();+ patchNotes(client, (prev) => ({+ ...prev,+ notes: prev.notes.map((n) => (n.id === note.id ? saved : n)),+ }));});- openAt(id);};const openNote = (n: CutNote) => openAt(n.id);useImperativeHandle(ref, () => ({ create: openNew }));- // A folder tile is on screen the moment it is made, so a note can be filed- // into it while its own write is still in flight. The write is held here- // and awaited before any note names that folder, so the server knows the- // folder by the time it has to resolve the id.- const folderWrites = useRef(new Map<string, Promise<unknown>>());- const settleFolder = async (folderId: string | null) => {- if (folderId) await folderWrites.current.get(folderId);- };// The same holds for labels: one made in the picker is on the note at once,// and its own write is awaited before a note carries the id to the server.// A write that failed answers false, and the id it minted never reaches a@@ -333,12 +365,20 @@ export function NotesView({ library, ref }: Props = {}) {void deleteNoteLabel(id).catch(() => reload());};- /** Write a note out and let go of it. */- const commit = (d: NoteDraft) => {- setEditing(null);- void writeNote(client, d, settleFolder, settleLabels).then((ok) => {- if (!ok) setFailedDraft(d);- else { setFailedDraft(null); reload(); }+ /** Write the draft as it stands, after any write still in flight. The open+ * draft takes what was sent as its baseline, so the next save writes only a+ * real change; a lost write hands the old baseline back, so the next save+ * tries again. A note already closed when its write is lost offers a retry. */+ const save = (d: NoteDraft): Promise<boolean> => {+ if (!noteChanged(d)) return Promise.resolve(true);+ const sent = { title: d.title.trim(), body: d.body.trimEnd(), colorIndex: d.colorIndex, labelIds: d.labelIds };+ if (buffer.current?.id === d.id) edit({ ...buffer.current, saved: sent });+ return queue(() => writeNote(client, d, settleFolder, settleLabels)).then((ok) => {+ const held = buffer.current;+ if (ok) setFailedDraft(null);+ else if (held?.id !== d.id) setFailedDraft(d);+ else if (held.saved === sent) edit({ ...held, saved: d.saved });+ return ok;});};@@ -351,24 +391,43 @@ export function NotesView({ library, ref }: Props = {}) {window.history.replaceState(null, "", notesHref(openFolder));}};- /** Write whatever the composer holds and let go of it. */+ // A typed edit saves once the note has sat still for the autosave delay.+ const autosave = useRef<ReturnType<typeof setTimeout> | null>(null);+ const holdAutosave = () => {+ if (autosave.current) clearTimeout(autosave.current);+ autosave.current = null;+ };+ const change = (d: NoteDraft) => {+ edit(d);+ holdAutosave();+ autosave.current = setTimeout(() => {+ autosave.current = null;+ if (buffer.current) void save(buffer.current);+ }, cutNotes().autosaveMs);+ };++ /** Save whatever the composer holds one last time and let go of it. */const letGo = () => {+ holdAutosave();const d = buffer.current;buffer.current = null;setEditing(null);- if (d) commit(d);+ if (d) void save(d).then((ok) => ok && reload());};const remove = () => {const d = draft;+ holdAutosave();buffer.current = null;setEditing(null);popNote();- if (!d || d.isNew) return;+ if (!d) return;patchNotes(client, (prev) => ({...prev,notes: prev.notes.filter((n) => n.id !== d.id),}));- void deleteNote(d.id).catch(() => reload());+ // Behind any save still queued for it, whose later stamp would bring+ // the note back.+ void queue(() => deleteNote(d.id).catch(() => reload()));};/** File a set of notes into a folder (or back to the top level). Each note@@ -451,14 +510,20 @@ export function NotesView({ library, ref }: Props = {}) {useEffect(() => {closing.current = letGo;});- /** Done, Escape, or the back arrow. */+ /** Escape or the back arrow. */const closeNote = () => {letGo();popNote();};+ // The note editor's code arrives while the list is up, so the first note+ // opens as fast as the rest.+ useEffect(() => {+ void import("./NoteBodyEditor");+ }, []);+// Leaving the page (the sidebar, another tab) writes the open note the same- // way its own Done does, so a draft is never dropped.+ // way its back arrow does, so a draft is never dropped.useEffect(() => () => closing.current(), []);// Back and forward are how a note closes, so the browser's own event is what@@ -515,11 +580,12 @@ export function NotesView({ library, ref }: Props = {}) {behind it, so closing comes back to the same scroll position. */}{draft && (<NoteComposer+ key={draft.id}draft={draft}back={library?.name ?? draftFolderName ?? "All notes"}from={pageRef}labels={labels}- onChange={edit}+ onChange={change}onClose={closeNote}onDelete={remove}onCreateLabel={createLabel}@@ -658,7 +724,7 @@ export function NotesView({ library, ref }: Props = {}) {onClick={() => openNote(n)}>{n.title && <div className="truncate text-[13px] font-semibold">{n.title}</div>}- <div className="line-clamp-5 text-[12px] whitespace-pre-wrap opacity-80">{n.body}</div>+ <NoteBodyPreview body={n.body} lines={5} className="text-[12px] opacity-80" />{worn.length > 0 && (<div className="mt-auto flex flex-wrap gap-1 pt-1.5">{worn.map((name) => (diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsxindex f6bbbbc0..9d98f032 100644--- a/site/src/cut/components/RequireSession.tsx+++ b/site/src/cut/components/RequireSession.tsx@@ -1,5 +1,5 @@"use client";-import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge } from "@/cut/lib/chatRuntime";+import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge, bindCutNotes } from "@/cut/lib/chatRuntime";import { bindCutColor } from "@/cut/lib/colorSettings";import { useEffect, type ReactNode } from "react";@@ -45,6 +45,7 @@ export function RequireSession({ children }: { children: ReactNode }) {bindChatgptPolling(config.data.settings.chatgptPolling);bindCutJudge(config.data.settings.cutJudge);bindCutClip(config.data.settings.cutClip);+ bindCutNotes(config.data.settings.cutNotes);bindCutColor(config.data.settings.cutColor);reportExposures(config.data);}, [userId, config.data]);diff --git a/site/src/cut/lib/chatRuntime.ts b/site/src/cut/lib/chatRuntime.tsindex 332fdd8b..6d4934d4 100644--- a/site/src/cut/lib/chatRuntime.ts+++ b/site/src/cut/lib/chatRuntime.ts@@ -27,3 +27,10 @@ export function bindCutClip(value: unknown): void {if (parsed.success) clip = parsed.data;}export function cutClip(): Settings["cutClip"] { return clip; }++let notes: Settings["cutNotes"] = SETTINGS.cutNotes.default;+export function bindCutNotes(value: unknown): void {+ const parsed = SETTINGS.cutNotes.schema.safeParse(value);+ if (parsed.success) notes = parsed.data;+}+export function cutNotes(): Settings["cutNotes"] { return notes; }diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex a48f30ad..449481bb 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -292,6 +292,13 @@ export const SETTINGS = defineSettings({description:"How a talk or an interview is read for the moments worth cutting a short from: what a clip may run, how widely the first sweep looks, how many moments earn the close read, and what the ranking weighs.",},+ cutNotes: {+ schema: z.object({ autosaveMs: z.number().int().min(200).max(10000) }).strict(),+ default: { autosaveMs: 800 },+ public: true,+ title: "Notes",+ description: "How long a note sits still after the last keystroke before it saves.",+ },cutColor: {schema: z.object({