Skip to content

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

:bug: Remove redundant super blocks after cross-window dragging https://github.com/siyuan-note/siyuan/issues/11815

Daniel1d9589e363d0
diff --git a/app/src/block/cancelSuperBlock.test.ts b/app/src/block/cancelSuperBlock.test.ts
index e846f82ec5..c4392e2a54 100644
--- a/app/src/block/cancelSuperBlock.test.ts
+++ b/app/src/block/cancelSuperBlock.test.ts
@@ -1,6 +1,6 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {buildCancelSuperBlockOperations} from "./cancelSuperBlock";
+import {appendCancelSuperBlockOperations, buildCancelSuperBlockOperations} from "./cancelSuperBlock";
describe("buildCancelSuperBlockOperations", () => {
it("moves every direct child with stable forward and undo anchors", () => {
@@ -78,3 +78,31 @@ describe("buildCancelSuperBlockOperations", () => {
assert.equal(result.undoOperations.some(operation => operation.id === "outside"), false);
});
});
+
+describe("appendCancelSuperBlockOperations", () => {
+ it("keeps cancellation before restoring the dragged block during undo", () => {
+ const doOperations = [{action: "move", id: "dragged"}] as IOperation[];
+ const undoOperations = [{action: "move", id: "dragged"}] as IOperation[];
+ appendCancelSuperBlockOperations(doOperations, undoOperations, {
+ doOperations: [
+ {action: "move", id: "remaining"},
+ {action: "delete", id: "super-block"},
+ ],
+ undoOperations: [
+ {action: "insert", id: "super-block"},
+ {action: "move", id: "remaining"},
+ ],
+ });
+
+ assert.deepEqual(doOperations.map(operation => `${operation.action}:${operation.id}`), [
+ "move:dragged",
+ "move:remaining",
+ "delete:super-block",
+ ]);
+ assert.deepEqual(undoOperations.reverse().map(operation => `${operation.action}:${operation.id}`), [
+ "insert:super-block",
+ "move:remaining",
+ "move:dragged",
+ ]);
+ });
+});
diff --git a/app/src/block/cancelSuperBlock.ts b/app/src/block/cancelSuperBlock.ts
index a5d76c4708..3b68f4a1f6 100644
--- a/app/src/block/cancelSuperBlock.ts
+++ b/app/src/block/cancelSuperBlock.ts
@@ -47,3 +47,12 @@ export const buildCancelSuperBlockOperations = (options: TCancelSuperBlockOperat
];
return {doOperations, undoOperations};
};
+
+export const appendCancelSuperBlockOperations = (
+ doOperations: IOperation[], undoOperations: IOperation[],
+ cancelOperations: {doOperations: IOperation[], undoOperations: IOperation[]}
+) => {
+ doOperations.push(...cancelOperations.doOperations);
+ // moveTo 会在返回前反转撤销数组,因此这里先按相反顺序压入。
+ undoOperations.push(...[...cancelOperations.undoOperations].reverse());
+};
diff --git a/app/src/block/util.ts b/app/src/block/util.ts
index 28ce9d977c..eedb3ff4eb 100644
--- a/app/src/block/util.ts
+++ b/app/src/block/util.ts
@@ -21,45 +21,52 @@ import {buildCancelSuperBlockOperations} from "./cancelSuperBlock";
import {shouldFocusJumpTarget, shouldFocusParentDocumentTitle} from "./jumpToParent";
import {getHorizontalSuperBlockChild} from "./superBlock";
-export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?: Range) => {
- let previousId = getPreviousBlockSibling(nodeElement)?.getAttribute("data-node-id");
- nodeElement.classList.remove("protyle-wysiwyg--select");
- nodeElement.removeAttribute("select-start");
- nodeElement.removeAttribute("select-end");
+export const getCancelSBOperations = async (nodeElement: Element, options: {
+ notebookID?: string,
+ previousID?: string,
+ parentID?: string,
+ fallbackParentID?: string,
+ resolveMissingPosition?: boolean,
+ excludedChildIDs?: Set<string>,
+}) => {
const id = nodeElement.getAttribute("data-node-id");
- const visibleChildElements = Array.from(nodeElement.children).filter(item => item.hasAttribute("data-node-id"));
+ const visibleChildElements = Array.from(nodeElement.children).filter(item =>
+ item.hasAttribute("data-node-id") && !options.excludedChildIDs?.has(item.getAttribute("data-node-id")));
let operationChildElements = visibleChildElements;
if (visibleChildElements.some(item => item.getAttribute("data-type") === "NodeHeading" &&
item.getAttribute("fold") === "1")) {
const response = await fetchSyncPost("/api/block/getBlockDOM", {
id,
- notebook: protyle.notebookId,
+ notebook: options.notebookID,
});
const template = document.createElement("template");
template.innerHTML = response.data?.dom || "";
const fullSuperBlockElement = template.content.querySelector(`[data-node-id="${id}"]`);
if (!fullSuperBlockElement) {
- return {doOperations: [], undoOperations: [], previousId};
+ return {doOperations: [], undoOperations: [], previousId: options.previousID};
}
operationChildElements = Array.from(fullSuperBlockElement.children).filter(item =>
- item.hasAttribute("data-node-id"));
+ item.hasAttribute("data-node-id") && !options.excludedChildIDs?.has(item.getAttribute("data-node-id")));
}
- // 先清理拖拽手柄,避免手柄被克隆进撤销用的 SB 副本,导致恢复后残留多余手柄
- nodeElement.querySelectorAll(".sb__resize").forEach(handle => handle.remove());
const sbElement = nodeElement.cloneNode() as HTMLElement;
sbElement.innerHTML = nodeElement.lastElementChild.outerHTML;
- let parentID = getEmbedChildOperationParentID(nodeElement) || getParentBlock(nodeElement)?.getAttribute("data-node-id");
+ let previousId = options.previousID;
+ if (typeof previousId !== "string") {
+ previousId = getPreviousBlockSibling(nodeElement)?.getAttribute("data-node-id");
+ }
+ let parentID = options.parentID || getEmbedChildOperationParentID(nodeElement) ||
+ getParentBlock(nodeElement)?.getAttribute("data-node-id");
// 缩放和反链需要接口获取
if (!previousId && !parentID) {
- if (protyle.block.showAll || protyle.options.backlinkData) {
+ if (options.resolveMissingPosition) {
const idData = await fetchSyncPost("/api/block/getBlockSiblingID", {
id,
- notebook: protyle.notebookId,
+ notebook: options.notebookID,
});
previousId = idData.data.previous;
parentID = idData.data.parent;
} else {
- parentID = protyle.block.rootID;
+ parentID = options.fallbackParentID;
}
}
const operationData = buildCancelSuperBlockOperations({
@@ -73,6 +80,26 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:
parentID,
});
const focusId = visibleChildElements[visibleChildElements.length - 1]?.getAttribute("data-node-id") || previousId;
+ return {
+ ...operationData,
+ previousId: focusId
+ };
+};
+
+export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?: Range) => {
+ nodeElement.classList.remove("protyle-wysiwyg--select");
+ nodeElement.removeAttribute("select-start");
+ nodeElement.removeAttribute("select-end");
+ const operationData = await getCancelSBOperations(nodeElement, {
+ notebookID: protyle.notebookId,
+ fallbackParentID: protyle.block.rootID,
+ resolveMissingPosition: protyle.block.showAll || !!protyle.options.backlinkData,
+ });
+ if (operationData.doOperations.length === 0) {
+ return operationData;
+ }
+ // 先清理拖拽手柄,避免手柄被移到超级块外部。
+ nodeElement.querySelectorAll(".sb__resize").forEach(handle => handle.remove());
if (range) {
getContenteditableElement(nodeElement)?.insertAdjacentHTML("afterbegin", "<wbr>");
}
@@ -90,10 +117,7 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:
blockRender(protyle, element);
}
});
- return {
- ...operationData,
- previousId: focusId
- };
+ return operationData;
};
export const genSBElement = (layout: string, id?: string, attrHTML?: string) => {
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 6a454e97de..4fc17677b9 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -62,6 +62,7 @@ import {
} from "../../block/util";
import {getHorizontalSuperBlockChild} from "../../block/superBlock";
import {setDragTipGhost} from "../util/dragTip";
+import {stringifyBlockDragData} from "../util/dragDocument";
import {countBlockWord} from "../../layout/status";
import {Constants} from "../../constants";
import {mathRender} from "../render/mathRender";
@@ -326,7 +327,11 @@ export class Gutter {
}
window.siyuan.dragElement = avElement as HTMLElement || protyle.wysiwyg.element;
event.dataTransfer.setData(`${Constants.SIYUAN_DROP_GUTTER}${buttonElement.getAttribute("data-type")}${Constants.ZWSP}${buttonElement.getAttribute("data-subtype")}${Constants.ZWSP}${selectIds}${Constants.ZWSP}${window.siyuan.config.system.workspaceDir}`,
- protyle.wysiwyg.element.innerHTML);
+ stringifyBlockDragData({
+ html: protyle.wysiwyg.element.innerHTML,
+ notebookID: protyle.notebookId,
+ rootID: protyle.block.rootID,
+ }));
isGutterDragging = true;
dragCleanupController?.abort();
const cleanupController = new AbortController();
diff --git a/app/src/protyle/util/dragDocument.test.ts b/app/src/protyle/util/dragDocument.test.ts
index 92bc46e4c9..7ce5912907 100644
--- a/app/src/protyle/util/dragDocument.test.ts
+++ b/app/src/protyle/util/dragDocument.test.ts
@@ -12,8 +12,10 @@ import {
isDragTargetInSource,
isSameDragEditor,
isSameSiblingMove,
+ parseBlockDragData,
replaceDragUndoOperation,
shouldKeepListBlockDragTarget,
+ stringifyBlockDragData,
uniqueDragIds
} from "./dragDocument";
@@ -89,6 +91,30 @@ describe("isSameDragEditor", () => {
});
});
+describe("block drag data", () => {
+ it("preserves the source editor context", () => {
+ const value = stringifyBlockDragData({
+ html: "<div>content</div>",
+ notebookID: "notebook",
+ rootID: "root",
+ });
+
+ assert.deepEqual(parseBlockDragData(value), {
+ html: "<div>content</div>",
+ notebookID: "notebook",
+ rootID: "root",
+ });
+ });
+
+ it("accepts the raw HTML used by older windows", () => {
+ assert.deepEqual(parseBlockDragData("<div>content</div>"), {
+ html: "<div>content</div>",
+ notebookID: "",
+ rootID: "",
+ });
+ });
+});
+
describe("getBlockDragoverTarget", () => {
it("uses the visible indicator when the cached target is stale", () => {
const cachedTarget = createDragoverTarget(false);
diff --git a/app/src/protyle/util/dragDocument.ts b/app/src/protyle/util/dragDocument.ts
index 0715c0a9da..eac18cede0 100644
--- a/app/src/protyle/util/dragDocument.ts
+++ b/app/src/protyle/util/dragDocument.ts
@@ -2,6 +2,37 @@ export const isSameDragEditor = (targetEditor: Pick<Element, "contains">, source
return targetEditor.contains(sourceElement);
};
+export type TBlockDragData = {
+ html: string,
+ notebookID: string,
+ rootID: string,
+};
+
+export const stringifyBlockDragData = (data: TBlockDragData) => JSON.stringify({
+ version: 1,
+ ...data,
+});
+
+export const parseBlockDragData = (value: string): TBlockDragData => {
+ try {
+ const data = JSON.parse(value);
+ if (data?.version === 1 && typeof data.html === "string") {
+ return {
+ html: data.html,
+ notebookID: typeof data.notebookID === "string" ? data.notebookID : "",
+ rootID: typeof data.rootID === "string" ? data.rootID : "",
+ };
+ }
+ } catch {
+ // 兼容旧版窗口传递的原始 HTML。
+ }
+ return {
+ html: value,
+ notebookID: "",
+ rootID: "",
+ };
+};
+
export const BLOCK_DRAGOVER_SELECTOR = [
".dragover__left",
".dragover__right",
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index 04c918cc27..d5b7e3c537 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -22,6 +22,7 @@ import {
cancelSB,
genEmptyElement,
genSBElement,
+ getCancelSBOperations,
insertEmptyBlock,
refreshSbAndPersistWidth,
refreshSbResize
@@ -66,6 +67,7 @@ import {
isDragTargetInSource,
isSameDragEditor,
isSameSiblingMove,
+ parseBlockDragData,
replaceDragUndoOperation,
shouldKeepListBlockDragTarget,
uniqueDragIds
@@ -75,9 +77,12 @@ import {getAVData, getAVPreviousItemID, getAVSelectedItemPoints, updateAVRowSele
import {setAVItemAnchor} from "../render/av/rangeSelect";
import {getCaretRect} from "./caretRect";
import {isBlockRefDropTargetDisabled} from "./blockRefDrop";
+import {appendCancelSuperBlockOperations} from "../../block/cancelSuperBlock";
const KANBAN_GROUP_DRAG_TYPE = `${Constants.SIYUAN_DROP_GUTTER}NodeAttributeView${Constants.ZWSP}Group${Constants.ZWSP}`;
const SHIFT_EMBED_INSERT_TARGET_TYPES = ["NodeParagraph", "NodeHeading", "NodeCodeBlock", "NodeAttributeView"];
+const DRAG_SOURCE_NOTEBOOK_ID = "data-drag-source-notebook-id";
+const DRAG_SOURCE_ROOT_ID = "data-drag-source-root-id";
const convertListItemSubtype = (listItem: Element, subtype: string) => {
const actionElement = listItem.querySelector(".protyle-action");
@@ -153,12 +158,51 @@ const getDragSourceParentID = async (protyle: IProtyle, element: Element) => {
if (sourceRootID) {
return sourceRootID;
}
+ const dragSourceElement = element.closest(`[${DRAG_SOURCE_ROOT_ID}]`);
+ sourceRootID = dragSourceElement?.getAttribute(DRAG_SOURCE_ROOT_ID) || "";
+ if (sourceRootID) {
+ return sourceRootID;
+ }
const response = await fetchSyncPost("/api/block/getBlockInfo", {
- id: element.getAttribute("data-node-id")
+ id: element.getAttribute("data-node-id"),
+ notebook: dragSourceElement?.getAttribute(DRAG_SOURCE_NOTEBOOK_ID) || "",
});
return response?.data?.rootID || "";
};
+const cancelDetachedSourceSB = async (nodeElement: Element, excludedChildIDs: Set<string>) => {
+ const sourceElement = nodeElement.closest(`[${DRAG_SOURCE_ROOT_ID}]`);
+ const notebookID = sourceElement?.getAttribute(DRAG_SOURCE_NOTEBOOK_ID) || "";
+ const relevantIDs = await fetchSyncPost("/api/block/getBlockRelevantIDs", {
+ id: nodeElement.getAttribute("data-node-id"),
+ notebook: notebookID,
+ });
+ const operationData = await getCancelSBOperations(nodeElement, {
+ notebookID,
+ previousID: relevantIDs?.data?.previousID,
+ parentID: relevantIDs?.data?.parentID || sourceElement?.getAttribute(DRAG_SOURCE_ROOT_ID) || "",
+ fallbackParentID: sourceElement?.getAttribute(DRAG_SOURCE_ROOT_ID) || "",
+ excludedChildIDs,
+ });
+ if (operationData.doOperations.length > 0) {
+ nodeElement.querySelectorAll(".sb__resize").forEach(handle => handle.remove());
+ nodeElement.lastElementChild.remove();
+ nodeElement.replaceWith(...nodeElement.children);
+ }
+ return operationData;
+};
+
+const cancelDragSourceSB = async (nodeElement: Element, excludedChildIDs: Set<string>) => {
+ /// #if !MOBILE
+ const sourceProtyleElement = hasClosestByClassName(nodeElement, "protyle", true);
+ const sourceEditor = getAllEditor().find(item => item.protyle.element === sourceProtyleElement);
+ if (sourceEditor) {
+ return cancelSB(sourceEditor.protyle, nodeElement);
+ }
+ /// #endif
+ return cancelDetachedSourceSB(nodeElement, excludedChildIDs);
+};
+
const wrapInRowSB = async (protyle: IProtyle, elements: Element[]) => {
const firstElement = elements[0];
const sourcePosition: TDragSourcePosition = {
@@ -221,6 +265,8 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
const doOperations: IOperation[] = [];
const undoOperations: IOperation[] = [];
const copyFoldHeadingIds: { newId: string, oldId: string }[] = [];
+ const removedSourceIDs = new Set(sourceElements.map(item => item.getAttribute("data-node-id"))
+ .filter((id): id is string => !!id));
const targetId = targetElement.getAttribute("data-node-id");
const newSourceElements: Element[] = [];
let tempTargetElement = targetElement;
@@ -440,6 +486,10 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
});
}
const topSourceParentElement = topSourceElement.parentElement;
+ const topSourceID = topSourceElement.getAttribute("data-node-id");
+ if (topSourceID) {
+ removedSourceIDs.add(topSourceID);
+ }
topSourceElement.remove();
if (!isSameEditor) {
// 打开两个相同的文档
@@ -452,44 +502,20 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
// 拖拽后,sb 只剩下一个元素
if (isSameEditor) {
const sbData = await cancelSB(protyle, topSourceParentElement);
- doOperations.push(sbData.doOperations[0], sbData.doOperations[1]);
- undoOperations.push(sbData.undoOperations[1], sbData.undoOperations[0]);
+ appendCancelSuperBlockOperations(doOperations, undoOperations, sbData);
} else {
- /// #if !MOBILE
- const allEditor = getAllEditor();
- const sourceProtyleElement = hasClosestByClassName(topSourceParentElement, "protyle", true);
- for (let i = 0; i < allEditor.length; i++) {
- if (allEditor[i].protyle.element === sourceProtyleElement) {
- const otherSbData = await cancelSB(allEditor[i].protyle, topSourceParentElement);
- doOperations.push(otherSbData.doOperations[0], otherSbData.doOperations[1]);
- undoOperations.push(otherSbData.undoOperations[1], otherSbData.undoOperations[0]);
- // 全局撤销栈下跨文档移动为可逆条目,无需清空源编辑器历史
- break;
- }
- }
- /// #endif
+ const sbData = await cancelDragSourceSB(topSourceParentElement, removedSourceIDs);
+ appendCancelSuperBlockOperations(doOperations, undoOperations, sbData);
}
}
} else if (oldSourceParentElement.classList.contains("sb") && getSbChildBlockCount(oldSourceParentElement) === 1) {
// 拖拽后,sb 只剩下一个元素
if (isSameEditor) {
const sbData = await cancelSB(protyle, oldSourceParentElement);
- doOperations.push(sbData.doOperations[0], sbData.doOperations[1]);
- undoOperations.push(sbData.undoOperations[1], sbData.undoOperations[0]);
+ appendCancelSuperBlockOperations(doOperations, undoOperations, sbData);
} else {
- /// #if !MOBILE
- const allEditor = getAllEditor();
- const sourceProtyleElement = hasClosestByClassName(oldSourceParentElement, "protyle", true);
- for (let i = 0; i < allEditor.length; i++) {
- if (allEditor[i].protyle.element === sourceProtyleElement) {
- const otherSbData = await cancelSB(allEditor[i].protyle, oldSourceParentElement);
- doOperations.push(otherSbData.doOperations[0], otherSbData.doOperations[1]);
- undoOperations.push(otherSbData.undoOperations[1], otherSbData.undoOperations[0]);
- // 全局撤销栈下跨文档移动为可逆条目,无需清空源编辑器历史
- break;
- }
- }
- /// #endif
+ const sbData = await cancelDragSourceSB(oldSourceParentElement, removedSourceIDs);
+ appendCancelSuperBlockOperations(doOperations, undoOperations, sbData);
}
} else if (oldSourceParentElement.classList.contains("protyle-wysiwyg") && oldSourceParentElement.childElementCount === 0) {
/// #if !MOBILE
@@ -1506,9 +1532,12 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
} else if (window.siyuan.config.system.workspaceDir.toLowerCase() === gutterTypes[3]) {
// 跨窗口拖拽
// 不能跨工作区域拖拽 https://github.com/siyuan-note/siyuan/issues/13582
- const targetProtyleElement = document.createElement("template");
- targetProtyleElement.innerHTML = `<div>${event.dataTransfer.getData(gutterType)}</div>`;
- targetProtyleElement.content.querySelectorAll(queryClass.substring(0, queryClass.length - 1)).forEach(elementItem => {
+ const dragData = parseBlockDragData(event.dataTransfer.getData(gutterType));
+ const sourceProtyleElement = document.createElement("div");
+ sourceProtyleElement.setAttribute(DRAG_SOURCE_NOTEBOOK_ID, dragData.notebookID);
+ sourceProtyleElement.setAttribute(DRAG_SOURCE_ROOT_ID, dragData.rootID);
+ sourceProtyleElement.innerHTML = dragData.html;
+ sourceProtyleElement.querySelectorAll(queryClass.substring(0, queryClass.length - 1)).forEach(elementItem => {
appendSourceElement(elementItem);
});
}