Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(editor): dedupe upload-node scan and markdown normalization (#4267)
Hzzzzzxe9e97ee6d2f1
diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsxindex 210d73ac3e..ae38388ee5 100644--- a/packages/views/editor/content-editor.test.tsx+++ b/packages/views/editor/content-editor.test.tsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { act, fireEvent, render, screen } from "@testing-library/react";+import { createRef } from "react";import type { Attachment } from "@multica/core/types";import type { UploadResult } from "@multica/core/hooks/use-file-upload";@@ -111,7 +112,7 @@ vi.mock("@tiptap/react", () => ({),}));-import { ContentEditor } from "./content-editor";+import { ContentEditor, type ContentEditorRef } from "./content-editor";describe("ContentEditor", () => {beforeEach(() => {@@ -253,6 +254,22 @@ describe("ContentEditor", () => {expect(mockSetContent).not.toHaveBeenCalled();});+ it("refactor safety net: imperative getMarkdown() stays untrimmed, keeping its exact current return value", () => {+ // The imperative `getMarkdown()` is deliberately NOT routed through+ // `normalizeMarkdown` (which would `trimEnd()`). This pins down that the+ // F2a/F3 dedupe refactor preserved the method's exact return value —+ // trailing blank lines included — instead of folding it into the trimming+ // helper. `stripBlobUrls` (unmocked here) only strips blob image markdown,+ // so the trailing newlines survive untouched.+ editorState.markdown = "kept body\n\n";++ const ref = createRef<ContentEditorRef>();+ render(<ContentEditor ref={ref} />);++ expect(ref.current).not.toBeNull();+ expect(ref.current?.getMarkdown()).toBe("kept body\n\n");+ });+it("flushes a pending debounced update on unmount when flushPendingOnUnmount is set", () => {vi.useFakeTimers();const onUpdate = vi.fn();diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex c709991f42..7d584843cb 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -39,7 +39,7 @@ import {useState,type MouseEvent as ReactMouseEvent,} from "react";-import { useEditor, EditorContent } from "@tiptap/react";+import { useEditor, EditorContent, type Editor } from "@tiptap/react";import { cn } from "@multica/ui/lib/utils";import type { UploadResult } from "@multica/core/hooks/use-file-upload";import { useWorkspaceSlug } from "@multica/core/paths";@@ -73,6 +73,33 @@ function stripBlobUrls(md: string): string {return md.replace(BLOB_IMAGE_RE, "");}+/** Canonical comparison form for a markdown string: drop process-local blob+ * URLs and trailing blank lines so both sides of a dirty check compare+ * like-for-like. One definition for the normalization rule — a future tweak+ * (e.g. stripping another ephemeral token) lands here instead of in the+ * several call sites it used to be copy-pasted across. */+function normalizeMarkdown(md: string): string {+ return stripBlobUrls(md).trimEnd();+}++/** `normalizeMarkdown` applied to the live editor's serialized content. */+function normalizeEditorMarkdown(editor: Editor): string {+ return normalizeMarkdown(editor.getMarkdown());+}++/** True when any node in the document is mid-upload (`attrs.uploading`). The+ * `return !found` early-out matches the original inline scans verbatim: in+ * ProseMirror it only stops descending into the matched node's subtree (not+ * the whole walk), but once `found` flips true the boolean result is fixed. */+function hasUploadingNode(editor: Editor): boolean {+ let found = false;+ editor.state.doc.descendants((node) => {+ if (node.attrs.uploading) found = true;+ return !found;+ });+ return found;+}+// ---------------------------------------------------------------------------// Types// ---------------------------------------------------------------------------@@ -299,7 +326,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(});}}- lastEmittedRef.current = stripBlobUrls(ed.getMarkdown()).trimEnd();+ lastEmittedRef.current = normalizeEditorMarkdown(ed);},content: mountChunked ? "" : initialContent,contentType: mountChunked@@ -322,13 +349,13 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(onUpdate: ({ editor: ed }) => {if (!onUpdateRef.current) return;if (flushPendingOnUnmountRef.current) {- pendingFlushRef.current = stripBlobUrls(ed.getMarkdown()).trimEnd();+ pendingFlushRef.current = normalizeEditorMarkdown(ed);}if (debounceRef.current) clearTimeout(debounceRef.current);debounceRef.current = setTimeout(() => {debounceRef.current = undefined;pendingFlushRef.current = null;- const md = stripBlobUrls(ed.getMarkdown()).trimEnd();+ const md = normalizeEditorMarkdown(ed);if (md === lastEmittedRef.current) return;lastEmittedRef.current = md;onUpdateRef.current?.(md);@@ -392,14 +419,9 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(// finalize can no longer find it (the file vanishes, leaving an empty// `!file[name]()`). Like the dirty guards below, an uploading node is// local state that an external sync must not overwrite.- let hasUploadingNode = false;- editor.state.doc.descendants((node) => {- if (node.attrs.uploading) hasUploadingNode = true;- return !hasUploadingNode;- });- if (hasUploadingNode) return;+ if (hasUploadingNode(editor)) return;- const current = stripBlobUrls(editor.getMarkdown()).trimEnd();+ const current = normalizeEditorMarkdown(editor);// "Dirty" = user has local edits not yet flushed through the debounced// `onUpdate`. `lastEmittedRef` is advanced only after a debounce fire,// so a divergence means the editor holds unsaved bytes.@@ -420,7 +442,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(if (isDirty) return;const incoming = defaultValue ? preprocessMarkdown(defaultValue) : "";- const incomingNormalized = stripBlobUrls(incoming).trimEnd();+ const incomingNormalized = normalizeMarkdown(incoming);// Guard 3: normalized-equal short-circuit. Avoids a no-op transaction// when the cache reflects a write this same editor just emitted.if (incomingNormalized === current) return;@@ -454,10 +476,12 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(to: Math.min(to, docSize),});- lastEmittedRef.current = stripBlobUrls(editor.getMarkdown()).trimEnd();+ lastEmittedRef.current = normalizeEditorMarkdown(editor);}, [defaultValue, editor]);useImperativeHandle(ref, () => ({+ // Intentionally NOT routed through `normalizeMarkdown` — this refactor+ // must preserve the exact current return value (no `trimEnd`).getMarkdown: () => stripBlobUrls(editor?.getMarkdown() ?? ""),clearContent: () => {editor?.commands.clearContent();@@ -473,15 +497,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(const endPos = editor.state.doc.content.size;uploadAndInsertFile(editor, file, onUploadFileRef.current, endPos);},- hasActiveUploads: () => {- if (!editor) return false;- let uploading = false;- editor.state.doc.descendants((node) => {- if (node.attrs.uploading) uploading = true;- return !uploading;- });- return uploading;- },+ hasActiveUploads: () => (editor ? hasUploadingNode(editor) : false),}));// Link hover card — disabled when BubbleMenu is active (has selection)