Compare commits

..

3 commits

Author SHA1 Message Date
CRT
711fc53c55 host: a restored window fits the monitor it opens on
A state saved on a larger or rearranged screen (2720x1800 at x=3347 on a smaller second monitor)
left the titlebar off-screen and the window could not be moved. After the window-state restore,
the window is moved inside, and shrunk to, the work area of the monitor it is mostly on (the
primary one when that monitor is gone). Maximized and full-screen windows are left to the OS.
window_fit::fit is pure and unit tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:29:35 +07:00
CRT
2a8e926967 shell: the app menu hangs from each pane's wB button; the titlebar logo is plain again
ShellMenu.trigger chooses the trigger: 'pane' (default; each pane's wB button opens the menu under
itself, lined up with its end edge and kept inside the window), 'button' (titlebar) or 'logo'.
Alt+F, F10, the palette and the account menu's last row open it under the focused pane's wB (the
first one on screen otherwise). The menu's Settings row and the other panel rows still open the
panel, and Ctrl+Shift+W still does. The logo is part of the drag region again, as before e5d43af.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:22:41 +07:00
CRT
9fbfa791b4 Theme engine: page flags instead of page-wide :has()
A theme rule gated by html:has(...) / body:not(:has(...)) made the browser
restyle the whole page for every node the site inserted. Measured live on
x.com under any theme: about 440 elements restyled per insertion, against 1.5
without a theme; with the gates gone, 2.5.

Sites name page states as selectors (ThemeRuntimeSite.flags). The engine
keeps html[data-wb-<name>] in step, checked once per DOM hub frame and also
inside the site's open shadow roots. It passes the flags that hold to css(),
so CSS for one state can be left out of the other. Changing flags rebuild the
theme (they are part of its render key). Tests: pageFlags, flagAttribute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:42:45 +07:00
13 changed files with 380 additions and 62 deletions

View file

@ -1160,6 +1160,32 @@ pub fn reset_lost_geometry(window: &tauri::Window, size: (f64, f64), min: (f64,
}
}
/// A restored window lies inside the work area of the monitor it opens on (the primary one when
/// that monitor is gone): a state saved on a larger or rearranged screen would otherwise leave
/// its titlebar out of reach ([`crate::window_fit::fit`]). A maximized or full-screen window is
/// the OS's to place.
pub fn fit_to_monitor(window: &tauri::Window) {
use crate::window_fit::{fit, Rect};
if window.is_maximized().unwrap_or(false) || window.is_fullscreen().unwrap_or(false) {
return;
}
let (Ok(position), Ok(size), Ok(monitors)) = (window.outer_position(), window.outer_size(), window.available_monitors()) else { return };
let area = |monitor: &tauri::Monitor| {
let work = monitor.work_area();
Rect::new(work.position.x, work.position.y, work.size.width, work.size.height)
};
let areas: Vec<Rect> = monitors.iter().map(area).collect();
let primary = window.primary_monitor().ok().flatten().map(|monitor| area(&monitor));
let Some(fitted) = fit(Rect::new(position.x, position.y, size.width, size.height), &areas, primary) else { return };
if (fitted.width, fitted.height) != (size.width, size.height) {
// The outer frame must fit; the inner size is what can be set, so the frame's border comes off it.
let inner = window.inner_size().unwrap_or(size);
let (extra_w, extra_h) = (size.width.saturating_sub(inner.width), size.height.saturating_sub(inner.height));
let _ = window.set_size(tauri::PhysicalSize::new(fitted.width.saturating_sub(extra_w), fitted.height.saturating_sub(extra_h)));
}
let _ = window.set_position(tauri::PhysicalPosition::new(fitted.x, fitted.y));
}
/// The host's commands ([`commands::SHELL`], [`commands::TAB`], [`commands::SITE`]).
fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![
@ -1459,6 +1485,7 @@ fn open_window(app: &mut tauri::App<Wry>, config: &AppConfig) -> Result<(), Box<
let _ = window.restore_state(window_state_flags());
}
reset_lost_geometry(&window, config.window_size, config.min_window_size);
fit_to_monitor(&window);
// `taskkill` (and anything else closing "the first visible window") must close the app
// even when a minimized window sits below the runtime's helper windows.
host::route_helper_closes(&window);

View file

@ -76,6 +76,7 @@ pub mod tabs;
pub mod testkit;
pub mod theme;
pub mod update;
pub mod window_fit;
pub mod workspaces;
pub mod zoom;

View file

