Skip to content

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

62.2 KB
Raw Blame
import {toggleMenu} from "../menus/menuToggle";
import {Layout} from "./index";
import {genUUID} from "../util/genID";
import {
    fixWndFlex1,
    getInstanceById,
    getWndByLayout,
    JSONToCenter, layoutToJSON,
    isSensitiveTab,
    newModelByInitData,
    pdfIsLoading,
    saveLayout,
    setPanelFocus,
} from "./util";
import {createTabHeaderElement, Tab} from "./Tab";
import {Model} from "./Model";
import {Editor} from "../editor";
import {Graph} from "./dock/Graph";
import {
    hasClosestBlock,
    hasClosestByAttribute,
    hasClosestByClassName,
    isInEmbedBlock
} from "../protyle/util/hasClosest";
import {Constants} from "../constants";
/// #if !BROWSER
import {ipcRenderer, webFrame} from "electron";
import {setModelsHash} from "../window/setHeader";
import {closeWindowAfterLastTab, flushClosingWindowTab} from "../window/closeWin";
/// #endif
import {showMessage} from "../dialog/message";
import {openFileById, updatePanelByEditor} from "../editor/util";
import {scrollCenter} from "../util/highlightById";
import {fetchPost, fetchSyncPost} from "../util/fetch";
import {getAllModels} from "./getAll";
import {clearCounter} from "./status";
import {saveScroll} from "../protyle/scroll/saveScroll";
import {restoreTabPosition, saveTabPosition} from "../protyle/scroll/tabPosition";
import {saveBackScroll} from "../util/backForward";
import {Asset} from "../asset";
import {newFile} from "../util/newFile";
import {MenuItem} from "../menus/Menu";
import {escapeHtml} from "../util/escape";
import {getFrontend} from "../util/functions";
import {hideAllElements} from "../protyle/ui/hideElements";
import {focusByOffset} from "../protyle/util/selection";
import {getSelectionOffset} from "../protyle/util/selectionOffsets";
import {Custom} from "./dock/Custom";
import type {App} from "../index";
import {getFileTreeIconHTML} from "../emoji/fileTreeIcon";
import {newCenterEmptyTab, resizeTabs, setTabPosition} from "./tabUtil";
import {setPosition} from "../util/setPosition";
import {clearOBG} from "./dock/util";
import {recordBeforeResizeTop, restoreBeforeResizeTop} from "../protyle/util/resize";
import {isPhablet, sanitizeClosedTabs, setStorageVal} from "../protyle/util/compatibility";
import {setTitle} from "../util/processTitle";
import {dragOverScroll} from "../boot/globalEvent/dragover";
import {
    clearDocumentTabMovePreview,
    clearTabDragPreview,
    clearTabHoverSwitch,
    findDefaultTabNextId,
    findNextTabId,
    getDocumentTabMovePosition,
    reorderTabItems,
    scheduleTabHoverSwitch
} from "./tabDrag";
import {parseDocumentTreeDragData} from "../util/fileTreeMove";
import {pathPosix} from "../util/pathName";

interface IDocumentTabMoveTarget {
    element: HTMLElement;
    rootID: string;
}

const getDocumentTabMoveTarget = (target: HTMLElement, headersElement: HTMLElement) => {
    const tabHeaderElement = hasClosestByAttribute(target, "data-type", "tab-header");
    if (!tabHeaderElement || !headersElement.contains(tabHeaderElement)) {
        return;
    }
    const tab = getInstanceById(tabHeaderElement.dataset.id) as Tab;
    if (!(tab?.model instanceof Editor)) {
        return;
    }
    const rootID = tab.model.editor.protyle.block.rootID;
    if (!rootID) {
        return;
    }
    return {
        element: tabHeaderElement,
        rootID,
    };
};

const updateDocumentTabMovePreview = (target: IDocumentTabMoveTarget, tabHeadersElement: HTMLElement, clientX: number) => {
    let dropElement = target.element.querySelector<HTMLElement>(":scope > .item__document-drop");
    if (!target.element.classList.contains("item--document-drop") || !dropElement) {
        clearDocumentTabMovePreview();
        target.element.classList.add("item--document-drop");
        tabHeadersElement.classList.add("layout-tab-bars--document-drop");
        target.element.insertAdjacentHTML("beforeend", `<span class="item__document-drop">
    <span class="item__document-drop-option" data-position="sibling">${escapeHtml(window.siyuan.languages.moveDocToSameLevel)}</span>
    <span class="item__document-drop-option" data-position="child">${escapeHtml(window.siyuan.languages.moveDocAsChild)}</span>
</span>`);
        dropElement = target.element.querySelector<HTMLElement>(":scope > .item__document-drop");
    }
    const rect = dropElement.getBoundingClientRect();
    const position = getDocumentTabMovePosition(clientX, rect.left, rect.width);
    target.element.dataset.documentDropPosition = position;
    dropElement.querySelectorAll<HTMLElement>(".item__document-drop-option").forEach((item) => {
        item.classList.toggle("item__document-drop-option--active", item.dataset.position === position);
    });
};

const moveDocumentsToTab = async (sourceIDs: string[], target: IDocumentTabMoveTarget,
                                  position: "sibling" | "child") => {
    if (sourceIDs.includes(target.rootID)) {
        return;
    }
    let toID = target.rootID;
    if (position === "sibling") {
        const response = await fetchSyncPost("/api/filetree/getPathByID", {id: target.rootID});
        if (response.code !== 0 || typeof response.data?.path !== "string" ||
            typeof response.data?.notebook !== "string") {
            return;
        }
        const parentPath = pathPosix().dirname(response.data.path);
        toID = parentPath === "/" ? response.data.notebook : pathPosix().basename(parentPath);
    }
    await fetchSyncPost("/api/filetree/moveDocsByID", {
        fromIDs: sourceIDs,
        toID,
    });
};

const createDragTabPlaceholder = () => {
    const dragTab = window.siyuan.dragTab;
    const element = createTabHeaderElement({
        title: dragTab?.title,
        icon: dragTab?.icon || (dragTab ? undefined : "iconFile"),
        docIcon: dragTab?.docIcon,
        focus: dragTab?.focus,
        pin: dragTab?.pin,
        unupdate: dragTab?.unupdate,
    });
    element.setAttribute("data-clone", "true");
    if (!dragTab) {
        element.setAttribute("data-drag-fallback", "true");
    }
    return element;
};

