An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Unify mobile and desktop backlinks and remove the legacy API https://github.com/siyuan-note/siyuan/issues/19250
Danielb05d6ee69a49
diff --git a/app/scripts/mobileBacklinks.test.js b/app/scripts/mobileBacklinks.test.jsnew file mode 100644index 0000000000..1fcacb4d6c--- /dev/null+++ b/app/scripts/mobileBacklinks.test.js@@ -0,0 +1,248 @@+const assert = require("node:assert/strict");+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");+const path = require("node:path");+const os = require("node:os");++const sources = () => {+ const ts = require("typescript");+ const preprocess = require("ifdef-loader/preprocessor").parse;+ const modules = {};+ for (const name of ["layout/dock/BacklinkContent", "layout/dock/backlinkRefresh",+ "layout/dock/backlinkReadingAnchor", "layout/dock/backlinkSourceFilter", "mobile/util/secondaryEditors",+ "mobile/util/backlinkPanels", "mobile/util/openBacklinks", "protyle/util/transactionQueue",+ "util/escape", "dialog/index"]) {+ modules[name] = ts.transpileModule(preprocess(+ readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"),+ {MOBILE: true, BROWSER: true}, false, true), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+ }).outputText;+ }+ return modules;+};++const runCases = async (sources) => {+ const assert = require("node:assert/strict");+ const cache = {};+ const noop = () => {};+ const requests = [];+ const tick = () => new Promise(resolve => setTimeout(resolve, 10));+ const stubs = {+ "layout/Model": {Model: class {constructor({app}) {this.app = app;} connect() {throw Error("mobile panel opened a desktop socket");}}},+ "util/Tree": {Tree: class {+ constructor(options) {this.element = options.element; this.options = options;}+ updateData() {this.element.replaceChildren();}+ createTopLevelItem(item) {+ const li = document.createElement("li");+ li.className = "b3-list-item";+ li.dataset.nodeId = item.id;+ li.dataset.notebookId = item.box;+ li.innerHTML = '<span><svg class="b3-list-item__arrow"></svg></span><span class="b3-list-item__text"></span>';+ li.lastElementChild.textContent = item.name;+ li.addEventListener("click", () => this.options.click(li));+ return li;+ }+ }},+ "mobile/editor": {openMobileFileById: noop},+ "util/fetch": {fetchPost: (url, data, callback) => new Promise(resolve => {+ requests.push({url, data, reply: response => {callback?.({data: response}); resolve();}});+ })},+ "constants": {Constants: {TIMEOUT_LOAD: 0, TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0}},+ "protyle/util/compatibility": {updateHotkeyAfterTip: () => "", isNotCtrl: () => true},+ "protyle/index": {Protyle: class {+ constructor(app, element, options) {+ element.className = "protyle";+ element.innerHTML = '<div class="protyle-wysiwyg" contenteditable="true">reference context</div>';+ this.protyle = {app, element, notebookId: options.notebookId, block: {rootID: options.blockId}, options,+ wysiwyg: {element: element.firstElementChild, flushPendingInput: async () => {}}};+ }+ destroy() {load("mobile/util/secondaryEditors").unregisterMobileSecondaryEditor(this); this.destroyed = true;}+ }},+ "menus/Menu": {MenuItem: class {}},+ "protyle/render/searchMarkRender": {isSupportCSSHL: () => true, searchMarkRender: noop},+ "util/pathName": {getDocDisplayName: item => item.name, isEncryptedBox: () => false},+ "layout/getAll": {getAllEditor: () => []},+ "util/functions": {isMobile: () => true},+ "protyle/ui/hideElements": {hideElements: noop},+ "protyle/wysiwyg/renderBacklink": {renderBacklink: async () => {}},+ "util/heightAnimation": {cancelHeightAnimation: noop, isHeightAnimating: () => false},+ "util/viewState": {ViewStateService: class {+ constructor() {this.ready = Promise.resolve(); this.values = new Map();}+ get(key) {return this.values.get(key);}+ set(key, value) {this.values.set(key, value);}+ has(key) {return this.values.has(key);}+ remove(key) {this.values.delete(key);}+ async destroy() {}+ }},+ "protyle/util/viewFold": {applyViewFoldStates: async () => {}, invalidateViewFoldRequests: noop,+ registerViewFoldContext: async () => {}, unregisterViewFoldContext: noop},+ "dialog/moveResize": {moveResize: noop},+ "util/genID": {genUUID: () => Math.random().toString()},+ "dialog/message": {showMessage: noop},+ "mobile/util/keyboardToolbar": {activeBlur: () => document.activeElement.blur()},+ };+ const load = name => {+ if (stubs[name]) {return stubs[name];}+ if (stubs[name + "/index"]) {return stubs[name + "/index"];}+ if (!sources[name] && sources[name + "/index"]) {return load(name + "/index");}+ if (!cache[name]) {+ assert.ok(sources[name], "unexpected module " + name);+ cache[name] = {};+ const resolve = dependency => load(require("node:path").posix.normalize(+ require("node:path").posix.dirname(name) + "/" + dependency));+ new Function("require", "exports", sources[name])(resolve, cache[name]);+ }+ return cache[name];+ };+ const style = document.createElement("style");+ style.textContent = ".fn__none{display:none!important}.protyle{min-height:32px}.panel{height:400px}";+ document.head.appendChild(style);+ const key = {custom: ""};+ window.siyuan = {config: {editor: {backlinkSort: 0, backmentionSort: 0, backlinkExpandCount: 0,+ backmentionExpandCount: 0}, keymap: {editor: {general: {expand: key, collapse: key}}, general: {closeTab: key}}},+ languages: new Proxy({}, {get: (target, property) => property}), dialogs: [], zIndex: 10,+ menus: {menu: {remove: noop, element: document.createElement("div")}}};+ const {BacklinkContent} = load("layout/dock/BacklinkContent");+ const registry = load("mobile/util/secondaryEditors");+ const panels = load("mobile/util/backlinkPanels");+ const element = document.createElement("div");+ element.className = "panel";+ document.body.appendChild(element);+ const panel = new BacklinkContent({app: {}, element, blockId: "host", rootId: "host", notebookId: "box",+ type: "local", surface: "mobile-sheet", onlyBacklinks: true});+ const unregister = panels.registerMobileBacklinkPanel(panel);+ await tick();+ assert.equal(requests.length, 1);+ assert.equal(requests[0].url, "/api/ref/getBacklink2");+ assert.equal(requests[0].data.includeMentions, false);+ const list = {box: "box", backlinks: [{id: "ref", box: "box", name: "Source", revision: "1"}],+ backmentions: [], linkRefsCount: 1, mentionsCount: 0, k: "", mk: "", revision: "list1"};+ requests.shift().reply(list);+ await tick();+ assert.equal(panel.editors.length, 0, "collapsed document must not allocate an editor");+ assert.equal(requests.length, 0, "collapsed document must not fetch context");+ element.querySelector('.b3-list-item[data-node-id="ref"]').click();+ assert.equal(requests[0].url, "/api/ref/getBacklinkDoc");+ requests.shift().reply({revision: "ctx1", backlinks: [{id: "ref-block"}], keywords: []});+ await tick();+ assert.equal(panel.editors.length, 1);+ const editor = panel.editors[0];+ assert.deepEqual(registry.getMobileSecondaryEditors(), [editor]);+ panel.markIndexDirty({backlinkChanged: true, backlinkFull: true});+ panel.refreshAfterIndex();+ const inFlight = requests.shift();+ editor.protyle.wysiwyg.element.focus();+ assert.equal(registry.getActiveMobileSecondaryEditor(), editor);+ inFlight.reply({...list, backlinks: [], linkRefsCount: 0, revision: "list2"});+ await tick();+ assert.equal(panel.editors[0], editor, "a response started before focus must not replace the active editor");+ panel.markIndexDirty({backlinkChanged: true, backlinkFull: true});+ panel.refreshAfterIndex();+ assert.equal(requests.length, 0, "index refresh must defer while editing");+ const toolbar = document.createElement("button");+ document.body.appendChild(toolbar);+ toolbar.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));+ assert.equal(registry.getActiveMobileSecondaryEditor(), editor, "keyboard toolbar must keep its source editor");+ element.querySelector('.b3-list-item[data-node-id="ref"]').click();+ assert.equal(editor.destroyed, undefined, "folding must retain pending mobile input");+ assert.equal(registry.getActiveMobileSecondaryEditor(), undefined, "folded editor must stop receiving commands");+ element.querySelector('.b3-list-item[data-node-id="ref"]').click();+ let finishInput;+ editor.protyle.wysiwyg.flushPendingInput = () => new Promise(resolve => {finishInput = resolve;});+ editor.protyle.wysiwyg.element.focus();+ toolbar.focus();+ editor.protyle.wysiwyg.flushPendingInput = async () => {};+ let flushed = false;+ const flushing = registry.flushMobileSecondaryEditor(editor).then(() => {flushed = true;});+ await tick();+ assert.equal(flushed, false, "closing must await input already started by focusout");+ finishInput();+ await flushing;+ assert.equal(flushed, true);+ editor.protyle.wysiwyg.element.focus();+ const main = document.createElement("div");+ main.className = "protyle";+ main.innerHTML = '<div contenteditable="true">main document</div>';+ document.body.appendChild(main);+ main.firstElementChild.focus();+ assert.equal(registry.getActiveMobileSecondaryEditor(), undefined, "keyboard focus must return commands to the main editor");+ panels.removeMobileBacklinkContent({notebookId: "box"});+ assert.equal(panel.editors.length, 0);+ assert.equal(registry.getMobileSecondaryEditors().length, 0);+ for (const request of requests.splice(0)) {request.reply(list);}+ await tick();+ assert.equal(panel.blockId, "", "stale index responses must not restore locked content");+ assert.equal(panel.editors.length, 0);+ unregister();+ panel.destroy();++ const ownerElement = document.createElement("div");+ document.body.appendChild(ownerElement);+ const owner = {app: {}, element: ownerElement, block: {rootID: "host"}, notebookId: "box"};+ await load("mobile/util/openBacklinks").openMobileBacklinks(owner, "host");+ const sheet = panels.getMobileBacklinkPanels()[0];+ assert.ok(sheet instanceof BacklinkContent, "sheet must use the shared implementation");+ let finishSave;+ const save = new Promise(resolve => {finishSave = resolve;});+ const sheetEditor = new stubs["protyle/index"].Protyle({}, document.createElement("div"), {blockId: "ref"});+ sheet.element.appendChild(sheetEditor.protyle.element);+ sheet.editors.push(sheetEditor);+ registry.registerMobileSecondaryEditor(sheetEditor, noop);+ sheetEditor.protyle.wysiwyg.flushPendingInput = () => save;+ const closing = panels.closeMobileBacklinkSheets();+ await tick();+ assert.equal(sheetEditor.destroyed, undefined, "sheet must remain mounted until pending input completes");+ finishSave();+ await closing;+ assert.equal(sheetEditor.destroyed, true);+ assert.equal(panels.getMobileBacklinkPanels().length, 0);+ assert.equal(registry.getMobileSecondaryEditors().length, 0);+ for (const request of requests.splice(0)) {request.reply(list);}+ await tick();+ assert.equal(window.siyuan.dialogs.length, 0);+ return "Mobile backlink lifecycle cases passed";+};++if (process.versions.electron && process.type === "browser") {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {+ nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true,+ }});+ let code = 0;+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ win.webContents.debugger.attach("1.3");+ await win.webContents.debugger.sendCommand("Emulation.setFocusEmulationEnabled", {enabled: true});+ console.log(await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources())})`));+ } catch (error) {+ console.error(error);+ code = 1;+ } finally {+ win.destroy();+ app.exit(code);+ }+ });+} else {+ const {it} = require("node:test");+ const {execFile} = require("node:child_process");+ const {promisify} = require("node:util");+ it("shares mobile backlink rendering and preserves editor lifecycle", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-mobile-backlinks-"));+ try {+ const {stdout} = await promisify(execFile)(require("electron"), [__filename, profile], {+ env, windowsHide: true, timeout: 40000,+ });+ assert.match(stdout, /Mobile backlink lifecycle cases passed/);+ } finally {+ assert.equal(path.dirname(profile), os.tmpdir());+ assert.ok(path.basename(profile).startsWith("siyuan-mobile-backlinks-"));+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex b4b79506f2..7da98d6119 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -1549,6 +1549,66 @@ body.mobile-topbar--merged {padding: var(--mobile-top-safe-area) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);}+.mobile-backlinks-dialog {+ .b3-dialog {+ align-items: flex-end;+ box-sizing: border-box;+ bottom: auto;+ height: 100%;+ }++ .mobile-backlinks-sheet {+ max-height: 100%;+ border-radius: 16px 16px 0 0;+ padding-top: 32px;+ box-sizing: border-box;+ transform: translateY(100%);+ transition: transform 150ms ease;+ }++ &.b3-dialog--open .mobile-backlinks-sheet {+ transform: translateY(0);+ }++ .mobile-backlinks-content {+ height: 100%;+ min-height: 0;+ }+}++.sy__backlink {+ min-height: 0;++ > .block__icons {+ flex-wrap: wrap;+ height: auto;+ min-height: 40px;+ }++ > .backlinkList,+ > .backlinkMList {+ min-height: 0;+ overflow: auto;+ overscroll-behavior: contain;+ }++ .protyle-breadcrumb__bar {+ min-height: 32px;+ }++ .block__icon {+ min-width: 28px;+ min-height: 28px;+ }++ &--only-backlinks {+ > .backlinkMList__header,+ > .backlinkMList {+ display: none !important;+ }+ }+}+.mobile-command-panel {flex: 1;min-height: 0;diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.tsindex 5ff2d54338..a68e3b4039 100644--- a/app/src/dialog/processSystem.ts+++ b/app/src/dialog/processSystem.ts@@ -21,16 +21,24 @@ import {isInAndroid, isInHarmony, isInIOS, setStorageVal} from "../protyle/util/import {emitToPlugins} from "../plugin/EventBusCore";import {createHostQuitGuard} from "./hostQuit";import {getHostCapabilities, sanitizeKernelHTML} from "../util/hostCapabilities";+/// #if MOBILE+import {getMobileBacklinkPanels} from "../mobile/util/backlinkPanels";+/// #endifexport const processBacklinkIndexCommit = (data: {rootIDs?: string[],backlinkChanged?: boolean,backlinkFull?: boolean,}) => {- /// #if !MOBILEif (!data?.backlinkChanged) {return;}+ /// #if MOBILE+ getMobileBacklinkPanels().forEach(item => {+ item.markIndexDirty(data);+ item.refreshAfterIndex();+ });+ /// #elsegetAllModels().backlink.forEach(item => {item.markIndexDirty(data);item.refreshAfterIndex();diff --git a/app/src/layout/dock/Backlink.ts b/app/src/layout/dock/Backlink.tsindex 2e146fbaa7..79bb4ad47c 100644--- a/app/src/layout/dock/Backlink.ts+++ b/app/src/layout/dock/Backlink.ts@@ -1,2161 +1,4 @@-import {Tab} from "../Tab";-import {Model} from "../Model";-import {Tree} from "../../util/Tree";-import {setPanelFocus} from "../util";-import {getDockByType} from "../tabUtil";-import {fetchPost} from "../../util/fetch";-import {Constants} from "../../constants";-import {updateHotkeyAfterTip} from "../../protyle/util/compatibility";-import {openFileById} from "../../editor/util";-import {Protyle} from "../../protyle";-import {MenuItem} from "../../menus/Menu";-import type {App} from "../../index";-import {isSupportCSSHL, searchMarkRender} from "../../protyle/render/searchMarkRender";-import {getDocDisplayName, isEncryptedBox} from "../../util/pathName";-import {getAllModels} from "../getAll";-import {hideElements} from "../../protyle/ui/hideElements";-import {renderBacklink} from "../../protyle/wysiwyg/renderBacklink";-import {- getBottomBacklinkVisibility,- getInitialBacklinkSectionState,- shouldDeferBottomBacklinkRefresh,- shouldRefreshAllBacklinkContexts,- shouldRenderBacklinkResponse,- shouldSaveBacklinkStatus-} from "./backlinkRefresh";-import {- cancelHeightAnimation,- collapseHeight,- expandHeight,- isHeightAnimating-} from "../../util/heightAnimation";-import {- createBacklinkSourceFilter,- getBacklinkSourceFilterParam,- type IBacklinkSourceFilter,- normalizeBacklinkSourceFilter,- type TBacklinkDailyNoteFilter-} from "./backlinkSourceFilter";-import {escapeHtml} from "../../util/escape";-import {ViewStateService} from "../../util/viewState";-import {- applyViewFoldStates,- invalidateViewFoldRequests,- registerViewFoldContext,- unregisterViewFoldContext,-} from "../../protyle/util/viewFold";-import {- captureBacklinkReadingAnchor,- type IBacklinkReadingAnchor,- restoreBacklinkReadingAnchor,-} from "./backlinkReadingAnchor";+import {BacklinkContent} from "./BacklinkContent";-interface IBacklinkItemRecord {- revision: string,- containerElement: HTMLDivElement,- 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-}--const getBacklinkOccurrenceBreadcrumb = (element: Element) => {- const wysiwygElement = element.closest(".protyle-wysiwyg");- if (!wysiwygElement) {- return;- }- let topLevelElement = element;- while (topLevelElement.parentElement && topLevelElement.parentElement !== wysiwygElement) {- topLevelElement = topLevelElement.parentElement;- }- if (topLevelElement.parentElement !== wysiwygElement) {- return;- }- let currentElement: Element | null = topLevelElement;- while (currentElement) {- if (currentElement.classList.contains("protyle-breadcrumb__bar") &&- currentElement.hasAttribute("data-backlink-id")) {- return currentElement;- }- currentElement = currentElement.previousElementSibling;- }-};--const getBacklinkOccurrenceID = (element: Element) =>- getBacklinkOccurrenceBreadcrumb(element)?.getAttribute("data-backlink-id") || "";--const getBacklinkOccurrenceRevision = (element: Element) =>- getBacklinkOccurrenceBreadcrumb(element)?.getAttribute("data-backlink-revision") || "";--export class Backlink extends Model {- public element: HTMLElement;- public inputsElement: NodeListOf<HTMLInputElement>;- public type: "pin" | "local" | "bottom";- public blockId: string;- public rootId: string; // "local" 和 "bottom" 必传- public ownerProtyle?: IProtyle;- public tree: Tree;- public notebookId: string;- public mTree: Tree;- public editors: Protyle[] = [];- public status: {- [key: string]: {- sort: number,- mSort: number,- scrollTop: number,- mScrollTop: number,- backlinkOpenIds: string[],- backlinkMOpenIds: string[],- backlinkMStatus: number, // 0 全展开,1 展开一半箭头向下,2 展开一半箭头向上,3 全收起- backlinkFolded: boolean,- backmentionFolded: boolean- }- } = {};- private dirty = false;- private destroyed = false;- private refreshQueued = false;- private searchQueued = false;- private requestID = 0;- private requesting = false;- private showingLoading = false;- private contextRequestVersions = [0, 0];- private itemRecords = [new Map<string, IBacklinkItemRecord>(), new Map<string, IBacklinkItemRecord>()];- private listRevision = "";- private listQueryKey = "";- private renderedQueryKey = "";- 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;- private sourceFilter = createBacklinkSourceFilter();- private viewState?: ViewStateService;- private viewStateReady: Promise<void> = Promise.resolve();- private viewStateLoaded = false;- private viewStateGeneration = 0;- private viewStateSearchQueued = false;- private viewStateSearchInit = false;- private viewStateSearchRefreshAll = false;- private readingAnchorTimers: [number?, number?] = [];- private restoringReadingAnchors: [boolean, boolean] = [false, false];- private readingAnchorScrollEpochs: [number, number] = [0, 0];- private readingAnchorRenderGeneration = 0;- private ownerScrollListener?: () => void;-- constructor(options: {- app: App,- tab?: Tab,- element?: HTMLElement,- blockId: string,- rootId?: string,- notebookId?: string,- type: "pin" | "local" | "bottom",- ownerProtyle?: IProtyle,- emptyChange?: (empty: boolean) => void,- }) {- super({app: options.app});-- if (options.type !== "bottom") {- this.connect({- id: options.tab.id,- type: "backlink",- callback: this.handelCallback.bind(this),- msgCallback: this.handleMsgCallback.bind(this),- });- }-- this.blockId = options.blockId;- this.rootId = options.rootId;- this.notebookId = options.notebookId || "";- this.type = options.type;- this.ownerProtyle = options.ownerProtyle;- 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;- this.ownerFocusoutListener = (event: FocusEvent) => {- if (!event.relatedTarget || !this.ownerProtyle.element.contains(event.relatedTarget as Node)) {- this.refreshIfVisible(true);- }- };- this.ownerProtyle.element.addEventListener("focusout", this.ownerFocusoutListener);- }- const backlinkSort = window.siyuan.config.editor.backlinkSort;- const backmentionSort = window.siyuan.config.editor.backmentionSort;- this.element.innerHTML = `<div class="block__icons backlinkList__header">- ${this.type === "bottom" ? `<span data-type="bLayout" class="block__icon block__icon--show fn__flex-center backlinkList__toggle ariaLabel" data-position="north" aria-label="${window.siyuan.languages.collapse}"><svg><use xlink:href="#iconDown"></use></svg></span>` : ""}- <div class="block__logo block__logo--counter fn__flex-1 fn__pointer" data-type="backlink">${window.siyuan.languages.backlinks}<span class="counter listCount"></span></div>- <input class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.filterKeywordEnter}" />- ${this.type === "bottom" ? "" : `<span data-type="refresh" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.refresh}"><svg><use xlink:href='#iconRefresh'></use></svg></span>- <span class="fn__space"></span>`}- <span data-type="search" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.filter}"><svg><use xlink:href='#iconFilter'></use></svg></span>- <span class="fn__space"></span>- <span data-type="sourceFilter" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.backlinkSourceFilter}"><svg><use xlink:href='#iconListFilterPlus'></use></svg></span>- <span class="fn__space"></span>- <span data-type="sort" data-sort="${backlinkSort}" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.sort}"><svg><use xlink:href='#iconSort'></use></svg></span>- <span class="fn__space"></span>- <span data-type="expand" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.expand}${this.type === "bottom" ? "" : updateHotkeyAfterTip(window.siyuan.config.keymap.editor.general.expand.custom)}">- <svg><use xlink:href="#iconExpand"></use></svg>- </span>- <span class="fn__space"></span>- <span data-type="collapse" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.collapse}${this.type === "bottom" ? "" : updateHotkeyAfterTip(window.siyuan.config.keymap.editor.general.collapse.custom)}">- <svg><use xlink:href="#iconContract"></use></svg>- </span>- <span class="${this.type !== "pin" ? "fn__none " : ""}fn__space"></span>- <span data-type="min" class="${this.type !== "pin" ? "fn__none " : ""}block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.min}${updateHotkeyAfterTip(window.siyuan.config.keymap.general.closeTab.custom)}"><svg><use xlink:href='#iconMin'></use></svg></span>-</div>-<div class="backlinkList fn__flex-1"></div>-<div class="block__icons backlinkMList__header">- ${this.type === "bottom" ? `<span data-type="layout" class="block__icon block__icon--show fn__flex-center backlinkList__toggle ariaLabel" data-position="north" aria-label="${window.siyuan.languages.collapse}"><svg><use xlink:href="#iconDown"></use></svg></span>` : ""}- <div class="block__logo block__logo--counter fn__flex-1 fn__pointer" data-type="mention">${window.siyuan.languages.mentions}<span class="counter listMCount"></span></div>- <input class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.filterKeywordEnter}" />- <span data-type="search" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.filter}"><svg><use xlink:href='#iconFilter'></use></svg></span>- <span class="fn__space"></span>- <span data-type="mSort" data-sort="${backmentionSort}" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.sort}"><svg><use xlink:href='#iconSort'></use></svg></span>- <span class="fn__space"></span>- <span data-type="mExpand" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.expand}">- <svg><use xlink:href="#iconExpand"></use></svg>- </span>- <span class="fn__space"></span>- <span data-type="mCollapse" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.collapse}">- <svg><use xlink:href="#iconContract"></use></svg>- </span>- ${this.type === "bottom" ? "" : `<span class="fn__space"></span>- <span data-type="layout" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.down}">- <svg><use xlink:href="#iconDown"></use></svg>- </span>`}-</div>-<div class="backlinkMList fn__flex-1"></div>`;-- this.inputsElement = this.element.querySelectorAll("input");- this.inputsElement.forEach((item) => {- item.addEventListener("blur", (event: KeyboardEvent) => {- const inputElement = event.target as HTMLInputElement;- inputElement.classList.add("fn__none");- const filterIconElement = inputElement.parentElement.querySelector('[data-type="search"]');- if (inputElement.value) {- filterIconElement.classList.add("block__icon--active");- filterIconElement.setAttribute("aria-label", window.siyuan.languages.filter + " " + inputElement.value);- } else {- filterIconElement.classList.remove("block__icon--active");- filterIconElement.setAttribute("aria-label", window.siyuan.languages.filter);- }- });- item.addEventListener("keydown", (event: KeyboardEvent) => {- if (!event.isComposing && event.key === "Enter") {- this.searchBacklinks();- }- });- });- this.element.querySelectorAll('[data-type="search"]').forEach((item, index) => {- item.addEventListener("click", (event) => {- event.stopPropagation();- const inputElement = this.inputsElement[index];- inputElement.classList.remove("fn__none");- inputElement.select();- });- });- this.tree = new Tree({- element: this.element.querySelector(".backlinkList") as HTMLElement,- data: null,- titleTooltipPosition: this.type === "bottom" ? "north" : "parentE",- click: (element) => {- this.toggleItem(element, false);- this.setFocus();- this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- ctrlClick: (element) => {- openFileById({- app: options.app,- id: element.getAttribute("data-node-id"),- action: [Constants.CB_GET_CONTEXT]- });- this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- altClick(element) {- openFileById({- app: options.app,- id: element.getAttribute("data-node-id"),- position: "right",- action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]- });- this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- shiftClick(element) {- openFileById({- app: options.app,- id: element.getAttribute("data-node-id"),- position: "bottom",- action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]- });- this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- toggleClick: (liElement) => {- this.toggleItem(liElement, false);- this.setFocus();- this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- }- });- this.mTree = new Tree({- element: this.element.querySelector(".backlinkMList") as HTMLElement,- data: null,- titleTooltipPosition: this.type === "bottom" ? "north" : "parentE",- click: (element) => {- this.toggleItem(element, true);- this.setFocus();- this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- ctrlClick(element) {- openFileById({- app: options.app,- id: element.getAttribute("data-node-id"),- action: [Constants.CB_GET_CONTEXT]- });- this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- altClick(element) {- openFileById({- app: options.app,- id: element.getAttribute("data-node-id"),- position: "right",- action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]- });- this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- shiftClick(element) {- openFileById({- app: options.app,- id: element.getAttribute("data-node-id"),- position: "bottom",- action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]- });- this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- toggleClick: (liElement) => {- this.toggleItem(liElement, true);- this.setFocus();- this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- },- blockExtHTML: `<span class="b3-list-item__action b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></span>`- });- this.tree.element.addEventListener("scroll", (event) => {- this.tree.element.querySelectorAll(".protyle-gutters").forEach(item => {- item.classList.add("fn__none");- item.innerHTML = "";- });- this.tree.element.querySelectorAll(".protyle-wysiwyg--hl").forEach((hlItem) => {- hlItem.classList.remove("protyle-wysiwyg--hl");- });- if (event.isTrusted) {- this.handleReadingAnchorScroll(false);- }- });- this.mTree.element.addEventListener("scroll", (event) => {- this.mTree.element.querySelectorAll(".protyle-gutters").forEach(item => {- item.classList.add("fn__none");- item.innerHTML = "";- });- this.mTree.element.querySelectorAll(".protyle-wysiwyg--hl").forEach((hlItem) => {- hlItem.classList.remove("protyle-wysiwyg--hl");- });- if (event.isTrusted) {- this.handleReadingAnchorScroll(true);- }- });- if (this.type === "bottom") {- this.ownerScrollListener = () => {- this.handleReadingAnchorScroll(false);- };- this.ownerProtyle.contentElement.addEventListener("scroll", this.ownerScrollListener);- }- // 为了快捷键的 dispatch- this.element.querySelector('[data-type="collapse"]').addEventListener("click", () => {- this.cancelContextRequests(this.tree.element, false);- this.hideEditorGutters(this.tree.element);- this.invalidateHeadingRequests(this.tree.element);- this.getDocumentItemElements(this.tree).forEach(item => {- this.setDocumentExpanded(false, item.getAttribute("data-node-id"), false);- });- this.tree.element.querySelectorAll(".protyle").forEach(item => {- item.classList.add("fn__none");- });- this.tree.element.querySelectorAll(".b3-list-item__arrow").forEach(item => {- item.classList.remove("b3-list-item__arrow--open");- });- this.updateBottomBacklinkSpacing();- });- this.element.querySelector('[data-type="expand"]').addEventListener("click", () => {- this.expandDocumentItems(this.tree, false);- });- this.element.addEventListener("click", (event) => {- let target = event.target as HTMLElement;- const eventProtyleElement = target.closest(".protyle");- if (this.type !== "bottom" || !eventProtyleElement || !this.element.contains(eventProtyleElement)) {- this.setFocus();- }- while (target && !target.isEqualNode(this.element)) {- if ((target.classList.contains("block__icon") || target.classList.contains("block__logo")) &&- target.parentElement.parentElement === this.element) {- const type = target.getAttribute("data-type");- switch (type) {- case "refresh":- this.refresh();- event.stopPropagation();- break;- case "mExpand":- this.expandDocumentItems(this.mTree, true);- event.stopPropagation();- break;- case "mCollapse":- this.cancelContextRequests(this.mTree.element, true);- this.hideEditorGutters(this.mTree.element);- this.invalidateHeadingRequests(this.mTree.element);- this.getDocumentItemElements(this.mTree).forEach(item => {- this.setDocumentExpanded(true, item.getAttribute("data-node-id"), false);- });- this.mTree.element.querySelectorAll(".protyle").forEach(item => {- item.classList.add("fn__none");- });- this.mTree.element.querySelectorAll(".b3-list-item__arrow").forEach(item => {- item.classList.remove("b3-list-item__arrow--open");- });- event.stopPropagation();- break;- case "min":- getDockByType("backlink").toggleModel("backlink", false, true);- event.stopPropagation();- break;- case "sort":- case "mSort":- this.showSortMenu(type, target.getAttribute("data-sort"));- window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});- event.stopPropagation();- break;- case "sourceFilter":- this.showSourceFilterMenu(event);- event.stopPropagation();- break;- case "layout":- if (this.type === "bottom") {- this.setBottomLayout(target, this.mTree.element);- } else {- this.setLayout(target);- }- event.stopPropagation();- break;- case "bLayout":- this.setBottomLayout(target, this.tree.element);- event.stopPropagation();- break;- case "backlink":- if (this.type === "bottom") {- this.setBottomLayout(target.parentElement.querySelector('[data-type="bLayout"]'), this.tree.element);- } else {- this.setDockSectionLayout(this.tree.element);- }- event.stopPropagation();- break;- case "mention":- if (this.type === "bottom") {- this.setBottomLayout(target.parentElement.querySelector('[data-type="layout"]'), this.mTree.element);- } else {- this.setDockSectionLayout(this.mTree.element);- }- event.stopPropagation();- break;- }- }- target = target.parentElement;- }- });-- this.setViewStateHost(this.blockId);- this.showBottomLoading();- this.searchBacklinks(true);- }-- private setViewStateHost(blockID: string) {- this.clearReadingAnchorTimers();- const previousReady = this.viewStateReady;- const previous = this.viewState;- const generation = ++this.viewStateGeneration;- this.viewState = undefined;- this.viewStateLoaded = !blockID;- const createService = async () => {- await previousReady;- if (previous) {- try {- await previous.destroy();- } catch (error) {- console.error(error);- }- }- if (generation !== this.viewStateGeneration || !blockID) {- return;- }- const service = new ViewStateService({- scope: "backlink",- surface: this.type,- hostID: blockID,- });- this.viewState = service;- await service.ready;- };- this.viewStateReady = createService().catch(error => {- console.error(error);- }).then(() => {- if (generation === this.viewStateGeneration) {- this.viewStateLoaded = true;- }- });- }-- private getDocumentStateField(isMention: boolean, documentID: string) {- return `item:${isMention ? "backmention" : "backlink"}:${encodeURIComponent(documentID)}`;- }-- private getSectionStateField(isMention: boolean) {- return `section:${isMention ? "backmention" : "backlink"}`;- }-- private setDocumentExpanded(isMention: boolean, documentID: string, expanded: boolean) {- if (documentID && this.viewState) {- this.viewState.set(this.getDocumentStateField(isMention, documentID), expanded);- }- }-- private setSectionFolded(isMention: boolean, folded: boolean) {- this.viewState?.set(this.getSectionStateField(isMention), folded);- }-- private handelCallback() {- if (this.type === "local") {- fetchPost("/api/block/checkBlockExist", {id: this.blockId}, existResponse => {- if (!existResponse.data) {- this.parent.parent.removeTab(this.parent.id);- }- });- }- }-- private handleMsgCallback(data: IWebSocketData) {- if (data && this.type === "local") {- switch (data.cmd) {- case "rename":- if (this.rootId === data.data.id) {- this.parent.updateTitle(getDocDisplayName(data.data.title, data.data.empty));- }- break;- case "closeBox":- case "removeBox":- if (this.notebookId === data.data.box && this.type === "local") {- this.parent.parent.removeTab(this.parent.id);- }- break;- case "removeDoc":- if (data.data.ids.includes(this.rootId) && this.type === "local") {- this.parent.parent.removeTab(this.parent.id);- }- break;- }- }- }-- private setLayout(element: HTMLElement) {- const backlinkWasFolded = this.tree.element.classList.contains("fn__none");- const backmentionWasFolded = this.mTree.element.style.height === "0px";- this.savePendingReadingAnchor(false);- this.savePendingReadingAnchor(true);- if (this.mTree.element.style.flex) {- if (this.mTree.element.style.height === "0px") {- this.tree.element.classList.remove("fn__none");- this.mTree.element.removeAttribute("style");- element.setAttribute("aria-label", window.siyuan.languages.up);- element.querySelector("use").setAttribute("xlink:href", "#iconUp");- } else {- this.tree.element.classList.remove("fn__none");- this.mTree.element.removeAttribute("style");- element.setAttribute("aria-label", window.siyuan.languages.down);- element.querySelector("use").setAttribute("xlink:href", "#iconDown");- }- } else {- if (element.getAttribute("aria-label") === window.siyuan.languages.down) {- this.tree.element.classList.remove("fn__none");- this.mTree.element.setAttribute("style", "flex:none;height:0px");- element.setAttribute("aria-label", window.siyuan.languages.up);- element.querySelector("use").setAttribute("xlink:href", "#iconUp");- } else {- this.tree.element.classList.add("fn__none");- this.mTree.element.setAttribute("style", `flex:none;height:${this.element.clientHeight - this.tree.element.previousElementSibling.clientHeight * 2}px`);- element.setAttribute("aria-label", window.siyuan.languages.down);- element.querySelector("use").setAttribute("xlink:href", "#iconDown");- }- }- this.setSectionFolded(false, this.tree.element.classList.contains("fn__none"));- this.setSectionFolded(true, this.mTree.element.style.height === "0px");- const viewFoldPromises = this.syncViewFoldVisibility();- const restoreBacklink = backlinkWasFolded && !this.tree.element.classList.contains("fn__none");- const restoreBackmention = backmentionWasFolded && this.mTree.element.style.height !== "0px";- this.tree.element.dispatchEvent(new CustomEvent("scroll"));- this.mTree.element.dispatchEvent(new CustomEvent("scroll"));- if (restoreBacklink) {- this.restorePersistedReadingAnchorAfter(false, viewFoldPromises[0]);- }- if (restoreBackmention) {- this.restorePersistedReadingAnchorAfter(true, viewFoldPromises[1]);- }- }-- private setDockSectionLayout(listElement: HTMLElement) {- const isMention = listElement === this.mTree.element;- const backlinkFolded = this.tree.element.classList.contains("fn__none");- const backmentionFolded = this.mTree.element.style.height === "0px";- const nextBacklinkFolded = isMention ? backlinkFolded : !backlinkFolded;- const nextBackmentionFolded = isMention ? !backmentionFolded : backmentionFolded;- if (isMention ? nextBackmentionFolded : nextBacklinkFolded) {- this.savePendingReadingAnchor(isMention);- }- this.applyDockLayout(- nextBacklinkFolded,- nextBackmentionFolded,- this.status[this.blockId]?.backlinkMStatus ?? 1,- );- this.setSectionFolded(isMention, isMention ? nextBackmentionFolded : nextBacklinkFolded);- const viewFoldPromises = this.syncViewFoldVisibility();- const restoreAnchor = isMention ? !nextBackmentionFolded : !nextBacklinkFolded;- this.saveStatus(false);- this.tree.element.dispatchEvent(new CustomEvent("scroll"));- this.mTree.element.dispatchEvent(new CustomEvent("scroll"));- if (restoreAnchor) {- this.restorePersistedReadingAnchorAfter(isMention, viewFoldPromises[isMention ? 1 : 0]);- }- }-- private setBottomLayout(element: HTMLElement, listElement: HTMLElement) {- if (isHeightAnimating(listElement)) {- return;- }- const folded = !listElement.classList.contains("fn__none");- if (folded) {- this.savePendingReadingAnchor(listElement === this.mTree.element);- }- if (folded) {- this.cancelContextRequests(listElement, listElement === this.mTree.element);- this.hideEditorGutters(listElement);- this.invalidateHeadingRequests(listElement);- listElement.dataset.heightFolding = "true";- collapseHeight(listElement, () => {- delete listElement.dataset.heightFolding;- listElement.classList.add("fn__none");- });- } else {- delete listElement.dataset.heightFolding;- listElement.classList.remove("fn__none");- const viewFoldPromise = this.resumeViewFoldStates(listElement);- const expandPromise = new Promise<void>(resolve => {- expandHeight(listElement, resolve);- });- this.restorePersistedReadingAnchorAfter(- listElement === this.mTree.element,- Promise.all([viewFoldPromise, expandPromise]).then(() => undefined),- );- }- if (folded) {- listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- }- element.setAttribute("aria-label", folded ? window.siyuan.languages.expand : window.siyuan.languages.collapse);- element.querySelector("use").setAttribute("xlink:href", folded ? "#iconRight" : "#iconDown");- this.setSectionFolded(listElement === this.mTree.element, folded);- this.saveStatus(false);- }-- private setFocus() {- if (this.type === "bottom") {- this.setOwnerFocus();- this.element.focus({preventScroll: true});- return;- }- if (this.type === "local") {- setPanelFocus(this.element.parentElement.parentElement);- } else {- setPanelFocus(this.element);- }- }-- private setOwnerFocus() {- const wndElement = this.ownerProtyle.element.closest('[data-type="wnd"]');- if (wndElement) {- setPanelFocus(wndElement);- }- }-- private showSortMenu(type: string, sort: string) {- const clickEvent = (currentSort: string) => {- (type === "sort" ? this.tree : this.mTree).element.previousElementSibling.querySelector(`[data-type="${type}"]`).setAttribute("data-sort", currentSort);- // 保存排序状态到配置- const sortValue = parseInt(currentSort);- if (type === "sort") {- window.siyuan.config.editor.backlinkSort = sortValue;- } else {- window.siyuan.config.editor.backmentionSort = sortValue;- }- fetchPost("/api/setting/setEditor", window.siyuan.config.editor, (response) => {- window.siyuan.config.editor = response.data;- });- this.searchBacklinks();- };- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "0",- iconHTML: "",- label: window.siyuan.languages.fileNameASC,- click: () => {- clickEvent("0");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "1",- iconHTML: "",- label: window.siyuan.languages.fileNameDESC,- click: () => {- clickEvent("1");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "4",- iconHTML: "",- label: window.siyuan.languages.fileNameNatASC,- click: () => {- clickEvent("4");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "5",- iconHTML: "",- label: window.siyuan.languages.fileNameNatDESC,- click: () => {- clickEvent("5");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "9",- iconHTML: "",- label: window.siyuan.languages.createdASC,- click: () => {- clickEvent("9");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "10",- iconHTML: "",- label: window.siyuan.languages.createdDESC,- click: () => {- clickEvent("10");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "2",- iconHTML: "",- label: window.siyuan.languages.modifiedASC,- click: () => {- clickEvent("2");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: sort === "3",- iconHTML: "",- label: window.siyuan.languages.modifiedDESC,- click: () => {- clickEvent("3");- }- }).element);- }-- private applySourceFilter(filter: IBacklinkSourceFilter) {- this.sourceFilter = normalizeBacklinkSourceFilter(filter);- this.element.querySelector('[data-type="sourceFilter"]')?.classList.toggle(- "block__icon--active",- Boolean(getBacklinkSourceFilterParam(this.sourceFilter)),- );- this.searchBacklinks();- }-- private showSourceFilterMenu(event: MouseEvent) {- const dailyNoteSubmenu = ([- ["all", window.siyuan.languages.all],- ["only", window.siyuan.languages.dailyNote],- ["exclude", window.siyuan.languages.nonDailyNote],- ] as Array<[TBacklinkDailyNoteFilter, string]>).map(([value, label]) => ({- checked: this.sourceFilter.dailyNote === value,- iconHTML: "",- label,- click: () => {- this.applySourceFilter({...this.sourceFilter, dailyNote: value});- }- }));- const notebookSubmenu: IMenu[] = [{- checked: this.sourceFilter.excludedNotebookIDs.length === 0,- iconHTML: "",- label: window.siyuan.languages.allNotebooks,- click: () => {- this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: []});- }- }, {type: "separator"}];- (window.siyuan.notebooks || []).filter(item => !item.closed).forEach(item => {- notebookSubmenu.push({- checked: !this.sourceFilter.excludedNotebookIDs.includes(item.id),- iconHTML: "",- label: escapeHtml(item.name),- click: () => {- const excludedNotebookIDs = new Set(this.sourceFilter.excludedNotebookIDs);- if (excludedNotebookIDs.has(item.id)) {- excludedNotebookIDs.delete(item.id);- } else {- excludedNotebookIDs.add(item.id);- }- this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: Array.from(excludedNotebookIDs)});- }- });- });-- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconCalendar",- label: window.siyuan.languages.dailyNote,- type: "submenu",- submenu: dailyNoteSubmenu,- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconFiles",- label: window.siyuan.languages.agentCatNotebook,- type: "submenu",- submenu: notebookSubmenu,- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: this.sourceFilter.excludeSelf,- iconHTML: "",- label: window.siyuan.languages.excludeSelfBacklink,- click: () => {- this.applySourceFilter({...this.sourceFilter, excludeSelf: !this.sourceFilter.excludeSelf});- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- disabled: !getBacklinkSourceFilterParam(this.sourceFilter),- icon: "iconUndo",- label: window.siyuan.languages.reset,- click: () => {- this.applySourceFilter(createBacklinkSourceFilter());- }- }).element);- window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});- }-- private toggleItem(liElement: HTMLElement, isMention: boolean, persist = true) {- const svgElement = liElement.firstElementChild?.firstElementChild;- if (!svgElement || svgElement.getAttribute("disabled")) {- return;- }- const docId = liElement.getAttribute("data-node-id");- const record = this.itemRecords[isMention ? 1 : 0].get(docId);- const editor = record?.editor;- 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);- invalidateViewFoldRequests(editor.protyle);- editor.protyle.element.classList.add("fn__none");- } else if (editor) {- unregisterViewFoldContext(editor.protyle);- editor.destroy();- this.editors.splice(this.editors.indexOf(editor), 1);- editor.protyle.element.remove();- if (record) {- record.editor = undefined;- record.contextRevision = "";- }- }- if (persist) {- this.setDocumentExpanded(isMention, docId, false);- }- this.updateBottomBacklinkSpacing();- } else if (editor && !record?.contextDirty) {- editor.protyle.element.classList.remove("fn__none");- svgElement.classList.add("b3-list-item__arrow--open");- void applyViewFoldStates(editor.protyle);- if (persist) {- this.setDocumentExpanded(isMention, docId, true);- }- this.updateBottomBacklinkSpacing();- } else {- this.loadContext(liElement, isMention, true, persist);- }- }-- private expandDocumentItems(tree: Tree, isMention: boolean) {- const listElement = tree.element;- if (this.type === "bottom" && isHeightAnimating(listElement)) {- return;- }- const folded = this.type === "bottom" ?- listElement.classList.contains("fn__none") :- (isMention ? listElement.style.height === "0px" : listElement.classList.contains("fn__none"));- if (folded) {- if (this.type === "bottom") {- const toggleType = isMention ? "layout" : "bLayout";- this.setBottomLayout(- listElement.previousElementSibling.querySelector(`[data-type="${toggleType}"]`),- listElement- );- } else {- this.setDockSectionLayout(listElement);- }- }- this.getDocumentItemElements(tree).forEach(item => {- if (!item.querySelector(".b3-list-item__arrow--open")) {- this.toggleItem(item, isMention);- }- });- }-- private loadContext(liElement: HTMLElement, isMention: boolean, expand: boolean, persist = false) {- 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 viewStateGeneration = this.viewStateGeneration;- 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 || viewStateGeneration !== this.viewStateGeneration ||- !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 editor = record.editor;- const scrollAnchor = this.captureReadingAnchor(isMention);- const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);- const anchorQueryKey = this.renderedQueryKey;- editor.protyle.options.backlinkData = backlinkData;- void renderBacklink(editor.protyle, backlinkData).then(() => {- window.requestAnimationFrame(() => {- if (this.destroyed || blockId !== this.blockId ||- viewStateGeneration !== this.viewStateGeneration ||- contextRequestVersion !== this.contextRequestVersions[index] ||- requestGeneration !== record.requestGeneration || record.editor !== editor ||- !editor.protyle.element.isConnected || editor.protyle.element.classList.contains("fn__none") ||- scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention) ||- anchorQueryKey !== this.renderedQueryKey || anchorQueryKey !== this.listQueryKey) {- return;- }- if (scrollAnchor) {- this.restoreReadingAnchor(scrollAnchor);- } else {- this.restorePersistedReadingAnchor(isMention, docId);- }- });- });- searchMarkRender(editor.protyle, response.data.keywords, undefined, undefined, {- excludeSelector: ".protyle-breadcrumb__bar[data-backlink-id]"- });- } 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);- record.containerElement.appendChild(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());- }- editor.protyle.notebookId = notebookId;- if (notebookId) {- editor.protyle.element.setAttribute("data-notebook-id", notebookId);- } else {- editor.protyle.element.removeAttribute("data-notebook-id");- }- searchMarkRender(editor.protyle, response.data.keywords, undefined, undefined, {- excludeSelector: ".protyle-breadcrumb__bar[data-backlink-id]"- });- this.editors.push(editor);- record.editor = editor;- const service = this.viewState;- const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);- const anchorQueryKey = this.renderedQueryKey;- if (service) {- void registerViewFoldContext(editor.protyle, {- store: service,- pane: isMention ? "backmention" : "backlink",- rootID: docId,- getOccurrenceID: getBacklinkOccurrenceID,- getOccurrenceRevision: getBacklinkOccurrenceRevision,- }).then(() => {- window.requestAnimationFrame(() => {- if (this.destroyed || blockId !== this.blockId ||- viewStateGeneration !== this.viewStateGeneration || service !== this.viewState ||- contextRequestVersion !== this.contextRequestVersions[index] ||- requestGeneration !== record.requestGeneration || record.editor !== editor ||- !editor.protyle.element.isConnected || editor.protyle.element.classList.contains("fn__none") ||- scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention) ||- anchorQueryKey !== this.renderedQueryKey || anchorQueryKey !== this.listQueryKey) {- return;- }- this.restorePersistedReadingAnchor(isMention, docId);- });- });- }- }- }- if (expand) {- record.editor?.protyle.element.classList.remove("fn__none");- svgElement.classList.add("b3-list-item__arrow--open");- if (persist) {- this.setDocumentExpanded(isMention, docId, true);- }- }- this.updateBottomBacklinkSpacing();- }).finally(() => {- if (requestGeneration === record.requestGeneration) {- svgElement.removeAttribute("disabled");- }- });- }-- private hideEditorGutters(element: Element) {- this.editors.forEach(editor => {- if (editor.protyle.element === element || element.contains(editor.protyle.element)) {- hideElements(["gutter"], editor.protyle);- }- });- }-- private invalidateHeadingRequests(element: Element) {- this.editors.forEach(editor => {- if (editor.protyle.element === element || element.contains(editor.protyle.element)) {- invalidateViewFoldRequests(editor.protyle);- }- });- }-- private resumeViewFoldStates(element: Element) {- const promises: Promise<void>[] = [];- this.editors.forEach(editor => {- if ((editor.protyle.element === element || element.contains(editor.protyle.element)) &&- !editor.protyle.element.classList.contains("fn__none")) {- promises.push(applyViewFoldStates(editor.protyle));- }- });- return Promise.all(promises).then(() => undefined);- }-- private syncViewFoldVisibility() {- const promises: [Promise<void>, Promise<void>] = [Promise.resolve(), Promise.resolve()];- [this.tree.element, this.mTree.element].forEach((element, index) => {- if (element.classList.contains("fn__none") || element.style.height === "0px") {- this.invalidateHeadingRequests(element);- } else {- promises[index] = this.resumeViewFoldStates(element);- }- });- return promises;- }-- private cancelContextRequests(element: Element, isMention: boolean) {- this.contextRequestVersions[isMention ? 1 : 0]++;- element.querySelectorAll(".b3-list-item__arrow[disabled]").forEach(item => {- item.removeAttribute("disabled");- });- }-- private destroyItemRecord(record: IBacklinkItemRecord) {- if (record.editor) {- unregisterViewFoldContext(record.editor.protyle);- record.editor.destroy();- const editorIndex = this.editors.indexOf(record.editor);- if (editorIndex > -1) {- this.editors.splice(editorIndex, 1);- }- }- record.containerElement.remove();- }-- public getDocumentItemElements(tree: Tree) {- return Array.from(tree.element.querySelectorAll(- ":scope > .b3-list > .backlinkList__item > .b3-list-item[data-node-id]"- )) as HTMLLIElement[];- }-- public getScrollElement(tree: Tree) {- return this.type === "bottom" ? this.ownerProtyle.contentElement : tree.element;- }-- 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);- const containerElement = document.createElement("div");- containerElement.className = "backlinkList__item";- containerElement.dataset.nodeId = id;- containerElement.appendChild(headerElement);- record = {- revision: item.revision || "",- containerElement,- headerElement,- requestGeneration: 0,- };- records.set(id, record);- listElement.appendChild(containerElement);- 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.containerElement !== cursor) {- listElement.insertBefore(record.containerElement, cursor);- changed = true;- }- cursor = record.containerElement.nextElementSibling;- });- return changed;- }-- private getReadingAnchorField(isMention: boolean) {- if (this.type === "bottom") {- return "anchor:bottom";- }- return `anchor:${isMention ? "backmention" : "backlink"}`;- }-- private getReadingAnchorIndex(isMention: boolean) {- return this.type === "bottom" ? 0 : (isMention ? 1 : 0);- }-- private getReadingAnchorScrollEpoch(isMention: boolean) {- return this.readingAnchorScrollEpochs[this.getReadingAnchorIndex(isMention)];- }-- private isRestoringReadingAnchor(isMention: boolean) {- return this.restoringReadingAnchors[this.getReadingAnchorIndex(isMention)];- }-- private isReadingAnchorPaneVisible(isMention: boolean) {- const listElement = isMention ? this.mTree.element : this.tree.element;- return !listElement.classList.contains("fn__none") && listElement.dataset.heightFolding !== "true" &&- (this.type === "bottom" || !isMention || listElement.style.height !== "0px");- }-- private isBottomReadingAnchorViewportActive() {- if (this.type !== "bottom" || !this.ownerProtyle || this.element.classList.contains("fn__none") ||- this.element.getClientRects().length === 0) {- return this.type !== "bottom";- }- const ownerRect = this.ownerProtyle.contentElement.getBoundingClientRect();- const panelRect = this.element.getBoundingClientRect();- return panelRect.bottom > ownerRect.top && panelRect.top < ownerRect.bottom;- }-- private capturePaneReadingAnchor(isMention: boolean): IBacklinkReadingAnchor | undefined {- const tree = isMention ? this.mTree : this.tree;- const pane = isMention ? "backmention" : "backlink";- const scrollElement = this.getScrollElement(tree);- const anchor = captureBacklinkReadingAnchor({- scopeElement: tree.element,- scrollElement,- pane,- queryKey: this.renderedQueryKey,- });- const scrollRect = scrollElement.getBoundingClientRect();- const scopeRect = tree.element.getBoundingClientRect();- const viewportTop = Math.max(scrollRect.top, scopeRect.top);- const viewportBottom = Math.min(scrollRect.bottom, scopeRect.bottom);- const titleElements = Array.from(tree.element.querySelectorAll(- ":scope > .b3-list > .backlinkList__item > .b3-list-item[data-node-id]"- )) as HTMLElement[];- const titleElement = titleElements.filter(item => {- const rect = item.getBoundingClientRect();- return rect.bottom > viewportTop && rect.top < viewportBottom;- }).sort((left, right) => {- const leftOffset = left.getBoundingClientRect().top - scrollRect.top;- const rightOffset = right.getBoundingClientRect().top - scrollRect.top;- if (leftOffset <= 0 && rightOffset > 0) {- return -1;- }- if (rightOffset <= 0 && leftOffset > 0) {- return 1;- }- return leftOffset <= 0 ? rightOffset - leftOffset : leftOffset - rightOffset;- })[0];- const titleAnchor = titleElement ? {- pane,- rootID: titleElement.getAttribute("data-node-id") || "",- occurrenceID: "",- blockID: "",- offset: titleElement.getBoundingClientRect().top - scrollRect.top,- queryKey: this.renderedQueryKey,- } satisfies IBacklinkReadingAnchor : undefined;- const anchors = [anchor, titleAnchor].filter((item): item is IBacklinkReadingAnchor => Boolean(item));- const crossingAnchor = anchors.filter(item => item.offset <= 0)- .sort((left, right) => right.offset - left.offset)[0];- return crossingAnchor || anchors.filter(item => item.offset > 0)- .sort((left, right) => left.offset - right.offset)[0];- }-- private captureReadingAnchor(isMention: boolean) {- if (this.type !== "bottom") {- return this.capturePaneReadingAnchor(isMention);- }- const anchors = [this.capturePaneReadingAnchor(false), this.capturePaneReadingAnchor(true)]- .filter((item): item is IBacklinkReadingAnchor => Boolean(item));- const crossingAnchor = anchors.filter(anchor => anchor.offset <= 0)- .sort((left, right) => right.offset - left.offset)[0];- return crossingAnchor || anchors.filter(anchor => anchor.offset > 0)- .sort((left, right) => left.offset - right.offset)[0];- }-- private restoreReadingAnchor(anchor?: IBacklinkReadingAnchor) {- if (!anchor) {- return;- }- const isMention = anchor.pane === "backmention";- if (!this.isReadingAnchorPaneVisible(isMention)) {- return;- }- const tree = isMention ? this.mTree : this.tree;- const index = this.getReadingAnchorIndex(isMention);- this.restoringReadingAnchors[index] = true;- const restored = restoreBacklinkReadingAnchor({- anchor,- scopeElement: tree.element,- scrollElement: this.getScrollElement(tree),- pane: anchor.pane,- queryKey: this.listQueryKey,- });- if (!restored) {- this.restoringReadingAnchors[index] = false;- return;- }- window.requestAnimationFrame(() => {- this.restoringReadingAnchors[index] = false;- });- }-- private restorePersistedReadingAnchor(isMention: boolean, loadedRootID?: string) {- if (this.type === "bottom" && !this.isBottomReadingAnchorViewportActive()) {- return;- }- const anchor = this.viewState?.get<IBacklinkReadingAnchor>(this.getReadingAnchorField(isMention));- if (loadedRootID && (anchor?.rootID !== loadedRootID ||- anchor.pane !== (isMention ? "backmention" : "backlink"))) {- return;- }- this.restoreReadingAnchor(anchor);- }-- private restorePersistedReadingAnchorAfter(isMention: boolean, promise: Promise<void>) {- const generation = this.viewStateGeneration;- const service = this.viewState;- const blockID = this.blockId;- const queryKey = this.renderedQueryKey;- const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);- void promise.then(() => {- if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||- blockID !== this.blockId || queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey ||- scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention)) {- return;- }- this.restorePersistedReadingAnchor(isMention);- });- }-- private clearReadingAnchorTimers() {- this.readingAnchorTimers.forEach(timer => {- if (timer) {- window.clearTimeout(timer);- }- });- this.readingAnchorTimers = [];- this.restoringReadingAnchors = [false, false];- this.readingAnchorScrollEpochs[0]++;- this.readingAnchorScrollEpochs[1]++;- this.readingAnchorRenderGeneration++;- }-- private handleReadingAnchorScroll(isMention: boolean) {- if (this.isRestoringReadingAnchor(isMention)) {- return;- }- this.readingAnchorScrollEpochs[this.getReadingAnchorIndex(isMention)]++;- this.scheduleReadingAnchorSave(isMention);- }-- private scheduleReadingAnchorSave(isMention: boolean) {- if (this.isRestoringReadingAnchor(isMention) || !this.viewState || !this.renderedQueryKey ||- this.renderedQueryKey !== this.listQueryKey) {- return;- }- const index = this.getReadingAnchorIndex(isMention);- if (this.readingAnchorTimers[index]) {- window.clearTimeout(this.readingAnchorTimers[index]);- }- const generation = this.viewStateGeneration;- const service = this.viewState;- const queryKey = this.renderedQueryKey;- this.readingAnchorTimers[index] = window.setTimeout(() => {- this.readingAnchorTimers[index] = undefined;- if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||- queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey) {- return;- }- this.saveReadingAnchor(isMention, service, queryKey);- }, 400);- }-- private savePendingReadingAnchor(isMention: boolean) {- const index = this.getReadingAnchorIndex(isMention);- if (this.readingAnchorTimers[index]) {- window.clearTimeout(this.readingAnchorTimers[index]);- this.readingAnchorTimers[index] = undefined;- }- this.saveReadingAnchor(isMention);- }-- private saveReadingAnchor(isMention: boolean, service = this.viewState, queryKey = this.renderedQueryKey) {- if (!service || service !== this.viewState || !queryKey || queryKey !== this.renderedQueryKey ||- queryKey !== this.listQueryKey) {- return;- }- const anchor = this.captureReadingAnchor(isMention);- if (!anchor || anchor.queryKey !== queryKey) {- if (this.type === "bottom" && !this.isBottomReadingAnchorViewportActive() &&- service.has(this.getReadingAnchorField(isMention))) {- service.remove(this.getReadingAnchorField(isMention));- }- return;- }- service.set(this.getReadingAnchorField(isMention), anchor);- }-- 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, false);- }- });- });- }-- private updateBottomBacklinkSpacing() {- if (this.type !== "bottom") {- return;- }- if (this.element.classList.contains("sy__backlink--backlinks-empty") ||- this.element.classList.contains("sy__backlink--mentions-empty")) {- this.tree.element.classList.remove("backlinkList--divider-spacing");- return;- }- const lastItem = this.tree.element.querySelector(- ":scope > .b3-list > .backlinkList__item:last-child > .b3-list-item"- );- this.tree.element.classList.toggle("backlinkList--divider-spacing",- !lastItem || !lastItem.querySelector(".b3-list-item__arrow--open"));- }-- private showBottomLoading() {- if (this.type !== "bottom") {- return;- }- this.showingLoading = true;- this.resetRenderedData(false);- this.element.classList.remove("sy__backlink--backlinks-empty", "sy__backlink--mentions-empty");- 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;- this.element.querySelector(".listCount").textContent = "";- this.element.querySelector(".listMCount").textContent = "";- this.updateBottomBacklinkSpacing();- }-- private resetRenderedData(resetLists: boolean) {- cancelHeightAnimation(this.tree.element);- cancelHeightAnimation(this.mTree.element);- delete this.tree.element.dataset.heightFolding;- delete this.mTree.element.dataset.heightFolding;- this.cancelContextRequests(this.tree.element, false);- this.cancelContextRequests(this.mTree.element, true);- this.editors.forEach(item => {- unregisterViewFoldContext(item.protyle);- item.destroy();- });- this.editors = [];- this.itemRecords.forEach(records => records.clear());- this.listRevision = "";- this.listQueryKey = "";- this.renderedQueryKey = "";- if (resetLists) {- this.tree.updateData(null);- this.mTree.updateData(null);- }- }-- public prepareForBlock(blockId: string, rootId: string) {- if (!this.showingLoading) {- this.saveStatus();- }- this.requestID++;- 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;- this.setViewStateHost(blockId);- this.setRequesting(false);- 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 = notebookId || "";- this.setViewStateHost(blockId);- 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.setRequesting(false);- 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 setRequesting(requesting: boolean) {- this.requesting = requesting;- this.element.querySelector('.block__icon[data-type="refresh"] svg')?.classList.toggle("fn__rotate", requesting);- }-- private finishRequest(requestID: number) {- if (this.destroyed || requestID !== this.requestID) {- return false;- }- this.setRequesting(false);- return true;- }-- private runQueuedRequest() {- if (this.refreshQueued) {- this.refresh();- return true;- }- if (this.searchQueued) {- this.searchBacklinks();- return true;- }- return false;- }-- public refresh() {- if (!this.blockId) {- return;- }- if (this.requesting) {- this.refreshQueued = true;- return;- }- this.refreshQueued = false;- this.setRequesting(true);- this.dirty = false;- const requestID = ++this.requestID;- let responseHandled = false;- fetchPost("/api/ref/refreshBacklink", {- id: this.blockId,- }, () => {- responseHandled = true;- if (!this.finishRequest(requestID)) {- return;- }- if (!this.runQueuedRequest()) {- this.searchBacklinks(false, true);- }- }).finally(() => {- if (responseHandled || !this.finishRequest(requestID)) {- return;- }- if (!this.runQueuedRequest()) {- // 即使重建索引失败,也重新读取已有的反链数据并释放加载状态。- this.searchBacklinks(false, true);- }- });- }-- private searchBacklinks(init = false, refreshAllContexts = false) {- if (!this.blockId) {- return;- }- if (!this.viewStateLoaded) {- this.viewStateSearchInit = this.viewStateSearchInit || init;- this.viewStateSearchRefreshAll = this.viewStateSearchRefreshAll || refreshAllContexts;- if (!this.viewStateSearchQueued) {- this.viewStateSearchQueued = true;- void this.viewStateReady.then(() => {- this.viewStateSearchQueued = false;- if (this.destroyed) {- return;- }- const queuedInit = this.viewStateSearchInit;- const queuedRefreshAll = this.viewStateSearchRefreshAll;- this.viewStateSearchInit = false;- this.viewStateSearchRefreshAll = false;- this.searchBacklinks(queuedInit, queuedRefreshAll);- });- }- return;- }- if (this.requesting) {- this.searchQueued = true;- return;- }- this.searchQueued = false;- this.setRequesting(true);- // 解析当前反链面板所属 box:优先用已记录的 notebookId,首次为空时按 rootId 在已打开的编辑器里查找- let notebookId = this.notebookId;- if (!notebookId && this.rootId) {- getAllModels().editor.some(item => {- if (item.editor.protyle.block.rootID === this.rootId) {- notebookId = item.editor.protyle.notebookId;- return true;- }- });- }- const param: {- sort: string,- mSort: string,- k: string,- mk: string,- id: string,- sourceFilter?: IBacklinkSourceFilter,- notebook?: string,- knownRevision?: string,- } = {- sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")).toString(),- mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")).toString(),- k: this.inputsElement[0].value,- mk: this.inputsElement[1].value,- id: this.blockId,- };- const sourceFilter = getBacklinkSourceFilterParam(this.sourceFilter);- if (sourceFilter) {- param.sourceFilter = sourceFilter;- }- const blockId = this.blockId;- 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 => {- responseHandled = true;- if (!this.finishRequest(requestID) || blockId !== this.blockId) {- return;- }- if (!shouldRenderBacklinkResponse(this.refreshQueued, this.searchQueued)) {- this.runQueuedRequest();- return;- }- if (!response.data) {- if (this.showingLoading || init) {- this.render(undefined, init);- }- return;- }- if (shouldSaveBacklinkStatus(init, this.showingLoading)) {- this.saveStatus();- }- 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();- }- }).finally(() => {- if (responseHandled || !this.finishRequest(requestID) || blockId !== this.blockId) {- return;- }- if (!this.runQueuedRequest() && this.type === "bottom" && this.dirty) {- this.refreshIfVisible();- }- });- }-- public saveStatus(includeReadingAnchor = true) {- if (includeReadingAnchor) {- this.saveReadingAnchor(false);- if (this.type !== "bottom") {- this.saveReadingAnchor(true);- }- }- this.status[this.blockId] = {- sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")),- mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")),- scrollTop: this.tree.element.scrollTop,- mScrollTop: this.mTree.element.scrollTop,- backlinkOpenIds: [],- backlinkMOpenIds: [],- backlinkMStatus: 3, // 0 全展开,1 展开一半箭头向下,2 展开一半箭头向上,3 全收起- backlinkFolded: this.tree.element.classList.contains("fn__none") ||- this.tree.element.dataset.heightFolding === "true",- backmentionFolded: this.type === "bottom" ?- (this.mTree.element.classList.contains("fn__none") ||- this.mTree.element.dataset.heightFolding === "true") :- this.mTree.element.style.height === "0px"- };- this.tree.element.querySelectorAll(".b3-list-item__arrow--open").forEach(item => {- this.status[this.blockId].backlinkOpenIds.push(item.parentElement.parentElement.getAttribute("data-node-id"));- });- this.mTree.element.querySelectorAll(".b3-list-item__arrow--open").forEach(item => {- this.status[this.blockId].backlinkMOpenIds.push(item.parentElement.parentElement.getAttribute("data-node-id"));- });- if (this.mTree.element.style.flex) {- if (this.mTree.element.style.height === "0px") {- this.status[this.blockId].backlinkMStatus = 3;- } else {- this.status[this.blockId].backlinkMStatus = 0;- }- } else {- if (this.mTree.element.previousElementSibling.querySelector('[data-type="layout"]').getAttribute("aria-label") === window.siyuan.languages.down) {- this.status[this.blockId].backlinkMStatus = 1;- } else {- this.status[this.blockId].backlinkMStatus = 2;- }- }- }-- public render(data?: IBacklinkListResponse, init = false) {- if (!data) {- this.listRevision = "";- this.listQueryKey = "";- data = {- box: "",- backlinks: [],- backmentions: [],- linkRefsCount: 0,- mentionsCount: 0,- k: "",- mk: ""- };- }- const wasLoading = this.showingLoading;- this.showingLoading = false;-- this.setRequesting(false);- this.notebookId = data.box;- this.inputsElement[0].value = data.k;- this.inputsElement[1].value = data.mk;- const runtimeAnchorRenderGeneration = ++this.readingAnchorRenderGeneration;- const runtimeAnchors = (this.type === "bottom" ? [false] : [false, true]).map(isMention => ({- anchor: this.captureReadingAnchor(isMention),- isMention,- scrollEpoch: this.getReadingAnchorScrollEpoch(isMention),- }));- const runtimeAnchorBlockID = this.blockId;- const runtimeAnchorQueryKey = this.renderedQueryKey;- const backlinkChanged = this.reconcileList(this.tree, data.backlinks, false);- const backmentionChanged = this.reconcileList(this.mTree, data.backmentions, true);- this.renderedQueryKey = this.listQueryKey;- if (backlinkChanged || backmentionChanged) {- window.requestAnimationFrame(() => {- if (this.destroyed || runtimeAnchorBlockID !== this.blockId ||- runtimeAnchorRenderGeneration !== this.readingAnchorRenderGeneration ||- runtimeAnchorQueryKey !== this.renderedQueryKey || runtimeAnchorQueryKey !== this.listQueryKey) {- return;- }- runtimeAnchors.forEach(({anchor, isMention, scrollEpoch}) => {- if (scrollEpoch === this.getReadingAnchorScrollEpoch(isMention)) {- this.restoreReadingAnchor(anchor);- }- });- });- }- const bottomVisibility = this.type === "bottom" ?- getBottomBacklinkVisibility(data.linkRefsCount, data.mentionsCount, data.k, data.mk) : undefined;- if (bottomVisibility) {- this.element.classList.toggle("sy__backlink--backlinks-empty", bottomVisibility.hideBacklinks);- this.element.classList.toggle("sy__backlink--mentions-empty", bottomVisibility.hideMentions);- }- this.updateBottomBacklinkSpacing();-- const countElement = this.element.querySelector(".listCount");- if (data.linkRefsCount === 0 && this.type !== "bottom") {- countElement.classList.add("fn__none");- } else {- countElement.classList.remove("fn__none");- countElement.textContent = data.linkRefsCount.toString();- }- const mCountElement = this.element.querySelector(".listMCount");- if (data.mentionsCount === 0 && this.type !== "bottom") {- mCountElement.classList.add("fn__none");- } else {- mCountElement.classList.remove("fn__none");- mCountElement.textContent = data.mentionsCount.toString();- }- if (!this.status[this.blockId]) {- const backlinkState = getInitialBacklinkSectionState(- window.siyuan.config.editor.backlinkExpandCount,- data.backlinks.map(item => item.id),- );- const backmentionState = getInitialBacklinkSectionState(- window.siyuan.config.editor.backmentionExpandCount,- data.backmentions.map(item => item.id),- );- const backlinkFolded = backlinkState.folded ||- (this.type !== "bottom" && data.linkRefsCount === 0 && data.mentionsCount > 0);- const backmentionFolded = backmentionState.folded ||- (this.type !== "bottom" && data.mentionsCount === 0);- this.status[this.blockId] = {- sort: window.siyuan.config.editor.backlinkSort,- mSort: window.siyuan.config.editor.backmentionSort,- scrollTop: 0,- mScrollTop: 0,- backlinkOpenIds: backlinkState.openIds,- backlinkMOpenIds: backmentionState.openIds,- backlinkMStatus: backlinkFolded ? 0 : (backmentionFolded ? 3 : 1),- backlinkFolded,- backmentionFolded- };- }-- const persistedBacklinkFolded = this.viewState?.get<boolean>(this.getSectionStateField(false));- const persistedBackmentionFolded = this.viewState?.get<boolean>(this.getSectionStateField(true));- if (typeof persistedBacklinkFolded === "boolean") {- this.status[this.blockId].backlinkFolded = persistedBacklinkFolded;- }- if (typeof persistedBackmentionFolded === "boolean") {- this.status[this.blockId].backmentionFolded = persistedBackmentionFolded;- }-- const applyDocumentState = (items: IBlockTree[], isMention: boolean, openIDs: string[]) => {- items.forEach(item => {- const expanded = this.viewState?.get<boolean>(this.getDocumentStateField(isMention, item.id));- if (typeof expanded !== "boolean") {- return;- }- const index = openIDs.indexOf(item.id);- if (expanded && index === -1) {- openIDs.push(item.id);- } else if (!expanded && index > -1) {- openIDs.splice(index, 1);- }- });- };- applyDocumentState(data.backlinks, false, this.status[this.blockId].backlinkOpenIds);- applyDocumentState(data.backmentions, true, this.status[this.blockId].backlinkMOpenIds);-- // restore status- this.status[this.blockId].backlinkOpenIds.forEach(item => {- const liElement = this.tree.element.querySelector(`.b3-list-item[data-node-id="${item}"]`) as HTMLElement;- if (liElement && !liElement.querySelector(".b3-list-item__arrow--open")) {- this.toggleItem(liElement, false, 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 && !liElement.querySelector(".b3-list-item__arrow--open")) {- this.toggleItem(liElement, true, false);- }- });- if (this.type === "bottom") {- this.restoreBottomLayout(this.tree.element.previousElementSibling.querySelector('[data-type="bLayout"]'), this.tree.element,- this.status[this.blockId].backlinkFolded);- this.restoreBottomLayout(this.mTree.element.previousElementSibling.querySelector('[data-type="layout"]'), this.mTree.element,- this.status[this.blockId].backmentionFolded);- } else {- this.applyDockLayout(- this.status[this.blockId].backlinkFolded,- this.status[this.blockId].backmentionFolded,- this.status[this.blockId].backlinkMStatus,- );- }- this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').setAttribute("data-sort", this.status[this.blockId].sort.toString());- this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').setAttribute("data-sort", this.status[this.blockId].mSort.toString());- if (bottomVisibility) {- const empty = bottomVisibility.hidePanel;- if (this.empty !== empty || wasLoading) {- this.empty = empty;- this.emptyChange?.(empty);- }- }-- if (init) {- const generation = this.viewStateGeneration;- const service = this.viewState;- const blockID = this.blockId;- const queryKey = this.renderedQueryKey;- const panes = this.type === "bottom" ? [false] : [false, true];- const scrollEpochs = panes.map(isMention => this.getReadingAnchorScrollEpoch(isMention));- setTimeout(() => {- if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||- blockID !== this.blockId || queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey) {- return;- }- panes.forEach((isMention, index) => {- if (scrollEpochs[index] !== this.getReadingAnchorScrollEpoch(isMention)) {- return;- }- const anchor = this.viewState?.get<IBacklinkReadingAnchor>(this.getReadingAnchorField(isMention));- const targetIsMention = this.type === "bottom" && anchor ?- anchor.pane === "backmention" : isMention;- if (!this.isReadingAnchorPaneVisible(targetIsMention)) {- return;- }- if (!anchor && this.type !== "bottom") {- (isMention ? this.mTree : this.tree).element.scrollTop = isMention ?- this.status[this.blockId].mScrollTop : this.status[this.blockId].scrollTop;- }- this.restorePersistedReadingAnchor(isMention);- });- }, Constants.TIMEOUT_LOAD);- }- }-- private applyDockLayout(backlinkFolded: boolean, backmentionFolded: boolean, backlinkMStatus: number) {- const layoutElement = this.mTree.element.previousElementSibling.querySelector('[data-type="layout"]');- this.mTree.element.classList.remove("fn__none");- if (!backlinkFolded && !backmentionFolded) {- this.tree.element.classList.remove("fn__none");- this.mTree.element.removeAttribute("style");- const splitUp = backlinkMStatus === 2;- layoutElement.setAttribute("aria-label", splitUp ? window.siyuan.languages.up : window.siyuan.languages.down);- layoutElement.querySelector("use").setAttribute("xlink:href", splitUp ? "#iconUp" : "#iconDown");- } else if (backlinkFolded) {- this.tree.element.classList.add("fn__none");- const height = backmentionFolded ? 0 :- Math.max(this.element.clientHeight - this.tree.element.previousElementSibling.clientHeight * 2, 0);- this.mTree.element.setAttribute("style", `flex:none;height:${height}px`);- layoutElement.setAttribute("aria-label", window.siyuan.languages.down);- layoutElement.querySelector("use").setAttribute("xlink:href", "#iconDown");- } else {- this.tree.element.classList.remove("fn__none");- this.mTree.element.setAttribute("style", "flex:none;height:0px");- layoutElement.setAttribute("aria-label", window.siyuan.languages.up);- layoutElement.querySelector("use").setAttribute("xlink:href", "#iconUp");- }- }-- private restoreBottomLayout(element: HTMLElement, listElement: HTMLElement, folded: boolean) {- cancelHeightAnimation(listElement);- delete listElement.dataset.heightFolding;- listElement.classList.toggle("fn__none", folded);- element.setAttribute("aria-label", folded ? window.siyuan.languages.expand : window.siyuan.languages.collapse);- element.querySelector("use").setAttribute("xlink:href", folded ? "#iconRight" : "#iconDown");- }-- public markDirty() {- this.indexChangeVersion++;- this.dirty = true;- this.pendingFull = true;- this.itemRecords.forEach(records => records.forEach(record => {- record.contextDirty = true;- }));- }-- public markIndexDirty(change: IBacklinkIndexChange) {- if (!change?.backlinkChanged) {- return;- }- 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.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(- this.element.contains(document.activeElement),- ignoreFocus- )) {- return;- }- if (this.empty) {- this.searchBacklinks();- return;- }- if (this.element.classList.contains("fn__none") ||- this.element.getClientRects().length === 0) {- return;- }- const rect = this.element.getBoundingClientRect();- const ownerRect = this.ownerProtyle.contentElement.getBoundingClientRect();- if (rect.top > ownerRect.bottom + 640 || rect.bottom < ownerRect.top - 640) {- return;- }- this.searchBacklinks();- }-- public refreshDirty() {- if (this.dirty) {- this.refreshIfVisible();- }- }-- public destroy() {- if (this.blockId && !this.showingLoading) {- this.saveStatus();- }- this.destroyed = true;- this.viewStateGeneration++;- this.clearReadingAnchorTimers();- cancelHeightAnimation(this.tree.element);- cancelHeightAnimation(this.mTree.element);- delete this.tree.element.dataset.heightFolding;- delete this.mTree.element.dataset.heightFolding;- if (this.ownerFocusoutListener) {- this.ownerProtyle.element.removeEventListener("focusout", this.ownerFocusoutListener);- }- if (this.ownerScrollListener) {- this.ownerProtyle.contentElement.removeEventListener("scroll", this.ownerScrollListener);- }- if (this.panelFocusoutListener) {- this.element.removeEventListener("focusout", this.panelFocusoutListener);- }- this.visibilityObserver?.disconnect();- this.editors.forEach(item => {- unregisterViewFoldContext(item.protyle);- item.destroy();- });- this.editors = [];- void this.viewState?.destroy().catch(error => console.error(error));- if (this.ws) {- this.ws.onclose = null;- this.ws.close();- }- }+export class Backlink extends BacklinkContent {}diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.tsnew file mode 100644index 0000000000..eb2908ef22--- /dev/null+++ b/app/src/layout/dock/BacklinkContent.ts@@ -0,0 +1,2214 @@+import type {Tab} from "../Tab";+import {Model} from "../Model";+import {Tree} from "../../util/Tree";+/// #if !MOBILE+import {setPanelFocus} from "../util";+import {getDockByType} from "../tabUtil";+import {openFileById} from "../../editor/util";+/// #else+import {openMobileFileById} from "../../mobile/editor";+import {registerMobileSecondaryEditor} from "../../mobile/util/secondaryEditors";+/// #endif+import {fetchPost} from "../../util/fetch";+import {Constants} from "../../constants";+import {updateHotkeyAfterTip} from "../../protyle/util/compatibility";+import {Protyle} from "../../protyle";+import {MenuItem} from "../../menus/Menu";+import type {App} from "../../index";+import {isSupportCSSHL, searchMarkRender} from "../../protyle/render/searchMarkRender";+import {getDocDisplayName, isEncryptedBox} from "../../util/pathName";+import {getAllEditor} from "../getAll";+import {isMobile} from "../../util/functions";+import {hideElements} from "../../protyle/ui/hideElements";+import {renderBacklink} from "../../protyle/wysiwyg/renderBacklink";+import {+ getBottomBacklinkVisibility,+ getInitialBacklinkSectionState,+ shouldDeferBottomBacklinkRefresh,+ shouldRefreshAllBacklinkContexts,+ shouldRenderBacklinkResponse,+ shouldSaveBacklinkStatus+} from "./backlinkRefresh";+import {+ cancelHeightAnimation,+ collapseHeight,+ expandHeight,+ isHeightAnimating+} from "../../util/heightAnimation";+import {+ createBacklinkSourceFilter,+ getBacklinkSourceFilterParam,+ type IBacklinkSourceFilter,+ normalizeBacklinkSourceFilter,+ type TBacklinkDailyNoteFilter+} from "./backlinkSourceFilter";+import {escapeHtml} from "../../util/escape";+import {ViewStateService} from "../../util/viewState";+import {+ applyViewFoldStates,+ invalidateViewFoldRequests,+ registerViewFoldContext,+ unregisterViewFoldContext,+} from "../../protyle/util/viewFold";+import {+ captureBacklinkReadingAnchor,+ type IBacklinkReadingAnchor,+ restoreBacklinkReadingAnchor,+} from "./backlinkReadingAnchor";++interface IBacklinkItemRecord {+ revision: string,+ containerElement: HTMLDivElement,+ 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+}++const getBacklinkOccurrenceBreadcrumb = (element: Element) => {+ const wysiwygElement = element.closest(".protyle-wysiwyg");+ if (!wysiwygElement) {+ return;+ }+ let topLevelElement = element;+ while (topLevelElement.parentElement && topLevelElement.parentElement !== wysiwygElement) {+ topLevelElement = topLevelElement.parentElement;+ }+ if (topLevelElement.parentElement !== wysiwygElement) {+ return;+ }+ let currentElement: Element | null = topLevelElement;+ while (currentElement) {+ if (currentElement.classList.contains("protyle-breadcrumb__bar") &&+ currentElement.hasAttribute("data-backlink-id")) {+ return currentElement;+ }+ currentElement = currentElement.previousElementSibling;+ }+};++const getBacklinkOccurrenceID = (element: Element) =>+ getBacklinkOccurrenceBreadcrumb(element)?.getAttribute("data-backlink-id") || "";++const getBacklinkOccurrenceRevision = (element: Element) =>+ getBacklinkOccurrenceBreadcrumb(element)?.getAttribute("data-backlink-revision") || "";++export class BacklinkContent extends Model {+ public element: HTMLElement;+ public inputsElement: NodeListOf<HTMLInputElement>;+ public type: "pin" | "local" | "bottom";+ public blockId: string;+ public rootId: string; // "local" 和 "bottom" 必传+ public ownerProtyle?: IProtyle;+ public tree: Tree;+ public notebookId: string;+ public mTree: Tree;+ public editors: Protyle[] = [];+ public status: {+ [key: string]: {+ sort: number,+ mSort: number,+ scrollTop: number,+ mScrollTop: number,+ backlinkOpenIds: string[],+ backlinkMOpenIds: string[],+ backlinkMStatus: number, // 0 全展开,1 展开一半箭头向下,2 展开一半箭头向上,3 全收起+ backlinkFolded: boolean,+ backmentionFolded: boolean+ }+ } = {};+ private dirty = false;+ private destroyed = false;+ private refreshQueued = false;+ private searchQueued = false;+ private requestID = 0;+ private requesting = false;+ private showingLoading = false;+ private contextRequestVersions = [0, 0];+ private itemRecords = [new Map<string, IBacklinkItemRecord>(), new Map<string, IBacklinkItemRecord>()];+ private listRevision = "";+ private listQueryKey = "";+ private renderedQueryKey = "";+ 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;+ private sourceFilter = createBacklinkSourceFilter();+ private viewState?: ViewStateService;+ private viewStateReady: Promise<void> = Promise.resolve();+ private viewStateLoaded = false;+ private viewStateGeneration = 0;+ private viewStateSearchQueued = false;+ private viewStateSearchInit = false;+ private viewStateSearchRefreshAll = false;+ private readingAnchorTimers: [number?, number?] = [];+ private restoringReadingAnchors: [boolean, boolean] = [false, false];+ private readingAnchorScrollEpochs: [number, number] = [0, 0];+ private readingAnchorRenderGeneration = 0;+ private ownerScrollListener?: () => void;+ private onlyBacklinks: boolean;+ private surface: string;++ constructor(options: {+ app: App,+ tab?: Tab,+ element?: HTMLElement,+ blockId: string,+ rootId?: string,+ notebookId?: string,+ type: "pin" | "local" | "bottom",+ ownerProtyle?: IProtyle,+ emptyChange?: (empty: boolean) => void,+ onlyBacklinks?: boolean,+ surface?: string,+ }) {+ super({app: options.app});++ if (options.tab && options.type !== "bottom") {+ this.connect({+ id: options.tab.id,+ type: "backlink",+ callback: this.handelCallback.bind(this),+ msgCallback: this.handleMsgCallback.bind(this),+ });+ }++ this.blockId = options.blockId;+ this.rootId = options.rootId;+ this.notebookId = options.notebookId || "";+ this.type = options.type;+ this.onlyBacklinks = !!options.onlyBacklinks;+ this.surface = options.surface || options.type;+ this.ownerProtyle = options.ownerProtyle;+ this.emptyChange = options.emptyChange;+ this.element = options.element || options.tab.panelElement;+ this.element.classList.add("fn__flex-column", "file-tree", "sy__backlink", "dockPanel");+ this.element.classList.toggle("sy__backlink--only-backlinks", this.onlyBacklinks);+ 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;+ this.ownerFocusoutListener = (event: FocusEvent) => {+ if (!event.relatedTarget || !this.ownerProtyle.element.contains(event.relatedTarget as Node)) {+ this.refreshIfVisible(true);+ }+ };+ this.ownerProtyle.element.addEventListener("focusout", this.ownerFocusoutListener);+ }+ const backlinkSort = window.siyuan.config.editor.backlinkSort;+ const backmentionSort = window.siyuan.config.editor.backmentionSort;+ this.element.innerHTML = `<div class="block__icons backlinkList__header">+ ${this.type === "bottom" ? `<span data-type="bLayout" class="block__icon block__icon--show fn__flex-center backlinkList__toggle ariaLabel" data-position="north" aria-label="${window.siyuan.languages.collapse}"><svg><use xlink:href="#iconDown"></use></svg></span>` : ""}+ <div class="block__logo block__logo--counter fn__flex-1 fn__pointer" data-type="backlink">${window.siyuan.languages.backlinks}<span class="counter listCount"></span></div>+ <input class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.filterKeywordEnter}" />+ ${this.type === "bottom" ? "" : `<span data-type="refresh" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.refresh}"><svg><use xlink:href='#iconRefresh'></use></svg></span>+ <span class="fn__space"></span>`}+ <span data-type="search" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.filter}"><svg><use xlink:href='#iconFilter'></use></svg></span>+ <span class="fn__space"></span>+ <span data-type="sourceFilter" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.backlinkSourceFilter}"><svg><use xlink:href='#iconListFilterPlus'></use></svg></span>+ <span class="fn__space"></span>+ <span data-type="sort" data-sort="${backlinkSort}" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.sort}"><svg><use xlink:href='#iconSort'></use></svg></span>+ <span class="fn__space"></span>+ <span data-type="expand" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.expand}${this.type === "bottom" ? "" : updateHotkeyAfterTip(window.siyuan.config.keymap.editor.general.expand.custom)}">+ <svg><use xlink:href="#iconExpand"></use></svg>+ </span>+ <span class="fn__space"></span>+ <span data-type="collapse" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.collapse}${this.type === "bottom" ? "" : updateHotkeyAfterTip(window.siyuan.config.keymap.editor.general.collapse.custom)}">+ <svg><use xlink:href="#iconContract"></use></svg>+ </span>+ <span class="${this.type !== "pin" ? "fn__none " : ""}fn__space"></span>+ <span data-type="min" class="${this.type !== "pin" ? "fn__none " : ""}block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.min}${updateHotkeyAfterTip(window.siyuan.config.keymap.general.closeTab.custom)}"><svg><use xlink:href='#iconMin'></use></svg></span>+</div>+<div class="backlinkList fn__flex-1"></div>+<div class="block__icons backlinkMList__header">+ ${this.type === "bottom" ? `<span data-type="layout" class="block__icon block__icon--show fn__flex-center backlinkList__toggle ariaLabel" data-position="north" aria-label="${window.siyuan.languages.collapse}"><svg><use xlink:href="#iconDown"></use></svg></span>` : ""}+ <div class="block__logo block__logo--counter fn__flex-1 fn__pointer" data-type="mention">${window.siyuan.languages.mentions}<span class="counter listMCount"></span></div>+ <input class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.filterKeywordEnter}" />+ <span data-type="search" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.filter}"><svg><use xlink:href='#iconFilter'></use></svg></span>+ <span class="fn__space"></span>+ <span data-type="mSort" data-sort="${backmentionSort}" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.sort}"><svg><use xlink:href='#iconSort'></use></svg></span>+ <span class="fn__space"></span>+ <span data-type="mExpand" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.expand}">+ <svg><use xlink:href="#iconExpand"></use></svg>+ </span>+ <span class="fn__space"></span>+ <span data-type="mCollapse" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.collapse}">+ <svg><use xlink:href="#iconContract"></use></svg>+ </span>+ ${this.type === "bottom" ? "" : `<span class="fn__space"></span>+ <span data-type="layout" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.down}">+ <svg><use xlink:href="#iconDown"></use></svg>+ </span>`}+</div>+<div class="backlinkMList fn__flex-1"></div>`;++ this.inputsElement = this.element.querySelectorAll("input");+ this.inputsElement.forEach((item) => {+ item.addEventListener("blur", (event: KeyboardEvent) => {+ const inputElement = event.target as HTMLInputElement;+ inputElement.classList.add("fn__none");+ const filterIconElement = inputElement.parentElement.querySelector('[data-type="search"]');+ if (inputElement.value) {+ filterIconElement.classList.add("block__icon--active");+ filterIconElement.setAttribute("aria-label", window.siyuan.languages.filter + " " + inputElement.value);+ } else {+ filterIconElement.classList.remove("block__icon--active");+ filterIconElement.setAttribute("aria-label", window.siyuan.languages.filter);+ }+ });+ item.addEventListener("keydown", (event: KeyboardEvent) => {+ if (!event.isComposing && event.key === "Enter") {+ this.searchBacklinks();+ }+ });+ });+ this.element.querySelectorAll('[data-type="search"]').forEach((item, index) => {+ item.addEventListener("click", (event) => {+ event.stopPropagation();+ const inputElement = this.inputsElement[index];+ inputElement.classList.remove("fn__none");+ inputElement.select();+ });+ });+ this.tree = new Tree({+ element: this.element.querySelector(".backlinkList") as HTMLElement,+ data: null,+ titleTooltipPosition: this.type === "bottom" ? "north" : "parentE",+ click: (element) => {+ this.toggleItem(element, false);+ this.setFocus();+ this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ ctrlClick: (element) => {+ this.openDocument({+ app: options.app,+ id: element.getAttribute("data-node-id"),+ action: [Constants.CB_GET_CONTEXT]+ });+ this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ altClick: (element) => {+ this.openDocument({+ app: options.app,+ id: element.getAttribute("data-node-id"),+ position: "right",+ action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]+ });+ this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ shiftClick: (element) => {+ this.openDocument({+ app: options.app,+ id: element.getAttribute("data-node-id"),+ position: "bottom",+ action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]+ });+ this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ toggleClick: (liElement) => {+ this.toggleItem(liElement, false);+ this.setFocus();+ this.mTree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ }+ });+ this.mTree = new Tree({+ element: this.element.querySelector(".backlinkMList") as HTMLElement,+ data: null,+ titleTooltipPosition: this.type === "bottom" ? "north" : "parentE",+ click: (element) => {+ this.toggleItem(element, true);+ this.setFocus();+ this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ ctrlClick: (element) => {+ this.openDocument({+ app: options.app,+ id: element.getAttribute("data-node-id"),+ action: [Constants.CB_GET_CONTEXT]+ });+ this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ altClick: (element) => {+ this.openDocument({+ app: options.app,+ id: element.getAttribute("data-node-id"),+ position: "right",+ action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]+ });+ this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ shiftClick: (element) => {+ this.openDocument({+ app: options.app,+ id: element.getAttribute("data-node-id"),+ position: "bottom",+ action: [Constants.CB_GET_FOCUS, Constants.CB_GET_CONTEXT]+ });+ this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ toggleClick: (liElement) => {+ this.toggleItem(liElement, true);+ this.setFocus();+ this.tree.element.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ },+ blockExtHTML: `<span class="b3-list-item__action b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></span>`+ });+ this.tree.element.addEventListener("scroll", (event) => {+ this.tree.element.querySelectorAll(".protyle-gutters").forEach(item => {+ item.classList.add("fn__none");+ item.innerHTML = "";+ });+ this.tree.element.querySelectorAll(".protyle-wysiwyg--hl").forEach((hlItem) => {+ hlItem.classList.remove("protyle-wysiwyg--hl");+ });+ if (event.isTrusted) {+ this.handleReadingAnchorScroll(false);+ }+ });+ this.mTree.element.addEventListener("scroll", (event) => {+ this.mTree.element.querySelectorAll(".protyle-gutters").forEach(item => {+ item.classList.add("fn__none");+ item.innerHTML = "";+ });+ this.mTree.element.querySelectorAll(".protyle-wysiwyg--hl").forEach((hlItem) => {+ hlItem.classList.remove("protyle-wysiwyg--hl");+ });+ if (event.isTrusted) {+ this.handleReadingAnchorScroll(true);+ }+ });+ if (this.type === "bottom") {+ this.ownerScrollListener = () => {+ this.handleReadingAnchorScroll(false);+ };+ this.ownerProtyle.contentElement.addEventListener("scroll", this.ownerScrollListener);+ }+ // 为了快捷键的 dispatch+ this.element.querySelector('[data-type="collapse"]').addEventListener("click", () => {+ this.cancelContextRequests(this.tree.element, false);+ this.hideEditorGutters(this.tree.element);+ this.invalidateHeadingRequests(this.tree.element);+ this.getDocumentItemElements(this.tree).forEach(item => {+ this.setDocumentExpanded(false, item.getAttribute("data-node-id"), false);+ });+ this.tree.element.querySelectorAll(".protyle").forEach(item => {+ item.classList.add("fn__none");+ });+ this.tree.element.querySelectorAll(".b3-list-item__arrow").forEach(item => {+ item.classList.remove("b3-list-item__arrow--open");+ });+ this.updateBottomBacklinkSpacing();+ });+ this.element.querySelector('[data-type="expand"]').addEventListener("click", () => {+ this.expandDocumentItems(this.tree, false);+ });+ this.element.addEventListener("click", (event) => {+ let target = event.target as HTMLElement;+ const eventProtyleElement = target.closest(".protyle");+ if (this.type !== "bottom" || !eventProtyleElement || !this.element.contains(eventProtyleElement)) {+ this.setFocus();+ }+ while (target && !target.isEqualNode(this.element)) {+ if ((target.classList.contains("block__icon") || target.classList.contains("block__logo")) &&+ target.parentElement.parentElement === this.element) {+ const type = target.getAttribute("data-type");+ switch (type) {+ case "refresh":+ this.refresh();+ event.stopPropagation();+ break;+ case "mExpand":+ this.expandDocumentItems(this.mTree, true);+ event.stopPropagation();+ break;+ case "mCollapse":+ this.cancelContextRequests(this.mTree.element, true);+ this.hideEditorGutters(this.mTree.element);+ this.invalidateHeadingRequests(this.mTree.element);+ this.getDocumentItemElements(this.mTree).forEach(item => {+ this.setDocumentExpanded(true, item.getAttribute("data-node-id"), false);+ });+ this.mTree.element.querySelectorAll(".protyle").forEach(item => {+ item.classList.add("fn__none");+ });+ this.mTree.element.querySelectorAll(".b3-list-item__arrow").forEach(item => {+ item.classList.remove("b3-list-item__arrow--open");+ });+ event.stopPropagation();+ break;+ case "min":+ /// #if !MOBILE+ getDockByType("backlink").toggleModel("backlink", false, true);+ /// #endif+ event.stopPropagation();+ break;+ case "sort":+ case "mSort":+ this.showSortMenu(type, target.getAttribute("data-sort"));+ window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});+ event.stopPropagation();+ break;+ case "sourceFilter":+ this.showSourceFilterMenu(event);+ event.stopPropagation();+ break;+ case "layout":+ if (this.type === "bottom") {+ this.setBottomLayout(target, this.mTree.element);+ } else {+ this.setLayout(target);+ }+ event.stopPropagation();+ break;+ case "bLayout":+ this.setBottomLayout(target, this.tree.element);+ event.stopPropagation();+ break;+ case "backlink":+ if (this.type === "bottom") {+ this.setBottomLayout(target.parentElement.querySelector('[data-type="bLayout"]'), this.tree.element);+ } else {+ this.setDockSectionLayout(this.tree.element);+ }+ event.stopPropagation();+ break;+ case "mention":+ if (this.type === "bottom") {+ this.setBottomLayout(target.parentElement.querySelector('[data-type="layout"]'), this.mTree.element);+ } else {+ this.setDockSectionLayout(this.mTree.element);+ }+ event.stopPropagation();+ break;+ }+ }+ target = target.parentElement;+ }+ });++ this.setViewStateHost(this.blockId);+ this.showLoading();+ this.searchBacklinks(true);+ }++ private setViewStateHost(blockID: string) {+ this.clearReadingAnchorTimers();+ const previousReady = this.viewStateReady;+ const previous = this.viewState;+ const generation = ++this.viewStateGeneration;+ this.viewState = undefined;+ this.viewStateLoaded = !blockID;+ const createService = async () => {+ await previousReady;+ if (previous) {+ try {+ await previous.destroy();+ } catch (error) {+ console.error(error);+ }+ }+ if (generation !== this.viewStateGeneration || !blockID) {+ return;+ }+ const service = new ViewStateService({+ scope: "backlink",+ surface: this.surface,+ hostID: blockID,+ });+ this.viewState = service;+ await service.ready;+ };+ this.viewStateReady = createService().catch(error => {+ console.error(error);+ }).then(() => {+ if (generation === this.viewStateGeneration) {+ this.viewStateLoaded = true;+ }+ });+ }++ private getDocumentStateField(isMention: boolean, documentID: string) {+ return `item:${isMention ? "backmention" : "backlink"}:${encodeURIComponent(documentID)}`;+ }++ private getSectionStateField(isMention: boolean) {+ return `section:${isMention ? "backmention" : "backlink"}`;+ }++ private setDocumentExpanded(isMention: boolean, documentID: string, expanded: boolean) {+ if (documentID && this.viewState) {+ this.viewState.set(this.getDocumentStateField(isMention, documentID), expanded);+ }+ }++ private setSectionFolded(isMention: boolean, folded: boolean) {+ this.viewState?.set(this.getSectionStateField(isMention), folded);+ }++ private handelCallback() {+ /// #if !MOBILE+ if (this.type === "local") {+ fetchPost("/api/block/checkBlockExist", {id: this.blockId}, existResponse => {+ if (!existResponse.data) {+ this.parent.parent.removeTab(this.parent.id);+ }+ });+ }+ /// #endif+ }++ private handleMsgCallback(data: IWebSocketData) {+ /// #if !MOBILE+ if (data && this.type === "local") {+ switch (data.cmd) {+ case "rename":+ if (this.rootId === data.data.id) {+ this.parent.updateTitle(getDocDisplayName(data.data.title, data.data.empty));+ }+ break;+ case "closeBox":+ case "removeBox":+ if (this.notebookId === data.data.box && this.type === "local") {+ this.parent.parent.removeTab(this.parent.id);+ }+ break;+ case "removeDoc":+ if (data.data.ids.includes(this.rootId) && this.type === "local") {+ this.parent.parent.removeTab(this.parent.id);+ }+ break;+ }+ }+ /// #endif+ }++ private setLayout(element: HTMLElement) {+ const backlinkWasFolded = this.tree.element.classList.contains("fn__none");+ const backmentionWasFolded = this.mTree.element.style.height === "0px";+ this.savePendingReadingAnchor(false);+ this.savePendingReadingAnchor(true);+ if (this.mTree.element.style.flex) {+ if (this.mTree.element.style.height === "0px") {+ this.tree.element.classList.remove("fn__none");+ this.mTree.element.removeAttribute("style");+ element.setAttribute("aria-label", window.siyuan.languages.up);+ element.querySelector("use").setAttribute("xlink:href", "#iconUp");+ } else {+ this.tree.element.classList.remove("fn__none");+ this.mTree.element.removeAttribute("style");+ element.setAttribute("aria-label", window.siyuan.languages.down);+ element.querySelector("use").setAttribute("xlink:href", "#iconDown");+ }+ } else {+ if (element.getAttribute("aria-label") === window.siyuan.languages.down) {+ this.tree.element.classList.remove("fn__none");+ this.mTree.element.setAttribute("style", "flex:none;height:0px");+ element.setAttribute("aria-label", window.siyuan.languages.up);+ element.querySelector("use").setAttribute("xlink:href", "#iconUp");+ } else {+ this.tree.element.classList.add("fn__none");+ this.mTree.element.setAttribute("style", `flex:none;height:${this.element.clientHeight - this.tree.element.previousElementSibling.clientHeight * 2}px`);+ element.setAttribute("aria-label", window.siyuan.languages.down);+ element.querySelector("use").setAttribute("xlink:href", "#iconDown");+ }+ }+ this.setSectionFolded(false, this.tree.element.classList.contains("fn__none"));+ this.setSectionFolded(true, this.mTree.element.style.height === "0px");+ const viewFoldPromises = this.syncViewFoldVisibility();+ const restoreBacklink = backlinkWasFolded && !this.tree.element.classList.contains("fn__none");+ const restoreBackmention = backmentionWasFolded && this.mTree.element.style.height !== "0px";+ this.tree.element.dispatchEvent(new CustomEvent("scroll"));+ this.mTree.element.dispatchEvent(new CustomEvent("scroll"));+ if (restoreBacklink) {+ this.restorePersistedReadingAnchorAfter(false, viewFoldPromises[0]);+ }+ if (restoreBackmention) {+ this.restorePersistedReadingAnchorAfter(true, viewFoldPromises[1]);+ }+ }++ private setDockSectionLayout(listElement: HTMLElement) {+ const isMention = listElement === this.mTree.element;+ const backlinkFolded = this.tree.element.classList.contains("fn__none");+ const backmentionFolded = this.mTree.element.style.height === "0px";+ const nextBacklinkFolded = isMention ? backlinkFolded : !backlinkFolded;+ const nextBackmentionFolded = isMention ? !backmentionFolded : backmentionFolded;+ if (isMention ? nextBackmentionFolded : nextBacklinkFolded) {+ this.savePendingReadingAnchor(isMention);+ }+ this.applyDockLayout(+ nextBacklinkFolded,+ nextBackmentionFolded,+ this.status[this.blockId]?.backlinkMStatus ?? 1,+ );+ this.setSectionFolded(isMention, isMention ? nextBackmentionFolded : nextBacklinkFolded);+ const viewFoldPromises = this.syncViewFoldVisibility();+ const restoreAnchor = isMention ? !nextBackmentionFolded : !nextBacklinkFolded;+ this.saveStatus(false);+ this.tree.element.dispatchEvent(new CustomEvent("scroll"));+ this.mTree.element.dispatchEvent(new CustomEvent("scroll"));+ if (restoreAnchor) {+ this.restorePersistedReadingAnchorAfter(isMention, viewFoldPromises[isMention ? 1 : 0]);+ }+ }++ private setBottomLayout(element: HTMLElement, listElement: HTMLElement) {+ if (isHeightAnimating(listElement)) {+ return;+ }+ const folded = !listElement.classList.contains("fn__none");+ if (folded) {+ this.savePendingReadingAnchor(listElement === this.mTree.element);+ }+ if (folded) {+ this.cancelContextRequests(listElement, listElement === this.mTree.element);+ this.hideEditorGutters(listElement);+ this.invalidateHeadingRequests(listElement);+ listElement.dataset.heightFolding = "true";+ collapseHeight(listElement, () => {+ delete listElement.dataset.heightFolding;+ listElement.classList.add("fn__none");+ });+ } else {+ delete listElement.dataset.heightFolding;+ listElement.classList.remove("fn__none");+ const viewFoldPromise = this.resumeViewFoldStates(listElement);+ const expandPromise = new Promise<void>(resolve => {+ expandHeight(listElement, resolve);+ });+ this.restorePersistedReadingAnchorAfter(+ listElement === this.mTree.element,+ Promise.all([viewFoldPromise, expandPromise]).then(() => undefined),+ );+ }+ if (folded) {+ listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ }+ element.setAttribute("aria-label", folded ? window.siyuan.languages.expand : window.siyuan.languages.collapse);+ element.querySelector("use").setAttribute("xlink:href", folded ? "#iconRight" : "#iconDown");+ this.setSectionFolded(listElement === this.mTree.element, folded);+ this.saveStatus(false);+ }++ private openDocument(options: {app: App, id: string, action: TProtyleAction[], position?: "right" | "bottom"}) {+ /// #if MOBILE+ openMobileFileById(options.app, options.id, options.action);+ /// #else+ openFileById(options);+ /// #endif+ }++ private setFocus() {+ /// #if !MOBILE+ if (this.type === "bottom") {+ this.setOwnerFocus();+ this.element.focus({preventScroll: true});+ return;+ }+ if (this.type === "local") {+ setPanelFocus(this.element.parentElement.parentElement);+ } else {+ setPanelFocus(this.element);+ }+ /// #endif+ }++ private setOwnerFocus() {+ /// #if !MOBILE+ const wndElement = this.ownerProtyle.element.closest('[data-type="wnd"]');+ if (wndElement) {+ setPanelFocus(wndElement);+ }+ /// #endif+ }++ private showSortMenu(type: string, sort: string) {+ const clickEvent = (currentSort: string) => {+ (type === "sort" ? this.tree : this.mTree).element.previousElementSibling.querySelector(`[data-type="${type}"]`).setAttribute("data-sort", currentSort);+ // 保存排序状态到配置+ const sortValue = parseInt(currentSort);+ if (type === "sort") {+ window.siyuan.config.editor.backlinkSort = sortValue;+ } else {+ window.siyuan.config.editor.backmentionSort = sortValue;+ }+ fetchPost("/api/setting/setEditor", window.siyuan.config.editor, (response) => {+ window.siyuan.config.editor = response.data;+ });+ this.searchBacklinks();+ };+ window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "0",+ iconHTML: "",+ label: window.siyuan.languages.fileNameASC,+ click: () => {+ clickEvent("0");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "1",+ iconHTML: "",+ label: window.siyuan.languages.fileNameDESC,+ click: () => {+ clickEvent("1");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "4",+ iconHTML: "",+ label: window.siyuan.languages.fileNameNatASC,+ click: () => {+ clickEvent("4");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "5",+ iconHTML: "",+ label: window.siyuan.languages.fileNameNatDESC,+ click: () => {+ clickEvent("5");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "9",+ iconHTML: "",+ label: window.siyuan.languages.createdASC,+ click: () => {+ clickEvent("9");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "10",+ iconHTML: "",+ label: window.siyuan.languages.createdDESC,+ click: () => {+ clickEvent("10");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "2",+ iconHTML: "",+ label: window.siyuan.languages.modifiedASC,+ click: () => {+ clickEvent("2");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: sort === "3",+ iconHTML: "",+ label: window.siyuan.languages.modifiedDESC,+ click: () => {+ clickEvent("3");+ }+ }).element);+ }++ private applySourceFilter(filter: IBacklinkSourceFilter) {+ this.sourceFilter = normalizeBacklinkSourceFilter(filter);+ this.element.querySelector('[data-type="sourceFilter"]')?.classList.toggle(+ "block__icon--active",+ Boolean(getBacklinkSourceFilterParam(this.sourceFilter)),+ );+ this.searchBacklinks();+ }++ private showSourceFilterMenu(event: MouseEvent) {+ const dailyNoteSubmenu = ([+ ["all", window.siyuan.languages.all],+ ["only", window.siyuan.languages.dailyNote],+ ["exclude", window.siyuan.languages.nonDailyNote],+ ] as Array<[TBacklinkDailyNoteFilter, string]>).map(([value, label]) => ({+ checked: this.sourceFilter.dailyNote === value,+ iconHTML: "",+ label,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, dailyNote: value});+ }+ }));+ const notebookSubmenu: IMenu[] = [{+ checked: this.sourceFilter.excludedNotebookIDs.length === 0,+ iconHTML: "",+ label: window.siyuan.languages.allNotebooks,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: []});+ }+ }, {type: "separator"}];+ (window.siyuan.notebooks || []).filter(item => !item.closed).forEach(item => {+ notebookSubmenu.push({+ checked: !this.sourceFilter.excludedNotebookIDs.includes(item.id),+ iconHTML: "",+ label: escapeHtml(item.name),+ click: () => {+ const excludedNotebookIDs = new Set(this.sourceFilter.excludedNotebookIDs);+ if (excludedNotebookIDs.has(item.id)) {+ excludedNotebookIDs.delete(item.id);+ } else {+ excludedNotebookIDs.add(item.id);+ }+ this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: Array.from(excludedNotebookIDs)});+ }+ });+ });++ window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconCalendar",+ label: window.siyuan.languages.dailyNote,+ type: "submenu",+ submenu: dailyNoteSubmenu,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconFiles",+ label: window.siyuan.languages.agentCatNotebook,+ type: "submenu",+ submenu: notebookSubmenu,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: this.sourceFilter.excludeSelf,+ iconHTML: "",+ label: window.siyuan.languages.excludeSelfBacklink,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, excludeSelf: !this.sourceFilter.excludeSelf});+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ disabled: !getBacklinkSourceFilterParam(this.sourceFilter),+ icon: "iconUndo",+ label: window.siyuan.languages.reset,+ click: () => {+ this.applySourceFilter(createBacklinkSourceFilter());+ }+ }).element);+ window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});+ }++ private toggleItem(liElement: HTMLElement, isMention: boolean, persist = true) {+ const svgElement = liElement.firstElementChild?.firstElementChild;+ if (!svgElement || svgElement.getAttribute("disabled")) {+ return;+ }+ const docId = liElement.getAttribute("data-node-id");+ const record = this.itemRecords[isMention ? 1 : 0].get(docId);+ const editor = record?.editor;+ 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" || isMobile())) {+ hideElements(["gutter"], editor.protyle);+ invalidateViewFoldRequests(editor.protyle);+ editor.protyle.element.classList.add("fn__none");+ } else if (editor) {+ unregisterViewFoldContext(editor.protyle);+ editor.destroy();+ this.editors.splice(this.editors.indexOf(editor), 1);+ editor.protyle.element.remove();+ if (record) {+ record.editor = undefined;+ record.contextRevision = "";+ }+ }+ if (persist) {+ this.setDocumentExpanded(isMention, docId, false);+ }+ this.updateBottomBacklinkSpacing();+ } else if (editor && !record?.contextDirty) {+ editor.protyle.element.classList.remove("fn__none");+ svgElement.classList.add("b3-list-item__arrow--open");+ void applyViewFoldStates(editor.protyle);+ if (persist) {+ this.setDocumentExpanded(isMention, docId, true);+ }+ this.updateBottomBacklinkSpacing();+ } else {+ this.loadContext(liElement, isMention, true, persist);+ }+ }++ private expandDocumentItems(tree: Tree, isMention: boolean) {+ const listElement = tree.element;+ if (this.type === "bottom" && isHeightAnimating(listElement)) {+ return;+ }+ const folded = this.type === "bottom" ?+ listElement.classList.contains("fn__none") :+ (isMention ? listElement.style.height === "0px" : listElement.classList.contains("fn__none"));+ if (folded) {+ if (this.type === "bottom") {+ const toggleType = isMention ? "layout" : "bLayout";+ this.setBottomLayout(+ listElement.previousElementSibling.querySelector(`[data-type="${toggleType}"]`),+ listElement+ );+ } else {+ this.setDockSectionLayout(listElement);+ }+ }+ this.getDocumentItemElements(tree).forEach(item => {+ if (!item.querySelector(".b3-list-item__arrow--open")) {+ this.toggleItem(item, isMention);+ }+ });+ }++ private loadContext(liElement: HTMLElement, isMention: boolean, expand: boolean, persist = false) {+ 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 viewStateGeneration = this.viewStateGeneration;+ 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 || viewStateGeneration !== this.viewStateGeneration ||+ !liElement.isConnected ||+ contextRequestVersion !== this.contextRequestVersions[index] ||+ requestGeneration !== record.requestGeneration) {+ return;+ }+ if (!response.data) {+ return;+ }+ svgElement.removeAttribute("disabled");+ if (record.editor?.protyle.element.contains(document.activeElement)) {+ record.contextDirty = true;+ this.dirty = true;+ this.pendingRootIDs.add(docId);+ return;+ }+ 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 editor = record.editor;+ const scrollAnchor = this.captureReadingAnchor(isMention);+ const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);+ const anchorQueryKey = this.renderedQueryKey;+ editor.protyle.options.backlinkData = backlinkData;+ void renderBacklink(editor.protyle, backlinkData).then(() => {+ window.requestAnimationFrame(() => {+ if (this.destroyed || blockId !== this.blockId ||+ viewStateGeneration !== this.viewStateGeneration ||+ contextRequestVersion !== this.contextRequestVersions[index] ||+ requestGeneration !== record.requestGeneration || record.editor !== editor ||+ !editor.protyle.element.isConnected || editor.protyle.element.classList.contains("fn__none") ||+ scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention) ||+ anchorQueryKey !== this.renderedQueryKey || anchorQueryKey !== this.listQueryKey) {+ return;+ }+ if (scrollAnchor) {+ this.restoreReadingAnchor(scrollAnchor);+ } else {+ this.restorePersistedReadingAnchor(isMention, docId);+ }+ });+ });+ searchMarkRender(editor.protyle, response.data.keywords, undefined, undefined, {+ excludeSelector: ".protyle-breadcrumb__bar[data-backlink-id]"+ });+ } 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);+ record.containerElement.appendChild(editorElement);+ const editor = new Protyle(this.app, editorElement, {+ blockId: docId,+ notebookId,+ 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());+ }+ editor.protyle.notebookId = notebookId;+ if (notebookId) {+ editor.protyle.element.setAttribute("data-notebook-id", notebookId);+ } else {+ editor.protyle.element.removeAttribute("data-notebook-id");+ }+ searchMarkRender(editor.protyle, response.data.keywords, undefined, undefined, {+ excludeSelector: ".protyle-breadcrumb__bar[data-backlink-id]"+ });+ /// #if MOBILE+ registerMobileSecondaryEditor(editor, () => this.switchBlock("", "", ""));+ /// #endif+ this.editors.push(editor);+ record.editor = editor;+ const service = this.viewState;+ const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);+ const anchorQueryKey = this.renderedQueryKey;+ if (service) {+ void registerViewFoldContext(editor.protyle, {+ store: service,+ pane: isMention ? "backmention" : "backlink",+ rootID: docId,+ getOccurrenceID: getBacklinkOccurrenceID,+ getOccurrenceRevision: getBacklinkOccurrenceRevision,+ }).then(() => {+ window.requestAnimationFrame(() => {+ if (this.destroyed || blockId !== this.blockId ||+ viewStateGeneration !== this.viewStateGeneration || service !== this.viewState ||+ contextRequestVersion !== this.contextRequestVersions[index] ||+ requestGeneration !== record.requestGeneration || record.editor !== editor ||+ !editor.protyle.element.isConnected || editor.protyle.element.classList.contains("fn__none") ||+ scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention) ||+ anchorQueryKey !== this.renderedQueryKey || anchorQueryKey !== this.listQueryKey) {+ return;+ }+ this.restorePersistedReadingAnchor(isMention, docId);+ });+ });+ }+ }+ }+ if (expand) {+ record.editor?.protyle.element.classList.remove("fn__none");+ svgElement.classList.add("b3-list-item__arrow--open");+ if (persist) {+ this.setDocumentExpanded(isMention, docId, true);+ }+ }+ this.updateBottomBacklinkSpacing();+ }).finally(() => {+ if (requestGeneration === record.requestGeneration) {+ svgElement.removeAttribute("disabled");+ }+ });+ }++ private hideEditorGutters(element: Element) {+ this.editors.forEach(editor => {+ if (editor.protyle.element === element || element.contains(editor.protyle.element)) {+ hideElements(["gutter"], editor.protyle);+ }+ });+ }++ private invalidateHeadingRequests(element: Element) {+ this.editors.forEach(editor => {+ if (editor.protyle.element === element || element.contains(editor.protyle.element)) {+ invalidateViewFoldRequests(editor.protyle);+ }+ });+ }++ private resumeViewFoldStates(element: Element) {+ const promises: Promise<void>[] = [];+ this.editors.forEach(editor => {+ if ((editor.protyle.element === element || element.contains(editor.protyle.element)) &&+ !editor.protyle.element.classList.contains("fn__none")) {+ promises.push(applyViewFoldStates(editor.protyle));+ }+ });+ return Promise.all(promises).then(() => undefined);+ }++ private syncViewFoldVisibility() {+ const promises: [Promise<void>, Promise<void>] = [Promise.resolve(), Promise.resolve()];+ [this.tree.element, this.mTree.element].forEach((element, index) => {+ if (element.classList.contains("fn__none") || element.style.height === "0px") {+ this.invalidateHeadingRequests(element);+ } else {+ promises[index] = this.resumeViewFoldStates(element);+ }+ });+ return promises;+ }++ private cancelContextRequests(element: Element, isMention: boolean) {+ this.contextRequestVersions[isMention ? 1 : 0]++;+ element.querySelectorAll(".b3-list-item__arrow[disabled]").forEach(item => {+ item.removeAttribute("disabled");+ });+ }++ private destroyItemRecord(record: IBacklinkItemRecord) {+ if (record.editor) {+ unregisterViewFoldContext(record.editor.protyle);+ record.editor.destroy();+ const editorIndex = this.editors.indexOf(record.editor);+ if (editorIndex > -1) {+ this.editors.splice(editorIndex, 1);+ }+ }+ record.containerElement.remove();+ }++ public getDocumentItemElements(tree: Tree) {+ return Array.from(tree.element.querySelectorAll(+ ":scope > .b3-list > .backlinkList__item > .b3-list-item[data-node-id]"+ )) as HTMLLIElement[];+ }++ public getScrollElement(tree: Tree) {+ return this.type === "bottom" ? this.ownerProtyle.contentElement : tree.element;+ }++ 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);+ const containerElement = document.createElement("div");+ containerElement.className = "backlinkList__item";+ containerElement.dataset.nodeId = id;+ containerElement.appendChild(headerElement);+ record = {+ revision: item.revision || "",+ containerElement,+ headerElement,+ requestGeneration: 0,+ };+ records.set(id, record);+ listElement.appendChild(containerElement);+ 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.containerElement !== cursor) {+ listElement.insertBefore(record.containerElement, cursor);+ changed = true;+ }+ cursor = record.containerElement.nextElementSibling;+ });+ return changed;+ }++ private getReadingAnchorField(isMention: boolean) {+ if (this.type === "bottom") {+ return "anchor:bottom";+ }+ return `anchor:${isMention ? "backmention" : "backlink"}`;+ }++ private getReadingAnchorIndex(isMention: boolean) {+ return this.type === "bottom" ? 0 : (isMention ? 1 : 0);+ }++ private getReadingAnchorScrollEpoch(isMention: boolean) {+ return this.readingAnchorScrollEpochs[this.getReadingAnchorIndex(isMention)];+ }++ private isRestoringReadingAnchor(isMention: boolean) {+ return this.restoringReadingAnchors[this.getReadingAnchorIndex(isMention)];+ }++ private isReadingAnchorPaneVisible(isMention: boolean) {+ const listElement = isMention ? this.mTree.element : this.tree.element;+ return !listElement.classList.contains("fn__none") && listElement.dataset.heightFolding !== "true" &&+ (this.type === "bottom" || !isMention || listElement.style.height !== "0px");+ }++ private isBottomReadingAnchorViewportActive() {+ if (this.type !== "bottom" || !this.ownerProtyle || this.element.classList.contains("fn__none") ||+ this.element.getClientRects().length === 0) {+ return this.type !== "bottom";+ }+ const ownerRect = this.ownerProtyle.contentElement.getBoundingClientRect();+ const panelRect = this.element.getBoundingClientRect();+ return panelRect.bottom > ownerRect.top && panelRect.top < ownerRect.bottom;+ }++ private capturePaneReadingAnchor(isMention: boolean): IBacklinkReadingAnchor | undefined {+ const tree = isMention ? this.mTree : this.tree;+ const pane = isMention ? "backmention" : "backlink";+ const scrollElement = this.getScrollElement(tree);+ const anchor = captureBacklinkReadingAnchor({+ scopeElement: tree.element,+ scrollElement,+ pane,+ queryKey: this.renderedQueryKey,+ });+ const scrollRect = scrollElement.getBoundingClientRect();+ const scopeRect = tree.element.getBoundingClientRect();+ const viewportTop = Math.max(scrollRect.top, scopeRect.top);+ const viewportBottom = Math.min(scrollRect.bottom, scopeRect.bottom);+ const titleElements = Array.from(tree.element.querySelectorAll(+ ":scope > .b3-list > .backlinkList__item > .b3-list-item[data-node-id]"+ )) as HTMLElement[];+ const titleElement = titleElements.filter(item => {+ const rect = item.getBoundingClientRect();+ return rect.bottom > viewportTop && rect.top < viewportBottom;+ }).sort((left, right) => {+ const leftOffset = left.getBoundingClientRect().top - scrollRect.top;+ const rightOffset = right.getBoundingClientRect().top - scrollRect.top;+ if (leftOffset <= 0 && rightOffset > 0) {+ return -1;+ }+ if (rightOffset <= 0 && leftOffset > 0) {+ return 1;+ }+ return leftOffset <= 0 ? rightOffset - leftOffset : leftOffset - rightOffset;+ })[0];+ const titleAnchor = titleElement ? {+ pane,+ rootID: titleElement.getAttribute("data-node-id") || "",+ occurrenceID: "",+ blockID: "",+ offset: titleElement.getBoundingClientRect().top - scrollRect.top,+ queryKey: this.renderedQueryKey,+ } satisfies IBacklinkReadingAnchor : undefined;+ const anchors = [anchor, titleAnchor].filter((item): item is IBacklinkReadingAnchor => Boolean(item));+ const crossingAnchor = anchors.filter(item => item.offset <= 0)+ .sort((left, right) => right.offset - left.offset)[0];+ return crossingAnchor || anchors.filter(item => item.offset > 0)+ .sort((left, right) => left.offset - right.offset)[0];+ }++ private captureReadingAnchor(isMention: boolean) {+ if (this.type !== "bottom") {+ return this.capturePaneReadingAnchor(isMention);+ }+ const anchors = [this.capturePaneReadingAnchor(false), this.capturePaneReadingAnchor(true)]+ .filter((item): item is IBacklinkReadingAnchor => Boolean(item));+ const crossingAnchor = anchors.filter(anchor => anchor.offset <= 0)+ .sort((left, right) => right.offset - left.offset)[0];+ return crossingAnchor || anchors.filter(anchor => anchor.offset > 0)+ .sort((left, right) => left.offset - right.offset)[0];+ }++ private restoreReadingAnchor(anchor?: IBacklinkReadingAnchor) {+ if (!anchor) {+ return;+ }+ const isMention = anchor.pane === "backmention";+ if (!this.isReadingAnchorPaneVisible(isMention)) {+ return;+ }+ const tree = isMention ? this.mTree : this.tree;+ const index = this.getReadingAnchorIndex(isMention);+ this.restoringReadingAnchors[index] = true;+ const restored = restoreBacklinkReadingAnchor({+ anchor,+ scopeElement: tree.element,+ scrollElement: this.getScrollElement(tree),+ pane: anchor.pane,+ queryKey: this.listQueryKey,+ });+ if (!restored) {+ this.restoringReadingAnchors[index] = false;+ return;+ }+ window.requestAnimationFrame(() => {+ this.restoringReadingAnchors[index] = false;+ });+ }++ private restorePersistedReadingAnchor(isMention: boolean, loadedRootID?: string) {+ if (this.type === "bottom" && !this.isBottomReadingAnchorViewportActive()) {+ return;+ }+ const anchor = this.viewState?.get<IBacklinkReadingAnchor>(this.getReadingAnchorField(isMention));+ if (loadedRootID && (anchor?.rootID !== loadedRootID ||+ anchor.pane !== (isMention ? "backmention" : "backlink"))) {+ return;+ }+ this.restoreReadingAnchor(anchor);+ }++ private restorePersistedReadingAnchorAfter(isMention: boolean, promise: Promise<void>) {+ const generation = this.viewStateGeneration;+ const service = this.viewState;+ const blockID = this.blockId;+ const queryKey = this.renderedQueryKey;+ const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);+ void promise.then(() => {+ if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||+ blockID !== this.blockId || queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey ||+ scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention)) {+ return;+ }+ this.restorePersistedReadingAnchor(isMention);+ });+ }++ private clearReadingAnchorTimers() {+ this.readingAnchorTimers.forEach(timer => {+ if (timer) {+ window.clearTimeout(timer);+ }+ });+ this.readingAnchorTimers = [];+ this.restoringReadingAnchors = [false, false];+ this.readingAnchorScrollEpochs[0]++;+ this.readingAnchorScrollEpochs[1]++;+ this.readingAnchorRenderGeneration++;+ }++ private handleReadingAnchorScroll(isMention: boolean) {+ if (this.isRestoringReadingAnchor(isMention)) {+ return;+ }+ this.readingAnchorScrollEpochs[this.getReadingAnchorIndex(isMention)]++;+ this.scheduleReadingAnchorSave(isMention);+ }++ private scheduleReadingAnchorSave(isMention: boolean) {+ if (this.isRestoringReadingAnchor(isMention) || !this.viewState || !this.renderedQueryKey ||+ this.renderedQueryKey !== this.listQueryKey) {+ return;+ }+ const index = this.getReadingAnchorIndex(isMention);+ if (this.readingAnchorTimers[index]) {+ window.clearTimeout(this.readingAnchorTimers[index]);+ }+ const generation = this.viewStateGeneration;+ const service = this.viewState;+ const queryKey = this.renderedQueryKey;+ this.readingAnchorTimers[index] = window.setTimeout(() => {+ this.readingAnchorTimers[index] = undefined;+ if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||+ queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey) {+ return;+ }+ this.saveReadingAnchor(isMention, service, queryKey);+ }, 400);+ }++ private savePendingReadingAnchor(isMention: boolean) {+ const index = this.getReadingAnchorIndex(isMention);+ if (this.readingAnchorTimers[index]) {+ window.clearTimeout(this.readingAnchorTimers[index]);+ this.readingAnchorTimers[index] = undefined;+ }+ this.saveReadingAnchor(isMention);+ }++ private saveReadingAnchor(isMention: boolean, service = this.viewState, queryKey = this.renderedQueryKey) {+ if (!service || service !== this.viewState || !queryKey || queryKey !== this.renderedQueryKey ||+ queryKey !== this.listQueryKey) {+ return;+ }+ const anchor = this.captureReadingAnchor(isMention);+ if (!anchor || anchor.queryKey !== queryKey) {+ if (this.type === "bottom" && !this.isBottomReadingAnchorViewportActive() &&+ service.has(this.getReadingAnchorField(isMention))) {+ service.remove(this.getReadingAnchorField(isMention));+ }+ return;+ }+ service.set(this.getReadingAnchorField(isMention), anchor);+ }++ 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, false);+ }+ });+ });+ }++ private updateBottomBacklinkSpacing() {+ if (this.type !== "bottom") {+ return;+ }+ if (this.element.classList.contains("sy__backlink--backlinks-empty") ||+ this.element.classList.contains("sy__backlink--mentions-empty")) {+ this.tree.element.classList.remove("backlinkList--divider-spacing");+ return;+ }+ const lastItem = this.tree.element.querySelector(+ ":scope > .b3-list > .backlinkList__item:last-child > .b3-list-item"+ );+ this.tree.element.classList.toggle("backlinkList--divider-spacing",+ !lastItem || !lastItem.querySelector(".b3-list-item__arrow--open"));+ }++ private showLoading() {+ if (this.type !== "bottom" && !isMobile()) {+ return;+ }+ this.showingLoading = true;+ this.resetRenderedData(false);+ this.element.classList.remove("sy__backlink--backlinks-empty", "sy__backlink--mentions-empty");+ 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;+ this.element.querySelector(".listCount").textContent = "";+ this.element.querySelector(".listMCount").textContent = "";+ this.updateBottomBacklinkSpacing();+ }++ private resetRenderedData(resetLists: boolean) {+ cancelHeightAnimation(this.tree.element);+ cancelHeightAnimation(this.mTree.element);+ delete this.tree.element.dataset.heightFolding;+ delete this.mTree.element.dataset.heightFolding;+ this.cancelContextRequests(this.tree.element, false);+ this.cancelContextRequests(this.mTree.element, true);+ this.editors.forEach(item => {+ unregisterViewFoldContext(item.protyle);+ item.destroy();+ });+ this.editors = [];+ this.itemRecords.forEach(records => records.clear());+ this.listRevision = "";+ this.listQueryKey = "";+ this.renderedQueryKey = "";+ if (resetLists) {+ this.tree.updateData(null);+ this.mTree.updateData(null);+ }+ }++ public prepareForBlock(blockId: string, rootId: string) {+ if (!this.showingLoading) {+ this.saveStatus();+ }+ this.requestID++;+ 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;+ this.setViewStateHost(blockId);+ this.setRequesting(false);+ this.showLoading();+ }++ 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 = notebookId || "";+ this.setViewStateHost(blockId);+ 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.setRequesting(false);+ if (!blockId) {+ this.render({+ box: "",+ backlinks: [],+ backmentions: [],+ linkRefsCount: 0,+ mentionsCount: 0,+ k: this.inputsElement[0].value,+ mk: this.inputsElement[1].value,+ }, true);+ return;+ }+ this.showLoading();+ this.searchBacklinks(true);+ }++ private setRequesting(requesting: boolean) {+ this.requesting = requesting;+ this.element.querySelector('.block__icon[data-type="refresh"] svg')?.classList.toggle("fn__rotate", requesting);+ }++ private finishRequest(requestID: number) {+ if (this.destroyed || requestID !== this.requestID) {+ return false;+ }+ this.setRequesting(false);+ return true;+ }++ private runQueuedRequest() {+ if (this.refreshQueued) {+ this.refresh();+ return true;+ }+ if (this.searchQueued) {+ this.searchBacklinks();+ return true;+ }+ return false;+ }++ public refresh() {+ if (!this.blockId) {+ return;+ }+ if (this.requesting) {+ this.refreshQueued = true;+ return;+ }+ this.refreshQueued = false;+ this.setRequesting(true);+ this.dirty = false;+ const requestID = ++this.requestID;+ let responseHandled = false;+ fetchPost("/api/ref/refreshBacklink", {+ id: this.blockId,+ }, () => {+ responseHandled = true;+ if (!this.finishRequest(requestID)) {+ return;+ }+ if (!this.runQueuedRequest()) {+ this.searchBacklinks(false, true);+ }+ }).finally(() => {+ if (responseHandled || !this.finishRequest(requestID)) {+ return;+ }+ if (!this.runQueuedRequest()) {+ // 即使重建索引失败,也重新读取已有的反链数据并释放加载状态。+ this.searchBacklinks(false, true);+ }+ });+ }++ private searchBacklinks(init = false, refreshAllContexts = false) {+ if (!this.blockId) {+ return;+ }+ if (!this.viewStateLoaded) {+ this.viewStateSearchInit = this.viewStateSearchInit || init;+ this.viewStateSearchRefreshAll = this.viewStateSearchRefreshAll || refreshAllContexts;+ if (!this.viewStateSearchQueued) {+ this.viewStateSearchQueued = true;+ void this.viewStateReady.then(() => {+ this.viewStateSearchQueued = false;+ if (this.destroyed) {+ return;+ }+ const queuedInit = this.viewStateSearchInit;+ const queuedRefreshAll = this.viewStateSearchRefreshAll;+ this.viewStateSearchInit = false;+ this.viewStateSearchRefreshAll = false;+ this.searchBacklinks(queuedInit, queuedRefreshAll);+ });+ }+ return;+ }+ if (this.requesting) {+ this.searchQueued = true;+ return;+ }+ this.searchQueued = false;+ this.setRequesting(true);+ // 解析当前反链面板所属 box:优先用已记录的 notebookId,首次为空时按 rootId 在已打开的编辑器里查找+ let notebookId = this.notebookId;+ if (!notebookId && this.rootId) {+ getAllEditor().some(item => {+ if (item.protyle.block.rootID === this.rootId) {+ notebookId = item.protyle.notebookId;+ return true;+ }+ });+ }+ const param: {+ sort: string,+ mSort: string,+ k: string,+ mk: string,+ id: string,+ sourceFilter?: IBacklinkSourceFilter,+ notebook?: string,+ knownRevision?: string,+ includeMentions?: boolean,+ } = {+ sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")).toString(),+ mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")).toString(),+ k: this.inputsElement[0].value,+ mk: this.inputsElement[1].value,+ id: this.blockId,+ };+ if (this.onlyBacklinks) {+ param.includeMentions = false;+ }+ const sourceFilter = getBacklinkSourceFilterParam(this.sourceFilter);+ if (sourceFilter) {+ param.sourceFilter = sourceFilter;+ }+ const blockId = this.blockId;+ 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 => {+ responseHandled = true;+ if (!this.finishRequest(requestID) || blockId !== this.blockId) {+ return;+ }+ if (!shouldRenderBacklinkResponse(this.refreshQueued, this.searchQueued)) {+ this.runQueuedRequest();+ return;+ }+ if (this.editors.some(editor => editor.protyle.element.contains(document.activeElement))) {+ this.markDirty();+ return;+ }+ if (!response.data) {+ if (this.showingLoading || init) {+ this.render(undefined, init);+ }+ return;+ }+ if (shouldSaveBacklinkStatus(init, this.showingLoading)) {+ this.saveStatus();+ }+ 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();+ }+ }).finally(() => {+ if (responseHandled || !this.finishRequest(requestID) || blockId !== this.blockId) {+ return;+ }+ if (!this.runQueuedRequest() && this.type === "bottom" && this.dirty) {+ this.refreshIfVisible();+ }+ });+ }++ public saveStatus(includeReadingAnchor = true) {+ if (includeReadingAnchor) {+ this.saveReadingAnchor(false);+ if (this.type !== "bottom") {+ this.saveReadingAnchor(true);+ }+ }+ this.status[this.blockId] = {+ sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")),+ mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")),+ scrollTop: this.tree.element.scrollTop,+ mScrollTop: this.mTree.element.scrollTop,+ backlinkOpenIds: [],+ backlinkMOpenIds: [],+ backlinkMStatus: 3, // 0 全展开,1 展开一半箭头向下,2 展开一半箭头向上,3 全收起+ backlinkFolded: this.tree.element.classList.contains("fn__none") ||+ this.tree.element.dataset.heightFolding === "true",+ backmentionFolded: this.type === "bottom" ?+ (this.mTree.element.classList.contains("fn__none") ||+ this.mTree.element.dataset.heightFolding === "true") :+ this.mTree.element.style.height === "0px"+ };+ this.tree.element.querySelectorAll(".b3-list-item__arrow--open").forEach(item => {+ this.status[this.blockId].backlinkOpenIds.push(item.parentElement.parentElement.getAttribute("data-node-id"));+ });+ this.mTree.element.querySelectorAll(".b3-list-item__arrow--open").forEach(item => {+ this.status[this.blockId].backlinkMOpenIds.push(item.parentElement.parentElement.getAttribute("data-node-id"));+ });+ if (this.mTree.element.style.flex) {+ if (this.mTree.element.style.height === "0px") {+ this.status[this.blockId].backlinkMStatus = 3;+ } else {+ this.status[this.blockId].backlinkMStatus = 0;+ }+ } else {+ if (this.mTree.element.previousElementSibling.querySelector('[data-type="layout"]').getAttribute("aria-label") === window.siyuan.languages.down) {+ this.status[this.blockId].backlinkMStatus = 1;+ } else {+ this.status[this.blockId].backlinkMStatus = 2;+ }+ }+ }++ public render(data?: IBacklinkListResponse, init = false) {+ if (!data) {+ this.listRevision = "";+ this.listQueryKey = "";+ data = {+ box: "",+ backlinks: [],+ backmentions: [],+ linkRefsCount: 0,+ mentionsCount: 0,+ k: "",+ mk: ""+ };+ }+ const wasLoading = this.showingLoading;+ this.showingLoading = false;++ this.setRequesting(false);+ this.notebookId = data.box;+ this.inputsElement[0].value = data.k;+ this.inputsElement[1].value = data.mk;+ const runtimeAnchorRenderGeneration = ++this.readingAnchorRenderGeneration;+ const runtimeAnchors = (this.type === "bottom" ? [false] : [false, true]).map(isMention => ({+ anchor: this.captureReadingAnchor(isMention),+ isMention,+ scrollEpoch: this.getReadingAnchorScrollEpoch(isMention),+ }));+ const runtimeAnchorBlockID = this.blockId;+ const runtimeAnchorQueryKey = this.renderedQueryKey;+ const backlinkChanged = this.reconcileList(this.tree, data.backlinks, false);+ const backmentionChanged = this.reconcileList(this.mTree, data.backmentions, true);+ this.renderedQueryKey = this.listQueryKey;+ if (backlinkChanged || backmentionChanged) {+ window.requestAnimationFrame(() => {+ if (this.destroyed || runtimeAnchorBlockID !== this.blockId ||+ runtimeAnchorRenderGeneration !== this.readingAnchorRenderGeneration ||+ runtimeAnchorQueryKey !== this.renderedQueryKey || runtimeAnchorQueryKey !== this.listQueryKey) {+ return;+ }+ runtimeAnchors.forEach(({anchor, isMention, scrollEpoch}) => {+ if (scrollEpoch === this.getReadingAnchorScrollEpoch(isMention)) {+ this.restoreReadingAnchor(anchor);+ }+ });+ });+ }+ const bottomVisibility = this.type === "bottom" ?+ getBottomBacklinkVisibility(data.linkRefsCount, data.mentionsCount, data.k, data.mk) : undefined;+ if (bottomVisibility) {+ this.element.classList.toggle("sy__backlink--backlinks-empty", bottomVisibility.hideBacklinks);+ this.element.classList.toggle("sy__backlink--mentions-empty", bottomVisibility.hideMentions);+ }+ this.updateBottomBacklinkSpacing();++ const countElement = this.element.querySelector(".listCount");+ if (data.linkRefsCount === 0 && this.type !== "bottom") {+ countElement.classList.add("fn__none");+ } else {+ countElement.classList.remove("fn__none");+ countElement.textContent = data.linkRefsCount.toString();+ }+ const mCountElement = this.element.querySelector(".listMCount");+ if (data.mentionsCount === 0 && this.type !== "bottom") {+ mCountElement.classList.add("fn__none");+ } else {+ mCountElement.classList.remove("fn__none");+ mCountElement.textContent = data.mentionsCount.toString();+ }+ if (!this.status[this.blockId]) {+ const backlinkState = getInitialBacklinkSectionState(+ window.siyuan.config.editor.backlinkExpandCount,+ data.backlinks.map(item => item.id),+ );+ const backmentionState = getInitialBacklinkSectionState(+ window.siyuan.config.editor.backmentionExpandCount,+ data.backmentions.map(item => item.id),+ );+ const backlinkFolded = backlinkState.folded ||+ (this.type !== "bottom" && data.linkRefsCount === 0 && data.mentionsCount > 0);+ const backmentionFolded = backmentionState.folded ||+ (this.type !== "bottom" && data.mentionsCount === 0);+ this.status[this.blockId] = {+ sort: window.siyuan.config.editor.backlinkSort,+ mSort: window.siyuan.config.editor.backmentionSort,+ scrollTop: 0,+ mScrollTop: 0,+ backlinkOpenIds: backlinkState.openIds,+ backlinkMOpenIds: backmentionState.openIds,+ backlinkMStatus: backlinkFolded ? 0 : (backmentionFolded ? 3 : 1),+ backlinkFolded,+ backmentionFolded+ };+ }++ const persistedBacklinkFolded = this.viewState?.get<boolean>(this.getSectionStateField(false));+ const persistedBackmentionFolded = this.viewState?.get<boolean>(this.getSectionStateField(true));+ if (typeof persistedBacklinkFolded === "boolean") {+ this.status[this.blockId].backlinkFolded = persistedBacklinkFolded;+ }+ if (typeof persistedBackmentionFolded === "boolean") {+ this.status[this.blockId].backmentionFolded = persistedBackmentionFolded;+ }++ const applyDocumentState = (items: IBlockTree[], isMention: boolean, openIDs: string[]) => {+ items.forEach(item => {+ const expanded = this.viewState?.get<boolean>(this.getDocumentStateField(isMention, item.id));+ if (typeof expanded !== "boolean") {+ return;+ }+ const index = openIDs.indexOf(item.id);+ if (expanded && index === -1) {+ openIDs.push(item.id);+ } else if (!expanded && index > -1) {+ openIDs.splice(index, 1);+ }+ });+ };+ applyDocumentState(data.backlinks, false, this.status[this.blockId].backlinkOpenIds);+ applyDocumentState(data.backmentions, true, this.status[this.blockId].backlinkMOpenIds);++ // restore status+ this.status[this.blockId].backlinkOpenIds.forEach(item => {+ const liElement = this.tree.element.querySelector(`.b3-list-item[data-node-id="${item}"]`) as HTMLElement;+ if (liElement && !liElement.querySelector(".b3-list-item__arrow--open")) {+ this.toggleItem(liElement, false, 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 && !liElement.querySelector(".b3-list-item__arrow--open")) {+ this.toggleItem(liElement, true, false);+ }+ });+ if (this.type === "bottom") {+ this.restoreBottomLayout(this.tree.element.previousElementSibling.querySelector('[data-type="bLayout"]'), this.tree.element,+ this.status[this.blockId].backlinkFolded);+ this.restoreBottomLayout(this.mTree.element.previousElementSibling.querySelector('[data-type="layout"]'), this.mTree.element,+ this.status[this.blockId].backmentionFolded);+ } else {+ this.applyDockLayout(+ this.status[this.blockId].backlinkFolded,+ this.status[this.blockId].backmentionFolded,+ this.status[this.blockId].backlinkMStatus,+ );+ }+ this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').setAttribute("data-sort", this.status[this.blockId].sort.toString());+ this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').setAttribute("data-sort", this.status[this.blockId].mSort.toString());+ if (bottomVisibility) {+ const empty = bottomVisibility.hidePanel;+ if (this.empty !== empty || wasLoading) {+ this.empty = empty;+ this.emptyChange?.(empty);+ }+ }++ if (init) {+ const generation = this.viewStateGeneration;+ const service = this.viewState;+ const blockID = this.blockId;+ const queryKey = this.renderedQueryKey;+ const panes = this.type === "bottom" ? [false] : [false, true];+ const scrollEpochs = panes.map(isMention => this.getReadingAnchorScrollEpoch(isMention));+ setTimeout(() => {+ if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||+ blockID !== this.blockId || queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey) {+ return;+ }+ panes.forEach((isMention, index) => {+ if (scrollEpochs[index] !== this.getReadingAnchorScrollEpoch(isMention)) {+ return;+ }+ const anchor = this.viewState?.get<IBacklinkReadingAnchor>(this.getReadingAnchorField(isMention));+ const targetIsMention = this.type === "bottom" && anchor ?+ anchor.pane === "backmention" : isMention;+ if (!this.isReadingAnchorPaneVisible(targetIsMention)) {+ return;+ }+ if (!anchor && this.type !== "bottom") {+ (isMention ? this.mTree : this.tree).element.scrollTop = isMention ?+ this.status[this.blockId].mScrollTop : this.status[this.blockId].scrollTop;+ }+ this.restorePersistedReadingAnchor(isMention);+ });+ }, Constants.TIMEOUT_LOAD);+ }+ }++ private applyDockLayout(backlinkFolded: boolean, backmentionFolded: boolean, backlinkMStatus: number) {+ const layoutElement = this.mTree.element.previousElementSibling.querySelector('[data-type="layout"]');+ this.mTree.element.classList.remove("fn__none");+ if (!backlinkFolded && !backmentionFolded) {+ this.tree.element.classList.remove("fn__none");+ this.mTree.element.removeAttribute("style");+ const splitUp = backlinkMStatus === 2;+ layoutElement.setAttribute("aria-label", splitUp ? window.siyuan.languages.up : window.siyuan.languages.down);+ layoutElement.querySelector("use").setAttribute("xlink:href", splitUp ? "#iconUp" : "#iconDown");+ } else if (backlinkFolded) {+ this.tree.element.classList.add("fn__none");+ const height = backmentionFolded ? 0 :+ Math.max(this.element.clientHeight - this.tree.element.previousElementSibling.clientHeight * 2, 0);+ this.mTree.element.setAttribute("style", `flex:none;height:${height}px`);+ layoutElement.setAttribute("aria-label", window.siyuan.languages.down);+ layoutElement.querySelector("use").setAttribute("xlink:href", "#iconDown");+ } else {+ this.tree.element.classList.remove("fn__none");+ this.mTree.element.setAttribute("style", "flex:none;height:0px");+ layoutElement.setAttribute("aria-label", window.siyuan.languages.up);+ layoutElement.querySelector("use").setAttribute("xlink:href", "#iconUp");+ }+ }++ private restoreBottomLayout(element: HTMLElement, listElement: HTMLElement, folded: boolean) {+ cancelHeightAnimation(listElement);+ delete listElement.dataset.heightFolding;+ listElement.classList.toggle("fn__none", folded);+ element.setAttribute("aria-label", folded ? window.siyuan.languages.expand : window.siyuan.languages.collapse);+ element.querySelector("use").setAttribute("xlink:href", folded ? "#iconRight" : "#iconDown");+ }++ public markDirty() {+ this.indexChangeVersion++;+ this.dirty = true;+ this.pendingFull = true;+ this.itemRecords.forEach(records => records.forEach(record => {+ record.contextDirty = true;+ }));+ }++ public markIndexDirty(change: IBacklinkIndexChange) {+ if (!change?.backlinkChanged) {+ return;+ }+ 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.destroyed || !this.blockId || !this.dirty || this.element.contains(document.activeElement)) {+ return;+ }+ 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(+ this.element.contains(document.activeElement),+ ignoreFocus+ )) {+ return;+ }+ if (this.empty) {+ this.searchBacklinks();+ return;+ }+ if (this.element.classList.contains("fn__none") ||+ this.element.getClientRects().length === 0) {+ return;+ }+ const rect = this.element.getBoundingClientRect();+ const ownerRect = this.ownerProtyle.contentElement.getBoundingClientRect();+ if (rect.top > ownerRect.bottom + 640 || rect.bottom < ownerRect.top - 640) {+ return;+ }+ this.searchBacklinks();+ }++ public refreshDirty() {+ if (this.dirty) {+ this.refreshIfVisible();+ }+ }++ public destroy() {+ if (this.destroyed) {+ return;+ }+ if (this.blockId && !this.showingLoading) {+ this.saveStatus();+ }+ this.destroyed = true;+ this.viewStateGeneration++;+ this.clearReadingAnchorTimers();+ cancelHeightAnimation(this.tree.element);+ cancelHeightAnimation(this.mTree.element);+ delete this.tree.element.dataset.heightFolding;+ delete this.mTree.element.dataset.heightFolding;+ if (this.ownerFocusoutListener) {+ this.ownerProtyle.element.removeEventListener("focusout", this.ownerFocusoutListener);+ }+ if (this.ownerScrollListener) {+ this.ownerProtyle.contentElement.removeEventListener("scroll", this.ownerScrollListener);+ }+ if (this.panelFocusoutListener) {+ this.element.removeEventListener("focusout", this.panelFocusoutListener);+ }+ this.visibilityObserver?.disconnect();+ this.editors.forEach(item => {+ unregisterViewFoldContext(item.protyle);+ item.destroy();+ });+ this.editors = [];+ void this.viewState?.destroy().catch(error => console.error(error));+ if (this.ws) {+ this.ws.onclose = null;+ this.ws.close();+ }+ }+}diff --git a/app/src/layout/getAll.ts b/app/src/layout/getAll.tsindex 9013ac011a..e41a420c79 100644--- a/app/src/layout/getAll.ts+++ b/app/src/layout/getAll.ts@@ -1,4 +1,7 @@import type {Protyle} from "../protyle";+/// #if MOBILE+import {getMobileSecondaryEditors} from "../mobile/util/secondaryEditors";+/// #endif/// #if !MOBILEimport {Layout} from "./index";import {Tab} from "./Tab";@@ -24,6 +27,7 @@ export const getAllEditor = () => {if (window.siyuan.mobile.popEditor) {editors.push(window.siyuan.mobile.popEditor);}+ editors.push(...getMobileSecondaryEditors());/// #elseconst models = getAllModels();models.editor.forEach(item => {diff --git a/app/src/mobile/dock/MobileBacklinks.ts b/app/src/mobile/dock/MobileBacklinks.tsindex 93f51c6beb..235f236bea 100644--- a/app/src/mobile/dock/MobileBacklinks.ts+++ b/app/src/mobile/dock/MobileBacklinks.ts@@ -1,173 +1,50 @@-import {Tree} from "../../util/Tree";-import {fetchPost} from "../../util/fetch";-import {Constants} from "../../constants";-import {openMobileFileById} from "../editor";import type {App} from "../../index";-import {isEncryptedBox} from "../../util/pathName";+import {BacklinkContent} from "../../layout/dock/BacklinkContent";+import {registerMobileBacklinkPanel} from "../util/backlinkPanels";+import {flushMobileSecondaryEditor} from "../util/secondaryEditors";-export class MobileBacklinks {- public element: HTMLElement;- private tree: Tree;- private notebookId: string;- private mTree: Tree;- private updateId = 0;- public beforeLen = 10;+export class MobileBacklinks extends BacklinkContent {+ private unregisterPanel: () => void;+ private updateVersion = 0;constructor(app: App, element: HTMLElement) {- this.element = element;- this.element.innerHTML = `<div class="toolbar toolbar--border toolbar--dark">- <div class="fn__space"></div>- <div class="toolbar__text">- ${window.siyuan.languages.backlinks}- </div>- <span class="counter listCount"></span>- <span class="fn__space"></span>- <svg data-type="expand" class="toolbar__icon"><use xlink:href="#iconExpand"></use></svg>- <span class="fn__space"></span>- <svg data-type="collapse" class="toolbar__icon"><use xlink:href="#iconContract"></use></svg>-</div>-<div class="backlinkList fn__flex-1"></div>-<div class="toolbar">- <div class="fn__space"></div>- <div class="toolbar__text">- ${window.siyuan.languages.mentions}- </div>- <span class="counter listMCount"></span>- <span class="fn__space"></span>- <svg data-type="mExpand" class="toolbar__icon"><use xlink:href="#iconExpand"></use></svg>- <span class="fn__space"></span>- <svg data-type="mCollapse" class="toolbar__icon"><use xlink:href="#iconContract"></use></svg>- <span class="fn__space"></span>- <svg data-type="layout" class="toolbar__icon"><use xlink:href="#iconDown"></use></svg>-</div>-<div class="backlinkMList fn__flex-1"></div>`;-- this.tree = new Tree({- element: this.element.querySelector(".backlinkList") as HTMLElement,- data: null,- click(element: HTMLElement) {- openMobileFileById(app, element.getAttribute("data-node-id"), [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT]);- }- });- this.mTree = new Tree({- element: this.element.querySelector(".backlinkMList") as HTMLElement,- data: null,- click: (element) => {- openMobileFileById(app, element.getAttribute("data-node-id"), [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT]);- },+ const protyle = window.siyuan.mobile.editor?.protyle;+ super({+ app,+ element,+ type: "local",+ surface: "mobile-dock",+ blockId: protyle?.block.id || "",+ rootId: protyle?.block.rootID,+ notebookId: protyle?.notebookId,});- this.element.addEventListener("click", (event) => {- let target = event.target as HTMLElement;- while (target && !target.isEqualNode(this.element)) {- if (target.classList.contains("toolbar__icon")) {- const type = target.getAttribute("data-type");- switch (type) {- case "collapse":- this.tree.collapseAll();- break;- case "expand":- this.tree.expandAll();- break;- case "mExpand":- this.mTree.expandAll();- break;- case "mCollapse":- this.mTree.collapseAll();- break;- case "layout":- if (this.mTree.element.style.flex) {- if (this.mTree.element.style.height === "0px") {- this.mTree.element.removeAttribute("style");- target.setAttribute("aria-label", window.siyuan.languages.up);- target.querySelector("use").setAttribute("xlink:href", "#iconUp");- } else {- this.mTree.element.removeAttribute("style");- target.setAttribute("aria-label", window.siyuan.languages.down);- target.querySelector("use").setAttribute("xlink:href", "#iconDown");- }- } else {- if (target.getAttribute("aria-label") === window.siyuan.languages.down) {- this.mTree.element.setAttribute("style", "flex:none;height:0px");- target.setAttribute("aria-label", window.siyuan.languages.up);- target.querySelector("use").setAttribute("xlink:href", "#iconUp");- } else {- this.mTree.element.setAttribute("style", `flex:none;height:${this.element.clientHeight - this.tree.element.previousElementSibling.clientHeight * 2}px`);- target.setAttribute("aria-label", window.siyuan.languages.down);- target.querySelector("use").setAttribute("xlink:href", "#iconDown");- }- }- target.setAttribute("data-clicked", "true");- break;- }- }- target = target.parentElement;- }- });-- this.update();+ this.unregisterPanel = registerMobileBacklinkPanel(this);}public update() {- const editor = window.siyuan.mobile.editor?.protyle;- const updateId = ++this.updateId;- if (!editor) {- this.tree.updateData([]);- this.mTree.updateData([]);- this.element.querySelectorAll(".listCount, .listMCount").forEach(item => item.classList.add("fn__none"));- return;- }- const blockId = editor.block.id;- const param: IObject = {- id: blockId,- beforeLen: this.beforeLen,- k: "",- mk: "",- };- if (isEncryptedBox(editor.notebookId)) {- param.notebook = editor.notebookId;+ const version = ++this.updateVersion;+ const protyle = window.siyuan.mobile.editor?.protyle;+ const blockId = protyle?.block.id || "";+ if (this.blockId !== blockId || this.notebookId !== (protyle?.notebookId || "")) {+ void Promise.all(this.editors.map(flushMobileSecondaryEditor)).then(() => {+ if (version === this.updateVersion) {+ this.switchBlock(blockId, protyle?.block.rootID || "", protyle?.notebookId || "");+ }+ }).catch(error => console.error(error));+ } else {+ this.markIndexDirty({backlinkChanged: true, backlinkFull: true});+ this.refreshAfterIndex();}- fetchPost("/api/ref/getBacklink", param, response => {- if (updateId !== this.updateId || window.siyuan.mobile.editor?.protyle.block.id !== blockId) {- return;- }- this.notebookId = response.data.box;- this.tree.updateData(response.data.backlinks);- this.mTree.updateData(response.data.backmentions);+ }- const countElement = this.element.querySelector(".listCount");- if (response.data.linkRefsCount === 0) {- countElement.classList.add("fn__none");- } else {- countElement.classList.remove("fn__none");- countElement.textContent = response.data.linkRefsCount.toString();- }- const mCountElement = this.element.querySelector(".listMCount");- if (response.data.mentionsCount === 0) {- mCountElement.classList.add("fn__none");- } else {- mCountElement.classList.remove("fn__none");- mCountElement.textContent = response.data.mentionsCount.toString();- }+ public destroy() {+ this.updateVersion++;+ this.unregisterPanel?.();+ super.destroy();+ }- const layoutElement = this.element.querySelector("[data-type='layout']");- if (layoutElement.getAttribute("data-clicked")) {- return;- }- if (response.data.mentionsCount === 0) {- this.mTree.element.setAttribute("style", "flex:none;height:0px");- layoutElement.setAttribute("aria-label", window.siyuan.languages.up);- layoutElement.querySelector("use").setAttribute("xlink:href", "#iconUp");- return;- }- if (response.data.linkRefsCount === 0) {- this.mTree.element.setAttribute("style", `flex:none;height:${this.element.clientHeight - this.tree.element.previousElementSibling.clientHeight * 2}px`);- layoutElement.setAttribute("aria-label", window.siyuan.languages.down);- layoutElement.querySelector("use").setAttribute("xlink:href", "#iconDown");- } else {- this.mTree.element.removeAttribute("style");- layoutElement.setAttribute("aria-label", window.siyuan.languages.down);- layoutElement.querySelector("use").setAttribute("xlink:href", "#iconDown");- }- });+ public switchBlock(blockId: string, rootId: string, notebookId: string) {+ this.updateVersion++;+ super.switchBlock(blockId, rootId, notebookId);}}diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.tsindex 3938908b53..e36fff1c69 100644--- a/app/src/mobile/editor.ts+++ b/app/src/mobile/editor.ts@@ -20,9 +20,11 @@ import {forEachPluginSubscriber} from "../plugin/EventBusCore";import {restoreMobileTopBarLayout, updateMobileTopBarLayout} from "./util/mobileTopBar";import {stickyRow} from "../protyle/render/av/row";import {invalidateTrackedRanges} from "../protyle/util/trackedRange";+import {getActiveMobileSecondaryEditor} from "./util/secondaryEditors";+import {closeMobileBacklinkSheets} from "./util/backlinkPanels";export const getCurrentEditor = () => {- return window.siyuan.mobile.popEditor || window.siyuan.mobile.editor;+ return getActiveMobileSecondaryEditor() || window.siyuan.mobile.popEditor || window.siyuan.mobile.editor;};// 串行更新时间,避免快速切换文档时较早的关闭请求覆盖较新的打开状态。@@ -305,6 +307,12 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[export const openMobileFileById = (app: App, id: string, action: TProtyleAction[] = [Constants.CB_GET_HL],scrollPosition?: ScrollLogicalPosition, notebookId?: string,afterOpen?: (protyle: IProtyle) => void, forceReload = false) => {+ const closing = closeMobileBacklinkSheets();+ if (closing) {+ void closing.then(() => openMobileFileById(app, id, action, scrollPosition, notebookId, afterOpen, forceReload))+ .catch(error => console.error(error));+ return;+ }if (window.siyuan.mobile.tabs) {const options = {action, scrollPosition, notebookId, afterOpen, forceReload};if (action.includes(Constants.CB_GET_OPENNEW)) {@@ -331,6 +339,12 @@ export const openMobileFileByIdInNewTab = (app: App, id: string,action: TProtyleAction[] = [Constants.CB_GET_HL],scrollPosition?: ScrollLogicalPosition, notebookId?: string,afterOpen?: (protyle: IProtyle) => void) => {+ const closing = closeMobileBacklinkSheets();+ if (closing) {+ void closing.then(() => openMobileFileByIdInNewTab(app, id, action, scrollPosition, notebookId, afterOpen))+ .catch(error => console.error(error));+ return;+ }if (window.siyuan.mobile.tabs) {void window.siyuan.mobile.tabs.openInNewTab(id, {action,diff --git a/app/src/mobile/util/backlinkPanels.ts b/app/src/mobile/util/backlinkPanels.tsnew file mode 100644index 0000000000..ece64f0fc4--- /dev/null+++ b/app/src/mobile/util/backlinkPanels.ts@@ -0,0 +1,35 @@+import type {BacklinkContent} from "../../layout/dock/BacklinkContent";++const panels = new Set<BacklinkContent>();+const sheets = new Map<BacklinkContent, () => Promise<void>>();++export const registerMobileBacklinkPanel = (panel: BacklinkContent, close?: () => Promise<void>) => {+ panels.add(panel);+ if (close) {+ sheets.set(panel, close);+ }+ return () => {+ sheets.delete(panel);+ panels.delete(panel);+ };+};++export const getMobileBacklinkPanels = () => Array.from(panels);++export const closeMobileBacklinkSheets = () => {+ if (sheets.size) {+ return Promise.all(Array.from(sheets.values(), close => close())).then(() => undefined);+ }+};++export const removeMobileBacklinkContent = (options: {notebookId?: string, rootIDs?: string[]}) => {+ panels.forEach(panel => {+ if ((options.notebookId && panel.notebookId === options.notebookId) ||+ options.rootIDs?.includes(panel.rootId) || Array.from(panel.element.querySelectorAll("[data-notebook-id]"))+ .some(element => element.getAttribute("data-notebook-id") === options.notebookId) || panel.editors.some(editor =>+ (options.notebookId && editor.protyle.notebookId === options.notebookId) ||+ options.rootIDs?.includes(editor.protyle.block.rootID))) {+ panel.switchBlock("", "", "");+ }+ });+};diff --git a/app/src/mobile/util/closePanel.ts b/app/src/mobile/util/closePanel.tsindex 4a46efb65e..c56427f204 100644--- a/app/src/mobile/util/closePanel.ts+++ b/app/src/mobile/util/closePanel.ts@@ -1,6 +1,7 @@import {activeBlur} from "./keyboardToolbar";import {Constants} from "../../constants";import {destroyModel} from "../menu/model";+import {clearActiveMobileSecondaryEditor, getActiveMobileSecondaryEditor} from "./secondaryEditors";let hidePanelMaskTimer = 0;@@ -15,6 +16,11 @@ export const showPanelMask = () => {};export const closePanel = (options: {preserveKeyboard?: boolean} = {}) => {+ const secondaryEditor = getActiveMobileSecondaryEditor();+ if (secondaryEditor?.protyle.element.closest("#sidebar, #sidebarRight")) {+ activeBlur(true);+ }+ clearActiveMobileSecondaryEditor();destroyModel();const menuElement = document.getElementById("menu");if (menuElement) {diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.tsindex 27c69a6f7b..b39718967e 100644--- a/app/src/mobile/util/onMessage.ts+++ b/app/src/mobile/util/onMessage.ts@@ -1,6 +1,7 @@import {openMobileFileById} from "../editor";import {forceQuit,+ processBacklinkIndexCommit,processSync,progressLoading,setDefRefCount,@@ -25,6 +26,7 @@ import {isInMobileApp} from "../../protyle/util/compatibility";import {handleMobileKernelExit} from "./kernelExit";import {sanitizeKernelHTML} from "../../util/hostCapabilities";import {applyEntryVisibility} from "../../config/entryVisibility/runtime";+import {removeMobileBacklinkContent} from "./backlinkPanels";let statusTimeout: number;const statusElement = document.querySelector("#status") as HTMLElement;@@ -36,6 +38,9 @@ const dispatchMobileSidePanelConfigChange = () => {export const onMessage = (app: App, data: IWebSocketData) => {if (data) {switch (data.cmd) {+ case "databaseIndexCommit":+ processBacklinkIndexCommit(data.data);+ break;case "setEntryVisibility":applyEntryVisibility(data.data);break;@@ -105,6 +110,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {break;case "closeBox":case "removeBox": {+ removeMobileBacklinkContent({notebookId: data.data.box});window.siyuan.mobile.tabs?.removeNotebook(data.data.box);break;}@@ -112,6 +118,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {void activateOnboarding(app, data.data);break;case "removeDoc":+ removeMobileBacklinkContent({rootIDs: data.data.ids});window.siyuan.mobile.tabs?.removeRoots(data.data.ids);if (window.siyuan.config.onboarding?.newUser && !window.siyuan.config.onboarding.dismissed &&data.data.ids.includes(window.siyuan.config.onboarding.documentID)) {diff --git a/app/src/mobile/util/openBacklinks.ts b/app/src/mobile/util/openBacklinks.tsindex dd895b218e..91c6ca472a 100644--- a/app/src/mobile/util/openBacklinks.ts+++ b/app/src/mobile/util/openBacklinks.ts@@ -1,39 +1,105 @@-import {Constants} from "../../constants";-import {fetchPost} from "../../util/fetch";-import {isEncryptedBox} from "../../util/pathName";-import {Tree} from "../../util/Tree";-import {openMobileFileById} from "../editor";+import {Dialog} from "../../dialog";+import {BacklinkContent} from "../../layout/dock/BacklinkContent";import {activeBlur} from "./keyboardToolbar";+import {registerMobileBacklinkPanel} from "./backlinkPanels";+import {clearActiveMobileSecondaryEditor, flushMobileSecondaryEditor} from "./secondaryEditors";+import {showMessage} from "../../dialog/message";+import {escapeHtml} from "../../util/escape";-export const openMobileBacklinks = (protyle: IProtyle, blockId: string) => {- activeBlur();- const menu = window.siyuan.menus.menu;- menu.remove();- const element = document.createElement("div");- const titleElement = document.createElement("div");- titleElement.className = "b3-menu__item b3-menu__item--readonly";- titleElement.textContent = window.siyuan.languages.backlinks;- const listElement = document.createElement("div");- element.append(titleElement, listElement);- menu.append(element);- menu.fullscreen("bottom");- const param: IObject = {id: blockId, beforeLen: 10, k: "", mk: "", includeMentions: false};- if (isEncryptedBox(protyle.notebookId)) {- param.notebook = protyle.notebookId;- }- fetchPost("/api/ref/getBacklink", param, response => {- if (!element.isConnected || menu.element.classList.contains("fn__none")) {- return;+class MobileBacklinkDialog extends Dialog {+ public beforeClose: () => Promise<void>;+ private closing?: Promise<void>;++ public close() {+ if (!this.closing) {+ this.closing = Promise.resolve().then(() => this.beforeClose?.()).then(() => {+ super.destroy();+ }).catch(error => {+ this.closing = undefined;+ showMessage(escapeHtml(String(error)));+ throw error;+ });}- const tree = new Tree({- element: listElement,- data: response.data.backlinks,- click(target) {- menu.remove();- openMobileFileById(protyle.app, target.getAttribute("data-node-id"),- [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL]);+ return this.closing;+ }++ public destroy() {+ void this.close().catch(error => console.error(error));+ }+}++let currentDialog: MobileBacklinkDialog;+let openVersion = 0;++export const openMobileBacklinks = async (protyle: IProtyle, blockId: string) => {+ const version = ++openVersion;+ activeBlur(true);+ window.siyuan.menus.menu.remove();+ try {+ await currentDialog?.close();+ } catch (error) {+ console.error(error);+ return;+ }+ if (version !== openVersion || !protyle.element.isConnected) {+ return;+ }+ const dialog = new MobileBacklinkDialog({+ content: '<div class="mobile-backlinks-content fn__flex-column"></div>',+ width: "100vw",+ height: "60vh",+ containerClassName: "mobile-backlinks-sheet",+ destroyCallback: () => {+ unregisterPanel?.();+ panel?.destroy();+ if (currentDialog === dialog) {+ currentDialog = undefined;+ clearActiveMobileSecondaryEditor();}- });- tree.expandAll();+ window.visualViewport?.removeEventListener("resize", resize);+ window.visualViewport?.removeEventListener("scroll", resize);+ }+ });+ currentDialog = dialog;+ dialog.element.classList.add("mobile-backlinks-dialog");+ const resize = () => {+ const viewport = window.visualViewport;+ const container = dialog.element.querySelector<HTMLElement>(".b3-dialog");+ if (viewport) {+ container.style.top = `${viewport.offsetTop}px`;+ container.style.height = `${viewport.height}px`;+ }+ };+ window.visualViewport?.addEventListener("resize", resize);+ window.visualViewport?.addEventListener("scroll", resize);+ resize();+ const panel = new BacklinkContent({+ app: protyle.app,+ element: dialog.element.querySelector(".mobile-backlinks-content"),+ blockId,+ rootId: protyle.block.rootID,+ notebookId: protyle.notebookId,+ type: "local",+ surface: "mobile-sheet",+ onlyBacklinks: true,});+ dialog.beforeClose = async () => {+ if (dialog.element.contains(document.activeElement)) {+ activeBlur(true);+ }+ dialog.element.setAttribute("inert", "");+ // 在移除编辑器及其 WebSocket 之前,将防抖输入提交到事务队列。+ try {+ await Promise.all(panel.editors.map(flushMobileSecondaryEditor));+ } catch (error) {+ dialog.element.removeAttribute("inert");+ throw error;+ }+ unregisterPanel?.();+ panel.destroy();+ if (currentDialog === dialog) {+ clearActiveMobileSecondaryEditor();+ }+ };+ const unregisterPanel = registerMobileBacklinkPanel(panel, () => dialog.close());};diff --git a/app/src/mobile/util/secondaryEditors.ts b/app/src/mobile/util/secondaryEditors.tsnew file mode 100644index 0000000000..da1e822492--- /dev/null+++ b/app/src/mobile/util/secondaryEditors.ts@@ -0,0 +1,86 @@+import type {Protyle} from "../../protyle";+import {waitForPendingTransactions} from "../../protyle/util/transactionQueue";++const editors = new Map<Protyle, {dispose: () => void, remove: () => void, flushing?: Promise<void>}>();+let activeEditor: Protyle;+let listening = false;++export const getMobileSecondaryEditors = () => Array.from(editors.keys());++export const getActiveMobileSecondaryEditor = () => {+ if (activeEditor && (!editors.has(activeEditor) || !activeEditor.protyle.element.isConnected ||+ activeEditor.protyle.element.closest("[inert]") ||+ activeEditor.protyle.element.getClientRects().length === 0)) {+ activeEditor = undefined;+ }+ return activeEditor;+};++export const clearActiveMobileSecondaryEditor = () => {+ activeEditor = undefined;+};++export const flushMobileSecondaryEditor = (editor: Protyle) => {+ const record = editors.get(editor);+ const flushing = Promise.all([record?.flushing, editor.protyle.wysiwyg.flushPendingInput()])+ .then(() => waitForPendingTransactions(editor.protyle));+ if (record) {+ record.flushing = flushing;+ void flushing.then(() => {+ if (record.flushing === flushing) {+ record.flushing = undefined;+ }+ }, () => undefined);+ }+ return flushing;+};++export const unregisterMobileSecondaryEditor = (editor: Protyle) => {+ editors.get(editor)?.dispose();+ editors.delete(editor);+ if (activeEditor === editor) {+ activeEditor = undefined;+ }+};++export const removeMobileSecondaryEditor = (editor: Protyle) => {+ const record = editors.get(editor);+ if (!record) {+ return false;+ }+ record.remove();+ return true;+};++export const registerMobileSecondaryEditor = (editor: Protyle, remove: () => void) => {+ if (!listening) {+ listening = true;+ const followFocus = (event: Event) => {+ const target = event.target as HTMLElement;+ const protyleElement = target.closest(".protyle");+ if (target.id === "toolbarName" ||+ protyleElement && !Array.from(editors.keys()).some(item => item.protyle.element === protyleElement)) {+ activeEditor = undefined;+ }+ };+ document.addEventListener("pointerdown", followFocus, true);+ document.addEventListener("focusin", followFocus, true);+ }+ unregisterMobileSecondaryEditor(editor);+ const activate = () => { activeEditor = editor; };+ const flush = () => {+ void flushMobileSecondaryEditor(editor).catch(error => console.error(error));+ };+ const element = editor.protyle.element;+ element.addEventListener("pointerdown", activate, true);+ element.addEventListener("focusin", activate, true);+ element.addEventListener("focusout", flush, true);+ editors.set(editor, {+ remove,+ dispose: () => {+ element.removeEventListener("pointerdown", activate, true);+ element.removeEventListener("focusin", activate, true);+ element.removeEventListener("focusout", flush, true);+ }+ });+};diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex 920a0c274e..6010e058da 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -36,6 +36,9 @@ import {disabledProtyle, enableProtyle, onGet, setReadonlyByConfig} from "./utilimport {reloadProtyle} from "./util/reload";import {renderBacklink} from "./wysiwyg/renderBacklink";import {setEmpty} from "../mobile/util/setEmpty";+/// #if MOBILE+import {removeMobileSecondaryEditor, unregisterMobileSecondaryEditor} from "../mobile/util/secondaryEditors";+/// #endifimport {resize} from "./util/resize";import {getDocByScroll} from "./scroll/saveScroll";import type {App} from "../index";@@ -388,7 +391,9 @@ export class Protyle {case "removeBox":if (this.protyle.notebookId === data.data.box) {/// #if MOBILE- setEmpty(app);+ if (!removeMobileSecondaryEditor(this)) {+ setEmpty(app);+ }/// #elseif (this.protyle.model) {this.protyle.model.parent.parent.removeTab(this.protyle.model.parent.id);@@ -399,7 +404,9 @@ export class Protyle {case "removeDoc":if (data.data.ids.includes(this.protyle.block.rootID)) {/// #if MOBILE- setEmpty(app);+ if (!removeMobileSecondaryEditor(this)) {+ setEmpty(app);+ }/// #elseif (this.protyle.model) {this.protyle.model.parent.parent.removeTab(this.protyle.model.parent.id);@@ -641,6 +648,9 @@ export class Protyle {/** 销毁编辑器 */public destroy() {+ /// #if MOBILE+ unregisterMobileSecondaryEditor(this);+ /// #endifdestroy(this.protyle);}diff --git a/app/src/protyle/util/setEditMode.ts b/app/src/protyle/util/setEditMode.tsindex dd138ea6d6..22f691e55c 100644--- a/app/src/protyle/util/setEditMode.ts+++ b/app/src/protyle/util/setEditMode.ts@@ -7,6 +7,9 @@ import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";/// #if MOBILEexport const updateMobileTitleReadonly = (protyle: IProtyle) => {+ if (window.siyuan.mobile.editor?.protyle !== protyle) {+ return;+ }const inputElement = document.getElementById("toolbarName") as HTMLInputElement;const readonlyElement = document.getElementById("toolbarNameReadonly");if (!inputElement || !readonlyElement) {diff --git a/app/src/util/reloadSync.ts b/app/src/util/reloadSync.tsindex 6ee324faab..4461354bb7 100644--- a/app/src/util/reloadSync.ts+++ b/app/src/util/reloadSync.ts@@ -9,6 +9,9 @@ import {getAllModels} from "../layout/getAll";import {setStorageVal} from "../protyle/util/compatibility";import type {Tab} from "../layout/Tab";import {setTitle} from "./processTitle";+/// #if MOBILE+import {getMobileBacklinkPanels, removeMobileBacklinkContent} from "../mobile/util/backlinkPanels";+/// #endif/// #if !MOBILEimport {removeBlockPanelEditors} from "../block/panelRemoval";/// #endif@@ -26,6 +29,11 @@ export const reloadSync = (hideMessage();}/// #if MOBILE+ removeMobileBacklinkContent({rootIDs: data.removeRootIDs});+ getMobileBacklinkPanels().forEach(panel => {+ panel.markIndexDirty({backlinkChanged: true, backlinkFull: true});+ panel.refreshAfterIndex();+ });if (window.siyuan.mobile.popEditor && window.siyuan.mobile.popEditor.protyle) {if (data.removeRootIDs.includes(window.siyuan.mobile.popEditor.protyle.block.rootID)) {hideElements(["dialog"]);diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 0b0a406af9..7248443ab3 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -198,6 +198,10 @@ func getBacklink2(c *gin.Context) {knownRevision, _ := arg["knownRevision"].(string)keyword := arg["k"].(string)mentionKeyword := arg["mk"].(string)+ includeMentions := true+ if val, ok := arg["includeMentions"].(bool); ok {+ includeMentions = val+ }sortArg := arg["sort"]sort := util.SortModeUpdatedDESCif nil != sortArg {@@ -225,9 +229,9 @@ func getBacklink2(c *gin.Context) {return}if notebook != "" && model.IsEncryptedBox(notebook) {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter)+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter, includeMentions)} else {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2WithFilter(id, keyword, mentionKeyword, sort, mentionSort, containChildren, sourceFilter)+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, "", sourceFilter, includeMentions)}}if model.IsReadOnlyRoleContext(c) {@@ -302,69 +306,3 @@ func parseBacklinkSourceFilter(arg map[string]any) *model.BacklinkSourceFilter {}return model.NormalizeBacklinkSourceFilter(filter)}--func getBacklink(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- if nil == arg["id"] {- return- }-- id := arg["id"].(string)- keyword := arg["k"].(string)- mentionKeyword := arg["mk"].(string)- includeMentions := true- if val, ok := arg["includeMentions"].(bool); ok {- includeMentions = val- }- beforeLen := 12- if nil != arg["beforeLen"] {- beforeLen = int(arg["beforeLen"].(float64))- }- containChildren := model.Conf.Editor.BacklinkContainChildren- if val, ok := arg["containChildren"]; ok {- containChildren = val.(bool)- }- var boxID string- var backlinks, backmentions []*model.Path- var linkRefsCount, mentionsCount int- // 加密笔记本的反链面板走 InBox 版(查加密 content db)- notebook, _ := arg["notebook"].(string)- if !isEncryptedNotebookDeniedForPublish(c, notebook) {- if err := holdEncryptedBoxRequest(c, notebook); err != nil {- ret.Code = 1- ret.Msg = err.Error()- return- }- if notebook != "" && model.IsEncryptedBox(notebook) {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklinkInBoxWithOptions(id, keyword, mentionKeyword, beforeLen, containChildren, notebook, includeMentions)- } else {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklinkInBoxWithOptions(id, keyword, mentionKeyword, beforeLen, containChildren, "", includeMentions)- }- }- if model.IsReadOnlyRoleContext(c) {- publishAccess := model.GetPublishAccess()- backlinks = model.FilterPathsByPublishAccess(c, publishAccess, backlinks)- backmentions = model.FilterPathsByPublishAccess(c, publishAccess, backmentions)- linkRefsCount = countBacklinkPaths(backlinks)- mentionsCount = countBacklinkPaths(backmentions)- }- ret.Data = map[string]any{- "backlinks": backlinks,- "linkRefsCount": linkRefsCount,- "backmentions": backmentions,- "mentionsCount": mentionsCount,- "k": keyword,- "mk": mentionKeyword,- "box": boxID,- }- if includeMentions {- util.RandomSleep(200, 500)- }-}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 7266454249..4a20c2dbda 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -326,7 +326,6 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/file/getUniqueFilename", model.CheckAuth, model.CheckAdminRole, getUniqueFilename)ginServer.Handle("POST", "/api/ref/refreshBacklink", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, refreshBacklink)- ginServer.Handle("POST", "/api/ref/getBacklink", model.CheckAuth, getBacklink)ginServer.Handle("POST", "/api/ref/getBacklink2", model.CheckAuth, getBacklink2)ginServer.Handle("POST", "/api/ref/getBacklinkDoc", model.CheckAuth, getBacklinkDoc)ginServer.Handle("POST", "/api/ref/getBackmentionDoc", model.CheckAuth, getBackmentionDoc)diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex 3375870a57..01f11724aa 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -575,6 +575,11 @@ func GetBacklink2InBox(id, keyword, mentionKeyword string, sortMode, mentionSort}func GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {+ return GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, boxID, sourceFilter, true)+}++// GetBacklink2InBoxWithOptions 查询反链文档列表,并按需搜索提及。+func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter, includeMentions bool) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {keyword = strings.TrimSpace(keyword)var keywords []stringif "" != keyword {@@ -626,11 +631,13 @@ func GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword string, sortMode, mreturn backlinks[i].ID > backlinks[j].ID})- mentionRefs, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, 12, boxID)- tmpBackmentions := toFlatTree(mentionRefs, 0, "backlink", nil)- for _, l := range tmpBackmentions {- l.Blocks = nil- backmentions = append(backmentions, l)+ if includeMentions {+ mentionRefs, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, 12, boxID)+ tmpBackmentions := toFlatTree(mentionRefs, 0, "backlink", nil)+ for _, l := range tmpBackmentions {+ l.Blocks = nil+ backmentions = append(backmentions, l)+ }}sort.Slice(backmentions, func(i, j int) bool {@@ -680,134 +687,6 @@ func GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword string, sortMode, mreturn}-func GetBacklink(id, keyword, mentionKeyword string, beforeLen int, containChildren bool) (boxID string, linkPaths, mentionPaths []*Path, linkRefsCount, mentionsCount int) {- return GetBacklinkInBox(id, keyword, mentionKeyword, beforeLen, containChildren, "")-}--// GetBacklinkInBox 与 GetBacklink 一致,但按 boxID 路由到加密 db 或全局 db。-func GetBacklinkInBox(id, keyword, mentionKeyword string, beforeLen int, containChildren bool, boxID string) (boxIDOut string, linkPaths, mentionPaths []*Path, linkRefsCount, mentionsCount int) {- return GetBacklinkInBoxWithOptions(id, keyword, mentionKeyword, beforeLen, containChildren, boxID, true)-}--// GetBacklinkInBoxWithOptions 按笔记本查询反链,并按需搜索提及。-func GetBacklinkInBoxWithOptions(id, keyword, mentionKeyword string, beforeLen int, containChildren bool, boxID string, includeMentions bool) (boxIDOut string, linkPaths, mentionPaths []*Path, linkRefsCount, mentionsCount int) {- linkPaths = []*Path{}- mentionPaths = []*Path{}-- sqlBlock := sql.GetBlockInBox(id, boxID)- if nil == sqlBlock {- return- }- rootID := sqlBlock.RootID- boxIDOut = sqlBlock.Box-- var links []*Block- refs := sql.QueryRefsByDefIDInBox(id, containChildren, boxID)- refs = removeDuplicatedRefs(refs)-- // 为了减少查询,组装好 IDs 后一次查出- defSQLBlockIDs, refSQLBlockIDs := map[string]bool{}, map[string]bool{}- var queryBlockIDs []string- for _, ref := range refs {- defSQLBlockIDs[ref.DefBlockID] = true- refSQLBlockIDs[ref.BlockID] = true- queryBlockIDs = append(queryBlockIDs, ref.DefBlockID)- queryBlockIDs = append(queryBlockIDs, ref.BlockID)- }- querySQLBlocks := sql.GetBlocksInBox(queryBlockIDs, boxID)- defSQLBlocksCache := map[string]*sql.Block{}- for _, defSQLBlock := range querySQLBlocks {- if nil != defSQLBlock && defSQLBlockIDs[defSQLBlock.ID] {- defSQLBlocksCache[defSQLBlock.ID] = defSQLBlock- }- }- refSQLBlocksCache := map[string]*sql.Block{}- for _, refSQLBlock := range querySQLBlocks {- if nil != refSQLBlock && refSQLBlockIDs[refSQLBlock.ID] {- refSQLBlocksCache[refSQLBlock.ID] = refSQLBlock- }- }-- excludeBacklinkIDs := hashset.New()- for _, ref := range refs {- defSQLBlock := defSQLBlocksCache[(ref.DefBlockID)]- if nil == defSQLBlock {- continue- }-- refSQLBlock := refSQLBlocksCache[ref.BlockID]- if nil == refSQLBlock {- continue- }- refBlock := fromSQLBlock(refSQLBlock, "", beforeLen)- if rootID == refBlock.RootID { // 排除当前文档内引用提及- excludeBacklinkIDs.Add(refBlock.RootID, refBlock.ID)- }- defBlock := fromSQLBlock(defSQLBlock, "", beforeLen)- if defBlock.RootID == rootID { // 当前文档的定义块- links = append(links, defBlock)- if ref.DefBlockID == defBlock.ID {- defBlock.Refs = append(defBlock.Refs, refBlock)- }- }- }-- for _, link := range links {- for _, ref := range link.Refs {- excludeBacklinkIDs.Add(ref.RootID, ref.ID)- }- linkRefsCount += len(link.Refs)- }-- var linkRefs []*Block- var backlinkRefBlocks []*Block- for _, link := range links {- for _, ref := range link.Refs {- backlinkRefBlocks = append(backlinkRefBlocks, ref)- }- }- coveredRefIDs := map[string]bool{}- originalRefBlockIDs := map[string]string{}- for _, mapping := range buildBacklinkParentMappings(backlinkRefBlocks, boxID) {- parent := sql.GetBlockInBox(mapping.parent.ID, boxID)- if nil == parent {- continue- }- originalRefBlockIDs[mapping.parent.ID] = mapping.refBlock.ID- for refID := range mapping.coveredRefIDs {- coveredRefIDs[refID] = true- }- linkRefsCount -= len(mapping.coveredRefIDs) - 1- linkRefs = append(linkRefs, fromSQLBlock(parent, keyword, beforeLen))- }- for _, link := range links {- for _, ref := range link.Refs {- if coveredRefIDs[ref.ID] {- continue- }-- ref.DefID = link.ID- ref.DefPath = link.Path-- content := ref.Content- if "" != keyword {- _, content = search.MarkText(content, keyword, beforeLen, Conf.Search.CaseSensitive)- ref.Content = content- }- linkRefs = append(linkRefs, ref)- }- }- linkPaths = toSubTreeInBox(linkRefs, keyword, boxID, originalRefBlockIDs)-- if !includeMentions {- return- }- mentions, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, beforeLen, boxID)- mentionsCount = len(mentions)- mentionPaths = toFlatTree(mentions, 0, "backlink", nil)- return-}-func buildLinkRefs(defRootID string, refs []*sql.Ref, keywords []string) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {return buildLinkRefsInBox(defRootID, refs, keywords, "")}diff --git a/kernel/model/backlink_options_fts5_test.go b/kernel/model/backlink_options_fts5_test.gonew file mode 100644index 0000000000..ce882303ac--- /dev/null+++ b/kernel/model/backlink_options_fts5_test.go@@ -0,0 +1,65 @@+//go:build fts5++package model++import (+ "reflect"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestBacklink2OptionalMentions(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search = conf.NewSearch()+ Conf.Search.BacklinkMentionDoc = true+ for _, id := range []string{fixture.sourceID, fixture.targetID} {+ tree, err := LoadTreeByBlockID(id)+ if err != nil {+ t.Fatal(err)+ }+ if id == fixture.sourceID {+ tree.Root.SetIALAttr("title", "BacklinkTarget")+ tree.HPath = "/BacklinkTarget"+ } else {+ for child := tree.Root.FirstChild; child != nil; {+ next := child.Next+ child.Unlink()+ child = next+ }+ ref := treenode.NewParagraph("20260909150000-ref0001")+ ref.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref",+ TextMarkBlockRefID: fixture.sourceID, TextMarkBlockRefSubtype: "s", TextMarkTextContent: "BacklinkTarget"})+ tree.Root.AppendChild(ref)+ mention := treenode.NewParagraph("20260909150001-mention")+ mention.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("BacklinkTarget")})+ tree.Root.AppendChild(mention)+ }+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.UpdateRefsTreeQueue(tree)+ }+ sql.FlushQueue()+ if refs := sql.QueryRefsByDefID(fixture.sourceID, false); len(refs) != 1 {+ t.Fatalf("fixture reference was not indexed: %+v", refs)+ }+ box, links, mentions, linkCount, mentionCount := GetBacklink2InBoxWithFilter(fixture.sourceID, "", "", 0, 0, false, "", nil)+ if len(links) != 1 || linkCount != 1 || len(mentions) != 1 || mentionCount != 1 {+ t.Fatalf("fixture should contain one backlink and one mention: %d/%d, %d/%d", len(links), linkCount, len(mentions), mentionCount)+ }+ gotBox, gotLinks, gotMentions, gotLinkCount, gotMentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, false)+ if gotBox != box || !reflect.DeepEqual(gotLinks, links) || gotLinkCount != linkCount {+ t.Fatal("omitting mentions changed the backlink results")+ }+ if gotMentions == nil || len(gotMentions) != 0 || gotMentionCount != 0 {+ t.Fatalf("omitted mentions must remain an empty array with zero count: %+v, %d", gotMentions, gotMentionCount)+ }+}diff --git a/kernel/model/path.go b/kernel/model/path.goindex fa7b42a627..926df57db4 100644--- a/kernel/model/path.go+++ b/kernel/model/path.go@@ -27,8 +27,6 @@ import ("github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/siyuan-note/logging"- "github.com/siyuan-note/siyuan/kernel/search"- "github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -191,284 +189,6 @@ func toFlatTree(blocks []*Block, baseDepth int, typ string, tree *parse.Tree) (rreturn}-func toSubTree(blocks []*Block, keyword string) (ret []*Path) {- return toSubTreeInBox(blocks, keyword, "", nil)-}--// toSubTreeInBox 与 toSubTree 一致,但按 boxID 路由到加密 db 或全局 db。-func toSubTreeInBox(blocks []*Block, keyword, boxID string, originalRefBlockIDs map[string]string) (ret []*Path) {- keyword = strings.TrimSpace(keyword)- var blockRoots []*Block- for _, block := range blocks {- root := getBlockIn(blockRoots, block.RootID)- if nil == root {- root, _ = getBlock(block.RootID, nil)- blockRoots = append(blockRoots, root)- }- block.Depth = 1- block.Count = len(block.Children)- root.Children = append(root.Children, block)- }-- for _, root := range blockRoots {- treeNode := &Path{- ID: root.ID,- Box: root.Box,- Name: path.Base(root.HPath),- Type: "backlink",- NodeType: "NodeDocument",- SubType: root.SubType,- Depth: 0,- Count: len(root.Children),- }- for _, c := range root.Children {- if "NodeDocument" == c.Type && "" != originalRefBlockIDs[c.ID] {- tree, _ := loadTreeByBlockIDInBox(c.RootID, boxID)- if nil == tree {- continue- }- for child := tree.Root.FirstChild; nil != child; child = child.Next {- if "" == child.ID || !child.IsBlock() {- continue- }- subBlock, _ := getBlock(child.ID, tree)- if nil == subBlock {- continue- }- subBlock.Depth = 1- treeNode.Blocks = append(treeNode.Blocks, subBlock)- }- } else if "NodeListItem" == c.Type {- tree, _ := loadTreeByBlockIDInBox(c.RootID, boxID)- li := treenode.GetNodeInTree(tree, c.ID)- if nil == li || nil == li.FirstChild {- // 反链面板拖拽到文档以后可能会出现这种情况 https://github.com/siyuan-note/siyuan/issues/5363- continue- }-- var first *sql.Block- if 3 != li.ListData.Typ {- first = sql.GetBlockInBox(li.FirstChild.ID, boxID)- } else {- first = sql.GetBlockInBox(li.FirstChild.Next.ID, boxID)- }- name := first.Content- parentPos := 0- if "" != keyword {- parentPos, name = search.MarkText(name, keyword, 12, Conf.Search.CaseSensitive)- }- subRoot := &Path{- ID: li.ID,- Box: li.Box,- Name: name,- Type: "backlink",- NodeType: li.Type.String(),- SubType: c.SubType,- Depth: 1,- Count: 1,- }-- refNode := li.FirstChild- if originalRefBlockID := originalRefBlockIDs[li.ID]; "" != originalRefBlockID {- if originalRefBlock := treenode.GetNodeInTree(tree, originalRefBlockID); nil != originalRefBlock {- refNode = originalRefBlock- }- }- unfold := true- for liFirstBlockSpan := refNode.FirstChild; nil != liFirstBlockSpan; liFirstBlockSpan = liFirstBlockSpan.Next {- if treenode.IsBlockRef(liFirstBlockSpan) {- continue- }- if "" != strings.TrimSpace(liFirstBlockSpan.Text()) {- unfold = false- break- }- }- for next := li.FirstChild.Next; nil != next; next = next.Next {- subBlock, _ := getBlock(next.ID, tree)- if unfold {- if ast.NodeList == next.Type {- for subLi := next.FirstChild; nil != subLi; subLi = subLi.Next {- subLiBlock, _ := getBlock(subLi.ID, tree)- if nil == subLiBlock || nil == subLi.FirstChild {- continue- }- var subFirst *sql.Block- if 3 != subLi.ListData.Typ {- subFirst = sql.GetBlockInBox(subLi.FirstChild.ID, boxID)- } else {- if nil == subLi.FirstChild.Next {- continue- }- subFirst = sql.GetBlockInBox(subLi.FirstChild.Next.ID, boxID)- }- if nil == subFirst {- continue- }- subPos := 0- content := subFirst.Content- if "" != keyword {- subPos, content = search.MarkText(subFirst.Content, keyword, 12, Conf.Search.CaseSensitive)- }- if -1 < subPos {- parentPos = 0 // 需要显示父级- }- subLiBlock.Content = content- subLiBlock.Depth = 2- subRoot.Blocks = append(subRoot.Blocks, subLiBlock)- }- } else if ast.NodeHeading == next.Type {- subBlock.Depth = 2- subRoot.Blocks = append(subRoot.Blocks, subBlock)- headingChildren := treenode.HeadingChildren(next)- var breakSub bool- for _, n := range headingChildren {- block, _ := getBlock(n.ID, tree)- subPos := 0- content := block.Content- if "" != keyword {- subPos, content = search.MarkText(block.Content, keyword, 12, Conf.Search.CaseSensitive)- }- if -1 < subPos {- parentPos = 0- }- block.Content = content- block.Depth = 3- subRoot.Blocks = append(subRoot.Blocks, block)- if ast.NodeHeading == n.Type {- // 跳过子标题下面的块- breakSub = true- break- }- }- if breakSub {- break- }- } else {- if nil == treenode.HeadingParent(next) {- subBlock.Depth = 2- subRoot.Blocks = append(subRoot.Blocks, subBlock)- }- }- }- }- if -1 < parentPos {- treeNode.Children = append(treeNode.Children, subRoot)- }- } else if "NodeHeading" == c.Type {- tree, _ := loadTreeByBlockIDInBox(c.RootID, boxID)- h := treenode.GetNodeInTree(tree, c.ID)- if nil == h {- continue- }-- sqlHeading := sql.GetBlockInBox(h.ID, boxID)- if nil == sqlHeading {- continue- }- name := sqlHeading.Content- parentPos := 0- if "" != keyword {- parentPos, name = search.MarkText(name, keyword, 12, Conf.Search.CaseSensitive)- }- subRoot := &Path{- ID: h.ID,- Box: h.Box,- Name: name,- Type: "backlink",- NodeType: h.Type.String(),- SubType: c.SubType,- Depth: 1,- Count: 1,- }-- unfold := "" != originalRefBlockIDs[h.ID]- if !unfold {- unfold = true- for headingFirstSpan := h.FirstChild; nil != headingFirstSpan; headingFirstSpan = headingFirstSpan.Next {- if treenode.IsBlockRef(headingFirstSpan) {- continue- }- if "" != strings.TrimSpace(headingFirstSpan.Text()) {- unfold = false- break- }- }- }-- if unfold {- headingChildren := treenode.HeadingChildren(h)- for _, headingChild := range headingChildren {- if ast.NodeList == headingChild.Type {- for subLi := headingChild.FirstChild; nil != subLi; subLi = subLi.Next {- subLiBlock, _ := getBlock(subLi.ID, tree)- if nil == subLiBlock || nil == subLi.FirstChild {- continue- }- var subFirst *sql.Block- if 3 != subLi.ListData.Typ {- subFirst = sql.GetBlockInBox(subLi.FirstChild.ID, boxID)- } else {- if nil == subLi.FirstChild.Next {- continue- }- subFirst = sql.GetBlockInBox(subLi.FirstChild.Next.ID, boxID)- }- if nil == subFirst {- continue- }- subPos := 0- content := subFirst.Content- if "" != keyword {- subPos, content = search.MarkText(content, keyword, 12, Conf.Search.CaseSensitive)- }- if -1 < subPos {- parentPos = 0- }- subLiBlock.Content = subFirst.Content- subLiBlock.Depth = 2- subRoot.Blocks = append(subRoot.Blocks, subLiBlock)- }- } else {- subBlock, _ := getBlock(headingChild.ID, tree)- subBlock.Depth = 2- subRoot.Blocks = append(subRoot.Blocks, subBlock)- }- }- }-- if -1 < parentPos {- treeNode.Children = append(treeNode.Children, subRoot)- }- } else {- pos := 0- content := c.Content- if "" != keyword {- pos, content = search.MarkText(content, keyword, 12, Conf.Search.CaseSensitive)- }- if -1 < pos {- treeNode.Blocks = append(treeNode.Blocks, c)- }- }- }-- rootPos := -1- var rootContent string- if "" != keyword {- rootPos, rootContent = search.MarkText(treeNode.Name, keyword, 12, Conf.Search.CaseSensitive)- treeNode.Name = rootContent- }- if 0 < len(treeNode.Children) || 0 < len(treeNode.Blocks) || (-1 < rootPos && "" != keyword) {- ret = append(ret, treeNode)- }- }-- sort.Slice(ret, func(i, j int) bool {- return ret[i].ID > ret[j].ID- })- return-}-func getBlockIn(blocks []*Block, id string) *Block {if "" == id {return nil