Skip to content

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

18.5 KB
Raw Blame
import {addScript} from "../protyle/util/addScript";
import {ensureLute} from "../protyle/util/lute";
import {completeStartup, guardStartup, reportStartupError, setStartupLanguage, setStartupStage} from "../boot/startupError";
import {Constants} from "../constants";
import {systemConfig} from "../config/systemConfig";
import {refreshSettingConfig} from "../config/setting/sync";
import {openStandaloneDatabaseItemByURI} from "../protyle/render/av/openStandaloneDatabaseItem";
import {onMessage} from "./util/onMessage";
import {genUUID} from "../util/genID";
import {
    hasClosestBlock,
    hasClosestByAttribute,
    hasClosestByClassName,
    hasTopClosestByClassName
} from "../protyle/util/hasClosest";
import {Model} from "../layout/Model";
import "../assets/scss/mobile.scss";
import {Menus} from "../menus";
import {addBaseURL, parseSiYuanUriInfo, setNoteBook} from "../util/pathName";
import {activateQueuedAVLocate, queueAVLocateRequest} from "../protyle/render/av/locate";
import {
    handleTouchCancel,
    handleTouchContextMenu,
    handleTouchEnd,
    handleTouchMove,
    handleTouchSelectionChange,
    handleTouchStart,
    handleTouchUp,
    handleTouchEditing,
    handleTouchFocusOut,
} from "./util/touch";
import {fetchPost} from "../util/fetch";
import {initFramework} from "./util/initFramework";
import {finishMobileSystemUris, processMobileSystemUri} from "./util/systemUri";
import {saveMobileLayout} from "./util/saveLayout";
import {initAssets} from "../util/assets";
import {bootSync, lockScreen} from "../dialog/processSystem";
import {initMessage, showMessage} from "../dialog/message";
import {goBack} from "./util/MobileBackFoward";
import {
    activeBlur,
    hideKeyboardToolbarByApp,
    hideKeyboardToolbarUtilOnEditorClick,
    showKeyboardToolbar,
} from "./util/keyboardToolbar";
import {
    applyPlatformClasses,
    getLocalStorage,
    initWindowOpenOverride,
    isChromeBrowser,
    isInIOS,
    isInMobileApp,
    isIOSDevice,
    writeText
} from "../protyle/util/compatibility";
import {getCurrentEditor, openMobileFileById} from "./editor";
import {ensureOnboarding} from "../onboarding";
import {checkPublishServiceClosed} from "../util/processMessage";
import {initRightMenu} from "./menu";
import {openChangelog} from "../boot/openChangelog";
import {registerServiceWorker} from "../util/serviceWorker";
import {loadPlugins} from "../plugin/loader";
import {emitToPlugins} from "../plugin/EventBusCore";
import {removeBlock} from "../protyle/wysiwyg/remove";
import {isNotEditBlock} from "../protyle/wysiwyg/getBlock";
import {updateCardHV} from "../card/util";
import {mobileKeydown} from "./util/keydown";
import {correctHotkey} from "../boot/globalEvent/commonHotkey";
import {processIOSPurchaseResponse} from "../util/iOSPurchase";
import {nbsp2space} from "../protyle/util/normalizeText";
import {armKeyboardLock, callMobileAppShowKeyboard, canInput, setWebViewFocusable} from "./util/mobileAppUtil";
import {hideAllElements} from "../protyle/ui/hideElements";
import {initTouchDragBridge} from "../util/touchDragBridge";
import {bindPanelTransitionGuard} from "../util/panelTransition";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
import {openByMobile} from "../editor/openLink";
import {initHarmonyTextSelectionMenu} from "../util/harmonyTextSelectionMenu";
import {initMobileSelect} from "./util/nativeSelect";
import {updateMobileTopBarLayout} from "./util/mobileTopBar";
import {bindMobileOrientationChange} from "./util/orientation";
import {showMobileBars} from "./util/mobileBars";
import {initializeEnglishCommandTranslations} from "../command/english";
import {loadLanguages} from "../boot/loadLanguages";
import {scrollInputIntoView} from "./util/visibleViewport";
import {installPluginStorageFetchAppId} from "../util/fetchAppId";
import {initMobileWithLoading} from "./util/startup";

