Skip to content

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

22.9 KB
Raw Blame
import {setEditMode} from "../util/setEditMode";
import {isTabGutterBridge} from "../gutter/tabs";
import {isContainerGutterBridge} from "../gutter/container";
import {cancelGutterHover, renderGutterOnHover} from "../gutter/hover";
import {scrollEvent} from "../scroll/event";
import {isMobile} from "../../util/functions";
import {Constants} from "../../constants";
import {getContenteditableElement, getEmbedGutterOperationContext, getLastBlock} from "../wysiwyg/getBlock";
import {genEmptyElement, genHeadingElement} from "../../block/util";
import {transaction} from "../wysiwyg/transaction";
import {focusByRange} from "../util/selectionOffsets";
/// #if !MOBILE
import {moveResize} from "../../dialog/moveResize";
/// #endif
import {
    hasClosestBlock,
    hasClosestByAttribute,
    hasClosestByClassName,
    hasClosestByTag,
    isInEmbedBlock
} from "../util/hasClosest";
import {hideElements} from "./hideElements";
import {AVAttributePanel} from "../render/av/attributePanel";
import {BACKLINK_EDITOR_PADDING, getEditorHorizontalPadding} from "./padding";
import {callMobileAppShowKeyboard} from "../../mobile/util/mobileAppUtil";
import {sanitizeKernelHTML} from "../../util/hostCapabilities";

const focusMobileAppEditor = (element: HTMLElement) => {
    if (window.JSAndroid?.showKeyboard || window.JSHarmony?.showKeyboard) {
        element.focus();
        callMobileAppShowKeyboard();
    }
};

