An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve mind map node text and restore empty task editing https://github.com/siyuan-note/siyuan/issues/19733
Vanessa7a3d2241d54c
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.syindex 22acaeaed1..93410ef96c 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy@@ -12311,6 +12311,38 @@}]},+ {+ "ID": "20260922005114-otwcwl2",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922005114-otwcwl2",+ "updated": "20260922005114"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "While editing a mind map node, list conversion shortcuts (including "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Ctrl+L"+ },+ {+ "Type": "NodeText",+ "Data": " / "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "⌘L"+ },+ {+ "Type": "NodeText",+ "Data": ") are disabled, and list conversion commands are hidden from the slash menu. Typing a list marker at the start of the first paragraph removes the marker while preserving the text and caret, without creating a list or child node."+ }+ ]+ },{"ID": "20260921105011-3srqnh0","Type": "NodeTable",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.syindex 987f79f86d..3b672ccbe7 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy@@ -12297,6 +12297,38 @@}]},+ {+ "ID": "20260922005114-vwg7ltx",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922005114-vwg7ltx",+ "updated": "20260922005114"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "编辑思维导图节点时,列表转换快捷键(包括 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Ctrl+L"+ },+ {+ "Type": "NodeText",+ "Data": " / "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "⌘L"+ },+ {+ "Type": "NodeText",+ "Data": ")不生效,斜杠菜单不提供列表转换。首段开头输入列表标记时会移除标记,保留正文和光标,不会生成列表或子节点。"+ }+ ]+ },{"ID": "20260921105011-fr0uxw6","Type": "NodeTable",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.syindex 1512963753..843b360d4c 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy@@ -12303,6 +12303,38 @@}]},+ {+ "ID": "20260922005114-96rb7ow",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922005114-96rb7ow",+ "updated": "20260922005114"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "編輯心智圖節點時,列表轉換快捷鍵(包括 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Ctrl+L"+ },+ {+ "Type": "NodeText",+ "Data": " / "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "⌘L"+ },+ {+ "Type": "NodeText",+ "Data": ")不生效,斜線選單不提供列表轉換。首段開頭輸入列表標記時會移除標記,保留正文與游標,不會建立列表或子節點。"+ }+ ]+ },{"ID": "20260921105011-f8y6pxv","Type": "NodeTable",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.syindex 2a4e3d72b2..d14a11689d 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy@@ -12261,6 +12261,38 @@}]},+ {+ "ID": "20260922005114-pteqyq5",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922005114-pteqyq5",+ "updated": "20260922005114"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "マインドマップのノードを編集中は、リストへの変換ショートカット("+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Ctrl+L"+ },+ {+ "Type": "NodeText",+ "Data": " / "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "⌘L"+ },+ {+ "Type": "NodeText",+ "Data": " を含む)は無効になり、スラッシュメニューにもリストへの変換コマンドは表示されません。最初の段落の先頭にリストマーカーを入力すると、本文とカーソル位置を保持したままマーカーが削除され、リストや子ノードは作成されません。"+ }+ ]+ },{"ID": "20260921105011-01k7syf","Type": "NodeTable",diff --git a/app/src/assets/scss/protyle/_list-mindmap.scss b/app/src/assets/scss/protyle/_list-mindmap.scssindex fd9a57125c..4a2aac8732 100644--- a/app/src/assets/scss/protyle/_list-mindmap.scss+++ b/app/src/assets/scss/protyle/_list-mindmap.scss@@ -345,7 +345,8 @@&__node[data-task] {display: grid;- grid-template-columns: max-content minmax(0, 1fr);+ // 空任务正文也保留输入宽度,确保光标能落入编辑器。+ grid-template-columns: max-content minmax(1em, 1fr);column-gap: 6px;align-items: start;diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex ba8bf271ba..9f30442dd1 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -79,7 +79,7 @@ import {getLiteSlashMenuHTML} from "../../mobile/util/liteSlashMenu";import {getVisibleViewportBounds} from "../../mobile/util/visibleViewport";import {getTopBarHeight} from "../../layout/getTopBarHeight";import {getSemanticInlineVisibleText, stripSemanticMarkersFromRangeText} from "../util/inlineElementMarker";-import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";+import {areProtylePluginExtensionsEnabled, isProtyleListItemFragment} from "../runtimeCapabilities";const genEmojiInsertHTML = (value: string) => {const kind = getIconValueKind(value);@@ -771,6 +771,11 @@ ${genHintItemHTML(item)}if (!nodeElement) {return;}+ if (["/", "、"].includes(this.splitChar) && isProtyleListItemFragment(protyle) &&+ ["- " + Lute.Caret, "1. " + Lute.Caret, "- [ ] " + Lute.Caret].includes(value)) {+ this.enableExtend = false;+ return;+ }// 新建标签的搜索状态:用选中的标签替换原空标签if (this.hashTagSearchElement && this.source === "hint") {const tagElement = this.hashTagSearchElement;diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.tsindex c5f4d4b9c0..4dcc881a09 100644--- a/app/src/protyle/render/listMindmap/editor.test.ts+++ b/app/src/protyle/render/listMindmap/editor.test.ts@@ -283,10 +283,18 @@ const browserCases = async (sourceCode: string, css: string) => {check.ok(parseFloat(getComputedStyle(quote).paddingLeft) > 4, "quote keeps shared indentation");check.ok(parseFloat(getComputedStyle(fixture.querySelector(".h1")).fontSize) >parseFloat(getComputedStyle(fixture.querySelector(".p")).fontSize), "heading keeps shared font size");- for (const text of ["Test text", '<span data-type="strong">11pppppp</span>', "First<br>Second", "First\nSecond",- '<span data-type="strong">1水电费ppppp</span>', '<span data-type="strong">1水电费pppppp</span>']) {+ for (const [text, task] of ["", "Test text", '<span data-type="strong">11pppppp</span>', "First<br>Second", "First\nSecond",+ '<span data-type="strong">1水电费ppppp</span>', '<span data-type="strong">1水电费pppppp</span>']+ .flatMap(text => [[text, false], [text, true]] as const)) {fixture.innerHTML = `<div data-node-id="list" data-type="NodeList"><div class="list-mindmap"><div class="list-mindmap__node"><div class="list-mindmap__content"><div class="p list-mindmap__preview-block" data-type="NodeParagraph"><div class="list-mindmap__text">${text}</div></div></div></div></div></div>`;const node = fixture.querySelector<HTMLElement>(".list-mindmap__node");+ if (task) {+ node.dataset.task = " ";+ const button = document.createElement("button");+ button.className = "protyle-action protyle-action--task list-mindmap__task";+ button.innerHTML = '<svg><use xlink:href="#iconUncheck"></use></svg>';+ node.prepend(button);+ }const content = fixture.querySelector<HTMLElement>(".list-mindmap__content");const before = {width: node.offsetWidth, height: node.offsetHeight};if (text === "Test text") {@@ -302,6 +310,19 @@ const browserCases = async (sourceCode: string, css: string) => {"entering edit mode preserves node dimensions with responsive padding and canvas zoom");content.style.minWidth = "";const editable = content.querySelector<HTMLElement>('[data-type="NodeParagraph"] > div');+ check.ok(editable.getBoundingClientRect().width > 0, JSON.stringify({text, task, scale,+ nodeWidth: node.offsetWidth, contentWidth: content.offsetWidth,+ contentMinWidth: getComputedStyle(content).minWidth,+ columns: getComputedStyle(node).gridTemplateColumns}));+ const beforeInput = editable.textContent;+ editable.focus();+ const range = document.createRange();+ range.selectNodeContents(editable);+ range.collapse(false);+ getSelection().removeAllRanges();+ getSelection().addRange(range);+ await require("electron").ipcRenderer.invoke("list-mindmap-editor-type", "a");+ check.equal(editable.textContent, beforeInput + "a", "focused node content accepts native text input");editable.textContent = "A longer sentence that expands the node while editing";const expandedWidth = node.offsetWidth;check.ok(expandedWidth > before.width, "typing expands the editor before blur");@@ -333,11 +354,14 @@ test("list mindmap editor flushes pending input and preserves text across finishconst css = require("sass").compile(path.resolve(__dirname, "../../../assets/scss/base.scss"), {logger: require("sass").Logger.silent,}).css;- const code = `const {app, BrowserWindow} = require("electron");+ const code = `const {app, BrowserWindow, ipcMain} = require("electron");app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});app.commandLine.appendSwitch("disable-gpu");app.whenReady().then(async () => {const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ ipcMain.handle("list-mindmap-editor-type", async (_event, text) => {+ await win.webContents.insertText(text);+ });try {await win.loadURL("data:text/html,<html><body></body></html>");const result = await win.webContents.executeJavaScript(${JSON.stringify(diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.tsindex db8d49c218..05b34e8d47 100644--- a/app/src/protyle/render/listMindmap/editor.ts+++ b/app/src/protyle/render/listMindmap/editor.ts@@ -60,7 +60,8 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {const toolbar = getDefaultToolbar(isMobile()).filter(item =>typeof item === "string" ? item !== "ai" : item.name !== "ai");const slash = registerBuiltinSlashHint((key: string, protyle: IProtyle, hintSource: THintSource) =>- hintSlash(key, protyle, hintSource).filter(item => TABLE_CELL_SLASH_IDS.has(item.id)));+ hintSlash(key, protyle, hintSource).filter(item => TABLE_CELL_SLASH_IDS.has(item.id) &&+ !["list", "orderedList", "check"].includes(item.id)));const hint: IProtyleOptions["hint"] = {extend: [{key: "((", hint: hintRef}, {key: "【【", hint: hintRef}, {key: "((", hint: hintRef},{key: "[[", hint: hintRef}, {key: "/", hint: slash}, {key: "、", hint: slash}],@@ -78,6 +79,7 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {protyleOptions: {notebookId: owner.notebookId, toolbar, hint},runtimeCapabilities: {upload: false, websocket: false, pluginExtensions: false, customBlockRender: false,+ listItemFragment: true,lute: getAVRichTextLute(), lockedOptions: {toolbar, hint},sanitizeBlockDOM: html => sanitizeAVRichTextBlockDOM(html, true),getUnsupportedPasteBlocks: html => getAVRichTextUnsupportedPasteBlocks(html, true),diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex 8df7a358c9..195fd9f5df 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -5,7 +5,7 @@ import {tmpdir} from "node:os";import * as path from "node:path";import {execFile} from "node:child_process";import {promisify} from "node:util";-import type {ListMindmapLayoutNode} from "./model";+import type {ListMindmapLayoutNode, ListMindmapNode} from "./model";const buildGlobals = ["SIYUAN_VERSION", "NODE_ENV"].map(name => ({name, descriptor: Object.getOwnPropertyDescriptor(globalThis, name),@@ -122,7 +122,8 @@ test("layout rejects cyclic or invalid trees and supports deep nesting without rassert.equal(layoutListMindmap(root).nodes.size, 5001);});-const browserCases = async (sourceCode: string, css: string, taskSource: string, taskCSS: string, dragSource: string) => {+const browserCases = async (sourceCode: string, css: string, taskSource: string, taskCSS: string, dragSource: string,+ inputSource: string) => {const check = require("node:assert/strict");const api = new Function("mathRender", "Constants", "highlightRender", sourceCode + "; return {readListMindmap, moveListMindmapNode, addListMindmapNode, " +"deleteListMindmapNode, replaceListMindmapContent, cleanListMindmapHTML, convertListMindmapToList, remapListMindmapIDs, writeListMindmapMetadata, " +@@ -149,6 +150,168 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,const ids = (list: HTMLElement) => Array.from(list.querySelectorAll("[data-node-id]")).map(element =>element.getAttribute("data-node-id"));+ // 虚拟根直属节点的首段复用列表输入链路,输入和保存均保留正文、块身份及光标。+ const inputTransactions: {forward: IOperation[], backward: IOperation[]}[] = [];+ const inputAPI = new Function("Constants", "dayjs", "transaction", "hideElements", "mathRender", "highlightRender",+ "normalizeInlineFontFamilyStyle", "getBlockquoteContext", "revealTabsForTarget",+ "updateTransaction", "isMac", "isOnlyMeta", "isNotCtrl", inputSource ++ "; return {input, configureListItemInput, listShortcut, ListHint};")(+ {ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing", KEYCODELIST: {76: "L", 74: "J"}}, () => ({format: () => "20260922120000"}),+ (_protyle: IProtyle, forward: IOperation[], backward: IOperation[]) => inputTransactions.push({forward, backward}),+ () => {}, () => {}, () => {}, (value: string) => value, (): undefined => undefined, () => {},+ (_protyle: IProtyle, block: HTMLElement, before: string) => {+ inputTransactions.push({forward: [{action: "update", id: block.dataset.nodeId, data: block.outerHTML}],+ backward: [{action: "update", id: block.dataset.nodeId, data: before}]});+ }, () => false, (event: KeyboardEvent) => event.ctrlKey && !event.metaKey,+ (event: KeyboardEvent) => !event.ctrlKey && !event.metaKey);+ window.siyuan = {config: {editor: {markdown: {}}, keymap: {editor: {insert: {+ list: {custom: "⌘J"}, "ordered-list": {custom: "⇧⌘J"}, check: {custom: "⌘L"}, quote: {custom: ""},+ }}}}, storage: {}} as unknown as typeof window.siyuan;+ document.body.append(holder);+ const inputHost = document.createElement("div");+ inputHost.className = "protyle-wysiwyg";+ inputHost.contentEditable = "true";+ document.body.append(inputHost);+ const inputProtyle = {lute, wysiwyg: {element: inputHost, lastHTMLs: {}},+ hint: {render: () => {}}, toolbar: {}, block: {parentID: "document"}} as unknown as IProtyle;+ const caretOffset = (element: Element) => {+ const selection = getSelection();+ check.ok(selection.isCollapsed);+ check.ok(element.contains(selection.anchorNode));+ const range = document.createRange();+ range.selectNodeContents(element);+ range.setEnd(selection.anchorNode, selection.anchorOffset);+ return range.toString().length;+ };+ const typeAtCaret = async (value: string) => {+ const range = getSelection().getRangeAt(0);+ const block = (range.startContainer.nodeType === Node.ELEMENT_NODE ? range.startContainer as Element :+ range.startContainer.parentElement).closest<HTMLElement>('[data-type="NodeParagraph"]');+ inputProtyle.wysiwyg.lastHTMLs[block.dataset.nodeId] = block.outerHTML;+ const text = document.createTextNode(value);+ range.insertNode(text);+ range.setStartAfter(text);+ range.collapse(true);+ await inputAPI.input(inputProtyle, block, range, true,+ new InputEvent("input", {inputType: "insertText", data: value}));+ };+ for (const body of ["", "Text **bold** and *italic*"]) {+ const list = reset("- " + (body || "Empty") + "\n- Sibling\n");+ const model = api.readListMindmap(list);+ const node = model.root.children[0];+ inputHost.innerHTML = node.contentBlocks.map((block: HTMLElement) => block.outerHTML).join("");+ inputAPI.configureListItemInput(inputProtyle);+ const blockID = node.contentBlocks[0].dataset.nodeId;+ const content = inputHost.firstElementChild.firstElementChild;+ if (!body) {+ content.textContent = "";+ }+ const before = content.innerHTML;+ const sourceIDs = ids(list);+ inputHost.focus();+ getSelection().setBaseAndExtent(content, 0, content, 0);+ inputTransactions.length = 0;+ await typeAtCaret("*");+ check.equal(inputHost.firstElementChild.getAttribute("data-type"), "NodeParagraph");+ check.equal(caretOffset(inputHost.firstElementChild.firstElementChild), 1);+ await typeAtCaret(" ");+ const paragraph = inputHost.firstElementChild;+ check.equal(paragraph.getAttribute("data-node-id"), blockID);+ check.equal(paragraph.firstElementChild.innerHTML, before);+ check.equal(caretOffset(paragraph.firstElementChild), 0);+ check.equal(inputHost.querySelector('[data-type="NodeList"]'), null);+ check.ok(inputTransactions.every(item => item.forward.every(operation => operation.action === "update")));+ const undoData = inputTransactions.at(-1).backward[0].data;+ check.ok(typeof undoData === "string" && undoData.includes("*"), "undo retains the typed marker");+ api.replaceListMindmapContent(list, node.id, inputHost.innerHTML);+ check.deepEqual(ids(list), sourceIDs);+ check.equal(api.readListMindmap(list).nodes.size, model.nodes.size);+ await typeAtCaret("x");+ check.equal(caretOffset(paragraph.firstElementChild), 1);+ check.ok(paragraph.firstElementChild.textContent.startsWith("x"));+ }+ // 真实根节点和下级节点的首段使用相同规则,后续段落仍可生成子列表。+ for (const [markdown, nodeIndex, paragraphIndex] of [+ ["- Single root\n", 0, 0],+ ["- Parent\n - Nested\n- Sibling\n", 2, 0],+ ["- First\n\n Second\n- Sibling\n", 0, 1],+ ] as const) {+ const model = api.readListMindmap(reset(markdown));+ const node = [...model.nodes.values()].filter((item: ListMindmapNode) => !item.virtual)[nodeIndex];+ inputHost.innerHTML = node.contentBlocks.map((block: HTMLElement) => block.outerHTML).join("");+ inputAPI.configureListItemInput(inputProtyle);+ const content = inputHost.children[paragraphIndex].firstElementChild;+ inputHost.focus();+ getSelection().setBaseAndExtent(content, 0, content, 0);+ await typeAtCaret("* ");+ if (paragraphIndex === 0) {+ check.equal(inputHost.querySelector(".list"), null);+ } else {+ check.ok(inputHost.children[paragraphIndex].classList.contains("list"), markdown);+ }+ }+ const checkListStructure = (list: HTMLElement) => {+ list.querySelectorAll<HTMLElement>('[data-type="NodeListItem"]').forEach(item => {+ check.equal(item.querySelector(":scope > [data-node-id]")?.getAttribute("data-type"), "NodeParagraph");+ });+ };+ // 每层节点都移除首段的列表标记,保存后仍以段落开头,正文、子树及块身份保持不变。+ for (const markdown of [+ "- Text <tag> & **bold**\n\n Second\n",+ "- Text **bold**\n\n Second\n- Other\n",+ "- Parent\n - Text **bold**\n\n Second\n - Descendant\n- Other\n",+ ]) {+ const list = reset(markdown);+ const model = api.readListMindmap(list);+ const node = [...model.nodes.values()].find((item: ListMindmapNode) =>+ item.contentBlocks[0]?.textContent.startsWith("Text"));+ const sourceIDs = ids(list);+ inputAPI.configureListItemInput(inputProtyle);+ for (const marker of ["* ", "- ", "+ ", "1. ", "2) ", "[]", "[x]"]) {+ inputHost.innerHTML = node.contentBlocks.map((block: HTMLElement) => block.outerHTML).join("");+ const content = inputHost.firstElementChild.firstElementChild;+ const before = content.innerHTML;+ inputHost.focus();+ getSelection().setBaseAndExtent(content, 0, content, 0);+ await typeAtCaret(marker);+ check.equal(content.innerHTML, before, marker);+ check.equal(caretOffset(content), 0);+ check.equal(inputHost.querySelector('[data-type="NodeList"]'), null);+ check.equal(api.replaceListMindmapContent(list, node.id, inputHost.innerHTML), true);+ check.deepEqual(ids(list), sourceIDs);+ check.equal(node.element.dataset.subtype, "u");+ checkListStructure(list);+ const saved = document.createElement("div");+ saved.innerHTML = lute.SpinBlockDOM(list.outerHTML);+ check.equal(saved.childElementCount, 1);+ check.deepEqual(ids(saved.firstElementChild as HTMLElement), sourceIDs);+ checkListStructure(saved);+ }+ // 列表快捷键和残留的斜杠菜单命令在所有段落都保持文本及选区。+ inputHost.innerHTML = node.contentBlocks.map((block: HTMLElement) => block.outerHTML).join("");+ const before = inputHost.innerHTML;+ for (const block of Array.from(inputHost.children)) {+ const content = block.firstElementChild;+ inputHost.focus();+ getSelection().setBaseAndExtent(content.firstChild, 0, content.firstChild, 2);+ const selected = getSelection().toString();+ for (const subtype of ["u", "o", "t"]) {+ const event = new KeyboardEvent("keydown", {key: subtype === "t" ? "l" : "j",+ keyCode: subtype === "t" ? 76 : 74, ctrlKey: true, shiftKey: subtype === "o", cancelable: true});+ inputAPI.listShortcut(inputProtyle, block, event);+ check.ok(event.defaultPrevented);+ const hint = new inputAPI.ListHint();+ hint.splitChar = "/";+ hint.lastIndex = 0;+ inputProtyle.toolbar.range = getSelection().getRangeAt(0);+ hint.fill((subtype === "o" ? "1. " : subtype === "t" ? "- [ ] " : "- ") + Lute.Caret, inputProtyle, false);+ check.equal(getSelection().toString(), selected);+ check.equal(inputHost.innerHTML, before);+ }+ }+ }+ inputHost.remove();+// mindmap 与其他语言一样生成可直接编辑的代码块,编辑重排时不会恢复图表节点。const legacySource = "- **Root**\n - [X] Done\n - [/] Progress\n";const legacyBlock = reset("```mindmap\n" + legacySource + "```\n");@@ -1860,6 +2023,22 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,const childNode = taskHost.querySelector(`[data-mindmap-id="${child.id}"] .p`);check.equal(getComputedStyle(childNode).textDecorationLine, "none", "parent state never styles child tasks");}+ taskHost.scrollIntoView({block: "center"});+ await settle();+ const taskTextBounds = taskView.getContentHost(taskId).firstElementChild.getBoundingClientRect();+ const taskTextPoint = {x: Math.round(taskTextBounds.left + taskTextBounds.width / 2),+ y: Math.round(taskTextBounds.top + taskTextBounds.height / 2)};+ await require("electron").ipcRenderer.invoke("list-mindmap-native-input", [+ {type: "mouseMove", ...taskTextPoint},+ {type: "mouseDown", ...taskTextPoint, button: "left", clickCount: 1},+ {type: "mouseUp", ...taskTextPoint, button: "left", clickCount: 1},+ {type: "mouseDown", ...taskTextPoint, button: "left", clickCount: 2},+ {type: "mouseUp", ...taskTextPoint, button: "left", clickCount: 2},+ ]);+ await settle();+ check.equal(taskEdits, 1, "native double click opens the task node editor");+ taskEdits = 0;+ taskView.setEditing(undefined);const taskSourceHTML = taskList.outerHTML;taskView.setReadOnly(true);taskButton().click();@@ -2151,6 +2330,54 @@ test("list mindmap mutations preserve block data in the real DOM and Lute", {readFileSync(file, "utf8").replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""), {compilerOptions: {target: typescript.ScriptTarget.ES2021},}).outputText;+ const inputModules = ["../../../util/escape.ts", "../../util/normalizeText.ts", "../../runtimeCapabilities.ts",+ "../../../util/keymapBindings.ts", "../../util/hotKey.ts",+ "../../util/longTextWrap.ts", "../../util/inlineElementBoundary.ts", "../../util/inlineElementMarker.ts",+ "../../util/hasClosest.ts", "../../wysiwyg/getBlock.ts", "../../util/selection.ts",+ "../../wysiwyg/taskListMarker.ts", "../../wysiwyg/turnIntoList.ts", "../../wysiwyg/input.ts"];+ let inputSource = inputModules.map(file => {+ const filename = path.join(__dirname, file);+ const module = typescript.createSourceFile(file, readFileSync(filename, "utf8"), typescript.ScriptTarget.ES2021, true);+ const names = module.statements.filter(typescript.isVariableStatement).filter(statement =>+ statement.modifiers?.some(modifier => modifier.kind === typescript.SyntaxKind.ExportKeyword))+ .flatMap(statement => statement.declarationList.declarations.map(declaration => declaration.name.getText(module)));+ return `const {${names.join(", ")}} = (() => {${compile(filename)}\nreturn {${names.join(", ")}};})();\n`;+ }).join("\n");+ const editorSource = typescript.createSourceFile("editor.ts", readFileSync(path.join(__dirname, "editor.ts"), "utf8"),+ typescript.ScriptTarget.ES2021, true);+ const listItemCapabilities: import("typescript").PropertyAssignment[] = [];+ const findListItemCapability = (node: import("typescript").Node) => {+ if (typescript.isPropertyAssignment(node) && node.name.getText(editorSource) === "listItemFragment") {+ listItemCapabilities.push(node);+ }+ typescript.forEachChild(node, findListItemCapability);+ };+ findListItemCapability(editorSource);+ assert.equal(listItemCapabilities.length, 1);+ inputSource += `\nconst configureListItemInput = (protyle) => {+ registerProtyleRuntimeCapabilities(protyle, {${listItemCapabilities.map(item => item.getText(editorSource)).join(",\n")}});+ };`;+ const keydownSource = typescript.createSourceFile("keydown.ts", readFileSync(path.join(__dirname, "../../wysiwyg/keydown.ts"), "utf8"),+ typescript.ScriptTarget.ES2021, true);+ const shortcutStatements: import("typescript").Node[] = [];+ const findShortcut = (node: import("typescript").Node) => {+ if ((typescript.isVariableStatement(node) && node.declarationList.declarations.some(item =>+ ["isMatchList", "isMatchOList", "isMatchCheck", "isMatchQuote"].includes(item.name.getText(keydownSource)))) ||+ (typescript.isIfStatement(node) && node.expression.getText(keydownSource).includes("isProtyleListItemFragment("))) {+ shortcutStatements.push(node);+ }+ typescript.forEachChild(node, findShortcut);+ };+ findShortcut(keydownSource);+ assert.equal(shortcutStatements.length, 5);+ const hintSource = typescript.createSourceFile("hint.ts", readFileSync(path.join(__dirname, "../../hint/index.ts"), "utf8"),+ typescript.ScriptTarget.ES2021, true);+ const hint = hintSource.statements.filter(typescript.isClassDeclaration).find(item => item.name?.text === "Hint");+ const fill = hint.members.find(item => item.name?.getText(hintSource) === "fill");+ inputSource += typescript.transpileModule(`\nconst listShortcut = (protyle, nodeElement, event) => {+ ${shortcutStatements.map(item => item.getText(keydownSource)).join("\n")}+ };+ class ListHint {${fill.getText(hintSource)}}`, {compilerOptions: {target: typescript.ScriptTarget.ES2021}}).outputText;const tabsSource = "const {tabsRender, destroyTabsRender, getTabTask} = (() => {" +["../../../util/escape.ts", "../tabsState.ts", "../tabsDrag.ts", "../tabsAttributes.ts", "../tabsRender.ts"].map(file => compile(path.join(__dirname, file))).join("\n") +@@ -2232,7 +2459,7 @@ app.whenReady().then(async () => {await win.loadURL("data:text/html,<html><body></body></html>");await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));const result = await win.webContents.executeJavaScript(${JSON.stringify(- `const __name = value => value; (${browserSource})(${JSON.stringify(source)}, ${JSON.stringify(css)}, ${JSON.stringify(taskSource)}, ${JSON.stringify(taskCSS)}, ${JSON.stringify(dragSource)})`)});+ `const __name = value => value; (${browserSource})(${JSON.stringify(source)}, ${JSON.stringify(css)}, ${JSON.stringify(taskSource)}, ${JSON.stringify(taskCSS)}, ${JSON.stringify(dragSource)}, ${JSON.stringify(inputSource)})`)});console.log(result);win.destroy();app.exit(0);diff --git a/app/src/protyle/runtimeCapabilities.ts b/app/src/protyle/runtimeCapabilities.tsindex 2783d81278..acf362f0b2 100644--- a/app/src/protyle/runtimeCapabilities.ts+++ b/app/src/protyle/runtimeCapabilities.ts@@ -7,6 +7,8 @@ export interface ProtyleRuntimeCapabilities {lockedOptions?: Partial<Pick<IProtyleOptions, "hint" | "toolbar">>;pluginExtensions?: boolean;customBlockRender?: boolean;+ // 片段内容作为列表项正文编辑,首段沿用列表输入规则。+ listItemFragment?: boolean;sanitizeBlockDOM?: (blockDOM: string) => string;getUnsupportedPasteBlocks?: (blockDOM: string) => string[];restoreLuteMarkdownSyntax?: (lute: Lute) => void;@@ -36,6 +38,13 @@ export const areProtylePluginExtensionsEnabled = (protyle: IProtyle) =>export const isProtyleCustomBlockRenderEnabled = (protyle: IProtyle) =>protyleRuntimeCapabilities.get(protyle)?.customBlockRender !== false;+export const isProtyleListItemFragment = (protyle: IProtyle) =>+ protyleRuntimeCapabilities.get(protyle)?.listItemFragment === true;++export const isProtyleListItemFirstParagraph = (protyle: IProtyle, blockElement: HTMLElement) =>+ isProtyleListItemFragment(protyle) && blockElement === protyle.wysiwyg.element.firstElementChild &&+ blockElement.dataset.type === "NodeParagraph";+export const getProtyleLockedToolbar = (protyle: IProtyle) =>protyleRuntimeCapabilities.get(protyle)?.lockedOptions?.toolbar;diff --git a/app/src/protyle/wysiwyg/input.ts b/app/src/protyle/wysiwyg/input.tsindex a5f752a293..9b83188a40 100644--- a/app/src/protyle/wysiwyg/input.ts+++ b/app/src/protyle/wysiwyg/input.ts@@ -33,6 +33,7 @@ import {} from "../util/inlineElementMarker";import {normalizeInlineFontFamilyStyle} from "../toolbar/fontFamilyCore";import {sanitizeKernelHTML} from "../../util/hostCapabilities";+import {isProtyleListItemFirstParagraph} from "../runtimeCapabilities";interface IInputOperations {doOperations: IOperation[];@@ -423,8 +424,9 @@ const inputBlock = async (protyle: IProtyle, blockElement: HTMLElement, range: RtempElement.innerHTML = html;// 列表项内紧挨标记的首个段落块不生成子列表,仅移除触发标记并保留现有内容// https://github.com/siyuan-note/siyuan/issues/17890 https://github.com/siyuan-note/siyuan/issues/18355- if (blockElement.closest('[data-type="NodeListItem"]') &&- blockElement.previousElementSibling?.classList.contains("protyle-action")) {+ if ((blockElement.closest('[data-type="NodeListItem"]') &&+ blockElement.previousElementSibling?.classList.contains("protyle-action")) ||+ isProtyleListItemFirstParagraph(protyle, blockElement)) {if (tempElement.content.firstElementChild.classList.contains("list")) {if (editElement.contains(wbrElement)) {const markerRange = document.createRange();diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex 893a24f498..4f250c82dc 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -1,4 +1,5 @@import type {BlockQueryRequestInput} from "../../types/api";+import {isProtyleListItemFragment} from "../runtimeCapabilities";import {hideElements} from "../ui/hideElements";import {isTabTextBoundary} from "./tabsBoundary";import {isNotCtrl, isOnlyMeta, updateHotkeyTip, writeText} from "../util/compatibility";@@ -2198,6 +2199,11 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {const isMatchCheck = matchHotKey(window.siyuan.config.keymap.editor.insert.check, event);const isMatchOList = matchHotKey(window.siyuan.config.keymap.editor.insert["ordered-list"], event);const isMatchQuote = matchHotKey(window.siyuan.config.keymap.editor.insert.quote, event);+ if ((isMatchList || isMatchOList || isMatchCheck) && isProtyleListItemFragment(protyle)) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }if ((isMatchList || isMatchOList || isMatchCheck || isMatchQuote) && !isInEmbedBlock(nodeElement)) {const rangeElements = isCrossBlock && selectText !== "" ? getBlockElementsByRange(range) : [];if (rangeElements.length > 1 && !rangeElements.some(item => item.classList.contains("li"))) {diff --git a/app/src/protyle/wysiwyg/turnIntoList.ts b/app/src/protyle/wysiwyg/turnIntoList.tsindex 5479bcedcd..e09a6d75ab 100644--- a/app/src/protyle/wysiwyg/turnIntoList.ts+++ b/app/src/protyle/wysiwyg/turnIntoList.ts@@ -1,9 +1,10 @@import {transaction, updateTransaction} from "./transaction";-import {focusByWbr} from "../util/selection";+import {focusByOffset, focusByWbr} from "../util/selection";import * as dayjs from "dayjs";import {decodeHTML, escapeAttr} from "../../util/escape";import {Constants} from "../../constants";import {getTaskListMarker} from "./taskListMarker";+import {isProtyleListItemFirstParagraph} from "../runtimeCapabilities";interface IAdditionalOperations {doOperations: IOperation[];@@ -29,6 +30,16 @@ export const turnIntoTaskList = (protyle: IProtyle, type: string, blockElement:!blockElement.previousElementSibling?.classList.contains("protyle-action--task") &&taskListMarker) {+ if (isProtyleListItemFirstParagraph(protyle, blockElement)) {+ const oldHTML = blockElement.outerHTML;+ const markerRange = focusByOffset(editElement, 0, taskListMarker.contentStartIndex, false);+ if (markerRange) {+ markerRange.deleteContents();+ }+ updateTransaction(protyle, blockElement, oldHTML, undefined, additionalOperations);+ focusByWbr(protyle.wysiwyg.element, range);+ return true;+ }editElement.removeAttribute("placeholder");const isDone = taskListMarker.marker !== " ";if (blockElement.parentElement.classList.contains("li") &&