const startupRequestFailed = (response: IWebSocketData) => reportStartupError(new Error(response.msg || String(response.code)));

class App {
    public plugins: import("../plugin").Plugin[] = [];
    public appId: string;

    constructor() {
        if (checkPublishServiceClosed()) {
            completeStartup();
            return;
        }
        registerServiceWorker(`${Constants.SERVICE_WORKER_PATH}?v=${Constants.SIYUAN_VERSION}`);
        addBaseURL();
        initHarmonyTextSelectionMenu();
        this.appId = Constants.SIYUAN_APPID;

        const mainWs = new Model({app: this});
        mainWs.connect({
            id: genUUID(),
            type: "main",
            callback: () => {
                if (window.siyuan.isReady) {
                    void refreshSettingConfig().catch(error => console.error("Could not refresh settings", error));
                }
            },
            msgCallback: (data) => {
                emitToPlugins("ws-main", data);
                onMessage(this, data);
            }
        });

        window.siyuan = {
            zIndex: 10,
            isReady: false,
            notebooks: [],
            reqIds: {},
            backStack: [],
            dialogs: [],
            blockPanels: [],
            mobile: {
                size: {},
                docks: {
                    outline: null,
                    file: null,
                    bookmark: null,
                    tag: null,
                    backlink: null,
                    inbox: null,
                    agent: null,
                }
            },
            ws: mainWs
        };
        // 不能使用 touchstart,否则会被 event.stopImmediatePropagation() 阻塞
        document.addEventListener("touchstart", (event: TouchEvent) => {
            if (window.JSAndroid?.setWebViewFocusable && canInput(event.target as Element)) {
                // 在原生选区建立前启用焦点,保留首次双击的选择手柄。
                armKeyboardLock();
                window.JSAndroid.setWebViewFocusable(true);
            }
        }, true);
        window.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {
            const menu = window.siyuan.menus?.menu;
            if (menu && !menu.element.contains(event.target) && !hasClosestByAttribute(event.target, "data-menu", "true")) {
                menu.remove();
            }
            const copyElement = hasTopClosestByClassName(event.target, "protyle-action__copy");
            if (copyElement) {
                let text = copyElement.parentElement.nextElementSibling.textContent.trimEnd();
                text = nbsp2space(text); // Replace non-breaking spaces with normal spaces when copying https://github.com/siyuan-note/siyuan/issues/9382
                writeText(text);
                showMessage(window.siyuan.languages.copied, 2000);
                event.preventDefault();
            }
            const editableElement = canInput(event.target);
            if (editableElement && ["INPUT", "TEXTAREA"].includes(editableElement.tagName)) {
                setTimeout(() => {
                    scrollInputIntoView(editableElement);
                }, Constants.TIMEOUT_TRANSITION);
            }
            if (editableElement) {
                hideKeyboardToolbarUtilOnEditorClick();
                // 原生 App 通过桥接主动唤起键盘;移动端浏览器没有桥接,但点击可编辑区域后也会立刻触发 resize,
                // 进而调用 activeBlur 关闭键盘(比如三星键盘 https://github.com/siyuan-note/siyuan/issues/18078),所以此处也需要上锁
                if (window.JSAndroid && window.JSAndroid.showKeyboard || window.JSHarmony && window.JSHarmony.showKeyboard) {
                    callMobileAppShowKeyboard();
                } else {
                    armKeyboardLock();
                }
            }
            if (document.contains(event.target) && !hasClosestByClassName(event.target as Element, "protyle-util")) {
                hideAllElements(["util"]);
            }
        });
        {
            const __siyuan_original_focus = HTMLElement.prototype.focus;
            HTMLElement.prototype.focus = function (this: HTMLElement, ...args) {
                try {
                    if (typeof __siyuan_original_focus === "function") {
                        __siyuan_original_focus.apply(this, args);
                    }
                } catch (e) {
                    console.error("Error in focus event:", e);
                }
                if (canInput(this)) {
                    // 原生 App 通过桥接主动唤起键盘;移动端浏览器没有桥接,仅上锁以阻止 focus 后立即触发的 activeBlur 关闭键盘
                    if (window.JSAndroid && window.JSAndroid.showKeyboard || window.JSHarmony && window.JSHarmony.showKeyboard) {
                        callMobileAppShowKeyboard();
                    } else {
                        armKeyboardLock();
                    }
                }
            };
        }
        window.addEventListener("beforeunload", () => {
            void saveMobileLayout();
        }, false);
        window.addEventListener("pagehide", () => {
            void saveMobileLayout();
        }, false);
        document.addEventListener("visibilitychange", () => {
            if (document.visibilityState === "hidden") {
                void saveMobileLayout();
            }
        });
        // 判断手机横竖屏状态
        bindMobileOrientationChange(() => {
            updateCardHV();
            updateMobileTopBarLayout();
            showMobileBars();
            activeBlur();
        });
        setStartupStage("configuration");
        fetchPost("/api/system/getConf", {}, guardStartup<IWebSocketData>(async (confResponse) => {
            setStartupLanguage(confResponse.data.conf.appearance.lang);
            setStartupStage("engine");
            await ensureLute({reloadOnFailure: false});
            addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");
            window.siyuan.config = systemConfig(confResponse.data.conf);
            window.siyuan.isPublish = confResponse.data.isPublish;
            applyPlatformClasses();
            correctHotkey(siyuanApp);
            setStartupStage("plugins");
            await loadPlugins(this);
            setStartupStage("storage");
            getLocalStorage(guardStartup<void>(() => {
                setStartupStage("language");
                void loadLanguages(window.siyuan.config.appearance.lang, Constants.SIYUAN_VERSION, guardStartup<IObject>(async (languages) => {
                    setStartupStage("interface");
                    window.siyuan.languages = languages;
                    void initializeEnglishCommandTranslations(
                        window.siyuan.config.appearance.lang,
                        languages as Record<string, string>,
                        Constants.SIYUAN_VERSION,
                    );
                    window.siyuan.menus = new Menus(this);
                    initMobileSelect();
                    document.title = window.siyuan.languages.siyuanNote;
                    initMessage();
                    if (!isInMobileApp()) {
                        if (isChromeBrowser()) {
                            document.querySelector('meta[name="viewport"]').setAttribute("content", "width=device-width, height=device-height, interactive-widget=resizes-content, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover");
                        } else {
                            document.querySelector('meta[name="viewport"]').setAttribute("content", "width=device-width, height=device-height, interactive-widget=resizes-visual, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover");
                            if (!isIOSDevice() && !window.siyuan.config.readonly && !window.siyuan.isPublish
                                && window.siyuan.config.appearance.notifications?.browserCompatibility !== false) {
                                showMessage(window.siyuan.languages.useChrome, 0, "error");
                            }
                        }
                    } else if (!isInIOS()) {
                        document.querySelector('meta[name="viewport"]').setAttribute("content", "width=device-width, height=device-height, interactive-widget=resizes-visual, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover");
                    }
                    fetchPost("/api/setting/getCloudUser", {cached: true}, guardStartup<IWebSocketData>(async userResponse => {
                        window.siyuan.user = userResponse.data && "userId" in userResponse.data ? userResponse.data : null;
                        await ensureOnboarding();
                        fetchPost("/api/system/getEmojiConf", {}, guardStartup<IWebSocketData>(async emojiResponse => {
                            window.siyuan.emojis = emojiResponse.data as IEmoji[];
                            await setNoteBook();
                            await initMobileWithLoading(async () => {
                                await appearanceConfigApi.apply(window.siyuan.config.appearance);
                                initAssets(true);
                                await initFramework(this, confResponse.data.start);
                                initRightMenu(this);
                                openChangelog();
                            });
                            window.siyuan.isReady = true;
                            finishMobileSystemUris(this);
                            mainWs.flushMainMessages();
                            bootSync();
                            completeStartup();
                            fetchPost("/api/setting/getCloudUser", {});
                        }), undefined, startupRequestFailed);
                    }), undefined, startupRequestFailed);
                }), reportStartupError);
            }), reportStartupError);
            document.addEventListener("touchstart", handleTouchStart, false);
            document.addEventListener("touchmove", handleTouchMove, {passive: false});
            document.addEventListener("touchend", handleTouchEnd, false);
            document.addEventListener("touchcancel", handleTouchCancel, false);
            document.addEventListener("contextmenu", handleTouchContextMenu, true);
            document.addEventListener("focusout", handleTouchFocusOut, true);
            document.addEventListener("selectionchange", handleTouchSelectionChange, true);
            window.addEventListener("nativePhysicalTouchUp", handleTouchUp, false);
            window.addEventListener("nativeTextMenuWillPresent", handleTouchEditing, false);
            document.addEventListener("beforeinput", handleTouchEditing, true);
            document.addEventListener("paste", handleTouchEditing, true);
            window.addEventListener("keyup", () => {
                window.siyuan.ctrlIsPressed = false;
                window.siyuan.shiftIsPressed = false;
                window.siyuan.altIsPressed = false;
            });
            window.addEventListener("blur", () => {
                setWebViewFocusable();
            });
            // 移动端删除键 https://github.com/siyuan-note/siyuan/issues/9259
            window.addEventListener("keydown", (event) => {
                mobileKeydown(siyuanApp, event);
                if (getSelection().rangeCount > 0) {
                    const range = getSelection().getRangeAt(0);
                    const editor = getCurrentEditor();
                    if (range.toString() === "" &&
                        editor && editor.protyle.wysiwyg.element.contains(range.startContainer) &&
                        !event.altKey && (event.key === "Backspace" || event.key === "Delete")) {
                        const nodeElement = hasClosestBlock(range.startContainer);
                        if (nodeElement && isNotEditBlock(nodeElement)) {
                            nodeElement.classList.add("protyle-wysiwyg--select");
                            removeBlock(editor.protyle, nodeElement, range, event.key);
                            event.stopPropagation();
                            event.preventDefault();
                            return;
                        }
                    }
                }
            });
            ["sidebar", "sidebarRight"].forEach(id => {
                bindPanelTransitionGuard(document.getElementById(id));
            });
            initTouchDragBridge();
        }), undefined, startupRequestFailed);
    }
}

installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, document.baseURI, location.origin);
const siyuanApp = new App();

initWindowOpenOverride(siyuanApp, openByMobile);
// https://github.com/siyuan-note/siyuan/issues/8441
window.reconnectWebSocket = () => {
    // 后台唤醒时任一 socket 可能仍在 CONNECTING,调用 send 会抛 InvalidStateError,
    // 单独 try/catch 防止首个错误中断整个 ping 序列;下次 reconnectWebSocket 会再次尝试
    const tryPing = (m?: { send: (cmd: string, p: Record<string, unknown>) => void }) => {
        if (!m) {
            return;
        }
        try {
            m.send("ping", {});
        } catch (e) {
            console.warn("reconnectWebSocket: ping skipped", e);
        }
    };
    tryPing(window.siyuan.ws);
    tryPing(window.siyuan.mobile.docks?.file);
    tryPing(window.siyuan.mobile.editor?.protyle.ws);
    tryPing(window.siyuan.mobile.popEditor?.protyle.ws);
};
window.lockscreenByMode = () => {
    if (window.siyuan.config?.system.lockScreenMode === 1) {
        lockScreen();
    }
};
window.goBack = goBack;
window.showMessage = showMessage;
window.processIOSPurchaseResponse = processIOSPurchaseResponse;
window.showKeyboardToolbar = showKeyboardToolbar;
window.hideKeyboardToolbar = hideKeyboardToolbarByApp;
window.openFileByURL = (openURL) => {
    const blockInfo = parseSiYuanUriInfo(openURL);
    if (blockInfo != null) {
        if (openStandaloneDatabaseItemByURI(siyuanApp, blockInfo)) {
            return true;
        }
        if (blockInfo.avItemID) {
            queueAVLocateRequest(blockInfo.id, {
                itemID: blockInfo.avItemID,
                viewID: blockInfo.avViewID,
                groupID: blockInfo.avGroupID,
            });
        }
        openMobileFileById(siyuanApp, blockInfo.id, blockInfo.avItemID ? [Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL] :
            (blockInfo.focus ? [Constants.CB_GET_ALL] : [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL]),
        blockInfo.avItemID ? undefined : "start", undefined, blockInfo.avItemID ? (protyle) => activateQueuedAVLocate(protyle, blockInfo.id) : undefined);
        return true;
    }
    return processMobileSystemUri(siyuanApp, openURL);
};