Skip to content

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

:bug: Correct database boundary navigation and embedded selection restoration https://github.com/siyuan-note/siyuan/issues/19184

Daniel5b4dd9d300b9
diff --git a/app/scripts/navigationLifecycle.cases.js b/app/scripts/navigationLifecycle.cases.js
index 437d4be9c2..366e48a976 100644
--- a/app/scripts/navigationLifecycle.cases.js
+++ b/app/scripts/navigationLifecycle.cases.js
@@ -137,6 +137,30 @@ module.exports = async () => {
cases++;
}
}
+ for (const count of [1, 2, 3]) {
+ const {protyle, editor} = setup(Array.from({length: count}, (_, i) =>
+ `<div data-type="NodeBlockQueryEmbed" data-node-id="outer${i}"><div data-node-id="container">
+ <div data-type="NodeBlockQueryEmbed" data-node-id="embed">${p("same", "copy" + i)}</div>
+ </div></div>`).join(""));
+ const copies = Array.from(editor.querySelectorAll('[data-node-id="same"]'));
+ copies.forEach((expected, index) => {
+ const context = {undoFocusId: "same", undoFocusEndId: "same", undoFocusStart: "0", undoFocusEnd: "0",
+ undoFocusIndex: String(index), undoFocusEndIndex: String(index), undoFocusEmbedId: "embed"};
+ const restore = load("util/restoreNavigationFocus").restoreFocusContext;
+ assert.equal(restore(protyle, context), true);
+ assert.equal(window.restoredFocusElement, expected);
+ assert.equal(restore(protyle, {...context, undoFocusEmbedId: "outer" + index}), false);
+ if (count > 1) {
+ assert.equal(restore(protyle, {...context, undoFocusEndIndex: String((index + 1) % count)}), false);
+ }
+ cases++;
+ });
+ copies.at(-1).parentElement.remove();
+ assert.equal(load("util/restoreNavigationFocus").restoreFocusContext(protyle, {
+ undoFocusId: "same", undoFocusIndex: String(count - 1), undoFocusEndIndex: String(count - 1),
+ undoFocusStart: "0", undoFocusEnd: "0", undoFocusEmbedId: "embed",
+ }), false);
+ }
for (const before of [true, false]) {
for (const protect of [true, false]) {
const {protyle, editor} = setup(Array.from({length: 100}, (_, i) => p("p" + i)).join(""));
@@ -161,7 +185,7 @@ module.exports = async () => {
const virtual = load("render/av/virtualScroll");
const avState = load("render/av/selectionState");
const constants = load("../constants").Constants;
- const createAV = (id, protyle, editor) => {
+ const createAV = (id, protyle, editor, count = 100, offset = 0) => {
const block = document.createElement("div");
block.className = "av";
block.dataset.avId = id;
@@ -171,14 +195,66 @@ module.exports = async () => {
block.setAttribute(constants.ATTRIBUTE_V_SCROLL, "true");
block.setAttribute(constants.CUSTOM_SY_AV_VIEW, "view");
const data = {viewType: "table", view: {id: "view", columns: [{id: "c0", type: "text"}],
- rows: Array.from({length: 100}, (_, i) => ({id: "r" + i, cells: [{id: "v" + i}]}))}};
- block.innerHTML = '<div class="av__cursor"> </div><div class="av__body">' +
- data.view.rows.map((row, rowIndex) => load("render/av/row").getRowHTML({row, rowIndex})).join("") +
+ rows: Array.from({length: count}, (_, i) => ({id: "r" + i, cells: [{id: "v" + i}]}))},
+ target: {offset}};
+ block.innerHTML = '<div class="av__cursor"> </div><div class="av__header"></div><div class="av__body">' +
+ '<div class="av__row av__row--header" style="position:sticky;top:0;height:30px"></div>' +
+ data.view.rows.slice(0, 100).map((row, rowIndex) =>
+ load("render/av/row").getRowHTML({row, rowIndex: rowIndex + offset})).join("") +
'<div class="av__row av__row--util"></div></div>';
editor.append(block);
+ if (offset) {
+ block.querySelector(".av__body").dataset.avLocateWindow = "true";
+ }
virtual.initVirtualScroll({protyle, blockElement: block, data});
return block;
};
+ for (const count of [200, 1000]) {
+ for (const offset of [0, 500]) {
+ const {protyle, editor} = setup("");
+ const block = createAV("boundary", protyle, editor, count, offset);
+ assert.equal(load("render/av/focus").focusAVVerticalRegion(block, "up", 20, false), true);
+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r" + (count - 1));
+ assert.equal(Number(block.querySelector(".av__cell--select").parentElement.dataset.index), count - 1 + offset);
+ assert.ok(block.querySelectorAll(".av__row[data-id]").length < 100);
+ assert.ok(protyle.contentElement.scrollTop > 0, "entry reveals the loaded boundary");
+ virtual.trimAVRowsSync(block, protyle.contentElement.getBoundingClientRect());
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r" + (count - 1));
+ load("render/av/navigationKeydown").run(block, new KeyboardEvent("keydown", {key: "ArrowUp"}));
+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r" + (count - 2));
+ assert.equal(load("render/av/focus").focusAVVerticalRegion(block, "down", 20, false), true);
+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r0");
+ cases++;
+ }
+ }
+ {
+ const {protyle, editor} = setup("");
+ const block = createAV("groups", protyle, editor, 200);
+ const data = virtual.getAVData(block);
+ const body = block.querySelector(".av__body");
+ body.dataset.groupId = "visible";
+ const hidden = body.cloneNode(true);
+ hidden.dataset.groupId = "hidden";
+ hidden.classList.add("fn__none");
+ hidden.style.display = "none";
+ const empty = body.cloneNode(true);
+ empty.dataset.groupId = "empty";
+ empty.querySelectorAll(".av__row[data-id]").forEach(row => row.remove());
+ block.append(hidden, empty);
+ data.view.groups = [{...data.view, id: "visible"}, {...data.view, id: "hidden", groupFolded: true},
+ {...data.view, id: "empty", rows: []}];
+ virtual.initVirtualScroll({protyle, blockElement: block, data});
+ const last = virtual.ensureAVTableBoundaryRow(block, "up");
+ assert.equal(last.dataset.id, "r199");
+ assert.equal(last.closest(".av__body"), body);
+ assert.ok(body.querySelectorAll(".av__row[data-id]").length < 100);
+ virtual.setAVData(block, {...data, view: {...data.view, groups: [{...data.view.groups[0]}]}});
+ hidden.remove();
+ empty.remove();
+ assert.equal(virtual.ensureAVTableBoundaryRow(block, "up"), undefined, "reject stale body state");
+ cases++;
+ }
// 相同持久 ID 的副本也必须独立;不同数据库交错 trim 不得污染滚动方向。
const {protyle, editor} = setup("");
const block = createAV("database", protyle, editor);
diff --git a/app/scripts/verticalNavigation.test.js b/app/scripts/verticalNavigation.test.js
index 72d44c63f5..d0d4ad457c 100644
--- a/app/scripts/verticalNavigation.test.js
+++ b/app/scripts/verticalNavigation.test.js
@@ -33,6 +33,7 @@ const rendererModules = () => {
modules["render/tabsRender"] = "export const setTabTitleNavigationEditing = () => false;";
modules["../util/highlightById"] = "export const scrollCenter = () => {};";
modules["render/av/focus"] = 'import {focusEditableAtGoalX} from "../../wysiwyg/verticalCaret";\n' +
+ 'import {ensureAVTableBoundaryRow, getAVData} from "./virtualScroll";\n' +
"const clearSelect = () => {};\n" +
extract("render/av/focus", ["getVisibleAVTitle", "focusAVTitleByVerticalArrow", "focusAVVerticalRegion",
"getOwnVisibleElements", "getClosestCell"]);
@@ -103,7 +104,10 @@ const rendererModules = () => {
'" style="height:30px"><div class="av__cell" data-col-id="c0" data-dtype="text">' + row.id + '</div></div>';`;
modules["render/av/focus"] = 'import {setAVCellAnchor} from "./rangeSelect";\n' +
'import {focusBlock} from "../../util/selection";\n' +
- "const addDragFill = () => {}, cellScrollIntoView = () => {};\n" + modules["render/av/focus"];
+ 'import {hasClosestByClassName} from "../../util/hasClosest";\n' +
+ "const addDragFill = () => {};\n" +
+ extract("render/av/cell", ["cellScrollIntoView"])
+ .replace(/\/\/\/ #if MOBILE[\s\S]*?\/\/\/ #else/g, "") + "\n" + modules["render/av/focus"];
const avKeydown = ts.createSourceFile("avKeydown.ts", readFileSync(path.join(root, "render/av/keydown.ts"), "utf8"),
ts.ScriptTarget.Latest, true);
let cellMoves;
diff --git a/app/src/protyle/render/av/focus.ts b/app/src/protyle/render/av/focus.ts
index 80054408f3..c811a01c0f 100644
--- a/app/src/protyle/render/av/focus.ts
+++ b/app/src/protyle/render/av/focus.ts
@@ -5,6 +5,7 @@ import {getFirstBlock, getLastBlock, getNextBlock, getPreviousBlock} from "../..
import {scrollCenter} from "../../../util/highlightById";
import {focusEditableAtGoalX, TVerticalDirection} from "../../wysiwyg/verticalCaret";
import {selectAVItemRange, setAVItemAnchor, setAVCellAnchor} from "./rangeSelect";
+import {ensureAVTableBoundaryRow, getAVData} from "./virtualScroll";
const isForwardArrow = (key: string) => key === "ArrowDown" || key === "ArrowRight";
@@ -65,7 +66,8 @@ export const focusAVVerticalRegion = (blockElement: HTMLElement, direction: TVer
if (blockElement.dataset.avType === "table") {
const rows = getOwnVisibleElements(blockElement, ".av__row[data-id]:not(.av__row--header)");
- const rowElement = rows[direction === "down" ? 0 : rows.length - 1];
+ const rowElement = getAVData(blockElement) ? ensureAVTableBoundaryRow(blockElement, direction) :
+ rows[direction === "down" ? 0 : rows.length - 1];
const cellElement = rowElement && getClosestCell(rowElement, goalX);
if (cellElement) {
if (!focusBlock(blockElement)) {
diff --git a/app/src/protyle/render/av/virtualScroll.ts b/app/src/protyle/render/av/virtualScroll.ts
index eacf1a2f6f..87b8975b98 100644
--- a/app/src/protyle/render/av/virtualScroll.ts
+++ b/app/src/protyle/render/av/virtualScroll.ts
@@ -69,6 +69,81 @@ const syncTableBottomSpacer = (bodyEl: HTMLElement, state: IBodyState, dataEnd:
spacerElement.style.height = height + "px";
};
+const rebuildTableWindow = (bodyEl: HTMLElement, state: IBodyState,
+ renderWindow: ReturnType<typeof getGroupTableViewportWindow>) => {
+ const endMarker = bodyEl.querySelector(".av__spacer--bottom") || bodyEl.querySelector(".av__row--util");
+ if (!renderWindow || !endMarker) {
+ return false;
+ }
+ const rows = (state.view as IAVTable).rows;
+ let rowsHTML = renderWindow.topSpacerHeight > 0 ?
+ `<div class="av__spacer" style="height:${renderWindow.topSpacerHeight}px"></div>` : "";
+ for (let i = renderWindow.renderedStart; i <= renderWindow.renderedEnd; i++) {
+ rowsHTML += getRowHTML({data: state.view, row: rows[i - state.dataOffset], rowIndex: i,
+ pinIndex: state.pinIndex, type: "table"});
+ }
+ bodyEl.querySelectorAll(".av__row[data-id], .av__spacer:not(.av__spacer--bottom)").forEach(row => row.remove());
+ endMarker.insertAdjacentHTML("beforebegin", rowsHTML);
+ state.renderedStart = renderWindow.renderedStart;
+ state.renderedEnd = renderWindow.renderedEnd;
+ state.topSpacerHeight = renderWindow.topSpacerHeight;
+ syncTableBottomSpacer(bodyEl, state, state.dataOffset + rows.length - 1);
+ bodyEl.querySelectorAll<HTMLElement>(".av__row[data-id]").forEach(row => {
+ if (state.selectedRowIds?.has(row.dataset.id)) {
+ row.classList.add("av__row--select");
+ row.querySelector(".av__firstcol use")?.setAttribute("xlink:href", "#iconCheck");
+ }
+ });
+ restoreAVCellSelection(bodyEl.closest(".av"));
+ renderAVRichTextElements(bodyEl);
+ return true;
+};
+
+// 跨块进入表格时按当前已加载数据定位边界,仅回填边界附近的虚拟窗口。
+export const ensureAVTableBoundaryRow = (blockElement: HTMLElement, direction: "up" | "down") => {
+ const bodies = Array.from(blockElement.querySelectorAll<HTMLElement>(".av__body")).filter(body =>
+ body.closest(".av") === blockElement && body.getClientRects().length > 0 && !body.classList.contains("fn__none"));
+ if (direction === "up") {
+ bodies.reverse();
+ }
+ for (const body of bodies) {
+ const view = getBodyData(body) as IAVTable;
+ if (!view) {
+ return;
+ }
+ if (!view.rows?.length) {
+ continue;
+ }
+ const state = bodyStates.get(body);
+ if (state && state.view !== view) {
+ return;
+ }
+ const row = view.rows[direction === "down" ? 0 : view.rows.length - 1];
+ const findRow = () => Array.from(body.querySelectorAll<HTMLElement>(".av__row[data-id]"))
+ .find(item => item.dataset.id === row.id);
+ const existing = findRow();
+ if (existing) {
+ return existing;
+ }
+ if (!state || !blockElement.isConnected) {
+ return;
+ }
+ const dataStart = state.dataOffset;
+ const dataEnd = dataStart + view.rows.length - 1;
+ const rowHeight = Math.max(state.rowHeight || 36, 1);
+ const viewportHeight = (getBacklinkScrollElement(blockElement) ||
+ dataStore.get(blockElement)?.protyle.contentElement)?.clientHeight || rowHeight;
+ const targetTop = (direction === "down" ? 0 : view.rows.length - 1) * rowHeight;
+ if (!rebuildTableWindow(body, state, getGroupTableViewportWindow({
+ dataStart, dataEnd, bodyTop: 0, headerHeight: 0, rowHeight,
+ viewportTop: targetTop, viewportBottom: targetTop + viewportHeight,
+ }))) {
+ return;
+ }
+ return findRow();
+ }
+};
+
const doTrim = (blockElement: HTMLElement, elementRect: DOMRect): void => {
const localScroller = getBacklinkScrollElement(blockElement);
if (localScroller) {
@@ -187,32 +262,6 @@ const doTrim = (blockElement: HTMLElement, elementRect: DOMRect): void => {
const bottomSpacerElement = bodyEl.querySelector(".av__spacer--bottom") as HTMLElement;
const firstRowRect = currentRows[0].getBoundingClientRect();
const lastRowRect = currentRows[currentRows.length - 1].getBoundingClientRect();
- const rebuildTableWindow = (renderWindow: ReturnType<typeof getGroupTableViewportWindow>) => {
- if (!renderWindow) {
- return;
- }
- currentRows.forEach(row => row.remove());
- spacerElement?.remove();
- let rowsHTML = renderWindow.topSpacerHeight > 0 ?
- `<div class="av__spacer" style="height:${renderWindow.topSpacerHeight}px"></div>` : "";
- for (let i = renderWindow.renderedStart; i <= renderWindow.renderedEnd; i++) {
- rowsHTML += getRowHTML({
- data: state.view,
- row: dataRows[i - dataStart],
- rowIndex: i,
- pinIndex: state.pinIndex,
- type: "table"
- });
- }
- const endMarker = bottomSpacerElement?.isConnected ? bottomSpacerElement :
- bodyEl.querySelector(".av__row--util");
- endMarker?.insertAdjacentHTML("beforebegin", rowsHTML);
- state.renderedStart = renderWindow.renderedStart;
- state.renderedEnd = renderWindow.renderedEnd;
- state.topSpacerHeight = renderWindow.topSpacerHeight;
- syncTableBottomSpacer(bodyEl, state, dataEnd);
- restoreSelect();
- };
const viewportTop = Math.max(elementRect.top, blockRect.top);
const viewportBottom = Math.min(elementRect.bottom, blockRect.bottom);
const windowOutsideBuffer = lastRowRect.bottom < topLimit || firstRowRect.top > bottomLimit;
@@ -220,7 +269,7 @@ const doTrim = (blockElement: HTMLElement, elementRect: DOMRect): void => {
if (groupedTable && (spacerElement || bottomSpacerElement) && windowOutsideBuffer && bodyIntersectsViewport) {
// 当前窗口完全离开缓冲区时,按视口在分组中的位置重建附近窗口。
const headerHeight = (bodyEl.querySelector(".av__row--header") as HTMLElement)?.offsetHeight || rowHeight;
- rebuildTableWindow(getGroupTableViewportWindow({
+ rebuildTableWindow(bodyEl, state, getGroupTableViewportWindow({
dataStart,
dataEnd,
bodyTop: bodyRect.top,
diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.ts
index 6b9edaf405..0bc0cb9b67 100644
--- a/app/src/protyle/util/selection.ts
+++ b/app/src/protyle/util/selection.ts
@@ -666,12 +666,6 @@ export const restoreFocusContext = (protyle: IProtyle, context: Record<string, s
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < 0) {
return false;
}
- 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(protyle.wysiwyg.element.querySelectorAll(
`[data-node-id="${context.undoFocusId}"]`
@@ -690,8 +684,14 @@ export const restoreFocusContext = (protyle: IProtyle, context: Record<string, s
context.undoFocusEndIndex,
item => !isInEmbedBlock(item, false),
);
- if (!startBlockElement || !endBlockElement ||
- !focusScopeElement.contains(startBlockElement) || !focusScopeElement.contains(endBlockElement)) {
+ if (!startBlockElement || !endBlockElement) {
+ return false;
+ }
+ // 持久 ID 可对应多个嵌入副本;作用域由已定位的端点所属显示实例确定。
+ const startEmbed = isInEmbedBlock(startBlockElement, false);
+ const endEmbed = isInEmbedBlock(endBlockElement, false);
+ if (startEmbed !== endEmbed || (context.undoFocusEmbedId &&
+ (!startEmbed || startEmbed.getAttribute("data-node-id") !== context.undoFocusEmbedId))) {
return false;
}
const startFocusElement = context.undoFocusCalloutTitle === "true" ?
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index f3f326db21..ab053600ab 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -787,9 +787,6 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
}
invalidateViewFoldRequests(protyle);
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 => {
@@ -1222,7 +1219,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]'),
operation,
).forEach(item => {
- if (item === undoFocusEmbedElement) {
+ if (undoFocusContext?.undoFocusEmbedId === item.getAttribute("data-node-id")) {
// 当前嵌入块需在撤销操作全部回放后渲染,否则中途移除选区会把光标带到源块
pendingUndoEmbedElements.add(item);
} else {