⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(editor): preserve formatting when pasting Markdown (#1797)
Tin Severea40211c79e2
diff --git a/apps/web/src/components/activity/comment-editor.tsx b/apps/web/src/components/activity/comment-editor.tsxindex c2792b226..b5ac73b32 100644--- a/apps/web/src/components/activity/comment-editor.tsx+++ b/apps/web/src/components/activity/comment-editor.tsx@@ -7,7 +7,6 @@ import TableHeader from "@tiptap/extension-table-header";import TableRow from "@tiptap/extension-table-row";import TaskList from "@tiptap/extension-task-list";import { Markdown } from "@tiptap/markdown";-import { Fragment, Slice } from "@tiptap/pm/model";import { TextSelection } from "@tiptap/pm/state";import { EditorContent, useEditor } from "@tiptap/react";import { BubbleMenu } from "@tiptap/react/menus";@@ -63,7 +62,6 @@ import {import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";import { cn } from "@/lib/cn";-import { parseTaskListMarkdownToNodes } from "@/lib/editor-task-list-paste";import {extractIssueKeyFromUrl,extractTaskIdFromUrl,@@ -72,6 +70,7 @@ import {} from "@/lib/editor-url-utils";import { isInCodeBlockLanguagePicker } from "@/lib/is-in-codeblock-language-picker";import { normalizeCommentMarkdown } from "@/lib/normalize-comment-markdown";+import { pasteMarkdown } from "@/lib/paste-markdown";import { toast } from "@/lib/toast";import { uploadTaskImage } from "@/lib/upload-task-image";@@ -712,20 +711,7 @@ export default function CommentEditor({}const plainText = event.clipboardData?.getData("text/plain") || "";- const taskListNodes = parseTaskListMarkdownToNodes(plainText);- if (taskListNodes) {- event.preventDefault();- const nodes = taskListNodes.map((node) =>- view.state.schema.nodeFromJSON(node),- );- const fragment = Fragment.fromArray(nodes);- view.dispatch(- view.state.tr- .replaceSelection(new Slice(fragment, 0, 0))- .scrollIntoView(),- );- return true;- }+ if (editor && pasteMarkdown(editor, event)) return true;const pastedText = plainText.trim();if (!pastedText || /\s/.test(pastedText)) return false;diff --git a/apps/web/src/components/task/task-description.test.tsx b/apps/web/src/components/task/task-description.test.tsxindex 3d2a8b7b7..95285899d 100644--- a/apps/web/src/components/task/task-description.test.tsx+++ b/apps/web/src/components/task/task-description.test.tsx@@ -6,6 +6,7 @@ import TaskDescription from "./task-description";const mocks = vi.hoisted(() => ({t: (key: string) => key,+ save: vi.fn(),tasks: new Map<string, { id: string; description: string }>(),}));@@ -45,7 +46,7 @@ vi.mock("@/hooks/queries/task/use-get-task", () => ({default: (taskId: string) => ({ data: mocks.tasks.get(taskId) }),}));vi.mock("@/hooks/mutations/task/use-update-task-description", () => ({- useUpdateTaskDescription: () => ({ mutateAsync: vi.fn() }),+ useUpdateTaskDescription: () => ({ mutateAsync: mocks.save }),}));vi.mock("@/hooks/use-workspace-permission", () => ({useWorkspacePermission: () => ({ canUpdateTasks: () => true }),@@ -64,6 +65,52 @@ vi.mock("@/lib/shiki-highlighter", () => ({}));describe("TaskDescription", () => {+ it("preserves bold Markdown when pasting, saving and reopening a checklist (#1779)", async () => {+ mocks.save.mockClear();+ mocks.tasks.set("markdown-task", { id: "markdown-task", description: "" });+ const { container, unmount } = render(+ <TaskDescription taskId="markdown-task" />,+ );+ await waitFor(() =>+ expect(+ container.querySelector('[contenteditable="true"]'),+ ).not.toBeNull(),+ );+ await new Promise(requestAnimationFrame);+ const editable = container.querySelector<HTMLElement>(+ '[contenteditable="true"]',+ );+ if (!editable) throw new Error("Editor missing");+ fireEvent.paste(editable, {+ clipboardData: {+ files: [],+ getData: (type: string) =>+ type === "text/plain"+ ? "- [ ] **Provide a staff-only interface.**"+ : "",+ },+ });+ await waitFor(() => expect(mocks.save).toHaveBeenCalled());+ const saved = mocks.save.mock.calls[0][0].description;+ expect(saved).toContain("**Provide a staff-only interface.**");+ expect(saved).not.toContain("\\*");+ expect(container.querySelector("strong")?.textContent).toBe(+ "Provide a staff-only interface.",+ );+ unmount();+ mocks.tasks.set("markdown-task", {+ id: "markdown-task",+ description: saved,+ });+ const reopened = render(<TaskDescription taskId="markdown-task" />);+ await waitFor(() =>+ expect(reopened.container.querySelector("strong")?.textContent).toBe(+ "Provide a staff-only interface.",+ ),+ );+ reopened.unmount();+ });+it("renders the parent description when navigating from a subtask (#1580)", async () => {mocks.tasks.set("child-task", {id: "child-task",diff --git a/apps/web/src/components/task/task-description.tsx b/apps/web/src/components/task/task-description.tsxindex 48a36e793..8ec2c25c5 100644--- a/apps/web/src/components/task/task-description.tsx+++ b/apps/web/src/components/task/task-description.tsx@@ -6,7 +6,6 @@ import TableHeader from "@tiptap/extension-table-header";import TableRow from "@tiptap/extension-table-row";import TaskList from "@tiptap/extension-task-list";import { Markdown } from "@tiptap/markdown";-import { Fragment, Slice } from "@tiptap/pm/model";import { EditorState, TextSelection } from "@tiptap/pm/state";import { EditorContent, useEditor } from "@tiptap/react";import { BubbleMenu } from "@tiptap/react/menus";@@ -63,7 +62,6 @@ import { useUpdateTaskDescription } from "@/hooks/mutations/task/use-update-taskimport useGetTask from "@/hooks/queries/task/use-get-task";import { useWorkspacePermission } from "@/hooks/use-workspace-permission";import { cn } from "@/lib/cn";-import { parseTaskListMarkdownToNodes } from "@/lib/editor-task-list-paste";import {extractIssueKeyFromUrl,extractTaskIdFromUrl,@@ -71,6 +69,7 @@ import {normalizeUrl,} from "@/lib/editor-url-utils";import { isInCodeBlockLanguagePicker } from "@/lib/is-in-codeblock-language-picker";+import { pasteMarkdown } from "@/lib/paste-markdown";import { toast } from "@/lib/toast";import { uploadTaskImage } from "@/lib/upload-task-image";import { AttachmentCard } from "./extensions/attachment-card";@@ -708,20 +707,7 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {}const plainText = event.clipboardData?.getData("text/plain") || "";- const taskListNodes = parseTaskListMarkdownToNodes(plainText);- if (taskListNodes) {- event.preventDefault();- const nodes = taskListNodes.map((node) =>- view.state.schema.nodeFromJSON(node),- );- const fragment = Fragment.fromArray(nodes);- view.dispatch(- view.state.tr- .replaceSelection(new Slice(fragment, 0, 0))- .scrollIntoView(),- );- return true;- }+ if (editor && pasteMarkdown(editor, event)) return true;const pastedText = plainText.trim();if (!pastedText || /\s/.test(pastedText)) return false;diff --git a/apps/web/src/lib/editor-task-list-paste.ts b/apps/web/src/lib/editor-task-list-paste.tsdeleted file mode 100644index 7ffe25a43..000000000--- a/apps/web/src/lib/editor-task-list-paste.ts+++ /dev/null@@ -1,84 +0,0 @@-type ProseMirrorNodeJSON = {- type: string;- attrs?: Record<string, unknown>;- content?: ProseMirrorNodeJSON[];- text?: string;-};--const TASK_LINE_REGEX = /^\s*[-*]\s+\[( |x|X)\]\s*(.*)$/;-const HEADING_REGEX = /^(#{1,6})\s+(.+)$/;--function createParagraphNode(text: string): ProseMirrorNodeJSON {- const normalizedText = text.trim();- if (!normalizedText) {- return { type: "paragraph" };- }-- return {- type: "paragraph",- content: [{ type: "text", text: normalizedText }],- };-}--export function parseTaskListMarkdownToNodes(- rawText: string,-): ProseMirrorNodeJSON[] | null {- if (!/(?:^|\n)\s*[-*]\s+\[(?: |x|X)\]\s+/.test(rawText)) {- return null;- }-- const lines = rawText.replace(/\r\n/g, "\n").split("\n");- const nodes: ProseMirrorNodeJSON[] = [];- let taskItems: ProseMirrorNodeJSON[] = [];- let hasTaskItems = false;-- const flushTaskItems = () => {- if (!taskItems.length) return;- nodes.push({- type: "taskList",- content: taskItems,- });- taskItems = [];- };-- for (const line of lines) {- const trimmedLine = line.trim();- if (!trimmedLine) {- flushTaskItems();- continue;- }-- const taskMatch = TASK_LINE_REGEX.exec(line);- if (taskMatch) {- hasTaskItems = true;- taskItems.push({- type: "taskItem",- attrs: { checked: taskMatch[1].toLowerCase() === "x" },- content: [createParagraphNode(taskMatch[2] || "")],- });- continue;- }-- flushTaskItems();-- const headingMatch = HEADING_REGEX.exec(trimmedLine);- if (headingMatch) {- nodes.push({- type: "heading",- attrs: { level: headingMatch[1].length },- content: [{ type: "text", text: headingMatch[2].trim() }],- });- continue;- }-- nodes.push(createParagraphNode(trimmedLine));- }-- flushTaskItems();-- if (!hasTaskItems || !nodes.length) {- return null;- }-- return nodes;-}diff --git a/apps/web/src/lib/paste-markdown.test.ts b/apps/web/src/lib/paste-markdown.test.tsnew file mode 100644index 000000000..ed4a7d190--- /dev/null+++ b/apps/web/src/lib/paste-markdown.test.ts@@ -0,0 +1,96 @@+import { Editor } from "@tiptap/core";+import TaskItem from "@tiptap/extension-task-item";+import TaskList from "@tiptap/extension-task-list";+import { Markdown } from "@tiptap/markdown";+import StarterKit from "@tiptap/starter-kit";+import { afterEach, describe, expect, it, vi } from "vitest";+import { pasteMarkdown } from "./paste-markdown";++let editor: Editor;+afterEach(() => editor?.destroy());+function setup(content = "") {+ editor = new Editor({+ extensions: [+ StarterKit,+ TaskList,+ TaskItem.configure({ nested: true }),+ Markdown,+ ],+ content,+ contentType: "markdown",+ });+}+function clipboard(text: string, html = "") {+ return {+ clipboardData: {+ getData: (type: string) => (type === "text/html" ? html : text),+ },+ preventDefault: vi.fn(),+ } as unknown as ClipboardEvent;+}+describe("Markdown paste and edit round trips", () => {+ it.each([+ "**Provide a staff-only interface.**",+ "- [ ] **Bold task**\n- [x] *Done*",+ "# Heading\n\n**Bold** and [link](https://example.com)",+ ])("preserves formatting in %s", (markdown) => {+ setup();+ expect(pasteMarkdown(editor, clipboard(markdown))).toBe(true);+ const saved = editor.getMarkdown();+ expect(saved).not.toContain("\\*");+ expect(editor.getHTML()).toContain("<strong>");+ editor.commands.setContent(saved, { contentType: "markdown" });+ expect(editor.getMarkdown()).toBe(saved);+ expect(editor.getHTML()).toContain("<strong>");+ });+ it("inserts inline formatting inside the existing paragraph", () => {+ setup("Hello world");+ editor.commands.setTextSelection(7);+ expect(pasteMarkdown(editor, clipboard("**bold** "))).toBe(true);+ expect(editor.getHTML()).toBe("<p>Hello <strong>bold</strong> world</p>");+ });+ it.each([+ "www.youtube.com/watch?v=video",+ "youtube.com/watch?v=video",+ "www.example.com/issue/TEST-1",+ ])("leaves %s to URL handlers", (url) => {+ setup();+ const event = clipboard(url);+ expect(pasteMarkdown(editor, event)).toBe(false);+ expect(event.preventDefault).not.toHaveBeenCalled();+ });+ it("leaves rich text, plain text and code-block pastes alone", () => {+ setup();+ expect(+ pasteMarkdown(editor, clipboard("**literal**", "<p>**literal**</p>")),+ ).toBe(false);+ expect(pasteMarkdown(editor, clipboard("plain text"))).toBe(false);+ expect(+ pasteMarkdown(editor, clipboard("https://youtube.com/watch?v=video")),+ ).toBe(false);+ editor.commands.setCodeBlock();+ expect(pasteMarkdown(editor, clipboard("**literal**"))).toBe(false);+ });+ it("leaves formatted text literal inside inline code", () => {+ setup("`literal`");+ editor.commands.setTextSelection(4);+ expect(editor.isActive("code")).toBe(true);+ const event = clipboard("**bold**");+ expect(pasteMarkdown(editor, event)).toBe(false);+ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(editor.getHTML()).toBe("<p><code>literal</code></p>");+ });+ it.each(["line \nbreak", "line\\\nbreak"])(+ "preserves explicit hard breaks in %s",+ (markdown) => {+ setup();+ expect(pasteMarkdown(editor, clipboard(markdown))).toBe(true);+ expect(editor.getHTML()).toBe("<p>line<br>break</p>");+ },+ );+ it("does not unescape deliberately literal Markdown on load", () => {+ setup("\\*\\*literal\\*\\*");+ expect(editor.getHTML()).not.toContain("<strong>");+ expect(editor.getMarkdown()).toContain("\\*");+ });+});diff --git a/apps/web/src/lib/paste-markdown.ts b/apps/web/src/lib/paste-markdown.tsnew file mode 100644index 000000000..eba84eb25--- /dev/null+++ b/apps/web/src/lib/paste-markdown.ts@@ -0,0 +1,45 @@+import type { Editor } from "@tiptap/core";++export function pasteMarkdown(editor: Editor, event: ClipboardEvent): boolean {+ const clipboard = event.clipboardData;+ // Rich clipboard content and code retain their native paste behavior.+ if (+ !editor.isEditable ||+ !clipboard ||+ clipboard.getData("text/html") ||+ editor.isActive("codeBlock") ||+ editor.isActive("code")+ ) {+ return false;+ }+ const text = clipboard.getData("text/plain");+ if (!text || !editor.markdown) return false;+ // Leave single URLs to the issue-link and video-embed paste handlers.+ if (/^https?:\/\/\S+$/i.test(text.trim())) return false;+ const document = editor.markdown.parse(text);+ const soleParagraph =+ document.content?.length === 1 && document.content[0].type === "paragraph"+ ? document.content[0]+ : undefined;+ const soleInline =+ soleParagraph?.content?.length === 1 ? soleParagraph.content[0] : undefined;+ // GFM autolinks such as www.youtube.com must reach specialized URL handlers.+ if (+ soleInline?.text === text.trim() &&+ soleInline.marks?.some((mark) => mark.type === "link")+ )+ return false;+ const hasFormatting = (nodes: typeof document.content): boolean =>+ (nodes ?? []).some(+ (node) =>+ (node.type !== "paragraph" && node.type !== "text") ||+ Boolean(node.marks?.length) ||+ hasFormatting(node.content),+ );+ if (!hasFormatting(document.content)) return false;+ event.preventDefault();+ editor.commands.insertContent(+ soleParagraph?.content ?? document.content ?? [],+ );+ return true;+}