Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(editor): preserve rich table cells across Markdown edits

tianma-ifce674b8caf42
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index cfc22d49..13e6caa1 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -59,6 +59,12 @@ import { EditorToolbar } from "./EditorToolbar";
import { EditorOutline } from "./EditorOutline";
import { EditorTagPicker } from "./EditorTagPicker";
import { useAiBubbleMenu } from "./editor/useAiBubbleMenu";
+import {
+ createMarkdownModeSnapshot,
+ isMarkdownSourceUnchanged,
+ resolveMarkdownModeContent,
+ type MarkdownModeSnapshot,
+} from "./editor/editor-mode-content";
import {
ImageUploadPlaceholderExtension,
addImageUploadPlaceholder,
@@ -724,6 +730,7 @@ const RichEditorPane = ({
const fileInputRef = useRef<HTMLInputElement | null>(null);
const noteSearchInputRef = useRef<HTMLInputElement | null>(null);
const markdownSourceEditorRef = useRef<MarkdownSourceEditorRef | null>(null);
+ const markdownModeSnapshotRef = useRef<MarkdownModeSnapshot | null>(null);
const openExternalLinkDialogRef = useRef<() => void>(() => undefined);
const slashCommandLabelsRef = useRef<SlashCommandLabels>({
menu: "",
@@ -1811,7 +1818,11 @@ const RichEditorPane = ({
contentJson: useMobilePlainTextEditor
? markdownToDoc(nextMobilePlainText)
: useMarkdownSourceEditor
- ? markdownToDoc(markdownSource)
+ ? resolveMarkdownModeContent(
+ markdownModeSnapshotRef.current,
+ currentMemo.id,
+ markdownSource,
+ )
: (currentEditor?.getJSON() as TiptapDoc),
updatedAt: new Date().toISOString(),
});
@@ -2036,7 +2047,11 @@ const RichEditorPane = ({
}
if (useMarkdownSourceEditor) {
- return markdownToDoc(markdownSource);
+ return resolveMarkdownModeContent(
+ markdownModeSnapshotRef.current,
+ memoRef.current?.id,
+ markdownSource,
+ );
}
const currentEditor = editorRef.current;
@@ -2100,6 +2115,7 @@ const RichEditorPane = ({
editSessionRef.current = null;
hydratedMemoIdRef.current = null;
appliedEditorSourceKeyRef.current = null;
+ markdownModeSnapshotRef.current = null;
setHydratedEditorMemoId(null);
editingMemoIdRef.current = null;
setHasUnsavedChanges(false);
@@ -2123,6 +2139,7 @@ const RichEditorPane = ({
if (!sameMemo) {
hydratedMemoIdRef.current = null;
appliedEditorSourceKeyRef.current = null;
+ markdownModeSnapshotRef.current = null;
setHydratedEditorMemoId(null);
}
@@ -2280,6 +2297,9 @@ const RichEditorPane = ({
setTagsText(nextTagsText);
setMobilePlainText(nextMarkdown);
setMarkdownSource(nextMarkdown);
+ markdownModeSnapshotRef.current = isMarkdownMode
+ ? createMarkdownModeSnapshot(memo.id, nextContent, nextMarkdown)
+ : null;
setMobilePlainTextElementValue(mobileTextAreaRef.current, nextMarkdown);
if (isEditorReady(currentEditor) && shouldReplaceDocument) {
@@ -2459,6 +2479,25 @@ const RichEditorPane = ({
};
}, []);
+ const applyMarkdownSourceToRichText = useCallback((scrollProgress: number) => {
+ if (!isEditorReady(editor)) {
+ return;
+ }
+
+ hydratingRef.current = true;
+ editor.commands.setContent(resolveMarkdownModeContent(
+ markdownModeSnapshotRef.current,
+ memoRef.current?.id,
+ markdownSource,
+ ));
+ markdownModeSnapshotRef.current = null;
+ setIsMarkdownMode(false);
+ restoreScrollAfterModeChange("rich", scrollProgress);
+ window.setTimeout(() => {
+ hydratingRef.current = false;
+ }, 0);
+ }, [editor, markdownSource, restoreScrollAfterModeChange]);
+
const handleMarkdownModeChange = useCallback(() => {
if (effectiveReadOnly || !isEditorReady(editor)) {
return;
@@ -2469,20 +2508,23 @@ const RichEditorPane = ({
);
if (isMarkdownMode) {
- hydratingRef.current = true;
- editor.commands.setContent(markdownToDoc(markdownSource));
- setIsMarkdownMode(false);
- restoreScrollAfterModeChange("rich", scrollProgress);
- window.setTimeout(() => {
- hydratingRef.current = false;
- }, 0);
+ applyMarkdownSourceToRichText(scrollProgress);
return;
}
- setMarkdownSource(docToMarkdown(editor.getJSON() as TiptapDoc));
+ const currentMemoId = memoRef.current?.id;
+ if (!currentMemoId) {
+ return;
+ }
+ const snapshot = createMarkdownModeSnapshot(
+ currentMemoId,
+ editor.getJSON() as TiptapDoc,
+ );
+ markdownModeSnapshotRef.current = snapshot;
+ setMarkdownSource(snapshot.markdownSource);
setIsMarkdownMode(true);
restoreScrollAfterModeChange("markdown", scrollProgress);
- }, [editor, effectiveReadOnly, isMarkdownMode, markdownSource, restoreScrollAfterModeChange]);
+ }, [applyMarkdownSourceToRichText, editor, effectiveReadOnly, isMarkdownMode, markdownSource, restoreScrollAfterModeChange]);
const handleMarkdownSourceChange = useCallback((value: string) => {
setMarkdownSource(value);
@@ -3412,6 +3454,9 @@ const RichEditorPane = ({
setTagsText(nextTagsText);
setMobilePlainText(nextMarkdown);
setMarkdownSource(nextMarkdown);
+ markdownModeSnapshotRef.current = isMarkdownMode
+ ? createMarkdownModeSnapshot(remoteMemo.id, nextContent, nextMarkdown)
+ : null;
setMobilePlainTextElementValue(mobileTextAreaRef.current, nextMarkdown);
const currentEditor = editorRef.current;
@@ -3446,7 +3491,7 @@ const RichEditorPane = ({
} finally {
setConflictActionPending(null);
}
- }, [conflictActionPending, onSaved, queryClient, repository, t]);
+ }, [conflictActionPending, isMarkdownMode, onSaved, queryClient, repository, t]);
if (isSelectionMode) {
return (
diff --git a/apps/web/src/components/editor/editor-mode-content.test.mjs b/apps/web/src/components/editor/editor-mode-content.test.mjs
new file mode 100644
index 00000000..9ce86103
--- /dev/null
+++ b/apps/web/src/components/editor/editor-mode-content.test.mjs
@@ -0,0 +1,83 @@
+import { describe, expect, test } from "bun:test";
+import { docToMarkdown } from "@edgeever/shared";
+import {
+ createMarkdownModeSnapshot,
+ isMarkdownSourceUnchanged,
+ resolveMarkdownModeContent,
+} from "./editor-mode-content.ts";
+
+const tableTaskListDocument = {
+ type: "doc",
+ content: [{
+ type: "table",
+ content: [
+ {
+ type: "tableRow",
+ content: [{
+ type: "tableHeader",
+ content: [{ type: "paragraph", content: [{ type: "text", text: "事项" }] }],
+ }],
+ },
+ {
+ type: "tableRow",
+ content: [{
+ type: "tableCell",
+ content: [{
+ type: "taskList",
+ content: [{
+ type: "taskItem",
+ attrs: { checked: false },
+ content: [{ type: "paragraph", content: [{ type: "text", text: "待办" }] }],
+ }],
+ }],
+ }],
+ },
+ ],
+ }],
+};
+
+describe("Markdown editor mode content preservation", () => {
+ test("preserves rich-only table task lists when source was only viewed", () => {
+ const snapshot = createMarkdownModeSnapshot("memo-1", tableTaskListDocument);
+ const restored = resolveMarkdownModeContent(snapshot, "memo-1", snapshot.markdownSource);
+
+ expect(isMarkdownSourceUnchanged(snapshot, "memo-1", snapshot.markdownSource)).toBe(true);
+ expect(restored).toEqual(tableTaskListDocument);
+ expect(restored.content[0].content[1].content[0].content[0].type).toBe("taskList");
+ });
+
+ test("treats equivalent line endings as an unchanged source projection", () => {
+ const snapshot = createMarkdownModeSnapshot("memo-1", tableTaskListDocument);
+ const windowsSource = snapshot.markdownSource.replaceAll("\n", "\r\n");
+
+ expect(isMarkdownSourceUnchanged(snapshot, "memo-1", windowsSource)).toBe(true);
+ expect(resolveMarkdownModeContent(snapshot, "memo-1", windowsSource)).toEqual(tableTaskListDocument);
+ });
+
+ test("preserves a rich table cell when content outside the table changes", () => {
+ const snapshot = createMarkdownModeSnapshot("memo-1", tableTaskListDocument);
+ const changedSource = `${snapshot.markdownSource}\n\n新增段落`;
+ const resolved = resolveMarkdownModeContent(snapshot, "memo-1", changedSource);
+
+ expect(isMarkdownSourceUnchanged(snapshot, "memo-1", changedSource)).toBe(false);
+ expect(resolved.content[0].content[1].content[0].content[0].type).toBe("taskList");
+ expect(docToMarkdown(resolved)).toContain("新增段落");
+ });
+
+ test("parses a rich table cell only when that cell was actually edited", () => {
+ const snapshot = createMarkdownModeSnapshot("memo-1", tableTaskListDocument);
+ const changedSource = snapshot.markdownSource.replace("待办", "待办 updated");
+ const resolved = resolveMarkdownModeContent(snapshot, "memo-1", changedSource);
+
+ expect(docToMarkdown(resolved)).toContain("updated");
+ expect(resolved.content[0].content[1].content[0].content[0].type).toBe("paragraph");
+ });
+
+ test("never reuses a snapshot belonging to another memo", () => {
+ const snapshot = createMarkdownModeSnapshot("memo-1", tableTaskListDocument);
+ const resolved = resolveMarkdownModeContent(snapshot, "memo-2", snapshot.markdownSource);
+
+ expect(isMarkdownSourceUnchanged(snapshot, "memo-2", snapshot.markdownSource)).toBe(false);
+ expect(resolved).not.toEqual(tableTaskListDocument);
+ });
+});
diff --git a/apps/web/src/components/editor/editor-mode-content.ts b/apps/web/src/components/editor/editor-mode-content.ts
new file mode 100644
index 00000000..f0a0776a
--- /dev/null
+++ b/apps/web/src/components/editor/editor-mode-content.ts
@@ -0,0 +1,158 @@
+import {
+ docToMarkdown,
+ markdownToDoc,
+ type TiptapDoc,
+} from "@edgeever/shared";
+
+export type MarkdownModeSnapshot = {
+ memoId: string;
+ contentJson: TiptapDoc;
+ markdownSource: string;
+};
+
+const normalizeMarkdownSource = (value: string) => value.replace(/\r\n?/g, "\n");
+
+const cloneContentJson = (contentJson: TiptapDoc): TiptapDoc =>
+ JSON.parse(JSON.stringify(contentJson)) as TiptapDoc;
+
+type ContentNode = {
+ type?: string;
+ content?: ContentNode[];
+ [key: string]: unknown;
+};
+
+const isTableCell = (node: ContentNode) =>
+ node.type === "tableCell" || node.type === "tableHeader";
+
+const hasBlockContent = (node: ContentNode) => isTableCell(node) && (
+ !Array.isArray(node.content)
+ || node.content.length !== 1
+ || node.content[0]?.type !== "paragraph"
+);
+
+const collectTables = (value: unknown): ContentNode[] => {
+ const tables: ContentNode[] = [];
+ const visit = (node: unknown) => {
+ if (!node || typeof node !== "object") return;
+ const contentNode = node as ContentNode;
+ if (contentNode.type === "table") {
+ tables.push(contentNode);
+ return;
+ }
+ contentNode.content?.forEach(visit);
+ };
+ visit(value);
+ return tables;
+};
+
+const collectCells = (table: ContentNode): ContentNode[] => {
+ const cells: ContentNode[] = [];
+ const visit = (node: ContentNode) => {
+ if (isTableCell(node)) {
+ cells.push(node);
+ return;
+ }
+ node.content?.forEach(visit);
+ };
+ visit(table);
+ return cells;
+};
+
+const nodesEqual = (left: ContentNode, right: ContentNode) =>
+ JSON.stringify(left) === JSON.stringify(right);
+
+/**
+ * Markdown flattens block nodes inside GFM table cells. Rehydrate an original
+ * rich cell only when its Markdown projection is still byte-for-byte
+ * equivalent to the parsed edited cell. Edits elsewhere in the source can
+ * therefore round-trip without damaging the untouched cell.
+ */
+const restoreUnchangedRichTableCells = (
+ original: TiptapDoc,
+ originalProjection: TiptapDoc,
+ editedProjection: TiptapDoc,
+): TiptapDoc => {
+ const restored = cloneContentJson(editedProjection);
+ const originalTables = collectTables(original);
+ const projectedTables = collectTables(originalProjection);
+ const editedTables = collectTables(restored);
+
+ originalTables.forEach((originalTable, tableIndex) => {
+ const projectedTable = projectedTables[tableIndex];
+ const editedTable = editedTables[tableIndex];
+ if (!projectedTable || !editedTable) return;
+
+ const originalCells = collectCells(originalTable);
+ const projectedCells = collectCells(projectedTable);
+ const editedCells = collectCells(editedTable);
+ if (
+ originalCells.length !== projectedCells.length
+ || projectedCells.length !== editedCells.length
+ ) return;
+
+ originalCells.forEach((originalCell, cellIndex) => {
+ if (
+ hasBlockContent(originalCell)
+ && nodesEqual(projectedCells[cellIndex]!, editedCells[cellIndex]!)
+ ) {
+ Object.keys(editedCells[cellIndex]!).forEach((key) => {
+ delete editedCells[cellIndex]![key];
+ });
+ Object.assign(
+ editedCells[cellIndex]!,
+ JSON.parse(JSON.stringify(originalCell)) as ContentNode,
+ );
+ }
+ });
+ });
+
+ return restored;
+};
+
+/**
+ * Captures the lossless rich document before exposing its Markdown projection.
+ * Markdown cannot represent every valid TipTap tree, so the JSON snapshot must
+ * remain authoritative until the user actually changes the source.
+ */
+export const createMarkdownModeSnapshot = (
+ memoId: string,
+ contentJson: TiptapDoc,
+ markdownSource = docToMarkdown(contentJson),
+): MarkdownModeSnapshot => ({
+ memoId,
+ contentJson: cloneContentJson(contentJson),
+ markdownSource,
+});
+
+export const isMarkdownSourceUnchanged = (
+ snapshot: MarkdownModeSnapshot | null,
+ memoId: string | null | undefined,
+ markdownSource: string,
+) => Boolean(
+ snapshot
+ && memoId
+ && snapshot.memoId === memoId
+ && normalizeMarkdownSource(snapshot.markdownSource) === normalizeMarkdownSource(markdownSource)
+);
+
+/** Resolve the document used by mode switching, drafts, autosave, and recovery. */
+export const resolveMarkdownModeContent = (
+ snapshot: MarkdownModeSnapshot | null,
+ memoId: string | null | undefined,
+ markdownSource: string,
+): TiptapDoc => {
+ if (isMarkdownSourceUnchanged(snapshot, memoId, markdownSource)) {
+ return snapshot!.contentJson;
+ }
+
+ const editedProjection = markdownToDoc(markdownSource);
+ if (!snapshot || !memoId || snapshot.memoId !== memoId) {
+ return editedProjection;
+ }
+
+ return restoreUnchangedRichTableCells(
+ snapshot.contentJson,
+ markdownToDoc(snapshot.markdownSource),
+ editedProjection,
+ );
+};