@ -0,0 +1,108 @@
//! A restored window fits the monitor it opens on. A saved state can come from a larger or a
//! differently arranged monitor (2720x1800 saved on a big screen, restored on a smaller second
//! one): the window then hangs past the work area, its titlebar out of reach, and it cannot be
//! moved. [`fit`] picks the monitor the window is mostly on (the primary one when it is on none),
//! shrinks the window to that monitor's work area when it is larger, and moves it inside.
//! Physical pixels throughout, as the OS reports monitors.
/// A rectangle in physical pixels (a window's outer frame, a monitor's work area).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
}
impl Rect {
pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
Self { x, y, width, height }
}
fn right(&self) -> i64 {
i64::from(self.x) + i64::from(self.width)
}
fn bottom(&self) -> i64 {
i64::from(self.y) + i64::from(self.height)
}
/// The area two rectangles share (0 when they do not meet).
fn overlap(&self, other: &Rect) -> i64 {
let width = self.right().min(other.right()) - i64::from(self.x.max(other.x));
let height = self.bottom().min(other.bottom()) - i64::from(self.y.max(other.y));
if width <= 0 || height <= 0 { 0 } else { width * height }
}
}
/// Where `window` should be so it lies inside a work area: `None` when it already does.
///
/// The work area is the one of the monitor the window overlaps most; when it overlaps none (that
/// monitor is gone), `primary`, else the first one. The size shrinks to the work area (never
/// grows); the position moves just enough to bring the whole frame inside.
pub fn fit(window: Rect, work_areas: &[Rect], primary: Option<Rect>) -> Option<Rect> {
let best = work_areas
.iter()
.map(|area| (window.overlap(area), area))
.filter(|(shared, _)| *shared > 0)
.max_by_key(|(shared, _)| *shared)
.map(|(_, area)| *area);
let area = best.or(primary).or_else(|| work_areas.first().copied())?;
if area.width == 0 || area.height == 0 {
return None;
}
let width = window.width.min(area.width);
let height = window.height.min(area.height);
let clamp = |at: i32, len: u32, start: i32, room: u32| -> i32 {
let last = i64::from(start) + i64::from(room) - i64::from(len);
i64::from(at).clamp(i64::from(start), last.max(i64::from(start))) as i32
};
let fitted = Rect::new(clamp(window.x, width, area.x, area.width), clamp(window.y, height, area.y, area.height), width, height);
(fitted != window).then_some(fitted)
}
#[cfg(test)]
mod tests {
use super::*;
// A 2560x1600 main monitor (taskbar 48 px) and a smaller 1920x1080 one to its right.
const MAIN: Rect = Rect::new(0, 0, 2560, 1552);
const SECOND: Rect = Rect::new(2560, 0, 1920, 1032);
#[test]
fn a_window_saved_on_a_bigger_screen_shrinks_into_the_smaller_monitor_it_opens_on() {
// The reported case: 2720x1800 at x=3347, mostly on the second monitor; its titlebar was off-screen.
let fitted = fit(Rect::new(3347, 40, 2720, 1800), &[MAIN, SECOND], Some(MAIN)).unwrap();
assert_eq!(fitted, SECOND);
}
#[test]
fn a_window_hanging_past_an_edge_moves_inside_and_keeps_its_size() {
let fitted = fit(Rect::new(3800, -30, 1200, 800), &[MAIN, SECOND], Some(MAIN)).unwrap();
assert_eq!(fitted, Rect::new(2560 + 1920 - 1200, 0, 1200, 800));
// Past the start edges too.
assert_eq!(fit(Rect::new(-500, 900, 1200, 800), &[MAIN, SECOND], Some(MAIN)), Some(Rect::new(0, 1552 - 800, 1200, 800)));
}
#[test]
fn a_window_whose_monitor_is_gone_opens_on_the_primary_one() {
let fitted = fit(Rect::new(6000, 200, 1400, 900), &[MAIN], Some(MAIN)).unwrap();
assert_eq!(fitted, Rect::new(2560 - 1400, 200, 1400, 900));
// No primary reported: the first monitor.
assert_eq!(fit(Rect::new(6000, 200, 1400, 900), &[SECOND], None), Some(Rect::new(2560 + 1920 - 1400, 1032 - 900, 1400, 900)));
}
#[test]
fn a_window_inside_its_work_area_is_left_alone() {
assert_eq!(fit(Rect::new(100, 80, 1600, 1000), &[MAIN, SECOND], Some(MAIN)), None);
assert_eq!(fit(SECOND, &[MAIN, SECOND], Some(MAIN)), None);
assert_eq!(fit(Rect::new(100, 80, 1600, 1000), &[], None), None);
}
#[test]
fn monitors_left_of_and_above_the_main_one_work_too() {
let left = Rect::new(-1920, -200, 1920, 1040);
let fitted = fit(Rect::new(-2100, -260, 2000, 1200), &[MAIN, left], Some(MAIN)).unwrap();
assert_eq!(fitted, left);
}
}

View file

