mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
Merge PR #64: dock trusted recovery controls in skin toolbars
# Conflicts: # package.json
This commit is contained in:
commit
02509ea551
43 files changed
+3843
-141
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
@@ -310,7 +310,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`
|
||||
|
||||
|
||||
@@ -331,7 +331,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`
|
||||
|
||||
|
||||
+138
-13
@@ -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`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
@@ -438,7 +440,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
- 宿主外壳的布局与层级:应用库外壳 `host.plugins.overlay` 仍由 WebSpeak 拥有——皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform`、尺寸等把它或其子元素变成全屏遮罩。装饰性宿主部件(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)可以被重定位、改变尺寸和动画化;恢复路径不依赖它们。
|
||||
- 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。
|
||||
- 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。
|
||||
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。
|
||||
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-recovery-toolbar`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]`、`:root [data-ws-part="home.header"] [data-ws-host-recovery-toolbar]` 这类带公开钩子的混合写法)。
|
||||
- 无 Popover API 或顶层提升被拒绝时,恢复胶囊会退回固定宿主层并使用 32 位最大 `z-index: 2147483647`。宿主层在 `#app` 之后追加到 `document.body`;与树内皮肤层同为最大层级时,后绘制的宿主层仍在上面。顶层(top layer)路径的 `showPopover()` / `showModal()` 仍高于两者。
|
||||
|
||||
可主题化的宿主部件:
|
||||
@@ -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"` 替换,快捷键都会临时隐藏工具栏并显示完整胶囊。macOS 上 ⌥ 会把字母键变成派生字符(美式为 `®`),宿主同时按物理键码 `KeyR` 判定,所以该组合键仍然生效。它不与 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,12 @@ 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` 或其他字段推断。 |
|
||||
| `appearance` | 可选,`"label"`(默认)、`"icon"` 或 `"icon-and-label"`,只接受 toolbar 模式。`label` 保持旧文字按钮;`icon` 使用宿主 16px 图标、24px 宽按钮和零内边距;`icon-and-label` 同时显示图标和本地化文字。三种形态都保留 `aria-label` / `title`。胶囊只接受 `label`;未知值或胶囊中的图标形态会以 `SKIN_CHROME_SLOT_INVALID` 拒绝。 |
|
||||
|
||||
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
|
||||
|
||||
@@ -490,11 +494,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 +516,106 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
|
||||
#### 工具栏模式:把恢复按钮并进皮肤顶栏(`mode: "toolbar"`)
|
||||
|
||||
默认的恢复入口是带胶囊壳的浮动/停靠胶囊。若皮肤顶栏已有自己的按钮风格,可以在 `chrome.json` 中显式声明 `mode: "toolbar"`,让宿主在锚点位置绘制**无胶囊壳的真实宿主按钮**。按钮仍由宿主创建、标注、聚焦和点击,位于闭合 Shadow DOM 的顶层;皮肤只提供锚点、`appearance` 形态声明和 `--skin-recovery-toolbar-*` 令牌,不能替换宿主图标、文案、顺序、点击处理或取得 DOM。`.ws-host-toolbar`、`data-ws-host-recovery-toolbar` 与 `data-ws-recovery-action` 都不是公开钩子,皮肤选择器引用它们会被拒绝。
|
||||
|
||||
两种声明方式互斥,同一份 `chrome.json` 只能选一种:
|
||||
|
||||
**组合式**(两个动作共用一个锚点,并排成一组,顺序为先「使用内置皮肤」、后「应用库」):
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header", "voice.header"],
|
||||
"align": "end"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**独立式**(每个动作有自己的锚点,可放在顶栏两侧或不同部件上):
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery.built-in": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon-and-label",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "end"
|
||||
},
|
||||
"host.recovery.library": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "start"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
上面只是示意:两个独立按钮若使用同一锚点,应选不同的 `align` 或不同锚点,否则会互相覆盖。
|
||||
|
||||
规则:
|
||||
|
||||
- `mode` 省略时,`host.recovery` 仍是 `capsule`,旧皮肤行为不变;独立按钮键省略时是 `toolbar`,显式写 `capsule` 会被拒绝。模式必须显式声明,宿主不会从 `compact` 或其他字段推断。
|
||||
- `compact` 只适用于胶囊;toolbar 配 `compact` 会被拒绝。toolbar 不会折叠成 ◈;`appearance` 省略时仍显示完整文字按钮。
|
||||
- `appearance: "icon"` 只改变 toolbar 的可见内容,不移除按钮的可访问名称。宿主图标为内联 SVG,`aria-hidden="true"`;按钮保留当前语言的 `aria-label`,`title` 仍说明动作/快捷键。`icon-and-label` 同时显示图标和文字。快捷键与失败回退始终使用完整文字胶囊,不受 toolbar 外观影响。
|
||||
- 组合式下「应用库」按钮只在应用库可用(已连接且插件会话就绪)时渲染;「使用内置皮肤」始终渲染。
|
||||
- 独立式下每个动作独立停靠:一个锚点失效只把该动作放回浮动胶囊,另一个仍留在工具栏;两个都失效时显示完整浮动胶囊。toolbar 模式下的胶囊永不折叠,因为它是兜底入口而不是设计目标。
|
||||
- 回退、抗抖动和复查节奏与胶囊相同:锚点失效立即回退;恢复后需连续 2 次检查通过才重新停靠;停靠时约 400 ms 复查,浮动时约 1 s。
|
||||
- 锚点候选数组按顺序取第一个可见项;页面切换、皮肤重载或锚点显隐后会重新解析,不要求重新绑定。
|
||||
- 快捷键 `Ctrl+Alt+Shift+R` / `⌘+⌥+⇧+R` 会隐藏工具栏并召唤完整胶囊;关闭(Escape 或焦点离开)后,锚点仍有效的 toolbar 自动恢复。快捷键仍在捕获阶段处理。
|
||||
- 按钮的最小命中高度、可见图标/文字、焦点环和指针/键盘操作都由宿主保证;皮肤不能通过选择器隐藏 toolbar、移除可访问名称或把按钮变成零尺寸。`appearance` 只能选择宿主提供的三种形态。
|
||||
|
||||
**应用库去重**:只要皮肤声明了 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` / 宿主白色)。完全透明(`transparent` 或 alpha 0)会保留;非零 alpha 仍按旧规则转为不透明 RGB。 |
|
||||
| `--skin-recovery-toolbar-foreground` | 图标/文字色。与不透明按钮背景的对比度必须 ≥ 4.5;背景透明时改与 `surface` 令牌或宿主采样的锚点/祖先不透明底色比较。整组颜色不可读时,背景和文字一起回退到已解析的胶囊配色。 |
|
||||
| `--skin-recovery-toolbar-border` | 边框色。完全不透明时与有效背景的对比度必须 ≥ 3,否则使用已解析的胶囊边框;完全透明边框有效。 |
|
||||
| `--skin-recovery-toolbar-hover-background` | 悬停背景,默认使用正常背景;宿主独立检查悬停后的文字对比度,不合格时回退到正常背景。 |
|
||||
| `--skin-recovery-toolbar-hover-border` | 悬停边框,默认使用正常边框;校验颜色语法,允许 Classic 的 subtle `#b8cfe8` 边缘,不强制 3:1。 |
|
||||
| `--skin-recovery-toolbar-surface` | 可选的完全不透明底色,仅用于透明按钮/悬停背景的文字对比度检查,不绘制按钮本身。优先级为 per-part、global、锚点/祖先计算背景采样、宿主白色。渐变或图片顶栏应显式提供该令牌。 |
|
||||
| `--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` | 一个或两个长度值(`上下 左右`,或一个值表示四边相同),默认 `6px 12px`,每个方向限制 0–48 px;接受 px 和无单位 `0`。`appearance: "icon"` 时宿主强制零内边距。 |
|
||||
| `--skin-recovery-toolbar-height` | 最小高度,px。省略时保持当前尺寸档位的 28/32/36 px;显式值限制 22–72 px,因此 Classic 22px 仅在 toolbar 生效。胶囊仍保持 28/32/36 px。 |
|
||||
| `--skin-recovery-toolbar-shadow` | `none` 或单个简单 `box-shadow`(2–4 个 px 偏移/尺寸加一个颜色,最长 160 字符),默认 `none`。`url()`、`var()`、多个阴影和额外声明一律忽略为 `none`,胶囊阴影不会带入。 |
|
||||
| `--skin-recovery-toolbar-gap` | 组合式两个宿主按钮之间的间距,px,默认 4,限制 0–16;Classic 可设 `1px`。独立式各自只有一个按钮。 |
|
||||
| `--skin-recovery-toolbar-icon-size` | 宿主图标边长,px,默认 16,限制 12–24。`appearance: "icon"` 时按钮宽度为 `max(24px, icon-size + 8px)`,16px 图标对应 Classic 24px 按钮。 |
|
||||
|
||||
无效、不可读的颜色,越界的字号/高度/内边距/间距/图标尺寸,皮肤字体和非法阴影都只会回退到可见的宿主默认值,不会隐藏按钮。toolbar 文案由宿主按当前界面语言本地化,长文本换行而不是裁掉;`prefers-reduced-motion` 下同样没有过渡。
|
||||
|
||||
**Classic 麦克风按钮对齐示例**(22px 高、透明底、1px 边框、2px 圆角、11px 字号、16px 图标、1px 组间距):
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-host-toolbar-background: transparent;
|
||||
--skin-host-toolbar-foreground: #1a1a1a;
|
||||
--skin-host-toolbar-border: transparent;
|
||||
--skin-host-toolbar-hover-background: #eaf2fd;
|
||||
--skin-host-toolbar-hover-border: #b8cfe8;
|
||||
--skin-host-toolbar-radius: 2px;
|
||||
--skin-host-toolbar-font-size: 11px;
|
||||
--skin-host-toolbar-padding: 0 4px;
|
||||
--skin-host-toolbar-height: 22px;
|
||||
--skin-host-toolbar-gap: 1px;
|
||||
--skin-host-toolbar-icon-size: 16px;
|
||||
--skin-host-toolbar-surface: #ffffff;
|
||||
}
|
||||
```
|
||||
|
||||
配合 `"appearance": "icon"` 使用。`surface` 只参与可读性计算;顶栏实际不是白色时应改成真实不透明底色。图标按钮的零内边距由宿主强制执行,`padding` 令牌仍用于 `label` / `icon-and-label`。
|
||||
|
||||
**旧 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 +732,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`、`appearance`;`anchor` 可以是单个部件名或最多 8 个候选名的数组。详见上文「将恢复入口停靠到皮肤布局」与「工具栏模式」。未知键、指向 `host.*` 或可信宿主部件的锚点、`toolbar` 配 `compact`、非法 `appearance` 或胶囊中的图标形态都会被拒绝。 |
|
||||
|
||||
工具栏形态只需在 `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()` 仍走包内资源解析,无法引用外部地址。
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Host chrome toolbar example
|
||||
|
||||
A minimal schema v3 open skin that docks the trusted recovery entry into the page header as Classic-aligned, host-owned icon buttons instead of the floating capsule shell. It is the smallest reference for `chrome.json` `mode: "toolbar"`, `appearance`, page-specific anchor candidates, transparent toolbar 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)
|
||||
- Author: WebSpeak Community
|
||||
- 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, version 1.1.1, minAppVersion 0.3.3, author WebSpeak Community
|
||||
chrome.json # one grouped toolbar slot with a home/voice anchor list
|
||||
skin.css # light page theme, Classic toolbar tokens and header space
|
||||
```
|
||||
|
||||
This package requires WebSpeak 0.3.3. WebSpeak 0.3.2 does not accept `mode`, `appearance`, or anchor candidate arrays, so importing it there cannot provide toolbar-mode behavior. Older slots without those fields remain valid and keep their capsule presentation.
|
||||
|
||||
`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.
|
||||
|
||||
## Grouped declaration
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header", "voice.header"],
|
||||
"align": "end"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `mode: "toolbar"` asks the host to render two real host buttons without the capsule shell.
|
||||
- `appearance: "icon"` selects the host-owned 16px built-in-skin and application-library SVGs. Each button is 24px wide, has zero padding and keeps its localized `aria-label` and `title`.
|
||||
- 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 icons, labels, click handlers, focus behaviour, shortcut handling and fallback. The skin only supplies the anchor, appearance and token values.
|
||||
- Old slots without `mode` keep the capsule presentation; this example opts in explicitly.
|
||||
|
||||
## Classic tokens
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-host-toolbar-background: transparent;
|
||||
--skin-host-toolbar-foreground: #1a1a1a;
|
||||
--skin-host-toolbar-border: transparent;
|
||||
--skin-host-toolbar-hover-background: #eaf2fd;
|
||||
--skin-host-toolbar-hover-border: #b8cfe8;
|
||||
--skin-host-toolbar-surface: #f4f7fb;
|
||||
--skin-host-toolbar-radius: 2px;
|
||||
--skin-host-toolbar-font-size: 11px;
|
||||
--skin-host-toolbar-padding: 0 4px;
|
||||
--skin-host-toolbar-height: 22px;
|
||||
--skin-host-toolbar-gap: 1px;
|
||||
--skin-host-toolbar-icon-size: 16px;
|
||||
}
|
||||
```
|
||||
|
||||
This produces 22px-high buttons, a transparent normal surface, a 1px transparent border, 2px corners, 11px type, 16px icons and a 1px gap. Hover uses `#eaf2fd` with a `#b8cfe8` edge. `surface` is not painted; it tells the host which opaque colour to use for contrast checks. Set it to the real header colour when adapting the example.
|
||||
|
||||
The package also declares an opaque `--skin-recovery-*` capsule palette. Capsule mode keeps its historical 28/32/36px size floors, full text labels and fixed `#fff7ed` built-in action; toolbar tokens never shrink or restyle that escape hatch.
|
||||
|
||||
## Independent declaration
|
||||
|
||||
Use the per-action keys when the two actions need different anchors or appearances. Do not declare them together with `host.recovery`.
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slots": {
|
||||
"host.recovery.built-in": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon-and-label",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "end"
|
||||
},
|
||||
"host.recovery.library": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "start"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`appearance` defaults to `"label"` for backward compatibility. The accepted toolbar values are `"label"`, `"icon"` and `"icon-and-label"`; unknown values and icon appearances in capsule mode are rejected with `SKIN_CHROME_SLOT_INVALID`.
|
||||
|
||||
## 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 24px host icons appear at the end of the home and voice headers, remain transparent at rest, use the Classic hover colours, 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 free 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 full-text capsule appears and focuses its first button. Press Escape to return to the toolbar.
|
||||
7. Check a narrow viewport and all five interface languages. Icon-only names must remain available to assistive technology, and the fallback capsule must keep readable localized labels.
|
||||
|
||||
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,11 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"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.1.1",
|
||||
"author": "WebSpeak Community",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "Minimal open skin that docks Classic-aligned host-owned recovery icons into the page header.",
|
||||
"entry": "skin.css",
|
||||
"chrome": "chrome.json",
|
||||
"minAppVersion": "0.3.3"
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/* Host chrome toolbar demo — v3 open skin (schemaVersion 3).
|
||||
The host owns the recovery structure, icons, labels, focus and actions.
|
||||
This package only declares an anchor, appearance and validated tokens. */
|
||||
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--skin-demo-surface: #f4f7fb;
|
||||
--skin-demo-foreground: #1a1a1a;
|
||||
--skin-demo-border: #d5dee8;
|
||||
--skin-demo-accent: #1d4ed8;
|
||||
|
||||
/* Classic microphone-button geometry and colours. `surface` is the opaque
|
||||
colour used to check text contrast behind the transparent toolbar. */
|
||||
--skin-host-toolbar-background: transparent;
|
||||
--skin-host-toolbar-foreground: #1a1a1a;
|
||||
--skin-host-toolbar-border: transparent;
|
||||
--skin-host-toolbar-hover-background: #eaf2fd;
|
||||
--skin-host-toolbar-hover-border: #b8cfe8;
|
||||
--skin-host-toolbar-surface: #f4f7fb;
|
||||
--skin-host-toolbar-radius: 2px;
|
||||
--skin-host-toolbar-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-toolbar-font-size: 11px;
|
||||
--skin-host-toolbar-padding: 0 4px;
|
||||
--skin-host-toolbar-height: 22px;
|
||||
--skin-host-toolbar-gap: 1px;
|
||||
--skin-host-toolbar-icon-size: 16px;
|
||||
--skin-host-toolbar-shadow: none;
|
||||
|
||||
/* The fallback and shortcut capsule remains opaque and full-text. */
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #1a1a1a;
|
||||
--skin-recovery-border: #9db6b2;
|
||||
--skin-recovery-accent: #1d4ed8;
|
||||
--skin-recovery-radius: 8px;
|
||||
}
|
||||
|
||||
[data-ws-page] {
|
||||
color: #1a1a1a;
|
||||
background: #ffffff;
|
||||
font-family: Tahoma, "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"],
|
||||
[data-ws-part="voice.header"] {
|
||||
background: #f4f7fb;
|
||||
border-bottom: 1px solid var(--skin-demo-border);
|
||||
color: var(--skin-demo-foreground);
|
||||
}
|
||||
|
||||
/* Keep the two 24px icon buttons clear of ordinary header actions. */
|
||||
[data-ws-part="home.header"],
|
||||
[data-ws-part="voice.header"] {
|
||||
padding-right: 72px;
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"],
|
||||
[data-ws-part="home.content"],
|
||||
[data-ws-part="voice.workspace"],
|
||||
[data-ws-part="voice.content"] {
|
||||
color: var(--skin-demo-foreground);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"] {
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--skin-demo-border);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 16px 40px #10203012;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
background: #f4f7fb;
|
||||
border-top: 1px solid var(--skin-demo-border);
|
||||
}
|
||||
|
||||
[data-ws-part="home.footer"] { color: #52606d; }
|
||||
[data-ws-part="home.footer.clear"] { color: var(--skin-demo-accent); }
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/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/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.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/voice-ice.test.ts src/shared/voice-profile.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/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts 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/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.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/voice-ice.test.ts src/shared/voice-profile.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/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts 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 web/src/services/host-recovery-presentation.test.ts",
|
||||
"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",
|
||||
|
||||
@@ -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,39 @@ 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";
|
||||
|
||||
/** Toolbar buttons may show host-owned icons without losing their accessible names. */
|
||||
export type SkinChromeSlotAppearance = "label" | "icon" | "icon-and-label";
|
||||
|
||||
/** 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;
|
||||
/** Toolbar-only label/icon shape; the host always supplies the icon and name. */
|
||||
appearance: SkinChromeSlotAppearance;
|
||||
}
|
||||
|
||||
export interface SkinChromeAssetInfo {
|
||||
@@ -147,10 +175,36 @@ 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";
|
||||
}
|
||||
|
||||
function isSlotAppearance(value: unknown): value is SkinChromeSlotAppearance {
|
||||
return value === "label" || value === "icon" || value === "icon-and-label";
|
||||
}
|
||||
|
||||
export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
const bytes = new TextEncoder().encode(source).byteLength;
|
||||
if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) {
|
||||
@@ -226,20 +280,49 @@ 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" && key !== "appearance") {
|
||||
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");
|
||||
}
|
||||
const appearance = value.appearance === undefined ? "label" : value.appearance;
|
||||
if (!isSlotAppearance(appearance)) {
|
||||
return reject(`Slot ${part} has an invalid appearance value: ${String(appearance)}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (mode !== "toolbar" && appearance !== "label") {
|
||||
return reject(`Slot ${part} appearance is only available in toolbar mode.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots[part] = { anchor, align, compact, mode, appearance };
|
||||
}
|
||||
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",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+102
-4
@@ -108,12 +108,15 @@ test("host-owned layer attributes are not skin hooks", () => {
|
||||
for (const attribute of [
|
||||
"data-ws-host-layer",
|
||||
"data-ws-host-recovery",
|
||||
"data-ws-host-recovery-toolbar",
|
||||
"data-ws-host-layer-content",
|
||||
"data-ws-recovery-action",
|
||||
]) {
|
||||
// A public hook in the same selector gets past the "must use a public hook"
|
||||
// check, so the attribute-name rejection is what stops the selector.
|
||||
assert.throws(() => compile(`:root [${attribute}] { display: none; }`), /host attribute/, attribute);
|
||||
// A :root-prefixed mixed selector with a public part hook must also fail.
|
||||
assert.throws(() => compile(`:root [data-ws-part="home.header"] [${attribute}] { color: red; }`), /host attribute/, attribute);
|
||||
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}] { color: red; }`), /host attribute/, attribute);
|
||||
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}="x"] { color: red; }`), /host attribute/, attribute);
|
||||
}
|
||||
@@ -121,6 +124,21 @@ test("host-owned layer attributes are not skin hooks", () => {
|
||||
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] { color: teal; }'));
|
||||
});
|
||||
|
||||
test("the host toolbar's private class is not a skin hook", () => {
|
||||
for (const css of [
|
||||
':root .ws-host-toolbar { color: red; }',
|
||||
':root [data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
|
||||
'[data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
|
||||
'[data-ws-part="home.header"].ws-host-toolbar { color: red; }',
|
||||
':root .WS-HOST-TOOLBAR { color: red; }',
|
||||
':root .\\77 s-host-toolbar { color: red; }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /private host class/i, css);
|
||||
}
|
||||
// Ordinary descendant classes remain available when a public hook anchors them.
|
||||
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] .skin-button { color: teal; }'));
|
||||
});
|
||||
|
||||
test("trusted, permission, recovery and essential audio controls stay available even for v3 skins", () => {
|
||||
for (const part of [
|
||||
"voice.audio-dock",
|
||||
@@ -197,22 +215,28 @@ 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,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true },
|
||||
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true, appearance: "label" },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(explicit.slots?.["host.recovery"], {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "start",
|
||||
compact: true,
|
||||
mode: "capsule",
|
||||
appearance: "label",
|
||||
});
|
||||
|
||||
// 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 +247,8 @@ 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",
|
||||
appearance: "label",
|
||||
});
|
||||
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
@@ -246,6 +272,78 @@ 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", appearance: "text" } } }, /invalid appearance/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", appearance: "icon" } } }, /appearance is only available in toolbar mode/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "capsule", appearance: "icon-and-label" } } }, /appearance is only available in toolbar 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",
|
||||
appearance: "icon",
|
||||
},
|
||||
},
|
||||
}));
|
||||
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",
|
||||
appearance: "icon",
|
||||
});
|
||||
|
||||
const perAction = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery.built-in": {
|
||||
mode: "toolbar",
|
||||
anchor: "skin.voice.topbar.part-built-in",
|
||||
align: "start",
|
||||
appearance: "icon-and-label",
|
||||
},
|
||||
"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",
|
||||
appearance: "icon-and-label",
|
||||
});
|
||||
// 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");
|
||||
assert.equal(perAction.slots?.["host.recovery.library"]?.appearance, "label");
|
||||
|
||||
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));
|
||||
|
||||
@@ -104,9 +104,11 @@ const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
|
||||
// opting into the element by attribute.
|
||||
"data-ws-host-layer",
|
||||
"data-ws-host-recovery",
|
||||
"data-ws-host-recovery-toolbar",
|
||||
"data-ws-host-layer-content",
|
||||
"data-ws-recovery-action",
|
||||
]);
|
||||
const FORBIDDEN_SCOPE_CLASSES = new Set(["ws-host-toolbar"]);
|
||||
/** CSS-wide keywords never name a keyframe and reset an animatable slot. */
|
||||
const CSS_WIDE_KEYWORDS = new Set(["initial", "inherit", "unset", "revert", "revert-layer"]);
|
||||
/** Shorthand keyword slots; a repeated category frees the word to be the name. */
|
||||
@@ -456,6 +458,9 @@ function assertHostChromeSelector(selector: string, schemaVersion: SkinCssSchema
|
||||
if (node.type === "attribute" && FORBIDDEN_SCOPE_ATTRIBUTES.has(node.attribute.toLowerCase())) {
|
||||
throw new SkinCssValidationError(`Skin selectors cannot reference the host attribute ${node.attribute}.`, "SKIN_CSS_SELECTOR");
|
||||
}
|
||||
if (node.type === "class" && FORBIDDEN_SCOPE_CLASSES.has(decodeCssEscapes(node.value).toLowerCase())) {
|
||||
throw new SkinCssValidationError(`Skin selectors cannot reference the private host class .${node.value}.`, "SKIN_CSS_SELECTOR");
|
||||
}
|
||||
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
|
||||
partNames.push(node.value.replace(/^['"]|['"]$/g, ""));
|
||||
}
|
||||
|
||||
@@ -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.
@@ -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.`);
|
||||
@@ -28,8 +28,125 @@
|
||||
<!-- 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"
|
||||
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="built-in"
|
||||
:aria-label="copy.useBuiltIn"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
|
||||
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="pluginLibraryAvailable"
|
||||
type="button"
|
||||
class="ws-host-toolbar-action"
|
||||
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="library"
|
||||
:aria-label="copy.library"
|
||||
:title="copy.library"
|
||||
@click="openLibrary"
|
||||
>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
|
||||
</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"
|
||||
:class="{ 'ws-host-toolbar-action-icon': builtInToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="built-in"
|
||||
:aria-label="copy.useBuiltIn"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>
|
||||
<span v-if="builtInToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
|
||||
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="builtInToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
|
||||
</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"
|
||||
:class="{ 'ws-host-toolbar-action-icon': libraryToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="library"
|
||||
:aria-label="copy.library"
|
||||
:title="copy.library"
|
||||
@click="openLibrary"
|
||||
>
|
||||
<span v-if="libraryToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="libraryToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref="recoveryPopover"
|
||||
popover="manual"
|
||||
@@ -38,7 +155,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 +163,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 +171,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 +183,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 +196,7 @@ import {
|
||||
isThirdPartySkinActive,
|
||||
openPluginLibrary,
|
||||
requestBuiltInSkin,
|
||||
setInlineLibraryEntryVisible,
|
||||
} from "../services/host-chrome.js";
|
||||
import {
|
||||
createHostOwnedLayer,
|
||||
@@ -89,13 +209,16 @@ import {
|
||||
type FloatingAvoidance,
|
||||
type FloatingPosition,
|
||||
} from "../services/host-floating-placement.js";
|
||||
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
|
||||
import { shouldShowRecovery, type HostPartRect } from "../services/host-chrome-visibility.js";
|
||||
import { thirdPartyAllowed } from "../services/instance-authorization.js";
|
||||
import {
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
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 +287,70 @@ 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: var(--ws-toolbar-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;
|
||||
gap: 4px;
|
||||
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 {
|
||||
border-color: var(--ws-toolbar-hover-border, var(--ws-toolbar-border, #9db6b2));
|
||||
background: var(--ws-toolbar-hover-background, var(--ws-toolbar-background, #fff));
|
||||
}
|
||||
.ws-host-toolbar-action:focus-visible {
|
||||
outline: 2px solid var(--ws-toolbar-focus, var(--ws-control-accent, #4c8f88));
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.ws-host-toolbar-icon {
|
||||
display: block;
|
||||
flex: 0 0 auto;
|
||||
width: var(--ws-toolbar-icon-size, 16px);
|
||||
height: var(--ws-toolbar-icon-size, 16px);
|
||||
}
|
||||
.ws-host-toolbar-icon svg { display: block; width: 100%; height: 100%; }
|
||||
.ws-host-toolbar-action-icon {
|
||||
width: max(24px, calc(var(--ws-toolbar-icon-size, 16px) + 8px));
|
||||
padding: 0;
|
||||
}
|
||||
@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 +375,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 +408,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 +482,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;
|
||||
@@ -267,40 +498,145 @@ function onRecoveryEscape() {
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
/** Unpin when the pointer goes down anywhere outside the host layer. */
|
||||
/** Dismiss shortcut expansion and unpin on pointer down outside the host layer. */
|
||||
function onDocumentPointerDown(event: PointerEvent) {
|
||||
if (!compactPinned.value || !layer) return;
|
||||
if (!layer) return;
|
||||
// Events from inside the closed shadow root are retargeted to its host.
|
||||
if (event.composedPath().includes(layer.host)) return;
|
||||
shortcutOpen.value = false;
|
||||
shortcutExpanded.value = false;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
function onRecoveryFocusOut(event: FocusEvent) {
|
||||
const next = event.relatedTarget;
|
||||
if (next instanceof Node && recoveryPopover.value?.contains(next)) return;
|
||||
shortcutOpen.value = false;
|
||||
shortcutExpanded.value = false;
|
||||
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",
|
||||
);
|
||||
}
|
||||
|
||||
/** A toolbar that is currently displayed (top layer or display fallback). */
|
||||
function isToolbarShown(control: HTMLElement | null): boolean {
|
||||
if (!control) return false;
|
||||
if (control.matches?.(":popover-open")) return true;
|
||||
const rect = control.getBoundingClientRect();
|
||||
return getComputedStyle(control).display !== "none" && rect.width > 0 && rect.height > 0;
|
||||
}
|
||||
|
||||
function rectOf(control: HTMLElement): HostPartRect {
|
||||
const rect = control.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left, top: rect.top, width: rect.width, height: rect.height,
|
||||
right: rect.right, bottom: rect.bottom,
|
||||
};
|
||||
}
|
||||
|
||||
/** Every recovery toolbar currently docked in the top layer. */
|
||||
function dockedToolbarRects(): HostPartRect[] {
|
||||
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
|
||||
.filter((element): element is HTMLElement => Boolean(element) && isToolbarShown(element))
|
||||
.map(rectOf);
|
||||
}
|
||||
|
||||
/** Other docked recovery toolbars this entry must not cover on a narrow screen. */
|
||||
function otherToolbarRects(control: HTMLElement): HostPartRect[] {
|
||||
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
|
||||
.filter((element): element is HTMLElement => Boolean(element)
|
||||
&& element !== control && isToolbarShown(element))
|
||||
.map(rectOf);
|
||||
}
|
||||
|
||||
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",
|
||||
otherControls: () => otherToolbarRects(control),
|
||||
// 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,
|
||||
// A slotted capsule must not cover a still-docked split toolbar either.
|
||||
otherControls: () => dockedToolbarRects(),
|
||||
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() {
|
||||
@@ -331,6 +667,11 @@ function bindFloating() {
|
||||
return { width: hit + 10, height: hit + 10 };
|
||||
},
|
||||
onCompactChange: next => { floatCompact.value = next; },
|
||||
// Docked toolbars are inside the closed shadow root, so the light-DOM
|
||||
// obstacle scan cannot see them. In split mode the library toolbar falls
|
||||
// back to this capsule while the built-in toolbar stays docked; without
|
||||
// this exclusion the capsule could cover it (320px GUI failure).
|
||||
avoidRects: () => dockedToolbarRects(),
|
||||
// Never move the capsule under the user's pointer or focus, and leave a
|
||||
// docked capsule to the slot binding.
|
||||
paused: () => slotMode.value === "slotted"
|
||||
@@ -341,10 +682,6 @@ function bindFloating() {
|
||||
});
|
||||
}
|
||||
|
||||
function syncPopover() {
|
||||
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
|
||||
}
|
||||
|
||||
function useBuiltInSkin() {
|
||||
shortcutOpen.value = false;
|
||||
requestBuiltInSkin();
|
||||
@@ -364,8 +701,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 +716,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 +783,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;
|
||||
|
||||
@@ -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,12 @@ test("slot declarations are honoured for third-party skins only", () => {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "end",
|
||||
compact: false,
|
||||
mode: "capsule",
|
||||
appearance: "label",
|
||||
});
|
||||
// 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"]) {
|
||||
|
||||
@@ -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
|
||||
@@ -116,16 +133,18 @@ export function requestBuiltInSkin(): void {
|
||||
builtInSkinRequests.value += 1;
|
||||
}
|
||||
|
||||
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key">;
|
||||
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key" | "code">;
|
||||
|
||||
/**
|
||||
* The documented recovery shortcut: Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS.
|
||||
* The letter is matched case-insensitively, but every modifier is required so
|
||||
* ordinary app shortcuts (Ctrl+R, Alt+R, Ctrl+Shift+R) keep their meaning.
|
||||
* On macOS, Option/Shift turn the letter key into a derived character (US
|
||||
* layout: ®), so `event.key` is not "r". Match the physical `code` as well;
|
||||
* every modifier is still required so ordinary app shortcuts (Ctrl+R, Alt+R,
|
||||
* Ctrl+Shift+R) keep their meaning.
|
||||
*/
|
||||
export function isRecoveryShortcut(event: RecoveryShortcutEvent): boolean {
|
||||
return (event.ctrlKey || event.metaKey)
|
||||
&& event.altKey
|
||||
&& event.shiftKey
|
||||
&& event.key.toLowerCase() === "r";
|
||||
&& (event.key?.toLowerCase() === "r" || event.code === "KeyR");
|
||||
}
|
||||
@@ -9,19 +9,38 @@ 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_GAP,
|
||||
TOOLBAR_DEFAULT_ICON_SIZE,
|
||||
TOOLBAR_DEFAULT_PADDING_X,
|
||||
TOOLBAR_DEFAULT_PADDING_Y,
|
||||
TOOLBAR_DEFAULT_RADIUS,
|
||||
TOOLBAR_MAX_FONT_SIZE,
|
||||
TOOLBAR_MAX_GAP,
|
||||
TOOLBAR_MAX_HEIGHT,
|
||||
TOOLBAR_MAX_ICON_SIZE,
|
||||
TOOLBAR_MAX_PADDING,
|
||||
TOOLBAR_MIN_HEIGHT,
|
||||
TOOLBAR_MIN_ICON_SIZE,
|
||||
applyHostControlTokens,
|
||||
applyHostControlToolbarTokens,
|
||||
compositeRgb,
|
||||
contrastRatio,
|
||||
fontFamilyNames,
|
||||
formatRgb,
|
||||
hasHostControlTokens,
|
||||
hasHostToolbarTokens,
|
||||
hostControlTokenKey,
|
||||
hostControlTokenProperty,
|
||||
hostToolbarTokenProperty,
|
||||
parseCssColor,
|
||||
parseCssColorWithAlpha,
|
||||
relativeLuminance,
|
||||
resolveHostControlTokens,
|
||||
resolveHostControlToolbarTokens,
|
||||
type HostControlRawTokens,
|
||||
} from "./host-control-tokens.js";
|
||||
|
||||
@@ -254,6 +273,13 @@ test("CSS colours parse to RGB and ignore alpha for contrast", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("alpha colours parse and composite over opaque toolbar surfaces", () => {
|
||||
assert.deepEqual(parseCssColorWithAlpha("transparent"), { r: 0, g: 0, b: 0, a: 0 });
|
||||
assert.deepEqual(parseCssColorWithAlpha("#10203080"), { r: 16, g: 32, b: 48, a: 128 / 255 });
|
||||
assert.deepEqual(parseCssColorWithAlpha("rgb(255 0 0 / 50%)"), { r: 255, g: 0, b: 0, a: 0.5 });
|
||||
assert.deepEqual(compositeRgb({ r: 0, g: 0, b: 0, a: 0.5 }, { r: 255, g: 255, b: 255 }), { r: 128, g: 128, b: 128 });
|
||||
});
|
||||
|
||||
test("WCAG contrast follows the relative-luminance formula", () => {
|
||||
assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0);
|
||||
assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1);
|
||||
@@ -281,3 +307,260 @@ 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 = {}, sampledSurface?: { r: number; g: number; b: number }) =>
|
||||
resolveHostControlToolbarTokens(
|
||||
style({ ...tokens, ...global }),
|
||||
"host.recovery",
|
||||
raw => raw,
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
undefined,
|
||||
sampledSurface,
|
||||
);
|
||||
|
||||
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(49, 82, 79)");
|
||||
assert.ok(contrastRatio(parseCssColor(defaults.border)!, parseCssColor(defaults.background)!) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
|
||||
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("toolbar colours preserve transparency and check text against an opaque surface", () => {
|
||||
const classic = resolveToolbar({
|
||||
"--skin-recovery-toolbar-background": "transparent",
|
||||
"--skin-recovery-toolbar-foreground": "#1a1a1a",
|
||||
"--skin-recovery-toolbar-border": "transparent",
|
||||
"--skin-recovery-toolbar-hover-background": "#eaf2fd",
|
||||
"--skin-recovery-toolbar-hover-border": "#b8cfe8",
|
||||
}, {}, { r: 255, g: 255, b: 255 });
|
||||
assert.equal(classic.background, "transparent");
|
||||
assert.equal(classic.border, "transparent");
|
||||
assert.equal(classic.foreground, "rgb(26, 26, 26)");
|
||||
assert.equal(classic.hoverBackground, "rgb(234, 242, 253)");
|
||||
assert.equal(classic.hoverBorder, "rgb(184, 207, 232)");
|
||||
|
||||
const explicitDarkSurface = resolveToolbar({
|
||||
"--skin-recovery-toolbar-background": "#00000000",
|
||||
"--skin-recovery-toolbar-foreground": "#ffffff",
|
||||
"--skin-recovery-toolbar-surface": "#102030",
|
||||
}, {}, { r: 255, g: 255, b: 255 });
|
||||
assert.equal(explicitDarkSurface.background, "transparent");
|
||||
assert.equal(explicitDarkSurface.foreground, "rgb(255, 255, 255)");
|
||||
|
||||
const sampledDarkSurface = resolveToolbar({
|
||||
"--skin-recovery-toolbar-background": "transparent",
|
||||
"--skin-recovery-toolbar-foreground": "#ffffff",
|
||||
}, {}, { r: 16, g: 32, b: 48 });
|
||||
assert.equal(sampledDarkSurface.background, "transparent");
|
||||
assert.equal(sampledDarkSurface.foreground, "rgb(255, 255, 255)");
|
||||
|
||||
const globalSurface = resolveToolbar({
|
||||
"--skin-recovery-toolbar-background": "transparent",
|
||||
"--skin-recovery-toolbar-foreground": "#ffffff",
|
||||
}, { "--skin-host-toolbar-surface": "#102030" }, { r: 255, g: 255, b: 255 });
|
||||
assert.equal(globalSurface.foreground, "rgb(255, 255, 255)");
|
||||
});
|
||||
|
||||
test("toolbar border and focus colours are rechecked against the final surface", () => {
|
||||
const palette = {
|
||||
"--skin-recovery-background": "#000000",
|
||||
"--skin-recovery-foreground": "#ffffff",
|
||||
"--skin-recovery-border": "#ffffff",
|
||||
"--skin-recovery-accent": "#ffffff",
|
||||
"--skin-recovery-toolbar-foreground": "#000000",
|
||||
"--skin-recovery-toolbar-surface": "#ffffff",
|
||||
};
|
||||
for (const background of ["#ffffff", "transparent"]) {
|
||||
for (const border of [undefined, "#ffffff"]) {
|
||||
const toolbar = resolveToolbar({
|
||||
...palette,
|
||||
"--skin-recovery-toolbar-background": background,
|
||||
...(border ? { "--skin-recovery-toolbar-border": border } : {}),
|
||||
});
|
||||
const surface = parseCssColor(background === "transparent" ? palette["--skin-recovery-toolbar-surface"] : background)!;
|
||||
assert.ok(contrastRatio(parseCssColor(toolbar.border)!, surface) >= HOST_CONTROL_MIN_BORDER_CONTRAST,
|
||||
`${background} background with ${border ?? "inherited"} border produced ${toolbar.border}`);
|
||||
assert.ok(contrastRatio(parseCssColor(toolbar.focus)!, surface) >= HOST_CONTROL_MIN_ACCENT_CONTRAST,
|
||||
`${background} background produced ${toolbar.focus} focus ring`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("toolbar hover colours and Classic geometry are sanitized independently", () => {
|
||||
const classic = resolveToolbar({
|
||||
"--skin-recovery-toolbar-height": "22px",
|
||||
"--skin-recovery-toolbar-padding": "0 4px",
|
||||
"--skin-recovery-toolbar-radius": "2px",
|
||||
"--skin-recovery-toolbar-font-size": "11px",
|
||||
"--skin-recovery-toolbar-gap": "1px",
|
||||
"--skin-recovery-toolbar-icon-size": "16px",
|
||||
});
|
||||
assert.equal(classic.minHeight, 22);
|
||||
assert.equal(classic.paddingX, 4);
|
||||
assert.equal(classic.paddingY, 0);
|
||||
assert.equal(classic.radius, 2);
|
||||
assert.equal(classic.fontSize, 11);
|
||||
assert.equal(classic.gap, 1);
|
||||
assert.equal(classic.iconSize, 16);
|
||||
|
||||
const unreadableHover = resolveToolbar({
|
||||
"--skin-recovery-toolbar-background": "#ffffff",
|
||||
"--skin-recovery-toolbar-foreground": "#757575",
|
||||
"--skin-recovery-toolbar-hover-background": "#eeeeee",
|
||||
"--skin-recovery-toolbar-hover-border": "not-a-colour",
|
||||
});
|
||||
assert.equal(unreadableHover.hoverBackground, "rgb(255, 255, 255)");
|
||||
assert.equal(unreadableHover.hoverBorder, "rgb(49, 82, 79)");
|
||||
|
||||
const clamped = resolveToolbar({
|
||||
"--skin-recovery-toolbar-gap": "100px",
|
||||
"--skin-recovery-toolbar-icon-size": "2px",
|
||||
});
|
||||
assert.equal(clamped.gap, TOOLBAR_MAX_GAP);
|
||||
assert.equal(clamped.iconSize, TOOLBAR_MIN_ICON_SIZE);
|
||||
const oversized = resolveToolbar({ "--skin-recovery-toolbar-icon-size": "100px" });
|
||||
assert.equal(oversized.iconSize, TOOLBAR_MAX_ICON_SIZE);
|
||||
assert.equal(resolveToolbar().gap, TOOLBAR_DEFAULT_GAP);
|
||||
assert.equal(resolveToolbar().iconSize, TOOLBAR_DEFAULT_ICON_SIZE);
|
||||
});
|
||||
|
||||
test("capsule tokens keep their opaque palette and 28px hit target", () => {
|
||||
const capsule = resolveHostControlTokens(style({
|
||||
"--skin-recovery-background": "transparent",
|
||||
"--skin-recovery-foreground": "#1a1a1a",
|
||||
"--skin-recovery-toolbar-height": "22px",
|
||||
}), "host.recovery", raw => raw, RECOVERY_CONTROL_DEFAULTS);
|
||||
assert.equal(capsule.background, "rgb(255, 255, 255)");
|
||||
assert.equal(capsule.hitTarget, 28);
|
||||
});
|
||||
|
||||
test("unreadable or invalid toolbar tokens fall back to a visible, readable button", () => {
|
||||
const transparentUnreadable = resolveToolbar({
|
||||
"--skin-recovery-toolbar-background": "rgba(0, 0, 0, 0)",
|
||||
"--skin-recovery-toolbar-foreground": "#ffffff",
|
||||
}, {}, { r: 255, g: 255, b: 255 });
|
||||
assert.equal(transparentUnreadable.background, "rgb(255, 255, 255)");
|
||||
assert.equal(transparentUnreadable.foreground, "rgb(49, 82, 79)");
|
||||
assert.ok(contrastRatio(parseCssColor(transparentUnreadable.foreground)!, parseCssColor(transparentUnreadable.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, TOOLBAR_MIN_HEIGHT);
|
||||
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": "#ffffff",
|
||||
"--skin-recovery-toolbar-foreground": "#1a1a1a",
|
||||
"--skin-recovery-toolbar-padding": "6px 14px",
|
||||
"--skin-recovery-toolbar-height": "36px",
|
||||
"--skin-recovery-toolbar-hover-background": "#eaf2fd",
|
||||
"--skin-recovery-toolbar-hover-border": "#b8cfe8",
|
||||
"--skin-recovery-toolbar-gap": "1px",
|
||||
"--skin-recovery-toolbar-icon-size": "16px",
|
||||
}));
|
||||
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.background), "rgb(255, 255, 255)");
|
||||
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.foreground), "rgb(26, 26, 26)");
|
||||
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");
|
||||
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBackground), "rgb(234, 242, 253)");
|
||||
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBorder), "rgb(184, 207, 232)");
|
||||
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.gap), "1px");
|
||||
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.iconSize), "16px");
|
||||
applyHostControlToolbarTokens(control, null);
|
||||
assert.equal(values.size, 0);
|
||||
});
|
||||
@@ -44,6 +44,42 @@ 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",
|
||||
"hover-background", "hover-border", "surface", "gap", "icon-size",
|
||||
] 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",
|
||||
"hover-background": "--skin-host-toolbar-hover-background",
|
||||
"hover-border": "--skin-host-toolbar-hover-border",
|
||||
surface: "--skin-host-toolbar-surface",
|
||||
gap: "--skin-host-toolbar-gap",
|
||||
"icon-size": "--skin-host-toolbar-icon-size",
|
||||
};
|
||||
|
||||
/** 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 +110,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 +128,25 @@ 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",
|
||||
hoverBackground: "--ws-toolbar-hover-background",
|
||||
hoverBorder: "--ws-toolbar-hover-border",
|
||||
gap: "--ws-toolbar-gap",
|
||||
iconSize: "--ws-toolbar-icon-size",
|
||||
} as const;
|
||||
|
||||
export interface HostControlRawTokens {
|
||||
/** Computed-style colour values; unresolved values are rejected. */
|
||||
accent?: string;
|
||||
@@ -130,12 +189,39 @@ 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; defaults to the size tier and may reach 22px in toolbar mode. */
|
||||
minHeight: number;
|
||||
shadow: string;
|
||||
hoverBackground: string;
|
||||
hoverBorder: string;
|
||||
/** Space between grouped host buttons. */
|
||||
gap: number;
|
||||
/** Size of the host-owned toolbar icon. */
|
||||
iconSize: number;
|
||||
/** Focus ring colour, from the readable accent of the control palette. */
|
||||
focus: string;
|
||||
}
|
||||
|
||||
export interface RgbColor {
|
||||
r: number;
|
||||
g: number;
|
||||
b: number;
|
||||
}
|
||||
|
||||
export interface RgbaColor extends RgbColor {
|
||||
a: number;
|
||||
}
|
||||
|
||||
const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 };
|
||||
const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 };
|
||||
const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 };
|
||||
@@ -147,6 +233,29 @@ 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; only an explicit height may reach 22px. */
|
||||
export const TOOLBAR_MIN_HEIGHT = 22;
|
||||
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;
|
||||
export const TOOLBAR_DEFAULT_GAP = 4;
|
||||
export const TOOLBAR_MAX_GAP = 16;
|
||||
export const TOOLBAR_DEFAULT_ICON_SIZE = 16;
|
||||
export const TOOLBAR_MIN_ICON_SIZE = 12;
|
||||
export const TOOLBAR_MAX_ICON_SIZE = 24;
|
||||
const MAX_SHADOW_LENGTH = 160;
|
||||
const LENGTH_PX_PATTERN = /^(-?\d+(?:\.\d+)?)px$/i;
|
||||
const PADDING_PATTERN = /^(0|\d+(?:\.\d+)?px)(?:\s+(0|\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
|
||||
@@ -206,10 +315,11 @@ export const PERMISSION_CONTROL_DEFAULTS: HostControlDefaults = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
|
||||
export function parseCssColor(value: string | undefined | null): RgbColor | null {
|
||||
/** Parse CSS colours to sRGB channels plus alpha for toolbar transparency checks. */
|
||||
export function parseCssColorWithAlpha(value: string | undefined | null): RgbaColor | null {
|
||||
if (!value) return null;
|
||||
const text = value.trim().toLowerCase();
|
||||
if (text === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
|
||||
const hex = /^#([0-9a-f]{3,8})$/.exec(text);
|
||||
if (hex) {
|
||||
const digits = hex[1];
|
||||
@@ -218,6 +328,7 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
|
||||
r: Number.parseInt(digits[0] + digits[0], 16),
|
||||
g: Number.parseInt(digits[1] + digits[1], 16),
|
||||
b: Number.parseInt(digits[2] + digits[2], 16),
|
||||
a: digits.length === 4 ? Number.parseInt(digits[3] + digits[3], 16) / 255 : 1,
|
||||
};
|
||||
}
|
||||
if (digits.length === 6 || digits.length === 8) {
|
||||
@@ -225,6 +336,7 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
|
||||
r: Number.parseInt(digits.slice(0, 2), 16),
|
||||
g: Number.parseInt(digits.slice(2, 4), 16),
|
||||
b: Number.parseInt(digits.slice(4, 6), 16),
|
||||
a: digits.length === 8 ? Number.parseInt(digits.slice(6, 8), 16) / 255 : 1,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
@@ -242,7 +354,30 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
|
||||
const channel = percent ? parsed * 2.55 : parsed;
|
||||
channels.push(Math.round(Math.min(255, Math.max(0, channel))));
|
||||
}
|
||||
return { r: channels[0], g: channels[1], b: channels[2] };
|
||||
let alpha = 1;
|
||||
if (parts.length === 4) {
|
||||
const rawAlpha = Number.parseFloat(parts[3]);
|
||||
if (!Number.isFinite(rawAlpha)) return null;
|
||||
alpha = parts[3].endsWith("%") ? rawAlpha / 100 : rawAlpha;
|
||||
alpha = Math.min(1, Math.max(0, alpha));
|
||||
}
|
||||
return { r: channels[0], g: channels[1], b: channels[2], a: alpha };
|
||||
}
|
||||
|
||||
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
|
||||
export function parseCssColor(value: string | undefined | null): RgbColor | null {
|
||||
const color = parseCssColorWithAlpha(value);
|
||||
return color ? { r: color.r, g: color.g, b: color.b } : null;
|
||||
}
|
||||
|
||||
/** Composite a possibly translucent colour over an opaque sRGB surface. */
|
||||
export function compositeRgb(foreground: RgbaColor, background: RgbColor): RgbColor {
|
||||
const alpha = Math.min(1, Math.max(0, foreground.a));
|
||||
return {
|
||||
r: Math.round(foreground.r * alpha + background.r * (1 - alpha)),
|
||||
g: Math.round(foreground.g * alpha + background.g * (1 - alpha)),
|
||||
b: Math.round(foreground.b * alpha + background.b * (1 - alpha)),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatRgb(color: RgbColor): string {
|
||||
@@ -449,6 +584,225 @@ 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(TOOLBAR_MIN_HEIGHT, height))
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function sanitizeToolbarLength(value: string | undefined, fallback: number, min: number, max: number): number {
|
||||
if (!value) return fallback;
|
||||
const match = LENGTH_PX_PATTERN.exec(value.trim());
|
||||
if (!match) return fallback;
|
||||
const length = Number.parseFloat(match[1]);
|
||||
return Number.isFinite(length) ? Math.min(max, Math.max(min, length)) : 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())
|
||||
);
|
||||
}
|
||||
|
||||
function parseToolbarColor(raw: string | undefined, probeColor: ColorProbe): RgbaColor | null {
|
||||
return parseCssColorWithAlpha(raw ? probeColor(raw) : undefined);
|
||||
}
|
||||
|
||||
function formatToolbarColor(color: RgbaColor): string {
|
||||
return color.a === 0 ? "transparent" : formatRgb(color);
|
||||
}
|
||||
|
||||
function resolveToolbarSurface(
|
||||
partTokens: Partial<Record<HostToolbarTokenName, string>>,
|
||||
globalTokens: Partial<Record<HostToolbarTokenName, string>>,
|
||||
probeColor: ColorProbe,
|
||||
sampledSurface: RgbColor | null | undefined,
|
||||
defaults: HostControlDefaults,
|
||||
): RgbColor {
|
||||
for (const raw of [partTokens.surface, globalTokens.surface]) {
|
||||
const color = parseToolbarColor(raw, probeColor);
|
||||
if (color?.a === 1) return { r: color.r, g: color.g, b: color.b };
|
||||
}
|
||||
return sampledSurface ?? defaults.background;
|
||||
}
|
||||
|
||||
function readableColorOn(candidates: readonly RgbColor[], background: RgbColor): RgbColor {
|
||||
const readable = candidates.find((color) => contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
|
||||
if (readable) return readable;
|
||||
return contrastRatio(ON_ACCENT_DARK, background) >= contrastRatio(ON_ACCENT_LIGHT, background)
|
||||
? ON_ACCENT_DARK
|
||||
: ON_ACCENT_LIGHT;
|
||||
}
|
||||
|
||||
function resolveToolbarBorder(
|
||||
raw: string | undefined,
|
||||
background: RgbColor,
|
||||
fallbacks: readonly RgbColor[],
|
||||
probeColor: ColorProbe,
|
||||
): string {
|
||||
const color = parseToolbarColor(raw, probeColor);
|
||||
if (!color) return formatRgb(readableColorOn(fallbacks, background));
|
||||
if (color.a === 0) return "transparent";
|
||||
return contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST
|
||||
? formatRgb(color)
|
||||
: formatRgb(readableColorOn(fallbacks, background));
|
||||
}
|
||||
|
||||
function resolveToolbarHoverBorder(raw: string | undefined, fallback: string, probeColor: ColorProbe): string {
|
||||
const color = parseToolbarColor(raw, probeColor);
|
||||
if (!color) return fallback;
|
||||
// Classic's subtle #b8cfe8 hover edge is intentionally below the 3:1
|
||||
// non-text contrast floor; validate syntax without rejecting that design.
|
||||
return formatToolbarColor(color);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the toolbar button palette and geometry.
|
||||
*
|
||||
* Transparent backgrounds and borders are valid. Text is checked against an
|
||||
* explicit opaque `surface` token, or the caller's sampled anchor/ancestor
|
||||
* surface, never against transparent black. Opaque colours keep the existing
|
||||
* capsule contrast floors. Hover colours fall back independently to the normal
|
||||
* button colours, and only an explicit toolbar height may reach the 22px
|
||||
* Classic toolbar floor; the size-tier default remains 28/32/36px.
|
||||
*/
|
||||
export function resolveHostControlToolbarTokens(
|
||||
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
|
||||
part: string,
|
||||
probeColor: ColorProbe,
|
||||
defaults: HostControlDefaults,
|
||||
isWebFont: WebFontCheck = NO_WEB_FONTS,
|
||||
sampledSurface?: RgbColor | null,
|
||||
): 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;
|
||||
const baseAccent = parseCssColor(base.accent) ?? defaults.accent;
|
||||
const surface = resolveToolbarSurface(partTokens, globalTokens, probeColor, sampledSurface, defaults);
|
||||
let background = parseToolbarColor(merged.background, probeColor) ?? { ...baseBackground, a: 1 };
|
||||
let foreground = parseToolbarColor(merged.foreground, probeColor) ?? { ...baseForeground, a: 1 };
|
||||
let effectiveBackground = background.a === 0 ? surface : background;
|
||||
if (contrastRatio(foreground, effectiveBackground) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
|
||||
background = { ...baseBackground, a: 1 };
|
||||
foreground = { ...baseForeground, a: 1 };
|
||||
effectiveBackground = baseBackground;
|
||||
}
|
||||
const border = resolveToolbarBorder(merged.border, effectiveBackground, [baseBorder, baseForeground], probeColor);
|
||||
|
||||
let hoverBackground = parseToolbarColor(merged["hover-background"], probeColor) ?? background;
|
||||
let effectiveHoverBackground = hoverBackground.a === 0 ? surface : hoverBackground;
|
||||
if (contrastRatio(foreground, effectiveHoverBackground) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
|
||||
hoverBackground = background;
|
||||
effectiveHoverBackground = effectiveBackground;
|
||||
}
|
||||
const hoverBorder = resolveToolbarHoverBorder(merged["hover-border"], border, probeColor);
|
||||
const padding = sanitizeToolbarPadding(merged.padding);
|
||||
|
||||
return {
|
||||
background: formatToolbarColor(background),
|
||||
foreground: formatRgb(foreground),
|
||||
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",
|
||||
hoverBackground: formatToolbarColor(hoverBackground),
|
||||
hoverBorder,
|
||||
gap: sanitizeToolbarLength(merged.gap, TOOLBAR_DEFAULT_GAP, 0, TOOLBAR_MAX_GAP),
|
||||
iconSize: sanitizeToolbarLength(
|
||||
merged["icon-size"],
|
||||
TOOLBAR_DEFAULT_ICON_SIZE,
|
||||
TOOLBAR_MIN_ICON_SIZE,
|
||||
TOOLBAR_MAX_ICON_SIZE,
|
||||
),
|
||||
focus: formatRgb(readableColorOn([baseAccent, baseForeground], effectiveBackground)),
|
||||
};
|
||||
}
|
||||
|
||||
/** 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);
|
||||
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBackground, tokens.hoverBackground);
|
||||
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBorder, tokens.hoverBorder);
|
||||
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.gap, `${tokens.gap}px`);
|
||||
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.iconSize, `${tokens.iconSize}px`);
|
||||
}
|
||||
|
||||
export interface HostControlThemeBindingOptions {
|
||||
layer: HostOwnedLayer;
|
||||
/** The host-owned element whose inline `--ws-control-*` variables are set. */
|
||||
@@ -584,8 +938,8 @@ export function createHostControlProbe(shadow: ShadowRoot): HostControlProbe {
|
||||
canvas.fillStyle = "#000";
|
||||
canvas.fillStyle = computed;
|
||||
canvas.fillRect(0, 0, 1, 1);
|
||||
const [r, g, b] = canvas.getImageData(0, 0, 1, 1).data;
|
||||
return formatRgb({ r, g, b });
|
||||
const [r, g, b, a] = canvas.getImageData(0, 0, 1, 1).data;
|
||||
return a === 255 ? formatRgb({ r, g, b }) : `rgba(${r}, ${g}, ${b}, ${a / 255})`;
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
FLOATING_WEIGHT_PROTECTED,
|
||||
FLOATING_WEIGHT_POINTER,
|
||||
chooseFloatingPosition,
|
||||
floatingHitsAvoidRect,
|
||||
floatingRect,
|
||||
shouldFold,
|
||||
floatingScore,
|
||||
@@ -33,6 +34,23 @@ test("floating rects follow the corner margins and stay inside the viewport", ()
|
||||
assert.ok(narrow.bottom <= 844);
|
||||
});
|
||||
|
||||
test("a docked host toolbar is an excluded floating spot, not just a weighted obstacle", () => {
|
||||
// 318px stage from the GUI retest: a 218x36 built-in toolbar docked at the
|
||||
// top-left; the fallback capsule is 169x38. Top corners overlap it, so a
|
||||
// capsule pushed off the bottom dock must not land there.
|
||||
const narrow = { width: 318, height: 638 };
|
||||
const cap = { width: 169, height: 38 };
|
||||
const dockedToolbar = rect(20, 10, 218, 36);
|
||||
assert.equal(floatingHitsAvoidRect("top-left", cap, narrow, margins, [dockedToolbar]), true);
|
||||
assert.equal(floatingHitsAvoidRect("top-right", cap, narrow, margins, [dockedToolbar]), true);
|
||||
assert.equal(floatingHitsAvoidRect("top-center", cap, narrow, margins, [dockedToolbar]), true);
|
||||
assert.equal(floatingHitsAvoidRect("middle-left", cap, narrow, margins, [dockedToolbar]), false);
|
||||
assert.equal(floatingHitsAvoidRect("middle-right", cap, narrow, margins, [dockedToolbar]), false);
|
||||
assert.equal(floatingHitsAvoidRect("bottom-left", cap, narrow, margins, [dockedToolbar]), false);
|
||||
// A one-pixel brush against the footprint is not a cover.
|
||||
assert.equal(floatingHitsAvoidRect("top-left", cap, narrow, margins, [rect(180, 50, 10, 10)]), false);
|
||||
});
|
||||
|
||||
test("score is zero without overlap, ignores 1px brushes and weights dialog and (above all) protected controls", () => {
|
||||
const footprint = rect(12, 724, 200, 38);
|
||||
assert.equal(floatingScore(footprint, [{ rect: rect(400, 400, 40, 40), weight: 1 }]), 0);
|
||||
@@ -108,6 +126,21 @@ test("a move never lands on the pointer or the focused control, but the current
|
||||
assert.equal(stay.position, "top-left");
|
||||
});
|
||||
|
||||
test("an externally excluded current position is scored like every replacement candidate", () => {
|
||||
const pointerAndFocus: FloatingObstacle = { rect: rect(84, 15, 32, 32), weight: FLOATING_WEIGHT_POINTER };
|
||||
const choice = chooseFloatingPosition({
|
||||
current: "bottom-left",
|
||||
currentEligible: false,
|
||||
size: capsule,
|
||||
viewport,
|
||||
margins,
|
||||
obstacles: [],
|
||||
moveObstacles: [pointerAndFocus],
|
||||
positions: ["top-left", "top-right"],
|
||||
});
|
||||
assert.deepEqual(choice, { position: "top-right", score: 0 });
|
||||
});
|
||||
|
||||
test("folding needs to free at least one control; a full-screen click-away layer does not fold the capsule", () => {
|
||||
const backdrop: FloatingObstacle[] = [{ rect: rect(0, 0, 1280, 800), weight: FLOATING_WEIGHT_CONTROL }];
|
||||
const full = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles: backdrop });
|
||||
|
||||
@@ -165,10 +165,13 @@ export interface FloatingChoice {
|
||||
* modal dialog's backdrop, a toast) and going back there would cover it.
|
||||
* `moveObstacles` (the user's pointer and focused control) only count against
|
||||
* positions the control would move to, so it never jumps under the cursor or
|
||||
* onto the field being typed in.
|
||||
* onto the field being typed in. Set `currentEligible` false when an external
|
||||
* hard exclusion removes the real current position; it must then be scored like
|
||||
* every other candidate instead of being replaced by a synthetic current spot.
|
||||
*/
|
||||
export function chooseFloatingPosition(input: {
|
||||
current: FloatingPosition;
|
||||
currentEligible?: boolean;
|
||||
size: FloatingSize;
|
||||
viewport: FloatingViewport;
|
||||
margins: FloatingMargins;
|
||||
@@ -179,17 +182,19 @@ export function chooseFloatingPosition(input: {
|
||||
}): FloatingChoice {
|
||||
const positions = input.positions ?? FLOATING_POSITIONS;
|
||||
const moveObstacles = input.moveObstacles ?? [];
|
||||
const currentEligible = input.currentEligible ?? true;
|
||||
const scoreAt = (position: FloatingPosition) => {
|
||||
const footprint = floatingRect(position, input.size, input.viewport, input.margins);
|
||||
const score = floatingScore(footprint, input.obstacles);
|
||||
return position === input.current || !moveObstacles.length ? score : score + floatingScore(footprint, moveObstacles);
|
||||
const keepCurrent = currentEligible && position === input.current;
|
||||
return keepCurrent || !moveObstacles.length ? score : score + floatingScore(footprint, moveObstacles);
|
||||
};
|
||||
const currentScore = scoreAt(input.current);
|
||||
if (currentScore === 0) {
|
||||
if (currentEligible && currentScore === 0) {
|
||||
if (input.home && input.home !== input.current && scoreAt(input.home) === 0) return { position: input.home, score: 0 };
|
||||
return { position: input.current, score: 0 };
|
||||
}
|
||||
let best: FloatingChoice = { position: input.current, score: currentScore };
|
||||
let best: FloatingChoice = { position: input.current, score: currentEligible ? currentScore : Number.POSITIVE_INFINITY };
|
||||
for (const position of positions) {
|
||||
if (position === input.current) continue;
|
||||
const score = scoreAt(position);
|
||||
@@ -228,6 +233,22 @@ function rectsIntersect(first: HostPartRect, second: HostPartRect): boolean {
|
||||
return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a candidate corner would put the control on top of a docked host
|
||||
* control. Used to exclude such spots outright; scoring alone can still pick
|
||||
* one when the other corners cover skin controls.
|
||||
*/
|
||||
export function floatingHitsAvoidRect(
|
||||
position: FloatingPosition,
|
||||
size: FloatingSize,
|
||||
viewport: FloatingViewport,
|
||||
margins: FloatingMargins,
|
||||
avoidRects: readonly HostPartRect[],
|
||||
): boolean {
|
||||
const footprint = floatingRect(position, size, viewport, margins);
|
||||
return avoidRects.some(rect => rectsIntersect(footprint, rect));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* DOM binding
|
||||
* ------------------------------------------------------------------ */
|
||||
@@ -358,6 +379,14 @@ export interface FloatingAvoidanceOptions {
|
||||
onCompactChange?: (compact: boolean) => void;
|
||||
/** Skip re-evaluation (hovered, focused, slotted, drawer open…). */
|
||||
paused?: () => boolean;
|
||||
/**
|
||||
* Footprints of host controls that are docked in the top layer. They are
|
||||
* invisible to `collectFloatingObstacles` (which scans the light DOM), but a
|
||||
* floating fallback must never sit on them: a covered button loses its
|
||||
* label and its click lands on the wrong action. Positions that intersect
|
||||
* one of these rects are skipped whenever any free position exists.
|
||||
*/
|
||||
avoidRects?: () => readonly HostPartRect[];
|
||||
}
|
||||
|
||||
export interface FloatingAvoidance {
|
||||
@@ -457,13 +486,28 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
|
||||
}
|
||||
const now = Date.now();
|
||||
const urgent = now < urgentUntil;
|
||||
// Return home only after a screen change (see chooseFloatingPosition).
|
||||
const home = urgent ? defaultPosition : undefined;
|
||||
const full = chooseFloatingPosition({ current: position, size, viewport, margins, obstacles, moveObstacles, home });
|
||||
// Docked recovery toolbars live in the closed shadow root, so the light-DOM
|
||||
// obstacle scan above cannot see them. Exclude their footprints outright:
|
||||
// scoring alone could still park the fallback where a docked button sits
|
||||
// (GUI reproduced this at 320px: the library capsule covered the built-in
|
||||
// toolbar and its centre click hit the built-in action). If every corner
|
||||
// is docked, fall back to scoring over all positions rather than trapping
|
||||
// the capsule off-screen.
|
||||
const avoid = options.avoidRects?.() ?? [];
|
||||
const forbiddenAt = (candidate: FloatingPosition) =>
|
||||
floatingHitsAvoidRect(candidate, size, viewport, margins, avoid);
|
||||
const freePositions = FLOATING_POSITIONS.filter(candidate => !forbiddenAt(candidate));
|
||||
const positions = freePositions.length ? freePositions : FLOATING_POSITIONS;
|
||||
const currentEligible = !forbiddenAt(position);
|
||||
const park = forbiddenAt(defaultPosition) && freePositions.length ? freePositions[0] : defaultPosition;
|
||||
// Return home only after a screen change (see chooseFloatingPosition), and
|
||||
// only when the default corner is not one of the docked footprints.
|
||||
const home = urgent && !forbiddenAt(defaultPosition) ? defaultPosition : undefined;
|
||||
const full = chooseFloatingPosition({ current: position, currentEligible, size, viewport, margins, obstacles, moveObstacles, positions, home });
|
||||
let next = full;
|
||||
let nextCompact = false;
|
||||
if (full.score > 0 && small && small.width > 0 && small.height > 0) {
|
||||
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles, moveObstacles });
|
||||
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles, moveObstacles, positions });
|
||||
if (shouldFold(full, reduced)) {
|
||||
next = reduced;
|
||||
nextCompact = true;
|
||||
@@ -514,8 +558,8 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
|
||||
moveTimes = [];
|
||||
frozenUntil = now + HOST_FLOATING_FLAP_FREEZE_MS;
|
||||
frozenEscaped = false;
|
||||
if (position !== defaultPosition) {
|
||||
position = defaultPosition;
|
||||
if (position !== park) {
|
||||
position = park;
|
||||
apply(position);
|
||||
}
|
||||
setCompact(false);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ type ShortcutEvent = {
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
key: string;
|
||||
code: string;
|
||||
};
|
||||
|
||||
const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
|
||||
@@ -17,6 +18,7 @@ const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
key: "",
|
||||
code: "",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
@@ -24,16 +26,28 @@ test("the recovery shortcut requires the full Ctrl/Cmd+Alt+Shift+R chord", () =>
|
||||
assert.equal(isRecoveryShortcut(shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "r" })), true);
|
||||
// macOS uses the Meta/Command key in place of Ctrl.
|
||||
assert.equal(isRecoveryShortcut(shortcut({ metaKey: true, altKey: true, shiftKey: true, key: "R" })), true);
|
||||
// Option/Shift turn the letter into a derived character (US layout: ®) on
|
||||
// macOS; the physical key code must still match.
|
||||
assert.equal(isRecoveryShortcut(shortcut({
|
||||
metaKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyR",
|
||||
})), true);
|
||||
assert.equal(isRecoveryShortcut(shortcut({
|
||||
ctrlKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyR",
|
||||
})), true);
|
||||
|
||||
for (const rejected of [
|
||||
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "x" }),
|
||||
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "Enter" }),
|
||||
// A derived character alone is not enough: the physical key must be R.
|
||||
shortcut({ metaKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyX" }),
|
||||
// Ordinary app/browser shortcuts must stay available.
|
||||
shortcut({ ctrlKey: true, key: "r" }),
|
||||
shortcut({ altKey: true, key: "r" }),
|
||||
shortcut({ ctrlKey: true, shiftKey: true, key: "r" }),
|
||||
shortcut({ ctrlKey: true, altKey: true, key: "r" }),
|
||||
shortcut({ ctrlKey: false, altKey: true, shiftKey: true, key: "r" }),
|
||||
// Incomplete modifiers stay rejected even when the physical code matches.
|
||||
shortcut({ ctrlKey: true, altKey: true, key: "®", code: "KeyR" }),
|
||||
]) {
|
||||
assert.equal(isRecoveryShortcut(rejected), false, JSON.stringify(rejected));
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -160,9 +161,68 @@ test("a slotted capsule that would cover a protected control falls back", () =>
|
||||
assert.deepEqual(evaluateSlottedControl({ ...baseEvaluation, coversProtected: false }), { ok: true });
|
||||
});
|
||||
|
||||
test("a toolbar that would cover another docked host control falls back", () => {
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({
|
||||
...baseEvaluation,
|
||||
otherControls: [rect(160, 105, 120, 30)],
|
||||
}),
|
||||
{ ok: false, reason: "covers-host-control" },
|
||||
);
|
||||
// Edge contact is not a collision; both toolbars can still dock side by side.
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({
|
||||
...baseEvaluation,
|
||||
otherControls: [rect(60, 105, 120, 30)],
|
||||
}),
|
||||
{ ok: true },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, otherControls: [] }),
|
||||
{ ok: true },
|
||||
);
|
||||
});
|
||||
|
||||
test("rect overlap ignores edge contact and sub-pixel slivers", () => {
|
||||
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(50, 10, 100, 40)), true);
|
||||
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(100, 0, 50, 40)), false);
|
||||
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 },
|
||||
);
|
||||
});
|
||||
@@ -20,11 +20,17 @@ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import {
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
applyHostControlTokens,
|
||||
applyHostControlToolbarTokens,
|
||||
compositeRgb,
|
||||
createHostControlProbe,
|
||||
findSkinRoot,
|
||||
parseCssColorWithAlpha,
|
||||
resolveHostControlTokens,
|
||||
resolveHostControlToolbarTokens,
|
||||
type HostControlTokens,
|
||||
type HostControlProbe,
|
||||
type RgbColor,
|
||||
type RgbaColor,
|
||||
} from "./host-control-tokens.js";
|
||||
|
||||
export interface SlotViewport {
|
||||
@@ -81,6 +87,7 @@ export type SlotFailureReason =
|
||||
| "control-too-small"
|
||||
| "control-offscreen"
|
||||
| "covers-protected"
|
||||
| "covers-host-control"
|
||||
| "hit-test";
|
||||
|
||||
export interface SlotAnchorSnapshot {
|
||||
@@ -107,6 +114,8 @@ export interface SlotEvaluationInput {
|
||||
* capsule is top layer, so it would block those controls for the pointer.
|
||||
*/
|
||||
coversProtected?: boolean;
|
||||
/** Footprints of other docked host controls this one must not cover. */
|
||||
otherControls?: readonly HostPartRect[];
|
||||
}
|
||||
|
||||
export type SlotEvaluation = { ok: true } | { ok: false; reason: SlotFailureReason };
|
||||
@@ -161,6 +170,13 @@ export function evaluateSlottedControl(input: SlotEvaluationInput): SlotEvaluati
|
||||
return { ok: false, reason: "control-too-small" };
|
||||
}
|
||||
if (!fullyInsideViewport(controlRect, viewport)) return { ok: false, reason: "control-offscreen" };
|
||||
// Two independently anchored recovery toolbars can converge on the same
|
||||
// narrow anchor (for example at 320px). Covering a sibling host control
|
||||
// would make one of the buttons unreachable, so that action returns to the
|
||||
// visible floating capsule instead of pretending to be docked.
|
||||
if (input.otherControls?.some((rect) => rectsOverlap(controlRect, rect))) {
|
||||
return { ok: false, reason: "covers-host-control" };
|
||||
}
|
||||
if (input.coversProtected) return { ok: false, reason: "covers-protected" };
|
||||
if (!hitTestOk) return { ok: false, reason: "hit-test" };
|
||||
return { ok: true };
|
||||
@@ -214,6 +230,22 @@ function rectOf(rect: DOMRect | HostPartRect): HostPartRect {
|
||||
};
|
||||
}
|
||||
|
||||
/** Composite the anchor and top-bar ancestor backgrounds over the page canvas. */
|
||||
export function sampleOpaqueSurface(element: Element | null, doc: Document = document): RgbColor {
|
||||
const view = doc.defaultView;
|
||||
const layers: RgbaColor[] = [];
|
||||
for (let current: Element | null = element; current && view; current = current.parentElement) {
|
||||
const color = parseCssColorWithAlpha(view.getComputedStyle(current).backgroundColor);
|
||||
if (color && color.a > 0) layers.push(color);
|
||||
if (color?.a === 1) break;
|
||||
}
|
||||
let surface: RgbColor = { r: 255, g: 255, b: 255 };
|
||||
for (let index = layers.length - 1; index >= 0; index -= 1) {
|
||||
surface = compositeRgb(layers[index], surface);
|
||||
}
|
||||
return surface;
|
||||
}
|
||||
|
||||
/** Overlap of two rects in CSS pixels on both axes (more than 1px each). */
|
||||
export function rectsOverlap(first: HostPartRect, second: HostPartRect): boolean {
|
||||
const width = Math.min(first.right, second.right) - Math.max(first.left, second.left);
|
||||
@@ -271,22 +303,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 +341,30 @@ 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-*` / `--skin-host-toolbar-*`
|
||||
* tokens for background, foreground, border, hover, radius, font, font size,
|
||||
* padding, height, shadow, surface, gap and icon size. 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;
|
||||
/** Live footprints of other docked host controls; overlaps force a fallback. */
|
||||
otherControls?: () => readonly HostPartRect[];
|
||||
onModeChange?: (change: HostSlotModeChange) => void;
|
||||
}
|
||||
|
||||
@@ -332,11 +392,12 @@ 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;
|
||||
let currentAnchor: HTMLElement | null = null;
|
||||
let observingControl = false;
|
||||
let observer: ResizeObserver | null = null;
|
||||
const probe: HostControlProbe = createHostControlProbe(layer.shadow);
|
||||
let frame: number | undefined;
|
||||
@@ -348,9 +409,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,
|
||||
@@ -387,27 +448,51 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
}
|
||||
|
||||
function observe(anchorElement: HTMLElement | null): void {
|
||||
if (currentAnchor === anchorElement) return;
|
||||
// Measurement-only display changes must not feed back into observer scheduling.
|
||||
const watchControl = !options.prepare || (state.slotted && control.getClientRects().length > 0);
|
||||
if (currentAnchor === anchorElement && observingControl === watchControl) return;
|
||||
currentAnchor = anchorElement;
|
||||
observingControl = watchControl;
|
||||
if (!observer && typeof ResizeObserver !== "undefined") {
|
||||
observer = new ResizeObserver(() => schedule());
|
||||
}
|
||||
if (!observer) return;
|
||||
observer.disconnect();
|
||||
observer.observe(control);
|
||||
if (watchControl) observer.observe(control);
|
||||
if (anchorElement) observer.observe(anchorElement);
|
||||
}
|
||||
|
||||
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);
|
||||
let toolbarMinHeight: number | undefined;
|
||||
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. A
|
||||
// transparent button is checked against the surface behind its anchor.
|
||||
const toolbarTokens = tokenStyle
|
||||
? resolveHostControlToolbarTokens(
|
||||
tokenStyle,
|
||||
"host.recovery",
|
||||
probe.probeColor,
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
probe.isWebFont,
|
||||
sampleOpaqueSurface(tokenSource, doc),
|
||||
)
|
||||
: null;
|
||||
toolbarMinHeight = toolbarTokens?.minHeight;
|
||||
applyHostControlToolbarTokens(control, toolbarTokens);
|
||||
}
|
||||
|
||||
const controlBox = control.getBoundingClientRect();
|
||||
maxSize = {
|
||||
@@ -462,8 +547,9 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
anchor: anchorSnapshot,
|
||||
controlRect: intendedRect,
|
||||
viewport,
|
||||
minHitTarget: tokens.hitTarget,
|
||||
minHitTarget: toolbarMinHeight ?? tokens.hitTarget,
|
||||
coversProtected,
|
||||
otherControls: options.otherControls?.(),
|
||||
hitTestOk: placement
|
||||
? hitTestAt(placement.left, placement.top, { width: controlBox.width, height: controlBox.height })
|
||||
: false,
|
||||
@@ -481,6 +567,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
lastReason = reason;
|
||||
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
|
||||
}
|
||||
options.settle?.(state.slotted);
|
||||
observe(anchorElement);
|
||||
}
|
||||
|
||||
/** Any unexpected error returns the capsule to the default corner. */
|
||||
@@ -488,6 +576,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
const wasSlotted = state.slotted;
|
||||
state = nextSlotModeState(state, false);
|
||||
clearPlacement();
|
||||
options.settle?.(false);
|
||||
observe(currentAnchor);
|
||||
if (wasSlotted) onModeChange?.({ mode: "floating" });
|
||||
}
|
||||
|
||||
@@ -535,6 +625,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
win.removeEventListener("scroll", schedule, { capture: true });
|
||||
clearPlacement();
|
||||
applyHostControlTokens(control, null);
|
||||
applyHostControlToolbarTokens(control, null);
|
||||
probe.dispose();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@ import { strToU8, zipSync } from "fflate";
|
||||
import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
import { BUILTIN_SKIN_CATALOG } from "./skin-catalog.js";
|
||||
import { APP_VERSION } from "./app-version.js";
|
||||
import type { SkinPluginDocument, SkinPluginNode } from "../../../src/shared/skin-plugin.js";
|
||||
import { createSkinExtensionWasmPrefixByteImmediateProbe } from "../../test/skin-extension-wasm-fixture.js";
|
||||
|
||||
@@ -483,6 +484,26 @@ test("a v4 surface cannot compete with a v3 surface on the same public page", as
|
||||
);
|
||||
});
|
||||
|
||||
test("the distributable host chrome toolbar declares its first compatible runtime", async () => {
|
||||
const archive = await readFile(new URL("../../../docs/examples/host-chrome-toolbar.wskin", import.meta.url));
|
||||
const bundledArchive = await readFile(new URL("../../public/host-chrome-toolbar.wskin", import.meta.url));
|
||||
assert.deepEqual(bundledArchive, archive, "the downloadable example and bundled skin stay in sync");
|
||||
const skin = await importSkinPack(new File([archive], "host-chrome-toolbar.wskin", { type: "application/octet-stream" }));
|
||||
assert.equal(skin.id, "community.host-chrome-toolbar");
|
||||
assert.equal(skin.minAppVersion, "0.3.3", "mode, appearance and anchor arrays are unavailable in WebSpeak 0.3.2");
|
||||
assert.equal(skin.version, "1.1.1");
|
||||
assert.equal(APP_VERSION, skin.minAppVersion, "the running build must satisfy the example's declared minimum");
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
assert.equal(skin.packageType, "open-skin");
|
||||
assert.deepEqual(skin.chromeData?.slots?.["host.recovery"], {
|
||||
mode: "toolbar",
|
||||
appearance: "icon",
|
||||
anchor: ["home.header", "voice.header"],
|
||||
align: "end",
|
||||
compact: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("the distributable KAAK package provides full home and voice surfaces", async () => {
|
||||
const archive = await readFile(new URL("../../../docs/examples/kaak-voice.wskin", import.meta.url));
|
||||
const bundledArchive = await readFile(new URL("../../public/skins/kaak-voice.wskin", import.meta.url));
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host floating placement: docked toolbar and pointer avoidance</title>
|
||||
<style>
|
||||
html, body { margin: 0; width: 100%; height: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
|
||||
import { bindFloatingAvoidance, floatingRect } from "/src/services/host-floating-placement.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const viewport = { width: innerWidth, height: innerHeight };
|
||||
const margins = { top: 12, right: 12, bottom: 38, left: 12 };
|
||||
const size = { width: 200, height: 30 };
|
||||
|
||||
try {
|
||||
const layer = createHostOwnedLayer("recovery", `
|
||||
.cap { position: fixed; display: flex; width: 200px; height: 30px; pointer-events: auto; }
|
||||
.cap button { width: 200px; height: 30px; }
|
||||
`);
|
||||
if (!layer) throw new Error("recovery layer was not created");
|
||||
const control = document.createElement("div");
|
||||
control.className = "cap";
|
||||
control.setAttribute("popover", "manual");
|
||||
control.innerHTML = '<button type="button">Use built-in skin</button>';
|
||||
layer.container.append(control);
|
||||
control.showPopover();
|
||||
let bound = false;
|
||||
const moves = [];
|
||||
const binding = bindFloatingAvoidance({
|
||||
element: control,
|
||||
isSelf: (node) => node === layer.host || layer.host.contains(node),
|
||||
margins,
|
||||
defaultPosition: "bottom-left",
|
||||
avoidRects: () => [
|
||||
floatingRect("bottom-left", size, viewport, margins),
|
||||
floatingRect("bottom-right", size, viewport, margins),
|
||||
],
|
||||
apply: (position) => {
|
||||
control.style.left = position.endsWith("left") ? "12px" : position.endsWith("center") ? "50%" : "auto";
|
||||
control.style.right = position.endsWith("right") ? "12px" : "auto";
|
||||
control.style.top = position.startsWith("top") ? "12px" : position.startsWith("middle") ? "50%" : "auto";
|
||||
control.style.bottom = position.startsWith("bottom") ? "38px" : "auto";
|
||||
control.style.translate = position.endsWith("center") ? "-50% 0" : position.startsWith("middle") ? "0 -50%" : "none";
|
||||
if (bound) moves.push(position);
|
||||
},
|
||||
});
|
||||
bound = true;
|
||||
const pointerTarget = floatingRect("top-left", size, viewport, margins);
|
||||
document.dispatchEvent(new PointerEvent("pointermove", {
|
||||
bubbles: true,
|
||||
pointerType: "mouse",
|
||||
clientX: pointerTarget.left + pointerTarget.width / 2,
|
||||
clientY: pointerTarget.top + pointerTarget.height / 2,
|
||||
}));
|
||||
binding.screenChanged();
|
||||
await sleep(80);
|
||||
binding.revalidate();
|
||||
const box = control.getBoundingClientRect();
|
||||
output.textContent = JSON.stringify({
|
||||
position: binding.position,
|
||||
moves,
|
||||
pointerTarget: "top-left",
|
||||
pointerHit: document.elementFromPoint(
|
||||
pointerTarget.left + pointerTarget.width / 2,
|
||||
pointerTarget.top + pointerTarget.height / 2,
|
||||
) === layer.host,
|
||||
rect: { left: box.left, top: box.top, width: box.width, height: box.height },
|
||||
});
|
||||
binding.dispose();
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,90 @@
|
||||
<!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 buttonStyle = getComputedStyle(button);
|
||||
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,
|
||||
capsuleHeight: capsule.getBoundingClientRect().height,
|
||||
builtInHeight: button.getBoundingClientRect().height,
|
||||
builtInBackground: buttonStyle.backgroundColor,
|
||||
builtInForeground: buttonStyle.color,
|
||||
clicked: hostBuiltInSkinRequests.value === before + 1,
|
||||
});
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,150 @@
|
||||
<!doctype html>
|
||||
<html lang="en" data-ws-route="webclient" data-ws-page="voice" data-ws-host-skin="community.classic-toolbar-fixture">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Classic recovery toolbar 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; background: #f4f7fb; }
|
||||
#topbar { position: absolute; left: 0; top: 0; right: 0; height: 32px; background: #f4f7fb; }
|
||||
#anchor { position: absolute; left: 40px; top: 5px; width: 320px; height: 22px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-skin="community.classic-toolbar-fixture" data-ws-page="voice" data-ws-part="app">
|
||||
<div id="topbar" data-ws-part="voice.header">
|
||||
<span id="anchor" data-ws-part="skin.voice.topbar.part-host-actions"
|
||||
style="--skin-recovery-toolbar-background:transparent;--skin-recovery-toolbar-foreground:#1a1a1a;--skin-recovery-toolbar-border:transparent;--skin-recovery-toolbar-hover-background:#eaf2fd;--skin-recovery-toolbar-hover-border:#b8cfe8;--skin-recovery-toolbar-radius:2px;--skin-recovery-toolbar-font-size:11px;--skin-recovery-toolbar-padding:0 4px;--skin-recovery-toolbar-height:22px;--skin-recovery-toolbar-gap:1px;--skin-recovery-toolbar-icon-size:16px"></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,
|
||||
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";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const isOpen = (element) => Boolean(element?.matches?.(":popover-open"))
|
||||
|| (element ? getComputedStyle(element).display !== "none" : false);
|
||||
|
||||
try {
|
||||
setSkinHostChromeParts(parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": {
|
||||
mode: "toolbar",
|
||||
appearance: "icon",
|
||||
anchor: "skin.voice.topbar.part-host-actions",
|
||||
align: "start",
|
||||
},
|
||||
},
|
||||
})));
|
||||
setHostChromeActiveSkin("community.classic-toolbar-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 toolbar = layer.container.querySelector("[data-ws-host-recovery-toolbar]");
|
||||
const capsule = layer.container.querySelector("[data-ws-host-recovery]");
|
||||
const actions = [...toolbar.querySelectorAll("[data-ws-recovery-action]")];
|
||||
if (actions.length !== 2) throw new Error("expected two toolbar actions");
|
||||
const first = actions[0];
|
||||
const style = getComputedStyle(first);
|
||||
const icon = first.querySelector(".ws-host-toolbar-icon");
|
||||
const iconStyle = getComputedStyle(icon);
|
||||
const firstRect = first.getBoundingClientRect();
|
||||
const hit = document.elementFromPoint(firstRect.left + firstRect.width / 2, firstRect.top + firstRect.height / 2);
|
||||
const builtInBefore = hostBuiltInSkinRequests.value;
|
||||
const libraryBefore = pluginLibraryRequests.value;
|
||||
first.click();
|
||||
actions[1].click();
|
||||
|
||||
const initial = {
|
||||
toolbarOpen: isOpen(toolbar),
|
||||
capsuleOpen: isOpen(capsule),
|
||||
actionCount: actions.length,
|
||||
height: firstRect.height,
|
||||
width: firstRect.width,
|
||||
minHeight: style.minHeight,
|
||||
paddingTop: style.paddingTop,
|
||||
paddingRight: style.paddingRight,
|
||||
paddingBottom: style.paddingBottom,
|
||||
paddingLeft: style.paddingLeft,
|
||||
borderTopWidth: style.borderTopWidth,
|
||||
radius: style.borderTopLeftRadius,
|
||||
fontSize: style.fontSize,
|
||||
background: style.backgroundColor,
|
||||
foreground: style.color,
|
||||
gap: getComputedStyle(toolbar).columnGap,
|
||||
hoverBackground: toolbar.style.getPropertyValue("--ws-toolbar-hover-background"),
|
||||
hoverBorder: toolbar.style.getPropertyValue("--ws-toolbar-hover-border"),
|
||||
iconWidth: icon.getBoundingClientRect().width,
|
||||
iconHeight: icon.getBoundingClientRect().height,
|
||||
iconDisplay: iconStyle.display,
|
||||
iconAriaHidden: icon.getAttribute("aria-hidden"),
|
||||
svgFocusable: icon.querySelector("svg").getAttribute("focusable"),
|
||||
visibleText: actions.map((button) => button.textContent.trim()),
|
||||
accessibleNames: actions.map((button) => button.getAttribute("aria-label")),
|
||||
titles: actions.map((button) => button.getAttribute("title")),
|
||||
groupName: toolbar.getAttribute("aria-label"),
|
||||
hitIsLayerHost: hit === layer.host,
|
||||
builtInClicked: hostBuiltInSkinRequests.value === builtInBefore + 1,
|
||||
libraryClicked: pluginLibraryRequests.value === libraryBefore + 1,
|
||||
};
|
||||
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", {
|
||||
key: "r", code: "KeyR", ctrlKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
|
||||
}));
|
||||
await nextTick();
|
||||
await sleep(100);
|
||||
const capsuleButtons = [...capsule.querySelectorAll("[data-ws-recovery-action]")];
|
||||
const builtInCapsuleStyle = getComputedStyle(capsuleButtons[0]);
|
||||
const shortcut = {
|
||||
capsuleOpen: isOpen(capsule),
|
||||
toolbarOpen: isOpen(toolbar),
|
||||
labels: capsuleButtons.map((button) => button.textContent.trim()),
|
||||
height: capsuleButtons[0].getBoundingClientRect().height,
|
||||
builtInBackground: builtInCapsuleStyle.backgroundColor,
|
||||
builtInForeground: builtInCapsuleStyle.color,
|
||||
focusedAction: layer.shadow.activeElement?.getAttribute?.("data-ws-recovery-action") ?? null,
|
||||
};
|
||||
capsule.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
await nextTick();
|
||||
await sleep(150);
|
||||
const afterEscape = { capsuleOpen: isOpen(capsule), toolbarOpen: isOpen(toolbar) };
|
||||
|
||||
const anchor = document.getElementById("anchor");
|
||||
anchor.style.setProperty("--skin-recovery-toolbar-foreground", "#ffffff");
|
||||
await sleep(700);
|
||||
const invalidStyle = getComputedStyle(first);
|
||||
const invalidTokens = {
|
||||
background: invalidStyle.backgroundColor,
|
||||
foreground: invalidStyle.color,
|
||||
visible: invalidStyle.display !== "none" && invalidStyle.visibility !== "hidden",
|
||||
};
|
||||
|
||||
output.textContent = JSON.stringify({ initial, shortcut, afterEscape, invalidTokens });
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,317 @@
|
||||
<!doctype html>
|
||||
<html lang="en" data-ws-route="webclient" data-ws-page="home" data-ws-host-skin="community.plugin-panel-fixture">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host recovery toolbar + real PluginPanel 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: min(420px, calc(100vw - 40px)); height: 48px; }
|
||||
#home-anchor { left: 20px; }
|
||||
#voice-anchor { left: 20px; display: none; }
|
||||
#dock { position: absolute; left: 12px; bottom: 12px; display: flex; gap: 8px; }
|
||||
#dock button { height: 32px; padding: 0 10px; border: 1px solid #47dcc4; border-radius: 8px; background: #102030; color: #fff; font: inherit; }
|
||||
#output-dock { position: absolute; right: 12px; bottom: 12px; }
|
||||
#output-dock button { height: 32px; padding: 0 10px; border: 1px solid #47dcc4; border-radius: 8px; background: #102030; color: #fff; font: inherit; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Unlike host-recovery-toolbar.html, there is deliberately NO fake
|
||||
`data-ws-part="host.plugins.launcher"` button here. The launcher is the
|
||||
real one rendered by PluginPanel.vue, so dedup is observed at the actual
|
||||
product v-if path and cannot be faked by hiding a static placeholder. -->
|
||||
<div class="ws-skin-root" data-ws-skin="community.plugin-panel-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>
|
||||
<div id="output-dock" data-ws-part="voice.audio-dock">
|
||||
<button type="button" data-ws-part="voice.audio-dock.output">Output</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="app"></div>
|
||||
<div id="plugin-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 PluginPanel from "/src/components/PluginPanel.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;
|
||||
const rectsOverlap = (a, b) => Math.min(a.right, b.right) - Math.max(a.left, b.left) > 1
|
||||
&& Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top) > 1;
|
||||
const isOpen = (element) => Boolean(element?.matches?.(":popover-open"))
|
||||
|| (element ? getComputedStyle(element).display !== "none" && element.getBoundingClientRect().width > 0 : false);
|
||||
const isVisible = (element) => {
|
||||
if (!element) return false;
|
||||
const style = getComputedStyle(element);
|
||||
const rect = element.getBoundingClientRect();
|
||||
return style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
// Real hit testing, not element.click(): a fallback capsule can be fully
|
||||
// covered by a still-docked toolbar while still reporting a visible box. All
|
||||
// recovery buttons live in the closed shadow root, so elementFromPoint on the
|
||||
// document retargets to the layer host; scoping it to the shadow root reveals
|
||||
// which action is actually on top at the button's own centre.
|
||||
const hitOf = (button, layer) => {
|
||||
const box = button.getBoundingClientRect();
|
||||
const x = box.left + box.width / 2;
|
||||
const y = box.top + box.height / 2;
|
||||
const docHit = document.elementFromPoint(x, y);
|
||||
const shadowHit = layer?.shadow.elementFromPoint(x, y);
|
||||
const hitButton = (shadowHit ?? docHit)?.closest?.("[data-ws-recovery-action]");
|
||||
return {
|
||||
docHitIsLayerHost: docHit === layer?.host,
|
||||
hitAction: hitButton?.getAttribute("data-ws-recovery-action") ?? null,
|
||||
};
|
||||
};
|
||||
|
||||
// The real PluginPanel calls createPluginAppClient().list() on mount. Keep it
|
||||
// entirely local and deterministic: no production gateway, no external fetch.
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
window.fetch = (input, init) => {
|
||||
const url = typeof input === "string" ? input : input?.url ?? "";
|
||||
if (url.includes("/api/plugins")) {
|
||||
return Promise.resolve(new Response(JSON.stringify({ plugins: [] }), {
|
||||
status: 200, headers: { "content-type": "application/json" },
|
||||
}));
|
||||
}
|
||||
return nativeFetch(input, init);
|
||||
};
|
||||
|
||||
const mode = location.hash.slice(1) || "group";
|
||||
const anchorList = ["skin.home.topbar.part-host-actions", "skin.voice.topbar.part-host-actions"];
|
||||
const slots = mode === "split"
|
||||
? {
|
||||
"host.recovery.built-in": { mode: "toolbar", anchor: anchorList, align: "start" },
|
||||
"host.recovery.library": { mode: "toolbar", anchor: anchorList, align: "end" },
|
||||
}
|
||||
: mode === "capsule"
|
||||
? { "host.recovery": { anchor: anchorList, align: "end" } }
|
||||
: { "host.recovery": { mode: "toolbar", anchor: anchorList, align: "end" } };
|
||||
|
||||
try {
|
||||
setSkinHostChromeParts(parseSkinChromeDocument(JSON.stringify({ schemaVersion: 1, slots })));
|
||||
setHostChromeActiveSkin("community.plugin-panel-fixture");
|
||||
|
||||
const hostLanguage = ref("de");
|
||||
const pluginLanguage = ref("de");
|
||||
createApp({
|
||||
render: () => h(HostChrome, {
|
||||
language: hostLanguage.value,
|
||||
connected: true,
|
||||
pluginLibraryAvailable: true,
|
||||
}),
|
||||
}).mount("#app");
|
||||
createApp({
|
||||
render: () => h(PluginPanel, {
|
||||
sessionToken: "a".repeat(43),
|
||||
gatewayUrl: location.origin,
|
||||
connected: true,
|
||||
language: pluginLanguage.value,
|
||||
toolbarTarget: null,
|
||||
presentation: "dialog",
|
||||
}),
|
||||
}).mount("#plugin-app");
|
||||
|
||||
const layer = hostOwnedLayers().find((entry) => entry.name === "recovery");
|
||||
if (!layer) throw new Error("recovery layer was not created");
|
||||
const toolbars = () => [...layer.container.querySelectorAll("[data-ws-host-recovery-toolbar]")];
|
||||
const capsule = () => layer.container.querySelector("[data-ws-host-recovery]");
|
||||
const launcher = () => document.querySelector('[data-ws-part="host.plugins.launcher"]');
|
||||
const actions = (element) => [...(element?.querySelectorAll("[data-ws-recovery-action]") ?? [])]
|
||||
.map((button) => button.getAttribute("data-ws-recovery-action"));
|
||||
const openToolbars = () => toolbars().filter(isOpen);
|
||||
// Observe only buttons that are actually displayed. A floating toolbar is a
|
||||
// closed popover (display:none), so its buttons must not be reported as if
|
||||
// the user could see or click them; the fallback capsule owns them instead.
|
||||
const visibleButtons = () => [
|
||||
...openToolbars().flatMap((toolbar) => [...toolbar.querySelectorAll("button")]),
|
||||
...(isOpen(capsule()) ? [...(capsule()?.querySelectorAll("button") ?? [])] : []),
|
||||
];
|
||||
|
||||
await nextTick();
|
||||
await sleep(400);
|
||||
|
||||
const snapshot = () => {
|
||||
const bars = toolbars();
|
||||
const cap = capsule();
|
||||
const lch = launcher();
|
||||
const capActions = isOpen(cap) ? actions(cap) : [];
|
||||
const shown = visibleButtons();
|
||||
const barRects = openToolbars().map(rectOf);
|
||||
const buttonRects = shown.map(rectOf);
|
||||
return {
|
||||
viewport: innerWidth,
|
||||
toolbarCount: bars.length,
|
||||
toolbars: bars.map((bar) => ({
|
||||
open: isOpen(bar),
|
||||
visible: isVisible(bar),
|
||||
rect: rectOf(bar),
|
||||
inViewport: withinViewport(rectOf(bar)),
|
||||
labels: [...bar.querySelectorAll("button")].map((button) => button.textContent?.trim()),
|
||||
actions: actions(bar),
|
||||
})),
|
||||
toolbarOverlap: barRects.length === 2 ? rectsOverlap(barRects[0], barRects[1]) : false,
|
||||
buttonOverlap: buttonRects.length === 2 ? rectsOverlap(buttonRects[0], buttonRects[1]) : false,
|
||||
visibleActions: shown.map((button) => ({
|
||||
action: button.getAttribute("data-ws-recovery-action"),
|
||||
text: button.textContent?.trim(),
|
||||
rect: rectOf(button),
|
||||
height: rectOf(button).height,
|
||||
visible: isVisible(button),
|
||||
inViewport: withinViewport(rectOf(button)),
|
||||
...hitOf(button, layer),
|
||||
})),
|
||||
capsuleOpen: isOpen(cap),
|
||||
capsuleVisible: isVisible(cap),
|
||||
capsuleFloat: cap?.getAttribute("data-ws-float") ?? null,
|
||||
capsuleRect: cap ? rectOf(cap) : null,
|
||||
capsuleActions: capActions,
|
||||
launcherPresent: Boolean(lch),
|
||||
launcherVisible: isVisible(lch),
|
||||
launcherCount: document.querySelectorAll('[data-ws-part="host.plugins.launcher"]').length,
|
||||
inlineFlag: isInlineLibraryEntryVisible(),
|
||||
visibleLibraryEntries: shown.filter((button) => button.getAttribute("data-ws-recovery-action") === "library").length
|
||||
+ (isVisible(lch) ? 1 : 0),
|
||||
};
|
||||
};
|
||||
|
||||
const initial = snapshot();
|
||||
|
||||
// Both split toolbars must be individually clickable, not just observable.
|
||||
const builtInBefore = hostBuiltInSkinRequests.value;
|
||||
const libraryBefore = pluginLibraryRequests.value;
|
||||
const builtInButton = visibleButtons().find((button) => button.getAttribute("data-ws-recovery-action") === "built-in");
|
||||
const libraryButton = visibleButtons().find((button) => button.getAttribute("data-ws-recovery-action") === "library");
|
||||
builtInButton?.click();
|
||||
libraryButton?.click();
|
||||
const clicks = {
|
||||
builtIn: hostBuiltInSkinRequests.value === builtInBefore + 1,
|
||||
library: pluginLibraryRequests.value === libraryBefore + 1,
|
||||
};
|
||||
|
||||
// Long labels in de/ru/ja have to remain readable, inside the viewport and
|
||||
// above the host hit-target floor, without the two toolbars covering each
|
||||
// other. This runs at both 1280px and 320px real viewports.
|
||||
const languages = {};
|
||||
for (const lang of ["de", "ru", "ja"]) {
|
||||
hostLanguage.value = lang;
|
||||
pluginLanguage.value = lang;
|
||||
await nextTick();
|
||||
await sleep(900);
|
||||
languages[lang] = visibleButtons().map((button) => ({
|
||||
action: button.getAttribute("data-ws-recovery-action"),
|
||||
text: button.textContent?.trim(),
|
||||
rect: rectOf(button),
|
||||
height: rectOf(button).height,
|
||||
visible: isVisible(button),
|
||||
inViewport: withinViewport(rectOf(button)),
|
||||
...hitOf(button, layer),
|
||||
}));
|
||||
}
|
||||
hostLanguage.value = "de";
|
||||
pluginLanguage.value = "de";
|
||||
await nextTick();
|
||||
await sleep(900);
|
||||
|
||||
// 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(350);
|
||||
const voiceAnchorRect = rectOf(document.getElementById("voice-anchor"));
|
||||
const afterSwitch = {
|
||||
...snapshot(),
|
||||
insideVoiceAnchor: openToolbars().every((bar) => withinRect(rectOf(bar), voiceAnchorRect)),
|
||||
resolvedVoice: resolveSkinAnchor(anchorList, document, "community.plugin-panel-fixture")?.id,
|
||||
};
|
||||
|
||||
// A bad anchor must return a visible floating capsule, still with exactly
|
||||
// one library entry (real PluginPanel launcher stays suppressed for toolbar
|
||||
// modes even while the fallback capsule shows the library action).
|
||||
document.getElementById("voice-anchor").style.display = "none";
|
||||
await sleep(1100);
|
||||
const fallback = snapshot();
|
||||
|
||||
// Restoring the anchor re-docks after the anti-flap streak.
|
||||
document.getElementById("voice-anchor").style.display = "block";
|
||||
await sleep(2300);
|
||||
const redocked = snapshot();
|
||||
// A narrow split layout must settle on one docked toolbar instead of
|
||||
// swapping the two actions between the anchor and the capsule every tick.
|
||||
const redockSamples = [];
|
||||
for (let sample = 0; sample < 4; sample += 1) {
|
||||
redockSamples.push(openToolbars().map((bar) => actions(bar).join("+")).join("|"));
|
||||
await sleep(250);
|
||||
}
|
||||
redocked.stable = redockSamples.every((value) => value === redockSamples[0]);
|
||||
redocked.samples = redockSamples;
|
||||
|
||||
// The chord summons the complete capsule and focuses its first button; Esc
|
||||
// returns to the docked toolbar while the anchor is still valid.
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", {
|
||||
key: "r", ctrlKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
|
||||
}));
|
||||
await nextTick();
|
||||
await sleep(120);
|
||||
const shortcut = {
|
||||
...snapshot(),
|
||||
focusedAction: layer.shadow.activeElement?.getAttribute?.("data-ws-recovery-action") ?? null,
|
||||
};
|
||||
capsule()?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
await nextTick();
|
||||
await sleep(220);
|
||||
const afterEscape = snapshot();
|
||||
|
||||
output.textContent = JSON.stringify({
|
||||
mode,
|
||||
initial,
|
||||
clicks,
|
||||
languages,
|
||||
afterSwitch,
|
||||
fallback,
|
||||
redocked,
|
||||
shortcut,
|
||||
afterEscape,
|
||||
});
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ mode, error: String(error?.stack ?? error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Real viewport wrapper for host recovery toolbar fixtures</title>
|
||||
<style>
|
||||
html, body { margin: 0; background: #fff; }
|
||||
/* Headless Chrome clamps --window-size=320 to a 500px viewport. A real
|
||||
320px iframe is a genuine CSS viewport: window.innerWidth, 100vw,
|
||||
flex-wrap and the host slot's viewport checks all see 320px. */
|
||||
iframe { display: block; width: 320px; height: 640px; border: 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<iframe id="frame" title="320px viewport fixture"></iframe>
|
||||
<pre id="result" style="position:relative;z-index:5;background:#fff">pending</pre>
|
||||
<script>
|
||||
const mode = location.hash.slice(1) || "group";
|
||||
const frame = document.getElementById("frame");
|
||||
const output = document.getElementById("result");
|
||||
frame.src = `/test/fixtures/host-recovery-toolbar-plugin-panel.html#${encodeURIComponent(mode)}`;
|
||||
const poll = () => {
|
||||
try {
|
||||
const text = frame.contentDocument?.getElementById("result")?.textContent;
|
||||
if (text && text !== "pending") {
|
||||
output.textContent = text;
|
||||
return;
|
||||
}
|
||||
} catch { /* same-origin fixture still loading */ }
|
||||
setTimeout(poll, 100);
|
||||
};
|
||||
setTimeout(poll, 100);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
<!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; }
|
||||
#blank { position: absolute; left: 20px; top: 100px; padding: 12px; background: #fff; }
|
||||
</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 id="blank" tabindex="-1">Blank area</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, 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")),
|
||||
};
|
||||
layer.shadow.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, composed: true }));
|
||||
await nextTick();
|
||||
await sleep(150);
|
||||
const afterEscape = {
|
||||
capsuleOpen: isOpen(capsule()),
|
||||
toolbarOpen: isOpen(toolbar()),
|
||||
};
|
||||
|
||||
// On macOS ⌥/⇧ turn the letter into a derived character (US layout: ®), so
|
||||
// `key` is not "r". The physical code must match. A skin-style capture
|
||||
// listener calling preventDefault() must not swallow the chord either.
|
||||
const skinCapture = (event) => { if (event.type === "keydown") event.preventDefault(); };
|
||||
window.addEventListener("keydown", skinCapture, true);
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", {
|
||||
key: "®", code: "KeyR", metaKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
|
||||
}));
|
||||
window.removeEventListener("keydown", skinCapture, true);
|
||||
await nextTick();
|
||||
await sleep(80);
|
||||
const macShortcut = {
|
||||
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")),
|
||||
};
|
||||
layer.shadow.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, composed: true }));
|
||||
await nextTick();
|
||||
await sleep(150);
|
||||
const afterMacEscape = {
|
||||
capsuleOpen: isOpen(capsule()),
|
||||
toolbarOpen: isOpen(toolbar()),
|
||||
};
|
||||
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", {
|
||||
key: "r", ctrlKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
|
||||
}));
|
||||
await nextTick();
|
||||
await sleep(80);
|
||||
document.getElementById("blank").focus();
|
||||
await nextTick();
|
||||
await sleep(150);
|
||||
const afterFocusOut = {
|
||||
focusedAction: layer.shadow.activeElement?.getAttribute?.("data-ws-recovery-action") ?? null,
|
||||
activeId: document.activeElement?.id ?? null,
|
||||
capsuleOpen: isOpen(capsule()),
|
||||
toolbarOpen: isOpen(toolbar()),
|
||||
};
|
||||
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", {
|
||||
key: "r", ctrlKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
|
||||
}));
|
||||
await nextTick();
|
||||
await sleep(80);
|
||||
const blank = document.getElementById("blank");
|
||||
blank.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, composed: true, pointerType: "mouse" }));
|
||||
blank.dispatchEvent(new MouseEvent("click", { bubbles: true, composed: true }));
|
||||
await nextTick();
|
||||
await sleep(150);
|
||||
const afterBlankClick = {
|
||||
activeId: document.activeElement?.id ?? null,
|
||||
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", "#ffffff");
|
||||
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,
|
||||
macShortcut,
|
||||
afterMacEscape,
|
||||
afterFocusOut,
|
||||
afterBlankClick,
|
||||
invalidTokens,
|
||||
});
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host slot observer scheduling fixture</title>
|
||||
<style>
|
||||
html, body { margin: 0; width: 100%; height: 100%; }
|
||||
.ws-skin-root { position: relative; width: 100vw; height: 100vh; }
|
||||
#anchor { position: absolute; left: 20px; top: 20px; width: 240px; height: 48px; background: #f4f7fb; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-skin="community.observer-fixture" data-ws-part="app">
|
||||
<div id="anchor" data-ws-part="skin.home.header.part-host-actions"></div>
|
||||
</div>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { bindHostSlot } from "/src/services/host-slot-placement.ts";
|
||||
import { createHostOwnedLayer, syncRecoveryPopover } from "/src/services/host-owned-layer.ts";
|
||||
|
||||
const NativeResizeObserver = window.ResizeObserver;
|
||||
const observedTargets = new Set();
|
||||
let resizeCallbacks = 0;
|
||||
window.ResizeObserver = class extends NativeResizeObserver {
|
||||
constructor(callback) {
|
||||
super((entries, observer) => {
|
||||
resizeCallbacks += 1;
|
||||
callback(entries, observer);
|
||||
});
|
||||
}
|
||||
observe(target) {
|
||||
observedTargets.add(target);
|
||||
super.observe(target);
|
||||
}
|
||||
unobserve(target) {
|
||||
observedTargets.delete(target);
|
||||
super.unobserve(target);
|
||||
}
|
||||
disconnect() {
|
||||
observedTargets.clear();
|
||||
super.disconnect();
|
||||
}
|
||||
};
|
||||
const observedIds = () => [...observedTargets]
|
||||
.map((target) => target.id || target.getAttribute("data-ws-part") || target.tagName.toLowerCase());
|
||||
const nativeRequestAnimationFrame = window.requestAnimationFrame.bind(window);
|
||||
let frameCallbacks = 0;
|
||||
window.requestAnimationFrame = (callback) => nativeRequestAnimationFrame((time) => {
|
||||
frameCallbacks += 1;
|
||||
callback(time);
|
||||
});
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const output = document.getElementById("result");
|
||||
|
||||
try {
|
||||
const layer = createHostOwnedLayer("recovery", `
|
||||
.toolbar { position: fixed; pointer-events: auto; min-width: 160px; min-height: 28px; }
|
||||
.toolbar:popover-open { display: flex; }
|
||||
.toolbar button { min-width: 120px; min-height: 28px; }
|
||||
`);
|
||||
if (!layer) throw new Error("recovery layer was not created");
|
||||
const control = document.createElement("div");
|
||||
control.id = "measurement-toolbar";
|
||||
control.className = "toolbar";
|
||||
control.popover = "manual";
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = "Use built-in skin";
|
||||
control.append(button);
|
||||
layer.container.append(control);
|
||||
const modeChanges = [];
|
||||
let toolbarVisible = true;
|
||||
let lastMode = "floating";
|
||||
const binding = bindHostSlot({
|
||||
layer,
|
||||
control,
|
||||
anchor: "skin.home.header.part-host-actions",
|
||||
skinId: "community.observer-fixture",
|
||||
presentation: "toolbar",
|
||||
prepare: () => syncRecoveryPopover(control, true),
|
||||
settle: (slotted) => { if (!slotted || !toolbarVisible) syncRecoveryPopover(control, false); },
|
||||
onModeChange: (change) => { modeChanges.push(change); lastMode = change.mode; },
|
||||
});
|
||||
await sleep(120);
|
||||
const initial = {
|
||||
mode: modeChanges.at(-1)?.mode ?? null,
|
||||
reason: modeChanges.at(-1)?.reason ?? null,
|
||||
open: control.matches(":popover-open"),
|
||||
width: control.getBoundingClientRect().width,
|
||||
height: control.getBoundingClientRect().height,
|
||||
observed: observedIds(),
|
||||
};
|
||||
|
||||
resizeCallbacks = 0;
|
||||
frameCallbacks = 0;
|
||||
modeChanges.length = 0;
|
||||
toolbarVisible = false;
|
||||
binding.revalidate();
|
||||
await sleep(600);
|
||||
const whileDockedButHidden = {
|
||||
mode: lastMode,
|
||||
open: control.matches(":popover-open"),
|
||||
resizeCallbacks,
|
||||
frameCallbacks,
|
||||
observed: observedIds(),
|
||||
};
|
||||
|
||||
resizeCallbacks = 0;
|
||||
frameCallbacks = 0;
|
||||
modeChanges.length = 0;
|
||||
document.getElementById("anchor").remove();
|
||||
binding.revalidate();
|
||||
await sleep(600);
|
||||
const afterAnchorRemoved = {
|
||||
mode: modeChanges.at(-1)?.mode ?? null,
|
||||
reason: modeChanges.at(-1)?.reason ?? null,
|
||||
open: control.matches(":popover-open"),
|
||||
display: getComputedStyle(control).display,
|
||||
resizeCallbacks,
|
||||
frameCallbacks,
|
||||
modeChanges: modeChanges.length,
|
||||
observed: observedIds(),
|
||||
};
|
||||
binding.dispose();
|
||||
output.textContent = JSON.stringify({ initial, whileDockedButHidden, afterAnchorRemoved });
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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, floatingPlacement, 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,10 @@ 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/services/host-floating-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,9 +90,49 @@ 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, /:aria-label="copy\.useBuiltIn"/);
|
||||
assert.match(hostChrome, /:aria-label="copy\.library"/);
|
||||
assert.match(hostChrome, /class="ws-host-toolbar-icon" aria-hidden="true"/);
|
||||
assert.match(hostChrome, /focusable="false"/);
|
||||
assert.match(hostChrome, /--ws-toolbar-hover-background/);
|
||||
assert.match(hostChrome, /--ws-toolbar-hover-border/);
|
||||
assert.match(hostChrome, /--ws-toolbar-gap/);
|
||||
assert.match(hostChrome, /--ws-toolbar-icon-size/);
|
||||
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/);
|
||||
// Two split recovery toolbars must not cover each other on a narrow screen.
|
||||
assert.match(slotPlacement, /covers-host-control/);
|
||||
assert.match(hostChrome, /otherControls:/);
|
||||
// A fallback capsule must also avoid toolbars that are still docked: they
|
||||
// live in the closed shadow root and are invisible to the light-DOM obstacle
|
||||
// scan, so the document scan alone cannot protect their labels/clicks.
|
||||
assert.match(hostChrome, /avoidRects:/);
|
||||
assert.match(hostChrome, /dockedToolbarRects\(\)/);
|
||||
assert.match(floatingPlacement, /avoidRects\?:/);
|
||||
assert.match(floatingPlacement, /forbiddenAt\(/);
|
||||
assert.match(hostChromeService, /export function activeHostSlot/);
|
||||
assert.match(hostChromeService, /HOST_SLOTTABLE_PART_IDS\.has\(part\)/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive\(\)/);
|
||||
@@ -314,6 +358,73 @@ test("a declared slot docks the capsule and falls back at runtime", { skip: !CHR
|
||||
assert.equal(byName.disposed.leftoverAccent, "");
|
||||
});
|
||||
|
||||
test("a docked toolbar does not resize-observe its measurement-only fallback", { 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-slot-observer-loop.html`,
|
||||
["--virtual-time-budget=5000", "--window-size=1280,800"],
|
||||
);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the observer fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
assert.equal(payload.initial.mode, "slotted");
|
||||
assert.equal(payload.initial.open, true);
|
||||
assert.ok(payload.initial.width >= 160 && payload.initial.height >= 28);
|
||||
assert.ok(payload.initial.observed.includes("anchor"), "the docked toolbar stopped observing its anchor");
|
||||
assert.ok(payload.initial.observed.includes("measurement-toolbar"), "the docked toolbar stopped observing its own rendered size");
|
||||
assert.equal(payload.whileDockedButHidden.mode, "slotted");
|
||||
assert.equal(payload.whileDockedButHidden.open, false);
|
||||
assert.ok(payload.whileDockedButHidden.resizeCallbacks <= 4, `hiding a docked toolbar caused ${payload.whileDockedButHidden.resizeCallbacks} ResizeObserver callbacks`);
|
||||
assert.ok(payload.whileDockedButHidden.frameCallbacks <= 4, `hiding a docked toolbar scheduled ${payload.whileDockedButHidden.frameCallbacks} animation frames`);
|
||||
assert.equal(payload.whileDockedButHidden.observed.includes("measurement-toolbar"), false, "a hidden docked toolbar remained in its own ResizeObserver feedback path");
|
||||
assert.equal(payload.afterAnchorRemoved.mode, "floating");
|
||||
assert.equal(payload.afterAnchorRemoved.reason, "anchor-missing");
|
||||
assert.equal(payload.afterAnchorRemoved.open, false);
|
||||
assert.ok(payload.afterAnchorRemoved.resizeCallbacks <= 4, `measurement display changes caused ${payload.afterAnchorRemoved.resizeCallbacks} ResizeObserver callbacks`);
|
||||
assert.ok(payload.afterAnchorRemoved.frameCallbacks <= 4, `measurement display changes scheduled ${payload.afterAnchorRemoved.frameCallbacks} animation frames`);
|
||||
assert.equal(payload.afterAnchorRemoved.modeChanges, 1, "the fallback repeatedly changed presentation");
|
||||
assert.equal(payload.afterAnchorRemoved.observed.includes("measurement-toolbar"), false, "the floating measurement-only toolbar remained in its own ResizeObserver feedback path");
|
||||
});
|
||||
|
||||
test("docked-toolbar exclusion still scores pointer and focus obstacles", { 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-floating-avoid-pointer.html`,
|
||||
["--virtual-time-budget=5000", "--window-size=1280,800"],
|
||||
);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the floating avoidance fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
assert.notEqual(payload.position, "top-left", "the first toolbar-free candidate bypassed pointer avoidance");
|
||||
assert.equal(payload.pointerHit, false, "the replacement position landed on the pointer");
|
||||
assert.ok(payload.rect.left >= 0 && payload.rect.top >= 0);
|
||||
assert.ok(payload.rect.left + payload.rect.width <= 1280 && payload.rect.top + payload.rect.height <= 800);
|
||||
});
|
||||
|
||||
test("floating host controls move off skin controls at runtime", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
|
||||
const server = await createServer({
|
||||
root: webRoot,
|
||||
@@ -491,3 +602,389 @@ 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("Classic toolbar icons keep 22px geometry, transparency, names and full-label shortcut recovery", { 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-toolbar-classic.html`,
|
||||
["--virtual-time-budget=10000", "--window-size=1280,800"],
|
||||
);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the Classic toolbar fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
|
||||
const initial = payload.initial;
|
||||
assert.equal(initial.toolbarOpen, true);
|
||||
assert.equal(initial.capsuleOpen, false);
|
||||
assert.equal(initial.actionCount, 2);
|
||||
assert.equal(initial.height, 22);
|
||||
assert.equal(initial.width, 24);
|
||||
assert.equal(initial.minHeight, "22px");
|
||||
assert.equal(initial.paddingTop, "0px");
|
||||
assert.equal(initial.paddingRight, "0px");
|
||||
assert.equal(initial.paddingBottom, "0px");
|
||||
assert.equal(initial.paddingLeft, "0px");
|
||||
assert.equal(initial.borderTopWidth, "1px");
|
||||
assert.equal(initial.radius, "2px");
|
||||
assert.equal(initial.fontSize, "11px");
|
||||
assert.equal(initial.background, "rgba(0, 0, 0, 0)");
|
||||
assert.equal(initial.foreground, "rgb(26, 26, 26)");
|
||||
assert.equal(initial.gap, "1px");
|
||||
assert.equal(initial.hoverBackground, "rgb(234, 242, 253)");
|
||||
assert.equal(initial.hoverBorder, "rgb(184, 207, 232)");
|
||||
assert.equal(initial.iconWidth, 16);
|
||||
assert.equal(initial.iconHeight, 16);
|
||||
assert.equal(initial.iconDisplay, "block");
|
||||
assert.equal(initial.iconAriaHidden, "true");
|
||||
assert.equal(initial.svgFocusable, "false");
|
||||
assert.deepEqual(initial.visibleText, ["", ""]);
|
||||
assert.deepEqual(initial.accessibleNames, ["Use built-in skin", "Application library"]);
|
||||
assert.equal(initial.titles[0], "Restore the built-in skin (Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS)");
|
||||
assert.equal(initial.titles[1], "Application library");
|
||||
assert.equal(initial.groupName, "Restore built-in skin");
|
||||
assert.equal(initial.hitIsLayerHost, true);
|
||||
assert.equal(initial.builtInClicked, true);
|
||||
assert.equal(initial.libraryClicked, true);
|
||||
|
||||
assert.equal(payload.shortcut.capsuleOpen, true);
|
||||
assert.equal(payload.shortcut.toolbarOpen, false);
|
||||
assert.deepEqual(payload.shortcut.labels, ["Use built-in skin", "Application library"]);
|
||||
assert.ok(payload.shortcut.height >= 28);
|
||||
assert.equal(payload.shortcut.builtInBackground, "rgb(255, 247, 237)");
|
||||
assert.equal(payload.shortcut.builtInForeground, "rgb(124, 45, 18)");
|
||||
assert.equal(payload.shortcut.focusedAction, "built-in");
|
||||
assert.equal(payload.afterEscape.capsuleOpen, false);
|
||||
assert.equal(payload.afterEscape.toolbarOpen, true);
|
||||
assert.equal(payload.invalidTokens.background, "rgb(255, 255, 255)");
|
||||
assert.equal(payload.invalidTokens.foreground, "rgb(49, 82, 79)");
|
||||
assert.equal(payload.invalidTokens.visible, true);
|
||||
});
|
||||
|
||||
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(/"/g, '"').replace(/&/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");
|
||||
|
||||
// The macOS chord arrives with a derived `key` (®) + physical `code` KeyR,
|
||||
// under a capture listener that calls preventDefault(); it must still work.
|
||||
assert.equal(payload.macShortcut.capsuleOpen, true, "the macOS ⌘⌥⇧R chord did not summon the capsule");
|
||||
assert.equal(payload.macShortcut.toolbarOpen, false, "the macOS chord must yield to the summoned capsule");
|
||||
assert.equal(payload.macShortcut.focusedAction, "built-in", "the macOS chord did not focus the first host button");
|
||||
assert.deepEqual(payload.macShortcut.capsuleActions, ["built-in", "library"]);
|
||||
assert.equal(payload.afterMacEscape.capsuleOpen, false);
|
||||
assert.equal(payload.afterMacEscape.toolbarOpen, true, "closing the macOS chord did not restore the docked toolbar");
|
||||
assert.equal(payload.afterFocusOut.activeId, "blank", "focus did not leave the summoned capsule");
|
||||
assert.equal(payload.afterFocusOut.focusedAction, null);
|
||||
assert.equal(payload.afterFocusOut.capsuleOpen, false, "focusout left the full shortcut capsule open");
|
||||
assert.equal(payload.afterFocusOut.toolbarOpen, true, "focusout did not restore the docked toolbar");
|
||||
assert.equal(payload.afterBlankClick.capsuleOpen, false, "clicking blank space left the full shortcut capsule open");
|
||||
assert.equal(payload.afterBlankClick.toolbarOpen, true, "clicking blank space 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)", "unreadable transparent foreground 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("real PluginPanel launcher is de-duplicated by group and split toolbars on desktop and a real 320px viewport", { 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 base = `http://127.0.0.1:${port}/test/fixtures`;
|
||||
const run = async (mode, real320 = false) => {
|
||||
// Headless Chrome clamps --window-size=320 to a 500px viewport. The
|
||||
// wrapper opens the fixture inside a genuine 320px iframe so window.innerWidth,
|
||||
// 100vw, flex-wrap and the slot viewport checks all see 320px.
|
||||
const url = real320
|
||||
? `${base}/host-recovery-toolbar-viewport.html#${mode}`
|
||||
: `${base}/host-recovery-toolbar-plugin-panel.html#${mode}`;
|
||||
const dom = await dumpDom(url, ["--virtual-time-budget=30000", "--window-size=1280,800"]);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, `${mode} @ ${real320 ? 320 : 1280}: the fixture did not emit a result block`);
|
||||
return JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
};
|
||||
const overlaps = (a, b) => Math.min(a.right, b.right) - Math.max(a.left, b.left) > 1
|
||||
&& Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top) > 1;
|
||||
const observableButtons = (snapshot, context, count = 2) => {
|
||||
const entries = snapshot.visibleActions;
|
||||
assert.equal(entries.length, count, `${context}: expected ${count} visible buttons, got ${JSON.stringify(entries)}`);
|
||||
for (let i = 0; i < entries.length; i += 1) {
|
||||
for (let j = i + 1; j < entries.length; j += 1) {
|
||||
assert.equal(overlaps(entries[i].rect, entries[j].rect), false, `${context}: buttons overlap each other`);
|
||||
}
|
||||
}
|
||||
for (const entry of entries) {
|
||||
assert.ok(entry.text && entry.text.length > 0, `${context}: button lost its label`);
|
||||
assert.equal(entry.visible, true, `${context}: button is not visible`);
|
||||
assert.equal(entry.inViewport, true, `${context}: button escaped the viewport: ${JSON.stringify(entry.rect)}`);
|
||||
assert.ok(entry.height >= 28, `${context}: button fell below the host hit target (${entry.height})`);
|
||||
// A visible box is not enough: elementFromPoint at the button's own
|
||||
// centre must resolve to that button, not to a sibling host control.
|
||||
assert.equal(entry.docHitIsLayerHost, true, `${context}: ${entry.action} is not in the host top layer`);
|
||||
assert.equal(entry.hitAction, entry.action, `${context}: ${entry.action} centre is covered by ${entry.hitAction}`);
|
||||
}
|
||||
};
|
||||
|
||||
const group = await run("group");
|
||||
assert.equal(group.error, undefined, group.error);
|
||||
assert.equal(group.initial.toolbarCount, 1);
|
||||
assert.equal(group.initial.toolbars[0].open, true, "the group toolbar did not dock");
|
||||
assert.deepEqual(group.initial.toolbars[0].labels, ["Integrierten Skin verwenden", "Anwendungsbibliothek"]);
|
||||
assert.equal(group.initial.launcherPresent, false, "the real PluginPanel launcher was not suppressed");
|
||||
assert.equal(group.initial.launcherCount, 0);
|
||||
assert.equal(group.initial.inlineFlag, true);
|
||||
assert.equal(group.initial.capsuleOpen, false);
|
||||
assert.equal(group.initial.visibleLibraryEntries, 1);
|
||||
observableButtons(group.initial, "group desktop");
|
||||
assert.equal(group.clicks.builtIn, true);
|
||||
assert.equal(group.clicks.library, true);
|
||||
assert.equal(group.afterSwitch.toolbars[0].open, true, "the toolbar did not survive the page switch");
|
||||
assert.equal(group.afterSwitch.insideVoiceAnchor, true);
|
||||
assert.equal(group.afterSwitch.resolvedVoice, "voice-anchor");
|
||||
assert.equal(group.fallback.toolbars[0].open, false, "the toolbar stayed docked with a broken anchor");
|
||||
assert.equal(group.fallback.capsuleVisible, true);
|
||||
assert.deepEqual(group.fallback.capsuleActions, ["built-in", "library"]);
|
||||
assert.equal(group.fallback.launcherPresent, false, "the fallback added a second real library entry");
|
||||
assert.equal(group.fallback.visibleLibraryEntries, 1);
|
||||
assert.equal(group.redocked.toolbars[0].open, true);
|
||||
assert.equal(group.shortcut.capsuleOpen, true);
|
||||
assert.equal(group.shortcut.toolbars[0].open, false);
|
||||
assert.equal(group.shortcut.focusedAction, "built-in");
|
||||
assert.equal(group.afterEscape.capsuleOpen, false);
|
||||
assert.equal(group.afterEscape.toolbars[0].open, true);
|
||||
assert.equal(group.redocked.stable, true, "the docked toolbar flapped between the anchor and the capsule");
|
||||
|
||||
const split = await run("split");
|
||||
assert.equal(split.error, undefined, split.error);
|
||||
assert.equal(split.initial.toolbarCount, 2, "split mode must render two separately observable toolbars");
|
||||
assert.deepEqual(split.initial.toolbars.map((bar) => bar.labels), [["Integrierten Skin verwenden"], ["Anwendungsbibliothek"]]);
|
||||
assert.equal(split.initial.toolbars[0].open, true);
|
||||
assert.equal(split.initial.toolbars[1].open, true);
|
||||
assert.equal(split.initial.toolbarOverlap, false);
|
||||
assert.equal(split.initial.launcherPresent, false, "the real launcher survived the split toolbar");
|
||||
assert.equal(split.initial.visibleLibraryEntries, 1);
|
||||
observableButtons(split.initial, "split desktop");
|
||||
assert.equal(split.clicks.builtIn, true, "the built-in split toolbar button was not clickable");
|
||||
assert.equal(split.clicks.library, true, "the library split toolbar button was not clickable");
|
||||
assert.equal(split.afterSwitch.toolbars[0].open, true);
|
||||
assert.equal(split.afterSwitch.toolbars[1].open, true);
|
||||
assert.equal(split.afterSwitch.insideVoiceAnchor, true);
|
||||
for (const lang of ["de", "ru", "ja"]) {
|
||||
observableButtons({ visibleActions: split.languages[lang] }, `${lang} split desktop`);
|
||||
}
|
||||
assert.equal(split.fallback.toolbars.every((bar) => !bar.open), true);
|
||||
assert.equal(split.fallback.capsuleVisible, true);
|
||||
assert.deepEqual(split.fallback.capsuleActions, ["built-in", "library"]);
|
||||
assert.equal(split.fallback.launcherPresent, false, "the bad-anchor fallback restored a second library entry");
|
||||
assert.equal(split.fallback.visibleLibraryEntries, 1);
|
||||
assert.equal(split.redocked.toolbars.filter((bar) => bar.open).length, 2);
|
||||
assert.equal(split.redocked.stable, true, "split toolbars flapped between the anchor and the capsule");
|
||||
assert.equal(split.shortcut.capsuleOpen, true);
|
||||
assert.equal(split.shortcut.toolbars.every((bar) => !bar.open), true);
|
||||
assert.equal(split.shortcut.focusedAction, "built-in");
|
||||
assert.equal(split.afterEscape.capsuleOpen, false);
|
||||
assert.equal(split.afterEscape.toolbars.filter((bar) => bar.open).length, 2);
|
||||
|
||||
// Legacy capsule mode is the control: the real launcher must be able to
|
||||
// render at all, otherwise "suppressed" above would be a false positive.
|
||||
const capsule = await run("capsule");
|
||||
assert.equal(capsule.error, undefined, capsule.error);
|
||||
assert.equal(capsule.initial.toolbarCount, 0);
|
||||
assert.equal(capsule.initial.capsuleOpen, true);
|
||||
assert.equal(capsule.initial.launcherPresent, true, "the real PluginPanel launcher never rendered");
|
||||
assert.equal(capsule.initial.launcherVisible, true);
|
||||
assert.equal(capsule.initial.launcherCount, 1);
|
||||
assert.equal(capsule.initial.inlineFlag, false);
|
||||
|
||||
// Real 320px viewport: group labels wrap and stay tappable; split falls back
|
||||
// to a visible capsule for the action that would cover its sibling toolbar.
|
||||
const narrowGroup = await run("group", true);
|
||||
assert.equal(narrowGroup.error, undefined, narrowGroup.error);
|
||||
assert.equal(narrowGroup.initial.viewport, 320, "the iframe did not provide a real 320px viewport");
|
||||
assert.equal(narrowGroup.initial.toolbars[0].open, true);
|
||||
assert.equal(narrowGroup.initial.toolbarOverlap, false);
|
||||
assert.equal(narrowGroup.initial.launcherPresent, false);
|
||||
assert.equal(narrowGroup.initial.visibleLibraryEntries, 1);
|
||||
observableButtons(narrowGroup.initial, "group 320px");
|
||||
assert.equal(narrowGroup.clicks.builtIn, true);
|
||||
assert.equal(narrowGroup.clicks.library, true);
|
||||
for (const lang of ["de", "ru", "ja"]) {
|
||||
observableButtons({ visibleActions: narrowGroup.languages[lang] }, `${lang} group 320px`);
|
||||
}
|
||||
assert.equal(narrowGroup.redocked.stable, true);
|
||||
|
||||
const narrowSplit = await run("split", true);
|
||||
assert.equal(narrowSplit.error, undefined, narrowSplit.error);
|
||||
assert.equal(narrowSplit.initial.viewport, 320, "the iframe did not provide a real 320px viewport");
|
||||
assert.equal(narrowSplit.initial.toolbarCount, 2);
|
||||
assert.equal(narrowSplit.initial.toolbarOverlap, false, "docked split toolbars still cover each other at 320px");
|
||||
assert.equal(narrowSplit.initial.launcherPresent, false, "the real launcher reappeared at 320px");
|
||||
assert.equal(narrowSplit.initial.visibleLibraryEntries, 1, "the narrow fallback added a duplicate library entry");
|
||||
observableButtons(narrowSplit.initial, "split 320px");
|
||||
// The pushed-out library toolbar falls back to the capsule while built-in
|
||||
// stays docked. Both bottom corners of the fixture are occupied, which is
|
||||
// what drives the capsule toward the top bar (the GUI-retested failure).
|
||||
// Assert the two footprints are disjoint and each action's centre resolves
|
||||
// to its own button via elementFromPoint, not a synthetic element.click().
|
||||
const dockedSplitBar = narrowSplit.initial.toolbars.find((bar) => bar.open);
|
||||
const dockedSplitButton = narrowSplit.initial.visibleActions.find((entry) => entry.action === "built-in");
|
||||
const capsuleSplitButton = narrowSplit.initial.visibleActions.find((entry) => entry.action === "library");
|
||||
assert.ok(dockedSplitBar && dockedSplitButton && capsuleSplitButton, "split 320px did not show one docked and one fallback action");
|
||||
assert.equal(
|
||||
overlaps(dockedSplitBar.rect, capsuleSplitButton.rect), false,
|
||||
`fallback capsule covers the docked toolbar at 320px: ${JSON.stringify({ toolbar: dockedSplitBar.rect, capsule: capsuleSplitButton.rect })}`,
|
||||
);
|
||||
assert.equal(dockedSplitButton.hitAction, "built-in", "the docked built-in button is not the hit target at its centre");
|
||||
assert.equal(capsuleSplitButton.hitAction, "library", "the fallback library button is not the hit target at its centre");
|
||||
assert.equal(narrowSplit.clicks.builtIn, true, "the docked split button was not clickable at 320px");
|
||||
assert.equal(narrowSplit.clicks.library, true, "the fallback capsule button was not clickable at 320px");
|
||||
for (const lang of ["de", "ru", "ja"]) {
|
||||
observableButtons({ visibleActions: narrowSplit.languages[lang] }, `${lang} split 320px`);
|
||||
}
|
||||
assert.equal(narrowSplit.fallback.capsuleVisible, true);
|
||||
assert.equal(narrowSplit.fallback.visibleLibraryEntries, 1);
|
||||
assert.equal(narrowSplit.redocked.stable, true, "the narrow split fallback flapped between controls");
|
||||
assert.equal(narrowSplit.shortcut.capsuleOpen, true);
|
||||
assert.equal(narrowSplit.shortcut.toolbars.every((bar) => !bar.open), true);
|
||||
assert.equal(narrowSplit.afterEscape.toolbars.filter((bar) => bar.open).length, 1);
|
||||
assert.equal(narrowSplit.afterEscape.capsuleOpen, true, "the fallback entry vanished after Esc at 320px");
|
||||
});
|
||||
|
||||
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(/"/g, '"').replace(/&/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.ok(payload.capsuleHeight >= 28, "the legacy capsule lost its original size floor");
|
||||
assert.ok(payload.builtInHeight >= 28, "the legacy capsule action lost its original size floor");
|
||||
assert.equal(payload.builtInBackground, "rgb(255, 247, 237)", "the capsule built-in action must keep its fixed light background");
|
||||
assert.equal(payload.builtInForeground, "rgb(124, 45, 18)");
|
||||
assert.equal(payload.clicked, true);
|
||||
});
|
||||
Reference in new issue
Block a user