Skip to content

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

13.6 KB
Raw Blame
import {toggleMenu} from "../../menus/menuToggle";
import {getTabContent, getTabItems, getTabTask, getTabTitle, getTabTitleBlock, hasTabsTasks, revealTabAncestors, tabsRender} from "../render/tabsRender";
import {repairActiveTab} from "./tabsRemoval";
import {transaction} from "./transaction";
import {Constants} from "../../constants";
import {fetchPost} from "../../util/fetch";
import {focusBlock} from "../util/selection";
import {focusByRange} from "../util/selectionOffsets";
import {genEmptyElement, genSBElement} from "../../block/util";
import {Menu} from "../../plugin/Menu";
import {processRender} from "../util/processCode";
import {avRender} from "../render/av/render";
import {isHiddenTabContent} from "../render/tabsVisibility";
import {queueTransaction} from "../util/transactionQueue";
import {remapTabsDOMIDs} from "../util/tabsCopy";
import {remapListMindmapIDs} from "../render/listMindmap/model";
import {copySubMenu, openAttr} from "../../menus/commonMenuItem";
import {isTaskListMarker, nextTaskListMarker} from "./taskListMarker";
import {hideElements} from "../ui/hideElements";
import {getTaskStatusItems} from "./taskStatusDialog";
import {canFocusTabItem, getFocusedTabItem, prepareFocusedTabItem} from "./tabsFocus";
import {zoomOut} from "../../menus/protyle";
import {getTabReadingID, saveTabReadingID} from "./tabsReading";

const boundFocusedTitles = new WeakSet<HTMLElement>();

export const toggleTabsTasks = (protyle: IProtyle, tabs: HTMLElement) => {
    const items = getTabItems(tabs);
    const enabled = hasTabsTasks(tabs);
    changeTabs(protyle, [tabs], () => {
        if (enabled) {
            tabs.removeAttribute("tabs-task");
        } else {
            tabs.setAttribute("tabs-task", "true");
        }
        items.forEach(item => item.removeAttribute("tabs-task"));
    });
};

export const setTabTask = (protyle: IProtyle, item: HTMLElement, marker: string) => {
    if (!item.isConnected || getTabTask(item) === null || !isTaskListMarker(marker)) {
        return;
    }
    changeTabs(protyle, [item], () => item.setAttribute("tabs-task", marker));
};

const canEdit = (protyle: IProtyle, element: Element) => !protyle.disabled &&
    !protyle.options.action.includes(Constants.CB_GET_HISTORY) &&
    !element.closest(".protyle-wysiwyg__embed, .mindmap-view__preview-block") &&
    element.closest(".protyle-wysiwyg") === protyle.wysiwyg.element;

// 同一事务提交受影响的最外层容器,嵌套移动时避免父子更新相互覆盖。
const changeTabs = (protyle: IProtyle, elements: HTMLElement[], change: () => void) => {
    if (elements.some(element => !element.dataset.nodeId || !canEdit(protyle, element))) {
        return;
    }
    const roots = Array.from(new Set(elements)).filter(element =>
        !elements.some(other => other !== element && other.contains(element)));
    const before = roots.map(element => element.outerHTML);
    change();
    transaction(protyle, roots.map(element => {
        element.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
        return {action: "update", id: element.dataset.nodeId, data: element.outerHTML};
    }), roots.map((element, index) => ({action: "update", id: element.dataset.nodeId, data: before[index]})));
};

const newTab = (protyle: IProtyle) => {
    const template = document.createElement("template");
    template.innerHTML = protyle.lute.Md2BlockDOM("::: tabs\n@tab\n\n:::\n");
    return template.content.querySelector<HTMLElement>(".tab-item");
};

export const renameTab = (protyle: IProtyle, item: HTMLElement) => {
    if (!canEdit(protyle, item)) {
        return;
    }
    revealTabAncestors(protyle.wysiwyg.element, item);
    item.dataset.tabsEditing = "true";
    initEditorTabs(protyle);
    const title = getTabTitle(item);
    const range = document.createRange();
    range.selectNodeContents(title);
    title.focus();
    focusByRange(range);
};

const addTab = (protyle: IProtyle, tabs: HTMLElement) => {
    const item = newTab(protyle);
    if (hasTabsTasks(tabs)) {
        item.setAttribute("tabs-task", " ");
    }
    changeTabs(protyle, [tabs], () => {
        tabs.insertBefore(item, tabs.querySelector(":scope > .protyle-attr"));
        tabs.setAttribute("tabs-active-id", item.dataset.nodeId);
    });
    renameTab(protyle, item);
};