export const initUI = (protyle: IProtyle) => {
    protyle.contentElement = document.createElement("div");
    protyle.contentElement.className = "protyle-content";
    if (window.siyuan.config.editor.fullWidth) {
        protyle.contentElement.dataset.fullwidth = "true";
        protyle.preview.element.dataset.fullwidth = "true";
    }
    if (!isMobile() && CSS.supports("container-type", "inline-size") &&
        CSS.supports("width", "1cqi") && !protyle.options.action.includes(Constants.CB_GET_HISTORY) &&
        !protyle.options.backlinkData) {
        protyle.contentElement.dataset.paddingMode = "responsive";
        if (protyle.options.preview.actions.includes("desktop")) {
            protyle.preview.element.dataset.paddingMode = "responsive";
        }
    }

    if (protyle.options.render.background || protyle.options.render.title) {
        protyle.contentElement.innerHTML = '<div class="protyle-top"></div>';
        if (protyle.options.render.background) {
            protyle.contentElement.firstElementChild.appendChild(protyle.background.element);
        }
        if (protyle.options.render.title) {
            protyle.contentElement.firstElementChild.appendChild(protyle.title.element);
        }
    }

    if (protyle.options.databaseAttr && !protyle.options.action.includes(Constants.CB_GET_HISTORY) && !protyle.options.backlinkData) {
        let topElement = protyle.contentElement.querySelector(".protyle-top");
        if (!topElement) {
            topElement = document.createElement("div");
            topElement.className = "protyle-top";
            protyle.contentElement.appendChild(topElement);
        }
        protyle.databaseAttributePanel = new AVAttributePanel(protyle);
        topElement.appendChild(protyle.databaseAttributePanel.element);
    }

    protyle.contentElement.appendChild(protyle.wysiwyg.element);
    if (!protyle.options.action.includes(Constants.CB_GET_HISTORY)) {
        scrollEvent(protyle, protyle.contentElement);
    }
    protyle.element.append(protyle.contentElement);
    protyle.element.appendChild(protyle.preview.element);
    if (protyle.upload) {
        protyle.element.appendChild(protyle.upload.element);
    }
    if (protyle.options.render.scroll) {
        protyle.element.appendChild(protyle.scroll.element.parentElement);
    }
    if (protyle.gutter) {
        protyle.element.appendChild(protyle.gutter.element);
    }

    protyle.element.appendChild(protyle.hint.element);

    const selectContainer = document.createElement("div");
    selectContainer.className = "protyle-select__container";
    protyle.selectElement = document.createElement("div");
    protyle.selectElement.className = "protyle-select fn__none";
    selectContainer.appendChild(protyle.selectElement);
    protyle.element.appendChild(selectContainer);

    protyle.element.appendChild(protyle.toolbar.element);
    protyle.element.appendChild(protyle.toolbar.subElement);
    /// #if !MOBILE
    moveResize(protyle.toolbar.subElement, (type) => {
        const pinElement = protyle.toolbar.subElement.querySelector('.block__icons [data-type="pin"]');
        if (pinElement) {
            pinElement.querySelector("svg use").setAttribute("xlink:href", "#iconUnpin");
            pinElement.setAttribute("aria-label", window.siyuan.languages.unpin);
            protyle.toolbar.subElement.firstElementChild.setAttribute("data-drag", "true");
        }
        if (type !== "move" && protyle.toolbar.subElementResizeCB) {
            protyle.toolbar.subElementResizeCB();
        }
    });
    /// #endif

    protyle.element.append(protyle.highlight.styleElement);

    addLoading(protyle);

    setEditMode(protyle, protyle.options.mode);
    document.execCommand("DefaultParagraphSeparator", false, "p");

    protyle.contentElement.addEventListener("mousedown", (event: MouseEvent & { target: HTMLElement }) => {
        if (event.button !== 0 || !event.shiftKey) {
            return;
        }
        const eventProtyleElement = hasClosestByClassName(event.target, "protyle", true);
        if (eventProtyleElement && eventProtyleElement !== protyle.element) {
            return;
        }
        if (hasClosestByClassName(event.target, "sy__backlink--bottom", true)) {
            return;
        }
        const lastElement = protyle.wysiwyg.element.lastElementChild;
        if (!lastElement || event.clientY <= lastElement.getBoundingClientRect().bottom) {
            return;
        }
        // 文档末尾空白位于 wysiwyg 外层,需在 click 聚焦末尾块之前完成 Shift 范围选择
        // https://github.com/siyuan-note/siyuan/issues/11960
        if (protyle.wysiwyg.selectByShiftClick(protyle, event, undefined, true)) {
            event.preventDefault();
            event.stopPropagation();
        }
    });
    protyle.contentElement.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {
        const eventProtyleElement = hasClosestByClassName(event.target, "protyle", true);
        if (eventProtyleElement && eventProtyleElement !== protyle.element) {
            return;
        }
        hideElements(["hint", "util"], protyle);
        // wysiwyg 元素下方点击无效果 https://github.com/siyuan-note/siyuan/issues/12009
        if (protyle.disabled ||
            // 选中块时,禁止添加空块 https://github.com/siyuan-note/siyuan/issues/13905
            protyle.contentElement.querySelector(".protyle-wysiwyg--select") ||
            (!event.target.classList.contains("protyle-content") && !event.target.classList.contains("protyle-wysiwyg"))) {
            return;
        }
        // https://github.com/siyuan-note/siyuan/issues/14190 选中最后一个块末尾点击底部时,range 会有值,需使用 setTimeout,最新测试无需 setTimeout 了,且会影响移动端键盘弹起故移除
        // 选中文本禁止添加空块 https://github.com/siyuan-note/siyuan/issues/13905
        if (window.getSelection().rangeCount > 0) {
            const currentRange = window.getSelection().getRangeAt(0);
            if (currentRange.toString() !== "" && protyle.wysiwyg.element.contains(currentRange.startContainer)) {
                return;
            }
        }
        const lastElement = protyle.wysiwyg.element.lastElementChild;
        const backlinkElement = protyle.wysiwyg.element.nextElementSibling;
        if (backlinkElement?.classList.contains("sy__backlink--bottom") &&
            backlinkElement.getClientRects().length > 0 &&
            event.clientY >= backlinkElement.getBoundingClientRect().top) {
            return;
        }
        const lastRect = lastElement.getBoundingClientRect();
        const range = document.createRange();
        if (event.y > lastRect.bottom) {
            const lastEditElement = getContenteditableElement(getLastBlock(lastElement));
            if (!protyle.options.click.preventInsetEmptyBlock && (
                !lastEditElement ||
                (lastElement.getAttribute("data-type") !== "NodeParagraph" && protyle.wysiwyg.element.getAttribute("data-doc-type") !== "NodeListItem") ||
                (lastElement.getAttribute("data-type") === "NodeParagraph" && getContenteditableElement(lastEditElement).innerHTML !== ""))
            ) {
                let emptyElement: Element;
                if (lastElement.getAttribute("data-type") === "NodeHeading" && lastElement.getAttribute("fold") === "1") {
                    emptyElement = genHeadingElement(lastElement) as Element;
                } else {
                    emptyElement = genEmptyElement(false, false);
                }
                protyle.wysiwyg.element.insertAdjacentElement("beforeend", emptyElement);
                transaction(protyle, [{
                    action: "insert",
                    data: emptyElement.outerHTML,
                    id: emptyElement.getAttribute("data-node-id"),
                    previousID: emptyElement.previousElementSibling.getAttribute("data-node-id"),
                    parentID: protyle.block.parentID
                }], [{
                    action: "delete",
                    id: emptyElement.getAttribute("data-node-id")
                }]);
                const emptyEditElement = getContenteditableElement(emptyElement) as HTMLElement;
                range.selectNodeContents(emptyEditElement);
                range.collapse(true);
                focusByRange(range);
                focusMobileAppEditor(emptyEditElement);
                // 需等待 range 更新再次进行渲染
                if (protyle.options.render.breadcrumb) {
                    setTimeout(() => {
                        protyle.breadcrumb.render(protyle);
                    }, Constants.TIMEOUT_TRANSITION);
                }
            } else if (lastEditElement) {
                range.selectNodeContents(lastEditElement);
                range.collapse(false);
                focusByRange(range);
                focusMobileAppEditor(lastEditElement as HTMLElement);
            }
            protyle.toolbar.range = range;
        }
    });
    let overAttr = false;
    protyle.element.addEventListener("mouseleave", () => cancelGutterHover(protyle.gutter?.element));
    protyle.element.addEventListener(isMobile() ? "pointerover" : "mouseover", (event: PointerEvent & {
        target: HTMLElement
    }) => {
        const eventProtyleElement = hasClosestByClassName(event.target, "protyle", true);
        if (eventProtyleElement && eventProtyleElement !== protyle.element) {
            return;
        }
        if (isMobile() && event.pointerType !== "mouse") {
            return;
        }
        cancelGutterHover(protyle.gutter?.element);
        if (hasClosestByClassName(event.target, "protyle-db-attr")) {
            return;
        }
        // attr
        const attrElement = hasClosestByClassName(event.target, "protyle-attr");
        if (attrElement && !attrElement.parentElement.classList.contains("protyle-title")) {
            const hlElement = protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--hl");
            if (hlElement) {
                hlElement.classList.remove("protyle-wysiwyg--hl");
            }
            overAttr = true;
            attrElement.parentElement.classList.add("protyle-wysiwyg--hl");
            return;
        } else if (overAttr) {
            const hlElement = protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--hl");
            if (hlElement) {
                hlElement.classList.remove("protyle-wysiwyg--hl");
            }
            overAttr = false;
        }

        if (protyle.gutter && isTabGutterBridge(protyle.wysiwyg.element, protyle.gutter.element,
            event.target, event.clientX, event.clientY)) {
            return;
        }
        const tabsHeader = hasClosestByClassName(event.target, "tabs-header");
        const nodeElement = tabsHeader ? hasClosestBlock(tabsHeader.parentElement) : hasClosestBlock(event.target);
        if (!tabsHeader && nodeElement && nodeElement.getAttribute("data-type") === "NodeTabItem" &&
            nodeElement.parentElement.classList.contains("tabs")) {
            hideElements(["gutter"], protyle);
            return;
        }
        if (protyle.options.render.gutter && nodeElement) {
            if (!protyle.wysiwyg.element.contains(nodeElement)) {
                hideElements(["gutter"], protyle);
                return;
            }
            if (isContainerGutterBridge(protyle.gutter.element, nodeElement, event.target,
                event.clientX, event.clientY, button => protyle.gutter.getNodeElement(protyle, button))) {
                return;
            }
            if (nodeElement && (nodeElement.classList.contains("list") || nodeElement.classList.contains("li"))) {
                // 光标在列表下部应显示右侧的元素,而不是列表本身。放在 windowEvent 中的 mousemove 下处理
                return;
            }
            const embedElement = isInEmbedBlock(nodeElement);
            if (embedElement) {
                renderGutterOnHover(protyle,
                    getEmbedGutterOperationContext(nodeElement) ? nodeElement : embedElement, event.target);
                return;
            }
            renderGutterOnHover(protyle, nodeElement, event.target);
            return;
        }

        // gutter
        const buttonElement = hasClosestByTag(event.target, "BUTTON");
        if (buttonElement && buttonElement.parentElement.classList.contains("protyle-gutters")) {
            const type = buttonElement.getAttribute("data-type");
            if (buttonElement.classList.contains("protyle-gutters__line") ||
                buttonElement.classList.contains("protyle-gutters__plus")) {
                return;
            }
            const targetButtonElement = type === "fold" ?
                buttonElement.previousElementSibling || buttonElement.nextElementSibling : buttonElement;
            if (!targetButtonElement) {
                hideElements(["gutter"], protyle);
                return;
            }
            const gutterNodeElement = protyle.gutter.getNodeElement(protyle, targetButtonElement);
            if (!gutterNodeElement) {
                hideElements(["gutter"], protyle);
                return;
            }
            if (type === "fold") {
                Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--hl, .av__row--hl")).forEach(item => {
                    item.classList.remove("protyle-wysiwyg--hl", "av__row--hl");
                });
                return;
            }
            const bodyQueryClass = (buttonElement.dataset.groupId && buttonElement.dataset.groupId !== "undefined") ? `.av__body[data-group-id="${buttonElement.dataset.groupId}"] ` : "";
            const rowItem = gutterNodeElement.querySelector(bodyQueryClass + `.av__row[data-id="${buttonElement.dataset.rowId}"]`);
            if ((type === "NodeAttributeViewRow" || type === "NodeAttributeViewRowMenu") && !rowItem) {
                hideElements(["gutter"], protyle);
                return;
            }
            if (type === "NodeAttributeViewRow") {
                Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--hl, .av__row--hl")).forEach(item => {
                    item.classList.remove("protyle-wysiwyg--hl", "av__row--hl");
                });
                return;
            }
            Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--hl, .av__row--hl")).forEach(hlItem => {
                if (gutterNodeElement !== hlItem) {
                    hlItem.classList.remove("protyle-wysiwyg--hl");
                }
                if (rowItem && rowItem !== hlItem) {
                    rowItem.classList.remove("av__row--hl");
                }
            });
            if (type === "NodeAttributeViewRowMenu") {
                rowItem.classList.add("av__row--hl");
            } else {
                gutterNodeElement.classList.add("protyle-wysiwyg--hl");
            }
            event.preventDefault();
            return;
        }

        // 面包屑
        if (protyle.selectElement.classList.contains("fn__none")) {
            const svgElement = hasClosestByAttribute(event.target, "data-node-id", null);
            if (svgElement && svgElement.parentElement.classList.contains("protyle-breadcrumb__bar")) {
                protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--hl").forEach(item => {
                    item.classList.remove("protyle-wysiwyg--hl");
                });
                const nodeElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${svgElement.getAttribute("data-node-id")}"]`);
                if (nodeElement) {
                    nodeElement.classList.add("protyle-wysiwyg--hl");
                }
            }
        }
    });
};

