AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(web): preserve Markdown source and caret across editor modes
tianma-iffbcb1367bf76
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex ef92563a..aa3fc15e 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -1346,6 +1346,7 @@ const RichEditorPane = ({const {clearMarkdownSnapshot,handleMarkdownModeChange,+ handleMarkdownSourceReady,hydrateMarkdownSource,isMarkdownMode,markdownModeSnapshotRef,@@ -4218,6 +4219,7 @@ const RichEditorPane = ({}}onLinkShortcut={openExternalLinkDialog}onSelectionChange={syncMarkdownAiMenu}+ onReady={handleMarkdownSourceReady}className="absolute inset-0 h-full w-full"/></Suspense>diff --git a/apps/web/src/components/editor/MarkdownSourceEditor.tsx b/apps/web/src/components/editor/MarkdownSourceEditor.tsxindex b4efb1b1..f970fed6 100644--- a/apps/web/src/components/editor/MarkdownSourceEditor.tsx+++ b/apps/web/src/components/editor/MarkdownSourceEditor.tsx@@ -1,4 +1,4 @@-import { forwardRef, useCallback, useImperativeHandle, useMemo, useRef, type ClipboardEvent as ReactClipboardEvent } from "react";+import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, type ClipboardEvent as ReactClipboardEvent } from "react";import CodeMirror, {EditorView,type ReactCodeMirrorRef,@@ -55,6 +55,7 @@ export interface MarkdownSourceEditorProps {onSlashCommandTrigger?: (commandStart: number) => void;onLinkShortcut?: () => void;onSelectionChange?: () => void;+ onReady?: () => void;}export const CODE_MIRROR_THEME_MAP: Record<MarkdownThemeName, Extension> = {@@ -126,6 +127,7 @@ export const MarkdownSourceEditor = forwardRef<MarkdownSourceEditorRef, MarkdownonSlashCommandTrigger,onLinkShortcut,onSelectionChange,+ onReady,},ref,) => {@@ -136,6 +138,22 @@ export const MarkdownSourceEditor = forwardRef<MarkdownSourceEditorRef, Markdownconst onSelectionChangeRef = useRef(onSelectionChange);onSelectionChangeRef.current = onSelectionChange;+ useEffect(() => {+ let frame = 0;+ let cancelled = false;+ let attempts = 0;+ const notifyWhenReady = () => {+ if (cancelled) return;+ if (cmRef.current?.view) onReady?.();+ else if (attempts++ < 120) frame = window.requestAnimationFrame(notifyWhenReady);+ };+ notifyWhenReady();+ return () => {+ cancelled = true;+ window.cancelAnimationFrame(frame);+ };+ }, [onReady]);+useImperativeHandle(ref,() => ({diff --git a/apps/web/src/components/editor/editor-mode-content.test.mjs b/apps/web/src/components/editor/editor-mode-content.test.mjsindex bbe16cc1..b84dccd9 100644--- a/apps/web/src/components/editor/editor-mode-content.test.mjs+++ b/apps/web/src/components/editor/editor-mode-content.test.mjs@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";import { docToMarkdown, markdownToDoc } from "@edgeever/shared";import {createMarkdownModeSnapshot,+ docToEditableMarkdown,isMarkdownSourceUnchanged,resolveMarkdownModeContent,selectMarkdownSourceForDocument,@@ -39,6 +40,36 @@ const tableTaskListDocument = {};describe("Markdown editor mode content preservation", () => {+ test("shows literal brackets and ampersands when they remain plain text", () => {+ const content = markdownToDoc("Alpha [ ] & Bravo");++ expect(docToMarkdown(content)).toBe("Alpha \\[ \\] & Bravo");+ expect(docToEditableMarkdown(content)).toBe("Alpha [ ] & Bravo");+ expect(markdownToDoc(docToEditableMarkdown(content))).toEqual(content);+ });++ test("keeps escapes when removing them would create a link or change literal entities", () => {+ const content = markdownToDoc("Literal \\[link\\](https://example.com) and &amp;");+ const canonical = docToMarkdown(content);++ expect(docToEditableMarkdown(content)).toBe(canonical);+ });++ test("retains the stored source of an older note until its rich content changes", () => {+ const storedSource = "Alpha \\[ \\] & Bravo";+ const content = markdownToDoc(storedSource);+ const snapshot = createMarkdownModeSnapshot("memo-1", content, storedSource);+ const changedContent = markdownToDoc("Alpha [ ] & Bravo updated");++ expect(selectMarkdownSourceForDocument(snapshot, "memo-1", content, docToEditableMarkdown(content))).toBe(storedSource);+ expect(selectMarkdownSourceForDocument(+ snapshot,+ "memo-1",+ changedContent,+ docToEditableMarkdown(changedContent),+ )).toBe("Alpha [ ] & Bravo updated");+ });+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);diff --git a/apps/web/src/components/editor/editor-mode-content.ts b/apps/web/src/components/editor/editor-mode-content.tsindex 9dafd2f6..c1dfd44d 100644--- a/apps/web/src/components/editor/editor-mode-content.ts+++ b/apps/web/src/components/editor/editor-mode-content.ts@@ -12,6 +12,20 @@ export type MarkdownModeSnapshot = {const normalizeMarkdownSource = (value: string) => value.replace(/\r\n?/g, "\n");+/** Keep harmless punctuation readable in the source editor without changing the shared export codec. */+export const docToEditableMarkdown = (contentJson: TiptapDoc): string => {+ const serialized = docToMarkdown(contentJson);+ const readable = serialized+ .replaceAll("\\[", "[")+ .replaceAll("\\]", "]")+ .replaceAll("&", "&");++ return readable !== serialized+ && JSON.stringify(markdownToDoc(readable)) === JSON.stringify(markdownToDoc(serialized))+ ? readable+ : serialized;+};+const cloneContentJson = (contentJson: TiptapDoc): TiptapDoc =>JSON.parse(JSON.stringify(contentJson)) as TiptapDoc;@@ -117,7 +131,7 @@ const restoreUnchangedRichTableCells = (export const createMarkdownModeSnapshot = (memoId: string,contentJson: TiptapDoc,- markdownSource = docToMarkdown(contentJson),+ markdownSource = docToEditableMarkdown(contentJson),): MarkdownModeSnapshot => ({memoId,contentJson: cloneContentJson(contentJson),diff --git a/apps/web/src/components/editor/editor-mode-selection.test.mjs b/apps/web/src/components/editor/editor-mode-selection.test.mjsnew file mode 100644index 00000000..652b9937--- /dev/null+++ b/apps/web/src/components/editor/editor-mode-selection.test.mjs@@ -0,0 +1,60 @@+import { describe, expect, test } from "bun:test";+import { Editor } from "@tiptap/core";+import { createEdgeEverDocumentExtensions, markdownToDoc } from "@edgeever/shared";+import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";+import { ensureTestWindowDom } from "../../lib/restore-test-global.mjs";+import { docToEditableMarkdown } from "./editor-mode-content.ts";+import { markdownOffsetToRichPosition, richPositionToMarkdownOffset } from "./editor-mode-selection.ts";++const createEditor = (source) => {+ ensureTestWindowDom();+ return new Editor({+ extensions: createEdgeEverDocumentExtensions({ mathematics: createEdgeEverMathematics() }),+ content: markdownToDoc(source),+ });+};++describe("Markdown mode cursor mapping", () => {+ test("keeps the caret after ordinary punctuation when entering source mode", () => {+ const editor = createEditor("Alpha [ ] & Bravo");+ const source = docToEditableMarkdown(editor.getJSON());+ const richPosition = 1 + "Alpha [ ] &".length;+ const sourceOffset = richPositionToMarkdownOffset(editor.state.doc, source, richPosition);++ expect(source).toBe("Alpha [ ] & Bravo");+ expect(sourceOffset).toBe("Alpha [ ] &".length);+ expect(markdownOffsetToRichPosition(editor.schema, editor.state.doc, source, sourceOffset)).toBe(richPosition);+ editor.destroy();+ });++ test("accounts for Markdown marks around a caret in formatted prose", () => {+ const editor = createEditor("Before **bold** after");+ const source = docToEditableMarkdown(editor.getJSON());+ const richPosition = 1 + "Before bold".length;+ const sourceOffset = richPositionToMarkdownOffset(editor.state.doc, source, richPosition);++ expect(sourceOffset).toBe(source.indexOf("** after"));+ expect(markdownOffsetToRichPosition(editor.schema, editor.state.doc, source, sourceOffset)).toBe(richPosition);+ editor.destroy();+ });++ test("keeps UTF-16 positions after Chinese text and emoji", () => {+ const editor = createEditor("繁體中文🙂 [ ] & 後文");+ const source = docToEditableMarkdown(editor.getJSON());+ const prefix = "繁體中文🙂 [ ] &";+ const richPosition = 1 + prefix.length;+ const sourceOffset = richPositionToMarkdownOffset(editor.state.doc, source, richPosition);++ expect(sourceOffset).toBe(prefix.length);+ expect(markdownOffsetToRichPosition(editor.schema, editor.state.doc, source, sourceOffset)).toBe(richPosition);+ editor.destroy();+ });++ test("declines unsafe positions inside Markdown syntax", () => {+ const editor = createEditor("[EdgeEver](https://edgeever.org)");+ const source = docToEditableMarkdown(editor.getJSON());++ expect(markdownOffsetToRichPosition(editor.schema, editor.state.doc, source, source.indexOf("https") + 2)).toBeNull();+ editor.destroy();+ });+});diff --git a/apps/web/src/components/editor/editor-mode-selection.ts b/apps/web/src/components/editor/editor-mode-selection.tsnew file mode 100644index 00000000..9b69c7aa--- /dev/null+++ b/apps/web/src/components/editor/editor-mode-selection.ts@@ -0,0 +1,54 @@+import type { Node as ProseMirrorNode, Schema } from "@tiptap/pm/model";+import { EditorState } from "@tiptap/pm/state";+import { markdownToDoc, type TiptapDoc } from "@edgeever/shared";+import { docToEditableMarkdown } from "./editor-mode-content";++const CURSOR_MARKER = "\uE000EDGEEVERCURSOR\uE001";++/** Map a rich-text position only if adding a temporary marker leaves the source unchanged. */+export const richPositionToMarkdownOffset = (+ doc: ProseMirrorNode,+ markdownSource: string,+ position: number,+): number | null => {+ if (position < 0 || position > doc.content.size || markdownSource.includes(CURSOR_MARKER)) return null;++ try {+ const markedDoc = EditorState.create({ doc }).tr.insertText(CURSOR_MARKER, position).doc;+ if (markedDoc.eq(doc)) return null;+ const markedSource = docToEditableMarkdown(markedDoc.toJSON() as TiptapDoc);+ const offset = markedSource.indexOf(CURSOR_MARKER);+ if (offset < 0 || markedSource.indexOf(CURSOR_MARKER, offset + 1) !== -1) return null;++ return markedSource.replace(CURSOR_MARKER, "") === markdownSource ? offset : null;+ } catch {+ return null;+ }+};++/** A source offset is safe when parsing around it recreates the same rich document. */+export const markdownOffsetToRichPosition = (+ schema: Schema,+ doc: ProseMirrorNode,+ markdownSource: string,+ offset: number,+): number | null => {+ if (offset < 0 || offset > markdownSource.length || markdownSource.includes(CURSOR_MARKER)) return null;++ try {+ const markedSource = `${markdownSource.slice(0, offset)}${CURSOR_MARKER}${markdownSource.slice(offset)}`;+ const markedDoc = schema.nodeFromJSON(markdownToDoc(markedSource));+ let position: number | null = null;+ markedDoc.descendants((node, start) => {+ if (!node.isText) return;+ const index = node.text?.indexOf(CURSOR_MARKER) ?? -1;+ if (index !== -1) position = start + index;+ });+ if (position === null) return null;++ const restored = EditorState.create({ doc: markedDoc }).tr.delete(position, position + CURSOR_MARKER.length).doc;+ return restored.eq(doc) ? position : null;+ } catch {+ return null;+ }+};diff --git a/apps/web/src/components/editor/useEditorMarkdownMode.ts b/apps/web/src/components/editor/useEditorMarkdownMode.tsindex 20bf0c53..c77cc093 100644--- a/apps/web/src/components/editor/useEditorMarkdownMode.ts+++ b/apps/web/src/components/editor/useEditorMarkdownMode.ts@@ -15,6 +15,7 @@ import {type MarkdownModeSnapshot,} from "./editor-mode-content";import { getEditorScrollProgress, restoreEditorScrollProgress } from "./editor-mode-scroll";+import { markdownOffsetToRichPosition, richPositionToMarkdownOffset } from "./editor-mode-selection";import type { MarkdownSourceEditorRef } from "./MarkdownSourceEditor";import { isEditorReady } from "./editor-pane-helpers";@@ -37,6 +38,20 @@ export const useEditorMarkdownMode = ({markdownSourceRef.current = markdownSource;const markdownSourceEditorRef = useRef<MarkdownSourceEditorRef | null>(null);const markdownModeSnapshotRef = useRef<MarkdownModeSnapshot | null>(null);+ const pendingSourceSelectionRef = useRef<{ memoId: string; from: number; to: number } | null>(null);+ const getMemoIdRef = useRef(getMemoId);+ getMemoIdRef.current = getMemoId;++ const handleMarkdownSourceReady = useCallback(() => {+ const sourceEditor = markdownSourceEditorRef.current;+ if (!sourceEditor) return;+ const pending = pendingSourceSelectionRef.current;+ pendingSourceSelectionRef.current = null;+ if (pending && pending.memoId === getMemoIdRef.current()) {+ sourceEditor.setSelection(pending.from, pending.to);+ }+ sourceEditor.focus();+ }, []);const restoreScrollAfterModeChange = useCallback((targetMode: "markdown" | "rich", progress: number) => {const restore = (attempt: number) => {@@ -65,13 +80,27 @@ export const useEditorMarkdownMode = ({currentMemoId,markdownSourceRef.current,);+ const sourceSelection = markdownSourceEditorRef.current?.getSelection();hydratingRef.current = true;editor.commands.setContent(content);+ const richFrom = sourceSelection+ ? markdownOffsetToRichPosition(editor.schema, editor.state.doc, markdownSourceRef.current, sourceSelection.from)+ : null;+ const richTo = sourceSelection?.to === sourceSelection?.from+ ? richFrom+ : sourceSelection+ ? markdownOffsetToRichPosition(editor.schema, editor.state.doc, markdownSourceRef.current, sourceSelection.to)+ : null;+ const hasMappedSelection = richFrom !== null && richTo !== null;+ if (hasMappedSelection) editor.commands.setTextSelection({ from: richFrom, to: richTo });markdownModeSnapshotRef.current = currentMemoId? createMarkdownModeSnapshot(currentMemoId, content, markdownSourceRef.current): null;setIsMarkdownMode(false);- restoreScrollAfterModeChange("rich", scrollProgress);+ if (!hasMappedSelection) restoreScrollAfterModeChange("rich", scrollProgress);+ window.requestAnimationFrame(() => {+ if (getMemoId() === currentMemoId && !markdownSourceEditorRef.current) editor.view.focus();+ });window.setTimeout(() => {hydratingRef.current = false;}, 0);@@ -103,6 +132,14 @@ export const useEditorMarkdownMode = ({contentJson,serialized.markdownSource,);+ const { from, to } = editor.state.selection;+ const sourceFrom = richPositionToMarkdownOffset(editor.state.doc, markdown, from);+ const sourceTo = to === from+ ? sourceFrom+ : richPositionToMarkdownOffset(editor.state.doc, markdown, to);+ pendingSourceSelectionRef.current = sourceFrom !== null && sourceTo !== null+ ? { memoId: currentMemoId, from: sourceFrom, to: sourceTo }+ : null;markdownModeSnapshotRef.current = createMarkdownModeSnapshot(currentMemoId,contentJson,@@ -110,7 +147,7 @@ export const useEditorMarkdownMode = ({);setMarkdownSource(markdown);setIsMarkdownMode(true);- restoreScrollAfterModeChange("markdown", scrollProgress);+ if (!pendingSourceSelectionRef.current) restoreScrollAfterModeChange("markdown", scrollProgress);}, [applyMarkdownSourceToRichText,editor,@@ -123,6 +160,7 @@ export const useEditorMarkdownMode = ({const resetMarkdownMode = useCallback(() => {markdownModeSnapshotRef.current = null;+ pendingSourceSelectionRef.current = null;setMarkdownSource("");setIsMarkdownMode(false);}, []);@@ -158,6 +196,7 @@ export const useEditorMarkdownMode = ({applyMarkdownSourceToRichText,clearMarkdownSnapshot,handleMarkdownModeChange,+ handleMarkdownSourceReady,hydrateMarkdownSource,isMarkdownMode,markdownModeSnapshotRef,diff --git a/docs/editor-lossless-acceptance.md b/docs/editor-lossless-acceptance.mdnew file mode 100644index 00000000..de41b6e2--- /dev/null+++ b/docs/editor-lossless-acceptance.md@@ -0,0 +1,48 @@+# Lossless acceptance criteria for rich text and Markdown views++Related to [Issue #469](https://github.com/tianma-if/edgeever/issues/469). These criteria apply to ordinary notes in the TipTap rich text view and CodeMirror Markdown source view on Web and desktop, including their shared save path. They describe observable results for users; they do not require both views to use the same editor component.++## Three levels of preservation++| Level | Assertion | When it applies |+|---|---|---|+| Exact source | The Markdown string is strictly equal, including blank lines, spaces, escapes, entities, and line endings | The user has not changed the source, or saves from source view and reopens without subsequently editing rich text |+| Rich structure | The persisted TipTap document structure and user-visible attributes are equal | View switching only, or source edits outside rich-only structures |+| Editing semantics | Text, formatting, link targets, list hierarchy and checked state, table data, attachments, and other supported nodes retain their meaning | The user edits rich text, so Markdown serialization may change its spelling |++These levels must not be combined into a claim of universally byte-for-byte lossless Markdown round trips. After a rich text edit, serialization may rewrite blank lines, list markers, or escapes. The guarantee then concerns the editing semantics of supported content, not exact source spelling. Markdown alone cannot prove that rich-only attributes survived.++## Required scenarios++| Scenario | Acceptance assertion |+|---|---|+| A. Switch views without editing | Rich text → Markdown → rich text → Markdown, without typing or pasting: the second source is character-for-character equal to the first; the rich document is unchanged; switching alone causes no content change, save, or new revision. An existing note retains its stored source rather than being reformatted merely by opening the view. |+| B. Edit in source view | After saving, reopening, and entering source view, the source is exactly what the user submitted. Switching to rich text and back without editing rich text retains that source. Supported content in rich text matches the parsed source. Autosave hydration must not replace a live buffer or move its caret. |+| C. Edit in rich text view | After saving and reopening, rich content and its user-visible attributes are preserved. Re-parsing generated Markdown retains the semantics of supported content. Markdown spelling may be normalized, but plain `[`, `]`, and `&` must not appear as unnecessary `\[`, `\]`, or `&`; escapes remain where removing them would change parsing. |+| D. Rich-only structures | Merely viewing source preserves rich-only structures and attributes exactly. Editing source elsewhere preserves unaffected rich-only structures. If an edit would degrade an affected structure, the UI must explain the specific loss before overwriting and allow cancellation. Silent structural loss fails acceptance. |+| E. Caret and focus | When switching within ordinary editable text, the caret or selection maps to the same visible content, focus enters the target editor, and the next keystroke does not land before or after an adjacent character. Within Markdown syntax or link destinations with no rich text edit position, a nearby safe position is acceptable; content must not change. |+| F. Conflicts and recovery | A–D continue to hold after autosave, offline draft recovery, and remote revision conflicts. A snapshot from another note must never be reused; conflict handling must not silently replace newer content with an older view. |++Silent deletion of body content, attachment references, or structures that Markdown cannot represent blocks acceptance in any test. “Equivalent Markdown syntax” does not excuse such deletion. If D cannot be met, preserve the original data and prevent a lossy overwrite until the user explicitly chooses to convert it.++## Fixtures and execution++Run A–C for every fixture, and D for fixtures with rich-only structures. Assert both rendered views and `contentJson` / `contentMarkdown` before and after persistence; screenshots or serialized strings alone are insufficient.++| Fixture | Required cases |+|---|---|+| Plain text | `Alpha [ ] & Bravo`, literal `&`, brackets that could form a link, backslashes, dollar signs, spaces and consecutive blank lines, CRLF, Chinese, and emoji |+| Markdown structures | Headings, emphasis, links and destinations, inline and fenced code, blockquotes, nested lists, task state, GFM tables, Mermaid, math, and `details` |+| EdgeEver content | Images and galleries, file and PDF attachments, plugin embeds, merge dividers, task lists or multiple paragraphs inside a rich table cell, and rich-only attributes |+| Input and switching | Chinese and English IME composition, paste, undo/redo, caret at punctuation and formatting boundaries, selections, rapid repeated switching, and long notes |++Automation must cover conversion and snapshot assertions, save and reopen, and actual browser typing and caret placement. Issue #469 was reported on Windows 10 / Chrome 154 / zh-TW; reproduce on that environment or an equivalent Windows Chrome environment with documented differences before closing it. Changes to the storage format, migrations, or cross-version reading also require a real old-version → new-version note test. Record pass / fail / unverified, platform, and version for each case. Do not report an unverified case as passing.++## Current implementation and gaps (2026-10-04)++- The save path stores both `contentJson` and `contentMarkdown`. Source-view saves submit the user's source; rich-view saves derive Markdown from JSON on the server. Thus C does not promise exact source after a rich text edit.+- Existing unit tests cover readable source for plain `[`, `]`, and `&`, necessary escapes, unchanged-source snapshots, an untouched complex table cell, and some caret mapping. A local browser check covered continued typing after ordinary punctuation.+- D is not fully met: directly changing a rich table cell containing a task list currently converts that cell to an ordinary paragraph without a conversion warning. Mark this case as failed until protection or a warning is implemented.+- A real Windows 10 / Chrome 154 check and save-and-reopen coverage for all fixtures have not been completed. No real cross-version test has been run; that test is a release gate if a storage or cross-version reading change is introduced. Do not claim Issue #469 meets the full lossless criteria on the current evidence.++Implementation references: [`editor-mode-content.ts`](../apps/web/src/components/editor/editor-mode-content.ts), [`useEditorMarkdownMode.ts`](../apps/web/src/components/editor/useEditorMarkdownMode.ts), [`content.ts`](../packages/shared/src/content.ts), and [`memo-service.ts`](../apps/api/src/memo-service.ts).diff --git a/docs/editor-lossless-acceptance.zh-CN.md b/docs/editor-lossless-acceptance.zh-CN.mdnew file mode 100644index 00000000..f549be49--- /dev/null+++ b/docs/editor-lossless-acceptance.zh-CN.md@@ -0,0 +1,48 @@+# 富文本与 Markdown 双视图的无损验收标准++关联 [Issue #469](https://github.com/tianma-if/edgeever/issues/469)。本标准适用于 Web 和桌面端普通笔记的 TipTap 富文本视图、CodeMirror Markdown 源码视图,以及两者共用的保存链路。它约束的是用户笔记的可观察结果,不要求两个视图使用同一个编辑器组件。++## “无损”的三个层次++| 层次 | 判定依据 | 适用情形 |+|---|---|---|+| 源码原样保留 | Markdown 字符串严格相等,包括空行、空格、转义、实体和换行符 | 源码未被用户改动,或用户从源码视图保存后重新打开且期间未修改富文本 |+| 富文本结构保留 | 持久化的 TipTap 文档结构及用户可见属性相等 | 仅切换视图,或修改源码中与富文本专有结构无关的部分 |+| 编辑语义保留 | 文本、格式、链接目标、列表层级和勾选状态、表格数据、附件及其他受支持节点的含义相等 | 用户确实修改了富文本,允许 Markdown 序列化改变写法 |++不能把这三个层次混称为“Markdown 往返完全无损”。富文本修改后,Markdown 的空行、列表标记、转义等写法可能被重新序列化;这种情况下保证的是受支持内容的编辑语义,不保证源码逐字不变。Markdown 无法表达的富文本属性,也不能仅凭序列化后的 Markdown 判定是否丢失。++## 必须通过的场景++| 场景 | 验收断言 |+|---|---|+| A. 只切换视图 | 富文本 → Markdown → 富文本 → Markdown,不输入、不粘贴:第二次看到的源码与第一次逐字相同;富文本文档与切换前相同;切换本身不产生内容修改、保存或新修订。已有笔记使用其保存的源码,不因进入视图就重新格式化。 |+| B. 在源码视图编辑 | 保存、重新打开、再次进入源码视图后,得到用户提交的源码原文。切到富文本再切回且未改富文本时,仍得到该原文。富文本中显示的受支持内容须与该源码的解析结果一致。自动保存回填不能覆盖仍在输入的源码或移动插入点。 |+| C. 在富文本视图编辑 | 保存、重新打开后,富文本内容及其用户可见属性保持一致;生成的 Markdown 再解析后,受支持的内容语义保持一致。允许 Markdown 写法规范化,但不能把普通 `[`、`]`、`&` 显示成无必要的 `\[`、`\]`、`&`;若去掉转义会改变解析结果,则必须保留转义。 |+| D. 富文本专有结构 | 仅查看源码时,富文本专有结构及属性必须原样保留。修改源码的其他位置时,未涉及的专有结构必须保留。若修改会迫使受影响结构降级,界面须在覆盖前明确说明会失去什么,并允许取消;未经告知的结构丢失为失败。 |+| E. 光标与焦点 | 在普通可编辑文本中切换,光标或选区应落在同一段可见内容的对应位置,焦点进入目标编辑器,下一次输入不得插到相邻字符之前或之后。对于 Markdown 标记、链接地址等富文本中没有对应编辑位置的区域,允许落到相邻的安全位置;不得修改内容。 |+| F. 冲突与恢复 | 自动保存、离线草稿恢复、远端修订冲突处理后,继续遵守 A–D。不同笔记的快照不得串用;冲突不得静默用旧视图覆盖新正文。 |++任何测试中正文、附件引用或不可由 Markdown 表达的结构发生静默删除,均为阻断问题,不能以“Markdown 语法等价”豁免。若能力边界无法满足 D,应保留原始数据并阻止有损覆盖,直到用户明确选择转换。++## 验收样本和执行方式++每类样本都执行 A–C;含专有结构的样本还执行 D。断言同时读取视图内容、保存前后的 `contentJson` 与 `contentMarkdown`,避免只凭截图或序列化字符串判断。++| 样本 | 必测内容 |+|---|---|+| 普通文字 | `Alpha [ ] & Bravo`、字面量 `&`、可形成链接的方括号、反斜杠、美元符号、空格与连续空行、CRLF、中文和 emoji |+| Markdown 结构 | 标题、强调、链接及地址、行内与围栏代码、引用、嵌套列表、待办状态、GFM 表格、Mermaid、公式、`details` |+| EdgeEver 内容 | 图片与图集、文件和 PDF 附件、插件嵌入、合并分隔符、富文本表格单元格中的待办列表或多段落、富文本专有属性 |+| 输入与切换 | 中英文输入法组合输入、粘贴、撤销/重做、光标在标点和格式边界、选区、快速反复切换、长笔记 |++自动化至少覆盖转换与快照断言、保存后重开,以及浏览器中的实际键入和光标位置。Issue #469 的复现环境为 Windows 10 / Chrome 154 / zh-TW;关闭该问题前应在该环境或可说明差异的等效 Windows Chrome 环境复验。若修改存储格式、迁移或跨版本读取机制,还必须用真实旧版本笔记完成旧版 → 新版验证。每项记录“通过 / 失败 / 未验证”、运行平台与版本;未验证不得写成通过。++## 当前实现与未完成项(2026-10-04)++- 当前保存链路同时存储 `contentJson` 和 `contentMarkdown`。源码视图保存时发送用户原文;富文本视图保存时服务端从 JSON 生成 Markdown。因此 C 不承诺富文本编辑后的源码逐字相同。+- 现有单元测试覆盖普通 `[`、`]`、`&` 的可读源码、危险转义保留、未编辑源码的快照恢复、未编辑的复杂表格单元格以及部分光标映射;本地浏览器验证了普通标点后的连续输入。+- D 尚未全面满足:直接改动含待办列表的富文本表格单元格时,当前解析会把该单元格降为普通段落,且尚无转换提示。此场景在补齐保护或提示前必须标记失败。+- Windows 10 / Chrome 154 的真实复验和全部样本的保存后重开尚未完成。真实旧版本跨版本验证也尚未完成;如引入存储或跨版本读取变更,须以此作为发布门禁。现有证据不足以宣称 Issue #469 已满足完整无损验收。++相关实现:[`editor-mode-content.ts`](../apps/web/src/components/editor/editor-mode-content.ts)、[`useEditorMarkdownMode.ts`](../apps/web/src/components/editor/useEditorMarkdownMode.ts)、[`content.ts`](../packages/shared/src/content.ts)、[`memo-service.ts`](../apps/api/src/memo-service.ts)。