@ -5,7 +5,7 @@
// the site adapter (`ThemeRuntimeSite`): X re-declares its own stylesheet rules with the theme's
// colors (`buildThemeCss`) and adds type/shape/layout rules over its selectors.
import { domRoots } from './domHub.ts';
import { domRoots, watchDom, type DomWatchHandle } from './domHub.ts';
import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts';
import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts';
import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts';
@ -160,7 +160,7 @@ export type ThemeRuntimeSite<Mode extends string = string> = {
/** The site's color mode as the page paints it now (read before the theme's own override: e.g. the body's inline style). */
readMode(win: Window): Mode;
/** The theme's CSS for the site's current `rules` (the engine's own sheet excluded) in `mode`; `vars` are `siteVars` as the site sets them. */
css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record<string, string>): string;
css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record<string, string>, flags: readonly string[]): string;
/** The active theme resolved for plugins and the UI kit (the site's own palette when the theme keeps its colors). */
resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme;
/** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */
@ -178,8 +178,28 @@ export type ThemeRuntimeSite<Mode extends string = string> = {
styleId?: string;
/** Name in console errors. */
name?: string;
/**
* Page states the theme's CSS keys on, as `html[data-wb-<name>]` attributes kept by the engine:
* set while `selector` matches in the page or one of its open shadow roots (domHub `shadowHosts`).
* A theme rule gated by `html[data-wb-chat]` costs nothing when the page changes; the same gate
* as `html:has(...)` makes the browser re-match the whole page on every insertion (seen on x.com:
* 10-100 ms per inserted node under a theme instead of 0.1 ms).
*/
flags?: Readonly<Record<string, string>>;
};
/** The attribute a page flag sets on `<html>`. */
export const flagAttribute = (name: string) => `data-wb-${name}`;
/** Which of `flags` hold in `roots` now (pure, for tests). */
export function pageFlags(roots: ReadonlyArray<{ querySelector(selector: string): unknown }>, flags: Readonly<Record<string, string>>): string[] {
const on: string[] = [];
for (const [name, selector] of Object.entries(flags)) {
try { if (roots.some(root => !!root.querySelector(selector))) on.push(name); } catch { /* A bad selector is never on. */ }
}
return on;
}
export type ThemeHandle<Mode extends string = string> = {
apply(choice: unknown): void;
current(): ThemeChoice;
@ -266,6 +286,36 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
let staticKey = '';
let staticText = '';
let siteVars: Record<string, string> = {};
// Page flags (`site.flags`): checked once per hub frame after the page changed, on every page (heavy ones too).
const flagNames = Object.keys(site.flags ?? {});
let flagWatch: DomWatchHandle | null = null;
// The flags that hold now; the theme's CSS is rebuilt when they change (a rule that only applies to a
// signed-out page can then be left out of a signed-in one instead of being gated by `:has()`).
let flagState: string[] = [];
const syncFlags = () => {
const root = doc.documentElement;
if (!root || !flagNames.length) return;
let on: string[] = [];
try { on = pageFlags(domRoots(win), site.flags!); } catch { on = []; }
for (const name of flagNames) {
const attr = flagAttribute(name);
const want = on.includes(name);
if (root.hasAttribute(attr) !== want) { if (want) root.setAttribute(attr, ''); else root.removeAttribute(attr); }
}
const changed = on.join(' ') !== flagState.join(' ');
flagState = on;
return changed;
};
const flagsOn = (on: boolean) => {
if (!flagNames.length) return;
if (on) {
syncFlags();
if (!flagWatch) { try { flagWatch = watchDom(win as never, () => { if (syncFlags()) { try { render(); } catch { /* Never break the site. */ } } }, { offOnHeavy: false }); } catch { flagWatch = null; } }
} else {
flagWatch?.dispose(); flagWatch = null;
for (const name of flagNames) doc.documentElement?.removeAttribute(flagAttribute(name));
}
};
// Open shadow roots the site renders a part of itself in (domHub `shadowHosts`; X's chat embed since
// 2026-10-01): the document's sheets do not reach inside, so each root adopts the theme built from
// its own rules plus the static sheet, kept last among its sheets, rebuilt when its rules change and
@ -283,7 +333,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
try { item = { sheet: new Sheet(), key: '' }; } catch { continue; }
rootSheets.set(root, item);
}
const key = `${snapshotKey}|${rootRuleCount(root, item.sheet)}|${staticText.length}`;
const key = `${snapshotKey}|${flagState.join(' ')}|${rootRuleCount(root, item.sheet)}|${staticText.length}`;
if (force || item.key !== key) {
item.key = key;
// The site's primitives as the root sees them (its own sheets may declare them; the document may not), read with our sheet off.
@ -295,7 +345,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
item.sheet.disabled = false;
}
let css = '';
try { css = site.css(collectRootRules(root, item.sheet, (win as Window & typeof globalThis).CSS), choice, mode, vars); } catch (error) { console.error(`[${name}] theme (shadow root) failed`, error); }
try { css = site.css(collectRootRules(root, item.sheet, (win as Window & typeof globalThis).CSS), choice, mode, vars, flagState); } catch (error) { console.error(`[${name}] theme (shadow root) failed`, error); }
try { item.sheet.replaceSync(staticText ? `${css}\n${staticText}` : css); } catch { /* Keeps the last good rules. */ }
}
// Last, so equal-specificity `!important` rules win over the site's; the site may re-set its list.
@ -312,8 +362,9 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
let fixed = doc.getElementById(staticId) as HTMLStyleElement | null;
if (doc.body) { watchMode(); syncResolved(); }
if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); syncRoots(false, '', false); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); syncRoots(false, '', false); flagsOn(false); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
if (!doc.body) return;
flagsOn(true);
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
if (early && snapshot?.key !== snapshotKey) dropEarly();
// The static sheet follows the theme and the mode only (and `refresh()`), never the site's rules.
@ -327,7 +378,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
if (fixed.textContent !== text) fixed.textContent = text;
} else { fixed?.remove(); fixed = null; }
}
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`;
const key = `${JSON.stringify(choice)}|${mode}|${flagState.join(' ')}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`;
if (!force && key === lastKey) { placeStatic(fixed, style); syncRoots(true, snapshotKey, false); return; }
lastKey = key;
if (!style) { style = doc.createElement('style'); style.id = styleId; }
@ -340,7 +391,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
}
if (style.sheet) style.sheet.disabled = false;
siteVars = vars;
const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars);
const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars, flagState);
if (style.textContent !== css) style.textContent = css;
// Last in <head> so equal-specificity `!important` rules win over the site's; the static sheet after it.
const last = fixed?.isConnected && doc.head?.lastElementChild === fixed ? fixed.previousElementSibling : doc.head?.lastElementChild;

View file

@ -5,7 +5,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.ts';
import { choiceForId, createThemeCatalog, serializeChoice, MAX_USER_THEMES } from '../src/themeChoice.ts';
import { SNAPSHOT_LOCAL_MAX, collectRootRules, collectRules, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
import { SNAPSHOT_LOCAL_MAX, collectRootRules, collectRules, flagAttribute, pageFlags, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
import {
BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, ROLE_LIMITS, applyOverrides, backgroundLayers, ensureContrast, fontChoiceOf, fontStack, isNeutral,
pageBackgroundCss, parseThemeJson, resolveFontRoles, sanitizeSpec, withFamily, withRoles, type ThemeSpec,
@ -262,3 +262,12 @@ test('collectRootRules reads a shadow root\'s adopted sheets and <style> element
assert.deepEqual(rules.map(rule => rule.selectorText), [':host, [data-theme="dark"]', '.bg-white\/15']);
assert.equal(rules[1]!.style.getPropertyValue('background-color'), 'color-mix(in oklab, var(--x-white) 15%, transparent)');
});
test('page flags: a flag holds while its selector matches in the page or one of its shadow roots', () => {
const root = (hits: string[]) => ({ querySelector: (selector: string) => (hits.includes(selector) ? {} : null) });
const flags = { chat: '[data-testid="dm-container"]', 'signed-out': 'body:not(:has(main))', bad: '::nope(' };
assert.deepEqual(pageFlags([root([]), root(['[data-testid="dm-container"]'])], flags), ['chat'], 'a match in a shadow root counts');
assert.deepEqual(pageFlags([root([])], flags), []);
assert.deepEqual(pageFlags([{ querySelector: () => { throw new Error('bad'); } }], { bad: 'x' }), [], 'a selector that throws is never on');
assert.equal(flagAttribute('chat'), 'data-wb-chat');
});

View file

@ -1,9 +1,11 @@
// The app menu: the titlebar's "Settings and more" button, at the far end of the titlebar cluster
// (before the caption buttons on Windows and Linux; macOS has none there). It opens on click, on
// Alt+F and F10 (Shell.tsx; a focused tab forwards the keys), from the command palette, from the
// last row of the account menu, and from the app's logo at the start of the titlebar (the same
// menu, hung under the logo on its side of the window). Its rows are the app's (`ShellSite.menu`, menuModel.ts): built-in
// ones by name, each shown only when the app serves what it needs, and the app's own.
// The app menu ("Settings and more"). Its trigger is the app's choice (`ShellMenu.trigger`): by
// default each pane's wayBetter button at the end of its toolbar (`PaneMenuButton`; the menu hangs
// under the button that was clicked, so in split view each pane opens it under itself), else a
// button at the end of the titlebar or the titlebar's logo. It also opens on Alt+F and F10
// (Shell.tsx; a focused tab forwards the keys), from the command palette and from the last row of
// the account menu: under the focused pane's button (the first one on screen when no pane is
// focused). Its rows are the app's (`ShellSite.menu`, menuModel.ts): built-in ones by name, each
// shown only when the app serves what it needs, and the app's own.
//
// Like every shell menu it is an overlay: while open the shell is raised above the tab webviews
// (`setOverlay`), panes stay visible and nothing is dimmed. Keyboard: arrows, Home/End, type-ahead,
@ -11,7 +13,7 @@
// Enter or Space chooses, Esc closes one level. Submenus fly out beside the menu and stay inside
// the window (in a narrow one they lie over it). Words: menuMessages.en.json (`menuText`).
import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { parseUpdateStatus, type UpdateStatus } from '../updateModel.ts';
import { invoke, listen } from './bridge.ts';
@ -22,8 +24,8 @@ import { useDev, usePaneTick, useT } from './hooks.ts';
import { formatNumber } from './i18n.ts';
import { Icon, type IconName } from './icons.tsx';
import {
DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow,
type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuModeStatus, type MenuRow,
DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, resolveTrigger, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow,
type AppMenuTrigger, type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuModeStatus, type MenuRow,
} from './menuModel.ts';
import { ReportDialog } from './ReportDialog.tsx';
import { safe, setSafeMode } from './safeStore.ts';
@ -35,8 +37,12 @@ import { loadWorkspaces, restoreWorkspace, workspaceList, workspaces } from './w
import { readZoom, stepZoom, zoomOf, zoomTarget } from './zoomStore.ts';
import './appMenu.css';
/** How the menu is asked to open: under the logo instead of its button, at a submenu, with the first row focused (keyboard), or closing if it is open. */
export type AppMenuRequest = { anchor?: 'button' | 'logo'; submenu?: string; keyboard?: boolean; toggle?: boolean };
/**
* How the menu is asked to open: at a trigger other than the app's own (`anchor`), under one pane's
* button (`pane`, a dockview panel id), at a submenu, with the first row focused (keyboard), or
* closing if it is open at that place.
*/
export type AppMenuRequest = { anchor?: AppMenuTrigger; pane?: string; submenu?: string; keyboard?: boolean; toggle?: boolean };
/** Opens the app menu (Alt+F / F10, the palette, the account menu's last row). */
export const openAppMenu = (request: AppMenuRequest = {}) => window.dispatchEvent(new CustomEvent('bt-app-menu', { detail: request }));
@ -49,17 +55,42 @@ const getError = (error: unknown) => (error instanceof Error ? error.message : S
const percent = (factor: number) => formatNumber(factor, { style: 'percent', maximumFractionDigits: 0 });
type Focus = { level: number; id?: string; edge?: 'first' | 'last' | 'menu' };
/** Where the menu hangs: under its button (from the window's end edge) or under the logo (from its start edge). */
type Anchor = { at: 'button' | 'logo'; top: number; left?: number; right?: number };
/**
* Where the menu hangs: under a button (its end edge lined up with the button's: from the window's
* right edge, or from the left in a right-to-left pane) or under the logo (from its start edge).
*/
type Anchor = { at: AppMenuTrigger; pane?: string; top: number; left?: number; right?: number };
/** One trigger, as a key: `pane:<id>` for a pane's button. */
const triggerKey = (at: AppMenuTrigger, pane?: string) => (at === 'pane' ? `pane:${pane ?? ''}` : at);
/** Which trigger the open menu hangs from (null: closed), for the triggers' `aria-expanded`. */
let openAt: Anchor['at'] | null = null;
function noteOpen(at: Anchor['at'] | null) {
if (openAt === at) return;
openAt = at;
let openAt: string | null = null;
function noteOpen(key: string | null) {
if (openAt === key) return;
openAt = key;
window.dispatchEvent(new CustomEvent('bt-app-menu-state'));
}
/** `aria-expanded` of one trigger. */
function useExpanded(key: string) {
const [expanded, setExpanded] = useState(openAt === key);
useEffect(() => {
const update = () => setExpanded(openAt === key);
update();
window.addEventListener('bt-app-menu-state', update);
return () => window.removeEventListener('bt-app-menu-state', update);
}, [key]);
return expanded;
}
/** Pane `id`'s menu button on screen; else the focused pane's; else the first one on screen. */
function paneButton(id?: string): HTMLElement | null {
const shown = Array.from(document.querySelectorAll<HTMLElement>('.bt-pane-menu[data-pane]')).filter(el => el.getClientRects().length > 0);
const find = (want: string | undefined) => (want ? shown.find(el => el.dataset.pane === want) : undefined);
return find(id) ?? find(shell.api?.activePanel?.id) ?? shown[0] ?? null;
}
/** The rows of one level a key can stop on: enabled items; the zoom row counts once. */
function stopsOf(menu: HTMLElement): HTMLElement[] {
const all = Array.from(menu.querySelectorAll<HTMLElement>('[data-item]:not(:disabled)'));
@ -69,7 +100,11 @@ function stopsOf(menu: HTMLElement): HTMLElement[] {
return all.filter(el => !('zoom' in el.dataset) || el === keep);
}
export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
/**
* The menu (mounted once, in the titlebar). `trigger`: where clicks and keys open it; default the
* app's `ShellMenu.trigger`, else `pane`. `true` / `false` are the older spellings of `button` / `logo`.
*/
export function AppMenu({ trigger }: { trigger?: AppMenuTrigger | boolean } = {}) {
const t = useT();
usePaneTick();
const dev = useDev();
@ -107,17 +142,32 @@ export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
};
}, []);
/** Where a request without an anchor opens: the button when this app shows one, else the logo. */
const home = (): Anchor['at'] => (trigger ? 'button' : 'logo');
/** Where a request without an anchor opens: the app's trigger. */
const home = (): AppMenuTrigger => menuTrigger(trigger);
/** The element a request hangs the menu under (null: none on screen). */
function triggerOf(at: AppMenuTrigger, pane?: string): HTMLElement | null {
if (at === 'pane') return paneButton(pane);
if (at === 'logo') return document.querySelector<HTMLElement>('button.bt-titlebar-logo');
return button.current;
}
function show(request: AppMenuRequest = {}) {
const at = request.anchor ?? home();
const el = triggerOf(at, request.pane);
const pane = at === 'pane' ? el?.dataset.pane : undefined;
diag(`menu open: anchor=${at} keyboard=${!!request.keyboard} hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`);
const logo = at === 'logo' ? document.querySelector('.bt-titlebar-logo') : null;
const rect = (logo ?? button.current)?.getBoundingClientRect();
const rect = el?.getBoundingClientRect();
if (rect) {
const top = Math.round(rect.bottom + 6);
setAnchor(logo ? { at: 'logo', top, left: Math.max(8, Math.round(rect.left - 3)) } : { at: 'button', top, right: Math.max(8, Math.round(window.innerWidth - rect.right)) });
const rtl = getComputedStyle(el!).direction === 'rtl';
if (at === 'logo') setAnchor({ at, top, left: Math.max(8, Math.round(rect.left - 3)) });
// The menu's end edge lines up with its button's, so it opens over the pane the button is in.
else if (rtl) setAnchor({ at, pane, top, left: Math.max(8, Math.round(rect.left)) });
else setAnchor({ at, pane, top, right: Math.max(8, Math.round(window.innerWidth - rect.right)) });
} else {
// No trigger on screen (only the app's own tab, a deck): under the titlebar, at its end.
setAnchor({ at, pane, top: 50, right: 8 });
}
const active = document.activeElement as HTMLElement | null;
before.current = active && active !== document.body && document.hasFocus() ? active : null;
@ -165,8 +215,10 @@ export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
useEffect(() => {
const onRequest = (event: Event) => {
const request = (event as CustomEvent<AppMenuRequest | undefined>).detail ?? {};
// Asked again from the other trigger, the open menu moves there instead of closing.
if (live.current.open && request.toggle && (request.anchor ?? home()) === (openAt ?? home())) close('escape'); else show(request);
// Asked again from another trigger, the open menu moves there instead of closing.
const at = request.anchor ?? home();
const key = triggerKey(at, at === 'pane' ? request.pane ?? paneButton()?.dataset.pane : undefined);
if (live.current.open && request.toggle && key === openAt) close('escape'); else show(request);
};
window.addEventListener('bt-app-menu', onRequest);
return () => window.removeEventListener('bt-app-menu', onRequest);
@ -176,7 +228,6 @@ export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
if (!open) return;
// Native tab webviews would cover the menu.
setOverlay(1);
noteOpen(anchor.at);
// The window lost the keyboard: the menu closes, unless the focus is back a moment later (taking the
// keyboard from a tab for Alt+F / F10 can pass through a blur on its way to the shell).
let leaving: ReturnType<typeof setTimeout> | undefined;
@ -199,14 +250,33 @@ export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
window.addEventListener('blur', away);
window.addEventListener('resize', resized);
window.addEventListener('keydown', onKey);
return () => { clearTimeout(leaving); setOverlay(-1); noteOpen(null); window.removeEventListener('blur', away); window.removeEventListener('resize', resized); window.removeEventListener('keydown', onKey); };
return () => { clearTimeout(leaving); setOverlay(-1); window.removeEventListener('blur', away); window.removeEventListener('resize', resized); window.removeEventListener('keydown', onKey); };
}, [open, anchor.at]);
const layer = (level: number) => layers.current?.querySelector<HTMLElement>(`[data-level="${level}"]`) ?? null;
// The trigger the menu hangs from shows it is open.
useEffect(() => {
noteOpen(open ? triggerKey(anchor.at, anchor.pane) : null);
return () => noteOpen(null);
}, [open, anchor.at, anchor.pane]);
const layer =(level: number) => layers.current?.querySelector<HTMLElement>(`[data-level="${level}"]`) ?? null;
// After every render: submenus sit beside their row, inside the window; then the focus that was asked for.
useLayoutEffect(() => {
if (!open) return;
// The menu stays inside the window: a button near the start edge (a narrow pane in split view)
// would push it out, so it slides back in.
const root = layer(0);
if (root) {
const edge = 8;
root.style.left = anchor.left === undefined ? '' : `${anchor.left}px`;
root.style.right = anchor.right === undefined ? '' : `${anchor.right}px`;
const box = root.getBoundingClientRect();
if (box.left < edge || box.right > window.innerWidth - edge) {
root.style.left = `${Math.round(Math.max(edge, Math.min(box.left, window.innerWidth - edge - box.width)))}px`;
root.style.right = 'auto';
}
}
for (let level = 1; level <= path.length; level += 1) {
const el = layer(level);
const parent = layer(level - 1);
@ -564,7 +634,7 @@ export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
const label = menuText('label');
return <>
{trigger && <button ref={button} type="button" className="bt-app-button" aria-haspopup="menu" aria-expanded={open && anchor.at === 'button'} aria-label={label} title={`${label} (${APP_MENU_KEYS})`}
{home() === 'button' && <button ref={button} type="button" className="bt-app-button" aria-haspopup="menu" aria-expanded={open && anchor.at === 'button'} aria-label={label} title={`${label} (${APP_MENU_KEYS})`}
onClick={event => (open && anchor.at === 'button' ? close('escape') : show({ keyboard: event.detail === 0 }))}>
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="5.75" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="12" cy="18.25" r="1.6"/></svg>
</button>}
@ -584,13 +654,8 @@ export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
*/
export function AppMenuLogo() {
useT();
const [expanded, setExpanded] = useState(openAt === 'logo');
const expanded = useExpanded('logo');
const press = useRef<{ x: number; y: number; dragged: boolean } | null>(null);
useEffect(() => {
const update = () => setExpanded(openAt === 'logo');
window.addEventListener('bt-app-menu-state', update);
return () => window.removeEventListener('bt-app-menu-state', update);
}, []);
const { product, logo } = site();
const label = menuText('label');
return <button type="button" className="bt-titlebar-logo" aria-haspopup="menu" aria-expanded={expanded} aria-label={`${product}: ${label}`} title={`${product} · ${label}`}
@ -614,3 +679,22 @@ export function AppMenuLogo() {
<img src={logo} alt="" draggable={false}/>
</button>;
}
/** The app's menu trigger: `trigger` as `AppMenu` takes it, else `ShellMenu.trigger`, else `pane`. */
export const menuTrigger = (trigger?: AppMenuTrigger | boolean): AppMenuTrigger => resolveTrigger(trigger, site().menu?.trigger);
/**
* One pane's menu button, at the end of its toolbar (the app's mark inside): opens the app menu
* under itself, or closes it when it is open there. Shown when the app's trigger is `pane`.
*/
export function PaneMenuButton({ pane, children }: { pane: string; children: ReactNode }) {
useT();
const expanded = useExpanded(triggerKey('pane', pane));
const label = menuText('label');
const { product } = site();
return <button type="button" className="bt-brand-button bt-pane-menu" data-pane={pane} aria-haspopup="menu" aria-expanded={expanded}
aria-label={`${product}: ${label}`} title={`${product} · ${label} (${APP_MENU_KEYS})`}
onClick={event => openAppMenu({ anchor: 'pane', pane, toggle: true, keyboard: event.detail === 0 })}>
{children}
</button>;
}

View file

@ -2,7 +2,7 @@ import { useEffect, type CSSProperties, type MouseEvent as ReactMouseEvent } fro
import { RESIZE_BORDER } from '../chrome.ts';
import { chipFor } from '../updateModel.ts';
import { AccountSwitcher } from './AccountSwitcher.tsx';
import { AppMenu, AppMenuLogo } from './AppMenu.tsx';
import { AppMenu, AppMenuLogo, menuTrigger } from './AppMenu.tsx';
import { invoke } from './bridge.ts';
import { useT, useUpdateStatus } from './hooks.ts';
import { tx } from './i18n.ts';
@ -24,18 +24,20 @@ export function titlebarContextMenu(event: ReactMouseEvent | MouseEvent) {
/**
* The 44px titlebar row. It sits under the dockview root: the top groups' tab headers are
* transparent and let clicks through to the drag layer, the logo and the caption buttons. The logo
* is the app menu's second trigger (AppMenu.tsx); everything else that is empty drags the window.
* is part of the drag region, unless the app chose it as the menu's trigger (`ShellMenu.trigger`);
* everything else that is empty drags the window.
*/
export function Titlebar({ maximized }: { maximized: boolean }) {
const trigger = menuTrigger();
return <header className="bt-titlebar" onContextMenu={titlebarContextMenu}>
<div className="bt-titlebar-drag" data-tauri-drag-region/>
<AppMenuLogo/>
{trigger === 'logo' ? <AppMenuLogo/> : <img className="bt-titlebar-logo" src={site().logo} alt="" draggable={false} data-tauri-drag-region/>}
<div className="bt-titlebar-spacer" data-tauri-drag-region/>
<TitlebarExtras/>
<AccountSwitcher/>
<UpdateChip/>
{/* One home for the app menu: the logo. Alt+F, F10, the palette and the account menu's last row open it there. */}
<AppMenu trigger={false}/>
{/* The app menu, mounted once; it hangs under its trigger (by default each pane's wB button). */}
<AppMenu trigger={trigger}/>
{os !== 'macos' && <WindowControls maximized={maximized}/>}
</header>;
}

View file

@ -2,6 +2,7 @@ import type { IDockviewPanelProps } from 'dockview';
import { Fragment, useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
import { menuTrigger, PaneMenuButton } from './AppMenu.tsx';
import { WB_MARK } from './brand.ts';
import { invoke } from './bridge.ts';
import { FindBar } from './FindBar.tsx';
@ -195,9 +196,12 @@ export function WebPanel(props: IDockviewPanelProps<WebParams>) {
</>}
</div>}
</div>
<button className="bt-brand-button" title={`${product} (Ctrl+Shift+W)`} aria-label={product} onClick={() => shell.openPanel(api.id)}>
{/* The app menu's trigger (its Settings row and the other panel rows open the panel); an app whose menu hangs elsewhere keeps it as the panel's button. */}
{menuTrigger() === 'pane'
? <PaneMenuButton pane={api.id}><img className="bt-wb" src={WB_MARK} alt="" width={30} height={17} draggable={false}/></PaneMenuButton>
: <button className="bt-brand-button" title={`${product} (Ctrl+Shift+W)`} aria-label={product} onClick={() => shell.openPanel(api.id)}>
<img className="bt-wb" src={WB_MARK} alt="" width={30} height={17} draggable={false}/>
</button>
</button>}
</div>
<div className="bt-viewport" ref={viewport}>
{/* Until the page's own webview is on screen: its last frame, else the site's shape (rail, timeline), not a blank pane. */}

View file

@ -16,17 +16,23 @@
/* An app that shows no menu button (`<AppMenu trigger={false}/>`, the logo is the menu's home) reserves no room for it. */
html:not(:has(.bt-app-button)) { --bt-tb-menu: 0px; }
/* The logo at the start of the titlebar: the menu's second trigger (a 30px target around the 20px
mark; with its margins it takes the 50px the tab strip leaves in --bt-tb-left). */
.bt-titlebar-logo {
/* The logo at the start of the titlebar. Plain, it is part of the drag region (clicks fall through
to it); as the app's chosen trigger it is a 30px target around the 20px mark. Either way it takes
the 50px the tab strip leaves in --bt-tb-left. */
img.bt-titlebar-logo { width: 20px; height: 20px; margin: 12px 14px 12px 16px; flex: 0 0 20px; -webkit-user-drag: none; } /* rtl-ok: titlebar */
button.bt-titlebar-logo {
align-self: center; display: inline-grid; place-items: center; width: 30px; height: 30px; flex: 0 0 30px; margin: 0 9px 0 11px; padding: 0; box-sizing: border-box; /* rtl-ok: titlebar */
border: 1px solid transparent; border-radius: 9px; background: transparent; cursor: pointer; -webkit-user-drag: none;
transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease);
}
.bt-titlebar-logo img { display: block; width: 20px; height: 20px; pointer-events: none; -webkit-user-drag: none; }
.bt-titlebar-logo:hover { background: var(--bt-hover); border-color: var(--bt-line-soft); }
.bt-titlebar-logo[aria-expanded=true] { background: var(--bt-hover); border-color: rgb(var(--bt-accent-rgb) / .5); }
.bt-titlebar-logo:focus-visible { outline: 0; box-shadow: var(--bt-ring); }
button.bt-titlebar-logo img { display: block; width: 20px; height: 20px; pointer-events: none; -webkit-user-drag: none; }
button.bt-titlebar-logo:hover { background: var(--bt-hover); border-color: var(--bt-line-soft); }
button.bt-titlebar-logo[aria-expanded=true] { background: var(--bt-hover); border-color: rgb(var(--bt-accent-rgb) / .5); }
button.bt-titlebar-logo:focus-visible { outline: 0; box-shadow: var(--bt-ring); }
/* Each pane's wB button is the menu's trigger: it stays lit while the menu hangs from it. */
.bt-pane-menu[aria-expanded=true] { background: var(--bt-hover); border-color: rgb(var(--bt-accent-rgb) / .55); }
.bt-pane-menu:focus-visible { outline: 0; box-shadow: var(--bt-ring); }
/* The menu and its submenus. `display: contents`: the layers are positioned on their own. */
.bt-app-layers { display: contents; }

View file

@ -55,8 +55,8 @@ export type { PaletteItem, PaletteAction, PaletteContext } from './paletteModel.
export { Icon, Avatar, ICONS, type IconName } from './icons.tsx';
export {
DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, menuWith, menuWithout,
type BuiltinMenuItem, type MenuEntry, type MenuGroups, type MenuItemSpec, type MenuLanguages, type MenuModes, type ReportDetails, type ShellMenu,
type AppMenuTrigger, type BuiltinMenuItem, type MenuEntry, type MenuGroups, type MenuItemSpec, type MenuLanguages, type MenuModes, type ReportDetails, type ShellMenu,
} from './menuModel.ts';
export { openAppMenu, type AppMenuRequest } from './AppMenu.tsx';
export { menuTrigger, openAppMenu, PaneMenuButton, type AppMenuRequest } from './AppMenu.tsx';
export { createLanguage, resolveLocale, type Language, type LanguageOptions, type LanguagePreference } from './language.ts';
export { createAppI18n, type AppI18n, type AppI18nOptions, type AppLanguage } from './appI18n.ts';

View file

@ -105,8 +105,24 @@ export type MenuModeStatus = { custom: boolean; on: string[]; off: string[]; add
/** Lines an app adds to the "Report a problem" summary (reportModel.ts): ids only, never anything about the person. */
export type ReportDetails = ReadonlyArray<{ label: string; values: readonly string[] }>;
/** Where the app menu's trigger is (`ShellMenu.trigger`). */
export type AppMenuTrigger = 'pane' | 'button' | 'logo';
/** The trigger in use: `AppMenu`'s own `trigger` (`true` / `false` are the older `button` / `logo`), else the app's, else `pane`. */
export function resolveTrigger(trigger: AppMenuTrigger | boolean | undefined, configured: AppMenuTrigger | undefined): AppMenuTrigger {
if (trigger === true) return 'button';
if (trigger === false) return 'logo';
return trigger ?? configured ?? 'pane';
}
/** `ShellSite.menu`: the app menu's rows and what the built-in ones need from the app. */
export type ShellMenu = {
/**
* What opens the menu with a click: `pane` (default), each pane's wayBetter button at the end of
* its toolbar (the menu hangs under the button that was clicked); `button`, a "⋮" button at the
* end of the titlebar; `logo`, the titlebar's logo. Keys and other requests open it at the same place.
*/
trigger?: AppMenuTrigger;
/** The rows, in order. A string is a built-in row, an object one of the app's. Default: `DEFAULT_MENU`. */
groups?: MenuGroups;
/** The Language submenu; omit for an app in one language. */

View file

@ -91,7 +91,7 @@ html, body, #root { height: 100%; margin: 0; overflow: hidden; background: var(-
pointer events only on its own controls; everything else falls through to the tabs and their
drag region. With no tabs the titlebar itself is the drag region again. */
.bt-titlebar { z-index: 2; pointer-events: none; }
.bt-titlebar > :not(.bt-titlebar-drag):not(.bt-titlebar-spacer) { pointer-events: auto; }
.bt-titlebar > :not(.bt-titlebar-drag):not(.bt-titlebar-spacer):not(img.bt-titlebar-logo) { pointer-events: auto; }
.bt-shell--empty .bt-titlebar > * { pointer-events: auto; }
/* Above the dock, so it must not paint: the tab strips hosted in the titlebar row show through it. */
.bt-shell:not(.bt-shell--empty) .bt-titlebar { background: transparent; }

View file

@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url';
import { setShellI18n, type ShellI18n } from '../src/frame/i18n.ts';
import {
DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, ZOOM_MAX, ZOOM_MIN, ZOOM_STEPS, builtinAvailable, findLabel, findSpec, joinGroups, languageChoice, languageRows, menuText, menuWith,
menuWithout, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow, zoomPercent, zoomStep,
menuWithout, moveStop, planMenu, resolveTrigger, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow, zoomPercent, zoomStep,
type MenuEnv, type MenuGroups, type MenuItemRow, type MenuItemSpec, type MenuLanguage, type MenuRow,
} from '../src/frame/menuModel.ts';
import { buildItems } from '../src/frame/paletteModel.ts';
@ -271,3 +271,13 @@ test('the palette opens the menu', () => {
const without = buildItems({ tabs: [], profiles: [], activeProfile: 'default' }, '', { site: { placeholder: () => '', sections: [] }, product: 'App', decks: false, media: false, find: false });
assert.equal(without.some(item => item.id === 'find'), false);
});
test("the menu hangs from each pane's button unless the app chose the titlebar", () => {
assert.equal(resolveTrigger(undefined, undefined), 'pane');
assert.equal(resolveTrigger(undefined, 'logo'), 'logo');
assert.equal(resolveTrigger(undefined, 'button'), 'button');
// A trigger given to the component wins over the app's; `true` / `false` are the older spellings.
assert.equal(resolveTrigger('pane', 'logo'), 'pane');
assert.equal(resolveTrigger(true, 'pane'), 'button');
assert.equal(resolveTrigger(false, 'pane'), 'logo');
});