feat: themed title bar for the desktop app (#1690)

This commit is contained in:
Giovanny Aranda authored and GitHub committed 2026-10-20 11:14:54 -05:00
1 parent 368a8eb415
commit e7d6d481df
8 files changed
+435 -2

No files matched your search

+69
View File
@@ -31,6 +31,10 @@ const { quitApp } = require("./app-quit.cjs");
const { selectLinuxPasswordStore } = require("./linux-password-store.cjs");
// Saved by the file manager after the user picks an editor in a file dialog.
const EXTERNAL_EDITOR_SETTING = "fileManager.externalEditorPath";
// The height of the title bar the app draws itself. The renderer uses the
// same number, so the bar and the window controls always line up.
const TITLE_BAR_HEIGHT = 40;
const { isExternalLoginUrl, isCallbackPort } = require("./external-login.cjs");
// The main process's Node.js networking (the global `fetch`) only
@@ -1327,12 +1331,27 @@ function createWindow() {
? "macOS"
: "Linux";
const isMac = process.platform === "darwin";
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
title: "Termix",
// The app draws its own title bar so it follows the active theme. macOS
// keeps the traffic lights on top of it, Windows and Linux get the
// native controls as an overlay whose colors the renderer keeps in sync.
titleBarStyle: isMac ? "hiddenInset" : "hidden",
...(isMac
? { trafficLightPosition: { x: 14, y: 16 } }
: {
titleBarOverlay: {
color: "#0f0f14",
symbolColor: "#e6e6ea",
height: TITLE_BAR_HEIGHT,
},
}),
icon: path.join(
appRoot,
"public",
@@ -1545,6 +1564,16 @@ function createWindow() {
}
});
const sendTitleBarVisible = () => {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send(
"title-bar-visible-changed",
titleBarVisible(mainWindow),
);
};
mainWindow.on("enter-full-screen", sendTitleBarVisible);
mainWindow.on("leave-full-screen", sendTitleBarVisible);
mainWindow.on("closed", () => {
embeddedViews.destroyAll();
mainWindow = null;
@@ -1574,10 +1603,50 @@ ipcMain.handle("get-app-version", () => {
return app.getVersion();
});
/** The window an IPC call came from, so the main window and the extra
* windows (isolated views, sign-in) can each answer for themselves. */
function windowFor(event) {
const win = BrowserWindow.fromWebContents(event.sender);
if (win && !win.isDestroyed()) return win;
if (mainWindow && !mainWindow.isDestroyed()) return mainWindow;
return null;
}
ipcMain.handle("get-platform", () => {
return process.platform;
});
// Whether the app-drawn title bar shows in the window that asks. Only the
// main window hides the native bar, and in full screen macOS hides the
// traffic lights, so the bar goes away there too.
function titleBarVisible(win) {
return !!win && win === mainWindow && !win.isFullScreen();
}
ipcMain.handle("get-title-bar-visible", (event) => {
return titleBarVisible(windowFor(event));
});
// The renderer sends the colors of the active theme so the window controls
// the system draws (Windows and Linux) match the app.
ipcMain.handle("set-title-bar-overlay", (event, colors) => {
const win = windowFor(event);
if (!win || process.platform === "darwin") return;
const options = {};
if (typeof colors?.color === "string" && colors.color) {
options.color = colors.color;
}
if (typeof colors?.symbolColor === "string" && colors.symbolColor) {
options.symbolColor = colors.symbolColor;
}
if (Object.keys(options).length === 0) return;
try {
win.setTitleBarOverlay(options);
} catch (error) {
logToFile("setTitleBarOverlay failed:", error);
}
});
ipcMain.handle("get-embedded-server-status", () => {
return {
running:
+13
View File
@@ -32,6 +32,19 @@ contextBridge.exposeInMainWorld("electronAPI", {
webFrame.setZoomFactor(Math.min(2, Math.max(0.5, value)));
},
getPlatform: () => ipcRenderer.invoke("get-platform"),
// Whether the app-drawn title bar shows in this window, and when it changes
// (full screen hides it).
getTitleBarVisible: () => ipcRenderer.invoke("get-title-bar-visible"),
onTitleBarVisibleChange: (callback) => {
const listener = (_event, visible) => callback(visible);
ipcRenderer.on("title-bar-visible-changed", listener);
return () =>
ipcRenderer.removeListener("title-bar-visible-changed", listener);
},
// Keeps the window controls the system draws in the colors of the theme.
setTitleBarOverlay: (colors) =>
ipcRenderer.invoke("set-title-bar-overlay", colors),
getEmbeddedServerStatus: () =>
ipcRenderer.invoke("get-embedded-server-status"),
+11
View File
@@ -35,6 +35,17 @@ export interface ElectronAPI {
getAppVersion: () => Promise<string>;
setZoomFactor?: (factor: number) => void;
getPlatform: () => Promise<string>;
/** Whether the app-drawn title bar shows in this window. */
getTitleBarVisible?: () => Promise<boolean>;
/** Calls back when the title bar shows or hides; returns an unsubscribe. */
onTitleBarVisibleChange?: (
callback: (visible: boolean) => void,
) => () => void;
/** Keeps the window controls the system draws in the colors of the theme. */
setTitleBarOverlay?: (colors: {
color?: string;
symbolColor?: string;
}) => Promise<void>;
getSetting?: (key: string) => Promise<string | null | undefined>;
setSetting?: (key: string, value: string) => Promise<void>;
+23 -2
View File
@@ -1,5 +1,10 @@
/* eslint-disable react-refresh/only-export-components */
import { prepareClientCacheVersion } from "@/lib/client-cache-version";
import {
TitleBar,
TITLE_BAR_OFFSET,
useTitleBarOverlayColors,
} from "@/shell/TitleBar";
import { StrictMode, Suspense, lazy, useState, useRef, useEffect } from "react";
import { createRoot } from "react-dom/client";
import "./ui/index.css";
@@ -160,6 +165,8 @@ function FullscreenAppGate() {
}
function App() {
// Keeps the window controls the system draws in the colors of the theme.
useTitleBarOverlayColors();
const stored = getStoredAuth();
const [phase, setPhase] = useState<Phase>(
stored?.loggedIn ? "verifying" : "idle-auth",
@@ -370,10 +377,17 @@ function App() {
const { t } = useTranslation();
const isTransitioning = phase === "fading-in" || phase === "fading-out";
// The desktop app draws a title bar on top of the window, so everything
// below it starts lower. The bar sets the offset only while it shows.
const titleBarOffset = TITLE_BAR_OFFSET;
if (phase === "verifying" || phase === "loading-app") {
return (
<div className="fixed inset-0 flex items-center justify-center bg-background">
<div
className="fixed inset-0 flex items-center justify-center bg-background"
style={{ paddingTop: titleBarOffset }}
>
<TitleBar />
<div className="flex flex-col items-center gap-4">
<div className="w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin" />
<p className="text-sm text-muted-foreground">{t("common.loading")}</p>
@@ -384,8 +398,13 @@ function App() {
return (
<>
<TitleBar />
{isTransitioning && (
<div className="fixed inset-0 z-0 flex items-center justify-center bg-background">
<div
className="fixed inset-0 z-0 flex items-center justify-center bg-background"
style={{ paddingTop: titleBarOffset }}
>
<div className="flex flex-col items-center gap-4">
<div className="w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin" />
<p className="text-sm text-muted-foreground">
@@ -416,6 +435,7 @@ function App() {
style={{
opacity: appOpacity,
pointerEvents: phase === "idle-app" ? "auto" : "none",
paddingTop: titleBarOffset,
}}
>
<Suspense fallback={null}>
@@ -432,6 +452,7 @@ function App() {
style={{
opacity: authOpacity,
pointerEvents: phase === "idle-auth" ? "auto" : "none",
paddingTop: titleBarOffset,
}}
>
<Auth onLogin={handleLogin} />
+25
View File
@@ -555,3 +555,28 @@ html.fs-xl {
background-color: color-mix(in oklab, var(--accent-brand) 35%, transparent);
color: inherit;
}
/*
* The title bar the desktop app draws on top of its window. The window has
* no native frame, so this strip is what moves the window around: the whole
* bar drags, everything inside it that takes clicks does not.
*/
.termix-titlebar {
-webkit-app-region: drag;
user-select: none;
}
.termix-titlebar button,
.termix-titlebar a,
.termix-titlebar input,
.termix-titlebar [role="button"] {
-webkit-app-region: no-drag;
}
/*
* Layouts size themselves to the viewport with h-dvh. Under the app-drawn
* title bar the usable height is shorter, so trim it while the bar shows.
*/
.h-dvh {
height: calc(100dvh - var(--termix-titlebar-height, 0px));
}
+2
View File
@@ -6,6 +6,7 @@ import { SurfaceScope } from "@/components/surface/surface-scope";
import { useUiPreferencesContext } from "@/contexts/UiPreferencesContext";
import { usePermissions } from "@/hooks/use-permissions";
import { isElectron } from "@/lib/electron";
import { TITLE_BAR_OFFSET } from "@/shell/TitleBar";
import {
getOnboardingPlugins,
type OnboardingPluginList,
@@ -236,6 +237,7 @@ export function OnboardingStage({
<OnboardingStageContext.Provider value={stageValue}>
<div
className="fixed inset-0 z-[60] overflow-y-auto bg-background text-foreground"
style={{ paddingTop: TITLE_BAR_OFFSET }}
role="dialog"
aria-modal="true"
aria-label={t("onboarding.stageLabel")}
+168
View File
@@ -0,0 +1,168 @@
/* eslint-disable react-refresh/only-export-components */
import { useEffect, useState } from "react";
import { isElectron } from "@/lib/electron";
import { useBranding } from "@/contexts/BrandingContext";
/**
* The height of the bar the desktop app draws on top of its window. The
* Electron main process uses the same number for the window controls the
* system draws, so both line up.
*/
export const TITLE_BAR_HEIGHT = 40;
/**
* How far content starts below the top of the window. The bar sets the
* variable only while it shows, so it is 0 on the web, in full screen and in
* windows that keep the native title bar.
*/
export const TITLE_BAR_OFFSET = "var(--termix-titlebar-height, 0px)";
/** Room the macOS traffic lights take on the left. */
const MAC_TRAFFIC_LIGHTS_WIDTH = 78;
/** Room the Windows and Linux window controls take on the right. */
const OVERLAY_CONTROLS_WIDTH = 140;
type Platform = "darwin" | "win32" | "linux" | "other";
/**
* The title bar of the desktop app. The system draws its own frame, so the
* bar is drawn by the app instead: it takes the colors of the active theme
* and keeps the window controls the system draws on top of it.
*/
export function TitleBar() {
const [platform, setPlatform] = useState<Platform | null>(null);
const [visible, setVisible] = useState(false);
useEffect(() => {
if (!isElectron()) return;
let cancelled = false;
const api = window.electronAPI;
if (typeof api?.getPlatform === "function") {
void api
.getPlatform()
.then((value: string) => {
if (!cancelled) setPlatform(value as Platform);
})
.catch(() => {});
} else {
// Without the bridge, fall back to what the user agent says.
setPlatform(/mac/i.test(navigator.userAgent) ? "darwin" : "other");
}
// Older builds without the visibility bridge always show the bar.
if (typeof api?.getTitleBarVisible === "function") {
void api
.getTitleBarVisible()
.then((value) => {
if (!cancelled) setVisible(value);
})
.catch(() => {});
} else {
setVisible(true);
}
const unsubscribe = api?.onTitleBarVisibleChange?.(setVisible);
return () => {
cancelled = true;
unsubscribe?.();
};
}, []);
const shown = isElectron() && platform !== null && visible;
useEffect(() => {
if (!shown) return;
const root = document.documentElement;
root.style.setProperty("--termix-titlebar-height", `${TITLE_BAR_HEIGHT}px`);
return () => {
root.style.removeProperty("--termix-titlebar-height");
};
}, [shown]);
if (!shown) return null;
const isMac = platform === "darwin";
const hasOverlayControls = platform === "win32" || platform === "linux";
return (
<div
className="termix-titlebar fixed inset-x-0 top-0 z-[70] flex items-center bg-background border-b border-border"
style={{ height: TITLE_BAR_HEIGHT }}
>
{isMac && (
<div
className="shrink-0"
style={{ width: MAC_TRAFFIC_LIGHTS_WIDTH }}
aria-hidden="true"
/>
)}
<TitleLabel />
<div className="flex-1" />
{hasOverlayControls && (
<div
className="shrink-0"
style={{ width: OVERLAY_CONTROLS_WIDTH }}
aria-hidden="true"
/>
)}
</div>
);
}
/** The name of the app, centered like the native bars do. */
function TitleLabel() {
const { appName } = useBranding();
return (
<div className="pointer-events-none absolute inset-x-0 flex items-center justify-center">
<span className="truncate px-3 text-sm font-medium text-muted-foreground">
{appName}
</span>
</div>
);
}
/**
* Keeps the window controls the system draws in the colors of the theme.
* Only Windows and Linux draw them, macOS keeps its own traffic lights.
*
* The theme is a class on the root element, so the colors are read from the
* style sheet whenever it changes.
*/
export function useTitleBarOverlayColors() {
useEffect(() => {
if (!isElectron()) return;
const api = window.electronAPI;
if (typeof api?.setTitleBarOverlay !== "function") return;
const send = () => {
// Computed colors always come back as rgb(), whatever format the
// theme uses (hex, oklch, ...).
const styles = getComputedStyle(document.body);
const color = toHexColor(styles.backgroundColor);
if (!color) return;
api.setTitleBarOverlay({
color,
symbolColor: toHexColor(styles.color) || "#e6e6ea",
});
};
send();
const observer = new MutationObserver(send);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class", "style"],
});
return () => observer.disconnect();
}, []);
}
/** Turns a computed rgb()/rgba() color into a hex string. */
function toHexColor(color: string): string {
const match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?/);
// A fully transparent color has nothing to show; keep the last one.
if (!match || match[4] === "0") return "";
const [, r, g, b] = match;
return `#${[r, g, b].map((part) => Number(part).toString(16).padStart(2, "0")).join("")}`;
}
+124
View File
@@ -0,0 +1,124 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
import { TitleBar, useTitleBarOverlayColors } from "@/shell/TitleBar";
vi.mock("@/contexts/BrandingContext", () => ({
useBranding: () => ({ appName: "Termix" }),
}));
type Listener = (visible: boolean) => void;
function installBridge(options: { visible?: boolean } = {}) {
let listener: Listener | null = null;
const api = {
getPlatform: vi.fn().mockResolvedValue("darwin"),
getTitleBarVisible: vi.fn().mockResolvedValue(options.visible ?? true),
onTitleBarVisibleChange: vi.fn((callback: Listener) => {
listener = callback;
return () => {
listener = null;
};
}),
setTitleBarOverlay: vi.fn().mockResolvedValue(undefined),
};
(window as unknown as { electronAPI?: unknown }).electronAPI = api;
return { api, emit: (visible: boolean) => listener?.(visible) };
}
const heightVar = () =>
document.documentElement.style.getPropertyValue("--termix-titlebar-height");
afterEach(() => {
cleanup();
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
document.documentElement.removeAttribute("style");
document.body.removeAttribute("style");
});
describe("TitleBar", () => {
it("renders nothing and sets no offset outside the desktop app", () => {
const { container } = render(<TitleBar />);
expect(container.firstChild).toBeNull();
expect(heightVar()).toBe("");
});
it("shows the bar and sets the offset when the window has one", async () => {
installBridge();
render(<TitleBar />);
expect(await screen.findByText("Termix")).toBeTruthy();
expect(heightVar()).toBe("40px");
});
it("stays hidden in windows without the app-drawn bar", async () => {
const { api } = installBridge({ visible: false });
const { container } = render(<TitleBar />);
await waitFor(() => expect(api.getTitleBarVisible).toHaveBeenCalled());
expect(container.firstChild).toBeNull();
expect(heightVar()).toBe("");
});
it("hides and clears the offset in full screen, and comes back after", async () => {
const { emit } = installBridge();
render(<TitleBar />);
await screen.findByText("Termix");
act(() => emit(false));
expect(screen.queryByText("Termix")).toBeNull();
expect(heightVar()).toBe("");
act(() => emit(true));
expect(screen.getByText("Termix")).toBeTruthy();
expect(heightVar()).toBe("40px");
});
it("unsubscribes from visibility changes on unmount", async () => {
const { api, emit } = installBridge();
const { unmount } = render(<TitleBar />);
await screen.findByText("Termix");
unmount();
expect(() => emit(false)).not.toThrow();
expect(api.onTitleBarVisibleChange).toHaveBeenCalledTimes(1);
expect(heightVar()).toBe("");
});
});
function OverlayColors() {
useTitleBarOverlayColors();
return null;
}
describe("useTitleBarOverlayColors", () => {
it("sends the computed theme colors as hex", () => {
const { api } = installBridge();
document.body.style.backgroundColor = "rgb(15, 15, 20)";
document.body.style.color = "rgb(230, 230, 234)";
render(<OverlayColors />);
expect(api.setTitleBarOverlay).toHaveBeenCalledWith({
color: "#0f0f14",
symbolColor: "#e6e6ea",
});
});
it("sends the new colors when the theme class changes", async () => {
const { api } = installBridge();
document.body.style.backgroundColor = "rgb(255, 255, 255)";
render(<OverlayColors />);
api.setTitleBarOverlay.mockClear();
document.body.style.backgroundColor = "rgb(40, 42, 54)";
document.documentElement.classList.add("dracula");
await waitFor(() =>
expect(api.setTitleBarOverlay).toHaveBeenCalledWith(
expect.objectContaining({ color: "#282a36" }),
),
);
document.documentElement.classList.remove("dracula");
});
it("sends nothing when the background color cannot be read", () => {
const { api } = installBridge();
document.body.style.backgroundColor = "transparent";
render(<OverlayColors />);
expect(api.setTitleBarOverlay).not.toHaveBeenCalled();
});
});