export const moveTab = (protyle: IProtyle, source: HTMLElement, target: HTMLElement, after = false) => {
    if (source === target || source.contains(target)) {
        return;
    }
    const from = source.parentElement;
    const to = target.parentElement;
    if (!from.classList.contains("tabs") || !to.classList.contains("tabs")) {
        return;
    }
    const ids = getTabItems(from).map(item => item.dataset.nodeId);
    const task = getTabTask(source);
    changeTabs(protyle, [from, to], () => {
        if (from !== to && task !== null) {
            source.setAttribute("tabs-task", task);
        }
        to.insertBefore(source, after ? target.nextSibling : target);
        if (from !== to) {
            repairActiveTab(from, ids, source.dataset.nodeId);
        }
        to.setAttribute("tabs-active-id", source.dataset.nodeId);
    });
};

export const unwrapTabs = (protyle: IProtyle, tabs: HTMLElement) => {
    changeTabs(protyle, [tabs], () => {
        getTabItems(tabs).forEach(item => {
            const content = getTabContent(item);
            const title = getTabTitle(item);
            const blocks = Array.from(content.children);
            const titleBlock = getTabTitleBlock(item);
            if (titleBlock) {
                titleBlock.removeAttribute("tabs-title");
                title.classList.remove("tab-item-title", "callout-title");
                blocks.unshift(titleBlock);
            } else if (title.innerHTML) {
                const paragraph = genEmptyElement(false, false);
                paragraph.firstElementChild.innerHTML = title.innerHTML;
                blocks.unshift(paragraph);
            }
            item.className = "sb";
            item.dataset.type = "NodeSuperBlock";
            item.dataset.sbLayout = "row";
            item.removeAttribute("data-tabs-hidden");
            item.removeAttribute("tabs-task");
            item.replaceChildren(...blocks, genSBElement("row").lastElementChild);
        });
        tabs.querySelector(":scope > .tabs-header")?.remove();
        tabs.querySelector(":scope > .tabs-divider")?.remove();
        tabs.className = "sb";
        tabs.dataset.type = "NodeSuperBlock";
        tabs.dataset.sbLayout = "row";
        tabs.removeAttribute("tabs-active-id");
        tabs.removeAttribute("tabs-position");
        tabs.removeAttribute("tabs-task");
    });
};

export const setTabsPosition = (protyle: IProtyle, tabs: HTMLElement, position: "top" | "left") => {
    if ((tabs.getAttribute("tabs-position") || "top") !== position) {
        changeTabs(protyle, [tabs], () => tabs.setAttribute("tabs-position", position));
    }
};

export const openTabsMenu = (protyle: IProtyle, tabs: HTMLElement, item: HTMLElement, anchor: HTMLElement, toggle = true) => {
    toggleMenu({
        target: anchor,
        toggle,
        build: (_menu, session) => {
            if (!item) {
                return;
            }
            const lang = window.siyuan.languages;
            const menu = new Menu();
            menu.addItem({icon: "iconCopy", label: lang.copy, submenu: copySubMenu([item.dataset.nodeId], false)});
            if (canFocusTabItem(protyle, item)) {
                menu.addItem({icon: "iconEnter", label: lang.enter, click: () => zoomOut({protyle, id: item.dataset.nodeId})});
            }
            if (canEdit(protyle, tabs)) {
                if (getTabTask(item) !== null) {
                    menu.addSeparator({id: "separator_taskStatusBefore"});
                    getTaskStatusItems(getTabTask(item), marker => setTabTask(protyle, item, marker))
                        .forEach(option => menu.addItem(option));
                    menu.addSeparator({id: "separator_taskStatus"});
                }
                menu.addItem({icon: "iconEdit", label: lang.rename, click: () => renameTab(protyle, item)});
            }
            if (canEdit(protyle, tabs) && tabs.classList.contains("tabs")) {
                menu.addItem({
                    icon: "iconCopy", label: lang.duplicateCopy, click: () => {
                        const copy = item.cloneNode(true) as HTMLElement;
                        const ids = new Map<string, string>();
                        [copy, ...Array.from(copy.querySelectorAll<HTMLElement>("[data-node-id]"))].forEach(block => {
                            const id = Lute.NewNodeID();
                            ids.set(block.dataset.nodeId, id);
                            block.dataset.nodeId = id;
                            block.setAttribute("updated", id.substring(0, 14));
                        });
                        remapTabsDOMIDs(copy, ids);
                        remapListMindmapIDs(copy, ids);
                        changeTabs(protyle, [tabs], () => {
                            item.after(copy);
                            tabs.setAttribute("tabs-active-id", copy.dataset.nodeId);
                        });
                    }
                });
                menu.addItem({
                    icon: "iconTrashcan", label: lang.delete, click: () => {
                        const ids = getTabItems(tabs).map(entry => entry.dataset.nodeId);
                        changeTabs(protyle, [tabs], () => {
                            item.remove();
                            repairActiveTab(tabs, ids, item.dataset.nodeId);
                        });
                        focusBlock(tabs);
                    }
                });
            }
            const rect = anchor.getBoundingClientRect();
            session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height}));

        },
    });
};

