Skip to content

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

113 KB
Raw Blame
import {config as configApi} from "../../config/util/configApi";
import {escapeHtml, escapeHtmlTextAndAttr} from "../../util/escape";
import {genFileTreeDocAriaLabel} from "../../util/fileTreeTooltip";
import {Tab} from "../Tab";
import {Model} from "../Model";
import {getInstanceById, setPanelFocus} from "../util";
import {getDockByType} from "../tabUtil";
import {Constants} from "../../constants";
import {getDocDisplayName, isMoveTargetAllowed, pathPosix, setNoteBook} from "../../util/pathName";
import {newFileInTree} from "../../util/newFile";
import {initFileMenu, initNavigationMenu, sortMenu} from "../../menus/navigation";
import {toggleMenu} from "../../menus/menuToggle";
import {isDocTreeDragSelectionAllowed} from "../../menus/navigationSelection";
import {MenuItem} from "../../menus/Menu";
import {showMessage} from "../../dialog/message";
import {
    getPublishAccessLevel,
    getPublishAccessOptionByLevel,
    openPublishAccessDialog
} from "../../protyle/util/publishAccess";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {restoreFileTreePaths} from "../../util/fileTreeRestore";
import {saveOpenFileTreePaths} from "../../util/fileTreePaths";
import {removeFileTreeItems} from "../../util/fileTreeRemove";
import {openEmojiPanel} from "../../emoji";
import {
    getFileTreeDefaultIconAttr,
    getFileTreeIconHTML,
    syncFileTreeItemDefaultIcon,
    updateFileTreeItemIcon,
} from "../../emoji/fileTreeIcon";
import {importNotebook, newEncryptedNotebook, newNotebook, openEncryptedNotebook} from "../../util/mount";
import {isNotCtrl, isOnlyMeta, isPhablet, setStorageVal, updateHotkeyAfterTip} from "../../protyle/util/compatibility";
import {openFileById} from "../../editor/util";
import {
    hasClosestByClassName,
    hasClosestByTag,
    hasTopClosestByTag
} from "../../protyle/util/hasClosest";
import type {App} from "../../index";
import {refreshFileTree} from "../../dialog/processSystem";
import {confirmDialog} from "../../dialog/confirmDialog";
import {emitToPlugins} from "../../plugin/EventBusCore";
/// #if !BROWSER
import {ipcRenderer} from "electron";
/// #endif
import {hideTooltip, showTooltip} from "../../dialog/tooltip";
import {selectOpenTab} from "./util";
import {hideDragTip, setDragTipGhost, showDragTip} from "../../protyle/util/dragTip";
import {parseBlockDragData} from "../../protyle/util/dragDocument";
import {
    cancelFileTreeCollapse,
    expandFileTree,
    toggleFileTree
} from "./fileTreeAnimation";
import {updateNotebookRootForBoxDoc} from "../../util/notebookRoot";
import {
    collectExpandedDocIDs,
    findMovedFileTreeItem,
    getRelativeReorderRequest,
    getFileTreeChildList,
    IDocumentTabDragData,
    IFileTreeMove,
    insertDocumentSortPath,
    insertDocumentsSortPaths,
    parseDocumentTabDragData,
    restoreMovedExpandedDocItems,
    updateMovedSubtree
} from "../../util/fileTreeMove";
import {
    FILE_TREE_CHILDREN_SORT_MODE,
    FILE_TREE_EFFECTIVE_SORT_MODE,
    getFileTreeSortRefreshTargets,
    getMovedFileTreeSortRefreshTargets,
    getResponseEffectiveSortMode,
    isCustomFileTreeList,
    reorderFileTreeNotebooks,
    type IDocSortModeChanged,
    updateFileTreeSortMode
} from "../../util/fileTreeSort";
import {clearDocumentTabMovePreview} from "../tabDrag";
import {reorderSortedFileTree} from "../../util/fileTreeReorder";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {PinnedDocs} from "./PinnedDocs";
import {selectFileTreeRange} from "./fileTreeSelection";
import {ParentDocClick} from "./parentDocClick";

export class Files extends Model {
    public element: HTMLElement;
    public parent: Tab;
    public closeElement: HTMLElement;
    public lastSelectedElement: Element = null;
    private actionsElement: HTMLElement;
    private pinnedDocs: PinnedDocs;
    private parentDocClick = new ParentDocClick();
    private reloadNotebookInfoTimeout: number;
    private docSortModeRefreshTimeout: number;
    private docSortModeChanges = new Map<string, IDocSortModeChanged>();
    private movedExpandedDocIDs = new Set<string>();