export const addLoading = (protyle: IProtyle, msg?: string) => {
    protyle.element.removeAttribute("data-loading");
    setTimeout(() => {
        if (protyle.element.getAttribute("data-loading") !== "finished") {
            protyle.element.insertAdjacentHTML("beforeend", `<div style="background-color: var(--b3-theme-background);flex-direction: column;" class="fn__loading wysiwygLoading">
    <span class="b3-loading b3-loading--large" aria-hidden="true"></span>
    <div style="color: var(--b3-theme-on-surface);margin-top: 8px;">${sanitizeKernelHTML(msg || "")}</div>
</div>`);
        }
    }, Constants.TIMEOUT_LOAD);
};

export const removeLoading = (protyle: IProtyle) => {
    protyle.element.setAttribute("data-loading", "finished");
    protyle.element.querySelectorAll(".wysiwygLoading").forEach(item => {
        item.remove();
    });
};

export const setPadding = (protyle: IProtyle) => {
    if (protyle.options.action.includes(Constants.CB_GET_HISTORY)) {
        return {
            width: 0,
            padding: 0
        };
    }
    const padding = getPadding(protyle);
    protyle.preview.updatePadding(padding);
    const responsivePadding = protyle.contentElement.dataset.paddingMode === "responsive";
    let paddingLeft = protyle.options.backlinkData ? 24 : padding.left;
    let paddingRight = protyle.options.backlinkData ? 16 : padding.right;
    if (protyle.element.classList.contains("protyle--page-scroll")) {
        paddingRight = Math.max(paddingRight, parseFloat(getComputedStyle(protyle.element)
            .getPropertyValue("--b3-protyle-page-scroll-gutter")) || 0);
    }
    const backlinkBottomElement = protyle.contentElement.querySelector(".sy__backlink--bottom") as HTMLElement;
    const backlinkBottomVisible = backlinkBottomElement &&
        !backlinkBottomElement.classList.contains("fn__none") &&
        !backlinkBottomElement.classList.contains("sy__backlink--pending");
    const backlinkBottomGap = 128;

    if (responsivePadding) {
        const paddingBottom = backlinkBottomVisible && protyle.options.typewriterMode ? backlinkBottomGap : padding.bottom;
        protyle.wysiwyg.element.style.padding = "";
        protyle.wysiwyg.element.style.paddingTop = `${padding.top}px`;
        protyle.wysiwyg.element.style.paddingBottom = `${paddingBottom}px`;
        const wysiwygStyle = getComputedStyle(protyle.wysiwyg.element);
        paddingLeft = parseFloat(wysiwygStyle.paddingLeft);
        paddingRight = parseFloat(wysiwygStyle.paddingRight);
    } else if (protyle.options.backlinkData) {
        protyle.wysiwyg.element.style.padding = BACKLINK_EDITOR_PADDING;
    } else {
        const paddingBottom = backlinkBottomVisible && protyle.options.typewriterMode ? backlinkBottomGap : padding.bottom;
        protyle.wysiwyg.element.style.padding = `${padding.top}px ${paddingRight}px ${paddingBottom}px ${paddingLeft}px`;
    }
    if (protyle.options.render.background) {
        const backgroundIAElement = protyle.background.element.querySelector<HTMLElement>(".protyle-background__ia");
        if (responsivePadding) {
            backgroundIAElement.style.margin = "";
        } else {
            backgroundIAElement.style.marginLeft = `${paddingLeft}px`;
            backgroundIAElement.style.marginRight = `${paddingRight}px`;
        }
    }
    if (protyle.options.render.title) {
        // pc 端 文档名 attr 过长和添加标签等按钮重合
        if (responsivePadding) {
            protyle.title.element.style.margin = "";
            protyle.title.element.style.marginTop = "16px";
        } else {
            protyle.title.element.style.margin = `16px ${paddingRight}px 0 ${paddingLeft}px`;
        }
    }
    if (protyle.databaseAttributePanel) {
        if (responsivePadding) {
            protyle.databaseAttributePanel.element.style.margin = "";
            protyle.databaseAttributePanel.element.style.marginTop = "8px";
            protyle.databaseAttributePanel.element.style.marginBottom = "8px";
        } else {
            protyle.databaseAttributePanel.element.style.margin = `8px ${paddingRight}px 8px ${paddingLeft}px`;
        }
    }
    if (backlinkBottomElement) {
        if (responsivePadding) {
            backlinkBottomElement.style.padding = "";
            backlinkBottomElement.style.paddingTop = "0";
            backlinkBottomElement.style.paddingBottom = "16px";
        } else {
            backlinkBottomElement.style.padding = `0 ${paddingRight}px 16px ${paddingLeft}px`;
        }
        backlinkBottomElement.style.marginBottom = backlinkBottomVisible && protyle.options.typewriterMode ?
            `${Math.max(padding.bottom - backlinkBottomGap, 0)}px` : "";
    }

    // https://github.com/siyuan-note/siyuan/issues/15021
    protyle.element.style.setProperty("--b3-width-protyle", protyle.element.clientWidth + "px");
    protyle.element.style.setProperty("--b3-width-protyle-content", protyle.contentElement.clientWidth + "px");
    const realWidth = protyle.wysiwyg.element.getAttribute("data-realwidth");
    const newWidth = protyle.wysiwyg.element.clientWidth - paddingLeft - paddingRight;
    protyle.wysiwyg.element.setAttribute("data-realwidth", newWidth.toString());
    protyle.element.style.setProperty("--b3-width-protyle-wysiwyg", newWidth.toString() + "px");
    return {
        width: realWidth ? Math.abs(parseFloat(realWidth) - newWidth) : 0,
    };
};

export const getPadding = (protyle: IProtyle) => {
    let right = 16;
    let left = 24;
    let bottom = 16;
    if (protyle.options.typewriterMode && protyle.preview.element.classList.contains("fn__none")) {
        bottom = protyle.element.clientHeight / 2;
    }
    if (!isMobile()) {
        let isFullWidth = protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_FULLWIDTH);
        if (!isFullWidth) {
            isFullWidth = window.siyuan.config.editor.fullWidth ? "true" : "false";
        }
        const padding = getEditorHorizontalPadding(protyle.element.clientWidth, isFullWidth !== "false");
        left = padding.left;
        right = padding.right;
    }
    return {
        left, right, bottom, top: 16
    };
};