const insertTabHeaderElement = (tabBarElement: HTMLElement, tabHeaderElement: HTMLElement) => {
    const tabElements = (Array.from(tabBarElement.children) as HTMLElement[]).filter((item) =>
        item !== tabHeaderElement && item.dataset.id);
    const nextId = findDefaultTabNextId(tabElements.map((item) => ({
        id: item.dataset.id,
        pin: item.classList.contains("item--pin"),
    })), tabHeaderElement.classList.contains("item--pin"));
    const nextElement = tabElements.find((item) => item.dataset.id === nextId);
    if (nextElement) {
        nextElement.before(tabHeaderElement);
    } else {
        tabBarElement.append(tabHeaderElement);
    }
    return nextId;
};

export class Wnd {
    private app: App;
    public id: string;
    public parent?: Layout;
    public element: HTMLElement;
    public headersElement: HTMLElement;
    public children: Tab[] = [];
    public resize?: Config.TUILayoutDirection;

    constructor(app: App, resize?: Config.TUILayoutDirection, parentType?: Config.TUILayoutType) {
        this.id = genUUID();
        this.app = app;
        this.resize = resize;
        this.element = document.createElement("div");
        this.element.classList.add("fn__flex-1", "fn__flex");
        let dragHTML = '<div class="layout-tab-container__drag fn__none"></div>';
        if (parentType === "left" || parentType === "right" || parentType === "bottom") {
            dragHTML = "";
        }
        this.element.innerHTML = `<div data-type="wnd" data-id="${this.id}" class="fn__flex-column fn__flex fn__flex-1">
    <div class="fn__flex fn__none">
        <ul class="fn__flex layout-tab-bar"></ul>
        <ul class="layout-tab-bar layout-tab-bar--readonly fn__flex-1">
            <li class="item item--readonly">
                <span data-type="new" class="block__icon block__icon--show ariaLabel${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.newFile}"><svg><use xlink:href="#iconAdd"></use></svg></span>
                <span class="fn__flex-1"></span>
                <span data-type="more" data-menu="true" class="block__icon block__icon--show ariaLabel" aria-label="${window.siyuan.languages.switchTab}"><svg><use xlink:href="#iconDown"></use></svg></span>
            </li>
        </ul>
    </div>
    <div class="layout-tab-container fn__flex-1">${dragHTML}</div>
</div>`;
        this.headersElement = this.element.querySelector(".layout-tab-bar");
        const dragElement = this.element.querySelector(".layout-tab-container__drag") as HTMLElement;
        if (!dragElement) {
            return;
        }
        this.headersElement.addEventListener("mousedown", (event) => {
            // 点击鼠标滚轮关闭
            if (event.button !== 1) {
                return;
            }
            let target = event.target as HTMLElement;
            while (target && !target.isEqualNode(this.headersElement)) {
                if (target.tagName === "LI") {
                    this.removeTab(target.getAttribute("data-id"));
                    window.siyuan.menus.menu.remove();
                    event.stopPropagation();
                    event.preventDefault();
                    const frontend = getFrontend();
                    if ((["desktop", "desktop-window"].includes(frontend) && window.siyuan.config.system.os === "linux") ||
                        (frontend === "browser-desktop" && navigator.userAgent.indexOf("Linux") !== -1)) {
                        const activeElement = document.activeElement;
                        window.addEventListener("paste", this.#preventPast, {
                            capture: true,
                            once: true
                        });
                        // TODO 保持原有焦点?https://github.com/siyuan-note/siyuan/pull/13395/files#r1877004077
                        if (activeElement instanceof HTMLElement) {
                            activeElement.focus();
                        }
                        // 如果在短时间内没有 paste 事件发生,移除监听
                        setTimeout(() => {
                            window.removeEventListener("paste", this.#preventPast, {
                                capture: true
                            });
                        }, Constants.TIMEOUT_INPUT);
                    }
                    break;
                }
                target = target.parentElement;
            }
        });
        this.headersElement.addEventListener("mousewheel", (event: WheelEvent) => {
            this.headersElement.scrollLeft = this.headersElement.scrollLeft + event.deltaY;
        }, {passive: true});

        let lastClickedTab: HTMLElement;
        this.headersElement.parentElement.addEventListener("click", (event) => {
            const tabElement = (event.target as Element).closest<HTMLElement>('[data-type="tab-header"][data-id]');
            const clickedTab = tabElement && this.headersElement.contains(tabElement) ? tabElement : undefined;
            // 连续点击按页签配对,浏览器的点击次数可以超过两次。
            if (event.button === 0 && event.detail > 1 && clickedTab && clickedTab === lastClickedTab &&
                window.siyuan.config.fileTree.closeTabOnDoubleClick) {
                lastClickedTab = undefined;
                this.removeTab(clickedTab.getAttribute("data-id"));
                return;
            }
            lastClickedTab = event.button === 0 ? clickedTab : undefined;
            let target = event.target as HTMLElement;
            while (target && !target.isEqualNode(this.headersElement)) {
                if (target.classList.contains("block__icon") && target.getAttribute("data-type") === "new") {
                    setPanelFocus(this.headersElement.parentElement.parentElement);
                    newFile(app);
                    break;
                } else if (target.classList.contains("block__icon") && target.getAttribute("data-type") === "more") {
                    this.renderTabList(target);
                    break;
                } else if (target.tagName === "LI" && target.getAttribute("data-id") && !pdfIsLoading(this.element)) {
                    if (target.classList.contains("item--focus")) {
                        this.switchTab(target, true, true, false, false);
                    } else {
                        this.switchTab(target, true);
                    }
                    this.showHeading();
                    break;
                }
                target = target.parentElement;
            }
        });
        this.headersElement.parentElement.addEventListener("dblclick", (event) => {
            const tabElement = (event.target as Element).closest<HTMLElement>('[data-type="tab-header"][data-id]');
            if (!tabElement || !this.headersElement.contains(tabElement)) {
                return;
            }
            if (!window.siyuan.config.fileTree.closeTabOnDoubleClick && window.siyuan.config.fileTree.openFilesUseCurrentTab) {
                tabElement.classList.remove("item--unupdate");
            }
        });
        const tabHeadersElement = this.headersElement.parentElement;
        tabHeadersElement.addEventListener("dragleave", (event: DragEvent) => {
            const isBlockDrag = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_BLOCK);
            const isTabDrag = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB);
            const isFileDrag = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_FILE);
            if (!isBlockDrag && !isTabDrag && !isFileDrag) {
                return;
            }
            const relatedTarget = event.relatedTarget;
            if (relatedTarget instanceof Node && tabHeadersElement.contains(relatedTarget)) {
                return;
            }
            const rect = tabHeadersElement.getBoundingClientRect();
            if (event.clientX < rect.left || event.clientX > rect.right ||
                event.clientY < rect.top || event.clientY > rect.bottom) {
                if (isBlockDrag) {
                    clearTabHoverSwitch();
                }
                if (isTabDrag) {
                    clearTabDragPreview(tabHeadersElement);
                }
                if (isFileDrag) {
                    clearDocumentTabMovePreview(tabHeadersElement);
                }
            }
        });
        tabHeadersElement.addEventListener("dragover", (event: DragEvent & {
            target: HTMLElement
        }) => {
            const it = event.currentTarget as HTMLElement;
            if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_BLOCK)) {
                const tabHeaderElement = hasClosestByAttribute(event.target, "data-type", "tab-header");
                if (!tabHeaderElement || !this.headersElement.contains(tabHeaderElement) ||
                    tabHeaderElement.classList.contains("item--focus")) {
                    clearTabHoverSwitch();
                    return;
                }
                scheduleTabHoverSwitch(tabHeaderElement.dataset.id, () => {
                    if (this.headersElement.contains(tabHeaderElement) &&
                        !tabHeaderElement.classList.contains("item--focus") && !pdfIsLoading(this.element)) {
                        this.switchTab(tabHeaderElement, true);
                    }
                }, Constants.TIMEOUT_TAB_SWITCH);
                return;
            }
            clearTabHoverSwitch();
            const isFileDrag = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_FILE);
            const isDocumentDrag = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENTS);
            const isTabDrag = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB);
            if (!isFileDrag && !isTabDrag) {
                return;
            }
            if (window.siyuan.currentDragOverTabHeadersElement !== it) {
                if (window.siyuan.currentDragOverTabHeadersElement) {
                    clearTabDragPreview(window.siyuan.currentDragOverTabHeadersElement);
                }
                window.siyuan.currentDragOverTabHeadersElement = it;
            }
            if (isFileDrag) {
                event.preventDefault();
                if ((event.shiftKey || it.classList.contains("layout-tab-bars--document-drop")) && isDocumentDrag) {
                    const documentTabTarget = getDocumentTabMoveTarget(event.target, this.headersElement);
                    it.classList.remove("layout-tab-bars--drag");
                    if (documentTabTarget) {
                        updateDocumentTabMovePreview(documentTabTarget, it, event.clientX);
                        event.dataTransfer.dropEffect = "move";
                    } else {
                        clearDocumentTabMovePreview(tabHeadersElement);
                        event.dataTransfer.dropEffect = "none";
                    }
                    return;
                }
                clearDocumentTabMovePreview(tabHeadersElement);
                it.classList.add("layout-tab-bars--drag");
                return;
            }
            event.preventDefault();
            const tabBarElement = it.firstElementChild as HTMLElement;
            dragOverScroll(event, tabBarElement.getBoundingClientRect(), tabBarElement, "x");
            let oldTabHeaderElement = tabBarElement.querySelector("li[data-clone='true']") as HTMLElement;
            if (oldTabHeaderElement?.hasAttribute("data-drag-fallback") && window.siyuan.dragTab) {
                const placeholderElement = createDragTabPlaceholder();
                oldTabHeaderElement.replaceWith(placeholderElement);
                oldTabHeaderElement = placeholderElement;
                insertTabHeaderElement(tabBarElement, oldTabHeaderElement);
            }
            if (!oldTabHeaderElement && window.siyuan.dragElement && tabBarElement.contains(window.siyuan.dragElement)) {
                oldTabHeaderElement = window.siyuan.dragElement;
            } else if (!oldTabHeaderElement && window.siyuan.dragElement) {
                oldTabHeaderElement = window.siyuan.dragElement.cloneNode(true) as HTMLElement;
                oldTabHeaderElement.setAttribute("data-clone", "true");
                oldTabHeaderElement.removeAttribute("data-id");
                oldTabHeaderElement.removeAttribute("draggable");
                oldTabHeaderElement.style.removeProperty("opacity");
                delete oldTabHeaderElement.dataset.dragDocumentId;
                insertTabHeaderElement(tabBarElement, oldTabHeaderElement);
            } else if (!oldTabHeaderElement) {
                oldTabHeaderElement = createDragTabPlaceholder();
                insertTabHeaderElement(tabBarElement, oldTabHeaderElement);
            }
            const newTabHeaderElement = hasClosestByAttribute(event.target, "data-type", "tab-header");
            if (!newTabHeaderElement) {
                if (!oldTabHeaderElement.classList.contains("item--pin")) {
                    it.classList.add("layout-tab-bars--drag");
                }
                return;
            }
            it.classList.remove("layout-tab-bars--drag");
            if (newTabHeaderElement !== oldTabHeaderElement &&
                ((oldTabHeaderElement.classList.contains("item--pin") && newTabHeaderElement.classList.contains("item--pin")) ||
                    (!oldTabHeaderElement.classList.contains("item--pin") && !newTabHeaderElement.classList.contains("item--pin")))) {
                const rect = newTabHeaderElement.getClientRects()[0];
                if (event.clientX > rect.left + rect.width / 2) {
                    newTabHeaderElement.after(oldTabHeaderElement);
                } else {
                    newTabHeaderElement.before(oldTabHeaderElement);
                }
            }
        });
        tabHeadersElement.addEventListener("drop", async function (event: DragEvent & {
            target: HTMLElement
        }) {
            clearTabHoverSwitch();
            const it = this as HTMLElement;
            if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_FILE)) {
                // 文档树拖拽
                const documentDragData = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENTS) ?
                    parseDocumentTreeDragData(event.dataTransfer.getData(Constants.SIYUAN_DROP_DOCUMENTS)) : undefined;
                const documentMoveActive = event.shiftKey || it.classList.contains("layout-tab-bars--document-drop");
                const documentTabTarget = getDocumentTabMoveTarget(event.target, it.firstElementChild as HTMLElement);
                const movePosition = documentTabTarget?.element.dataset.documentDropPosition as
                    "sibling" | "child" | undefined;
                setPanelFocus(it.parentElement);
                if (documentMoveActive && documentDragData) {
                    event.preventDefault();
                    event.stopPropagation();
                    clearTabDragPreview(it);
                    window.siyuan.dragElement = undefined;
                    if (documentTabTarget && movePosition) {
                        await moveDocumentsToTab(documentDragData.ids, documentTabTarget, movePosition);
                    }
                    return;
                }
                event.dataTransfer.getData(Constants.SIYUAN_DROP_FILE).split(",").forEach(item => {
                    if (item) {
                        openFileById({
                            app,
                            id: item,
                            action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
                            forceCurrentWindow: true,
                        });
                    }
                });
                window.siyuan.dragElement = undefined;
                clearTabDragPreview(it);
                return;
            }
            if (!event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB)) {
                return;
            }
            event.preventDefault();
            const tabBarElement = it.firstElementChild as HTMLElement;
            const cloneTabElement = tabBarElement.querySelector("li[data-clone='true']") as HTMLElement;
            const dragTabHeaderElement = cloneTabElement ||
                (window.siyuan.dragElement && tabBarElement.contains(window.siyuan.dragElement) ? window.siyuan.dragElement : undefined);
            if (!dragTabHeaderElement) {
                clearTabDragPreview(it);
                return;
            }
            const nextTabIds: string[] = [];
            let nextTabHeaderElement = dragTabHeaderElement.nextElementSibling as HTMLElement;
            while (nextTabHeaderElement) {
                const nextTabId = nextTabHeaderElement.getAttribute("data-id");
                if (nextTabId) {
                    nextTabIds.push(nextTabId);
                }
                nextTabHeaderElement = nextTabHeaderElement.nextElementSibling as HTMLElement;
            }
            const tabData = JSON.parse(event.dataTransfer.getData(Constants.SIYUAN_DROP_TAB));
            let oldTab = getInstanceById(tabData.id) as Tab;
            const wnd = getInstanceById(it.parentElement.getAttribute("data-id")) as Wnd;
            if (!(wnd instanceof Wnd)) {
                clearTabDragPreview(it);
                return;
            }
            let isCrossWindow = false;
            /// #if !BROWSER
            if (!oldTab) { // 从主窗口拖拽到页签新窗口
                const existingTabs = new Set(wnd.children);
                JSONToCenter(app, tabData, wnd);
                oldTab = wnd.children.find((item) => !existingTabs.has(item));
                isCrossWindow = true;
            }
            /// #endif
            if (!oldTab) {
                clearTabDragPreview(it);
                return;
            }
            const nextTabId = findNextTabId(wnd.children, nextTabIds);
            const oldWnd = oldTab.parent;
            if (cloneTabElement) {
                cloneTabElement.before(oldTab.headElement);
                cloneTabElement.remove();
            }
            if (oldWnd !== wnd) {
                // 从其他 Wnd 拖动过来
                wnd.moveTab(oldTab, nextTabId);
                resizeTabs();
            } else {
                if (!reorderTabItems(wnd.children, oldTab, nextTabId)) {
                    clearTabDragPreview(it);
                    return;
                }
                if (isCrossWindow) {
                    wnd.switchTab(oldTab.headElement);
                } else {
                    saveLayout();
                }
            }
            clearTabDragPreview(it);
            /// #if !BROWSER
            if (isCrossWindow) {
                ipcRenderer.send(Constants.SIYUAN_SEND_WINDOWS, {cmd: "resetTabsStyle", data: "rmDragStyle"});
                ipcRenderer.send(Constants.SIYUAN_SEND_WINDOWS, {cmd: "resetTabsStyle", data: "addRegionStyle"});
                ipcRenderer.send(Constants.SIYUAN_SEND_WINDOWS, {cmd: "closetab", data: tabData.id});
                ipcRenderer.send(Constants.SIYUAN_CMD, "focus");
            }
            /// #endif
        });
        let elementDragCounter = 0;
        this.element.addEventListener("dragenter", (event: DragEvent & { target: HTMLElement }) => {
            elementDragCounter++;
            if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB)) {
                if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENT_TAB) &&
                    hasClosestByClassName(event.target, "sy__file")) {
                    dragElement.classList.add("fn__none");
                    dragElement.removeAttribute("style");
                    return;
                }
                const tabHeadersElement = hasClosestByClassName(event.target, "layout-tab-bar");
                if (tabHeadersElement) {
                    return;
                }
                const tabPanelsElement = hasClosestByClassName(event.target, "layout-tab-container", true);
                if (tabPanelsElement) {
                    dragElement.classList.remove("fn__none");
                    this.updateDragElement(event, dragElement.parentElement.getBoundingClientRect(), dragElement);
                }
            }
        });
        //  dragElement dragleave 后还会触发 dragenter https://github.com/siyuan-note/siyuan/issues/13753
        this.element.addEventListener("dragleave", () => {
            elementDragCounter--;
            if (elementDragCounter === 0) {
                dragElement.classList.add("fn__none");
                dragElement.removeAttribute("style");
            }
        });
        dragElement.addEventListener("dragover", (event: DragEvent & { layerX: number, layerY: number }) => {
            document.querySelectorAll(".layout-tab-bars--drag").forEach(item => {
                item.classList.remove("layout-tab-bars--drag");
            });
            event.preventDefault();
            if (!dragElement.nextElementSibling) {
                return;
            }
            this.updateDragElement(event, dragElement.parentElement.getBoundingClientRect(), dragElement);
        });

        dragElement.addEventListener("dragleave", () => {
            dragElement.classList.add("fn__none");
            dragElement.removeAttribute("style");
        });

        dragElement.addEventListener("drop", (event: DragEvent & { target: HTMLElement }) => {
            dragElement.classList.add("fn__none");
            const targetWndElement = event.target.parentElement.parentElement;
            const targetWnd = getInstanceById(targetWndElement.getAttribute("data-id")) as Wnd;
            const tabData = JSON.parse(event.dataTransfer.getData(Constants.SIYUAN_DROP_TAB));
            let oldTab = getInstanceById(tabData.id) as Tab;
            /// #if !BROWSER
            if (!oldTab) { // 从主窗口拖拽到页签新窗口
                JSONToCenter(app, tabData, this);
                this.children.find(item => {
                    if (item.headElement.getAttribute("data-activetime") === tabData.activeTime) {
                        oldTab = item;
                        return true;
                    }
                });
                ipcRenderer.send(Constants.SIYUAN_SEND_WINDOWS, {cmd: "closetab", data: tabData.id});
                ipcRenderer.send(Constants.SIYUAN_CMD, "focus");
            }
            /// #endif
            if (!oldTab) {
                dragElement.removeAttribute("style");
                return;
            }

            if (dragElement.style.height === "50%" || dragElement.style.width === "50%") {
                // split
                if (dragElement.style.height === "50%") {
                    // split to bottom
                    const newWnd = targetWnd.split("tb", dragElement.style.bottom !== "50%");
                    newWnd.headersElement.append(oldTab.headElement);
                    newWnd.headersElement.parentElement.classList.remove("fn__none");
                    newWnd.moveTab(oldTab);
                } else if (dragElement.style.width === "50%") {
                    // split to right
                    const newWnd = targetWnd.split("lr", dragElement.style.right !== "50%");
                    newWnd.headersElement.append(oldTab.headElement);
                    newWnd.headersElement.parentElement.classList.remove("fn__none");
                    newWnd.moveTab(oldTab);
                }
                resizeTabs();
                setTabPosition();
                dragElement.removeAttribute("style");
                return;
            }
            dragElement.removeAttribute("style");
            if (targetWndElement.contains(document.querySelector(`[data-id="${tabData.id}"]`))) {
                return;
            }
            if (targetWnd) {
                recordBeforeResizeTop();
                const nextTabId = insertTabHeaderElement(targetWnd.headersElement, oldTab.headElement);
                targetWnd.headersElement.parentElement.classList.remove("fn__none");
                targetWnd.moveTab(oldTab, nextTabId);
                resizeTabs();
            }
        });
    }

    private isPointWithinLines(x: number, y: number, line1: { k: number, b: number }, line2: {
        k: number,
        b: number
    }): boolean {
        const y1 = line1.k * x + line1.b;
        const y2 = line2.k * x + line2.b;
        return (y >= Math.min(y1, y2) && y <= Math.max(y1, y2));
    }

    private updateDragElement(event: DragEvent, rect: DOMRect, dragElement: HTMLElement) {
        const height = rect.height;
        const width = rect.width;
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        if (x < width / 5 && this.isPointWithinLines(x, y, {
            // 左上角 (0.1w, 0); (0.2w, 0.15h)
            k: 1.5 * height / width, b: -0.15 * height
        }, {
            // 左下角 (0.04w, h); (0.2w, 0.8h)
            k: -1.25 * height / width, b: 1.05 * height
        })) {
            dragElement.setAttribute("style", "height:100%;width:50%;right:50%;bottom:0;left:0;top:0");
        } else if (x > width * 0.8 && this.isPointWithinLines(x, y, {
            // 右上角 (0.9w, 0); (0.8w, 0.15h)
            k: -1.5 * height / width, b: 1.35 * height
        }, {
            // 右下角 (0.96w, h); (0.8w, 0.8h)
            k: 1.25 * height / width, b: -0.2 * height
        })) {
            dragElement.setAttribute("style", "height:100%;width:50%;right:0;bottom:0;left:50%;top:0");
        } else if (y < height * .15) {
            dragElement.setAttribute("style", "height:50%;width:100%;right:0;bottom:50%;left:0;top:0");
        } else if (y > height * .8) {
            dragElement.setAttribute("style", "height:50%;width:100%;right:0;bottom:0;left:0;top:50%");
        } else {
            dragElement.setAttribute("style", "height:100%;width:100%;right:0;bottom:0;left:0;top:0");
        }
    };

    public showHeading() {
        const currentElement = this.headersElement.querySelector(".item--focus") as HTMLElement;
        if (!currentElement) {
            return;
        }
        if (currentElement.offsetLeft + currentElement.clientWidth > this.headersElement.scrollLeft + this.headersElement.clientWidth) {
            this.headersElement.scrollLeft = currentElement.offsetLeft + currentElement.clientWidth - this.headersElement.clientWidth;
        } else if (currentElement.offsetLeft < this.headersElement.scrollLeft) {
            this.headersElement.scrollLeft = currentElement.offsetLeft;
        }
    }

    public switchTab(target: HTMLElement, pushBack = false, update = true, resize = true, isSaveLayout = true,
                     focusEditor = !isPhablet()) {
        let currentTab: Tab;
        let isInitActive = false;
        this.children.forEach((item) => {
            if (target === item.headElement) {
                if (item.headElement && item.headElement.classList.contains("fn__none")) {
                    // https://github.com/siyuan-note/siyuan/issues/267
                } else {
                    if (item.headElement) {
                        item.headElement.classList.add("item--focus");
                        if (item.headElement.getAttribute("data-init-active") === "true") {
                            item.headElement.removeAttribute("data-init-active");
                            isInitActive = true;
                        } else {
                            item.headElement.setAttribute("data-activetime", (new Date()).getTime().toString());
                            // 更新文档浏览时间
                            if (item.model instanceof Editor) {
                                fetchPost("/api/storage/updateRecentDocViewTime", {rootID: item.model.editor.protyle.block.rootID});
                            }
                        }
                    }
                    item.panelElement.classList.remove("fn__none");
                    if (isPhablet() && item.model instanceof Editor) {
                        restoreTabPosition(item.model.editor.protyle);
                    }
                }
                currentTab = item;
            } else {
                item.headElement?.classList.remove("item--focus");
                if (!item.panelElement.classList.contains("fn__none")) {
                    if (isPhablet() && item.model instanceof Editor) {
                        saveTabPosition(item.model.editor.protyle);
                        saveBackScroll(item.model.editor.protyle);
                    }
                    // 必须现判断,否则会触发 observer.observe(this.element, {attributeFilter: ["class"]}); 导致 https://ld246.com/article/1641198819303
                    item.panelElement.classList.add("fn__none");
                }
            }
        });
        // 在 JSONToLayout 中进行 focus
        if (!isInitActive) {
            setPanelFocus(this.headersElement.parentElement.parentElement, isSaveLayout);
        }
        if (currentTab && currentTab.headElement) {
            const initData = currentTab.headElement.getAttribute("data-initdata");
            if (initData) {
                currentTab.addModel(newModelByInitData(this.app, currentTab, JSON.parse(initData)));
                currentTab.headElement.removeAttribute("data-initdata");
                if (isSaveLayout) {
                    saveLayout();
                }
                return;
            }
        }

        if (currentTab && target === currentTab.headElement) {
            if (currentTab.model instanceof Graph) {
                currentTab.model.onGraph();
            } else if (currentTab.model instanceof Asset && currentTab.model.pdfObject && currentTab.model.pdfObject.pdfViewer) {
                // https://github.com/siyuan-note/siyuan/issues/5655
                currentTab.model.pdfObject.pdfViewer.container.focus();
            }
        }

        if (currentTab && currentTab.model instanceof Editor) {
            const keepCursorId = currentTab.headElement.getAttribute("keep-cursor");
            if (keepCursorId) {
                // 在新页签中打开,但不跳转到新页签,但切换到新页签时需调整滚动
                let nodeElement: HTMLElement;
                Array.from(currentTab.model.editor.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${keepCursorId}"]`)).find((item: HTMLElement) => {
                    if (!isInEmbedBlock(item)) {
                        nodeElement = item;
                        return true;
                    }
                });
                if (nodeElement) {
                    if (!currentTab.model.editor.protyle.toolbar.range) {
                        const range = document.createRange();
                        range.selectNodeContents(nodeElement);
                        range.collapse();
                        currentTab.model.editor.protyle.toolbar.range = range;
                    }
                    scrollCenter(currentTab.model.editor.protyle, nodeElement, "start");
                } else {
                    openFileById({
                        app: this.app,
                        id: keepCursorId,
                        action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL]
                    });
                }
                currentTab.headElement.removeAttribute("keep-cursor");
            }
            // focusin 触发前,layout__wnd--active 和 tab 已设置,需在调用里面更新
            if (update) {
                updatePanelByEditor({
                    protyle: currentTab.model.editor.protyle,
                    focus: focusEditor,
                    pushBackStack: pushBack,
                    reload: false,
                    resize,
                });
            }
            if (window.siyuan.editorIsFullscreen) {
                currentTab.model.editor.setFullscreen(true);
            }
        } else {
            clearOBG();
        }
        if (isSaveLayout) {
            saveLayout();
        }
    }

    public addTab(tab: Tab, keepCursor = false, isSaveLayout = true, activeTime?: string, replaceTabID?: string) {
        if (keepCursor) {
            tab.headElement?.classList.remove("item--focus");
            tab.panelElement.classList.add("fn__none");
        }
        let oldFocusIndex = 0;
        this.children.forEach((item, index) => {
            if (item.headElement && item.headElement.classList.contains("item--focus")) {
                oldFocusIndex = index;
                let nextElement = item.headElement.nextElementSibling;
                while (nextElement && nextElement.classList.contains("item--pin")) {
                    oldFocusIndex++;
                    nextElement = nextElement.nextElementSibling;
                }
            }
            if (!keepCursor) {
                if (isPhablet() && item.model instanceof Editor && !item.panelElement.classList.contains("fn__none")) {
                    saveTabPosition(item.model.editor.protyle);
                    saveBackScroll(item.model.editor.protyle);
                }
                item.headElement?.classList.remove("item--focus");
                item.panelElement.classList.add("fn__none");
            }
        });

        this.children.splice(oldFocusIndex + 1, 0, tab);

        if (tab.headElement) {
            this.headersElement.parentElement.classList.remove("fn__none");
            if (this.headersElement.childElementCount === 0) {
                this.headersElement.append(tab.headElement);
            } else {
                this.headersElement.children[oldFocusIndex].after(tab.headElement);
            }
            tab.headElement.querySelector(".item__close").addEventListener("click", (event) => {
                if (tab.headElement.classList.contains("item--pin")) {
                    tab.unpin();
                } else {
                    tab.parent.removeTab(tab.id);
                }
                window.siyuan.menus.menu.remove();
                event.stopPropagation();
                event.preventDefault();
            });
            tab.headElement.setAttribute("data-activetime", activeTime || (new Date()).getTime().toString());
        }
        const containerElement = this.element.querySelector(".layout-tab-container");
        if (!containerElement.querySelector(".fn__flex-1")) {
            // empty center
            containerElement.append(tab.panelElement);
        } else if (!containerElement.querySelector(".layout-tab-container__drag")) {
            // Dock
            containerElement.children[oldFocusIndex].after(tab.panelElement);
        } else {
            containerElement.children[oldFocusIndex + 1].after(tab.panelElement);
        }

        tab.parent = this;
        if (tab.callback) {
            tab.callback(tab);
        }

        // 预览切换先移除被替换的页签,再检查数量上限,避免关闭无关页签。
        if (replaceTabID && replaceTabID !== tab.id) {
            this.removeTab(replaceTabID, false, false, false);
        }

        // 移除 centerLayout 中的 empty
        if (this.parent.type === "center" && this.children.length === 2 && !this.children[0].headElement) {
            this.removeTab(this.children[0].id);
        } else if (this.children.length > window.siyuan.config.fileTree.maxOpenTabCount) {
            this.removeOverCounter(isSaveLayout);
        }
        /// #if !BROWSER
        setModelsHash();
        /// #endif
        if (isSaveLayout) {
            setTabPosition();
            saveLayout();
        }
    }

    #preventPast(event: ClipboardEvent) {
        event.preventDefault();
        event.stopPropagation();
    }

    public renderTabList(target = this.headersElement.parentElement.querySelector<HTMLElement>('[data-type="more"]'), focus = false) {
        if (!target || this.headersElement.children.length === 0) {
            return;
        }
        if (focus && !window.siyuan.menus.menu.element.classList.contains("fn__none") &&
            window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_TAB_LIST) {
            return;
        }
        toggleMenu({
            target: target,
            toggle: !focus,
            build: (_menu, session) => {
                window.siyuan.menus.menu.element.classList.add("b3-menu--list");
                Array.from(this.headersElement.children).forEach((item: HTMLElement) => {
                    const iconElement = item.querySelector(".item__icon");
                    const graphicElement = item.querySelector(".item__graphic");
                    let iconHTML = undefined;
                    if (iconElement) {
                        if (iconElement.firstElementChild?.tagName === "IMG") {
                            // 图标为图片的文档
                            iconHTML = `<img src="${iconElement.firstElementChild.getAttribute("src")}"  class="b3-menu__icon">`;
                        } else {
                            // 有图标的文档
                            iconHTML = `<span class="b3-menu__icon">${iconElement.innerHTML}</span>`;
                        }
                    } else if (!graphicElement) {
                        // 没有图标的文档
                        iconHTML = getFileTreeIconHTML("", "file", "b3-menu__icon", true);
                    }
                    window.siyuan.menus.menu.append(new MenuItem({
                        label: escapeHtml(item.querySelector(".item__text").textContent),
                        action: "iconCloseRound",
                        iconHTML,
                        icon: graphicElement ? graphicElement.firstElementChild.getAttribute("xlink:href").substring(1) : "",
                        bind: (element) => {
                            element.addEventListener("click", (itemEvent) => {
                                if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {
                                    this.removeTab(item.getAttribute("data-id"));
                                    if (element.previousElementSibling || element.nextElementSibling) {
                                        element.remove();
                                        setPosition(window.siyuan.menus.menu.element, rect.left + rect.width - window.siyuan.menus.menu.element.clientWidth, rect.top + rect.height);
                                    } else {
                                        window.siyuan.menus.menu.remove();
                                    }
                                } else {
                                    this.switchTab(item, true);
                                    this.showHeading();
                                    window.siyuan.menus.menu.remove();
                                }
                                itemEvent.preventDefault();
                                itemEvent.stopPropagation();
                            });
                        },
                        current: item.classList.contains("item--focus")
                    }).element);
                });
                window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TAB_LIST);
                const rect = target.getBoundingClientRect();
                session.show(() => window.siyuan.menus.menu.popup({
                    x: rect.left + rect.width,
                    y: rect.top + rect.height,
                    h: rect.height,
                    isLeft: true
                }));
                if (focus) {
                    const menu = window.siyuan.menus.menu;
                    const activeElement = document.activeElement;
                    const currentElement = menu.element.querySelector<HTMLElement>(".b3-menu__item--selected") ||
                        menu.element.querySelector<HTMLElement>(".b3-menu__item");
                    currentElement?.classList.add("b3-menu__item--current");
                    currentElement?.focus({preventScroll: true});
                    currentElement?.scrollIntoView({block: "nearest"});
                    // 仅在焦点仍位于菜单内时恢复,避免页签切换后抢回原编辑器焦点。
                    menu.removeCB = () => {
                        if (activeElement instanceof HTMLElement && activeElement.isConnected &&
                            menu.element.contains(document.activeElement)) {
                            activeElement.focus({preventScroll: true});
                        }
                    };
                }

            },
        });
    }

    private removeOverCounter(isSaveLayout = false) {
        let removeId: string;
        let openTime: string;
        let removeCount = 0;
        this.children.forEach((item, index) => {
            if (!item.headElement) {
                return;
            }
            if (item.headElement.classList.contains("item--pin") || item.headElement.classList.contains("item--focus")) {
                return;
            }
            removeCount++;
            if (!openTime) {
                openTime = item.headElement.getAttribute("data-activetime");
                removeId = this.children[index].id;
            } else if (item.headElement.getAttribute("data-activetime") < openTime) {
                openTime = item.headElement.getAttribute("data-activetime");
                removeId = this.children[index].id;
            }
        });
        if (removeId) {
            this.removeTab(removeId, false, false, isSaveLayout);
            removeCount--;
        }
        if (removeCount > 0 && this.children.length > window.siyuan.config.fileTree.maxOpenTabCount) {
            this.removeOverCounter(isSaveLayout);
        }
    }

    private destroyModel(model: Model) {
        if (!model) {
            return;
        }
        if (model instanceof Editor && model.editor) {
            window.siyuan.blockPanels.forEach((item) => {
                if (item.element && model.editor.protyle.wysiwyg.element.contains(item.element)) {
                    item.destroy();
                }
            });
        }
        model.destroy();
        model.send("closews", {});
    }

    private removeTabAction = (id: string, isBatchClose = false, animate = true, isSaveLayout = true) => {
        let removedTab = false;
        this.children.find((item, index) => {
            if (item.id !== id) {
                return;
            }
            removedTab = !!item.headElement;
            /// #if !BROWSER
            if (removedTab && item.model instanceof Editor && item.model.editor) {
                flushClosingWindowTab(item.model.editor);
            }
            /// #endif
            window.siyuan.storage[Constants.LOCAL_CLOSED_TABS] =
                sanitizeClosedTabs(window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);
            if (item.headElement && !isSensitiveTab(item)) {
                const tabJSON = {};
                layoutToJSON(item, tabJSON);
                window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].push(tabJSON);
            }
            while (window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].length > Constants.SIZE_UNDO) {
                window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].shift();
            }
            setStorageVal(Constants.LOCAL_CLOSED_TABS, window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);
            if (item.model instanceof Custom && item.model.beforeDestroy) {
                item.model.beforeDestroy();
            }
            if (item.model instanceof Editor) {
                saveBackScroll(item.model.editor.protyle);
                saveScroll(item.model.editor.protyle);
                // 更新文档关闭时间(批量关闭页签时由 closeTabByType 批量处理,这里不单独调用)
                if (!isBatchClose) {
                    fetchPost("/api/storage/updateRecentDocCloseTime", {rootID: item.model.editor.protyle.block.rootID});
                }
            }
            if (this.children.length === 1) {
                this.destroyModel(this.children[0].model);
                this.children = [];
                if (["bottom", "left", "right"].includes(this.parent.type)) {
                    item.panelElement.remove();
                } else {
                    recordBeforeResizeTop();
                    this.remove();
                }
                // 关闭分屏页签后光标消失
                const editors = getAllModels().editor;
                if (editors.length === 0) {
                    clearOBG();
                } else {
                    editors.forEach(item => {
                        if (!item.element.classList.contains("fn__none")) {
                            setPanelFocus(item.parent.parent.headersElement.parentElement.parentElement);
                            updatePanelByEditor({
                                protyle: item.editor.protyle,
                                focus: true,
                                pushBackStack: true,
                                reload: false,
                                resize: true,
                            });
                            return;
                        }
                    });
                }
                return;
            }
            if (item.headElement) {
                if (item.headElement.classList.contains("item--focus")) {
                    let latestHeadElement: HTMLElement;
                    Array.from(item.headElement.parentElement.children).forEach((headItem: HTMLElement) => {
                        if (headItem !== item.headElement &&
                            headItem.style.maxWidth !== "0px"   // 不对比已移除但还在动画效果中的元素 https://github.com/siyuan-note/siyuan/issues/7878
                        ) {
                            if (!latestHeadElement) {
                                latestHeadElement = headItem;
                            } else if (headItem.getAttribute("data-activetime") > latestHeadElement.getAttribute("data-activetime")) {
                                latestHeadElement = headItem;
                            }
                        }
                    });
                    if (latestHeadElement && !isBatchClose) {
                        this.switchTab(latestHeadElement, true, true, false, false);
                        this.showHeading();
                    }
                }
                if (animate) {
                    item.headElement.setAttribute("style", "max-width: 0px;");
                    setTimeout(() => {
                        item.headElement.remove();
                    }, 200);
                } else {
                    item.headElement.remove();
                }
            }
            item.panelElement.remove();
            this.destroyModel(item.model);
            this.children.splice(index, 1);
            resizeTabs(false);
            return true;
        });
        // 初始化移除窗口,但 centerLayout 还没有赋值 https://ld246.com/article/1658718634416
        if (window.siyuan.layout.centerLayout) {
            const wnd = getWndByLayout(window.siyuan.layout.centerLayout);
            if (!wnd) {
                const wnd = new Wnd(this.app);
                window.siyuan.layout.centerLayout.addWnd(wnd);
                wnd.addTab(newCenterEmptyTab(this.app), false, false);
                clearCounter();
                setTitle("", true);
            }
        }
        if (isSaveLayout) {
            setTabPosition();
            saveLayout();
        }
        /// #if !BROWSER
        webFrame.clearCache();
        ipcRenderer.send(Constants.SIYUAN_CMD, "clearCache");
        setModelsHash();
        if (removedTab) {
            void closeWindowAfterLastTab(this.app);
        }
        /// #endif
    };

    public removeTab(id: string, isBatchClose = false, animate = true, isSaveLayout = true) {
        for (let index = 0; index < this.children.length; index++) {
            const item = this.children[index];
            if (item.id === id) {
                if ((item.model instanceof Editor) && item.model.editor?.protyle) {
                    if (item.model.editor.protyle.upload.isUploading) {
                        showMessage(window.siyuan.languages.uploading);
                        return;
                    }
                    this.removeTabAction(id, isBatchClose, animate, isSaveLayout);
                } else {
                    this.removeTabAction(id, isBatchClose, animate, isSaveLayout);
                }
                return;
            }
        }
    }

    public moveTab(tab: Tab, nextId?: string) {
        const protyle = tab.model instanceof Editor ? tab.model.editor.protyle : undefined;
        const scrollTop = protyle?.contentElement.scrollTop;
        let rangeData: {
            id: string,
            start: number,
            end: number
        };
        if (tab.model instanceof Editor && tab.model.editor.protyle.toolbar.range) {
            const blockElement = hasClosestBlock(tab.model.editor.protyle.toolbar.range.startContainer);
            if (blockElement) {
                const startEnd = getSelectionOffset(blockElement, undefined, tab.model.editor.protyle.toolbar.range);
                rangeData = {
                    id: blockElement.getAttribute("data-node-id"),
                    start: startEnd.start,
                    end: startEnd.end
                };
            }
        }
        this.element.querySelector(".layout-tab-container").append(tab.panelElement);
        if (rangeData && tab.model instanceof Editor) {
            // DOM 移动后 range 会变化
            const range = focusByOffset(tab.model.editor.protyle.wysiwyg.element.querySelector(`[data-node-id="${rangeData.id}"]`), rangeData.start, rangeData.end);
            if (range) {
                tab.model.editor.protyle.toolbar.range = range;
            }
        }
        if (nextId) {
            // 只能用 find https://github.com/siyuan-note/siyuan/issues/3455
            this.children.find((item, index) => {
                if (item.id === nextId) {
                    this.children.splice(index, 0, tab);
                    return true;
                }
            });
        } else {
            this.children.push(tab);
        }
        if (this.children.length > window.siyuan.config.fileTree.maxOpenTabCount) {
            this.removeOverCounter();
        }

        const oldWnd = tab.parent;
        if (oldWnd.children.length === 1) {
            oldWnd.children = [];
            oldWnd.remove();
        } else {
            oldWnd.children.find((item, index) => {
                if (item.id === tab.id) {
                    oldWnd.children.splice(index, 1);
                    resizeTabs();
                    return true;
                }
            });
            if (!oldWnd.headersElement.querySelector(".item--focus")) {
                let latestHeadElement: HTMLElement;
                Array.from(oldWnd.headersElement.children).forEach((headItem: HTMLElement) => {
                    if (!latestHeadElement) {
                        latestHeadElement = headItem;
                    } else if (headItem.getAttribute("data-activetime") > latestHeadElement.getAttribute("data-activetime")) {
                        latestHeadElement = headItem;
                    }
                });
                if (latestHeadElement) {
                    oldWnd.switchTab(latestHeadElement, true);
                }
            }
        }

        // https://github.com/siyuan-note/siyuan/issues/13551
        this.switchTab(tab.headElement);

        tab.parent = this;
        hideAllElements(["toolbar"]);
        setTabPosition();
        if (protyle) {
            // 在浏览器绘制前恢复阅读位置,保留锚点供尺寸动画结束后再次校准。
            if (!restoreBeforeResizeTop(protyle, false)) {
                protyle.contentElement.scrollTop = scrollTop;
            }
        }
    }

    public split(direction: Config.TUILayoutDirection, after = true) {
        if (this.children.length === 1 && !this.children[0].headElement) {
            // 场景:没有打开的文档,点击标签面板打开
            return this;
        }
        recordBeforeResizeTop();
        const wnd = new Wnd(this.app, direction);
        if (direction === this.parent.direction) {
            this.parent.addWnd(wnd, this.id, after);
        } else if (this.parent.children.length === 1) {
            // layout 仅含一个时,只需更新 direction
            this.parent.direction = direction;
            if (direction === "tb") {
                this.parent.element.classList.add("fn__flex-column");
                this.parent.element.style.minHeight = "8px";
                this.parent.element.classList.remove("fn__flex");
            } else {
                this.parent.element.classList.remove("fn__flex-column");
                this.parent.element.classList.add("fn__flex");
            }
            this.parent.addWnd(wnd, this.id, after);
        } else {
            this.parent.children.find((item, index) => {
                if (item.id === this.id) {
                    const layout = new Layout({
                        resize: item.resize,
                        direction,
                    });
                    this.parent.addLayout(layout, item.id, after);
                    const movedWnd = this.parent.children.splice(after ? index : index + 1, 1)[0];
                    if (movedWnd.resize) {
                        if (movedWnd.element.previousElementSibling && movedWnd.element.previousElementSibling.classList.contains("layout__resize")) {
                            movedWnd.element.previousElementSibling.remove();
                        } else if (movedWnd.element.nextElementSibling && movedWnd.element.nextElementSibling.classList.contains("layout__resize")) {
                            movedWnd.element.nextElementSibling.remove();
                        }
                        movedWnd.resize = undefined;
                    }
                    if (after) {
                        layout.addWnd.call(layout, movedWnd);
                        layout.addWnd.call(layout, wnd);
                    } else {
                        layout.addWnd.call(layout, wnd);
                        layout.addWnd.call(layout, movedWnd);
                    }

                    if (direction === "tb" && movedWnd.element.style.width) {
                        layout.element.style.width = movedWnd.element.style.width;
                        layout.element.classList.remove("fn__flex-1");
                        movedWnd.element.style.width = "";
                        movedWnd.element.classList.add("fn__flex-1");
                    } else if (direction === "lr" && movedWnd.element.style.height) {
                        layout.element.style.height = movedWnd.element.style.height;
                        layout.element.classList.remove("fn__flex-1");
                        movedWnd.element.style.height = "";
                        movedWnd.element.classList.add("fn__flex-1");
                    }
                    return true;
                }
            });
        }
        return wnd;
    }

    private remove() {
        let layout = this.parent;
        let element = this.element;
        let id = this.id;
        while (layout && layout.children.length === 1 && "center" !== layout.type) {
            id = layout.id;
            element = layout.element;
            layout = layout.parent;
        }

        layout.children.find((item, index) => {
            if (item.id === id) {
                if (layout.children.length > 1) {
                    let previous = layout.children[index - 1];
                    if (index === 0) {
                        previous = layout.children[1];
                    }
                    if (layout.children.length === 2) {
                        if (layout.direction === "lr") {
                            previous.element.style.width = "";
                        } else {
                            previous.element.style.height = "";
                        }
                        previous.resize = undefined;
                        previous.element.classList.add("fn__flex-1");
                    }
                    // https://github.com/siyuan-note/siyuan/issues/5844
                    if (layout.children.length > 2 && index === 0) {
                        layout.children[1].resize = undefined;
                    }
                }
                layout.children.splice(index, 1);
                return true;
            }
        });
        if (element.previousElementSibling && element.previousElementSibling.classList.contains("layout__resize")) {
            element.previousElementSibling.remove();
        } else if (element.nextElementSibling && element.nextElementSibling.classList.contains("layout__resize")) {
            element.nextElementSibling.remove();
        }
        element.remove();
        fixWndFlex1(layout);
        resizeTabs();
    }
}