export const initEditorTabs = (protyle: IProtyle) => {
    const root = protyle.wysiwyg.element;
    const measured = new WeakSet<Element>();
    if (!boundFocusedTitles.has(root)) {
        boundFocusedTitles.add(root);
        root.addEventListener("contextmenu", event => {
            if (event.shiftKey || protyle.toolbar?.isMultiSelectMode()) {
                return;
            }
            const item = getFocusedTabItem(protyle);
            const info = (event.target as Element).closest(".tab-item-info");
            if (item?.parentElement === root && info?.parentElement === item) {
                event.preventDefault();
                event.stopPropagation();
                openTabsMenu(protyle, item, item, info as HTMLElement, false);
            }
        }, true);
    }
    tabsRender(root, {
        prepare: () => prepareFocusedTabItem(protyle),
        readonly: tabs => !canEdit(protyle, tabs || root),
        restore: tabs => getTabReadingID(protyle, tabs),
        remember: (tabs, id) => saveTabReadingID(protyle, tabs, id),
        label: window.siyuan.languages.tabItem,
        addLabel: window.siyuan.languages.newTabItem,
        taskLabel: window.siyuan.languages.task,
        attributes: {label: window.siyuan.languages.attr, open: (block, focus) => openAttr(block, focus, protyle)},
        task: item => setTabTask(protyle, item, nextTaskListMarker(getTabTask(item))),
        endEdit: () => hideElements(["toolbar"], protyle),
        activate: item => {
            if (!canEdit(protyle, item)) {
                return;
            }
            // 切换页签时同步正文光标和工具栏选区,后续操作沿用当前页签的位置。
            const content = getTabContent(item);
            const target = Array.from(content.querySelectorAll<HTMLElement>('[contenteditable="true"]'))
                .find(element => !isHiddenTabContent(element) && element.getClientRects().length > 0);
            const range = document.createRange();
            range.selectNodeContents(target || content);
            range.collapse(true);
            hideElements(["toolbar"], protyle);
            focusByRange(range);
            protyle.toolbar.range = range.cloneRange();
        },
        select: (tabs, id) => {
            if (!canEdit(protyle, tabs) || tabs.getAttribute("tabs-active-id") === id) {
                return;
            }
            tabs.setAttribute("tabs-active-id", id);
            if (!protyle.lite) {
                queueTransaction(protyle, async () => {
                    // 撤销及移动会替换容器或移除占位页签,排队保存时只提交仍有效的当前选择。
                    if (!tabs.isConnected || tabs.getAttribute("tabs-active-id") !== id ||
                        !getTabItems(tabs).some(item => item.dataset.nodeId === id)) {
                        return;
                    }
                    await fetchPost("/api/attr/setBlockAttrs", {
                        id: tabs.dataset.nodeId, attrs: {"tabs-active-id": id},
                    });
                });
            }
        },
        rename: item => renameTab(protyle, item),
        add: tabs => addTab(protyle, tabs),
        menu: (tabs, item, anchor) => openTabsMenu(protyle, tabs, item, anchor),
        move: (source, target, after) => moveTab(protyle, source, target, after),
        shown: item => requestAnimationFrame(() => {
            if (!item.isConnected || isHiddenTabContent(item)) {
                return;
            }
            item.querySelectorAll(".render-node[data-subtype]").forEach(element => {
                if (!isHiddenTabContent(element) && !measured.has(element)) {
                    element.removeAttribute("data-render");
                    measured.add(element);
                }
            });
            processRender(item);
            avRender(item, protyle);
            protyle.contentElement?.dispatchEvent(new Event("scroll"));
        }),
    });
};