An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Incrementally update backlink panels https://github.com/siyuan-note/siyuan/issues/18360
Danielc6a9122b41b5
diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.tsindex 79e37cb701..cf195da4a2 100644--- a/app/src/dialog/processSystem.ts+++ b/app/src/dialog/processSystem.ts@@ -21,20 +21,20 @@ import {saveScroll} from "../protyle/scroll/saveScroll";import {isInAndroid, isInHarmony, isInIOS, setStorageVal} from "../protyle/util/compatibility";import {Plugin} from "../plugin";-const BACKLINK_REFRESH_DELAY = 3600;-let backlinkRefreshTimeout: number;--export const scheduleBacklinkRefresh = () => {- window.clearTimeout(backlinkRefreshTimeout);- // 等待索引队列写入后再查询提及,并合并连续事务触发的刷新。- backlinkRefreshTimeout = window.setTimeout(() => {- getAllModels().backlink.forEach(item => {- if (item.type === "bottom") {- item.markDirty();- item.refreshIfVisible();- }- });- }, BACKLINK_REFRESH_DELAY);+export const processBacklinkIndexCommit = (data: {+ rootIDs?: string[],+ backlinkChanged?: boolean,+ backlinkFull?: boolean,+}) => {+ /// #if !MOBILE+ if (!data?.backlinkChanged) {+ return;+ }+ getAllModels().backlink.forEach(item => {+ item.markIndexDirty(data);+ item.refreshAfterIndex();+ });+ /// #endif};export const setRefDynamicText = (data: {@@ -49,7 +49,6 @@ export const setRefDynamicText = (data: {item.innerHTML = data.refText;});});- scheduleBacklinkRefresh();};export const setDefRefCount = (data: {@@ -59,17 +58,6 @@ export const setDefRefCount = (data: {"rootRefCount": number,"rootID": string}) => {- /// #if !MOBILE- getAllModels().backlink.forEach(item => {- const containsChangedBlock = window.siyuan.config.editor.backlinkContainChildren && item.rootId === data.rootID;- if (item.type !== "bottom" || (!containsChangedBlock &&- item.blockId !== data.rootID && item.blockId !== data.blockID && !data.defIDs?.includes(item.blockId))) {- return;- }- item.markDirty();- item.refreshIfVisible();- });- /// #endifgetAllEditor().forEach(editor => {if (editor.protyle.block.rootID === data.rootID && editor.protyle.title) {const attrElement = editor.protyle.title.element.querySelector(".protyle-attr");diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex 5898240a25..30d09737ab 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -727,26 +727,7 @@ export const updateBacklinkGraph = (models: IModels, protyle: IProtyle) => {if (blockId === item.blockId) {return;}- item.element.querySelector('.block__icon[data-type="refresh"] svg').classList.add("fn__rotate");- const backlinkParam: IObject = {- sort: item.status[blockId] ? item.status[blockId].sort.toString() : window.siyuan.config.editor.backlinkSort.toString(),- mSort: item.status[blockId] ? item.status[blockId].mSort.toString() : window.siyuan.config.editor.backmentionSort.toString(),- id: blockId || "",- k: item.inputsElement[0].value,- mk: item.inputsElement[1].value,- };- if (protyle && isEncryptedBox(protyle.notebookId)) {- backlinkParam.notebook = protyle.notebookId;- }- fetchPost("/api/ref/getBacklink2", backlinkParam, response => {- if (!isCurrentEditor(blockId) || item.blockId === blockId) {- item.element.querySelector('.block__icon[data-type="refresh"] svg').classList.remove("fn__rotate");- return;- }- item.saveStatus();- item.blockId = blockId;- item.render(response.data);- });+ item.switchBlock(blockId, protyle?.block?.rootID || "", protyle?.notebookId || "");});};diff --git a/app/src/index.ts b/app/src/index.tsindex 027b7be6b1..3a2f0623b3 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -25,7 +25,7 @@ import {progressBackgroundTask,progressLoading,progressStatus,- scheduleBacklinkRefresh,+ processBacklinkIndexCommit,setDefRefCount,setRefDynamicText,transactionError@@ -88,8 +88,8 @@ export class App {case "setDefRefCount":setDefRefCount(data.data);break;- case "transactions":- scheduleBacklinkRefresh();+ case "databaseIndexCommit":+ processBacklinkIndexCommit(data.data);break;case "reloadTag":if (getDockByType("tag")?.data.tag instanceof Tag) {@@ -152,7 +152,6 @@ export class App {});break;case "rename":- scheduleBacklinkRefresh();getAllTabs().forEach((tab) => {if (tab.headElement) {const initTab = tab.headElement.getAttribute("data-initdata");diff --git a/app/src/layout/dock/Backlink.ts b/app/src/layout/dock/Backlink.tsindex a180834ebb..62f6a75b32 100644--- a/app/src/layout/dock/Backlink.ts+++ b/app/src/layout/dock/Backlink.ts@@ -14,13 +14,49 @@ import {isSupportCSSHL, searchMarkRender} from "../../protyle/render/searchMarkRimport {getDocDisplayName, isEncryptedBox} from "../../util/pathName";import {getAllModels} from "../getAll";import {hideElements} from "../../protyle/ui/hideElements";+import {renderBacklink} from "../../protyle/wysiwyg/renderBacklink";import {shouldDeferBottomBacklinkRefresh,shouldHideBottomBacklinks,+ shouldRefreshAllBacklinkContexts,shouldRenderBacklinkResponse,shouldSaveBacklinkStatus} from "./backlinkRefresh";+interface IBacklinkItemRecord {+ revision: string,+ headerElement: HTMLLIElement,+ editor?: Protyle,+ contextRevision?: string,+ contextDirty?: boolean,+ requestGeneration: number,+}++interface IBacklinkIndexChange {+ rootIDs?: string[],+ backlinkChanged?: boolean,+ backlinkFull?: boolean,+}++interface IBacklinkListResponse {+ unchanged?: boolean,+ revision?: string,+ box: string,+ backlinks: IBlockTree[],+ backmentions: IBlockTree[],+ linkRefsCount: number,+ mentionsCount: number,+ k: string,+ mk: string+}++interface IBacklinkScrollAnchor {+ rootID: string,+ isMention: boolean,+ offset: number,+ scrollElement: HTMLElement,+}+export class Backlink extends Model {public element: HTMLElement;public inputsElement: NodeListOf<HTMLInputElement>;@@ -52,7 +88,15 @@ export class Backlink extends Model {private requestID = 0;private showingLoading = false;private contextRequestVersions = [0, 0];+ private itemRecords = [new Map<string, IBacklinkItemRecord>(), new Map<string, IBacklinkItemRecord>()];+ private listRevision = "";+ private listQueryKey = "";+ private indexChangeVersion = 0;+ private pendingRootIDs = new Set<string>();+ private pendingFull = false;private ownerFocusoutListener?: (event: FocusEvent) => void;+ private panelFocusoutListener?: () => void;+ private visibilityObserver?: IntersectionObserver;private empty = false;private emptyChange?: (empty: boolean) => void;@@ -84,6 +128,22 @@ export class Backlink extends Model {this.emptyChange = options.emptyChange;this.element = options.element || options.tab.panelElement;this.element.classList.add("fn__flex-column", "file-tree", "sy__backlink", "dockPanel");+ this.panelFocusoutListener = () => {+ window.setTimeout(() => {+ if (this.dirty && !this.element.contains(document.activeElement)) {+ this.refreshAfterIndex();+ }+ });+ };+ this.element.addEventListener("focusout", this.panelFocusoutListener);+ if (this.type !== "bottom") {+ this.visibilityObserver = new IntersectionObserver((entries) => {+ if (entries[0].isIntersecting) {+ this.refreshAfterIndex();+ }+ });+ this.visibilityObserver.observe(this.element);+ }if (this.type === "bottom") {this.element.classList.add("sy__backlink--bottom");this.element.tabIndex = -1;@@ -553,11 +613,14 @@ export class Backlink extends Model {if (!svgElement || svgElement.getAttribute("disabled")) {return;}- svgElement.setAttribute("disabled", "disabled");const docId = liElement.getAttribute("data-node-id");- const editor = this.editors.find(item => item.protyle.element === liElement.nextElementSibling);+ const record = this.itemRecords[isMention ? 1 : 0].get(docId);+ const editor = record?.editor || this.editors.find(item => item.protyle.element === liElement.nextElementSibling);if (svgElement.classList.contains("b3-list-item__arrow--open")) {svgElement.classList.remove("b3-list-item__arrow--open");+ if (record) {+ record.requestGeneration++;+ }if (editor && this.type === "bottom") {hideElements(["gutter"], editor.protyle);editor.protyle.element.classList.add("fn__none");@@ -565,57 +628,107 @@ export class Backlink extends Model {editor.destroy();this.editors.splice(this.editors.indexOf(editor), 1);editor.protyle.element.remove();+ if (record) {+ record.editor = undefined;+ record.contextRevision = "";+ }}- svgElement.removeAttribute("disabled");this.updateBottomBacklinkSpacing();- } else if (editor) {+ } else if (editor && !record?.contextDirty) {editor.protyle.element.classList.remove("fn__none");- svgElement.removeAttribute("disabled");svgElement.classList.add("b3-list-item__arrow--open");this.updateBottomBacklinkSpacing();} else {- const keyword = isMention ? this.inputsElement[1].value : this.inputsElement[0].value;- const blockId = this.blockId;- const contextRequestVersion = this.contextRequestVersions[isMention ? 1 : 0];- fetchPost(isMention ? "/api/ref/getBackmentionDoc" : "/api/ref/getBacklinkDoc", {- defID: blockId,- refTreeID: docId,- highlight: !isSupportCSSHL(),- keyword,- }, (response) => {- if (this.destroyed || blockId !== this.blockId || !liElement.isConnected ||- contextRequestVersion !== this.contextRequestVersions[isMention ? 1 : 0]) {- return;- }- svgElement.removeAttribute("disabled");- svgElement.classList.add("b3-list-item__arrow--open");- this.updateBottomBacklinkSpacing();- const editorElement = document.createElement("div");- editorElement.style.minHeight = "auto";- editorElement.setAttribute("data-defid", blockId);- editorElement.setAttribute("data-ismention", isMention ? "true" : "false");- liElement.after(editorElement);- const editor = new Protyle(this.app, editorElement, {- blockId: docId,- click: {- preventInsetEmptyBlock: true- },- backlinkData: isMention ? response.data.backmentions : response.data.backlinks,- render: {- background: false,- gutter: true,- scroll: false,- breadcrumb: false,+ this.loadContext(liElement, isMention, true);+ }+ }++ private loadContext(liElement: HTMLElement, isMention: boolean, expand: boolean) {+ const index = isMention ? 1 : 0;+ const docId = liElement.getAttribute("data-node-id");+ const record = this.itemRecords[index].get(docId);+ const svgElement = liElement.firstElementChild?.firstElementChild;+ if (!record || !svgElement) {+ return;+ }+ svgElement.setAttribute("disabled", "disabled");+ const keyword = isMention ? this.inputsElement[1].value : this.inputsElement[0].value;+ const blockId = this.blockId;+ const contextRequestVersion = this.contextRequestVersions[index];+ const requestGeneration = ++record.requestGeneration;+ const param: IObject = {+ defID: blockId,+ refTreeID: docId,+ highlight: !isSupportCSSHL(),+ keyword,+ };+ const notebookId = liElement.getAttribute("data-notebook-id");+ if (isEncryptedBox(notebookId)) {+ param.notebook = notebookId;+ }+ if (record.contextRevision) {+ param.knownRevision = record.contextRevision;+ }+ fetchPost(isMention ? "/api/ref/getBackmentionDoc" : "/api/ref/getBacklinkDoc", param, (response) => {+ if (this.destroyed || blockId !== this.blockId || !liElement.isConnected ||+ contextRequestVersion !== this.contextRequestVersions[index] ||+ requestGeneration !== record.requestGeneration) {+ return;+ }+ if (!response.data) {+ return;+ }+ svgElement.removeAttribute("disabled");+ record.contextDirty = false;+ record.contextRevision = response.data.revision;+ record.editor?.protyle.element.setAttribute("data-backlink-revision", response.data.revision);+ if (!response.data.unchanged) {+ const backlinkData = isMention ? response.data.backmentions : response.data.backlinks;+ if (record.editor) {+ const scrollAnchor = this.captureScrollAnchor(this.type === "bottom" ? undefined : (isMention ? this.mTree : this.tree));+ record.editor.protyle.options.backlinkData = backlinkData;+ renderBacklink(record.editor.protyle, backlinkData);+ searchMarkRender(record.editor.protyle, response.data.keywords);+ this.restoreScrollAnchor(scrollAnchor);+ } else {+ const editorElement = document.createElement("div");+ editorElement.style.minHeight = "auto";+ editorElement.setAttribute("data-defid", blockId);+ editorElement.setAttribute("data-ismention", isMention ? "true" : "false");+ editorElement.setAttribute("data-backlink-revision", response.data.revision);+ liElement.after(editorElement);+ const editor = new Protyle(this.app, editorElement, {+ blockId: docId,+ click: {+ preventInsetEmptyBlock: true+ },+ backlinkData,+ render: {+ background: false,+ gutter: true,+ scroll: false,+ breadcrumb: false,+ }+ });+ if (this.type === "bottom") {+ editor.protyle.wysiwyg.element.addEventListener("focusin", () => this.setOwnerFocus());}- });- if (this.type === "bottom") {- editor.protyle.wysiwyg.element.addEventListener("focusin", () => this.setOwnerFocus());+ editor.protyle.notebookId = notebookId;+ searchMarkRender(editor.protyle, response.data.keywords);+ this.editors.push(editor);+ record.editor = editor;}- editor.protyle.notebookId = liElement.getAttribute("data-notebook-id");- searchMarkRender(editor.protyle, response.data.keywords);- this.editors.push(editor);- });- }+ }+ if (expand) {+ record.editor?.protyle.element.classList.remove("fn__none");+ svgElement.classList.add("b3-list-item__arrow--open");+ }+ this.updateBottomBacklinkSpacing();+ }).finally(() => {+ if (requestGeneration === record.requestGeneration) {+ svgElement.removeAttribute("disabled");+ }+ });}private hideEditorGutters(element: Element) {@@ -633,6 +746,158 @@ export class Backlink extends Model {});}+ private destroyItemRecord(record: IBacklinkItemRecord) {+ if (record.editor) {+ record.editor.destroy();+ const editorIndex = this.editors.indexOf(record.editor);+ if (editorIndex > -1) {+ this.editors.splice(editorIndex, 1);+ }+ record.editor.protyle.element.remove();+ }+ record.headerElement.remove();+ }++ private ensureListElement(tree: Tree) {+ let listElement = tree.element.querySelector(":scope > .b3-list") as HTMLUListElement;+ if (!listElement) {+ tree.element.replaceChildren();+ listElement = document.createElement("ul");+ listElement.className = "b3-list b3-list--background";+ tree.element.appendChild(listElement);+ }+ return listElement;+ }++ private reconcileList(tree: Tree, data: IBlockTree[], isMention: boolean) {+ let changed = false;+ const records = this.itemRecords[isMention ? 1 : 0];+ const ids = new Set(data.map(item => item.id).filter((id): id is string => Boolean(id)));+ records.forEach((record, id) => {+ if (!ids.has(id)) {+ this.destroyItemRecord(record);+ records.delete(id);+ changed = true;+ }+ });++ const listElement = this.ensureListElement(tree);+ if (data.length === 0) {+ if (!listElement.querySelector(":scope > .b3-list--empty")) {+ const emptyElement = document.createElement("li");+ emptyElement.className = "b3-list--empty";+ emptyElement.textContent = window.siyuan.languages.emptyContent;+ listElement.replaceChildren(emptyElement);+ changed = true;+ }+ return changed;+ }+ const emptyElement = listElement.querySelector(":scope > .b3-list--empty");+ if (emptyElement) {+ emptyElement.remove();+ changed = true;+ }++ const orderedRecords: IBacklinkItemRecord[] = [];+ data.forEach(item => {+ const id = item.id;+ if (!id) {+ return;+ }+ let record = records.get(id);+ if (!record) {+ const headerElement = tree.createTopLevelItem(item);+ record = {+ revision: item.revision || "",+ headerElement,+ requestGeneration: 0,+ };+ records.set(id, record);+ listElement.appendChild(headerElement);+ changed = true;+ } else if (!item.revision || record.revision !== item.revision) {+ const headerElement = tree.createTopLevelItem(item);+ const oldArrow = record.headerElement.querySelector(".b3-list-item__arrow");+ const newArrow = headerElement.querySelector(".b3-list-item__arrow");+ if (oldArrow?.classList.contains("b3-list-item__arrow--open")) {+ newArrow?.classList.add("b3-list-item__arrow--open");+ }+ if (record.headerElement.classList.contains("b3-list-item--focus")) {+ headerElement.classList.add("b3-list-item--focus");+ }+ record.headerElement.replaceWith(headerElement);+ record.headerElement = headerElement;+ record.revision = item.revision || "";+ changed = true;+ }+ orderedRecords.push(record);+ });++ let cursor = listElement.firstElementChild;+ orderedRecords.forEach(record => {+ if (record.headerElement !== cursor) {+ listElement.insertBefore(record.headerElement, cursor);+ changed = true;+ }+ cursor = record.headerElement.nextElementSibling;+ if (record.editor) {+ if (record.editor.protyle.element !== cursor) {+ listElement.insertBefore(record.editor.protyle.element, cursor);+ changed = true;+ }+ cursor = record.editor.protyle.element.nextElementSibling;+ }+ });+ return changed;+ }++ private captureScrollAnchor(tree?: Tree): IBacklinkScrollAnchor | undefined {+ const scrollElement = this.type === "bottom" ? this.ownerProtyle.contentElement : tree.element;+ const scopeElement = tree?.element || this.element;+ const scrollRect = scrollElement.getBoundingClientRect();+ const itemElements = Array.from(scopeElement.querySelectorAll(".b3-list > .b3-list-item[data-node-id]")) as HTMLElement[];+ const anchorElement = itemElements.find(item => item.getBoundingClientRect().bottom >= scrollRect.top);+ if (!anchorElement) {+ return;+ }+ return {+ rootID: anchorElement.getAttribute("data-node-id"),+ isMention: this.mTree.element.contains(anchorElement),+ offset: anchorElement.getBoundingClientRect().top - scrollRect.top,+ scrollElement,+ };+ }++ private restoreScrollAnchor(anchor?: IBacklinkScrollAnchor) {+ if (!anchor) {+ return;+ }+ const tree = anchor.isMention ? this.mTree : this.tree;+ const anchorElement = tree.element.querySelector(`.b3-list-item[data-node-id="${anchor.rootID}"]`);+ if (!anchorElement) {+ return;+ }+ const offset = anchorElement.getBoundingClientRect().top - anchor.scrollElement.getBoundingClientRect().top;+ anchor.scrollElement.scrollTop += offset - anchor.offset;+ }++ private refreshExpandedContexts(rootIDs: Set<string>, full: boolean) {+ this.itemRecords.forEach((records, index) => {+ records.forEach((record, rootID) => {+ const arrowElement = record.headerElement.querySelector(".b3-list-item__arrow");+ if (!arrowElement?.classList.contains("b3-list-item__arrow--open")) {+ if (full || rootIDs.has(rootID)) {+ record.contextDirty = true;+ }+ return;+ }+ if (full || rootIDs.has(rootID)) {+ this.loadContext(record.headerElement, index === 1, true);+ }+ });+ });+ }+private updateBottomBacklinkSpacing() {if (this.type !== "bottom") {return;@@ -647,10 +912,7 @@ export class Backlink extends Model {return;}this.showingLoading = true;- this.cancelContextRequests(this.tree.element, false);- this.cancelContextRequests(this.mTree.element, true);- this.editors.forEach(item => item.destroy());- this.editors = [];+ this.resetRenderedData(false);const loadingHTML = '<div class="backlinkList__loading"><img width="32px" height="32px" src="/stage/loading-pure.svg"></div>';this.tree.element.innerHTML = loadingHTML;this.mTree.element.innerHTML = loadingHTML;@@ -659,6 +921,20 @@ export class Backlink extends Model {this.updateBottomBacklinkSpacing();}+ private resetRenderedData(resetLists: boolean) {+ this.cancelContextRequests(this.tree.element, false);+ this.cancelContextRequests(this.mTree.element, true);+ this.editors.forEach(item => item.destroy());+ this.editors = [];+ this.itemRecords.forEach(records => records.clear());+ this.listRevision = "";+ this.listQueryKey = "";+ if (resetLists) {+ this.tree.updateData(null);+ this.mTree.updateData(null);+ }+ }+public prepareForBlock(blockId: string, rootId: string) {if (!this.showingLoading) {this.saveStatus();@@ -667,6 +943,9 @@ export class Backlink extends Model {this.refreshQueued = false;this.searchQueued = false;this.dirty = false;+ this.pendingRootIDs.clear();+ this.pendingFull = false;+ this.indexChangeVersion++;this.notebookId = "";this.blockId = blockId;this.rootId = rootId;@@ -674,6 +953,46 @@ export class Backlink extends Model {this.showBottomLoading();}+ public switchBlock(blockId: string, rootId: string, notebookId: string) {+ if (this.blockId) {+ this.saveStatus();+ }+ this.requestID++;+ this.refreshQueued = false;+ this.searchQueued = false;+ this.dirty = false;+ this.pendingRootIDs.clear();+ this.pendingFull = false;+ this.indexChangeVersion++;+ this.resetRenderedData(true);+ this.blockId = blockId;+ this.rootId = rootId;+ this.notebookId = isEncryptedBox(notebookId) ? notebookId : "";+ const status = this.status[blockId];+ this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').setAttribute(+ "data-sort",+ (status?.sort ?? window.siyuan.config.editor.backlinkSort).toString(),+ );+ this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').setAttribute(+ "data-sort",+ (status?.mSort ?? window.siyuan.config.editor.backmentionSort).toString(),+ );+ this.element.querySelector('.block__icon[data-type="refresh"] svg').classList.remove("fn__rotate");+ if (!blockId) {+ this.render({+ box: "",+ backlinks: [],+ backmentions: [],+ linkRefsCount: 0,+ mentionsCount: 0,+ k: this.inputsElement[0].value,+ mk: this.inputsElement[1].value,+ }, true);+ return;+ }+ this.searchBacklinks(true);+ }+private finishRequest(requestID: number) {if (this.destroyed || requestID !== this.requestID) {return false;@@ -700,12 +1019,6 @@ export class Backlink extends Model {return;}if (element.classList.contains("fn__rotate")) {- if (!this.refreshQueued && this.type === "bottom") {- if (!this.showingLoading) {- this.saveStatus();- }- this.showBottomLoading();- }this.refreshQueued = true;return;}@@ -722,7 +1035,7 @@ export class Backlink extends Model {return;}if (!this.runQueuedRequest()) {- this.searchBacklinks();+ this.searchBacklinks(false, true);}}).finally(() => {if (responseHandled || !this.finishRequest(requestID)) {@@ -730,12 +1043,15 @@ export class Backlink extends Model {}if (!this.runQueuedRequest()) {// 即使重建索引失败,也重新读取已有的反链数据并释放加载状态。- this.searchBacklinks();+ this.searchBacklinks(false, true);}});}- private searchBacklinks(init = false) {+ private searchBacklinks(init = false, refreshAllContexts = false) {+ if (!this.blockId) {+ return;+ }const element = this.element.querySelector('.block__icon[data-type="refresh"] svg');if (element.classList.contains("fn__rotate")) {this.searchQueued = true;@@ -743,7 +1059,6 @@ export class Backlink extends Model {}this.searchQueued = false;element.classList.add("fn__rotate");- this.dirty = false;// 解析当前反链面板所属 box:优先用已记录的 notebookId,首次为空时按 rootId 在已打开的编辑器里查找let notebookId = this.notebookId;if (!notebookId && this.rootId) {@@ -765,6 +1080,21 @@ export class Backlink extends Model {if (isEncryptedBox(notebookId)) {param.notebook = notebookId;}+ const queryKey = JSON.stringify(param);+ const queryChanged = queryKey !== this.listQueryKey;+ if (!queryChanged && this.listRevision) {+ param.knownRevision = this.listRevision;+ }+ const indexChangeVersion = this.indexChangeVersion;+ const changedRootIDs = new Set(this.pendingRootIDs);+ const fullContextRefresh = shouldRefreshAllBacklinkContexts(+ changedRootIDs,+ this.rootId,+ this.blockId,+ refreshAllContexts,+ queryChanged,+ this.pendingFull,+ );const requestID = ++this.requestID;let responseHandled = false;fetchPost("/api/ref/getBacklink2", param, response => {@@ -776,10 +1106,26 @@ export class Backlink extends Model {this.runQueuedRequest();return;}+ if (!response.data) {+ if (this.showingLoading || init) {+ this.render(undefined, init);+ }+ return;+ }if (shouldSaveBacklinkStatus(init, this.showingLoading)) {this.saveStatus();}- this.render(response.data);+ this.listQueryKey = queryKey;+ this.listRevision = response.data.revision;+ if (!response.data.unchanged) {+ this.render(response.data, init);+ }+ this.refreshExpandedContexts(changedRootIDs, fullContextRefresh);+ if (indexChangeVersion === this.indexChangeVersion) {+ this.pendingRootIDs.clear();+ this.pendingFull = false;+ this.dirty = false;+ }if (this.type === "bottom" && this.dirty) {this.refreshIfVisible();}@@ -826,16 +1172,10 @@ export class Backlink extends Model {}}- public render(data: {- box: string,- backlinks: IBlockTree[],- backmentions: IBlockTree[],- linkRefsCount: number,- mentionsCount: number,- k: string,- mk: string- }) {+ public render(data?: IBacklinkListResponse, init = false) {if (!data) {+ this.listRevision = "";+ this.listQueryKey = "";data = {box: "",backlinks: [],@@ -846,18 +1186,21 @@ export class Backlink extends Model {mk: ""};}+ const wasLoading = this.showingLoading;this.showingLoading = false;- this.editors.forEach(item => {- item.destroy();- });- this.editors = [];this.element.querySelector('.block__icon[data-type="refresh"] svg').classList.remove("fn__rotate");this.notebookId = data.box;this.inputsElement[0].value = data.k;this.inputsElement[1].value = data.mk;- this.tree.updateData(data.backlinks);- this.mTree.updateData(data.backmentions);+ const backlinkAnchor = this.captureScrollAnchor(this.type === "bottom" ? undefined : this.tree);+ const mentionAnchor = this.type === "bottom" ? undefined : this.captureScrollAnchor(this.mTree);+ const backlinkChanged = this.reconcileList(this.tree, data.backlinks, false);+ const backmentionChanged = this.reconcileList(this.mTree, data.backmentions, true);+ if (backlinkChanged || backmentionChanged) {+ this.restoreScrollAnchor(backlinkAnchor);+ this.restoreScrollAnchor(mentionAnchor);+ }this.updateBottomBacklinkSpacing();const countElement = this.element.querySelector(".listCount");@@ -916,13 +1259,13 @@ export class Backlink extends Model {// restore statusthis.status[this.blockId].backlinkOpenIds.forEach(item => {const liElement = this.tree.element.querySelector(`.b3-list-item[data-node-id="${item}"]`) as HTMLElement;- if (liElement) {+ if (liElement && !liElement.querySelector(".b3-list-item__arrow--open")) {this.toggleItem(liElement, false);}});this.status[this.blockId].backlinkMOpenIds.forEach(item => {const liElement = this.mTree.element.querySelector(`.b3-list-item[data-node-id="${item}"]`) as HTMLElement;- if (liElement) {+ if (liElement && !liElement.querySelector(".b3-list-item__arrow--open")) {this.toggleItem(liElement, true);}});@@ -960,14 +1303,18 @@ export class Backlink extends Model {this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').setAttribute("data-sort", this.status[this.blockId].mSort.toString());if (this.type === "bottom") {const empty = shouldHideBottomBacklinks(data.linkRefsCount, data.mentionsCount, data.k, data.mk);- this.empty = empty;- this.emptyChange?.(empty);+ if (this.empty !== empty || wasLoading) {+ this.empty = empty;+ this.emptyChange?.(empty);+ }}- setTimeout(() => {- this.tree.element.scrollTop = this.status[this.blockId].scrollTop;- this.mTree.element.scrollTop = this.status[this.blockId].mScrollTop;- }, Constants.TIMEOUT_LOAD);+ if (init) {+ setTimeout(() => {+ this.tree.element.scrollTop = this.status[this.blockId].scrollTop;+ this.mTree.element.scrollTop = this.status[this.blockId].mScrollTop;+ }, Constants.TIMEOUT_LOAD);+ }}private restoreBottomLayout(element: HTMLElement, listElement: HTMLElement, folded: boolean) {@@ -977,18 +1324,45 @@ export class Backlink extends Model {}public markDirty() {+ this.indexChangeVersion++;this.dirty = true;+ this.pendingFull = true;+ this.itemRecords.forEach(records => records.forEach(record => {+ record.contextDirty = true;+ }));}- public refreshIfVisible(ignoreFocus = false) {- if (this.type !== "bottom" || !this.dirty) {+ public markIndexDirty(change: IBacklinkIndexChange) {+ if (!change?.backlinkChanged) {return;}- if (!this.element.isConnected || this.ownerProtyle.element.getClientRects().length === 0) {+ this.indexChangeVersion++;+ this.dirty = true;+ this.pendingFull = this.pendingFull || Boolean(change.backlinkFull);+ change.rootIDs?.forEach(rootID => this.pendingRootIDs.add(rootID));+ this.itemRecords.forEach(records => records.forEach((record, rootID) => {+ if (this.pendingFull || this.pendingRootIDs.has(rootID)) {+ record.contextDirty = true;+ }+ }));+ }++ public refreshAfterIndex() {+ if (!this.blockId || !this.dirty || this.element.contains(document.activeElement)) {return;}- if (this.empty) {+ if (this.type === "bottom") {+ this.refreshIfVisible();+ } else if (this.element.isConnected && this.element.getClientRects().length > 0) {this.searchBacklinks();+ }+ }++ public refreshIfVisible(ignoreFocus = false) {+ if (this.type !== "bottom" || !this.dirty) {+ return;+ }+ if (!this.element.isConnected || this.ownerProtyle.element.getClientRects().length === 0) {return;}if (shouldDeferBottomBacklinkRefresh(@@ -997,6 +1371,10 @@ export class Backlink extends Model {)) {return;}+ if (this.empty) {+ this.searchBacklinks();+ return;+ }if (this.element.classList.contains("fn__none") ||this.element.getClientRects().length === 0) {return;@@ -1020,6 +1398,10 @@ export class Backlink extends Model {if (this.ownerFocusoutListener) {this.ownerProtyle.element.removeEventListener("focusout", this.ownerFocusoutListener);}+ if (this.panelFocusoutListener) {+ this.element.removeEventListener("focusout", this.panelFocusoutListener);+ }+ this.visibilityObserver?.disconnect();this.editors.forEach(item => item.destroy());this.editors = [];if (this.ws) {diff --git a/app/src/layout/dock/backlinkRefresh.test.ts b/app/src/layout/dock/backlinkRefresh.test.tsindex a433bd7cb3..2915eac096 100644--- a/app/src/layout/dock/backlinkRefresh.test.ts+++ b/app/src/layout/dock/backlinkRefresh.test.ts@@ -3,6 +3,7 @@ import * as assert from "node:assert/strict";import {shouldDeferBottomBacklinkRefresh,shouldHideBottomBacklinks,+ shouldRefreshAllBacklinkContexts,shouldRenderBacklinkResponse,shouldSaveBacklinkStatus} from "./backlinkRefresh";@@ -46,3 +47,27 @@ describe("shouldHideBottomBacklinks", () => {assert.equal(shouldHideBottomBacklinks(0, 0, "", "mention"), false);});});++describe("shouldRefreshAllBacklinkContexts", () => {+ it("refreshes every expanded context when the target document changes", () => {+ assert.equal(shouldRefreshAllBacklinkContexts(+ new Set(["20260725000000-target"]),+ "20260725000000-target",+ "20260725000000-block",+ false,+ false,+ false,+ ), true);+ });++ it("keeps source-root changes scoped to their expanded context", () => {+ assert.equal(shouldRefreshAllBacklinkContexts(+ new Set(["20260725000000-source"]),+ "20260725000000-target",+ "20260725000000-block",+ false,+ false,+ false,+ ), false);+ });+});diff --git a/app/src/layout/dock/backlinkRefresh.ts b/app/src/layout/dock/backlinkRefresh.tsindex 7fd96ec9b5..4246804e1a 100644--- a/app/src/layout/dock/backlinkRefresh.ts+++ b/app/src/layout/dock/backlinkRefresh.ts@@ -18,3 +18,14 @@ export const shouldHideBottomBacklinks = () => {return linkRefsCount === 0 && mentionsCount === 0 && !backlinkKeyword && !mentionKeyword;};++export const shouldRefreshAllBacklinkContexts = (+ rootIDs: Set<string>,+ targetRootID: string,+ blockID: string,+ explicit: boolean,+ queryChanged: boolean,+ full: boolean,+) => {+ return explicit || queryChanged || full || rootIDs.has(targetRootID) || rootIDs.has(blockID);+};diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex 94ab290a1f..fc043c6e48 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -341,21 +341,7 @@ export class Protyle {let hasDeleteOp = false;data.data[0].doOperations.find((item: IOperation) => {if (this.protyle.options.backlinkData && ["delete", "move"].includes(item.action)) {- // 只对特定情况刷新,否则展开、编辑等操作刷新会频繁- /// #if !MOBILE- if (2 == data.data[0].doOperations.length && "insert" === data.data[0].doOperations[0].action && "delete" === data.data[0].doOperations[1].action) {- // 从反链面板复制块到正文粘贴时不再自动刷新反链面板- // The list in the backlink panel no longer collapses automatically https://github.com/siyuan-note/siyuan/issues/17362- return true;- }-- getAllModels().backlink.find(backlinkItem => {- if (backlinkItem.element.contains(this.protyle.element)) {- backlinkItem.refresh();- return true;- }- });- /// #endif+ // 反链上下文只展示源文档的一部分,结构操作等待索引提交后按内容版本增量同步。return true;} else {if (item.action === "delete") {diff --git a/app/src/protyle/util/reload.ts b/app/src/protyle/util/reload.tsindex dae474b60a..b7d31e0310 100644--- a/app/src/protyle/util/reload.ts+++ b/app/src/protyle/util/reload.ts@@ -50,12 +50,29 @@ export const reloadProtyle = (protyle: IProtyle, focus: boolean, updateReadonly?if (tabElement) {const inputsElement = tabElement.querySelectorAll(".b3-text-field") as NodeListOf<HTMLInputElement>;const keyword = isMention ? inputsElement[1].value : inputsElement[0].value;- fetchPost(isMention ? "/api/ref/getBackmentionDoc" : "/api/ref/getBacklinkDoc", {+ const param: IObject = {defID: protyle.element.getAttribute("data-defid"),refTreeID: protyle.block.rootID,highlight: !isSupportCSSHL(),keyword,- }, response => {+ };+ if (protyle.notebookId) {+ param.notebook = protyle.notebookId;+ }+ const revision = protyle.element.getAttribute("data-backlink-revision");+ if (revision) {+ param.knownRevision = revision;+ }+ fetchPost(isMention ? "/api/ref/getBackmentionDoc" : "/api/ref/getBacklinkDoc", param, response => {+ if (!response.data) {+ removeLoading(protyle);+ return;+ }+ protyle.element.setAttribute("data-backlink-revision", response.data.revision);+ if (response.data.unchanged) {+ removeLoading(protyle);+ return;+ }protyle.options.backlinkData = isMention ? response.data.backmentions : response.data.backlinks;renderBacklink(protyle, protyle.options.backlinkData);searchMarkRender(protyle, response.data.keywords);diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.tsindex 3c9af9561f..0fb3ef4ddd 100644--- a/app/src/protyle/wysiwyg/renderBacklink.ts+++ b/app/src/protyle/wysiwyg/renderBacklink.ts@@ -10,22 +10,124 @@ import {avRender} from "../render/av/render";import {hasClosestByAttribute} from "../util/hasClosest";import {isEncryptedBox} from "../../util/pathName";-export const renderBacklink = (protyle: IProtyle, backlinkData: {+interface IBacklinkData {+ id?: string,+ revision?: string,blockPaths: IBreadcrumb[],dom: string,expand: boolean-}[]) => {+}++interface IBacklinkDOMRecord {+ revision: string,+ anchor: HTMLElement,+}++const backlinkDOMRecords = new WeakMap<IProtyle, Map<string, IBacklinkDOMRecord>>();++const getBacklinkDOMNodes = (anchor: HTMLElement) => {+ const nodes: Node[] = [anchor];+ let next = anchor.nextSibling;+ while (next) {+ if (next instanceof HTMLElement && next.classList.contains("protyle-breadcrumb__bar") &&+ next.hasAttribute("data-backlink-id")) {+ break;+ }+ nodes.push(next);+ next = next.nextSibling;+ }+ return nodes;+};++const removeBacklinkDOMRecord = (record: IBacklinkDOMRecord) => {+ getBacklinkDOMNodes(record.anchor).forEach(item => item.parentNode?.removeChild(item));+};++const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string) => {+ const template = document.createElement("template");+ template.innerHTML = genBreadcrumb(item.blockPaths, false, index, id) + setBacklinkFold(item.dom, item.expand);+ const nodes = Array.from(template.content.childNodes);+ return {+ record: {+ revision: item.revision || "",+ anchor: nodes[0] as HTMLElement,+ },+ nodes,+ };+};++const renderBacklinkDOMNodes = (protyle: IProtyle, nodes: Node[]) => {+ nodes.forEach(item => {+ if (!(item instanceof HTMLElement)) {+ return;+ }+ improveBreadcrumbAppearance(item);+ processRender(item);+ highlightRender(item);+ avRender(item, protyle);+ blockRender(protyle, item);+ });+};++export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[]) => {protyle.block.showAll = true;- let html = "";+ const element = protyle.wysiwyg.element;+ let records = backlinkDOMRecords.get(protyle);+ if (!records) {+ records = new Map<string, IBacklinkDOMRecord>();+ backlinkDOMRecords.set(protyle, records);+ element.replaceChildren();+ }++ const ids = new Set(backlinkData.map((item, index) => item.id || `legacy-${index}`));+ records.forEach((record, id) => {+ if (!ids.has(id)) {+ removeBacklinkDOMRecord(record);+ records.delete(id);+ }+ });++ const changedNodes: Node[][] = [];+ const orderedRecords: IBacklinkDOMRecord[] = [];backlinkData.forEach((item, index) => {- html += genBreadcrumb(item.blockPaths, false, index) + setBacklinkFold(item.dom, item.expand);+ const id = item.id || `legacy-${index}`;+ let record = records.get(id);+ if (record && record.anchor.parentElement !== element) {+ records.delete(id);+ record = undefined;+ }+ if (!record || !item.revision || record.revision !== item.revision) {+ const created = createBacklinkDOMRecord(item, index, id);+ if (record) {+ created.nodes.forEach(node => element.insertBefore(node, record.anchor));+ removeBacklinkDOMRecord(record);+ } else {+ created.nodes.forEach(node => element.appendChild(node));+ }+ record = created.record;+ records.set(id, record);+ changedNodes.push(created.nodes);+ }+ orderedRecords.push(record);+ });++ let cursor = element.firstChild;+ orderedRecords.forEach((record, index) => {+ const nodes = getBacklinkDOMNodes(record.anchor);+ if (nodes[0] !== cursor) {+ const fragment = document.createDocumentFragment();+ nodes.forEach(node => fragment.appendChild(node));+ element.insertBefore(fragment, cursor);+ }+ cursor = nodes[nodes.length - 1].nextSibling;+ if (record.anchor.style.width === "100%") {+ const borderTop = index === 0 ? "0px" : "1px solid var(--b3-border-color)";+ if (record.anchor.style.borderTop !== borderTop) {+ record.anchor.style.borderTop = borderTop;+ }+ }});- protyle.wysiwyg.element.innerHTML = html;- improveBreadcrumbAppearance(protyle.wysiwyg.element);- processRender(protyle.wysiwyg.element);- highlightRender(protyle.wysiwyg.element);- avRender(protyle.wysiwyg.element, protyle);- blockRender(protyle, protyle.wysiwyg.element);+ changedNodes.forEach(nodes => renderBacklinkDOMNodes(protyle, nodes));removeLoading(protyle);if (window.siyuan.config.readonly || window.siyuan.config.editor.readOnly) {disabledProtyle(protyle);@@ -101,9 +203,10 @@ export const getBacklinkHeadingMore = (moreElement: HTMLElement) => {moreElement.remove();};-export const genBreadcrumb = (blockPaths: IBreadcrumb[], renderFirst: boolean, parentIndex?: number) => {+export const genBreadcrumb = (blockPaths: IBreadcrumb[], renderFirst: boolean, parentIndex?: number, backlinkID?: string) => {+ const backlinkAttr = backlinkID ? ` data-backlink-id="${backlinkID}"` : "";if (1 > blockPaths.length) {- return `<div contenteditable="false" style="border-top: ${parentIndex === 0 ? 0 : 1}px solid var(--b3-border-color);min-height: 0;width: 100%;" class="protyle-breadcrumb__bar"><span></span></div>`;+ return `<div${backlinkAttr} contenteditable="false" style="border-top: ${parentIndex === 0 ? 0 : 1}px solid var(--b3-border-color);min-height: 0;width: 100%;" class="protyle-breadcrumb__bar"><span></span></div>`;}let html = "";@@ -119,11 +222,16 @@ export const genBreadcrumb = (blockPaths: IBreadcrumb[], renderFirst: boolean, phtml += '<svg class="protyle-breadcrumb__arrow"><use xlink:href="#iconRight"></use></svg>';}});- return `<div contenteditable="false" class="protyle-breadcrumb__bar protyle-breadcrumb__bar--nowrap">${html}</div>`;+ return `<div${backlinkAttr} contenteditable="false" class="protyle-breadcrumb__bar protyle-breadcrumb__bar--nowrap">${html}</div>`;};export const improveBreadcrumbAppearance = (element: HTMLElement) => {- element.querySelectorAll(".protyle-breadcrumb__bar").forEach((item: HTMLElement) => {+ const elements: HTMLElement[] = [];+ if (element.classList.contains("protyle-breadcrumb__bar")) {+ elements.push(element);+ }+ elements.push(...Array.from(element.querySelectorAll(".protyle-breadcrumb__bar")) as HTMLElement[]);+ elements.forEach((item: HTMLElement) => {item.classList.remove("protyle-breadcrumb__bar--nowrap");const itemElements = Array.from(item.querySelectorAll(".protyle-breadcrumb__text"));if (itemElements.length === 0) {diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 2d443596d0..e2f97e62fa 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -868,6 +868,7 @@ interface IFile {interface IBlockTree {box: string,+ revision?: string,number?: string,nodeType: string,hPath: string,diff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.tsindex 6d22ed9b4d..7bddb8383f 100644--- a/app/src/types/protyle.d.ts+++ b/app/src/types/protyle.d.ts@@ -470,6 +470,8 @@ interface IProtyleOptions {snapshot?: string},backlinkData?: {+ id?: string,+ revision?: string,blockPaths: IBreadcrumb[],dom: stringexpand: booleandiff --git a/app/src/util/Tree.ts b/app/src/util/Tree.tsindex fdd12954ff..deb91b2f70 100644--- a/app/src/util/Tree.ts+++ b/app/src/util/Tree.ts@@ -63,6 +63,14 @@ export class Tree {}}+ public createTopLevelItem(data: IBlockTree) {+ const template = document.createElement("template");+ template.innerHTML = this.genHTML([data]);+ const element = template.content.querySelector(".b3-list > .b3-list-item") as HTMLLIElement;+ mathRender(element);+ return element;+ }+private genHTML(data: (IBlockTree & { folded?: boolean })[]) {const isM = isMobile();let html = `<ul${data[0].depth === 0 ? " class='b3-list b3-list--background'" : ""}>`;diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex 359bf256a5..428040efe1 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -13,7 +13,7 @@ import {progressBackgroundTask,progressLoading,progressStatus,- scheduleBacklinkRefresh,+ processBacklinkIndexCommit,setDefRefCount,setRefDynamicText,transactionError@@ -62,8 +62,8 @@ class App {case "setDefRefCount":setDefRefCount(data.data);break;- case "transactions":- scheduleBacklinkRefresh();+ case "databaseIndexCommit":+ processBacklinkIndexCommit(data.data);break;case "setRefDynamicText":setRefDynamicText(data.data);@@ -109,7 +109,6 @@ class App {});break;case "rename":- scheduleBacklinkRefresh();getAllTabs().forEach((tab) => {if (tab.headElement) {const initTab = tab.headElement.getAttribute("data-initdata");diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 9d5cb80d28..bde5ee43d2 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -62,18 +62,15 @@ func getBackmentionDoc(c *gin.Context) {defID := arg["defID"].(string)refTreeID := arg["refTreeID"].(string)- if !isBacklinkDocAccessible(c, refTreeID) {- ret.Data = map[string]any{- "backmentions": []*model.Backlink{},- "keywords": []string{},- }- return- }+ knownRevision, _ := arg["knownRevision"].(string)keyword := arg["keyword"].(string)var notebook stringif val, ok := arg["notebook"]; ok {notebook = val.(string)}+ if notebook != "" && !model.IsEncryptedBox(notebook) {+ notebook = ""+ }containChildren := model.Conf.Editor.BacklinkContainChildrenif val, ok := arg["containChildren"]; ok {containChildren = val.(bool)@@ -82,17 +79,33 @@ func getBackmentionDoc(c *gin.Context) {if val, ok := arg["highlight"]; ok {highlight = val.(bool)}+var backlinks []*model.Backlinkvar keywords []string- if notebook != "" && model.IsEncryptedBox(notebook) {+ if !isBacklinkDocAccessible(c, refTreeID) {+ backlinks, keywords = []*model.Backlink{}, []string{}+ } else if notebook != "" && model.IsEncryptedBox(notebook) {backlinks, keywords = model.GetBackmentionDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)} else {backlinks, keywords = model.GetBackmentionDoc(defID, refTreeID, keyword, containChildren, highlight)}- ret.Data = map[string]any{- "backmentions": backlinks,- "keywords": keywords,+ keywords = canonicalBacklinkKeywords(keywords)+ items := newBacklinkContextResponses(backlinks)+ revision := hashBacklinkRevision("bc1:", struct {+ DefID string+ RefTreeID string+ Keyword string+ Notebook string+ ContainChildren bool+ Highlight bool+ Items []*backlinkContextResponse+ Keywords []string+ }{defID, refTreeID, keyword, notebook, containChildren, highlight, items, keywords})+ if knownRevision == revision {+ ret.Data = &backlinkContextResult{Unchanged: true, Revision: revision}+ return}+ ret.Data = &backlinkContextResult{Revision: revision, Backmentions: items, Keywords: keywords}}func getBacklinkDoc(c *gin.Context) {@@ -106,18 +119,15 @@ func getBacklinkDoc(c *gin.Context) {defID := arg["defID"].(string)refTreeID := arg["refTreeID"].(string)- if !isBacklinkDocAccessible(c, refTreeID) {- ret.Data = map[string]any{- "backlinks": []*model.Backlink{},- "keywords": []string{},- }- return- }+ knownRevision, _ := arg["knownRevision"].(string)keyword := arg["keyword"].(string)var notebook stringif val, ok := arg["notebook"]; ok {notebook = val.(string)}+ if notebook != "" && !model.IsEncryptedBox(notebook) {+ notebook = ""+ }containChildren := model.Conf.Editor.BacklinkContainChildrenif val, ok := arg["containChildren"]; ok {containChildren = val.(bool)@@ -126,17 +136,33 @@ func getBacklinkDoc(c *gin.Context) {if val, ok := arg["highlight"]; ok {highlight = val.(bool)}+var backlinks []*model.Backlinkvar keywords []string- if notebook != "" && model.IsEncryptedBox(notebook) {+ if !isBacklinkDocAccessible(c, refTreeID) {+ backlinks, keywords = []*model.Backlink{}, []string{}+ } else if notebook != "" && model.IsEncryptedBox(notebook) {backlinks, keywords = model.GetBacklinkDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)} else {backlinks, keywords = model.GetBacklinkDoc(defID, refTreeID, keyword, containChildren, highlight)}- ret.Data = map[string]any{- "backlinks": backlinks,- "keywords": keywords,+ keywords = canonicalBacklinkKeywords(keywords)+ items := newBacklinkContextResponses(backlinks)+ revision := hashBacklinkRevision("bc1:", struct {+ DefID string+ RefTreeID string+ Keyword string+ Notebook string+ ContainChildren bool+ Highlight bool+ Items []*backlinkContextResponse+ Keywords []string+ }{defID, refTreeID, keyword, notebook, containChildren, highlight, items, keywords})+ if knownRevision == revision {+ ret.Data = &backlinkContextResult{Unchanged: true, Revision: revision}+ return}+ ret.Data = &backlinkContextResult{Revision: revision, Backlinks: items, Keywords: keywords}}func getBacklink2(c *gin.Context) {@@ -153,6 +179,7 @@ func getBacklink2(c *gin.Context) {}id := arg["id"].(string)+ knownRevision, _ := arg["knownRevision"].(string)keyword := arg["k"].(string)mentionKeyword := arg["mk"].(string)sortArg := arg["sort"]@@ -173,7 +200,8 @@ func getBacklink2(c *gin.Context) {var backlinks, backmentions []*model.Pathvar linkRefsCount, mentionsCount int// 加密笔记本的反链面板走 InBox 版(查加密 content db)- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {+ notebook, _ := arg["notebook"].(string)+ if notebook != "" && model.IsEncryptedBox(notebook) {boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBox(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook)} else {boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2(id, keyword, mentionKeyword, sort, mentionSort, containChildren)@@ -182,16 +210,52 @@ func getBacklink2(c *gin.Context) {publishAccess := model.GetPublishAccess()backlinks = model.FilterPathsByPublishAccess(c, publishAccess, backlinks)backmentions = model.FilterPathsByPublishAccess(c, publishAccess, backmentions)+ linkRefsCount = countBacklinkPaths(backlinks)+ mentionsCount = countBacklinkPaths(backmentions)+ }+ backlinkResponses := newBacklinkPathResponses(backlinks)+ backmentionResponses := newBacklinkPathResponses(backmentions)+ response := &backlinkListResponse{+ Backlinks: backlinkResponses,+ LinkRefsCount: linkRefsCount,+ Backmentions: backmentionResponses,+ MentionsCount: mentionsCount,+ K: keyword,+ MK: mentionKeyword,+ Box: boxID,+ }+ response.Revision = hashBacklinkRevision("bl1:", struct {+ ID string+ Keyword string+ MentionKeyword string+ Sort int+ MentionSort int+ ContainChildren bool+ Notebook string+ Backlinks []string+ LinkRefsCount int+ Backmentions []string+ MentionsCount int+ Box string+ }{+ id,+ keyword,+ mentionKeyword,+ sort,+ mentionSort,+ containChildren,+ notebook,+ backlinkPathRevisions(backlinkResponses),+ linkRefsCount,+ backlinkPathRevisions(backmentionResponses),+ mentionsCount,+ boxID,+ })+ if knownRevision == response.Revision {+ ret.Data = &backlinkListResponse{Unchanged: true, Revision: response.Revision}+ return}- ret.Data = map[string]any{- "backlinks": backlinks,- "linkRefsCount": linkRefsCount,- "backmentions": backmentions,- "mentionsCount": mentionsCount,- "k": keyword,- "mk": mentionKeyword,- "box": boxID,- }+ ret.Data = response}func getBacklink(c *gin.Context) {diff --git a/kernel/api/ref_revision.go b/kernel/api/ref_revision.gonew file mode 100644index 0000000000..e911f0a27d--- /dev/null+++ b/kernel/api/ref_revision.go@@ -0,0 +1,149 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "sort"++ "github.com/siyuan-note/siyuan/kernel/model"+)++type backlinkPathResponse struct {+ *model.Path+ Revision string `json:"revision"`+}++type backlinkContextResponse struct {+ ID string `json:"id"`+ DOM string `json:"dom"`+ BlockPaths []*model.BlockPath `json:"blockPaths"`+ Expand bool `json:"expand"`+ Revision string `json:"revision"`+}++type backlinkListResponse struct {+ Unchanged bool `json:"unchanged"`+ Revision string `json:"revision"`+ Backlinks []*backlinkPathResponse `json:"backlinks"`+ LinkRefsCount int `json:"linkRefsCount"`+ Backmentions []*backlinkPathResponse `json:"backmentions"`+ MentionsCount int `json:"mentionsCount"`+ K string `json:"k"`+ MK string `json:"mk"`+ Box string `json:"box"`+}++type backlinkContextResult struct {+ Unchanged bool `json:"unchanged"`+ Revision string `json:"revision"`+ Backlinks []*backlinkContextResponse `json:"backlinks"`+ Backmentions []*backlinkContextResponse `json:"backmentions"`+ Keywords []string `json:"keywords"`+}++func newBacklinkPathResponses(paths []*model.Path) (ret []*backlinkPathResponse) {+ ret = make([]*backlinkPathResponse, 0, len(paths))+ for _, item := range paths {+ ret = append(ret, &backlinkPathResponse{+ Path: item,+ Revision: hashBacklinkRevision("bi1:", struct {+ ID string+ Box string+ Name string+ Number string+ HPath string+ Type string+ NodeType string+ SubType string+ Depth int+ Count int+ Folded bool+ }{+ item.ID,+ item.Box,+ item.Name,+ item.Number,+ item.HPath,+ item.Type,+ item.NodeType,+ item.SubType,+ item.Depth,+ item.Count,+ item.Folded,+ }),+ })+ }+ return+}++func backlinkPathRevisions(items []*backlinkPathResponse) (ret []string) {+ ret = make([]string, 0, len(items))+ for _, item := range items {+ ret = append(ret, item.Revision)+ }+ return+}++func canonicalBacklinkKeywords(keywords []string) []string {+ ret := append([]string{}, keywords...)+ sort.Slice(ret, func(i, j int) bool {+ if len(ret[i]) == len(ret[j]) {+ return ret[i] < ret[j]+ }+ return len(ret[i]) > len(ret[j])+ })+ return ret+}++func newBacklinkContextResponses(backlinks []*model.Backlink) (ret []*backlinkContextResponse) {+ ret = make([]*backlinkContextResponse, 0, len(backlinks))+ for _, item := range backlinks {+ response := &backlinkContextResponse{+ ID: item.ID,+ DOM: item.DOM,+ BlockPaths: item.BlockPaths,+ Expand: item.Expand,+ }+ response.Revision = hashBacklinkRevision("bci1:", struct {+ ID string+ DOM string+ BlockPaths []*model.BlockPath+ Expand bool+ }{response.ID, response.DOM, response.BlockPaths, response.Expand})+ ret = append(ret, response)+ }+ return+}++func hashBacklinkRevision(prefix string, value any) string {+ data, err := json.Marshal(value)+ if err != nil {+ return prefix+ }+ sum := sha256.Sum256(data)+ return prefix + hex.EncodeToString(sum[:])+}++func countBacklinkPaths(paths []*model.Path) (ret int) {+ for _, item := range paths {+ ret += item.Count+ }+ return+}diff --git a/kernel/api/ref_revision_test.go b/kernel/api/ref_revision_test.gonew file mode 100644index 0000000000..c9aef9f8c5--- /dev/null+++ b/kernel/api/ref_revision_test.go@@ -0,0 +1,80 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestHashBacklinkRevision(t *testing.T) {+ value := struct {+ ID string+ Name string+ }{"20260725000000-test", "foo"}+ first := hashBacklinkRevision("bl1:", value)+ second := hashBacklinkRevision("bl1:", value)+ if first != second {+ t.Fatalf("expected stable revision, got %q and %q", first, second)+ }++ value.Name = "bar"+ changed := hashBacklinkRevision("bl1:", value)+ if first == changed {+ t.Fatalf("expected changed revision, got %q", changed)+ }+}++func TestCanonicalBacklinkKeywords(t *testing.T) {+ keywords := []string{"beta", "alphabet", "alpha"}+ canonical := canonicalBacklinkKeywords(keywords)+ if canonical[0] != "alphabet" || canonical[1] != "alpha" || canonical[2] != "beta" {+ t.Fatalf("unexpected canonical keywords: %#v", canonical)+ }+ if keywords[0] != "beta" {+ t.Fatalf("expected source keywords to remain unchanged: %#v", keywords)+ }+}++func TestNewBacklinkResponses(t *testing.T) {+ paths := []*model.Path{{ID: "20260725000000-source", Name: "Source", Count: 2}}+ pathResponses := newBacklinkPathResponses(paths)+ if len(pathResponses) != 1 || pathResponses[0].Revision == "" {+ t.Fatalf("expected path revision, got %#v", pathResponses)+ }+ paths[0].Updated = "20260725235959"+ updatedPathResponses := newBacklinkPathResponses(paths)+ if pathResponses[0].Revision != updatedPathResponses[0].Revision {+ t.Fatal("expected a timestamp-only change to preserve the visible item revision")+ }+ paths[0].Name = "Changed"+ changedPathResponses := newBacklinkPathResponses(paths)+ if pathResponses[0].Revision == changedPathResponses[0].Revision {+ t.Fatal("expected a visible path change to update the item revision")+ }++ contexts := []*model.Backlink{{+ ID: "20260725000000-ref",+ DOM: `<div data-node-id="20260725000000-ref"></div>`,+ Expand: true,+ }}+ contextResponses := newBacklinkContextResponses(contexts)+ if len(contextResponses) != 1 || contextResponses[0].ID != contexts[0].ID || contextResponses[0].Revision == "" {+ t.Fatalf("expected context ID and revision, got %#v", contextResponses)+ }+}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex dba366d876..6bb7c38851 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -70,6 +70,7 @@ func refreshRefsByDefID(defID string) {}type Backlink struct {+ ID string `json:"id"`DOM string `json:"dom"`BlockPaths []*BlockPath `json:"blockPaths"`Expand bool `json:"expand"`@@ -382,7 +383,7 @@ func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[stif 1 > len(blockPaths) {blockPaths = []*BlockPath{}}- ret = &Backlink{DOM: dom, BlockPaths: blockPaths, Expand: expand, node: node}+ ret = &Backlink{ID: refID, DOM: dom, BlockPaths: blockPaths, Expand: expand, node: node}return}diff --git a/kernel/sql/queue.go b/kernel/sql/queue.goindex 46f6b1f6b4..32b9b60b18 100644--- a/kernel/sql/queue.go+++ b/kernel/sql/queue.go@@ -23,6 +23,7 @@ import ("math""path""runtime/debug"+ "sort""sync""sync/atomic""time"@@ -55,6 +56,81 @@ type dbQueueOperation struct {removeAssetHashes []string // delete_assets}+type backlinkIndexChange struct {+ rootIDs map[string]struct{}+ changed bool+ full bool+}++func newBacklinkIndexChange() *backlinkIndexChange {+ return &backlinkIndexChange{rootIDs: map[string]struct{}{}}+}++func (change *backlinkIndexChange) addRootID(rootID string) {+ if rootID == "" {+ change.full = true+ return+ }+ change.rootIDs[rootID] = struct{}{}+}++func (change *backlinkIndexChange) addOperation(op *dbQueueOperation) {+ switch op.action {+ case "index", "rename", "move":+ change.changed = true+ if op.indexTree == nil {+ change.full = true+ } else {+ change.addRootID(op.indexTree.ID)+ }+ case "upsert", "update_refs", "delete_refs":+ change.changed = true+ if op.upsertTree == nil {+ change.full = true+ } else {+ change.addRootID(op.upsertTree.ID)+ }+ case "update_block_content":+ change.changed = true+ if op.block == nil {+ change.full = true+ } else {+ change.addRootID(op.block.RootID)+ }+ case "delete_id":+ change.changed = true+ change.addRootID(op.removeTreeID)+ case "delete_ids":+ change.changed = true+ for _, rootID := range op.removeTreeIDs {+ change.addRootID(rootID)+ }+ case "index_node":+ change.changed = true+ if bt := treenode.GetBlockTree(op.id); bt != nil {+ change.addRootID(bt.RootID)+ } else {+ change.full = true+ }+ case "delete", "delete_box", "delete_box_refs":+ change.changed = true+ change.full = true+ }+}++func (change *backlinkIndexChange) data() map[string]any {+ rootIDs := make([]string, 0, len(change.rootIDs))+ for rootID := range change.rootIDs {+ rootIDs = append(rootIDs, rootID)+ }+ sort.Strings(rootIDs)+ return map[string]any{+ "rootIDs": rootIDs,+ "backlinkChanged": change.changed,+ "backlinkFull": change.full,+ }+}+// boxID 从 op 提取目标 boxID,供 beginTxForBox 路由到加密 db 或全局 db。// delete_ids/delete_assets 无 box 上下文,返回空串 → 走全局 db。func (op *dbQueueOperation) boxID() string {@@ -181,6 +257,7 @@ func FlushQueue() {}groupOpsCurrent := map[string]int{}+ backlinkChange := newBacklinkIndexChange()for i, op := range ops {if util.IsExiting.Load() {return@@ -205,6 +282,7 @@ func FlushQueue() {logging.LogErrorf("commit tx failed: %s", err)continue}+ backlinkChange.addOperation(op)switch op.action {case "index":@@ -232,7 +310,7 @@ func FlushQueue() {}// Push database index commit event https://github.com/siyuan-note/siyuan/issues/8814- util.BroadcastByType("main", "databaseIndexCommit", 0, "", nil)+ util.BroadcastByType("main", "databaseIndexCommit", 0, "", backlinkChange.data())eventbus.Publish(eventbus.EvtSQLIndexFlushed)diff --git a/kernel/sql/queue_backlink_test.go b/kernel/sql/queue_backlink_test.gonew file mode 100644index 0000000000..f38181df66--- /dev/null+++ b/kernel/sql/queue_backlink_test.go@@ -0,0 +1,46 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package sql++import "testing"++func TestBacklinkIndexChange(t *testing.T) {+ change := newBacklinkIndexChange()+ change.addOperation(&dbQueueOperation{+ action: "update_block_content",+ block: &Block{RootID: "20260725000000-source"},+ })+ change.addOperation(&dbQueueOperation{+ action: "delete_ids",+ removeTreeIDs: []string{"20260725000000-deleted"},+ })+ change.addOperation(&dbQueueOperation{action: "delete_assets"})++ data := change.data()+ if !data["backlinkChanged"].(bool) || data["backlinkFull"].(bool) {+ t.Fatalf("unexpected change flags: %#v", data)+ }+ rootIDs := data["rootIDs"].([]string)+ if len(rootIDs) != 2 || rootIDs[0] != "20260725000000-deleted" || rootIDs[1] != "20260725000000-source" {+ t.Fatalf("unexpected root IDs: %#v", rootIDs)+ }++ change.addOperation(&dbQueueOperation{action: "delete_box"})+ if !change.data()["backlinkFull"].(bool) {+ t.Fatal("expected full backlink change")+ }+}