Skip to content

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

:zap: Improve block move anchoring with nextID https://github.com/siyuan-note/siyuan/issues/19936

Daniel77c52244d210
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index ffefa529d1..f59aa75047 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -131,10 +131,27 @@ const getTargetListItem = (targetElement: Element, isBottom: boolean) => {
};
type TDragSourcePosition = {
+ nextID?: string,
previousID: string,
parentID: string
};
+const getDragSourceNextID = (element: Element, sources: Element[]) => {
+ let current = element;
+ while (current) {
+ let next = getNextBlockSibling(current);
+ // 折叠标题下辖块与其他源块都会移动,撤销锚点必须留在原容器中。
+ while (next && shouldUnfoldMovedHeading(current, next)) {
+ next = getNextBlockSibling(next);
+ }
+ if (!next || !sources.includes(next)) {
+ return next?.getAttribute("data-node-id") || "";
+ }
+ current = next;
+ }
+ return "";
+};
+
type TDragSourceContainerSnapshot = {
operation: IOperation,
placeholderID: string
@@ -221,6 +238,7 @@ const cancelDragSourceSB = async (nodeElement: Element, excludedChildIDs: Set<st
const wrapInRowSB = async (protyle: IProtyle, elements: Element[]) => {
const firstElement = elements[0];
const sourcePosition: TDragSourcePosition = {
+ nextID: getDragSourceNextID(firstElement, elements),
previousID: getPreviousBlockSibling(firstElement)?.getAttribute("data-node-id") || "",
parentID: await getDragSourceParentID(protyle, firstElement)
};
@@ -284,19 +302,6 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
.filter((id): id is string => !!id));
const targetId = targetElement.classList.contains("tab-item-content") ?
targetElement.parentElement.getAttribute("data-node-id") : targetElement.getAttribute("data-node-id");
- let targetPreviousID: string;
- // 聚焦视图首块的前一个同级块可能未渲染,必须从文档树取得真实位置。
- if (position === "beforebegin" && !getPreviousBlockSibling(targetElement) &&
- getParentBlock(targetElement) === protyle.wysiwyg.element && protyle.block.showAll) {
- const response = await fetchSyncPost("/api/block/getBlockRelevantIDs", {
- id: targetId,
- notebook: protyle.notebookId,
- });
- if (response.code !== 0) {
- throw new Error(response.msg);
- }
- targetPreviousID = response.data.previousID;
- }
const newSourceElements: Element[] = [];
let tempTargetElement = targetElement;
let isSameLi = true;
@@ -337,6 +342,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
const id = item.getAttribute("data-node-id");
if (id && !sourcePositions.has(id)) {
sourcePositions.set(id, {
+ nextID: getDragSourceNextID(item, sourceElements),
previousID: getPreviousBlockSibling(item)?.getAttribute("data-node-id") || "",
parentID: await getDragSourceParentID(protyle, item)
});
@@ -373,7 +379,8 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
action: "insert",
data: newListElement.outerHTML,
id: newListId,
- previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : getPreviousBlockSibling(tempTargetElement)?.getAttribute("data-node-id") || targetPreviousID),
+ nextID: position === "beforebegin" ? tempTargetElement.getAttribute("data-node-id") : undefined,
+ previousID: position === "afterend" ? targetId : undefined,
parentID: position === "afterbegin" ? targetId : (getParentBlock(tempTargetElement)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID),
});
undoOperations.push({
@@ -401,10 +408,11 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
});
} else {
// 用 DOM 移动前预捕获的源位置构造撤销操作,避免移动后 item 的父/兄弟已变导致撤销移到错误位置
- const srcPos = sourcePositions.get(id) || {previousID: "", parentID};
+ const srcPos = sourcePositions.get(id) || {nextID: "", previousID: "", parentID};
undoMoveOperation = {
action: "move",
id,
+ nextID: srcPos.nextID,
previousID: srcPos.previousID,
parentID: srcPos.parentID,
context: {moveGroupID},
@@ -451,7 +459,8 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
action: "insert",
id: copyNewId,
data: copyElement.outerHTML,
- previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : getPreviousBlockSibling(copyElement)?.getAttribute("data-node-id") || targetPreviousID), // 不能使用常量,移动后会被修改
+ nextID: position === "beforebegin" ? tempTargetElement.getAttribute("data-node-id") : undefined,
+ previousID: position === "afterend" ? targetId : undefined,
parentID: position === "afterbegin" ? targetId : (getParentBlock(copyElement)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID),
});
newSourceElements.push(copyElement);
@@ -523,7 +532,8 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
doOperations.push({
action: "move",
id,
- previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : getPreviousBlockSibling(item)?.getAttribute("data-node-id") || targetPreviousID), // 不能使用常量,移动后会被修改
+ nextID: position === "beforebegin" ? tempTargetElement.getAttribute("data-node-id") : undefined,
+ previousID: position === "afterend" ? targetId : undefined,
parentID: position === "afterbegin" ? targetId : (getParentBlock(item)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID),
context: {moveGroupID},
});
@@ -801,6 +811,9 @@ const dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElemen
wrapUndoOperations.splice(0, 0, ...targetWrap.undoOperations);
targetElement = targetWrap.element;
sourcePositions.forEach(position => {
+ if (position.nextID === targetID) {
+ position.nextID = targetElement.getAttribute("data-node-id");
+ }
if (position.previousID === targetID) {
position.previousID = targetElement.getAttribute("data-node-id");
}
@@ -973,6 +986,9 @@ const dragSame = async (protyle: IProtyle, sourceElements: Element[], targetElem
wrapUndoOperations.splice(0, 0, ...targetWrap.undoOperations);
targetElement = targetWrap.element;
sourcePositions.forEach(position => {
+ if (position.nextID === targetID) {
+ position.nextID = targetElement.getAttribute("data-node-id");
+ }
if (position.previousID === targetID) {
position.previousID = targetElement.getAttribute("data-node-id");
}
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 6fc12745b1..346aeb7cea 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -374,7 +374,14 @@ const promiseTransaction = (options: {
}
});
let hasFind = false;
- if (operation.previousID && updateElements.length > 0) {
+ if (operation.nextID && updateElements.length > 0) {
+ protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`).forEach(item => {
+ if (!isInEmbedBlock(item) && !item.contains(range.startContainer)) {
+ item.before(...cloneMoveElements(primaryMoveElements));
+ hasFind = true;
+ }
+ });
+ } else if (operation.previousID && updateElements.length > 0) {
Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => {
if (!isInEmbedBlock(item) && !getNextBlockSibling(item)?.contains(range.startContainer)) {
item.after(...cloneMoveElements(primaryMoveElements));
@@ -416,7 +423,7 @@ const promiseTransaction = (options: {
pendingEmbedElements.add(item);
});
// 移动块(含撤销移动)后刷新相关超级块的拖拽手柄,避免手柄残留/缺失
- const moveEls = [operation.id, operation.parentID, operation.previousID]
+ const moveEls = [operation.id, operation.parentID, operation.previousID, operation.nextID]
.map(id => id ? protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) : null)
.filter(Boolean) as Element[];
refreshSbs(...moveEls);
@@ -1224,7 +1231,14 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
originSbs.push(sb);
}
});
- if (operation.previousID && updateElements.length > 0) {
+ if (operation.nextID && updateElements.length > 0) {
+ protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`).forEach(item => {
+ if (!isInEmbedBlock(item)) {
+ item.before(...cloneMoveElements(primaryMoveElements));
+ hasFind = true;
+ }
+ });
+ } else if (operation.previousID && updateElements.length > 0) {
const previousElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`);
if (previousElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {
// 反链面板删除超级块中的最后一个段落块后撤销重做
@@ -1307,7 +1321,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
}
});
// 移动块(含重做/同步)后刷新相关超级块的拖拽手柄
- const moveEls = [operation.id, operation.parentID, operation.previousID]
+ const moveEls = [operation.id, operation.parentID, operation.previousID, operation.nextID]
.map(id => id ? protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) : null)
.filter(Boolean) as Element[];
refreshSbs(...moveEls);
diff --git a/app/src/protyle/wysiwyg/transactionEmbed.test.ts b/app/src/protyle/wysiwyg/transactionEmbed.test.ts
index 12654b7a57..b7c8c814d1 100644
--- a/app/src/protyle/wysiwyg/transactionEmbed.test.ts
+++ b/app/src/protyle/wysiwyg/transactionEmbed.test.ts
@@ -52,6 +52,11 @@ describe("getMoveAffectedEmbedElements", () => {
{id: "heading", blockIDs: ["heading-child"]},
), [embed]);
});
+
+ it("refreshes embeds containing only the next sibling anchor", () => {
+ const embed = asElement(new TestEmbedElement(["next"]));
+ assert.deepEqual(getMoveAffectedEmbedElements([embed], {id: "moved", nextID: "next"}), [embed]);
+ });
});
describe("shouldSyncMoveCopies", () => {
diff --git a/app/src/protyle/wysiwyg/transactionEmbed.ts b/app/src/protyle/wysiwyg/transactionEmbed.ts
index f884653d7f..f25926ecc2 100644
--- a/app/src/protyle/wysiwyg/transactionEmbed.ts
+++ b/app/src/protyle/wysiwyg/transactionEmbed.ts
@@ -1,9 +1,9 @@
export const getMoveAffectedEmbedElements = (
embedElements: Iterable<Element>,
- operation: Pick<IOperation, "id" | "blockIDs" | "parentID" | "previousID">,
+ operation: Pick<IOperation, "id" | "blockIDs" | "parentID" | "previousID" | "nextID">,
editingEmbedElement?: Element,
) => {
- const anchorIDs = [operation.id, operation.parentID, operation.previousID].filter(Boolean);
+ const anchorIDs = [operation.id, operation.parentID, operation.previousID, operation.nextID].filter(Boolean);
const blockIDs = new Set(operation.blockIDs || []);
if (anchorIDs.length === 0 && blockIDs.size === 0) {
return [];
diff --git a/app/tests/tabsDrag.test.js b/app/tests/tabsDrag.test.js
index 82d0c66bff..5d229c346c 100644
--- a/app/tests/tabsDrag.test.js
+++ b/app/tests/tabsDrag.test.js
@@ -17,8 +17,9 @@ const sources = () => {
}).outputText;
};
return [
- extract("protyle/util/editorCommonEvent.ts", ["getDragSourceParentID", "moveTo"]),
- extract("protyle/wysiwyg/getBlock.ts", ["getParentBlock", "getPreviousBlockSibling", "getTopAloneElement"]),
+ extract("protyle/util/editorCommonEvent.ts", ["getDragSourceParentID", "getDragSourceNextID", "moveTo"]),
+ extract("protyle/util/foldHeadingMove.ts", ["isFoldedHeading", "getHeadingLevel", "shouldUnfoldMovedHeading"]),
+ extract("protyle/wysiwyg/getBlock.ts", ["getParentBlock", "getPreviousBlockSibling", "getNextBlockSibling", "getTopAloneElement"]),
(() => {
const file = ts.createSourceFile("tabsRender.ts", readFileSync(path.join(__dirname,
"../src/protyle/render/tabsRender.ts"), "utf8"), ts.ScriptTarget.Latest, true);
@@ -69,8 +70,8 @@ const cases = async (source) => {
check.equal(data.notebook, "notebook");
return {code: 0, data: {previousID: "outside-focus", parentID: "doc"}};
};
- const {moveTo, bindTabsDrag, isDraggingTabs, syncBlockAttrs, tabsRender, destroyTabsRender} = new Function("Constants", "genEmptyElement", "root", "protyle", "fetchSyncPost", "remapListMindmapIDs",
- source + "; return {moveTo, bindTabsDrag, isDraggingTabs, syncBlockAttrs, tabsRender, destroyTabsRender};")(
+ const {moveTo, getDragSourceNextID, bindTabsDrag, isDraggingTabs, syncBlockAttrs, tabsRender, destroyTabsRender} = new Function("Constants", "genEmptyElement", "root", "protyle", "fetchSyncPost", "remapListMindmapIDs",
+ source + "; return {moveTo, getDragSourceNextID, bindTabsDrag, isDraggingTabs, syncBlockAttrs, tabsRender, destroyTabsRender};")(
constants, genEmptyElement, root, protyle, fetchSyncPost, () => {});
const list = document.createElement("div");
const button = document.createElement("button");
@@ -131,7 +132,9 @@ const cases = async (source) => {
template.innerHTML = lute.SpinBlockDOM(operation.data);
moving = template.content.firstElementChild;
}
- if (operation.previousID) {
+ if (operation.nextID) {
+ find(operation.nextID).before(moving);
+ } else if (operation.previousID) {
find(operation.previousID).after(moving);
} else {
find(operation.parentID).prepend(moving);
@@ -191,9 +194,12 @@ const cases = async (source) => {
const requestsBefore = relevantIDRequests;
const focusedMove = await moveTo(protyle, moving, heading, true, "beforebegin", copy);
const placements = focusedMove.doOperations.filter(op => op.action === (copy ? "insert" : "move"));
- check.equal(relevantIDRequests - requestsBefore, focused ? 1 : 0);
+ check.equal(relevantIDRequests - requestsBefore, 0);
check.equal(placements.length, count);
- placements.forEach(op => check.equal(op.previousID, focused ? "outside-focus" : undefined));
+ placements.forEach((op, i) => {
+ check.equal(op.previousID, undefined);
+ check.equal(op.nextID, i === 0 ? heading.dataset.nodeId : placements[i - 1].id);
+ });
check.equal(root.children[count], heading);
if (!copy) {
check.equal(focusedMove.undoOperations[0].previousID, heading.dataset.nodeId);
@@ -213,6 +219,22 @@ const cases = async (source) => {
}
}
}
+ for (const count of [1, 2]) {
+ root.innerHTML = lute.Md2BlockDOM(count === 1 ? "First\n\nTarget" : "First\n\nSecond\n\nTarget");
+ protyle.block.showAll = true;
+ stored.innerHTML = '<div data-node-id="outside-focus">Hidden predecessor</div>' + root.innerHTML;
+ const originalIDs = Array.from(stored.children).map(node => node.dataset.nodeId);
+ const target = root.lastElementChild;
+ const moving = Array.from(root.children).slice(0, count);
+ const operations = await moveTo(protyle, moving, target, true, "afterend", false);
+ operations.undoOperations.forEach(op => check.equal(op.nextID, target.dataset.nodeId));
+ replay(operations.doOperations);
+ replay(operations.undoOperations);
+ check.deepEqual(Array.from(stored.children).map(node => node.dataset.nodeId), originalIDs);
+ }
+ root.innerHTML = lute.Md2BlockDOM("## Heading\n\nChild\n\n### Nested\n\nNested child\n\n## Boundary");
+ root.firstElementChild.setAttribute("fold", "1");
+ check.equal(getDragSourceNextID(root.firstElementChild, [root.firstElementChild]), root.lastElementChild.dataset.nodeId);
root.remove();
return "Tabs drag cases passed";
};
diff --git a/kernel/api/contract_transaction_test.go b/kernel/api/contract_transaction_test.go
index e4a2c9f257..faa500c742 100644
--- a/kernel/api/contract_transaction_test.go
+++ b/kernel/api/contract_transaction_test.go
@@ -96,6 +96,7 @@ func TestTransactionContractMapping(t *testing.T) {
t.Fatal(err)
}
fixtures := []*model.Transaction{{Timestamp: 123, DoOperations: []*model.Operation{
+ {Action: "move", ID: "source", NextID: "next", PreviousID: "previous", ParentID: "parent", BlockIDs: []string{"child"}},
{Action: "update", Data: "<div>content</div>", Context: map[string]any{"focusId": "block"}},
{Action: "updateAttrViewCell", Data: map[string]any{"text": nil}},
{Action: "updateAttrViewCells", CellUpdates: []*model.AttrViewCellUpdate{{KeyID: "key", RowID: "item", Data: map[string]any{"number": map[string]any{"content": 1.5}}}}},
diff --git a/kernel/apicontract/transaction_types.go b/kernel/apicontract/transaction_types.go
index 470df918c7..91d833b91d 100644
--- a/kernel/apicontract/transaction_types.go
+++ b/kernel/apicontract/transaction_types.go
@@ -40,11 +40,13 @@ func (value TransactionOperationData) MarshalJSON() ([]byte, error) {
}
type TransactionOperationFields struct {
- Action string `json:"action" api:"optional,nullable"`
- ID string `json:"id" api:"optional,nullable"`
- RootID string `json:"rootID" api:"optional,nullable"`
- ParentID string `json:"parentID" api:"optional,nullable"`
- PreviousID string `json:"previousID" api:"optional,nullable"`
+ Action string `json:"action" api:"optional,nullable"`
+ ID string `json:"id" api:"optional,nullable"`
+ RootID string `json:"rootID" api:"optional,nullable"`
+ ParentID string `json:"parentID" api:"optional,nullable"`
+ PreviousID string `json:"previousID" api:"optional,nullable"`
+ // NextID 用于 insert、move 的前置同级锚点,优先于 previousID 和 parentID。
+ // move 保留源块及折叠标题下辖块的顺序,不将整列表自动解包为列表项。
NextID string `json:"nextID" api:"optional,nullable"`
BlockIDs []string `json:"blockIDs" api:"optional,nullable"`
BlockID string `json:"blockID" api:"optional,nullable"`
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 4a0d326209..1556374868 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -606,12 +606,17 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
logging.LogWarnf("%s [%s]", msg, id)
return &TxErr{code: TxErrCodePushMsg, msg: msg, id: id}
}
- if targetPreviousID := operation.PreviousID; "" != targetPreviousID {
- if targetBlockTree := treenode.GetBlockTree(targetPreviousID); nil != targetBlockTree &&
+ targetSiblingID := operation.NextID
+ moveBefore := "" != targetSiblingID
+ if !moveBefore {
+ targetSiblingID = operation.PreviousID
+ }
+ if "" != targetSiblingID {
+ if targetBlockTree := treenode.GetBlockTree(targetSiblingID); nil != targetBlockTree &&
treenode.TypeAbbr(ast.NodeDocument.String()) == targetBlockTree.Type {
- msg := "document blocks cannot be used as previous siblings"
- logging.LogWarnf("%s [%s]", msg, targetPreviousID)
- return &TxErr{code: TxErrCodePushMsg, msg: msg, id: targetPreviousID}
+ msg := "document blocks cannot be used as sibling anchors"
+ logging.LogWarnf("%s [%s]", msg, targetSiblingID)
+ return &TxErr{code: TxErrCodePushMsg, msg: msg, id: targetSiblingID}
}
}
@@ -634,18 +639,17 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
treenode.SetSelfFolded(srcNode, false)
}
- targetPreviousID := operation.PreviousID
targetParentID := operation.ParentID
- if "" != targetPreviousID {
- if id == targetPreviousID {
+ if "" != targetSiblingID {
+ if id == targetSiblingID {
return &TxErr{code: TxErrCodeSkipTx}
}
var targetTree *parse.Tree
- targetTree, err = tx.loadTree(targetPreviousID)
+ targetTree, err = tx.loadTree(targetSiblingID)
if err != nil {
- logging.LogErrorf("load tree [%s] failed: %s", targetPreviousID, err)
- return &TxErr{code: TxErrCodeBlockNotFound, id: targetPreviousID}
+ logging.LogErrorf("load tree [%s] failed: %s", targetSiblingID, err)
+ return &TxErr{code: TxErrCodeBlockNotFound, id: targetSiblingID}
}
isSameTree := srcTree.ID == targetTree.ID
if isSameTree {
@@ -657,18 +661,18 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
return &TxErr{code: TxErrCodeSkipTx}
}
- targetNode := treenode.GetNodeInTree(targetTree, targetPreviousID)
+ targetNode := treenode.GetNodeInTree(targetTree, targetSiblingID)
if nil == targetNode {
- logging.LogErrorf("get node [%s] in tree [%s] failed", targetPreviousID, targetTree.Root.ID)
- return &TxErr{code: TxErrCodeBlockNotFound, id: targetPreviousID}
+ logging.LogErrorf("get node [%s] in tree [%s] failed", targetSiblingID, targetTree.Root.ID)
+ return &TxErr{code: TxErrCodeBlockNotFound, id: targetSiblingID}
}
if ast.NodeDocument == targetNode.Type {
- msg := "document blocks cannot be used as previous siblings"
- logging.LogWarnf("%s [%s]", msg, targetPreviousID)
- return &TxErr{code: TxErrCodePushMsg, msg: msg, id: targetPreviousID}
+ msg := "document blocks cannot be used as sibling anchors"
+ logging.LogWarnf("%s [%s]", msg, targetSiblingID)
+ return &TxErr{code: TxErrCodePushMsg, msg: msg, id: targetSiblingID}
}
- if ast.NodeHeading == targetNode.Type && treenode.IsSelfFolded(targetNode) {
+ if !moveBefore && ast.NodeHeading == targetNode.Type && treenode.IsSelfFolded(targetNode) {
targetChildren := treenode.HeadingChildren(targetNode)
if l := len(targetChildren); 0 < l {
@@ -684,12 +688,12 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
return &TxErr{code: TxErrCodeSkipTx}
}
- if nil == operation.BlockIDs && 0 < len(headingChildren) {
+ if !moveBefore && nil == operation.BlockIDs && 0 < len(headingChildren) {
// 折叠标题再编辑形成外层列表(前面加上 * )时,前端给的 tx 序列会形成死循环,在这里解开
// Nested lists cause hang after collapsing headings https://github.com/siyuan-note/siyuan/issues/15943
lastChild := headingChildren[len(headingChildren)-1]
if ast.NodeList == lastChild.Type &&
- nil != lastChild.FirstChild && nil != lastChild.FirstChild.FirstChild && lastChild.FirstChild.FirstChild.ID == targetPreviousID {
+ nil != lastChild.FirstChild && nil != lastChild.FirstChild.FirstChild && lastChild.FirstChild.FirstChild.ID == targetSiblingID {
headingChildren = headingChildren[:len(headingChildren)-1]
}
}
@@ -698,27 +702,23 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
}
tx.markListItemFoldCandidate(srcParent, srcTree)
- for i := len(headingChildren) - 1; -1 < i; i-- {
- c := headingChildren[i]
- targetNode.InsertAfter(c)
+ if moveBefore {
+ // 先插入标题,再按原顺序插入下辖块,保持整个移动集合位于锚点之前。
+ targetNode.InsertBefore(srcNode)
+ for _, child := range headingChildren {
+ targetNode.InsertBefore(child)
+ }
+ } else {
+ for i := len(headingChildren) - 1; -1 < i; i-- {
+ targetNode.InsertAfter(headingChildren[i])
+ }
+ targetNode.InsertAfter(srcNode)
}
- targetNode.InsertAfter(srcNode)
if nil != srcEmptyList {
srcEmptyList.Unlink()
}
- treenode.RefreshUpdated(srcNode)
- tx.nodes[srcNode.ID] = srcNode
- tx.markStructureCheck(srcNode)
- for _, child := range headingChildren {
- tx.markStructureCheck(child)
- }
- treenode.RefreshUpdated(srcTree.Root)
- tx.writeTree(srcTree)
- if !isSameTree {
- tx.writeTree(targetTree)
- tx.recordCrossTreeMoveRefRefresh(srcTree, targetTree, srcNode, headingChildren)
- }
+ tx.finishMove(srcTree, targetTree, srcNode, headingChildren)
return
}
@@ -735,7 +735,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
if isSameTree {
targetTree = srcTree
}
- // 禁止跨加密边界移动块(同 doMove targetPreviousID 分支)
+ // 禁止跨加密边界移动块(同 doMove targetSiblingID 分支)
if !isSameTree && !IsSameCryptoBoundary(srcTree.Box, targetTree.Box) {
util.PushMsg(Conf.Language(391), 5000)
return &TxErr{code: TxErrCodeSkipTx}
@@ -800,6 +800,11 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
}
}
+ tx.finishMove(srcTree, targetTree, srcNode, headingChildren)
+ return
+}
+
+func (tx *Transaction) finishMove(srcTree, targetTree *parse.Tree, srcNode *ast.Node, headingChildren []*ast.Node) {
treenode.RefreshUpdated(srcNode)
tx.nodes[srcNode.ID] = srcNode
tx.markStructureCheck(srcNode)
@@ -808,11 +813,10 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
}
treenode.RefreshUpdated(srcTree.Root)
tx.writeTree(srcTree)
- if !isSameTree {
+ if srcTree.ID != targetTree.ID {
tx.writeTree(targetTree)
tx.recordCrossTreeMoveRefRefresh(srcTree, targetTree, srcNode, headingChildren)
}
- return
}
const moveGroupIDContextKey = "moveGroupID"
diff --git a/kernel/model/transaction_move_next_fts5_test.go b/kernel/model/transaction_move_next_fts5_test.go
new file mode 100644
index 0000000000..4c582feb50
--- /dev/null
+++ b/kernel/model/transaction_move_next_fts5_test.go
@@ -0,0 +1,130 @@
+//go:build fts5
+
+package model
+
+import (
+ "slices"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+func assertMoveNextOrder(t *testing.T, rootID string, ids ...string) {
+ t.Helper()
+ tree, err := LoadTreeByBlockID(rootID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var actual []string
+ for node := tree.Root.FirstChild; node != nil; node = node.Next {
+ if node.IsBlock() && node.Type != ast.NodeKramdownBlockIAL {
+ actual = append(actual, node.ID)
+ }
+ }
+ if !slices.Equal(actual, ids) {
+ t.Fatalf("block order: got %v, want %v", actual, ids)
+ }
+}
+
+func TestMoveNextIDOrderAndReplay(t *testing.T) {
+ for _, crossTree := range []bool{false, true} {
+ t.Run(map[bool]string{false: "same tree", true: "cross tree"}[crossTree], func(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ const (
+ outside = "20260928000001-outside"
+ anchor = "20260928000002-heading"
+ child = "20260928000003-child00"
+ boundary = "20260928000004-boundar"
+ first = "20260928000005-first00"
+ second = "20260928000006-second0"
+ end = "20260928000007-end0000"
+ )
+ heading := newFoldMoveTestHeading(anchor, 2)
+ targetID := fixture.sourceID
+ sourceNodes := []*ast.Node{treenode.NewParagraph(outside)}
+ targetNodes := []*ast.Node{heading, treenode.NewParagraph(child), newFoldMoveTestHeading(boundary, 2)}
+ if crossTree {
+ targetID = fixture.targetID
+ writeFoldMoveTestTree(t, targetID, targetNodes...)
+ } else {
+ sourceNodes = append(sourceNodes, targetNodes...)
+ }
+ sourceNodes = append(sourceNodes, treenode.NewParagraph(first), treenode.NewParagraph(second), treenode.NewParagraph(end))
+ writeFoldMoveTestTree(t, fixture.sourceID, sourceNodes...)
+ forward := &Transaction{DoOperations: []*Operation{
+ {Action: "move", ID: second, NextID: anchor, PreviousID: fixture.sourceID, ParentID: "missing"},
+ {Action: "move", ID: first, NextID: second, PreviousID: fixture.sourceID, ParentID: "missing"},
+ }, UndoOperations: []*Operation{
+ {Action: "move", ID: first, NextID: end},
+ {Action: "move", ID: second, NextID: end},
+ }}
+ for step := 0; step < 3; step++ {
+ tx := forward
+ if step == 1 {
+ tx = &Transaction{DoOperations: cloneOperations(forward.UndoOperations)}
+ tx.MarkReplay()
+ } else if step == 2 {
+ tx = &Transaction{DoOperations: cloneOperations(forward.DoOperations)}
+ tx.MarkReplay()
+ }
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatalf("step %d: %v", step, err)
+ }
+ if crossTree {
+ if step == 1 {
+ assertMoveNextOrder(t, fixture.sourceID, outside, first, second, end)
+ assertMoveNextOrder(t, targetID, anchor, child, boundary)
+ } else {
+ assertMoveNextOrder(t, fixture.sourceID, outside, end)
+ assertMoveNextOrder(t, targetID, first, second, anchor, child, boundary)
+ }
+ } else if step == 1 {
+ assertMoveNextOrder(t, targetID, outside, anchor, child, boundary, first, second, end)
+ } else {
+ assertMoveNextOrder(t, targetID, outside, first, second, anchor, child, boundary, end)
+ }
+ }
+ })
+ }
+}
+
+func TestMoveNextIDFoldedHeading(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ const (
+ heading = "20260928000101-heading"
+ first = "20260928000102-first00"
+ second = "20260928000103-second0"
+ boundary = "20260928000104-boundar"
+ anchor = "20260928000105-anchor0"
+ )
+ writeFoldMoveTestTree(t, fixture.sourceID, newFoldMoveTestHeading(heading, 2),
+ treenode.NewParagraph(first), treenode.NewParagraph(second), newFoldMoveTestHeading(boundary, 2))
+ writeFoldMoveTestTree(t, fixture.targetID, treenode.NewParagraph(anchor))
+ forward := &Transaction{DoOperations: []*Operation{{Action: "move", ID: heading, NextID: anchor,
+ Context: map[string]any{moveGroupIDContextKey: "next-heading"}}},
+ UndoOperations: []*Operation{{Action: "move", ID: heading, NextID: boundary,
+ Context: map[string]any{moveGroupIDContextKey: "next-heading"}}}}
+ if err := PerformTxSync(forward); err != nil {
+ t.Fatal(err)
+ }
+ assertMoveNextOrder(t, fixture.sourceID, boundary)
+ assertMoveNextOrder(t, fixture.targetID, heading, first, second, anchor)
+ if !slices.Equal(forward.DoOperations[0].BlockIDs, []string{first, second}) {
+ t.Fatal("folded move group was not captured")
+ }
+ undo := &Transaction{DoOperations: cloneOperations(forward.UndoOperations)}
+ undo.MarkReplay()
+ if err := PerformTxSync(undo); err != nil {
+ t.Fatal(err)
+ }
+ assertMoveNextOrder(t, fixture.sourceID, heading, first, second, boundary)
+ assertMoveNextOrder(t, fixture.targetID, anchor)
+ for _, target := range []string{heading, first} {
+ // 移向自身或下辖块不能破坏标题移动集合。
+ _ = PerformTxSync(&Transaction{DoOperations: []*Operation{{Action: "move", ID: heading, NextID: target}}})
+ assertMoveNextOrder(t, fixture.sourceID, heading, first, second, boundary)
+ }
+}
diff --git a/kernel/model/transaction_structure_test.go b/kernel/model/transaction_structure_test.go
index 38977cda41..682b0ebfe7 100644
--- a/kernel/model/transaction_structure_test.go
+++ b/kernel/model/transaction_structure_test.go
@@ -125,6 +125,12 @@ func TestMoveRejectsParagraphDirectlyUnderList(t *testing.T) {
return &Operation{Action: "move", ID: sourceID, ParentID: listID, PreviousID: itemID}
},
},
+ {
+ name: "next id",
+ operation: func(sourceID, listID, itemID string) *Operation {
+ return &Operation{Action: "move", ID: sourceID, ParentID: listID, NextID: itemID}
+ },
+ },
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {