An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Align settings window style and avoid authentication token conflicts https://github.com/siyuan-note/siyuan/issues/20002
Daniel4812a854bbed
diff --git a/app/electron/main.js b/app/electron/main.jsindex 6458f7a51f..cbc3251b03 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -136,6 +136,7 @@ createSettingsTaskBridge({const settingsWindowPolicy = createSettingsWindows({ipcMain,screen,+ icon: path.join(appDir, "stage", "icon-large.png"),getTarget: id => getWindowKernelTarget(id),show: win => showWindow(win),log: message => writeLog(message),diff --git a/app/electron/settingsWindows.js b/app/electron/settingsWindows.jsindex 7fe4e43276..d7b94a6845 100644--- a/app/electron/settingsWindows.js+++ b/app/electron/settingsWindows.js@@ -3,7 +3,7 @@ const {normalizeWindowGeometry, captureWindowGeometry} = require("./windowGeometconst settingsPath = "/stage/build/app/settings.html";// 只允许已登记的内核页面打开预先授权的设置页,不改变普通链接的打开规则。-const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, log}) => {+const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, log, icon, platform = process.platform}) => {const pending = new Map();const reservations = new Map();const windows = new Map();@@ -59,7 +59,7 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lo}if (reserved) cancel(reserved);const url = new URL(settingsPath, target.origin);- url.searchParams.set("token", data.token);+ url.searchParams.set("settingsWindowToken", data.token);if (target.mode === "remote") {url.searchParams.set("remote", "1");}@@ -85,6 +85,7 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loif (created.url !== approved.url) return;release(approved);windows.set(approved.key, win);+ if (platform !== "darwin") win.setMenu(null);initialize(win, approved.target);const close = () => { if (!win.isDestroyed()) win.destroy(); };contents.once("destroyed", close);@@ -116,7 +117,12 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loaction: "allow",overrideBrowserWindowOptions: {title: approved.data.title || "SiYuan",- frame: true,+ frame: platform === "darwin",+ titleBarStyle: "hidden",+ trafficLightPosition: {x: 8, y: 8},+ autoHideMenuBar: true,+ fullscreenable: true,+ icon,minWidth: 493,minHeight: 376,width: 1000,diff --git a/app/electron/settingsWindows.test.js b/app/electron/settingsWindows.test.jsindex e7a6aa5fb6..c0d9f14743 100644--- a/app/electron/settingsWindows.test.js+++ b/app/electron/settingsWindows.test.js@@ -3,7 +3,7 @@ const {EventEmitter} = require("node:events");const {test} = require("node:test");const {createSettingsWindows} = require("./settingsWindows");-const setup = () => {+const setup = (platform = "win32") => {let prepare;let close;const shown = [];@@ -14,6 +14,7 @@ const setup = () => {sent: [], send(...message) { this.sent.push(message); },});const policy = createSettingsWindows({+ platform,ipcMain: {handle: (_name, callback) => { prepare = callback; }, on: (_name, callback) => { close = callback; }},screen: {}, getTarget: id => id === 1 ? target : undefined,initialize: (...args) => initialized.push(args), show: win => shown.push(win), log() {},@@ -29,11 +30,15 @@ test("settings popup authorization requires the registered top-level page and exassert.equal(prepared.create, true);assert.equal(new URL(prepared.url).pathname, "/stage/build/app/settings.html");assert.equal(new URL(prepared.url).searchParams.get("remote"), "1");+ assert.equal(new URL(prepared.url).searchParams.has("token"), false);+ assert.equal(new URL(prepared.url).searchParams.get("settingsWindowToken"), "first-token");assert.equal(policy(owner, {url: prepared.url + "x", frameName: prepared.frameName}), undefined);assert.equal(policy(owner, {url: prepared.url, frameName: "other-frame"}), undefined);const allowed = policy(owner, prepared);assert.equal(allowed.action, "allow");- assert.equal(allowed.overrideBrowserWindowOptions.frame, true);+ assert.equal(allowed.overrideBrowserWindowOptions.frame, false);+ assert.equal(allowed.overrideBrowserWindowOptions.titleBarStyle, "hidden");+ assert.equal(allowed.overrideBrowserWindowOptions.autoHideMenuBar, true);assert.equal(allowed.overrideBrowserWindowOptions.parent, undefined);assert.equal(allowed.overrideBrowserWindowOptions.webPreferences.webSecurity, true);assert.equal(policy(owner, prepared), undefined);@@ -50,9 +55,11 @@ test("settings windows reuse their workspace instance and close with the owninglet destroyed = false;const win = Object.assign(new EventEmitter(), {webContents: contents, isDestroyed: () => destroyed,+ menu: "default", setMenu(menu) { this.menu = menu; },destroy() { destroyed = true; this.emit("closed"); },});owner.emit("did-create-window", win, {url: prepared.url});+ assert.equal(win.menu, null);assert.equal(initialized.length, 1);contents.emit("did-finish-load");assert.deepEqual(contents.sent[0], ["siyuan-settings-command", {tab: "appearance"}]);@@ -81,7 +88,7 @@ test("simultaneous popups initialize their own windows and canceled reservationspolicy(owner, plugin);const create = prepared => {const contents = Object.assign(new EventEmitter(), {send() {}});- const win = Object.assign(new EventEmitter(), {webContents: contents, isDestroyed: () => false});+ const win = Object.assign(new EventEmitter(), {webContents: contents, isDestroyed: () => false, setMenu() {}});owner.emit("did-create-window", win, {url: prepared.url});return win;};@@ -94,3 +101,11 @@ test("simultaneous popups initialize their own windows and canceled reservationsassert.deepEqual(owner.sent.at(-1), ["siyuan-settings-closed", "canceled-token"]);assert.equal(open({token: "reopened-token", key: "plugin-other"}).create, true);});++test("macOS settings windows retain native traffic lights with the main window title bar style", () => {+ const {policy, owner, open} = setup("darwin");+ const allowed = policy(owner, open());+ assert.equal(allowed.overrideBrowserWindowOptions.frame, true);+ assert.equal(allowed.overrideBrowserWindowOptions.titleBarStyle, "hidden");+ assert.deepEqual(allowed.overrideBrowserWindowOptions.trafficLightPosition, {x: 8, y: 8});+});diff --git a/app/src/assets/scss/component/_dialog.scss b/app/src/assets/scss/component/_dialog.scssindex 7b421cf839..d546b49ae8 100644--- a/app/src/assets/scss/component/_dialog.scss+++ b/app/src/assets/scss/component/_dialog.scss@@ -1,5 +1,9 @@.b3-dialog {&--window {+ & > .b3-dialog__container > .toolbar {+ flex-shrink: 0;+ }+& > .b3-dialog__scrim,& > .b3-dialog__container > [class^="resize__"] {display: none;diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.tsindex 5a478ba20a..1bf9636d0b 100644--- a/app/src/boot/onGetConfig.ts+++ b/app/src/boot/onGetConfig.ts@@ -10,6 +10,7 @@ import * as fs from "fs";import * as path from "path";import {afterExport} from "../protyle/export/util";import {onWindowsMsg} from "../window/onWindowsMsg";+import {applyWindowState, initWindowControls} from "./windowControls";/// #endifimport {Constants} from "../constants";import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";@@ -185,28 +186,16 @@ export const initWindow = async (app: App) => {ipcRenderer.send(Constants.SIYUAN_EVENT);ipcRenderer.on(Constants.SIYUAN_EVENT, (event, cmd) => {+ applyWindowState(cmd);if (cmd === "focus") {// 由于 https://github.com/siyuan-note/siyuan/issues/10060 和新版 electron 应用切出再切进会保持光标,故移除 focuswindow.siyuan.altIsPressed = false;window.siyuan.ctrlIsPressed = false;window.siyuan.shiftIsPressed = false;- document.body.classList.remove("body--blur");- } else if (cmd === "blur") {- document.body.classList.add("body--blur");} else if (cmd === "enter-full-screen") {- document.body.classList.add("body--fullscreen");- // 全屏下红绿灯隐藏,清除缩放补偿让 body--fullscreen 的 5px 生效- setToolbarLeftMac(window.siyuan.storage[Constants.LOCAL_ZOOM]);setTabPosition();} else if (cmd === "leave-full-screen") {- document.body.classList.remove("body--fullscreen");- // 退出全屏后按当前缩放重新补偿- setToolbarLeftMac(window.siyuan.storage[Constants.LOCAL_ZOOM]);setTabPosition();- } else if (cmd === "maximize") {- document.body.classList.add("body--maximize");- } else if (cmd === "unmaximize") {- document.body.classList.remove("body--maximize");}});if (!isWindow()) {@@ -398,51 +387,9 @@ ${response.data.replace("%pages", "<span class=totalPages></span>").replace("%paif (!isMac()) {document.body.classList.add("body--win32");- // 添加窗口控件- const controlsHTML = `<div class="toolbar__item ariaLabel toolbar__item--win" aria-label="${window.siyuan.languages.min}" id="minWindow">- <svg>- <use xlink:href="#iconMin"></use>- </svg>-</div>-<div aria-label="${window.siyuan.languages.max}" class="ariaLabel toolbar__item toolbar__item--win" id="maxWindow">- <svg>- <use xlink:href="#iconMax"></use>- </svg>-</div>-<div aria-label="${window.siyuan.languages.restore}" class="ariaLabel toolbar__item toolbar__item--win" id="restoreWindow">- <svg>- <use xlink:href="#iconRestore"></use>- </svg>-</div>-<div aria-label="${window.siyuan.languages.close}" class="ariaLabel toolbar__item toolbar__item--close" id="closeWindow">- <svg>- <use xlink:href="#iconClose"></use>- </svg>-</div>`;- if (isWindow()) {- document.querySelector(".toolbar__window").insertAdjacentHTML("beforeend", controlsHTML);- } else {- document.getElementById("windowControls").innerHTML = controlsHTML;- }- const maxBtnElement = document.getElementById("maxWindow");- const restoreBtnElement = document.getElementById("restoreWindow");-- restoreBtnElement.addEventListener("click", () => {- ipcRenderer.send(Constants.SIYUAN_CMD, "restore");- });- maxBtnElement.addEventListener("click", () => {- ipcRenderer.send(Constants.SIYUAN_CMD, "maximize");- });-- const minBtnElement = document.getElementById("minWindow");- const closeBtnElement = document.getElementById("closeWindow");- minBtnElement.addEventListener("click", () => {- if (minBtnElement.classList.contains("window-controls__item--disabled")) {- return;- }- ipcRenderer.send(Constants.SIYUAN_CMD, "minimize");- });- closeBtnElement.addEventListener("click", () => {+ const controls = isWindow() ? document.querySelector<HTMLElement>(".toolbar__window") : document.getElementById("windowControls");+ if (!isWindow()) controls.replaceChildren();+ initWindowControls(controls, () => {if (isWindow()) {closeWindow(app);} else {diff --git a/app/src/boot/windowControls.test.ts b/app/src/boot/windowControls.test.tsnew file mode 100644index 0000000000..78a222c420--- /dev/null+++ b/app/src/boot/windowControls.test.ts@@ -0,0 +1,31 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++test("shared window state restores controls and macOS spacing after fullscreen and maximization", () => {+ const code = transpileModule(readFileSync("src/boot/windowControls.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const classes = new Set<string>();+ const spacing: number[] = [];+ const dependencies = {Constants: {LOCAL_ZOOM: "zoom"}, setToolbarLeftMac: (zoom: number) => spacing.push(zoom)};+ const exports = {} as {applyWindowState: (command: string) => void};+ runInNewContext(code, {exports, require: () => dependencies, window: {siyuan: {storage: {zoom: 0.8}}},+ document: {body: {classList: {add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name),+ toggle: (name: string, active: boolean) => active ? classes.add(name) : classes.delete(name)}}}});+ exports.applyWindowState("blur");+ assert.equal(classes.has("body--blur"), true);+ exports.applyWindowState("focus");+ assert.equal(classes.has("body--blur"), false);+ exports.applyWindowState("maximize");+ assert.equal(classes.has("body--maximize"), true);+ exports.applyWindowState("unmaximize");+ assert.equal(classes.has("body--maximize"), false);+ exports.applyWindowState("enter-full-screen");+ assert.equal(classes.has("body--fullscreen"), true);+ exports.applyWindowState("leave-full-screen");+ assert.equal(classes.has("body--fullscreen"), false);+ assert.deepEqual(spacing, [0.8, 0.8]);+});diff --git a/app/src/boot/windowControls.ts b/app/src/boot/windowControls.tsnew file mode 100644index 0000000000..68c53bfb60--- /dev/null+++ b/app/src/boot/windowControls.ts@@ -0,0 +1,46 @@+import {ipcRenderer} from "electron";+import {Constants} from "../constants";+import {setToolbarLeftMac} from "../util/functions";++// 主窗口和设置窗口共用本机窗口控件及其命令,关闭行为由各窗口提供。+export const initWindowControls = (container: HTMLElement, close: () => void) => {+ container.insertAdjacentHTML("beforeend", `<div class="toolbar__item ariaLabel toolbar__item--win" aria-label="${window.siyuan.languages.min}" id="minWindow">+ <svg><use xlink:href="#iconMin"></use></svg>+</div>+<div aria-label="${window.siyuan.languages.max}" class="ariaLabel toolbar__item toolbar__item--win" id="maxWindow">+ <svg><use xlink:href="#iconMax"></use></svg>+</div>+<div aria-label="${window.siyuan.languages.restore}" class="ariaLabel toolbar__item toolbar__item--win" id="restoreWindow">+ <svg><use xlink:href="#iconRestore"></use></svg>+</div>+<div aria-label="${window.siyuan.languages.close}" class="ariaLabel toolbar__item toolbar__item--close" id="closeWindow">+ <svg><use xlink:href="#iconClose"></use></svg>+</div>`);+ container.querySelector("#restoreWindow").addEventListener("click", () => {+ ipcRenderer.send(Constants.SIYUAN_CMD, "restore");+ });+ container.querySelector("#maxWindow").addEventListener("click", () => {+ ipcRenderer.send(Constants.SIYUAN_CMD, "maximize");+ });+ const minimize = container.querySelector("#minWindow");+ minimize.addEventListener("click", () => {+ if (!minimize.classList.contains("window-controls__item--disabled")) {+ ipcRenderer.send(Constants.SIYUAN_CMD, "minimize");+ }+ });+ container.querySelector("#closeWindow").addEventListener("click", close);+};++export const applyWindowState = (command: string) => {+ switch (command) {+ case "focus": document.body.classList.remove("body--blur"); break;+ case "blur": document.body.classList.add("body--blur"); break;+ case "maximize": document.body.classList.add("body--maximize"); break;+ case "unmaximize": document.body.classList.remove("body--maximize"); break;+ case "enter-full-screen":+ case "leave-full-screen":+ document.body.classList.toggle("body--fullscreen", command === "enter-full-screen");+ setToolbarLeftMac(window.siyuan.storage[Constants.LOCAL_ZOOM]);+ break;+ }+};diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.tsindex 5a11e58bf6..7813a52d68 100644--- a/app/src/config/setting/window.ts+++ b/app/src/config/setting/window.ts@@ -6,7 +6,7 @@ import {Menus} from "../../menus";import {genUUID} from "../../util/genID";import {fetchSyncPost} from "../../util/fetch";import {addBaseURL, redirectToCheckAuth, setNoteBook} from "../../util/pathName";-import {getLocalStorage, initNativeDialogOverride, initWindowOpenOverride} from "../../protyle/util/compatibility";+import {getLocalStorage, initNativeDialogOverride, initWindowOpenOverride, isMac, isWindows} from "../../protyle/util/compatibility";import {addScriptSync} from "../../protyle/util/addScript";import {loadDesktopHostConnection, initDesktopHost} from "../../boot/onGetConfig";import {loadLanguages} from "../../boot/loadLanguages";@@ -31,10 +31,11 @@ import type {Dialog} from "../../dialog";import type {ISettingsCommand} from "./nativeWindow";import {getSettingTabDefs} from "./tabs";import {onWindowsMsg} from "../../window/onWindowsMsg";+import {applyWindowState} from "../../boot/windowControls";const initialize = async () => {addBaseURL();- const token = new URLSearchParams(location.search).get("token");+ const token = new URLSearchParams(location.search).get("settingsWindowToken");if (!token || !window.opener || window.opener.location.origin !== location.origin) {window.close();return;@@ -119,6 +120,19 @@ const initialize = async () => {await initDesktopHost();ipcRenderer.on(Constants.SIYUAN_SEND_WINDOWS, (_event, data: IWebSocketData) => onWindowsMsg(data));webFrame.setZoomFactor(window.siyuan.storage[Constants.LOCAL_ZOOM]);+ document.body.classList.toggle("body--windows", isWindows());+ document.body.classList.toggle("body--win32", !isMac());+ ipcRenderer.on(Constants.SIYUAN_EVENT, (_event, command: string) => applyWindowState(command));+ ipcRenderer.send(Constants.SIYUAN_EVENT);+ const [fullscreen, maximized] = await Promise.all([+ ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "isFullScreen"}),+ ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "isMaximized"}),+ ]);+ applyWindowState(fullscreen ? "enter-full-screen" : "leave-full-screen");+ applyWindowState(maximized ? "maximize" : "unmaximize");+ const zoom = window.siyuan.storage[Constants.LOCAL_ZOOM];+ const position = Constants.SIZE_ZOOM.find(item => item.zoom === zoom)?.position;+ if (position) ipcRenderer.send(Constants.SIYUAN_CMD, {cmd: "setTrafficLightPosition", zoom, position});const user = await fetchSyncPost("/api/setting/getCloudUser", {cached: true});window.siyuan.user = user.data && "userId" in user.data ? user.data : null;const emoji = await fetchSyncPost("/api/system/getEmojiConf", {});diff --git a/app/src/config/setting/windowDialog.ts b/app/src/config/setting/windowDialog.tsindex 226ddb9a67..2a459b68ec 100644--- a/app/src/config/setting/windowDialog.ts+++ b/app/src/config/setting/windowDialog.ts@@ -1,4 +1,8 @@import type {Dialog} from "../../dialog";+/// #if !BROWSER+import {initWindowControls} from "../../boot/windowControls";+import {isMac} from "../../protyle/util/compatibility";+/// #endif// 页面铺满原生窗口,内部确认框仍使用普通 Dialog 的覆盖范围和焦点管理。export const fitSettingsWindowDialog = (dialog: Dialog) => {@@ -11,4 +15,22 @@ export const fitSettingsWindowDialog = (dialog: Dialog) => {container.style.top = "auto";container.setAttribute("aria-modal", "false");dialog.element.querySelectorAll(".resize__move").forEach(element => element.classList.remove("resize__move"));+ /// #if !BROWSER+ const header = container.querySelector<HTMLElement>(".b3-dialog__header");+ const title = header.textContent || document.title;+ header.className = "toolbar fn__flex";+ const drag = document.createElement("div");+ drag.id = "drag";+ drag.className = "fn__flex-1";+ drag.textContent = title;+ header.replaceChildren(drag);+ container.setAttribute("aria-labelledby", header.id);+ if (!isMac()) {+ const controls = document.createElement("div");+ controls.id = "windowControls";+ controls.className = "fn__flex";+ header.append(controls);+ initWindowControls(controls, () => dialog.destroy());+ }+ /// #endif};diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.jsindex a1dca6fe17..bed22efd55 100644--- a/app/tests/settingsWindow.test.js+++ b/app/tests/settingsWindow.test.js@@ -14,7 +14,8 @@ const loadRendererModule = (source, modules) => {const rendererModules = (sources) => {let sequence = 0;- window.siyuan = {dialogs: [], zIndex: 1, storage: {}, languages: {cancel: "Cancel", save: "Save", config: "Settings"},+ window.siyuan = {dialogs: [], zIndex: 1, storage: {zoom: 1}, languages: {cancel: "Cancel", save: "Save", config: "Settings",+ min: "Minimize", max: "Maximize", restore: "Restore", close: "Close"},menus: {menu: {element: document.createElement("div"), remove() {}}}, ws: {app: {plugins: [], appId: "test"}}};const genUUID = () => "test-" + (++sequence);const {Dialog} = loadRendererModule(sources.dialog, {@@ -23,14 +24,22 @@ const rendererModules = (sources) => {"../constants": {Constants: {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0}},});const context = {isSettingsWindow: () => document.body.classList.contains("body--settings")};- const fit = loadRendererModule(sources.fit, {});- return {Dialog, genUUID, context, fit};+ const {ipcRenderer} = require("electron");+ const controls = loadRendererModule(sources.controls, {+ electron: {ipcRenderer}, "../constants": {Constants: {SIYUAN_CMD: "siyuan-cmd", LOCAL_ZOOM: "zoom"}},+ "../util/functions": {setToolbarLeftMac() {}},+ });+ document.body.classList.toggle("body--win32", process.platform !== "darwin");+ const fit = loadRendererModule(sources.fit, {+ "../../boot/windowControls": controls, "../../protyle/util/compatibility": {isMac: () => process.platform === "darwin"},+ });+ return {Dialog, genUUID, context, fit, controls};};const bootChild = async (sources) => {const {Dialog, genUUID, context, fit} = rendererModules(sources);const host = await new Promise(resolve => {- const token = new URLSearchParams(location.search).get("token");+ const token = new URLSearchParams(location.search).get("settingsWindowToken");window.opener.dispatchEvent(new CustomEvent("siyuan-settings-host-" + token, {detail: resolve}));});if (host.plugin) {@@ -89,6 +98,38 @@ const runCases = async (sources) => {assert.equal(created, 1);assert.notEqual(control.ownerDocument, document);assert.equal(setting.dialog.element.querySelector("input"), control);+ assert.equal(setting.dialog.element.querySelector(".toolbar #drag").textContent, "Plugin");+ if (process.platform !== "darwin") {+ assert.ok(setting.dialog.element.querySelector("#minWindow"));+ assert.ok(setting.dialog.element.querySelector("#maxWindow"));+ assert.ok(setting.dialog.element.querySelector("#closeWindow"));+ for (const id of ["minWindow", "maxWindow", "restoreWindow"]) {+ setting.dialog.element.querySelector("#" + id).click();+ }+ await wait();+ assert.deepEqual(await ipcRenderer.invoke("test-settings-commands"), ["minimize", "maximize", "restore"]);+ }+ await ipcRenderer.invoke("test-settings-size", 493, 376);+ await wait();+ const childDocument = control.ownerDocument;+ for (const theme of ["daylight", "midnight"]) {+ const link = childDocument.getElementById("fixtureTheme");+ await new Promise(resolve => {+ link.onload = resolve;+ link.href = "/fixture/" + theme + ".css?v=" + Date.now();+ });+ for (const fontSize of [14, 32]) {+ childDocument.documentElement.style.setProperty("--b3-font-size", fontSize + "px");+ const toolbar = setting.dialog.element.querySelector(".toolbar");+ assert.equal(childDocument.defaultView.getComputedStyle(toolbar).height, "32px");+ assert.equal(childDocument.defaultView.getComputedStyle(toolbar.querySelector("#drag")).getPropertyValue("-webkit-app-region"), "drag");+ if (process.platform !== "darwin") {+ const close = toolbar.querySelector("#closeWindow").getBoundingClientRect();+ assert.ok(close.right <= childDocument.defaultView.innerWidth);+ assert.ok(close.height >= 30);+ }+ }+ }setting.open("Plugin");await wait();assert.equal(created, 1);@@ -101,7 +142,8 @@ const runCases = async (sources) => {setting.open("Plugin");await ipcRenderer.invoke("test-settings-wait");- setting.close();+ if (process.platform === "darwin") setting.close();+ else setting.dialog.element.querySelector("#closeWindow").click();await wait();assert.equal(confirmed, 1);assert.equal(destroyed, 2);@@ -122,18 +164,37 @@ if (process.versions.electron && process.type === "browser") {let ready = 0;let waiting;const children = new Set();+ const commands = [];const ts = require("typescript");const sources = {};+ const styles = require("sass").compile(path.join(__dirname, "../src/assets/scss/base.scss"), {+ logger: {warn() {}, debug() {}},+ }).css;+ const themes = Object.fromEntries(["daylight", "midnight"].map(name => [name,+ fs.readFileSync(path.join(__dirname, "../appearance/themes", name, "theme.css"), "utf8")]));for (const [key, file] of Object.entries({dialog: "dialog/index.ts", setting: "plugin/Setting.ts",- native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts"})) {+ native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.ts"})) {sources[key] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", file), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},}).outputText;}const server = createServer((request, response) => {+ const pathname = new URL(request.url, "http://localhost").pathname;+ if (pathname.startsWith("/fixture/")) {+ response.setHeader("Content-Type", "text/css; charset=utf-8");+ response.end(pathname === "/fixture/base.css" ? styles : themes[path.basename(pathname, ".css")]);+ return;+ }response.setHeader("Content-Type", "text/html; charset=utf-8");const child = request.url.startsWith("/stage/build/app/settings.html");- response.end(`<html><body class="${child ? "body--settings" : ""}">${child ?+ if (child && (new URL(request.url, "http://localhost").searchParams.has("token") ||+ !request.headers.cookie?.includes("settings-auth=authenticated"))) {+ response.writeHead(401);+ response.end(JSON.stringify({code: -1, msg: "Auth failed [query token]"}));+ return;+ }+ if (!child) response.setHeader("Set-Cookie", "settings-auth=authenticated; HttpOnly; SameSite=Strict; Path=/");+ response.end(`<html><head><link rel="stylesheet" href="/fixture/base.css"><link id="fixtureTheme" rel="stylesheet" href="/fixture/daylight.css"></head><body class="${child ? "body--settings" : ""}">${child ?`<script>const loadRendererModule = ${loadRendererModule.toString()}; const rendererModules = ${rendererModules.toString()}; (${bootChild.toString()})(${JSON.stringify(sources)});</script>` : ""}</body></html>`);});await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));@@ -143,6 +204,7 @@ if (process.versions.electron && process.type === "browser") {children.add(win);assert.equal(win.getParentWindow(), null);assert.equal(win.isModal(), false);+ if (process.platform !== "darwin") assert.equal(win.isMenuBarVisible(), false);win.on("closed", () => children.delete(win));}, show() {}, log() {}});ipcMain.on("test-settings-ready", () => {@@ -150,6 +212,14 @@ if (process.versions.electron && process.type === "browser") {});ipcMain.handle("test-settings-wait", () => ready ? (--ready, Promise.resolve()) : new Promise(resolve => { waiting = resolve; }));ipcMain.handle("test-settings-window-count", () => children.size);+ ipcMain.on("siyuan-cmd", (event, command) => {+ assert.ok([...children].some(child => child.webContents === event.sender));+ commands.push(command);+ });+ ipcMain.handle("test-settings-commands", () => commands);+ ipcMain.handle("test-settings-size", (_event, width, height) => {+ for (const child of children) child.setSize(width, height);+ });try {owner = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});owner.webContents.setWindowOpenHandler(details => {