Skip to content

Open source CapCut alternative.

TypeScript

feat(site): one-click lists in the note toolbar

David Le853fe70b36ed
diff --git a/site/src/cut/components/NoteBodyEditor.tsx b/site/src/cut/components/NoteBodyEditor.tsx
index 14ba692b..cadb9cbc 100644
--- a/site/src/cut/components/NoteBodyEditor.tsx
+++ b/site/src/cut/components/NoteBodyEditor.tsx
@@ -6,9 +6,12 @@ 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 { Slice } from "@tiptap/pm/model";
+import type { EditorView } from "@tiptap/pm/view";
+import { Bold, Check, ChevronDown, Italic, List, ListOrdered, ListTodo, Strikethrough, Underline } from "lucide-react";
+import { NOTE_TEXT_COLORS, parseNoteBody, pastedNoteBlocks, serializeNoteBody, type NoteTextColor } from "@/cut/lib/noteMarkdown";
+import { blocksOf, docOf, dropBlankLines, splitSelection, TextColor } from "@/cut/lib/noteDoc";
+import { useLocalPref } from "@/cut/lib/uiState";
import { cn } from "@/lib/utils";
/** What a selection can turn its lines into, the way the toolbar names it. */
@@ -20,15 +23,14 @@ const TURN_INTO: { id: string; label: string; active: (e: Editor) => boolean; ru
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: "bullet", label: "Bulleted list", active: (e) => e.isActive("bulletList"), run: (e) => toList(e).toggleBulletList().run() },
+ { id: "number", label: "Numbered list", active: (e) => e.isActive("orderedList"), run: (e) => toList(e).toggleOrderedList().run() },
+ { id: "todo", label: "To-do list", active: (e) => e.isActive("taskList"), run: (e) => toList(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();
+function toText(e: Editor, 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();
@@ -36,6 +38,49 @@ function toText(e: Editor) {
return chain;
}
+/** Lines turning into a list: selected words cut out onto lines of their
+ * own, then the blank lines between the written ones drop. */
+function toList(e: Editor) {
+ return toText(e, e.chain().focus().command(splitSelection)).command(dropBlankLines);
+}
+
+/** The list styles the toolbar's list button makes, by their turn-into ids. */
+const LIST_STYLES = [
+ { id: "bullet", icon: List },
+ { id: "number", icon: ListOrdered },
+ { id: "todo", icon: ListTodo },
+] as const;
+type ListStyle = (typeof LIST_STYLES)[number]["id"];
+
+/** Paste plain text as the note's Markdown when its lines carry block
+ * markers, so "- a" or "1. a" copied from a chat or a text file lands as the
+ * list it was written as. A copy from a note, or rich text that brings its
+ * own blocks, pastes as the editor reads it. */
+function pasteMarkdown(view: EditorView, event: ClipboardEvent, slice: Slice): boolean {
+ const html = event.clipboardData?.getData("text/html") ?? "";
+ if (html.includes("data-pm-slice")) {
+ return false;
+ }
+ let blocks = false;
+ slice.content.forEach((node) => {
+ blocks ||= node.type.name !== "paragraph";
+ });
+ if (blocks) {
+ return false;
+ }
+ const pasted = pastedNoteBlocks(event.clipboardData?.getData("text/plain") ?? "");
+ if (!pasted) {
+ return false;
+ }
+
+ // Leading and trailing text joins the line the caret is on, the way a
+ // plain paste does.
+ const doc = view.state.schema.nodeFromJSON(docOf(pasted));
+ const open = (node: typeof doc.firstChild) => (node?.type.name === "paragraph" ? 1 : 0);
+ view.dispatch(view.state.tr.replaceSelection(new Slice(doc.content, open(doc.firstChild), open(doc.lastChild))).scrollIntoView());
+ return true;
+}
+
/** 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
@@ -78,7 +123,7 @@ export default function NoteBodyEditor({
Placeholder.configure({ placeholder: "Write your note…" }),
],
content: initial,
- editorProps: { attributes: { class: "outline-none min-h-[50vh]" } },
+ editorProps: { attributes: { class: "outline-none min-h-[50vh]" }, handlePaste: pasteMarkdown },
onCreate: ({ editor }) => handlers.current.onEditor?.(editor),
onDestroy: () => handlers.current.onEditor?.(null),
onUpdate: ({ editor }) => handlers.current.onChange(serializeNoteBody(blocksOf(editor.getJSON()))),
@@ -110,11 +155,16 @@ export default function NoteBodyEditor({
/** 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 [panel, setPanel] = useState<"turn" | "list" | "color" | null>(null);
+ // The style the list button makes: the last one picked from its menu, kept
+ // across notes and reloads.
+ const [listStyle, setListStyle] = useLocalPref<ListStyle>("cut-note-list-style", "bullet", (v) =>
+ LIST_STYLES.some((l) => l.id === v),
+ );
const state = useEditorState({
editor,
selector: ({ editor: e }) => ({
- turn: TURN_INTO.find((t) => t.active(e))?.label ?? "Text",
+ turn: TURN_INTO.find((t) => t.active(e))?.id ?? "text",
bold: e.isActive("bold"),
italic: e.isActive("italic"),
underline: e.isActive("underline"),
@@ -124,6 +174,10 @@ function Toolbar({ editor }: { editor: Editor }) {
});
const keep = (e: React.MouseEvent) => e.preventDefault();
const color = NOTE_TEXT_COLORS.find((c) => c.id === state.color);
+ const turn = (id: string) => TURN_INTO.find((t) => t.id === id)!.run(editor);
+ const label = (id: string) => TURN_INTO.find((t) => t.id === id)!.label;
+ const activeList = LIST_STYLES.find((l) => l.id === state.turn);
+ const list = LIST_STYLES.find((l) => l.id === listStyle)!;
return (
<BubbleMenu
@@ -135,10 +189,10 @@ function Toolbar({ editor }: { editor: Editor }) {
<Menu
open={panel === "turn"}
onToggle={() => setPanel(panel === "turn" ? null : "turn")}
- trigger={<>{state.turn}<ChevronDown className="size-3.5 opacity-50" /></>}
+ trigger={<>{label(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); }}>
+ <MenuItem key={t.id} checked={t.id === state.turn} onPick={() => { t.run(editor); setPanel(null); }}>
{t.label}
</MenuItem>
))}
@@ -149,6 +203,21 @@ function Toolbar({ editor }: { editor: Editor }) {
<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 />
+ <Toggle label={label(list.id)} on={state.turn === list.id} onPress={() => turn(state.turn === list.id ? "text" : list.id)}><list.icon className="size-4" /></Toggle>
+ <Menu
+ open={panel === "list"}
+ onToggle={() => setPanel(panel === "list" ? null : "list")}
+ label="List style"
+ trigger={<ChevronDown className="size-3.5 opacity-50" />}
+ fit="icon"
+ >
+ {LIST_STYLES.map((l) => (
+ <MenuItem key={l.id} checked={l.id === activeList?.id} onPick={() => { setListStyle(l.id); turn(l.id); setPanel(null); }}>
+ <l.icon className="size-4" /> {label(l.id)}
+ </MenuItem>
+ ))}
+ </Menu>
+ <Divider />
<Menu
open={panel === "color"}
onToggle={() => setPanel(panel === "color" ? null : "color")}
@@ -184,14 +253,17 @@ function Toggle({ label, on, onPress, children }: { label: string; on: boolean;
);
}
-function Menu({ open, onToggle, label, trigger, children }: { open: boolean; onToggle: () => void; label?: string; trigger: ReactNode; children: ReactNode }) {
+/** How a menu's trigger sits: around a label, or close around a lone icon. */
+type MenuFit = "label" | "icon";
+
+function Menu({ open, onToggle, label, trigger, fit = "label", children }: { open: boolean; onToggle: () => void; label?: string; trigger: ReactNode; fit?: MenuFit; 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")}
+ className={cn("flex h-7 cursor-pointer items-center gap-1 rounded-md hover:bg-black/5", fit === "icon" ? "px-1" : "px-2", open && "bg-black/5")}
onClick={onToggle}
>
{trigger}
diff --git a/site/src/cut/lib/noteDoc.ts b/site/src/cut/lib/noteDoc.ts
index 16acbfce..fbde0a82 100644
--- a/site/src/cut/lib/noteDoc.ts
+++ b/site/src/cut/lib/noteDoc.ts
@@ -1,4 +1,5 @@
-import { Mark, mergeAttributes, type JSONContent } from "@tiptap/core";
+import { Mark, mergeAttributes, type Command, type JSONContent } from "@tiptap/core";
+import { TextSelection, type Transaction } from "@tiptap/pm/state";
import {
NOTE_LIST_KINDS,
NOTE_TEXT_COLORS,
@@ -121,6 +122,82 @@ export function docOf(blocks: NoteBlock[]): JSONContent {
return { type: "doc", content };
}
+/** Take the blank lines out of a selection of several written lines, so the
+ * list it turns into numbers only what was written: 1, 2, 3, never 1, 3, 5
+ * around empty items. A blank line alone stays to take the list. */
+export const dropBlankLines: Command = ({ tr }) => {
+ const blanks: { from: number; to: number }[] = [];
+ let written = 0;
+ tr.doc.nodesBetween(tr.selection.from, tr.selection.to, (node, pos) => {
+ if (!node.isTextblock) {
+ return true;
+ }
+ if (node.content.size === 0) {
+ blanks.push({ from: pos, to: pos + node.nodeSize });
+ } else {
+ written++;
+ }
+ return false;
+ });
+ if (written === 0) {
+ return true;
+ }
+
+ // Last first, so the earlier positions still hold.
+ for (const b of blanks.reverse()) {
+ tr.delete(b.from, b.to);
+ }
+ return true;
+};
+
+/** Cut the selected words out of their lines onto lines of their own, so a
+ * list made from a piece of a line takes that piece: "eggs" selected in "milk
+ * eggs bread" leaves "milk", "eggs", "bread". Spaces at a cut go with it. Only
+ * plain lines cut; a heading, quote or list line turns whole. */
+export const splitSelection: Command = ({ tr }) => {
+ const { from, to, empty } = tr.selection;
+ if (empty) {
+ return true;
+ }
+
+ // The end first, so the start's position still holds; then the end maps
+ // through the start's cut.
+ const end = cutLine(tr, to) ?? to;
+ const steps = tr.steps.length;
+ const start = cutLine(tr, from);
+ // A cut start's words open the next line, past the split's two tokens.
+ const head = start === null ? from : start + 2;
+ tr.setSelection(TextSelection.create(tr.doc, head, tr.mapping.slice(steps).map(end, -1)));
+ return true;
+};
+
+/** Split a plain line at `pos`, dropping the spaces around the cut. Returns
+ * where the words before the cut now end, or null when the line is left
+ * whole because the cut sits at its edge. */
+function cutLine(tr: Transaction, pos: number): number | null {
+ const $pos = tr.doc.resolve(pos);
+ if ($pos.depth !== 1 || $pos.parent.type.name !== "paragraph") {
+ return null;
+ }
+ const text = $pos.parent.textContent;
+ let before = $pos.parentOffset;
+ let after = before;
+ while (before > 0 && /\s/.test(text[before - 1])) {
+ before--;
+ }
+ while (after < text.length && /\s/.test(text[after])) {
+ after++;
+ }
+ if (before === 0 || after === text.length) {
+ return null;
+ }
+
+ const base = $pos.start();
+ tr.delete(base + before, base + after);
+ tr.split(base + before);
+ return base + before;
+}
+
/** A named text color. The name is what the body stores; the ink is the
* paper's. */
export const TextColor = Mark.create({
diff --git a/site/src/cut/lib/noteMarkdown.test.ts b/site/src/cut/lib/noteMarkdown.test.ts
index 45e485ae..a237e0fc 100644
--- a/site/src/cut/lib/noteMarkdown.test.ts
+++ b/site/src/cut/lib/noteMarkdown.test.ts
@@ -1,10 +1,11 @@
import { describe, expect, test } from "bun:test";
import { getSchema } from "@tiptap/core";
import { Node } from "@tiptap/pm/model";
+import { EditorState, TextSelection } from "@tiptap/pm/state";
import StarterKit from "@tiptap/starter-kit";
import { TaskItem, TaskList } from "@tiptap/extension-list";
-import { noteBodyText, parseInline, parseNoteBody, serializeNoteBody } from "@/cut/lib/noteMarkdown";
-import { blocksOf, docOf, TextColor } from "@/cut/lib/noteDoc";
+import { noteBodyText, parseInline, parseNoteBody, pastedNoteBlocks, serializeNoteBody } from "@/cut/lib/noteMarkdown";
+import { blocksOf, docOf, dropBlankLines, splitSelection, TextColor } from "@/cut/lib/noteDoc";
const roundTrip = (body: string) => serializeNoteBody(parseNoteBody(body));
@@ -76,6 +77,16 @@ describe("note markdown", () => {
];
expect(parseNoteBody(serializeNoteBody(blocks))).toEqual(blocks);
});
+
+ test("pasted Markdown lists come in as lists, loose lists closed up", () => {
+ const pasted = (text: string) => {
+ const blocks = pastedNoteBlocks(text);
+ return blocks && serializeNoteBody(blocks);
+ };
+ expect(pasted("1. one\r\n\r\n2. two\n\n\n3. three\n")).toBe("1. one\n2. two\n3. three");
+ expect(pasted("Plan\n\n- a\n\n- b\n\nAfter")).toBe("Plan\n\n- a\n- b\n\nAfter");
+ expect(pasted("just words\n\nmore words")).toBeNull();
+ });
});
describe("note editor document", () => {
@@ -93,4 +104,37 @@ describe("note editor document", () => {
expect(serializeNoteBody(blocksOf(doc))).toBe(body);
}
});
+
+ test("blank lines inside a selection drop before it turns into a list", () => {
+ const body = "one\n\ntwo\n\nthree\n\nafter";
+ const doc = Node.fromJSON(schema, docOf(parseNoteBody(body)));
+ const lines = (from: number, to: number) => {
+ const state = EditorState.create({ doc, selection: TextSelection.create(doc, from, to) });
+ const tr = state.tr;
+ dropBlankLines({ tr } as Parameters<typeof dropBlankLines>[0]);
+ return serializeNoteBody(blocksOf(tr.doc.toJSON()));
+ };
+ // From inside "one" to inside "three": the blanks between go, the one after stays.
+ expect(lines(2, 16)).toBe("one\ntwo\nthree\n\nafter");
+ // A blank line on its own is left for the list to take.
+ expect(lines(6, 6)).toBe(body);
+ });
+
+ test("selected words cut out onto their own lines before a list takes them", () => {
+ const cut = (body: string, words: string) => {
+ const doc = Node.fromJSON(schema, docOf(parseNoteBody(body)));
+ // The words' positions: one past the line's opening.
+ const from = doc.textContent.indexOf(words) + 1;
+ const state = EditorState.create({ doc, selection: TextSelection.create(doc, from, from + words.length) });
+ const tr = state.tr;
+ splitSelection({ tr } as Parameters<typeof splitSelection>[0]);
+ return [serializeNoteBody(blocksOf(tr.doc.toJSON())), tr.doc.textBetween(tr.selection.from, tr.selection.to, "|")];
+ };
+ expect(cut("milk eggs bread", "eggs")).toEqual(["milk\neggs\nbread", "eggs"]);
+ expect(cut("I quit. I'll find one.", "I'll find one.")).toEqual(["I quit.\nI'll find one.", "I'll find one."]);
+ expect(cut("I quit. I'll find one.", " I'll")).toEqual(["I quit.\nI'll\nfind one.", "I'll"]);
+ // A whole line, or a piece of a heading, stays as it is.
+ expect(cut("milk eggs", "milk eggs")).toEqual(["milk eggs", "milk eggs"]);
+ expect(cut("# milk eggs", "eggs")).toEqual(["# milk eggs", "eggs"]);
+ });
});
diff --git a/site/src/cut/lib/noteMarkdown.ts b/site/src/cut/lib/noteMarkdown.ts
index fec9a846..32943f52 100644
--- a/site/src/cut/lib/noteMarkdown.ts
+++ b/site/src/cut/lib/noteMarkdown.ts
@@ -261,6 +261,38 @@ export function serializeInline(runs: NoteRun[]): string {
return out;
}
+/** Plain text pasted into a note, read as the note's Markdown when a line
+ * opens with a block marker, so a list, heading or quote copied from a chat
+ * or a text file comes in as that block. Blank lines between list lines close
+ * up, keeping a loose list one list: "1. a\n\n2. b" is items 1 and 2. Text
+ * with no marker returns null and pastes as it is. */
+export function pastedNoteBlocks(text: string): NoteBlock[] | null {
+ const blocks = parseNoteBody(text.replace(/\r\n?/g, "\n").replace(/\n+$/, ""));
+ if (blocks.every((b) => b.kind === "paragraph")) {
+ return null;
+ }
+
+ // Drop each run of blank lines that sits between two list lines.
+ const blank = (b: NoteBlock) => b.kind === "paragraph" && b.runs.every((r) => !r.text);
+ const out: NoteBlock[] = [];
+ for (let i = 0; i < blocks.length; i++) {
+ if (!blank(blocks[i])) {
+ out.push(blocks[i]);
+ continue;
+ }
+ let next = i;
+ while (next < blocks.length && blank(blocks[next])) {
+ next++;
+ }
+ const between = NOTE_LIST_KINDS.has(out.at(-1)?.kind ?? "paragraph") && NOTE_LIST_KINDS.has(blocks[next]?.kind ?? "paragraph");
+ if (!between) {
+ out.push(...blocks.slice(i, next));
+ }
+ i = next - 1;
+ }
+ return out;
+}
+
/** The words of a body with its markup taken out. */
export function noteBodyText(body: string): string {
return parseNoteBody(body)