Skip to content

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

:bug: Stabilize database layout and refresh in backlinks https://github.com/siyuan-note/siyuan/issues/19268

Danielb15c9c395a82
diff --git a/app/src/assets/scss/main/_main.scss b/app/src/assets/scss/main/_main.scss
index a16f0557a8..b9b32fcc1c 100644
--- a/app/src/assets/scss/main/_main.scss
+++ b/app/src/assets/scss/main/_main.scss
@@ -260,8 +260,8 @@ html[data-frontend="browser-desktop"] {
}
.file-tree {
- .block__icons .block__icon,
- &:not(.fullscreen) .block__icons .fn__space {
+ .block__icons:not(.protyle-wysiwyg *) .block__icon:not(.backlinkList__toggle),
+ &:not(.fullscreen) .block__icons:not(.protyle-wysiwyg *) .fn__space {
display: none;
transition: opacity .3s cubic-bezier(0, 0, .2, 1) 0ms, display .3s cubic-bezier(0, 0, .2, 1) 0ms allow-discrete;
}
@@ -270,13 +270,13 @@ html[data-frontend="browser-desktop"] {
display: none;
}
- &:hover .block__icons .fn__space {
+ &:hover .block__icons:not(.protyle-wysiwyg *) .fn__space {
display: block;
}
- &:hover .block__icons .block__icon:not([disabled]),
- &:not(.fullscreen):hover .block__icons .fn__space,
- &.fullscreen .block__icons .block__icon:not([disabled]) {
+ &:hover .block__icons:not(.protyle-wysiwyg *) .block__icon:not([disabled], .backlinkList__toggle),
+ &:not(.fullscreen):hover .block__icons:not(.protyle-wysiwyg *) .fn__space,
+ &.fullscreen .block__icons:not(.protyle-wysiwyg *) .block__icon:not([disabled], .backlinkList__toggle) {
opacity: 1;
display: flex;
@starting-style {
@@ -284,7 +284,7 @@ html[data-frontend="browser-desktop"] {
}
}
- &:hover .block__icons .block__icon[disabled] {
+ &:hover .block__icons:not(.protyle-wysiwyg *) .block__icon[disabled]:not(.backlinkList__toggle) {
opacity: .38;
display: block;
cursor: not-allowed;
diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.ts
index 42dd6f2b40..e6df7f464e 100644
--- a/app/src/layout/dock/BacklinkContent.ts
+++ b/app/src/layout/dock/BacklinkContent.ts
@@ -21,6 +21,7 @@ import {getAllEditor} from "../getAll";
import {isMobile} from "../../util/functions";
import {hideElements} from "../../protyle/ui/hideElements";
import {renderBacklink} from "../../protyle/wysiwyg/renderBacklink";
+import {hasAVEditorSession} from "../../protyle/render/av/editorSession";
import {BACKLINK_BLOCK_TYPES, configureBacklinkTypeFold, normalizeBacklinkFoldTypes} from "../../protyle/wysiwyg/backlinkTypeFold";
import {
getBottomBacklinkVisibility,
@@ -221,6 +222,7 @@ export class BacklinkContent extends Model {
});
};
this.element.addEventListener("focusout", this.panelFocusoutListener);
+ this.element.addEventListener("av-editor-close", this.panelFocusoutListener);
if (this.type !== "bottom") {
this.visibilityObserver = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
@@ -1134,7 +1136,8 @@ export class BacklinkContent extends Model {
return;
}
svgElement.removeAttribute("disabled");
- if (record.editor?.protyle.element.contains(document.activeElement)) {
+ if (record.editor && (record.editor.protyle.element.contains(document.activeElement) ||
+ hasAVEditorSession(record.editor.protyle.element))) {
record.contextDirty = true;
this.dirty = true;
this.pendingRootIDs.add(docId);
@@ -2261,7 +2264,8 @@ export class BacklinkContent extends Model {
}
public refreshAfterIndex() {
- if (this.destroyed || !this.blockId || !this.dirty || this.element.contains(document.activeElement)) {
+ if (this.destroyed || !this.blockId || !this.dirty || this.element.contains(document.activeElement) ||
+ hasAVEditorSession(this.element)) {
return;
}
if (this.type === "bottom") {
@@ -2279,7 +2283,7 @@ export class BacklinkContent extends Model {
return;
}
if (shouldDeferBottomBacklinkRefresh(
- this.element.contains(document.activeElement),
+ this.element.contains(document.activeElement) || hasAVEditorSession(this.element),
ignoreFocus
)) {
return;
@@ -2329,6 +2333,7 @@ export class BacklinkContent extends Model {
}
if (this.panelFocusoutListener) {
this.element.removeEventListener("focusout", this.panelFocusoutListener);
+ this.element.removeEventListener("av-editor-close", this.panelFocusoutListener);
}
this.visibilityObserver?.disconnect();
this.editors.forEach(item => {
diff --git a/app/src/protyle/render/av/backlink.test.ts b/app/src/protyle/render/av/backlink.test.ts
new file mode 100644
index 0000000000..ca984d254f
--- /dev/null
+++ b/app/src/protyle/render/av/backlink.test.ts
@@ -0,0 +1,42 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync("src/protyle/render/av/backlink.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+test("initial backlinks locate once while reused databases only restore reference marks", () => {
+ const requests: {itemID: string, scroll: boolean, highlight: boolean}[] = [];
+ const exports: {prepareBacklinkAV?: (element: unknown, targets: unknown[]) => void} = {};
+ runInNewContext(compiled, {
+ exports,
+ require: () => ({setAVLocateRequest: (_element: unknown, request: typeof requests[number]) => requests.push(request)}),
+ });
+ let rendered = false;
+ let marked = false;
+ let listeners = 0;
+ const reference = {dataset: {id: "definition"}, classList: {add: () => { marked = true; }}};
+ const database = {
+ dataset: {nodeId: "database"},
+ matches: () => true,
+ classList: {add: () => {}},
+ addEventListener: () => listeners++,
+ getAttribute: () => rendered ? "true" : null,
+ querySelectorAll: (selector: string) => selector === ".def--mark" ? [] : [{querySelectorAll: () => [reference]}],
+ };
+ const targets = [{blockID: "database", matches: [{itemID: "first", keyID: "key", defIDs: ["definition"]}]}];
+ exports.prepareBacklinkAV(database, targets);
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].itemID, "first");
+ assert.equal(requests[0].scroll, true);
+ assert.equal(requests[0].highlight, true);
+ rendered = true;
+ exports.prepareBacklinkAV(database, targets);
+ exports.prepareBacklinkAV(database, targets);
+ assert.equal(requests.length, 1);
+ assert.equal(listeners, 1);
+ assert.equal(marked, true);
+});
diff --git a/app/src/protyle/render/av/backlink.ts b/app/src/protyle/render/av/backlink.ts
index 93c506a3e7..1aed649fa5 100644
--- a/app/src/protyle/render/av/backlink.ts
+++ b/app/src/protyle/render/av/backlink.ts
@@ -25,6 +25,22 @@ export const prepareBacklinkAV = (element: HTMLElement, targets: IBacklinkAVTarg
if (!target?.matches.length) {
return;
}
+ if (initialized.has(database) && database.getAttribute("data-render") === "true") {
+ target.matches.forEach(match => {
+ const cells = database.querySelectorAll<HTMLElement>(
+ `.av__row[data-id="${match.itemID}"] [data-col-id="${match.keyID}"], ` +
+ `.av__gallery-item[data-id="${match.itemID}"] [data-field-id="${match.keyID}"]`
+ );
+ cells.forEach(cell => {
+ cell.querySelectorAll<HTMLElement>('[data-type~="block-ref"][data-id]').forEach(ref => {
+ if (match.defIDs.includes(ref.dataset.id)) {
+ ref.classList.add("def--mark");
+ }
+ });
+ });
+ });
+ return;
+ }
const match = target.matches[0];
database.classList.add("av--backlink");
if (!initialized.has(database)) {
diff --git a/app/src/protyle/render/av/backlinkReuse.test.ts b/app/src/protyle/render/av/backlinkReuse.test.ts
new file mode 100644
index 0000000000..3200df4c67
--- /dev/null
+++ b/app/src/protyle/render/av/backlinkReuse.test.ts
@@ -0,0 +1,123 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {captureBacklinkAVSources, reuseBacklinkAVSources} from "./backlinkReuse";
+import type {IBacklinkAVTarget} from "./backlink";
+
+class ElementStub {
+ attributes = new Map<string, string>([["data-node-id", "block"], ["data-av-id", "database"], ["updated", "1"]]);
+ dataset = {nodeId: "block"};
+ isConnected = true;
+ scrollTop = 0;
+ scrollLeft = 0;
+ children: ElementStub[] = [];
+ replacement?: ElementStub;
+ innerHTML = "<div></div>";
+
+ get outerHTML() {
+ return JSON.stringify([...this.attributes]) + this.innerHTML;
+ }
+
+ getAttribute(name: string) {
+ return this.attributes.get(name) ?? null;
+ }
+
+ setAttribute(name: string, value: string) {
+ this.attributes.set(name, value);
+ }
+
+ removeAttribute(name: string) {
+ this.attributes.delete(name);
+ }
+
+ matches() {
+ return true;
+ }
+
+ querySelectorAll() {
+ return this.children;
+ }
+
+ cloneNode() {
+ const clone = new ElementStub();
+ clone.attributes = new Map(this.attributes);
+ clone.innerHTML = this.innerHTML;
+ return clone;
+ }
+
+ replaceWith(element: ElementStub) {
+ this.replacement = element;
+ [element, ...element.children].forEach(item => {
+ item.scrollTop = 0;
+ item.scrollLeft = 0;
+ });
+ }
+}
+
+const targets: IBacklinkAVTarget[] = [{
+ blockID: "block",
+ matches: [{itemID: "item", keyID: "key", valueID: "value", title: "title", keyName: "key", defIDs: ["definition"]}],
+}];
+
+test("backlink refresh reuses rendered databases and restores nested scrolling", () => {
+ const previousHTMLElement = globalThis.HTMLElement;
+ globalThis.HTMLElement = ElementStub as unknown as typeof HTMLElement;
+ try {
+ const old = new ElementStub();
+ const oldSources = captureBacklinkAVSources([old as unknown as Node], targets);
+ old.setAttribute("data-render", "true");
+ old.innerHTML = "rendered rows and selection";
+ old.scrollTop = 480;
+ const body = new ElementStub();
+ body.scrollLeft = 200;
+ old.children.push(body);
+ const next = new ElementStub();
+ next.setAttribute("updated", "2");
+ const nodes = [next as unknown as Node];
+ const sources = captureBacklinkAVSources(nodes, targets);
+ const restore = reuseBacklinkAVSources(nodes, sources, oldSources);
+ restore();
+ assert.equal(nodes[0], old);
+ assert.equal(sources.get("block").element, old);
+ assert.equal(old.innerHTML, "rendered rows and selection");
+ assert.equal(old.scrollTop, 480);
+ assert.equal(body.scrollLeft, 200);
+ assert.equal(old.getAttribute("updated"), "2");
+ } finally {
+ globalThis.HTMLElement = previousHTMLElement;
+ }
+});
+
+test("changed configuration, targets, missing or unrendered copies are rendered afresh", () => {
+ const previousHTMLElement = globalThis.HTMLElement;
+ globalThis.HTMLElement = ElementStub as unknown as typeof HTMLElement;
+ try {
+ for (const change of ["database", "view", "content", "target", "detached", "unrendered", "missing"]) {
+ const old = new ElementStub();
+ const oldSources = captureBacklinkAVSources([old as unknown as Node], targets);
+ old.setAttribute("data-render", "true");
+ const next = new ElementStub();
+ const nextTargets = JSON.parse(JSON.stringify(targets)) as IBacklinkAVTarget[];
+ if (change === "database") {
+ next.setAttribute("data-av-id", "other");
+ } else if (change === "view") {
+ next.setAttribute("custom-sy-av-view", "other");
+ } else if (change === "content") {
+ next.innerHTML = "changed attributes";
+ } else if (change === "target") {
+ nextTargets[0].matches[0].itemID = "other";
+ } else if (change === "detached") {
+ old.isConnected = false;
+ } else if (change === "unrendered") {
+ old.removeAttribute("data-render");
+ } else {
+ oldSources.clear();
+ }
+ const nodes = [next as unknown as Node];
+ reuseBacklinkAVSources(nodes, captureBacklinkAVSources(nodes, nextTargets), oldSources)();
+ assert.equal(nodes[0], next, change);
+ assert.equal(next.replacement, undefined, change);
+ }
+ } finally {
+ globalThis.HTMLElement = previousHTMLElement;
+ }
+});
diff --git a/app/src/protyle/render/av/backlinkReuse.ts b/app/src/protyle/render/av/backlinkReuse.ts
new file mode 100644
index 0000000000..f886408446
--- /dev/null
+++ b/app/src/protyle/render/av/backlinkReuse.ts
@@ -0,0 +1,74 @@
+import type {IBacklinkAVTarget} from "./backlink";
+
+interface IBacklinkAVSource {
+ element: HTMLElement;
+ source: string;
+ target: string;
+}
+
+export const captureBacklinkAVSources = (nodes: Node[], targets: IBacklinkAVTarget[]) => {
+ const sources = new Map<string, IBacklinkAVSource>();
+ nodes.forEach(node => {
+ if (!(node instanceof HTMLElement)) {
+ return;
+ }
+ const databases = node.matches(".av[data-node-id]") ? [node] :
+ Array.from(node.querySelectorAll<HTMLElement>(".av[data-node-id]"));
+ databases.forEach(element => {
+ const target = targets.find(item => item.blockID === element.dataset.nodeId);
+ if (!target?.matches.length) {
+ return;
+ }
+ const source = element.cloneNode(true) as HTMLElement;
+ // 修改时间不改变数据库副本的配置,单元格内容由事务刷新。
+ source.removeAttribute("updated");
+ sources.set(element.dataset.nodeId, {
+ element,
+ source: source.outerHTML,
+ target: JSON.stringify(target.matches.map(item => ({
+ itemID: item.itemID,
+ keyID: item.keyID,
+ defIDs: item.defIDs,
+ }))),
+ });
+ });
+ });
+ return sources;
+};
+
+// 同一反链条目内复用已渲染的数据库,保留滚动位置、虚拟窗口和选区。
+export const reuseBacklinkAVSources = (nodes: Node[], sources: Map<string, IBacklinkAVSource>,
+ previous: Map<string, IBacklinkAVSource>) => {
+ const scrollPositions: {element: HTMLElement, top: number, left: number}[] = [];
+ sources.forEach((source, id) => {
+ const old = previous.get(id);
+ if (!old || old.source !== source.source || old.target !== source.target ||
+ !old.element.isConnected || old.element.getAttribute("data-render") !== "true") {
+ return;
+ }
+ [old.element, ...Array.from(old.element.querySelectorAll<HTMLElement>("*"))].forEach(element => {
+ if (element.scrollTop || element.scrollLeft) {
+ scrollPositions.push({element, top: element.scrollTop, left: element.scrollLeft});
+ }
+ });
+ const updated = source.element.getAttribute("updated");
+ if (updated !== null) {
+ old.element.setAttribute("updated", updated);
+ } else {
+ old.element.removeAttribute("updated");
+ }
+ const index = nodes.indexOf(source.element);
+ source.element.replaceWith(old.element);
+ if (index !== -1) {
+ nodes[index] = old.element;
+ }
+ source.element = old.element;
+ });
+ // 节点重新接入文档后同步恢复各层滚动,避免移动节点时浏览器重置视口。
+ return () => {
+ scrollPositions.forEach(({element, top, left}) => {
+ element.scrollTop = top;
+ element.scrollLeft = left;
+ });
+ };
+};
diff --git a/app/src/protyle/render/av/editorSession.test.ts b/app/src/protyle/render/av/editorSession.test.ts
new file mode 100644
index 0000000000..3391a4b81b
--- /dev/null
+++ b/app/src/protyle/render/av/editorSession.test.ts
@@ -0,0 +1,28 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {beginAVEditorSession, hasAVEditorSession} from "./editorSession";
+
+test("floating editors defer only their owning panel and notify once when closed", () => {
+ const events: Event[] = [];
+ const owner = {dispatchEvent: (event: Event) => events.push(event)} as unknown as HTMLElement;
+ const panel = {contains: (element: HTMLElement) => element === owner} as HTMLElement;
+ const otherPanel = {contains: () => false} as unknown as HTMLElement;
+ const endFirst = beginAVEditorSession(owner);
+ const endSecond = beginAVEditorSession(owner);
+ try {
+ assert.equal(hasAVEditorSession(panel), true);
+ assert.equal(hasAVEditorSession(otherPanel), false);
+ endFirst();
+ endFirst();
+ assert.equal(hasAVEditorSession(panel), true);
+ assert.equal(events.length, 1);
+ endSecond();
+ assert.equal(hasAVEditorSession(panel), false);
+ assert.equal(events.length, 2);
+ assert.equal(events[0].type, "av-editor-close");
+ assert.equal(events[0].bubbles, true);
+ } finally {
+ endFirst();
+ endSecond();
+ }
+});
diff --git a/app/src/protyle/render/av/editorSession.ts b/app/src/protyle/render/av/editorSession.ts
new file mode 100644
index 0000000000..a0ea9c95dd
--- /dev/null
+++ b/app/src/protyle/render/av/editorSession.ts
@@ -0,0 +1,16 @@
+const sessions = new Set<{owner: HTMLElement}>();
+
+export const hasAVEditorSession = (element: HTMLElement) => {
+ return Array.from(sessions).some(session => element.contains(session.owner));
+};
+
+// 浮层位于正文之外,使用所属编辑器标记编辑期间,关闭后通知反链处理延迟刷新。
+export const beginAVEditorSession = (owner: HTMLElement) => {
+ const session = {owner};
+ sessions.add(session);
+ return () => {
+ if (sessions.delete(session)) {
+ owner.dispatchEvent(new CustomEvent("av-editor-close", {bubbles: true}));
+ }
+ };
+};
diff --git a/app/src/protyle/render/av/richTextEditor.ts b/app/src/protyle/render/av/richTextEditor.ts
index 8a907c10c0..99d0ba8c9d 100644
--- a/app/src/protyle/render/av/richTextEditor.ts
+++ b/app/src/protyle/render/av/richTextEditor.ts
@@ -9,6 +9,7 @@ import {mathRender} from "../mathRender";
import {positionAVRichTextEditor} from "./richTextEditorPosition";
import {getAVData} from "./virtualScroll";
import {resolveAVSelectedCell} from "./selectionState";
+import {beginAVEditorSession} from "./editorSession";
import {
configureAVRichTextLute,
createAVRichTextValue,
@@ -109,6 +110,7 @@ export const openAVRichTextEditor = (options: AVRichTextEditorOptions) => {
</div>` : ""}
</div>`;
document.body.appendChild(maskElement);
+ const endEditorSession = beginAVEditorSession(options.protyle.element);
const panelElement = maskElement.firstElementChild as HTMLElement;
const hostElement = panelElement.querySelector<HTMLElement>(".av__richtext-host");
hostElement.dataset.protyleLiteRender = "safe";
@@ -222,6 +224,7 @@ export const openAVRichTextEditor = (options: AVRichTextEditorOptions) => {
if (activeEditor?.finish === finish) {
activeEditor = undefined;
}
+ endEditorSession();
options.onDestroy?.();
}
};
diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.ts
index 0b166d35e9..61e63d74a6 100644
--- a/app/src/protyle/wysiwyg/renderBacklink.ts
+++ b/app/src/protyle/wysiwyg/renderBacklink.ts
@@ -18,6 +18,7 @@ import {
} from "../util/viewFold";
import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";
import {IBacklinkAVTarget, prepareBacklinkAV} from "../render/av/backlink";
+import {captureBacklinkAVSources, reuseBacklinkAVSources} from "../render/av/backlinkReuse";
import {markBacklinkReference, updateBacklinkReferenceVisibility} from "./backlinkReference";
import {setBacklinkTypeFoldExpandHandler, updateBacklinkTypeFolds} from "./backlinkTypeFold";
@@ -37,6 +38,7 @@ interface IBacklinkDOMRecord {
revision: string,
anchor: HTMLElement,
targets: IBacklinkAVTarget[],
+ databases: ReturnType<typeof captureBacklinkAVSources>,
}
const backlinkDOMRecords = new WeakMap<IProtyle, Map<string, IBacklinkDOMRecord>>();
@@ -72,6 +74,7 @@ const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string)
revision: item.revision || "",
anchor: nodes[0] as HTMLElement,
targets: item.attributeViewTargets || [],
+ databases: captureBacklinkAVSources(nodes, item.attributeViewTargets || []),
},
nodes,
};
@@ -131,8 +134,10 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])
clearViewFoldDefaults(protyle, id);
const created = createBacklinkDOMRecord(item, index, id);
if (record) {
+ const restoreAVScroll = reuseBacklinkAVSources(created.nodes, created.record.databases, record.databases);
created.nodes.forEach(node => element.insertBefore(node, record.anchor));
removeBacklinkDOMRecord(record);
+ restoreAVScroll();
} else {
created.nodes.forEach(node => element.appendChild(node));
}