Skip to content

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

:bug: Restore nested lists when undoing drag operations https://github.com/siyuan-note/siyuan/issues/18470

Daniel1a81b7a94205
diff --git a/app/src/protyle/util/dragDocument.test.ts b/app/src/protyle/util/dragDocument.test.ts
index 9eb42835ad..4819cb8247 100644
--- a/app/src/protyle/util/dragDocument.test.ts
+++ b/app/src/protyle/util/dragDocument.test.ts
@@ -1,6 +1,11 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {isSameDragEditor, uniqueDragIds} from "./dragDocument";
+import {
+ isSameDragEditor,
+ isSameSiblingMove,
+ replaceDragUndoOperation,
+ uniqueDragIds
+} from "./dragDocument";
describe("isSameDragEditor", () => {
it("does not treat a nested Protyle as the target editor", () => {
@@ -25,3 +30,36 @@ describe("uniqueDragIds", () => {
assert.deepEqual(uniqueDragIds(["a", "", "b", "a", "b", "c"]), ["a", "b", "c"]);
});
});
+
+describe("isSameSiblingMove", () => {
+ it("treats dropping a selection onto one of its items as a no-op", () => {
+ assert.equal(isSameSiblingMove(["a", "b", "c"], ["a", "b", "c"], "c", true), true);
+ });
+
+ it("recognizes an unchanged sibling order", () => {
+ assert.equal(isSameSiblingMove(["a", "b", "c", "d"], ["b", "c"], "a", true), true);
+ });
+
+ it("allows a sibling move that changes the order", () => {
+ assert.equal(isSameSiblingMove(["a", "b", "c", "d"], ["b", "c"], "d", true), false);
+ });
+});
+
+describe("replaceDragUndoOperation", () => {
+ it("restores a valid container before moving the remaining items back", () => {
+ const operations = ["move-c", "move-b", "move-a"];
+ replaceDragUndoOperation(operations, "move-a", [
+ "delete-placeholder",
+ "move-a",
+ "insert-list-with-placeholder"
+ ]);
+
+ assert.deepEqual(operations.reverse(), [
+ "insert-list-with-placeholder",
+ "move-a",
+ "delete-placeholder",
+ "move-b",
+ "move-c"
+ ]);
+ });
+});
diff --git a/app/src/protyle/util/dragDocument.ts b/app/src/protyle/util/dragDocument.ts
index e91c0f0820..d52c15ebc7 100644
--- a/app/src/protyle/util/dragDocument.ts
+++ b/app/src/protyle/util/dragDocument.ts
@@ -5,3 +5,27 @@ export const isSameDragEditor = (targetEditor: Pick<Element, "contains">, source
export const uniqueDragIds = (ids: string[]) => {
return Array.from(new Set(ids.filter(Boolean)));
};
+
+export const isSameSiblingMove = <T>(siblings: T[], sources: T[], target: T, isBottom: boolean) => {
+ if (sources.length === 0 || sources.includes(target)) {
+ return sources.includes(target);
+ }
+ const sourceSet = new Set(sources);
+ if (!siblings.includes(target) || sources.some(item => !siblings.includes(item))) {
+ return false;
+ }
+ const orderedSources = siblings.filter(item => sourceSet.has(item));
+ const reordered = siblings.filter(item => !sourceSet.has(item));
+ const targetIndex = reordered.indexOf(target);
+ reordered.splice(targetIndex + (isBottom ? 1 : 0), 0, ...orderedSources);
+ return reordered.every((item, index) => item === siblings[index]);
+};
+
+export const replaceDragUndoOperation = <T>(operations: T[], operation: T, replacements: T[]) => {
+ const index = operations.indexOf(operation);
+ if (index < 0) {
+ return false;
+ }
+ operations.splice(index, 1, ...replacements);
+ return true;
+};
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index c305f92ec6..c3fd5b3888 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -53,7 +53,12 @@ import {clearSelect} from "./clear";
import {dragoverTab} from "../render/av/view";
import {setFold} from "./blockFold";
import {isEncryptedBox} from "../../util/pathName";
-import {isSameDragEditor, uniqueDragIds} from "./dragDocument";
+import {
+ isSameDragEditor,
+ isSameSiblingMove,
+ replaceDragUndoOperation,
+ uniqueDragIds
+} from "./dragDocument";
import {getAVFilteredTipContext, getAVViewID} from "../render/av/filteredTip";
import {getAVSelectedItemPoints, updateAVRowSelect} from "../render/av/virtualScroll";
import {setAVItemAnchor} from "../render/av/rangeSelect";
@@ -103,6 +108,24 @@ type TDragSourcePosition = {
parentID: string
};
+type TDragSourceContainerSnapshot = {
+ operation: IOperation,
+ placeholderID: string
+};
+
+const genDragListItemPlaceholder = (lute: Lute, subtype: string) => {
+ let marker = "*";
+ if (subtype === "o") {
+ marker = "1.";
+ } else if (subtype === "t") {
+ marker = "* [ ]";
+ }
+ const template = document.createElement("template");
+ // 零宽非连接符会被 Lute 保留,可确保占位列表项在事务处理中不会被规范化为空段落。
+ template.innerHTML = lute.Md2BlockDOM(`${marker} \u200C`);
+ return template.content.querySelector("[data-type='NodeListItem']");
+};
+
const getDragSourceParentID = async (protyle: IProtyle, element: Element) => {
const parentBlock = getParentBlock(element);
const parentID = parentBlock?.getAttribute("data-node-id");
@@ -249,6 +272,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
}
let copyElement;
+ let undoMoveOperation: IOperation;
if (isCopy) {
undoOperations.push({
action: "delete",
@@ -257,12 +281,13 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
} else {
// 用 DOM 移动前预捕获的源位置构造撤销操作,避免移动后 item 的父/兄弟已变导致撤销移到错误位置
const srcPos = sourcePositions.get(id) || {previousID: "", parentID};
- undoOperations.push({
+ undoMoveOperation = {
action: "move",
id,
previousID: srcPos.previousID,
parentID: srcPos.parentID,
- });
+ };
+ undoOperations.push(undoMoveOperation);
}
if (!isSameEditor && !isCopy) {
// 打开两个相同的文档
@@ -307,6 +332,42 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
} else {
let topSourceElement = getTopAloneElement(item);
const oldSourceParentElement = getParentBlock(item);
+ const sourceContainerSnapshots = new Map<Element, TDragSourceContainerSnapshot>();
+ if (topSourceElement !== item && item.getAttribute("data-type") === "NodeListItem") {
+ let sourceContainer = oldSourceParentElement;
+ while (sourceContainer) {
+ const sourceContainerID = sourceContainer.getAttribute("data-node-id");
+ if (sourceContainerID) {
+ const sourceContainerClone = sourceContainer.cloneNode(true) as Element;
+ const movedItemClone = sourceContainerClone.querySelector(`[data-node-id="${id}"]`);
+ if (movedItemClone) {
+ const placeholderElement = genDragListItemPlaceholder(
+ protyle.lute,
+ movedItemClone.getAttribute("data-subtype")
+ );
+ const placeholderID = placeholderElement?.getAttribute("data-node-id");
+ if (!placeholderElement || !placeholderID) {
+ break;
+ }
+ movedItemClone.replaceWith(placeholderElement);
+ sourceContainerSnapshots.set(sourceContainer, {
+ operation: {
+ action: "insert",
+ data: sourceContainerClone.outerHTML,
+ id: sourceContainerID,
+ previousID: getPreviousBlockSibling(sourceContainer)?.getAttribute("data-node-id"),
+ parentID: await getDragSourceParentID(protyle, sourceContainer)
+ },
+ placeholderID
+ });
+ }
+ }
+ if (sourceContainer === topSourceElement) {
+ break;
+ }
+ sourceContainer = getParentBlock(sourceContainer);
+ }
+ }
if (item.classList.contains("li") && item.getAttribute("data-subtype") === "o") {
orderListElements[item.parentElement.getAttribute("data-node-id")] = item.parentElement;
}
@@ -337,13 +398,26 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
action: "delete",
id: topSourceElement.getAttribute("data-node-id"),
});
- undoOperations.push({
- action: "insert",
- data: topSourceElement.outerHTML,
- id: topSourceElement.getAttribute("data-node-id"),
- previousID: getPreviousBlockSibling(topSourceElement)?.getAttribute("data-node-id"),
- parentID: getParentBlock(topSourceElement)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID
- });
+ const sourceContainerSnapshot = sourceContainerSnapshots.get(topSourceElement);
+ if (sourceContainerSnapshot && undoMoveOperation) {
+ // 使用占位列表项保持容器快照有效,撤销时恢复容器、移回原列表项,再删除占位项。
+ replaceDragUndoOperation(undoOperations, undoMoveOperation, [
+ {
+ action: "delete",
+ id: sourceContainerSnapshot.placeholderID,
+ },
+ undoMoveOperation,
+ sourceContainerSnapshot.operation
+ ]);
+ } else {
+ undoOperations.push({
+ action: "insert",
+ data: topSourceElement.outerHTML,
+ id: topSourceElement.getAttribute("data-node-id"),
+ previousID: getPreviousBlockSibling(topSourceElement)?.getAttribute("data-node-id"),
+ parentID: getParentBlock(topSourceElement)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID
+ });
+ }
const topSourceParentElement = topSourceElement.parentElement;
topSourceElement.remove();
if (!isSameEditor) {
@@ -687,6 +761,11 @@ const dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElemen
};
const dragSame = async (protyle: IProtyle, sourceElements: Element[], targetElement: Element, isBottom: boolean, isCopy: boolean) => {
+ const siblingElements = Array.from(targetElement.parentElement.children)
+ .filter(item => item.hasAttribute("data-node-id"));
+ if (!isCopy && isSameSiblingMove(siblingElements, sourceElements, targetElement, isBottom)) {
+ return;
+ }
const isSameEditor = isSameDragEditor(protyle.wysiwyg.element, sourceElements[0]);
const focusSourceElement = sourceElements[0];
const doOperations: IOperation[] = [];
diff --git a/kernel/model/undolog.go b/kernel/model/undolog.go
index 6e6b814f19..6d5e4713a6 100644
--- a/kernel/model/undolog.go
+++ b/kernel/model/undolog.go
@@ -25,6 +25,7 @@ import (
"github.com/88250/gulu"
"github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
"github.com/siyuan-note/siyuan/kernel/treenode"
)
@@ -371,6 +372,46 @@ var dataNodeIDPattern = regexp.MustCompile(`data-node-id="([^"]+)"`)
var refcountAttrPattern = regexp.MustCompile(`\s*refcount="[^"]*"`)
var refcountDivPattern = regexp.MustCompile(`<div class="protyle-attr--refcount[^"]*"[^>]*>.*?</div>`)
+func replaceReplayOperationID(operation *Operation, replacements map[string]string) (replaced bool) {
+ newID, replaced := replacements[operation.ID]
+ if !replaced {
+ return false
+ }
+ // insert 恢复的容器 ID 换新后,紧随其后的 update 也必须指向新容器;delete 仍保留旧 ID 以清理冲突块。
+ if "insert" == operation.Action || "update" == operation.Action {
+ operation.ID = newID
+ }
+ return true
+}
+
+func existingReplayBlockIDs(ids []string) map[string]bool {
+ ret := map[string]bool{}
+ blockTrees := treenode.GetBlockTrees(ids)
+ loadedTrees := map[string]*parse.Tree{}
+ loadFailed := map[string]bool{}
+ for _, id := range ids {
+ ret[id] = false
+ blockTree := blockTrees[id]
+ if nil == blockTree {
+ continue
+ }
+ key := blockTree.BoxID + "\x00" + blockTree.Path
+ tree, loaded := loadedTrees[key]
+ if !loaded && !loadFailed[key] {
+ var err error
+ tree, err = loadTreeByBlockTree(blockTree)
+ if nil != err || nil == tree {
+ // 无法读取时按存在处理,避免在不确定状态下引入重复 ID。
+ loadFailed[key] = true
+ } else {
+ loadedTrees[key] = tree
+ }
+ }
+ ret[id] = loadFailed[key] || nil != tree && nil != treenode.GetNodeInTree(tree, id)
+ }
+ return ret
+}
+
// ResolveReplayDuplicateIds 在 undo/redo 重放事务前解决块 ID 冲突。
// 场景:剪切块 X 后粘贴到别处(保留原 ID),再撤销剪切会 insert X,而 X 已存在于粘贴处,产生重复 ID。
// 这里对即将重放的 insert 操作做检查——若其引入的 ID 在块树中已存在,则在正反向操作及关联字段
@@ -416,7 +457,8 @@ func ResolveReplayDuplicateIds(tx *Transaction) {
for id := range ids {
idList = append(idList, id)
}
- exist := treenode.ExistBlockTrees(idList)
+ // blocktree 索引异步更新,立即撤销时可能仍残留已删除容器的记录,必须以当前 .sy 树为准。
+ exist := existingReplayBlockIDs(idList)
// 已存在的 ID 生成替换
replacements := map[string]string{}
@@ -429,21 +471,16 @@ func ResolveReplayDuplicateIds(tx *Transaction) {
return
}
- // 对 do/undo 两套操作统一替换 ID 及关联字段
+ // 对实际重放的操作统一替换 ID 及关联字段
apply := func(ops []*Operation) {
for _, op := range ops {
- // 记录本操作的 ID 是否被换新(在改 op.ID 之前判断,否则 replacements 的 key 是 oldID 查不到)
- _, idReplaced := replacements[op.ID]
- // 仅 insert 操作替换 op.ID。delete 操作声明的 ID 是待删除的旧块本身,若换为新 ID,
+ // 记录本操作的 ID 是否被换新,以便清除引用角标。
+ idReplaced := replaceReplayOperationID(op, replacements)
+ // delete 操作声明的 ID 是待删除的旧块本身,若换为新 ID,
// doDelete 会找不到节点而静默跳过,导致旧块残留并在重放后产生重复块。
// 典型场景:列表转段落后撤销——undo 先 delete 扁平化出的子块,再 insert 原列表
// (HTML 内联同一批子块 ID),这些子块会被前置 delete 清理,本不该参与冲突替换。
// https://github.com/siyuan-note/siyuan/issues/18012
- if "insert" == op.Action {
- if newID, ok := replacements[op.ID]; ok {
- op.ID = newID
- }
- }
if newID, ok := replacements[op.ParentID]; ok {
op.ParentID = newID
}
diff --git a/kernel/model/undolog_test.go b/kernel/model/undolog_test.go
new file mode 100644
index 0000000000..6f8fcefbf4
--- /dev/null
+++ b/kernel/model/undolog_test.go
@@ -0,0 +1,44 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import "testing"
+
+func TestReplaceReplayOperationID(t *testing.T) {
+ replacements := map[string]string{"old": "new"}
+ tests := []struct {
+ action string
+ want string
+ }{
+ {action: "insert", want: "new"},
+ {action: "update", want: "new"},
+ {action: "delete", want: "old"},
+ {action: "move", want: "old"},
+ }
+
+ for _, test := range tests {
+ t.Run(test.action, func(t *testing.T) {
+ operation := &Operation{Action: test.action, ID: "old"}
+ if !replaceReplayOperationID(operation, replacements) {
+ t.Fatal("expected replacement to be detected")
+ }
+ if operation.ID != test.want {
+ t.Fatalf("expected operation ID %q, got %q", test.want, operation.ID)
+ }
+ })
+ }
+}