Skip to content

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

:bug: Show themed loading when opening detached windows https://github.com/siyuan-note/siyuan/issues/20192

Danielda9e402e1468
diff --git a/app/electron/main.js b/app/electron/main.js
index 1b631d761f..6f63607b3c 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -130,7 +130,6 @@ const notebookSystemLock = createNotebookSystemLock({
});
const windowKernelTargets = new Map();
const initializedWindowIds = new Set();
-const pendingWindowIds = new Set();
createSettingsTaskBridge({
ipcMain,
getTarget: id => getWindowKernelTarget(id),
@@ -3967,19 +3966,26 @@ app.whenReady().then(() => {
}
const existingWindow = windowWorkspaces.get(kernelTarget.origin, workspaceID);
if (existingWindow) {
- if (!pendingWindowIds.has(existingWindow.webContents.id)) {
- showWindow(existingWindow);
- }
+ showWindow(existingWindow);
return;
}
}
+ const themeMode = data.themeMode === "dark" ? "dark" : "light";
+ const backgroundColor = /^#[\da-f]{6}$/i.test(data.backgroundColor) ? data.backgroundColor :
+ (themeMode === "dark" ? "#1e1e1e" : "#ffffff");
+ const foregroundColor = /^#[\da-f]{6}$/i.test(data.foregroundColor) ? data.foregroundColor :
+ (themeMode === "dark" ? "#d4d4d4" : "#222222");
+ windowURL.searchParams.set("windowThemeMode", themeMode);
+ windowURL.searchParams.set("windowBackground", backgroundColor);
+ windowURL.searchParams.set("windowForeground", foregroundColor);
const mainWindow = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
const mainBounds = mainWindow.getBounds();
const mainScreen = screen.getDisplayNearestPoint({x: mainBounds.x, y: mainBounds.y});
const geometry = workspaceID ? normalizeWindowGeometry(data.windowGeometry, screen) : undefined;
const win = new BrowserWindow({
title: "SiYuan",
- show: false,
+ show: true,
+ backgroundColor,
trafficLightPosition: {x: 8, y: 13},
width: Math.floor(data.width || mainScreen.size.width * 0.7),
height: Math.floor(data.height || mainScreen.size.height * 0.9),
@@ -3991,7 +3997,6 @@ app.whenReady().then(() => {
icon: path.join(appDir, "stage", "icon-large.png"),
titleBarStyle: "hidden",
webPreferences: {
- backgroundThrottling: false,
contextIsolation: false,
nodeIntegration: true,
nodeIntegrationInSubFrames: false,
@@ -4010,57 +4015,12 @@ app.whenReady().then(() => {
windowWorkspaces.associate(win, kernelTarget.origin, workspaceID);
}
- // 原生窗口和主题内容均完成绘制后再显示,最大化和全屏也延后到此时执行。
- const windowId = win.webContents.id;
- pendingWindowIds.add(windowId);
- let painted = false;
- let initialized = false;
- const stopWaiting = () => {
- clearTimeout(readyTimeout);
- ipcMain.removeListener("siyuan-window-ready", onWindowReady);
- pendingWindowIds.delete(windowId);
- };
- const revealWindow = () => {
- if (!painted || !initialized || win.isDestroyed() || !pendingWindowIds.has(windowId)) {
- return;
- }
- stopWaiting();
- if (geometry && data.windowGeometry.maximized) {
- win.maximize();
- }
- if (geometry && data.windowGeometry.fullscreen) {
- win.setFullScreen(true);
- }
- showWindow(win);
- win.webContents.setBackgroundThrottling(true);
- };
- const onWindowReady = readyEvent => {
- if (readyEvent.sender.id === windowId) {
- initialized = true;
- revealWindow();
- }
- };
- ipcMain.on("siyuan-window-ready", onWindowReady);
- win.once("ready-to-show", () => {
- painted = true;
- revealWindow();
- });
- win.webContents.on("did-finish-load", () => {
- if (getWindowPathname(win) !== "/stage/build/app/window.html") {
- initialized = true;
- revealWindow();
- }
- });
- // 初始化失败时显示窗口供用户处理,避免留下无法访问的隐藏窗口。
- const readyTimeout = setTimeout(() => {
- if (!win.isDestroyed()) {
- writeLog("siyuan-window-ready timeout, force showing detached window");
- painted = true;
- initialized = true;
- revealWindow();
- }
- }, 60000);
- win.once("closed", stopWaiting);
+ if (geometry && data.windowGeometry.maximized) {
+ win.maximize();
+ }
+ if (geometry && data.windowGeometry.fullscreen) {
+ win.setFullScreen(true);
+ }
if (!geometry && data.position) {
win.setPosition(data.position.x, data.position.y);
@@ -4073,8 +4033,8 @@ app.whenReady().then(() => {
win.loadURL(windowURL.href);
windowNavigate(win, "window", kernelTarget.origin, kernelTarget.mode === "remote");
win.on("close", (event) => {
- if (kernelTarget.mode === "remote" && (getWindowPathname(win) !== "/stage/build/app/window.html" ||
- !initializedWindowIds.has(win.webContents.id))) {
+ if (!initializedWindowIds.has(win.webContents.id) ||
+ (kernelTarget.mode === "remote" && getWindowPathname(win) !== "/stage/build/app/window.html")) {
event.preventDefault();
markExpectedRendererExit(win);
win.destroy();
diff --git a/app/electron/windowGeometry.test.js b/app/electron/windowGeometry.test.js
index c981550b19..36cb045f14 100644
--- a/app/electron/windowGeometry.test.js
+++ b/app/electron/windowGeometry.test.js
@@ -100,15 +100,15 @@ test("异步退出全屏后才恢复边界和全屏状态", async () => {
assert.equal(f.window.listenerCount("leave-full-screen"), 0);
});
-const openWindow = windowGeometry => {
+const openWindow = (windowGeometry, appearance = {}, mode = "local") => {
const source = readFileSync("electron/main.js", "utf8");
const start = source.indexOf('ipcMain.on("siyuan-open-window",');
const end = source.indexOf('ipcMain.on("siyuan-open-workspace",', start);
const calls = [];
- const timers = new Set();
const ipcMain = new EventEmitter();
- const pendingWindowIds = new Set();
+ const initializedWindowIds = new Set();
let options;
+ let url;
const windows = [];
let pathname = "/stage/build/app/window.html";
class Window extends EventEmitter {
@@ -122,7 +122,7 @@ const openWindow = windowGeometry => {
this.destroyed = false;
this.webContents = Object.assign(new EventEmitter(), {id: 2,
session: {setSpellCheckerLanguages: () => {}},
- setBackgroundThrottling: value => calls.push(["throttling", value]),
+ send: value => calls.push(value),
});
}
center() { calls.push("center"); }
@@ -131,14 +131,16 @@ const openWindow = windowGeometry => {
maximize() { calls.push("maximize"); }
setFullScreen() { calls.push("fullscreen"); }
setAlwaysOnTop() {}
- loadURL() {}
+ loadURL(value) { url = value; }
isDestroyed() { return this.destroyed; }
+ destroy() { this.destroyed = true; calls.push("destroy"); }
}
const workArea = {x: 1920, y: 0, width: 1280, height: 1000};
runInNewContext(source.slice(start, end), {
- ipcMain, pendingWindowIds,
+ ipcMain, initializedWindowIds,
BrowserWindow: Window, URL, process: {platform: "win32"},
- getWindowKernelTarget: () => ({origin: "http://127.0.0.1:6806", mode: "local"}),
+ getWindowKernelTarget: () => ({origin: "http://127.0.0.1:6806", mode}),
+ getRemoteSession: () => ({}),
windowWorkspaces: {get: () => windows[0], associate: () => {}},
screen: {
...screen,
@@ -149,28 +151,25 @@ const openWindow = windowGeometry => {
remote: {enable: () => {}}, bindSpellcheckContextMenu: () => {}, rememberWindowKernelTarget: () => {},
windowNavigate: () => {},
showWindow: () => calls.push("show"), getWindowPathname: () => pathname, writeLog: () => {},
- setTimeout: callback => { timers.add(callback); return callback; },
- clearTimeout: timer => timers.delete(timer),
+ markExpectedRendererExit: () => calls.push("expected-exit"),
});
const open = () => ipcMain.emit("siyuan-open-window", {sender: {id: 1}}, {
url: "http://127.0.0.1:6806/stage/build/app/window.html?windowWorkspace=20260924100000-abcdefg",
windowGeometry,
+ ...appearance,
});
open();
const win = windows[0];
- return {options, calls, workArea, win, ipcMain, timers, pendingWindowIds, open,
- navigate: value => { pathname = value; win.webContents.emit("did-finish-load"); },
- ready: () => ipcMain.emit("siyuan-window-ready", {sender: win.webContents}),
+ return {options, calls, workArea, win, ipcMain, initializedWindowIds, url, open,
+ navigate: value => { pathname = value; },
+ close: () => win.emit("close", {preventDefault: () => calls.push("prevent-close")}),
};
};
test("新窗口创建时使用保存边界,不被鼠标所在显示器覆盖", () => {
const f = openWindow(state({maximized: true}));
assert.deepEqual([f.options.x, f.options.y, f.options.width, f.options.height], [100, 80, 900, 700]);
- assert.deepEqual(f.calls, []);
- f.win.emit("ready-to-show");
- f.ready();
- assert.deepEqual(f.calls, ["maximize", "show", ["throttling", true]]);
+ assert.deepEqual(f.calls, ["maximize"]);
});
test("旧窗口布局继续使用默认窗口位置", () => {
@@ -178,64 +177,54 @@ test("旧窗口布局继续使用默认窗口位置", () => {
assert.deepEqual(f.calls, ["center", f.workArea]);
});
-for (const rendererFirst of [true, false]) {
- test(`新窗口等待自身内容和原生绘制就绪:rendererFirst=${rendererFirst}`, () => {
- const f = openWindow(state());
- assert.equal(f.options.show, false);
- assert.equal(f.options.webPreferences.backgroundThrottling, false);
- f.ipcMain.emit("siyuan-window-ready", {sender: {id: 99}});
- f.navigate("/stage/build/app/window.html");
- f.open();
- assert.deepEqual(f.calls, []);
- if (rendererFirst) f.ready();
- else f.win.emit("ready-to-show");
- assert.deepEqual(f.calls, []);
- f.open();
- assert.deepEqual(f.calls, []);
- if (rendererFirst) f.win.emit("ready-to-show");
- else f.ready();
- assert.deepEqual(f.calls, ["show", ["throttling", true]]);
- assert.equal(f.timers.size, 0);
- assert.equal(f.ipcMain.listenerCount("siyuan-window-ready"), 0);
- assert.equal(f.pendingWindowIds.size, 0);
- f.ready();
- f.win.emit("ready-to-show");
- assert.deepEqual(f.calls, ["show", ["throttling", true]]);
- f.open();
- assert.equal(f.calls.at(-1), "show");
- });
-}
+test("新窗口立即显示,重复打开激活已有窗口", () => {
+ const f = openWindow(state());
+ assert.equal(f.options.show, true);
+ assert.equal(f.options.webPreferences.backgroundThrottling, undefined);
+ assert.equal(f.ipcMain.listenerCount("siyuan-window-ready"), 0);
+ f.open();
+ assert.deepEqual(f.calls, ["show"]);
+});
-test("全屏窗口也等到内容绘制完成再恢复状态", () => {
+test("全屏窗口立即恢复状态", () => {
const f = openWindow(state({fullscreen: true}));
- assert.deepEqual(f.calls, []);
- f.ready();
- f.win.emit("ready-to-show");
- assert.deepEqual(f.calls, ["fullscreen", "show", ["throttling", true]]);
+ assert.deepEqual(f.calls, ["fullscreen"]);
});
-test("跳转到认证页面后等待原生绘制完成并显示", () => {
- const f = openWindow(state());
- f.navigate("/check-auth");
- assert.deepEqual(f.calls, []);
- f.win.emit("ready-to-show");
- assert.deepEqual(f.calls, ["show", ["throttling", true]]);
+test("原生窗口和页面使用同一实际主题颜色,非法颜色使用安全默认值", () => {
+ for (const appearance of [
+ {themeMode: "dark", backgroundColor: "#234567", foregroundColor: "#abcdef"},
+ {themeMode: "light", backgroundColor: "#f0e8d8", foregroundColor: "#345678"},
+ {themeMode: "dark", backgroundColor: "transparent", foregroundColor: "red;}"},
+ {},
+ ]) {
+ const f = openWindow(state(), appearance);
+ const dark = appearance.themeMode === "dark";
+ const background = appearance.backgroundColor?.startsWith("#") ? appearance.backgroundColor : dark ? "#1e1e1e" : "#ffffff";
+ const foreground = appearance.foregroundColor?.startsWith("#") ? appearance.foregroundColor : dark ? "#d4d4d4" : "#222222";
+ assert.equal(f.options.backgroundColor, background);
+ const params = new URL(f.url).searchParams;
+ assert.equal(params.get("windowBackground"), background);
+ assert.equal(params.get("windowForeground"), foreground);
+ assert.equal(params.get("windowThemeMode"), dark ? "dark" : "light");
+ }
});
-test("初始化超时可显示窗口,关闭窗口会清理等待资源", () => {
- const f = openWindow(state());
- [...f.timers][0]();
- assert.deepEqual(f.calls, ["show", ["throttling", true]]);
- assert.equal(f.ipcMain.listenerCount("siyuan-window-ready"), 0);
- const closed = openWindow(state());
- const timeout = [...closed.timers][0];
- closed.win.destroyed = true;
- closed.win.emit("closed");
- closed.ready();
- closed.win.emit("ready-to-show");
- timeout();
- assert.deepEqual(closed.calls, []);
- assert.equal(closed.timers.size, 0);
- assert.equal(closed.ipcMain.listenerCount("siyuan-window-ready"), 0);
- assert.equal(closed.pendingWindowIds.size, 0);
-});
+for (const mode of ["local", "remote"]) {
+ test(`加载期间可直接关闭窗口,初始化后仍保存布局:${mode}`, () => {
+ const loading = openWindow(state(), {}, mode);
+ loading.close();
+ assert.deepEqual(loading.calls, ["prevent-close", "expected-exit", "destroy"]);
+ const ready = openWindow(state(), {}, mode);
+ ready.initializedWindowIds.add(ready.win.webContents.id);
+ ready.close();
+ assert.deepEqual(ready.calls, ["siyuan-save-close", "prevent-close"]);
+ if (mode === "remote") {
+ const auth = openWindow(state(), {}, mode);
+ auth.initializedWindowIds.add(auth.win.webContents.id);
+ auth.navigate("/check-auth");
+ auth.close();
+ assert.deepEqual(auth.calls, ["prevent-close", "expected-exit", "destroy"]);
+ }
+ });
+}
diff --git a/app/src/assets/scss/business/_window-workspace.scss b/app/src/assets/scss/business/_window-workspace.scss
index 68c3a210ff..1aa789bf5b 100644
--- a/app/src/assets/scss/business/_window-workspace.scss
+++ b/app/src/assets/scss/business/_window-workspace.scss
@@ -1,3 +1,8 @@
+.window-loading {
+ background-color: var(--b3-theme-background);
+ -webkit-app-region: drag;
+}
+
.window-workspace {
&__list {
width: min(256px, 70vw);
diff --git a/app/src/assets/template/app/window.tpl b/app/src/assets/template/app/window.tpl
index e914701912..d50754f3d7 100644
--- a/app/src/assets/template/app/window.tpl
+++ b/app/src/assets/template/app/window.tpl
@@ -5,13 +5,30 @@
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover, user-scalable=no">
<title>SiYuan</title>
+ <script>
+ (() => {
+ const appearance = new URLSearchParams(location.search);
+ const dark = appearance.get("windowThemeMode") === "dark";
+ document.documentElement.setAttribute("data-theme-mode", dark ? "dark" : "light");
+ const color = (name, fallback) => /^#[\da-f]{6}$/i.test(appearance.get(name)) ? appearance.get(name) : fallback;
+ const background = color("windowBackground", dark ? "#1e1e1e" : "#ffffff");
+ const foreground = color("windowForeground", dark ? "#d4d4d4" : "#222222");
+ const style = document.createElement("style");
+ style.id = "windowAppearanceStyle";
+ style.textContent = `:root{--b3-theme-background:${background};--b3-body-background:${background};--b3-theme-on-background:${foreground};--b3-theme-on-surface:${foreground};}`;
+ document.head.appendChild(style);
+ })();
+ </script>
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="apple-touch-icon" href="../../icon.png">
<link id="protyleKatexStyle" rel="stylesheet" href="../../protyle/js/katex/katex.min.css?v=0.19.0">
<script src="../../protyle/js/pdf/pdf.min.mjs?v=6.4.299-siyuan.1" type="module"></script>
</head>
-<body class="fn__flex-column body--window">
+<body class="fn__flex-column body--window" aria-busy="true">
+<div id="loading" class="fn__loading window-loading" role="status">
+ <img width="48" src="../../loading-pure.svg" alt="">
+</div>
<div class="fn__flex-1 fn__flex">
<div id="layouts" class="layout fn__flex-1"></div>
</div>
diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.ts
index 9ec4cfd11e..b500c5fafb 100644
--- a/app/src/card/openCard.ts
+++ b/app/src/card/openCard.ts
@@ -17,6 +17,7 @@ import {openFile} from "../editor/util";
/// #endif
/// #if !BROWSER
import {ipcRenderer} from "electron";
+import {getWindowAppearance} from "../window/appearance";
/// #endif
import * as dayjs from "dayjs";
import {getDisplayName, movePathTo} from "../util/pathName";
@@ -642,7 +643,9 @@ export const bindCardEvent = async (options: {
const url = new URL("/stage/build/app/window.html", window.location.origin);
url.searchParams.set("v", Constants.SIYUAN_VERSION);
url.searchParams.set("json", JSON.stringify(json));
- ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: appendRemoteQuery(url).href});
+ ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {
+ ...getWindowAppearance(), url: appendRemoteQuery(url).href,
+ });
options.dialog.destroy();
}
});
diff --git a/app/src/util/assets.ts b/app/src/util/assets.ts
index ffd10f596d..f471458af8 100644
--- a/app/src/util/assets.ts
+++ b/app/src/util/assets.ts
@@ -434,6 +434,10 @@ const cssVarToRgba = (varName: string) => {
return rgba;
};
+export const getThemeColor = (varName: string, fallback: string) => {
+ return rgbaToHex(cssVarToRgba(varName)).slice(0, 7) || fallback;
+};
+
const updateMobileTheme = (OSTheme: string) => {
if (isInMobileApp()) {
setTimeout(() => {
diff --git a/app/src/util/windowPaint.ts b/app/src/util/windowPaint.ts
index 82027abdde..cf5cd51b7d 100644
--- a/app/src/util/windowPaint.ts
+++ b/app/src/util/windowPaint.ts
@@ -1,6 +1,6 @@
const FRAME_WAIT_LIMIT = 250;
-// 等主题样式和窗口内容绘制完成,再通知主进程显示原生窗口。
+// 等主题样式加载完成并绘制窗口内容。
export const waitForWindowPaint = async (render: () => Promise<void>) => {
const initialStyles = new Set(document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'));
const styles = new Map<HTMLLinkElement, () => void>();
@@ -36,7 +36,7 @@ export const waitForWindowPaint = async (render: () => Promise<void>) => {
cancelAnimationFrame(frame);
resolve();
};
- // 帧回调未及时执行时允许继续显示,原生窗口仍需满足 ready-to-show。
+ // 帧回调未及时执行时也允许完成初始化。
const timer = window.setTimeout(finish, FRAME_WAIT_LIMIT);
frame = requestAnimationFrame(() => { frame = requestAnimationFrame(finish); });
});
diff --git a/app/src/window/appearance.ts b/app/src/window/appearance.ts
new file mode 100644
index 0000000000..b7e0d518cc
--- /dev/null
+++ b/app/src/window/appearance.ts
@@ -0,0 +1,10 @@
+import {getThemeColor, getThemeMode} from "../util/assets";
+
+export const getWindowAppearance = () => {
+ const themeMode = document.documentElement.getAttribute("data-theme-mode") || getThemeMode();
+ return {
+ themeMode,
+ backgroundColor: getThemeColor("--b3-theme-background", themeMode === "dark" ? "#1e1e1e" : "#ffffff"),
+ foregroundColor: getThemeColor("--b3-theme-on-background", themeMode === "dark" ? "#d4d4d4" : "#222222"),
+ };
+};
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index 8c1218e416..5430fb9104 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -47,8 +47,7 @@ import {emitToPlugins} from "../plugin/EventBusCore";
import {initializeEnglishCommandTranslations} from "../command/english";
import {loadLanguages} from "../boot/loadLanguages";
import {installPluginStorageFetchAppId} from "../util/fetchAppId";
-import {waitForWindowPaint} from "../util/windowPaint";
-import {ipcRenderer} from "electron";
+import {initWindowWithLoading} from "./loading";
class App {
public plugins: import("../plugin").Plugin[] = [];
@@ -258,12 +257,11 @@ class App {
window.siyuan.menus = new Menus(this);
fetchPost("/api/setting/getCloudUser", {cached: true}, async userResponse => {
window.siyuan.user = userResponse.data && "userId" in userResponse.data ? userResponse.data : null;
- await waitForWindowPaint(() => init(this));
+ await initWindowWithLoading(() => init(this));
setTitle("", true);
initMessage();
window.siyuan.isReady = true;
mainWs.flushMainMessages();
- ipcRenderer.send("siyuan-window-ready");
fetchPost("/api/setting/getCloudUser", {});
});
});
diff --git a/app/src/window/init.ts b/app/src/window/init.ts
index df16b9b8a3..dda881a66f 100644
--- a/app/src/window/init.ts
+++ b/app/src/window/init.ts
@@ -89,7 +89,7 @@ export const init = async (app: App) => {
initNativeDialogOverride();
/// #endif
appearanceConfigApi.apply(window.siyuan.config.appearance);
- initAssets();
+ initAssets(true);
await enqueueAppearanceUpdate(async () => {
await setInlineStyle();
});
diff --git a/app/src/window/loading.ts b/app/src/window/loading.ts
new file mode 100644
index 0000000000..f7d039cc25
--- /dev/null
+++ b/app/src/window/loading.ts
@@ -0,0 +1,9 @@
+import {waitForWindowPaint} from "../util/windowPaint";
+
+export const initWindowWithLoading = async (render: () => Promise<void>) => {
+ document.getElementById("loading")?.setAttribute("aria-label", window.siyuan.languages.loading);
+ await waitForWindowPaint(render);
+ document.getElementById("windowAppearanceStyle")?.remove();
+ document.getElementById("loading")?.remove();
+ document.body.removeAttribute("aria-busy");
+};
diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.ts
index c9e3905030..1f2e4c5d65 100644
--- a/app/src/window/openNewWindow.ts
+++ b/app/src/window/openNewWindow.ts
@@ -11,6 +11,7 @@ import {getSearch} from "../util/functions";
import {isBrowserRenderableImagePath} from "../util/imageURL";
import {appendRemoteQuery} from "../util/hostCapabilities";
import type {IWindowGeometry} from "./geometry";
+import {getWindowAppearance} from "./appearance";
interface windowOptions {
position?: {
@@ -33,7 +34,9 @@ export const openNewWindowByWorkspace = (id: string, windowGeometry?: IWindowGeo
/// #if !BROWSER
const url = new URL(getWindowURL([]));
url.searchParams.set("windowWorkspace", id);
- ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: url.href, alwaysOnTop: false, windowGeometry});
+ ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {
+ ...getWindowAppearance(), url: url.href, alwaysOnTop: false, windowGeometry,
+ });
/// #endif
};
@@ -42,6 +45,7 @@ export const openNewWindow = (tab: Tab, options: windowOptions = {}) => {
layoutToJSON(tab, json);
/// #if !BROWSER
ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {
+ ...getWindowAppearance(),
position: options.position,
width: options.width,
height: options.height,
@@ -86,6 +90,7 @@ export const openNewWindowById = async (id: string | string[], options: windowOp
}
/// #if !BROWSER
ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {
+ ...getWindowAppearance(),
position: options.position,
width: options.width,
height: options.height,
@@ -126,6 +131,7 @@ export const openAssetNewWindow = (
}
}];
ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {
+ ...getWindowAppearance(),
position: options.position,
width: options.width,
height: options.height,
diff --git a/app/tests/detachedWindowLoading.test.js b/app/tests/detachedWindowLoading.test.js
new file mode 100644
index 0000000000..837ec872d2
--- /dev/null
+++ b/app/tests/detachedWindowLoading.test.js
@@ -0,0 +1,159 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const runRendererCase = async (sources, expected) => {
+ const assert = require("node:assert/strict");
+ const load = (source, modules = {}) => {
+ const exports = {};
+ new Function("require", "exports", source)(name => modules[name] || {}, exports);
+ return exports;
+ };
+ window.siyuan = {languages: {loading: "Loading..."}, config: {appearance: {mode: expected.mode === "dark" ? 1 : 0}}};
+ const assets = load(sources.assets);
+ const appearance = load(sources.appearance, {"../util/assets": assets});
+ const {waitForWindowPaint} = load(sources.paint);
+ const {initWindowWithLoading} = load(sources.loading, {"../util/windowPaint": {waitForWindowPaint}});
+ const loader = document.getElementById("loading");
+ assert.equal(getComputedStyle(loader).backgroundColor, expected.background);
+ assert.equal(document.documentElement.getAttribute("data-theme-mode"), expected.mode);
+ assert.equal(getComputedStyle(loader).getPropertyValue("-webkit-app-region"), "drag");
+ const rect = loader.getBoundingClientRect();
+ assert.deepEqual([rect.x, rect.y, rect.width, rect.height], [0, 0, innerWidth, innerHeight]);
+ const image = loader.querySelector("img");
+ if (!image.complete) await new Promise(resolve => image.addEventListener("load", resolve, {once: true}));
+ assert.ok(image.naturalWidth > 0, "shared spinner loads");
+ const imgRect = image.getBoundingClientRect();
+ assert.ok(Math.abs(imgRect.x + imgRect.width / 2 - innerWidth / 2) < 1);
+ assert.ok(Math.abs(imgRect.y + imgRect.height / 2 - innerHeight / 2) < 1);
+ assert.equal(appearance.getWindowAppearance().backgroundColor, expected.hex);
+ let release;
+ let done = false;
+ const initialized = initWindowWithLoading(async () => {
+ const theme = document.createElement("link");
+ theme.rel = "stylesheet";
+ theme.href = "/pending-theme.css";
+ document.head.appendChild(theme);
+ await new Promise(resolve => { release = resolve; });
+ document.getElementById("layouts").textContent = "Ready";
+ }).then(() => { done = true; });
+ assert.equal(loader.getAttribute("aria-label"), "Loading...");
+ window.releaseInitialization = release;
+ window.loadingResult = initialized;
+ await new Promise(resolve => setTimeout(resolve, 80));
+ assert.equal(done, false);
+ assert.ok(loader.isConnected);
+ return true;
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app, BrowserWindow} = require("electron");
+ const {createServer} = require("node:http");
+ app.disableHardwareAcceleration();
+ app.setPath("userData", process.argv[2]);
+ app.whenReady().then(async () => {
+ const watchdog = setTimeout(() => app.exit(1), 45000);
+ const sources = {};
+ const ts = require("typescript");
+ for (const [key, file] of Object.entries({assets: "util/assets.ts", appearance: "window/appearance.ts",
+ paint: "util/windowPaint.ts", loading: "window/loading.ts"})) {
+ sources[key] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", file), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},
+ }).outputText;
+ }
+ const css = require("sass").compile(path.join(__dirname, "../src/assets/scss/base.scss"), {
+ logger: {warn() {}, debug() {}},
+ }).css;
+ const template = fs.readFileSync(path.join(__dirname, "../src/assets/template/app/window.tpl"), "utf8")
+ .replace("</head>", '<link rel="stylesheet" href="/base.css"></head>');
+ const pending = [];
+ const server = createServer((request, response) => {
+ const pathname = new URL(request.url, "http://localhost").pathname;
+ if (pathname === "/pending-theme.css") {
+ pending.push(response);
+ return;
+ }
+ if (pathname === "/base.css") {
+ response.setHeader("Content-Type", "text/css");
+ response.end(css);
+ return;
+ }
+ if (pathname === "/stage/loading-pure.svg") {
+ response.setHeader("Content-Type", "image/svg+xml");
+ response.end(fs.readFileSync(path.join(__dirname, "../stage/loading-pure.svg")));
+ return;
+ }
+ if (pathname === "/stage/build/app/window.html") {
+ response.setHeader("Content-Type", "text/html");
+ response.end(template);
+ return;
+ }
+ response.statusCode = 404;
+ response.end();
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ let win;
+ let code = 0;
+ try {
+ for (const expected of [
+ {mode: "light", hex: "#ffffff", background: "rgb(255, 255, 255)"},
+ {mode: "dark", hex: "#1e1e1e", background: "rgb(30, 30, 30)"},
+ {mode: "dark", hex: "#234567", background: "rgb(35, 69, 103)"},
+ ]) {
+ win = new BrowserWindow({show: false, backgroundColor: expected.hex, width: 640, height: 480,
+ webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ assert.equal(win.getBackgroundColor(), expected.hex.toUpperCase());
+ const url = new URL(`http://127.0.0.1:${server.address().port}/stage/build/app/window.html`);
+ url.searchParams.set("windowThemeMode", expected.mode);
+ url.searchParams.set("windowBackground", expected.hex);
+ url.searchParams.set("windowForeground", "#abcdef");
+ await win.loadURL(url.href);
+ await win.webContents.executeJavaScript(`(${runRendererCase.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(expected)})`);
+ const first = await win.webContents.capturePage();
+ const bitmap = first.toBitmap();
+ assert.deepEqual([...bitmap.subarray(0, 3)], [parseInt(expected.hex.slice(5, 7), 16),
+ parseInt(expected.hex.slice(3, 5), 16), parseInt(expected.hex.slice(1, 3), 16)], "painted background");
+ await new Promise(resolve => setTimeout(resolve, 180));
+ const second = await win.webContents.capturePage();
+ assert.equal(first.toPNG().equals(second.toPNG()), false, "spinner animates");
+ await win.webContents.executeJavaScript("window.releaseInitialization()");
+ assert.equal(await win.webContents.executeJavaScript('!!document.getElementById("loading")'), true,
+ "loader stays while theme stylesheet is pending");
+ assert.equal(pending.length, 1);
+ pending.pop().writeHead(200, {"Content-Type": "text/css"}).end(
+ ":root{--b3-theme-background:#567890;--b3-body-background:#567890;}");
+ await win.webContents.executeJavaScript("window.loadingResult");
+ assert.equal(await win.webContents.executeJavaScript('document.getElementById("loading")'), null);
+ assert.equal(await win.webContents.executeJavaScript('document.getElementById("windowAppearanceStyle")'), null);
+ assert.equal(await win.webContents.executeJavaScript('document.body.hasAttribute("aria-busy")'), false);
+ assert.equal(await win.webContents.executeJavaScript("getComputedStyle(document.body).backgroundColor"), "rgb(86, 120, 144)");
+ win.destroy();
+ }
+ } catch (error) {
+ console.error(error);
+ code = 1;
+ } finally {
+ if (win && !win.isDestroyed()) win.destroy();
+ pending.forEach(response => response.end());
+ server.close();
+ clearTimeout(watchdog);
+ app.exit(code);
+ }
+ });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("detached windows show themed backgrounds and animated loading until content and theme are painted", {timeout: 60000}, async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-detached-loading-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 55000});
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}