Skip to content

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

:sparkles: Support title bar overlay on Windows https://github.com/siyuan-note/siyuan/issues/20870

Daniel157d739920a7
diff --git a/app/electron/main.js b/app/electron/main.js
index 3334f5a6ef..73726150f4 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -88,6 +88,7 @@ const {dispatchWindowMessage} = require("./windowMessaging");
const {WindowWorkspaceRegistry, flushWindowWorkspaces} = require("./windowWorkspaces");
const {captureWindowGeometry, normalizeWindowGeometry, restoreWindowGeometry} = require("./windowGeometry");
const {createSettingsWindows} = require("./settingsWindows");
+const {getTitleBarOverlayOptions, updateTitleBarOverlay} = require("./windowControlsOverlay");
const {createSettingsTaskBridge} = require("./settingsTasks");
const {bindWebviewDevToolsShortcut} = require("./webviewDevTools");
const {createWebPageFetcher, installWebPageFetchIPC} = require("./webPageFetch");
@@ -2251,6 +2252,7 @@ const initMainWindow = (kernel = kernelPort, remoteAuthenticated = true) => {
},
frame: "darwin" === process.platform,
titleBarStyle: "hidden",
+ titleBarOverlay: getTitleBarOverlayOptions(),
icon: path.join(appDir, "stage", "icon-large.png"),
});
remote.enable(currentWindow.webContents);
@@ -3992,6 +3994,11 @@ app.whenReady().then(() => {
}
break;
}
+ case "setTitleBarOverlay":
+ if (event.senderFrame === event.sender.mainFrame && webContentsId === event.sender.id) {
+ updateTitleBarOverlay(currentWindow, data);
+ }
+ break;
case "setTrafficLightPosition":
if (!currentWindow || !currentWindow.setWindowButtonPosition) {
return;
@@ -4226,6 +4233,7 @@ app.whenReady().then(() => {
frame: "darwin" === process.platform,
icon: path.join(appDir, "stage", "icon-large.png"),
titleBarStyle: "hidden",
+ titleBarOverlay: getTitleBarOverlayOptions(),
webPreferences: {
contextIsolation: false,
nodeIntegration: true,
diff --git a/app/electron/settingsWindows.js b/app/electron/settingsWindows.js
index c19c4193ed..7ce09beadc 100644
--- a/app/electron/settingsWindows.js
+++ b/app/electron/settingsWindows.js
@@ -1,4 +1,5 @@
const {normalizeWindowGeometry, captureWindowGeometry} = require("./windowGeometry");
+const {getTitleBarOverlayOptions} = require("./windowControlsOverlay");
const settingsPath = "/stage/build/app/settings.html";
@@ -260,6 +261,7 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, getWindows, initiali
title: approved.data.title || "SiYuan",
frame: platform === "darwin",
titleBarStyle: "hidden",
+ titleBarOverlay: getTitleBarOverlayOptions(platform),
trafficLightPosition: {x: 8, y: 8},
autoHideMenuBar: true,
fullscreenable: true,
diff --git a/app/electron/settingsWindows.test.js b/app/electron/settingsWindows.test.js
index 00d263f1c6..e231cd4300 100644
--- a/app/electron/settingsWindows.test.js
+++ b/app/electron/settingsWindows.test.js
@@ -136,6 +136,7 @@ test("settings popup authorization requires the registered top-level page and ex
assert.equal(allowed.overrideBrowserWindowOptions.show, false);
assert.equal(allowed.overrideBrowserWindowOptions.frame, false);
assert.equal(allowed.overrideBrowserWindowOptions.titleBarStyle, "hidden");
+ assert.deepEqual(allowed.overrideBrowserWindowOptions.titleBarOverlay, {color: "#00000000", symbolColor: "#808080"});
assert.equal(allowed.overrideBrowserWindowOptions.autoHideMenuBar, true);
assert.equal(allowed.overrideBrowserWindowOptions.parent, undefined);
assert.equal(allowed.overrideBrowserWindowOptions.webPreferences.webSecurity, true);
@@ -254,6 +255,14 @@ test("macOS settings windows retain native traffic lights with the main window t
assert.equal(allowed.overrideBrowserWindowOptions.frame, true);
assert.equal(allowed.overrideBrowserWindowOptions.titleBarStyle, "hidden");
assert.deepEqual(allowed.overrideBrowserWindowOptions.trafficLightPosition, {x: 8, y: 8});
+ assert.equal(allowed.overrideBrowserWindowOptions.titleBarOverlay, false);
+});
+
+test("Linux settings windows retain the page window controls", () => {
+ const {policy, owner, open} = setup("linux");
+ const allowed = policy(owner, open());
+ assert.equal(allowed.overrideBrowserWindowOptions.frame, false);
+ assert.equal(allowed.overrideBrowserWindowOptions.titleBarOverlay, false);
});
for (const platform of ["win32", "linux", "darwin"]) {
diff --git a/app/electron/windowControlsOverlay.js b/app/electron/windowControlsOverlay.js
new file mode 100644
index 0000000000..f396c72c02
--- /dev/null
+++ b/app/electron/windowControlsOverlay.js
@@ -0,0 +1,27 @@
+const styles = new WeakMap();
+
+const getTitleBarOverlayOptions = (platform = process.platform) => platform === "win32" ? {
+ color: "#00000000",
+ symbolColor: "#808080",
+} : false;
+
+// 只接收本窗口的尺寸和图标颜色,背景透出页面,保留主题的透明与渐变效果。
+const updateTitleBarOverlay = (win, data, platform = process.platform) => {
+ if (platform !== "win32" || !win || win.isDestroyed() || !data || !Number.isInteger(data.height) ||
+ data.height < 1 || data.height > 256 || typeof data.symbolColor !== "string" ||
+ !data.symbolColor || data.symbolColor.length > 100) {
+ return false;
+ }
+ const style = {color: "#00000000", symbolColor: data.symbolColor, height: data.height};
+ const key = JSON.stringify(style);
+ if (styles.get(win) === key) return true;
+ try {
+ win.setTitleBarOverlay(style);
+ styles.set(win, key);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+module.exports = {getTitleBarOverlayOptions, updateTitleBarOverlay};
diff --git a/app/electron/windowControlsOverlay.test.js b/app/electron/windowControlsOverlay.test.js
new file mode 100644
index 0000000000..baca3b35c8
--- /dev/null
+++ b/app/electron/windowControlsOverlay.test.js
@@ -0,0 +1,52 @@
+const assert = require("node:assert/strict");
+const {test} = require("node:test");
+const {getTitleBarOverlayOptions, updateTitleBarOverlay} = require("./windowControlsOverlay");
+
+test("caption overlays are Windows-only and keep the page background visible", () => {
+ assert.deepEqual(getTitleBarOverlayOptions("win32"), {color: "#00000000", symbolColor: "#808080"});
+ assert.equal(getTitleBarOverlayOptions("darwin"), false);
+ assert.equal(getTitleBarOverlayOptions("linux"), false);
+});
+
+test("caption updates deduplicate per window and preserve transparent theme backgrounds", () => {
+ const calls = [];
+ const win = {isDestroyed: () => false, setTitleBarOverlay: style => calls.push(style)};
+ const data = {height: 42, symbolColor: "rgb(85, 85, 85)", color: "#ffffff"};
+ assert.equal(updateTitleBarOverlay(win, data, "win32"), true);
+ assert.equal(updateTitleBarOverlay(win, data, "win32"), true);
+ assert.equal(calls.length, 1);
+ assert.deepEqual(calls[0], {color: "#00000000", symbolColor: data.symbolColor, height: 42});
+ assert.equal(updateTitleBarOverlay(win, {...data, height: 63}, "win32"), true);
+ assert.equal(calls.at(-1).height, 63);
+ assert.equal(updateTitleBarOverlay({...win}, data, "win32"), true);
+ assert.equal(calls.length, 3);
+});
+
+test("invalid caption dimensions, unavailable windows and non-Windows updates are ignored", () => {
+ const win = {isDestroyed: () => false, setTitleBarOverlay: () => assert.fail("invalid update reached Electron")};
+ for (const height of [NaN, Infinity, -1, 0, 0.5, 257, "42", undefined]) {
+ assert.equal(updateTitleBarOverlay(win, {height, symbolColor: "#ffffff"}, "win32"), false);
+ }
+ for (const symbolColor of [undefined, 1, "", "x".repeat(101)]) {
+ assert.equal(updateTitleBarOverlay(win, {height: 42, symbolColor}, "win32"), false);
+ }
+ assert.equal(updateTitleBarOverlay(win, null, "win32"), false);
+ assert.equal(updateTitleBarOverlay(undefined, {}, "win32"), false);
+ assert.equal(updateTitleBarOverlay({...win, isDestroyed: () => true}, {}, "win32"), false);
+ assert.equal(updateTitleBarOverlay(win, {height: 42, symbolColor: "#fff"}, "linux"), false);
+ assert.equal(updateTitleBarOverlay(win, {height: 42, symbolColor: "#fff"}, "darwin"), false);
+});
+
+test("failed native caption updates do not poison later retries", () => {
+ let fail = true;
+ let calls = 0;
+ const win = {isDestroyed: () => false, setTitleBarOverlay: () => {
+ calls++;
+ if (fail) throw new Error("overlay is not ready");
+ }};
+ const style = {height: 32, symbolColor: "#555555"};
+ assert.equal(updateTitleBarOverlay(win, style, "win32"), false);
+ fail = false;
+ assert.equal(updateTitleBarOverlay(win, style, "win32"), true);
+ assert.equal(calls, 2);
+});
diff --git a/app/src/assets/scss/main/_main.scss b/app/src/assets/scss/main/_main.scss
index b573512211..9e5b826301 100644
--- a/app/src/assets/scss/main/_main.scss
+++ b/app/src/assets/scss/main/_main.scss
@@ -279,6 +279,65 @@ body.body--harmony {
}
}
+// 原生按钮的实际尺寸由 Electron 上报,页面仅为同一块区域预留空间。
+html.window-controls-overlay {
+ --b3-window-controls-width: calc(100vw - env(titlebar-area-width, 100vw) - env(titlebar-area-x, 0px));
+ --b3-window-controls-height: env(titlebar-area-height, 0px);
+ --b3-window-controls-top-height: max(var(--b3-ui-panel-height, 42px), var(--b3-window-controls-height));
+
+ &.window-controls-overlay--hidden {
+ --b3-window-controls-width: 0px;
+ --b3-window-controls-height: 0px;
+ }
+
+ .body--windows {
+ #toolbar,
+ .toolbar--settings {
+ height: max(var(--b3-ui-toolbar-height, 32px), var(--b3-window-controls-height));
+ }
+
+ .window-controls-overlay__placeholder {
+ width: var(--b3-window-controls-width);
+ height: var(--b3-window-controls-height);
+ flex-shrink: 0;
+ pointer-events: none;
+ }
+
+ .toolbar__window,
+ .toolbar__window .toolbar__item,
+ .window-controls-overlay__top-row {
+ min-height: var(--b3-window-controls-top-height);
+ }
+
+ .fullscreen > .protyle-breadcrumb,
+ .fullscreen > .block__icons {
+ padding-right: calc(var(--b3-window-controls-width) + 8px);
+ min-height: var(--b3-window-controls-height);
+ }
+
+ &.body--toolbar-hide {
+ #toolbar,
+ #toolbar #drag,
+ #toolbar #drag::before,
+ #toolbar #drag::after {
+ height: var(--b3-window-controls-top-height);
+ }
+
+ #dockLeft,
+ #dockRight,
+ .layout__dockl:not(.layout--float),
+ .layout__dockr:not(.layout--float) {
+ margin-top: var(--b3-window-controls-top-height);
+ }
+
+ #dockLeft:not(.dock--float),
+ #dockRight:not(.dock--float) {
+ height: calc(100% - var(--b3-window-controls-top-height));
+ }
+ }
+ }
+}
+
.status {
& > [data-entry-hidden="true"] {
display: none !important;
diff --git a/app/src/boot/windowControls.ts b/app/src/boot/windowControls.ts
index 68c53bfb60..6be4766060 100644
--- a/app/src/boot/windowControls.ts
+++ b/app/src/boot/windowControls.ts
@@ -1,9 +1,11 @@
import {ipcRenderer} from "electron";
import {Constants} from "../constants";
import {setToolbarLeftMac} from "../util/functions";
+import {initWindowControlsOverlay} from "./windowControlsOverlay";
// 主窗口和设置窗口共用本机窗口控件及其命令,关闭行为由各窗口提供。
export const initWindowControls = (container: HTMLElement, close: () => void) => {
+ if (initWindowControlsOverlay(container)) return;
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>
diff --git a/app/src/boot/windowControlsOverlay.test.ts b/app/src/boot/windowControlsOverlay.test.ts
new file mode 100644
index 0000000000..57f264cff1
--- /dev/null
+++ b/app/src/boot/windowControlsOverlay.test.ts
@@ -0,0 +1,148 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {compile} from "sass";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (sources: string[], css: string, nativeEnabled = true) => {
+ const check: typeof assert = require("node:assert/strict");
+ const {webFrame} = require("electron") as typeof import("electron");
+ document.body.innerHTML = `<style>${css}
+ :root{--b3-ui-panel-height:42px;--b3-ui-toolbar-height:32px;--b3-toolbar-color:#555555}
+ .fn__flex{display:flex}.fn__flex-1{flex:1;min-width:0}.fn__none{display:none!important}
+ .toolbar{padding:0}body{margin:0}#tooltip{--b3-tooltips-background:black;--b3-tooltips-color:white}
+ </style><div id="toolbar" class="toolbar fn__flex"><div id="drag" class="fn__flex-1"></div>
+ <div id="windowControls" class="fn__flex"></div></div>
+ <div><div class="layout-tab-bar"></div></div><div id="tooltip" class="tooltip fn__none"></div>`;
+ window.siyuan = {isReady: true, languages: {min: "Minimize", max: "Maximize", restore: "Restore", close: "Close"},
+ storage: {zoom: 1}} as unknown as typeof window.siyuan;
+ window.DOMPurify = {sanitize: (value: string) => value} as typeof window.DOMPurify;
+ let resizeCalls = 0;
+ const overlay = {} as typeof import("./windowControlsOverlay");
+ const controls = {} as typeof import("./windowControls");
+ const tooltip = {} as typeof import("../dialog/tooltip");
+ const dependencies = {Constants: {SIYUAN_CMD: "siyuan-cmd", LOCAL_ZOOM: "zoom"},
+ resizeTopBar: () => { resizeCalls++; }, setToolbarLeftMac() {},
+ isMobile: () => false, isTouchHoverInput: () => false, emitToPlugins() {}, forEachPluginSubscriber() {}};
+ const load = (code: string, exports: object) => new Function("exports", "require", code)(exports, (id: string) => {
+ if (id === "electron") return require("electron");
+ if (id === "./windowControlsOverlay") return overlay;
+ return dependencies;
+ });
+ load(sources[0], overlay);
+ load(sources[1], controls);
+ load(sources[2], tooltip);
+ const container = document.getElementById("windowControls");
+ document.body.className = "body--linux";
+ let closed = 0;
+ controls.initWindowControls(container, () => { closed++; });
+ check.equal(container.querySelectorAll("#minWindow,#maxWindow,#restoreWindow,#closeWindow").length, 4);
+ container.querySelector<HTMLElement>("#closeWindow").click();
+ check.equal(closed, 1);
+ check.equal(document.documentElement.classList.contains("window-controls-overlay"), false);
+ container.replaceChildren();
+ document.body.className = "body--windows";
+ if (!nativeEnabled) {
+ controls.initWindowControls(container, () => { closed++; });
+ check.equal(container.querySelectorAll("#minWindow,#maxWindow,#restoreWindow,#closeWindow").length, 4,
+ "Windows hosts without an enabled overlay retain self-drawn controls after a frontend refresh");
+ check.equal(document.documentElement.classList.contains("window-controls-overlay"), false);
+ return "Window controls overlay cases passed";
+ }
+ controls.initWindowControls(container, () => { closed++; });
+ check.equal(container.children.length, 0, "native controls replace the self-drawn buttons");
+ const api = (navigator as Navigator & {windowControlsOverlay: import("./windowControlsOverlay").IWindowControlsOverlay}).windowControlsOverlay;
+ for (const fused of [false, true]) for (const zoom of [0.67, 1, 1.5]) {
+ document.body.classList.toggle("body--toolbar-hide", fused);
+ webFrame.setZoomFactor(zoom);
+ overlay.updateWindowControlsOverlay();
+ await new Promise(resolve => setTimeout(resolve, 300));
+ const safe = api.getTitlebarAreaRect();
+ const rect = container.getBoundingClientRect();
+ check.ok(Math.abs(rect.left - safe.right) < 1.5);
+ check.ok(Math.abs(rect.right - innerWidth) < 1.5);
+ check.ok(document.getElementById("toolbar").getBoundingClientRect().height >= safe.height - 1);
+ const target = document.createElement("span");
+ target.style.cssText = `position:fixed;right:${innerWidth - safe.right + 2}px;top:4px;width:20px;height:18px`;
+ document.body.append(target);
+ tooltip.showTooltip("A long caption tooltip that extends into the native buttons", target);
+ const tip = document.getElementById("tooltip");
+ check.ok(parseFloat(tip.style.top) >= safe.bottom + 4, "tooltip avoids the native caption before animation");
+ check.ok(parseFloat(tip.style.maxHeight) <= innerHeight - parseFloat(tip.style.top));
+ tooltip.showTooltip('<a href="#test">An interactive caption tooltip</a>', target, "memo");
+ check.equal(tip.classList.contains("tooltip--interactive"), true);
+ check.ok(parseFloat(tip.style.top) >= safe.bottom + 4);
+ tooltip.hideTooltip();
+ target.remove();
+ }
+ webFrame.setZoomFactor(0.67);
+ document.body.classList.remove("body--toolbar-hide");
+ overlay.updateWindowControlsOverlay();
+ await new Promise(resolve => setTimeout(resolve, 300));
+ document.body.classList.add("body--fullscreen");
+ overlay.updateWindowControlsOverlay();
+ check.equal(container.getBoundingClientRect().width, 0, "fullscreen releases stale native geometry");
+ check.ok(document.getElementById("toolbar").getBoundingClientRect().height <= 32.1);
+ document.body.classList.remove("body--fullscreen");
+ overlay.updateWindowControlsOverlay();
+ check.ok(container.getBoundingClientRect().width > 0);
+ const wide = document.createElement("div");
+ wide.style.cssText = "width:2000px;flex-shrink:0";
+ document.getElementById("toolbar").prepend(wide);
+ overlay.updateWindowControlsOverlay();
+ check.ok(resizeCalls > 0, "overflow uses the existing toolbar folding logic");
+ wide.remove();
+ return "Window controls overlay cases passed";
+};
+
+test("native Windows captions reserve geometry, preserve legacy controls and keep tooltips clear", {
+ skip: process.platform !== "win32", timeout: 20000,
+}, async () => {
+ const sources = ["src/boot/windowControlsOverlay.ts", "src/boot/windowControls.ts", "src/dialog/tooltip.ts"].map(file =>
+ transpileModule(readFileSync(file, "utf8"), {compilerOptions: {
+ module: ModuleKind.CommonJS, target: ScriptTarget.ES2021,
+ }}).outputText);
+ const css = ["main/_main.scss", "util/_reset.scss", "component/_tooltips.scss"]
+ .map(file => compile("src/assets/scss/" + file).css).join("\n");
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-window-controls-overlay-"));
+ const script = path.join(temporary, "run.cjs");
+ const html = path.join(temporary, "index.html");
+ writeFileSync(html, "<!doctype html><html><head></head><body></body></html>", "utf8");
+ writeFileSync(script, `const {app,BrowserWindow,ipcMain}=require("electron");
+const {updateTitleBarOverlay}=require(${JSON.stringify(path.resolve("electron/windowControlsOverlay.js"))});
+app.setPath("userData",${JSON.stringify(path.join(temporary, "profile"))});
+app.whenReady().then(async()=>{
+ const win=new BrowserWindow({show:false,width:800,height:600,frame:false,titleBarStyle:"hidden",
+ titleBarOverlay:{color:"#00000000"},webPreferences:{nodeIntegration:true,contextIsolation:false,backgroundThrottling:false}});
+ ipcMain.on("siyuan-cmd",(event,data)=>{if(data.cmd==="setTitleBarOverlay")updateTitleBarOverlay(win,data);});
+ try{
+ const legacy=new BrowserWindow({show:false,width:800,height:600,frame:false,titleBarStyle:"hidden",
+ webPreferences:{nodeIntegration:true,contextIsolation:false,backgroundThrottling:false}});
+ await legacy.loadFile(${JSON.stringify(html)});
+ const fallback=await legacy.webContents.executeJavaScript(${JSON.stringify("const __name=value=>value;(" +
+ browserCases.toString() + ")(" + JSON.stringify(sources) + "," + JSON.stringify(css) + ",false)")});
+ if(fallback!=="Window controls overlay cases passed")throw new Error(fallback);
+ legacy.destroy();
+ await win.loadFile(${JSON.stringify(html)});
+ const result=await win.webContents.executeJavaScript(${JSON.stringify("const __name=value=>value;(" +
+ browserCases.toString() + ")(" + JSON.stringify(sources) + "," + JSON.stringify(css) + ")")});
+ console.log(result);win.destroy();app.exit(0);
+ }catch(error){console.error(error);win.destroy();app.exit(1);}
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, timeout: 15000, windowsHide: true});
+ assert.match(result.stdout, /Window controls overlay cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-window-controls-overlay-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/boot/windowControlsOverlay.ts b/app/src/boot/windowControlsOverlay.ts
new file mode 100644
index 0000000000..09ee79d976
--- /dev/null
+++ b/app/src/boot/windowControlsOverlay.ts
@@ -0,0 +1,110 @@
+import {ipcRenderer, webFrame} from "electron";
+import {Constants} from "../constants";
+import {resizeTopBar} from "../layout/util";
+
+export interface IWindowControlsOverlay extends EventTarget {
+ readonly visible: boolean;
+ getTitlebarAreaRect: () => DOMRect;
+}
+
+let initialized = false;
+let scheduled = false;
+let minimumHeight = 31;
+let lastStyle = "";
+let lastLayout = "";
+let sizeObserver: ResizeObserver;
+
+const getOverlay = () => (navigator as Navigator & {windowControlsOverlay?: IWindowControlsOverlay}).windowControlsOverlay;
+
+export const updateWindowControlsOverlay = () => {
+ scheduled = false;
+ const overlay = getOverlay();
+ if (!initialized || !overlay) return;
+ const visible = overlay.visible && !document.body.classList.contains("body--fullscreen");
+ document.documentElement.classList.toggle("window-controls-overlay--hidden", !visible);
+ const toolbar = document.querySelector<HTMLElement>("#toolbar, .toolbar__window, .toolbar--settings");
+ if (!toolbar) return;
+ const standalone = toolbar.classList.contains("toolbar__window");
+ const fused = document.body.classList.contains("body--toolbar-hide");
+ const rootStyle = getComputedStyle(document.documentElement);
+ const height = parseFloat(rootStyle.getPropertyValue(standalone || fused ?
+ "--b3-ui-panel-height" : "--b3-ui-toolbar-height")) || (standalone || fused ? 42 : 32);
+ const icon = toolbar.querySelector<HTMLElement>(".toolbar__item");
+ const symbolColor = getComputedStyle(icon || toolbar).color;
+ const style = {cmd: "setTitleBarOverlay", symbolColor,
+ height: Math.max(minimumHeight, Math.round(height * webFrame.getZoomFactor()))};
+ const styleKey = JSON.stringify(style);
+ if (lastStyle !== styleKey) {
+ lastStyle = styleKey;
+ ipcRenderer.send(Constants.SIYUAN_CMD, style);
+ }
+
+ const topRows = new Set<Element>();
+ if (standalone || fused) {
+ document.querySelectorAll(".layout-tab-bar").forEach(item => {
+ const header = item.parentElement;
+ const rect = header.getBoundingClientRect();
+ if (rect.height > 0 && rect.top <= 1) topRows.add(header);
+ });
+ }
+ document.querySelectorAll(".window-controls-overlay__top-row").forEach(item => {
+ if (!topRows.has(item)) item.classList.remove("window-controls-overlay__top-row");
+ });
+ topRows.forEach(item => item.classList.add("window-controls-overlay__top-row"));
+
+ const safe = overlay.getTitlebarAreaRect();
+ const layout = [safe.x, safe.width, safe.height, visible, fused, standalone, innerWidth, webFrame.getZoomFactor()].join(",");
+ if (window.siyuan?.isReady) {
+ // 外观或可见项刷新后,重新使用工具栏自身的折叠逻辑,避免窄窗口中的按钮溢出。
+ if (toolbar.id === "toolbar" && toolbar.scrollWidth > toolbar.clientWidth + 2) resizeTopBar();
+ if (lastLayout !== layout) {
+ lastLayout = layout;
+ window.dispatchEvent(new Event("resize"));
+ }
+ }
+};
+
+const schedule = () => {
+ if (scheduled) return;
+ scheduled = true;
+ window.setTimeout(updateWindowControlsOverlay, 32);
+};
+
+export const initWindowControlsOverlay = (container: HTMLElement) => {
+ const overlay = getOverlay();
+ if (!document.body.classList.contains("body--windows") || !overlay?.visible) return false;
+ if (container.id === "windowControls") {
+ container.classList.add("window-controls-overlay__placeholder");
+ } else if (!container.querySelector(".window-controls-overlay__placeholder")) {
+ const placeholder = document.createElement("div");
+ placeholder.className = "window-controls-overlay__placeholder";
+ container.append(placeholder);
+ }
+ if (!initialized) {
+ initialized = true;
+ minimumHeight = Math.ceil(overlay.getTitlebarAreaRect().height * webFrame.getZoomFactor()) || 31;
+ document.documentElement.classList.add("window-controls-overlay");
+ new MutationObserver(schedule).observe(document.body, {attributes: true, attributeFilter: ["class"]});
+ new MutationObserver(schedule).observe(document.documentElement, {
+ attributes: true, attributeFilter: ["data-ui-density", "data-theme-mode"],
+ });
+ new MutationObserver(schedule).observe(document.head, {childList: true, subtree: true});
+ document.head.addEventListener("load", schedule, true);
+ const selector = "#toolbar, #windowControls, .toolbar__window, .toolbar--settings, .layout-tab-bar";
+ new MutationObserver(records => {
+ if (records.some(record => [...record.addedNodes, ...record.removedNodes].some(node =>
+ node instanceof Element && (node.matches(selector) || node.querySelector(selector))))) schedule();
+ }).observe(document.body, {childList: true, subtree: true});
+ const toolbar = document.getElementById("toolbar");
+ if (toolbar) new MutationObserver(schedule).observe(toolbar, {
+ childList: true, subtree: true, attributes: true,
+ attributeFilter: ["class", "data-entry-hidden", "data-topbar-empty"],
+ });
+ sizeObserver = new ResizeObserver(schedule);
+ window.addEventListener("resize", schedule);
+ overlay.addEventListener("geometrychange", schedule);
+ }
+ sizeObserver.observe(container);
+ updateWindowControlsOverlay();
+ return true;
+};
diff --git a/app/src/dialog/tooltip.ts b/app/src/dialog/tooltip.ts
index 8ec8ed0712..4ecd6d31fa 100644
--- a/app/src/dialog/tooltip.ts
+++ b/app/src/dialog/tooltip.ts
@@ -1,6 +1,7 @@
import {isMobile} from "../util/functions";
import {emitToPlugins, forEachPluginSubscriber} from "../plugin/EventBusCore";
import {initHoverInput, isTouchHoverInput} from "../util/hoverInput";
+import type {IWindowControlsOverlay} from "../boot/windowControlsOverlay";
const INTERACTIVE_TOOLTIP_SELECTOR = "a, button, input, select, textarea, [contenteditable='true'], [tabindex], [role='button']";
@@ -191,6 +192,20 @@ export const showTooltip = (
left = window.innerWidth - messageElement.clientWidth;
}
}
+ // 原生窗口按钮显示在页面之上,提示框进入其区域时向下避让。
+ if (document.documentElement.classList.contains("window-controls-overlay") &&
+ !document.body.classList.contains("body--fullscreen")) {
+ const overlay = (navigator as Navigator & {windowControlsOverlay?: IWindowControlsOverlay}).windowControlsOverlay;
+ if (overlay?.visible) {
+ const safe = overlay.getTitlebarAreaRect();
+ if (top < safe.bottom && (Math.max(0, left) + messageElement.clientWidth > safe.right || left < safe.left)) {
+ top = safe.bottom + 4;
+ const available = Math.max(0, window.innerHeight - top - 4);
+ const maxHeight = parseFloat(getComputedStyle(messageElement).maxHeight);
+ messageElement.style.maxHeight = Math.min(Number.isFinite(maxHeight) ? maxHeight : available, available) + "px";
+ }
+ }
+ }
messageElement.style.top = top + "px";
messageElement.style.left = Math.max(0, left) + "px";
// 与 data-position 同套风格:触发元素可用 data-delay 指定悬浮延迟(毫秒),未设置时沿用 SCSS 默认值