merge #1117: fix(floating) clear the desktop shell's native title-bar band

This commit is contained in:
Menghuan1918 committed 2026-11-08 00:10:32 +08:00
commit b8988aa389
13 files changed
+661 -24

No files matched your search

+3
View File
@@ -10,6 +10,9 @@
- 🎯 **设置页「侧边卡片」的导航图标不再叠成两个**:插件此前按"宿主设置导航还没有图标通道"的老假设,用 CSS 把兜底齿轮藏起来、再画自己的图标;宿主早已提供按 section id 寻址的 `settings.section.icon` 插槽,而且图标的 DOM 外面多了一层 span,老选择器失效后兜底 SVG 露了出来,与插件图标并排显示。现在改为**走宿主插槽**提供图标,删掉标记 + CSS 遮罩那一套(顺带去掉了一个监听整个 document 的 MutationObserver)。
- 🧪 测试:`tests/settings-nav-icon.spec.tsx` 钉住图标按宿主给的 `size` 缩放、只用 `currentColor`;真实宿主上用无头浏览器确认导航行只剩一个 `svg`、无残留标记。
- 🪟 **浮层不再把自己的标题栏摆进桌面壳的原生窗口控件带**([#805](https://github.com/omdsh-dev/DSH-better-sidebar/issues/805) 同根因):Windows 桌面壳用 `titleBarOverlay` 在视口顶部画原生「最小化/最大化/关闭」,那条带子里的指针事件到不了网页。任务详情浮窗(`FloatingWindow`)的最小顶部距离写死 8px、自身标题栏 34px,× 正好落在带子里点不动;节点详情弹层(`AnchoredPopover`)与 mermaid 放大图工具栏同理。新增 `src/client/viewport-inset.ts` 读标准 `navigator.windowControlsOverlay`(`visible` + `getTitlebarAreaRect()`,订阅 `geometrychange`,`resize` 兜底)求出带高,三处消费者把可交互区压在带子下方;拖拽/重排的纵向下限同步,带子出现时把已摆好的浮层抬起、消失时不主动下拉(用户摆的位置不被最大化/还原弹走)。**只读探测、零配置**:不写 CSS 变量、不写 DOM 属性、不加偏好键、不复活 #430 删掉的 `--dsh-title-bar-strip`;API 缺失 / `visible:false` / 读取抛错一律退化为 0,普通浏览器与网页版的位置与今天逐字一致。
- 🧪 测试:新增 `tests/viewport-inset.spec.ts`(11 例:API 缺失 / 读到带高 / 高度 0 / `visible:false` / 抛错 / 小数取整 / `y+height` 取值 / 只在值真变时通知 / `resize` 兜底 / `visible` 运行时翻转 / 换源清理监听);`tests/floating-window.spec.tsx` 新增 6 例(锚点在带内抬起 / 拖拽不越界 / 带子出现抬起 / 带子消失不下拉 / 高度上限让出带子 / 幽灵接口保持原 8px);新增 `tests/anchored-popover.spec.tsx`(3 例:带内抬起 / 无带子保持原位 / 视口最顶保持历史位置);挂载 lane 注入假 WCO 断言放大图工具栏 16→52→16 的真实布局。
### v0.30.0
- 🧭 **适配 DSH 0.2.2-rc.1(本版 peer 下限抬到 `^0.2.2-rc.1`)**:宿主把模型选择从可安装的 `ModelSelectionRef` 换成 agent 自有的 `AgentModel`——`agent.model.select()` 同时落盘并作用于下一步,侧边对话的线程模型选择随之改写(不再自己 install 一份 ref);`dsh-tools` 移除了 PTC(`tool/ptc-dispatch*`)的事件**类型声明**(运行期仍记录),宿主图标由内联 `<path>` 改为 sprite `<use href="#dsw-icon-…">`。**支持线随之移动**:0.x 的 caret 不跨 minor,因此 DSH 0.2.1 线(`0.2.1-rc.1 ~ rc.5`,即当前的宿主 npm `latest`)请继续固定插件 **v0.28.2**(`v0.29.0` 从未发布到 npm),0.2.2-rc.1+ 请用 **v0.30.0**。
+3
View File
@@ -12,6 +12,9 @@
- 🎯 **The "Side card" settings row no longer shows two icons**: the plugin still assumed the settings navigation had no icon channel, so it hid the fallback gear with CSS and painted its own glyph. The shell has long since exposed a `settings.section.icon` slot addressed by section id, and it now wraps the nav icon in a span — the stale `> svg:first-child` rule stopped hiding the fallback, so both glyphs rendered side by side. The row now contributes its icon **through the slot**, and the marker + CSS-mask apparatus is gone (along with a document-wide MutationObserver).
- 🧪 `tests/settings-nav-icon.spec.tsx` pins the glyph to the slot-provided `size` and `currentColor`; a headless pass against a real host confirms one `svg` in the row and no leftover marker.
- 🪟 **Floating layers no longer place their own title bar under the desktop shell's native window-control band** (same root cause as [#805](https://github.com/omdsh-dev/DSH-better-sidebar/issues/805)): on Windows the shell paints its native minimize/maximize/close buttons over the top band of the viewport with `titleBarOverlay`, and pointer events in that band never reach the page. The task-detail window (`FloatingWindow`) had a hard-coded 8px top floor with a 34px title bar, so its × landed inside the band and could not be clicked; the node-detail popover (`AnchoredPopover`) and the mermaid zoom toolbar had the same problem. New `src/client/viewport-inset.ts` reads the standard `navigator.windowControlsOverlay` (`visible` + `getTitlebarAreaRect()`, `geometrychange` with a `resize` fallback) and all three consumers keep their interactive area below the band; vertical drag/re-layout floors follow it, an appearing band lifts an already-placed layer, and a disappearing band never pulls it back up (maximize/restore does not move what the reader placed). **Read-only probe, zero configuration**: no CSS variable, no DOM attribute, no preference key, no revival of the `--dsh-title-bar-strip` mechanism removed in #430; a missing API, `visible:false`, or a throwing read degrade to 0, so plain browsers and the web build behave exactly as before.
- 🧪 Tests: new `tests/viewport-inset.spec.ts` (11 cases); 6 new cases in `tests/floating-window.spec.tsx`; new `tests/anchored-popover.spec.tsx` (3 cases); the mount lane injects a fake WCO and asserts the zoom toolbar's real layout moves 16→52→16.
### v0.30.0
- 🧭 **Adapted to DSH 0.2.2-rc.1 (peer floors move to `^0.2.2-rc.1`)**: the host replaced the installable `ModelSelectionRef` with an agent-owned `AgentModel` — `agent.model.select()` records the choice durably and applies it to the next step, so the side-chat thread model selection rides the agent's own handle instead of an installed ref. `dsh-tools` dropped the PTC (`tool/ptc-dispatch*`) event **type declarations** (the runtime still records them), and host icons switched from inline `<path>` to sprite `<use href="#dsw-icon-…">`. **The support line moves with it**: a 0.x caret never spans a minor, so DSH 0.2.1 hosts (`0.2.1-rc.1 ~ rc.5`, today's npm `latest`) keep pinning plugin **v0.28.2** (`v0.29.0` was never published), while 0.2.2-rc.1+ takes **v0.30.0**.
+2 -1
View File
@@ -1247,7 +1247,8 @@ interface SettingsDescriptor {
- **布局变量**(`<html>` 上,面板打开时有效):`--dsh-sidebar-width` / `--dsh-sidebar-height`。右面板宽度 = AppFrame 的 `padding-right` 预留(新版 `#root [data-dsh-frame]` / rc.8 `#root > [data-slot="root"] > div` 双锚点),AppFrame border box 保持完整桌面视口宽度(Harness 以此判定桌面/窄屏布局,避免插件面板展开误入窄屏);AppFrame 的 details 拖拽手柄按同一变量向左平移贴合列边缘。底部面板仍走 centerCol `margin-bottom`;centerCol 锚点 = **JS 标注**(禁止 `nth-child`):侧栏 shell 的定位器给测得的 centerCol 节点打 `[data-dsh-center-col]` 标签(`Sidebar.tsx` locate,节点更换/HMR 时随 ref 迁移),`layout.css` 用 `#root [data-dsh-center-col]` 选中(`drag-layout.e2e.ts` 断言恰一节点且为对话槽宿主的父级——alpha.2 起 shell 把 `#root [data-slot="main.conversation"]` 解析进列并跳过 `display: contents` 祖先(`center-column.ts` 的 `CENTER_COLUMN_SELECTOR` 同时认 `main.conversation` 与 alpha.1 的 `conversation`),定位器从槽宿主向上取第一个非 `contents` 的祖先;frame 宽度与桌面 Session Log 由 `desktop-layout.e2e.ts` 断言)。
- **用户空间 CSS(v0.14.1+;titleBar 让位机制移除后只剩它)**:`SidebarPrefs.customCss`(设置页「自定义 CSS」分组)注入 `<style data-dsh-custom-css="custom">` 到 head 末尾(后写胜出;覆盖 JS 内联需 `!important`),fiber 卸载即移除,**非空即生效**(不再有方案门控)。稳定寻址面:`[data-dsh-toggle-cluster]` / `[data-dsh-panel]` / `[data-dsh-bottom-panel]`。
- **已移除:位置兼容模式 / titleBar 让位机制**(v0.14.1 引入,本次整体删除,见 [docs/plans/2026-10-05-remove-titlebar-compat-strip.md](plans/2026-10-05-remove-titlebar-compat-strip.md))。历史模型是四方案 `titleBarScheme`(`auto` / `web` / 壳预设 / `custom`),由 `src/client/titlebar-strip.ts` 的纯函数按「壳自带 `ctx.desktopWindow` 契约 → `navigator.windowControlsOverlay` 真实几何 → URL `dsh-desktop-titlebar-inset` → 壳预设 → 手动 px」求出顶栏让位高度,写 `body[data-dsh-title-bar-compat]` + `--dsh-title-bar-strip`。删除原因:插件自 v0.19.0 起不再自绘顶部 chrome,**CSS 里没有任何规则读这两个值**,宿主也不读这条契约(用户想移动的侧边栏按钮是宿主原生控件,插件没有它的位置 API),于是改设置只写变量、什么都不动;而设置项描述与现实不符。
- **对消费插件的影响**:不要引用 `SidebarPrefs.titleBarScheme` / `titleBarPresetId` / `titleBarCompat` / `titleBarStripPx`(`toggles` 里声明它们会被当成未知键),也不要写 `--dsh-title-bar-strip` / `body[data-dsh-title-bar-compat]`(无人消费)。桌面壳仍会戳 URL(`dsh-desktop-mode` / `-platform` / `-titlebar-inset`)并提供 `ctx.desktopWindow`/`navigator.windowControlsOverlay`,但**本插件一律不再读**——需要顶部几何的插件请自己探测,注意 `ctx.desktopWindow` 是可选客户端服务,**绝不能写进 `dsh.client.inject`**(普通浏览器没有它,注入会让插件永远 pending)。
- **对消费插件的影响**:不要引用 `SidebarPrefs.titleBarScheme` / `titleBarPresetId` / `titleBarCompat` / `titleBarStripPx`(`toggles` 里声明它们会被当成未知键),也不要写 `--dsh-title-bar-strip` / `body[data-dsh-title-bar-compat]`(无人消费)。桌面壳仍会戳 URL(`dsh-desktop-mode` / `-platform` / `-titlebar-inset`)并暴露 `ctx.desktopWindow` / `navigator.windowControlsOverlay`;**URL 戳记与 `ctx.desktopWindow` 本插件仍不读**(注意后者是可选客户端服务,**绝不能写进 `dsh.client.inject`**——普通浏览器没有它,注入会让插件永远 pending)。
- **例外:标准 WCO 几何(尚未发布,见 [docs/plans/2026-11-04-floating-window-native-titlebar-band.md](plans/2026-11-04-floating-window-native-titlebar-band.md))**:`src/client/viewport-inset.ts` 读 `navigator.windowControlsOverlay`(`visible` + `getTitlebarAreaRect()`,并订阅 `geometrychange`)求出壳的原生窗口控件带高度,供 `FloatingWindow` / `AnchoredPopover` / mermaid 放大图工具栏把自己的可交互标题区压在带子下方——带子里的指针事件到不了网页,标题栏落进去就读作「点不动」(issue #805,任务详情浮窗的 × 是同一根因)。这是**只读探测、零配置**:不写 CSS 变量、不写 DOM 属性、不进 `PrefsSchema`、不做预设检测;API 缺失 / `visible:false` / 读取抛错一律退化成 0,于是普通浏览器行为与加这条之前逐字一致。
- 旧偏好数据安全:已删的四个键在宿主 schema 里是未知键(OPEN),解析不报错、不写回;客户端 `parsePrefs` 只按声明字段构造,它们不会进入 UI(`tests/prefs.spec.ts` / `tests/plugin-shape.spec.ts` 守护)。
- **拖拽区退出**:交互 chrome(`.toggleCluster` / `.toggleButton` / `.tabBar`)统一 `-webkit-app-region: no-drag`(无边框壳拖拽带吞点击,#103/#111)。
- **拖拽区退出(视口层)**:宿主把每个**直挂 body 的子元素**都设成 `no-drag`(`html[data-platform=darwin] body > :not(#root)`,选择器含 id,只能靠 `!important` 压过),而 app-region **无视 `pointer-events`**——插件宿主就是这样一个 body 子元素,在 Electron 里该值还会传到它内部的**铺满视口的面板层**(#772 的 CDP 实测;挂载 lane 用的浏览器引擎不传播该属性,所以面板层自己也声明了同一条规则),于是它把下面每条 `[data-window-drag]` 拖拽带一起抵消(窗口拖一次就失效,同时丢掉 macOS 双击标题栏缩放,issue #772)。契约:装饰性的视口层用**中性值** `-webkit-app-region: initial !important` 退出计算(`initial` 的计算值 `none` 不扣减拖拽区;注意**字面量 `none` 不是中性值**——它计算成 `no-drag`,是扣减值),层内的面板/控件再声明 `no-drag` 保住点击;当前覆盖 `[data-dsh-better-sidebar]`、`[data-dsh-panel-host]`(`> *` 保持 `no-drag`)与 `.mermaidModal`(放大视图是第二个**持久**铺满视口的 body 直挂层)。**交互弹层不要加 `initial`**(`.selectionPopup` 是 `<button>`,`FloatingWindow` / `AnchoredPopover` 自带指针拖拽、不是遮罩层):宿主 `:is(button, a, input, …)` 已给它们 `no-drag`,反过来声明 `initial !important` 会让按下变成拖窗(重演 #103/#111)。放大视图是**遮罩层例外**——它是模态,只有其中的控件必须保持 `no-drag`;代价是它覆盖在顶部拖拽带上时,点背景会变成拖窗而不是关闭(为「放大图时窗口仍可拖」付的账)。**未纳入**:`FileTree` 的 `.uploadDropChatHint` 同样是 body 直挂的装饰层,但它只在 OS 文件拖拽悬停期间存在且 `pointer-events: none`,收益极小、暂不处理(`FloatingWindow` / `AnchoredPopover` 是交互层,按上面的判据本就该保持 `no-drag`)。形状由 `tests/panel-host-css.spec.ts` 在 Linux 的 `pnpm test` 里守护(无 macOS runner;`tests/theme.spec.ts` 只守颜色,故本轮不涉及),真实级联由挂载 lane 的探针按宿主规则断言计算值(面板宿主探针复现宿主两条 darwin 规则,放大视图探针直接用页面里宿主自己的规则)。
@@ -0,0 +1,69 @@
# 浮层让出桌面壳的原生窗口控件带
日期:2026-11-04 分支:`fix/floating-window-titlebar-band`
关联 issue:[#805](https://github.com/omdsh-dev/DSH-better-sidebar/issues/805)(mermaid 放大图工具栏,同一根因)、PR [#812](https://github.com/omdsh-dev/DSH-better-sidebar/pull/812)(读已删除变量,无效)、[#430](https://github.com/omdsh-dev/DSH-better-sidebar/issues/430) / [2026-10-05 移除 titleBar 让位机制](2026-10-05-remove-titlebar-compat-strip.md)(被删的旧机制,本方案与之无关)
## 症状与根因
用户在 DSH 桌面壳(Windows)里点任务卡片,弹出的「任务详情」浮窗右上角 × 点不动。
- 壳用 Electron `titleBarOverlay` 在视口顶部画原生「最小化/最大化/关闭」。**带子里的指针事件到不了网页**(`elementFromPoint` 仍返回网页元素,所以从页面侧看一切正常,这是排查最费时的一点)。
- `FloatingWindow` 的顶部下限写死 `VIEWPORT_MARGIN = 8`,自绘标题栏高 34px → × 的纵向范围约 8~42,正落在带子里。
- 同一根因的另外两处:任务页节点详情弹层(`AnchoredPopover`,锚点行靠近窗口顶部时弹层标题区落进带子)、mermaid 放大图工具栏(#805,`top: 16px`)。
## 方案
新增 `src/client/viewport-inset.ts` 作为**唯一**几何来源:
- 读标准 `navigator.windowControlsOverlay`:`visible !== true` → 0;否则 `Math.round(rect.y + rect.height)`。取 `y + height` 而不是 `height`:macOS 的控件在左上、窗口按钮占左侧一段,区域矩形可以带 `y` 偏移。
- 模块求值时探测一次并挂 `geometrychange`(首帧就拿到真值,不会先画在 8px 再跳),`window.resize` 兜底重读;值变了才广播。
- 导出 `useViewportInsetTop()`(`useSyncExternalStore`)与 `setViewportInsetSourceForTests()`。不写 CSS 变量、不碰 DOM。
三个消费者只做一件事——把可交互区的**纵向下限**从 `VIEWPORT_MARGIN` 抬到 `VIEWPORT_MARGIN + insetTop`:
| 消费者 | 改动 |
| --- | --- |
| `FloatingWindow.tsx` | `initialBox` 有/无锚点两条路径都用 `topFloor`;高度上限扣掉 `topFloor`;拖拽与 resize 的纵向夹取同步;几何变化时把已摆好的窗抬出带子,**不主动下拉** |
| `AnchoredPopover.tsx` | 布局 effect 补 `top = Math.max(topFloor, top)`(锚点自身在带子里时也要退让);拖拽纵向下限同步 |
| `mermaid.tsx` | 工具栏 `style={{ top: 16 + insetTop }}` + `data-mermaid-toolbar`(稳定寻址,供挂载 lane 量真实布局) |
`insetTop === 0` 时三者与改动前逐字等价。
## 与 #430 删除的机制不是一回事
维护者刚在 2026-10-05 整套删过同类东西,必须正面说清区别:
| | #430 删掉的机制 | 本方案 |
| --- | --- | --- |
| 来源 | 五级取值链(声明式服务 → WCO → URL 戳记 → 壳预设 → 手动 px) | 单一标准 API(`navigator.windowControlsOverlay`) |
| 配置 | 4 个偏好键 + 设置界面 + 壳预设表 | 零配置、零设置项 |
| 输出 | 写 `body[data-dsh-title-bar-compat]` + `--dsh-title-bar-strip` | 不写任何全局值,只经 hook 返回一个数 |
| 消费者 | **零**(CSS 无人读、宿主不读) | 三个真实浮层(本次修复的直接对象) |
| 删掉后的症状 | 无——顶部行为不变,删掉的只是一条没人读的写路径 | 浮层标题栏压在原生按钮下,点不动 |
共同点只有「都读 WCO 求顶部高度」;旧机制失败的原因是**没有消费者**,不是读取方式错——它还在位时的表现正是「改设置什么都不动」。
## 降级表
| 情况 | `insetTop` | 效果 |
| --- | --- | --- |
| 普通浏览器 / 网页版(无 API) | 0 | 与今天完全一致 |
| 有 API 但 `visible: false`(headless Chromium、部分 macOS 构建) | 0 | 同上 |
| 区域高度 0 / 非有限数 / 抛错 | 0 | 同上 |
| 有 API、`visible: true`、高度 h | h | 浮层让出 h |
已知残留:壳若不暴露 WCO,本方案退化为 0,症状仍在——这种情况需要壳侧修,插件没有别的可靠来源(URL 戳记已证实与真实几何脱节,见 #864)。
## 测试证据
- `tests/viewport-inset.spec.ts`(11 例):API 缺失 / 读到带高 36 / 高度 0 / `visible:false` / 读取抛错不炸 / 小数四舍五入(35.6→36)/ `y:4,height:32`→36 / 只在值真变时通知(同值重发不唤醒订阅者)/ `resize` 兜底重读 / `visible` 运行时翻转 / 换源清理旧监听。
- `tests/floating-window.spec.tsx` 新增 6 例:锚点在带内时抬到 52(8+44)/ 拖到最上仍停 52 / 带子出现把已摆好的窗抬起 / 带子消失不下拉 / 高度上限让出带子(400 高视口 + 44 带子 → 340)/ 幽灵接口保持原 8px。
- `tests/anchored-popover.spec.tsx`(3 例):锚点在带内时弹层落到 52 / 无带子时仍是锚点下方 26px / 视口最顶的锚点保持历史位置 6px(不因本次改动被抬到 8)。
- `tests/e2e/mount.e2e.ts`:`addInitScript` 注入假 WCO(初始 0,保证其余断言不受影响),在放大图流程里量真实布局——工具栏 `top` 16 → 设带高 36 → 52 → 归零 → 16。
## 风险
- **壳不暴露 WCO**:见降级表,退化为 0,需壳侧修复。
- **核心 bundle 与 mermaid chunk 各打包一份模块**:各自读同一 API、各自挂一个监听,无共享状态;两个监听都只在值变化时广播,代价可忽略。
- **不动的部分**:没有任何 `-webkit-app-region` 声明被修改——问题在原生命中带,不是拖拽区;给交互浮层加 `initial` 会重演 #103/#111。
+12 -5
View File
@@ -21,6 +21,7 @@ import {
} from 'react'
import { createPortal } from 'react-dom'
import { createFrameBatcher } from './frame-batcher.ts'
import { useViewportInsetTop } from './viewport-inset.ts'
/** The popover's default visual width (viewport-clamped). */
const POP_WIDTH = 264
@@ -62,6 +63,8 @@ export function AnchoredPopover(props: AnchoredPopoverProps): ReactNode {
const baseRef = useRef({ left: 0, top: 0 })
const cardWidth = Math.min(width, window.innerWidth - VIEWPORT_MARGIN * 2)
/** The shell's native window-control band: pointer events die in it. */
const topFloor = VIEWPORT_MARGIN + useViewportInsetTop()
// Measure + position once the card is in the DOM (and whenever the anchor
// or content changes size). layout effect: no visible jump.
@@ -73,15 +76,19 @@ export function AnchoredPopover(props: AnchoredPopoverProps): ReactNode {
const height = card.offsetHeight
let top = rect.bottom + 6
if (top + height > window.innerHeight - VIEWPORT_MARGIN) {
top = Math.max(VIEWPORT_MARGIN, rect.top - height - 6)
top = Math.max(topFloor, rect.top - height - 6)
}
// The anchor itself may sit in the band (a row near the top edge): opening
// just below it still leaves our own header under the native controls.
// With no band, keep the historical placement byte-for-byte.
if (topFloor > VIEWPORT_MARGIN) top = Math.max(topFloor, top)
const left = Math.min(
Math.max(VIEWPORT_MARGIN, rect.left),
Math.max(VIEWPORT_MARGIN, window.innerWidth - cardWidth - VIEWPORT_MARGIN),
)
baseRef.current = { left, top }
setPos({ left: left + offsetRef.current.x, top: top + offsetRef.current.y })
}, [anchor, children, cardWidth])
}, [anchor, children, cardWidth, topFloor])
// A new anchor starts a fresh placement (never inherit another node's drag).
useEffect(() => { setOffset({ x: 0, y: 0 }) }, [anchor])
@@ -103,8 +110,8 @@ export function AnchoredPopover(props: AnchoredPopoverProps): ReactNode {
Math.max(VIEWPORT_MARGIN - base.left, window.innerWidth - cardWidth - VIEWPORT_MARGIN - base.left),
)
const nextY = Math.min(
Math.max(start.y + (move.clientY - startY), VIEWPORT_MARGIN - base.top),
Math.max(VIEWPORT_MARGIN - base.top, window.innerHeight - 48 - base.top),
Math.max(start.y + (move.clientY - startY), topFloor - base.top),
Math.max(topFloor - base.top, window.innerHeight - 48 - base.top),
)
pendingDragRef.current = {
offset: { x: nextX, y: nextY },
@@ -127,7 +134,7 @@ export function AnchoredPopover(props: AnchoredPopoverProps): ReactNode {
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
window.addEventListener('pointercancel', onUp)
}, [cardWidth, dragBatcher, draggable])
}, [cardWidth, dragBatcher, draggable, topFloor])
// Global dismissal (see the file header for the contract).
useEffect(() => {
+41 -16
View File
@@ -37,6 +37,7 @@ import { createPortal } from 'react-dom'
import { Button, IconCloseFillRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import { createFrameBatcher } from './frame-batcher.ts'
import { t } from './locales.ts'
import { useViewportInsetTop } from './viewport-inset.ts'
import css from './FloatingWindow.module.css'
/** Default share of the viewport a fresh window takes. */
@@ -105,11 +106,22 @@ function clamp(value: number, min: number, max: number): number {
* title bar / its right edge) reachable": a window that hangs off the bottom
* edge hides its own resize corner, which is exactly how the first real-host
* check lost it.
*
* `minStart` is the lowest the origin may go; callers pass the top edge raised
* past the shell's native window-control band, which takes pointer events
* before the page sees them (./viewport-inset.ts). The overflow branch keeps
* its old shape: there the title bar is already off-screen, so raising the
* floor would only push the window's bottom further out.
*/
function clampOrigin(start: number, size: number, viewport: number): number {
function clampOrigin(
start: number,
size: number,
viewport: number,
minStart = VIEWPORT_MARGIN,
): number {
const fullyInside = viewport - size - VIEWPORT_MARGIN
return fullyInside >= VIEWPORT_MARGIN
? clamp(start, VIEWPORT_MARGIN, fullyInside)
return fullyInside >= minStart
? clamp(start, minStart, fullyInside)
: clamp(start, KEEP_ON_SCREEN - size, viewport - KEEP_ON_SCREEN)
}
@@ -119,7 +131,9 @@ function initialBox(
size: { width: number; height: number } | undefined,
min: { width: number; height: number },
viewport: { width: number; height: number },
insetTop: number,
): WindowBox {
const topFloor = VIEWPORT_MARGIN + insetTop
const width = clamp(
size?.width ?? viewport.width * DEFAULT_WIDTH_RATIO,
min.width,
@@ -128,15 +142,15 @@ function initialBox(
const height = clamp(
size?.height ?? viewport.height * DEFAULT_HEIGHT_RATIO,
min.height,
Math.max(min.height, viewport.height - VIEWPORT_MARGIN * 2),
Math.max(min.height, viewport.height - topFloor - VIEWPORT_MARGIN),
)
const rect = anchor?.getBoundingClientRect()
const left = rect === undefined
? (viewport.width - width) / 2
: clamp(rect.left, VIEWPORT_MARGIN, viewport.width - width - VIEWPORT_MARGIN)
const top = rect === undefined
? Math.max(VIEWPORT_MARGIN, (viewport.height - height) / 2)
: clamp(rect.bottom + 6, VIEWPORT_MARGIN, viewport.height - height - VIEWPORT_MARGIN)
? Math.max(topFloor, (viewport.height - height) / 2)
: clamp(rect.bottom + 6, topFloor, viewport.height - height - VIEWPORT_MARGIN)
return {
left: Math.round(left),
top: Math.round(top),
@@ -158,6 +172,9 @@ export function FloatingWindow(props: FloatingWindowProps): ReactNode {
width: minSize?.width ?? DEFAULT_MIN_WIDTH,
height: minSize?.height ?? DEFAULT_MIN_HEIGHT,
}), [minSize?.width, minSize?.height])
/** The shell's native window-control band: pointer events die in it. */
const insetTop = useViewportInsetTop()
const topFloor = VIEWPORT_MARGIN + insetTop
const frameRef = useRef<HTMLDivElement>(null)
const onCloseRef = useRef(onClose)
onCloseRef.current = onClose
@@ -174,8 +191,10 @@ export function FloatingWindow(props: FloatingWindowProps): ReactNode {
setBox(initialBox(anchor, initialSize, min, {
width: window.innerWidth,
height: window.innerHeight,
}))
// Mount-only on purpose: see the comment above.
}, insetTop))
// Mount-only on purpose: see the comment above. The inset is read
// synchronously at module evaluation, so this first box already clears the
// shell band; a later change is handled by the re-clamp effect below.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
@@ -185,21 +204,27 @@ export function FloatingWindow(props: FloatingWindowProps): ReactNode {
const current = boxRef.current
if (current === null) return
const width = clamp(current.width, min.width, Math.max(min.width, window.innerWidth - VIEWPORT_MARGIN * 2))
const height = clamp(
current.height,
min.height,
Math.max(min.height, window.innerHeight - MIN_VIEWPORT_HEIGHT),
// Old cap ("leave room for the title bar below") AND the new top floor:
// a band that grew while the window sat near the top would otherwise
// leave its title bar under the native controls.
const heightCap = Math.min(
window.innerHeight - MIN_VIEWPORT_HEIGHT,
window.innerHeight - topFloor - VIEWPORT_MARGIN,
)
const height = clamp(current.height, min.height, Math.max(min.height, heightCap))
setBox({
width,
height,
left: clampOrigin(current.left, width, window.innerWidth),
top: clampOrigin(current.top, height, window.innerHeight),
top: clampOrigin(current.top, height, window.innerHeight, topFloor),
})
}
window.addEventListener('resize', onResize)
// The band changed under an already-placed window: lift it out, never
// push it back down (that would move a window the reader placed).
onResize()
return () => { window.removeEventListener('resize', onResize) }
}, [min.width, min.height])
}, [min.width, min.height, topFloor])
// Escape only: no outside-click, no blur, no anchor observer (see the header).
useEffect(() => {
@@ -230,7 +255,7 @@ export function FloatingWindow(props: FloatingWindowProps): ReactNode {
pendingDragRef.current = {
...start,
left: clampOrigin(start.left + (move.clientX - startX), start.width, window.innerWidth),
top: clampOrigin(start.top + (move.clientY - startY), start.height, window.innerHeight),
top: clampOrigin(start.top + (move.clientY - startY), start.height, window.innerHeight, topFloor),
}
dragBatcher.schedule(() => {
const pending = pendingDragRef.current
@@ -248,7 +273,7 @@ export function FloatingWindow(props: FloatingWindowProps): ReactNode {
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
window.addEventListener('pointercancel', onUp)
}, [dragBatcher])
}, [dragBatcher, topFloor])
/** Resize from one edge handle: `axis` picks which dimension the handle owns. */
const resizeBatcher = useRef(createFrameBatcher()).current
+8 -1
View File
@@ -32,6 +32,7 @@ import { isDarkScheme, subscribeColorScheme } from './theme.ts'
import { markdownTextProps } from './markdown-labels.tsx'
import { t } from './locales.ts'
import { sanitizeSvg } from './mermaid-sanitize.ts'
import { useViewportInsetTop } from './viewport-inset.ts'
import type { MermaidMarkdownProps } from './mermaid-blocks.ts'
import { splitMermaidBlocks } from './mermaid-blocks.ts'
import { renderMermaidDiagram, type MermaidTheme } from './mermaid-frame.ts'
@@ -192,6 +193,8 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () =>
const svgRef = useRef<SVGSVGElement | null>(null)
const dragRef = useRef({ active: false, startX: 0, startY: 0 })
const zoomRef = useRef({ scale: 1, tx: 0, ty: 0 })
/** The shell's native window-control band: it eats pointer events (#805). */
const insetTop = useViewportInsetTop()
const applyTransform = (): void => {
const node = svgRef.current
@@ -298,7 +301,11 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () =>
return createPortal(
<div className={css.mermaidModal} data-mermaid-modal ref={overlayRef}>
<div className={css.mermaidModalToolbar}>
<div
className={css.mermaidModalToolbar}
data-mermaid-toolbar
style={{ top: 16 + insetTop }}
>
<button
type="button"
className={css.mermaidModalButton}
+2 -1
View File
@@ -2055,9 +2055,10 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
backdrop-filter: blur(2px);
}
/* `top` is written inline by mermaid.tsx (it has to clear the shell's native
window-control band, #805). */
.mermaidModalToolbar {
position: absolute;
top: 16px;
right: 16px;
display: flex;
gap: 8px;
+124
View File
@@ -0,0 +1,124 @@
/**
* How many CSS pixels at the top of the viewport the DESKTOP SHELL paints its
* native window controls over (minimize / maximize / close).
*
* Why this exists: on Windows the shell enables Electron's `titleBarOverlay`,
* which draws those buttons OVER the page and takes every pointer event in
* that band before it can reach the DOM. A floating surface pinned to the
* viewport top therefore loses its whole title bar: the close button looks
* dead while `document.elementFromPoint` still answers it (the two-point
* bisection in issue #805 measured the same mechanism for the mermaid zoom
* toolbar; the Tasks detail window is the same bug one component over).
*
* The ONE source is the standard Window Controls Overlay geometry. No
* preference, no settings row, no URL stamp, no shell-supplied service, and
* nothing is published to the DOM — the previous configurable "title-bar
* strip" was removed in #430 because it had grown five sources and zero
* consumers; this has one source and three real consumers.
*/
import { useSyncExternalStore } from 'react'
/** The slice of `navigator.windowControlsOverlay` this module needs. */
export interface WindowControlsOverlayLike {
readonly visible: boolean
getTitlebarAreaRect(): {
readonly x: number
readonly y: number
readonly width: number
readonly height: number
}
addEventListener(type: 'geometrychange', listener: () => void): void
removeEventListener(type: 'geometrychange', listener: () => void): void
}
function overlayOf(navigatorLike: Navigator | undefined): WindowControlsOverlayLike | undefined {
const candidate = (navigatorLike as
| (Navigator & { windowControlsOverlay?: WindowControlsOverlayLike })
| undefined)?.windowControlsOverlay
return candidate ?? undefined
}
/**
* The safe gap below the native control band.
*
* `y + height` rather than `height` alone: the rect names the title-bar AREA,
* so its bottom edge is the first pixel the page can own (the two coincide on
* Windows, where `y` is 0, but a shell may inset the band).
*
* Everything unusable collapses to 0 — no API, `visible: false` (headless
* Chromium and some macOS builds expose the interface with no overlay), a
* zero-height band, or a throwing call. 0 keeps plain browsers and web
* profiles exactly as they were.
*/
function computeInset(candidate: WindowControlsOverlayLike | undefined): number {
if (candidate === undefined) return 0
try {
if (candidate.visible !== true) return 0
const rect = candidate.getTitlebarAreaRect()
const top = Math.round(rect.y + rect.height)
return Number.isFinite(top) && top > 0 ? top : 0
} catch {
return 0
}
}
let source: WindowControlsOverlayLike | undefined
// A number, not an object: the change check below is then a value comparison,
// so an unchanged band never wakes the consumers.
let snapshot = 0
const listeners = new Set<() => void>()
function emit(): void {
for (const listener of listeners) listener()
}
function reread(): void {
const next = computeInset(source)
if (next === snapshot) return
snapshot = next
emit()
}
// Probe at module evaluation, not on the first subscriber: `useSyncExternalStore`
// reads the snapshot before it subscribes, so a lazy mount would paint the
// first frame at the unsafe position and then jump the window down.
if (typeof navigator !== 'undefined') {
source = overlayOf(navigator)
if (source !== undefined) {
snapshot = computeInset(source)
source.addEventListener('geometrychange', reread)
}
}
// Some Electron builds expose the overlay without firing `geometrychange` on
// maximize / restore; a resize is the same event in practice. Event-driven, so
// it costs nothing while idle (unlike the polling the steady-state rules guard).
if (typeof window !== 'undefined') {
window.addEventListener('resize', reread)
}
/** The current inset in CSS pixels (0 when there is none). */
export function getViewportInset(): number {
return snapshot
}
/** Subscribe to geometry changes; returns the disposer. */
export function subscribeViewportInset(listener: () => void): () => void {
listeners.add(listener)
return () => { listeners.delete(listener) }
}
/** Swap the overlay source (tests). `undefined` = no overlay API. */
export function setViewportInsetSourceForTests(
next: WindowControlsOverlayLike | undefined,
): void {
source?.removeEventListener('geometrychange', reread)
source = next
reread()
next?.addEventListener('geometrychange', reread)
}
/** React consumer: the inset, re-rendering only when the shell band changes. */
export function useViewportInsetTop(): number {
return useSyncExternalStore(subscribeViewportInset, getViewportInset, getViewportInset)
}
+82
View File
@@ -0,0 +1,82 @@
/**
* The anchored popover (AnchoredPopover.tsx): the card opens below its anchor
* but never inside the shell's native window-control band (issue #805's
* mechanism; the Tasks detail window is the same bug one component over).
*
* jsdom performs no layout, so the card measures 0 tall and its placement is
* read back from the inline style the component writes.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from 'vitest'
import { createElement } from 'react'
import { renderRoot, setupReactAct } from './test-utils.ts'
import { AnchoredPopover } from '../src/client/AnchoredPopover.tsx'
import {
setViewportInsetSourceForTests,
type WindowControlsOverlayLike,
} from '../src/client/viewport-inset.ts'
setupReactAct()
afterEach(() => {
setViewportInsetSourceForTests(undefined)
for (const el of document.querySelectorAll('body > div')) el.remove()
})
function overlayBand(height: number): WindowControlsOverlayLike {
return {
visible: true,
getTitlebarAreaRect: () => ({ x: 0, y: 0, width: 1_000, height }),
addEventListener: () => {},
removeEventListener: () => {},
}
}
/** A real button in the DOM, positioned so its bottom edge sits at `bottom`. */
function anchorAt(bottom: number): HTMLElement {
const anchor = document.createElement('button')
document.body.append(anchor)
anchor.getBoundingClientRect = () => ({
left: 100, top: bottom - 20, right: 200, bottom, width: 100, height: 20,
x: 100, y: bottom - 20, toJSON: () => ({}),
}) as DOMRect
return anchor
}
function render(anchor: HTMLElement) {
return renderRoot(createElement(AnchoredPopover, {
anchor,
onClose: () => {},
children: createElement('div', null, 'node detail'),
}))
}
/** The card's inline top (jsdom has no layout). */
function cardTop(): number {
const card = document.querySelector('[role="dialog"]')
if (card === null) throw new Error('no popover rendered')
return Number.parseFloat((card as HTMLElement).style.top)
}
describe('AnchoredPopover and the native window-control band', () => {
it('lifts the card below the band when the anchor sits inside it', () => {
setViewportInsetSourceForTests(overlayBand(44))
const { unmount } = render(anchorAt(20))
// Without the band the card would open at 26, inside the native controls.
expect(cardTop()).toBe(52)
unmount()
})
it('keeps opening just below the anchor when there is no band', () => {
const { unmount } = render(anchorAt(20))
expect(cardTop()).toBe(26)
unmount()
})
it('keeps the historical placement for an anchor at the very top', () => {
// No band means no extra floor: 8 + rect.bottom, as before the band work.
const { unmount } = render(anchorAt(0))
expect(cardTop()).toBe(6)
unmount()
})
})
+43
View File
@@ -168,6 +168,30 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
if (message.type() === 'error') consoleErrors.push(message.text())
})
// A fake Window Controls Overlay so the test can play the desktop shell's
// native window-control band. It starts at 0 (plain-browser behaviour, so
// every other assertion in this lane stays exactly as before); the mermaid
// section below raises it and measures the REAL layout.
await page.addInitScript(() => {
const listeners = new Set<() => void>()
const band = { height: 0, visible: true }
Object.defineProperty(navigator, 'windowControlsOverlay', {
configurable: true,
value: {
get visible() { return band.visible },
getTitlebarAreaRect: () => ({ x: 0, y: 0, width: window.innerWidth, height: band.height }),
addEventListener: (type: string, listener: () => void) => {
if (type === 'geometrychange') listeners.add(listener)
},
removeEventListener: (_type: string, listener: () => void) => { listeners.delete(listener) },
},
})
;(window as unknown as { __setTitlebarBand(height: number): void }).__setTitlebarBand = (height) => {
band.height = height
for (const listener of listeners) listener()
}
})
// Load the shell. The app renders into #root; the plugin appends its own
// [data-dsh-better-sidebar] host once its client half activates.
//
@@ -577,6 +601,25 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
})
expect(modalRegions.modal, 'the zoom modal must opt out of app-region computation').toBe('none')
expect(modalRegions.button, 'its buttons must stay no-drag').toBe('no-drag')
// Issue #805: the shell draws its native window controls OVER the page's
// top-right and those pointer events never reach the document, so the
// toolbar must sit below that band. At the reporter's 42px overlay a bare
// 16px inset left only the bottom 10px of each 36px button clickable while
// `elementFromPoint` still answered the button — the control read as dead.
// Play the band and measure the real layout.
const toolbar = page.locator('[data-mermaid-modal] [data-mermaid-toolbar]')
const toolbarTop = async (): Promise<number> => await toolbar.evaluate(
(element) => Math.round(element.getBoundingClientRect().top),
)
expect(await toolbarTop(), 'with no band the toolbar keeps its 16px inset').toBe(16)
await page.evaluate(() => {
;(window as unknown as { __setTitlebarBand(h: number): void }).__setTitlebarBand(36)
})
await expect.poll(toolbarTop, 'a 36px band must push the toolbar clear of it').toBe(52)
await page.evaluate(() => {
;(window as unknown as { __setTitlebarBand(h: number): void }).__setTitlebarBand(0)
})
await expect.poll(toolbarTop, 'shrinking the band must pull the toolbar back').toBe(16)
await page.keyboard.press('Escape')
await expect(modal, 'Esc must close the zoom modal').toHaveCount(0, { timeout: 10_000 })
await assertNoCrash()
+113
View File
@@ -15,6 +15,10 @@ import { createElement, createRef, type RefObject } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot, setupReactAct } from './test-utils.ts'
import { FloatingWindow } from '../src/client/FloatingWindow.tsx'
import {
setViewportInsetSourceForTests,
type WindowControlsOverlayLike,
} from '../src/client/viewport-inset.ts'
setupReactAct()
@@ -57,6 +61,7 @@ beforeEach(() => {
})
afterEach(() => {
setViewportInsetSourceForTests(undefined)
vi.unstubAllGlobals()
for (const el of document.querySelectorAll('body > div')) el.remove()
})
@@ -67,12 +72,14 @@ function renderWindow(props: {
bodyRef?: RefObject<HTMLDivElement>
footer?: boolean
actions?: boolean
initialSize?: { width: number; height: number }
} = {}) {
const rendered = renderRoot(createElement(FloatingWindow, {
title: 'bash-1',
onClose: () => { closed += 1 },
...(props.anchor === undefined ? {} : { anchor: props.anchor }),
...(props.bodyRef === undefined ? {} : { bodyRef: props.bodyRef }),
...(props.initialSize === undefined ? {} : { initialSize: props.initialSize }),
...(props.footer === true ? { footer: createElement('button', { type: 'button' }, 'stop') } : {}),
...(props.actions === true ? { actions: createElement('button', { type: 'button' }, 'copy') } : {}),
children: createElement('div', null, 'line 1'),
@@ -242,3 +249,109 @@ describe('FloatingWindow gestures', () => {
unmount()
})
})
/** A controllable Window Controls Overlay: the shell's native control band. */
function overlayBand(height: number, visible = true): {
source: WindowControlsOverlayLike
set(next: number): void
emit(): void
} {
let band = height
const listeners = new Set<() => void>()
return {
source: {
get visible() { return visible },
getTitlebarAreaRect: () => ({ x: 0, y: 0, width: 1_000, height: band }),
addEventListener: (_type, listener) => { listeners.add(listener) },
removeEventListener: (_type, listener) => { listeners.delete(listener) },
},
set(next) { band = next },
emit() { for (const listener of listeners) listener() },
}
}
/** Drag the title bar into the top-left corner (the clamp's tightest case). */
function dragToTopLeft(): void {
const handle = frame().querySelector('[data-window-handle]') as HTMLElement
act(() => {
pointer(handle, 'pointerdown', 500, 100)
pointer(window, 'pointermove', -5_000, -5_000)
pointer(window, 'pointerup', -5_000, -5_000)
})
}
/**
* The desktop shell paints its native window controls OVER the viewport's top
* band and the page never sees those pointer events (issue #805 measured it).
* A floating window whose title bar lands there reads as unclosable: the Tasks
* detail window's × was the report that started this.
*/
describe('FloatingWindow keeps its title bar out of the native control band', () => {
it('lifts an anchored window below the band', () => {
setViewportInsetSourceForTests(overlayBand(44).source)
const anchor = document.createElement('button')
document.body.append(anchor)
anchor.getBoundingClientRect = () => ({
left: 100, top: 0, right: 200, bottom: 20, width: 100, height: 20,
x: 100, y: 0, toJSON: () => ({}),
}) as DOMRect
const { unmount } = renderWindow({ anchor })
// Without the band the anchor would place it at 26; the floor is 8 + 44.
expect(box().top).toBe(52)
unmount()
})
it('never drags the window into the band', () => {
setViewportInsetSourceForTests(overlayBand(44).source)
const { unmount } = renderWindow()
dragToTopLeft()
expect(box().top).toBe(52)
unmount()
})
it('lifts an already-placed window when the band appears', () => {
const band = overlayBand(0)
setViewportInsetSourceForTests(band.source)
const { unmount } = renderWindow()
dragToTopLeft()
expect(box().top).toBe(8)
act(() => { band.set(44); band.emit() })
expect(box().top).toBe(52)
unmount()
})
it('does not pull the window back up when the band disappears', () => {
// Deliberate: a window the reader placed must not jump on maximize/restore;
// the floor only ever guarantees "not inside the band".
const band = overlayBand(44)
setViewportInsetSourceForTests(band.source)
const { unmount } = renderWindow()
dragToTopLeft()
expect(box().top).toBe(52)
act(() => { band.set(0); band.emit() })
expect(box().top).toBe(52)
unmount()
})
it('caps the height so a tall window still clears the band', () => {
Object.defineProperty(window, 'innerHeight', { configurable: true, value: 400 })
setViewportInsetSourceForTests(overlayBand(44).source)
const { unmount } = renderWindow({ initialSize: { width: 600, height: 500 } })
const current = box()
// Asked for 500 but only 400 - 52 (band) - 8 (margin) fits.
expect(current.height).toBe(340)
expect(current.top).toBe(52)
expect(current.top + current.height).toBe(392)
unmount()
})
it('leaves plain browsers untouched when the overlay is a ghost', () => {
// Headless Chromium and some macOS builds expose the interface with
// `visible: false`: no band, so the old 8px floor must stay exact.
setViewportInsetSourceForTests(overlayBand(44, false).source)
const { unmount } = renderWindow()
dragToTopLeft()
expect(box().top).toBe(8)
unmount()
})
})
+159
View File
@@ -0,0 +1,159 @@
/**
* The viewport's top inset (viewport-inset.ts): the band the desktop shell
* paints its native window controls over, which floating surfaces must stay
* out of (issue #805; the Tasks detail window's close button is the same bug).
*
* Every unusable shape collapses to 0 so plain browsers keep their exact
* behaviour: no API, a `visible: false` ghost interface (headless Chromium,
* some macOS builds), a zero-height band, and a throwing read.
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
getViewportInset,
setViewportInsetSourceForTests,
subscribeViewportInset,
type WindowControlsOverlayLike,
} from '../src/client/viewport-inset.ts'
interface Rect { x: number; y: number; width: number; height: number }
/** A controllable WCO source: `emit()` plays the browser's geometrychange. */
function overlay(initial: Rect, visible = true): {
source: WindowControlsOverlayLike
set(next: Partial<Rect>): void
setVisible(next: boolean): void
emit(): void
listenerCount(): number
boom(): void
} {
let rect = { ...initial }
let isVisible = visible
let throws = false
const listeners = new Set<() => void>()
return {
source: {
get visible() { return isVisible },
getTitlebarAreaRect() {
if (throws) throw new Error('geometry raced the layout')
return { ...rect }
},
addEventListener(_type, listener) { listeners.add(listener) },
removeEventListener(_type, listener) { listeners.delete(listener) },
},
set(next) { rect = { ...rect, ...next } },
setVisible(next) { isVisible = next },
emit() { for (const listener of listeners) listener() },
listenerCount: () => listeners.size,
boom() { throws = true },
}
}
beforeEach(() => {
setViewportInsetSourceForTests(undefined)
})
afterEach(() => {
setViewportInsetSourceForTests(undefined)
})
describe('viewport inset: the shape of the native control band', () => {
it('is zero without the Window Controls Overlay API', () => {
expect(getViewportInset()).toBe(0)
})
it('reads the band height', () => {
setViewportInsetSourceForTests(overlay({ x: 0, y: 0, width: 1_000, height: 36 }).source)
expect(getViewportInset()).toBe(36)
})
it('rounds a fractional height', () => {
setViewportInsetSourceForTests(overlay({ x: 0, y: 0, width: 1_000, height: 35.6 }).source)
expect(getViewportInset()).toBe(36)
})
it('uses the rect bottom edge, not the raw height', () => {
// A shell that insets the band: the page may start at y + height.
setViewportInsetSourceForTests(overlay({ x: 0, y: 4, width: 1_000, height: 32 }).source)
expect(getViewportInset()).toBe(36)
})
it('treats a non-visible overlay as absent (ghost interface)', () => {
setViewportInsetSourceForTests(overlay({ x: 0, y: 0, width: 1_000, height: 44 }, false).source)
expect(getViewportInset()).toBe(0)
})
it('treats a zero-height band as no band', () => {
setViewportInsetSourceForTests(overlay({ x: 0, y: 0, width: 1_000, height: 0 }).source)
expect(getViewportInset()).toBe(0)
})
it('does not throw when the geometry read races the layout', () => {
const fake = overlay({ x: 0, y: 0, width: 1_000, height: 44 })
setViewportInsetSourceForTests(fake.source)
expect(getViewportInset()).toBe(44)
fake.boom()
expect(() => { fake.emit() }).not.toThrow()
expect(getViewportInset()).toBe(0)
})
})
describe('viewport inset: live geometry', () => {
it('notifies subscribers only when the band actually changes', () => {
const fake = overlay({ x: 0, y: 0, width: 1_000, height: 0 })
setViewportInsetSourceForTests(fake.source)
let calls = 0
const dispose = subscribeViewportInset(() => { calls += 1 })
expect(getViewportInset()).toBe(0)
fake.set({ height: 36 })
fake.emit()
expect(getViewportInset()).toBe(36)
expect(calls).toBe(1)
// A later event with the same geometry must not wake React again.
fake.emit()
expect(calls).toBe(1)
fake.set({ height: 0 })
fake.emit()
expect(getViewportInset()).toBe(0)
expect(calls).toBe(2)
dispose()
fake.set({ height: 36 })
fake.emit()
expect(calls).toBe(2)
})
it('re-reads on window resize (the maximize / restore fallback)', () => {
// Some Electron builds expose the overlay without firing geometrychange.
const fake = overlay({ x: 0, y: 0, width: 1_000, height: 0 })
setViewportInsetSourceForTests(fake.source)
fake.set({ height: 36 })
window.dispatchEvent(new Event('resize'))
expect(getViewportInset()).toBe(36)
})
it('drops and restores the inset when visibility flips at runtime', () => {
const fake = overlay({ x: 0, y: 0, width: 1_000, height: 36 })
setViewportInsetSourceForTests(fake.source)
expect(getViewportInset()).toBe(36)
fake.setVisible(false)
fake.emit()
expect(getViewportInset()).toBe(0)
fake.setVisible(true)
fake.emit()
expect(getViewportInset()).toBe(36)
})
it('detaches the previous source when tests swap it', () => {
const first = overlay({ x: 0, y: 0, width: 1_000, height: 36 })
setViewportInsetSourceForTests(first.source)
expect(first.listenerCount()).toBe(1)
const second = overlay({ x: 0, y: 0, width: 1_000, height: 44 })
setViewportInsetSourceForTests(second.source)
expect(first.listenerCount()).toBe(0)
expect(getViewportInset()).toBe(44)
})
})