Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Preserve database fields when converting lists to paragraphs https://github.com/siyuan-note/siyuan/issues/19827

Daniela8db7ae48907
diff --git a/app/src/protyle/wysiwyg/cancelList.ts b/app/src/protyle/wysiwyg/cancelList.ts
new file mode 100644
index 0000000000..c7265523c4
--- /dev/null
+++ b/app/src/protyle/wysiwyg/cancelList.ts
@@ -0,0 +1,45 @@
+export const buildCancelListOperations = (source: Element, options: {
+ previousID?: string,
+ parentID?: string,
+ recursively?: boolean,
+}) => {
+ const root = source.cloneNode(true) as Element;
+ const container = document.createElement("div");
+ container.append(root);
+ const lists = [root];
+ if (options.recursively) {
+ lists.push(...Array.from(root.querySelectorAll('[data-type="NodeList"]')).filter(item =>
+ item.getAttribute("data-subtype") === root.getAttribute("data-subtype")));
+ }
+ const doOperations: IOperation[] = [];
+ const undoOperations: IOperation[] = [];
+ // 从内到外拆除列表,内容块始终通过移动保留数据库关联及属性。
+ lists.reverse().forEach(list => {
+ const id = list.getAttribute("data-node-id");
+ const parentID = list === root ? options.parentID : list.parentElement.closest("[data-node-id]")?.getAttribute("data-node-id");
+ let previous = list.previousElementSibling;
+ while (previous && !previous.hasAttribute("data-node-id")) {
+ previous = previous.previousElementSibling;
+ }
+ const previousID = list === root ? options.previousID : previous?.getAttribute("data-node-id");
+ const restoreMoves: IOperation[] = [];
+ let anchor = list;
+ Array.from(list.children).filter(item => item.getAttribute("data-type") === "NodeListItem").forEach(item => {
+ let childPreviousID: string;
+ Array.from(item.children).filter(child => child.hasAttribute("data-node-id")).forEach(child => {
+ const childID = child.getAttribute("data-node-id");
+ doOperations.push({action: "move", id: childID, previousID: anchor.getAttribute("data-node-id"), parentID});
+ restoreMoves.push({action: "move", id: childID, previousID: childPreviousID,
+ parentID: item.getAttribute("data-node-id")});
+ childPreviousID = childID;
+ anchor.after(child);
+ anchor = child;
+ });
+ });
+ // 撤销先恢复空列表外壳,再移回原内容,避免重新插入内容块时清除数据库属性。
+ undoOperations.unshift({action: "insert", id, data: list.outerHTML, previousID, parentID}, ...restoreMoves);
+ doOperations.push({action: "delete", id});
+ list.remove();
+ });
+ return {doOperations, undoOperations};
+};
diff --git a/app/src/protyle/wysiwyg/headingConversion.test.ts b/app/src/protyle/wysiwyg/headingConversion.test.ts
index 8df9a75f12..d70849e418 100644
--- a/app/src/protyle/wysiwyg/headingConversion.test.ts
+++ b/app/src/protyle/wysiwyg/headingConversion.test.ts
@@ -8,9 +8,12 @@ import {promisify} from "node:util";
import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
import type {Node} from "typescript";
-const browserCases = (source: string, menuSource: string, rangeSource: string) => {
+const browserCases = async (source: string, menuSource: string, rangeSource: string) => {
const check: typeof assert = require("node:assert/strict");
const lute = Lute.New();
+ lute.SetKramdownIAL(true);
+ lute.SetProtyleWYSIWYG(true);
+ lute.SetDataTask(true);
const editor = document.createElement("div");
document.body.append(editor);
const batches: Array<{doOperations: IOperation[], undoOperations: IOperation[]}> = [];
@@ -43,11 +46,24 @@ const browserCases = (source: string, menuSource: string, rangeSource: string) =
getSemanticMarkerPrefixLengthForNode: () => 0,
hasPreviousSibling: (element: Element) => element.previousSibling,
setFold: () => check.fail("List folding must not unfold unrelated content"),
+ unfoldListHeadings: async (): Promise<IOperation[]> => [],
+ cleanHeadingNumberHTML: (html: string) => html,
+ cleanListMindmapHTML: (html: string) => html,
+ convertListMindmapToList: (): undefined => undefined,
+ isTabsListConversion: () => false,
+ getPreviousBlockSibling: (element: Element) => element.previousElementSibling,
+ getParentBlock: (element: Element) => element.parentElement,
+ getEmbedChildOperationParentID: (): undefined => undefined,
+ getContenteditableElement: (element: Element) => element.querySelector('[contenteditable="true"]'),
+ getEditorRange: () => document.createRange(),
+ hasViewFoldContext: () => false,
+ onTransaction: noop,
};
const api = new Function(...Object.keys(dependencies), source +
- "\nreturn {turnsIntoTransaction, getHeadingConversionElements, isListHeadingContainer};")(...Object.values(dependencies)) as
- typeof import("./transaction") & typeof import("./headingConversion");
- const protyle = {wysiwyg: {element: editor}, lute, observerLoad: {disconnect: () => disconnects++}} as unknown as IProtyle;
+ "\nreturn {turnsIntoTransaction, turnsOneInto, turnListsRecursively, getHeadingConversionElements, isListHeadingContainer, buildCancelListOperations};")(...Object.values(dependencies)) as
+ typeof import("./transaction") & typeof import("./headingConversion") & typeof import("./cancelList");
+ const protyle = {wysiwyg: {element: editor}, lute, block: {rootID: "document", parentID: "document"},
+ observerLoad: {disconnect: () => disconnects++}} as unknown as IProtyle;
const Gutter = new Function("turnsIntoTransaction", "getHeadingConversionElements", menuSource + "\nreturn Gutter;")(
api.turnsIntoTransaction, api.getHeadingConversionElements);
const gutter = new Gutter() as {
@@ -190,11 +206,96 @@ const browserCases = (source: string, menuSource: string, rangeSource: string) =
check.equal(batches[0].doOperations.length, 4);
check.equal(editor.lastElementChild.getAttribute("data-type"), "NodeHeading");
check.equal(editor.querySelectorAll('[data-type="NodeList"]').length, 2);
+ // 使用真实块 DOM 比较取消列表与 Lute 的结果,并往返重放结构操作。
+ editor.innerHTML = lute.Md2BlockDOM("# First\n\n## Second");
+ Array.from(editor.children).forEach(block => block.setAttribute("custom-avs", "database"));
+ batches.length = 0;
+ api.turnsIntoTransaction({protyle, selectsElement: Array.from(editor.children), type: "Blocks2Ps", isContinue: true});
+ check.deepEqual(batches[0].doOperations.map(operation => operation.action), ["update", "update"]);
+ check.deepEqual(batches[0].undoOperations.map(operation => operation.action), ["update", "update"]);
+ check.equal(editor.querySelectorAll('[data-type="NodeParagraph"][custom-avs="database"]').length, 2);
+ for (const marker of ["-", "1.", "- [x]"]) {
+ for (const recursively of [false, true]) {
+ editor.innerHTML = lute.Md2BlockDOM(`${marker} # Heading\n\n tail\n\n ${marker} nested\n\n > ${marker} quoted\n\n${marker} second`);
+ const sourceList = editor.firstElementChild;
+ sourceList.querySelectorAll('[data-type="NodeHeading"], [data-type="NodeParagraph"]').forEach(block => {
+ block.setAttribute("custom-avs", "database");
+ block.setAttribute("custom-av-database-field", "value");
+ });
+ const originalWithAttributes = editor.innerHTML;
+ // @ts-expect-error Lute 声明尚未包含 CancelList。
+ const expected = recursively ? lute.CancelListRecursively(sourceList.outerHTML) : lute.CancelList(sourceList.outerHTML);
+ const shape = (html: string) => {
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ return Array.from(template.content.querySelectorAll("[data-node-id]")).map(block => ({
+ id: id(block), type: block.getAttribute("data-type"), parent: block.parentElement?.getAttribute("data-node-id"),
+ avs: block.getAttribute("custom-avs"), field: block.getAttribute("custom-av-database-field"),
+ text: block.querySelector(':scope > [contenteditable="true"]')?.textContent,
+ }));
+ };
+ const operations = api.buildCancelListOperations(sourceList, {parentID: "document", recursively});
+ check.equal(editor.innerHTML, originalWithAttributes, "building operations must not mutate the editor");
+ const boundNodes = Array.from(editor.querySelectorAll("[custom-avs]"));
+ const replayStructure = (batch: IOperation[]) => batch.forEach(operation => {
+ const node = editor.querySelector(`[data-node-id="${operation.id}"]`);
+ if (operation.action === "delete") {
+ check.equal(node.querySelectorAll("[custom-avs]").length, 0, "delete only empty list shells");
+ node.remove();
+ return;
+ }
+ let moved = node;
+ if (operation.action === "insert") {
+ const template = document.createElement("template");
+ template.innerHTML = operation.data as string;
+ moved = template.content.firstElementChild;
+ check.equal(moved.querySelectorAll("[custom-avs]").length, 0, "never reinsert bound content");
+ } else {
+ check.equal(operation.action, "move");
+ }
+ if (operation.previousID) {
+ editor.querySelector(`[data-node-id="${operation.previousID}"]`).after(moved);
+ } else {
+ const parent = operation.parentID === "document" ? editor :
+ editor.querySelector(`[data-node-id="${operation.parentID}"]`);
+ const firstBlock = Array.from(parent.children).find(child => child.hasAttribute("data-node-id"));
+ if (firstBlock) {
+ firstBlock.before(moved);
+ } else if (parent.lastElementChild?.classList.contains("protyle-attr")) {
+ parent.lastElementChild.before(moved);
+ } else {
+ parent.append(moved);
+ }
+ }
+ });
+ for (let cycle = 0; cycle < 3; cycle++) {
+ replayStructure(operations.doOperations);
+ check.deepEqual(shape(editor.innerHTML), shape(expected));
+ boundNodes.forEach(node => check.equal(editor.querySelector(`[data-node-id="${id(node)}"]`), node));
+ replayStructure(operations.undoOperations);
+ check.equal(editor.innerHTML, originalWithAttributes);
+ }
+ }
+ }
+ for (const recursively of [false, true]) {
+ editor.innerHTML = lute.Md2BlockDOM("- # Bound\n\n - nested");
+ batches.length = 0;
+ const sourceList = editor.firstElementChild;
+ if (recursively) {
+ await api.turnListsRecursively({protyle, nodeElements: [sourceList], type: "CancelListRecursively"});
+ } else {
+ await api.turnsOneInto({protyle, nodeElement: sourceList, id: id(sourceList), type: "CancelList"});
+ }
+ check.equal(batches.length, 1);
+ check.ok(batches[0].doOperations.some(operation => operation.action === "move"));
+ check.ok(batches[0].doOperations.every(operation => operation.action !== "insert"));
+ check.equal(editor.querySelectorAll('[data-type="NodeList"]').length, recursively ? 0 : 1);
+ }
editor.remove();
return "List heading conversion cases passed";
};
-test("list heading menus and shortcuts preserve containers, content, IDs and undo operations", {
+test("list heading conversion and cancellation preserve content, IDs, database bindings and undo operations", {
skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
timeout: 45000,
}, async () => {
@@ -216,7 +317,8 @@ test("list heading menus and shortcuts preserve containers, content, IDs and und
assert.ok(result, name);
return result;
};
- const source = compile(read("headingConversion.ts") + "\n" + extract("transaction.ts", "turnsIntoTransaction") +
+ const source = compile(read("headingConversion.ts") + "\n" + read("cancelList.ts") + "\n" + extract("transaction.ts", "turnsIntoTransaction") +
+ "\n" + extract("transaction.ts", "turnsOneInto") + "\n" + extract("transaction.ts", "turnListsRecursively") +
"\n" + extract("getBlock.ts", "getNextBlockSibling") + "\n" + extract("../util/selection.ts", "focusByWbr"));
const rangeSource = compile(extract("keydown.ts", "turnCrossBlockRangeInto"));
const parsed = createSourceFile("gutter.ts", read("../gutter/index.ts"), ScriptTarget.Latest, true);
@@ -235,8 +337,11 @@ app.whenReady().then(async () => {
try {
await win.loadURL("data:text/html,<html><body></body></html>");
await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));
- console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +
- browserCases.toString() + ")(" + [source, menuSource, rangeSource].map(value => JSON.stringify(value)).join(",") + ")")}));
+ const result = await win.webContents.executeJavaScript(${JSON.stringify("(async () => { try { const __name = value => value; return {value: await (" +
+ browserCases.toString() + ")(" + [source, menuSource, rangeSource].map(value => JSON.stringify(value)).join(",") +
+ ")}; } catch (error) { return {error: error.stack}; } })()")} );
+ if (result.error) { throw new Error(result.error); }
+ console.log(result.value);
win.destroy();
app.exit(0);
} catch (error) {
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index cccf0e79d9..25a4f864f7 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -77,6 +77,7 @@ import {isEmptyParagraph} from "./emptyTextBlock";
import {getHeadingConversionElements, isListHeadingContainer} from "./headingConversion";
import {cleanTableCellRichHTML, retainTableCellRichMetadata} from "../util/tableCellRich";
import {cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource} from "../render/listMindmap/model";
+import {buildCancelListOperations} from "./cancelList";
import {getProtyleTransactionOwner} from "../runtimeCapabilities";
import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";
import {waitForPendingTransactions} from "../util/transactionQueue";
@@ -1881,6 +1882,8 @@ export const turnsIntoTransaction = (options: {
const doOperations: IOperation[] = [];
const undoOperations: IOperation[] = [];
let previousId: string;
+ const updateParagraphsIndividually = options.type === "Blocks2Ps" && selectsElement.every(item =>
+ ["NodeHeading", "NodeParagraph"].includes(item.getAttribute("data-type")));
selectsElement.forEach((item: HTMLElement, index) => {
item.classList.remove("protyle-wysiwyg--select");
item.removeAttribute("select-start");
@@ -1889,7 +1892,7 @@ export const turnsIntoTransaction = (options: {
const id = item.getAttribute("data-node-id");
const tempElement = document.createElement("template");
- if (!options.isContinue || options.level) {
+ if (!options.isContinue || options.level || updateParagraphsIndividually) {
// @ts-ignore
let newHTML = options.protyle.lute[options.type](item.outerHTML, options.level);
tempElement.innerHTML = newHTML;
@@ -2149,35 +2152,13 @@ export const turnListsRecursively = async (options: {
}
const doPreviousId = getPreviousBlockSibling(nodeElement)?.getAttribute("data-node-id") || context.previousId;
- doOperations.push({
- action: "delete",
- id: context.id
- });
- const tempElement = document.createElement("template");
- tempElement.innerHTML = newHTML;
- let tempPreviousId = doPreviousId;
- Array.from(tempElement.content.children).forEach((item) => {
- const tempId = item.getAttribute("data-node-id");
- doOperations.push({
- action: "insert",
- data: item.outerHTML,
- id: tempId,
- previousID: tempPreviousId,
- parentID: context.parentId
- });
- undoOperations.push({
- action: "delete",
- id: tempId
- });
- tempPreviousId = tempId;
- });
- undoOperations.push({
- action: "insert",
- data: oldHTML,
- id: context.id,
- previousID: context.previousId,
- parentID: context.parentId
+ const operations = buildCancelListOperations(nodeElement, {
+ previousID: doPreviousId,
+ parentID: context.parentId,
+ recursively: true,
});
+ doOperations.push(...operations.doOperations);
+ undoOperations.unshift(...operations.undoOperations);
disposeCustomBlocksInElement(nodeElement);
nodeElement.insertAdjacentHTML("afterend", newHTML);
nodeElement.remove();
@@ -2302,6 +2283,11 @@ export const turnsOneInto = async (options: {
// @ts-ignore
newHTML = listHTML ?? options.protyle.lute[options.type](sourceHTML, options.level);
}
+ const cancelListOperations = options.type === "CancelList" &&
+ options.nodeElement.getAttribute("data-type") === "NodeList" ? buildCancelListOperations(options.nodeElement, {
+ previousID: previousId,
+ parentID: parentId,
+ }) : undefined;
disposeCustomBlocksInElement(options.nodeElement);
options.nodeElement.insertAdjacentHTML("afterend", newHTML);
options.nodeElement = options.nodeElement.nextElementSibling as HTMLElement;
@@ -2309,34 +2295,36 @@ export const turnsOneInto = async (options: {
if (["CancelBlockquote", "CancelList", "CancelCallout"].includes(options.type)) {
const tempElement = document.createElement("template");
tempElement.innerHTML = newHTML;
- const doOperations: IOperation[] = [{
+ const doOperations: IOperation[] = cancelListOperations?.doOperations || [{
action: "delete",
id: options.id
}];
- const undoOperations: IOperation[] = [];
+ const undoOperations: IOperation[] = cancelListOperations?.undoOperations || [];
let tempPreviousId = previousId;
- Array.from(tempElement.content.children).forEach((item) => {
- const tempId = item.getAttribute("data-node-id");
- doOperations.push({
- action: "insert",
- data: item.outerHTML,
- id: tempId,
- previousID: tempPreviousId,
- parentID: parentId
+ if (!cancelListOperations) {
+ Array.from(tempElement.content.children).forEach((item) => {
+ const tempId = item.getAttribute("data-node-id");
+ doOperations.push({
+ action: "insert",
+ data: item.outerHTML,
+ id: tempId,
+ previousID: tempPreviousId,
+ parentID: parentId
+ });
+ undoOperations.push({
+ action: "delete",
+ id: tempId
+ });
+ tempPreviousId = tempId;
});
undoOperations.push({
- action: "delete",
- id: tempId
+ action: "insert",
+ data: oldHTML,
+ id: options.id,
+ previousID: previousId,
+ parentID: parentId
});
- tempPreviousId = tempId;
- });
- undoOperations.push({
- action: "insert",
- data: oldHTML,
- id: options.id,
- previousID: previousId,
- parentID: parentId
- });
+ }
if (options.additionalOperations) {
doOperations.unshift(...options.additionalOperations.doOperations);
undoOperations.push(...options.additionalOperations.undoOperations);
diff --git a/kernel/model/transaction_cancel_list_fts5_test.go b/kernel/model/transaction_cancel_list_fts5_test.go
new file mode 100644
index 0000000000..f7049645d4
--- /dev/null
+++ b/kernel/model/transaction_cancel_list_fts5_test.go
@@ -0,0 +1,106 @@
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+func TestCancelListPreservesDatabaseFields(t *testing.T) {
+ for _, subtype := range []int{0, 1, 3} {
+ t.Run(string(rune('0'+subtype)), func(t *testing.T) {
+ fixture, before, deletion := setupAttributeViewDeletedBlockTest(t, "container")
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ list := treenode.GetNodeInTree(tree, deletion.DoOperations[0].ID)
+ var blocks []*ast.Node
+ for child := list.FirstChild; child != nil; child = child.Next {
+ blocks = append(blocks, child)
+ }
+ list.Type = ast.NodeList
+ list.ListData = &ast.ListData{Typ: subtype, Start: 1, BulletChar: '*', Delimiter: '.'}
+ var items []*ast.Node
+ for _, block := range blocks {
+ block.Type, block.HeadingLevel = ast.NodeHeading, 2
+ block.SetIALAttr(av.NodeAttrViewStaticText+before.ID+"-field", "retained")
+ item := &ast.Node{Type: ast.NodeListItem, ID: ast.NewNodeID(), ListData: list.ListData}
+ item.SetIALAttr("id", item.ID)
+ if subtype == 3 {
+ item.AppendChild(&ast.Node{Type: ast.NodeTaskListItemMarker, TaskListItemChecked: true})
+ }
+ list.AppendChild(item)
+ item.AppendChild(block)
+ items = append(items, item)
+ }
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ sql.FlushQueue()
+
+ tx := &Transaction{fromAPI: true}
+ previousID := list.Previous.ID
+ anchor := list.ID
+ var restore []*Operation
+ for i, block := range blocks {
+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: "move", ID: block.ID,
+ PreviousID: anchor, ParentID: tree.ID})
+ restore = append(restore, &Operation{Action: "move", ID: block.ID, ParentID: items[i].ID})
+ anchor = block.ID
+ block.Unlink()
+ }
+ // 与前端相同,只插入不含内容块的列表外壳。
+ shell := NewLute().RenderNodeBlockDOM(list)
+ for i, block := range blocks {
+ items[i].AppendChild(block)
+ }
+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: "delete", ID: list.ID})
+ tx.UndoOperations = append([]*Operation{{Action: "insert", ID: list.ID, Data: shell,
+ PreviousID: previousID, ParentID: tree.ID}}, restore...)
+ if err = PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ entry := GlobalUndoLog.Peek(fixture.sourceID)
+ if entry == nil {
+ t.Fatal("missing undo entry")
+ }
+ check := func(inList bool) {
+ t.Helper()
+ assertAttributeViewFieldsTest(t, before, readAttributeViewItemsTest(t, before.ID))
+ current, loadErr := LoadTreeByBlockID(fixture.sourceID)
+ if loadErr != nil {
+ t.Fatal(loadErr)
+ }
+ for i, block := range blocks {
+ node := treenode.GetNodeInTree(current, block.ID)
+ if node == nil || node.IALAttr(av.NodeAttrNameAvs) != before.ID ||
+ node.IALAttr(av.NodeAttrViewStaticText+before.ID+"-field") != "retained" {
+ t.Fatal("content block lost database attributes")
+ }
+ parentID := current.ID
+ if inList {
+ parentID = items[i].ID
+ }
+ if node.Parent.ID != parentID {
+ t.Fatalf("unexpected parent: got %s, want %s", node.Parent.ID, parentID)
+ }
+ }
+ }
+ for cycle := 0; cycle < 3; cycle++ {
+ check(false)
+ replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())
+ check(true)
+ replayAttributeViewFieldsTest(t, entry.DoOperationsForReplay())
+ }
+ })
+ }
+}