Skip to content

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

:art: https://github.com/siyuan-note/siyuan/issues/18620

Vanessa7d13eb013936
diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.ts
index d236063f4b..8a98a316bd 100644
--- a/app/src/protyle/util/selection.ts
+++ b/app/src/protyle/util/selection.ts
@@ -18,6 +18,7 @@ import {countBlockWord, countSelectWord} from "../../layout/status";
import {hideElements} from "../ui/hideElements";
import {genRenderFrame} from "../render/util";
import {Constants} from "../../constants";
+import {getUndoFocusElement} from "./selectionFocus";
const selectIsEditor = (editor: Element, range?: Range) => {
if (!range) {
@@ -680,7 +681,7 @@ Record<string, string> | undefined => {
endRange.collapse(false);
const start = getSelectionOffset(startEditableElement, undefined, startRange, ignoreZWSP).start;
const end = getSelectionOffset(endEditableElement, undefined, endRange, ignoreZWSP).end;
- return {
+ const context: Record<string, string> = {
undoFocusId: startBlockElement.getAttribute("data-node-id"),
undoFocusIndex: startBlockElements.indexOf(startBlockElement).toString(),
undoFocusStart: start.toString(),
@@ -690,6 +691,11 @@ Record<string, string> | undefined => {
undoFocusEnd: end.toString(),
undoFocusIgnoreZWSP: ignoreZWSP.toString(),
};
+ const startEmbedElement = isInEmbedBlock(startBlockElement, false);
+ if (startEmbedElement && startEmbedElement === isInEmbedBlock(endBlockElement, false)) {
+ context.undoFocusEmbedId = startEmbedElement.getAttribute("data-node-id");
+ }
+ return context;
};
export const restoreFocusContext = (protyle: IProtyle, context: Record<string, string>) => {
@@ -698,22 +704,29 @@ export const restoreFocusContext = (protyle: IProtyle, context: Record<string, s
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < 0) {
return false;
}
- const startBlockElements = Array.from(protyle.wysiwyg.element.querySelectorAll(
+ const focusScopeElement = context.undoFocusEmbedId ? protyle.wysiwyg.element.querySelector(
+ `[data-type="NodeBlockQueryEmbed"][data-node-id="${context.undoFocusEmbedId}"]`
+ ) : protyle.wysiwyg.element;
+ if (!focusScopeElement) {
+ return false;
+ }
+ const startBlockElements = Array.from(focusScopeElement.querySelectorAll(
`[data-node-id="${context.undoFocusId}"]`
));
- const startIndex = Number(context.undoFocusIndex);
- const indexedStartElement = Number.isInteger(startIndex) && startIndex >= 0 ?
- startBlockElements[startIndex] : undefined;
- const startBlockElement = indexedStartElement ||
- startBlockElements.find(item => !isInEmbedBlock(item, false)) || startBlockElements[0];
+ const startBlockElement = getUndoFocusElement(
+ startBlockElements,
+ context.undoFocusIndex,
+ item => !isInEmbedBlock(item, false),
+ );
const endBlockElements = context.undoFocusEndId === context.undoFocusId ?
- startBlockElements : Array.from(protyle.wysiwyg.element.querySelectorAll(
+ startBlockElements : Array.from(focusScopeElement.querySelectorAll(
`[data-node-id="${context.undoFocusEndId || context.undoFocusId}"]`
));
- const endIndex = Number(context.undoFocusEndIndex);
- const indexedEndElement = Number.isInteger(endIndex) && endIndex >= 0 ? endBlockElements[endIndex] : undefined;
- const endBlockElement = indexedEndElement ||
- endBlockElements.find(item => !isInEmbedBlock(item, false)) || endBlockElements[0];
+ const endBlockElement = getUndoFocusElement(
+ endBlockElements,
+ context.undoFocusEndIndex,
+ item => !isInEmbedBlock(item, false),
+ );
if (!startBlockElement || !endBlockElement) {
return false;
}
diff --git a/app/src/protyle/util/selectionFocus.test.ts b/app/src/protyle/util/selectionFocus.test.ts
new file mode 100644
index 0000000000..920b0bccc3
--- /dev/null
+++ b/app/src/protyle/util/selectionFocus.test.ts
@@ -0,0 +1,17 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getUndoFocusElement} from "./selectionFocus";
+
+describe("getUndoFocusElement", () => {
+ it("uses the recorded duplicate index when it remains available", () => {
+ assert.equal(getUndoFocusElement(["source", "embed"], "1", item => item === "source"), "embed");
+ });
+
+ it("uses the target embed element when the global duplicate index is outside its scope", () => {
+ assert.equal(getUndoFocusElement(["embed"], "1", item => item === "source"), "embed");
+ });
+
+ it("does not fall back to another scope while the target embed is rendering", () => {
+ assert.equal(getUndoFocusElement([], "1", () => true), undefined);
+ });
+});
diff --git a/app/src/protyle/util/selectionFocus.ts b/app/src/protyle/util/selectionFocus.ts
new file mode 100644
index 0000000000..8ae08dfed3
--- /dev/null
+++ b/app/src/protyle/util/selectionFocus.ts
@@ -0,0 +1,9 @@
+export const getUndoFocusElement = <T>(
+ elements: T[],
+ indexValue: string | undefined,
+ isPreferred: (element: T) => boolean,
+) => {
+ const index = Number(indexValue);
+ const indexedElement = Number.isInteger(index) && index >= 0 ? elements[index] : undefined;
+ return indexedElement || elements.find(isPreferred) || elements[0];
+};
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 53e67d2055..19e60fd225 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -1,5 +1,12 @@
import {fetchPost, fetchSyncPost} from "../../util/fetch";
-import {focusBlock, focusByWbr, focusSideBlock, getEditorRange, getUndoFocusContext} from "../util/selection";
+import {
+ focusBlock,
+ focusByWbr,
+ focusSideBlock,
+ getEditorRange,
+ getUndoFocusContext,
+ restoreUndoFocus
+} from "../util/selection";
import {
getContenteditableElement,
getEmbedChildOperationContext,
@@ -39,6 +46,7 @@ import {
} from "../util/headingNumber";
import {MERMAID_LAYOUT_ATTR} from "../render/mermaidLayout";
import {getPartialUpdateCleanupElements} from "./transactionUpdate";
+import {getMoveAffectedEmbedElements, shouldSyncMoveCopies} from "./transactionEmbed";
const removeTopElement = (updateElement: Element, protyle: IProtyle) => {
// 移动到其他文档中,该块需移除
@@ -138,7 +146,10 @@ const promiseTransaction = (options: {
if (getSelection().rangeCount > 0) {
range = getSelection().getRangeAt(0);
}
- const isEmbedChildOperation = !!(range && getEmbedChildOperationContext(range.startContainer));
+ const embedChildOperationContext = range && getEmbedChildOperationContext(range.startContainer);
+ const isEmbedChildOperation = !!embedChildOperationContext;
+ const editingEmbedElement = embedChildOperationContext &&
+ (isInEmbedBlock(embedChildOperationContext.resultElement, false) || undefined);
if (!options.skipSync) {
options.doOperations.forEach((operation: IOperation) => {
if (operation.action === "update") {
@@ -225,7 +236,8 @@ const promiseTransaction = (options: {
return;
}
if (operation.action === "move") {
- if (protyle.options.backlinkData) {
+ // 反链和嵌入块编辑中存在同 ID 的普通副本,需同步回放移动操作
+ if (shouldSyncMoveCopies(!!protyle.options.backlinkData, isEmbedChildOperation)) {
const updateElements: Element[] = [];
Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {
if (!isInEmbedBlock(item)) {
@@ -278,11 +290,13 @@ const promiseTransaction = (options: {
// 块移出后刷新源超级块的手柄(originSb 在元素被移除前捕获)
refreshSbs(...originSbs);
}
- // 更新嵌入块
- protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {
- if (item.querySelector(`[data-node-id="${operation.id}"],[data-node-id="${operation.parentID}"],[data-node-id="${operation.previousID}"]`)) {
- pendingEmbedElements.add(item);
- }
+ // 当前编辑副本已由本地 DOM 操作更新,仅刷新其他受影响的嵌入块
+ getMoveAffectedEmbedElements(
+ protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]'),
+ operation,
+ editingEmbedElement,
+ ).forEach(item => {
+ pendingEmbedElements.add(item);
});
// 移动块(含撤销移动)后刷新相关超级块的拖拽手柄,避免手柄残留/缺失
const moveEls = [operation.id, operation.parentID, operation.previousID]
@@ -528,8 +542,9 @@ const refreshSbs = (...elements: (Element | undefined | null)[]) => {
sbs.forEach(sb => refreshSbResize(sb));
};
-const deleteBlock = (updateElements: Element[], id: string, protyle: IProtyle, isUndo: boolean) => {
- if (isUndo && updateElements[0]) {
+const deleteBlock = (updateElements: Element[], id: string, protyle: IProtyle, isUndo: boolean,
+ deferUndoFocus = false) => {
+ if (isUndo && updateElements[0] && !deferUndoFocus) {
focusSideBlock(updateElements[0]);
}
// 删除前记录所在超级块,删除后刷新其拖拽手柄
@@ -626,6 +641,12 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
if (protyle.wysiwyg.element.firstElementChild?.classList.contains("protyle-password")) {
return;
}
+ const undoFocusContext = isUndo ? operations.find(item => item.context?.undoFocusId)?.context : undefined;
+ const undoFocusEmbedElement = undoFocusContext?.undoFocusEmbedId ? protyle.wysiwyg.element.querySelector(
+ `[data-type="NodeBlockQueryEmbed"][data-node-id="${undoFocusContext.undoFocusEmbedId}"]`
+ ) : undefined;
+ const deferUndoFocus = !!undoFocusContext?.undoFocusEmbedId;
+ const pendingUndoEmbedElements = new Set<Element>();
operations.forEach(operation => {
const updateElements: Element[] = [];
Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {
@@ -713,7 +734,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
}
if (operation.action === "delete") {
if (updateElements.length > 0 || !isUndo) {
- deleteBlock(updateElements, operation.id, protyle, isUndo);
+ deleteBlock(updateElements, operation.id, protyle, isUndo, deferUndoFocus);
} else if (isUndo) {
zoomOut({
protyle,
@@ -726,7 +747,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
updateElements.push(item);
}
});
- deleteBlock(updateElements, operation.id, protyle, isUndo);
+ deleteBlock(updateElements, operation.id, protyle, isUndo, deferUndoFocus);
}
});
}
@@ -1048,8 +1069,13 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
// 更新嵌入块。undo 已由 kernel 执行事务后广播,查询能拿到最新数据,无竞态。
protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {
if (item.querySelector(`[data-node-id="${operation.id}"],[data-node-id="${operation.parentID}"],[data-node-id="${operation.previousID}"]`)) {
- item.removeAttribute("data-render");
- blockRender(protyle, item);
+ if (item === undoFocusEmbedElement) {
+ // 当前嵌入块需在撤销操作全部回放后渲染,否则中途移除选区会把光标带到源块
+ pendingUndoEmbedElements.add(item);
+ } else {
+ item.removeAttribute("data-render");
+ blockRender(protyle, item);
+ }
}
});
// 移动块(含重做/同步)后刷新相关超级块的拖拽手柄
@@ -1236,6 +1262,17 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
return;
}
});
+ pendingUndoEmbedElements.forEach(item => {
+ if (!item.isConnected) {
+ return;
+ }
+ item.removeAttribute("data-render");
+ blockRender(protyle, item, undefined, () => {
+ if (restoreUndoFocus(protyle, operations)) {
+ scrollCenter(protyle);
+ }
+ });
+ });
queueHeadingNumberRefresh(protyle, operations);
};
diff --git a/app/src/protyle/wysiwyg/transactionEmbed.test.ts b/app/src/protyle/wysiwyg/transactionEmbed.test.ts
new file mode 100644
index 0000000000..6b5c43a83a
--- /dev/null
+++ b/app/src/protyle/wysiwyg/transactionEmbed.test.ts
@@ -0,0 +1,50 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getMoveAffectedEmbedElements, shouldSyncMoveCopies} from "./transactionEmbed";
+
+class TestEmbedElement {
+ constructor(private nodeIDs: string[]) {
+ }
+
+ querySelector(selector: string) {
+ const ids = Array.from(selector.matchAll(/\[data-node-id="([^"]+)"\]/g), match => match[1]);
+ return ids.some(id => this.nodeIDs.includes(id)) ? {} : null;
+ }
+}
+
+const asElement = (element: TestEmbedElement) => element as unknown as Element;
+
+describe("getMoveAffectedEmbedElements", () => {
+ it("preserves the locally updated embed while refreshing other affected copies", () => {
+ const editingEmbed = asElement(new TestEmbedElement(["moved", "parent"]));
+ const otherEmbed = asElement(new TestEmbedElement(["parent"]));
+ const unrelatedEmbed = asElement(new TestEmbedElement(["unrelated"]));
+
+ const result = getMoveAffectedEmbedElements(
+ [editingEmbed, otherEmbed, unrelatedEmbed],
+ {id: "moved", parentID: "parent", previousID: "previous"},
+ editingEmbed,
+ );
+
+ assert.deepEqual(result, [otherEmbed]);
+ });
+
+ it("matches the previous block when the destination parent is outside the embed", () => {
+ const embed = asElement(new TestEmbedElement(["previous"]));
+
+ assert.deepEqual(getMoveAffectedEmbedElements(
+ [embed],
+ {id: "moved", previousID: "previous"},
+ ), [embed]);
+ });
+});
+
+describe("shouldSyncMoveCopies", () => {
+ it("replays moves in normal copies when editing an embed", () => {
+ assert.equal(shouldSyncMoveCopies(false, true), true);
+ });
+
+ it("keeps ordinary document moves local", () => {
+ assert.equal(shouldSyncMoveCopies(false, false), false);
+ });
+});
diff --git a/app/src/protyle/wysiwyg/transactionEmbed.ts b/app/src/protyle/wysiwyg/transactionEmbed.ts
new file mode 100644
index 0000000000..d6fb5dd671
--- /dev/null
+++ b/app/src/protyle/wysiwyg/transactionEmbed.ts
@@ -0,0 +1,16 @@
+export const getMoveAffectedEmbedElements = (
+ embedElements: Iterable<Element>,
+ operation: Pick<IOperation, "id" | "parentID" | "previousID">,
+ editingEmbedElement?: Element,
+) => {
+ const ids = [operation.id, operation.parentID, operation.previousID].filter(Boolean);
+ if (ids.length === 0) {
+ return [];
+ }
+ const selector = ids.map(id => `[data-node-id="${id}"]`).join(",");
+ return Array.from(embedElements).filter(item =>
+ item !== editingEmbedElement && !!item.querySelector(selector));
+};
+
+export const shouldSyncMoveCopies = (isBacklink: boolean, isEmbedChildOperation: boolean) =>
+ isBacklink || isEmbedChildOperation;