    constructor(options: { tab: Tab, app: App }) {
        super({app: options.app});
        this.connect({
            type: "filetree",
            id: options.tab.id,
            msgCallback: this.handleMsgCallback.bind(this)
        });
        options.tab.panelElement.classList.add("fn__flex-column", "file-tree", "sy__file", "dockPanel");
        options.tab.panelElement.innerHTML = `<div class="block__icons">
    <div class="block__logo fn__flex-1">${window.siyuan.languages.fileTree}</div>
    <span data-type="focus" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.selectOpen1}${updateHotkeyAfterTip(window.siyuan.config.keymap.general.selectOpen1.custom)}"><svg><use xlink:href='#iconFocus'></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}${updateHotkeyAfterTip(window.siyuan.config.keymap.editor.general.collapse.custom)}">
        <svg><use xlink:href="#iconContract"></use></svg>
    </span>
    <div class="fn__space${window.siyuan.config.readonly ? " fn__none" : ""}"></div>
    <div data-type="more" data-menu="true" class="ariaLabel block__icon${window.siyuan.config.readonly ? " fn__none" : ""}" data-position="north" aria-label="${window.siyuan.languages.more}">
        <svg><use xlink:href="#iconMore"></use></svg>
    </div>
    <span class="fn__space"></span>
    <span data-type="min" class="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="file-tree__items fn__flex-1" style="padding-top: 2px;"></div>
<ul class="b3-list fn__flex-column" style="min-height: auto;height:30px;border-top: 1px solid var(--b3-border-color);transition: height  .2s cubic-bezier(0, 0, .2, 1) 0ms">
    <li class="b3-list-item" data-type="toggle">
        <span class="b3-list-item__toggle">
            <svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
        </span>
        <span class="b3-list-item__text">${window.siyuan.languages.closeNotebook}</span>
        <span class="counter" style="cursor: auto"></span>
    </li>
    <ul class="fn__none fn__flex-1"></ul>
</ul>`;
        this.actionsElement = options.tab.panelElement.firstElementChild as HTMLElement;
        this.element = this.actionsElement.nextElementSibling as HTMLElement;
        this.closeElement = options.tab.panelElement.lastElementChild as HTMLElement;
        this.pinnedDocs = new PinnedDocs(options.app, this.element, (id) => {
            openFileById({app: options.app, id, action: [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL]});
        }, false, this.parentDocClick);
        this.closeElement.addEventListener("click", (event) => {
            setPanelFocus(this.element.parentElement);
            let target = event.target as HTMLElement;
            while (target && !target.isEqualNode(this.closeElement)) {
                const type = target.getAttribute("data-type");
                if (target.classList.contains("b3-list-item__icon")) {
                    event.preventDefault();
                    event.stopPropagation();
                    const notebookElement = target.closest("li[data-encrypted=true]");
                    if (notebookElement) {
                        openEncryptedNotebook(this.app, notebookElement.getAttribute("data-url"), notebookElement.querySelector(".b3-list-item__text").textContent);
                        break;
                    }
                    const rect = target.getBoundingClientRect();
                    openEmojiPanel(target.parentElement.getAttribute("data-url"), "notebook", {
                        x: rect.left,
                        y: rect.bottom,
                        h: rect.height,
                        w: rect.width,
                    }, undefined, target.querySelector("img"));
                    break;
                } else if (type === "toggle") {
                    const svgElement = target.querySelector("svg");
                    if (svgElement.classList.contains("b3-list-item__arrow--open")) {
                        this.closeElement.style.height = "30px";
                        svgElement.classList.remove("b3-list-item__arrow--open");
                        this.closeElement.lastElementChild.classList.add("fn__none");
                    } else {
                        this.closeElement.style.height = "40%";
                        svgElement.classList.add("b3-list-item__arrow--open");
                        this.closeElement.lastElementChild.classList.remove("fn__none");
                    }
                    window.siyuan.menus.menu.remove();
                    event.stopPropagation();
                    event.preventDefault();
                    break;
                } else if (type === "open") {
                    const notebookId = target.getAttribute("data-url");
                    const liElement = target.closest("li");
                    // 加密笔记本关闭(锁定)时点"打开"先弹解锁框,解锁成功后再挂载
                    if (liElement && liElement.getAttribute("data-encrypted") === "true") {
                        openEncryptedNotebook(this.app, notebookId, liElement.querySelector(".b3-list-item__text").textContent);
                    } else {
                        fetchPost("/api/notebook/openNotebook", {
                            notebook: notebookId
                        });
                    }
                    window.siyuan.menus.menu.remove();
                    event.stopPropagation();
                    event.preventDefault();
                    break;
                }
                target = target.parentElement;
            }
        });
        // 为了快捷键的 dispatch
        this.actionsElement.querySelector('[data-type="collapse"]').addEventListener("click", () => {
            this.parentDocClick.cancel();
            this.pinnedDocs.collapse();
            Array.from(this.element.children).forEach(item => {
                const liElement = item.firstElementChild;
                const toggleElement = liElement.querySelector(".b3-list-item__arrow");
                if (toggleElement.classList.contains("b3-list-item__arrow--open")) {
                    toggleElement.classList.remove("b3-list-item__arrow--open");
                    liElement.nextElementSibling.remove();
                }
            });
            window.siyuan.storage[Constants.LOCAL_FILESPATHS] = [];
            setStorageVal(Constants.LOCAL_FILESPATHS, []);
        });
        this.actionsElement.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {
            let target = event.target as HTMLElement;
            let isFocus = true;
            while (target && !target.isEqualNode(this.actionsElement)) {
                const type = target.getAttribute("data-type");
                if (type === "min") {
                    getDockByType("file").toggleModel("file", false, true);
                    event.preventDefault();
                    event.stopPropagation();
                    window.siyuan.menus.menu.remove();
                    isFocus = false;
                    break;
                } else if (type === "focus") {
                    selectOpenTab();
                    event.preventDefault();
                    break;
                } else if (type === "more") {
                    toggleMenu({
                        target: target, build: () => {
                            const rect = target.getBoundingClientRect();
                            this.initMoreMenu().popup({x: rect.left, y: rect.bottom, h: rect.height});
                        }
                    });
                    event.preventDefault();
                    event.stopPropagation();
                    break;
                }
                target = target.parentElement;
            }
            if (isFocus) {
                setPanelFocus(this.element.parentElement);
            }
        });
        this.element.addEventListener("mousedown", (event) => {
            // 点击鼠标滚轮关闭
            if (event.button !== 1 || !window.siyuan.config.fileTree.openFilesUseCurrentTab) {
                return;
            }
            let target = event.target as HTMLElement;
            while (target && !target.isEqualNode(this.element)) {
                if (target.tagName === "LI" && target.getAttribute("data-node-id") && !target.getAttribute("data-opening")) {
                    target.setAttribute("data-opening", "true");
                    openFileById({
                        app: options.app,
                        removeCurrentTab: false,
                        id: target.getAttribute("data-node-id"),
                        action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                        afterOpen() {
                            target.removeAttribute("data-opening");
                        }
                    });
                    event.stopPropagation();
                    event.preventDefault();
                    break;
                }
                target = target.parentElement;
            }
        });
        this.element.addEventListener("click", (event) => {
            let target = event.target as HTMLElement;
            if (!target.closest(".b3-list-item__text") || !isNotCtrl(event) || event.altKey || event.shiftKey) {
                this.parentDocClick.cancel();
            }
            const ulElement = hasTopClosestByTag(target, "UL");
            let needFocus = true;
            if (ulElement) {
                const notebookId = ulElement.getAttribute("data-url");
                while (target && !target.isEqualNode(this.element)) {
                    if (isNotCtrl(event) && !event.shiftKey && target.classList.contains("b3-list-item__icon") && window.siyuan.config.system.container !== "ios") {
                        event.preventDefault();
                        event.stopPropagation();
                        const liElement = target.parentElement;
                        const isFile = liElement.getAttribute("data-type") === "navigation-file";
                        // 单击文档图标展开或折叠下级,笔记本图标始终用于修改图标
                        if (isFile && window.siyuan.config.fileTree.docIconClickMode === 1) {
                            if (Number(liElement.getAttribute("data-count")) > 0) {
                                this.lastSelectedElement = liElement;
                                this.setCurrent(liElement, false);
                                this.toggleLeaf(liElement, notebookId);
                                break;
                            }
                            needFocus = false;
                            if (!liElement.getAttribute("data-opening")) {
                                this.lastSelectedElement = liElement;
                                this.setCurrent(liElement, false);
                                liElement.setAttribute("data-opening", "true");
                                openFileById({
                                    app: options.app,
                                    id: liElement.getAttribute("data-node-id"),
                                    action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                                    afterOpen() {
                                        liElement.removeAttribute("data-opening");
                                    }
                                });
                            }
                            break;
                        }
                        const rect = target.getBoundingClientRect();
                        if (isFile) {
                            openEmojiPanel(liElement.getAttribute("data-node-id"), "doc", {
                                x: rect.left,
                                y: rect.bottom,
                                h: rect.height,
                                w: rect.width,
                            }, undefined, target.querySelector("img"));
                        } else {
                            openEmojiPanel(target.parentElement.parentElement.getAttribute("data-url"), "notebook", {
                                x: rect.left,
                                y: rect.bottom,
                                h: rect.height,
                                w: rect.width,
                            }, undefined, target.querySelector("img"));
                        }
                        break;
                    } else if (isNotCtrl(event) && target.classList.contains("b3-list-item__toggle")) {
                        const liElement = target.parentElement;
                        this.toggleLeaf(liElement, notebookId);
                        event.preventDefault();
                        event.stopPropagation();
                        window.siyuan.menus.menu.remove();
                        break;
                    } else if (target.classList.contains("b3-list-item__switch")) {
                        event.preventDefault();
                        event.stopPropagation();
                        if (target.closest("[data-encrypted=true]")) {
                            break;
                        }
                        const rect = target.getBoundingClientRect();
                        openPublishAccessDialog(target.parentElement.getAttribute("data-type") === "navigation-root" ?
                            notebookId : target.parentElement.getAttribute("data-node-id"), {
                            x: rect.left,
                            y: rect.bottom,
                            h: rect.height,
                            w: rect.width,
                        }, (access) => {
                            target.innerHTML = access.iconHTML;
                            fetchPost("/api/filetree/setPublishAccess", {
                                id: access.id,
                                visible: access.visible,
                                password: access.password,
                                disable: access.disable,
                            });
                        });
                        break;
                    } else if (isNotCtrl(event) && target.classList.contains("b3-list-item__action")) {
                        const type = target.getAttribute("data-type");
                        const pathString = target.parentElement.getAttribute("data-path");
                        if (!window.siyuan.config.readonly) {
                            if (type === "new") {
                                newFileInTree(options.app, notebookId, pathString);
                            } else if (type === "more-root") {
                                toggleMenu({
                                    target: target, build: () => {
                                        const rect = target.getBoundingClientRect();
                                        initNavigationMenu(options.app, target.parentElement).popup({
                                            x: rect.left,
                                            y: rect.bottom,
                                            h: rect.height,
                                        });
                                    }
                                });
                            }
                        }
                        if (type === "more-file") {
                            toggleMenu({
                                target: target, build: () => {
                                    const rect = target.getBoundingClientRect();
                                    initFileMenu(options.app, notebookId, pathString, target.parentElement).popup({
                                        x: rect.left,
                                        y: rect.bottom,
                                        h: rect.height,
                                    });
                                }
                            });
                        }
                        event.preventDefault();
                        event.stopPropagation();
                        break;
                    } else if (event.button === 0 && isNotCtrl(event) && !event.altKey && !event.shiftKey &&
                        target.classList.contains("b3-list-item__text") &&
                        (target.parentElement.getAttribute("data-type") === "navigation-file" ||
                            (target.parentElement.getAttribute("data-type") === "navigation-root" && target.parentElement.getAttribute("data-node-id"))) &&
                        window.siyuan.config.fileTree.parentDocTitleClickMode !== 0 &&
                        Number(target.parentElement.getAttribute("data-count")) > 0) {
                        this.lastSelectedElement = target.parentElement;
                        this.setCurrent(target.parentElement, false);
                        const row = target.parentElement;
                        // 单击展开且不双击打开时立即切换,无需等待双击判定
                        if (window.siyuan.config.fileTree.parentDocTitleClickMode !== 2) {
                            this.toggleLeaf(row, notebookId);
                            event.preventDefault();
                            event.stopPropagation();
                            window.siyuan.menus.menu.remove();
                            break;
                        }
                        this.parentDocClick.click(row, async () => {
                            const expanded = !!row.querySelector(".b3-list-item__arrow--open");
                            const path = row.getAttribute("data-path");
                            const response = expanded ? undefined : await fetchSyncPost("/api/filetree/listDocsByPath", {
                                notebook: notebookId,
                                path,
                                app: Constants.SIYUAN_APPID,
                            });
                            return () => {
                                if (window.siyuan.config.fileTree.parentDocTitleClickMode !== 2 ||
                                    row.getAttribute("data-path") !== path ||
                                    !!row.querySelector(".b3-list-item__arrow--open") !== expanded) { return; }
                                if (expanded) {
                                    this.toggleLeaf(row, notebookId);
                                } else if (response.code === 0) {
                                    toggleFileTree(row, () => this.getOpenPaths(), () => {
                                        this.onLsHTML(response.data);
                                        this.getOpenPaths();
                                    });
                                }
                            };
                        }, () => {
                            openFileById({
                                app: options.app,
                                id: row.getAttribute("data-node-id"),
                                action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                            });
                        });
                        event.preventDefault();
                        event.stopPropagation();
                        window.siyuan.menus.menu.remove();
                        break;
                    } else if (target.tagName === "LI") {
                        this.parentDocClick.cancel();
                        if (isOnlyMeta(event) && !event.altKey && !event.shiftKey) {
                            target.classList.toggle("b3-list-item--focus");
                            this.lastSelectedElement = target;
                        } else if (event.shiftKey && !event.altKey && isNotCtrl(event)) {
                            this.lastSelectedElement = selectFileTreeRange(this.element, this.lastSelectedElement, target);
                        } else {
                            this.lastSelectedElement = target;
                            this.setCurrent(target, false);
                            if (target.getAttribute("data-type") === "navigation-file" ||
                                (target.getAttribute("data-type") === "navigation-root" && target.getAttribute("data-node-id"))) {
                                // 更新最后点击的文档项
                                needFocus = false;
                                if (target.getAttribute("data-opening")) {
                                    return;
                                }
                                target.setAttribute("data-opening", "true");
                                if (event.altKey && isNotCtrl(event) && !event.shiftKey) {
                                    openFileById({
                                        app: options.app,
                                        id: target.getAttribute("data-node-id"),
                                        position: "right",
                                        action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                                        afterOpen() {
                                            target.removeAttribute("data-opening");
                                        }
                                    });
                                } else if (!event.altKey && isOnlyMeta(event) && event.shiftKey) {
                                    openFileById({
                                        app: options.app,
                                        id: target.getAttribute("data-node-id"),
                                        position: "bottom",
                                        action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                                        afterOpen() {
                                            target.removeAttribute("data-opening");
                                        }
                                    });
                                } else if (window.siyuan.config.fileTree.openFilesUseCurrentTab &&
                                    event.altKey && isOnlyMeta(event) && !event.shiftKey) {
                                    openFileById({
                                        app: options.app,
                                        removeCurrentTab: false,
                                        id: target.getAttribute("data-node-id"),
                                        action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                                        afterOpen() {
                                            target.removeAttribute("data-opening");
                                        }
                                    });
                                } else {
                                    openFileById({
                                        app: options.app,
                                        id: target.getAttribute("data-node-id"),
                                        action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                                        afterOpen() {
                                            target.removeAttribute("data-opening");
                                        }
                                    });
                                }
                            } else if (target.getAttribute("data-type") === "navigation-root") {
                                this.toggleLeaf(target, notebookId);
                            }
                        }
                        this.element.querySelector('[select-end="true"]')?.removeAttribute("select-end");
                        this.element.querySelector('[select-start="true"]')?.removeAttribute("select-start");
                        window.siyuan.menus.menu.remove();
                        event.stopPropagation();
                        event.preventDefault();
                        break;
                    }
                    target = target.parentElement;
                }
            }
            if (needFocus) {
                setPanelFocus(this.element.parentElement);
            }
        });
        this.element.addEventListener("dragstart", (event: DragEvent & { target: HTMLElement }) => {
            this.parentDocClick.cancel();
            if (window.siyuan.config.readonly) return;
            window.getSelection().removeAllRanges();
            hideTooltip();
            const liElement = hasClosestByTag(event.target, "LI");
            if (liElement) {
                let selectElements: Element[] = Array.from(this.element.querySelectorAll(".b3-list-item--focus"));
                if (!liElement.classList.contains("b3-list-item--focus")) {
                    selectElements.forEach((item) => {
                        item.classList.remove("b3-list-item--focus");
                    });
                    liElement.classList.add("b3-list-item--focus");
                    selectElements = [liElement];
                }
                if (!isDocTreeDragSelectionAllowed(selectElements)) {
                    event.preventDefault();
                    return;
                }
                this.parent.panelElement.classList.add("sy__file--disablehover");
                let ids = "";
                const ghostElement = document.createElement("ul");
                selectElements.forEach((item: HTMLElement, index) => {
                    ghostElement.append(item.cloneNode(true));
                    item.style.opacity = "0.38";
                    const itemNodeId = item.dataset.nodeId ||
                        item.dataset.path; // 拖拽笔记本时值不能为空,否则 drop 就不会继续排序
                    if (itemNodeId) {
                        ids += itemNodeId;
                        if (index < selectElements.length - 1) {
                            ids += ",";
                        }
                    }
                });
                ghostElement.setAttribute("style", `width: 219px;position: fixed;top:-${selectElements.length * 30}px`);
                ghostElement.setAttribute("class", "b3-list b3-list--background");
                document.body.append(ghostElement);
                setDragTipGhost(ghostElement, 16, 16);
                event.dataTransfer.setDragImage(ghostElement, 16, 16);
                if (window.siyuan.touchDragActive) {
                    // 合成拖拽保留 DOM ghost 供指针跟随。
                    window.siyuan.touchDragGhost = ghostElement;
                } else {
                    setTimeout(() => {
                        ghostElement.remove();
                    });
                }
                event.dataTransfer.setData(Constants.SIYUAN_DROP_FILE, ids);
                if (selectElements.every((item) => item.getAttribute("data-type") === "navigation-file")) {
                    event.dataTransfer.setData(Constants.SIYUAN_DROP_DOCUMENTS, JSON.stringify({
                        ids: ids.split(","),
                    }));
                }
                event.dataTransfer.dropEffect = "move";
                let selectionTitle = "";
                if (selectElements.length > 1) {
                    if (selectElements.every((item) => item.getAttribute("data-type") === "navigation-file")) {
                        selectionTitle = window.siyuan.languages.dragTipSelectedDocs;
                    } else if (selectElements.every((item) => item.getAttribute("data-type") === "navigation-root")) {
                        selectionTitle = window.siyuan.languages.dragTipSelectedNotebooks;
                    }
                    selectionTitle = selectionTitle.replace("${count}", selectElements.length.toString());
                }
                window.siyuan.dragTitle = selectionTitle ||
                    (selectElements[0] as HTMLElement)?.querySelector(".b3-list-item__text")?.textContent?.trim() || "";
                window.siyuan.dragElement = document.createElement("div");
                window.siyuan.dragElement.innerText = ids;
            }
        });
        const dragOverLastObj: {
            element: HTMLElement,
            positionY: number,
            rafId: number,
            sourceOnlyRoot: boolean,
            update?: () => void,
        } = {
            element: null,
            positionY: null,
            rafId: null,
            sourceOnlyRoot: null
        };
        let counter = 0;
        this.element.addEventListener("dragend", (event) => {
            counter = 0;
            if (dragOverLastObj.rafId) {
                cancelAnimationFrame(dragOverLastObj.rafId);
                dragOverLastObj.rafId = null;
            }
            dragOverLastObj.update = undefined;
            dragOverLastObj.element = null;
            dragOverLastObj.positionY = null;
            dragOverLastObj.sourceOnlyRoot = null;
            this.element.querySelectorAll(".dragover, .dragover__bottom, .dragover__top").forEach((item: HTMLElement) => {
                item.classList.remove("dragover", "dragover__bottom", "dragover__top");
            });
            this.parent.panelElement.classList.remove("sy__file--disablehover");
            this.element.querySelectorAll('.b3-list-item[style*="opacity: 0.38;"]').forEach((item: HTMLElement, index) => {
                item.style.opacity = "";
                // https://github.com/siyuan-note/siyuan/issues/11587
                if (index === 0 && hasClosestByClassName(document.elementFromPoint(event.clientX, event.clientY), "sy__file")) {
                    const ariaLabelElement = item.querySelector(".ariaLabel");
                    if (ariaLabelElement) {
                        showTooltip(ariaLabelElement.getAttribute("aria-label"), ariaLabelElement);
                    }
                }
            });
            window.siyuan.dragElement = undefined;
            hideDragTip();
            window.siyuan.dragTitle = "";
            clearDocumentTabMovePreview();
            /// #if !BROWSER
            ipcRenderer.send(Constants.SIYUAN_SEND_WINDOWS, {cmd: "resetTabsStyle", data: "rmDragStyle"});
            /// #else
            document.querySelectorAll(".layout-tab-bars--drag").forEach(item => {
                item.classList.remove("layout-tab-bars--drag");
            });
            /// #endif
        });
        this.element.addEventListener("dragover", (event: DragEvent & { target: HTMLElement }) => {
            const isDocumentTab = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENT_TAB);
            let gutterType = "";
            for (const item of event.dataTransfer.items) {
                if (item.type.startsWith(Constants.SIYUAN_DROP_GUTTER)) {
                    gutterType = item.type;
                }
            }
            const isForeignFileDrag = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_FILE) &&
                !window.siyuan.dragElement;
            if (window.siyuan.config.readonly || (!window.siyuan.dragElement && !gutterType) ||
                (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB) && !isDocumentTab)) {
                if (isForeignFileDrag) {
                    this.element.querySelectorAll(".dragover, .dragover__bottom, .dragover__top").forEach((item) => {
                        item.classList.remove("dragover", "dragover__bottom", "dragover__top");
                    });
                    hideDragTip();
                }
                event.preventDefault();
                return;
            }
            // 标题/列表项等块标源拖到文档树的提示在下方 rAF 回调中根据高亮类判定
            // 其余无法转换的块标源(如段落)不显示提示
            if (gutterType) {
                const gutterTypes = gutterType.replace(Constants.SIYUAN_DROP_GUTTER, "").split(Constants.ZWSP);
                if (!["nodelistitem", "nodeheading"].includes(gutterTypes[0])) {
                    hideDragTip();
                }
            }
            // 文档→文档拖拽的提示在下方 rAF 回调中根据高亮类判定(需等高亮类确定后再显示)
            const updateDragOver = () => {
                const hitElement = event.isTrusted ? event.target :
                    document.elementFromPoint(event.clientX, event.clientY);
                let liElement = hitElement?.closest("li") as HTMLElement;
                if (!liElement) {
                    liElement = document.elementFromPoint(event.clientX, event.clientY - 1)?.closest("li") as HTMLElement;
                }
                if (!liElement || !this.element.contains(liElement)) {
                    dragOverLastObj.element?.classList.remove("dragover", "dragover__bottom", "dragover__top");
                    dragOverLastObj.element = null;
                    dragOverLastObj.positionY = null;
                    hideDragTip();
                    event.preventDefault();
                    return;
                }
                const targetType = liElement.getAttribute("data-type");
                const targetChanged = dragOverLastObj.element !== liElement;
                if (targetChanged) {
                    dragOverLastObj.element?.classList.remove("dragover", "dragover__bottom", "dragover__top");
                    if (gutterType) {
                        // 块标拖拽
                        const gutterTypes = gutterType.replace(Constants.SIYUAN_DROP_GUTTER, "").split(Constants.ZWSP);
                        if (!["nodelistitem", "nodeheading"].includes(gutterTypes[0])) {
                            event.preventDefault();
                            return;
                        }
                    } else if (isDocumentTab && liElement.dataset.nodeId ===
                        window.siyuan.dragElement.dataset.dragDocumentId) {
                        hideDragTip();
                        event.preventDefault();
                        return;
                    } else if (!isDocumentTab && liElement.classList.contains("b3-list-item--focus")) {
                        // 选中的文档不能拖拽到自己上,但允许标题拖拽到文档树的选中文档上 https://github.com/siyuan-note/siyuan/issues/6552
                        hideDragTip();
                        event.preventDefault();
                        return;
                    }

                    dragOverLastObj.sourceOnlyRoot = gutterType || isDocumentTab ? false : true;
                    if (dragOverLastObj.sourceOnlyRoot) {
                        const focusItems = this.element.querySelectorAll(".b3-list-item--focus");
                        for (let i = 0; i < focusItems.length; i++) {
                            if (focusItems[i].getAttribute("data-type") === "navigation-file") {
                                dragOverLastObj.sourceOnlyRoot = false;
                                break;
                            }
                        }
                    }
                    if (dragOverLastObj.sourceOnlyRoot && targetType !== "navigation-root") {
                        hideDragTip();
                        event.preventDefault();
                        return;
                    }
                }
                if (targetChanged || dragOverLastObj.positionY !== event.clientY || !event.isTrusted) {
                    const targetListElement = liElement.parentElement;
                    if (!targetListElement) {
                        hideDragTip();
                        event.preventDefault();
                        return;
                    }
                    if ((dragOverLastObj.sourceOnlyRoot && targetType === "navigation-root" && window.siyuan.config.fileTree.sort === 6) ||
                        (!dragOverLastObj.sourceOnlyRoot && targetType !== "navigation-root" &&
                            (isCustomFileTreeList(targetListElement) || !gutterType))
                    ) {
                        const nodeRect = liElement.getBoundingClientRect();
                        const dragHeight = nodeRect.height * .2;
                        liElement.classList.remove("dragover__top", "dragover__bottom", "dragover");
                        if (targetType === "navigation-root" && dragOverLastObj.sourceOnlyRoot) {
                            if (event.clientY > nodeRect.top + nodeRect.height / 2) {
                                liElement.classList.add("dragover__bottom");
                            } else {
                                liElement.classList.add("dragover__top");
                            }
                        } else if (event.clientY > nodeRect.bottom - dragHeight) {
                            liElement.classList.add("dragover__bottom");
                        } else if (event.clientY < nodeRect.top + dragHeight) {
                            liElement.classList.add("dragover__top");
                        }
                    }
                    if (liElement.classList.contains("dragover__top") || liElement.classList.contains("dragover__bottom") ||
                        (targetType === "navigation-root" && dragOverLastObj.sourceOnlyRoot)) {
                        // do nothing
                    } else {
                        liElement.classList.add("dragover");
                    }
                }
                if (targetChanged) {
                    dragOverLastObj.element = liElement;
                }
                dragOverLastObj.positionY = event.clientY;
                // 文档→文档拖拽:依据当前高亮类显示对应操作提示(带目标文档名)
                if (!gutterType) {
                    const name = liElement.querySelector(".b3-list-item__text")?.textContent || "";
                    const title = window.siyuan.dragTitle || "";
                    if (liElement.classList.contains("dragover__top")) {
                        showDragTip(title, window.siyuan.languages.dragTipMoveBefore, event.clientX, event.clientY, name);
                    } else if (liElement.classList.contains("dragover__bottom")) {
                        showDragTip(title, window.siyuan.languages.dragTipMoveAfter, event.clientX, event.clientY, name);
                    } else if (liElement.classList.contains("dragover")) {
                        showDragTip(title, window.siyuan.languages.dragTipMoveChild, event.clientX, event.clientY, name);
                    } else {
                        hideDragTip();
                    }
                } else {
                    // 块标(标题/列表项)→文档树:结合“转换为文档”和位置(带目标文档名)
                    const gutterTypes = gutterType.replace(Constants.SIYUAN_DROP_GUTTER, "").split(Constants.ZWSP);
                    if (["nodelistitem", "nodeheading"].includes(gutterTypes[0])) {
                        const name = liElement.querySelector(".b3-list-item__text")?.textContent || "";
                        const title = window.siyuan.dragTitle || "";
                        let action: string;
                        if (liElement.classList.contains("dragover__top")) {
                            action = window.siyuan.languages.dragTip2DocBefore;
                        } else if (liElement.classList.contains("dragover__bottom")) {
                            action = window.siyuan.languages.dragTip2DocAfter;
                        } else {
                            action = window.siyuan.languages.dragTip2DocChild;
                        }
                        showDragTip(title, action, event.clientX, event.clientY, name);
                    }
                }
                event.preventDefault();
                event.dataTransfer.dropEffect = "move";
            };
            dragOverLastObj.update = updateDragOver;
            if (!dragOverLastObj.rafId) {
                dragOverLastObj.rafId = requestAnimationFrame(() => {
                    dragOverLastObj.rafId = null;
                    const update = dragOverLastObj.update;
                    dragOverLastObj.update = undefined;
                    update?.();
                });
            }
            event.preventDefault();
        });
        this.element.addEventListener("dragleave", () => {
            counter--;
            if (counter <= 0) {
                counter = 0;
                if (dragOverLastObj.rafId) {
                    cancelAnimationFrame(dragOverLastObj.rafId);
                    dragOverLastObj.rafId = null;
                }
                dragOverLastObj.update = undefined;
                dragOverLastObj.element = null;
                dragOverLastObj.positionY = null;
                dragOverLastObj.sourceOnlyRoot = null;
                this.element.querySelectorAll(".dragover, .dragover__bottom, .dragover__top").forEach((item: HTMLElement) => {
                    item.classList.remove("dragover", "dragover__bottom", "dragover__top");
                });
                hideDragTip();
            }
        });
        this.element.addEventListener("dragenter", (event: DragEvent) => {
            event.preventDefault();
            if (!event.isTrusted) {
                // 合成拖拽滚动后会重新命中节点,不依赖已被移除节点的 dragleave 来平衡计数。
                counter = 0;
            }
            counter++;
        });
        this.element.addEventListener("drop", async (event: DragEvent & { target: HTMLElement }) => {
            counter = 0;
            if (dragOverLastObj.rafId) {
                cancelAnimationFrame(dragOverLastObj.rafId);
                dragOverLastObj.rafId = null;
            }
            const updateDragOver = dragOverLastObj.update;
            dragOverLastObj.update = undefined;
            updateDragOver?.();
            hideDragTip();
            window.siyuan.dragTitle = "";
            if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_FILE) && !window.siyuan.dragElement) {
                this.element.querySelectorAll(".dragover, .dragover__bottom, .dragover__top").forEach((item) => {
                    item.classList.remove("dragover", "dragover__bottom", "dragover__top");
                });
                return;
            }
            const documentTabData = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENT_TAB) ?
                parseDocumentTabDragData(event.dataTransfer.getData(Constants.SIYUAN_DROP_DOCUMENT_TAB)) : undefined;
            const sourceTab = documentTabData ? getInstanceById(documentTabData.tabId) as Tab : undefined;
            sourceTab?.restoreHeadElementOrder();
            const newElement = this.element.querySelector<HTMLElement>(".dragover, .dragover__bottom, .dragover__top");
            if (!newElement) {
                return;
            }
            const newUlElement = hasTopClosestByTag(newElement, "UL");
            if (!newUlElement) {
                return;
            }
            const oldScrollTop = this.element.scrollTop;
            const toURL = newUlElement.getAttribute("data-url");
            const toPath = newElement.getAttribute("data-path");
            if (documentTabData) {
                event.preventDefault();
                event.stopPropagation();
                window.siyuan.dragElement = undefined;
                await this.dropDocumentTab(documentTabData, newElement, newUlElement, oldScrollTop);
                return;
            }
            let gutterType = "";
            for (const item of event.dataTransfer.items) {
                if (item.type.startsWith(Constants.SIYUAN_DROP_GUTTER)) {
                    gutterType = item.type;
                }
            }
            // 块标拖拽
            if (gutterType) {
                const gutterTypes = gutterType.replace(Constants.SIYUAN_DROP_GUTTER, "").split(Constants.ZWSP);
                if (["nodelistitem", "nodeheading"].includes(gutterTypes[0])) {
                    const sourceNotebookId = window.siyuan.dragElement?.closest("[data-notebook-id]")?.getAttribute("data-notebook-id") ||
                        parseBlockDragData(event.dataTransfer.getData(gutterType)).notebookID;
                    if (!isMoveTargetAllowed([sourceNotebookId], toURL)) {
                        showMessage(window.siyuan.languages._kernel[391]);
                        newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                        window.siyuan.dragElement = undefined;
                        return;
                    }
                    const toDocOptions: {
                        targetNoteBook: string;
                        toTop?: boolean;
                        targetPath?: string;
                        previousPath?: string;
                    } = {
                        targetNoteBook: toURL,
                    };
                    if (newElement.classList.contains("dragover")) {
                        toDocOptions.targetPath = toPath;
                    } else if (newElement.classList.contains("dragover__bottom")) {
                        toDocOptions.previousPath = toPath;
                    } else if (newElement.classList.contains("dragover__top")) {
                        if (newElement.previousElementSibling) {
                            toDocOptions.previousPath = newElement.previousElementSibling.getAttribute("data-path");
                        } else {
                            // 拖到第一个子文档上方,作为父文档的第一个子文档
                            const parentLi = newElement.parentElement.previousElementSibling as HTMLElement;
                            toDocOptions.targetPath = parentLi.getAttribute("data-path");
                            toDocOptions.toTop = true;
                        }
                    }
                    if (gutterTypes[0] === "nodeheading") {
                        fetchPost("/api/filetree/heading2Doc", {...toDocOptions, srcHeadingID: gutterTypes[2].split(",")[0]});
                    } else {
                        fetchPost("/api/filetree/li2Doc", {...toDocOptions, srcListItemID: gutterTypes[2].split(",")[0]});
                    }
                }
                newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                window.siyuan.dragElement = undefined;
                return;
            }
            window.siyuan.dragElement = undefined;
            if (!event.dataTransfer.getData(Constants.SIYUAN_DROP_FILE)) {
                newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                return;
            }
            const selectRootElements: HTMLElement[] = [];
            const selectFileElements: HTMLElement[] = [];
            const fromPaths: string[] = [];
            let invalidMoveTarget = false;
            this.element.querySelectorAll(".b3-list-item--focus").forEach((item: HTMLElement) => {
                if (item.getAttribute("data-type") === "navigation-root") {
                    selectRootElements.push(item);
                } else {
                    const dataPath = item.getAttribute("data-path");
                    const isChild = fromPaths.find(itemPath => {
                        if (dataPath.startsWith(itemPath.replace(".sy", ""))) {
                            return true;
                        }
                    });
                    if (!isChild) {
                        // 禁止父节点移动到子节点 https://github.com/siyuan-note/siyuan/issues/12539
                        if (newElement.getAttribute("data-path").startsWith(item.dataset.path.replace(".sy", ""))) {
                            invalidMoveTarget = true;
                            return;
                        }
                        selectFileElements.push(item);
                        fromPaths.push(dataPath);
                    }
                }
            });
            if (invalidMoveTarget) {
                showMessage(window.siyuan.languages._kernel[87], 7000, "error");
                newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                return;
            }
            if (newElement.classList.contains("dragover")) {
                const sourceNotebookIds = selectFileElements.map((item) =>
                    item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
                if (!isMoveTargetAllowed(sourceNotebookIds, toURL)) {
                    showMessage(window.siyuan.languages._kernel[391]);
                    newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                    return;
                }
                fetchPost("/api/filetree/moveDocs", {
                    toNotebook: toURL,
                    fromPaths,
                    toPath,
                });
                newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                return;
            }
            if (newElement.classList.contains("dragover__bottom") || newElement.classList.contains("dragover__top")) {
                const targetListElement = newElement.parentElement;
                if (window.siyuan.config.fileTree.sort === 6 && selectRootElements.length > 0 &&
                    newElement.getAttribute("data-path") === "/") {
                    const sourceIDs = selectRootElements.map(item => item.parentElement.getAttribute("data-url"));
                    if (sourceIDs.includes(toURL)) {
                        newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                        return;
                    }
                    if (newElement.classList.contains("dragover__top")) {
                        selectRootElements.forEach(item => {
                            newElement.parentElement.before(item.parentElement);
                        });
                    } else {
                        selectRootElements.reverse().forEach(item => {
                            newElement.parentElement.after(item.parentElement);
                        });
                    }
                    fetchPost("/api/notebook/reorder", getRelativeReorderRequest(
                        sourceIDs,
                        toURL,
                        !newElement.classList.contains("dragover__top")
                    ));
                } else if (!isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
                    const after = newElement.classList.contains("dragover__bottom");
                    newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                    const sourceNotebookIds = selectFileElements.map(item =>
                        item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
                    if (!isMoveTargetAllowed(sourceNotebookIds, toURL)) {
                        showMessage(window.siyuan.languages._kernel[391]);
                        return;
                    }
                    await this.reorderSortedDocuments(selectFileElements.map(item => item.getAttribute("data-node-id")),
                        newElement.getAttribute("data-node-id"), after, oldScrollTop);
                } else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
                    const toDir = pathPosix().dirname(toPath);
                    const newElementClassList = newElement.getAttribute("class");
                    const sourceNotebookIds = selectFileElements.map((item) =>
                        item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
                    if (!isMoveTargetAllowed(sourceNotebookIds, toURL)) {
                        showMessage(window.siyuan.languages._kernel[391]);
                        newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                        return;
                    }
                    const siblingPaths: string[] = [];
                    Array.from(newElement.parentElement.children).forEach(item => {
                        const itemPath = item.getAttribute("data-path");
                        if (item.tagName === "LI" && itemPath) {
                            siblingPaths.push(itemPath);
                        }
                    });
                    const newPaths = selectFileElements.map((item) =>
                        pathPosix().join(toDir, item.getAttribute("data-node-id") + ".sy"));
                    const sortedPaths = insertDocumentsSortPaths(
                        siblingPaths,
                        newPaths,
                        toPath,
                        newElementClassList.includes("dragover__bottom")
                    );
                    if (!sortedPaths || (sortedPaths.length === siblingPaths.length &&
                        sortedPaths.every((itemPath, index) => itemPath === siblingPaths[index]))) {
                        newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                        return;
                    }
                    const moveResponse = await fetchSyncPost("/api/filetree/moveDocs", {
                        toNotebook: toURL,
                        fromPaths,
                        toPath: toDir === "/" ? "/" : toDir + ".sy",
                        callback: Constants.CB_MOVE_NOLIST,
                    });
                    if (moveResponse.code !== 0) {
                        newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                        return;
                    }
                    selectFileElements.forEach((item, index) => {
                        const fromPath = item.getAttribute("data-path");
                        updateMovedSubtree(item, getFileTreeChildList(item), fromPath, newPaths[index]);
                    });
                    if (newElementClassList.includes("dragover__top")) {
                        selectFileElements.forEach(item => {
                            let nextULElement;
                            if (item.nextElementSibling && item.nextElementSibling.tagName === "UL") {
                                nextULElement = item.nextElementSibling;
                            }
                            newElement.before(item);
                            if (nextULElement) {
                                item.after(nextULElement);
                            }
                        });
                    } else if (newElementClassList.includes("dragover__bottom")) {
                        [...selectFileElements].reverse().forEach(item => {
                            let nextULElement;
                            if (item.nextElementSibling && item.nextElementSibling.tagName === "UL") {
                                nextULElement = item.nextElementSibling;
                            }
                            if (newElement.nextElementSibling && newElement.nextElementSibling.tagName === "UL") {
                                newElement.nextElementSibling.after(item);
                            } else {
                                newElement.after(item);
                            }
                            if (nextULElement) {
                                item.after(nextULElement);
                            }
                        });
                    }
                    const sortResponse = await fetchSyncPost("/api/filetree/reorderDocs", getRelativeReorderRequest(
                        selectFileElements.map(item => item.getAttribute("data-node-id")),
                        newElement.getAttribute("data-node-id"),
                        !newElementClassList.includes("dragover__top")
                    ));
                    if (sortResponse.code !== 0) {
                        newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
                        return;
                    }
                    const listResponse = await fetchSyncPost("/api/filetree/listDocsByPath", {
                        notebook: toURL,
                        path: toDir === "/" ? "/" : toDir + ".sy",
                        app: Constants.SIYUAN_APPID,
                    });
                    if (listResponse.code === 0 && listResponse.data?.files) {
                        if (listResponse.data.path === "/" && listResponse.data.files.length === 0) {
                            showMessage(window.siyuan.languages.emptyContent);
                        } else {
                            this.onLsHTML(listResponse.data, oldScrollTop);
                        }
                    }
                }
            }
            newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
        });
        this.init();
    }

    private async reorderSortedDocuments(sourceIDs: string[], targetID: string, after: boolean, scrollTop: number) {
        const result = await reorderSortedFileTree(sourceIDs, targetID, after);
        if (!result) {
            return;
        }
        const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
            notebook: result.notebook,
            path: result.parentPath,
            app: Constants.SIYUAN_APPID,
        });
        if (response.code === 0 && response.data?.files) {
            this.onLsHTML(response.data, scrollTop);
        }
    }

    private async dropDocumentTab(
        documentTabData: IDocumentTabDragData,
        targetElement: HTMLElement,
        notebookElement: HTMLElement,
        oldScrollTop: number
    ) {
        const moveAsChild = targetElement.classList.contains("dragover");
        const insertAfter = targetElement.classList.contains("dragover__bottom");
        const insertBefore = targetElement.classList.contains("dragover__top");
        const targetNotebook = notebookElement.getAttribute("data-url");
        const targetPath = targetElement.getAttribute("data-path");
        targetElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
        if (!targetNotebook || !targetPath || (!moveAsChild && !insertAfter && !insertBefore)) {
            return;
        }

        const pathResponse = await fetchSyncPost("/api/filetree/getPathByID", {id: documentTabData.rootId});
        if (pathResponse.code !== 0 || !pathResponse.data?.path || !pathResponse.data?.notebook) {
            return;
        }
        const sourcePath = pathResponse.data.path as string;
        const sourceNotebook = pathResponse.data.notebook as string;
        if (!isMoveTargetAllowed([sourceNotebook], targetNotebook)) {
            showMessage(window.siyuan.languages._kernel[391]);
            return;
        }
        if (sourceNotebook === targetNotebook) {
            const sourceDirectory = sourcePath.endsWith(".sy") ? sourcePath.slice(0, -3) : sourcePath;
            if (targetPath === sourcePath || targetPath.startsWith(sourceDirectory + "/")) {
                return;
            }
        }

        if (moveAsChild) {
            const sourceParentDirectory = pathPosix().dirname(sourcePath);
            const sourceParentPath = sourceParentDirectory === "/" ? "/" : sourceParentDirectory + ".sy";
            if (sourceNotebook === targetNotebook && sourceParentPath === targetPath) {
                return;
            }
            await fetchSyncPost("/api/filetree/moveDocs", {
                toNotebook: targetNotebook,
                fromPaths: [sourcePath],
                toPath: targetPath,
            });
            return;
        }

        if (!isCustomFileTreeList(targetElement.parentElement)) {
            await this.reorderSortedDocuments([documentTabData.rootId], targetElement.getAttribute("data-node-id"),
                insertAfter, oldScrollTop);
            return;
        }
        const targetDirectory = pathPosix().dirname(targetPath);
        const newPath = pathPosix().join(targetDirectory, documentTabData.rootId + ".sy");
        const siblingPaths: string[] = [];
        Array.from(targetElement.parentElement.children).forEach((item) => {
            const path = item.getAttribute("data-path");
            if (item.tagName === "LI" && path) {
                siblingPaths.push(path);
            }
        });
        const sortedPaths = insertDocumentSortPath(
            siblingPaths,
            documentTabData.rootId,
            newPath,
            targetPath,
            insertAfter
        );
        if (!sortedPaths || (sortedPaths.length === siblingPaths.length &&
            sortedPaths.every((path, index) => path === siblingPaths[index]))) {
            return;
        }
        const targetParentPath = targetDirectory === "/" ? "/" : targetDirectory + ".sy";
        const moveResponse = await fetchSyncPost("/api/filetree/moveDocs", {
            toNotebook: targetNotebook,
            fromPaths: [sourcePath],
            toPath: targetParentPath,
            callback: Constants.CB_MOVE_NOLIST,
        });
        if (moveResponse.code !== 0) {
            return;
        }
        const sortResponse = await fetchSyncPost("/api/filetree/reorderDocs", getRelativeReorderRequest(
            [documentTabData.rootId],
            targetElement.getAttribute("data-node-id"),
            insertAfter
        ));
        if (sortResponse.code !== 0) {
            return;
        }
        const listResponse = await fetchSyncPost("/api/filetree/listDocsByPath", {
            notebook: targetNotebook,
            path: targetParentPath,
            app: Constants.SIYUAN_APPID,
        });
        if (listResponse.code === 0 && listResponse.data?.files?.length > 0) {
            this.onLsHTML(listResponse.data, oldScrollTop);
        }
    }

    private handleMsgCallback(data: IWebSocketData) {
        if (data) { this.pinnedDocs?.onFileTreeMessage(data); }
        if (data) {
            switch (data.cmd) {
                case "reloadDocInfo":
                    this.updateDocInfo(data);
                    break;
                case "moveDocs":
                    this.onMove(data);
                    break;
                case "reloadFiletree":
                    setNoteBook(() => {
                        this.init(false);
                    });
                    break;
                case "boxDocFeatureChanged":
                    setNoteBook(() => {
                        this.updateBoxDocFeature();
                    });
                    break;
                case "notebookIconChanged":
                    this.updateNotebookIcon(data.data);
                    break;
                case "reloadNotebookInfo":
                    window.clearTimeout(this.reloadNotebookInfoTimeout);
                    this.reloadNotebookInfoTimeout = window.setTimeout(() => {
                        setNoteBook((notebooks) => {
                            notebooks.forEach((notebook) => {
                                const liElement = this.element.querySelector<HTMLElement>(
                                    `ul[data-url="${notebook.id}"] > li[data-type="navigation-root"]`
                                );
                                if (liElement) {
                                    this.updateSubFileCount(liElement, notebook.subFileCount);
                                }
                            });
                        });
                    }, 128);
                    break;
                case "mount":
                    this.onMount(data);
                    emitToPlugins("opened-notebook", data);
                    break;
                case "createnotebook":
                    setNoteBook((notebooks) => {
                        let previousId: string;
                        notebooks.find(item => {
                            if (!item.closed) {
                                if (item.id === data.data.box.id) {
                                    if (previousId) {
                                        this.element.querySelector(`.b3-list[data-url="${previousId}"]`).insertAdjacentHTML("afterend", this.genNotebook(item));
                                    } else {
                                        this.element.insertAdjacentHTML("afterbegin", this.genNotebook(item));
                                    }
                                    return true;
                                }
                                previousId = item.id;
                            }
                        });
                    });
                    break;
                case "closeBox":
                case "removeBox":
                    this.onRemove(data);
                    emitToPlugins("closed-notebook", data);
                    break;
                case "removeDoc":
                    this.onRemove(data);
                    break;
                case "create":
                    if (data.data.listDocTree) {
                        this.selectItem(data.data.box.id, data.data.path);
                    } else {
                        this.updateItemArrow(data.data.box.id, data.data.path);
                    }
                    break;
                case "heading2doc":
                    this.updateItemArrow(data.data.box.id, data.data.path);
                    break;
                case "createdailynote":
                case "li2doc":
                    this.selectItem(data.data.box.id, data.data.path);
                    break;
                case "renamenotebook": {
                    const name = data.data.name;
                    if (typeof name !== "string") {
                        break;
                    }
                    const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.box);
                    if (notebook) {
                        notebook.name = name;
                    }
                    const textElement = this.element.querySelector(`[data-url="${data.data.box}"] .b3-list-item__text`) ||
                        this.closeElement.querySelector(`[data-url="${data.data.box}"] .b3-list-item__text`);
                    if (textElement) {
                        textElement.textContent = name;
                    }
                    break;
                }
                case "rename":
                    this.onRename(data.data);
                    break;
            }
        }
    }

    private updateDocInfo(data: IWebSocketData) {
        const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.rootID);
        const subFileCount = notebook && window.siyuan.isPublish ? notebook.subFileCount : data.data.subFileCount;
        if (notebook) {
            notebook.subFileCount = subFileCount;
        }
        const liElement = this.element.querySelector(
            `li[data-node-id="${data.data.rootID}"][data-type="navigation-file"], ` +
            `li[data-node-id="${data.data.rootID}"][data-type="navigation-root"]`
        );
        if (liElement) {
            if (liElement.getAttribute("data-type") === "navigation-file") {
                liElement.querySelector(".b3-list-item__text.ariaLabel")?.setAttribute("aria-label", genFileTreeDocAriaLabel(data.data));
            }
            this.updateSubFileCount(liElement as HTMLElement, subFileCount);
        }
    }

    private updateSubFileCount(liElement: HTMLElement, subFileCount: number) {
        liElement.setAttribute("data-count", subFileCount.toString());
        if (subFileCount === 0) {
            liElement.querySelector(".b3-list-item__toggle")?.classList.add("fn__hidden");
            liElement.querySelector(".b3-list-item__arrow")?.classList.remove("b3-list-item__arrow--open");
            if (liElement.nextElementSibling?.tagName === "UL") {
                liElement.nextElementSibling.remove();
            }
        } else {
            liElement.querySelector(".b3-list-item__toggle")?.classList.remove("fn__hidden");
        }
        syncFileTreeItemDefaultIcon(liElement);
        this.updateDocActionElement(liElement);
    }

    private updateDocActionElement(liElement: HTMLElement) {
        const iconElement = liElement.querySelector<HTMLElement>(".b3-list-item__icon");
        if (!iconElement) {
            return;
        }
        const isFile = liElement.getAttribute("data-type") === "navigation-file";
        const hasChildren = Number(liElement.getAttribute("data-count")) > 0;
        // 单击文档图标展开或折叠下级,笔记本图标不参与
        const iconClickExpands = isFile && window.siyuan.config.fileTree.docIconClickMode === 1;
        const iconExpands = iconClickExpands && hasChildren;
        const iconOpens = iconClickExpands && !hasChildren;
        const editingPublishAccess = this.element.classList.contains("file-tree__publish-access--active");
        // 点击会修改图标时给出提示,展开或打开时不提示
        iconElement.classList.toggle("ariaLabel", !iconClickExpands);
        if (iconClickExpands) {
            iconElement.removeAttribute("aria-label");
        } else {
            iconElement.setAttribute("aria-label", window.siyuan.languages.changeIcon);
        }
        liElement.classList.toggle("file-tree__item--icon-expand", iconExpands && !editingPublishAccess);
        liElement.classList.toggle("file-tree__item--icon-open", iconOpens && !editingPublishAccess);
        liElement.classList.toggle("file-tree__item--title-expand", hasChildren &&
            window.siyuan.config.fileTree.parentDocTitleClickMode !== 0);
    }

    public updateDocActions() {
        this.pinnedDocs?.updateDocActions();
        this.element.querySelectorAll<HTMLElement>(
            'li[data-type="navigation-file"], li[data-type="navigation-root"]'
        ).forEach((item) => {
            this.updateDocActionElement(item);
        });
    }

    private updateBoxDocFeature() {
        const enabled = window.siyuan.config.fileTree.boxDocEnabled;
        window.siyuan.notebooks.forEach((notebook) => {
            if (notebook.closed) {
                return;
            }
            const notebookElement = this.element.querySelector<HTMLElement>(`:scope > ul[data-url="${notebook.id}"]`);
            const rootElement = notebookElement?.querySelector<HTMLElement>(":scope > li[data-type=\"navigation-root\"]");
            if (!notebookElement || !rootElement) {
                return;
            }

            updateNotebookRootForBoxDoc(rootElement, notebook, enabled);
            const iconElement = rootElement.querySelector<HTMLElement>(".b3-list-item__icon");
            iconElement?.classList.toggle("popover__block", enabled);
            if (enabled) {
                iconElement?.setAttribute("data-id", notebook.id);
            } else {
                iconElement?.removeAttribute("data-id");
            }
            this.updateDocActionElement(rootElement);
            this.element.append(notebookElement);
        });
    }

    private updateItemArrow(notebookId: string, filePath: string) {
        const treeElement = this.element.querySelector(`[data-url="${notebookId}"]`);
        if (!treeElement) {
            return;
        }
        let currentPath = filePath;
        let liElement;
        while (!liElement) {
            // 新文档只影响父级的子文档状态,从父路径开始查找。
            const dirname = pathPosix().dirname(currentPath);
            if (dirname === "/") {
                const rootElement = treeElement.firstElementChild as HTMLElement;
                if (rootElement.querySelector(".b3-list-item__arrow--open")) {
                    this.getLeaf(rootElement, notebookId, true);
                }
                break;
            }
            currentPath = dirname + ".sy";
            liElement = treeElement.querySelector(`[data-path="${currentPath}"]`);
            if (liElement) {
                const hiddenElement = liElement.querySelector(".fn__hidden");
                if (hiddenElement) {
                    // 原先无子文档:显示展开箭头
                    hiddenElement.classList.remove("fn__hidden");
                    syncFileTreeItemDefaultIcon(liElement as HTMLElement);
                } else if (liElement.querySelector(".b3-list-item__arrow--open")) {
                    // 父文档已展开:刷新子列表
                    this.getLeaf(liElement, notebookId, true);
                }
                break;
            }
        }
    }

    private updateNotebookIcon(data: { boxID: string, icon: string }) {
        if (!data || typeof data.boxID !== "string" || typeof data.icon !== "string") {
            return;
        }
        const notebook = window.siyuan.notebooks.find((item) => item.id === data.boxID);
        if (!notebook) {
            return;
        }
        notebook.icon = data.icon;
        if (notebook.encrypted && notebook.closed) {
            return;
        }
        const liElement = notebook.closed ?
            this.closeElement.querySelector<HTMLElement>(`li[data-url="${data.boxID}"]`) :
            this.element.querySelector<HTMLElement>(
                `ul[data-url="${data.boxID}"] > li[data-type="navigation-root"]`
            );
        if (liElement) {
            updateFileTreeItemIcon(liElement, data.icon, "notebook");
        }
    }

    private genNotebook(item: INotebook) {
        const editingPublishAccess = this.element.classList.contains("file-tree__publish-access--active");
        const locked = item.encrypted && item.closed;
        const iconContent = locked
            ? getFileTreeIconHTML("", "lock")
            : getFileTreeIconHTML(item.icon, "notebook");
        const defaultIconAttr = getFileTreeDefaultIconAttr(locked ? "" : item.icon, locked ? "lock" : "notebook");
        const isBoxDoc = !item.closed && window.siyuan.config.fileTree.boxDocEnabled;
        const hasChildren = !item.closed && item.subFileCount > 0;
        // 笔记本图标始终用于修改图标
        const actionClasses = `${hasChildren && window.siyuan.config.fileTree.parentDocTitleClickMode !== 0 ?
            " file-tree__item--title-expand" : ""}`;
        const emojiHTML = `<span class="b3-list-item__icon ariaLabel${isBoxDoc ? " popover__block" : ""}${editingPublishAccess && !item.encrypted ? " fn__none" : ""}" data-position="8east"${isBoxDoc ? ` data-id="${item.id}"` : ""} aria-label="${window.siyuan.languages.changeIcon}">${iconContent}</span>`;
        const switchHTML = `<span class="b3-list-item__switch b3-tooltips b3-tooltips__e${editingPublishAccess && !item.encrypted ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>`;
        if (item.closed) {
            return `<li data-url="${item.id}" class="b3-list-item b3-list-item--hide-action"${item.encrypted ? ' data-encrypted="true"' : ""}${defaultIconAttr}>
    <span class="b3-list-item__toggle fn__hidden">
        <svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
    </span>
    ${emojiHTML}
    ${switchHTML}
    <span class="b3-list-item__text" style="cursor: default;">${escapeHtml(item.name)}</span>
    <span data-type="open" data-url="${item.id}" class="b3-list-item__action b3-tooltips b3-tooltips__w${(window.siyuan.config.readonly) ? " fn__none" : ""}" aria-label="${window.siyuan.languages.openBy}">
        <svg><use xlink:href="#iconOpen"></use></svg>
    </span>
</li>`;
        } else {
            return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sort="${item.sort}" data-sortmode="${item.sortMode}"${item.encrypted ? " data-encrypted=\"true\"" : ""}>
<li class="b3-list-item b3-list-item--hide-action${actionClasses}" ${window.siyuan.config.fileTree.sort === 6 ? 'draggable="true"' : ""}
style="--file-toggle-width:22px;--file-action-offset:22px"
data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? item.id : ""}"${defaultIconAttr}>
    <span class="b3-list-item__toggle b3-list-item__toggle--hl${isBoxDoc && !hasChildren ? " fn__hidden" : ""}">
        <svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
    </span>
    ${emojiHTML}
    ${switchHTML}
    <span class="b3-list-item__text ariaLabel" data-position="parentE">${escapeHtml(item.name)}</span>
    <span data-type="more-root" data-menu="true" class="b3-list-item__action b3-tooltips b3-tooltips__w${(window.siyuan.config.readonly) ? " fn__none" : ""}" aria-label="${window.siyuan.languages.more}">
        <svg><use xlink:href="#iconMore"></use></svg>
    </span>
    <span data-type="new" class="b3-list-item__action b3-tooltips b3-tooltips__w${(window.siyuan.config.readonly) ? " fn__none" : ""}" aria-label="${window.siyuan.languages.newSubDoc}">
        <svg><use xlink:href="#iconAdd"></use></svg>
    </span>
</li></ul>`;
        }
    }

    public init(init = true) {
        this.pinnedDocs?.scheduleRefresh();
        let html = "";
        let closeHtml = "";
        let closeCounter = 0;
        const scrollTop = this.element.scrollTop;
        window.siyuan.notebooks.forEach((item) => {
            if (item.closed) {
                closeCounter++;
                closeHtml += this.genNotebook(item);
            } else {
                html += this.genNotebook(item);
            }
        });
        this.element.innerHTML = html;
        this.closeElement.lastElementChild.innerHTML = closeHtml;
        const counterElement = this.closeElement.querySelector(".counter");
        counterElement.textContent = closeCounter.toString();
        if (closeCounter) {
            this.closeElement.classList.remove("fn__none");
        } else {
            this.closeElement.classList.add("fn__none");
        }
        const firstNotebook = this.element.firstElementChild;
        void restoreFileTreePaths(window.siyuan.storage[Constants.LOCAL_FILESPATHS], async (notebookId, path) => {
            if (this.element.firstElementChild !== firstNotebook) {
                return;
            }
            const liElement = this.element.querySelector(`ul[data-url="${notebookId}"] li[data-path="${path}"]`);
            if (!liElement || liElement.querySelector(".b3-list-item__arrow--open")) {
                return;
            }
            const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
                notebook: notebookId,
                path,
                app: Constants.SIYUAN_APPID,
            });
            if (response.code !== 0 || !response.data || !this.element.contains(liElement) ||
                liElement.querySelector(".b3-list-item__arrow--open")) {
                return;
            }
            await this.onLsSelect(response.data, path, false, false);
        }).then(() => {
            if (this.element.firstElementChild === firstNotebook) {
                this.refreshPublishAccessSwitch();
                this.element.scrollTop = scrollTop;
            }
        });
        this.refreshPublishAccessSwitch();
        if (!init) {
            return;
        }
        const svgElement = this.closeElement.querySelector("svg");
        if (html !== "") {
            this.closeElement.style.height = "30px";
            svgElement.classList.remove("b3-list-item__arrow--open");
            this.closeElement.lastElementChild.classList.add("fn__none");
        } else {
            this.closeElement.style.height = "40%";
            svgElement.classList.add("b3-list-item__arrow--open");
            this.closeElement.lastElementChild.classList.remove("fn__none");
        }
    }

    private onRemove(data: IWebSocketData) {
        removeFileTreeItems({
            element: this.element,
            closeElement: this.closeElement,
            genNotebook: (notebook) => this.genNotebook(notebook),
            updateDocActionElement: (element) => this.updateDocActionElement(element),
        }, data);
    }

    private onMount(data: IWebSocketData) {
        if (data.data.existed) {
            return;
        }
        const liElement = this.closeElement.querySelector(`li[data-url="${data.data.box.id}"]`) as HTMLElement;
        if (liElement) {
            const counterElement = this.closeElement.querySelector(".counter");
            counterElement.textContent = (parseInt(counterElement.textContent) - 1).toString();
            if (counterElement.textContent === "0") {
                this.closeElement.classList.add("fn__none");
            }
            liElement.remove();
        }
        setNoteBook((notebooks: INotebook[]) => {
            const notebook = notebooks.find((item) => item.id === data.data.box.id) || data.data.box;
            const html = this.genNotebook(notebook);
            if (this.element.childElementCount === 0) {
                this.element.innerHTML = html;
            } else {
                let previousId;
                notebooks.find((item, index) => {
                    if (item.id === data.data.box.id) {
                        while (index > 0) {
                            if (!notebooks[index - 1].closed) {
                                previousId = notebooks[index - 1].id;
                                break;
                            } else {
                                index--;
                            }
                        }
                        return true;
                    }
                });
                if (previousId) {
                    this.element.querySelector(`[data-url="${previousId}"]`).insertAdjacentHTML("afterend", html);
                } else {
                    this.element.insertAdjacentHTML("afterbegin", html);
                }
            }
        });
    }

    public onRename(data: { path: string, title: string, box: string }) {
        const fileItemElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${data.path}"]`);
        if (fileItemElement) {
            fileItemElement.setAttribute("data-name", data.title);
            fileItemElement.querySelector(".b3-list-item__text").innerHTML = escapeHtml(data.title);
        }
        const parentPath = pathPosix().dirname(data.path);
        const listPath = parentPath === "/" ? "/" : `${parentPath}.sy`;
        const parentElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${listPath}"]`);
        const listElement = parentElement?.nextElementSibling;
        if (listElement?.tagName === "UL" && !isCustomFileTreeList(listElement)) {
            this.onFiletreeSortChanged({notebook: data.box, parentPath});
        }
    }

    public onFiletreeSortChanged(data: { notebook: string, parentPath: string }) {
        const notebookElement = this.element.querySelector(`ul[data-url="${data.notebook}"]`);
        if (!notebookElement) {
            return;
        }
        const listPath = data.parentPath === "/" ? "/" : `${data.parentPath}.sy`;
        const liElement = notebookElement.querySelector(`li[data-path="${listPath}"]`);
        const listElement = liElement?.nextElementSibling;
        if (!listElement || listElement.tagName !== "UL") {
            return;
        }
        fetchPost("/api/filetree/listDocsByPath", {
            notebook: data.notebook,
            path: listPath,
            app: Constants.SIYUAN_APPID,
        }, response => {
            this.onLsHTML(response.data);
        });
    }

    public onDocsImported(data: { notebook: string, parentPath: string, rootIDs: string[] }) {
        const rootID = data.rootIDs?.[0];
        if (!rootID) {
            return;
        }
        this.pinnedDocs?.scheduleRefresh();
        const importedPath = data.parentPath === "/" ? `/${rootID}.sy` : `${data.parentPath}/${rootID}.sy`;
        this.updateItemArrow(data.notebook, importedPath);
    }

    public onDocSortModeChanged(data: IDocSortModeChanged) {
        this.pinnedDocs?.scheduleRefresh();
        updateFileTreeSortMode(data, this.element);
        this.docSortModeChanges.set(`${data.scope}:${data.box}:${data.id}:${data.path}`, data);
        window.clearTimeout(this.docSortModeRefreshTimeout);
        this.docSortModeRefreshTimeout = window.setTimeout(() => {
            const changes = Array.from(this.docSortModeChanges.values());
            this.docSortModeChanges.clear();
            const refreshLists = () => {
                getFileTreeSortRefreshTargets(this.element, changes).forEach((target) => {
                    const notebookElement = Array.from(this.element.children).find((item) =>
                        item.getAttribute("data-url") === target.notebookId
                    );
                    const liElement = Array.from(notebookElement?.querySelectorAll("li[data-path]") || []).find((item) =>
                        item.getAttribute("data-path") === target.path
                    );
                    if (liElement) {
                        this.getLeaf(liElement, target.notebookId, true);
                    }
                });
            };
            if (changes.some((item) => item.scope === "global")) {
                setNoteBook((notebooks) => {
                    reorderFileTreeNotebooks(this.element, this.closeElement.lastElementChild, notebooks);
                    this.element.querySelectorAll<HTMLElement>(
                        ":scope > ul[data-url] > li[data-type=\"navigation-root\"]"
                    ).forEach((item) => {
                        if (window.siyuan.config.fileTree.sort === 6) {
                            item.setAttribute("draggable", "true");
                        } else {
                            item.removeAttribute("draggable");
                        }
                    });
                    refreshLists();
                });
            } else {
                refreshLists();
            }
        }, 100);
    }

    public onNotebookSortChanged() {
        if (window.siyuan.config.fileTree.sort !== 6) {
            return;
        }
        setNoteBook((notebooks) => {
            reorderFileTreeNotebooks(this.element, this.closeElement.lastElementChild, notebooks);
        });
    }

    private onMove(response: IWebSocketData) {
        const moves = response.data.moves as IFileTreeMove[];
        const hasParentChange = moves.some((move) =>
            move.fromNotebook !== move.toNotebook ||
            pathPosix().dirname(move.fromPath) !== pathPosix().dirname(move.newPath));
        const refreshTargets = new Map<string, { element: HTMLElement, notebookId: string }>();
        moves.forEach((move) => {
            const expandedDocIDs = new Set<string>();
            const movedItem = findMovedFileTreeItem(this.element, move);
            const sourceElement = movedItem?.element;
            const sourceAtTarget = movedItem?.isAtTarget;
            let childListElement: HTMLElement;
            if (sourceElement) {
                childListElement = getFileTreeChildList(sourceElement);
                collectExpandedDocIDs(sourceElement, childListElement, expandedDocIDs);
                updateMovedSubtree(sourceElement, childListElement, move.fromPath, move.newPath);
            }
            if (sourceElement && !sourceAtTarget) {
                const sourceListElement = sourceElement.parentElement;
                childListElement?.remove();
                if (sourceListElement.childElementCount === 1) {
                    const parentLiElement = sourceListElement.previousElementSibling as HTMLElement;
                    if (parentLiElement) {
                        if (parentLiElement.getAttribute("data-type") !== "navigation-root" ||
                            parentLiElement.dataset.nodeId) {
                            parentLiElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
                        }
                        parentLiElement.querySelector(".b3-list-item__arrow").classList.remove(
                            "b3-list-item__arrow--open"
                        );
                        parentLiElement.setAttribute("data-count", "0");
                        this.updateDocActionElement(parentLiElement);
                        syncFileTreeItemDefaultIcon(parentLiElement);
                    }
                    sourceListElement.remove();
                } else {
                    sourceElement.remove();
                }
            } else if (!sourceElement || sourceAtTarget) {
                const parentPath = pathPosix().dirname(move.fromPath);
                const parentElement = this.element.querySelector(
                    `ul[data-url="${move.fromNotebook}"] li[data-path="${parentPath === "/" ? "/" : parentPath + ".sy"}"]`
                ) as HTMLElement;
                if (parentElement && parentElement.getAttribute("data-count") === "1") {
                    parentElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
                    parentElement.querySelector(".b3-list-item__arrow").classList.remove(
                        "b3-list-item__arrow--open"
                    );
                    syncFileTreeItemDefaultIcon(parentElement);
                }
            }

            const targetElement = this.element.querySelector(
                `[data-url="${move.toNotebook}"] li[data-path="${move.toPath}"]`
            ) as HTMLElement;
            if (!targetElement) {
                expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
                return;
            }
            targetElement.querySelector(".b3-list-item__toggle").classList.remove("fn__hidden");
            if (targetElement.getAttribute("data-type") === "navigation-root") {
                targetElement.setAttribute(
                    "data-count",
                    Math.max(1, Number(targetElement.getAttribute("data-count"))).toString()
                );
                this.updateDocActionElement(targetElement);
            }
            syncFileTreeItemDefaultIcon(targetElement);

            const targetListElement = getFileTreeChildList(targetElement);
            const targetExpanded = Boolean(targetElement.querySelector(".b3-list-item__arrow--open"));
            if (sourceElement && targetListElement && !sourceAtTarget) {
                targetListElement.append(sourceElement);
                if (childListElement) {
                    sourceElement.after(childListElement);
                }
            }
            if (!targetExpanded || !sourceElement || (!sourceAtTarget && !targetListElement)) {
                expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
            }
            if (targetExpanded) {
                refreshTargets.set(`${move.toNotebook}:${move.toPath}`, {
                    element: targetElement,
                    notebookId: move.toNotebook,
                });
            }
        });
        if (hasParentChange) {
            this.getOpenPaths();
        }
        if (response.callback !== Constants.CB_MOVE_NOLIST) {
            refreshTargets.forEach((target) => {
                this.getLeaf(target.element, target.notebookId, true);
            });
        }
        getMovedFileTreeSortRefreshTargets(this.element, moves).forEach((target) => {
            const notebookElement = Array.from(this.element.children).find((item) =>
                item.getAttribute("data-url") === target.notebookId
            );
            const liElement = Array.from(notebookElement?.querySelectorAll("li[data-path]") || []).find((item) =>
                item.getAttribute("data-path") === target.path
            );
            if (liElement) {
                this.getLeaf(liElement, target.notebookId, true);
            }
        });
    }

    private restoreMovedExpandedItems(listElement: Element, notebookId: string) {
        restoreMovedExpandedDocItems(listElement, this.movedExpandedDocIDs, (item) => {
            this.getLeaf(item, notebookId, true);
        });
    }

    private onLsHTML(data: IFileTreeList, scrollTop?: number) {
        this.parentDocClick.cancel();
        if (data.files.length === 0) {
            return;
        }
        const liElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${data.path}"]`);
        if (!liElement) {
            return;
        }
        let fileHTML = "";
        data.files.forEach((item: IFile) => {
            fileHTML += this.genFileHTML(item);
        });
        const effectiveSortMode = getResponseEffectiveSortMode(data, data.box);
        let nextElement = liElement.nextElementSibling;
        if (nextElement && nextElement.tagName === "UL") {
            // 文件展开时,刷新
            const tempElement = document.createElement("template");
            tempElement.innerHTML = fileHTML;
            const focusedIDs = Array.from(nextElement.querySelectorAll(":scope > .b3-list-item--focus")).map((item) =>
                item.getAttribute("data-node-id")
            );
            const lastSelectedID = nextElement.contains(this.lastSelectedElement) ?
                this.lastSelectedElement.getAttribute("data-node-id") : "";
            focusedIDs.forEach((id) => {
                Array.from(tempElement.content.children).find((item) =>
                    item.getAttribute("data-node-id") === id
                )?.classList.add("b3-list-item--focus");
            });
            // 保持文件夹展开状态
            nextElement.querySelectorAll(":scope > .b3-list-item > .b3-list-item__toggle> .b3-list-item__arrow--open").forEach(item => {
                const openLiElement = hasClosestByClassName(item, "b3-list-item");
                if (openLiElement) {
                    const tempOpenLiElement = tempElement.content.querySelector(`.b3-list-item[data-node-id="${openLiElement.getAttribute("data-node-id")}"]`);
                    if (tempOpenLiElement) {
                        tempOpenLiElement.after(openLiElement.nextElementSibling);
                        tempOpenLiElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
                    }
                }
            });
            nextElement.innerHTML = tempElement.innerHTML;
            if (lastSelectedID) {
                this.lastSelectedElement = Array.from(nextElement.querySelectorAll("[data-node-id]")).find((item) =>
                    item.getAttribute("data-node-id") === lastSelectedID
                ) || null;
            }
            nextElement.setAttribute(FILE_TREE_EFFECTIVE_SORT_MODE, effectiveSortMode.toString());
            this.restoreMovedExpandedItems(nextElement, data.box);
            if (typeof scrollTop === "number") {
                this.element.scroll({top: scrollTop, behavior: "smooth"});
            }
            this.refreshPublishAccessSwitch();
            return;
        }
        liElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
        liElement.insertAdjacentHTML("afterend", `<ul ${FILE_TREE_EFFECTIVE_SORT_MODE}="${effectiveSortMode}">${fileHTML}</ul>`);
        nextElement = liElement.nextElementSibling;
        this.restoreMovedExpandedItems(nextElement, data.box);
        expandFileTree(nextElement as HTMLElement, () => {
            if (typeof scrollTop === "number") {
                this.element.scroll({top: scrollTop, behavior: "smooth"});
            }
        });
        this.refreshPublishAccessSwitch();
    }

    private async onLsSelect(data: IFileTreeList, filePath: string, setStorage: boolean, isSetCurrent: boolean) {
        if (data.files.length === 0) {
            return;
        }
        const liElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${data.path}"]`);
        if (!liElement) {
            return;
        }
        const arrowElement = liElement.querySelector(".b3-list-item__arrow");
        arrowElement.parentElement.classList.remove("fn__hidden");
        syncFileTreeItemDefaultIcon(liElement as HTMLElement);
        this.onLsHTML(data);
        let newLiElement;
        for (let i = 0; i < data.files.length; i++) {
            const item = data.files[i];
            if (filePath === item.path) {
                newLiElement = await this.selectItem(data.box, filePath, undefined, setStorage, isSetCurrent);
            } else if (filePath.startsWith(item.path.replace(".sy", ""))) {
                const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
                    notebook: data.box,
                    path: item.path,
                    app: Constants.SIYUAN_APPID,
                });
                if (response.code === 0) {
                    newLiElement = await this.selectItem(response.data.box, filePath, response.data, setStorage, isSetCurrent);
                }
            }
        }
        if (isSetCurrent) {
            this.setCurrent(newLiElement);
        }
        return newLiElement;
    }

    private toggleLeaf(liElement: Element, notebookId: string) {
        this.parentDocClick.cancel();
        toggleFileTree(
            liElement,
            () => this.getOpenPaths(),
            () => this.getLeaf(liElement, notebookId)
        );
    }

    public setCurrent(target: HTMLElement, isScroll = true) {
        if (!target) {
            return;
        }
        this.pinnedDocs.clearSelection();
        this.element.querySelectorAll("li.b3-list-item--focus").forEach((liItem) => {
            liItem.classList.remove("b3-list-item--focus");
        });
        target.classList.add("b3-list-item--focus");

        if (isScroll) {
            const elementRect = this.element.getBoundingClientRect();
            this.element.scrollTop = this.element.scrollTop + (target.getBoundingClientRect().top - (elementRect.top + elementRect.height / 2));
        }
    }

    public getLeaf(liElement: Element, notebookId: string, focusUpdate = false) {
        this.parentDocClick.cancel();
        const toggleElement = liElement.querySelector(".b3-list-item__arrow");
        if (cancelFileTreeCollapse(liElement)) {
            this.getOpenPaths();
            if (!focusUpdate) {
                return;
            }
        }
        const leafElement = liElement.nextElementSibling as HTMLElement;
        if (toggleElement.classList.contains("b3-list-item__arrow--open") && !focusUpdate) {
            toggleElement.classList.remove("b3-list-item__arrow--open");
            if (leafElement?.tagName === "UL") {
                leafElement.remove();
                this.getOpenPaths();
            } else {
                // 没有UL,直接更新路径
                this.getOpenPaths();
            }
            return;
        }
        fetchPost("/api/filetree/listDocsByPath", {
            notebook: notebookId,
            path: liElement.getAttribute("data-path"),
            app: Constants.SIYUAN_APPID,
        }, response => {
            if (response.data.path === "/" && response.data.files.length === 0) {
                newFileInTree(this.app, notebookId, "/");
                return;
            }
            this.onLsHTML(response.data);
            this.getOpenPaths();
        });
    }

    public async selectItem(notebookId: string, filePath: string, data?: IFileTreeList,
                            setStorage = true, isSetCurrent = true) {
        filePath = filePath.replace(/\/\/+/g, "/");
        const treeElement = this.element.querySelector(`[data-url="${notebookId}"]`);
        if (!treeElement) {
            // 有文件树和编辑器的布局初始化时,文件树还未挂载
            return;
        }
        const boxDocID = window.siyuan.config.fileTree.boxDocEnabled ? notebookId : "";
        if (boxDocID && filePath === `/${boxDocID}.sy`) {
            const boxDocElement = treeElement.querySelector("[data-type=\"navigation-root\"]") as HTMLElement;
            if (isSetCurrent) {
                this.setCurrent(boxDocElement);
            }
            return boxDocElement;
        }
        let currentPath = filePath;
        let liElement: HTMLElement;
        const visitedPaths = new Set<string>();
        while (!liElement) {
            if (visitedPaths.has(currentPath)) {
                return;
            }
            visitedPaths.add(currentPath);
            liElement = treeElement.querySelector(`[data-path="${currentPath}"]`);
            if (!liElement) {
                const dirname = pathPosix().dirname(currentPath);
                if (dirname === "/") {
                    currentPath = dirname;
                } else {
                    currentPath = dirname + ".sy";
                }
            }
        }

        if (liElement.getAttribute("data-path") === filePath) {
            if (setStorage) {
                this.getOpenPaths();
            }
            if (isSetCurrent) {
                this.setCurrent(liElement);
            }
            return liElement;
        }

        if (data && data.path === currentPath) {
            liElement = await this.onLsSelect(data, filePath, setStorage, isSetCurrent);
        } else {
            const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
                notebook: notebookId,
                path: currentPath,
                app: Constants.SIYUAN_APPID,
            });
            if (response.code === 0) {
                liElement = await this.onLsSelect(response.data, filePath, setStorage, isSetCurrent);
            }
        }
        this.refreshPublishAccessSwitch();
        return liElement;
    }

    private getOpenPaths() {
        saveOpenFileTreePaths(this.element);
    }

    private genFileHTML(item: IFile) {
        let countHTML = "";
        if (item.count && item.count > 0) {
            countHTML = `<span class="popover__block counter b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.ref}">${item.count}</span>`;
        }
        const ariaLabel = genFileTreeDocAriaLabel(item, true);
        const paddingLeft = (item.path.split("/").length - 1) * 18;
        const editingPublishAccess = this.element.classList.contains("file-tree__publish-access--active");
        const iconExpands = window.siyuan.config.fileTree.docIconClickMode === 1;
        // 点击会修改图标时给出提示,展开或打开时不提示
        const iconChanges = !iconExpands;
        const actionClasses = `${iconExpands && item.subFileCount > 0 && !editingPublishAccess ? " file-tree__item--icon-expand" : ""}${
            iconExpands && item.subFileCount === 0 && !editingPublishAccess ? " file-tree__item--icon-open" : ""}${
            window.siyuan.config.fileTree.parentDocTitleClickMode !== 0 && item.subFileCount > 0 ? " file-tree__item--title-expand" : ""}`;
        const defaultIcon = item.subFileCount === 0 ? "file" : "folder";
        return `<li data-node-id="${item.id}" data-name="${escapeHtmlTextAndAttr(item.name)}" draggable="true" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}"
data-type="navigation-file"
style="--file-toggle-width:${paddingLeft + 18}px;--file-action-offset:${paddingLeft + 20}px"
class="b3-list-item b3-list-item--hide-action${actionClasses}" data-path="${item.path}"${getFileTreeDefaultIconAttr(item.icon, defaultIcon)}>
    <span style="padding-left: ${paddingLeft}px" class="b3-list-item__toggle b3-list-item__toggle--hl${item.subFileCount === 0 ? " fn__hidden" : ""}">
        <svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
    </span>
    <span class="b3-list-item__icon${iconChanges ? " ariaLabel" : ""} popover__block${editingPublishAccess ? " fn__none" : ""}" data-position="8east" data-id="${item.id}"${iconChanges ? ` aria-label="${window.siyuan.languages.changeIcon}"` : ""}>${getFileTreeIconHTML(item.icon, defaultIcon)}</span>
    <span class="b3-list-item__switch b3-tooltips b3-tooltips__n${editingPublishAccess ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>
    <span class="b3-list-item__text ariaLabel" data-delay="200" data-position="parentE" data-tooltip-encoding="none"
aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}</span>
    <span data-type="more-file" data-menu="true" class="b3-list-item__action b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.more}">
        <svg><use xlink:href="#iconMore"></use></svg>
    </span>
    <span data-type="new" class="b3-list-item__action b3-tooltips b3-tooltips__nw${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.newSubDoc}">
        <svg><use xlink:href="#iconAdd"></use></svg>
    </span>
    ${countHTML}
</li>`;
    }

    public destroy() {
        this.parentDocClick.cancel();
        this.pinnedDocs.destroy();
    }

    private initMoreMenu() {
        window.siyuan.menus.menu.remove();
        window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_DOC_TREE_PANEL_MORE);
        if (!window.siyuan.config.readonly) {
            window.siyuan.menus.menu.append(new MenuItem({
                id: "newNotebook",
                icon: "iconNewNoteBook",
                label: window.siyuan.languages.newNotebook,
                click: () => {
                    newNotebook();
                }
            }).element);
            if (window.siyuan.config.notebookCrypto?.enabled) {
                window.siyuan.menus.menu.append(new MenuItem({
                    id: "newEncryptedNotebook",
                    icon: "iconLock",
                    label: window.siyuan.languages.newEncryptedNotebook,
                    click: () => {
                        newEncryptedNotebook();
                    }
                }).element);
            }
            if (getHostCapabilities().documentImportExport) {
                window.siyuan.menus.menu.append(new MenuItem({
                    id: "importNotebook",
                    icon: "iconUpload",
                    label: `${window.siyuan.languages.importNotebook}<input class="b3-form__upload" type="file" accept="application/zip">`,
                    bind: (element) => {
                        element.querySelector<HTMLInputElement>(".b3-form__upload").addEventListener("change", (event) => {
                            const file = (event.target as HTMLInputElement).files?.[0];
                            if (file) {
                                window.siyuan.menus.menu.remove();
                                importNotebook(file);
                            }
                        });
                    },
                }).element);
            }
        }
        window.siyuan.menus.menu.append(new MenuItem({
            id: "rebuildDataIndex",
            icon: "iconRefresh",
            label: window.siyuan.languages.rebuildDataIndex,
            click: () => {
                if (!this.element.getAttribute("disabled")) {
                    this.element.setAttribute("disabled", "disabled");
                    confirmDialog(window.siyuan.languages.rebuildDataIndex, window.siyuan.languages.rebuildDataIndexTip, () => {
                        refreshFileTree(() => {
                            this.element.removeAttribute("disabled");
                            this.init(false);
                        });
                    }, () => {
                        this.element.removeAttribute("disabled");
                    });
                }
            }
        }).element);
        if (!window.siyuan.config.readonly) {
            const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort) => {
                if (sort === null) {
                    return;
                }
                configApi.set("fileTree.sort", sort, () => {
                    this.onDocSortModeChanged({
                        scope: "global",
                        box: "",
                        id: "",
                        path: "/",
                        sortMode: sort,
                    });
                });
            });
            window.siyuan.menus.menu.append(new MenuItem({
                id: "sort",
                icon: "iconSort",
                label: window.siyuan.languages.sort,
                type: "submenu",
                submenu: subMenu,
            }).element);
        }
        if (!window.siyuan.config.readonly && window.siyuan.config.publish.enable) {
            window.siyuan.menus.menu.append(new MenuItem({
                id: "publishAccess",
                icon: "iconEye",
                label: window.siyuan.languages.publishAccess,
                checked: this.element.classList.contains("file-tree__publish-access--active"),
                click: () => {
                    this.element.classList.toggle("file-tree__publish-access--active");
                    this.updateDocActions();
                    this.refreshPublishAccessSwitch();
                }
            }).element);
        }
        return window.siyuan.menus.menu;
    }

    private updatePublishAccessControls(editingPublishAccess: boolean) {
        this.element.querySelectorAll(".b3-list-item__icon").forEach(item => {
            const encrypted = Boolean(item.closest("[data-encrypted=true]"));
            item.classList.toggle("fn__none", editingPublishAccess && !encrypted);
            const switchElement = item.nextElementSibling;
            if (switchElement) {
                switchElement.classList.toggle("fn__none", !editingPublishAccess || encrypted);
            }
        });
    }

    private refreshPublishAccessSwitch() {
        const editingPublishAccess = this.element.classList.contains("file-tree__publish-access--active");
        this.updatePublishAccessControls(editingPublishAccess);
        if (window.siyuan.config.readonly || window.siyuan.isPublish || !editingPublishAccess) {
            return;
        }
        const ids: string[] = [];
        this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => {
            if (!element.closest("[data-encrypted=true]")) {
                ids.push(element.getAttribute("data-url"));
            }
        });
        this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => {
            if (!element.closest("[data-encrypted=true]")) {
                ids.push(element.getAttribute("data-node-id"));
            }
        });
        fetchPost("/api/filetree/getPublishAccess", {
            ids
        }, response => {
            response.data.publishAccess.forEach((item: IPublishAccessItem) => {
                const element = this.element.querySelector(`[data-url="${item.id}"] .b3-list-item__switch`) || this.element.querySelector(`[data-node-id="${item.id}"] .b3-list-item__switch`);
                if (element) {
                    element.innerHTML = getPublishAccessOptionByLevel(getPublishAccessLevel(item.visible, item.password, item.disable)).iconHTML;
                }
            });
        });
    }
}