Skip to content

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

2.6 KB
Raw Blame
const editors = new Map<Element, IProtyle>();
let activeEditor: IProtyle;
const undoContexts = new WeakMap<IProtyle, {owner: IProtyle, run: (redo: boolean) => void}>();

export const setMobileToolbarUndo = (protyle: IProtyle, owner: IProtyle, run: (redo: boolean) => void) => {
    undoContexts.set(protyle, {owner, run});
};

export const getMobileToolbarUndo = (protyle: IProtyle) => undoContexts.get(protyle);

export const getMobileToolbarPaddingElement = (protyle: IProtyle) => {
    // 单元格的键盘占位放在所属编辑器上,避免撑高表格行。
    const owner = undoContexts.get(protyle)?.owner || protyle;
    // 智能体输入框有高度上限,键盘占位由整个页面承担,保持输入区位于面板上方。
    const agentPanel = owner.element.closest<HTMLElement>(".sy__agentChat--mobile");
    if (agentPanel) {
        return agentPanel;
    }
    return owner.lite ? owner.contentElement : owner.element.parentElement;
};

export const getMobileToolbarProtyle = () => {
    const root = document.activeElement?.closest(".protyle-wysiwyg");
    if (root) {
        activeEditor = editors.get(root);
    }
    if (activeEditor && (!activeEditor.element.isConnected || activeEditor.element.closest("[inert]"))) {
        activeEditor = undefined;
    }
    return activeEditor;
};

export const bindMobileToolbar = (protyle: IProtyle) => {
    const element = protyle.wysiwyg.element;
    editors.set(element, protyle);
    const activate = (event: Event) => {
        if ((event.target as Element).closest(".protyle-wysiwyg") !== element) {
            return;
        }
        if (activeEditor === protyle) {
            // 重新获得焦点时刷新工具栏,同时保留当前编辑器已经展开的菜单。
            if (event.type === "focusin") {
                window.dispatchEvent(new Event("siyuan-mobile-toolbar-focus"));
            }
            return;
        }
        const previous = activeEditor;
        activeEditor = protyle;
        // 共享工具栏切换编辑上下文,保留各编辑器自己的选区和撤销栈。
        window.dispatchEvent(new CustomEvent("siyuan-mobile-toolbar-editor", {detail: previous}));
    };
    element.addEventListener("focusin", activate);
    element.addEventListener("pointerdown", activate);
    return () => {
        element.removeEventListener("focusin", activate);
        element.removeEventListener("pointerdown", activate);
        editors.delete(element);
        if (activeEditor === protyle) {
            activeEditor = undefined;
            window.dispatchEvent(new CustomEvent("siyuan-mobile-toolbar-editor", {detail: protyle}));
        }
    };
};