Skip to content

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

:bug: Wait for the initial mobile view before completing startup https://github.com/siyuan-note/siyuan/issues/20870

Daniel9aafc184d9a0
diff --git a/app/src/boot/startupError.test.ts b/app/src/boot/startupError.test.ts
index 92d59293e4..2a86d2d876 100644
--- a/app/src/boot/startupError.test.ts
+++ b/app/src/boot/startupError.test.ts
@@ -145,14 +145,14 @@ test("background time does not consume a startup deadline", () => {
});
test("normal layout completion preserves a visible startup failure until the application is ready", () => {
- const source = readFileSync("src/mobile/util/setEmpty.ts", "utf8");
+ const source = readFileSync("src/mobile/util/startup.ts", "utf8");
const functionSource = source.match(/export const finishMobileStartup = \(\) => \{[\s\S]*?\n};/)[0];
let removed = false;
const loading = {classList: {contains: () => true}, remove: () => removed = true};
const document = {getElementById: () => loading, body: {style: {removeProperty() {}}}};
- runInNewContext(functionSource.replace("export const", "const") + "\nfinishMobileStartup();", {document});
+ runInNewContext(functionSource.replace("export const", "const") + "\nfinishMobileStartup();", {document, finishInitialView: undefined});
assert.equal(removed, false);
loading.classList.contains = () => false;
- runInNewContext(functionSource.replace("export const", "const") + "\nfinishMobileStartup();", {document});
+ runInNewContext(functionSource.replace("export const", "const") + "\nfinishMobileStartup();", {document, finishInitialView: undefined});
assert.equal(removed, true);
});
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index 97b043f5dd..8ab5adb2a9 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -83,6 +83,7 @@ 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)));
@@ -243,9 +244,7 @@ class App {
window.siyuan.menus = new Menus(this);
initMobileSelect();
document.title = window.siyuan.languages.siyuanNote;
- void Promise.resolve(appearanceConfigApi.apply(window.siyuan.config.appearance)).catch(reportStartupError);
initMessage();
- initAssets(true);
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");
@@ -265,9 +264,13 @@ class App {
fetchPost("/api/system/getEmojiConf", {}, guardStartup<IWebSocketData>(async emojiResponse => {
window.siyuan.emojis = emojiResponse.data as IEmoji[];
await setNoteBook();
- await initFramework(this, confResponse.data.start);
- initRightMenu(this);
- openChangelog();
+ 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();
diff --git a/app/src/mobile/util/initFramework.ts b/app/src/mobile/util/initFramework.ts
index e019c843f8..50e5267047 100644
--- a/app/src/mobile/util/initFramework.ts
+++ b/app/src/mobile/util/initFramework.ts
@@ -9,7 +9,8 @@ import {getEventName, isDisabledFeature, isInMobileApp} from "../../protyle/util
import {fetchPost} from "../../util/fetch";
import {setInlineStyle} from "../../util/assets";
import {renderSnippet} from "../../config/util/snippets";
-import {finishMobileStartup, setEmpty} from "./setEmpty";
+import {setEmpty} from "./setEmpty";
+import {finishMobileStartup} from "./startup";
import {getOpenNotebookCount, parseSiYuanUriInfo, parseUriInfo} from "../../util/pathName";
import {processMobileSystemUri} from "./systemUri";
import {popMenu} from "../menu";
diff --git a/app/src/mobile/util/setEmpty.ts b/app/src/mobile/util/setEmpty.ts
index a424ab9f0d..aa305edef9 100644
--- a/app/src/mobile/util/setEmpty.ts
+++ b/app/src/mobile/util/setEmpty.ts
@@ -10,14 +10,7 @@ import {updateMobileTopBarLayout} from "./mobileTopBar";
import {invalidateTrackedRanges} from "../../protyle/util/trackedRange";
import {closeAVCellEditor} from "../../protyle/render/av/cellEditor";
import {closeMobileBottomBacklinkPanel} from "./bottomBacklink";
-
-export const finishMobileStartup = () => {
- const loadingElement = document.getElementById("loading");
- if (loadingElement && !loadingElement.classList.contains("startup-error")) {
- loadingElement.remove();
- document.body.style.removeProperty("background-color");
- }
-};
+import {finishMobileStartup} from "./startup";
export const setEmpty = (app: App) => {
void closeMobileBottomBacklinkPanel()?.catch(error => console.error(error));
diff --git a/app/src/mobile/util/startup.ts b/app/src/mobile/util/startup.ts
new file mode 100644
index 0000000000..00a717c456
--- /dev/null
+++ b/app/src/mobile/util/startup.ts
@@ -0,0 +1,33 @@
+import {waitForWindowPaint} from "../../util/windowPaint";
+
+let finishInitialView: (() => void) | undefined;
+
+// 首个文档或空白页就绪时通知启动流程,后续切换仍沿用已有界面显隐逻辑。
+export const finishMobileStartup = () => {
+ if (finishInitialView) {
+ finishInitialView();
+ return;
+ }
+ const loading = document.getElementById("loading");
+ if (loading && !loading.classList.contains("startup-error")) {
+ loading.remove();
+ document.body.style.removeProperty("background-color");
+ }
+};
+
+export const initMobileWithLoading = async (render: () => Promise<void>) => {
+ const initialView = new Promise<void>(resolve => { finishInitialView = resolve; });
+ document.body.setAttribute("aria-busy", "true");
+ document.getElementById("loading")?.setAttribute("aria-label", window.siyuan.languages.loading);
+ try {
+ await waitForWindowPaint(async () => {
+ await render();
+ await initialView;
+ });
+ finishInitialView = undefined;
+ finishMobileStartup();
+ document.body.removeAttribute("aria-busy");
+ } finally {
+ finishInitialView = undefined;
+ }
+};
diff --git a/app/tests/mobileWindowLoading.test.js b/app/tests/mobileWindowLoading.test.js
new file mode 100644
index 0000000000..620e07d547
--- /dev/null
+++ b/app/tests/mobileWindowLoading.test.js
@@ -0,0 +1,134 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const runCase = (sources, options) => {
+ const check = require("node:assert/strict");
+ const load = (source, modules = {}) => {
+ const exports = {};
+ new Function("require", "exports", source)(name => modules[name] || {}, exports);
+ return exports;
+ };
+ window.siyuan = {isReady: false, languages: {loading: "Loading"}, config: {readonly: false, appearance: {}},
+ mobile: {docks: {}}};
+ document.body.classList.add("body--" + options.platform);
+ const {waitForWindowPaint} = load(sources.paint);
+ const startup = load(sources.startup, {"../../util/windowPaint": {waitForWindowPaint}});
+ const view = load(sources.view, {
+ "./startup": startup, "../../util/processTitle": {setTitle() {}},
+ "./mobileBars": {clearMobileBarsScroll() {}}, "./mobileTopBar": {updateMobileTopBarLayout() {}},
+ "../../protyle/render/av/cellEditor": {closeAVCellEditor() {}},
+ "./bottomBacklink": {closeMobileBottomBacklinkPanel() {}},
+ });
+ let renderComplete;
+ const render = new Promise(resolve => { renderComplete = resolve; });
+ const dependencies = {
+ initMobileWithLoading: startup.initMobileWithLoading,
+ appearanceConfigApi: {apply() {
+ const theme = document.createElement("link");
+ theme.rel = "stylesheet";
+ theme.href = "/theme.css";
+ document.head.appendChild(theme);
+ }},
+ initAssets() {}, initFramework: () => render, initRightMenu() {}, openChangelog() {}, confResponse: {data: {start: true}},
+ };
+ window.mobileLoadingResult = new Function(...Object.keys(dependencies),
+ "return (async function(){" + sources.entry + "}).call(this);")(...Object.values(dependencies));
+ window.releaseFramework = () => {
+ view.setEditor(false);
+ check.ok(document.getElementById("loading"), "showing a pending editor must not dismiss startup");
+ renderComplete();
+ };
+ window.releaseInitialView = () => {
+ if (options.empty) {
+ view.setEmpty({});
+ } else {
+ document.getElementById("editor").textContent = "First document";
+ view.setEditor();
+ }
+ check.ok(document.getElementById("loading"), "the initial view still waits for theme loading and paint");
+ check.equal(window.siyuan.isReady, false, "native startup remains visible until painting finishes");
+ };
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app, BrowserWindow} = require("electron");
+ const {createServer} = require("node:http");
+ const {once} = require("node:events");
+ app.disableHardwareAcceleration();
+ app.setPath("userData", process.argv[2]);
+ app.on("window-all-closed", () => {});
+ app.whenReady().then(async () => {
+ const ts = require("typescript");
+ const sources = {};
+ for (const [key, file] of Object.entries({paint: "util/windowPaint.ts", startup: "mobile/util/startup.ts",
+ view: "mobile/util/setEmpty.ts"})) {
+ sources[key] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", file), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},
+ }).outputText;
+ }
+ const entry = fs.readFileSync(path.join(__dirname, "../src/mobile/index.ts"), "utf8");
+ sources.entry = entry.slice(entry.indexOf("await initMobileWithLoading("), entry.indexOf(" finishMobileSystemUris(this);"));
+ const template = fs.readFileSync(path.join(__dirname, "../src/assets/template/mobile/index.tpl"), "utf8");
+ const pending = [];
+ const server = createServer((request, response) => {
+ if (request.url === "/theme.css") {
+ pending.push(response);
+ server.emit("theme-request");
+ } else {
+ response.setHeader("Content-Type", "text/html");
+ response.end(template);
+ }
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ let win;
+ let code = 0;
+ try {
+ for (const platform of ["android", "ios", "harmony"]) for (const empty of [true, false]) for (const dark of [true, false]) {
+ win = new BrowserWindow({show: false, width: 390, height: 844,
+ webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ win.webContents.on("console-message", event => {
+ if (event.level === "error") console.error(event.message);
+ });
+ await win.loadURL(`http://127.0.0.1:${server.address().port}/mobile.html`);
+ const themeRequest = once(server, "theme-request", {signal: AbortSignal.timeout(5000)});
+ await win.webContents.executeJavaScript(`(${runCase.toString()})(${JSON.stringify(sources)},${JSON.stringify({platform, empty})})`);
+ await themeRequest;
+ await win.webContents.executeJavaScript("window.releaseFramework()");
+ await win.webContents.executeJavaScript("window.releaseInitialView()");
+ assert.equal(await win.webContents.executeJavaScript("window.siyuan.isReady"), false);
+ pending.pop().writeHead(200, {"Content-Type": "text/css"}).end(`body{color:${dark ? "#ddd" : "#222"}}`);
+ await win.webContents.executeJavaScript("window.mobileLoadingResult");
+ assert.equal(await win.webContents.executeJavaScript("window.siyuan.isReady"), true);
+ assert.equal(await win.webContents.executeJavaScript('!!document.getElementById("loading")'), false);
+ assert.equal(await win.webContents.executeJavaScript('document.body.hasAttribute("aria-busy")'), false);
+ assert.equal(await win.webContents.executeJavaScript("document.body.style.backgroundColor"), "");
+ win.destroy();
+ }
+ console.log("Verified 12 mobile startup cases");
+ } catch (error) { console.error(error); code = 1; }
+ finally {
+ if (win && !win.isDestroyed()) win.destroy();
+ pending.forEach(response => response.end());
+ server.close();
+ app.exit(code);
+ }
+ });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("mobile startup acknowledges readiness after the theme and initial document or empty view are painted", {timeout: 45000}, async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-mobile-startup-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const {stdout} = await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});
+ assert.match(stdout, /Verified 12 mobile startup cases/);
+ } finally {
+ assert.equal(path.dirname(profile), os.tmpdir());
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}