mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
feat: let skins dock the recovery capsule into their layout with runtime fallback
- chrome.json#slots names an existing skin data-ws-part as anchor for host.recovery (align start/center/end, optional compact); host/trusted parts rejected as anchors - reusable host-slot-placement module: positions the closed-shadow top-layer capsule over the anchor, re-checks visibility/size/on-screen/elementFromPoint, snaps back to the default corner on any failure with anti-flap re-slotting - --skin-recovery-* tokens (accent/background/foreground/radius/font/size tier) sanitized with 28px minimum hit target and WCAG contrast fallback - compact mode only after 5s full display post-activation; shortcut always full - no new skin CSS compile-time restrictions; docs and host-chrome-demo updated
This commit is contained in:
1 parent
fa720bf260
commit
aefa0bc163
18 files changed
+1547
-254
No files matched your search
@@ -96,7 +96,7 @@ assets/preview.jpg # 可选:管理后台显示的预览图,也可
|
||||
assets/background.webp # 可选:页面艺术素材
|
||||
assets/brand.woff2 # 可选:自带字体
|
||||
components.json # v3 可选:声明式组件或完整页面 surface
|
||||
chrome.json # v3/v4 可选:宿主装饰隐藏与图标位图覆盖(见「chrome.json」章节)
|
||||
chrome.json # v3/v4 可选:宿主装饰、图标位图与可信控件停靠(见「chrome.json」章节)
|
||||
assets/icons/language.png # v3/v4 可选:工具栏图标位图覆盖素材
|
||||
plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件
|
||||
plugins/<plugin-id>/index.js # v4 插件代码,目前只校验和缓存
|
||||
@@ -406,7 +406,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery` / `host.permission` / `app.skin-load-recovery` 仅为宿主内部标识(闭合 Shadow DOM,恢复入口与授权对话框还在顶层;无 CSS 钩子,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
|
||||
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠到皮肤布局,但仍无 CSS 钩子)/ `host.permission` / `app.skin-load-recovery` 仅为宿主内部标识(闭合 Shadow DOM,恢复入口与授权对话框还在顶层;无 CSS 钩子,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
|
||||
| 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) |
|
||||
|
||||
`voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
@@ -453,13 +453,13 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
### 恢复入口与授权对话框:结构上不可被皮肤触及
|
||||
|
||||
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或主题化的 CSS 钩子:当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们:
|
||||
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接主题化的 CSS 钩子(`host.recovery` 只能通过下文的 `chrome.json#slots` 声明锚点和受限的 `--skin-recovery-*` 令牌间接参与布局):当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们:
|
||||
|
||||
1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。
|
||||
2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `<dialog>` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。
|
||||
3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
|
||||
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角;它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
|
||||
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
|
||||
|
||||
@@ -467,6 +467,48 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。
|
||||
|
||||
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
|
||||
|
||||
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "end", "compact": true }
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| 键名 | 目前只接受 `host.recovery`(`src/shared/skin-visual-parts.ts` 的 `HOST_SLOTTABLE_PART_IDS`;后续可加入其他受保护控件)。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
|
||||
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称。不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。宿主只取第一个可见匹配;锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
|
||||
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;胶囊在锚点矩形内按此水平对齐,并垂直居中。 |
|
||||
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 |
|
||||
|
||||
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
|
||||
|
||||
- v3 `components.json` 组件根:`skin.<page>.<componentId>`。
|
||||
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
|
||||
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
|
||||
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
|
||||
**样式令牌**:皮肤可在锚点或它的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。只有颜色对比度不达标时整组颜色才回退到宿主默认值。
|
||||
|
||||
| 令牌 | 规则 |
|
||||
| --- | --- |
|
||||
| `--skin-recovery-accent` | 强调色,用于「使用内置皮肤」按钮的边框/重点。与背景的对比度必须 ≥ 3,否则整组颜色回退。 |
|
||||
| `--skin-recovery-background` | 胶囊背景。宿主强制不透明(alpha 视为 1)。 |
|
||||
| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
|
||||
| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
|
||||
| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;其他值使用宿主默认字体。 |
|
||||
| `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
|
||||
|
||||
颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
|
||||
|
||||
**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停或键盘聚焦时展开为完整按钮。新皮肤激活后的约 5 秒内始终显示完整胶囊,避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。
|
||||
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
|
||||
`host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。
|
||||
|
||||
示例(v3 `skin.css`):
|
||||
@@ -494,7 +536,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| `home.toolbar.settings` | 首页工具栏设置图标 |
|
||||
| `voice.performance` | 语音页 Voice status / 性能触发器图标 |
|
||||
|
||||
### `chrome.json`:声明式显示 / 隐藏与图标位图覆盖
|
||||
### `chrome.json`:声明式显示 / 隐藏、图标位图覆盖与控件停靠
|
||||
|
||||
v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根目录,最多 32 KiB:
|
||||
|
||||
@@ -507,6 +549,9 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
|
||||
"language.trigger": "assets/icons/language.png",
|
||||
"skin.trigger": "assets/icons/skin.png",
|
||||
"host.plugins.launcher": "assets/icons/apps.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "end", "compact": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -516,6 +561,7 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
|
||||
| `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 |
|
||||
| `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 |
|
||||
| `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 |
|
||||
| `slots` | 可选,最多 8 项;键名目前只能是 `host.recovery`,值只能包含 `anchor`、`align`、`compact`。详见上文「将恢复入口停靠到皮肤布局」。未知键、指向 `host.*` 或可信宿主部件的锚点会被拒绝。 |
|
||||
|
||||
图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。
|
||||
|
||||
|
||||
Binary file not shown.
@@ -8,5 +8,8 @@
|
||||
"host.plugins.launcher": "assets/icons/apps.png",
|
||||
"home.toolbar.settings": "assets/icons/settings.png",
|
||||
"voice.performance": "assets/icons/status.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "end", "compact": true }
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,13 @@
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
border-top: 1px solid var(--skin-border);
|
||||
background: #f7f9fb;
|
||||
/* Fold the trusted recovery capsule into the audio dock (chrome.json#slots). */
|
||||
--skin-recovery-accent: #1d4f9c;
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #141414;
|
||||
--skin-recovery-radius: 999px;
|
||||
--skin-recovery-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-recovery-size: small;
|
||||
}
|
||||
|
||||
/* --- Host chrome (outside .ws-skin-root) --- */
|
||||
|
||||
Binary file not shown.
+1
-1
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-recovery-helpers.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
|
||||
+103
-5
@@ -1,15 +1,25 @@
|
||||
import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./skin-visual-parts.js";
|
||||
import {
|
||||
DECORATIVE_PART_IDS,
|
||||
HOST_SKIN_ATTRIBUTE,
|
||||
HOST_SLOTTABLE_PART_IDS,
|
||||
SKIN_ICON_SLOT_IDS,
|
||||
TRUSTED_PART_IDS,
|
||||
isHostPart,
|
||||
} from "./skin-visual-parts.js";
|
||||
|
||||
/**
|
||||
* `chrome.json` is an optional, declarative companion to an open skin.
|
||||
*
|
||||
* It describes two host-chrome capabilities that CSS alone cannot express
|
||||
* safely:
|
||||
* It describes host-chrome capabilities that CSS alone cannot express safely:
|
||||
* - `visibleParts`: decorations the skin asks the host to render. This is the
|
||||
* only opt-in; official and built-in skins stay clean.
|
||||
* - `hiddenParts`: non-critical decorations the skin wants collapsed by
|
||||
* default. Only explicitly optional parts are accepted.
|
||||
* - `icons`: bitmap overrides for stable icon slots, keyed by part name.
|
||||
* - `slots`: declarative anchors for trusted host controls. A skin never
|
||||
* receives the control; it only names a part it already renders so the
|
||||
* host can position its own top-layer capsule there and fall back to the
|
||||
* default corner when the anchor stops being usable.
|
||||
*
|
||||
* Both the browser importer and the server-side registry parse the exact same
|
||||
* document, so a package accepted by one is accepted by the other.
|
||||
@@ -18,10 +28,21 @@ import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./
|
||||
export const SKIN_CHROME_MAX_BYTES = 32 * 1024;
|
||||
export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32;
|
||||
export const SKIN_CHROME_MAX_ICONS = 16;
|
||||
export const SKIN_CHROME_MAX_SLOTS = 8;
|
||||
export const SKIN_ICON_MAX_BYTES = 64 * 1024;
|
||||
export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024;
|
||||
export const SKIN_ICON_DIRECTORY = "assets/icons/";
|
||||
|
||||
/**
|
||||
* Anchor names are `data-ws-part` values, including host-rendered v3 component
|
||||
* parts (`skin.<page>.<component>.part-<name>`) and v4 runtime plugin parts
|
||||
* (`skin.<page>.runtime_plugin_<plugin>__<component>.part-<name>`). Each
|
||||
* dot-separated segment follows the same identifier grammar as other part
|
||||
* names; the generous overall limit covers a namespaced runtime plugin.
|
||||
*/
|
||||
export const SKIN_SLOT_ANCHOR_MAX_LENGTH = 240;
|
||||
const PART_NAME_SEGMENT = /^[-_a-z][-_a-z0-9]*$/i;
|
||||
|
||||
const SUPPORTED_ICON_EXTENSIONS = new Set(["png", "jpg", "jpeg", "webp", "avif", "gif"]);
|
||||
|
||||
/**
|
||||
@@ -45,6 +66,19 @@ export interface SkinChromeDocument {
|
||||
*/
|
||||
visibleParts?: string[];
|
||||
icons: Record<string, string>;
|
||||
/** Protected host controls folded into skin-owned layout anchors. */
|
||||
slots?: Partial<Record<string, SkinChromeSlot>>;
|
||||
}
|
||||
|
||||
export type SkinChromeSlotAlign = "start" | "center" | "end";
|
||||
|
||||
export interface SkinChromeSlot {
|
||||
/** Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box. */
|
||||
anchor: string;
|
||||
/** Horizontal alignment inside the anchor; the control is vertically centred. */
|
||||
align: SkinChromeSlotAlign;
|
||||
/** Collapse to the mark only until hovered or focused. */
|
||||
compact: boolean;
|
||||
}
|
||||
|
||||
export interface SkinChromeAssetInfo {
|
||||
@@ -94,6 +128,29 @@ export function normalizeSkinIconPath(raw: unknown): string {
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* A slot anchor is an existing part name, never host-owned UI: a skin must not
|
||||
* be able to park a protected control on the launcher, the authorization
|
||||
* dialog or another trusted element it could then cover or remove.
|
||||
*/
|
||||
function normalizeSlotAnchor(raw: unknown): string {
|
||||
if (typeof raw !== "string" || !raw || raw.length > SKIN_SLOT_ANCHOR_MAX_LENGTH) {
|
||||
return reject(`A slot anchor must be a part name of at most ${SKIN_SLOT_ANCHOR_MAX_LENGTH} characters.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const segments = raw.split(".");
|
||||
if (segments.some((segment) => !PART_NAME_SEGMENT.test(segment))) {
|
||||
return reject(`A slot anchor is not a valid part name: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (isHostPart(raw) || TRUSTED_PART_IDS.has(raw)) {
|
||||
return reject(`A slot anchor cannot point at trusted host UI: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function isSlotAlign(value: unknown): value is SkinChromeSlotAlign {
|
||||
return value === "start" || value === "center" || value === "end";
|
||||
}
|
||||
|
||||
export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
const bytes = new TextEncoder().encode(source).byteLength;
|
||||
if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) {
|
||||
@@ -104,7 +161,7 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
catch { return reject("chrome.json is not valid JSON.", "SKIN_CHROME_INVALID"); }
|
||||
if (!isRecord(raw)) return reject("chrome.json must be an object.", "SKIN_CHROME_INVALID");
|
||||
for (const key of Object.keys(raw)) {
|
||||
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons") {
|
||||
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons" && key !== "slots") {
|
||||
return reject(`chrome.json contains an unsupported field: ${key}.`, "SKIN_CHROME_INVALID");
|
||||
}
|
||||
}
|
||||
@@ -151,7 +208,48 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
icons[slot] = normalizeSkinIconPath(path);
|
||||
}
|
||||
}
|
||||
return { schemaVersion: 1, hiddenParts, ...(visibleParts ? { visibleParts } : {}), icons };
|
||||
let slots: Partial<Record<string, SkinChromeSlot>> | undefined;
|
||||
if (raw.slots !== undefined) {
|
||||
if (!isRecord(raw.slots)) {
|
||||
return reject("slots must be an object mapping protected part names to anchors.", "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const entries = Object.entries(raw.slots);
|
||||
if (entries.length > SKIN_CHROME_MAX_SLOTS) {
|
||||
return reject(`A skin may declare at most ${SKIN_CHROME_MAX_SLOTS} slots.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots = Object.create(null) as Partial<Record<string, SkinChromeSlot>>;
|
||||
for (const [part, value] of entries) {
|
||||
if (!HOST_SLOTTABLE_PART_IDS.has(part)) {
|
||||
return reject(`Unknown slottable host part: ${part}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return reject(`Slot ${part} must be an object.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
for (const key of Object.keys(value)) {
|
||||
if (key !== "anchor" && key !== "align" && key !== "compact") {
|
||||
return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
}
|
||||
const anchor = normalizeSlotAnchor(value.anchor);
|
||||
const align = value.align === undefined ? "end" : value.align;
|
||||
if (!isSlotAlign(align)) {
|
||||
return reject(`Slot ${part} has an invalid align value: ${String(align)}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const compact = value.compact === undefined ? false : value.compact;
|
||||
if (typeof compact !== "boolean") {
|
||||
return reject(`Slot ${part} compact must be a boolean.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots[part] = { anchor, align, compact };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
hiddenParts,
|
||||
...(visibleParts ? { visibleParts } : {}),
|
||||
icons,
|
||||
...(slots ? { slots } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { compileSkinCss, OPTIONAL_VISUAL_PARTS } from "./skin-css.js";
|
||||
import { DECORATIVE_PART_IDS as LAYOUT_DECORATIVE, PROTECTED_PART_IDS } from "./skin-layout.js";
|
||||
import { DECORATIVE_PART_IDS } from "./skin-visual-parts.js";
|
||||
import { DECORATIVE_PART_IDS, HOST_SLOTTABLE_PART_IDS } from "./skin-visual-parts.js";
|
||||
import {
|
||||
compileSkinChromeCss,
|
||||
DEFAULT_HIDDEN_HOST_PARTS,
|
||||
@@ -196,6 +196,62 @@ test("chrome.json declares hidden parts and icon bitmaps, with path and size val
|
||||
assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: 10, mime: "text/plain" })), /raster image/);
|
||||
});
|
||||
|
||||
test("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => {
|
||||
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], ["host.recovery"]);
|
||||
|
||||
const explicit = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(explicit.slots?.["host.recovery"], {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "start",
|
||||
compact: true,
|
||||
});
|
||||
|
||||
// Defaults: align "end", compact off. Component and runtime-plugin parts are
|
||||
// ordinary anchors; only host/trusted parts are off limits.
|
||||
const defaults = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "skin.voice.harbor-dock.part-anchor" },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(defaults.slots?.["host.recovery"], {
|
||||
anchor: "skin.voice.harbor-dock.part-anchor",
|
||||
align: "end",
|
||||
compact: false,
|
||||
});
|
||||
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: { "host.recovery": { anchor: "skin.voice.runtime_plugin_voice-surface__dock.part-anchor" } },
|
||||
})));
|
||||
|
||||
// Slot declarations are runtime input, not compiled CSS: the generated host
|
||||
// stylesheet must stay exactly as empty as before.
|
||||
assert.equal(compileSkinChromeCss(explicit, "demo-skin"), "");
|
||||
|
||||
const invalidDocuments: Array<[unknown, RegExp]> = [
|
||||
[{ schemaVersion: 1, slots: [] }, /must be an object/],
|
||||
[{ schemaVersion: 1, slots: { "host.permission": { anchor: "voice.audio-dock" } } }, /Unknown slottable host part/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": "voice.audio-dock" } }, /must be an object/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "host.plugins.launcher" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.connection-status" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "app" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", align: "left" } } }, /invalid align/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", compact: "yes" } } }, /compact must be a boolean/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", extra: true } } }, /unsupported field/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "../escape" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "Voice Audio Dock" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "" } } }, /at most 240 characters/],
|
||||
];
|
||||
for (const [value, message] of invalidDocuments) {
|
||||
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
|
||||
}
|
||||
});
|
||||
|
||||
test("instance-level hidden parts ignore unknown and protected names", () => {
|
||||
assert.deepEqual(parseHiddenHostParts("host.watermark, host.hint voice.audio-dock home.footer"), ["host.watermark", "host.hint"]);
|
||||
assert.deepEqual(parseHiddenHostParts(["host.hint", "host.hint", "nope"]), ["host.hint"]);
|
||||
|
||||
@@ -43,6 +43,17 @@ export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
|
||||
"host.permission",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Trusted host controls that an open skin may fold into its own layout through
|
||||
* `chrome.json#slots`. The key names the protected part, not a CSS hook: the
|
||||
* skin only declares an anchor rectangle, the host still owns, paints and
|
||||
* hit-tests the control. Extend this set (for example with `host.permission`)
|
||||
* when another protected control learns the same runtime placement.
|
||||
*/
|
||||
export const HOST_SLOTTABLE_PART_IDS: ReadonlySet<string> = new Set([
|
||||
"host.recovery",
|
||||
]);
|
||||
|
||||
/** All host-owned parts (used by the part registry and documentation). */
|
||||
export const HOST_PART_IDS: ReadonlySet<string> = new Set([
|
||||
...HOST_CHROME_PART_IDS,
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -35,6 +35,8 @@
|
||||
popover="manual"
|
||||
@keydown.escape="shortcutOpen = false"
|
||||
class="ws-host-recovery"
|
||||
:class="{ 'ws-host-recovery-compact': compact }"
|
||||
:tabindex="compact ? 0 : undefined"
|
||||
data-ws-host-recovery
|
||||
role="region"
|
||||
:aria-label="copy.recovery"
|
||||
@@ -42,12 +44,14 @@
|
||||
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
data-ws-recovery-action="built-in"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>{{ copy.useBuiltIn }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
v-if="pluginLibraryAvailable"
|
||||
data-ws-recovery-action="library"
|
||||
:title="copy.library"
|
||||
@@ -62,6 +66,8 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
import { hostChromeCopy } from "../i18n/host-chrome.js";
|
||||
import {
|
||||
activeHostSlot,
|
||||
hostChromeActiveSkinId,
|
||||
isHostPartHidden,
|
||||
isHostPartVisuallyReachable,
|
||||
isRecoveryShortcut,
|
||||
@@ -74,6 +80,7 @@ import {
|
||||
syncRecoveryPopover,
|
||||
type HostOwnedLayer,
|
||||
} from "../services/host-owned-layer.js";
|
||||
import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js";
|
||||
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
|
||||
import { thirdPartyAllowed } from "../services/instance-authorization.js";
|
||||
|
||||
@@ -94,35 +101,52 @@ const RECOVERY_LAYER_CSS = `
|
||||
max-width: calc(100vw - 24px);
|
||||
padding: 4px 5px 4px 9px;
|
||||
border: 1px solid #9db6b2;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, #ffffff 92%, transparent);
|
||||
color: #31524f;
|
||||
border-radius: var(--ws-recovery-radius, 999px);
|
||||
background: var(--ws-recovery-background, color-mix(in srgb, #ffffff 92%, transparent));
|
||||
color: var(--ws-recovery-foreground, #31524f);
|
||||
font-family: var(--ws-recovery-font, ui-sans-serif, system-ui, sans-serif);
|
||||
font-size: var(--ws-recovery-font-size, 11px);
|
||||
box-shadow: 0 6px 18px #0f2a2626;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.ws-host-recovery:popover-open { display: flex; }
|
||||
.ws-host-recovery-mark { font-size: 12px; line-height: 1; }
|
||||
.ws-host-recovery-mark {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
.ws-host-recovery button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
min-height: var(--ws-recovery-hit, 28px);
|
||||
padding: 4px 9px;
|
||||
border: 1px solid #9db6b2;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #31524f;
|
||||
border-radius: var(--ws-recovery-radius, 999px);
|
||||
background: var(--ws-recovery-background, #fff);
|
||||
color: var(--ws-recovery-foreground, #31524f);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
|
||||
border-color: #b45309;
|
||||
border-color: var(--ws-recovery-accent, #b45309);
|
||||
background: #fff7ed;
|
||||
color: #7c2d12;
|
||||
}
|
||||
.ws-host-recovery button:hover { filter: brightness(.96); }
|
||||
.ws-host-recovery button:focus-visible { outline: 2px solid #4c8f88; outline-offset: 2px; }
|
||||
@media (prefers-reduced-motion: reduce) { .ws-host-recovery button { transition: none; } }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) { gap: 0; padding: 4px; }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-action { display: none; }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-mark {
|
||||
min-width: var(--ws-recovery-hit, 28px);
|
||||
min-height: var(--ws-recovery-hit, 28px);
|
||||
}
|
||||
.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-recovery-accent, #4c8f88); outline-offset: 2px; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ws-host-recovery, .ws-host-recovery button { transition: none !important; }
|
||||
}
|
||||
`;
|
||||
|
||||
const layer: HostOwnedLayer | null = createHostOwnedLayer("recovery", RECOVERY_LAYER_CSS);
|
||||
@@ -148,6 +172,49 @@ const shortcutOpen = ref(false);
|
||||
const recoveryPopover = ref<HTMLElement | null>(null);
|
||||
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
|
||||
|
||||
/**
|
||||
* Optional anchor from the active skin's chrome.json. Only third-party skins
|
||||
* can declare it; the host still owns the capsule and the module falls back to
|
||||
* the default corner whenever the anchor stops being usable.
|
||||
*/
|
||||
const slotConfig = computed(() => activeHostSlot("host.recovery"));
|
||||
const slotMode = ref<"floating" | "slotted">("floating");
|
||||
const compactHold = ref(true);
|
||||
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
watch(hostChromeActiveSkinId, () => {
|
||||
// Keep the full capsule visible for a moment after a skin is activated, so
|
||||
// the entry stays discoverable before it folds into the skin's layout.
|
||||
compactHold.value = true;
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
compactHoldTimer = setTimeout(() => { compactHold.value = false; }, 5000);
|
||||
}, { immediate: true });
|
||||
|
||||
const compact = computed(() => Boolean(slotConfig.value?.compact)
|
||||
&& slotMode.value === "slotted"
|
||||
&& !compactHold.value
|
||||
&& !shortcutOpen.value);
|
||||
|
||||
let slotBinding: HostSlotBinding | undefined;
|
||||
function syncSlotBinding() {
|
||||
slotBinding?.dispose();
|
||||
slotBinding = undefined;
|
||||
const control = recoveryPopover.value;
|
||||
const config = slotConfig.value;
|
||||
if (!control || !config || !layer) {
|
||||
slotMode.value = "floating";
|
||||
return;
|
||||
}
|
||||
slotBinding = bindHostSlot({
|
||||
layer,
|
||||
control,
|
||||
anchor: config.anchor,
|
||||
skinId: hostChromeActiveSkinId.value,
|
||||
align: config.align,
|
||||
onModeChange: change => { slotMode.value = change.mode; },
|
||||
});
|
||||
}
|
||||
|
||||
function syncPopover() {
|
||||
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
|
||||
}
|
||||
@@ -169,7 +236,11 @@ function onKeydown(event: KeyboardEvent) {
|
||||
if (isRecoveryShortcut(event)) {
|
||||
event.preventDefault();
|
||||
shortcutOpen.value = true;
|
||||
void nextTick(() => { syncPopover(); recoveryPopover.value?.querySelector("button")?.focus(); });
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
recoveryPopover.value?.querySelector("button")?.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,7 +249,18 @@ function refreshLauncherReachability() {
|
||||
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
|
||||
}
|
||||
|
||||
watch([recoveryVisible, recoveryPopover], () => { void nextTick(syncPopover); }, { flush: "post" });
|
||||
watch([recoveryVisible, recoveryPopover], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
watch([slotConfig, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
|
||||
|
||||
onMounted(() => {
|
||||
@@ -186,10 +268,15 @@ onMounted(() => {
|
||||
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
|
||||
window.addEventListener("resize", refreshLauncherReachability);
|
||||
window.addEventListener("keydown", onKeydown, true);
|
||||
void nextTick(syncPopover);
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
});
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
if (reachabilityTimer) clearInterval(reachabilityTimer);
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
slotBinding?.dispose();
|
||||
window.removeEventListener("resize", refreshLauncherReachability);
|
||||
window.removeEventListener("keydown", onKeydown, true);
|
||||
layer?.dispose();
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isBundledSkin } from "./host-chrome.js";
|
||||
import { parseSkinChromeDocument } from "../../../src/shared/skin-chrome.js";
|
||||
import {
|
||||
activeHostSlot,
|
||||
isBundledSkin,
|
||||
setHostChromeActiveSkin,
|
||||
setSkinHostChromeParts,
|
||||
} from "./host-chrome.js";
|
||||
import { isHostPartReachable, shouldShowRecovery, type HostPartVisibilitySnapshot } from "./host-chrome-visibility.js";
|
||||
|
||||
const snapshot = (overrides: Partial<HostPartVisibilitySnapshot> = {}): HostPartVisibilitySnapshot => ({
|
||||
@@ -78,3 +84,28 @@ test("the recovery entry is persistent for third-party skins only", () => {
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, thirdPartySkinActive: true }), false);
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, launcherHiddenByConfig: true }), false);
|
||||
});
|
||||
|
||||
test("slot declarations are honoured for third-party skins only", () => {
|
||||
const document = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: { "host.recovery": { anchor: "voice.audio-dock" } },
|
||||
}));
|
||||
setSkinHostChromeParts(document);
|
||||
setHostChromeActiveSkin("community.demo");
|
||||
assert.deepEqual(activeHostSlot("host.recovery"), {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "end",
|
||||
compact: false,
|
||||
});
|
||||
// A part that is not slottable cannot be selected through chrome.json.
|
||||
assert.equal(activeHostSlot("host.permission"), undefined);
|
||||
|
||||
// Bundled/official skins keep the default floating placement.
|
||||
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
|
||||
setHostChromeActiveSkin(id);
|
||||
assert.equal(activeHostSlot("host.recovery"), undefined, String(id));
|
||||
}
|
||||
|
||||
setSkinHostChromeParts(undefined);
|
||||
setHostChromeActiveSkin(undefined);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { computed, readonly, ref, shallowRef } from "vue";
|
||||
import { DECORATIVE_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import { resolveHiddenHostParts, type SkinChromeDocument } from "../../../src/shared/skin-chrome.js";
|
||||
import { DECORATIVE_PART_IDS, HOST_SLOTTABLE_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import { resolveHiddenHostParts, type SkinChromeDocument, type SkinChromeSlot } from "../../../src/shared/skin-chrome.js";
|
||||
import { isHostPartReachable } from "./host-chrome-visibility.js";
|
||||
|
||||
/**
|
||||
@@ -30,6 +30,9 @@ export function setHostChromeActiveSkin(id: string | undefined): void {
|
||||
activeSkin.value = id;
|
||||
}
|
||||
|
||||
/** Read-only view for host chrome that reacts to skin activations. */
|
||||
export const hostChromeActiveSkinId = readonly(activeSkin);
|
||||
|
||||
export function isBundledSkin(id: string | undefined): boolean {
|
||||
return !id || id.startsWith("builtin.") || BUNDLED_SKIN_IDS.has(id);
|
||||
}
|
||||
@@ -60,6 +63,16 @@ export function isHostPartHidden(part: string): boolean {
|
||||
return hiddenParts.value.has(part);
|
||||
}
|
||||
|
||||
/**
|
||||
* Slot declarations are honoured only for an active third-party skin. Bundled
|
||||
* skins, and any skin without a matching `chrome.json#slots` entry, keep the
|
||||
* default floating placement.
|
||||
*/
|
||||
export function activeHostSlot(part: string): SkinChromeSlot | undefined {
|
||||
if (!HOST_SLOTTABLE_PART_IDS.has(part) || !isThirdPartySkinActive()) return undefined;
|
||||
return skinChrome.value?.slots?.[part];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the live DOM to find out whether a host part can actually be used.
|
||||
* Declarative hiding (`v-if`) removes the element entirely; CSS-only hiding
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
INITIAL_SLOT_MODE_STATE,
|
||||
RECOVERY_MIN_ACCENT_CONTRAST,
|
||||
RECOVERY_MIN_FONT_SIZE,
|
||||
RECOVERY_MIN_FOREGROUND_CONTRAST,
|
||||
RECOVERY_MIN_HIT_TARGET,
|
||||
RECOVERY_SIZE_METRICS,
|
||||
computeSlotPlacement,
|
||||
contrastRatio,
|
||||
evaluateSlottedControl,
|
||||
nextSlotModeState,
|
||||
parseCssColor,
|
||||
relativeLuminance,
|
||||
resolveRecoveryTokens,
|
||||
type SlotAnchorSnapshot,
|
||||
} from "./host-slot-placement.js";
|
||||
import type { HostPartRect } from "./host-chrome-visibility.js";
|
||||
|
||||
const rect = (left: number, top: number, width: number, height: number): HostPartRect => ({
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
});
|
||||
|
||||
const anchor = (overrides: Partial<SlotAnchorSnapshot> = {}): SlotAnchorSnapshot => ({
|
||||
rect: rect(100, 100, 200, 40),
|
||||
display: "flex",
|
||||
visibility: "visible",
|
||||
opacity: "1",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const baseEvaluation = {
|
||||
anchor: anchor(),
|
||||
controlRect: rect(180, 105, 120, 30),
|
||||
viewport: { width: 800, height: 600 },
|
||||
minHitTarget: RECOVERY_MIN_HIT_TARGET,
|
||||
hitTestOk: true,
|
||||
};
|
||||
|
||||
test("slot placement aligns inside the anchor and centres vertically", () => {
|
||||
const control = { width: 120, height: 30 };
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport, "start"), { left: 100, top: 105 });
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport, "center"), { left: 140, top: 105 });
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport), { left: 180, top: 105 });
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport, "end"), { left: 180, top: 105 });
|
||||
});
|
||||
|
||||
test("slot placement clamps the control fully inside the viewport", () => {
|
||||
const viewport = { width: 800, height: 600 };
|
||||
const control = { width: 120, height: 30 };
|
||||
// Anchor off the left/top edge: the control stops at the safe inset.
|
||||
assert.deepEqual(computeSlotPlacement(rect(-500, -200, 100, 40), control, viewport, "start"), { left: 4, top: 4 });
|
||||
// Anchor off the right/bottom edge: the control stops before the edge.
|
||||
assert.deepEqual(computeSlotPlacement(rect(900, 700, 100, 40), control, viewport, "end"), { left: 676, top: 566 });
|
||||
// The anchor may be smaller than the control; the control overflows the
|
||||
// anchor but still stays inside the viewport.
|
||||
const tiny = computeSlotPlacement(rect(400, 300, 20, 10), control, viewport, "center");
|
||||
assert.ok(tiny.left >= 4 && tiny.left + control.width <= viewport.width - 4);
|
||||
assert.ok(tiny.top >= 4 && tiny.top + control.height <= viewport.height - 4);
|
||||
});
|
||||
|
||||
test("a usable slotted control passes every check", () => {
|
||||
assert.deepEqual(evaluateSlottedControl(baseEvaluation), { ok: true });
|
||||
});
|
||||
|
||||
test("missing, hidden, tiny and off-screen anchors fall back", () => {
|
||||
assert.deepEqual(evaluateSlottedControl({ ...baseEvaluation, anchor: null }), { ok: false, reason: "anchor-missing" });
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ display: "none" }) }),
|
||||
{ ok: false, reason: "anchor-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ visibility: "hidden" }) }),
|
||||
{ ok: false, reason: "anchor-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ opacity: "0" }) }),
|
||||
{ ok: false, reason: "anchor-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ rect: rect(100, 100, 4, 4) }) }),
|
||||
{ ok: false, reason: "anchor-tiny" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ rect: rect(-500, -500, 100, 40) }) }),
|
||||
{ ok: false, reason: "anchor-offscreen" },
|
||||
);
|
||||
// Only a small fraction of the anchor is on screen.
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ rect: rect(790, 100, 100, 40) }) }),
|
||||
{ ok: false, reason: "anchor-offscreen" },
|
||||
);
|
||||
// A clipped anchor is unusable even when its box looks fine.
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ clipPath: "inset(50%)" }) }),
|
||||
{ ok: false, reason: "anchor-offscreen" },
|
||||
);
|
||||
});
|
||||
|
||||
test("an anchor that is at least half visible can host the control", () => {
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({
|
||||
...baseEvaluation,
|
||||
anchor: anchor({ rect: rect(750, 100, 100, 40) }),
|
||||
controlRect: rect(700, 100, 60, 30),
|
||||
}),
|
||||
{ ok: true },
|
||||
);
|
||||
});
|
||||
|
||||
test("control size, position and hit test are enforced", () => {
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, controlRect: rect(180, 105, 0, 0) }),
|
||||
{ ok: false, reason: "control-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, controlRect: rect(180, 105, 20, 20) }),
|
||||
{ ok: false, reason: "control-too-small" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, controlRect: rect(760, 105, 120, 30) }),
|
||||
{ ok: false, reason: "control-offscreen" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, hitTestOk: false }),
|
||||
{ ok: false, reason: "hit-test" },
|
||||
);
|
||||
});
|
||||
|
||||
test("CSS colours parse to RGB and ignore alpha for contrast", () => {
|
||||
assert.deepEqual(parseCssColor("#1d4f9c"), { r: 29, g: 79, b: 156 });
|
||||
assert.deepEqual(parseCssColor("#fff"), { r: 255, g: 255, b: 255 });
|
||||
assert.deepEqual(parseCssColor("#ffff"), { r: 255, g: 255, b: 255 });
|
||||
assert.deepEqual(parseCssColor("rgb(29, 79, 156)"), { r: 29, g: 79, b: 156 });
|
||||
assert.deepEqual(parseCssColor("rgb(29 79 156 / 50%)"), { r: 29, g: 79, b: 156 });
|
||||
assert.deepEqual(parseCssColor("rgba(255, 0, 0, .4)"), { r: 255, g: 0, b: 0 });
|
||||
assert.deepEqual(parseCssColor("rgb(300, -5, 0)"), { r: 255, g: 0, b: 0 });
|
||||
for (const invalid of ["", "red", "hsl(10, 20%, 30%)", "color(srgb 1 0 0)", "#12345", "rgb(1, 2)"]) {
|
||||
assert.equal(parseCssColor(invalid), null, invalid);
|
||||
}
|
||||
});
|
||||
|
||||
test("WCAG contrast follows the relative-luminance formula", () => {
|
||||
assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0);
|
||||
assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1);
|
||||
assert.equal(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }), 21);
|
||||
assert.equal(contrastRatio({ r: 12, g: 34, b: 56 }, { r: 12, g: 34, b: 56 }), 1);
|
||||
});
|
||||
|
||||
test("skin tokens default to the host palette", () => {
|
||||
const tokens = resolveRecoveryTokens();
|
||||
assert.deepEqual(tokens, {
|
||||
accent: "rgb(180, 83, 9)",
|
||||
background: "rgb(255, 255, 255)",
|
||||
foreground: "rgb(49, 82, 79)",
|
||||
radius: 999,
|
||||
font: "ui-sans-serif, system-ui, sans-serif",
|
||||
size: "small",
|
||||
hitTarget: 28,
|
||||
fontSize: 11,
|
||||
});
|
||||
});
|
||||
|
||||
test("a readable skin palette is kept and translucent backgrounds become opaque", () => {
|
||||
const tokens = resolveRecoveryTokens({
|
||||
accent: "#47dcc4",
|
||||
background: "rgba(9, 19, 23, 0.4)",
|
||||
foreground: "#edf8f5",
|
||||
});
|
||||
assert.equal(tokens.accent, "rgb(71, 220, 196)");
|
||||
assert.equal(tokens.background, "rgb(9, 19, 23)");
|
||||
assert.equal(tokens.foreground, "rgb(237, 248, 245)");
|
||||
});
|
||||
|
||||
test("an unreadable colour group falls back as a whole", () => {
|
||||
const lowForeground = resolveRecoveryTokens({ background: "#777777", foreground: "#888888", accent: "#47dcc4" });
|
||||
assert.equal(lowForeground.background, "rgb(255, 255, 255)");
|
||||
assert.equal(lowForeground.foreground, "rgb(49, 82, 79)");
|
||||
assert.equal(lowForeground.accent, "rgb(180, 83, 9)");
|
||||
|
||||
const lowAccent = resolveRecoveryTokens({ background: "#ffffff", foreground: "#31524f", accent: "#eeeeee" });
|
||||
assert.equal(lowAccent.accent, "rgb(180, 83, 9)");
|
||||
assert.ok(contrastRatio(parseCssColor(lowAccent.accent)!, parseCssColor(lowAccent.background)!) >= RECOVERY_MIN_ACCENT_CONTRAST);
|
||||
assert.ok(contrastRatio(parseCssColor(lowAccent.foreground)!, parseCssColor(lowAccent.background)!) >= RECOVERY_MIN_FOREGROUND_CONTRAST);
|
||||
});
|
||||
|
||||
test("radius, font and size tokens are sanitized and host minimums win", () => {
|
||||
assert.equal(resolveRecoveryTokens({ radius: "12px" }).radius, 12);
|
||||
assert.equal(resolveRecoveryTokens({ radius: "2000px" }).radius, 999);
|
||||
assert.equal(resolveRecoveryTokens({ radius: "-5px" }).radius, 0);
|
||||
assert.equal(resolveRecoveryTokens({ radius: "1em" }).radius, 999);
|
||||
assert.equal(resolveRecoveryTokens({ radius: "12" }).radius, 999);
|
||||
|
||||
assert.equal(
|
||||
resolveRecoveryTokens({ font: 'Tahoma, "Segoe UI", sans-serif' }).font,
|
||||
'Tahoma, "Segoe UI", sans-serif',
|
||||
);
|
||||
for (const font of ["url(https://example.invalid/a.woff2)", "Tahoma; color: red", "x".repeat(121)]) {
|
||||
assert.equal(resolveRecoveryTokens({ font }).font, "ui-sans-serif, system-ui, sans-serif", font);
|
||||
}
|
||||
|
||||
assert.equal(resolveRecoveryTokens({ size: "medium" }).hitTarget, 32);
|
||||
assert.equal(resolveRecoveryTokens({ size: "medium" }).fontSize, 12);
|
||||
assert.equal(resolveRecoveryTokens({ size: "large" }).hitTarget, 36);
|
||||
assert.equal(resolveRecoveryTokens({ size: "large" }).fontSize, 13);
|
||||
assert.equal(resolveRecoveryTokens({ size: "huge" }).size, "small");
|
||||
for (const metrics of Object.values(RECOVERY_SIZE_METRICS)) {
|
||||
assert.ok(metrics.hitTarget >= RECOVERY_MIN_HIT_TARGET);
|
||||
assert.ok(metrics.fontSize >= RECOVERY_MIN_FONT_SIZE);
|
||||
}
|
||||
});
|
||||
|
||||
test("the mode gate does not flap between the anchor and the fallback", () => {
|
||||
let state = INITIAL_SLOT_MODE_STATE;
|
||||
// The first valid check slots immediately, even under the anti-flap rule.
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.deepEqual(state, { slotted: true, validStreak: 0, hasSlotted: true });
|
||||
|
||||
// Any failure returns to the floating position at once.
|
||||
state = nextSlotModeState(state, false);
|
||||
assert.deepEqual(state, { slotted: false, validStreak: 0, hasSlotted: true });
|
||||
|
||||
// A single valid sample is not enough to re-slot.
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.equal(state.slotted, false);
|
||||
assert.equal(state.validStreak, 1);
|
||||
|
||||
// A failure resets the streak.
|
||||
state = nextSlotModeState(state, false);
|
||||
assert.equal(state.validStreak, 0);
|
||||
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.equal(state.slotted, false);
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.equal(state.slotted, true);
|
||||
assert.equal(state.hasSlotted, true);
|
||||
});
|
||||
@@ -0,0 +1,683 @@
|
||||
/**
|
||||
* Runtime placement for trusted host controls that a skin may fold into its
|
||||
* own layout.
|
||||
*
|
||||
* A skin cannot own, style or hide these controls: the control still lives in
|
||||
* the host's closed shadow root and top layer. `chrome.json#slots` only names
|
||||
* an existing `data-ws-part` anchor inside `.ws-skin-root`; this module reads
|
||||
* that anchor, positions the host control over it, and falls back to the
|
||||
* default corner whenever the anchor stops being a safe place to click.
|
||||
*
|
||||
* `isHostPartReachable` stays the single visibility predicate for host parts;
|
||||
* the extra checks here cover only slot-specific geometry (anchor size and
|
||||
* on-screen ratio, control hit target, top-layer hit test).
|
||||
*/
|
||||
|
||||
import type { SkinChromeSlotAlign } from "../../../src/shared/skin-chrome.js";
|
||||
import type { HostOwnedLayer } from "./host-owned-layer.js";
|
||||
import { isHostPartReachable, type HostPartRect } from "./host-chrome-visibility.js";
|
||||
|
||||
export interface SlotViewport {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Small inset so the capsule never touches the viewport edge. */
|
||||
export const HOST_SLOT_VIEWPORT_INSET = 4;
|
||||
/** An anchor narrower or shorter than this cannot host a usable control. */
|
||||
export const HOST_SLOT_MIN_ANCHOR_SIZE = 8;
|
||||
/** At least half of the anchor must be on screen. */
|
||||
export const HOST_SLOT_MIN_VISIBLE_RATIO = 0.5;
|
||||
/** Re-slot only after the anchor stays usable for consecutive checks. */
|
||||
export const HOST_SLOT_REQUIRED_VALID_CHECKS = 2;
|
||||
export const HOST_SLOT_SLOTTED_INTERVAL_MS = 400;
|
||||
export const HOST_SLOT_IDLE_INTERVAL_MS = 1000;
|
||||
|
||||
/**
|
||||
* Place the control inside the anchor rect, vertically centred and aligned on
|
||||
* one horizontal edge. The result is clamped so the whole control stays inside
|
||||
* the viewport; when the anchor is smaller than the control the control may
|
||||
* overflow the anchor, but never the viewport.
|
||||
*/
|
||||
export function computeSlotPlacement(
|
||||
anchor: HostPartRect,
|
||||
control: { width: number; height: number },
|
||||
viewport: SlotViewport,
|
||||
align: SkinChromeSlotAlign = "end",
|
||||
): { left: number; top: number } {
|
||||
const width = Math.max(0, control.width);
|
||||
const height = Math.max(0, control.height);
|
||||
const inset = HOST_SLOT_VIEWPORT_INSET;
|
||||
const desiredLeft = align === "start"
|
||||
? anchor.left
|
||||
: align === "center"
|
||||
? anchor.left + (anchor.width - width) / 2
|
||||
: anchor.right - width;
|
||||
const desiredTop = anchor.top + (anchor.height - height) / 2;
|
||||
const maxLeft = Math.max(inset, viewport.width - inset - width);
|
||||
const maxTop = Math.max(inset, viewport.height - inset - height);
|
||||
return {
|
||||
left: Math.min(Math.max(inset, desiredLeft), maxLeft),
|
||||
top: Math.min(Math.max(inset, desiredTop), maxTop),
|
||||
};
|
||||
}
|
||||
|
||||
export type SlotFailureReason =
|
||||
| "anchor-missing"
|
||||
| "anchor-hidden"
|
||||
| "anchor-tiny"
|
||||
| "anchor-offscreen"
|
||||
| "control-hidden"
|
||||
| "control-too-small"
|
||||
| "control-offscreen"
|
||||
| "hit-test";
|
||||
|
||||
export interface SlotAnchorSnapshot {
|
||||
rect: HostPartRect;
|
||||
display: string;
|
||||
visibility: string;
|
||||
opacity: string;
|
||||
clipPath?: string;
|
||||
clip?: string;
|
||||
}
|
||||
|
||||
export interface SlotEvaluationInput {
|
||||
anchor: SlotAnchorSnapshot | null | undefined;
|
||||
controlRect: HostPartRect;
|
||||
viewport: SlotViewport;
|
||||
/** Host-enforced minimum hit target for the current size tier. */
|
||||
minHitTarget: number;
|
||||
/** `document.elementFromPoint` at the control centre is the host layer. */
|
||||
hitTestOk: boolean;
|
||||
}
|
||||
|
||||
export type SlotEvaluation = { ok: true } | { ok: false; reason: SlotFailureReason };
|
||||
|
||||
function visibleAreaRatio(rect: HostPartRect, viewport: SlotViewport): number {
|
||||
const width = Math.min(rect.right, viewport.width) - Math.max(rect.left, 0);
|
||||
const height = Math.min(rect.bottom, viewport.height) - Math.max(rect.top, 0);
|
||||
const area = rect.width * rect.height;
|
||||
if (!(area > 0) || !(width > 0) || !(height > 0)) return 0;
|
||||
return (width * height) / area;
|
||||
}
|
||||
|
||||
function fullyInsideViewport(rect: HostPartRect, viewport: SlotViewport): boolean {
|
||||
const epsilon = 0.5;
|
||||
return rect.left >= -epsilon
|
||||
&& rect.top >= -epsilon
|
||||
&& rect.right <= viewport.width + epsilon
|
||||
&& rect.bottom <= viewport.height + epsilon;
|
||||
}
|
||||
|
||||
export function evaluateSlottedControl(input: SlotEvaluationInput): SlotEvaluation {
|
||||
const { anchor, controlRect, viewport, minHitTarget, hitTestOk } = input;
|
||||
if (!anchor) return { ok: false, reason: "anchor-missing" };
|
||||
if (anchor.display === "none" || anchor.visibility === "hidden" || anchor.visibility === "collapse") {
|
||||
return { ok: false, reason: "anchor-hidden" };
|
||||
}
|
||||
const opacity = Number.parseFloat(anchor.opacity);
|
||||
if (Number.isFinite(opacity) && opacity <= 0.01) return { ok: false, reason: "anchor-hidden" };
|
||||
if (anchor.rect.width < HOST_SLOT_MIN_ANCHOR_SIZE || anchor.rect.height < HOST_SLOT_MIN_ANCHOR_SIZE) {
|
||||
return { ok: false, reason: "anchor-tiny" };
|
||||
}
|
||||
// The anchor itself does not have to accept pointer events: the control is
|
||||
// hit-tested separately, above it.
|
||||
if (!isHostPartReachable({
|
||||
display: anchor.display,
|
||||
visibility: anchor.visibility,
|
||||
opacity: anchor.opacity,
|
||||
pointerEvents: "auto",
|
||||
clipPath: anchor.clipPath,
|
||||
clip: anchor.clip,
|
||||
rect: anchor.rect,
|
||||
viewport,
|
||||
})) {
|
||||
return { ok: false, reason: "anchor-offscreen" };
|
||||
}
|
||||
if (visibleAreaRatio(anchor.rect, viewport) < HOST_SLOT_MIN_VISIBLE_RATIO) {
|
||||
return { ok: false, reason: "anchor-offscreen" };
|
||||
}
|
||||
|
||||
if (!(controlRect.width > 0) || !(controlRect.height > 0)) return { ok: false, reason: "control-hidden" };
|
||||
if (controlRect.width < minHitTarget || controlRect.height < minHitTarget) {
|
||||
return { ok: false, reason: "control-too-small" };
|
||||
}
|
||||
if (!fullyInsideViewport(controlRect, viewport)) return { ok: false, reason: "control-offscreen" };
|
||||
if (!hitTestOk) return { ok: false, reason: "hit-test" };
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export interface SlotModeState {
|
||||
slotted: boolean;
|
||||
/** Consecutive valid checks since the last fallback. */
|
||||
validStreak: number;
|
||||
/** Once true, re-slotting needs the anti-flap streak. */
|
||||
hasSlotted: boolean;
|
||||
}
|
||||
|
||||
export const INITIAL_SLOT_MODE_STATE: SlotModeState = { slotted: false, validStreak: 0, hasSlotted: false };
|
||||
|
||||
/**
|
||||
* The first valid check slots immediately (no initial flash); after any
|
||||
* fallback, the anchor must stay valid for `requiredValidChecks` checks so a
|
||||
* flickering CSS animation cannot make the capsule jump every frame.
|
||||
*/
|
||||
export function nextSlotModeState(
|
||||
current: SlotModeState,
|
||||
ok: boolean,
|
||||
requiredValidChecks = HOST_SLOT_REQUIRED_VALID_CHECKS,
|
||||
): SlotModeState {
|
||||
if (!ok) {
|
||||
return { slotted: false, validStreak: 0, hasSlotted: current.hasSlotted };
|
||||
}
|
||||
if (current.slotted) return { ...current, validStreak: 0 };
|
||||
const validStreak = current.validStreak + 1;
|
||||
const slotted = !current.hasSlotted || validStreak >= Math.max(1, requiredValidChecks);
|
||||
return {
|
||||
slotted,
|
||||
validStreak: slotted ? 0 : validStreak,
|
||||
hasSlotted: current.hasSlotted || slotted,
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* Style tokens
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
export type RecoverySizeTier = "small" | "medium" | "large";
|
||||
|
||||
export interface RecoverySizeMetrics {
|
||||
/** Host-enforced minimum button hit target in CSS pixels. */
|
||||
readonly hitTarget: number;
|
||||
/** Host-enforced minimum font size in CSS pixels. */
|
||||
readonly fontSize: number;
|
||||
}
|
||||
|
||||
export const RECOVERY_MIN_HIT_TARGET = 28;
|
||||
export const RECOVERY_MIN_FONT_SIZE = 11;
|
||||
export const RECOVERY_MIN_FOREGROUND_CONTRAST = 4.5;
|
||||
export const RECOVERY_MIN_ACCENT_CONTRAST = 3;
|
||||
|
||||
/** Host-controlled metrics; a skin can choose a tier, never a smaller size. */
|
||||
export const RECOVERY_SIZE_METRICS: Readonly<Record<RecoverySizeTier, RecoverySizeMetrics>> = {
|
||||
small: { hitTarget: RECOVERY_MIN_HIT_TARGET, fontSize: RECOVERY_MIN_FONT_SIZE },
|
||||
medium: { hitTarget: 32, fontSize: 12 },
|
||||
large: { hitTarget: 36, fontSize: 13 },
|
||||
};
|
||||
|
||||
export interface RecoveryRawTokens {
|
||||
/** Computed-style colour values; unresolved CSS values are rejected. */
|
||||
accent?: string;
|
||||
background?: string;
|
||||
foreground?: string;
|
||||
radius?: string;
|
||||
font?: string;
|
||||
size?: string;
|
||||
}
|
||||
|
||||
export interface RecoveryTokens {
|
||||
accent: string;
|
||||
background: string;
|
||||
foreground: string;
|
||||
radius: number;
|
||||
font: string;
|
||||
size: RecoverySizeTier;
|
||||
hitTarget: number;
|
||||
fontSize: number;
|
||||
}
|
||||
|
||||
export interface RgbColor {
|
||||
r: number;
|
||||
g: number;
|
||||
b: number;
|
||||
}
|
||||
|
||||
/** CSS custom properties a skin declares on the anchor or an ancestor. */
|
||||
export const RECOVERY_SKIN_TOKEN_PROPERTIES = {
|
||||
accent: "--skin-recovery-accent",
|
||||
background: "--skin-recovery-background",
|
||||
foreground: "--skin-recovery-foreground",
|
||||
radius: "--skin-recovery-radius",
|
||||
font: "--skin-recovery-font",
|
||||
size: "--skin-recovery-size",
|
||||
} as const;
|
||||
|
||||
/** Host-owned variables set inside the closed shadow root. */
|
||||
export const RECOVERY_APPLIED_VARIABLES = {
|
||||
accent: "--ws-recovery-accent",
|
||||
background: "--ws-recovery-background",
|
||||
foreground: "--ws-recovery-foreground",
|
||||
radius: "--ws-recovery-radius",
|
||||
font: "--ws-recovery-font",
|
||||
hitTarget: "--ws-recovery-hit",
|
||||
fontSize: "--ws-recovery-font-size",
|
||||
} as const;
|
||||
|
||||
const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 };
|
||||
const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 };
|
||||
const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 };
|
||||
const DEFAULT_RADIUS = 999;
|
||||
const DEFAULT_FONT = "ui-sans-serif, system-ui, sans-serif";
|
||||
const MAX_RADIUS = 999;
|
||||
const MAX_FONT_LENGTH = 120;
|
||||
const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/;
|
||||
|
||||
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
|
||||
export function parseCssColor(value: string | undefined | null): RgbColor | null {
|
||||
if (!value) return null;
|
||||
const text = value.trim().toLowerCase();
|
||||
const hex = /^#([0-9a-f]{3,8})$/.exec(text);
|
||||
if (hex) {
|
||||
const digits = hex[1];
|
||||
if (digits.length === 3 || digits.length === 4) {
|
||||
return {
|
||||
r: Number.parseInt(digits[0] + digits[0], 16),
|
||||
g: Number.parseInt(digits[1] + digits[1], 16),
|
||||
b: Number.parseInt(digits[2] + digits[2], 16),
|
||||
};
|
||||
}
|
||||
if (digits.length === 6 || digits.length === 8) {
|
||||
return {
|
||||
r: Number.parseInt(digits.slice(0, 2), 16),
|
||||
g: Number.parseInt(digits.slice(2, 4), 16),
|
||||
b: Number.parseInt(digits.slice(4, 6), 16),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const fn = /^rgba?\(([^()]*)\)$/.exec(text);
|
||||
if (!fn) return null;
|
||||
const parts = fn[1].replace(/\//g, " ").split(/[\s,]+/).filter(Boolean);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const channels: number[] = [];
|
||||
for (const part of parts.slice(0, 3)) {
|
||||
const percent = part.endsWith("%");
|
||||
const parsed = Number.parseFloat(part);
|
||||
if (!Number.isFinite(parsed)) return null;
|
||||
const channel = percent ? parsed * 2.55 : parsed;
|
||||
channels.push(Math.round(Math.min(255, Math.max(0, channel))));
|
||||
}
|
||||
return { r: channels[0], g: channels[1], b: channels[2] };
|
||||
}
|
||||
|
||||
export function formatRgb(color: RgbColor): string {
|
||||
return `rgb(${color.r}, ${color.g}, ${color.b})`;
|
||||
}
|
||||
|
||||
/** WCAG 2.x relative luminance, 0 (black) to 1 (white). */
|
||||
export function relativeLuminance(color: RgbColor): number {
|
||||
const channel = (value: number): number => {
|
||||
const normalized = Math.min(255, Math.max(0, value)) / 255;
|
||||
return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
|
||||
}
|
||||
|
||||
export function contrastRatio(first: RgbColor, second: RgbColor): number {
|
||||
const lighter = Math.max(relativeLuminance(first), relativeLuminance(second));
|
||||
const darker = Math.min(relativeLuminance(first), relativeLuminance(second));
|
||||
return (lighter + 0.05) / (darker + 0.05);
|
||||
}
|
||||
|
||||
export function isRecoverySizeTier(value: unknown): value is RecoverySizeTier {
|
||||
return value === "small" || value === "medium" || value === "large";
|
||||
}
|
||||
|
||||
function sanitizeRadius(value: string | undefined): number {
|
||||
if (!value) return DEFAULT_RADIUS;
|
||||
const match = /^(-?\d+(?:\.\d+)?)px$/i.exec(value.trim());
|
||||
if (!match) return DEFAULT_RADIUS;
|
||||
const radius = Number.parseFloat(match[1]);
|
||||
return Number.isFinite(radius) ? Math.min(MAX_RADIUS, Math.max(0, radius)) : DEFAULT_RADIUS;
|
||||
}
|
||||
|
||||
function sanitizeFont(value: string | undefined): string {
|
||||
if (!value) return DEFAULT_FONT;
|
||||
const font = value.trim().replace(/\s+/g, " ");
|
||||
if (!font || font.length > MAX_FONT_LENGTH || !FONT_FAMILY_PATTERN.test(font) || !/[A-Za-z0-9]/.test(font)) {
|
||||
return DEFAULT_FONT;
|
||||
}
|
||||
return font;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize skin-provided tokens. Colours are all-or-nothing: a readable
|
||||
* foreground/background pair and a visible accent keep the skin palette;
|
||||
* otherwise the whole colour group reverts to the host palette so a skin can
|
||||
* never make the recovery action unreadable.
|
||||
*/
|
||||
export function resolveRecoveryTokens(raw: RecoveryRawTokens = {}): RecoveryTokens {
|
||||
const accent = parseCssColor(raw.accent) ?? DEFAULT_ACCENT;
|
||||
const background = parseCssColor(raw.background) ?? DEFAULT_BACKGROUND;
|
||||
const foreground = parseCssColor(raw.foreground) ?? DEFAULT_FOREGROUND;
|
||||
const readable = contrastRatio(foreground, background) >= RECOVERY_MIN_FOREGROUND_CONTRAST
|
||||
&& contrastRatio(accent, background) >= RECOVERY_MIN_ACCENT_CONTRAST;
|
||||
const palette = readable ? { accent, background, foreground } : {
|
||||
accent: DEFAULT_ACCENT,
|
||||
background: DEFAULT_BACKGROUND,
|
||||
foreground: DEFAULT_FOREGROUND,
|
||||
};
|
||||
const sizeValue = raw.size?.trim();
|
||||
const size = isRecoverySizeTier(sizeValue) ? sizeValue : "small";
|
||||
const metrics = RECOVERY_SIZE_METRICS[size];
|
||||
return {
|
||||
accent: formatRgb(palette.accent),
|
||||
background: formatRgb(palette.background),
|
||||
foreground: formatRgb(palette.foreground),
|
||||
radius: sanitizeRadius(raw.radius),
|
||||
font: sanitizeFont(raw.font),
|
||||
size,
|
||||
hitTarget: metrics.hitTarget,
|
||||
fontSize: metrics.fontSize,
|
||||
};
|
||||
}
|
||||
|
||||
/** Apply (or clear) host-owned variables on the control inside the shadow root. */
|
||||
export function applyRecoveryTokens(control: HTMLElement, tokens: RecoveryTokens | null): void {
|
||||
const style = control.style;
|
||||
if (!tokens) {
|
||||
for (const property of Object.values(RECOVERY_APPLIED_VARIABLES)) style.removeProperty(property);
|
||||
return;
|
||||
}
|
||||
style.setProperty(RECOVERY_APPLIED_VARIABLES.accent, tokens.accent);
|
||||
style.setProperty(RECOVERY_APPLIED_VARIABLES.background, tokens.background);
|
||||
style.setProperty(RECOVERY_APPLIED_VARIABLES.foreground, tokens.foreground);
|
||||
style.setProperty(RECOVERY_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
|
||||
style.setProperty(RECOVERY_APPLIED_VARIABLES.font, tokens.font);
|
||||
style.setProperty(RECOVERY_APPLIED_VARIABLES.hitTarget, `${tokens.hitTarget}px`);
|
||||
style.setProperty(RECOVERY_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* DOM binding
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
function rectOf(rect: DOMRect | HostPartRect): HostPartRect {
|
||||
return {
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
right: rect.right,
|
||||
bottom: rect.bottom,
|
||||
};
|
||||
}
|
||||
|
||||
function isVisibleAnchor(element: HTMLElement): boolean {
|
||||
const view = element.ownerDocument.defaultView;
|
||||
if (!view) return false;
|
||||
const style = view.getComputedStyle(element);
|
||||
return isHostPartReachable({
|
||||
display: style.display,
|
||||
visibility: style.visibility,
|
||||
opacity: style.opacity,
|
||||
pointerEvents: "auto",
|
||||
clipPath: style.clipPath,
|
||||
clip: style.clip,
|
||||
rect: rectOf(element.getBoundingClientRect()),
|
||||
viewport: { width: view.innerWidth, height: view.innerHeight },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the first visible `[data-ws-part="<anchor>"]` inside the active
|
||||
* skin's DOM. Plugin and surface hosts render inside `.ws-skin-root` too
|
||||
* (runtime plugins may Teleport to a `data-ws-skin-mount` slot, but every
|
||||
* mount slot is part of the skin root), so a skin cannot point the recovery
|
||||
* control at host chrome outside its own subtree.
|
||||
*/
|
||||
export function resolveSkinAnchor(
|
||||
anchor: string,
|
||||
doc: Document = document,
|
||||
skinId?: string,
|
||||
): HTMLElement | null {
|
||||
const selector = `[data-ws-part="${anchor}"]`;
|
||||
for (const root of doc.querySelectorAll(".ws-skin-root")) {
|
||||
if (skinId && root.getAttribute("data-ws-skin") !== skinId) continue;
|
||||
for (const element of root.querySelectorAll<HTMLElement>(selector)) {
|
||||
if (isVisibleAnchor(element)) return element;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The active skin's root element; the token source while no anchor is usable. */
|
||||
export function findSkinRoot(skinId: string | undefined, doc: Document = document): Element | null {
|
||||
for (const root of doc.querySelectorAll(".ws-skin-root")) {
|
||||
if (!skinId || root.getAttribute("data-ws-skin") === skinId) return root;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface HostSlotModeChange {
|
||||
mode: "slotted" | "floating";
|
||||
reason?: SlotFailureReason;
|
||||
}
|
||||
|
||||
export interface HostSlotBindingOptions {
|
||||
layer: HostOwnedLayer;
|
||||
control: HTMLElement;
|
||||
anchor: string;
|
||||
/** Restricts anchor resolution and token fallback to this active skin. */
|
||||
skinId?: string;
|
||||
align?: SkinChromeSlotAlign;
|
||||
resolveAnchor?: (anchor: string) => HTMLElement | null;
|
||||
onModeChange?: (change: HostSlotModeChange) => void;
|
||||
}
|
||||
|
||||
export interface HostSlotBinding {
|
||||
revalidate(): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
const NOOP_BINDING: HostSlotBinding = {
|
||||
revalidate: () => undefined,
|
||||
dispose: () => undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* Position the controlled host element over its anchor, re-check it on layout
|
||||
* changes and return it to the default floating position on any failure.
|
||||
* Tokens are read from the anchor's computed style and applied inside the
|
||||
* closed shadow root; the skin never writes to the control itself.
|
||||
*/
|
||||
export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
const { layer, control, anchor: anchorName, onModeChange } = options;
|
||||
const align = options.align ?? "end";
|
||||
const doc = control.ownerDocument;
|
||||
const view = doc.defaultView;
|
||||
if (!view) return NOOP_BINDING;
|
||||
const win = view;
|
||||
const resolveAnchor = options.resolveAnchor
|
||||
?? ((name: string) => resolveSkinAnchor(name, doc, options.skinId));
|
||||
|
||||
let state = INITIAL_SLOT_MODE_STATE;
|
||||
let lastReason: SlotFailureReason | undefined;
|
||||
let currentAnchor: HTMLElement | null = null;
|
||||
let observer: ResizeObserver | null = null;
|
||||
let probe: HTMLElement | null = null;
|
||||
let frame: number | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false;
|
||||
|
||||
const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback);
|
||||
const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
|
||||
|
||||
function ensureProbe(): HTMLElement | null {
|
||||
if (probe) return probe;
|
||||
probe = doc.createElement("span");
|
||||
probe.setAttribute("aria-hidden", "true");
|
||||
probe.style.cssText = "position:absolute;left:-9999px;top:0;width:0;height:0;visibility:hidden;pointer-events:none;";
|
||||
layer.shadow.append(probe);
|
||||
return probe;
|
||||
}
|
||||
|
||||
/** Resolve a CSS colour through the browser, inside the closed shadow root. */
|
||||
function probeColor(raw: string | undefined): string | undefined {
|
||||
if (!raw) return undefined;
|
||||
const element = ensureProbe();
|
||||
if (!element) return undefined;
|
||||
element.style.color = "rgb(1, 2, 3)";
|
||||
element.style.color = raw;
|
||||
const computed = win.getComputedStyle(element).color;
|
||||
return computed === "rgb(1, 2, 3)" ? undefined : computed;
|
||||
}
|
||||
|
||||
function readTokens(source: Element | null): RecoveryTokens {
|
||||
if (!source) return resolveRecoveryTokens();
|
||||
const style = win.getComputedStyle(source);
|
||||
const read = (property: string): string | undefined => style.getPropertyValue(property).trim() || undefined;
|
||||
return resolveRecoveryTokens({
|
||||
accent: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.accent)),
|
||||
background: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.background)),
|
||||
foreground: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.foreground)),
|
||||
radius: read(RECOVERY_SKIN_TOKEN_PROPERTIES.radius),
|
||||
font: read(RECOVERY_SKIN_TOKEN_PROPERTIES.font),
|
||||
size: read(RECOVERY_SKIN_TOKEN_PROPERTIES.size),
|
||||
});
|
||||
}
|
||||
|
||||
function clearPlacement(): void {
|
||||
control.style.removeProperty("position");
|
||||
control.style.removeProperty("left");
|
||||
control.style.removeProperty("top");
|
||||
control.style.removeProperty("right");
|
||||
control.style.removeProperty("bottom");
|
||||
}
|
||||
|
||||
function applyPlacement(left: number, top: number): void {
|
||||
control.style.position = "fixed";
|
||||
control.style.left = `${left}px`;
|
||||
control.style.top = `${top}px`;
|
||||
control.style.right = "auto";
|
||||
control.style.bottom = "auto";
|
||||
}
|
||||
|
||||
function hitTestAt(left: number, top: number, size: { width: number; height: number }): boolean {
|
||||
if (typeof doc.elementFromPoint !== "function") return true;
|
||||
// A hit inside the closed shadow root retargets to the layer host, which is
|
||||
// exactly what `elementFromPoint` returns for the top-layer capsule.
|
||||
const hit = doc.elementFromPoint(left + size.width / 2, top + size.height / 2);
|
||||
return hit === layer.host;
|
||||
}
|
||||
|
||||
function observe(anchorElement: HTMLElement | null): void {
|
||||
if (currentAnchor === anchorElement) return;
|
||||
currentAnchor = anchorElement;
|
||||
if (!observer && typeof ResizeObserver !== "undefined") {
|
||||
observer = new ResizeObserver(() => schedule());
|
||||
}
|
||||
if (!observer) return;
|
||||
observer.disconnect();
|
||||
observer.observe(control);
|
||||
if (anchorElement) observer.observe(anchorElement);
|
||||
}
|
||||
|
||||
function evaluate(): void {
|
||||
if (disposed) return;
|
||||
const anchorElement = resolveAnchor(anchorName);
|
||||
observe(anchorElement);
|
||||
// The fallback keeps the skin palette: read tokens from the anchor, or
|
||||
// from the skin root when the anchor is missing or hidden.
|
||||
const tokenSource = anchorElement
|
||||
?? (options.skinId ? findSkinRoot(options.skinId, doc) : null);
|
||||
const tokens = readTokens(tokenSource);
|
||||
applyRecoveryTokens(control, tokenSource ? tokens : null);
|
||||
|
||||
const controlBox = control.getBoundingClientRect();
|
||||
const viewport: SlotViewport = { width: win.innerWidth, height: win.innerHeight };
|
||||
let anchorSnapshot: SlotAnchorSnapshot | null = null;
|
||||
if (anchorElement) {
|
||||
const style = win.getComputedStyle(anchorElement);
|
||||
anchorSnapshot = {
|
||||
rect: rectOf(anchorElement.getBoundingClientRect()),
|
||||
display: style.display,
|
||||
visibility: style.visibility,
|
||||
opacity: style.opacity,
|
||||
clipPath: style.clipPath,
|
||||
clip: style.clip,
|
||||
};
|
||||
}
|
||||
|
||||
const canPlace = Boolean(anchorSnapshot) && controlBox.width > 0 && controlBox.height > 0;
|
||||
const placement = canPlace && anchorSnapshot
|
||||
? computeSlotPlacement(anchorSnapshot.rect, controlBox, viewport, align)
|
||||
: null;
|
||||
const intendedRect: HostPartRect = placement
|
||||
? {
|
||||
width: controlBox.width,
|
||||
height: controlBox.height,
|
||||
left: placement.left,
|
||||
top: placement.top,
|
||||
right: placement.left + controlBox.width,
|
||||
bottom: placement.top + controlBox.height,
|
||||
}
|
||||
: rectOf(controlBox);
|
||||
// Move first, then hit-test: the capsule has to actually occupy the
|
||||
// intended point before `elementFromPoint` can see it. The move and a
|
||||
// failed revert happen in one task, so nothing paints in between.
|
||||
if (placement) applyPlacement(placement.left, placement.top);
|
||||
const evaluation = evaluateSlottedControl({
|
||||
anchor: anchorSnapshot,
|
||||
controlRect: intendedRect,
|
||||
viewport,
|
||||
minHitTarget: tokens?.hitTarget ?? RECOVERY_SIZE_METRICS.small.hitTarget,
|
||||
hitTestOk: placement
|
||||
? hitTestAt(placement.left, placement.top, { width: controlBox.width, height: controlBox.height })
|
||||
: false,
|
||||
});
|
||||
|
||||
const next = nextSlotModeState(state, evaluation.ok);
|
||||
const changed = next.slotted !== state.slotted;
|
||||
state = next;
|
||||
if (state.slotted && placement) applyPlacement(placement.left, placement.top);
|
||||
else clearPlacement();
|
||||
|
||||
const reason = evaluation.ok ? undefined : evaluation.reason;
|
||||
const mode = state.slotted ? "slotted" : "floating";
|
||||
if (changed || (mode === "floating" && reason !== lastReason)) {
|
||||
lastReason = reason;
|
||||
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
|
||||
}
|
||||
}
|
||||
|
||||
function schedule(): void {
|
||||
if (disposed || frame !== undefined) return;
|
||||
frame = requestFrame(() => {
|
||||
frame = undefined;
|
||||
evaluate();
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleTick(): void {
|
||||
if (disposed) return;
|
||||
timer = setTimeout(() => {
|
||||
if (disposed) return;
|
||||
evaluate();
|
||||
scheduleTick();
|
||||
}, state.slotted ? HOST_SLOT_SLOTTED_INTERVAL_MS : HOST_SLOT_IDLE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
win.addEventListener("resize", schedule, { passive: true });
|
||||
win.addEventListener("scroll", schedule, { capture: true, passive: true });
|
||||
evaluate();
|
||||
scheduleTick();
|
||||
|
||||
return {
|
||||
revalidate: evaluate,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
if (frame !== undefined) cancelFrame(frame);
|
||||
if (timer) clearTimeout(timer);
|
||||
win.removeEventListener("resize", schedule);
|
||||
win.removeEventListener("scroll", schedule, { capture: true });
|
||||
clearPlacement();
|
||||
applyRecoveryTokens(control, null);
|
||||
probe?.remove();
|
||||
probe = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
+2
@@ -78,7 +78,9 @@ if (!layer) {
|
||||
popoverOpen: popover.matches(":popover-open"),
|
||||
// elementFromPoint retargets nodes inside a closed shadow root to its
|
||||
// host, so either the inner button or the host proves the top layer won.
|
||||
// Slot placement compares strictly against the host; record that too.
|
||||
topLayerHit: hit === layer.host || hit === button || layer.container.contains(hit),
|
||||
hitIsLayerHost: hit === layer.host,
|
||||
hostileCovered: hit === dock,
|
||||
visible: computed.display !== "none" && computed.visibility !== "hidden"
|
||||
&& Number(computed.opacity) > 0.01 && computed.pointerEvents !== "none",
|
||||
|
||||
@@ -1,226 +1,239 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { compileSkinCss } from "../../src/shared/skin-css.ts";
|
||||
|
||||
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
|
||||
const webRoot = fileURLToPath(new URL("../", import.meta.url));
|
||||
const CHROME = [process.env.WEBSPEAK_TEST_CHROME, "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"]
|
||||
.find((candidate) => candidate && existsSync(candidate));
|
||||
|
||||
const compileHostile = (css) => compileSkinCss(css, "community.hostile-fixture", {}, 3).css;
|
||||
|
||||
/**
|
||||
* Hostile rules that the compiler still accepts (they are legitimate page /
|
||||
* themable-host styling) but that must not be able to hide, cover, or disable
|
||||
* the recovery entry. `fullscreen-audio-dock` is the case the previous review
|
||||
* reproduced: a public part promoted to a `z-index: 2147483647` fullscreen layer.
|
||||
*/
|
||||
const scenarios = [
|
||||
{
|
||||
name: "fullscreen-audio-dock",
|
||||
css: compileHostile('[data-ws-part="voice.audio-dock"] { position: fixed; inset: 0; z-index: 2147483647; }'),
|
||||
},
|
||||
{
|
||||
name: "opacity-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { opacity: 0; }'),
|
||||
},
|
||||
{
|
||||
name: "filter-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { filter: opacity(0); }'),
|
||||
},
|
||||
{
|
||||
name: "display-none-overlay",
|
||||
css: compileHostile('[data-ws-part="host.plugins.overlay"] { display: none !important; }'),
|
||||
},
|
||||
{
|
||||
name: "pointer-events-none",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"], [data-ws-part="host.plugins.overlay"] { pointer-events: none !important; }'),
|
||||
},
|
||||
{
|
||||
// Decorative host chrome may legitimately be a fixed, viewport-sized,
|
||||
// max-stacking decoration. Recovery lives in a closed-shadow top layer and
|
||||
// must still win the hit test.
|
||||
name: "decorative-watermark-overlay",
|
||||
css: compileHostile(`
|
||||
@keyframes drift { from { transform: translateX(0); } to { transform: translateX(12px); } }
|
||||
[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; background: #123; animation: drift 3s ease-in-out infinite alternate; }
|
||||
`),
|
||||
},
|
||||
];
|
||||
|
||||
test("host chrome renders recovery and authorization in a closed-shadow top layer", async () => {
|
||||
const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin, recoveryNotice] = await Promise.all([
|
||||
read("../src/components/HostChrome.vue"),
|
||||
read("../src/components/InstanceAuthorization.vue"),
|
||||
read("../src/services/host-owned-layer.ts"),
|
||||
read("../src/services/host-chrome.ts"),
|
||||
read("../src/composables/usePublicSkin.ts"),
|
||||
read("../src/components/SkinLoadRecoveryNotice.vue"),
|
||||
]);
|
||||
|
||||
// Recovery: closed shadow root + manual popover + no skin hook.
|
||||
assert.match(hostChrome, /createHostOwnedLayer\("recovery"/);
|
||||
assert.match(hostChrome, /popover="manual"/);
|
||||
assert.match(hostChrome, /data-ws-recovery-action="built-in"/);
|
||||
assert.match(hostChrome, /requestBuiltInSkin/);
|
||||
assert.match(hostChrome, /isThirdPartySkinActive/);
|
||||
// The shortcut runs in the capture phase so a plugin/skin capture listener
|
||||
// cannot swallow it with preventDefault().
|
||||
assert.match(hostChrome, /addEventListener\("keydown", onKeydown, true\)/);
|
||||
assert.match(hostChrome, /removeEventListener\("keydown", onKeydown, true\)/);
|
||||
// Escape closes the popover from inside its closed shadow root.
|
||||
assert.match(hostChrome, /@keydown\.escape="shortcutOpen = false"/);
|
||||
assert.doesNotMatch(hostChrome, /event\.defaultPrevented \|\| event\.repeat/);
|
||||
assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/);
|
||||
|
||||
// Authorization: showModal() inside the same host-owned mechanism.
|
||||
assert.match(authorization, /createHostOwnedLayer\('authorization'/);
|
||||
assert.match(authorization, /showModal\(\)/);
|
||||
assert.doesNotMatch(authorization, /data-ws-part="host\.permission"/);
|
||||
|
||||
// The load-failure banner is trusted UI too: closed shadow layer, stylesheet
|
||||
// inside the boundary, no document-level scoped stylesheet to override.
|
||||
assert.match(recoveryNotice, /createHostOwnedLayer\("skin-load"/);
|
||||
assert.match(recoveryNotice, /data-ws-part="app\.skin-load-recovery"/);
|
||||
assert.doesNotMatch(recoveryNotice, /<style scoped>/);
|
||||
|
||||
// The layer itself: closed shadow root, no data-ws-part, fixed fallback.
|
||||
assert.match(ownedLayer, /attachShadow\(\{ mode: "closed" \}\)/);
|
||||
assert.match(ownedLayer, /data-ws-host-layer/);
|
||||
assert.doesNotMatch(ownedLayer, /setAttribute\("data-ws-part"/);
|
||||
|
||||
// The reset path is independent of the skinnable plugin overlay.
|
||||
assert.match(hostChromeService, /requestBuiltInSkin/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive/);
|
||||
assert.match(publicSkin, /hostBuiltInSkinRequests/);
|
||||
assert.match(publicSkin, /switchToBuiltIn/);
|
||||
|
||||
// Defense in depth: there is still no compiler route to a "host.recovery"
|
||||
// selector, even if a node ever regressed to carrying that attribute.
|
||||
for (const selector of ['[data-ws-part="host.recovery"]', '[data-ws-part="host.permission"]']) {
|
||||
assert.throws(() => compileSkinCss(`${selector} { display: none; }`, "community.evil", {}, 3), /Trusted or unknown host part/);
|
||||
}
|
||||
|
||||
// A leading `:root` must not reach body-level siblings (the host layer in the
|
||||
// preview/fixture topology) through `+` / `~`.
|
||||
for (const selector of [
|
||||
":root ~ [data-ws-host-layer]",
|
||||
":root ~ *",
|
||||
":root + [data-ws-host-layer]",
|
||||
":root:hover ~ *",
|
||||
]) {
|
||||
assert.throws(
|
||||
() => compileSkinCss(`${selector} { display: none !important; }`, "community.evil", {}, 3),
|
||||
/sibling combinator after :root/,
|
||||
selector,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("the themed preview keeps recovery in its own hookless top layer", async () => {
|
||||
const [preview, bridge] = await Promise.all([
|
||||
read("../host-chrome-preview.html"),
|
||||
read("../src/services/host-chrome-preview.ts"),
|
||||
]);
|
||||
assert.match(bridge, /resolveHiddenHostParts/);
|
||||
assert.match(preview, /host-chrome-preview\.ts/);
|
||||
assert.match(preview, /resolveHiddenHostParts\(chromeData, \[\]\)/);
|
||||
assert.match(preview, /hiddenParts\.has\(part\)/);
|
||||
assert.match(preview, /isHostPartReachable\(/);
|
||||
assert.match(preview, /launcherReachable/);
|
||||
assert.match(preview, /recoveryLayer\.remove\(\)/);
|
||||
assert.match(preview, /popover="manual"/);
|
||||
assert.doesNotMatch(preview, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(preview, /const watermarkHidden = getComputedStyle/);
|
||||
});
|
||||
|
||||
test("the public-skin composable opts in only through chrome.json#visibleParts", async () => {
|
||||
const usePublicSkin = await read("../src/composables/usePublicSkin.ts");
|
||||
assert.match(usePublicSkin, /setSkinHostChromeParts\(skin\?\.chromeData\)/);
|
||||
// Sniffing the combined stylesheet would match the importer-generated
|
||||
// hiddenParts/icon CSS and leak decorations for hiddenParts-only packs.
|
||||
assert.doesNotMatch(usePublicSkin, /\.test\(skin\.css\)/);
|
||||
});
|
||||
|
||||
async function dumpDom(url) {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(CHROME, [
|
||||
"--headless=new",
|
||||
"--no-sandbox",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--hide-scrollbars",
|
||||
"--dump-dom",
|
||||
url,
|
||||
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
reject(new Error(`Headless Chrome timed out.\n${stderr.slice(-2000)}`));
|
||||
}, 60000);
|
||||
child.on("error", (error) => { clearTimeout(timer); reject(error); });
|
||||
child.on("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (!stdout.includes('id="result"')) {
|
||||
reject(new Error(`Headless Chrome exited ${code} without a result.\n${stderr.slice(-2000)}`));
|
||||
return;
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("recovery stays visible and clickable under hostile compiled skins", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
|
||||
const server = await createServer({
|
||||
root: webRoot,
|
||||
configFile: path.join(webRoot, "vite.config.ts"),
|
||||
logLevel: "silent",
|
||||
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
|
||||
});
|
||||
t.after(() => server.close());
|
||||
await server.listen();
|
||||
const address = server.httpServer?.address();
|
||||
const port = address && typeof address === "object" ? address.port : 0;
|
||||
assert.ok(port, "Vite did not expose a listening port");
|
||||
|
||||
const hash = encodeURIComponent(JSON.stringify(scenarios));
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-chrome-recovery.html#${hash}`);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1]);
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
assert.equal(payload.results.length, scenarios.length);
|
||||
|
||||
assert.ok(payload.authorization, "the authorization dialog was not mounted");
|
||||
assert.equal(payload.authorization.modalOpen, true, "the authorization dialog is not modal / in the top layer");
|
||||
assert.equal(payload.authorization.topLayerHit, true, "the hostile layer covers the authorization dialog");
|
||||
assert.equal(payload.authorization.hostileCovered, false, "the hostile layer received the authorization hit test");
|
||||
assert.equal(payload.authorization.layerOutsideSkinRoot, true, "the authorization dialog was rendered inside .ws-skin-root");
|
||||
assert.equal(payload.authorization.sized, true, "the authorization dialog has no layout box");
|
||||
|
||||
// The pre-Popover / rejected-promotion fallback must actually lay the capsule
|
||||
// out: a closed [popover] is display:none !important until the attribute goes.
|
||||
assert.ok(payload.popoverFallback, "the fixture did not exercise the popover fallback");
|
||||
assert.equal(payload.popoverFallback.display, "flex", "the fallback capsule is not displayed");
|
||||
assert.equal(payload.popoverFallback.popoverAttribute, false, "the popover attribute still forces display:none");
|
||||
assert.equal(payload.popoverFallback.visible, true, "the fallback capsule has no layout box");
|
||||
|
||||
for (const result of payload.results) {
|
||||
assert.equal(result.popoverOpen, true, `${result.name}: recovery popover is not in the top layer`);
|
||||
assert.equal(result.topLayerHit, true, `${result.name}: recovery is covered by the hostile layer`);
|
||||
assert.equal(result.hostileCovered, false, `${result.name}: the hostile layer received the hit test`);
|
||||
assert.equal(result.visible, true, `${result.name}: recovery is visually hidden or non-interactive`);
|
||||
assert.equal(result.clicked, true, `${result.name}: clicking "use built-in skin" did not reach the handler`);
|
||||
assert.equal(result.layerOutsideSkinRoot, true, `${result.name}: recovery was rendered inside .ws-skin-root`);
|
||||
}
|
||||
});
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { compileSkinCss } from "../../src/shared/skin-css.ts";
|
||||
|
||||
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
|
||||
const webRoot = fileURLToPath(new URL("../", import.meta.url));
|
||||
const CHROME = [process.env.WEBSPEAK_TEST_CHROME, "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"]
|
||||
.find((candidate) => candidate && existsSync(candidate));
|
||||
|
||||
const compileHostile = (css) => compileSkinCss(css, "community.hostile-fixture", {}, 3).css;
|
||||
|
||||
/**
|
||||
* Hostile rules that the compiler still accepts (they are legitimate page /
|
||||
* themable-host styling) but that must not be able to hide, cover, or disable
|
||||
* the recovery entry. `fullscreen-audio-dock` is the case the previous review
|
||||
* reproduced: a public part promoted to a `z-index: 2147483647` fullscreen layer.
|
||||
*/
|
||||
const scenarios = [
|
||||
{
|
||||
name: "fullscreen-audio-dock",
|
||||
css: compileHostile('[data-ws-part="voice.audio-dock"] { position: fixed; inset: 0; z-index: 2147483647; }'),
|
||||
},
|
||||
{
|
||||
name: "opacity-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { opacity: 0; }'),
|
||||
},
|
||||
{
|
||||
name: "filter-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { filter: opacity(0); }'),
|
||||
},
|
||||
{
|
||||
name: "display-none-overlay",
|
||||
css: compileHostile('[data-ws-part="host.plugins.overlay"] { display: none !important; }'),
|
||||
},
|
||||
{
|
||||
name: "pointer-events-none",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"], [data-ws-part="host.plugins.overlay"] { pointer-events: none !important; }'),
|
||||
},
|
||||
{
|
||||
// Decorative host chrome may legitimately be a fixed, viewport-sized,
|
||||
// max-stacking decoration. Recovery lives in a closed-shadow top layer and
|
||||
// must still win the hit test.
|
||||
name: "decorative-watermark-overlay",
|
||||
css: compileHostile(`
|
||||
@keyframes drift { from { transform: translateX(0); } to { transform: translateX(12px); } }
|
||||
[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; background: #123; animation: drift 3s ease-in-out infinite alternate; }
|
||||
`),
|
||||
},
|
||||
];
|
||||
|
||||
test("host chrome renders recovery and authorization in a closed-shadow top layer", async () => {
|
||||
const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin, recoveryNotice, slotPlacement] = await Promise.all([
|
||||
read("../src/components/HostChrome.vue"),
|
||||
read("../src/components/InstanceAuthorization.vue"),
|
||||
read("../src/services/host-owned-layer.ts"),
|
||||
read("../src/services/host-chrome.ts"),
|
||||
read("../src/composables/usePublicSkin.ts"),
|
||||
read("../src/components/SkinLoadRecoveryNotice.vue"),
|
||||
read("../src/services/host-slot-placement.ts"),
|
||||
]);
|
||||
|
||||
// Recovery: closed shadow root + manual popover + no skin hook.
|
||||
assert.match(hostChrome, /createHostOwnedLayer\("recovery"/);
|
||||
assert.match(hostChrome, /popover="manual"/);
|
||||
assert.match(hostChrome, /data-ws-recovery-action="built-in"/);
|
||||
assert.match(hostChrome, /requestBuiltInSkin/);
|
||||
assert.match(hostChrome, /isThirdPartySkinActive/);
|
||||
// The shortcut runs in the capture phase so a plugin/skin capture listener
|
||||
// cannot swallow it with preventDefault().
|
||||
assert.match(hostChrome, /addEventListener\("keydown", onKeydown, true\)/);
|
||||
assert.match(hostChrome, /removeEventListener\("keydown", onKeydown, true\)/);
|
||||
// Escape closes the popover from inside its closed shadow root.
|
||||
assert.match(hostChrome, /@keydown\.escape="shortcutOpen = false"/);
|
||||
assert.doesNotMatch(hostChrome, /event\.defaultPrevented \|\| event\.repeat/);
|
||||
assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/);
|
||||
// Slots are a declarative anchor, not a skin hook: the host still binds the
|
||||
// capsule itself and switches back to the fixed position at runtime.
|
||||
assert.match(hostChrome, /activeHostSlot\("host\.recovery"\)/);
|
||||
assert.match(hostChrome, /bindHostSlot\(/);
|
||||
assert.match(hostChrome, /onModeChange/);
|
||||
assert.match(slotPlacement, /querySelectorAll\("\.ws-skin-root"\)/);
|
||||
assert.match(slotPlacement, /isHostPartReachable\(/);
|
||||
assert.match(slotPlacement, /evaluateSlottedControl/);
|
||||
assert.match(hostChromeService, /export function activeHostSlot/);
|
||||
assert.match(hostChromeService, /HOST_SLOTTABLE_PART_IDS\.has\(part\)/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive\(\)/);
|
||||
|
||||
// Authorization: showModal() inside the same host-owned mechanism.
|
||||
assert.match(authorization, /createHostOwnedLayer\('authorization'/);
|
||||
assert.match(authorization, /showModal\(\)/);
|
||||
assert.doesNotMatch(authorization, /data-ws-part="host\.permission"/);
|
||||
|
||||
// The load-failure banner is trusted UI too: closed shadow layer, stylesheet
|
||||
// inside the boundary, no document-level scoped stylesheet to override.
|
||||
assert.match(recoveryNotice, /createHostOwnedLayer\("skin-load"/);
|
||||
assert.match(recoveryNotice, /data-ws-part="app\.skin-load-recovery"/);
|
||||
assert.doesNotMatch(recoveryNotice, /<style scoped>/);
|
||||
|
||||
// The layer itself: closed shadow root, no data-ws-part, fixed fallback.
|
||||
assert.match(ownedLayer, /attachShadow\(\{ mode: "closed" \}\)/);
|
||||
assert.match(ownedLayer, /data-ws-host-layer/);
|
||||
assert.doesNotMatch(ownedLayer, /setAttribute\("data-ws-part"/);
|
||||
|
||||
// The reset path is independent of the skinnable plugin overlay.
|
||||
assert.match(hostChromeService, /requestBuiltInSkin/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive/);
|
||||
assert.match(publicSkin, /hostBuiltInSkinRequests/);
|
||||
assert.match(publicSkin, /switchToBuiltIn/);
|
||||
|
||||
// Defense in depth: there is still no compiler route to a "host.recovery"
|
||||
// selector, even if a node ever regressed to carrying that attribute.
|
||||
for (const selector of ['[data-ws-part="host.recovery"]', '[data-ws-part="host.permission"]']) {
|
||||
assert.throws(() => compileSkinCss(`${selector} { display: none; }`, "community.evil", {}, 3), /Trusted or unknown host part/);
|
||||
}
|
||||
|
||||
// A leading `:root` must not reach body-level siblings (the host layer in the
|
||||
// preview/fixture topology) through `+` / `~`.
|
||||
for (const selector of [
|
||||
":root ~ [data-ws-host-layer]",
|
||||
":root ~ *",
|
||||
":root + [data-ws-host-layer]",
|
||||
":root:hover ~ *",
|
||||
]) {
|
||||
assert.throws(
|
||||
() => compileSkinCss(`${selector} { display: none !important; }`, "community.evil", {}, 3),
|
||||
/sibling combinator after :root/,
|
||||
selector,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("the themed preview keeps recovery in its own hookless top layer", async () => {
|
||||
const [preview, bridge] = await Promise.all([
|
||||
read("../host-chrome-preview.html"),
|
||||
read("../src/services/host-chrome-preview.ts"),
|
||||
]);
|
||||
assert.match(bridge, /resolveHiddenHostParts/);
|
||||
assert.match(preview, /host-chrome-preview\.ts/);
|
||||
assert.match(preview, /resolveHiddenHostParts\(chromeData, \[\]\)/);
|
||||
assert.match(preview, /hiddenParts\.has\(part\)/);
|
||||
assert.match(preview, /isHostPartReachable\(/);
|
||||
assert.match(preview, /launcherReachable/);
|
||||
assert.match(preview, /recoveryLayer\.remove\(\)/);
|
||||
assert.match(preview, /popover="manual"/);
|
||||
assert.doesNotMatch(preview, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(preview, /const watermarkHidden = getComputedStyle/);
|
||||
});
|
||||
|
||||
test("the public-skin composable opts in only through chrome.json#visibleParts", async () => {
|
||||
const usePublicSkin = await read("../src/composables/usePublicSkin.ts");
|
||||
assert.match(usePublicSkin, /setSkinHostChromeParts\(skin\?\.chromeData\)/);
|
||||
// Sniffing the combined stylesheet would match the importer-generated
|
||||
// hiddenParts/icon CSS and leak decorations for hiddenParts-only packs.
|
||||
assert.doesNotMatch(usePublicSkin, /\.test\(skin\.css\)/);
|
||||
});
|
||||
|
||||
async function dumpDom(url) {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(CHROME, [
|
||||
"--headless=new",
|
||||
"--no-sandbox",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--hide-scrollbars",
|
||||
"--dump-dom",
|
||||
url,
|
||||
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
reject(new Error(`Headless Chrome timed out.\n${stderr.slice(-2000)}`));
|
||||
}, 60000);
|
||||
child.on("error", (error) => { clearTimeout(timer); reject(error); });
|
||||
child.on("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (!stdout.includes('id="result"')) {
|
||||
reject(new Error(`Headless Chrome exited ${code} without a result.\n${stderr.slice(-2000)}`));
|
||||
return;
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("recovery stays visible and clickable under hostile compiled skins", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
|
||||
const server = await createServer({
|
||||
root: webRoot,
|
||||
configFile: path.join(webRoot, "vite.config.ts"),
|
||||
logLevel: "silent",
|
||||
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
|
||||
});
|
||||
t.after(() => server.close());
|
||||
await server.listen();
|
||||
const address = server.httpServer?.address();
|
||||
const port = address && typeof address === "object" ? address.port : 0;
|
||||
assert.ok(port, "Vite did not expose a listening port");
|
||||
|
||||
const hash = encodeURIComponent(JSON.stringify(scenarios));
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-chrome-recovery.html#${hash}`);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1]);
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
assert.equal(payload.results.length, scenarios.length);
|
||||
|
||||
assert.ok(payload.authorization, "the authorization dialog was not mounted");
|
||||
assert.equal(payload.authorization.modalOpen, true, "the authorization dialog is not modal / in the top layer");
|
||||
assert.equal(payload.authorization.topLayerHit, true, "the hostile layer covers the authorization dialog");
|
||||
assert.equal(payload.authorization.hostileCovered, false, "the hostile layer received the authorization hit test");
|
||||
assert.equal(payload.authorization.layerOutsideSkinRoot, true, "the authorization dialog was rendered inside .ws-skin-root");
|
||||
assert.equal(payload.authorization.sized, true, "the authorization dialog has no layout box");
|
||||
|
||||
// The pre-Popover / rejected-promotion fallback must actually lay the capsule
|
||||
// out: a closed [popover] is display:none !important until the attribute goes.
|
||||
assert.ok(payload.popoverFallback, "the fixture did not exercise the popover fallback");
|
||||
assert.equal(payload.popoverFallback.display, "flex", "the fallback capsule is not displayed");
|
||||
assert.equal(payload.popoverFallback.popoverAttribute, false, "the popover attribute still forces display:none");
|
||||
assert.equal(payload.popoverFallback.visible, true, "the fallback capsule has no layout box");
|
||||
|
||||
for (const result of payload.results) {
|
||||
assert.equal(result.popoverOpen, true, `${result.name}: recovery popover is not in the top layer`);
|
||||
assert.equal(result.topLayerHit, true, `${result.name}: recovery is covered by the hostile layer`);
|
||||
assert.equal(result.hitIsLayerHost, true, `${result.name}: elementFromPoint did not retarget the closed shadow root to the layer host`);
|
||||
assert.equal(result.hostileCovered, false, `${result.name}: the hostile layer received the hit test`);
|
||||
assert.equal(result.visible, true, `${result.name}: recovery is visually hidden or non-interactive`);
|
||||
assert.equal(result.clicked, true, `${result.name}: clicking "use built-in skin" did not reach the handler`);
|
||||
assert.equal(result.layerOutsideSkinRoot, true, `${result.name}: recovery was rendered inside .ws-skin-root`);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user