From 04e08f94a830a0407bd293c53bfc798ca3a976dd Mon Sep 17 00:00:00 2001
From: mapxn <16299874+mapxn@users.noreply.github.com>
Date: Sun, 29 Nov 2026 22:40:22 +0800
Subject: [PATCH 1/3] chore: checkpoint vhQgz75-BRChiiAGW4tRo
---
web/src/editor/code-block-toggle.test.ts | 125 +++++++++++++++++
web/src/editor/extensions.ts | 147 ++++++++++++++++++-
web/src/editor/paste/paste-plugin.test.ts | 163 ++++++++++++++++++++++
web/src/editor/paste/paste-plugin.ts | 14 ++
4 files changed, 445 insertions(+), 4 deletions(-)
create mode 100644 web/src/editor/code-block-toggle.test.ts
create mode 100644 web/src/editor/paste/paste-plugin.test.ts
diff --git a/web/src/editor/code-block-toggle.test.ts b/web/src/editor/code-block-toggle.test.ts
new file mode 100644
index 0000000..74ba589
--- /dev/null
+++ b/web/src/editor/code-block-toggle.test.ts
@@ -0,0 +1,125 @@
+import { Editor } from "@tiptap/core"
+import { afterEach, beforeAll, describe, expect, it } from "vitest"
+import { createExtensions } from "@/editor/extensions"
+import { installTiptapJsdomShims } from "@/test/tiptap-jsdom"
+import { docJson } from "@/test/tiptap-json"
+
+/**
+ * 代码块合并/拆回(缺陷一):
+ * 跨块选区点代码块应合并为单个 codeBlock(各块纯文本 \n 连接、行内标记剥除),
+ * 再点一次按行拆回段落;单块选区保持原生开关行为。
+ */
+
+const editors: Editor[] = []
+
+function cleanupEditors() {
+ while (editors.length) {
+ const ed = editors.pop()
+ const el = ed?.options.element
+ if (el instanceof Element) el.remove()
+ ed?.destroy()
+ }
+}
+
+function makeEditor(content: string): Editor {
+ const host = document.createElement("div")
+ document.body.appendChild(host)
+ const editor = new Editor({
+ element: host,
+ extensions: createExtensions("edit"),
+ content
+ })
+ editors.push(editor)
+ return editor
+}
+
+function codeBlockNode(editor: Editor) {
+ return docJson(editor).content?.find((node) => node.type === "codeBlock")
+}
+
+function paragraphTexts(editor: Editor): string[] {
+ return (docJson(editor).content ?? [])
+ .filter((node) => node.type === "paragraph" && node.content?.length)
+ .map((node) =>
+ (node.content ?? [])
+ .map((child) => ("text" in child ? child.text : ""))
+ .join("")
+ )
+}
+
+describe("代码块合并与拆回", () => {
+ beforeAll(() => {
+ installTiptapJsdomShims()
+ })
+
+ afterEach(() => {
+ cleanupEditors()
+ })
+
+ it("选中 3 个段落点代码块:恰好 1 个 codeBlock、三行文本、行内标记剥除;再点一次拆回 3 段", () => {
+ const editor = makeEditor(
+ "
第一行
第二行
第三行
"
+ )
+ editor.commands.selectAll()
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const doc = docJson(editor)
+ const codeBlocks = (doc.content ?? []).filter(
+ (node) => node.type === "codeBlock"
+ )
+ expect(codeBlocks).toHaveLength(1)
+
+ const code = codeBlockNode(editor)
+ expect(code?.attrs).toMatchObject({ language: null, collapsed: null })
+ expect(code?.content).toHaveLength(1)
+ expect(code?.content?.[0]).toEqual({
+ type: "text",
+ text: "第一行\n第二行\n第三行"
+ })
+
+ // 再点一次拆回段落(忽略 TrailingNode 追加的空段落)
+ editor.chain().focus().toggleCodeBlock().run()
+ expect(codeBlockNode(editor)).toBeUndefined()
+ expect(paragraphTexts(editor)).toEqual(["第一行", "第二行", "第三行"])
+ })
+
+ it("含标题/列表项的混合选区:合并为 1 个代码块,每块一行", () => {
+ const editor = makeEditor(
+ "标题
"
+ )
+ // 选中标题 + 整个列表(不要 selectAll:它会把 TrailingNode 追加的空段落也选进来)
+ editor.commands.setTextSelection({
+ from: 0,
+ to: editor.state.doc.content.size
+ })
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const code = codeBlockNode(editor)
+ expect(code).toBeTruthy()
+ expect(code?.attrs).toMatchObject({ language: null, collapsed: null })
+ expect(code?.content?.[0]).toEqual({
+ type: "text",
+ text: "标题\n项目一\n项目二"
+ })
+ expect(
+ (docJson(editor).content ?? []).filter(
+ (node) => node.type === "codeBlock"
+ )
+ ).toHaveLength(1)
+
+ editor.chain().focus().toggleCodeBlock().run()
+ expect(paragraphTexts(editor)).toEqual(["标题", "项目一", "项目二"])
+ })
+
+ it("单段落选区保持原生开关:点一次成单行代码块,再点一次回段落", () => {
+ const editor = makeEditor("单段
")
+ editor.commands.selectAll()
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const code = codeBlockNode(editor)
+ expect(code?.content?.[0]).toEqual({ type: "text", text: "单段" })
+
+ editor.chain().focus().toggleCodeBlock().run()
+ expect(paragraphTexts(editor)).toEqual(["单段"])
+ })
+})
diff --git a/web/src/editor/extensions.ts b/web/src/editor/extensions.ts
index 757a79e..cfdcca9 100644
--- a/web/src/editor/extensions.ts
+++ b/web/src/editor/extensions.ts
@@ -1,12 +1,17 @@
+import { type CommandProps, isNodeActive, isNodeSelection } from "@tiptap/core"
import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight"
-import { isNodeSelection } from "@tiptap/core"
import Image from "@tiptap/extension-image"
import Placeholder from "@tiptap/extension-placeholder"
-import { Table, createTable } from "@tiptap/extension-table"
+import { createTable, Table } from "@tiptap/extension-table"
import TableRow from "@tiptap/extension-table-row"
import TaskItem from "@tiptap/extension-task-item"
import TaskList from "@tiptap/extension-task-list"
-import { TextSelection } from "@tiptap/pm/state"
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model"
+import {
+ type EditorState,
+ NodeSelection,
+ TextSelection
+} from "@tiptap/pm/state"
import { ReactNodeViewRenderer } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
import { insertBlockAfterNodeSelection } from "@/editor/block-insert"
@@ -20,8 +25,8 @@ import {
WikiTextStyle
} from "@/editor/colors/extensions"
import { WikiExcalidraw } from "@/editor/excalidraw/extension"
-import { WikiHtmlEmbed } from "@/editor/htmlEmbed/extension"
import { WikiFontSize } from "@/editor/font-size/extensions"
+import { WikiHtmlEmbed } from "@/editor/htmlEmbed/extension"
import { ImageBlock } from "@/editor/ImageBlock"
import { imageWidth } from "@/editor/image-attributes"
import { lowlight } from "@/editor/lowlight"
@@ -38,6 +43,106 @@ function stopForInteractive({ event }: { event: Event }): boolean {
return Boolean(target.closest("button, input, a, select, [data-code-header]"))
}
+/** 找到当前选区所在的代码块:NodeSelection 直接取,否则从选区锚点向上找。 */
+function codeBlockRangeAt(state: EditorState): {
+ node: ProseMirrorNode
+ from: number
+ to: number
+} | null {
+ const codeBlock = state.schema.nodes.codeBlock
+ if (!codeBlock) return null
+ const { selection } = state
+ if (selection instanceof NodeSelection && selection.node.type === codeBlock) {
+ return { node: selection.node, from: selection.from, to: selection.to }
+ }
+ const $from = selection.$from
+ for (let depth = $from.depth; depth > 0; depth -= 1) {
+ const node = $from.node(depth)
+ if (node.type === codeBlock) {
+ return { node, from: $from.before(depth), to: $from.after(depth) }
+ }
+ }
+ return null
+}
+
+/** 代码块 → 按行拆回段落(与「合并为单个代码块」互为逆操作)。 */
+function splitCodeBlockIntoParagraphs(
+ state: EditorState,
+ dispatch: CommandProps["dispatch"]
+): boolean {
+ const range = codeBlockRangeAt(state)
+ if (!range) return false
+ const paragraph = state.schema.nodes.paragraph
+ if (!paragraph) return false
+ if (dispatch) {
+ const paragraphs = range.node.textContent
+ .split("\n")
+ .map((line) =>
+ line.length
+ ? paragraph.create(null, state.schema.text(line))
+ : paragraph.create()
+ )
+ const tr = state.tr.replaceWith(range.from, range.to, paragraphs)
+ dispatch(
+ tr
+ .setSelection(TextSelection.near(tr.doc.resolve(range.from + 1)))
+ .scrollIntoView()
+ )
+ }
+ return true
+}
+
+/** 列表容器自身不成行:合并时下沉到每个列表项取一行。 */
+const LIST_CONTAINER_NAMES = new Set(["bulletList", "orderedList", "taskList"])
+
+/** 选区覆盖的逻辑块逐块取纯文本(每块一行):段落/标题/列表项/引用等。 */
+function blockLines(doc: ProseMirrorNode, from: number, to: number): string[] {
+ const lines: string[] = []
+ doc.nodesBetween(from, to, (node) => {
+ if (LIST_CONTAINER_NAMES.has(node.type.name)) {
+ return true
+ }
+ if (
+ node.isTextblock ||
+ node.type.name === "listItem" ||
+ node.type.name === "blockquote"
+ ) {
+ lines.push(node.textContent)
+ return false
+ }
+ return true
+ })
+ return lines
+}
+
+/**
+ * 跨块选区 → 合并为单个代码块:各块纯文本以 \n 连接(行内标记剥除),
+ * 语言取默认(无语言),折叠属性取默认 null。
+ */
+function mergeBlocksIntoCodeBlock(
+ state: EditorState,
+ dispatch: CommandProps["dispatch"],
+ from: number,
+ to: number
+): boolean {
+ const codeBlock = state.schema.nodes.codeBlock
+ if (!codeBlock) return false
+ const text = blockLines(state.doc, from, to).join("\n")
+ if (dispatch) {
+ const node = codeBlock.create(
+ { language: null, collapsed: null },
+ text ? state.schema.text(text) : null
+ )
+ const tr = state.tr.replaceWith(from, to, node)
+ dispatch(
+ tr
+ .setSelection(TextSelection.near(tr.doc.resolve(from + 1)))
+ .scrollIntoView()
+ )
+ }
+ return true
+}
+
/** 代码块:语言角标 + 复制按钮,编辑态与阅读态共用同一个 NodeView。 */
export const WikiCodeBlock = CodeBlockLowlight.extend({
addAttributes() {
@@ -71,6 +176,40 @@ export const WikiCodeBlock = CodeBlockLowlight.extend({
stopEvent: stopForInteractive
})
},
+ addCommands() {
+ const parent = this.parent?.() ?? {}
+ return {
+ ...parent,
+ toggleCodeBlock:
+ (attributes?: Record) =>
+ ({ state, dispatch, commands }) => {
+ const codeBlock = state.schema.nodes.codeBlock
+ if (!codeBlock) return false
+
+ // 已在代码块内:拆回段落(与合并互为逆操作)
+ if (isNodeActive(state, codeBlock, attributes)) {
+ return splitCodeBlockIntoParagraphs(state, dispatch)
+ }
+
+ // 选区跨块且落在顶层:合并为单个代码块
+ const { selection } = state
+ if (!selection.empty) {
+ const range = selection.$from.blockRange(selection.$to)
+ if (range && range.depth === 0) {
+ return mergeBlocksIntoCodeBlock(
+ state,
+ dispatch,
+ range.start,
+ range.end
+ )
+ }
+ }
+
+ // 单块选区或嵌套位置:保持原生开关行为(单段落 ↔ 代码块)
+ return commands.toggleNode(this.name, "paragraph", attributes)
+ }
+ }
+ },
addProseMirrorPlugins() {
return [
WikiLowlightPlugin({
diff --git a/web/src/editor/paste/paste-plugin.test.ts b/web/src/editor/paste/paste-plugin.test.ts
new file mode 100644
index 0000000..c56ed52
--- /dev/null
+++ b/web/src/editor/paste/paste-plugin.test.ts
@@ -0,0 +1,163 @@
+import { Editor } from "@tiptap/core"
+import { afterEach, beforeAll, describe, expect, it } from "vitest"
+import { createExtensions } from "@/editor/extensions"
+import { ConfluencePaste } from "@/editor/paste/paste-plugin"
+import { installTiptapJsdomShims } from "@/test/tiptap-jsdom"
+import { docJson } from "@/test/tiptap-json"
+
+/**
+ * 粘贴管线(缺陷二):
+ * 光标在代码块内时一律按纯文本插入,换行保留为块内换行、不溢出到块外;
+ * 非代码块位置的三路粘贴(图片/HTML/纯文本)维持现行行为。
+ */
+
+const editors: Editor[] = []
+
+function cleanupEditors() {
+ while (editors.length) {
+ const ed = editors.pop()
+ const el = ed?.options.element
+ if (el instanceof Element) el.remove()
+ ed?.destroy()
+ }
+}
+
+function makeEditor(content: string): Editor {
+ const host = document.createElement("div")
+ document.body.appendChild(host)
+ const editor = new Editor({
+ element: host,
+ extensions: [...createExtensions("edit"), ConfluencePaste],
+ content
+ })
+ editors.push(editor)
+ return editor
+}
+
+interface PasteInput {
+ text?: string
+ html?: string
+ files?: File[]
+}
+
+function pasteInto(editor: Editor, input: PasteInput) {
+ const event = new Event("paste", { bubbles: true, cancelable: true })
+ Object.defineProperty(event, "clipboardData", {
+ value: {
+ getData: (type: string) =>
+ type === "text/plain"
+ ? (input.text ?? "")
+ : type === "text/html"
+ ? (input.html ?? "")
+ : "",
+ files: input.files ?? []
+ }
+ })
+ editor.view.dom.dispatchEvent(event)
+}
+
+function codeBlockText(editor: Editor): string {
+ const code = docJson(editor).content?.find((n) => n.type === "codeBlock")
+ return (code?.content ?? [])
+ .map((child) => ("text" in child ? child.text : ""))
+ .join("")
+}
+
+describe("代码块内粘贴", () => {
+ beforeAll(() => {
+ installTiptapJsdomShims()
+ })
+
+ afterEach(() => {
+ cleanupEditors()
+ })
+
+ it("空代码块内粘贴多行纯文本:全部进块内、行数一致,块外不新增块", () => {
+ const editor = makeEditor("
")
+ editor.commands.setTextSelection(1)
+
+ pasteInto(editor, { text: "a\nb\nc" })
+
+ expect(codeBlockText(editor)).toBe("a\nb\nc")
+ // 恰好一个 codeBlock,且块外没有承载内容的块(空占位段落不算新增块)
+ const blocks = docJson(editor).content ?? []
+ expect(blocks.filter((n) => n.type === "codeBlock")).toHaveLength(1)
+ expect(
+ blocks.filter((n) => n.type !== "codeBlock" && n.content?.length)
+ ).toHaveLength(0)
+ })
+
+ it("已有代码块中间粘贴(不带选区):插入到光标处,不溢出到块外", () => {
+ const editor = makeEditor("aaa\nbbb\nccc
")
+ // 光标在 "aa" 之后(文本第 2 个字符后)
+ editor.commands.setTextSelection(3)
+
+ pasteInto(editor, { text: "X\nY" })
+
+ expect(codeBlockText(editor)).toBe("aaX\nYa\nbbb\nccc")
+ const blocks = docJson(editor).content ?? []
+ expect(blocks.filter((n) => n.type === "codeBlock")).toHaveLength(1)
+ })
+
+ it("已有代码块中间粘贴(带选区):替换选区,不溢出到块外", () => {
+ const editor = makeEditor("aaa\nbbb\nccc
")
+ // 选中第二行 "bbb"(pos 5..8)
+ editor.commands.setTextSelection({ from: 5, to: 8 })
+
+ pasteInto(editor, { text: "Z" })
+
+ expect(codeBlockText(editor)).toBe("aaa\nZ\nccc")
+ const blocks = docJson(editor).content ?? []
+ expect(blocks.filter((n) => n.type === "codeBlock")).toHaveLength(1)
+ })
+
+ it("代码块内粘贴同时带 text/html 与 text/plain:按纯文本插入,且不做 HTML 解析", () => {
+ const editor = makeEditor("line1
")
+ editor.commands.setTextSelection(2)
+
+ pasteInto(editor, {
+ text: "x&",
+ html: "不应出现
"
+ })
+
+ // 尖括号按字面量进块,不解析成标签;HTML 分支不触发
+ expect(codeBlockText(editor)).toBe("lx&ine1")
+ expect(editor.getJSON().content?.some((n) => n.type === "heading")).toBe(
+ false
+ )
+ })
+})
+
+describe("非代码块位置粘贴维持现行行为", () => {
+ beforeAll(() => {
+ installTiptapJsdomShims()
+ })
+
+ afterEach(() => {
+ cleanupEditors()
+ })
+
+ it("普通段落粘贴 Confluence 样本:走 HTML 清洗管线插入", () => {
+ const editor = makeEditor("普通段落
")
+ editor.commands.setTextSelection(editor.state.doc.content.size - 1)
+
+ pasteInto(editor, {
+ html: ''
+ })
+
+ const doc = docJson(editor)
+ expect(doc.content?.some((n) => n.type === "heading")).toBe(true)
+ expect(doc.content?.some((n) => n.type === "paragraph")).toBe(true)
+ expect(editor.getHTML()).toContain("标题")
+ expect(editor.getHTML()).toContain("加粗")
+ })
+
+ it("普通段落粘贴纯文本:交 ProseMirror 原生处理", () => {
+ const editor = makeEditor("普通段落
")
+ editor.commands.setTextSelection(editor.state.doc.content.size - 1)
+
+ pasteInto(editor, { text: "追加文字" })
+
+ expect(editor.getText()).toContain("追加文字")
+ })
+})
diff --git a/web/src/editor/paste/paste-plugin.ts b/web/src/editor/paste/paste-plugin.ts
index bf11e46..0da79d4 100644
--- a/web/src/editor/paste/paste-plugin.ts
+++ b/web/src/editor/paste/paste-plugin.ts
@@ -59,6 +59,20 @@ export const ConfluencePaste = Extension.create({
return true
}
+ // 光标在代码块内:一律按纯文本插入,换行原样保留为块内换行;
+ // 选区非空时 insertContent 会先替换选区。
+ if (editor.isActive("codeBlock")) {
+ editor
+ .chain()
+ .focus()
+ .insertContent({
+ type: "text",
+ text: data.getData("text/plain")
+ })
+ .run()
+ return true
+ }
+
const html = data.getData("text/html")
if (!html.trim()) return false
From cde0a45940f858276b57302678b21e11f39907ac Mon Sep 17 00:00:00 2001
From: mapxn <16299874+mapxn@users.noreply.github.com>
Date: Sun, 29 Nov 2026 23:05:56 +0800
Subject: [PATCH 2/3] chore: checkpoint rNveB3zjdni-3DwchqEVw
---
web/src/editor/code-block-toggle.test.ts | 70 ++++++++-
web/src/editor/extensions.ts | 182 +++++++++++++++++------
2 files changed, 209 insertions(+), 43 deletions(-)
diff --git a/web/src/editor/code-block-toggle.test.ts b/web/src/editor/code-block-toggle.test.ts
index 74ba589..4721a73 100644
--- a/web/src/editor/code-block-toggle.test.ts
+++ b/web/src/editor/code-block-toggle.test.ts
@@ -113,7 +113,7 @@ describe("代码块合并与拆回", () => {
it("单段落选区保持原生开关:点一次成单行代码块,再点一次回段落", () => {
const editor = makeEditor("单段
")
- editor.commands.selectAll()
+ editor.commands.setTextSelection({ from: 1, to: 3 })
editor.chain().focus().toggleCodeBlock().run()
const code = codeBlockNode(editor)
@@ -122,4 +122,72 @@ describe("代码块合并与拆回", () => {
editor.chain().focus().toggleCodeBlock().run()
expect(paragraphTexts(editor)).toEqual(["单段"])
})
+
+ it("引用块内两段选区:合并为 1 个代码块(嵌在引用块内),每段一行", () => {
+ const editor = makeEditor("甲
乙
")
+ editor.commands.setTextSelection({
+ from: 0,
+ to: editor.state.doc.content.size
+ })
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const doc = docJson(editor)
+ const blockquote = doc.content?.find((node) => node.type === "blockquote")
+ const code = blockquote?.content?.find((node) => node.type === "codeBlock")
+ expect(code?.content?.[0]).toEqual({ type: "text", text: "甲\n乙" })
+ // 整篇只有这一个代码块
+ expect(
+ (doc.content ?? []).filter((node) => node.type === "codeBlock")
+ ).toHaveLength(0)
+ })
+
+ it("列表两项选区:合并为 1 个代码块,每项一行", () => {
+ const editor = makeEditor("")
+ editor.commands.setTextSelection({
+ from: 0,
+ to: editor.state.doc.content.size
+ })
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const code = codeBlockNode(editor)
+ expect(code?.content?.[0]).toEqual({ type: "text", text: "一\n二" })
+ expect(
+ (docJson(editor).content ?? []).filter(
+ (node) => node.type === "codeBlock"
+ )
+ ).toHaveLength(1)
+ })
+
+ it("列表部分项选区:只合并选中项,未选中项留在列表里", () => {
+ const editor = makeEditor("")
+ // 选中 "二" 与 "三"(文本位置 8..14)
+ editor.commands.setTextSelection({ from: 8, to: 14 })
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const doc = docJson(editor)
+ const list = doc.content?.find((node) => node.type === "bulletList")
+ const code = doc.content?.find((node) => node.type === "codeBlock")
+ expect(list?.content?.[0]?.content?.[0]?.content?.[0]).toEqual({
+ type: "text",
+ text: "一"
+ })
+ expect(code?.content?.[0]).toEqual({ type: "text", text: "二\n三" })
+ expect(
+ (doc.content ?? []).filter((node) => node.type === "codeBlock")
+ ).toHaveLength(1)
+ })
+
+ it("全选标题+列表:合并文本不包含尾随空行", () => {
+ const editor = makeEditor(
+ "标题
"
+ )
+ editor.commands.selectAll()
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const code = codeBlockNode(editor)
+ expect(code?.content?.[0]).toEqual({
+ type: "text",
+ text: "标题\n项目一\n项目二"
+ })
+ })
})
diff --git a/web/src/editor/extensions.ts b/web/src/editor/extensions.ts
index cfdcca9..f161662 100644
--- a/web/src/editor/extensions.ts
+++ b/web/src/editor/extensions.ts
@@ -6,11 +6,12 @@ import { createTable, Table } from "@tiptap/extension-table"
import TableRow from "@tiptap/extension-table-row"
import TaskItem from "@tiptap/extension-task-item"
import TaskList from "@tiptap/extension-task-list"
-import type { Node as ProseMirrorNode } from "@tiptap/pm/model"
+import type { NodeRange, Node as ProseMirrorNode } from "@tiptap/pm/model"
import {
type EditorState,
NodeSelection,
- TextSelection
+ TextSelection,
+ type Transaction
} from "@tiptap/pm/state"
import { ReactNodeViewRenderer } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
@@ -92,52 +93,154 @@ function splitCodeBlockIntoParagraphs(
return true
}
-/** 列表容器自身不成行:合并时下沉到每个列表项取一行。 */
-const LIST_CONTAINER_NAMES = new Set(["bulletList", "orderedList", "taskList"])
+/** 列表容器与引用块是容器:合并时下沉到内部块逐行取纯文本。 */
+const BLOCK_CONTAINER_NAMES = new Set([
+ "bulletList",
+ "orderedList",
+ "taskList",
+ "blockquote"
+])
-/** 选区覆盖的逻辑块逐块取纯文本(每块一行):段落/标题/列表项/引用等。 */
-function blockLines(doc: ProseMirrorNode, from: number, to: number): string[] {
+/** 单个块节点的纯文本行:列表/引用容器继续下沉到内部块。 */
+function nodeLines(node: ProseMirrorNode): string[] {
+ if (BLOCK_CONTAINER_NAMES.has(node.type.name)) {
+ const lines: string[] = []
+ node.forEach((child) => {
+ lines.push(...nodeLines(child))
+ })
+ return lines
+ }
+ return [node.textContent]
+}
+
+/** 选区覆盖的相邻同级块逐块取纯文本(每块一行)。 */
+function siblingLines(
+ parent: ProseMirrorNode,
+ startIndex: number,
+ endIndex: number
+): string[] {
const lines: string[] = []
- doc.nodesBetween(from, to, (node) => {
- if (LIST_CONTAINER_NAMES.has(node.type.name)) {
- return true
- }
- if (
- node.isTextblock ||
- node.type.name === "listItem" ||
- node.type.name === "blockquote"
- ) {
- lines.push(node.textContent)
- return false
- }
- return true
- })
+ for (let i = startIndex; i < endIndex; i += 1) {
+ lines.push(...nodeLines(parent.child(i)))
+ }
return lines
}
+/** TrailingNode 在文末追加的空占位段落(Ctrl+A 全选会把它一起选进来)。 */
+function isTrailingEmptyParagraph(node: ProseMirrorNode): boolean {
+ return node.type.name === "paragraph" && node.childCount === 0
+}
+
+/** 把光标放进刚插入的代码块内部(保证「再点一次拆回」能命中代码块)。 */
+function setCursorInsideCodeBlock(tr: Transaction, pos: number): Transaction {
+ return tr
+ .setSelection(TextSelection.near(tr.doc.resolve(pos + 1)))
+ .scrollIntoView()
+}
+
/**
- * 跨块选区 → 合并为单个代码块:各块纯文本以 \n 连接(行内标记剥除),
+ * 选区覆盖 ≥2 个同级块时合并为单个代码块:各块纯文本以 \n 连接(行内标记剥除),
* 语言取默认(无语言),折叠属性取默认 null。
+ *
+ * 能直接在原地放代码块的父节点(文档、引用、表格单元格等)就地替换;
+ * 列表容器不允许代码块子节点,改为把整表替换成「剩余前段列表 + 代码块 + 剩余后段列表」。
*/
-function mergeBlocksIntoCodeBlock(
+function mergeRangeIntoCodeBlock(
state: EditorState,
dispatch: CommandProps["dispatch"],
- from: number,
- to: number
+ range: NodeRange
): boolean {
const codeBlock = state.schema.nodes.codeBlock
if (!codeBlock) return false
- const text = blockLines(state.doc, from, to).join("\n")
- if (dispatch) {
- const node = codeBlock.create(
- { language: null, collapsed: null },
- text ? state.schema.text(text) : null
+
+ const parent = range.parent
+ const startIndex = range.startIndex
+ let endIndex = range.endIndex
+
+ // 全选会把文末的空占位段落一起选中,剔除它避免多一个尾随空行。
+ if (range.depth === 0) {
+ while (
+ endIndex > startIndex &&
+ endIndex === parent.childCount &&
+ isTrailingEmptyParagraph(parent.child(endIndex - 1))
+ ) {
+ endIndex -= 1
+ }
+ }
+
+ if (endIndex - startIndex < 2) {
+ return false
+ }
+
+ const text = siblingLines(parent, startIndex, endIndex).join("\n")
+ const node = codeBlock.create(
+ { language: null, collapsed: null },
+ text ? state.schema.text(text) : null
+ )
+
+ if (parent.canReplaceWith(startIndex, endIndex, codeBlock)) {
+ const from = range.$from.posAtIndex(startIndex, range.depth)
+ const to = range.$from.posAtIndex(endIndex, range.depth)
+ if (dispatch) {
+ dispatch(
+ setCursorInsideCodeBlock(state.tr.replaceWith(from, to, node), from)
+ )
+ }
+ return true
+ }
+
+ if (BLOCK_CONTAINER_NAMES.has(parent.type.name)) {
+ return liftListItemsIntoCodeBlock(
+ state,
+ dispatch,
+ range,
+ startIndex,
+ endIndex,
+ node
)
- const tr = state.tr.replaceWith(from, to, node)
+ }
+
+ return false
+}
+
+/** 列表容器内的同级项无法就地换代码块,整表替换并保留前后未选中的项。 */
+function liftListItemsIntoCodeBlock(
+ state: EditorState,
+ dispatch: CommandProps["dispatch"],
+ range: NodeRange,
+ startIndex: number,
+ endIndex: number,
+ codeBlockNode: ProseMirrorNode
+): boolean {
+ const list = range.parent
+ const listStart = range.$from.before(range.depth)
+ const listEnd = range.$to.after(range.depth)
+
+ const beforeItems: ProseMirrorNode[] = []
+ for (let i = 0; i < startIndex; i += 1) beforeItems.push(list.child(i))
+ const afterItems: ProseMirrorNode[] = []
+ for (let i = endIndex; i < list.childCount; i += 1)
+ afterItems.push(list.child(i))
+
+ const beforeList = beforeItems.length
+ ? list.type.create(list.attrs, beforeItems)
+ : null
+ const afterList = afterItems.length
+ ? list.type.create(list.attrs, afterItems)
+ : null
+
+ const content: ProseMirrorNode[] = []
+ if (beforeList) content.push(beforeList)
+ content.push(codeBlockNode)
+ if (afterList) content.push(afterList)
+
+ if (dispatch) {
+ const codeBlockPos = listStart + (beforeList ? beforeList.nodeSize : 0)
dispatch(
- tr
- .setSelection(TextSelection.near(tr.doc.resolve(from + 1)))
- .scrollIntoView()
+ setCursorInsideCodeBlock(
+ state.tr.replaceWith(listStart, listEnd, content),
+ codeBlockPos
+ )
)
}
return true
@@ -191,21 +294,16 @@ export const WikiCodeBlock = CodeBlockLowlight.extend({
return splitCodeBlockIntoParagraphs(state, dispatch)
}
- // 选区跨块且落在顶层:合并为单个代码块
+ // 选区覆盖 ≥2 个同级块:合并为单个代码块(单个块交给下方原生开关)
const { selection } = state
if (!selection.empty) {
const range = selection.$from.blockRange(selection.$to)
- if (range && range.depth === 0) {
- return mergeBlocksIntoCodeBlock(
- state,
- dispatch,
- range.start,
- range.end
- )
+ if (range && mergeRangeIntoCodeBlock(state, dispatch, range)) {
+ return true
}
}
- // 单块选区或嵌套位置:保持原生开关行为(单段落 ↔ 代码块)
+ // 单块选区:保持原生开关行为(单段落 ↔ 代码块)
return commands.toggleNode(this.name, "paragraph", attributes)
}
}
From 343a17925c4ec65dbcbc692e61ffea4df9a603a6 Mon Sep 17 00:00:00 2001
From: mapxn <16299874+mapxn@users.noreply.github.com>
Date: Sun, 29 Nov 2026 23:27:02 +0800
Subject: [PATCH 3/3] chore: checkpoint EupBf-MXDFuYrmnfQjlwz
---
web/src/editor/code-block-toggle.test.ts | 16 ++++++++++++++++
web/src/editor/extensions.ts | 11 ++++++-----
2 files changed, 22 insertions(+), 5 deletions(-)
diff --git a/web/src/editor/code-block-toggle.test.ts b/web/src/editor/code-block-toggle.test.ts
index 4721a73..b1f22e0 100644
--- a/web/src/editor/code-block-toggle.test.ts
+++ b/web/src/editor/code-block-toggle.test.ts
@@ -190,4 +190,20 @@ describe("代码块合并与拆回", () => {
text: "标题\n项目一\n项目二"
})
})
+
+ it("全选单个标题(含文末空占位段落):恰好 1 个代码块,不生成空代码块", () => {
+ const editor = makeEditor("标题
")
+ editor.commands.selectAll()
+ editor.chain().focus().toggleCodeBlock().run()
+
+ const doc = docJson(editor)
+ const codeBlocks = (doc.content ?? []).filter(
+ (node) => node.type === "codeBlock"
+ )
+ expect(codeBlocks).toHaveLength(1)
+ expect(codeBlocks[0]?.content?.[0]).toEqual({
+ type: "text",
+ text: "标题"
+ })
+ })
})
diff --git a/web/src/editor/extensions.ts b/web/src/editor/extensions.ts
index f161662..8fe4f64 100644
--- a/web/src/editor/extensions.ts
+++ b/web/src/editor/extensions.ts
@@ -157,7 +157,12 @@ function mergeRangeIntoCodeBlock(
const startIndex = range.startIndex
let endIndex = range.endIndex
- // 全选会把文末的空占位段落一起选中,剔除它避免多一个尾随空行。
+ // 仅当原始选区覆盖 ≥2 个同级块时才合并;单块交给原生开关。
+ if (endIndex - startIndex < 2) {
+ return false
+ }
+
+ // 全选会把文末的空占位段落一起选中:只从文本/替换范围剔除,不参与块数判定。
if (range.depth === 0) {
while (
endIndex > startIndex &&
@@ -168,10 +173,6 @@ function mergeRangeIntoCodeBlock(
}
}
- if (endIndex - startIndex < 2) {
- return false
- }
-
const text = siblingLines(parent, startIndex, endIndex).join("\n")
const node = codeBlock.create(
{ language: null, collapsed: null },