Skip to content

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

117 KB
Raw Blame
import {config as configApi} from "../../config/util/configApi";
import {toggleMenu} from "../../menus/menuToggle";
import {GlobalBacklinkList} from "./GlobalBacklinkList";
import {bindPanelSearch} from "./panelSearch";
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 {isPhablet, 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 {hasAVEditorSession} from "../../protyle/render/av/editorSession";
import {BACKLINK_BLOCK_TYPES, configureBacklinkTypeFold, normalizeBacklinkFoldTypes} from "../../protyle/wysiwyg/backlinkTypeFold";
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 {loadBacklinkRefFilterMenu} from "./backlinkRefFilterMenu";
import {loadBacklinkDatabaseFilterMenu} from "./backlinkDatabaseFilter";
import {BacklinkMentionCache, getBacklinkMentionQueryKey} from "./backlinkMentionCache";
import {BottomBacklinkScroll} from "./bottomBacklinkScroll";
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 mentionCache = new BacklinkMentionCache<Pick<IBacklinkListResponse, "backmentions" | "mentionsCount">>();
    private listQueryKey = "";
    private renderedQueryKey = "";
    private indexChangeVersion = 0;
    private indexRefreshTimer?: number;
    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 bottomLayoutScroll?: BottomBacklinkScroll;
    private ownerScrollListener?: () => void;
    private onlyBacklinks: boolean;
    private surface: string;
    private globalList?: GlobalBacklinkList;

    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);
        this.element.addEventListener("av-editor-close", 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 spellcheck="false" class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.searchPlaceholder}" />
    ${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.search}"><svg><use xlink:href='#iconSearch'></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 spellcheck="false" class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.searchPlaceholder}" />
    <span data-type="search" class="block__icon b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.search}"><svg><use xlink:href='#iconSearch'></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((inputElement) => {
            const searchElement = inputElement.parentElement.querySelector('[data-type="search"]');
            const showSearch = bindPanelSearch(inputElement, searchElement, () => this.searchBacklinks(), {
                trim: false, trigger: "enter",
            });
            searchElement.addEventListener("click", (event) => {
                event.stopPropagation();
                showSearch();
            });
        });
        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: [isPhablet() ? Constants.CB_GET_HL : 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: [isPhablet() ? Constants.CB_GET_HL : 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: [isPhablet() ? Constants.CB_GET_HL : 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: [isPhablet() ? Constants.CB_GET_HL : 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", () => {
            if (this.globalList) {
                this.globalList.setCollapsed(true);
                return;
            }
            const finishScroll = this.beginBottomScroll();
            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();
            finishScroll?.();
        });
        this.element.querySelector('[data-type="expand"]').addEventListener("click", () => {
            if (this.globalList) {
                this.globalList.setCollapsed(false);
                return;
            }
            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": {
                            const finishScroll = this.beginBottomScroll();
                            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();
                            finishScroll?.();
                            break;
                        }
                        case "min":
                            /// #if !MOBILE
                            getDockByType("backlink").toggleModel("backlink", false, true);
                            /// #endif
                            event.stopPropagation();
                            break;
                        case "sort":
                        case "mSort": {
                            toggleMenu({
                                target: target,
                                build: (_menu, session) => {
                                    this.showSortMenu(type, target.getAttribute("data-sort"));
                                    const rect = target.getBoundingClientRect();
                                    session.show(() => window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));

                                },
                            });
                        event.stopPropagation();
                            break;
                        }
                        case "sourceFilter":
                            this.showSourceFilterMenu(target);
                            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.mentionCache.clear();
        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;
                this.updateSourceFilterButton();
            }
        });
    }

    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 beginBottomScroll() {
        if (this.type !== "bottom") {
            return;
        }
        this.bottomLayoutScroll ??= new BottomBacklinkScroll(this.element, this.ownerProtyle.contentElement);
        return this.bottomLayoutScroll.begin();
    }

    private setBottomLayout(element: HTMLElement, listElement: HTMLElement) {
        if (isHeightAnimating(listElement)) {
            return;
        }
        const finishScroll = this.beginBottomScroll();
        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");
                finishScroll();
            });
        } else {
            delete listElement.dataset.heightFolding;
            listElement.classList.remove("fn__none");
            // 手动展开时保持当前位置,避免共享阅读锚点将页面滚动到提及区域。
            void this.resumeViewFoldStates(listElement);
            expandHeight(listElement, finishScroll);
        }
        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, "start");
        /// #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 globalSort = window.siyuan.config.editor.backlinkGlobalSort || 0;
        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;
                window.siyuan.config.editor.backlinkGlobalSort = 0;
            } else {
                window.siyuan.config.editor.backmentionSort = sortValue;
            }
            configApi.set("editor", type === "sort" ?
                {backlinkSort: sortValue, backlinkGlobalSort: 0} : {backmentionSort: sortValue});
            this.searchBacklinks();
        };
        window.siyuan.menus.menu.remove();
        if (type === "sort") {
            window.siyuan.menus.menu.append(new MenuItem({
                type: "readonly",
                iconHTML: "",
                label: window.siyuan.languages.backlinkDocumentSort,
            }).element);
        }
        window.siyuan.menus.menu.append(new MenuItem({
            checked: (type !== "sort" || !globalSort) && sort === "0",
            iconHTML: "",
            label: window.siyuan.languages.fileNameASC,
            click: () => {
                clickEvent("0");
            }
        }).element);
        window.siyuan.menus.menu.append(new MenuItem({
            checked: (type !== "sort" || !globalSort) && sort === "1",
            iconHTML: "",
            label: window.siyuan.languages.fileNameDESC,
            click: () => {
                clickEvent("1");
            }
        }).element);
        window.siyuan.menus.menu.append(new MenuItem({
            checked: (type !== "sort" || !globalSort) && sort === "4",
            iconHTML: "",
            label: window.siyuan.languages.fileNameNatASC,
            click: () => {
                clickEvent("4");
            }
        }).element);
        window.siyuan.menus.menu.append(new MenuItem({
            checked: (type !== "sort" || !globalSort) && 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: (type !== "sort" || !globalSort) && sort === "9",
            iconHTML: "",
            label: window.siyuan.languages.createdASC,
            click: () => {
                clickEvent("9");
            }
        }).element);
        window.siyuan.menus.menu.append(new MenuItem({
            checked: (type !== "sort" || !globalSort) && sort === "10",
            iconHTML: "",
            label: window.siyuan.languages.createdDESC,
            click: () => {
                clickEvent("10");
            }
        }).element);
        window.siyuan.menus.menu.append(new MenuItem({
            checked: (type !== "sort" || !globalSort) && sort === "2",
            iconHTML: "",
            label: window.siyuan.languages.modifiedASC,
            click: () => {
                clickEvent("2");
            }
        }).element);
        window.siyuan.menus.menu.append(new MenuItem({
            checked: (type !== "sort" || !globalSort) && sort === "3",
            iconHTML: "",
            label: window.siyuan.languages.modifiedDESC,
            click: () => {
                clickEvent("3");
            }
        }).element);
        if (type === "sort") {
            window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
            window.siyuan.menus.menu.append(new MenuItem({
                type: "readonly",
                iconHTML: "",
                label: window.siyuan.languages.backlinkBlockSort,
            }).element);
            [window.siyuan.languages.backlinkBodyOrder, window.siyuan.languages.backlinkAnchorASC,
                window.siyuan.languages.backlinkAnchorDESC].forEach((label, mode) => {
                window.siyuan.menus.menu.append(new MenuItem({
                    label,
                    iconHTML: "",
                    checked: !globalSort && mode === (window.siyuan.config.editor.backlinkBlockSort || 0),
                    click: () => {
                        window.siyuan.config.editor.backlinkBlockSort = mode;
                        window.siyuan.config.editor.backlinkGlobalSort = 0;
                        configApi.set("editor", {backlinkBlockSort: mode, backlinkGlobalSort: 0});
                        this.cancelContextRequests(this.tree.element, false);
                        if (this.globalList) {
                            this.searchBacklinks(true);
                            return;
                        }
                        this.refreshExpandedContexts(new Set<string>(), true, true);
                    },
                }).element);
            });
            window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
            window.siyuan.menus.menu.append(new MenuItem({
                type: "readonly", iconHTML: "", label: window.siyuan.languages.backlinkGlobalSort,
            }).element);
            [window.siyuan.languages.backlinkAnchorASC, window.siyuan.languages.backlinkAnchorDESC].forEach((label, index) => {
                window.siyuan.menus.menu.append(new MenuItem({
                    label, iconHTML: "", checked: globalSort === index + 1,
                    click: () => {
                        window.siyuan.config.editor.backlinkGlobalSort = index + 1;
                        configApi.set("editor", {backlinkGlobalSort: index + 1});
                        this.searchBacklinks();
                    },
                }).element);
            });
        }
    }

    private applySourceFilter(filter: IBacklinkSourceFilter) {
        this.sourceFilter = normalizeBacklinkSourceFilter(filter);
        this.updateSourceFilterButton();
        this.searchBacklinks();
    }

    private syncGlobalList(refresh: boolean) {
        const mode = window.siyuan.config.editor.backlinkGlobalSort || 0;
        if (mode !== 1 && mode !== 2) {
            if (this.globalList) {
                this.globalList.destroy();
                this.globalList = undefined;
                this.listQueryKey = "";
                this.listRevision = "";
                this.tree.element.scrollTop = this.status[this.blockId]?.scrollTop || 0;
            }
            return;
        }
        if (!this.globalList) {
            if (this.status[this.blockId] && !this.showingLoading) { this.saveStatus(); }
            this.cancelContextRequests(this.tree.element, false);
            this.itemRecords[0].forEach(record => this.destroyItemRecord(record));
            this.itemRecords[0].clear();
            this.globalList = new GlobalBacklinkList({
                app: this.app,
                host: this.tree.element,
                scroll: this.getScrollElement(this.tree),
                sharedScroll: this.type === "bottom",
                state: () => this.viewState,
                foldedTypes: () => normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes")),
                open: id => this.openDocument({app: this.app, id, action: [Constants.CB_GET_CONTEXT]}),
                editorAdded: editor => {
                    this.editors.push(editor);
                    if (this.type === "bottom") {
                        editor.protyle.wysiwyg.element.addEventListener("focusin", () => this.setOwnerFocus());
                    }
                },
                editorRemoved: editor => {
                    const index = this.editors.indexOf(editor);
                    if (index !== -1) { this.editors.splice(index, 1); }
                },
                count: total => {
                    const countElement = this.element.querySelector(".listCount");
                    countElement.textContent = total.toString();
                    countElement.classList.toggle("fn__none", total === 0 && this.type !== "bottom");
                    if (this.type === "bottom") {
                        const hideBacklinks = total === 0 && !this.inputsElement[0].value &&
                            !getBacklinkSourceFilterParam(this.sourceFilter) && !this.globalList?.hasError;
                        this.element.classList.toggle("sy__backlink--backlinks-empty", hideBacklinks);
                        const empty = hideBacklinks &&
                            this.element.classList.contains("sy__backlink--mentions-empty");
                        if (empty !== this.empty) { this.empty = empty; this.emptyChange?.(empty); }
                    }
                },
            });
        }
        this.globalList.search({
            id: this.blockId,
            notebook: isEncryptedBox(this.notebookId) ? this.notebookId : "",
            keyword: this.inputsElement[0].value,
            sort: mode,
            containChildren: window.siyuan.config.editor.backlinkContainChildren,
            sourceFilter: getBacklinkSourceFilterParam(this.sourceFilter),
        }, refresh);
    }

    private updateSourceFilterButton() {
        this.element.querySelector('[data-type="sourceFilter"]')?.classList.toggle(
            "block__icon--active",
            Boolean(getBacklinkSourceFilterParam(this.sourceFilter)) ||
            normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes")).length > 0,
        );
    }

    private showSourceFilterMenu(target: HTMLElement) {
        // 工具栏离开悬停后会隐藏按钮,在打开菜单前保留其位置。
        const rect = target.getBoundingClientRect();
        toggleMenu({
            target: target,
            build: (_menu, session) => {
                let foldedTypes = normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes"));
                const foldItems = new Map<string, HTMLElement>();
                let foldResetElement: HTMLElement;
                let resetElement: HTMLElement;
                const applyFoldTypes = (types: string[]) => {
                    this.viewState?.set("foldedBlockTypes", types);
                    this.updateSourceFilterButton();
                    BACKLINK_BLOCK_TYPES.forEach(([type]) => {
                        if (foldedTypes.includes(type) !== types.includes(type)) {
                            const field = `type-fold-generation:${type}`;
                            this.viewState?.set(field, (this.viewState.get<number>(field) || 0) + 1);
                        }
                    });
                    foldedTypes = types;
                    foldItems.forEach((element, type) => {
                        element.querySelector(".b3-menu__checked")?.remove();
                        if (foldedTypes.includes(type)) {
                            element.insertAdjacentHTML("beforeend", '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>');
                        }
                    });
                    if (foldedTypes.length === 0) {
                        foldResetElement?.setAttribute("disabled", "disabled");
                    } else {
                        foldResetElement?.removeAttribute("disabled");
                    }
                    if (!getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0) {
                        resetElement?.setAttribute("disabled", "disabled");
                    } else {
                        resetElement?.removeAttribute("disabled");
                    }
                    this.itemRecords[0].forEach(record => {
                        if (record.editor && this.viewState) {
                            configureBacklinkTypeFold(record.editor.protyle, types, this.viewState);
                        }
                    });
                    this.globalList?.updateFoldTypes();
                };
                const blockTypeFoldSubmenu: IMenu[] = [{
                    label: window.siyuan.languages.reset,
                    icon: "iconUndo",
                    disabled: foldedTypes.length === 0,
                    bind: element => {foldResetElement = element;},
                    click: () => {
                        applyFoldTypes([]);
                        return true;
                    },
                }, {type: "separator"}, ...BACKLINK_BLOCK_TYPES.map(([type, label]) => ({
                    label: window.siyuan.languages[label] || label,
                    checked: foldedTypes.includes(type),
                    iconHTML: "",
                    bind: (element: HTMLElement) => {foldItems.set(type, element);},
                    click: () => {
                        applyFoldTypes(foldedTypes.includes(type) ?
                            foldedTypes.filter(item => item !== type) : [...foldedTypes, type]);
                        return true;
                    },
                }))];
                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.append(new MenuItem({
                    icon: "iconContract",
                    label: window.siyuan.languages.backlinkFoldByType,
                    type: "submenu",
                    disabled: !this.viewStateLoaded || !this.viewState,
                    submenu: blockTypeFoldSubmenu,
                }).element);
                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);
                const refFilterGeneration = this.viewStateGeneration;
                window.siyuan.menus.menu.append(new MenuItem({
                    label: window.siyuan.languages.backlinkDatabaseFields,
                    icon: "iconDatabase",
                    checked: Boolean(this.sourceFilter.database),
                    disabled: !this.blockId || window.siyuan.isPublish,
                    loadSubmenu: () => loadBacklinkDatabaseFilterMenu({
                        id: this.blockId,
                        notebook: isEncryptedBox(this.notebookId) ? this.notebookId : "",
                        keyword: this.inputsElement[0].value,
                        filter: this.sourceFilter,
                        target,
                        anchorRect: rect,
                        protyle: this.ownerProtyle || this.editors[0]?.protyle,
                        getSelected: () => this.sourceFilter.database,
                        isCurrent: () => !this.destroyed && refFilterGeneration === this.viewStateGeneration,
                        apply: database => this.applySourceFilter({...this.sourceFilter, database}),
                    }),
                }).element);
                let refFilterMenuElement: HTMLElement;
                window.siyuan.menus.menu.append(new MenuItem({
                    iconHTML: "",
                    label: `${window.siyuan.languages.backlinkExcludeRefDefs} (${this.sourceFilter.excludedRefDefIDs.length})`,
                    disabled: !this.blockId,
                    bind: element => {refFilterMenuElement = element;},
                    loadSubmenu: () => {
                        return loadBacklinkRefFilterMenu({
                            id: this.blockId,
                            notebook: isEncryptedBox(this.notebookId) ? this.notebookId : "",
                            keyword: this.inputsElement[0].value,
                            filter: this.sourceFilter,
                            getSelected: () => this.sourceFilter.excludedRefDefIDs,
                            isCurrent: () => !this.destroyed && refFilterGeneration === this.viewStateGeneration,
                            apply: ids => {
                                this.applySourceFilter({...this.sourceFilter, excludedRefDefIDs: ids});
                                refFilterMenuElement.querySelector(":scope > .b3-menu__label").textContent =
                                    `${window.siyuan.languages.backlinkExcludeRefDefs} (${this.sourceFilter.excludedRefDefIDs.length})`;
                                resetElement?.toggleAttribute("disabled", !getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0);
                            },
                        });
                    },
                }).element);
                window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
                window.siyuan.menus.menu.append(new MenuItem({
                    disabled: !getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0,
                    bind: element => {resetElement = element;},
                    icon: "iconUndo",
                    label: window.siyuan.languages.reset,
                    click: () => {
                        this.applySourceFilter(createBacklinkSourceFilter());
                        applyFoldTypes([]);
                    }
                }).element);
                session.show(() => window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));

            },
        });
    }

    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")) {
            const finishScroll = persist ? this.beginBottomScroll() : undefined;
            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();
            finishScroll?.();
        } else if (editor && !record?.contextDirty) {
            const finishScroll = persist ? this.beginBottomScroll() : undefined;
            editor.protyle.element.classList.remove("fn__none");
            svgElement.classList.add("b3-list-item__arrow--open");
            void applyViewFoldStates(editor.protyle).finally(() => finishScroll?.());
            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: import("../../types/api").BacklinkDocumentRequestInput = {
            defID: blockId,
            refTreeID: docId,
            highlight: !isSupportCSSHL(),
            keyword,
        };
        const notebookId = liElement.getAttribute("data-notebook-id");
        if (!isMention) {
            param.sourceFilter = getBacklinkSourceFilterParam(this.sourceFilter);
            param.blockSort = window.siyuan.config.editor.backlinkBlockSort || 0;
        }
        if (isEncryptedBox(notebookId)) {
            param.notebook = notebookId;
        }
        if (record.contextRevision) {
            param.knownRevision = record.contextRevision;
        }
        let finishScroll: (() => void) | undefined;
        const viewPromises: Promise<unknown>[] = [];
        const manualBottomExpand = this.type === "bottom" && expand && persist;
        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.code !== 0 || !response.data) {
                return;
            }
            svgElement.removeAttribute("disabled");
            if (record.editor && (record.editor.protyle.element.contains(document.activeElement) ||
                hasAVEditorSession(record.editor.protyle.element))) {
                record.contextDirty = true;
                this.dirty = true;
                this.pendingRootIDs.add(docId);
                return;
            }
            // 收到有效内容后再保护当前视口,等待请求期间仍允许用户正常滚动。
            finishScroll = manualBottomExpand ? this.beginBottomScroll() : undefined;
            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;
                    viewPromises.push(renderBacklink(editor.protyle, backlinkData).then(() => {
                        if (manualBottomExpand) {
                            return;
                        }
                        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;
                    if (!isMention && service) {
                        configureBacklinkTypeFold(editor.protyle, normalizeBacklinkFoldTypes(service.get("foldedBlockTypes")), service);
                    }
                    const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);
                    const anchorQueryKey = this.renderedQueryKey;
                    if (service) {
                        viewPromises.push(registerViewFoldContext(editor.protyle, {
                            store: service,
                            pane: isMention ? "backmention" : "backlink",
                            rootID: docId,
                            getOccurrenceID: getBacklinkOccurrenceID,
                            getOccurrenceRevision: getBacklinkOccurrenceRevision,
                        }).then(() => {
                            if (manualBottomExpand) {
                                return;
                            }
                            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(() => {
            void Promise.allSettled(viewPromises).then(() => finishScroll?.());
            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 => 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 (!isMention && this.globalList) { return; }
        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 (!isMention && this.globalList) { return; }
        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, reuseMentions = false) {
        this.itemRecords.forEach((records, index) => {
            if (index === 1 && reuseMentions) {
                return;
            }
            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"><span class="b3-loading" aria-hidden="true"></span></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) {
        this.globalList?.destroy();
        this.globalList = undefined;
        cancelHeightAnimation(this.tree.element);
        cancelHeightAnimation(this.mTree.element);
        this.bottomLayoutScroll?.reset();
        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) {
        this.clearIndexRefresh();
        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) {
        this.clearIndexRefresh();
        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() {
        this.clearIndexRefresh();
        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.clearIndexRefresh();
        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,
            includeBacklinks?: 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 (notebookId) { this.notebookId = notebookId; }
        this.syncGlobalList(init || refreshAllContexts || this.dirty);
        if (this.globalList) { param.includeBacklinks = false; }
        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 mentionQueryKey = JSON.stringify([
            getBacklinkMentionQueryKey(param),
            window.siyuan.config.search,
            window.siyuan.config.editor.backlinkMentionExclude,
            window.siyuan.config.editor.backlinkContainChildren,
        ]);
        const cachedMentions = !this.onlyBacklinks && !init && !refreshAllContexts && !this.dirty ?
            this.mentionCache.get(mentionQueryKey, this.indexChangeVersion) : undefined;
        if (cachedMentions) {
            param.includeMentions = false;
        }
        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.code !== 0 || !response.data || !("revision" in 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) {
                if (cachedMentions) {
                    Object.assign(response.data, cachedMentions);
                } else if (!this.onlyBacklinks) {
                    this.mentionCache.set(mentionQueryKey, indexChangeVersion, {
                        backmentions: response.data.backmentions,
                        mentionsCount: response.data.mentionsCount,
                    });
                }
                this.render(response.data, init);
            }
            this.refreshExpandedContexts(changedRootIDs, fullContextRefresh, Boolean(cachedMentions));
            if (indexChangeVersion === this.indexChangeVersion) {
                this.pendingRootIDs.clear();
                this.pendingFull = false;
                this.dirty = false;
            }
            if (this.dirty) {
                this.refreshAfterIndex();
            }
        }).finally(() => {
            if (responseHandled || !this.finishRequest(requestID) || blockId !== this.blockId) {
                return;
            }
            if (!this.runQueuedRequest() && indexChangeVersion !== this.indexChangeVersion && this.dirty) {
                this.refreshAfterIndex();
            }
        });
    }

    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.globalList ? this.status[this.blockId]?.scrollTop || 0 : this.tree.element.scrollTop,
            mScrollTop: this.mTree.element.scrollTop,
            backlinkOpenIds: this.globalList ? this.status[this.blockId]?.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.mentionCache.clear();
            this.listRevision = "";
            this.listQueryKey = "";
            data = {
                box: "",
                backlinks: [],
                backmentions: [],
                linkRefsCount: 0,
                mentionsCount: 0,
                k: "",
                mk: ""
            };
        }
        const wasLoading = this.showingLoading;
        if (this.globalList) { data = {...data, linkRefsCount: this.globalList.count}; }
        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.globalList ? false : 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,
                Boolean(getBacklinkSourceFilterParam(this.sourceFilter))) : undefined;
        if (bottomVisibility) {
            if (this.globalList?.hasError) {
                bottomVisibility.hideBacklinks = false;
                bottomVisibility.hidePanel = false;
            }
            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.globalList && 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.globalList?.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.globalList?.markDirty();
        this.indexChangeVersion++;
        this.dirty = true;
        this.pendingFull = this.pendingFull || Boolean(change.backlinkFull) || Boolean(this.sourceFilter.database);
        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;
            }
        }));
    }

    private clearIndexRefresh() {
        window.clearTimeout(this.indexRefreshTimer);
        this.indexRefreshTimer = undefined;
    }

    public refreshAfterIndex() {
        this.clearIndexRefresh();
        if (this.destroyed || !this.blockId || !this.dirty) {
            return;
        }
        // 连续索引更新合并到空闲时处理;请求期间只保留脏标记,完成后再安排下一次刷新。
        this.indexRefreshTimer = window.setTimeout(() => {
            this.indexRefreshTimer = undefined;
            if (this.destroyed || this.requesting || !this.dirty || this.element.contains(document.activeElement) ||
                hasAVEditorSession(this.element)) {
                return;
            }
            if (this.type === "bottom") {
                this.refreshIfVisible();
            } else if (this.element.isConnected && this.element.getClientRects().length > 0) {
                this.searchBacklinks();
            }
        }, 1000);
    }

    public refreshIfVisible(ignoreFocus = false) {
        if (this.destroyed || this.type !== "bottom" || !this.dirty || this.requesting ||
            (!ignoreFocus && this.indexRefreshTimer !== undefined)) {
            return;
        }
        if (!this.element.isConnected || this.ownerProtyle.element.getClientRects().length === 0) {
            return;
        }
        if (shouldDeferBottomBacklinkRefresh(
            this.element.contains(document.activeElement) || hasAVEditorSession(this.element),
            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.globalList?.destroy();
        this.globalList = undefined;
        this.destroyed = true;
        this.clearIndexRefresh();
        this.viewStateGeneration++;
        this.clearReadingAnchorTimers();
        cancelHeightAnimation(this.tree.element);
        cancelHeightAnimation(this.mTree.element);
        this.bottomLayoutScroll?.reset();
        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.element.removeEventListener("av-editor-close", 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();
        }
    }
}