feat(skin): dock recovery as host-owned toolbar buttons

Add chrome.json slot mode "toolbar" with grouped and per-action recovery buttons, page-specific anchor candidates and sanitized toolbar style tokens. Keep the floating capsule as the bad-anchor fallback, hide the duplicate plugin launcher, and preserve legacy capsule slots. Document the full contract, add a minimal toolbar example package, and cover the new behavior in unit and browser tests.
This commit is contained in:
OddTurtleHead committed 2026-11-26 23:06:43 +08:00
1 parent 9a12e2ee7b
commit 881354e283
33 files changed
+2016 -113

No files matched your search

@@ -25,6 +25,7 @@ When a WebSpeak checkout is unavailable, read the [published skin guide](https:/
- Use component schema v3 and set `minAppVersion` to at least `0.3.2` when using `voice.plugin-launcher`. Place it once in the voice surface, inside a visible slot. Set `options.pluginPresentation` to `drawer-side` for a sidebar, `drawer-below` for a header button, or `dialog` for the default library. The built-in Day, Night and ILLUSIA skins use the header drawer. The KAAK and Discord examples use the sidebar drawer.
- Style `voice.plugin-launcher`, `voice.plugin-drawer` and `voice.plugin-drawer.app` through the published parts. WebSpeak owns app availability, pinning, authorization and the app window. Layouts without a usable mount can fall back to the host library. In a connected, authorized voice session verify that the launcher mounts in the intended slot, that the drawer stays within desktop and narrow viewports, and that both pinned and unpinned apps open. For KAAK, verify the rail itself and check the package version served by the instance if the launcher still floats.
- For a compact rail, `home.social-links` accepts `options.communityLinks: false` to keep the admin entry and hide community links. The admin console uses host styling. Use `chrome.json#visibleParts` only for documented host decorations. Confirm that the host-owned recovery action remains usable after applying the skin.
- To fold recovery into a skin top bar, declare `chrome.json#slots` with `"mode": "toolbar"` (one grouped entry) or the independent `host.recovery.built-in` / `host.recovery.library` keys. Supply page-specific anchor candidates and `--skin-recovery-toolbar-*` / `--skin-host-toolbar-*` tokens; never target the host toolbar DOM. The host keeps the button labels, click handlers, minimum hit target and floating-capsule fallback, and hides the ordinary plugin launcher so the library has one entry. See [Host chrome toolbar example](../../../docs/examples/HOST-CHROME-TOOLBAR.md).
- Test changes to the public home and voice surfaces with the same released archive. Check cold load for a theme flash, long translations for clipping, and live/shared media for artwork layering. Use a real voice session for interaction claims.
## Automatic distribution PR
+1 -1
View File
@@ -308,7 +308,7 @@ Disable and save the relay configuration to remove the relay option from the wel
Skins own appearance, layout and their attached widgets. Administrators install, enable and choose the default skin. Authors use the public contract without changing WebSpeak source code.
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) · [Host chrome toolbar example](./examples/HOST-CHROME-TOOLBAR.md)
### Functional plugins `.wplugin`
+1 -1
View File
@@ -329,7 +329,7 @@ relay.example.com {
皮肤包负责外观、布局及其附属小组件。管理员可安装、启用和设置默认皮肤;开发时遵循公开接口,无需修改 WebSpeak 源码。
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) · [宿主顶栏 toolbar 示例](./examples/HOST-CHROME-TOOLBAR.md)
### 功能插件 `.wplugin`
+104 -12
View File
@@ -26,6 +26,8 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
宿主外壳与恢复入口的 toolbar 停靠见 [Host Chrome Toolbar 示例](examples/HOST-CHROME-TOOLBAR.md):它用最小包演示 `mode: "toolbar"`、按页候选锚点、工具栏令牌、应用库去重和坏锚点回退,不包含任何真实服务器或成员数据。
## 使用与发布
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
@@ -406,7 +408,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`(可经 `chrome.json#slots` 停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 以胶囊或 `mode: "toolbar"` 的宿主按钮停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 以及 `--skin-recovery-toolbar-*` / `--skin-host-toolbar-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`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,15 +455,15 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
### 恢复入口与授权对话框:结构上不可被皮肤触及
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局:
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局,或声明 `mode: "toolbar"` 后以无胶囊壳的宿主按钮并入皮肤顶栏(见下文「工具栏模式」):
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`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点,或用 `mode: "toolbar"` 改成宿主顶栏按钮);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;无论胶囊是停靠、浮动还是被 `mode: "toolbar"` 替换,快捷键都会临时隐藏工具栏并显示完整胶囊。它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
@@ -469,7 +471,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复入口停靠在皮肤界面里,而不是固定盖在左下角。默认仍是带胶囊壳的恢复胶囊;显式写 `mode: "toolbar"` 时改为无胶囊壳的宿主按钮,可直接并入皮肤顶栏。两种形态都是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它们的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
```json
"slots": {
@@ -479,10 +481,11 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
| 字段 | 规则 |
| --- | --- |
| 键名 | 目前只接受 `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` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 |
| 键名 | `host.recovery` 表示整组恢复入口(胶囊或 toolbar 组合);`host.recovery.built-in` 与 `host.recovery.library` 表示两个独立按钮,只接受 toolbar 形态。同一份 `chrome.json` 只能二选一:声明了 `host.recovery` 就不能再声明独立按钮键,反之亦然。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称,或 1–8 个候选名称组成的数组(按页面/组件变体排列,重复项自动去重);宿主按顺序取第一个可见匹配,因此同一份声明可同时覆盖首页和语音页。每个候选名最长 240 字符,不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;控件在锚点矩形内按此水平对齐,并垂直居中。 |
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。仅胶囊模式可用;`mode: "toolbar"` 与 `compact: true` 同时出现会被拒绝。 |
| `mode` | 可选,`"capsule"` 或 `"toolbar"`。`host.recovery` 省略时保持历史默认 `"capsule"`(旧皮肤无需改动);`host.recovery.built-in` / `host.recovery.library` 省略时为 `"toolbar"`,且显式写 `"capsule"` 会被拒绝。模式必须显式声明,宿主不会从 `compact` 或其他字段推断。 |
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
@@ -490,11 +493,11 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
- 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` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊或 toolbar 按钮位于顶层,会挡住它下面的一切,因此宿主还会检查控件的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s(期间若默认角落盖住了控件,最多再挪开一次,之后保持不动);判断某个控件是否被盖住时会“看穿”短暂出现的提示条(`app.toast`)和另一个宿主浮动控件,提示条暂时挡住的控件仍按存在计算,不会因此把那个角落误判为空闲;同一页面内,当前位置不遮挡时不会为了回到默认角落而移动(默认角落“看起来空”可能只是被模态对话框的遮罩或提示条暂时挡住);进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,并在默认角落和当前位置都空闲(鼠标也不在那里)时回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。这些胶囊令牌也是 toolbar 颜色的最终回退;toolbar 的圆角、内边距、高度和阴影使用下一节自己的默认值,不会继承胶囊的 999px 圆角或浮动阴影。
| 令牌 | 规则 |
| --- | --- |
@@ -512,6 +515,74 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
#### 工具栏模式:把恢复按钮并进皮肤顶栏(`mode: "toolbar"`)
默认的恢复入口是带胶囊壳的浮动/停靠胶囊。若皮肤顶栏已有自己的按钮风格,可以在 `chrome.json` 中显式声明 `mode: "toolbar"`,让宿主在锚点位置绘制**无胶囊壳的真实宿主按钮**。按钮仍由宿主创建、标注、聚焦和点击,位于闭合 Shadow DOM 的顶层;皮肤只提供锚点和 `--skin-recovery-toolbar-*` 令牌,不能替换文字、图标、顺序、点击处理或取得 DOM。`.ws-host-toolbar`、`data-ws-host-recovery-toolbar` 与 `data-ws-recovery-action` 都不是公开钩子,皮肤选择器引用它们会被拒绝。
两种声明方式互斥,同一份 `chrome.json` 只能选一种:
**组合式**(两个动作共用一个锚点,并排成一组,顺序为先「使用内置皮肤」、后「应用库」):
```json
"slots": {
"host.recovery": {
"mode": "toolbar",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
```
**独立式**(每个动作有自己的锚点,可放在顶栏两侧或不同部件上):
```json
"slots": {
"host.recovery.built-in": {
"anchor": ["home.header-tools", "voice.header-actions"],
"align": "end"
},
"host.recovery.library": {
"anchor": ["home.header-tools", "voice.header-actions"],
"align": "start"
}
}
```
上面只是示意:两个独立按钮若使用同一锚点,应选不同的 `align` 或不同锚点,否则会互相覆盖。
规则:
- `mode` 省略时,`host.recovery` 仍是 `capsule`,旧皮肤行为不变;独立按钮键省略时是 `toolbar`,显式写 `capsule` 会被拒绝。模式必须显式声明,宿主不会从 `compact` 或其他字段推断。
- `compact` 只适用于胶囊;toolbar 配 `compact` 会被拒绝。toolbar 永远显示完整文字按钮,不会折叠成 ◈。
- 组合式下「应用库」按钮只在应用库可用(已连接且插件会话就绪)时渲染;「使用内置皮肤」始终渲染。
- 独立式下每个动作独立停靠:一个锚点失效只把该动作放回浮动胶囊,另一个仍留在工具栏;两个都失效时显示完整浮动胶囊。toolbar 模式下的胶囊永不折叠,因为它是兜底入口而不是设计目标。
- 回退、抗抖动和复查节奏与胶囊相同:锚点失效立即回退;恢复后需连续 2 次检查通过才重新停靠;停靠时约 400 ms 复查,浮动时约 1 s。
- 锚点候选数组按顺序取第一个可见项;页面切换、皮肤重载或锚点显隐后会重新解析,不要求重新绑定。
- 快捷键 `Ctrl+Alt+Shift+R` / `⌘+⌥+⇧+R` 会隐藏工具栏并召唤完整胶囊;关闭(Escape 或焦点离开)后,锚点仍有效的 toolbar 自动恢复。快捷键仍在捕获阶段处理。
- 按钮的最小命中高度、可见文字、焦点环和指针/键盘操作都由宿主保证;皮肤不能把 toolbar 变成图标按钮、空白按钮或零尺寸按钮。
**应用库去重**:只要皮肤声明了 toolbar 形式的恢复入口(组合式的 `host.recovery`,或独立式的 `host.recovery.library`),并且应用库可用,宿主就把工具栏里的「应用库」按钮当作该页唯一的应用库入口,并隐藏普通的 `host.plugins.launcher`。即使锚点失效、入口退回浮动胶囊,启动器仍保持隐藏(胶囊继续提供应用库按钮),避免同一页出现两个入口;应用库不可用时启动器照常显示,工具栏也不渲染该按钮。这个去重只影响 toolbar 声明,不改变普通胶囊皮肤或内置皮肤。
**工具栏令牌**:皮肤在皮肤根、锚点或锚点祖先上声明下列普通变量;宿主从每个按钮当前锚点的计算样式读取、校验,再写入闭合 Shadow DOM。每个 `--skin-recovery-toolbar-*` 都有全局回退 `--skin-host-toolbar-*`,前者优先。组合式和独立式按钮共用同一组变量名;由于值按锚点继承,不同页面或不同锚点可以给同一变量不同的值。
| 令牌 | 默认与规则 |
| --- | --- |
| `--skin-recovery-toolbar-background` | 按钮背景。省略时沿用已解析的胶囊底色(`--skin-recovery-background` / `--skin-host-background` / 宿主白色)。alpha 视为 1,宿主强制不透明。 |
| `--skin-recovery-toolbar-foreground` | 文字色。与背景的对比度必须 ≥ 4.5;整组颜色不可读时,背景和文字一起回退到已解析的胶囊配色,而不是只改一项。 |
| `--skin-recovery-toolbar-border` | 边框色。与背景的对比度必须 ≥ 3,否则使用已解析的胶囊边框。 |
| `--skin-recovery-toolbar-radius` | 圆角,px 长度,限制 0–24,默认 6;胶囊的 999px 不会带入 toolbar。 |
| `--skin-recovery-toolbar-font` | 字体族列表,规则与胶囊相同:只接受已安装字体或通用族名,皮肤 `@font-face`(包括 `ws-` 前缀)整项忽略。 |
| `--skin-recovery-toolbar-font-size` | 字号,px,默认沿用当前尺寸档位的宿主字号(≥ 11/12/13 px),限制 11–20 px;不能低于宿主下限。 |
| `--skin-recovery-toolbar-padding` | 一个或两个 px 值(`上下 左右`,或一个值表示四边相同),默认 `6px 12px`,每个方向限制 0–48 px。 |
| `--skin-recovery-toolbar-height` | 最小高度,px,默认当前尺寸档位的最小命中高度(28/32/36 px),限制不低于该值且不超过 72 px。 |
| `--skin-recovery-toolbar-shadow` | `none` 或单个简单 `box-shadow`(2–4 个 px 偏移/尺寸加一个颜色,最长 160 字符),默认 `none`。`url()`、`var()`、多个阴影和额外声明一律忽略为 `none`,胶囊阴影不会带入。 |
无效、透明或不可读的颜色、越界的字号/高度/内边距、皮肤字体和非法阴影都只会回退到可见的宿主默认值,不会隐藏按钮。toolbar 文字由宿主按当前界面语言本地化,长文本换行而不是裁掉;`prefers-reduced-motion` 下同样没有过渡。
**旧 slots 兼容**:旧包里的 `{ "anchor": ..., "align": ..., "compact": ... }` 没有 `mode`,仍按胶囊停靠,行为不变;`chrome.json` 的其它字段(`visibleParts`、`hiddenParts`、`icons`)不受影响。只有显式写 `mode: "toolbar"` 才会切换形态。
**不影响其它宿主控件**:工具栏令牌只作用于恢复按钮。授权对话框(`--skin-permission-*`)和皮肤加载失败横幅(`--skin-load-recovery-*`)继续使用各自令牌与默认外观;本节的变量不会改变它们。
#### 受保护控件的主题化
28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
@@ -628,7 +699,28 @@ 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.*` 或可信宿主部件的锚点会被拒绝。 |
| `slots` | 可选,最多 8 项;键名只能是 `host.recovery`(整组)或 `host.recovery.built-in` / `host.recovery.library`(独立 toolbar 按钮),两种写法互斥。值只能包含 `anchor`、`align`、`compact`、`mode`;`anchor` 可以是单个部件名或最多 8 个候选名的数组。详见上文「将恢复入口停靠到皮肤布局」与「工具栏模式」。未知键、指向 `host.*` 或可信宿主部件的锚点、`toolbar` 配 `compact` 都会被拒绝。 |
工具栏形态只需在 `host.recovery` 上写 `"mode": "toolbar"`(两个按钮共用一个锚点):
```json
"slots": {
"host.recovery": {
"mode": "toolbar",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
```
也可以改用独立按钮键,让两个动作各自停靠:
```json
"slots": {
"host.recovery.built-in": { "anchor": ["home.header-tools", "voice.header-actions"], "align": "end" },
"host.recovery.library": { "anchor": ["home.header-tools", "voice.header-actions"], "align": "start" }
}
```
图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。
+51
View File
@@ -0,0 +1,51 @@
# Host chrome toolbar example
A minimal schema v3 open skin that docks the trusted recovery entry into the page header as host-owned buttons instead of the floating capsule shell. It is the smallest reference for `chrome.json` `mode: "toolbar"`, page-specific anchor candidates, toolbar style tokens, application-library de-duplication and the floating-capsule fallback.
- Source: [host-chrome-toolbar](./host-chrome-toolbar/)
- Importable package: [host-chrome-toolbar.wskin](./host-chrome-toolbar.wskin)
- Shared component and permission rules: [skin development guide](../SKIN_DEVELOPMENT.md)
- Host chrome and toolbar contract: [skin development guide](../SKIN_DEVELOPMENT.md) (see the `chrome.json#slots` and toolbar-mode sections)
## Package layout
```text
host-chrome-toolbar/
manifest.json # schema v3, author WebSpeak Community
chrome.json # one grouped toolbar slot with a home/voice anchor list
skin.css # page theme, toolbar tokens and header space reservation
```
`skin.css` uses only public `data-ws-part` hooks and sets `--skin-host-toolbar-*` / `--skin-recovery-toolbar-*` variables. It never targets the host toolbar DOM, the recovery capsule, the authorization dialog or the load-failure banner.
## What the declaration does
```json
{
"schemaVersion": 1,
"slots": {
"host.recovery": {
"mode": "toolbar",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
}
```
- `mode: "toolbar"` asks the host to render two plain host buttons (use built-in skin, application library) without the capsule shell.
- The anchor list covers both pages; the host picks the first visible one and re-resolves it after a page switch. A missing or hidden anchor returns the complete, visible floating capsule.
- While the library is available, the host hides the ordinary application-library launcher so the page keeps exactly one library entry. The fallback capsule keeps that entry when the anchor fails.
- The host owns the labels, click handlers, focus behaviour, minimum hit target and shortcut handling. The skin only supplies anchor and token values.
- Old slots without `mode` keep the capsule presentation; this example opts in explicitly.
## Trying it
1. Build or import [host-chrome-toolbar.wskin](./host-chrome-toolbar.wskin) in a local WebSpeak instance.
2. Allow the third-party skin when the host asks.
3. Connect to **Demo Server**, join **Demo Lobby**, and check the header as **Demo User**.
4. Confirm the two host buttons appear at the end of the home and voice headers, use the dark toolbar palette, and open the built-in-skin and application-library actions.
5. Remove or hide the anchor in the page inspector; the complete floating capsule should appear at a corner. Restore the anchor; the toolbar should re-dock after the anti-flap check.
6. Press `Ctrl+Alt+Shift+R` (`⌘+⌥+⇧+R` on macOS); the toolbar hides, the complete capsule appears and focuses its first button. Press Escape to return to the toolbar.
The example contains no server addresses, member names, chat contents or other real instance data. Public descriptions use only the Demo Server / Demo Lobby / Demo User placeholders.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,10 @@
{
"schemaVersion": 1,
"slots": {
"host.recovery": {
"mode": "toolbar",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
}
@@ -0,0 +1,13 @@
{
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.host-chrome-toolbar",
"name": "Host Chrome Toolbar",
"version": "1.0.0",
"author": "WebSpeak Community",
"license": "AGPL-3.0-only",
"description": "Minimal open skin that docks the trusted recovery actions as host-owned toolbar buttons.",
"entry": "skin.css",
"chrome": "chrome.json",
"minAppVersion": "0.3.2"
}
@@ -0,0 +1,96 @@
/* Host chrome toolbar demo — v3 open skin (schemaVersion 3).
The only host integration is chrome.json: the trusted recovery entry is
declared as `mode: "toolbar"` and docked into the page header. The skin
supplies anchors and tokens; the host still owns the buttons and handlers.
Selectors stay inside :root, [data-ws-page] and [data-ws-part]. */
:root {
--skin-demo-surface: #13263d;
--skin-demo-foreground: #eef7ff;
--skin-demo-border: #3a628c;
--skin-demo-accent: #47dcc4;
/* Host-owned recovery buttons (toolbar mode). Every value is validated by
the host; invalid or unreadable values fall back to a visible button. */
--skin-host-toolbar-background: #13263d;
--skin-host-toolbar-foreground: #eef7ff;
--skin-host-toolbar-border: #3a628c;
--skin-host-toolbar-radius: 8px;
--skin-host-toolbar-font: Tahoma, "Segoe UI", sans-serif;
--skin-host-toolbar-font-size: 12px;
--skin-host-toolbar-padding: 7px 14px;
--skin-host-toolbar-height: 34px;
--skin-host-toolbar-shadow: none;
/* The floating capsule is the fallback when an anchor disappears. Keep the
same palette so a failed toolbar does not turn into a white popup. */
--skin-recovery-background: #13263d;
--skin-recovery-foreground: #eef7ff;
--skin-recovery-border: #3a628c;
--skin-recovery-accent: #47dcc4;
}
[data-ws-page] {
color-scheme: dark;
color: #e8f0f8;
background: #09131f;
font-family: Tahoma, "Segoe UI", "Microsoft YaHei", sans-serif;
}
[data-ws-part="home.header"],
[data-ws-part="voice.header"] {
background: linear-gradient(180deg, #12253c, #0d1a2b);
border-bottom: 1px solid #2a4a6a;
color: #e8f0f8;
}
/* Voice page can carry a slightly darker value on its own anchor; the host
reads tokens from the anchor that actually docked the button. */
[data-ws-part="voice.header"] {
--skin-recovery-toolbar-background: #0e2236;
--skin-recovery-toolbar-foreground: #f4fbff;
--skin-recovery-toolbar-border: #4f7fb0;
}
/* Reserve the right edge of the top bar for the host-owned toolbar. Without
this the docked buttons would sit on top of the header actions. */
@media (min-width: 900px) {
[data-ws-part="home.header"],
[data-ws-part="voice.header"] {
padding-right: 320px;
}
}
[data-ws-part="home.join-card"],
[data-ws-part="home.content"] {
color: #e8f0f8;
}
[data-ws-part="home.join-card"] {
background: #0f1f33;
border: 1px solid #2a4a6a;
border-radius: 16px;
box-shadow: 0 24px 60px #0008;
}
[data-ws-part="voice.workspace"] {
background: #09131f;
}
[data-ws-part="voice.content"] {
color: #e8f0f8;
}
[data-ws-part="voice.audio-dock"] {
background: #0f1f33;
border-top: 1px solid #2a4a6a;
}
[data-ws-part="home.footer"] {
color: #9db5c8;
}
[data-ws-part="home.footer.clear"] {
color: var(--skin-demo-accent);
}
+1 -1
View File
@@ -11,7 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.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-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.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/host-recovery-presentation.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-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-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",
+74 -7
View File
@@ -18,7 +18,8 @@ import {
* - `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
* host can position its own top-layer capsule (or, with an explicit
* `mode: "toolbar"`, chrome-less host buttons) 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
@@ -29,6 +30,7 @@ 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_CHROME_MAX_SLOT_ANCHORS = 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/";
@@ -72,13 +74,34 @@ export interface SkinChromeDocument {
export type SkinChromeSlotAlign = "start" | "center" | "end";
/**
* How a slotted recovery control is presented:
* - `capsule` (default): the existing rounded host capsule with its own shell.
* - `toolbar`: independent, chrome-less host buttons that can match a skin's
* top bar. The host still creates the buttons, their labels, focus and
* click handlers; the skin only names anchors and style tokens.
*
* The mode is explicit and never inferred from `compact`: an old slot without
* `mode` keeps docking the capsule exactly as before.
*/
export type SkinChromeSlotMode = "capsule" | "toolbar";
/** One anchor name, or ordered candidates (for example one per page). */
export type SkinChromeSlotAnchor = string | string[];
export interface SkinChromeSlot {
/** Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box. */
anchor: string;
/**
* Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box.
* A list lists page/component candidates: the host takes the first visible
* one, so one slot can cover both the home and the voice page.
*/
anchor: SkinChromeSlotAnchor;
/** Horizontal alignment inside the anchor; the control is vertically centred. */
align: SkinChromeSlotAlign;
/** Collapse to the mark only until hovered or focused. */
/** Collapse to the mark only until hovered or focused (capsule mode only). */
compact: boolean;
/** Explicit presentation; see `SkinChromeSlotMode`. */
mode: SkinChromeSlotMode;
}
export interface SkinChromeAssetInfo {
@@ -147,6 +170,28 @@ function normalizeSlotAnchor(raw: unknown): string {
return raw;
}
/**
* A slot may name one anchor or an ordered candidate list (one per page or
* per component variant). Candidates are validated exactly like a single
* anchor; duplicates are removed so a page cannot be tried twice per check.
*/
function normalizeSlotAnchors(raw: unknown): SkinChromeSlotAnchor {
if (!Array.isArray(raw)) return normalizeSlotAnchor(raw);
if (!raw.length || raw.length > SKIN_CHROME_MAX_SLOT_ANCHORS) {
return reject(`A slot anchor list must contain between 1 and ${SKIN_CHROME_MAX_SLOT_ANCHORS} part names.`, "SKIN_CHROME_SLOT_INVALID");
}
const anchors: string[] = [];
for (const entry of raw) {
const anchor = normalizeSlotAnchor(entry);
if (!anchors.includes(anchor)) anchors.push(anchor);
}
return anchors;
}
function isSlotMode(value: unknown): value is SkinChromeSlotMode {
return value === "capsule" || value === "toolbar";
}
function isSlotAlign(value: unknown): value is SkinChromeSlotAlign {
return value === "start" || value === "center" || value === "end";
}
@@ -226,20 +271,42 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
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") {
if (key !== "anchor" && key !== "align" && key !== "compact" && key !== "mode") {
return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID");
}
}
const anchor = normalizeSlotAnchor(value.anchor);
const anchor = normalizeSlotAnchors(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");
}
// The group slot keeps the historical capsule default. The two
// single-action slots only exist for toolbar presentation; a one-button
// capsule would be a new, ambiguous surface with no product need.
const mode = value.mode === undefined
? (part === "host.recovery" ? "capsule" : "toolbar")
: value.mode;
if (!isSlotMode(mode)) {
return reject(`Slot ${part} has an invalid mode value: ${String(mode)}.`, "SKIN_CHROME_SLOT_INVALID");
}
if (part !== "host.recovery" && mode !== "toolbar") {
return reject(`Slot ${part} only supports toolbar mode.`, "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 };
if (mode === "toolbar" && compact) {
return reject(`Slot ${part} compact is only valid in capsule mode.`, "SKIN_CHROME_SLOT_INVALID");
}
slots[part] = { anchor, align, compact, mode };
}
const perAction = slots["host.recovery.built-in"] !== undefined || slots["host.recovery.library"] !== undefined;
if (slots["host.recovery"] && perAction) {
return reject(
"Declare either host.recovery or its per-action slots (host.recovery.built-in / host.recovery.library), not both.",
"SKIN_CHROME_SLOT_INVALID",
);
}
}
+73 -3
View File
@@ -197,7 +197,11 @@ test("chrome.json declares hidden parts and icon bitmaps, with path and size val
});
test("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => {
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], ["host.recovery"]);
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], [
"host.recovery",
"host.recovery.built-in",
"host.recovery.library",
]);
const explicit = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
@@ -209,10 +213,11 @@ test("chrome.json slots accept skin-owned anchors and reject trusted host UI", (
anchor: "voice.audio-dock",
align: "start",
compact: true,
mode: "capsule",
});
// Defaults: align "end", compact off. Component and runtime-plugin parts are
// ordinary anchors; only host/trusted parts are off limits.
// Old slots without `mode` keep the docked capsule: the presentation is
// explicit, never inferred from compact or any other field.
const defaults = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
@@ -223,6 +228,7 @@ test("chrome.json slots accept skin-owned anchors and reject trusted host UI", (
anchor: "skin.voice.harbor-dock.part-anchor",
align: "end",
compact: false,
mode: "capsule",
});
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
@@ -246,6 +252,70 @@ test("chrome.json slots accept skin-owned anchors and reject trusted host UI", (
[{ 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/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "float" } } }, /invalid mode/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "toolbar", compact: true } } }, /compact is only valid in capsule mode/],
[{ schemaVersion: 1, slots: { "host.recovery.built-in": { anchor: "voice.audio-dock", mode: "capsule" } } }, /only supports toolbar mode/],
[{ schemaVersion: 1, slots: { "host.recovery.built-in": { anchor: "voice.audio-dock", compact: true } } }, /compact is only valid in capsule mode/],
];
for (const [value, message] of invalidDocuments) {
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
}
});
test("chrome.json toolbar slots support page candidates and separate action buttons", () => {
const toolbar = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery": {
mode: "toolbar",
anchor: [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
"skin.home.topbar.part-host-actions",
],
align: "end",
},
},
}));
assert.deepEqual(toolbar.slots?.["host.recovery"], {
anchor: [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
],
align: "end",
compact: false,
mode: "toolbar",
});
const perAction = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery.built-in": {
mode: "toolbar",
anchor: "skin.voice.topbar.part-built-in",
align: "start",
},
"host.recovery.library": {
mode: "toolbar",
anchor: "skin.voice.topbar.part-library",
},
},
}));
assert.deepEqual(perAction.slots?.["host.recovery.built-in"], {
anchor: "skin.voice.topbar.part-built-in",
align: "start",
compact: false,
mode: "toolbar",
});
// Single-action slots are toolbar-only and default to toolbar mode.
assert.equal(perAction.slots?.["host.recovery.library"]?.mode, "toolbar");
assert.equal(perAction.slots?.["host.recovery.library"]?.align, "end");
const invalidDocuments: Array<[unknown, RegExp]> = [
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: [] } } }, /between 1 and 8/],
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: Array.from({ length: 9 }, (_, index) => `part-${index}`) } } }, /between 1 and 8/],
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: ["voice.audio-dock", "host.plugins.launcher"] } } }, /trusted host UI/],
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: "voice.audio-dock" }, "host.recovery.built-in": { mode: "toolbar", anchor: "voice.audio-dock" } } }, /either host.recovery or its per-action slots/],
];
for (const [value, message] of invalidDocuments) {
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
+9 -2
View File
@@ -47,11 +47,18 @@ export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
* 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.
* hit-tests the control.
*
* `host.recovery` is the historical capsule group. The two action keys only
* exist for `mode: "toolbar"` and let a skin dock the "use built-in skin" and
* "application library" host buttons separately; they are still host-owned
* buttons, never DOM hooks. Extend this set when another protected control
* learns the same runtime placement.
*/
export const HOST_SLOTTABLE_PART_IDS: ReadonlySet<string> = new Set([
"host.recovery",
"host.recovery.built-in",
"host.recovery.library",
]);
/** All host-owned parts (used by the part registry and documentation). */
Binary file not shown.
Binary file not shown.
Binary file not shown.
+25 -4
View File
@@ -3,8 +3,11 @@ import { deflateSync } from "node:zlib";
import { zipSync, strToU8 } from "fflate";
const source = new URL("../../docs/examples/host-chrome-demo/", import.meta.url);
const toolbarSource = new URL("../../docs/examples/host-chrome-toolbar/", import.meta.url);
const examples = new URL("../../docs/examples/", import.meta.url);
const publicDir = new URL("../public/", import.meta.url);
// Keep rebuilt archives byte-stable when their inputs do not change.
const archiveMtime = new Date(2026, 10, 15, 16, 33, 0);
const crcTable = (() => {
const table = new Uint32Array(256);
@@ -66,12 +69,20 @@ const icons = {
"assets/icons/status.png": iconPng([150, 60, 90], [84, 28, 52]),
};
const [manifestText, cssText, chromeText] = await Promise.all([
const [manifestText, cssText, chromeText, toolbarManifestText, toolbarCssText, toolbarChromeText] = await Promise.all([
readFile(new URL("manifest.json", source), "utf8"),
readFile(new URL("skin.css", source)),
readFile(new URL("chrome.json", source), "utf8"),
readFile(new URL("manifest.json", toolbarSource), "utf8"),
readFile(new URL("skin.css", toolbarSource)),
readFile(new URL("chrome.json", toolbarSource), "utf8"),
]);
const toolbarManifest = JSON.parse(toolbarManifestText);
if (toolbarManifest.author !== "WebSpeak Community") {
throw new Error("host-chrome-toolbar manifest author must be WebSpeak Community");
}
const chrome = JSON.parse(chromeText);
const sharedFiles = {
"skin.css": new Uint8Array(cssText),
@@ -85,20 +96,30 @@ const themed = zipSync({
"manifest.json": strToU8(themedManifest),
"chrome.json": strToU8(themedChrome),
...sharedFiles,
}, { level: 9 });
}, { level: 9, mtime: archiveMtime });
// Variant B: the same package plus declarative hiding of non-critical chrome.
const hidden = zipSync({
"manifest.json": strToU8(manifestText),
"chrome.json": strToU8(chromeText),
...sharedFiles,
}, { level: 9 });
}, { level: 9, mtime: archiveMtime });
// Minimal toolbar-mode sample: host-owned recovery buttons docked into the
// header, with page-wide anchor candidates and toolbar tokens.
const toolbar = zipSync({
"manifest.json": strToU8(toolbarManifestText),
"chrome.json": strToU8(toolbarChromeText),
"skin.css": new Uint8Array(toolbarCssText),
}, { level: 9, mtime: archiveMtime });
await Promise.all([
writeFile(new URL("host-chrome-themed.wskin", examples), themed),
writeFile(new URL("host-chrome-demo.wskin", examples), hidden),
writeFile(new URL("host-chrome-toolbar.wskin", examples), toolbar),
writeFile(new URL("host-chrome-themed.wskin", publicDir), themed),
writeFile(new URL("host-chrome-demo.wskin", publicDir), hidden),
writeFile(new URL("host-chrome-toolbar.wskin", publicDir), toolbar),
]);
console.log(`Built host chrome demo skins (${themed.byteLength} / ${hidden.byteLength} bytes) into docs/examples and web/public.`);
console.log(`Built host chrome demo skins (${themed.byteLength} / ${hidden.byteLength} / ${toolbar.byteLength} bytes) into docs/examples and web/public.`);
+353 -61
View File
@@ -28,8 +28,77 @@
<!-- Trusted recovery entry. It lives in a closed shadow root and a manual
popover, so no compiled skin selector can target it (shadow boundary)
and no normal stacking context can cover it (top layer). It carries no
`data-ws-part`: there is intentionally no skin hook for this control. -->
`data-ws-part`: there is intentionally no skin hook for this control.
With an explicit `chrome.json` `mode: "toolbar"` the host paints plain
host buttons instead of the capsule shell. The buttons are still owned,
labelled, focusable and clickable by the host; the skin only supplies
an anchor and style tokens. -->
<Teleport v-if="layer" :to="layer.container">
<!-- One grouped toolbar entry: both actions share an anchor. -->
<div
v-if="groupToolbarConfig"
ref="groupToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="built-in"
:title="copy.shortcut"
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
v-if="pluginLibraryAvailable"
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
>{{ copy.library }}</button>
</div>
<!-- Per-action toolbar entries: each action has its own anchor. -->
<div
v-if="builtInToolbarConfig"
ref="builtInToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="built-in"
:title="copy.shortcut"
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
</div>
<div
v-if="libraryToolbarConfig"
ref="libraryToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
>{{ copy.library }}</button>
</div>
<div
ref="recoveryPopover"
popover="manual"
@@ -38,7 +107,7 @@
@focusout="onRecoveryFocusOut"
class="ws-host-recovery"
:class="{ 'ws-host-recovery-compact': compact }"
:data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
:data-ws-float="capsuleSlotConfig && slotMode === 'slotted' ? undefined : floatPosition"
:tabindex="compact || compactPinned ? 0 : undefined"
data-ws-host-recovery
role="region"
@@ -46,6 +115,7 @@
>
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
<button
v-if="capsuleActions.includes('built-in')"
type="button"
class="ws-host-recovery-action"
data-ws-recovery-action="built-in"
@@ -53,9 +123,9 @@
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
v-if="capsuleActions.includes('library') && pluginLibraryAvailable"
type="button"
class="ws-host-recovery-action"
v-if="pluginLibraryAvailable"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
@@ -65,8 +135,9 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, watchEffect, type Ref } from "vue";
import type { SiteLanguage } from "../../../src/site-copy.js";
import type { SkinChromeSlot } from "../../../src/shared/skin-chrome.js";
import { hostChromeCopy } from "../i18n/host-chrome.js";
import {
activeHostSlot,
@@ -77,6 +148,7 @@ import {
isThirdPartySkinActive,
openPluginLibrary,
requestBuiltInSkin,
setInlineLibraryEntryVisible,
} from "../services/host-chrome.js";
import {
createHostOwnedLayer,
@@ -96,6 +168,9 @@ import {
bindHostControlTheme,
findSkinRoot,
} from "../services/host-control-tokens.js";
import {
resolveHostRecoveryPresentation,
} from "../services/host-recovery-presentation.js";
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: boolean }>(), { connected: false });
const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
@@ -164,8 +239,55 @@ const RECOVERY_LAYER_CSS = `
min-height: var(--ws-control-hit, 28px);
}
.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-control-accent, #4c8f88); outline-offset: 2px; }
/* Toolbar mode: no capsule shell, margin, border or fixed shadow. The wrapper
only lays the host buttons out; every visible surface comes from the
--ws-toolbar-* variables resolved from the skin's validated tokens. */
.ws-host-toolbar {
position: fixed;
inset: auto;
margin: 0;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
gap: 4px;
max-width: calc(100vw - 8px);
pointer-events: auto;
}
.ws-host-toolbar:popover-open { display: flex; }
.ws-host-toolbar-action {
display: inline-flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
min-height: var(--ws-toolbar-min-height, var(--ws-control-hit, 28px));
max-width: min(320px, calc(100vw - 8px));
padding: var(--ws-toolbar-padding-y, 6px) var(--ws-toolbar-padding-x, 12px);
border: 1px solid var(--ws-toolbar-border, #9db6b2);
border-radius: var(--ws-toolbar-radius, 6px);
background: var(--ws-toolbar-background, #fff);
color: var(--ws-toolbar-foreground, #31524f);
box-shadow: var(--ws-toolbar-shadow, none);
font-family: var(--ws-toolbar-font, ui-sans-serif, system-ui, sans-serif);
font-size: var(--ws-toolbar-font-size, 11px);
line-height: 1.25;
text-align: center;
white-space: normal;
overflow-wrap: anywhere;
cursor: pointer;
touch-action: manipulation;
}
.ws-host-toolbar-action:hover { filter: brightness(.96); }
.ws-host-toolbar-action:focus-visible {
outline: 2px solid var(--ws-toolbar-focus, var(--ws-control-accent, #4c8f88));
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
.ws-host-recovery, .ws-host-recovery button { transition: none !important; }
.ws-host-recovery, .ws-host-recovery button, .ws-host-toolbar-action { transition: none !important; }
}
`;
@@ -190,14 +312,32 @@ const showRecovery = computed(() => shouldShowRecovery({
// already reset). It never renders decoration on its own.
const shortcutOpen = ref(false);
const recoveryPopover = ref<HTMLElement | null>(null);
const groupToolbarElement = ref<HTMLElement | null>(null);
const builtInToolbarElement = ref<HTMLElement | null>(null);
const libraryToolbarElement = ref<HTMLElement | null>(null);
let slotBinding: HostSlotBinding | undefined;
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
/**
* Theme the capsule even when the skin does not declare a slot. While a slot
* binding exists it reads the anchor first and owns the tokens; this
* root-level pass covers the slot-less capsule and refreshes itself when the
* skin stylesheet arrives after the stored skin id.
* Optional anchor from the active skin's chrome.json. Only third-party skins
* can declare it; the host still owns the controls and the module falls back
* to the default corner whenever an anchor stops being usable.
*/
const slotConfig = computed(() => activeHostSlot("host.recovery"));
const builtInSlotConfig = computed(() => activeHostSlot("host.recovery.built-in"));
const librarySlotConfig = computed(() => activeHostSlot("host.recovery.library"));
const groupToolbarConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? slotConfig.value : undefined);
const capsuleSlotConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? undefined : slotConfig.value);
const builtInToolbarConfig = computed<SkinChromeSlot | undefined>(() => builtInSlotConfig.value?.mode === "toolbar" ? builtInSlotConfig.value : undefined);
const libraryToolbarConfig = computed<SkinChromeSlot | undefined>(() => librarySlotConfig.value?.mode === "toolbar" ? librarySlotConfig.value : undefined);
/**
* Theme the capsule even when the skin does not declare a slot. While a
* capsule slot binding exists it reads the anchor first and owns the tokens;
* this root-level pass covers the slot-less capsule and refreshes itself when
* the skin stylesheet arrives after the stored skin id. Toolbar bindings keep
* their own `--ws-toolbar-*` variables and do not disable this pass, so the
* floating fallback keeps the capsule palette.
*/
const recoveryTheme = layer ? bindHostControlTheme({
layer,
@@ -205,19 +345,43 @@ const recoveryTheme = layer ? bindHostControlTheme({
part: "host.recovery",
defaults: RECOVERY_CONTROL_DEFAULTS,
source: () => findSkinRoot(hostChromeActiveSkinId.value),
// While a slot binding exists it owns the capsule tokens (anchor first).
active: () => !slotBinding,
active: () => !capsuleBinding,
}) : 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 groupToolbarMode = ref<"floating" | "slotted">("floating");
const builtInToolbarMode = ref<"floating" | "slotted">("floating");
const libraryToolbarMode = ref<"floating" | "slotted">("floating");
const builtInActionState = computed(() => ({
available: Boolean(groupToolbarConfig.value || builtInToolbarConfig.value),
docked: groupToolbarConfig.value
? groupToolbarMode.value === "slotted"
: builtInToolbarMode.value === "slotted",
}));
const libraryActionState = computed(() => ({
available: Boolean(props.pluginLibraryAvailable) && Boolean(groupToolbarConfig.value || libraryToolbarConfig.value),
docked: groupToolbarConfig.value
? groupToolbarMode.value === "slotted"
: libraryToolbarMode.value === "slotted",
}));
const presentation = computed(() => resolveHostRecoveryPresentation({
visible: recoveryVisible.value,
shortcutOpen: shortcutOpen.value,
libraryAvailable: Boolean(props.pluginLibraryAvailable),
builtIn: builtInActionState.value,
library: libraryActionState.value,
}));
const capsuleActions = computed(() => presentation.value.capsuleActions);
// Exactly one application-library entry per page: the host toolbar button is
// the library entry while a toolbar slot exists, so PluginPanel hides its
// ordinary launcher (including while the capsule fallback shows the button).
watchEffect(() => {
setInlineLibraryEntryVisible(presentation.value.suppressLauncher);
});
const compactHold = ref(true);
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
@@ -255,11 +419,15 @@ let floatingElement: HTMLElement | null = null;
/** Sticky `:hover` after a tap on touch screens must not pause avoidance. */
const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches;
const compact = computed(() => !shortcutExpanded.value
&& !compactPinned.value
&& (slotMode.value === "slotted"
? Boolean(slotConfig.value?.compact) && !compactHold.value
: floatCompact.value));
const compact = computed(() => {
if (shortcutExpanded.value || compactPinned.value) return false;
const config = capsuleSlotConfig.value;
if (config) return Boolean(config.compact) && !compactHold.value;
// A toolbar-mode capsule is the fallback entry, not the target look: never
// fold it, otherwise a failed anchor could leave only a small mark.
if (groupToolbarConfig.value || builtInToolbarConfig.value || libraryToolbarConfig.value) return false;
return floatCompact.value;
});
function onRecoveryEscape() {
shortcutOpen.value = false;
@@ -282,25 +450,93 @@ function onRecoveryFocusOut(event: FocusEvent) {
compactPinned.value = false;
}
function syncSlotBinding() {
slotBinding?.dispose();
slotBinding = undefined;
// Disposing a slot clears its inline tokens; restore the root-level theme
// before deciding whether a new anchor should override it.
recoveryTheme?.apply();
// A fresh binding starts floating and reports its first successful dock.
slotMode.value = "floating";
const control = recoveryPopover.value;
const config = slotConfig.value;
if (!control || !config || !layer) return;
slotBinding = bindHostSlot({
let capsuleBinding: HostSlotBinding | undefined;
let toolbarBindings: HostSlotBinding[] = [];
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, presentation.value.capsuleVisible);
}
function syncToolbarPopovers() {
const visible = presentation.value.toolbar.visible;
syncRecoveryPopover(
groupToolbarElement.value,
Boolean(groupToolbarConfig.value) && visible && groupToolbarMode.value === "slotted",
);
syncRecoveryPopover(
builtInToolbarElement.value,
Boolean(builtInToolbarConfig.value) && visible && builtInToolbarMode.value === "slotted",
);
syncRecoveryPopover(
libraryToolbarElement.value,
Boolean(libraryToolbarConfig.value) && Boolean(props.pluginLibraryAvailable)
&& visible && libraryToolbarMode.value === "slotted",
);
}
function bindToolbarEntry(
control: HTMLElement | null,
config: SkinChromeSlot | undefined,
mode: Ref<"floating" | "slotted">,
) {
if (!layer || !control || !config) return;
toolbarBindings.push(bindHostSlot({
layer,
control,
anchor: config.anchor,
skinId: hostChromeActiveSkinId.value,
align: config.align,
onModeChange: change => { slotMode.value = change.mode; },
});
presentation: "toolbar",
// A floating toolbar is a closed popover (display:none). Show it for the
// synchronous measurement/hit test and hide it again unless it docked.
prepare: () => syncRecoveryPopover(control, true),
settle: slotted => {
if (!slotted || !presentation.value.toolbar.visible) syncRecoveryPopover(control, false);
},
onModeChange: change => {
mode.value = change.mode;
syncPopover();
syncToolbarPopovers();
},
}));
}
function syncSlotBindings() {
capsuleBinding?.dispose();
capsuleBinding = undefined;
for (const binding of toolbarBindings) binding.dispose();
toolbarBindings = [];
// Disposing a slot clears its inline tokens; restore the root-level theme
// before deciding whether a new anchor should override it.
recoveryTheme?.apply();
// A fresh binding starts floating and reports its first successful dock.
slotMode.value = "floating";
groupToolbarMode.value = "floating";
builtInToolbarMode.value = "floating";
libraryToolbarMode.value = "floating";
const capsuleConfig = capsuleSlotConfig.value;
if (recoveryPopover.value && capsuleConfig && layer) {
capsuleBinding = bindHostSlot({
layer,
control: recoveryPopover.value,
anchor: capsuleConfig.anchor,
skinId: hostChromeActiveSkinId.value,
align: capsuleConfig.align,
onModeChange: change => { slotMode.value = change.mode; },
});
}
bindToolbarEntry(groupToolbarElement.value, groupToolbarConfig.value, groupToolbarMode);
bindToolbarEntry(builtInToolbarElement.value, builtInToolbarConfig.value, builtInToolbarMode);
if (props.pluginLibraryAvailable) {
bindToolbarEntry(libraryToolbarElement.value, libraryToolbarConfig.value, libraryToolbarMode);
}
syncPopover();
syncToolbarPopovers();
}
function revalidateBindings() {
capsuleBinding?.revalidate();
for (const binding of toolbarBindings) binding.revalidate();
}
function bindFloating() {
@@ -341,10 +577,6 @@ function bindFloating() {
});
}
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
}
function useBuiltInSkin() {
shortcutOpen.value = false;
requestBuiltInSkin();
@@ -364,8 +596,11 @@ function onKeydown(event: KeyboardEvent) {
shortcutOpen.value = true;
shortcutExpanded.value = true;
void nextTick(() => {
// The shortcut always brings back the complete capsule, even while a
// toolbar anchor is healthy.
syncPopover();
slotBinding?.revalidate();
syncToolbarPopovers();
revalidateBindings();
recoveryPopover.value?.querySelector("button")?.focus();
});
}
@@ -376,30 +611,66 @@ function refreshLauncherReachability() {
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
}
watch([recoveryVisible, recoveryPopover], () => {
void nextTick(() => {
syncPopover();
slotBinding?.revalidate();
bindFloating();
floatingAvoidance?.revalidate();
});
}, { flush: "post" });
watch(
[recoveryVisible, recoveryPopover, groupToolbarElement, builtInToolbarElement, libraryToolbarElement],
() => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
bindFloating();
floatingAvoidance?.revalidate();
});
},
{ flush: "post" },
);
watch([recoveryPopover, hostChromeActiveSkinId], () => {
void nextTick(() => recoveryTheme?.apply());
}, { flush: "post", immediate: true });
watch([slotConfig, hostChromeActiveSkinId], () => {
void nextTick(() => {
syncPopover();
syncSlotBinding();
});
}, { flush: "post" });
watch(
[
slotConfig,
builtInSlotConfig,
librarySlotConfig,
hostChromeActiveSkinId,
groupToolbarElement,
builtInToolbarElement,
libraryToolbarElement,
() => props.pluginLibraryAvailable,
],
() => {
void nextTick(() => {
syncSlotBindings();
bindFloating();
});
},
{ flush: "post" },
);
// Home <-> voice page and skin switches replace the controls the floating
// capsule was avoiding; re-place it promptly (and back to its default corner
// when that is free) instead of leaving it where the previous screen needed it.
watch([() => props.connected, hostChromeActiveSkinId], () => {
void nextTick(() => floatingAvoidance?.screenChanged());
void nextTick(() => {
revalidateBindings();
floatingAvoidance?.screenChanged();
});
}, { flush: "post" });
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
// Opening or closing the shortcut changes which presentation is active; docked
// toolbar buttons must hide while the complete capsule is summoned, and come
// back (if their anchor is still valid) when it closes.
watch(shortcutOpen, () => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
});
}, { flush: "post" });
// A page switch can mount a new `.ws-skin-root` with a different
// `data-ws-page` without changing the skin id. Re-resolve the declared anchor
// candidates promptly instead of waiting for the periodic safety check.
let pageObserver: MutationObserver | undefined;
onMounted(() => {
refreshLauncherReachability();
@@ -407,16 +678,37 @@ onMounted(() => {
window.addEventListener("resize", refreshLauncherReachability);
window.addEventListener("keydown", onKeydown, true);
window.addEventListener("pointerdown", onDocumentPointerDown, true);
if (typeof MutationObserver === "function") {
pageObserver = new MutationObserver(() => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
floatingAvoidance?.screenChanged();
});
});
pageObserver.observe(document.documentElement, {
subtree: true,
attributes: true,
attributeFilter: ["data-ws-page", "data-ws-skin"],
});
}
void nextTick(() => {
syncPopover();
syncSlotBinding();
syncSlotBindings();
bindFloating();
});
});
onBeforeUnmount(() => {
if (reachabilityTimer) clearInterval(reachabilityTimer);
if (compactHoldTimer) clearTimeout(compactHoldTimer);
slotBinding?.dispose();
pageObserver?.disconnect();
pageObserver = undefined;
capsuleBinding?.dispose();
capsuleBinding = undefined;
for (const binding of toolbarBindings) binding.dispose();
toolbarBindings = [];
setInlineLibraryEntryVisible(false);
floatingAvoidance?.dispose();
floatingAvoidance = undefined;
floatingElement = null;
+5 -2
View File
@@ -1,7 +1,7 @@
<template>
<Teleport :to="toolbarTarget ?? 'body'">
<div v-if="thirdPartyAllowed && connected && sessionToken" ref="toolbar" class="ws-plugin-toolbar" :class="{ 'ws-plugin-toolbar-fallback': !toolbarTarget }" :data-ws-float="toolbarTarget ? undefined : fallbackPosition" data-ws-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
<button v-if="!isHostPartHidden('host.plugins.launcher')" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @click="toggle">
<button v-if="!isHostPartHidden('host.plugins.launcher') && !inlineLibraryEntry" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @click="toggle">
<svg viewBox="0 0 24 24" data-ws-icon-slot="host.plugins.launcher" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
<span v-if="presentation === 'drawer-side'">{{ tr('title') }}</span>
</button>
@@ -68,7 +68,7 @@ import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
import type { SiteLanguage } from '../../../src/site-copy.js';
import { thirdPartyAllowed } from '../services/instance-authorization.js';
import { isHostPartHidden, isHostPartVisuallyReachable, pluginLibraryRequests } from '../services/host-chrome.js';
import { isHostPartHidden, isHostPartVisuallyReachable, isInlineLibraryEntryVisible, pluginLibraryRequests } from '../services/host-chrome.js';
import type { SkinPluginWidgetOptions } from '../../../src/shared/skin-plugin.js';
import { bindFloatingAvoidance, type FloatingAvoidance, type FloatingPosition } from '../services/host-floating-placement.js';
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage; toolbarTarget: HTMLElement | null; presentation: NonNullable<SkinPluginWidgetOptions['pluginPresentation']> }>();
@@ -77,6 +77,9 @@ const ui = computed(() => pluginWindowTranslations[props.language]);
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
const toolbar = ref<HTMLElement | null>(null);
// A toolbar-mode recovery slot already renders the host-owned application
// library button; do not render a second launcher on the same page.
const inlineLibraryEntry = computed(() => isInlineLibraryEntryVisible());
// The fallback toolbar floats in a viewport corner the skin knows nothing
// about; move it off any skin control it would cover (runtime only).
const fallbackPosition = ref<FloatingPosition>('bottom-right');
@@ -85,6 +85,41 @@ test("the recovery entry is persistent for third-party skins only", () => {
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, launcherHiddenByConfig: true }), false);
});
test("toolbar and per-action recovery slots are exposed for third-party skins", () => {
const document = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery.built-in": {
mode: "toolbar",
anchor: ["skin.home.topbar.part-host-actions", "skin.voice.topbar.part-host-actions"],
},
"host.recovery.library": {
mode: "toolbar",
anchor: "skin.voice.topbar.part-host-library",
},
},
}));
setSkinHostChromeParts(document);
setHostChromeActiveSkin("community.toolbar");
try {
assert.deepEqual(activeHostSlot("host.recovery.built-in")?.anchor, [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
]);
assert.equal(activeHostSlot("host.recovery.built-in")?.mode, "toolbar");
assert.equal(activeHostSlot("host.recovery.library")?.mode, "toolbar");
assert.equal(activeHostSlot("host.recovery"), undefined);
// Bundled skins never see the toolbar declaration; their launcher stays.
setHostChromeActiveSkin("builtin.light");
assert.equal(activeHostSlot("host.recovery.built-in"), undefined);
assert.equal(activeHostSlot("host.recovery.library"), undefined);
} finally {
setSkinHostChromeParts(undefined);
setHostChromeActiveSkin(undefined);
}
});
test("slot declarations are honoured for third-party skins only", () => {
const document = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
@@ -97,9 +132,11 @@ test("slot declarations are honoured for third-party skins only", () => {
anchor: "voice.audio-dock",
align: "end",
compact: false,
mode: "capsule",
});
// A part that is not slottable cannot be selected through chrome.json.
assert.equal(activeHostSlot("host.permission"), undefined);
assert.equal(activeHostSlot("host.recovery.library"), undefined);
// Bundled/official skins keep the default floating placement.
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
+17
View File
@@ -104,6 +104,23 @@ export function openPluginLibrary(): void {
libraryRequests.value += 1;
}
/**
* True while a toolbar-mode recovery slot provides the application library.
* PluginPanel then hides its ordinary `host.plugins.launcher` so the same page
* has exactly one application-library entry. The state is host-only: a skin
* can request the slot through chrome.json, but cannot set this flag or click
* the host button.
*/
const inlineLibraryEntry = ref(false);
export function setInlineLibraryEntryVisible(visible: boolean): void {
inlineLibraryEntry.value = visible;
}
export function isInlineLibraryEntryVisible(): boolean {
return inlineLibraryEntry.value;
}
/**
* Recovery's guaranteed escape hatch: reset to the built-in Day/Night skin.
* `usePublicSkin` watches this counter, so it works even when the skinnable
@@ -9,19 +9,30 @@ import {
HOST_CONTROL_MIN_FOREGROUND_CONTRAST,
HOST_CONTROL_MIN_HIT_TARGET,
HOST_CONTROL_SIZE_METRICS,
HOST_TOOLBAR_APPLIED_VARIABLES,
PERMISSION_CONTROL_DEFAULTS,
RECOVERY_CONTROL_DEFAULTS,
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
TOOLBAR_DEFAULT_PADDING_X,
TOOLBAR_DEFAULT_PADDING_Y,
TOOLBAR_DEFAULT_RADIUS,
TOOLBAR_MAX_FONT_SIZE,
TOOLBAR_MAX_HEIGHT,
TOOLBAR_MAX_PADDING,
applyHostControlTokens,
applyHostControlToolbarTokens,
contrastRatio,
fontFamilyNames,
formatRgb,
hasHostControlTokens,
hasHostToolbarTokens,
hostControlTokenKey,
hostControlTokenProperty,
hostToolbarTokenProperty,
parseCssColor,
relativeLuminance,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlRawTokens,
} from "./host-control-tokens.js";
@@ -281,3 +292,142 @@ test("host controls ignore fonts registered by a skin @font-face", () => {
assert.equal(resolve('"ws-community-evil-blank", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
assert.equal(resolve("Tahoma, ws-community-evil-blank"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
});
const resolveToolbar = (tokens: TokenMap = {}, global: TokenMap = {}) =>
resolveHostControlToolbarTokens(
style({ ...prefixed("host", {}), ...tokens, ...global }),
"host.recovery",
raw => raw,
RECOVERY_CONTROL_DEFAULTS,
);
test("toolbar tokens are independent of the capsule shell and keep host floors", () => {
const defaults = resolveToolbar();
assert.equal(defaults.background, "rgb(255, 255, 255)");
assert.equal(defaults.foreground, "rgb(49, 82, 79)");
assert.equal(defaults.border, "rgb(157, 182, 178)");
assert.equal(defaults.radius, TOOLBAR_DEFAULT_RADIUS, "a capsule radius must not leak into toolbar mode");
assert.equal(defaults.paddingX, TOOLBAR_DEFAULT_PADDING_X);
assert.equal(defaults.paddingY, TOOLBAR_DEFAULT_PADDING_Y);
assert.equal(defaults.minHeight, HOST_CONTROL_MIN_HIT_TARGET);
assert.equal(defaults.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
assert.equal(defaults.shadow, "none", "the capsule shadow must not be copied into toolbar mode");
const custom = resolveToolbar({
"--skin-recovery-toolbar-background": "#102030",
"--skin-recovery-toolbar-foreground": "#ffffff",
"--skin-recovery-toolbar-border": "#47dcc4",
"--skin-recovery-toolbar-radius": "10px",
"--skin-recovery-toolbar-font": "Tahoma, sans-serif",
"--skin-recovery-toolbar-font-size": "15px",
"--skin-recovery-toolbar-padding": "8px 18px",
"--skin-recovery-toolbar-height": "40px",
"--skin-recovery-toolbar-shadow": "0 2px 6px #00000033",
});
assert.equal(custom.background, "rgb(16, 32, 48)");
assert.equal(custom.foreground, "rgb(255, 255, 255)");
assert.equal(custom.border, "rgb(71, 220, 196)");
assert.equal(custom.radius, 10);
assert.equal(custom.font, "Tahoma, sans-serif");
assert.equal(custom.fontSize, 15);
assert.equal(custom.paddingX, 18);
assert.equal(custom.paddingY, 8);
assert.equal(custom.minHeight, 40);
assert.equal(custom.shadow, "0 2px 6px #00000033");
// Global toolbar tokens lose to the per-part set, but still override defaults.
const global = resolveToolbar({}, { "--skin-host-toolbar-background": "#222222", "--skin-host-toolbar-foreground": "#ffffff" });
assert.equal(global.background, "rgb(34, 34, 34)");
assert.equal(global.foreground, "rgb(255, 255, 255)");
});
test("unreadable or invalid toolbar tokens fall back to a visible, readable button", () => {
// Transparent backgrounds are treated as opaque RGB by parseCssColor; the
// result is unreadable against the text and the whole pair reverts.
const transparent = resolveToolbar({
"--skin-recovery-toolbar-background": "rgba(0, 0, 0, 0)",
"--skin-recovery-toolbar-foreground": "#111111",
});
assert.equal(transparent.background, "rgb(255, 255, 255)");
assert.equal(transparent.foreground, "rgb(49, 82, 79)");
assert.ok(contrastRatio(parseCssColor(transparent.foreground)!, parseCssColor(transparent.background)!) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST);
const lowContrast = resolveToolbar({
"--skin-recovery-toolbar-background": "#777777",
"--skin-recovery-toolbar-foreground": "#888888",
});
assert.equal(lowContrast.background, "rgb(255, 255, 255)");
assert.equal(lowContrast.foreground, "rgb(49, 82, 79)");
const invalid = resolveToolbar({
"--skin-recovery-toolbar-background": "not-a-colour",
"--skin-recovery-toolbar-foreground": "not-a-colour",
"--skin-recovery-toolbar-radius": "999px",
"--skin-recovery-toolbar-font": "url(https://example.invalid/font.woff2)",
"--skin-recovery-toolbar-font-size": "2px",
"--skin-recovery-toolbar-padding": "100px",
"--skin-recovery-toolbar-height": "2px",
"--skin-recovery-toolbar-shadow": "url(https://example.invalid/pixel)",
});
assert.equal(invalid.background, "rgb(255, 255, 255)");
assert.equal(invalid.foreground, "rgb(49, 82, 79)");
assert.equal(invalid.radius, 24, "the toolbar radius is clamped to its own maximum");
assert.equal(invalid.font, RECOVERY_CONTROL_DEFAULTS.font);
assert.equal(invalid.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
// A syntactically valid but oversized padding is clamped, not applied raw.
assert.equal(invalid.paddingX, TOOLBAR_MAX_PADDING);
assert.equal(invalid.paddingY, TOOLBAR_MAX_PADDING);
assert.equal(invalid.minHeight, HOST_CONTROL_MIN_HIT_TARGET);
assert.equal(invalid.shadow, "none");
const oversized = resolveToolbar({
"--skin-recovery-toolbar-font-size": "64px",
"--skin-recovery-toolbar-height": "200px",
"--skin-recovery-toolbar-padding": "100px 100px",
});
assert.equal(oversized.fontSize, TOOLBAR_MAX_FONT_SIZE);
assert.equal(oversized.minHeight, TOOLBAR_MAX_HEIGHT);
assert.equal(oversized.paddingX, TOOLBAR_MAX_PADDING);
assert.equal(oversized.paddingY, TOOLBAR_MAX_PADDING);
});
test("toolbar tokens reject skin fonts and detect declarations", () => {
assert.equal(hostToolbarTokenProperty("host.recovery", "background"), "--skin-recovery-toolbar-background");
assert.equal(hostToolbarTokenProperty("host.recovery", "font-size"), "--skin-recovery-toolbar-font-size");
assert.equal(hasHostToolbarTokens(style({}), "host.recovery"), false);
assert.equal(hasHostToolbarTokens(style({ "--skin-host-toolbar-shadow": "none" }), "host.recovery"), true);
assert.equal(hasHostToolbarTokens(style({ "--skin-recovery-toolbar-padding": "4px" }), "host.recovery"), true);
const webFonts = new Set(["blank glyphs"]);
const font = resolveHostControlToolbarTokens(
style({ "--skin-recovery-toolbar-font": '"Blank Glyphs", sans-serif' }),
"host.recovery",
raw => raw,
RECOVERY_CONTROL_DEFAULTS,
family => webFonts.has(family),
).font;
assert.equal(font, RECOVERY_CONTROL_DEFAULTS.font);
});
test("applying and clearing toolbar tokens writes only toolbar variables", () => {
const values = new Map<string, string>();
const control = {
style: {
setProperty: (name: string, value: string) => { values.set(name, value); },
removeProperty: (name: string) => { values.delete(name); },
},
} as unknown as HTMLElement;
applyHostControlToolbarTokens(control, resolveToolbar({
"--skin-recovery-toolbar-background": "#102030",
"--skin-recovery-toolbar-foreground": "#ffffff",
"--skin-recovery-toolbar-padding": "6px 14px",
"--skin-recovery-toolbar-height": "36px",
}));
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.background), "rgb(16, 32, 48)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.foreground), "rgb(255, 255, 255)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.paddingX), "14px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.paddingY), "6px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.minHeight), "36px");
applyHostControlToolbarTokens(control, null);
assert.equal(values.size, 0);
});
+220
View File
@@ -44,6 +44,36 @@ export const HOST_CONTROL_TOKEN_NAMES = [
export type HostControlTokenName = (typeof HOST_CONTROL_TOKEN_NAMES)[number];
/**
* Extra tokens read only for `mode: "toolbar"` recovery buttons. They make a
* host-owned button able to match a neighbouring top-bar button without
* giving the skin any DOM control:
*
* --skin-recovery-toolbar-<token> (per-part)
* --skin-host-toolbar-<token> (global fallback)
*
* Colours fall back to the normal `--skin-recovery-*` / `--skin-host-*` set;
* radius, padding, height, font size and shadow use toolbar defaults so a
* capsule radius (999px) or the fixed pale built-in button never leaks in.
*/
export const HOST_TOOLBAR_TOKEN_NAMES = [
"background", "foreground", "border", "radius", "font", "font-size", "padding", "height", "shadow",
] as const;
export type HostToolbarTokenName = (typeof HOST_TOOLBAR_TOKEN_NAMES)[number];
export const HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES: Readonly<Record<HostToolbarTokenName, string>> = {
background: "--skin-host-toolbar-background",
foreground: "--skin-host-toolbar-foreground",
border: "--skin-host-toolbar-border",
radius: "--skin-host-toolbar-radius",
font: "--skin-host-toolbar-font",
"font-size": "--skin-host-toolbar-font-size",
padding: "--skin-host-toolbar-padding",
height: "--skin-host-toolbar-height",
shadow: "--skin-host-toolbar-shadow",
};
/** Global token set read from the active skin root (or a slot anchor). */
export const HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES: Readonly<Record<HostControlTokenName, string>> = {
accent: "--skin-host-accent",
@@ -74,6 +104,10 @@ export function hostControlTokenProperty(part: string, token: HostControlTokenNa
return `--skin-${hostControlTokenKey(part)}-${token}`;
}
export function hostToolbarTokenProperty(part: string, token: HostToolbarTokenName): string {
return `--skin-${hostControlTokenKey(part)}-toolbar-${token}`;
}
/** Host-owned variables written inside the closed shadow root. */
export const HOST_CONTROL_APPLIED_VARIABLES = {
accent: "--ws-control-accent",
@@ -88,6 +122,21 @@ export const HOST_CONTROL_APPLIED_VARIABLES = {
builtInBorder: "--ws-control-builtin-border",
} as const;
/** Host-owned variables read by the toolbar-mode button CSS. */
export const HOST_TOOLBAR_APPLIED_VARIABLES = {
background: "--ws-toolbar-background",
foreground: "--ws-toolbar-foreground",
border: "--ws-toolbar-border",
radius: "--ws-toolbar-radius",
font: "--ws-toolbar-font",
fontSize: "--ws-toolbar-font-size",
paddingX: "--ws-toolbar-padding-x",
paddingY: "--ws-toolbar-padding-y",
minHeight: "--ws-toolbar-min-height",
shadow: "--ws-toolbar-shadow",
focus: "--ws-toolbar-focus",
} as const;
export interface HostControlRawTokens {
/** Computed-style colour values; unresolved values are rejected. */
accent?: string;
@@ -130,6 +179,23 @@ export interface HostControlTokens {
builtInBorder?: string;
}
/** Resolved style of a toolbar-mode recovery button (applied to its wrapper). */
export interface HostControlToolbarTokens {
background: string;
foreground: string;
border: string;
radius: number;
font: string;
fontSize: number;
paddingX: number;
paddingY: number;
/** Minimum button height; never below the current size tier hit target. */
minHeight: number;
shadow: string;
/** Focus ring colour, from the readable accent of the control palette. */
focus: string;
}
export interface RgbColor {
r: number;
g: number;
@@ -147,6 +213,23 @@ const ON_ACCENT_DARK: RgbColor = { r: 17, g: 24, b: 39 };
const MAX_RADIUS = 999;
const MAX_FONT_LENGTH = 120;
const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/;
/** Toolbar-mode geometry limits; a skin cannot shrink below host minimums. */
export const TOOLBAR_DEFAULT_RADIUS = 6;
export const TOOLBAR_MAX_RADIUS = 24;
export const TOOLBAR_DEFAULT_PADDING_X = 12;
export const TOOLBAR_DEFAULT_PADDING_Y = 6;
export const TOOLBAR_MAX_PADDING = 48;
export const TOOLBAR_MAX_HEIGHT = 72;
export const TOOLBAR_MAX_FONT_SIZE = 20;
const MAX_SHADOW_LENGTH = 160;
const LENGTH_PX_PATTERN = /^(-?\d+(?:\.\d+)?)px$/i;
const PADDING_PATTERN = /^(\d+(?:\.\d+)?)px(?:\s+(\d+(?:\.\d+)?)px)?$/i;
/**
* A single box-shadow value: optional `inset`, two to four px offsets/sizes
* and one simple colour. `url()`, `var()`, extra shadows and declarations are
* rejected so a token can never load a resource or escape the inline value.
*/
const SHADOW_PATTERN = /^(?:none|(?:inset\s+)?(?:-?(?:0|(?:\d+(?:\.\d+)?)px)\s+){2,4}(?:#[0-9a-f]{3,8}|rgba?\([^()]*\)|[a-z]+))$/i;
/**
* The skin compiler renames every skin/plugin `@font-face` family to
* `ws-<skin id>[-<plugin id>]-<name>` (see `compileSkinCss` in
@@ -449,6 +532,143 @@ export function applyHostControlTokens(control: HTMLElement, tokens: HostControl
if (tokens.builtInBorder) style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder);
}
function readToolbarTokenSet(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
resolveProperty: (token: HostToolbarTokenName) => string,
): Partial<Record<HostToolbarTokenName, string>> {
if (!style) return {};
const tokens: Partial<Record<HostToolbarTokenName, string>> = {};
for (const token of HOST_TOOLBAR_TOKEN_NAMES) {
const value = style.getPropertyValue(resolveProperty(token)).trim();
if (value) tokens[token] = value;
}
return tokens;
}
function sanitizeToolbarFontSize(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const size = Number.parseFloat(match[1]);
return Number.isFinite(size)
? Math.min(TOOLBAR_MAX_FONT_SIZE, Math.max(HOST_CONTROL_MIN_FONT_SIZE, fallback, size))
: fallback;
}
function sanitizeToolbarPadding(value: string | undefined): { x: number; y: number } | undefined {
if (!value) return undefined;
const match = PADDING_PATTERN.exec(value.trim());
if (!match) return undefined;
const first = Number.parseFloat(match[1]);
const second = match[2] === undefined ? first : Number.parseFloat(match[2]);
if (!Number.isFinite(first) || !Number.isFinite(second)) return undefined;
const clamp = (size: number) => Math.min(TOOLBAR_MAX_PADDING, Math.max(0, size));
return { x: clamp(second), y: clamp(first) };
}
function sanitizeToolbarHeight(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const height = Number.parseFloat(match[1]);
return Number.isFinite(height)
? Math.min(TOOLBAR_MAX_HEIGHT, Math.max(fallback, height))
: fallback;
}
function sanitizeToolbarShadow(value: string | undefined): string | undefined {
if (!value) return undefined;
const shadow = value.trim().replace(/\s+/g, " ");
if (!shadow || shadow.length > MAX_SHADOW_LENGTH || !SHADOW_PATTERN.test(shadow)) return undefined;
return shadow;
}
/** True when the skin declares at least one toolbar-mode token. */
export function hasHostToolbarTokens(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
part: string,
): boolean {
if (!style) return false;
return HOST_TOOLBAR_TOKEN_NAMES.some((token) =>
Boolean(style.getPropertyValue(hostToolbarTokenProperty(part, token)).trim())
|| Boolean(style.getPropertyValue(HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES[token]).trim())
);
}
/**
* Resolve the toolbar button palette and geometry.
*
* The base control palette is resolved first (background/foreground/accent/
* border/font/size, with every existing readability floor). Toolbar tokens
* then override colours and radius; an unreadable toolbar colour pair falls
* back to the readable base pair, so an invalid or transparent value can never
* make the button invisible. `font-size`, `padding` and `height` may raise the
* button but never go below `HOST_CONTROL_MIN_FONT_SIZE` / the current hit
* target; `shadow` accepts one simple box-shadow value and otherwise becomes
* `none` (no fixed capsule shadow).
*/
export function resolveHostControlToolbarTokens(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
part: string,
probeColor: ColorProbe,
defaults: HostControlDefaults,
isWebFont: WebFontCheck = NO_WEB_FONTS,
): HostControlToolbarTokens {
const base = resolveHostControlTokens(style, part, probeColor, defaults, isWebFont);
const globalTokens = readToolbarTokenSet(style, (token) => HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES[token]);
const partTokens = readToolbarTokenSet(style, (token) => hostToolbarTokenProperty(part, token));
const merged = { ...globalTokens, ...partTokens };
const baseBackground = parseCssColor(base.background) ?? defaults.background;
const baseForeground = parseCssColor(base.foreground) ?? defaults.foreground;
const baseBorder = parseCssColor(base.border) ?? defaults.border;
let background = parseCssColor(probeColor(merged.background)) ?? baseBackground;
let foreground = parseCssColor(probeColor(merged.foreground)) ?? baseForeground;
// A toolbar colour pair must keep the same text contrast floor as the
// capsule; on any failure the already-readable base palette wins as a pair.
if (contrastRatio(foreground, background) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
background = baseBackground;
foreground = baseForeground;
}
const border = resolveBorder(merged.border, background, probeColor) ?? baseBorder;
const padding = sanitizeToolbarPadding(merged.padding);
return {
background: formatRgb(background),
foreground: formatRgb(foreground),
border: formatRgb(border),
radius: sanitizeRadius(merged.radius, TOOLBAR_DEFAULT_RADIUS, TOOLBAR_MAX_RADIUS),
font: sanitizeFont(merged.font, base.font, isWebFont),
fontSize: sanitizeToolbarFontSize(merged["font-size"], base.fontSize),
paddingX: padding?.x ?? TOOLBAR_DEFAULT_PADDING_X,
paddingY: padding?.y ?? TOOLBAR_DEFAULT_PADDING_Y,
minHeight: sanitizeToolbarHeight(merged.height, base.hitTarget),
shadow: sanitizeToolbarShadow(merged.shadow) ?? "none",
focus: base.accent,
};
}
/** Apply (or clear) toolbar-mode variables on the button wrapper. */
export function applyHostControlToolbarTokens(
control: HTMLElement,
tokens: HostControlToolbarTokens | null,
): void {
const style = control.style;
for (const property of Object.values(HOST_TOOLBAR_APPLIED_VARIABLES)) style.removeProperty(property);
if (!tokens) return;
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.background, tokens.background);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.foreground, tokens.foreground);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.border, tokens.border);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.font, tokens.font);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.paddingX, `${tokens.paddingX}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.paddingY, `${tokens.paddingY}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.minHeight, `${tokens.minHeight}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.shadow, tokens.shadow);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.focus, tokens.focus);
}
export interface HostControlThemeBindingOptions {
layer: HostOwnedLayer;
/** The host-owned element whose inline `--ws-control-*` variables are set. */
+7 -3
View File
@@ -103,17 +103,21 @@ const popoverFallbacks = new WeakSet<HTMLElement>();
* assigning `display`. The same path is used when the Popover API is missing
* or when top-layer promotion throws (for example in a constrained embed).
*/
export function syncRecoveryPopover(element: HTMLElement | null | undefined, visible: boolean): void {
export function syncRecoveryPopover(
element: HTMLElement | null | undefined,
visible: boolean,
display: "flex" | "inline-flex" = "flex",
): void {
if (!element) return;
const enterFallback = (): void => {
popoverFallbacks.add(element);
element.removeAttribute("popover");
element.style.display = visible ? "flex" : "none";
element.style.display = visible ? display : "none";
};
if (popoverFallbacks.has(element)) {
element.style.display = visible ? "flex" : "none";
element.style.display = visible ? display : "none";
return;
}
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveHostRecoveryPresentation } from "./host-recovery-presentation.js";
const base = {
visible: true,
shortcutOpen: false,
libraryAvailable: true,
builtIn: { available: false, docked: false },
library: { available: false, docked: false },
};
test("a capsule-only skin keeps both actions in the capsule", () => {
const result = resolveHostRecoveryPresentation(base);
assert.deepEqual(result.capsuleActions, ["built-in", "library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.suppressLauncher, false);
assert.equal(result.toolbar.docked, false);
});
test("a docked toolbar group removes both actions from the capsule", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.docked, { builtIn: true, library: true });
assert.deepEqual(result.capsuleActions, []);
assert.equal(result.capsuleVisible, false);
assert.equal(result.suppressLauncher, true, "the toolbar library is the only library entry");
});
test("a failed anchor returns its action to the capsule without duplicating the other", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: true, docked: false },
});
assert.deepEqual(result.docked, { builtIn: true, library: false });
assert.deepEqual(result.capsuleActions, ["library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.suppressLauncher, true, "the floating capsule now carries the only library entry");
});
test("the shortcut forces the complete capsule and hides the toolbar", () => {
const result = resolveHostRecoveryPresentation({
...base,
shortcutOpen: true,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.docked, { builtIn: false, library: false });
assert.deepEqual(result.capsuleActions, ["built-in", "library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.toolbar.visible, false);
});
test("no recovery entry means no capsule, no toolbar and no launcher suppression", () => {
const result = resolveHostRecoveryPresentation({
...base,
visible: false,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.capsuleActions, []);
assert.equal(result.capsuleVisible, false);
assert.equal(result.toolbar.visible, false);
assert.equal(result.suppressLauncher, false);
});
test("an unavailable library never renders or suppresses anything", () => {
const result = resolveHostRecoveryPresentation({
...base,
libraryAvailable: false,
library: { available: false, docked: true },
});
assert.deepEqual(result.capsuleActions, ["built-in"]);
assert.equal(result.suppressLauncher, false);
});
test("a docked built-in toolbar button leaves only the library in the capsule", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: false, docked: false },
});
assert.deepEqual(result.capsuleActions, ["library"]);
assert.equal(result.capsuleVisible, true);
});
@@ -0,0 +1,87 @@
/**
* Pure presentation decisions for the trusted recovery entry.
*
* The recovery entry has two host buttons ("use built-in skin" and
* "application library"). A skin may dock them as one capsule (the historical
* `host.recovery` slot), as one chrome-less toolbar group, or as two separate
* toolbar buttons (`host.recovery.built-in` / `host.recovery.library`).
*
* This module keeps the duplicate and fallback rules in one testable place:
* - an action is only "in the toolbar" when its anchor is currently slotted,
* so a missing/hidden anchor immediately returns it to the floating capsule;
* - the capsule renders only the actions that are not currently in the
* toolbar, so the same page never shows two copies of an action;
* - the shortcut forces every action back into the capsule (and hides the
* toolbar) so one keystroke still summons the complete recovery entry;
* - a toolbar-mode application-library action suppresses the ordinary
* `host.plugins.launcher`, because the host button is now the only library
* entry on that page (docked or floating, the capsule still offers it).
*/
export type HostRecoveryAction = "built-in" | "library";
export interface HostRecoveryToolbarActionState {
/** The slot declaration exists and the action is usable on this page. */
available: boolean;
/** The slot binding currently reports a valid, docked anchor. */
docked: boolean;
}
export interface HostRecoveryPresentationInput {
/** The recovery entry should be visible at all (third-party skin / shortcut). */
visible: boolean;
/** The recovery shortcut is currently holding the entry open. */
shortcutOpen: boolean;
/** The application library is usable (connected with a plugin session). */
libraryAvailable: boolean;
builtIn: HostRecoveryToolbarActionState;
library: HostRecoveryToolbarActionState;
}
export interface HostRecoveryPresentation {
/** Toolbar entries the host should paint (and bind) on this page. */
toolbar: HostRecoveryToolbarActionState & { visible: boolean };
/** Whether each action is currently painted by a docked toolbar button. */
docked: HostRecoveryDockedState;
/** Actions still shown by the floating capsule, in render order. */
capsuleActions: HostRecoveryAction[];
capsuleVisible: boolean;
/** Hide the ordinary plugin launcher to keep exactly one library entry. */
suppressLauncher: boolean;
}
export interface HostRecoveryDockedState {
builtIn: boolean;
library: boolean;
}
export function resolveHostRecoveryPresentation(
input: HostRecoveryPresentationInput,
): HostRecoveryPresentation {
const toolbarVisible = input.visible && !input.shortcutOpen;
const docked: HostRecoveryDockedState = {
builtIn: toolbarVisible && input.builtIn.available && input.builtIn.docked,
library: toolbarVisible && input.libraryAvailable && input.library.available && input.library.docked,
};
const capsuleActions: HostRecoveryAction[] = [];
if (input.visible && !docked.builtIn) capsuleActions.push("built-in");
if (input.visible && input.libraryAvailable && !docked.library) capsuleActions.push("library");
return {
toolbar: {
available: toolbarVisible && (input.builtIn.available || input.library.available),
docked: docked.builtIn || docked.library,
visible: toolbarVisible,
},
docked,
capsuleActions,
capsuleVisible: capsuleActions.length > 0,
// A toolbar-mode library button replaces the normal launcher even while
// its anchor is invalid, because the fallback capsule would otherwise add
// a second library entry next to that launcher.
suppressLauncher: input.visible
&& input.libraryAvailable
&& input.library.available,
};
}
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
HOST_SLOT_VIEWPORT_INSET,
INITIAL_SLOT_MODE_STATE,
computeSlotPlacement,
evaluateSlottedControl,
@@ -166,3 +167,40 @@ test("rect overlap ignores edge contact and sub-pixel slivers", () => {
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(99.5, 0, 50, 40)), false);
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(0, 60, 100, 40)), false);
});
test("toolbar buttons with long localised labels stay inside a narrow viewport", () => {
// German "Integrierten Skin verwenden" / Russian / Japanese labels make a
// toolbar button much wider than the capsule's short actions. The placement
// clamps it into the viewport; when the control is wider than the viewport
// the slot rejects it and the caller falls back to the capsule.
const viewport = { width: 320, height: 640 };
const wide = { width: 300, height: 64 };
const placement = computeSlotPlacement(rect(280, 8, 32, 32), wide, viewport, "end");
assert.ok(placement.left >= HOST_SLOT_VIEWPORT_INSET);
assert.ok(placement.left + wide.width <= viewport.width - HOST_SLOT_VIEWPORT_INSET);
const tooWide = rect(4, 8, 340, 64);
assert.deepEqual(
evaluateSlottedControl({
anchor: anchor({ rect: rect(0, 0, 320, 48) }),
controlRect: tooWide,
viewport,
minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
hitTestOk: true,
}),
{ ok: false, reason: "control-offscreen" },
"an oversized toolbar must fall back to the visible capsule, not disappear",
);
// A wrapped two-line button (64px high) still passes the minimum hit target.
assert.deepEqual(
evaluateSlottedControl({
anchor: anchor({ rect: rect(0, 0, 320, 120) }),
controlRect: rect(4, 8, 300, 64),
viewport,
minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
hitTestOk: true,
}),
{ ok: true },
);
});
+66 -15
View File
@@ -20,9 +20,11 @@ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
import {
RECOVERY_CONTROL_DEFAULTS,
applyHostControlTokens,
applyHostControlToolbarTokens,
createHostControlProbe,
findSkinRoot,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlTokens,
type HostControlProbe,
} from "./host-control-tokens.js";
@@ -271,22 +273,31 @@ function isVisibleAnchor(element: HTMLElement): boolean {
}
/**
* Resolve the first visible `[data-ws-part="<anchor>"]` inside the active
* skin's DOM. Plugin and surface hosts render inside `.ws-skin-root` too
* Resolve the first visible candidate `[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.
*
* A candidate list lets one declaration cover several pages: the home and
* voice surfaces render different prefixed parts, but only one page is visible
* at a time, so the first visible candidate is the deterministic one. The
* binding re-resolves on every check, which is what makes a page switch (or a
* skin reload) fall back and re-dock without a rebind.
*/
export function resolveSkinAnchor(
anchor: string,
anchor: string | readonly 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;
const anchors = typeof anchor === "string" ? [anchor] : anchor;
for (const candidate of anchors) {
const selector = `[data-ws-part="${candidate}"]`;
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;
@@ -300,11 +311,27 @@ export interface HostSlotModeChange {
export interface HostSlotBindingOptions {
layer: HostOwnedLayer;
control: HTMLElement;
anchor: string;
/** One anchor name, or ordered candidates (first visible one wins). */
anchor: string | readonly string[];
/** Restricts anchor resolution and token fallback to this active skin. */
skinId?: string;
align?: SkinChromeSlotAlign;
resolveAnchor?: (anchor: string) => HTMLElement | null;
/**
* `toolbar` also applies `--skin-recovery-toolbar-*` tokens (background,
* foreground, border, radius, font, font size, padding, min height, shadow).
* The capsule mode keeps the historical control tokens only.
*/
presentation?: "capsule" | "toolbar";
/**
* Called before measuring. A toolbar popover is closed while it floats, so
* its box would be 0×0 and the control could never re-dock after a fallback.
* The callback shows it for the synchronous check; `settle` hides it again
* in the same task when the anchor is still unusable, so nothing paints.
*/
prepare?: () => void;
/** Called after each evaluation with the resulting docked state. */
settle?: (slotted: boolean) => void;
resolveAnchor?: (anchor: string | readonly string[]) => HTMLElement | null;
onModeChange?: (change: HostSlotModeChange) => void;
}
@@ -332,7 +359,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
if (!view) return NOOP_BINDING;
const win = view;
const resolveAnchor = options.resolveAnchor
?? ((name: string) => resolveSkinAnchor(name, doc, options.skinId));
?? ((name: string | readonly string[]) => resolveSkinAnchor(name, doc, options.skinId));
let state = INITIAL_SLOT_MODE_STATE;
let lastReason: SlotFailureReason | undefined;
@@ -348,9 +375,9 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback);
const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
function readTokens(source: Element | null): HostControlTokens {
function readTokens(style: CSSStyleDeclaration | null): HostControlTokens {
return resolveHostControlTokens(
source ? win.getComputedStyle(source) : null,
style,
"host.recovery",
probe.probeColor,
RECOVERY_CONTROL_DEFAULTS,
@@ -400,14 +427,35 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
function evaluate(): void {
if (disposed) return;
// A floating toolbar popover is closed; show it for this synchronous
// measurement. `settle` hides it again before paint on any failure.
options.prepare?.();
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);
applyHostControlTokens(control, tokenSource ? tokens : null);
const tokenStyle = tokenSource ? win.getComputedStyle(tokenSource) : null;
const tokens = readTokens(tokenStyle);
applyHostControlTokens(control, tokenStyle ? tokens : null);
if (options.presentation === "toolbar") {
// Toolbar buttons get a second, independent token set so they can match
// a neighbouring top-bar button instead of the capsule palette. The
// resolver keeps the same contrast/font floors and falls back as a group.
applyHostControlToolbarTokens(
control,
tokenStyle
? resolveHostControlToolbarTokens(
tokenStyle,
"host.recovery",
probe.probeColor,
RECOVERY_CONTROL_DEFAULTS,
probe.isWebFont,
)
: null,
);
}
const controlBox = control.getBoundingClientRect();
maxSize = {
@@ -481,6 +529,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
lastReason = reason;
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
}
options.settle?.(state.slotted);
}
/** Any unexpected error returns the capsule to the default corner. */
@@ -488,6 +537,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
const wasSlotted = state.slotted;
state = nextSlotModeState(state, false);
clearPlacement();
options.settle?.(false);
if (wasSlotted) onModeChange?.({ mode: "floating" });
}
@@ -535,6 +585,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
win.removeEventListener("scroll", schedule, { capture: true });
clearPlacement();
applyHostControlTokens(control, null);
applyHostControlToolbarTokens(control, null);
probe.dispose();
},
};
+85
View File
@@ -0,0 +1,85 @@
<!doctype html>
<html lang="en" data-ws-route="webclient" data-ws-page="voice" data-ws-host-skin="community.legacy-slot-fixture">
<head>
<meta charset="utf-8" />
<title>Legacy recovery slot fixture</title>
<script>
try { localStorage.setItem("webspeak:instance-authorization:v1", JSON.stringify({ schemaVersion: 1, allowed: true })); } catch {}
</script>
<style>
html, body { margin: 0; width: 100%; height: 100%; font: 12px/1.5 system-ui, sans-serif; }
.ws-skin-root { position: relative; width: 100vw; height: 100vh; }
#dock { position: absolute; left: 40px; top: 120px; width: 640px; height: 56px; background: #eef4f2; }
#anchor { position: absolute; left: 0; top: 4px; width: 320px; height: 48px; }
</style>
</head>
<body>
<!-- The same anchor shape as the existing slot fixture, but through chrome.json
with the historical slot object (no `mode`). -->
<div class="ws-skin-root" data-ws-skin="community.legacy-slot-fixture" data-ws-page="voice" data-ws-part="app">
<div id="dock" data-ws-part="voice.audio-dock">
<span id="anchor" data-ws-part="skin.voice.dock.part-anchor"
style="--skin-recovery-background:#102030;--skin-recovery-foreground:#ffffff"></span>
</div>
</div>
<div id="app"></div>
<pre id="result" style="position:relative;z-index:5;background:#fff">pending</pre>
<script type="module">
import { createApp, h, nextTick } from "vue";
import HostChrome from "/src/components/HostChrome.vue";
import {
hostBuiltInSkinRequests,
setHostChromeActiveSkin,
setSkinHostChromeParts,
} from "/src/services/host-chrome.ts";
import { parseSkinChromeDocument } from "../../../src/shared/skin-chrome.ts";
import { hostOwnedLayers } from "/src/services/host-owned-layer.ts";
const output = document.getElementById("result");
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
try {
setSkinHostChromeParts(parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
// No `mode`: the historical slot must keep docking the capsule.
"host.recovery": { anchor: "skin.voice.dock.part-anchor", align: "start", compact: false },
},
})));
setHostChromeActiveSkin("community.legacy-slot-fixture");
createApp({
render: () => h(HostChrome, { language: "en", connected: true, pluginLibraryAvailable: true }),
}).mount("#app");
await nextTick();
await sleep(300);
const layer = hostOwnedLayers().find((entry) => entry.name === "recovery");
if (!layer) throw new Error("recovery layer was not created");
const capsule = layer.container.querySelector("[data-ws-host-recovery]");
const toolbar = layer.container.querySelector("[data-ws-host-recovery-toolbar]");
const anchorRect = document.getElementById("anchor").getBoundingClientRect();
const capsuleRect = capsule.getBoundingClientRect();
const button = capsule.querySelector('[data-ws-recovery-action="built-in"]');
const style = getComputedStyle(capsule);
const isOpen = Boolean(capsule.matches(":popover-open")) || style.display !== "none";
const before = hostBuiltInSkinRequests.value;
button.click();
output.textContent = JSON.stringify({
capsuleOpen: isOpen,
toolbarRendered: toolbar !== null,
insideAnchor: capsuleRect.left >= anchorRect.left - 0.5 && capsuleRect.right <= anchorRect.right + 0.5
&& capsuleRect.top >= anchorRect.top - 0.5 && capsuleRect.bottom <= anchorRect.bottom + 0.5,
actions: [...capsule.querySelectorAll("[data-ws-recovery-action]")]
.map((entry) => entry.getAttribute("data-ws-recovery-action")),
background: style.backgroundColor,
foreground: style.color,
clicked: hostBuiltInSkinRequests.value === before + 1,
});
} catch (error) {
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
}
</script>
</body>
</html>
+252
View File
@@ -0,0 +1,252 @@
<!doctype html>
<html lang="en" data-ws-route="webclient" data-ws-page="home" data-ws-host-skin="community.toolbar-fixture">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Host recovery toolbar fixture</title>
<script>
// Authorize third-party skins before instance-authorization.ts is evaluated.
try { localStorage.setItem("webspeak:instance-authorization:v1", JSON.stringify({ schemaVersion: 1, allowed: true })); } catch {}
</script>
<style>
html, body { margin: 0; width: 100%; height: 100%; font: 12px/1.5 system-ui, sans-serif; }
.ws-skin-root { position: relative; width: 100vw; height: 100vh; }
.topbar { position: absolute; left: 0; top: 0; right: 0; height: 56px; background: #f4f7fb; }
.anchor { position: absolute; top: 4px; width: 420px; height: 48px; }
#home-anchor { left: 20px; }
#voice-anchor { left: 20px; display: none; }
#dock { position: absolute; left: 12px; bottom: 12px; display: flex; gap: 8px; }
</style>
</head>
<body>
<!-- A minimal skin surface with one anchor per page. Only one is visible at a
time, exactly like a real skin switching between home and voice pages. -->
<div class="ws-skin-root" data-ws-skin="community.toolbar-fixture" data-ws-page="home" data-ws-part="app">
<div class="topbar" data-ws-part="home.header">
<span id="home-anchor" class="anchor" data-ws-part="skin.home.topbar.part-host-actions"
style="--skin-recovery-toolbar-background:#102030;--skin-recovery-toolbar-foreground:#ffffff;--skin-recovery-toolbar-border:#47dcc4;--skin-recovery-toolbar-radius:8px;--skin-recovery-toolbar-font-size:14px;--skin-recovery-toolbar-padding:6px 14px;--skin-recovery-toolbar-height:36px;--skin-recovery-toolbar-shadow:none"></span>
</div>
<div class="topbar" data-ws-part="voice.header">
<span id="voice-anchor" class="anchor" data-ws-part="skin.voice.topbar.part-host-actions"
style="--skin-recovery-toolbar-background:#102030;--skin-recovery-toolbar-foreground:#ffffff;--skin-recovery-toolbar-border:#47dcc4;--skin-recovery-toolbar-radius:8px;--skin-recovery-toolbar-font-size:14px;--skin-recovery-toolbar-padding:6px 14px;--skin-recovery-toolbar-height:36px;--skin-recovery-toolbar-shadow:none"></span>
</div>
<div id="dock" data-ws-part="voice.audio-dock">
<button type="button" data-ws-part="voice.audio-dock.microphone">Mic</button>
</div>
<button type="button" id="launcher" data-ws-part="host.plugins.launcher">Plugins</button>
</div>
<div id="app"></div>
<pre id="result" style="position:relative;z-index:5;background:#fff">pending</pre>
<script type="module">
import { createApp, h, nextTick, ref } from "vue";
import HostChrome from "/src/components/HostChrome.vue";
import {
hostBuiltInSkinRequests,
isInlineLibraryEntryVisible,
pluginLibraryRequests,
setHostChromeActiveSkin,
setSkinHostChromeParts,
} from "/src/services/host-chrome.ts";
import { parseSkinChromeDocument } from "../../../src/shared/skin-chrome.ts";
import { hostOwnedLayers } from "/src/services/host-owned-layer.ts";
import { resolveSkinAnchor } from "/src/services/host-slot-placement.ts";
const output = document.getElementById("result");
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const round = (value) => Math.round(value * 10) / 10;
const rectOf = (element) => {
const rect = element.getBoundingClientRect();
return { left: round(rect.left), top: round(rect.top), width: round(rect.width), height: round(rect.height), right: round(rect.right), bottom: round(rect.bottom) };
};
const withinViewport = (rect) => rect.left >= -0.5 && rect.top >= -0.5
&& rect.right <= innerWidth + 0.5 && rect.bottom <= innerHeight + 0.5;
const withinRect = (inner, outer) => inner.left >= outer.left - 0.5 && inner.right <= outer.right + 0.5
&& inner.top >= outer.top - 0.5 && inner.bottom <= outer.bottom + 0.5;
try {
setSkinHostChromeParts(parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery": {
mode: "toolbar",
anchor: [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
],
align: "end",
},
},
})));
setHostChromeActiveSkin("community.toolbar-fixture");
const language = ref("de");
createApp({
render: () => h(HostChrome, {
language: language.value,
connected: true,
pluginLibraryAvailable: true,
}),
}).mount("#app");
const layer = hostOwnedLayers().find((entry) => entry.name === "recovery");
if (!layer) throw new Error("recovery layer was not created");
const toolbar = () => layer.container.querySelector("[data-ws-host-recovery-toolbar]");
const capsule = () => layer.container.querySelector("[data-ws-host-recovery]");
const buttons = () => [...(toolbar()?.querySelectorAll("button") ?? [])];
const isOpen = (element) => Boolean(element?.matches?.(":popover-open"))
|| (element ? getComputedStyle(element).display !== "none" : false);
await nextTick();
await sleep(300);
const initial = toolbar();
if (!initial) throw new Error("toolbar element was not rendered");
const initialRect = rectOf(initial);
const homeRect = rectOf(document.getElementById("home-anchor"));
const first = buttons()[0];
const firstStyle = getComputedStyle(first);
const initialSnapshot = {
toolbarOpen: isOpen(initial),
insideAnchor: withinRect(initialRect, homeRect),
insideViewport: withinViewport(initialRect),
labels: buttons().map((button) => button.textContent?.trim()),
actionCount: buttons().length,
capsuleOpen: isOpen(capsule()),
background: firstStyle.backgroundColor,
foreground: firstStyle.color,
border: firstStyle.borderColor,
radius: firstStyle.borderTopLeftRadius,
fontSize: firstStyle.fontSize,
minHeight: firstStyle.minHeight,
shadow: firstStyle.boxShadow,
clickable: Boolean(first.checkVisibility?.({ opacityProperty: true, visibilityProperty: true }) ?? true),
launcherSuppressed: isInlineLibraryEntryVisible(),
rect: initialRect,
buttonRects: buttons().map(rectOf),
};
const builtInBefore = hostBuiltInSkinRequests.value;
buttons()[0].click();
const builtInClicked = hostBuiltInSkinRequests.value === builtInBefore + 1;
const libraryBefore = pluginLibraryRequests.value;
buttons()[1].click();
const libraryClicked = pluginLibraryRequests.value === libraryBefore + 1;
// Long German / Russian / Japanese labels must stay visible, inside the
// viewport and at least at the host hit-target floor.
const languages = {};
for (const lang of ["de", "ru", "ja"]) {
language.value = lang;
await nextTick();
await sleep(120);
const entries = buttons();
languages[lang] = entries.map((button) => ({
text: button.textContent?.trim(),
rect: rectOf(button),
height: button.getBoundingClientRect().height,
visible: getComputedStyle(button).display !== "none" && getComputedStyle(button).visibility !== "hidden",
inViewport: withinViewport(rectOf(button)),
}));
}
language.value = "de";
await nextTick();
await sleep(120);
// Page switch: the home anchor disappears and the voice anchor appears.
const root = document.querySelector(".ws-skin-root");
document.getElementById("home-anchor").style.display = "none";
document.getElementById("voice-anchor").style.display = "block";
root.dataset.wsPage = "voice";
await sleep(250);
const voiceRect = rectOf(document.getElementById("voice-anchor"));
const afterSwitch = {
toolbarOpen: isOpen(toolbar()),
insideVoiceAnchor: withinRect(rectOf(toolbar()), voiceRect),
insideViewport: withinViewport(rectOf(toolbar())),
resolvedVoice: resolveSkinAnchor(
["skin.home.topbar.part-host-actions", "skin.voice.topbar.part-host-actions"],
document,
"community.toolbar-fixture",
)?.id,
};
// A bad anchor must return the complete, visible floating capsule.
document.getElementById("voice-anchor").style.display = "none";
await sleep(900);
const fallbackCapsule = capsule();
const fallbackActions = [...(fallbackCapsule?.querySelectorAll('[data-ws-recovery-action]') ?? [])]
.map((button) => button.getAttribute("data-ws-recovery-action"));
const fallback = {
toolbarOpen: isOpen(toolbar()),
capsuleOpen: isOpen(fallbackCapsule),
capsuleVisible: fallbackCapsule ? getComputedStyle(fallbackCapsule).display !== "none"
&& fallbackCapsule.getBoundingClientRect().width > 0
&& fallbackCapsule.getBoundingClientRect().height > 0 : false,
capsuleActions: fallbackActions,
launcherSuppressed: isInlineLibraryEntryVisible(),
};
// Restoring the anchor re-docks after the anti-flap streak.
document.getElementById("voice-anchor").style.display = "block";
await sleep(2200);
const redocked = {
toolbarOpen: isOpen(toolbar()),
insideVoiceAnchor: withinRect(rectOf(toolbar()), rectOf(document.getElementById("voice-anchor"))),
capsuleOpen: isOpen(capsule()),
};
// The documented chord still summons the complete capsule and focuses the
// first host button, even while the toolbar is docked.
window.dispatchEvent(new KeyboardEvent("keydown", {
key: "r", ctrlKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
}));
await nextTick();
await sleep(80);
const shortcut = {
capsuleOpen: isOpen(capsule()),
toolbarOpen: isOpen(toolbar()),
focusedAction: layer.shadow.activeElement?.getAttribute?.("data-ws-recovery-action") ?? null,
capsuleActions: [...(capsule()?.querySelectorAll("[data-ws-recovery-action]") ?? [])]
.map((button) => button.getAttribute("data-ws-recovery-action")),
};
capsule().dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
await nextTick();
await sleep(150);
const afterEscape = {
capsuleOpen: isOpen(capsule()),
toolbarOpen: isOpen(toolbar()),
};
// Invalid / unreadable toolbar tokens must not make the button invisible.
const voiceAnchor = document.getElementById("voice-anchor");
voiceAnchor.style.setProperty("--skin-recovery-toolbar-background", "rgba(0,0,0,0)");
voiceAnchor.style.setProperty("--skin-recovery-toolbar-foreground", "#111111");
voiceAnchor.style.setProperty("--skin-recovery-toolbar-shadow", "url(https://example.invalid/pixel)");
await sleep(700);
const fallbackStyle = getComputedStyle(buttons()[0]);
const invalidTokens = {
background: fallbackStyle.backgroundColor,
foreground: fallbackStyle.color,
shadow: fallbackStyle.boxShadow,
visible: fallbackStyle.display !== "none" && fallbackStyle.visibility !== "hidden",
inViewport: withinViewport(rectOf(buttons()[0])),
};
output.textContent = JSON.stringify({
initial: initialSnapshot,
builtInClicked,
libraryClicked,
languages,
afterSwitch,
fallback,
redocked,
shortcut,
afterEscape,
invalidTokens,
});
} catch (error) {
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
}
</script>
</body>
</html>
+151 -1
View File
@@ -55,7 +55,7 @@ const scenarios = [
];
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([
const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin, recoveryNotice, slotPlacement, pluginPanel, presentation, controlTokens] = await Promise.all([
read("../src/components/HostChrome.vue"),
read("../src/components/InstanceAuthorization.vue"),
read("../src/services/host-owned-layer.ts"),
@@ -63,6 +63,9 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye
read("../src/composables/usePublicSkin.ts"),
read("../src/components/SkinLoadRecoveryNotice.vue"),
read("../src/services/host-slot-placement.ts"),
read("../src/components/PluginPanel.vue"),
read("../src/services/host-recovery-presentation.ts"),
read("../src/services/host-control-tokens.ts"),
]);
// Recovery: closed shadow root + manual popover + no skin hook.
@@ -86,6 +89,28 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye
assert.match(hostChrome, /activeHostSlot\("host\.recovery"\)/);
assert.match(hostChrome, /bindHostSlot\(/);
assert.match(hostChrome, /onModeChange/);
// Explicit toolbar presentation: plain host buttons, no capsule shell, real
// host click handlers and i18n labels. The mode is a separate schema field,
// not inferred from compact.
assert.match(hostChrome, /activeHostSlot\("host\.recovery\.built-in"\)/);
assert.match(hostChrome, /activeHostSlot\("host\.recovery\.library"\)/);
assert.match(hostChrome, /presentation: "toolbar"/);
assert.match(hostChrome, /resolveHostRecoveryPresentation/);
assert.match(hostChrome, /class="ws-host-toolbar-action"/);
assert.match(hostChrome, /data-ws-recovery-action="built-in"[\s\S]*?@click="useBuiltInSkin"/);
assert.match(hostChrome, /data-ws-recovery-action="library"[\s\S]*?@click="openLibrary"/);
assert.match(hostChrome, /resolveHostRecoveryPresentation\(/);
assert.match(presentation, /suppressLauncher/);
assert.match(hostChrome, /setInlineLibraryEntryVisible/);
assert.match(pluginPanel, /isInlineLibraryEntryVisible/);
assert.match(pluginPanel, /!inlineLibraryEntry/);
// Toolbar tokens are sanitized by the same shared reader with their own
// geometry defaults; no capsule shadow/radius/pale fixed background.
assert.match(controlTokens, /HOST_TOOLBAR_TOKEN_NAMES/);
assert.match(controlTokens, /resolveHostControlToolbarTokens/);
assert.match(slotPlacement, /applyHostControlToolbarTokens/);
assert.match(slotPlacement, /resolveHostControlToolbarTokens/);
assert.match(slotPlacement, /presentation === "toolbar"/);
assert.match(slotPlacement, /querySelectorAll\("\.ws-skin-root"\)/);
assert.match(slotPlacement, /isHostPartReachable\(/);
assert.match(slotPlacement, /evaluateSlottedControl/);
@@ -491,3 +516,128 @@ test("host control tokens follow late skin CSS, resolve modern colours and refus
assert.notEqual(resized.inlineBackground, resized.beforeResize, "a viewport change did not refresh @media tokens");
assert.equal(byName["after-dispose"].inlineBackground, late.inlineBackground, "a disposed binding kept observing the document");
});
test("toolbar-mode recovery docks plain host buttons, de-duplicates the library and falls back", { 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 run = async (windowSize) => {
const dom = await dumpDom(
`http://127.0.0.1:${port}/test/fixtures/host-recovery-toolbar.html`,
["--virtual-time-budget=30000", `--window-size=${windowSize}`],
);
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
assert.ok(match, "the toolbar fixture did not emit a result block");
return JSON.parse(match[1].replace(/&quot;/g, '"').replace(/&amp;/g, "&"));
};
const payload = await run("1280,800");
assert.equal(payload.error, undefined, payload.error);
const initial = payload.initial;
assert.equal(initial.toolbarOpen, true, "the toolbar did not dock into the declared anchor");
assert.equal(initial.insideAnchor, true, "the toolbar is not placed inside the page anchor");
assert.equal(initial.insideViewport, true);
assert.equal(initial.actionCount, 2, "the group slot must render both independent host buttons");
assert.deepEqual(initial.labels, ["Integrierten Skin verwenden", "Anwendungsbibliothek"]);
assert.equal(initial.capsuleOpen, false, "the capsule shell must not be shown next to a docked toolbar");
assert.equal(initial.background, "rgb(16, 32, 48)", "toolbar background token was not applied");
assert.equal(initial.foreground, "rgb(255, 255, 255)", "toolbar foreground token was not applied");
assert.equal(initial.border, "rgb(71, 220, 196)", "toolbar border token was not applied");
assert.equal(initial.radius, "8px", "toolbar radius token was not applied");
assert.equal(initial.fontSize, "14px", "toolbar font-size token was not applied");
assert.equal(initial.minHeight, "36px", "toolbar height token was not applied");
assert.equal(initial.shadow, "none", "the capsule shadow must not leak into toolbar mode");
assert.equal(initial.clickable, true);
assert.equal(initial.launcherSuppressed, true, "the host library button must replace the ordinary launcher");
assert.equal(payload.builtInClicked, true, "clicking the toolbar button must run the host reset action");
assert.equal(payload.libraryClicked, true, "clicking the toolbar library button must reach the host handler");
for (const lang of ["de", "ru", "ja"]) {
const entries = payload.languages[lang];
assert.equal(entries.length, 2, `${lang}: both host buttons must stay rendered`);
for (const entry of entries) {
assert.ok(entry.text && entry.text.length > 0, `${lang}: button lost its visible label`);
assert.equal(entry.visible, true, `${lang}: button is not visible`);
assert.equal(entry.inViewport, true, `${lang}: button escaped the viewport`);
assert.ok(entry.height >= 28, `${lang}: button fell below the host hit target (${entry.height})`);
}
}
assert.equal(payload.afterSwitch.toolbarOpen, true, "the toolbar did not survive the home -> voice page switch");
assert.equal(payload.afterSwitch.insideVoiceAnchor, true, "the toolbar stayed on the previous page anchor");
assert.equal(payload.afterSwitch.resolvedVoice, "voice-anchor", "the candidate list did not resolve the voice anchor");
assert.equal(payload.fallback.toolbarOpen, false, "the toolbar stayed visible with a broken anchor");
assert.equal(payload.fallback.capsuleVisible, true, "no visible floating recovery entry after the anchor failed");
assert.deepEqual(payload.fallback.capsuleActions, ["built-in", "library"]);
assert.equal(payload.fallback.launcherSuppressed, true, "the fallback capsule must keep exactly one library entry");
assert.equal(payload.redocked.toolbarOpen, true, "the toolbar did not re-dock after the anchor returned");
assert.equal(payload.redocked.insideVoiceAnchor, true);
assert.equal(payload.redocked.capsuleOpen, false);
assert.equal(payload.shortcut.capsuleOpen, true, "the shortcut did not summon the recovery capsule");
assert.equal(payload.shortcut.toolbarOpen, false, "the docked toolbar must yield to the summoned capsule");
assert.equal(payload.shortcut.focusedAction, "built-in", "the shortcut did not focus the first host button");
assert.deepEqual(payload.shortcut.capsuleActions, ["built-in", "library"]);
assert.equal(payload.afterEscape.capsuleOpen, false);
assert.equal(payload.afterEscape.toolbarOpen, true, "closing the shortcut did not restore the docked toolbar");
assert.equal(payload.invalidTokens.visible, true, "invalid toolbar tokens hid the button");
assert.equal(payload.invalidTokens.inViewport, true);
assert.equal(payload.invalidTokens.background, "rgb(255, 255, 255)", "transparent background must fall back to a visible surface");
assert.equal(payload.invalidTokens.foreground, "rgb(49, 82, 79)");
assert.equal(payload.invalidTokens.shadow, "none", "the invalid shadow token must not be applied");
// Narrow viewport: long labels wrap inside the viewport and stay tappable.
const narrow = await run("320,640");
assert.equal(narrow.error, undefined, narrow.error);
assert.equal(narrow.initial.toolbarOpen, true, JSON.stringify(narrow.initial));
assert.equal(narrow.initial.insideViewport, true, JSON.stringify(narrow.initial.rect));
assert.equal(narrow.initial.actionCount, 2);
for (const entry of narrow.languages.de) {
assert.equal(entry.visible, true);
assert.equal(entry.inViewport, true, JSON.stringify(entry.rect));
assert.ok(entry.height >= 28, JSON.stringify(entry));
}
});
test("legacy slots without a mode still dock the capsule", { 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 dom = await dumpDom(
`http://127.0.0.1:${port}/test/fixtures/host-recovery-legacy-slot.html`,
["--virtual-time-budget=10000", "--window-size=1280,800"],
);
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
assert.ok(match, "the legacy slot fixture did not emit a result block");
const payload = JSON.parse(match[1].replace(/&quot;/g, '"').replace(/&amp;/g, "&"));
assert.equal(payload.error, undefined, payload.error);
assert.equal(payload.capsuleOpen, true, "an old slot without mode must keep the capsule presentation");
assert.equal(payload.toolbarRendered, false, "an old slot must not grow a toolbar");
assert.equal(payload.insideAnchor, true, "the capsule did not dock into the legacy anchor");
assert.deepEqual(payload.actions, ["built-in", "library"]);
assert.equal(payload.background, "rgb(16, 32, 48)", "the capsule still reads --skin-recovery-* tokens");
assert.equal(payload.foreground, "rgb(255, 255, 255)");
assert.equal(payload.clicked, true);
});