mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
Merge pull request #60 from OddTurtleHead/fix/skin-css-hardening
feat: integrate host recovery controls with skins and improve compatibility
This commit is contained in:
34 files changed
+5131
-402
No files matched your search
+125
-10
@@ -96,7 +96,7 @@ assets/preview.jpg # 可选:管理后台显示的预览图,也可
|
||||
assets/background.webp # 可选:页面艺术素材
|
||||
assets/brand.woff2 # 可选:自带字体
|
||||
components.json # v3 可选:声明式组件或完整页面 surface
|
||||
chrome.json # v3/v4 可选:宿主装饰隐藏与图标位图覆盖(见「chrome.json」章节)
|
||||
chrome.json # v3/v4 可选:宿主装饰、图标位图与可信控件停靠(见「chrome.json」章节)
|
||||
assets/icons/language.png # v3/v4 可选:工具栏图标位图覆盖素材
|
||||
plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件
|
||||
plugins/<plugin-id>/index.js # v4 插件代码,目前只校验和缓存
|
||||
@@ -406,7 +406,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | `host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`、`app.skin-load-recovery`、`skin.library`;`host.recovery` / `host.permission` 仅为概念标识(闭合 Shadow DOM + 顶层,无 CSS 钩子,见下文) |
|
||||
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`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` 是皮肤菜单里的应用库入口 |
|
||||
| 首页页脚拆分 | `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`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
@@ -435,7 +435,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
- 皮肤激活时,宿主在 `documentElement` 上设置 `data-ws-host-skin="<皮肤 ID>"`;停用或回退到内置皮肤时立即移除。
|
||||
- 编译 `skin.css` 时,**只**命中下列宿主部件的单个选择器会被限定到 `:root[data-ws-host-skin="<皮肤 ID>"] …`,其余规则仍限定到 `.ws-skin-root[data-ws-skin="…"]`。宿主部件的选择器必须**以可主题化的 `[data-ws-part="host.…"]` 开头**,不能把 `:root`、`html`、`body` 或 `*:has(…)` 作为规则主体;`:root:has([data-ws-part="host.watermark"])` 一类写法会被拒绝。皮肤作者不能自己写 `html`、`body`、`data-ws-host-skin`、`data-ws-route`、`data-theme` 或 `data-ws-skin` 选择器,也不能在同一选择器里混用宿主部件与页面部件;宿主部件只对 schema v3/v4 开放皮肤生效。
|
||||
- 宿主外壳的布局与层级由 WebSpeak 拥有:皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform` 等把 `host.plugins.overlay` 之类控件变成全屏遮罩。
|
||||
- 宿主外壳的布局与层级:应用库外壳 `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]` 这类带公开钩子的混合写法)。
|
||||
@@ -453,20 +453,129 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
### 恢复入口与授权对话框:结构上不可被皮肤触及
|
||||
|
||||
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或主题化的 CSS 钩子:当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们:
|
||||
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局:
|
||||
|
||||
1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。
|
||||
2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `<dialog>` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。
|
||||
3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
|
||||
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角;它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
|
||||
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。
|
||||
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
|
||||
|
||||
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅使用独立部件 `app.skin-load-recovery`(「切换到内置皮肤」),与恢复胶囊不是同一个钩子。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
|
||||
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
|
||||
|
||||
恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。
|
||||
|
||||
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
|
||||
|
||||
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| 键名 | 目前只接受 `host.recovery`(`src/shared/skin-visual-parts.ts` 的 `HOST_SLOTTABLE_PART_IDS`;后续可加入其他受保护控件)。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
|
||||
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称。不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。宿主只取第一个可见匹配;锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
|
||||
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;胶囊在锚点矩形内按此水平对齐,并垂直居中。 |
|
||||
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 |
|
||||
|
||||
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
|
||||
|
||||
- v3 `components.json` 组件根:`skin.<page>.<componentId>`。
|
||||
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
|
||||
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
|
||||
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`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-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
|
||||
|
||||
| 令牌 | 规则 |
|
||||
| --- | --- |
|
||||
| `--skin-recovery-accent` | 强调色,用于紧凑模式焦点框和「使用内置皮肤」按钮的边框。与背景的对比度必须 ≥ 3,否则整组颜色回退。该按钮自身固定为浅色底 `#fff7ed`,如果强调色在这块浅底上对比度不足 3,只有这个按钮的边框改用宿主默认 `#b45309`,其余位置仍用皮肤强调色。 |
|
||||
| `--skin-recovery-background` | 胶囊和按钮背景。宿主强制不透明(alpha 视为 1)。 |
|
||||
| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
|
||||
| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 |
|
||||
| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
|
||||
| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;列表中只要出现皮肤用 `@font-face` 注册的字体就整项忽略(只认系统已安装字体和通用族名);其他值使用宿主默认字体。 |
|
||||
| `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
|
||||
|
||||
颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
|
||||
|
||||
**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停、键盘聚焦或点按/轻触 ◈ 时展开为完整按钮;点按展开会保持到焦点离开胶囊、在胶囊外按下指针或按 Escape。新皮肤激活后、胶囊首次成功停靠起的约 5 秒内始终显示完整胶囊(从停靠时刻开始计时,皮肤加载慢也不会提前收起),避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。
|
||||
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
|
||||
#### 受保护控件的主题化
|
||||
|
||||
28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
|
||||
|
||||
**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`(字面值)、`outline` 等纯视觉属性都可以写:
|
||||
|
||||
```css
|
||||
[data-ws-part="voice.audio-dock.microphone"],
|
||||
[data-ws-part="auth.password.dialog"],
|
||||
[data-ws-part="home.footer.clear"] {
|
||||
color: var(--skin-ink);
|
||||
background: linear-gradient(135deg, #0f172a, #1e3a5f);
|
||||
border: 2px solid var(--skin-accent);
|
||||
border-radius: 16px;
|
||||
font: 600 14px/1.4 Tahoma, "Segoe UI", sans-serif;
|
||||
padding: 10px 16px;
|
||||
min-width: 56px;
|
||||
min-height: 56px;
|
||||
box-shadow: 0 8px 24px #0006;
|
||||
}
|
||||
```
|
||||
|
||||
以下规则仍会被拒绝,因为它们会隐藏、禁用或把控件移出视口:`display:none`、`visibility:hidden/collapse`、`opacity:0`、`pointer-events:none`、使 `clip`/`clip-path`/`mask` 完全裁掉内容、`transform`/`scale` 缩到 0、`inset`/`top`/`left`/`margin` 等把控件推到视口外,以及在这些隐藏/移动属性上使用 `var()`/`attr()`。`margin` 仍算移动属性,所以 `margin: var(--skin-gap)` 会被拒绝;普通的小 `margin` 数值可以写。自定义变量仍然只能使用 `--skin-` 前缀。
|
||||
|
||||
个别受保护部件的子元素(例如音频面板和音频设置里的 `<input type="range">`)由 Vue 写入内联 `style`;要给滑轨本身换肤,用视觉属性的 `!important` 覆盖即可,受保护的外壳不受影响。
|
||||
|
||||
**宿主自有的受保护控件。** `host.recovery`、`app.skin-load-recovery` 横幅和授权对话框在闭合 Shadow DOM 内,皮肤 CSS 不能命中。宿主提供一组统一的令牌;皮肤把变量写在活动皮肤根(`:root`,编译后就是皮肤根)上即可,恢复胶囊也接受写在锚点或其祖先上的值:
|
||||
|
||||
| 控件 | 每部件前缀 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `host.recovery` | `--skin-recovery-*` | 兼容原有令牌;写到锚点、锚点祖先或皮肤根上都有效 |
|
||||
| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠。令牌取自横幅出现时的**活动**皮肤:加载失败后宿主会退回内置皮肤(内置皮肤不声明令牌),所以失败皮肤自己的值通常不会作用在自己的横幅上,横幅保持默认琥珀色 |
|
||||
| 授权对话框(`host.permission` 概念) | `--skin-permission-*` | `host.permission` 没有 DOM 渲染点;令牌作用于宿主自己的授权对话框 |
|
||||
|
||||
每个每部件令牌都有全局回退:`--skin-host-accent`、`--skin-host-background`、`--skin-host-foreground`、`--skin-host-border`、`--skin-host-radius`、`--skin-host-font`、`--skin-host-size`。每部件值优先于全局值。例如:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-host-accent: #47dcc4;
|
||||
--skin-host-background: #0b1418;
|
||||
--skin-host-foreground: #edf8f5;
|
||||
--skin-host-border: #2a5a54;
|
||||
--skin-host-radius: 10px;
|
||||
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-size: medium;
|
||||
|
||||
/* 只覆盖恢复胶囊,其他宿主控件继续使用全局值 */
|
||||
--skin-recovery-background: #102030;
|
||||
}
|
||||
```
|
||||
|
||||
宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式、窗口尺寸变化让 `@media` 里的令牌生效时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
|
||||
|
||||
- 背景强制不透明(alpha 视为 1)。
|
||||
- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
|
||||
- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
|
||||
- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
|
||||
- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`,或带有编译器给皮肤字体加的 `ws-` 作用域前缀(包括放在暂未生效的 `@media` 里的字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
|
||||
- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
|
||||
- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白;如果黑白两种文字在强调色上都达不到 4.5,这组颜色同样整体回退到宿主默认。
|
||||
- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
|
||||
|
||||
`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)和「使用内置皮肤」的重置路径完全不受令牌影响。旧皮肤继续写 `--skin-recovery-*` 也能工作;新皮肤建议优先使用全局 `--skin-host-*`,只在需要区分具体控件时写每部件覆盖。
|
||||
|
||||
`host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。
|
||||
|
||||
示例(v3 `skin.css`):
|
||||
@@ -494,7 +603,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| `home.toolbar.settings` | 首页工具栏设置图标 |
|
||||
| `voice.performance` | 语音页 Voice status / 性能触发器图标 |
|
||||
|
||||
### `chrome.json`:声明式显示 / 隐藏与图标位图覆盖
|
||||
### `chrome.json`:声明式显示 / 隐藏、图标位图覆盖与控件停靠
|
||||
|
||||
v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根目录,最多 32 KiB:
|
||||
|
||||
@@ -507,6 +616,9 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
|
||||
"language.trigger": "assets/icons/language.png",
|
||||
"skin.trigger": "assets/icons/skin.png",
|
||||
"host.plugins.launcher": "assets/icons/apps.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -516,6 +628,7 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
|
||||
| `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 |
|
||||
| `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 |
|
||||
| `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 |
|
||||
| `slots` | 可选,最多 8 项;键名目前只能是 `host.recovery`,值只能包含 `anchor`、`align`、`compact`。详见上文「将恢复入口停靠到皮肤布局」。未知键、指向 `host.*` 或可信宿主部件的锚点会被拒绝。 |
|
||||
|
||||
图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。
|
||||
|
||||
@@ -618,9 +731,11 @@ v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显
|
||||
[data-ws-part="host.plugins.launcher"]
|
||||
```
|
||||
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。
|
||||
|
||||
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
|
||||
关键帧与普通声明遵循同一套受保护控件检查,但只检查动画能够**停留**的帧:`to` / `100%` 始终检查;`from` / `0%` 仅在引用它的声明(含同一主体上另一条规则的方向 / 填充 / 播放状态长属性)使用 `reverse`、`alternate`、`alternate-reverse` 方向、`backwards` / `both` 填充模式或 `paused` 播放状态时检查;转义的 `to` / `from` 与 `1e2%` 这类写法按停留帧识别;`50%` 等中间帧不会因为过渡状态被拒绝,缺少 `to` / `100%` 时结束状态回到元素自身样式(`paused` 配合负延迟、或超长动画停在中间帧属于已知残留,由闭合 Shadow DOM 的恢复胶囊兜底)。受保护控件上被拒绝的写法包括 `display: none`、`visibility: hidden|collapse`、`opacity` ≤ 0.01(含 `0`、`0%`、`0e0`、`calc(0)` 等)、`pointer-events: none`、`filter` / `-webkit-filter` 的 `opacity(≤0.01)` / `brightness(0)`、`transform` / `scale` 的零缩放、`content-visibility: hidden`、`clip-path` 的 `inset(...)`(任一边对合计 ≥ 100%)、`circle(0)` / `ellipse(0 …)`、`clip: rect(0,0,0,0)`,以及 `mask` / `mask-image` 的 `alpha(0)` / `luminance(0)` 或全透明渐变色标;`polygon()` 等装饰性裁切不受限制。受保护主体的判定会展开 `:is()` / `:where()` 参数、双重否定 `:not(:not(X))` 与 `:nth-child(An+B of S)` / `:nth-last-child(...)` 的 `S`,`[data-ws-part="…" i]` 按不区分大小写匹配。把控件移出视口只在明显越界时拒绝:负向 ≤ -1000px 或 ≤ -100%,正向 ≥ 2000px 或 ≥ 200%(`margin` / `inset` / `left` / `right` / `top` / `bottom` / `translate` / `transform`,含简单 `calc()` 与 `matrix()` 平移);`scale`、`rotate` 和小幅平移不受影响。`host.plugins.overlay` 的布局锁在关键帧中复用普通声明的属性锁:停留帧里的定位、变换等锁定属性只能取中性或单位变换(`none`、`auto`、`static`、`0`、`scale(1)`、`translateY(0)`、`rotate(0deg)` 或 CSS 全局关键字),尺寸属性仅在达到视口尺寸时拒绝(含 `calc(50vw * 2)`);入场动画停在这些值时通过。受保护控件和 `host.plugins.overlay` 上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名;受保护控件上的 `filter` / `-webkit-filter`、`clip` 与 `content-visibility` 同样只接受字面值,不能用 `var()` / `attr()`(否则变量可以绕过上面的隐藏检查),其他部件不受影响。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
|
||||
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。装饰性宿主外壳(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)和普通页面部件不受布局锁限制,可以自由使用 flex/grid、重定位、自定义尺寸、大背景和动画;固定定位或极端 `z-index` 只会给出提示。开放皮肤(v3/v4)的布局与视觉质量由官方库的人工审核保证,编译器不会阻止一般性的布局回归。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
|
||||
|
||||
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
|
||||
Binary file not shown.
@@ -8,5 +8,8 @@
|
||||
"host.plugins.launcher": "assets/icons/apps.png",
|
||||
"home.toolbar.settings": "assets/icons/settings.png",
|
||||
"voice.performance": "assets/icons/status.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
"version": "1.0.0",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "Minimal open skin demonstrating host chrome theming, declarative hiding and bitmap icon overrides.",
|
||||
"description": "Minimal open skin demonstrating host chrome theming, protected-control theming, declarative hiding and bitmap icon overrides.",
|
||||
"entry": "skin.css",
|
||||
"chrome": "chrome.json",
|
||||
"minAppVersion": "0.3.2"
|
||||
|
||||
@@ -7,6 +7,26 @@
|
||||
--skin-panel: #ffffff;
|
||||
--skin-border: #c9c9c9;
|
||||
--skin-text: #141414;
|
||||
|
||||
/* Host-owned protected controls: one global set, per-part overrides below. */
|
||||
--skin-host-accent: #1d4f9c;
|
||||
--skin-host-background: #ffffff;
|
||||
--skin-host-foreground: #141414;
|
||||
--skin-host-border: #9db6b2;
|
||||
--skin-host-radius: 10px;
|
||||
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-size: medium;
|
||||
--skin-recovery-accent: #1d4f9c;
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #141414;
|
||||
--skin-recovery-border: #9db6b2;
|
||||
--skin-recovery-radius: 999px;
|
||||
--skin-load-recovery-accent: #b45309;
|
||||
--skin-load-recovery-background: #fff7ed;
|
||||
--skin-load-recovery-foreground: #7c2d12;
|
||||
--skin-permission-accent: #1d4f9c;
|
||||
--skin-permission-background: #ffffff;
|
||||
--skin-permission-foreground: #141414;
|
||||
}
|
||||
|
||||
[data-ws-page] {
|
||||
@@ -25,6 +45,50 @@
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
border-top: 1px solid var(--skin-border);
|
||||
background: #f7f9fb;
|
||||
/* Fold the trusted recovery capsule into the audio dock (chrome.json#slots). */
|
||||
--skin-recovery-accent: #1d4f9c;
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #141414;
|
||||
--skin-recovery-radius: 999px;
|
||||
--skin-recovery-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-recovery-size: small;
|
||||
}
|
||||
|
||||
/* --- Protected app-DOM controls: purely visual theming is allowed --- */
|
||||
[data-ws-part="voice.audio-dock.microphone"] button,
|
||||
[data-ws-part="voice.audio-dock.output"] button,
|
||||
[data-ws-part="voice.connection-status.reconnect"],
|
||||
[data-ws-part="home.footer.clear"] {
|
||||
color: #141414;
|
||||
background: linear-gradient(180deg, #ffffff, #eef3fa);
|
||||
border: 1px solid var(--skin-accent);
|
||||
border-radius: 8px;
|
||||
font-family: Tahoma, "Segoe UI", sans-serif;
|
||||
font-size: 12px;
|
||||
padding: 8px 12px;
|
||||
min-height: 44px;
|
||||
box-shadow: 0 2px 6px #1d4f9c22;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone"] button:hover,
|
||||
[data-ws-part="voice.audio-dock.output"] button:hover,
|
||||
[data-ws-part="voice.connection-status.reconnect"]:hover,
|
||||
[data-ws-part="home.footer.clear"]:hover {
|
||||
background: #e7eefb;
|
||||
}
|
||||
|
||||
[data-ws-part="auth.password.dialog"],
|
||||
[data-ws-part="voice.audio-settings"] {
|
||||
background: #ffffff;
|
||||
border: 2px solid var(--skin-accent);
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 18px 48px #1d4f9c33;
|
||||
}
|
||||
|
||||
[data-ws-part="auth.password.dialog"] h2,
|
||||
[data-ws-part="voice.audio-settings"] h2 {
|
||||
color: var(--skin-accent);
|
||||
letter-spacing: .01em;
|
||||
}
|
||||
|
||||
/* --- Host chrome (outside .ws-skin-root) --- */
|
||||
|
||||
Binary file not shown.
+1
-1
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-recovery-helpers.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
|
||||
+103
-5
@@ -1,15 +1,25 @@
|
||||
import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./skin-visual-parts.js";
|
||||
import {
|
||||
DECORATIVE_PART_IDS,
|
||||
HOST_SKIN_ATTRIBUTE,
|
||||
HOST_SLOTTABLE_PART_IDS,
|
||||
SKIN_ICON_SLOT_IDS,
|
||||
TRUSTED_PART_IDS,
|
||||
isHostPart,
|
||||
} from "./skin-visual-parts.js";
|
||||
|
||||
/**
|
||||
* `chrome.json` is an optional, declarative companion to an open skin.
|
||||
*
|
||||
* It describes two host-chrome capabilities that CSS alone cannot express
|
||||
* safely:
|
||||
* It describes host-chrome capabilities that CSS alone cannot express safely:
|
||||
* - `visibleParts`: decorations the skin asks the host to render. This is the
|
||||
* only opt-in; official and built-in skins stay clean.
|
||||
* - `hiddenParts`: non-critical decorations the skin wants collapsed by
|
||||
* default. Only explicitly optional parts are accepted.
|
||||
* - `icons`: bitmap overrides for stable icon slots, keyed by part name.
|
||||
* - `slots`: declarative anchors for trusted host controls. A skin never
|
||||
* receives the control; it only names a part it already renders so the
|
||||
* host can position its own top-layer capsule there and fall back to the
|
||||
* default corner when the anchor stops being usable.
|
||||
*
|
||||
* Both the browser importer and the server-side registry parse the exact same
|
||||
* document, so a package accepted by one is accepted by the other.
|
||||
@@ -18,10 +28,21 @@ import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./
|
||||
export const SKIN_CHROME_MAX_BYTES = 32 * 1024;
|
||||
export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32;
|
||||
export const SKIN_CHROME_MAX_ICONS = 16;
|
||||
export const SKIN_CHROME_MAX_SLOTS = 8;
|
||||
export const SKIN_ICON_MAX_BYTES = 64 * 1024;
|
||||
export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024;
|
||||
export const SKIN_ICON_DIRECTORY = "assets/icons/";
|
||||
|
||||
/**
|
||||
* Anchor names are `data-ws-part` values, including host-rendered v3 component
|
||||
* parts (`skin.<page>.<component>.part-<name>`) and v4 runtime plugin parts
|
||||
* (`skin.<page>.runtime_plugin_<plugin>__<component>.part-<name>`). Each
|
||||
* dot-separated segment follows the same identifier grammar as other part
|
||||
* names; the generous overall limit covers a namespaced runtime plugin.
|
||||
*/
|
||||
export const SKIN_SLOT_ANCHOR_MAX_LENGTH = 240;
|
||||
const PART_NAME_SEGMENT = /^[-_a-z][-_a-z0-9]*$/i;
|
||||
|
||||
const SUPPORTED_ICON_EXTENSIONS = new Set(["png", "jpg", "jpeg", "webp", "avif", "gif"]);
|
||||
|
||||
/**
|
||||
@@ -45,6 +66,19 @@ export interface SkinChromeDocument {
|
||||
*/
|
||||
visibleParts?: string[];
|
||||
icons: Record<string, string>;
|
||||
/** Protected host controls folded into skin-owned layout anchors. */
|
||||
slots?: Partial<Record<string, SkinChromeSlot>>;
|
||||
}
|
||||
|
||||
export type SkinChromeSlotAlign = "start" | "center" | "end";
|
||||
|
||||
export interface SkinChromeSlot {
|
||||
/** Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box. */
|
||||
anchor: string;
|
||||
/** Horizontal alignment inside the anchor; the control is vertically centred. */
|
||||
align: SkinChromeSlotAlign;
|
||||
/** Collapse to the mark only until hovered or focused. */
|
||||
compact: boolean;
|
||||
}
|
||||
|
||||
export interface SkinChromeAssetInfo {
|
||||
@@ -94,6 +128,29 @@ export function normalizeSkinIconPath(raw: unknown): string {
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* A slot anchor is an existing part name, never host-owned UI: a skin must not
|
||||
* be able to park a protected control on the launcher, the authorization
|
||||
* dialog or another trusted element it could then cover or remove.
|
||||
*/
|
||||
function normalizeSlotAnchor(raw: unknown): string {
|
||||
if (typeof raw !== "string" || !raw || raw.length > SKIN_SLOT_ANCHOR_MAX_LENGTH) {
|
||||
return reject(`A slot anchor must be a part name of at most ${SKIN_SLOT_ANCHOR_MAX_LENGTH} characters.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const segments = raw.split(".");
|
||||
if (segments.some((segment) => !PART_NAME_SEGMENT.test(segment))) {
|
||||
return reject(`A slot anchor is not a valid part name: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (isHostPart(raw) || TRUSTED_PART_IDS.has(raw)) {
|
||||
return reject(`A slot anchor cannot point at trusted host UI: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function isSlotAlign(value: unknown): value is SkinChromeSlotAlign {
|
||||
return value === "start" || value === "center" || value === "end";
|
||||
}
|
||||
|
||||
export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
const bytes = new TextEncoder().encode(source).byteLength;
|
||||
if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) {
|
||||
@@ -104,7 +161,7 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
catch { return reject("chrome.json is not valid JSON.", "SKIN_CHROME_INVALID"); }
|
||||
if (!isRecord(raw)) return reject("chrome.json must be an object.", "SKIN_CHROME_INVALID");
|
||||
for (const key of Object.keys(raw)) {
|
||||
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons") {
|
||||
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons" && key !== "slots") {
|
||||
return reject(`chrome.json contains an unsupported field: ${key}.`, "SKIN_CHROME_INVALID");
|
||||
}
|
||||
}
|
||||
@@ -151,7 +208,48 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
icons[slot] = normalizeSkinIconPath(path);
|
||||
}
|
||||
}
|
||||
return { schemaVersion: 1, hiddenParts, ...(visibleParts ? { visibleParts } : {}), icons };
|
||||
let slots: Partial<Record<string, SkinChromeSlot>> | undefined;
|
||||
if (raw.slots !== undefined) {
|
||||
if (!isRecord(raw.slots)) {
|
||||
return reject("slots must be an object mapping protected part names to anchors.", "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const entries = Object.entries(raw.slots);
|
||||
if (entries.length > SKIN_CHROME_MAX_SLOTS) {
|
||||
return reject(`A skin may declare at most ${SKIN_CHROME_MAX_SLOTS} slots.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots = Object.create(null) as Partial<Record<string, SkinChromeSlot>>;
|
||||
for (const [part, value] of entries) {
|
||||
if (!HOST_SLOTTABLE_PART_IDS.has(part)) {
|
||||
return reject(`Unknown slottable host part: ${part}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return reject(`Slot ${part} must be an object.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
for (const key of Object.keys(value)) {
|
||||
if (key !== "anchor" && key !== "align" && key !== "compact") {
|
||||
return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
}
|
||||
const anchor = normalizeSlotAnchor(value.anchor);
|
||||
const align = value.align === undefined ? "end" : value.align;
|
||||
if (!isSlotAlign(align)) {
|
||||
return reject(`Slot ${part} has an invalid align value: ${String(align)}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const compact = value.compact === undefined ? false : value.compact;
|
||||
if (typeof compact !== "boolean") {
|
||||
return reject(`Slot ${part} compact must be a boolean.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots[part] = { anchor, align, compact };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
hiddenParts,
|
||||
...(visibleParts ? { visibleParts } : {}),
|
||||
icons,
|
||||
...(slots ? { slots } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+415
-6
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { compileSkinCss, OPTIONAL_VISUAL_PARTS } from "./skin-css.js";
|
||||
import { DECORATIVE_PART_IDS as LAYOUT_DECORATIVE, PROTECTED_PART_IDS } from "./skin-layout.js";
|
||||
import { DECORATIVE_PART_IDS } from "./skin-visual-parts.js";
|
||||
import { DECORATIVE_PART_IDS, HOST_SLOTTABLE_PART_IDS } from "./skin-visual-parts.js";
|
||||
import {
|
||||
compileSkinChromeCss,
|
||||
DEFAULT_HIDDEN_HOST_PARTS,
|
||||
@@ -196,6 +196,62 @@ test("chrome.json declares hidden parts and icon bitmaps, with path and size val
|
||||
assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: 10, mime: "text/plain" })), /raster image/);
|
||||
});
|
||||
|
||||
test("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => {
|
||||
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], ["host.recovery"]);
|
||||
|
||||
const explicit = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(explicit.slots?.["host.recovery"], {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "start",
|
||||
compact: true,
|
||||
});
|
||||
|
||||
// Defaults: align "end", compact off. Component and runtime-plugin parts are
|
||||
// ordinary anchors; only host/trusted parts are off limits.
|
||||
const defaults = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "skin.voice.harbor-dock.part-anchor" },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(defaults.slots?.["host.recovery"], {
|
||||
anchor: "skin.voice.harbor-dock.part-anchor",
|
||||
align: "end",
|
||||
compact: false,
|
||||
});
|
||||
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: { "host.recovery": { anchor: "skin.voice.runtime_plugin_voice-surface__dock.part-anchor" } },
|
||||
})));
|
||||
|
||||
// Slot declarations are runtime input, not compiled CSS: the generated host
|
||||
// stylesheet must stay exactly as empty as before.
|
||||
assert.equal(compileSkinChromeCss(explicit, "demo-skin"), "");
|
||||
|
||||
const invalidDocuments: Array<[unknown, RegExp]> = [
|
||||
[{ schemaVersion: 1, slots: [] }, /must be an object/],
|
||||
[{ schemaVersion: 1, slots: { "host.permission": { anchor: "voice.audio-dock" } } }, /Unknown slottable host part/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": "voice.audio-dock" } }, /must be an object/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "host.plugins.launcher" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.connection-status" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "app" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", align: "left" } } }, /invalid align/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", compact: "yes" } } }, /compact must be a boolean/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", extra: true } } }, /unsupported field/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "../escape" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "Voice Audio Dock" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "" } } }, /at most 240 characters/],
|
||||
];
|
||||
for (const [value, message] of invalidDocuments) {
|
||||
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
|
||||
}
|
||||
});
|
||||
|
||||
test("instance-level hidden parts ignore unknown and protected names", () => {
|
||||
assert.deepEqual(parseHiddenHostParts("host.watermark, host.hint voice.audio-dock home.footer"), ["host.watermark", "host.hint"]);
|
||||
assert.deepEqual(parseHiddenHostParts(["host.hint", "host.hint", "nope"]), ["host.hint"]);
|
||||
@@ -247,10 +303,12 @@ test("protected controls cannot be hidden through variables or moved off-screen"
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: -9999px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-inline: -9999px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-block-start: -1200px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -1000px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: -100vw; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 5000px); }',
|
||||
'[data-ws-part="voice.audio-dock"] { transform: matrix(1, 0, 0, 1, -4000, 0); }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: -1e4px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { transform: translateX(calc(2px*-1000)); }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /must remain on screen/, css);
|
||||
}
|
||||
@@ -263,8 +321,18 @@ test("protected controls cannot be hidden through variables or moved off-screen"
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { background: var(--skin-panel); }'));
|
||||
assert.doesNotThrow(() => compile(':root { --skin-hide: none; } [data-ws-part="host.watermark"] { display: var(--skin-hide); }'));
|
||||
// A small margin on a protected control and a decorative dock child are still
|
||||
// legitimate v3 theming.
|
||||
// legitimate v3 theming. Ordinary placement is no longer mistaken for a
|
||||
// yeet: only values clearly beyond a viewport are rejected.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: -6px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-top: 120px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 auto 120px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { top: 100%; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { scale: 100%; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { rotate: 4deg; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { transform: rotate(8deg); }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }'));
|
||||
// The off-screen guard only protects the subject, not decorative or
|
||||
// non-protected parts.
|
||||
@@ -272,12 +340,76 @@ test("protected controls cannot be hidden through variables or moved off-screen"
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { margin-left: -9999px; }'));
|
||||
});
|
||||
|
||||
test("protected controls accept every purely visual property", () => {
|
||||
const themed = compileSkinCss(`
|
||||
:root {
|
||||
--skin-ink: #f8fafc;
|
||||
--skin-card: #0f172a;
|
||||
--skin-line: #38bdf8;
|
||||
--skin-pad: 14px;
|
||||
--skin-size: 56px;
|
||||
--skin-shadow: 0 10px 30px #0006;
|
||||
}
|
||||
[data-ws-part="voice.audio-dock.microphone"],
|
||||
[data-ws-part="voice.connection-status.reconnect"],
|
||||
[data-ws-part="home.footer.clear"],
|
||||
[data-ws-part="auth.password.dialog"] {
|
||||
color: var(--skin-ink);
|
||||
background-color: var(--skin-card);
|
||||
background-image: linear-gradient(135deg, #123456, #654321), url("assets/protected-pattern.png");
|
||||
border: 2px solid var(--skin-line);
|
||||
border-radius: 18px;
|
||||
font-family: var(--skin-font, Tahoma, "Segoe UI", sans-serif);
|
||||
font-size: 15px;
|
||||
padding: var(--skin-pad);
|
||||
width: var(--skin-size);
|
||||
height: var(--skin-size);
|
||||
box-shadow: var(--skin-shadow);
|
||||
text-shadow: 0 1px 2px #0008;
|
||||
}
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"]::before,
|
||||
[data-ws-part="auth.password.actions"] > button {
|
||||
background: var(--skin-line);
|
||||
border-color: var(--skin-line);
|
||||
border-radius: 12px;
|
||||
}
|
||||
`, "demo-skin", new Set(["assets/protected-pattern.png"]), 3);
|
||||
|
||||
assert.match(themed.css, /\[data-ws-part="voice\.audio-dock\.microphone"\]/);
|
||||
assert.match(themed.css, /wskin-asset:assets%2Fprotected-pattern\.png/);
|
||||
// The hide/move guarantees are unchanged.
|
||||
for (const css of [
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { display: none; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { visibility: hidden; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { opacity: 0; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { pointer-events: none; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { clip-path: inset(100%); }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }',
|
||||
':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock.microphone"] { margin-left: var(--skin-pull); }',
|
||||
// Literal filter/clip/content-visibility hiding is rejected, so a variable
|
||||
// must not smuggle the same value past the check.
|
||||
':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { filter: var(--skin-x); }',
|
||||
':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { -webkit-filter: var(--skin-x); }',
|
||||
':root { --skin-x: rect(0, 0, 0, 0); } [data-ws-part="voice.audio-dock.microphone"] { clip: var(--skin-x); }',
|
||||
':root { --skin-x: hidden; } [data-ws-part="voice.audio-dock.microphone"] { content-visibility: var(--skin-x); }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /must remain available|must remain on screen|cannot use indirect values/, css);
|
||||
}
|
||||
});
|
||||
|
||||
test("indirect filter values stay free outside protected controls", () => {
|
||||
for (const version of [2, 3] as const) {
|
||||
assert.doesNotThrow(() => compileSkinCss(':root { --skin-glow: drop-shadow(0 0 4px #0ff); } [data-ws-part="voice.header"] { filter: var(--skin-glow); }', "demo-skin", new Set(), version));
|
||||
}
|
||||
// Literal visual filters remain allowed on protected controls.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock.microphone"] { filter: drop-shadow(0 0 4px #0ff) saturate(1.2); }'));
|
||||
});
|
||||
|
||||
test("host chrome cannot be restyled into a viewport-sized overlay", () => {
|
||||
assert.throws(
|
||||
() => compile('[data-ws-part="host.plugins.overlay"] { position: fixed; inset: 0; z-index: 2147483647; }'),
|
||||
/layout is owned by WebSpeak/,
|
||||
);
|
||||
assert.throws(() => compile('[data-ws-part="host.watermark"] { position: fixed; }'), /layout is owned by WebSpeak/);
|
||||
assert.throws(() => compile('[data-ws-part="host.plugins.overlay"] { width: 100vw; height: 100vh; }'), /fullscreen overlay/);
|
||||
|
||||
// Descendant rules are the same escape: `*` can turn the library contents
|
||||
@@ -286,7 +418,6 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => {
|
||||
'[data-ws-part="host.plugins.overlay"] * { position: fixed; inset: 0; z-index: 2147483647; }',
|
||||
'[data-ws-part="host.plugins.overlay"] * { width: 100vw; height: 100vh; }',
|
||||
'[data-ws-part="host.plugins.overlay"] .ws-plugin-library { position: fixed; top: 0; left: 0; }',
|
||||
'[data-ws-part="host.watermark"] * { z-index: 2147483647; }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
|
||||
}
|
||||
@@ -299,12 +430,290 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => {
|
||||
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
|
||||
}
|
||||
|
||||
// Decorative host chrome is not on the recovery path: it may be repositioned,
|
||||
// resized, restacked and animated, at most with a warning.
|
||||
for (const css of [
|
||||
'[data-ws-part="host.watermark"] { position: fixed; }',
|
||||
'[data-ws-part="host.watermark"] * { z-index: 2147483647; }',
|
||||
'[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; }',
|
||||
'[data-ws-part="host.plugins.launcher"] { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; }',
|
||||
'[data-ws-part="host.hint"] { position: absolute; transform: translateX(-10px); }',
|
||||
'[data-ws-part="host.voice-status-decoration"] { position: fixed; inset: 0; pointer-events: none; }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
|
||||
// Colors, borders, radius, shadows and artwork stay available, including on
|
||||
// descendants of the overlay.
|
||||
const themed = compile('[data-ws-part="host.plugins.overlay"] { border: 2px solid #1d4f9c; border-radius: 4px; background: #fff; box-shadow: 0 2px 8px #0003; }');
|
||||
assert.match(themed.css, /data-ws-part="host\.plugins\.overlay"/);
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { color: #fff; border-color: #1d4f9c; border-radius: 6px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }'));
|
||||
// Overlay contents may use normal sizing and margins; only a viewport-sized
|
||||
// box would turn the library contents into a fullscreen mask.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] button { min-width: 44px; min-height: 44px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { margin: 0; }'));
|
||||
});
|
||||
|
||||
test("keyframes follow the same protected-control rules as regular declarations", () => {
|
||||
const rejected: Array<[string, RegExp]> = [
|
||||
['@keyframes k { to { display: none; opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { transform: translateX(-9999px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
['@keyframes k { to { inset: 0 0 0 -120vw; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
['@keyframes k { to { filter: opacity(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/],
|
||||
['@keyframes k { to { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/],
|
||||
// A variable animation name must not hide the name from the walk.
|
||||
[':root { --skin-anim: k; } @keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: var(--skin-anim) 1s forwards; }', /cannot use indirect values/],
|
||||
['@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { --skin-anim: k; } [data-ws-part="voice.audio-dock"] { animation-name: var(--skin-anim); }', /cannot use indirect values/],
|
||||
];
|
||||
for (const [css, message] of rejected) {
|
||||
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
|
||||
}
|
||||
// A keyframe shared by a protected and a non-protected part is judged by the
|
||||
// protected reference.
|
||||
assert.throws(
|
||||
() => compile('@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation: k 1s; }'),
|
||||
/must remain available/,
|
||||
);
|
||||
|
||||
// Harmless fades, color tweens and gentle motion on non-protected parts, and
|
||||
// visual / motion keyframes on decorative host parts, still compile.
|
||||
for (const css of [
|
||||
'@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: fade 2s ease; }',
|
||||
'@keyframes tint { from { color: #fff; } to { color: #1d4f9c; } } [data-ws-part="home.header"] { animation: tint 1.2s; }',
|
||||
'@keyframes drift { from { transform: translateY(0); } to { transform: translateY(-6px); } } [data-ws-part="home.hero.eyebrow"] { animation: drift 3s infinite alternate; }',
|
||||
'@keyframes wm { from { opacity: .1; color: #8ab9cf; transform: translateX(0); } to { opacity: .3; color: #2b6d8a; transform: translateX(20px); } } [data-ws-part="host.watermark"] { animation: wm 4s infinite alternate; }',
|
||||
'@keyframes big { to { width: 100vw; height: 100vh; opacity: .2; } } [data-ws-part="host.watermark"] { animation: big 1s forwards; }',
|
||||
'@keyframes hide { to { display: none; } } [data-ws-part="host.hint"] { animation: hide 1s forwards; }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
});
|
||||
|
||||
test("keyframes hide protected parts only when the animation can rest there", () => {
|
||||
// Entrances and pulses that merely pass through a hidden/intermediate state
|
||||
// are legitimate: only `to`/`100%` (and a genuinely resting `from`) count.
|
||||
for (const css of [
|
||||
'@keyframes in { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="app"] { animation: in .3s; }',
|
||||
'@keyframes toastIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } } [data-ws-part="app.toast"] { animation: toastIn .3s; }',
|
||||
'@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: fade .4s; }',
|
||||
'@keyframes slide { from { transform: translateX(-100%); } to { transform: none; } } [data-ws-part="voice.mobile-nav"] { animation: slide .25s; }',
|
||||
'@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="app.toast"] { animation: pop .2s; }',
|
||||
'@keyframes pulse { 50% { opacity: 0; } 100% { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: pulse 2s infinite; }',
|
||||
'@keyframes in { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } } [data-ws-part="host.plugins.overlay"] { animation: in .2s; }',
|
||||
'@keyframes pop { from { scale: 0; } to { scale: 1; } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }',
|
||||
'@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }',
|
||||
'@keyframes slide { from { transform: translateY(8px); } to { transform: translateY(0); } } [data-ws-part="host.plugins.overlay"] { animation: slide .2s; }',
|
||||
// A keyframe without a `to` frame ends on the element's own style.
|
||||
'@keyframes tint { 50% { opacity: 0; } } [data-ws-part="voice.connection-status"] { animation: tint 2s; }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
|
||||
const rejected: Array<[string, RegExp]> = [
|
||||
['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { 100% { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
// Reverse/alternate/fill-backwards animations can end (or hold) on `from`.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
|
||||
['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s alternate; }', /must remain available/],
|
||||
['@keyframes k { from { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-direction: alternate-reverse; }', /must remain available/],
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-fill-mode: both; }', /must remain available/],
|
||||
['@keyframes k { 0% { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
|
||||
// Declaration order cannot hide a reverse direction behind a longhand.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-direction: normal; animation: k 1s reverse; }', /must remain available/],
|
||||
// A variable fill mode is unknowable, so the start frame is treated as resting.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-fill-mode: var(--skin-fill); }', /must remain available/],
|
||||
// A paused animation renders its start frame from the first paint.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s paused; }', /must remain available/],
|
||||
['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-play-state: paused; }', /must remain available/],
|
||||
// Escaped `to`/`from` and `1e2%` must still be recognised as resting steps.
|
||||
['@keyframes k { \\74 o { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { t\\6f { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
['@keyframes k { \\66 rom { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
|
||||
['@keyframes k { 1e2% { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
// Direction/fill longhands in a sibling rule on the same subject still rest on `from`.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation-direction: reverse; animation-fill-mode: both; }', /must remain available/],
|
||||
];
|
||||
for (const [css, message] of rejected) {
|
||||
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
|
||||
}
|
||||
});
|
||||
|
||||
test("escaped animation names are matched and rewritten", () => {
|
||||
const escaped = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation-name: p\\75 lse; }');
|
||||
assert.match(escaped.css, /animation-name: ws-demo-skin-pulse/);
|
||||
assert.doesNotMatch(escaped.css, /p\\75 lse/);
|
||||
|
||||
const shorthand = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: p\\75 lse .3s ease; }');
|
||||
assert.match(shorthand.css, /animation: ws-demo-skin-pulse \.3s ease/);
|
||||
|
||||
// Only the name slot is rewritten: a keyframe named like a timing keyword
|
||||
// must not turn the timing function into a keyframe reference.
|
||||
const timing = compile('@keyframes linear { from { opacity: 1; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: linear 1s linear; }');
|
||||
assert.match(timing.css, /animation: linear 1s ws-demo-skin-linear/);
|
||||
});
|
||||
|
||||
test("keyword-shaped animation tokens do not become keyframe references", () => {
|
||||
const named = compile('@keyframes alternate { from { opacity: 1; } to { opacity: 1; } } @keyframes bob { from { transform: translateY(0); } to { transform: translateY(4px); } } [data-ws-part="voice.audio-dock"] { animation: bob 2s alternate; }');
|
||||
assert.match(named.css, /@keyframes ws-demo-skin-alternate/);
|
||||
assert.match(named.css, /animation: ws-demo-skin-bob 2s alternate/);
|
||||
assert.doesNotMatch(named.css, /animation: bob 2s ws-demo-skin-alternate/);
|
||||
});
|
||||
|
||||
test("normalised hidden values cannot hide protected parts", () => {
|
||||
const hidden: Array<[string, string]> = [
|
||||
["display", "none"],
|
||||
["visibility", "hidden"],
|
||||
["visibility", "collapse"],
|
||||
["opacity", ".0"],
|
||||
["opacity", "+0"],
|
||||
["opacity", "-1"],
|
||||
["opacity", "0%"],
|
||||
["opacity", "0.5%"],
|
||||
["opacity", "0.001"],
|
||||
["opacity", "calc(0)"],
|
||||
["filter", "opacity(0.0)"],
|
||||
["filter", "brightness(0)"],
|
||||
["-webkit-filter", "opacity(0)"],
|
||||
["pointer-events", "none"],
|
||||
["transform", "scale(0)"],
|
||||
["transform", "scaleX(0)"],
|
||||
["transform", "scaleY(0)"],
|
||||
["transform", "scale3d(0, 1, 1)"],
|
||||
["transform", "scale(0 0)"],
|
||||
["scale", "0"],
|
||||
["scale", "0%"],
|
||||
["scale", "0 0"],
|
||||
["content-visibility", "hidden"],
|
||||
["clip-path", "inset(50%)"],
|
||||
["clip-path", "inset(60% 0)"],
|
||||
["clip-path", "inset(0 60%)"],
|
||||
["clip-path", "circle(0)"],
|
||||
["clip-path", "ellipse(0 10px)"],
|
||||
["clip", "rect(0,0,0,0)"],
|
||||
["clip", "rect(0 0 0 0)"],
|
||||
["mask", "alpha(0)"],
|
||||
["mask-image", "luminance(0)"],
|
||||
["mask-image", "linear-gradient(transparent, transparent)"],
|
||||
["mask-image", "linear-gradient(#0000, #0000)"],
|
||||
["mask-image", "linear-gradient(rgb(0 0 0 / 0), rgb(0 0 0 / 0))"],
|
||||
["mask-image", "conic-gradient(from 0deg, transparent, transparent)"],
|
||||
["opacity", "0e0"],
|
||||
["opacity", "1e-3"],
|
||||
["filter", "opacity(1e-2)"],
|
||||
["transform", "scale(0e0)"],
|
||||
["scale", "1e-9"],
|
||||
];
|
||||
for (const [property, value] of hidden) {
|
||||
const direct = `[data-ws-part="voice.audio-dock"] { ${property}: ${value}; }`;
|
||||
assert.throws(() => compile(direct), /must remain available/, direct);
|
||||
const frame = `@keyframes k { to { ${property}: ${value}; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; }`;
|
||||
assert.throws(() => compile(frame), /must remain available/, frame);
|
||||
}
|
||||
// Partial effects and artwork clipping remain legitimate.
|
||||
for (const css of [
|
||||
'[data-ws-part="voice.audio-dock"] { opacity: .5; }',
|
||||
'[data-ws-part="voice.audio-dock"] { filter: opacity(.4); }',
|
||||
'[data-ws-part="voice.audio-dock"] { transform: scale(.5); }',
|
||||
'[data-ws-part="voice.audio-dock"] { scale: .8; }',
|
||||
'[data-ws-part="voice.audio-dock"] { clip-path: polygon(0 0, 100% 0, 100% 80%, 0 100%); }',
|
||||
'[data-ws-part="voice.audio-dock"] { clip-path: inset(20%); }',
|
||||
'[data-ws-part="voice.audio-dock"] { mask-image: linear-gradient(transparent, red); }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
});
|
||||
|
||||
test("selector variants cannot disguise a protected subject", () => {
|
||||
for (const css of [
|
||||
'[data-ws-part="VOICE.AUDIO-DOCK" i] { display: none; }',
|
||||
'[data-ws-part="voice.audio-dock" I] { opacity: 0; }',
|
||||
':not(:not([data-ws-part="voice.audio-dock"])) { display: none; }',
|
||||
':not(:not([data-ws-part="voice.audio-dock"]):hover) { visibility: hidden; }',
|
||||
':nth-child(2n of [data-ws-part="voice.audio-dock"]) { display: none; }',
|
||||
':nth-last-child(odd of .member, [data-ws-part="voice.audio-dock"]) { pointer-events: none; }',
|
||||
':not(:not([data-ws-part="voice.audio-dock"]), [data-ws-part="home.title"]) { display: none; }',
|
||||
':not(:is(:not([data-ws-part="voice.audio-dock"]))) { display: none; }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /must remain available/, css);
|
||||
}
|
||||
// The `s` flag keeps matching case-sensitive, so this selects nothing.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="VOICE.AUDIO-DOCK" s] { display: none; }'));
|
||||
// A single :not() still means "every other element".
|
||||
assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }'));
|
||||
});
|
||||
|
||||
test("escaped, namespaced and :is()/:where() animation names cannot bypass the protected-control locks", () => {
|
||||
const rejected: Array<[string, RegExp]> = [
|
||||
// Escaped property name used to skip the keyframe mapping walk.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { anim\\61 tion: k 1s forwards; }', /must remain available/],
|
||||
// A pack can predict the namespace and reference the already-renamed keyframe.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-k 1s forwards; }', /must remain available/],
|
||||
// The protected subject can be wrapped in a functional pseudo-class.
|
||||
[':is([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/],
|
||||
[':where([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/],
|
||||
['@keyframes k { to { opacity: 0; } } :is([data-ws-part="voice.audio-dock"]) { animation: k 1s forwards; }', /must remain available/],
|
||||
// -webkit-* animation longhands participate in the same walks.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation-name: k; }', /must remain available/],
|
||||
['[data-ws-part="voice.audio-dock"] { -webkit-animation: var(--skin-a); }', /cannot use indirect values/],
|
||||
// Escaped *values* used to bail out of the mapping walk on a backslash and
|
||||
// still resolve to the renamed keyframe in the browser.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\6b 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\00006b 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: \\6b; }', /must remain available/],
|
||||
// Prefixed visual-removal properties must use the same checks as the unprefixed form.
|
||||
['[data-ws-part="voice.audio-dock"] { -webkit-filter: opacity(0); }', /must remain available/],
|
||||
['[data-ws-part="voice.audio-dock"] { -webkit-transform: scale(0); }', /must remain available/],
|
||||
];
|
||||
for (const [css, message] of rejected) {
|
||||
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
|
||||
}
|
||||
|
||||
// `:not()` does not make the protected part the subject; only a v3 warning.
|
||||
assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }'));
|
||||
|
||||
// A harmless -webkit-animation on a non-protected part still compiles and its
|
||||
// keyframe name is rewritten into the skin namespace.
|
||||
const webkit = compile('@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { -webkit-animation: fade 2s ease; }');
|
||||
assert.match(webkit.css, /@keyframes ws-demo-skin-fade/);
|
||||
assert.match(webkit.css, /-webkit-animation: ws-demo-skin-fade 2s ease/);
|
||||
});
|
||||
|
||||
test("keyframes cannot turn the plugin overlay into a fullscreen layer", () => {
|
||||
for (const css of [
|
||||
'@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }',
|
||||
'@keyframes k { to { width: 100vw; height: 100vh; } } [data-ws-part="host.plugins.overlay"] * { animation: k 1s forwards; }',
|
||||
'@keyframes k { to { zoom: 10; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }',
|
||||
'@keyframes k { to { transform: scale(10); } } [data-ws-part="host.plugins.overlay"] { animation-name: k; }',
|
||||
'@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { --skin-a: ws-demo-skin-k; animation: var(--skin-a) 1s forwards; }',
|
||||
'[data-ws-part="host.plugins.overlay"] * { width: calc(50vw * 2); }',
|
||||
'[data-ws-part="host.plugins.overlay"] * { width: calc(99vw + 1vw); }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
|
||||
}
|
||||
// The same animation is harmless on decorative host chrome.
|
||||
assert.doesNotThrow(() => compile('@keyframes k { to { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; } } [data-ws-part="host.watermark"] { animation: k 1s forwards; }'));
|
||||
});
|
||||
|
||||
test("large layout restyles of non-protected parts and decorative host chrome compile", () => {
|
||||
for (const css of [
|
||||
'[data-ws-part="home.header"] { display: grid; grid-template-columns: 1fr 2fr; gap: 16px; position: relative; width: 80vw; height: 50vh; }',
|
||||
'[data-ws-part="home.header"] { display: flex; flex-direction: column; align-items: stretch; translate: 24px 0; }',
|
||||
'[data-ws-part="voice.audio-dock"] > div:first-child { position: absolute; width: 100vw; height: 100vh; }',
|
||||
// Whole-page and protected-part layout rewrites are the owner's explicit
|
||||
// use case; placement is no longer mistaken for a yeet.
|
||||
'[data-ws-part="app"] { display: grid; grid-template-areas: "rail main"; grid-template-columns: 72px 1fr; position: relative; }',
|
||||
'[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; display: flex; flex-direction: column; gap: 10px; }',
|
||||
'[data-ws-part="home"] { display: flex; flex-direction: column; align-items: stretch; min-height: 100vh; }',
|
||||
// Official example skins (harbor, kaak) clip their own artwork.
|
||||
'[data-ws-part="home.header"] { clip-path: polygon(0 0, 100% 0, 100% 82%, 0 100%); }',
|
||||
'[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; transform: rotate(-8deg); }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
});
|
||||
|
||||
test("official and built-in skins hide host decorations unless the active skin opts in", () => {
|
||||
|
||||
+601
-129
@@ -1,6 +1,6 @@
|
||||
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
|
||||
import selectorParser from "postcss-selector-parser";
|
||||
import valueParser from "postcss-value-parser";
|
||||
import selectorParser, { type Node as SelectorNode, type Pseudo as SelectorPseudo } from "postcss-selector-parser";
|
||||
import valueParser, { type Node as ValueNode } from "postcss-value-parser";
|
||||
import {
|
||||
DECORATIVE_PART_IDS as OPTIONAL_VISUAL_PARTS,
|
||||
HOST_CHROME_PART_IDS,
|
||||
@@ -67,7 +67,12 @@ const HOST_OVERLAY_LOCKED_PROPERTIES = new Set([
|
||||
"aspect-ratio", "margin", "margin-block", "margin-inline", "margin-block-start", "margin-block-end",
|
||||
"margin-inline-start", "margin-inline-end",
|
||||
]);
|
||||
/** Properties whose indirect values could smuggle a hidden or moved control past the static checks. */
|
||||
/**
|
||||
* Properties whose indirect values could smuggle a hidden or moved control past
|
||||
* the static checks. Purely visual properties (colour, background, border,
|
||||
* radius, font, shadow, padding, width/height) are deliberately absent: a
|
||||
* protected control may theme them with `var()`.
|
||||
*/
|
||||
const INDIRECT_VALUE_PROPERTIES = new Set([
|
||||
"all", "display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image",
|
||||
"position", "top", "right", "bottom", "left", "inset",
|
||||
@@ -79,6 +84,14 @@ const INDIRECT_VALUE_PROPERTIES = new Set([
|
||||
"margin-block", "margin-block-start", "margin-block-end",
|
||||
"margin-inline", "margin-inline-start", "margin-inline-end",
|
||||
]);
|
||||
/**
|
||||
* Visual properties whose literal hiding values (`filter: opacity(0)`,
|
||||
* `clip: rect(0 0 0 0)`, `content-visibility: hidden`) are rejected on
|
||||
* protected controls. They stay free on every other part, but a protected
|
||||
* control may not take them from `var()`/`attr()`, which would hide the
|
||||
* same value from the static check.
|
||||
*/
|
||||
const PROTECTED_INDIRECT_HIDE_PROPERTIES = new Set(["filter", "clip", "content-visibility"]);
|
||||
/** Attributes a skin author must never use to reach outside the public hooks. */
|
||||
const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
|
||||
HOST_SKIN_ATTRIBUTE,
|
||||
@@ -94,6 +107,19 @@ const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
|
||||
"data-ws-host-layer-content",
|
||||
"data-ws-recovery-action",
|
||||
]);
|
||||
/** 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. */
|
||||
const ANIMATION_KEYWORD_CATEGORIES = new Map<string, string>([
|
||||
["linear", "timing"], ["ease", "timing"], ["ease-in", "timing"], ["ease-out", "timing"],
|
||||
["ease-in-out", "timing"], ["step-start", "timing"], ["step-end", "timing"],
|
||||
["normal", "direction"], ["reverse", "direction"], ["alternate", "direction"], ["alternate-reverse", "direction"],
|
||||
["none", "fill"], ["forwards", "fill"], ["backwards", "fill"], ["both", "fill"],
|
||||
["running", "play"], ["paused", "play"], ["infinite", "iteration"],
|
||||
]);
|
||||
/** Words that let an animation hold its `from`/`0%` frame. */
|
||||
const RESTING_START_KEYWORDS = new Set(["reverse", "alternate", "alternate-reverse", "backwards", "both", "paused"]);
|
||||
|
||||
export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } {
|
||||
const size = new TextEncoder().encode(source).byteLength;
|
||||
if (!size || size > MAX_CSS_BYTES) throw new SkinCssValidationError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
|
||||
@@ -105,10 +131,8 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
|
||||
const scope = pluginId
|
||||
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
|
||||
: skinScope;
|
||||
// Host chrome is Teleported outside `.ws-skin-root`. Rules that target only
|
||||
// registered host parts use a second, document-level scope anchored to an
|
||||
// attribute the host sets while this exact skin is active. Author CSS never
|
||||
// names html/body: the host generates the scope itself.
|
||||
// Host chrome is Teleported outside `.ws-skin-root`; these rules get their own
|
||||
// document-level scope, which the host anchors to the active skin attribute.
|
||||
const hostSkinScope = `:root[${HOST_SKIN_ATTRIBUTE}="${id}"]`;
|
||||
const hostScopeNodes = selectorParser().astSync(hostSkinScope).first!.nodes.map((node) => node.clone());
|
||||
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
|
||||
@@ -180,48 +204,100 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
|
||||
|
||||
const referencedKeyframes = new Set<string>();
|
||||
const nonOptionalKeyframes = new Set<string>();
|
||||
// Keyframes inherit the protected/locked status of their referencing rules;
|
||||
// params are namespaced here, and `from`/`0%` only rests for some rules.
|
||||
const protectedKeyframeParts = new Map<string, string>();
|
||||
const lockedHostKeyframeParts = new Map<string, Set<string>>();
|
||||
const restingFromKeyframes = new Set<string>();
|
||||
// Direction/fill/play-state longhands may sit in a sibling rule on the same
|
||||
// subject; collect names per subject, then mark resting-from afterwards.
|
||||
const subjectKeyframes = new Map<string, Set<string>>();
|
||||
const restingSubjects = new Set<string>();
|
||||
root.walkRules((rule: Rule) => {
|
||||
if (hasKeyframesAncestor(rule)) return;
|
||||
const optionalTarget = hideableRules.has(rule);
|
||||
const protectedTarget = selectorSubjectProtectedPart(rule.selector);
|
||||
const lockedHostParts = selectorLockedHostParts(rule.selector);
|
||||
const subjects = [
|
||||
...selectorSubjectParts(rule.selector, PROTECTED_PART_IDS),
|
||||
...selectorSubjectParts(rule.selector, HOST_CHROME_PART_IDS).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part)),
|
||||
];
|
||||
const restsAtStart = subjects.length > 0 && ruleCanRestAtStart(rule);
|
||||
if (restsAtStart) for (const subject of subjects) restingSubjects.add(subject);
|
||||
rule.walkDecls((declaration: Declaration) => {
|
||||
const property = declaration.prop.toLowerCase();
|
||||
// Decode the property like the enforcement walk (`anim\61 tion`), and the
|
||||
// value so escaped identifiers match their declared names.
|
||||
const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase());
|
||||
if (property !== "animation" && property !== "animation-name") return;
|
||||
const value = declaration.value;
|
||||
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
|
||||
const decodedValue = decodeCssEscapes(declaration.value);
|
||||
if (/\b(?:var|attr)\s*\(/i.test(decodedValue)) {
|
||||
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
|
||||
return;
|
||||
}
|
||||
for (const name of keyframeNames.keys()) {
|
||||
if (!referencesCssIdentifier(value, name)) continue;
|
||||
referencedKeyframes.add(name);
|
||||
if (!optionalTarget) nonOptionalKeyframes.add(name);
|
||||
const { names } = parseAnimationLayers(decodedValue, property);
|
||||
for (const nameNode of names) {
|
||||
if (!nameNode) continue;
|
||||
const name = nameNode.value;
|
||||
for (const [original, scopedName] of keyframeNames) {
|
||||
if (name !== original && name !== scopedName) continue;
|
||||
referencedKeyframes.add(original);
|
||||
if (!optionalTarget) nonOptionalKeyframes.add(original);
|
||||
if (protectedTarget && !protectedKeyframeParts.has(scopedName)) {
|
||||
protectedKeyframeParts.set(scopedName, protectedTarget);
|
||||
}
|
||||
if (lockedHostParts.length) {
|
||||
const parts = lockedHostKeyframeParts.get(scopedName) ?? new Set<string>();
|
||||
for (const part of lockedHostParts) parts.add(part);
|
||||
lockedHostKeyframeParts.set(scopedName, parts);
|
||||
}
|
||||
if (restsAtStart) restingFromKeyframes.add(scopedName);
|
||||
for (const subject of subjects) {
|
||||
const names = subjectKeyframes.get(subject) ?? new Set<string>();
|
||||
names.add(scopedName);
|
||||
subjectKeyframes.set(subject, names);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
for (const subject of restingSubjects) {
|
||||
for (const name of subjectKeyframes.get(subject) ?? []) restingFromKeyframes.add(name);
|
||||
}
|
||||
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
|
||||
.filter((name) => !nonOptionalKeyframes.has(name))
|
||||
.map((name) => keyframeNames.get(name)!));
|
||||
|
||||
root.walkDecls((declaration: Declaration) => {
|
||||
const property = decodeCssEscapes(declaration.prop).toLowerCase();
|
||||
const unprefixedProperty = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
|
||||
const unprefixedProperty = unprefixed(property);
|
||||
const value = declaration.value.trim();
|
||||
const decodedValue = decodeCssEscapes(value);
|
||||
const owningRule = findOwningRule(declaration);
|
||||
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
|
||||
const keyframeScope = keyframesRule?.params.trim() ?? null;
|
||||
// `to`/`100%` always rest, and `from`/`0%` when the rule can rest at start.
|
||||
const restingFrame = !keyframesRule
|
||||
|| (keyframeScope !== null && keyframeStepCanRest(owningRule!.selector, restingFromKeyframes.has(keyframeScope)));
|
||||
const canHideTarget = owningRule
|
||||
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
|
||||
: false;
|
||||
// Trusted UI and essential audio/recovery controls stay available even for
|
||||
// open skins. The host also draws authorization and recovery UI outside the
|
||||
// skin root, so a container-level hide cannot remove them either.
|
||||
const protectedTarget = owningRule && !keyframesRule ? selectorSubjectProtectedPart(owningRule.selector) : null;
|
||||
// Every themeable host part referenced anywhere in the selector. A rule may
|
||||
// target a descendant of the overlay (for example with `*`), so the subject
|
||||
// alone is not enough to decide whether host chrome layout is at stake.
|
||||
const hostChromeParts = owningRule && !keyframesRule ? selectorHostChromeParts(owningRule.selector) : [];
|
||||
// A keyframe inherits the protected status of its referencing rules.
|
||||
const protectedTarget = owningRule
|
||||
? keyframesRule
|
||||
? (keyframeScope ? protectedKeyframeParts.get(keyframeScope) ?? null : null)
|
||||
: selectorSubjectProtectedPart(owningRule.selector)
|
||||
: null;
|
||||
// Every locked host part in the selector, not just the subject: `*` under
|
||||
// the overlay is still host chrome. Decorative parts are excluded.
|
||||
const hostChromeParts = owningRule
|
||||
? keyframesRule
|
||||
? (keyframeScope ? [...(lockedHostKeyframeParts.get(keyframeScope) ?? [])] : [])
|
||||
: selectorLockedHostParts(owningRule.selector)
|
||||
: [];
|
||||
const inHostChromeScope = hostChromeParts.length > 0;
|
||||
const inOverlayScope = hostChromeParts.includes("host.plugins.overlay");
|
||||
const overlaySubject = Boolean(!keyframesRule && owningRule
|
||||
&& selectorSubjectPart(owningRule.selector, HOST_CHROME_PART_IDS) === "host.plugins.overlay");
|
||||
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
|
||||
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
|
||||
throw declaration.error(pluginId
|
||||
@@ -231,55 +307,60 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
|
||||
if (schemaVersion < 3 && isLayoutAffectingProperty(property)) {
|
||||
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
|
||||
}
|
||||
// Host chrome lives outside the skin root and owns its own placement. A
|
||||
// skin may repaint it (colors, borders, radius, artwork) but must not turn
|
||||
// it — or any of its descendants — into a viewport-sized overlay above
|
||||
// authorization/recovery UI.
|
||||
if (inHostChromeScope && HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) {
|
||||
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls.");
|
||||
}
|
||||
if (inOverlayScope && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) {
|
||||
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
|
||||
// Host chrome keeps its placement and footprint; decorative host parts skip
|
||||
// this lock. Overlay contents may size themselves unless viewport-sized.
|
||||
if (inHostChromeScope && !keyframesRule) {
|
||||
if (HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) {
|
||||
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls.");
|
||||
}
|
||||
if (overlaySubject && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) {
|
||||
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
|
||||
}
|
||||
// Overlay contents may size themselves, but not to the viewport.
|
||||
if (inOverlayScope && !overlaySubject && OVERLAY_SIZE_PROPERTIES.has(unprefixedProperty) && valueIsViewportSized(decodedValue)) {
|
||||
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
|
||||
}
|
||||
} else if (inHostChromeScope && restingFrame && keyframeEscapesHostLock(unprefixedProperty, decodedValue)) {
|
||||
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition, restack or resize host controls into a fullscreen layer.");
|
||||
}
|
||||
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
|
||||
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) {
|
||||
throw declaration.error("Executable CSS values are not allowed.");
|
||||
}
|
||||
const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase();
|
||||
if (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
|
||||
const indirectValue = restingFrame && /\b(?:var|attr)\s*\(/i.test(decodedValue);
|
||||
if (indirectValue && protectedTarget
|
||||
&& (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) || PROTECTED_INDIRECT_HIDE_PROPERTIES.has(unprefixedProperty))) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
|
||||
}
|
||||
if (indirectValue && !protectedTarget && INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
|
||||
}
|
||||
// An indirect animation name is checked at the declaration site. Locked
|
||||
// host chrome (the plugin overlay) uses the same rule, otherwise a
|
||||
// variable could point at a fullscreen keyframe.
|
||||
if (!keyframesRule && (unprefixedProperty === "animation" || unprefixedProperty === "animation-name")
|
||||
&& /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
|
||||
if (protectedTarget) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
|
||||
}
|
||||
if (!canHideTarget && schemaVersion < 3) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
|
||||
if (inHostChromeScope) {
|
||||
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls through an indirect animation name.");
|
||||
}
|
||||
}
|
||||
const removesVisual = property === "all"
|
||||
|| (property === "display" && compactValue === "none")
|
||||
|| (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue))
|
||||
|| (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue))
|
||||
|| (property === "pointer-events" && compactValue === "none")
|
||||
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|
||||
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
|
||||
if (removesVisual && protectedTarget) {
|
||||
// One predicate for every way a declaration can hide or disable a part.
|
||||
const hidesVisual = restingFrame && hidesVisually(unprefixedProperty, decodedValue);
|
||||
if (hidesVisual && protectedTarget) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" must remain available; permission, recovery and essential audio paths cannot be hidden.`);
|
||||
}
|
||||
if (removesVisual && !canHideTarget && schemaVersion < 3) {
|
||||
if (hidesVisual && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
|
||||
}
|
||||
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue))
|
||||
|| (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue))
|
||||
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue));
|
||||
if (visuallyRemoves && protectedTarget) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" must remain visible.`);
|
||||
}
|
||||
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
|
||||
}
|
||||
if (protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) {
|
||||
if (restingFrame && protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" must remain on screen and reachable.`);
|
||||
}
|
||||
if (schemaVersion >= 3 && removesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
|
||||
if (schemaVersion >= 3 && hidesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
|
||||
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
|
||||
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
|
||||
const withScopedNames = rewriteScopedNames(value, unprefixedProperty, keyframeNames, fontFamilyNames);
|
||||
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
|
||||
if (!hasSkinCssAsset(assets, assetPath)) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
|
||||
return `wskin-asset:${encodeURIComponent(assetPath)}`;
|
||||
@@ -427,24 +508,87 @@ function assertHostChromeSubject(parsed: selectorParser.Root): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Find a protected part in the subject (last compound) of any selector in a rule. */
|
||||
function selectorSubjectProtectedPart(selector: string): string | null {
|
||||
/** Functional pseudo-classes whose arguments keep the subject role. */
|
||||
const SUBJECT_PSEUDO_CLASSES = new Set([":is", ":where", ":matches", ":-webkit-any", ":-moz-any"]);
|
||||
|
||||
/** The nodes after the last combinator, i.e. the subject compound. */
|
||||
function lastCompound(nodes: SelectorNode[]): SelectorNode[] {
|
||||
let start = 0;
|
||||
for (let index = nodes.length - 1; index >= 0; index -= 1) {
|
||||
if (nodes[index].type === "combinator") { start = index + 1; break; }
|
||||
}
|
||||
return nodes.slice(start);
|
||||
}
|
||||
|
||||
/** Find a part in a compound; `:is()`/`:where()`/`:nth-child(… of S)` and
|
||||
* `:not(:not(X))` keep the subject role, a single `:not()` does not. */
|
||||
function compoundPart(nodes: SelectorNode[], parts: ReadonlySet<string>): string | null {
|
||||
for (const node of nodes) {
|
||||
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
|
||||
const value = node.value.replace(/^['"]|['"]$/g, "");
|
||||
if (node.insensitive) {
|
||||
const lower = value.toLowerCase();
|
||||
for (const part of parts) if (part.toLowerCase() === lower) return part;
|
||||
} else if (parts.has(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
if (node.type !== "pseudo" || !node.nodes) continue;
|
||||
const pseudo = node.value.toLowerCase();
|
||||
if (SUBJECT_PSEUDO_CLASSES.has(pseudo) || pseudo === ":nth-child" || pseudo === ":nth-last-child") {
|
||||
for (const nested of node.nodes) {
|
||||
const part = compoundPart(lastCompound(nested.nodes), parts);
|
||||
if (part) return part;
|
||||
}
|
||||
} else if (pseudo === ":not") {
|
||||
// `:not(:not(X))` and `:not(:not(X), Y)` are `X`; wrappers like
|
||||
// `:not(:is(:not(X)))` unwrap the same way. A single `:not(X)` is skipped.
|
||||
for (const argument of node.nodes) {
|
||||
const inner = nestedNegation(lastCompound(argument.nodes));
|
||||
if (!inner) continue;
|
||||
for (const nested of inner.nodes) {
|
||||
const part = compoundPart(lastCompound(nested.nodes), parts);
|
||||
if (part) return part;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A `:not(...)` argument that is itself a `:not`, possibly wrapped in `:is()`. */
|
||||
function nestedNegation(nodes: SelectorNode[]): SelectorPseudo | null {
|
||||
const direct = nodes.find((node): node is SelectorPseudo => node.type === "pseudo" && node.value.toLowerCase() === ":not");
|
||||
if (direct) return direct;
|
||||
for (const node of nodes) {
|
||||
if (node.type !== "pseudo" || !node.nodes || !SUBJECT_PSEUDO_CLASSES.has(node.value.toLowerCase())) continue;
|
||||
for (const nested of node.nodes) {
|
||||
const found = nestedNegation(lastCompound(nested.nodes));
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every matching part in the subject of any selector in a rule. */
|
||||
function selectorSubjectParts(selector: string, parts: ReadonlySet<string>): string[] {
|
||||
const found: string[] = [];
|
||||
try {
|
||||
const parsed = selectorParser().astSync(selector);
|
||||
for (const item of parsed.nodes) {
|
||||
let start = 0;
|
||||
for (let index = item.nodes.length - 1; index >= 0; index -= 1) {
|
||||
if (item.nodes[index].type === "combinator") { start = index + 1; break; }
|
||||
}
|
||||
for (let index = start; index < item.nodes.length; index += 1) {
|
||||
const node = item.nodes[index];
|
||||
if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) continue;
|
||||
const part = node.value.replace(/^['"]|['"]$/g, "");
|
||||
if (PROTECTED_PART_IDS.has(part)) return part;
|
||||
}
|
||||
const part = compoundPart(lastCompound(item.nodes), parts);
|
||||
if (part && !found.includes(part)) found.push(part);
|
||||
}
|
||||
} catch { /* A malformed selector is rejected elsewhere. */ }
|
||||
return null;
|
||||
return found;
|
||||
}
|
||||
|
||||
function selectorSubjectPart(selector: string, parts: ReadonlySet<string>): string | null {
|
||||
return selectorSubjectParts(selector, parts)[0] ?? null;
|
||||
}
|
||||
|
||||
function selectorSubjectProtectedPart(selector: string): string | null {
|
||||
return selectorSubjectPart(selector, PROTECTED_PART_IDS);
|
||||
}
|
||||
|
||||
/** Find every themeable host part referenced by a selector, in any compound. */
|
||||
@@ -460,71 +604,396 @@ function selectorHostChromeParts(selector: string): string[] {
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** Host parts whose layout stays locked; decorative chrome is excluded. */
|
||||
function selectorLockedHostParts(selector: string): string[] {
|
||||
return selectorHostChromeParts(selector).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part));
|
||||
}
|
||||
|
||||
function unprefixed(property: string): string {
|
||||
return property.replace(/^-(?:webkit|moz|ms|o)-/, "");
|
||||
}
|
||||
|
||||
function isLayoutAffectingProperty(property: string): boolean {
|
||||
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
|
||||
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
|
||||
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
|
||||
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
|
||||
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
|
||||
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
|
||||
const local = unprefixed(property);
|
||||
if (LAYOUT_AFFECTING_PROPERTIES.has(local)) return true;
|
||||
if (/^(?:margin|padding)(?:-|$)/.test(local)) return true;
|
||||
if (/^border(?:-|$)/.test(local) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(local)) return true;
|
||||
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(local)) return true;
|
||||
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(local);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a positioning/margin/transform value can push a protected control
|
||||
* off-screen. Thresholds are deliberately low: a protected control has a
|
||||
* minimum 44 px hit target, so an offset of a hundred pixels is already enough
|
||||
* to make it unreachable. Percentages and viewport units are compared against a
|
||||
* full viewport/containing block.
|
||||
* clearly off-screen: -1000 px / -100 % or +2000 px / +200 %. Ordinary layout
|
||||
* moves are legitimate, so only viewport-ejecting values are rejected.
|
||||
*/
|
||||
const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform|scale|rotate)(?:-|$)/;
|
||||
const ABSOLUTE_OFFSET_LIMIT_PX = 100;
|
||||
const RELATIVE_OFFSET_LIMIT = 100;
|
||||
const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform)(?:-|$)/;
|
||||
const OFFSET_LIMITS = { negativePx: 1000, positivePx: 2000, negativePercent: 100, positivePercent: 200 };
|
||||
|
||||
function absoluteLengthToPixels(magnitude: number, unit: string): number | null {
|
||||
switch (unit) {
|
||||
case "px": return magnitude;
|
||||
case "rem": case "em": return magnitude * 16;
|
||||
case "ex": case "rex": case "ch": return magnitude * 8;
|
||||
case "cm": return magnitude * 37.8;
|
||||
case "mm": return magnitude * 3.78;
|
||||
case "q": return magnitude * 0.945;
|
||||
case "in": return magnitude * 96;
|
||||
case "pt": return magnitude * 1.333;
|
||||
case "pc": return magnitude * 16;
|
||||
default: return null;
|
||||
type Dimension = { value: number; unit: string };
|
||||
|
||||
const ABSOLUTE_UNIT_PIXELS: Record<string, number> = { px: 1, rem: 16, em: 16, ex: 8, rex: 8, ch: 8, cm: 37.8, mm: 3.78, q: 0.945, in: 96, pt: 1.333, pc: 16 };
|
||||
function absoluteLengthToPixels(value: number, unit: string): number | null {
|
||||
const factor = ABSOLUTE_UNIT_PIXELS[unit];
|
||||
return factor ? value * factor : null;
|
||||
}
|
||||
|
||||
type OffsetMeasurement = { kind: "pixels" | "percent"; value: number };
|
||||
|
||||
const VIEWPORT_UNIT_PATTERN = /^(?:s|l|d)?v(?:w|h|i|min|max)$|^cq(?:w|h|min|max|i|b)$/;
|
||||
|
||||
/** CSS `<number>` including a scientific-notation exponent. */
|
||||
const CSS_NUMBER_PATTERN = "[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?";
|
||||
|
||||
/** One CSS number, percentage or length, including a flat `calc()`. */
|
||||
function parseDimension(text: string): Dimension | null {
|
||||
const compact = text.trim().toLowerCase();
|
||||
const calc = /^calc\(([\s\S]*)\)$/.exec(compact);
|
||||
if (calc) return evaluateCalc(calc[1]);
|
||||
const match = new RegExp(`^(${CSS_NUMBER_PATTERN})([a-z%]*)$`).exec(compact);
|
||||
return match ? { value: Number(match[1]), unit: match[2] } : null;
|
||||
}
|
||||
|
||||
/** Flat `calc()`: sums of products over numbers and one unit; nested or mixed
|
||||
* input is unknown (`null` → allowed). A sign after `*`/`/` is a factor,
|
||||
* so `calc(2px*-1000)` is -2000px, not 2px + -1000. */
|
||||
function evaluateCalc(text: string): Dimension | null {
|
||||
const compact = text.replace(/\s+/g, "");
|
||||
const tokens = compact.match(new RegExp(`[*/]|${CSS_NUMBER_PATTERN}(?:[a-z%]+)?`, "g"));
|
||||
if (!tokens || tokens.join("") !== compact) return null;
|
||||
const total: Dimension = { value: 0, unit: "" };
|
||||
let term: Dimension | null = null;
|
||||
let pending: "*" | "/" | null = null;
|
||||
const addTerm = (): boolean => {
|
||||
if (!term || (total.unit && term.unit && total.unit !== term.unit)) return false;
|
||||
total.value += term.value;
|
||||
total.unit ||= term.unit;
|
||||
return true;
|
||||
};
|
||||
for (const token of tokens) {
|
||||
if (token === "*" || token === "/") { pending = token; continue; }
|
||||
const factor = parseDimension(token);
|
||||
if (!factor) return null;
|
||||
if (pending && term) {
|
||||
if (factor.unit && (term.unit || pending === "/")) return null;
|
||||
term = { value: pending === "/" ? term.value / factor.value : term.value * factor.value, unit: term.unit || factor.unit };
|
||||
pending = null;
|
||||
continue;
|
||||
}
|
||||
if (term && !addTerm()) return null;
|
||||
term = factor;
|
||||
pending = null;
|
||||
}
|
||||
return !pending && addTerm() ? total : null;
|
||||
}
|
||||
|
||||
/** Normalise one length for comparison; a bare number is not a length. */
|
||||
function lengthMeasurement(value: string): OffsetMeasurement | null {
|
||||
const dimension = parseDimension(value);
|
||||
if (!dimension?.unit) return null;
|
||||
if (dimension.unit === "%" || VIEWPORT_UNIT_PATTERN.test(dimension.unit)) return { kind: "percent", value: dimension.value };
|
||||
const pixels = absoluteLengthToPixels(dimension.value, dimension.unit);
|
||||
return pixels === null ? null : { kind: "pixels", value: pixels };
|
||||
}
|
||||
|
||||
function exceedsOffset(measurement: OffsetMeasurement | null): boolean {
|
||||
if (!measurement) return false;
|
||||
const [negative, positive] = measurement.kind === "percent"
|
||||
? [OFFSET_LIMITS.negativePercent, OFFSET_LIMITS.positivePercent]
|
||||
: [OFFSET_LIMITS.negativePx, OFFSET_LIMITS.positivePx];
|
||||
return measurement.value <= -negative || measurement.value >= positive;
|
||||
}
|
||||
|
||||
function valueMovesOffscreen(property: string, value: string): boolean {
|
||||
if (!OFFSET_PROPERTY_PATTERN.test(property)) return false;
|
||||
let offscreen = false;
|
||||
valueParser(value).walk((node) => {
|
||||
if (node.type !== "word") return;
|
||||
const match = /^(-?(?:\d+|\d*\.\d+))(px|rem|em|r?ex|ch|%|cm|mm|q|in|pt|pc|(?:s|l|d)?v(?:w|h|min|max)|cq(?:w|h|min|max|i|b))$/i.exec(node.value);
|
||||
if (!match) return;
|
||||
const magnitude = Math.abs(Number(match[1]));
|
||||
const unit = match[2].toLowerCase();
|
||||
if (unit === "%" || /^(?:s|l|d)?v(?:w|h|min|max)$/.test(unit) || /^cq(?:w|h|min|max|i|b)$/.test(unit)) {
|
||||
if (magnitude >= RELATIVE_OFFSET_LIMIT) offscreen = true;
|
||||
return;
|
||||
const name = node.type === "function" ? node.value.toLowerCase() : "";
|
||||
if (node.type === "word") offscreen ||= exceedsOffset(lengthMeasurement(node.value));
|
||||
else if (name === "calc") {
|
||||
offscreen ||= exceedsOffset(lengthMeasurement(valueParser.stringify(node)));
|
||||
return false;
|
||||
} else if (node.type === "function" && (name === "matrix" || name === "matrix3d")) {
|
||||
// A matrix can smuggle a large translation in unitless numbers.
|
||||
const items = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim()));
|
||||
offscreen ||= (name === "matrix" ? [items[4], items[5]] : [items[12], items[13]])
|
||||
.some((item) => item <= -OFFSET_LIMITS.negativePx || item >= OFFSET_LIMITS.positivePx);
|
||||
return false;
|
||||
}
|
||||
const pixels = absoluteLengthToPixels(magnitude, unit);
|
||||
if (pixels !== null && pixels >= ABSOLUTE_OFFSET_LIMIT_PX) offscreen = true;
|
||||
return undefined;
|
||||
});
|
||||
// A matrix transform can smuggle a large translation in unitless numbers.
|
||||
if (property === "transform") {
|
||||
valueParser(value).walk((node) => {
|
||||
if (node.type !== "function") return;
|
||||
const name = node.value.toLowerCase();
|
||||
if (name !== "matrix" && name !== "matrix3d") return;
|
||||
const numbers = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim()));
|
||||
const translations = name === "matrix" ? [numbers[4], numbers[5]] : [numbers[12], numbers[13]];
|
||||
if (translations.some((translation) => Number.isFinite(translation) && Math.abs(translation) >= ABSOLUTE_OFFSET_LIMIT_PX)) offscreen = true;
|
||||
});
|
||||
}
|
||||
return offscreen;
|
||||
}
|
||||
|
||||
/** This declaration removes the element from view; partial effects stay allowed. */
|
||||
function hidesVisually(property: string, value: string): boolean {
|
||||
if (property === "all") return true;
|
||||
const text = decodeCssEscapes(value).trim().toLowerCase();
|
||||
if ((property === "display" && text === "none") || (property === "visibility" && /^(?:hidden|collapse)$/.test(text))
|
||||
|| (property === "pointer-events" && text === "none") || (property === "content-visibility" && text === "hidden")) return true;
|
||||
if (property === "opacity") return (numericValue(text) ?? 1) <= 0.01;
|
||||
if (property === "filter") return filterHides(text);
|
||||
if (property === "transform") return transformHides(text);
|
||||
if (property === "scale") return scalePropertyHides(text);
|
||||
if (property === "clip-path") return clipPathHides(text);
|
||||
if (property === "clip") return clipHides(text);
|
||||
return property === "mask" || property === "mask-image" ? maskHides(text) : false;
|
||||
}
|
||||
|
||||
/** Visit every function node; `test` gets the lower-cased name and its arguments. */
|
||||
function anyFunction(value: string, test: (name: string, args: string) => boolean): boolean {
|
||||
let hit = false;
|
||||
valueParser(value).walk((node) => {
|
||||
if (node.type === "function" && test(node.value.toLowerCase(), valueParser.stringify(node.nodes))) hit = true;
|
||||
});
|
||||
return hit;
|
||||
}
|
||||
|
||||
/** A number, a percentage as 0–1, or a flat `calc()` of numbers. */
|
||||
function numericValue(value: string): number | null {
|
||||
const dimension = parseDimension(value);
|
||||
if (!dimension) return null;
|
||||
return dimension.unit === "%" ? dimension.value / 100 : dimension.unit === "" ? dimension.value : null;
|
||||
}
|
||||
|
||||
function filterHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) => {
|
||||
const amount = numericValue(args);
|
||||
return amount !== null && (name === "opacity" ? amount <= 0.01 : name === "brightness" && amount <= 0);
|
||||
});
|
||||
}
|
||||
|
||||
function numbers(text: string): number[] {
|
||||
return text.split(/[\s,]+/).map(numericValue).filter((item): item is number => item !== null);
|
||||
}
|
||||
|
||||
function isZeroFactor(value: number): boolean {
|
||||
return Math.abs(value) <= 0.001;
|
||||
}
|
||||
|
||||
function transformHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) => {
|
||||
const factors = numbers(args);
|
||||
if (name === "scale" || name === "scale3d") return factors.slice(0, 2).some(isZeroFactor);
|
||||
return (name === "scalex" || name === "scaley") && isZeroFactor(factors[0] ?? 1);
|
||||
});
|
||||
}
|
||||
|
||||
function scalePropertyHides(value: string): boolean {
|
||||
const factors = numbers(value);
|
||||
return factors.length > 0 && (isZeroFactor(factors[0]) || (factors.length > 1 && isZeroFactor(factors[1])));
|
||||
}
|
||||
|
||||
function zeroLength(value: string | undefined): boolean {
|
||||
const dimension = value ? parseDimension(value) : null;
|
||||
return dimension !== null && isZeroFactor(dimension.value);
|
||||
}
|
||||
|
||||
function insetHides(args: string): boolean {
|
||||
const sides = args.split(/\bround\b/i)[0].trim().split(/\s+/).map(parseDimension);
|
||||
if (sides.some((side) => !side || (side.unit !== "" && side.unit !== "%"))) return false;
|
||||
const values = sides.map((side) => side!.value);
|
||||
const [top, right = top, bottom = top, left = right] = values;
|
||||
return top + bottom >= 100 || left + right >= 100;
|
||||
}
|
||||
|
||||
function clipPathHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) => {
|
||||
const shape = args.split(/\bat\b/i)[0].trim();
|
||||
if (name === "inset") return insetHides(args);
|
||||
if (name === "circle") return zeroLength(shape.split(/\s+/)[0]);
|
||||
return name === "ellipse" && shape.split(/\s+/).filter(Boolean).slice(0, 2).some(zeroLength);
|
||||
});
|
||||
}
|
||||
|
||||
function clipHides(value: string): boolean {
|
||||
const match = /^rect\(([\s\S]*)\)$/i.exec(value.trim());
|
||||
if (!match) return false;
|
||||
const sides = match[1].split(/[\s,]+/).filter(Boolean);
|
||||
return sides.length === 4 && sides.every(zeroLength);
|
||||
}
|
||||
|
||||
const GRADIENT_PRELUDE_KEYWORDS = new Set([
|
||||
"from", "to", "left", "right", "top", "bottom", "center", "at", "circle", "ellipse",
|
||||
"closest-side", "closest-corner", "farthest-side", "farthest-corner", "in",
|
||||
]);
|
||||
|
||||
/** `#rgb0` / `#rrggbb00`, `transparent`, or a colour function with alpha ≤ 0.01. */
|
||||
function colorIsTransparent(text: string): boolean {
|
||||
const value = text.trim().toLowerCase();
|
||||
if (value === "transparent" || /^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(value)) return true;
|
||||
return anyFunction(value, (name, args) => {
|
||||
if (!/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)$/.test(name)) return false;
|
||||
const slash = args.split("/");
|
||||
if (slash.length > 1) return (numericValue(slash[slash.length - 1].trim()) ?? 1) <= 0.01;
|
||||
const channels = numbers(args);
|
||||
return (name === "rgba" || name === "hsla") && channels.length >= 4 && channels[3] <= 0.01;
|
||||
});
|
||||
}
|
||||
|
||||
/** A gradient is a full mask only when every colour stop is fully transparent. */
|
||||
function gradientIsAllTransparent(args: string): boolean {
|
||||
let transparent = false;
|
||||
for (const segment of args.split(/,(?![^(]*\))/)) {
|
||||
const text = segment.trim().toLowerCase();
|
||||
if (!text) continue;
|
||||
const first = valueParser(text).nodes.find((node) => node.type !== "space" && node.type !== "comment");
|
||||
if (!first) continue;
|
||||
if (first.type === "function" ? colorIsTransparent(valueParser.stringify([first])) : colorIsTransparent(first.value)) {
|
||||
transparent = true;
|
||||
continue;
|
||||
}
|
||||
if (first.type === "word" && (GRADIENT_PRELUDE_KEYWORDS.has(first.value.toLowerCase()) || parseDimension(first.value)?.unit)) continue;
|
||||
return false;
|
||||
}
|
||||
return transparent;
|
||||
}
|
||||
|
||||
function maskHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) =>
|
||||
name === "alpha" || name === "luminance"
|
||||
? (numericValue(args) ?? 1) <= 0
|
||||
: name.endsWith("gradient") && gradientIsAllTransparent(args));
|
||||
}
|
||||
|
||||
/**
|
||||
* Name token per layer. In the shorthand a keyword fills the first slot of its
|
||||
* category; a repeated category (or any other word) is the name, so
|
||||
* `bob 2s alternate` references `bob`. Times, numbers and functions are skipped.
|
||||
*/
|
||||
function parseAnimationLayers(value: string, property: string): { parsed: ReturnType<typeof valueParser>; names: Array<ValueNode | null> } {
|
||||
const parsed = valueParser(value);
|
||||
const groups: ValueNode[][] = [[]];
|
||||
for (const node of parsed.nodes) {
|
||||
if (node.type === "div" && node.value === ",") groups.push([]);
|
||||
else if (node.type !== "space" && node.type !== "comment") groups[groups.length - 1].push(node);
|
||||
}
|
||||
const names = groups.map((nodes) => {
|
||||
const words = nodes.filter((node) => node.type === "word" || node.type === "string");
|
||||
if (property === "animation-name") {
|
||||
const name = words[0] ? decodeCssEscapes(words[0].value).toLowerCase() : "";
|
||||
return words[0] && name !== "none" && !CSS_WIDE_KEYWORDS.has(name) ? words[0] : null;
|
||||
}
|
||||
const used = new Set<string>();
|
||||
for (const node of words) {
|
||||
const token = decodeCssEscapes(node.value).toLowerCase();
|
||||
const dimension = parseDimension(token);
|
||||
if (dimension && ["", "s", "ms"].includes(dimension.unit)) continue;
|
||||
const category = ANIMATION_KEYWORD_CATEGORIES.get(token);
|
||||
if (category && used.has(category)) return node;
|
||||
if (category) used.add(category);
|
||||
else if (node.type === "word" && CSS_WIDE_KEYWORDS.has(token)) continue;
|
||||
else return node;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return { parsed, names };
|
||||
}
|
||||
|
||||
/** Any restart/alternate/fill keyword or indirect value can hold the start frame.
|
||||
* Multi-layer rules are judged as a whole, which errs towards checking `from`. */
|
||||
function ruleCanRestAtStart(rule: Rule): boolean {
|
||||
let resting = false;
|
||||
rule.walkDecls((declaration: Declaration) => {
|
||||
const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase());
|
||||
if (!["animation", "animation-direction", "animation-fill-mode", "animation-play-state"].includes(property)) return;
|
||||
const value = decodeCssEscapes(declaration.value).toLowerCase();
|
||||
resting ||= /\b(?:var|attr)\s*\(/.test(value)
|
||||
|| valueParser(value).nodes.some((node) => node.type === "word" && RESTING_START_KEYWORDS.has(node.value));
|
||||
});
|
||||
return resting;
|
||||
}
|
||||
|
||||
/** `to`/`100%` always rest; `from`/`0%` rest for reverse/alternate, a
|
||||
* backwards/both fill, or a paused start. A long animation or a pause mid-way
|
||||
* (negative delay) can linger on an unchecked intermediate frame — accepted,
|
||||
* because recovery lives in a closed-shadow top-layer capsule. */
|
||||
function keyframeStepCanRest(selector: string, restsAtStart: boolean): boolean {
|
||||
return selector.split(",").some((step) => {
|
||||
const value = decodeCssEscapes(step).trim().toLowerCase();
|
||||
if (value === "to") return true;
|
||||
if (value === "from") return restsAtStart;
|
||||
const position = parseDimension(value);
|
||||
return position?.unit === "%" && (position.value >= 100 || (restsAtStart && position.value <= 0));
|
||||
});
|
||||
}
|
||||
|
||||
const OVERLAY_SIZE_PROPERTIES = new Set([
|
||||
"width", "height", "min-width", "min-height", "max-width", "max-height",
|
||||
"inline-size", "block-size", "min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio",
|
||||
]);
|
||||
|
||||
function isViewportSizedDimension(dimension: Dimension | null): boolean {
|
||||
return Boolean(dimension && VIEWPORT_UNIT_PATTERN.test(dimension.unit) && Math.abs(dimension.value) >= 100);
|
||||
}
|
||||
|
||||
function valueIsViewportSized(value: string): boolean {
|
||||
let sized = false;
|
||||
valueParser(value).walk((node) => {
|
||||
if (node.type === "word") sized ||= isViewportSizedDimension(parseDimension(node.value));
|
||||
else if (node.type === "function" && node.value.toLowerCase() === "calc") {
|
||||
sized ||= isViewportSizedDimension(parseDimension(valueParser.stringify(node)));
|
||||
return false;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
return sized;
|
||||
}
|
||||
|
||||
function isIdentityNumber(value: number): boolean {
|
||||
return Math.abs(value - 1) <= 0.001;
|
||||
}
|
||||
|
||||
function isZeroAngleOrLength(value: string): boolean {
|
||||
return zeroLength(value);
|
||||
}
|
||||
|
||||
/** Identity transforms (`none`, `scale(1)`, `translate(0)`, `rotate(0deg)`). */
|
||||
function transformIsIdentity(value: string): boolean {
|
||||
const compact = value.trim().toLowerCase();
|
||||
if (compact === "none") return true;
|
||||
let seen = false;
|
||||
let identity = true;
|
||||
valueParser(compact).walk((node) => {
|
||||
if (node.type !== "function") return;
|
||||
seen = true;
|
||||
const name = node.value.toLowerCase();
|
||||
const args = valueParser.stringify(node.nodes);
|
||||
const factors = numbers(args);
|
||||
if (name === "scale" || name === "scale3d") identity &&= factors.length > 0 && factors.every(isIdentityNumber);
|
||||
else if (name === "scalex" || name === "scaley" || name === "scalez") identity &&= factors.length > 0 && isIdentityNumber(factors[0]);
|
||||
else if (/^translate(?:3d|[xyz])?$/.test(name)) identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength);
|
||||
else if (/^rotate(?:3d|[xyz])?$/.test(name) || name === "skew" || name === "skewx" || name === "skewy") {
|
||||
identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength);
|
||||
} else identity = false;
|
||||
});
|
||||
return seen && identity;
|
||||
}
|
||||
|
||||
function isNeutralLockValue(property: string, value: string): boolean {
|
||||
const compact = value.trim().toLowerCase();
|
||||
if (["none", "auto", "static"].includes(compact) || CSS_WIDE_KEYWORDS.has(compact)) return true;
|
||||
if (property === "scale" || property === "zoom") {
|
||||
const factors = numbers(compact);
|
||||
return factors.length > 0 && factors.every(isIdentityNumber);
|
||||
}
|
||||
if (property === "rotate") return isZeroAngleOrLength(compact);
|
||||
if (property === "transform") return transformIsIdentity(compact);
|
||||
if (property === "translate" || property.startsWith("inset") || /^(?:top|right|bottom|left)$/.test(property)) {
|
||||
return compact.split(/\s+/).every((token) => token === "auto" || isZeroAngleOrLength(token));
|
||||
}
|
||||
return compact === "0" || isZeroAngleOrLength(compact);
|
||||
}
|
||||
|
||||
/** Resting host-chrome keyframes reuse the direct lock per property: locked
|
||||
* properties only accept identity/neutral values; sizes only reject viewport sizes. */
|
||||
function keyframeEscapesHostLock(property: string, value: string): boolean {
|
||||
const compact = decodeCssEscapes(value).trim().toLowerCase();
|
||||
if (isNeutralLockValue(property, compact)) return false;
|
||||
if (OVERLAY_SIZE_PROPERTIES.has(property)) return valueIsViewportSized(value);
|
||||
return HOST_CHROME_LOCKED_PROPERTIES.has(property);
|
||||
}
|
||||
|
||||
function findOwningRule(node: Node): Rule | null {
|
||||
let parent = node.parent;
|
||||
while (parent && parent.type !== "root") {
|
||||
@@ -543,11 +1012,6 @@ function findKeyframesRule(rule: Rule): AtRule | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function referencesCssIdentifier(value: string, identifier: string): boolean {
|
||||
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
|
||||
}
|
||||
|
||||
export function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
|
||||
const parsed = valueParser(value);
|
||||
const resolvePackageAsset = (rawValue: string): string => {
|
||||
@@ -605,16 +1069,24 @@ function parseSingleFontFamily(value: string): string {
|
||||
}
|
||||
|
||||
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
|
||||
const parsed = valueParser(value);
|
||||
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
|
||||
parsed.walk((node) => {
|
||||
if (node.type !== "word" && node.type !== "string") return;
|
||||
const keyframe = keyframes.get(node.value);
|
||||
if (keyframe) node.value = keyframe;
|
||||
const family = fontFamilies.get(node.value.toLowerCase());
|
||||
if (family) node.value = family;
|
||||
});
|
||||
if (!["animation", "animation-name", "font", "font-family"].includes(property)) return value;
|
||||
// Rewrite against the decoded value: `p\75 lse` must become the scoped name
|
||||
// of `@keyframes pulse`, exactly like the matching walk above.
|
||||
const decoded = decodeCssEscapes(value);
|
||||
if (property === "animation" || property === "animation-name") {
|
||||
const { parsed, names } = parseAnimationLayers(decoded, property);
|
||||
for (const node of names) {
|
||||
const scoped = node ? keyframes.get(node.value) : undefined;
|
||||
if (node && scoped) node.value = scoped;
|
||||
}
|
||||
return parsed.toString();
|
||||
}
|
||||
const parsed = valueParser(decoded);
|
||||
parsed.walk((node) => {
|
||||
if (node.type !== "word" && node.type !== "string") return;
|
||||
const family = fontFamilies.get(node.value.toLowerCase());
|
||||
if (family) node.value = family;
|
||||
});
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,17 @@ export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
|
||||
"host.permission",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Trusted host controls that an open skin may fold into its own layout through
|
||||
* `chrome.json#slots`. The key names the protected part, not a CSS hook: the
|
||||
* skin only declares an anchor rectangle, the host still owns, paints and
|
||||
* hit-tests the control. Extend this set (for example with `host.permission`)
|
||||
* when another protected control learns the same runtime placement.
|
||||
*/
|
||||
export const HOST_SLOTTABLE_PART_IDS: ReadonlySet<string> = new Set([
|
||||
"host.recovery",
|
||||
]);
|
||||
|
||||
/** All host-owned parts (used by the part registry and documentation). */
|
||||
export const HOST_PART_IDS: ReadonlySet<string> = new Set([
|
||||
...HOST_CHROME_PART_IDS,
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -33,7 +33,13 @@
|
||||
<div
|
||||
ref="recoveryPopover"
|
||||
popover="manual"
|
||||
@keydown.escape="onRecoveryEscape"
|
||||
@click="compactPinned = compact || compactPinned"
|
||||
@focusout="onRecoveryFocusOut"
|
||||
class="ws-host-recovery"
|
||||
:class="{ 'ws-host-recovery-compact': compact }"
|
||||
:data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
|
||||
:tabindex="compact || compactPinned ? 0 : undefined"
|
||||
data-ws-host-recovery
|
||||
role="region"
|
||||
:aria-label="copy.recovery"
|
||||
@@ -41,12 +47,14 @@
|
||||
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
data-ws-recovery-action="built-in"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>{{ copy.useBuiltIn }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
v-if="pluginLibraryAvailable"
|
||||
data-ws-recovery-action="library"
|
||||
:title="copy.library"
|
||||
@@ -61,6 +69,8 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
import { hostChromeCopy } from "../i18n/host-chrome.js";
|
||||
import {
|
||||
activeHostSlot,
|
||||
hostChromeActiveSkinId,
|
||||
isHostPartHidden,
|
||||
isHostPartVisuallyReachable,
|
||||
isRecoveryShortcut,
|
||||
@@ -73,8 +83,19 @@ import {
|
||||
syncRecoveryPopover,
|
||||
type HostOwnedLayer,
|
||||
} from "../services/host-owned-layer.js";
|
||||
import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js";
|
||||
import {
|
||||
bindFloatingAvoidance,
|
||||
type FloatingAvoidance,
|
||||
type FloatingPosition,
|
||||
} from "../services/host-floating-placement.js";
|
||||
import { shouldShowRecovery } 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";
|
||||
|
||||
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: boolean }>(), { connected: false });
|
||||
const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
|
||||
@@ -92,36 +113,60 @@ const RECOVERY_LAYER_CSS = `
|
||||
gap: 4px;
|
||||
max-width: calc(100vw - 24px);
|
||||
padding: 4px 5px 4px 9px;
|
||||
border: 1px solid #9db6b2;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, #ffffff 92%, transparent);
|
||||
color: #31524f;
|
||||
border: 1px solid var(--ws-control-border, #9db6b2);
|
||||
border-radius: var(--ws-control-radius, 999px);
|
||||
background: var(--ws-control-background, color-mix(in srgb, #ffffff 92%, transparent));
|
||||
color: var(--ws-control-foreground, #31524f);
|
||||
font-family: var(--ws-control-font, ui-sans-serif, system-ui, sans-serif);
|
||||
font-size: var(--ws-control-font-size, 11px);
|
||||
box-shadow: 0 6px 18px #0f2a2626;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.ws-host-recovery:popover-open { display: flex; }
|
||||
.ws-host-recovery-mark { font-size: 12px; line-height: 1; }
|
||||
/* Runtime collision avoidance (host-floating-placement.ts): when the default
|
||||
corner would cover a skin control, the floating capsule moves. A docked
|
||||
(slotted) capsule carries no data-ws-float and uses inline placement. */
|
||||
.ws-host-recovery[data-ws-float$="right"] { left: auto; right: max(12px, env(safe-area-inset-right)); }
|
||||
.ws-host-recovery[data-ws-float^="top"] { bottom: auto; top: max(12px, env(safe-area-inset-top)); }
|
||||
.ws-host-recovery[data-ws-float^="middle"] { bottom: auto; top: 50%; translate: 0 -50%; }
|
||||
.ws-host-recovery[data-ws-float$="center"] { left: 50%; translate: -50% 0; }
|
||||
.ws-host-recovery-mark {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
.ws-host-recovery button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
min-height: var(--ws-control-hit, 28px);
|
||||
padding: 4px 9px;
|
||||
border: 1px solid #9db6b2;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #31524f;
|
||||
border: 1px solid var(--ws-control-border, #9db6b2);
|
||||
border-radius: var(--ws-control-radius, 999px);
|
||||
background: var(--ws-control-background, #fff);
|
||||
color: var(--ws-control-foreground, #31524f);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
|
||||
border-color: #b45309;
|
||||
border-color: var(--ws-control-builtin-border, #b45309);
|
||||
background: #fff7ed;
|
||||
color: #7c2d12;
|
||||
}
|
||||
.ws-host-recovery button:hover { filter: brightness(.96); }
|
||||
.ws-host-recovery button:focus-visible { outline: 2px solid #4c8f88; outline-offset: 2px; }
|
||||
@media (prefers-reduced-motion: reduce) { .ws-host-recovery button { transition: none; } }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) { gap: 0; padding: 4px; }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-action { display: none; }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-mark {
|
||||
min-width: var(--ws-control-hit, 28px);
|
||||
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; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ws-host-recovery, .ws-host-recovery button { transition: none !important; }
|
||||
}
|
||||
`;
|
||||
|
||||
const layer: HostOwnedLayer | null = createHostOwnedLayer("recovery", RECOVERY_LAYER_CSS);
|
||||
@@ -145,8 +190,157 @@ const showRecovery = computed(() => shouldShowRecovery({
|
||||
// already reset). It never renders decoration on its own.
|
||||
const shortcutOpen = ref(false);
|
||||
const recoveryPopover = ref<HTMLElement | null>(null);
|
||||
|
||||
let slotBinding: HostSlotBinding | undefined;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
const recoveryTheme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
control: () => recoveryPopover.value,
|
||||
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,
|
||||
}) : null;
|
||||
|
||||
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
|
||||
|
||||
/**
|
||||
* Optional anchor from the active skin's chrome.json. Only third-party skins
|
||||
* can declare it; the host still owns the capsule and the module falls back to
|
||||
* the default corner whenever the anchor stops being usable.
|
||||
*/
|
||||
const slotConfig = computed(() => activeHostSlot("host.recovery"));
|
||||
const slotMode = ref<"floating" | "slotted">("floating");
|
||||
const compactHold = ref(true);
|
||||
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
// Keep the full capsule visible for a moment after it first docks into a
|
||||
// newly activated skin, so the entry stays discoverable before it folds into
|
||||
// the skin's layout. The skin id is known from localStorage before the skin
|
||||
// (and its anchor) has loaded, so the 5 s window starts on the first
|
||||
// floating -> slotted transition for that skin, not on the id change.
|
||||
let compactHoldStarted = false;
|
||||
watch(hostChromeActiveSkinId, () => {
|
||||
compactHold.value = true;
|
||||
compactHoldStarted = false;
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
compactHoldTimer = undefined;
|
||||
}, { immediate: true });
|
||||
watch(slotMode, (mode) => {
|
||||
if (mode !== "slotted" || compactHoldStarted) return;
|
||||
compactHoldStarted = true;
|
||||
compactHoldTimer = setTimeout(() => { compactHold.value = false; }, 5000);
|
||||
});
|
||||
|
||||
/** Set by the shortcut; cleared once focus leaves the capsule. */
|
||||
const shortcutExpanded = ref(false);
|
||||
/** A tap/click on the compact mark keeps it expanded (no hover on touch). */
|
||||
const compactPinned = ref(false);
|
||||
|
||||
/**
|
||||
* Floating (not docked) capsule: corner chosen at runtime so it does not cover
|
||||
* skin controls, and folded to its mark when every corner collides.
|
||||
*/
|
||||
const floatPosition = ref<FloatingPosition>("bottom-left");
|
||||
const floatCompact = ref(false);
|
||||
let floatingAvoidance: FloatingAvoidance | undefined;
|
||||
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));
|
||||
|
||||
function onRecoveryEscape() {
|
||||
shortcutOpen.value = false;
|
||||
shortcutExpanded.value = false;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
/** Unpin when the pointer goes down anywhere outside the host layer. */
|
||||
function onDocumentPointerDown(event: PointerEvent) {
|
||||
if (!compactPinned.value || !layer) return;
|
||||
// Events from inside the closed shadow root are retargeted to its host.
|
||||
if (event.composedPath().includes(layer.host)) return;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
function onRecoveryFocusOut(event: FocusEvent) {
|
||||
const next = event.relatedTarget;
|
||||
if (next instanceof Node && recoveryPopover.value?.contains(next)) return;
|
||||
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({
|
||||
layer,
|
||||
control,
|
||||
anchor: config.anchor,
|
||||
skinId: hostChromeActiveSkinId.value,
|
||||
align: config.align,
|
||||
onModeChange: change => { slotMode.value = change.mode; },
|
||||
});
|
||||
}
|
||||
|
||||
function bindFloating() {
|
||||
const control = recoveryPopover.value;
|
||||
// Idempotent: called on mount and whenever the popover element appears.
|
||||
if (floatingAvoidance && floatingElement === control) return;
|
||||
floatingAvoidance?.dispose();
|
||||
floatingAvoidance = undefined;
|
||||
floatingElement = null;
|
||||
if (!control || !layer) return;
|
||||
const host = layer.host;
|
||||
floatingElement = control;
|
||||
floatingAvoidance = bindFloatingAvoidance({
|
||||
element: control,
|
||||
isSelf: node => node === host || host.contains(node),
|
||||
// Same numbers as RECOVERY_LAYER_CSS, including env(safe-area-inset-*).
|
||||
margins: insets => ({
|
||||
top: Math.max(12, insets.top),
|
||||
right: Math.max(12, insets.right),
|
||||
bottom: 38 + insets.bottom,
|
||||
left: Math.max(12, insets.left),
|
||||
}),
|
||||
insetsParent: layer.shadow,
|
||||
defaultPosition: "bottom-left",
|
||||
apply: next => { floatPosition.value = next; },
|
||||
compactSize: () => {
|
||||
const hit = Number.parseFloat(getComputedStyle(control).getPropertyValue("--ws-control-hit")) || 28;
|
||||
return { width: hit + 10, height: hit + 10 };
|
||||
},
|
||||
onCompactChange: next => { floatCompact.value = next; },
|
||||
// Never move the capsule under the user's pointer or focus, and leave a
|
||||
// docked capsule to the slot binding.
|
||||
paused: () => slotMode.value === "slotted"
|
||||
|| shortcutExpanded.value
|
||||
|| compactPinned.value
|
||||
|| (canHover() && control.matches(":hover"))
|
||||
|| Boolean(layer.shadow.activeElement),
|
||||
});
|
||||
}
|
||||
|
||||
function syncPopover() {
|
||||
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
|
||||
}
|
||||
@@ -162,14 +356,19 @@ function openLibrary() {
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.defaultPrevented || event.repeat || !thirdPartyAllowed.value) return;
|
||||
if (event.repeat || !thirdPartyAllowed.value) return;
|
||||
// The recovery chord must survive a capture-phase preventDefault() from a
|
||||
// skin or plugin, so it is handled before anything else.
|
||||
if (isRecoveryShortcut(event)) {
|
||||
event.preventDefault();
|
||||
shortcutOpen.value = true;
|
||||
void nextTick(() => recoveryPopover.value?.querySelector("button")?.focus());
|
||||
return;
|
||||
shortcutExpanded.value = true;
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
recoveryPopover.value?.querySelector("button")?.focus();
|
||||
});
|
||||
}
|
||||
if (event.key === "Escape" && shortcutOpen.value) shortcutOpen.value = false;
|
||||
}
|
||||
|
||||
let reachabilityTimer: ReturnType<typeof setInterval> | undefined;
|
||||
@@ -177,20 +376,54 @@ function refreshLauncherReachability() {
|
||||
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
|
||||
}
|
||||
|
||||
watch([recoveryVisible, recoveryPopover], () => { void nextTick(syncPopover); }, { flush: "post" });
|
||||
watch([recoveryVisible, recoveryPopover], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
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" });
|
||||
// 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());
|
||||
}, { flush: "post" });
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
|
||||
|
||||
onMounted(() => {
|
||||
refreshLauncherReachability();
|
||||
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
|
||||
window.addEventListener("resize", refreshLauncherReachability);
|
||||
window.addEventListener("keydown", onKeydown);
|
||||
void nextTick(syncPopover);
|
||||
window.addEventListener("keydown", onKeydown, true);
|
||||
window.addEventListener("pointerdown", onDocumentPointerDown, true);
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
bindFloating();
|
||||
});
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
if (reachabilityTimer) clearInterval(reachabilityTimer);
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
slotBinding?.dispose();
|
||||
floatingAvoidance?.dispose();
|
||||
floatingAvoidance = undefined;
|
||||
floatingElement = null;
|
||||
recoveryTheme?.dispose();
|
||||
window.removeEventListener("resize", refreshLauncherReachability);
|
||||
window.removeEventListener("keydown", onKeydown);
|
||||
window.removeEventListener("keydown", onKeydown, true);
|
||||
window.removeEventListener("pointerdown", onDocumentPointerDown, true);
|
||||
layer?.dispose();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -25,13 +25,19 @@ import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
|
||||
import { createHostOwnedLayer, type HostOwnedLayer } from '../services/host-owned-layer.js';
|
||||
import { hostChromeActiveSkinId } from '../services/host-chrome.js';
|
||||
import {
|
||||
PERMISSION_CONTROL_DEFAULTS,
|
||||
bindHostControlTheme,
|
||||
findSkinRoot,
|
||||
} from '../services/host-control-tokens.js';
|
||||
|
||||
const AUTHORIZATION_LAYER_CSS = `
|
||||
:host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
||||
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:inherit;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
|
||||
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid var(--ws-control-border,#dbe3f1);border-radius:var(--ws-control-radius,20px);background:var(--ws-control-background,#fff);color:var(--ws-control-foreground,#25324b);font-family:var(--ws-control-font,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--ws-control-font-size,14px);line-height:1.75;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
|
||||
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:var(--ws-control-foreground,#526079)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));border:1px solid var(--ws-control-border,#dce3f3);border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:var(--ws-control-hit,42px);padding:9px 16px;border:1px solid var(--ws-control-border,#d9e1ef);border-radius:var(--ws-control-radius,10px);background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));color:var(--ws-control-foreground,#43516d);font:600 var(--ws-control-font-size,14px)/1.5 var(--ws-control-font,system-ui);cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:var(--ws-control-accent,#5265df);color:var(--ws-control-on-accent,#fff);border-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid var(--ws-control-accent,#5265df);outline-offset:3px}
|
||||
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
|
||||
`;
|
||||
|
||||
@@ -39,9 +45,21 @@ const layer: HostOwnedLayer | null = createHostOwnedLayer('authorization', AUTHO
|
||||
const props = defineProps<{ language: SiteLanguage }>();
|
||||
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
|
||||
const copy = computed(() => instanceAuthorizationCopy[props.language]);
|
||||
|
||||
/** The authorization dialog is host-owned; only sanitized tokens can theme it. */
|
||||
const theme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
control: () => dialog.value,
|
||||
part: 'host.permission',
|
||||
defaults: PERMISSION_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot(hostChromeActiveSkinId.value),
|
||||
}) : null;
|
||||
|
||||
watch([dialog, hostChromeActiveSkinId], () => { theme?.apply(); }, { flush: 'post', immediate: true });
|
||||
watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
|
||||
watch([dialog, authorizationRequested, authorizationDecision], () => {
|
||||
if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
|
||||
theme?.apply();
|
||||
firstVisit.value = authorizationDecision.value === null;
|
||||
checked.value = authorizationDecision.value === true;
|
||||
dialog.value.showModal();
|
||||
@@ -50,5 +68,5 @@ function finish() { authorizationRequested.value = false; dialog.value?.close();
|
||||
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
|
||||
function decline() { setInstanceAuthorization(false); finish(); }
|
||||
function cancel() { if (firstVisit.value) decline(); else finish(); }
|
||||
onBeforeUnmount(() => { dialog.value?.close(); layer?.dispose(); });
|
||||
onBeforeUnmount(() => { dialog.value?.close(); theme?.dispose(); layer?.dispose(); });
|
||||
</script>
|
||||
@@ -1,6 +1,6 @@
|
||||
<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-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
|
||||
<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">
|
||||
<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>
|
||||
@@ -70,12 +70,17 @@ 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 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']> }>();
|
||||
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
|
||||
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);
|
||||
// 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');
|
||||
let fallbackAvoidance: FloatingAvoidance | undefined;
|
||||
const drawerOpen = ref(false);
|
||||
const drawer = ref<HTMLElement | null>(null);
|
||||
const drawerSearch = ref<HTMLInputElement | null>(null);
|
||||
@@ -227,6 +232,25 @@ watch(pluginLibraryRequests, () => {
|
||||
if (props.presentation !== 'dialog' && isHostPartVisuallyReachable('host.plugins.launcher')) openDrawer();
|
||||
else openLibraryDialog();
|
||||
});
|
||||
watch([toolbar, () => props.toolbarTarget], ([element, target]) => {
|
||||
fallbackAvoidance?.dispose();
|
||||
fallbackAvoidance = undefined;
|
||||
fallbackPosition.value = 'bottom-right';
|
||||
if (!element || target) return;
|
||||
fallbackAvoidance = bindFloatingAvoidance({
|
||||
element,
|
||||
isSelf: node => element.contains(node),
|
||||
// Same numbers as .ws-plugin-toolbar-fallback in plugin-overlay.css.
|
||||
margins: insets => ({ top: 16 + insets.top, right: 16, bottom: 16 + insets.bottom, left: 16 }),
|
||||
defaultPosition: 'bottom-right',
|
||||
apply: next => { fallbackPosition.value = next; },
|
||||
// Sticky :hover after a tap on touch screens must not pause avoidance.
|
||||
paused: () => drawerOpen.value
|
||||
|| (matchMedia('(hover: hover)').matches && element.matches(':hover'))
|
||||
|| element.contains(document.activeElement),
|
||||
});
|
||||
}, { flush: 'post' });
|
||||
onBeforeUnmount(() => { fallbackAvoidance?.dispose(); fallbackAvoidance = undefined; });
|
||||
onMounted(() => {
|
||||
document.addEventListener('pointerdown', closeDrawerOutside, true);
|
||||
window.addEventListener('resize', fitDrawer);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<section v-if="error" class="skin-load-recovery" data-ws-part="app.skin-load-recovery" role="alert">
|
||||
<Teleport v-if="layer" :to="layer.container">
|
||||
<section v-if="error" ref="banner" class="skin-load-recovery" data-ws-part="app.skin-load-recovery" role="alert">
|
||||
<p>{{ labels.skinLoadError(error.skinId) }}</p>
|
||||
<button type="button" @click="$emit('use-built-in')">{{ labels.skinUseBuiltIn }}</button>
|
||||
</section>
|
||||
@@ -8,9 +8,16 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
import { resolveSkinLayoutLanguage, skinLayoutLabels } from "../i18n/skin-layout.js";
|
||||
import { createHostOwnedLayer, type HostOwnedLayer } from "../services/host-owned-layer.js";
|
||||
import { hostChromeActiveSkinId } from "../services/host-chrome.js";
|
||||
import {
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
bindHostControlTheme,
|
||||
findSkinRoot,
|
||||
} from "../services/host-control-tokens.js";
|
||||
|
||||
defineEmits<{ "use-built-in": [] }>();
|
||||
|
||||
@@ -19,9 +26,11 @@ const props = defineProps<{
|
||||
language: Language;
|
||||
}>();
|
||||
const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.language)]);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
// The banner is trusted host UI: render it in a closed shadow root so compiled
|
||||
// skin CSS cannot restyle it (or hide it) from the document. The layer's fixed
|
||||
// wrapper is pointer-transparent, so the banner re-enables pointer events.
|
||||
const SKIN_LOAD_LAYER_CSS = `
|
||||
.skin-load-recovery {
|
||||
position: fixed;
|
||||
z-index: 2147482500;
|
||||
@@ -32,21 +41,50 @@ const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.l
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
width: min(720px, calc(100vw - 24px));
|
||||
box-sizing: border-box;
|
||||
padding: 10px 12px;
|
||||
transform: translateX(-50%);
|
||||
border: 1px solid #f59e0b;
|
||||
border-radius: 12px;
|
||||
color: #78350f;
|
||||
background: #fffbeb;
|
||||
border: 1px solid var(--ws-control-border, #f59e0b);
|
||||
border-radius: var(--ws-control-radius, 12px);
|
||||
color: var(--ws-control-foreground, #78350f);
|
||||
background: var(--ws-control-background, #fffbeb);
|
||||
box-shadow: 0 8px 28px #0f172a33;
|
||||
font: 14px/1.45 ui-sans-serif, system-ui, sans-serif;
|
||||
font-family: var(--ws-control-font, ui-sans-serif, system-ui, sans-serif);
|
||||
font-size: var(--ws-control-font-size, 14px);
|
||||
line-height: 1.45;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.skin-load-recovery p { flex: 1; min-width: 0; margin: 0; overflow-wrap: anywhere; }
|
||||
.skin-load-recovery button { flex: 0 0 auto; min-height: 44px; max-width: 100%; padding: 7px 10px; border: 1px solid #b45309; border-radius: 8px; color: #78350f; background: #fff; cursor: pointer; white-space: normal; }
|
||||
.skin-load-recovery button:focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; }
|
||||
|
||||
.skin-load-recovery button { flex: 0 0 auto; min-height: var(--ws-control-hit, 44px); max-width: 100%; padding: 7px 10px; border: 1px solid var(--ws-control-accent, #b45309); border-radius: var(--ws-control-radius, 8px); color: var(--ws-control-foreground, #78350f); background: var(--ws-control-background, #fff); font: inherit; cursor: pointer; white-space: normal; }
|
||||
.skin-load-recovery button:focus-visible { outline: 3px solid var(--ws-control-accent, #1d4ed8); outline-offset: 2px; }
|
||||
@media (max-width: 520px) {
|
||||
.skin-load-recovery { align-items: stretch; flex-direction: column; gap: 7px; }
|
||||
.skin-load-recovery button { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
`;
|
||||
|
||||
const layer: HostOwnedLayer | null = createHostOwnedLayer("skin-load", SKIN_LOAD_LAYER_CSS);
|
||||
const banner = ref<HTMLElement | null>(null);
|
||||
|
||||
/**
|
||||
* Tokens come from the active skin root, never from the document. The banner
|
||||
* appears when a skin failed to load, so a missing root simply keeps the
|
||||
* built-in amber surface; an unreadable palette reverts the same way.
|
||||
*/
|
||||
const theme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
control: () => banner.value,
|
||||
part: "app.skin-load-recovery",
|
||||
defaults: SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot(hostChromeActiveSkinId.value),
|
||||
}) : null;
|
||||
|
||||
watch([() => props.error, banner, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => theme?.apply());
|
||||
}, { flush: "post", immediate: true });
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
theme?.dispose();
|
||||
layer?.dispose();
|
||||
});
|
||||
</script>
|
||||
@@ -4,7 +4,7 @@ import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
const en = {
|
||||
hint: "Audio controls remain available in the toolbar and voice workspace.",
|
||||
library: "Application library",
|
||||
recovery: "Restore application library",
|
||||
recovery: "Restore built-in skin",
|
||||
useBuiltIn: "Use built-in skin",
|
||||
shortcut: "Restore the built-in skin (Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS)",
|
||||
};
|
||||
@@ -13,28 +13,28 @@ export const hostChromeCopy: Record<SiteLanguage, typeof en> = {
|
||||
zh: {
|
||||
hint: "音频控制始终保留在工具栏和语音工作区中。",
|
||||
library: "应用库",
|
||||
recovery: "恢复应用库",
|
||||
recovery: "恢复内置皮肤",
|
||||
useBuiltIn: "使用内置皮肤",
|
||||
shortcut: "恢复内置皮肤(Ctrl+Alt+Shift+R,macOS 为 ⌘+⌥+⇧+R)",
|
||||
},
|
||||
de: {
|
||||
hint: "Audiosteuerung bleibt in der Werkzeugleiste und im Sprachbereich verfügbar.",
|
||||
library: "Anwendungsbibliothek",
|
||||
recovery: "Anwendungsbibliothek wiederherstellen",
|
||||
recovery: "Integrierten Skin wiederherstellen",
|
||||
useBuiltIn: "Integrierten Skin verwenden",
|
||||
shortcut: "Integrierten Skin wiederherstellen (Strg+Alt+Umschalt+R, unter macOS ⌘+⌥+⇧+R)",
|
||||
},
|
||||
ru: {
|
||||
hint: "Управление звуком остаётся доступным на панели инструментов и в голосовой области.",
|
||||
library: "Библиотека приложений",
|
||||
recovery: "Восстановить библиотеку приложений",
|
||||
recovery: "Восстановить встроенную тему",
|
||||
useBuiltIn: "Использовать встроенную тему",
|
||||
shortcut: "Восстановить встроенную тему (Ctrl+Alt+Shift+R, в macOS ⌘+⌥+⇧+R)",
|
||||
},
|
||||
ja: {
|
||||
hint: "音声コントロールはツールバーと音声ワークスペースで常に利用できます。",
|
||||
library: "アプリライブラリ",
|
||||
recovery: "アプリライブラリを復元",
|
||||
recovery: "組み込みスキンを復元",
|
||||
useBuiltIn: "組み込みスキンを使用",
|
||||
shortcut: "組み込みスキンを復元(Ctrl+Alt+Shift+R、macOS は ⌘+⌥+⇧+R)",
|
||||
},
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isBundledSkin } from "./host-chrome.js";
|
||||
import { parseSkinChromeDocument } from "../../../src/shared/skin-chrome.js";
|
||||
import {
|
||||
activeHostSlot,
|
||||
isBundledSkin,
|
||||
setHostChromeActiveSkin,
|
||||
setSkinHostChromeParts,
|
||||
} from "./host-chrome.js";
|
||||
import { isHostPartReachable, shouldShowRecovery, type HostPartVisibilitySnapshot } from "./host-chrome-visibility.js";
|
||||
|
||||
const snapshot = (overrides: Partial<HostPartVisibilitySnapshot> = {}): HostPartVisibilitySnapshot => ({
|
||||
@@ -78,3 +84,31 @@ test("the recovery entry is persistent for third-party skins only", () => {
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, thirdPartySkinActive: true }), false);
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, launcherHiddenByConfig: true }), false);
|
||||
});
|
||||
|
||||
test("slot declarations are honoured for third-party skins only", () => {
|
||||
const document = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: { "host.recovery": { anchor: "voice.audio-dock" } },
|
||||
}));
|
||||
setSkinHostChromeParts(document);
|
||||
setHostChromeActiveSkin("community.demo");
|
||||
try {
|
||||
assert.deepEqual(activeHostSlot("host.recovery"), {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "end",
|
||||
compact: false,
|
||||
});
|
||||
// A part that is not slottable cannot be selected through chrome.json.
|
||||
assert.equal(activeHostSlot("host.permission"), undefined);
|
||||
|
||||
// Bundled/official skins keep the default floating placement.
|
||||
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
|
||||
setHostChromeActiveSkin(id);
|
||||
assert.equal(activeHostSlot("host.recovery"), undefined, String(id));
|
||||
}
|
||||
} finally {
|
||||
// Module-global state: never leak it into sibling tests.
|
||||
setSkinHostChromeParts(undefined);
|
||||
setHostChromeActiveSkin(undefined);
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { computed, readonly, ref, shallowRef } from "vue";
|
||||
import { DECORATIVE_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import { resolveHiddenHostParts, type SkinChromeDocument } from "../../../src/shared/skin-chrome.js";
|
||||
import { DECORATIVE_PART_IDS, HOST_SLOTTABLE_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import { resolveHiddenHostParts, type SkinChromeDocument, type SkinChromeSlot } from "../../../src/shared/skin-chrome.js";
|
||||
import { isHostPartReachable } from "./host-chrome-visibility.js";
|
||||
|
||||
/**
|
||||
@@ -30,6 +30,9 @@ export function setHostChromeActiveSkin(id: string | undefined): void {
|
||||
activeSkin.value = id;
|
||||
}
|
||||
|
||||
/** Read-only view for host chrome that reacts to skin activations. */
|
||||
export const hostChromeActiveSkinId = readonly(activeSkin);
|
||||
|
||||
export function isBundledSkin(id: string | undefined): boolean {
|
||||
return !id || id.startsWith("builtin.") || BUNDLED_SKIN_IDS.has(id);
|
||||
}
|
||||
@@ -60,6 +63,16 @@ export function isHostPartHidden(part: string): boolean {
|
||||
return hiddenParts.value.has(part);
|
||||
}
|
||||
|
||||
/**
|
||||
* Slot declarations are honoured only for an active third-party skin. Bundled
|
||||
* skins, and any skin without a matching `chrome.json#slots` entry, keep the
|
||||
* default floating placement.
|
||||
*/
|
||||
export function activeHostSlot(part: string): SkinChromeSlot | undefined {
|
||||
if (!HOST_SLOTTABLE_PART_IDS.has(part) || !isThirdPartySkinActive()) return undefined;
|
||||
return skinChrome.value?.slots?.[part];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the live DOM to find out whether a host part can actually be used.
|
||||
* Declarative hiding (`v-if`) removes the element entirely; CSS-only hiding
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
HOST_CONTROL_APPLIED_VARIABLES,
|
||||
HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES,
|
||||
HOST_CONTROL_MIN_ACCENT_CONTRAST,
|
||||
HOST_CONTROL_MIN_BORDER_CONTRAST,
|
||||
HOST_CONTROL_MIN_FONT_SIZE,
|
||||
HOST_CONTROL_MIN_FOREGROUND_CONTRAST,
|
||||
HOST_CONTROL_MIN_HIT_TARGET,
|
||||
HOST_CONTROL_SIZE_METRICS,
|
||||
PERMISSION_CONTROL_DEFAULTS,
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
applyHostControlTokens,
|
||||
contrastRatio,
|
||||
fontFamilyNames,
|
||||
formatRgb,
|
||||
hasHostControlTokens,
|
||||
hostControlTokenKey,
|
||||
hostControlTokenProperty,
|
||||
parseCssColor,
|
||||
relativeLuminance,
|
||||
resolveHostControlTokens,
|
||||
type HostControlRawTokens,
|
||||
} from "./host-control-tokens.js";
|
||||
|
||||
type TokenMap = Record<string, string>;
|
||||
|
||||
const style = (tokens: TokenMap): Pick<CSSStyleDeclaration, "getPropertyValue"> => ({
|
||||
getPropertyValue: (name) => tokens[name] ?? "",
|
||||
});
|
||||
|
||||
const prefixed = (prefix: string, tokens: HostControlRawTokens): TokenMap => Object.fromEntries(
|
||||
Object.entries(tokens)
|
||||
.filter((entry): entry is [string, string] => typeof entry[1] === "string")
|
||||
.map(([name, value]) => [`--skin-${prefix}-${name}`, value]),
|
||||
);
|
||||
|
||||
const resolveRecovery = (part: HostControlRawTokens = {}, global: HostControlRawTokens = {}) =>
|
||||
resolveHostControlTokens(
|
||||
style({ ...prefixed("host", global), ...prefixed("recovery", part) }),
|
||||
"host.recovery",
|
||||
raw => raw,
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
);
|
||||
|
||||
test("host control token names are stable and keep --skin-recovery-* working", () => {
|
||||
assert.equal(hostControlTokenKey("host.recovery"), "recovery");
|
||||
assert.equal(hostControlTokenKey("app.skin-load-recovery"), "load-recovery");
|
||||
assert.equal(hostControlTokenKey("host.permission"), "permission");
|
||||
assert.equal(hostControlTokenKey("host.future"), "future");
|
||||
|
||||
assert.equal(hostControlTokenProperty("host.recovery", "background"), "--skin-recovery-background");
|
||||
assert.equal(hostControlTokenProperty("app.skin-load-recovery", "size"), "--skin-load-recovery-size");
|
||||
assert.equal(hostControlTokenProperty("host.permission", "accent"), "--skin-permission-accent");
|
||||
assert.equal(HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES.foreground, "--skin-host-foreground");
|
||||
});
|
||||
|
||||
test("recovery tokens default to the host palette", () => {
|
||||
const tokens = resolveHostControlTokens(null, "host.recovery", () => undefined, RECOVERY_CONTROL_DEFAULTS);
|
||||
assert.equal(tokens.accent, "rgb(180, 83, 9)");
|
||||
assert.equal(tokens.builtInBorder, "rgb(180, 83, 9)");
|
||||
assert.equal(tokens.background, "rgb(255, 255, 255)");
|
||||
assert.equal(tokens.foreground, "rgb(49, 82, 79)");
|
||||
assert.equal(tokens.border, "rgb(157, 182, 178)");
|
||||
assert.equal(tokens.radius, 999);
|
||||
assert.equal(tokens.font, "ui-sans-serif, system-ui, sans-serif");
|
||||
assert.equal(tokens.size, "small");
|
||||
assert.equal(tokens.hitTarget, HOST_CONTROL_MIN_HIT_TARGET);
|
||||
assert.equal(tokens.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
|
||||
assert.ok(contrastRatio(parseCssColor(tokens.onAccent)!, parseCssColor(tokens.accent)!) >= 4.5);
|
||||
});
|
||||
|
||||
test("a readable skin palette is kept and translucent backgrounds become opaque", () => {
|
||||
const tokens = resolveRecovery({
|
||||
accent: "#47dcc4",
|
||||
background: "rgba(9, 19, 23, 0.4)",
|
||||
foreground: "#edf8f5",
|
||||
border: "#47dcc4",
|
||||
});
|
||||
assert.equal(tokens.accent, "rgb(71, 220, 196)");
|
||||
assert.equal(tokens.background, "rgb(9, 19, 23)");
|
||||
assert.equal(tokens.foreground, "rgb(237, 248, 245)");
|
||||
assert.equal(tokens.border, "rgb(71, 220, 196)");
|
||||
});
|
||||
|
||||
test("per-part tokens win over the global set and both fall back as a colour group", () => {
|
||||
const readable = resolveRecovery(
|
||||
{ background: "#102030", foreground: "#ffffff", accent: "#47dcc4" },
|
||||
{ background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" },
|
||||
);
|
||||
assert.equal(readable.background, "rgb(16, 32, 48)", "the per-part background must win");
|
||||
assert.equal(readable.foreground, "rgb(255, 255, 255)");
|
||||
assert.equal(readable.accent, "rgb(71, 220, 196)");
|
||||
|
||||
// An unreadable per-part group falls back to a readable global palette.
|
||||
const globalFallback = resolveRecovery(
|
||||
{ background: "#777777", foreground: "#888888", accent: "#47dcc4" },
|
||||
{ background: "#102030", foreground: "#ffffff", accent: "#47dcc4" },
|
||||
);
|
||||
assert.equal(globalFallback.background, "rgb(16, 32, 48)");
|
||||
assert.equal(globalFallback.foreground, "rgb(255, 255, 255)");
|
||||
assert.equal(globalFallback.accent, "rgb(71, 220, 196)");
|
||||
|
||||
// No readable layer: the built-in palette wins as a whole.
|
||||
const reset = resolveRecovery(
|
||||
{ background: "#777777", foreground: "#888888", accent: "#47dcc4" },
|
||||
{ background: "#888888", foreground: "#999999", accent: "#eeeeee" },
|
||||
);
|
||||
assert.equal(reset.background, "rgb(255, 255, 255)");
|
||||
assert.equal(reset.foreground, "rgb(49, 82, 79)");
|
||||
assert.equal(reset.accent, "rgb(180, 83, 9)");
|
||||
});
|
||||
|
||||
test("the border only uses a colour visible against the resolved background", () => {
|
||||
assert.equal(resolveRecovery({ border: "#ffffff" }).border, "rgb(157, 182, 178)");
|
||||
assert.equal(resolveRecovery({ border: "#000000" }).border, "rgb(0, 0, 0)");
|
||||
|
||||
const globalFallback = resolveRecovery({ border: "#ffffff" }, { border: "#000000" });
|
||||
assert.equal(globalFallback.border, "rgb(0, 0, 0)");
|
||||
assert.ok(contrastRatio(parseCssColor(globalFallback.border)!, parseCssColor(globalFallback.background)!) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
|
||||
});
|
||||
|
||||
test("radius, font and size tokens are sanitized and host minimums win", () => {
|
||||
assert.equal(resolveRecovery({ radius: "12px" }).radius, 12);
|
||||
assert.equal(resolveRecovery({ radius: "2000px" }).radius, 999);
|
||||
assert.equal(resolveRecovery({ radius: "-5px" }).radius, 0);
|
||||
assert.equal(resolveRecovery({ radius: "1em" }).radius, 999);
|
||||
assert.equal(resolveRecovery({ radius: "12" }).radius, 999);
|
||||
|
||||
assert.equal(resolveRecovery({ font: 'Tahoma, "Segoe UI", sans-serif' }).font, 'Tahoma, "Segoe UI", sans-serif');
|
||||
for (const font of ["url(https://example.invalid/a.woff2)", "Tahoma; color: red", "x".repeat(121)]) {
|
||||
assert.equal(resolveRecovery({ font }).font, "ui-sans-serif, system-ui, sans-serif", font);
|
||||
}
|
||||
|
||||
assert.equal(resolveRecovery({ size: "medium" }).hitTarget, 32);
|
||||
assert.equal(resolveRecovery({ size: "medium" }).fontSize, 12);
|
||||
assert.equal(resolveRecovery({ size: "large" }).hitTarget, 36);
|
||||
assert.equal(resolveRecovery({ size: "large" }).fontSize, 13);
|
||||
assert.equal(resolveRecovery({ size: "huge" }).size, "small");
|
||||
for (const metrics of Object.values(HOST_CONTROL_SIZE_METRICS)) {
|
||||
assert.ok(metrics.hitTarget >= HOST_CONTROL_MIN_HIT_TARGET);
|
||||
assert.ok(metrics.fontSize >= HOST_CONTROL_MIN_FONT_SIZE);
|
||||
}
|
||||
|
||||
// Controls with a larger built-in action never shrink below it.
|
||||
const banner = resolveHostControlTokens(
|
||||
style(prefixed("host", { size: "small" })),
|
||||
"app.skin-load-recovery",
|
||||
raw => raw,
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
);
|
||||
assert.equal(banner.hitTarget, 44);
|
||||
assert.equal(banner.fontSize, 14);
|
||||
const bannerLarge = resolveHostControlTokens(
|
||||
style(prefixed("load-recovery", { size: "large" })),
|
||||
"app.skin-load-recovery",
|
||||
raw => raw,
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
);
|
||||
assert.equal(bannerLarge.hitTarget, 48);
|
||||
assert.equal(bannerLarge.fontSize, 16);
|
||||
});
|
||||
|
||||
test("the built-in button border only uses an accent visible on its fixed light background", () => {
|
||||
const pale = resolveRecovery({ background: "#141414", foreground: "#ffffff", accent: "#fff7ec" });
|
||||
assert.equal(pale.accent, "rgb(255, 247, 236)");
|
||||
assert.equal(pale.builtInBorder, "rgb(180, 83, 9)");
|
||||
|
||||
const strong = resolveRecovery({ background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" });
|
||||
assert.equal(strong.builtInBorder, "rgb(29, 78, 216)");
|
||||
});
|
||||
|
||||
test("global tokens theme the banner and the authorization dialog", () => {
|
||||
const root = style(prefixed("host", {
|
||||
background: "#102030",
|
||||
foreground: "#ffffff",
|
||||
accent: "#47dcc4",
|
||||
border: "#47dcc4",
|
||||
radius: "18px",
|
||||
font: "Tahoma, sans-serif",
|
||||
size: "large",
|
||||
}));
|
||||
const banner = resolveHostControlTokens(root, "app.skin-load-recovery", raw => raw, SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS);
|
||||
assert.equal(banner.background, "rgb(16, 32, 48)");
|
||||
assert.equal(banner.foreground, "rgb(255, 255, 255)");
|
||||
assert.equal(banner.radius, 18);
|
||||
assert.equal(banner.font, "Tahoma, sans-serif");
|
||||
assert.equal(banner.hitTarget, 48);
|
||||
|
||||
const dialog = resolveHostControlTokens(root, "host.permission", raw => raw, PERMISSION_CONTROL_DEFAULTS);
|
||||
assert.equal(dialog.background, "rgb(16, 32, 48)");
|
||||
assert.equal(dialog.foreground, "rgb(255, 255, 255)");
|
||||
assert.ok(contrastRatio(parseCssColor(dialog.onAccent)!, parseCssColor(dialog.accent)!) >= 4.5);
|
||||
assert.equal(dialog.hitTarget, 46);
|
||||
|
||||
// A mid-grey accent passes 3:1 on white, but neither black nor white text
|
||||
// reaches 4.5:1 on it (best is ~4.23), so the palette falls back as a group.
|
||||
const midTone = resolveHostControlTokens(
|
||||
style(prefixed("host", { background: "#ffffff", foreground: "#000000", accent: "#7b7b7b" })),
|
||||
"host.permission",
|
||||
raw => raw,
|
||||
PERMISSION_CONTROL_DEFAULTS,
|
||||
);
|
||||
assert.equal(midTone.accent, formatRgb(PERMISSION_CONTROL_DEFAULTS.accent));
|
||||
assert.ok(contrastRatio(parseCssColor(midTone.onAccent)!, parseCssColor(midTone.accent)!) >= 4.5);
|
||||
|
||||
const override = resolveHostControlTokens(
|
||||
style({ ...prefixed("host", { background: "#102030", foreground: "#ffffff", accent: "#47dcc4" }), ...prefixed("load-recovery", { background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" }) }),
|
||||
"app.skin-load-recovery",
|
||||
raw => raw,
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
);
|
||||
assert.equal(override.background, "rgb(255, 255, 255)");
|
||||
});
|
||||
|
||||
test("only a declared global or per-part token triggers host theming", () => {
|
||||
assert.equal(hasHostControlTokens(style({}), "host.recovery"), false);
|
||||
assert.equal(hasHostControlTokens(style({ "--skin-unrelated": "red" }), "host.recovery"), false);
|
||||
assert.equal(hasHostControlTokens(style({ "--skin-host-background": "#102030" }), "host.recovery"), true);
|
||||
assert.equal(hasHostControlTokens(style({ "--skin-recovery-radius": "8px" }), "host.recovery"), true);
|
||||
assert.equal(hasHostControlTokens(style({ "--skin-load-recovery-accent": "#123456" }), "app.skin-load-recovery"), true);
|
||||
assert.equal(hasHostControlTokens(style({ "--skin-permission-font": "Tahoma" }), "host.permission"), true);
|
||||
});
|
||||
|
||||
test("applying and clearing tokens writes only host-owned 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;
|
||||
const tokens = resolveRecovery({ background: "#102030", foreground: "#ffffff", accent: "#47dcc4", radius: "8px" });
|
||||
applyHostControlTokens(control, tokens);
|
||||
assert.equal(values.get(HOST_CONTROL_APPLIED_VARIABLES.background), "rgb(16, 32, 48)");
|
||||
assert.equal(values.get(HOST_CONTROL_APPLIED_VARIABLES.radius), "8px");
|
||||
assert.ok(values.has(HOST_CONTROL_APPLIED_VARIABLES.onAccent));
|
||||
applyHostControlTokens(control, null);
|
||||
assert.equal(values.size, 0);
|
||||
});
|
||||
|
||||
test("CSS colours parse to RGB and ignore alpha for contrast", () => {
|
||||
assert.deepEqual(parseCssColor("#1d4f9c"), { r: 29, g: 79, b: 156 });
|
||||
assert.deepEqual(parseCssColor("#fff"), { r: 255, g: 255, b: 255 });
|
||||
assert.deepEqual(parseCssColor("#ffff"), { r: 255, g: 255, b: 255 });
|
||||
assert.deepEqual(parseCssColor("rgb(29, 79, 156)"), { r: 29, g: 79, b: 156 });
|
||||
assert.deepEqual(parseCssColor("rgb(29 79 156 / 50%)"), { r: 29, g: 79, b: 156 });
|
||||
assert.deepEqual(parseCssColor("rgba(255, 0, 0, .4)"), { r: 255, g: 0, b: 0 });
|
||||
assert.deepEqual(parseCssColor("rgb(300, -5, 0)"), { r: 255, g: 0, b: 0 });
|
||||
for (const invalid of ["", "red", "hsl(10, 20%, 30%)", "color(srgb 1 0 0)", "#12345", "rgb(1, 2)"]) {
|
||||
assert.equal(parseCssColor(invalid), null, invalid);
|
||||
}
|
||||
});
|
||||
|
||||
test("WCAG contrast follows the relative-luminance formula", () => {
|
||||
assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0);
|
||||
assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1);
|
||||
assert.equal(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }), 21);
|
||||
assert.equal(contrastRatio({ r: 12, g: 34, b: 56 }, { r: 12, g: 34, b: 56 }), 1);
|
||||
assert.ok(HOST_CONTROL_MIN_FOREGROUND_CONTRAST > HOST_CONTROL_MIN_ACCENT_CONTRAST);
|
||||
});
|
||||
|
||||
test("host controls ignore fonts registered by a skin @font-face", () => {
|
||||
assert.deepEqual(fontFamilyNames(`"Wave Font", 'Other' , sans-serif`), ["wave font", "other", "sans-serif"]);
|
||||
const webFonts = new Set(["blank glyphs"]);
|
||||
const isWebFont = (family: string) => webFonts.has(family);
|
||||
const resolve = (font: string) => resolveHostControlTokens(
|
||||
style({ "--skin-host-font": font }),
|
||||
"app.skin-load-recovery",
|
||||
raw => raw,
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
isWebFont,
|
||||
).font;
|
||||
assert.equal(resolve('"Blank Glyphs", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
|
||||
assert.equal(resolve("Tahoma, 'blank glyphs'"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
|
||||
assert.equal(resolve('Tahoma, "Segoe UI", sans-serif'), 'Tahoma, "Segoe UI", sans-serif');
|
||||
// Compiled skin faces are always `ws-<skin id>-<name>`; a face gated behind a
|
||||
// non-matching @media is not in document.fonts yet but must still be refused.
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,612 @@
|
||||
/**
|
||||
* Style tokens for host-owned protected controls.
|
||||
*
|
||||
* Recovery, the skin-load banner and the authorization dialog live inside
|
||||
* closed shadow roots, so compiled skin CSS can never reach them. A skin may
|
||||
* declare a small, sanitised token set on the active skin root instead; the
|
||||
* host reads it, checks readability and applies the result inside the shadow
|
||||
* root. The control still owns its structure, hit target and fallback.
|
||||
*
|
||||
* Token names:
|
||||
* --skin-host-accent | background | foreground | border | radius | font | size
|
||||
* --skin-<part-key>-<token> (per-part override)
|
||||
*
|
||||
* `host.recovery` keeps its historical `recovery` key so `--skin-recovery-*`
|
||||
* continues to work; its per-part values win over the global set.
|
||||
*/
|
||||
|
||||
import type { HostOwnedLayer } from "./host-owned-layer.js";
|
||||
|
||||
export type HostControlSizeTier = "small" | "medium" | "large";
|
||||
export interface HostControlMetrics {
|
||||
/** Host-enforced minimum button hit target in CSS pixels. */
|
||||
readonly hitTarget: number;
|
||||
/** Host-enforced minimum font size in CSS pixels. */
|
||||
readonly fontSize: number;
|
||||
}
|
||||
|
||||
export const HOST_CONTROL_MIN_HIT_TARGET = 28;
|
||||
export const HOST_CONTROL_MIN_FONT_SIZE = 11;
|
||||
export const HOST_CONTROL_MIN_FOREGROUND_CONTRAST = 4.5;
|
||||
export const HOST_CONTROL_MIN_ACCENT_CONTRAST = 3;
|
||||
export const HOST_CONTROL_MIN_BORDER_CONTRAST = 3;
|
||||
|
||||
/** Host-controlled size tiers; a skin can choose a tier, never a smaller size. */
|
||||
export const HOST_CONTROL_SIZE_METRICS: Readonly<Record<HostControlSizeTier, HostControlMetrics>> = {
|
||||
small: { hitTarget: 28, fontSize: 11 },
|
||||
medium: { hitTarget: 32, fontSize: 12 },
|
||||
large: { hitTarget: 36, fontSize: 13 },
|
||||
};
|
||||
|
||||
export const HOST_CONTROL_TOKEN_NAMES = [
|
||||
"accent", "background", "foreground", "border", "radius", "font", "size",
|
||||
] as const;
|
||||
|
||||
export type HostControlTokenName = (typeof HOST_CONTROL_TOKEN_NAMES)[number];
|
||||
|
||||
/** 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",
|
||||
background: "--skin-host-background",
|
||||
foreground: "--skin-host-foreground",
|
||||
border: "--skin-host-border",
|
||||
radius: "--skin-host-radius",
|
||||
font: "--skin-host-font",
|
||||
size: "--skin-host-size",
|
||||
};
|
||||
|
||||
/**
|
||||
* Stable per-part token keys. The last dotted segment would turn
|
||||
* `app.skin-load-recovery` into `--skin-skin-load-recovery-*`; the explicit
|
||||
* keys keep the public names readable.
|
||||
*/
|
||||
export const HOST_CONTROL_TOKEN_KEYS: Readonly<Record<string, string>> = {
|
||||
"host.recovery": "recovery",
|
||||
"app.skin-load-recovery": "load-recovery",
|
||||
"host.permission": "permission",
|
||||
};
|
||||
|
||||
export function hostControlTokenKey(part: string): string {
|
||||
return HOST_CONTROL_TOKEN_KEYS[part] ?? part.split(".").pop() ?? part;
|
||||
}
|
||||
|
||||
export function hostControlTokenProperty(part: string, token: HostControlTokenName): string {
|
||||
return `--skin-${hostControlTokenKey(part)}-${token}`;
|
||||
}
|
||||
|
||||
/** Host-owned variables written inside the closed shadow root. */
|
||||
export const HOST_CONTROL_APPLIED_VARIABLES = {
|
||||
accent: "--ws-control-accent",
|
||||
onAccent: "--ws-control-on-accent",
|
||||
background: "--ws-control-background",
|
||||
foreground: "--ws-control-foreground",
|
||||
border: "--ws-control-border",
|
||||
radius: "--ws-control-radius",
|
||||
font: "--ws-control-font",
|
||||
hitTarget: "--ws-control-hit",
|
||||
fontSize: "--ws-control-font-size",
|
||||
builtInBorder: "--ws-control-builtin-border",
|
||||
} as const;
|
||||
|
||||
export interface HostControlRawTokens {
|
||||
/** Computed-style colour values; unresolved values are rejected. */
|
||||
accent?: string;
|
||||
background?: string;
|
||||
foreground?: string;
|
||||
border?: string;
|
||||
radius?: string;
|
||||
font?: string;
|
||||
size?: string;
|
||||
}
|
||||
|
||||
export interface HostControlDefaults {
|
||||
accent: RgbColor;
|
||||
background: RgbColor;
|
||||
foreground: RgbColor;
|
||||
border: RgbColor;
|
||||
radius: number;
|
||||
maxRadius: number;
|
||||
font: string;
|
||||
hitTarget: number;
|
||||
fontSize: number;
|
||||
/** Optional per-tier metrics; defaults to HOST_CONTROL_SIZE_METRICS. */
|
||||
sizeMetrics?: Readonly<Record<HostControlSizeTier, HostControlMetrics>>;
|
||||
/** A fixed light-background action that keeps its own border contrast check. */
|
||||
builtInButton?: { background: RgbColor; border: RgbColor };
|
||||
}
|
||||
|
||||
export interface HostControlTokens {
|
||||
accent: string;
|
||||
/** Text colour that stays readable on top of `accent`. */
|
||||
onAccent: string;
|
||||
background: string;
|
||||
foreground: string;
|
||||
border: string;
|
||||
radius: number;
|
||||
font: string;
|
||||
size: HostControlSizeTier;
|
||||
hitTarget: number;
|
||||
fontSize: number;
|
||||
builtInBorder?: string;
|
||||
}
|
||||
|
||||
export interface RgbColor {
|
||||
r: number;
|
||||
g: number;
|
||||
b: 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 };
|
||||
const DEFAULT_BORDER: RgbColor = { r: 157, g: 182, b: 178 };
|
||||
const RECOVERY_BUILT_IN_BACKGROUND: RgbColor = { r: 255, g: 247, b: 237 };
|
||||
const RECOVERY_BUILT_IN_BORDER: RgbColor = { r: 180, g: 83, b: 9 };
|
||||
const ON_ACCENT_LIGHT: RgbColor = { r: 255, g: 255, b: 255 };
|
||||
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}$/;
|
||||
/**
|
||||
* The skin compiler renames every skin/plugin `@font-face` family to
|
||||
* `ws-<skin id>[-<plugin id>]-<name>` (see `compileSkinCss` in
|
||||
* src/shared/skin-css.ts), so that prefix identifies a skin font even when the
|
||||
* face is not in `document.fonts` yet (for example behind a non-matching
|
||||
* `@media` that activates after the token was accepted).
|
||||
*/
|
||||
const SCOPED_SKIN_FONT_PREFIX = "ws-";
|
||||
|
||||
/** Defaults for the recovery capsule: white surface, teal text, amber accent. */
|
||||
export const RECOVERY_CONTROL_DEFAULTS: HostControlDefaults = {
|
||||
accent: DEFAULT_ACCENT,
|
||||
background: DEFAULT_BACKGROUND,
|
||||
foreground: DEFAULT_FOREGROUND,
|
||||
border: DEFAULT_BORDER,
|
||||
radius: 999,
|
||||
maxRadius: MAX_RADIUS,
|
||||
font: "ui-sans-serif, system-ui, sans-serif",
|
||||
hitTarget: HOST_CONTROL_MIN_HIT_TARGET,
|
||||
fontSize: HOST_CONTROL_MIN_FONT_SIZE,
|
||||
builtInButton: { background: RECOVERY_BUILT_IN_BACKGROUND, border: RECOVERY_BUILT_IN_BORDER },
|
||||
};
|
||||
|
||||
/** Defaults for the skin-load failure banner: amber alert, 44px action. */
|
||||
export const SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS: HostControlDefaults = {
|
||||
accent: { r: 180, g: 83, b: 9 },
|
||||
background: { r: 255, g: 251, b: 235 },
|
||||
foreground: { r: 120, g: 53, b: 15 },
|
||||
border: { r: 245, g: 158, b: 11 },
|
||||
radius: 12,
|
||||
maxRadius: 64,
|
||||
font: "ui-sans-serif, system-ui, sans-serif",
|
||||
hitTarget: 44,
|
||||
fontSize: 14,
|
||||
sizeMetrics: {
|
||||
small: { hitTarget: 44, fontSize: 14 },
|
||||
medium: { hitTarget: 46, fontSize: 15 },
|
||||
large: { hitTarget: 48, fontSize: 16 },
|
||||
},
|
||||
};
|
||||
|
||||
/** Defaults for the host-owned authorization ("permission") dialog. */
|
||||
export const PERMISSION_CONTROL_DEFAULTS: HostControlDefaults = {
|
||||
accent: { r: 82, g: 101, b: 223 },
|
||||
background: { r: 255, g: 255, b: 255 },
|
||||
foreground: { r: 37, g: 50, b: 75 },
|
||||
border: { r: 219, g: 227, b: 241 },
|
||||
radius: 20,
|
||||
maxRadius: 64,
|
||||
font: 'system-ui, -apple-system, "Segoe UI", sans-serif',
|
||||
hitTarget: 42,
|
||||
fontSize: 14,
|
||||
sizeMetrics: {
|
||||
small: { hitTarget: 42, fontSize: 14 },
|
||||
medium: { hitTarget: 44, fontSize: 15 },
|
||||
large: { hitTarget: 46, fontSize: 16 },
|
||||
},
|
||||
};
|
||||
|
||||
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
|
||||
export function parseCssColor(value: string | undefined | null): RgbColor | null {
|
||||
if (!value) return null;
|
||||
const text = value.trim().toLowerCase();
|
||||
const hex = /^#([0-9a-f]{3,8})$/.exec(text);
|
||||
if (hex) {
|
||||
const digits = hex[1];
|
||||
if (digits.length === 3 || digits.length === 4) {
|
||||
return {
|
||||
r: Number.parseInt(digits[0] + digits[0], 16),
|
||||
g: Number.parseInt(digits[1] + digits[1], 16),
|
||||
b: Number.parseInt(digits[2] + digits[2], 16),
|
||||
};
|
||||
}
|
||||
if (digits.length === 6 || digits.length === 8) {
|
||||
return {
|
||||
r: Number.parseInt(digits.slice(0, 2), 16),
|
||||
g: Number.parseInt(digits.slice(2, 4), 16),
|
||||
b: Number.parseInt(digits.slice(4, 6), 16),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const fn = /^rgba?\(([^()]*)\)$/.exec(text);
|
||||
if (!fn) return null;
|
||||
const parts = fn[1].replace(/\//g, " ").split(/[\s,]+/).filter(Boolean);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const channels: number[] = [];
|
||||
for (const part of parts.slice(0, 3)) {
|
||||
const percent = part.endsWith("%");
|
||||
const parsed = Number.parseFloat(part);
|
||||
if (!Number.isFinite(parsed)) return null;
|
||||
const channel = percent ? parsed * 2.55 : parsed;
|
||||
channels.push(Math.round(Math.min(255, Math.max(0, channel))));
|
||||
}
|
||||
return { r: channels[0], g: channels[1], b: channels[2] };
|
||||
}
|
||||
|
||||
export function formatRgb(color: RgbColor): string {
|
||||
return `rgb(${color.r}, ${color.g}, ${color.b})`;
|
||||
}
|
||||
|
||||
/** WCAG 2.x relative luminance, 0 (black) to 1 (white). */
|
||||
export function relativeLuminance(color: RgbColor): number {
|
||||
const channel = (value: number): number => {
|
||||
const normalized = Math.min(255, Math.max(0, value)) / 255;
|
||||
return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
|
||||
}
|
||||
|
||||
export function contrastRatio(first: RgbColor, second: RgbColor): number {
|
||||
const lighter = Math.max(relativeLuminance(first), relativeLuminance(second));
|
||||
const darker = Math.min(relativeLuminance(first), relativeLuminance(second));
|
||||
return (lighter + 0.05) / (darker + 0.05);
|
||||
}
|
||||
|
||||
export function isHostControlSizeTier(value: unknown): value is HostControlSizeTier {
|
||||
return value === "small" || value === "medium" || value === "large";
|
||||
}
|
||||
|
||||
function sanitizeRadius(value: string | undefined, fallback: number, maxRadius: number): number {
|
||||
if (!value) return fallback;
|
||||
const match = /^(-?\d+(?:\.\d+)?)px$/i.exec(value.trim());
|
||||
if (!match) return fallback;
|
||||
const radius = Number.parseFloat(match[1]);
|
||||
return Number.isFinite(radius) ? Math.min(maxRadius, Math.max(0, radius)) : fallback;
|
||||
}
|
||||
|
||||
/** Lower-cased family names from a `font-family` list, quotes removed. */
|
||||
export function fontFamilyNames(value: string): string[] {
|
||||
return value.split(",").map((name) => name.trim().replace(/^["']|["']$/g, "").trim().toLowerCase()).filter(Boolean);
|
||||
}
|
||||
|
||||
function sanitizeFont(value: string | undefined, fallback: string, isWebFont: WebFontCheck): string {
|
||||
if (!value) return fallback;
|
||||
const font = value.trim().replace(/\s+/g, " ");
|
||||
if (!font || font.length > MAX_FONT_LENGTH || !FONT_FAMILY_PATTERN.test(font) || !/[A-Za-z0-9]/.test(font)) {
|
||||
return fallback;
|
||||
}
|
||||
// A skin-supplied @font-face can ship glyph-less outlines and blank the
|
||||
// control's label, so host-owned controls only accept installed/generic fonts.
|
||||
if (fontFamilyNames(font).some((name) => name.startsWith(SCOPED_SKIN_FONT_PREFIX) || isWebFont(name))) return fallback;
|
||||
return font;
|
||||
}
|
||||
|
||||
function readTokenSet(
|
||||
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
|
||||
resolveProperty: (token: HostControlTokenName) => string,
|
||||
): HostControlRawTokens {
|
||||
if (!style) return {};
|
||||
const read = (token: HostControlTokenName): string | undefined => {
|
||||
const value = style.getPropertyValue(resolveProperty(token)).trim();
|
||||
return value || undefined;
|
||||
};
|
||||
return {
|
||||
accent: read("accent"),
|
||||
background: read("background"),
|
||||
foreground: read("foreground"),
|
||||
border: read("border"),
|
||||
radius: read("radius"),
|
||||
font: read("font"),
|
||||
size: read("size"),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeRawTokens(...layers: readonly HostControlRawTokens[]): HostControlRawTokens {
|
||||
const merged: HostControlRawTokens = {};
|
||||
for (const layer of layers) {
|
||||
for (const token of HOST_CONTROL_TOKEN_NAMES) {
|
||||
if (layer[token] !== undefined) merged[token] = layer[token];
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
type ColorProbe = (raw: string | undefined) => string | undefined;
|
||||
/** True when a (lower-cased, unquoted) family is provided by a document @font-face. */
|
||||
type WebFontCheck = (family: string) => boolean;
|
||||
const NO_WEB_FONTS: WebFontCheck = () => false;
|
||||
|
||||
function resolvePalette(
|
||||
raw: HostControlRawTokens,
|
||||
defaults: HostControlDefaults,
|
||||
probeColor: ColorProbe,
|
||||
): { accent: RgbColor; background: RgbColor; foreground: RgbColor } {
|
||||
return {
|
||||
accent: parseCssColor(probeColor(raw.accent)) ?? defaults.accent,
|
||||
background: parseCssColor(probeColor(raw.background)) ?? defaults.background,
|
||||
foreground: parseCssColor(probeColor(raw.foreground)) ?? defaults.foreground,
|
||||
};
|
||||
}
|
||||
|
||||
function paletteReadable(palette: { accent: RgbColor; background: RgbColor; foreground: RgbColor }): boolean {
|
||||
return contrastRatio(palette.foreground, palette.background) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST
|
||||
&& contrastRatio(palette.accent, palette.background) >= HOST_CONTROL_MIN_ACCENT_CONTRAST
|
||||
// Primary actions put host-chosen text on the accent; mid-tone accents
|
||||
// where neither black nor white reaches the text floor are rejected.
|
||||
&& contrastRatio(readableOnAccent(palette.accent), palette.accent) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST;
|
||||
}
|
||||
|
||||
function resolveBorder(
|
||||
raw: string | undefined,
|
||||
background: RgbColor,
|
||||
probeColor: ColorProbe,
|
||||
): RgbColor | undefined {
|
||||
const color = parseCssColor(probeColor(raw));
|
||||
return color && contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST ? color : undefined;
|
||||
}
|
||||
|
||||
function readableOnAccent(accent: RgbColor): RgbColor {
|
||||
return contrastRatio(ON_ACCENT_LIGHT, accent) >= contrastRatio(ON_ACCENT_DARK, accent)
|
||||
? ON_ACCENT_LIGHT
|
||||
: ON_ACCENT_DARK;
|
||||
}
|
||||
|
||||
/** True when the skin root declares at least one global or per-part token. */
|
||||
export function hasHostControlTokens(
|
||||
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
|
||||
part: string,
|
||||
): boolean {
|
||||
if (!style) return false;
|
||||
return HOST_CONTROL_TOKEN_NAMES.some((token) =>
|
||||
Boolean(style.getPropertyValue(hostControlTokenProperty(part, token)).trim())
|
||||
|| Boolean(style.getPropertyValue(HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES[token]).trim())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and sanitize the skin token layers from one computed style.
|
||||
*
|
||||
* `--skin-<part-key>-*` wins per token; unset values fall back to
|
||||
* `--skin-host-*`, then to the control's built-in defaults. Colours are
|
||||
* all-or-nothing: if the combined foreground/background/accent palette is
|
||||
* unreadable, the resolver retries the global layer and finally the built-in
|
||||
* palette, so a skin can never make a protected control unreadable. The
|
||||
* border is optional and must stay visible against the resolved background.
|
||||
* Fonts registered by the document (skin `@font-face`) and names carrying the
|
||||
* compiler's scoped skin-font prefix (`ws-`) are ignored.
|
||||
*/
|
||||
export function resolveHostControlTokens(
|
||||
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
|
||||
part: string,
|
||||
probeColor: ColorProbe,
|
||||
defaults: HostControlDefaults,
|
||||
isWebFont: WebFontCheck = NO_WEB_FONTS,
|
||||
): HostControlTokens {
|
||||
const partTokens = readTokenSet(style, (token) => hostControlTokenProperty(part, token));
|
||||
const globalTokens = readTokenSet(style, (token) => HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES[token]);
|
||||
const merged = mergeRawTokens(globalTokens, partTokens);
|
||||
|
||||
let palette = resolvePalette(merged, defaults, probeColor);
|
||||
if (!paletteReadable(palette)) palette = resolvePalette(globalTokens, defaults, probeColor);
|
||||
if (!paletteReadable(palette)) palette = resolvePalette({}, defaults, probeColor);
|
||||
|
||||
const border = resolveBorder(merged.border, palette.background, probeColor)
|
||||
?? resolveBorder(globalTokens.border, palette.background, probeColor)
|
||||
?? defaults.border;
|
||||
|
||||
const sizeValue = merged.size?.trim();
|
||||
const size = isHostControlSizeTier(sizeValue) ? sizeValue : "small";
|
||||
const tierMetrics = (defaults.sizeMetrics ?? HOST_CONTROL_SIZE_METRICS)[size];
|
||||
const hitTarget = Math.max(defaults.hitTarget, tierMetrics.hitTarget);
|
||||
const fontSize = Math.max(defaults.fontSize, tierMetrics.fontSize);
|
||||
const builtInBorder = defaults.builtInButton
|
||||
? contrastRatio(palette.accent, defaults.builtInButton.background) >= HOST_CONTROL_MIN_ACCENT_CONTRAST
|
||||
? palette.accent
|
||||
: defaults.builtInButton.border
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
accent: formatRgb(palette.accent),
|
||||
onAccent: formatRgb(readableOnAccent(palette.accent)),
|
||||
background: formatRgb(palette.background),
|
||||
foreground: formatRgb(palette.foreground),
|
||||
border: formatRgb(border),
|
||||
radius: sanitizeRadius(merged.radius, defaults.radius, defaults.maxRadius),
|
||||
font: sanitizeFont(merged.font, defaults.font, isWebFont),
|
||||
size,
|
||||
hitTarget,
|
||||
fontSize,
|
||||
...(builtInBorder ? { builtInBorder: formatRgb(builtInBorder) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Apply (or clear) host-owned variables on the control inside the shadow root. */
|
||||
export function applyHostControlTokens(control: HTMLElement, tokens: HostControlTokens | null): void {
|
||||
const style = control.style;
|
||||
for (const property of Object.values(HOST_CONTROL_APPLIED_VARIABLES)) style.removeProperty(property);
|
||||
if (!tokens) return;
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.accent, tokens.accent);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.onAccent, tokens.onAccent);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.background, tokens.background);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.foreground, tokens.foreground);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.border, tokens.border);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.font, tokens.font);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.hitTarget, `${tokens.hitTarget}px`);
|
||||
style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`);
|
||||
if (tokens.builtInBorder) style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder);
|
||||
}
|
||||
|
||||
export interface HostControlThemeBindingOptions {
|
||||
layer: HostOwnedLayer;
|
||||
/** The host-owned element whose inline `--ws-control-*` variables are set. */
|
||||
control: () => HTMLElement | null;
|
||||
part: string;
|
||||
defaults: HostControlDefaults;
|
||||
/** The active skin root (or a slot anchor) to read token values from. */
|
||||
source: () => Element | null;
|
||||
/**
|
||||
* When this returns false another owner (the recovery slot binding) is
|
||||
* writing the control's tokens, so `apply()` leaves them untouched.
|
||||
*/
|
||||
active?: () => boolean;
|
||||
}
|
||||
|
||||
export interface HostControlThemeBinding {
|
||||
apply(): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind one host-owned control to the active skin's token set. The returned
|
||||
* binding owns the hidden probe and never stores a token value on the skin
|
||||
* side. Callers re-apply it when the active skin or the control changes; the
|
||||
* binding also re-applies itself when stylesheets in `<head>` or the document
|
||||
* root attributes change, because a stored skin id is known before its CSS
|
||||
* (and therefore its tokens) has been injected, and on viewport resize, because
|
||||
* tokens may be declared inside `@media`.
|
||||
*/
|
||||
export function bindHostControlTheme(options: HostControlThemeBindingOptions): HostControlThemeBinding {
|
||||
let probe: HostControlProbe | null = null;
|
||||
let observer: MutationObserver | null = null;
|
||||
const doc = options.layer.shadow.ownerDocument;
|
||||
const win = doc.defaultView;
|
||||
|
||||
// MutationObserver already batches a burst of changes into one callback.
|
||||
// Frames are avoided on purpose: they do not run in background tabs.
|
||||
if (win && typeof win.MutationObserver === "function") {
|
||||
observer = new win.MutationObserver(() => binding.apply());
|
||||
observer.observe(doc.head, { childList: true, subtree: true, characterData: true });
|
||||
observer.observe(doc.documentElement, { attributes: true });
|
||||
}
|
||||
// Tokens declared inside `@media` change with the viewport, not the DOM.
|
||||
const onResize = (): void => binding.apply();
|
||||
win?.addEventListener("resize", onResize, { passive: true });
|
||||
|
||||
const binding: HostControlThemeBinding = {
|
||||
apply() {
|
||||
if (options.active && !options.active()) return;
|
||||
const control = options.control();
|
||||
if (!control) return;
|
||||
const source = options.source();
|
||||
const view = source?.ownerDocument.defaultView;
|
||||
if (!source || !view) {
|
||||
applyHostControlTokens(control, null);
|
||||
return;
|
||||
}
|
||||
const style = view.getComputedStyle(source);
|
||||
// No token declaration keeps the control's built-in CSS fallback.
|
||||
if (!hasHostControlTokens(style, options.part)) {
|
||||
applyHostControlTokens(control, null);
|
||||
return;
|
||||
}
|
||||
probe ??= createHostControlProbe(options.layer.shadow);
|
||||
applyHostControlTokens(
|
||||
control,
|
||||
resolveHostControlTokens(style, options.part, probe.probeColor, options.defaults, probe.isWebFont),
|
||||
);
|
||||
},
|
||||
dispose() {
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
win?.removeEventListener("resize", onResize);
|
||||
probe?.dispose();
|
||||
probe = null;
|
||||
},
|
||||
};
|
||||
return binding;
|
||||
}
|
||||
|
||||
/** The active skin root; the token source for controls without a slot anchor. */
|
||||
export function findSkinRoot(skinId: string | undefined, doc: Document = document): Element | null {
|
||||
for (const root of doc.querySelectorAll(".ws-skin-root")) {
|
||||
if (!skinId || root.getAttribute("data-ws-skin") === skinId) return root;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface HostControlProbe {
|
||||
/** Resolve a CSS colour through the browser, inside the closed shadow root. */
|
||||
probeColor(raw: string | undefined): string | undefined;
|
||||
/** True when `family` (lower-cased, unquoted) comes from a document `@font-face`. */
|
||||
isWebFont(family: string): boolean;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hidden probe for resolving arbitrary CSS colour syntax (for example
|
||||
* `color-mix()` or `oklch()`) to a concrete `rgb()` value, and for spotting
|
||||
* fonts that a skin registered itself.
|
||||
*/
|
||||
export function createHostControlProbe(shadow: ShadowRoot): HostControlProbe {
|
||||
const doc = shadow.ownerDocument;
|
||||
const win = doc.defaultView;
|
||||
let canvas: CanvasRenderingContext2D | null | undefined;
|
||||
const element = doc.createElement("span");
|
||||
element.setAttribute("aria-hidden", "true");
|
||||
element.style.cssText = "position:absolute;left:-9999px;top:0;width:0;height:0;visibility:hidden;pointer-events:none;";
|
||||
shadow.append(element);
|
||||
|
||||
const resolveWith = (raw: string, sentinel: string): string | undefined => {
|
||||
if (!win) return undefined;
|
||||
// An invalid value leaves the previous colour in place. Probe against two
|
||||
// different sentinels so a real token equal to one of them still resolves.
|
||||
element.style.color = sentinel;
|
||||
element.style.color = raw;
|
||||
return win.getComputedStyle(element).color;
|
||||
};
|
||||
|
||||
/**
|
||||
* Browsers serialise `oklch()`, `lab()` and most `color-mix()` results in
|
||||
* their own colour space instead of `rgb()`. Paint those into a 1×1 canvas
|
||||
* to get sRGB channels the contrast check understands.
|
||||
*/
|
||||
const toRgb = (computed: string): string | undefined => {
|
||||
if (parseCssColor(computed)) return computed;
|
||||
if (canvas === undefined) {
|
||||
canvas = doc.createElement("canvas").getContext("2d", { willReadFrequently: true });
|
||||
if (canvas) canvas.canvas.width = canvas.canvas.height = 1;
|
||||
}
|
||||
if (!canvas) return undefined;
|
||||
canvas.clearRect(0, 0, 1, 1);
|
||||
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 });
|
||||
};
|
||||
|
||||
return {
|
||||
probeColor(raw) {
|
||||
if (!raw) return undefined;
|
||||
const first = resolveWith(raw, "rgb(1, 2, 3)");
|
||||
if (first !== "rgb(1, 2, 3)") return first === undefined ? undefined : toRgb(first);
|
||||
const second = resolveWith(raw, "rgb(4, 5, 6)");
|
||||
return second === undefined || second === "rgb(4, 5, 6)" ? undefined : toRgb(second);
|
||||
},
|
||||
isWebFont(family) {
|
||||
const fonts = doc.fonts;
|
||||
if (!fonts) return false;
|
||||
let found = false;
|
||||
fonts.forEach((face) => {
|
||||
if (!found && fontFamilyNames(face.family).includes(family)) found = true;
|
||||
});
|
||||
return found;
|
||||
},
|
||||
dispose() {
|
||||
element.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
FLOATING_WEIGHT_CONTROL,
|
||||
FLOATING_WEIGHT_DIALOG,
|
||||
FLOATING_WEIGHT_PROTECTED,
|
||||
FLOATING_WEIGHT_POINTER,
|
||||
chooseFloatingPosition,
|
||||
floatingRect,
|
||||
shouldFold,
|
||||
floatingScore,
|
||||
reachableThrough,
|
||||
type FloatingObstacle,
|
||||
} from "./host-floating-placement.js";
|
||||
import type { HostPartRect } from "./host-chrome-visibility.js";
|
||||
|
||||
const rect = (left: number, top: number, width: number, height: number): HostPartRect => ({
|
||||
left, top, width, height, right: left + width, bottom: top + height,
|
||||
});
|
||||
const viewport = { width: 1280, height: 800 };
|
||||
const margins = { top: 12, right: 12, bottom: 38, left: 12 };
|
||||
const capsule = { width: 200, height: 38 };
|
||||
|
||||
test("floating rects follow the corner margins and stay inside the viewport", () => {
|
||||
assert.deepEqual(floatingRect("bottom-left", capsule, viewport, margins), rect(12, 724, 200, 38));
|
||||
assert.deepEqual(floatingRect("bottom-right", capsule, viewport, margins), rect(1068, 724, 200, 38));
|
||||
assert.deepEqual(floatingRect("top-left", capsule, viewport, margins), rect(12, 12, 200, 38));
|
||||
assert.deepEqual(floatingRect("middle-right", capsule, viewport, margins), rect(1068, 381, 200, 38));
|
||||
assert.deepEqual(floatingRect("bottom-center", capsule, viewport, margins), rect(540, 724, 200, 38));
|
||||
// A control wider than a phone viewport is clamped to x = 0, never off-screen.
|
||||
const narrow = floatingRect("bottom-right", { width: 500, height: 38 }, { width: 390, height: 844 }, margins);
|
||||
assert.equal(narrow.left, 0);
|
||||
assert.ok(narrow.bottom <= 844);
|
||||
});
|
||||
|
||||
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);
|
||||
assert.equal(floatingScore(footprint, [{ rect: rect(211, 724, 40, 38), weight: 1 }]), 0);
|
||||
const control = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_CONTROL }]);
|
||||
const protectedPart = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_PROTECTED }]);
|
||||
const dialog = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_DIALOG }]);
|
||||
assert.ok(control > 0 && dialog > control && protectedPart > dialog);
|
||||
});
|
||||
|
||||
test("the default corner is kept while it is free", () => {
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles: [] });
|
||||
assert.deepEqual(choice, { position: "bottom-left", score: 0 });
|
||||
});
|
||||
|
||||
test("a free capsule away from home goes back once the default corner is free, but not while home is busy or under the pointer", () => {
|
||||
// Left the voice page: the spot picked there is free, and so is home.
|
||||
const back = chooseFloatingPosition({ current: "middle-right", size: capsule, viewport, margins, obstacles: [], home: "bottom-left" });
|
||||
assert.deepEqual(back, { position: "bottom-left", score: 0 });
|
||||
// Home still covers the microphone: stay put (no flapping).
|
||||
const busy = chooseFloatingPosition({ current: "middle-right", size: capsule, viewport, margins, obstacles: [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_PROTECTED }], home: "bottom-left" });
|
||||
assert.equal(busy.position, "middle-right");
|
||||
// The pointer rests on home: do not jump under it.
|
||||
const pointer: FloatingObstacle = { rect: rect(84, 727, 32, 32), weight: FLOATING_WEIGHT_POINTER };
|
||||
const underPointer = chooseFloatingPosition({ current: "middle-right", size: capsule, viewport, margins, obstacles: [], moveObstacles: [pointer], home: "bottom-left" });
|
||||
assert.equal(underPointer.position, "middle-right");
|
||||
});
|
||||
|
||||
test("a capsule over the microphone moves to the first free corner", () => {
|
||||
// Persona-style dock: microphone at x≈226 under the default capsule.
|
||||
const obstacles: FloatingObstacle[] = [
|
||||
{ rect: rect(209, 738, 34, 34), weight: FLOATING_WEIGHT_PROTECTED },
|
||||
// Something in the bottom-right corner too (chat composer send button).
|
||||
{ rect: rect(1200, 730, 40, 40), weight: FLOATING_WEIGHT_CONTROL },
|
||||
];
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles });
|
||||
assert.equal(choice.position, "top-left");
|
||||
assert.equal(choice.score, 0);
|
||||
});
|
||||
|
||||
test("when every position collides, the least harmful one wins and dialogs dominate", () => {
|
||||
const mobile = { width: 390, height: 844 };
|
||||
const wide = { width: 250, height: 38 };
|
||||
// Bottom sheet: Cancel (left) and Enter (right) inside a dialog; header
|
||||
// controls at the top are ordinary controls.
|
||||
const obstacles: FloatingObstacle[] = [
|
||||
{ rect: rect(20, 780, 190, 44), weight: FLOATING_WEIGHT_DIALOG },
|
||||
{ rect: rect(228, 780, 140, 44), weight: FLOATING_WEIGHT_DIALOG },
|
||||
{ rect: rect(0, 0, 390, 70), weight: FLOATING_WEIGHT_CONTROL },
|
||||
{ rect: rect(0, 380, 390, 90), weight: FLOATING_WEIGHT_CONTROL },
|
||||
];
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: wide, viewport: mobile, margins, obstacles });
|
||||
assert.ok(!choice.position.startsWith("bottom"), choice.position);
|
||||
assert.ok(choice.score > 0 && choice.score < FLOATING_WEIGHT_DIALOG);
|
||||
});
|
||||
|
||||
test("ties keep the current position (no flapping between equal corners)", () => {
|
||||
const obstacles: FloatingObstacle[] = [{ rect: rect(0, 0, 1280, 800), weight: 1 }];
|
||||
const choice = chooseFloatingPosition({ current: "top-right", size: capsule, viewport, margins, obstacles });
|
||||
assert.equal(choice.position, "top-right");
|
||||
});
|
||||
|
||||
test("a move never lands on the pointer or the focused control, but the current spot is not pushed by them", () => {
|
||||
// Default corner covers the microphone; top-left would be free but the
|
||||
// pointer rests there, so the capsule takes another free spot.
|
||||
const obstacles: FloatingObstacle[] = [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_PROTECTED }];
|
||||
const pointer: FloatingObstacle = { rect: rect(84, 15, 32, 32), weight: FLOATING_WEIGHT_POINTER };
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles, moveObstacles: [pointer] });
|
||||
assert.notEqual(choice.position, "top-left");
|
||||
assert.equal(choice.score, 0);
|
||||
// A pointer next to (or on) a collision-free capsule never makes it move.
|
||||
const stay = chooseFloatingPosition({ current: "top-left", size: capsule, viewport, margins, obstacles: [], moveObstacles: [pointer] });
|
||||
assert.equal(stay.position, "top-left");
|
||||
});
|
||||
|
||||
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 });
|
||||
const reduced = chooseFloatingPosition({ current: full.position, size: { width: 38, height: 38 }, viewport, margins, obstacles: backdrop });
|
||||
assert.ok(full.score > 0 && reduced.score < full.score);
|
||||
assert.equal(shouldFold(full, reduced), false);
|
||||
// Freeing a real control (score drops by at least 0.25 × weight) folds.
|
||||
assert.equal(shouldFold({ position: "bottom-left", score: 1.25 }, { position: "bottom-left", score: 0 }), true);
|
||||
assert.equal(shouldFold({ position: "bottom-left", score: 0.35 }, { position: "bottom-left", score: 0 }), true);
|
||||
assert.equal(shouldFold({ position: "bottom-left", score: 0 }, { position: "bottom-left", score: 0 }), false);
|
||||
});
|
||||
|
||||
test("safe-area margins shift the modelled rect exactly like the CSS env() offsets", () => {
|
||||
const insets = { top: 47, right: 0, bottom: 34, left: 0 };
|
||||
const phone = { width: 390, height: 844 };
|
||||
const withInsets = { top: Math.max(12, insets.top), right: Math.max(12, insets.right), bottom: 38 + insets.bottom, left: Math.max(12, insets.left) };
|
||||
// CSS: bottom: calc(38px + env(safe-area-inset-bottom)) -> 844 - 72 - 38.
|
||||
assert.equal(floatingRect("bottom-left", capsule, phone, withInsets).top, 844 - 72 - 38);
|
||||
assert.equal(floatingRect("top-left", capsule, phone, withInsets).top, 47);
|
||||
});
|
||||
|
||||
test("with every spot taken, the capsule covers a dialog button before a protected control", () => {
|
||||
const mobile = { width: 390, height: 844 };
|
||||
const wide = { width: 250, height: 38 };
|
||||
// Dialog buttons everywhere except top-left, where the microphone is.
|
||||
const obstacles: FloatingObstacle[] = [
|
||||
{ rect: rect(0, 0, 270, 60), weight: FLOATING_WEIGHT_PROTECTED },
|
||||
{ rect: rect(120, 0, 270, 60), weight: FLOATING_WEIGHT_DIALOG },
|
||||
{ rect: rect(0, 380, 390, 90), weight: FLOATING_WEIGHT_DIALOG },
|
||||
{ rect: rect(0, 740, 390, 104), weight: FLOATING_WEIGHT_DIALOG },
|
||||
];
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: wide, viewport: mobile, margins, obstacles });
|
||||
const footprint = floatingRect(choice.position, wide, mobile, margins);
|
||||
assert.equal(floatingScore(footprint, [obstacles[0]]), 0, choice.position);
|
||||
});
|
||||
|
||||
test("a toast or the other host control passing over a control does not hide it from the obstacle check", () => {
|
||||
// Stand-ins for elementsFromPoint() results, topmost first.
|
||||
const button = { id: "accompaniment" } as unknown as Element;
|
||||
const icon = { id: "accompaniment-icon" } as unknown as Element;
|
||||
const toast = { id: "toast" } as unknown as Element;
|
||||
const toastText = { id: "toast-text" } as unknown as Element;
|
||||
const otherHost = { id: "library-launcher" } as unknown as Element;
|
||||
const skinLayer = { id: "skin-panel" } as unknown as Element;
|
||||
const backdrop = { id: "modal-backdrop" } as unknown as Element;
|
||||
const isTarget = (element: Element) => element === button || element === icon;
|
||||
const isTransparent = (element: Element) => element === toast || element === toastText || element === otherHost;
|
||||
assert.equal(reachableThrough([icon, button], isTarget, isTransparent), true);
|
||||
// The toast is on top for a moment: the control under it still counts.
|
||||
assert.equal(reachableThrough([toastText, toast, icon, button], isTarget, isTransparent), true);
|
||||
assert.equal(reachableThrough([otherHost, toast, button], isTarget, isTransparent), true);
|
||||
// A skin layer or modal backdrop really hides it (even under a toast).
|
||||
assert.equal(reachableThrough([skinLayer, button], isTarget, isTransparent), false);
|
||||
assert.equal(reachableThrough([toast, backdrop, button], isTarget, isTransparent), false);
|
||||
assert.equal(reachableThrough([toast], isTarget, isTransparent), false);
|
||||
assert.equal(reachableThrough([], isTarget, isTransparent), false);
|
||||
});
|
||||
|
||||
test("a corner whose control is counted (not hidden by a toast) is never chosen as the free default corner", () => {
|
||||
// Library launcher: default bottom-right, parked top-left because the skin's
|
||||
// accompaniment button sits in the bottom-right corner.
|
||||
const launcher = { width: 34, height: 34 };
|
||||
const launcherMargins = { top: 16, right: 16, bottom: 16, left: 16 };
|
||||
const accompaniment = { rect: rect(1218, 738, 34, 34), weight: FLOATING_WEIGHT_PROTECTED };
|
||||
const counted = chooseFloatingPosition({ current: "top-left", size: launcher, viewport, margins: launcherMargins, obstacles: [accompaniment], home: "bottom-right" });
|
||||
assert.equal(counted.position, "top-left");
|
||||
// What 854a488 did while a toast hid the button: the corner looked free.
|
||||
const hidden = chooseFloatingPosition({ current: "top-left", size: launcher, viewport, margins: launcherMargins, obstacles: [], home: "bottom-right" });
|
||||
assert.equal(hidden.position, "bottom-right");
|
||||
});
|
||||
@@ -0,0 +1,591 @@
|
||||
/**
|
||||
* Runtime collision avoidance for host-owned floating controls.
|
||||
*
|
||||
* The recovery capsule (closed-shadow top layer) and the fallback application
|
||||
* library launcher float in a fixed viewport corner. Neither knows the active
|
||||
* skin's layout, so a skin that puts its own audio dock, chat composer or a
|
||||
* dialog's buttons in that corner used to lose those controls under the host
|
||||
* control: v0.3.2 already covered the microphone in the Persona skins, the
|
||||
* whole Harbor audio dock and the "Cancel" button of the mobile channel
|
||||
* password sheet.
|
||||
*
|
||||
* This module never restricts what a skin may do. It samples the skin's
|
||||
* visible interactive controls at runtime and moves the host control to the
|
||||
* candidate position that covers the fewest of them (protected parts and
|
||||
* controls inside an open dialog count more). When every position collides,
|
||||
* the caller may fall back to a compact footprint (only when that frees at
|
||||
* least one control). The host control stays in the viewport and stays
|
||||
* clickable in every position; only its corner changes. It does not move while
|
||||
* hovered or focused, and never moves onto the last pointer position or the
|
||||
* focused control. A control briefly hidden by a toast (or by the other host
|
||||
* floating control) still counts, so a passing toast never makes its corner
|
||||
* look free.
|
||||
*/
|
||||
|
||||
import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import type { HostPartRect } from "./host-chrome-visibility.js";
|
||||
|
||||
export const FLOATING_POSITIONS = [
|
||||
"bottom-left",
|
||||
"bottom-right",
|
||||
"top-left",
|
||||
"top-right",
|
||||
"middle-left",
|
||||
"middle-right",
|
||||
"bottom-center",
|
||||
"top-center",
|
||||
] as const;
|
||||
|
||||
export type FloatingPosition = typeof FLOATING_POSITIONS[number];
|
||||
|
||||
export interface FloatingMargins {
|
||||
top: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
}
|
||||
|
||||
export interface FloatingObstacle {
|
||||
rect: HostPartRect;
|
||||
/** Higher weight = worse to cover (protected part, open dialog, other host control). */
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface FloatingSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface FloatingViewport {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Interval of the runtime re-check while the control is shown. */
|
||||
export const HOST_FLOATING_INTERVAL_MS = 400;
|
||||
/** Extra re-check shortly after a click, which is what usually opens a dialog or sheet. */
|
||||
export const HOST_FLOATING_AFTER_CLICK_MS = 150;
|
||||
/** Obstacle weights. */
|
||||
export const FLOATING_WEIGHT_CONTROL = 1;
|
||||
/** Above dialogs and the other host control: a protected control is the last thing to cover. */
|
||||
export const FLOATING_WEIGHT_PROTECTED = 16;
|
||||
export const FLOATING_WEIGHT_DIALOG = 8;
|
||||
export const FLOATING_WEIGHT_HOST = 8;
|
||||
/** Weight of the user's last pointer position and focused control when moving. */
|
||||
export const FLOATING_WEIGHT_POINTER = 8;
|
||||
/**
|
||||
* Folding to the compact mark must free at least one control's worth of score
|
||||
* (every covered obstacle costs at least `weight × 0.25`). A sliver less of a
|
||||
* viewport-sized click-away layer is not a reason to hide the buttons.
|
||||
*/
|
||||
export const FLOATING_FOLD_MIN_GAIN = 0.25;
|
||||
/**
|
||||
* Anti-flap: a move needs the collision to persist for `MOVE_CONFIRM_MS`, moves
|
||||
* are at least `MOVE_MIN_INTERVAL_MS` apart, and more than `FLAP_MAX_MOVES`
|
||||
* moves within `FLAP_WINDOW_MS` (an animated or hostile skin) park the control
|
||||
* at its default corner for `FLAP_FREEZE_MS`, so it is never a moving target
|
||||
* (one escape per freeze is allowed when that corner covers a control).
|
||||
*/
|
||||
export const HOST_FLOATING_MOVE_CONFIRM_MS = 250;
|
||||
export const HOST_FLOATING_MOVE_MIN_INTERVAL_MS = 1000;
|
||||
export const HOST_FLOATING_FLAP_WINDOW_MS = 10_000;
|
||||
export const HOST_FLOATING_FLAP_MAX_MOVES = 6;
|
||||
export const HOST_FLOATING_FLAP_FREEZE_MS = 10_000;
|
||||
/**
|
||||
* After the screen changes (home <-> voice page, skin switch) the old spot was
|
||||
* chosen for controls that no longer exist, so for this long the control moves
|
||||
* as soon as a sample disagrees, without the confirm delay or minimum interval.
|
||||
*/
|
||||
export const HOST_FLOATING_SCREEN_CHANGE_MS = 1500;
|
||||
/** Re-samples after a screen change (the new screen renders over a few frames). */
|
||||
export const HOST_FLOATING_SCREEN_CHANGE_SAMPLES_MS = [0, 120, 400, 900] as const;
|
||||
/** Parts that wrap ordinary controls; a control inside them is not "protected" by that alone. */
|
||||
const CONTAINER_PARTS: ReadonlySet<string> = new Set(["app", "home.footer"]);
|
||||
/** Radius around the last pointer position that a move must not land on. */
|
||||
const POINTER_RADIUS = 16;
|
||||
|
||||
/** Rect a control of `size` would occupy at `position`. */
|
||||
export function floatingRect(
|
||||
position: FloatingPosition,
|
||||
size: FloatingSize,
|
||||
viewport: FloatingViewport,
|
||||
margins: FloatingMargins,
|
||||
): HostPartRect {
|
||||
const width = Math.max(0, size.width);
|
||||
const height = Math.max(0, size.height);
|
||||
let left: number;
|
||||
if (position.endsWith("left")) left = margins.left;
|
||||
else if (position.endsWith("right")) left = viewport.width - margins.right - width;
|
||||
else left = (viewport.width - width) / 2;
|
||||
let top: number;
|
||||
if (position.startsWith("top")) top = margins.top;
|
||||
else if (position.startsWith("bottom")) top = viewport.height - margins.bottom - height;
|
||||
else top = (viewport.height - height) / 2;
|
||||
// Never leave the viewport, even on a viewport narrower than the control.
|
||||
left = Math.max(0, Math.min(left, viewport.width - width));
|
||||
top = Math.max(0, Math.min(top, viewport.height - height));
|
||||
return { left, top, width, height, right: left + width, bottom: top + height };
|
||||
}
|
||||
|
||||
function overlapArea(first: HostPartRect, second: HostPartRect): number {
|
||||
const width = Math.min(first.right, second.right) - Math.max(first.left, second.left);
|
||||
const height = Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top);
|
||||
// A one-pixel brush (shadow, border) is not a collision.
|
||||
return width > 1 && height > 1 ? width * height : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collision score of a footprint: for every obstacle, the covered fraction of
|
||||
* that obstacle times its weight. Zero means nothing interactive is covered.
|
||||
*/
|
||||
export function floatingScore(footprint: HostPartRect, obstacles: readonly FloatingObstacle[]): number {
|
||||
let score = 0;
|
||||
for (const obstacle of obstacles) {
|
||||
const area = obstacle.rect.width * obstacle.rect.height;
|
||||
if (!(area > 0)) continue;
|
||||
const covered = overlapArea(footprint, obstacle.rect);
|
||||
if (covered > 0) score += obstacle.weight * Math.min(1, covered / area + 0.25);
|
||||
}
|
||||
return score;
|
||||
}
|
||||
|
||||
export interface FloatingChoice {
|
||||
position: FloatingPosition;
|
||||
score: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep `current` while it is collision-free; otherwise take the position with
|
||||
* the lowest score. Ties keep `current`, then follow `FLOATING_POSITIONS`
|
||||
* order. When `home` (the default corner) is given and both it and `current`
|
||||
* are free, go back home: a spot picked for one screen must not linger over
|
||||
* controls that appear on the next one (e.g. after leaving the voice page).
|
||||
* The binding passes `home` only right after a screen change: on the same
|
||||
* screen a free-looking default corner may just be hidden for a moment (a
|
||||
* 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.
|
||||
*/
|
||||
export function chooseFloatingPosition(input: {
|
||||
current: FloatingPosition;
|
||||
size: FloatingSize;
|
||||
viewport: FloatingViewport;
|
||||
margins: FloatingMargins;
|
||||
obstacles: readonly FloatingObstacle[];
|
||||
moveObstacles?: readonly FloatingObstacle[];
|
||||
positions?: readonly FloatingPosition[];
|
||||
home?: FloatingPosition;
|
||||
}): FloatingChoice {
|
||||
const positions = input.positions ?? FLOATING_POSITIONS;
|
||||
const moveObstacles = input.moveObstacles ?? [];
|
||||
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 currentScore = scoreAt(input.current);
|
||||
if (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 };
|
||||
for (const position of positions) {
|
||||
if (position === input.current) continue;
|
||||
const score = scoreAt(position);
|
||||
if (score < best.score - 1e-6) best = { position, score };
|
||||
if (best.score === 0) break;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Fold to the compact mark only when that frees at least one control's worth. */
|
||||
export function shouldFold(full: FloatingChoice, reduced: FloatingChoice): boolean {
|
||||
return full.score > 0 && reduced.score <= full.score - FLOATING_FOLD_MIN_GAIN + 1e-6;
|
||||
}
|
||||
|
||||
/** Margins of a floating control: its own spacing plus the device safe area. */
|
||||
export function readSafeAreaInsets(parent: Node & ParentNode): FloatingMargins {
|
||||
const zero = { top: 0, right: 0, bottom: 0, left: 0 };
|
||||
const doc = parent.ownerDocument ?? (parent as unknown as Document);
|
||||
const view = doc?.defaultView;
|
||||
if (!view) return zero;
|
||||
const probe = doc.createElement("span");
|
||||
probe.setAttribute("aria-hidden", "true");
|
||||
probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none;width:0;height:0;overflow:hidden;"
|
||||
+ "padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)";
|
||||
parent.appendChild(probe);
|
||||
try {
|
||||
const style = view.getComputedStyle(probe);
|
||||
const read = (value: string) => Math.max(0, Number.parseFloat(value) || 0);
|
||||
return { top: read(style.paddingTop), right: read(style.paddingRight), bottom: read(style.paddingBottom), left: read(style.paddingLeft) };
|
||||
} finally {
|
||||
probe.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function rectsIntersect(first: HostPartRect, second: HostPartRect): boolean {
|
||||
return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* DOM binding
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
const INTERACTIVE_SELECTOR = "a[href],button,input:not([type='hidden']),select,textarea,summary,iframe,audio[controls],video[controls],"
|
||||
+ "[role='button'],[role='tab'],[role='menuitem'],[role='link'],[role='option'],[role='switch'],[role='checkbox'],[role='radio'],"
|
||||
+ "[contenteditable='true'],[tabindex]:not([tabindex='-1'])";
|
||||
const DIALOG_SELECTOR = "dialog[open],[role='dialog'],[role='alertdialog'],[aria-modal='true']";
|
||||
/**
|
||||
* Transient layers that float over the skin for a moment (the app toast). A
|
||||
* control under one is still there a second later, so it keeps counting as an
|
||||
* obstacle: otherwise a toast passing over a corner makes that corner look
|
||||
* free and the host control jumps onto the control the toast was covering.
|
||||
*/
|
||||
const TRANSIENT_OVERLAY_SELECTOR = "[data-ws-part='app.toast']";
|
||||
|
||||
/** Live host floating controls, so they also avoid each other. */
|
||||
const registry = new Set<{ owner: Element; isSelf: (element: Element) => boolean; rect: () => HostPartRect | null }>();
|
||||
|
||||
/**
|
||||
* Whether a control is the topmost thing at a point once see-through layers
|
||||
* are skipped. `stack` is `elementsFromPoint` (topmost first); `isTarget` is
|
||||
* the control (or the floating control being placed, which is the collision
|
||||
* we want to resolve); `isTransparent` marks transient overlays and the other
|
||||
* host floating controls, which do not hide a control from this check.
|
||||
*/
|
||||
export function reachableThrough(
|
||||
stack: readonly Element[],
|
||||
isTarget: (element: Element) => boolean,
|
||||
isTransparent: (element: Element) => boolean,
|
||||
): boolean {
|
||||
for (const element of stack) {
|
||||
if (isTarget(element)) return true;
|
||||
if (!isTransparent(element)) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function toRect(rect: DOMRect | HostPartRect): HostPartRect {
|
||||
return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, right: rect.right, bottom: rect.bottom };
|
||||
}
|
||||
|
||||
/**
|
||||
* Visible, topmost interactive controls of the page (outside `self`). A control
|
||||
* hidden under the host control itself still counts: that is the collision we
|
||||
* want to resolve. A control hidden under a modal backdrop does not.
|
||||
*/
|
||||
export function collectFloatingObstacles(options: {
|
||||
doc: Document;
|
||||
/** Elements that belong to the floating control (light DOM wrapper or layer host). */
|
||||
isSelf: (element: Element) => boolean;
|
||||
owner: Element;
|
||||
/**
|
||||
* Only controls intersecting one of these rects can change a score; others
|
||||
* skip the style read and hit test (keeps a 3 000-control skin cheap).
|
||||
*/
|
||||
regions?: readonly HostPartRect[];
|
||||
}): FloatingObstacle[] {
|
||||
const { doc, isSelf, owner, regions } = options;
|
||||
const view = doc.defaultView;
|
||||
if (!view) return [];
|
||||
const obstacles: FloatingObstacle[] = [];
|
||||
const viewportWidth = view.innerWidth;
|
||||
const viewportHeight = view.innerHeight;
|
||||
const otherEntries = [...registry].filter(entry => entry.owner !== owner);
|
||||
const others = otherEntries.map(entry => entry.owner);
|
||||
const transparent = (element: Element) => element.closest(TRANSIENT_OVERLAY_SELECTOR) !== null
|
||||
|| otherEntries.some(entry => entry.isSelf(element));
|
||||
const stackAt = (x: number, y: number): Element[] => {
|
||||
if (typeof doc.elementsFromPoint === "function") return doc.elementsFromPoint(x, y);
|
||||
const hit = doc.elementFromPoint(x, y);
|
||||
return hit ? [hit] : [];
|
||||
};
|
||||
for (const element of doc.querySelectorAll<HTMLElement>(INTERACTIVE_SELECTOR)) {
|
||||
if (isSelf(element)) continue;
|
||||
// Another host floating control is added once below, with its own weight.
|
||||
if (others.some(other => other.contains(element))) continue;
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.width < 2 || rect.height < 2) continue;
|
||||
if (rect.right <= 0 || rect.bottom <= 0 || rect.left >= viewportWidth || rect.top >= viewportHeight) continue;
|
||||
if (regions && !regions.some(region => rectsIntersect(region, rect))) continue;
|
||||
// Invisible (opacity 0 / visibility hidden) controls cannot be covered.
|
||||
if (typeof element.checkVisibility === "function"
|
||||
&& !element.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue;
|
||||
const style = view.getComputedStyle(element);
|
||||
if (style.visibility === "hidden" || style.visibility === "collapse" || style.pointerEvents === "none") continue;
|
||||
// Disabled controls still count: a "Send" button is disabled only until the
|
||||
// user types, and the host control must not sit on it either way.
|
||||
const x = Math.min(Math.max(rect.left + rect.width / 2, 0), viewportWidth - 1);
|
||||
const y = Math.min(Math.max(rect.top + rect.height / 2, 0), viewportHeight - 1);
|
||||
// Look through toasts and the other host floating control: what they hide
|
||||
// now is back in a moment. A modal backdrop or a skin layer still hides it.
|
||||
const isTarget = (hit: Element) => hit === element || element.contains(hit) || isSelf(hit);
|
||||
if (!reachableThrough(stackAt(x, y), isTarget, transparent)) continue;
|
||||
const part = element.closest("[data-ws-part]")?.getAttribute("data-ws-part") ?? "";
|
||||
const protectedPart = PROTECTED_PART_IDS.has(part) && !CONTAINER_PARTS.has(part);
|
||||
const weight = protectedPart
|
||||
? FLOATING_WEIGHT_PROTECTED
|
||||
: element.closest(DIALOG_SELECTOR) ? FLOATING_WEIGHT_DIALOG : FLOATING_WEIGHT_CONTROL;
|
||||
obstacles.push({ rect: toRect(rect), weight });
|
||||
}
|
||||
for (const entry of registry) {
|
||||
if (entry.owner === owner) continue;
|
||||
const rect = entry.rect();
|
||||
if (rect && rect.width > 0 && rect.height > 0) obstacles.push({ rect, weight: FLOATING_WEIGHT_HOST });
|
||||
}
|
||||
return obstacles;
|
||||
}
|
||||
|
||||
export interface FloatingAvoidanceOptions {
|
||||
/** The floating element whose box is measured. */
|
||||
element: HTMLElement;
|
||||
/** Element that identifies "self" for hit tests (layer host or the element). */
|
||||
isSelf: (element: Element) => boolean;
|
||||
/**
|
||||
* Fixed margins, or margins derived from the device safe-area insets (the
|
||||
* CSS positions the control with `env(safe-area-inset-*)`, so the model must
|
||||
* use the same numbers). Insets are re-read on bind and on resize.
|
||||
*/
|
||||
margins: FloatingMargins | ((insets: FloatingMargins) => FloatingMargins);
|
||||
/** Where the safe-area probe is inserted (the control's shadow root or element). */
|
||||
insetsParent?: Node & ParentNode;
|
||||
defaultPosition?: FloatingPosition;
|
||||
/** Apply a position (attribute/class on the element; never inline skin styles). */
|
||||
apply: (position: FloatingPosition) => void;
|
||||
/** Optional smaller footprint used when every full-size position collides. */
|
||||
compactSize?: () => FloatingSize | null;
|
||||
onCompactChange?: (compact: boolean) => void;
|
||||
/** Skip re-evaluation (hovered, focused, slotted, drawer open…). */
|
||||
paused?: () => boolean;
|
||||
}
|
||||
|
||||
export interface FloatingAvoidance {
|
||||
revalidate(): void;
|
||||
/**
|
||||
* The page behind the control changed (route/view or skin switch): drop any
|
||||
* pending confirmation and re-place promptly instead of keeping a spot that
|
||||
* was picked for the previous screen.
|
||||
*/
|
||||
screenChanged(): void;
|
||||
readonly position: FloatingPosition;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): FloatingAvoidance {
|
||||
const { element, isSelf, apply, onCompactChange } = options;
|
||||
const doc = element.ownerDocument;
|
||||
const view = doc.defaultView;
|
||||
const defaultPosition = options.defaultPosition ?? "bottom-left";
|
||||
let position: FloatingPosition = defaultPosition;
|
||||
let compact = false;
|
||||
let fullSize: FloatingSize = { width: 0, height: 0 };
|
||||
let disposed = false;
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
let lastViewport = { width: 0, height: 0 };
|
||||
let margins: FloatingMargins = { top: 0, right: 0, bottom: 0, left: 0 };
|
||||
let pointer: { x: number; y: number } | null = null;
|
||||
let pendingSince = 0;
|
||||
let lastMoveAt = Number.NEGATIVE_INFINITY;
|
||||
let frozenUntil = 0;
|
||||
let frozenEscaped = false;
|
||||
let moveTimes: number[] = [];
|
||||
let confirmTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let urgentUntil = 0;
|
||||
let screenTimers: ReturnType<typeof setTimeout>[] = [];
|
||||
function scheduleConfirm(delay: number) {
|
||||
if (confirmTimer) clearTimeout(confirmTimer);
|
||||
confirmTimer = setTimeout(() => { confirmTimer = undefined; safeEvaluate(); }, Math.max(0, delay) + 20);
|
||||
}
|
||||
function refreshMargins() {
|
||||
const spec = options.margins;
|
||||
if (typeof spec !== "function") { margins = spec; return; }
|
||||
let insets = { top: 0, right: 0, bottom: 0, left: 0 };
|
||||
try { insets = readSafeAreaInsets(options.insetsParent ?? element); } catch { /* keep zero insets */ }
|
||||
margins = spec(insets);
|
||||
}
|
||||
refreshMargins();
|
||||
const entry = {
|
||||
owner: element as Element,
|
||||
isSelf,
|
||||
rect: () => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0 ? toRect(rect) : null;
|
||||
},
|
||||
};
|
||||
registry.add(entry);
|
||||
apply(position);
|
||||
|
||||
function setCompact(next: boolean) {
|
||||
if (compact === next) return;
|
||||
compact = next;
|
||||
onCompactChange?.(next);
|
||||
}
|
||||
|
||||
function evaluate() {
|
||||
if (disposed || !view) return;
|
||||
if (options.paused?.()) return;
|
||||
const box = element.getBoundingClientRect();
|
||||
if (!(box.width > 0) || !(box.height > 0)) return;
|
||||
const viewport = { width: view.innerWidth, height: view.innerHeight };
|
||||
if (viewport.width !== lastViewport.width || viewport.height !== lastViewport.height) {
|
||||
// Rotation / resize: re-read the safe area and forget the old footprint.
|
||||
lastViewport = viewport;
|
||||
fullSize = { width: 0, height: 0 };
|
||||
refreshMargins();
|
||||
}
|
||||
// Score with the expanded footprint the user sees on hover/focus: the live
|
||||
// size while expanded (it follows language changes), the last expanded
|
||||
// size while folded.
|
||||
if (!compact) fullSize = { width: box.width, height: box.height };
|
||||
const size = fullSize.width > 0 ? fullSize : { width: box.width, height: box.height };
|
||||
const small = options.compactSize?.() ?? null;
|
||||
const regions: HostPartRect[] = [];
|
||||
for (const candidate of FLOATING_POSITIONS) {
|
||||
regions.push(floatingRect(candidate, size, viewport, margins));
|
||||
if (small && small.width > 0 && small.height > 0) regions.push(floatingRect(candidate, small, viewport, margins));
|
||||
}
|
||||
const obstacles = collectFloatingObstacles({ doc, isSelf, owner: element, regions });
|
||||
const moveObstacles: FloatingObstacle[] = [];
|
||||
if (pointer) {
|
||||
moveObstacles.push({ rect: { left: pointer.x - POINTER_RADIUS, top: pointer.y - POINTER_RADIUS, width: POINTER_RADIUS * 2, height: POINTER_RADIUS * 2, right: pointer.x + POINTER_RADIUS, bottom: pointer.y + POINTER_RADIUS }, weight: FLOATING_WEIGHT_POINTER });
|
||||
}
|
||||
const focused = doc.activeElement;
|
||||
if (focused && focused !== doc.body && focused !== doc.documentElement && !isSelf(focused)) {
|
||||
const rect = focused.getBoundingClientRect();
|
||||
if (rect.width > 0 && rect.height > 0) moveObstacles.push({ rect: toRect(rect), weight: FLOATING_WEIGHT_POINTER });
|
||||
}
|
||||
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 });
|
||||
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 });
|
||||
if (shouldFold(full, reduced)) {
|
||||
next = reduced;
|
||||
nextCompact = true;
|
||||
}
|
||||
}
|
||||
if (next.position === position && nextCompact === compact) {
|
||||
pendingSince = 0;
|
||||
return;
|
||||
}
|
||||
const frozen = now < frozenUntil;
|
||||
if (frozen) {
|
||||
// Frozen at the default corner: hold still, except one escape per
|
||||
// freeze when the parked spot covers a control and the move frees some
|
||||
// of it (e.g. a toast hid that control when the control was parked).
|
||||
const parked = floatingRect(position, compact && small ? small : size, viewport, margins);
|
||||
const parkedScore = floatingScore(parked, obstacles);
|
||||
if (frozenEscaped || !(parkedScore > 0 && next.score < parkedScore - 1e-6)) return;
|
||||
}
|
||||
if (!urgent && !pendingSince) {
|
||||
pendingSince = now;
|
||||
scheduleConfirm(HOST_FLOATING_MOVE_CONFIRM_MS);
|
||||
return;
|
||||
}
|
||||
if (!urgent && now - pendingSince < HOST_FLOATING_MOVE_CONFIRM_MS) {
|
||||
scheduleConfirm(HOST_FLOATING_MOVE_CONFIRM_MS - (now - pendingSince));
|
||||
return;
|
||||
}
|
||||
if (!urgent && now - lastMoveAt < HOST_FLOATING_MOVE_MIN_INTERVAL_MS) {
|
||||
scheduleConfirm(HOST_FLOATING_MOVE_MIN_INTERVAL_MS - (now - lastMoveAt));
|
||||
return;
|
||||
}
|
||||
pendingSince = 0;
|
||||
lastMoveAt = now;
|
||||
if (frozen) {
|
||||
// The escape does not count as flapping, and is the only one until the freeze ends.
|
||||
frozenEscaped = true;
|
||||
if (next.position !== position) {
|
||||
position = next.position;
|
||||
apply(position);
|
||||
}
|
||||
setCompact(nextCompact);
|
||||
return;
|
||||
}
|
||||
moveTimes = moveTimes.filter(time => now - time < HOST_FLOATING_FLAP_WINDOW_MS);
|
||||
moveTimes.push(now);
|
||||
if (moveTimes.length > HOST_FLOATING_FLAP_MAX_MOVES) {
|
||||
// Flapping: park at the default corner, expanded, and hold still.
|
||||
moveTimes = [];
|
||||
frozenUntil = now + HOST_FLOATING_FLAP_FREEZE_MS;
|
||||
frozenEscaped = false;
|
||||
if (position !== defaultPosition) {
|
||||
position = defaultPosition;
|
||||
apply(position);
|
||||
}
|
||||
setCompact(false);
|
||||
return;
|
||||
}
|
||||
if (next.position !== position) {
|
||||
position = next.position;
|
||||
apply(position);
|
||||
}
|
||||
setCompact(nextCompact);
|
||||
}
|
||||
|
||||
function safeEvaluate() {
|
||||
try {
|
||||
evaluate();
|
||||
} catch {
|
||||
// A failed sample must never strand the control; return to the default.
|
||||
if (position !== defaultPosition) {
|
||||
position = defaultPosition;
|
||||
apply(position);
|
||||
}
|
||||
setCompact(false);
|
||||
}
|
||||
}
|
||||
|
||||
let clickTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const afterClick = () => {
|
||||
if (clickTimer) clearTimeout(clickTimer);
|
||||
clickTimer = setTimeout(safeEvaluate, HOST_FLOATING_AFTER_CLICK_MS);
|
||||
};
|
||||
const onPointer = (event: PointerEvent) => { pointer = { x: event.clientX, y: event.clientY }; };
|
||||
const onPointerLeave = () => { pointer = null; };
|
||||
if (view) {
|
||||
timer = setInterval(safeEvaluate, HOST_FLOATING_INTERVAL_MS);
|
||||
view.addEventListener("resize", safeEvaluate, { passive: true });
|
||||
doc.addEventListener("click", afterClick, { capture: true, passive: true });
|
||||
// A scrolled list can carry a control under the host control.
|
||||
doc.addEventListener("scroll", afterClick, { capture: true, passive: true });
|
||||
doc.addEventListener("pointermove", onPointer, { capture: true, passive: true });
|
||||
doc.addEventListener("pointerdown", onPointer, { capture: true, passive: true });
|
||||
doc.documentElement.addEventListener("pointerleave", onPointerLeave, { passive: true });
|
||||
}
|
||||
safeEvaluate();
|
||||
|
||||
function screenChanged() {
|
||||
if (disposed) return;
|
||||
for (const pending of screenTimers) clearTimeout(pending);
|
||||
pendingSince = 0;
|
||||
urgentUntil = Date.now() + HOST_FLOATING_SCREEN_CHANGE_MS;
|
||||
screenTimers = HOST_FLOATING_SCREEN_CHANGE_SAMPLES_MS.map(delay => setTimeout(safeEvaluate, delay));
|
||||
}
|
||||
|
||||
return {
|
||||
revalidate: safeEvaluate,
|
||||
screenChanged,
|
||||
get position() { return position; },
|
||||
dispose() {
|
||||
disposed = true;
|
||||
for (const pending of screenTimers) clearTimeout(pending);
|
||||
registry.delete(entry);
|
||||
if (timer) clearInterval(timer);
|
||||
if (clickTimer) clearTimeout(clickTimer);
|
||||
if (confirmTimer) clearTimeout(confirmTimer);
|
||||
view?.removeEventListener("resize", safeEvaluate);
|
||||
doc.removeEventListener("click", afterClick, { capture: true });
|
||||
doc.removeEventListener("scroll", afterClick, { capture: true });
|
||||
doc.removeEventListener("pointermove", onPointer, { capture: true });
|
||||
doc.removeEventListener("pointerdown", onPointer, { capture: true });
|
||||
doc.documentElement.removeEventListener("pointerleave", onPointerLeave);
|
||||
setCompact(false);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
* without the Popover API still shows the UI above ordinary content.
|
||||
*/
|
||||
|
||||
export type HostOwnedLayerName = "recovery" | "authorization";
|
||||
export type HostOwnedLayerName = "recovery" | "authorization" | "skin-load";
|
||||
|
||||
/**
|
||||
* The CSS 32-bit maximum stacking value. A compiled skin may legitimately use
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
INITIAL_SLOT_MODE_STATE,
|
||||
computeSlotPlacement,
|
||||
evaluateSlottedControl,
|
||||
nextSlotModeState,
|
||||
rectsOverlap,
|
||||
type SlotAnchorSnapshot,
|
||||
} from "./host-slot-placement.js";
|
||||
import { HOST_CONTROL_MIN_HIT_TARGET } from "./host-control-tokens.js";
|
||||
import type { HostPartRect } from "./host-chrome-visibility.js";
|
||||
|
||||
const rect = (left: number, top: number, width: number, height: number): HostPartRect => ({
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
});
|
||||
|
||||
const anchor = (overrides: Partial<SlotAnchorSnapshot> = {}): SlotAnchorSnapshot => ({
|
||||
rect: rect(100, 100, 200, 40),
|
||||
display: "flex",
|
||||
visibility: "visible",
|
||||
opacity: "1",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const baseEvaluation = {
|
||||
anchor: anchor(),
|
||||
controlRect: rect(180, 105, 120, 30),
|
||||
viewport: { width: 800, height: 600 },
|
||||
minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
|
||||
hitTestOk: true,
|
||||
};
|
||||
|
||||
test("slot placement aligns inside the anchor and centres vertically", () => {
|
||||
const control = { width: 120, height: 30 };
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport, "start"), { left: 100, top: 105 });
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport, "center"), { left: 140, top: 105 });
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport), { left: 180, top: 105 });
|
||||
assert.deepEqual(computeSlotPlacement(anchor().rect, control, baseEvaluation.viewport, "end"), { left: 180, top: 105 });
|
||||
});
|
||||
|
||||
test("slot placement clamps the control fully inside the viewport", () => {
|
||||
const viewport = { width: 800, height: 600 };
|
||||
const control = { width: 120, height: 30 };
|
||||
// Anchor off the left/top edge: the control stops at the safe inset.
|
||||
assert.deepEqual(computeSlotPlacement(rect(-500, -200, 100, 40), control, viewport, "start"), { left: 4, top: 4 });
|
||||
// Anchor off the right/bottom edge: the control stops before the edge.
|
||||
assert.deepEqual(computeSlotPlacement(rect(900, 700, 100, 40), control, viewport, "end"), { left: 676, top: 566 });
|
||||
// The anchor may be smaller than the control; the control overflows the
|
||||
// anchor but still stays inside the viewport.
|
||||
const tiny = computeSlotPlacement(rect(400, 300, 20, 10), control, viewport, "center");
|
||||
assert.ok(tiny.left >= 4 && tiny.left + control.width <= viewport.width - 4);
|
||||
assert.ok(tiny.top >= 4 && tiny.top + control.height <= viewport.height - 4);
|
||||
});
|
||||
|
||||
test("a usable slotted control passes every check", () => {
|
||||
assert.deepEqual(evaluateSlottedControl(baseEvaluation), { ok: true });
|
||||
});
|
||||
|
||||
test("missing, hidden, tiny and off-screen anchors fall back", () => {
|
||||
assert.deepEqual(evaluateSlottedControl({ ...baseEvaluation, anchor: null }), { ok: false, reason: "anchor-missing" });
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ display: "none" }) }),
|
||||
{ ok: false, reason: "anchor-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ visibility: "hidden" }) }),
|
||||
{ ok: false, reason: "anchor-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ opacity: "0" }) }),
|
||||
{ ok: false, reason: "anchor-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ rect: rect(100, 100, 4, 4) }) }),
|
||||
{ ok: false, reason: "anchor-tiny" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ rect: rect(-500, -500, 100, 40) }) }),
|
||||
{ ok: false, reason: "anchor-offscreen" },
|
||||
);
|
||||
// Only a small fraction of the anchor is on screen.
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ rect: rect(790, 100, 100, 40) }) }),
|
||||
{ ok: false, reason: "anchor-offscreen" },
|
||||
);
|
||||
// A clipped anchor is unusable even when its box looks fine.
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, anchor: anchor({ clipPath: "inset(50%)" }) }),
|
||||
{ ok: false, reason: "anchor-offscreen" },
|
||||
);
|
||||
});
|
||||
|
||||
test("an anchor that is at least half visible can host the control", () => {
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({
|
||||
...baseEvaluation,
|
||||
anchor: anchor({ rect: rect(750, 100, 100, 40) }),
|
||||
controlRect: rect(700, 100, 60, 30),
|
||||
}),
|
||||
{ ok: true },
|
||||
);
|
||||
});
|
||||
|
||||
test("control size, position and hit test are enforced", () => {
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, controlRect: rect(180, 105, 0, 0) }),
|
||||
{ ok: false, reason: "control-hidden" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, controlRect: rect(180, 105, 20, 20) }),
|
||||
{ ok: false, reason: "control-too-small" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, controlRect: rect(760, 105, 120, 30) }),
|
||||
{ ok: false, reason: "control-offscreen" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, hitTestOk: false }),
|
||||
{ ok: false, reason: "hit-test" },
|
||||
);
|
||||
});
|
||||
|
||||
test("the mode gate does not flap between the anchor and the fallback", () => {
|
||||
let state = INITIAL_SLOT_MODE_STATE;
|
||||
// The first valid check slots immediately, even under the anti-flap rule.
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.deepEqual(state, { slotted: true, validStreak: 0, hasSlotted: true });
|
||||
|
||||
// Any failure returns to the floating position at once.
|
||||
state = nextSlotModeState(state, false);
|
||||
assert.deepEqual(state, { slotted: false, validStreak: 0, hasSlotted: true });
|
||||
|
||||
// A single valid sample is not enough to re-slot.
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.equal(state.slotted, false);
|
||||
assert.equal(state.validStreak, 1);
|
||||
|
||||
// A failure resets the streak.
|
||||
state = nextSlotModeState(state, false);
|
||||
assert.equal(state.validStreak, 0);
|
||||
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.equal(state.slotted, false);
|
||||
state = nextSlotModeState(state, true);
|
||||
assert.equal(state.slotted, true);
|
||||
assert.equal(state.hasSlotted, true);
|
||||
});
|
||||
|
||||
test("a slotted capsule that would cover a protected control falls back", () => {
|
||||
assert.deepEqual(
|
||||
evaluateSlottedControl({ ...baseEvaluation, coversProtected: true }),
|
||||
{ ok: false, reason: "covers-protected" },
|
||||
);
|
||||
assert.deepEqual(evaluateSlottedControl({ ...baseEvaluation, coversProtected: false }), { 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);
|
||||
});
|
||||
@@ -0,0 +1,537 @@
|
||||
/**
|
||||
* Runtime placement for trusted host controls that a skin may fold into its
|
||||
* own layout.
|
||||
*
|
||||
* A skin cannot own, style or hide these controls: the control still lives in
|
||||
* the host's closed shadow root and top layer. `chrome.json#slots` only names
|
||||
* an existing `data-ws-part` anchor inside `.ws-skin-root`; this module reads
|
||||
* that anchor, positions the host control over it, and falls back to the
|
||||
* default corner whenever the anchor stops being a safe place to click.
|
||||
*
|
||||
* `isHostPartReachable` stays the single visibility predicate for host parts;
|
||||
* the extra checks here cover only slot-specific geometry (anchor size and
|
||||
* on-screen ratio, control hit target, top-layer hit test).
|
||||
*/
|
||||
|
||||
import type { SkinChromeSlotAlign } from "../../../src/shared/skin-chrome.js";
|
||||
import type { HostOwnedLayer } from "./host-owned-layer.js";
|
||||
import { isHostPartReachable, type HostPartRect } from "./host-chrome-visibility.js";
|
||||
import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import {
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
applyHostControlTokens,
|
||||
createHostControlProbe,
|
||||
findSkinRoot,
|
||||
resolveHostControlTokens,
|
||||
type HostControlTokens,
|
||||
type HostControlProbe,
|
||||
} from "./host-control-tokens.js";
|
||||
|
||||
export interface SlotViewport {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Small inset so the capsule never touches the viewport edge. */
|
||||
export const HOST_SLOT_VIEWPORT_INSET = 4;
|
||||
/** An anchor narrower or shorter than this cannot host a usable control. */
|
||||
export const HOST_SLOT_MIN_ANCHOR_SIZE = 8;
|
||||
/** At least half of the anchor must be on screen. */
|
||||
export const HOST_SLOT_MIN_VISIBLE_RATIO = 0.5;
|
||||
/** Re-slot only after the anchor stays usable for consecutive checks. */
|
||||
export const HOST_SLOT_REQUIRED_VALID_CHECKS = 2;
|
||||
export const HOST_SLOT_SLOTTED_INTERVAL_MS = 400;
|
||||
export const HOST_SLOT_IDLE_INTERVAL_MS = 1000;
|
||||
|
||||
/**
|
||||
* Place the control inside the anchor rect, vertically centred and aligned on
|
||||
* one horizontal edge. The result is clamped so the whole control stays inside
|
||||
* the viewport; when the anchor is smaller than the control the control may
|
||||
* overflow the anchor, but never the viewport.
|
||||
*/
|
||||
export function computeSlotPlacement(
|
||||
anchor: HostPartRect,
|
||||
control: { width: number; height: number },
|
||||
viewport: SlotViewport,
|
||||
align: SkinChromeSlotAlign = "end",
|
||||
): { left: number; top: number } {
|
||||
const width = Math.max(0, control.width);
|
||||
const height = Math.max(0, control.height);
|
||||
const inset = HOST_SLOT_VIEWPORT_INSET;
|
||||
const desiredLeft = align === "start"
|
||||
? anchor.left
|
||||
: align === "center"
|
||||
? anchor.left + (anchor.width - width) / 2
|
||||
: anchor.right - width;
|
||||
const desiredTop = anchor.top + (anchor.height - height) / 2;
|
||||
const maxLeft = Math.max(inset, viewport.width - inset - width);
|
||||
const maxTop = Math.max(inset, viewport.height - inset - height);
|
||||
return {
|
||||
left: Math.min(Math.max(inset, desiredLeft), maxLeft),
|
||||
top: Math.min(Math.max(inset, desiredTop), maxTop),
|
||||
};
|
||||
}
|
||||
|
||||
export type SlotFailureReason =
|
||||
| "anchor-missing"
|
||||
| "anchor-hidden"
|
||||
| "anchor-tiny"
|
||||
| "anchor-offscreen"
|
||||
| "control-hidden"
|
||||
| "control-too-small"
|
||||
| "control-offscreen"
|
||||
| "covers-protected"
|
||||
| "hit-test";
|
||||
|
||||
export interface SlotAnchorSnapshot {
|
||||
rect: HostPartRect;
|
||||
display: string;
|
||||
visibility: string;
|
||||
opacity: string;
|
||||
clipPath?: string;
|
||||
clip?: string;
|
||||
}
|
||||
|
||||
export interface SlotEvaluationInput {
|
||||
anchor: SlotAnchorSnapshot | null | undefined;
|
||||
controlRect: HostPartRect;
|
||||
viewport: SlotViewport;
|
||||
/** Host-enforced minimum hit target for the current size tier. */
|
||||
minHitTarget: number;
|
||||
/** `document.elementFromPoint` at the control centre is the host layer. */
|
||||
hitTestOk: boolean;
|
||||
/**
|
||||
* The capsule's footprint (at its largest observed size, so a compact
|
||||
* capsule that expands on hover is included) overlaps a visible protected
|
||||
* control such as the microphone, output or "clear local data" link. The
|
||||
* capsule is top layer, so it would block those controls for the pointer.
|
||||
*/
|
||||
coversProtected?: boolean;
|
||||
}
|
||||
|
||||
export type SlotEvaluation = { ok: true } | { ok: false; reason: SlotFailureReason };
|
||||
|
||||
function visibleAreaRatio(rect: HostPartRect, viewport: SlotViewport): number {
|
||||
const width = Math.min(rect.right, viewport.width) - Math.max(rect.left, 0);
|
||||
const height = Math.min(rect.bottom, viewport.height) - Math.max(rect.top, 0);
|
||||
const area = rect.width * rect.height;
|
||||
if (!(area > 0) || !(width > 0) || !(height > 0)) return 0;
|
||||
return (width * height) / area;
|
||||
}
|
||||
|
||||
function fullyInsideViewport(rect: HostPartRect, viewport: SlotViewport): boolean {
|
||||
const epsilon = 0.5;
|
||||
return rect.left >= -epsilon
|
||||
&& rect.top >= -epsilon
|
||||
&& rect.right <= viewport.width + epsilon
|
||||
&& rect.bottom <= viewport.height + epsilon;
|
||||
}
|
||||
|
||||
export function evaluateSlottedControl(input: SlotEvaluationInput): SlotEvaluation {
|
||||
const { anchor, controlRect, viewport, minHitTarget, hitTestOk } = input;
|
||||
if (!anchor) return { ok: false, reason: "anchor-missing" };
|
||||
if (anchor.display === "none" || anchor.visibility === "hidden" || anchor.visibility === "collapse") {
|
||||
return { ok: false, reason: "anchor-hidden" };
|
||||
}
|
||||
const opacity = Number.parseFloat(anchor.opacity);
|
||||
if (Number.isFinite(opacity) && opacity <= 0.01) return { ok: false, reason: "anchor-hidden" };
|
||||
if (anchor.rect.width < HOST_SLOT_MIN_ANCHOR_SIZE || anchor.rect.height < HOST_SLOT_MIN_ANCHOR_SIZE) {
|
||||
return { ok: false, reason: "anchor-tiny" };
|
||||
}
|
||||
// The anchor itself does not have to accept pointer events: the control is
|
||||
// hit-tested separately, above it.
|
||||
if (!isHostPartReachable({
|
||||
display: anchor.display,
|
||||
visibility: anchor.visibility,
|
||||
opacity: anchor.opacity,
|
||||
pointerEvents: "auto",
|
||||
clipPath: anchor.clipPath,
|
||||
clip: anchor.clip,
|
||||
rect: anchor.rect,
|
||||
viewport,
|
||||
})) {
|
||||
return { ok: false, reason: "anchor-offscreen" };
|
||||
}
|
||||
if (visibleAreaRatio(anchor.rect, viewport) < HOST_SLOT_MIN_VISIBLE_RATIO) {
|
||||
return { ok: false, reason: "anchor-offscreen" };
|
||||
}
|
||||
|
||||
if (!(controlRect.width > 0) || !(controlRect.height > 0)) return { ok: false, reason: "control-hidden" };
|
||||
if (controlRect.width < minHitTarget || controlRect.height < minHitTarget) {
|
||||
return { ok: false, reason: "control-too-small" };
|
||||
}
|
||||
if (!fullyInsideViewport(controlRect, viewport)) return { ok: false, reason: "control-offscreen" };
|
||||
if (input.coversProtected) return { ok: false, reason: "covers-protected" };
|
||||
if (!hitTestOk) return { ok: false, reason: "hit-test" };
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export interface SlotModeState {
|
||||
slotted: boolean;
|
||||
/** Consecutive valid checks since the last fallback. */
|
||||
validStreak: number;
|
||||
/** Once true, re-slotting needs the anti-flap streak. */
|
||||
hasSlotted: boolean;
|
||||
}
|
||||
|
||||
export const INITIAL_SLOT_MODE_STATE: SlotModeState = { slotted: false, validStreak: 0, hasSlotted: false };
|
||||
|
||||
/**
|
||||
* The first valid check slots immediately (no initial flash); after any
|
||||
* fallback, the anchor must stay valid for `requiredValidChecks` checks so a
|
||||
* flickering CSS animation cannot make the capsule jump every frame.
|
||||
*/
|
||||
export function nextSlotModeState(
|
||||
current: SlotModeState,
|
||||
ok: boolean,
|
||||
requiredValidChecks = HOST_SLOT_REQUIRED_VALID_CHECKS,
|
||||
): SlotModeState {
|
||||
if (!ok) {
|
||||
return { slotted: false, validStreak: 0, hasSlotted: current.hasSlotted };
|
||||
}
|
||||
if (current.slotted) return { ...current, validStreak: 0 };
|
||||
const validStreak = current.validStreak + 1;
|
||||
const slotted = !current.hasSlotted || validStreak >= Math.max(1, requiredValidChecks);
|
||||
return {
|
||||
slotted,
|
||||
validStreak: slotted ? 0 : validStreak,
|
||||
hasSlotted: current.hasSlotted || slotted,
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* DOM binding
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
function rectOf(rect: DOMRect | HostPartRect): HostPartRect {
|
||||
return {
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
right: rect.right,
|
||||
bottom: rect.bottom,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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);
|
||||
const height = Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top);
|
||||
return width > 1 && height > 1;
|
||||
}
|
||||
|
||||
const INTERACTIVE_SELECTOR = "a[href],button,input,select,textarea,[role='button'],[tabindex],[contenteditable='true']";
|
||||
|
||||
/**
|
||||
* Protected controls (`PROTECTED_PART_IDS`) that the capsule must not sit on.
|
||||
* Ancestors of the anchor (for example `app` or `voice.audio-dock` around a
|
||||
* dedicated anchor node) are containers, not click targets, and are skipped;
|
||||
* the anchor itself only counts when it is or contains an interactive control.
|
||||
*/
|
||||
export function protectedPartsCovered(
|
||||
footprint: HostPartRect,
|
||||
anchorElement: Element,
|
||||
doc: Document = anchorElement.ownerDocument,
|
||||
): boolean {
|
||||
const view = doc.defaultView;
|
||||
for (const element of doc.querySelectorAll<HTMLElement>("[data-ws-part]")) {
|
||||
const part = element.getAttribute("data-ws-part") ?? "";
|
||||
if (!PROTECTED_PART_IDS.has(part)) continue;
|
||||
if (element === anchorElement) {
|
||||
if (!element.matches(INTERACTIVE_SELECTOR) && !element.querySelector(INTERACTIVE_SELECTOR)) continue;
|
||||
} else if (element.contains(anchorElement)) {
|
||||
continue;
|
||||
}
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (!(rect.width > 0) || !(rect.height > 0)) continue;
|
||||
if (view) {
|
||||
const style = view.getComputedStyle(element);
|
||||
if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") continue;
|
||||
}
|
||||
if (rectsOverlap(footprint, rectOf(rect))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isVisibleAnchor(element: HTMLElement): boolean {
|
||||
const view = element.ownerDocument.defaultView;
|
||||
if (!view) return false;
|
||||
const style = view.getComputedStyle(element);
|
||||
return isHostPartReachable({
|
||||
display: style.display,
|
||||
visibility: style.visibility,
|
||||
opacity: style.opacity,
|
||||
pointerEvents: "auto",
|
||||
clipPath: style.clipPath,
|
||||
clip: style.clip,
|
||||
rect: rectOf(element.getBoundingClientRect()),
|
||||
viewport: { width: view.innerWidth, height: view.innerHeight },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the first visible `[data-ws-part="<anchor>"]` inside the active
|
||||
* skin's DOM. Plugin and surface hosts render inside `.ws-skin-root` too
|
||||
* (runtime plugins may Teleport to a `data-ws-skin-mount` slot, but every
|
||||
* mount slot is part of the skin root), so a skin cannot point the recovery
|
||||
* control at host chrome outside its own subtree.
|
||||
*/
|
||||
export function resolveSkinAnchor(
|
||||
anchor: string,
|
||||
doc: Document = document,
|
||||
skinId?: string,
|
||||
): HTMLElement | null {
|
||||
const selector = `[data-ws-part="${anchor}"]`;
|
||||
for (const root of doc.querySelectorAll(".ws-skin-root")) {
|
||||
if (skinId && root.getAttribute("data-ws-skin") !== skinId) continue;
|
||||
for (const element of root.querySelectorAll<HTMLElement>(selector)) {
|
||||
if (isVisibleAnchor(element)) return element;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface HostSlotModeChange {
|
||||
mode: "slotted" | "floating";
|
||||
reason?: SlotFailureReason;
|
||||
}
|
||||
|
||||
export interface HostSlotBindingOptions {
|
||||
layer: HostOwnedLayer;
|
||||
control: HTMLElement;
|
||||
anchor: string;
|
||||
/** Restricts anchor resolution and token fallback to this active skin. */
|
||||
skinId?: string;
|
||||
align?: SkinChromeSlotAlign;
|
||||
resolveAnchor?: (anchor: string) => HTMLElement | null;
|
||||
onModeChange?: (change: HostSlotModeChange) => void;
|
||||
}
|
||||
|
||||
export interface HostSlotBinding {
|
||||
revalidate(): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
const NOOP_BINDING: HostSlotBinding = {
|
||||
revalidate: () => undefined,
|
||||
dispose: () => undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* Position the controlled host element over its anchor, re-check it on layout
|
||||
* changes and return it to the default floating position on any failure.
|
||||
* Tokens are read from the anchor's computed style and applied inside the
|
||||
* closed shadow root; the skin never writes to the control itself.
|
||||
*/
|
||||
export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
const { layer, control, anchor: anchorName, onModeChange } = options;
|
||||
const align = options.align ?? "end";
|
||||
const doc = control.ownerDocument;
|
||||
const view = doc.defaultView;
|
||||
if (!view) return NOOP_BINDING;
|
||||
const win = view;
|
||||
const resolveAnchor = options.resolveAnchor
|
||||
?? ((name: string) => resolveSkinAnchor(name, doc, options.skinId));
|
||||
|
||||
let state = INITIAL_SLOT_MODE_STATE;
|
||||
let lastReason: SlotFailureReason | undefined;
|
||||
let currentAnchor: HTMLElement | null = null;
|
||||
let observer: ResizeObserver | null = null;
|
||||
const probe: HostControlProbe = createHostControlProbe(layer.shadow);
|
||||
let frame: number | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false;
|
||||
/** Largest capsule size seen; covers a compact capsule's expanded footprint. */
|
||||
let maxSize = { width: 0, height: 0 };
|
||||
|
||||
const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback);
|
||||
const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
|
||||
|
||||
function readTokens(source: Element | null): HostControlTokens {
|
||||
return resolveHostControlTokens(
|
||||
source ? win.getComputedStyle(source) : null,
|
||||
"host.recovery",
|
||||
probe.probeColor,
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
probe.isWebFont,
|
||||
);
|
||||
}
|
||||
|
||||
function clearPlacement(): void {
|
||||
control.style.removeProperty("position");
|
||||
control.style.removeProperty("left");
|
||||
control.style.removeProperty("top");
|
||||
control.style.removeProperty("right");
|
||||
control.style.removeProperty("bottom");
|
||||
}
|
||||
|
||||
function applyPlacement(left: number, top: number): void {
|
||||
control.style.position = "fixed";
|
||||
control.style.left = `${left}px`;
|
||||
control.style.top = `${top}px`;
|
||||
control.style.right = "auto";
|
||||
control.style.bottom = "auto";
|
||||
}
|
||||
|
||||
function hitTestAt(left: number, top: number, size: { width: number; height: number }): boolean {
|
||||
if (typeof doc.elementFromPoint !== "function") return true;
|
||||
// A hit inside the closed shadow root retargets to the layer host, which is
|
||||
// exactly what `elementFromPoint` returns for the top-layer capsule.
|
||||
const hit = doc.elementFromPoint(left + size.width / 2, top + size.height / 2);
|
||||
return hit === layer.host;
|
||||
}
|
||||
|
||||
function observe(anchorElement: HTMLElement | null): void {
|
||||
if (currentAnchor === anchorElement) return;
|
||||
currentAnchor = anchorElement;
|
||||
if (!observer && typeof ResizeObserver !== "undefined") {
|
||||
observer = new ResizeObserver(() => schedule());
|
||||
}
|
||||
if (!observer) return;
|
||||
observer.disconnect();
|
||||
observer.observe(control);
|
||||
if (anchorElement) observer.observe(anchorElement);
|
||||
}
|
||||
|
||||
function evaluate(): void {
|
||||
if (disposed) return;
|
||||
const anchorElement = resolveAnchor(anchorName);
|
||||
observe(anchorElement);
|
||||
// The fallback keeps the skin palette: read tokens from the anchor, or
|
||||
// from the skin root when the anchor is missing or hidden.
|
||||
const tokenSource = anchorElement
|
||||
?? (options.skinId ? findSkinRoot(options.skinId, doc) : null);
|
||||
const tokens = readTokens(tokenSource);
|
||||
applyHostControlTokens(control, tokenSource ? tokens : null);
|
||||
|
||||
const controlBox = control.getBoundingClientRect();
|
||||
maxSize = {
|
||||
width: Math.max(maxSize.width, controlBox.width),
|
||||
height: Math.max(maxSize.height, controlBox.height),
|
||||
};
|
||||
const viewport: SlotViewport = { width: win.innerWidth, height: win.innerHeight };
|
||||
let anchorSnapshot: SlotAnchorSnapshot | null = null;
|
||||
if (anchorElement) {
|
||||
const style = win.getComputedStyle(anchorElement);
|
||||
anchorSnapshot = {
|
||||
rect: rectOf(anchorElement.getBoundingClientRect()),
|
||||
display: style.display,
|
||||
visibility: style.visibility,
|
||||
opacity: style.opacity,
|
||||
clipPath: style.clipPath,
|
||||
clip: style.clip,
|
||||
};
|
||||
}
|
||||
|
||||
const canPlace = Boolean(anchorSnapshot) && controlBox.width > 0 && controlBox.height > 0;
|
||||
const placement = canPlace && anchorSnapshot
|
||||
? computeSlotPlacement(anchorSnapshot.rect, controlBox, viewport, align)
|
||||
: null;
|
||||
const intendedRect: HostPartRect = placement
|
||||
? {
|
||||
width: controlBox.width,
|
||||
height: controlBox.height,
|
||||
left: placement.left,
|
||||
top: placement.top,
|
||||
right: placement.left + controlBox.width,
|
||||
bottom: placement.top + controlBox.height,
|
||||
}
|
||||
: rectOf(controlBox);
|
||||
// Move first, then hit-test: the capsule has to actually occupy the
|
||||
// intended point before `elementFromPoint` can see it. The move and a
|
||||
// failed revert happen in one task, so nothing paints in between.
|
||||
let coversProtected = false;
|
||||
if (anchorElement && anchorSnapshot && placement) {
|
||||
const footprintPlacement = computeSlotPlacement(anchorSnapshot.rect, maxSize, viewport, align);
|
||||
coversProtected = protectedPartsCovered({
|
||||
width: maxSize.width,
|
||||
height: maxSize.height,
|
||||
left: footprintPlacement.left,
|
||||
top: footprintPlacement.top,
|
||||
right: footprintPlacement.left + maxSize.width,
|
||||
bottom: footprintPlacement.top + maxSize.height,
|
||||
}, anchorElement, doc);
|
||||
}
|
||||
if (placement) applyPlacement(placement.left, placement.top);
|
||||
const evaluation = evaluateSlottedControl({
|
||||
anchor: anchorSnapshot,
|
||||
controlRect: intendedRect,
|
||||
viewport,
|
||||
minHitTarget: tokens.hitTarget,
|
||||
coversProtected,
|
||||
hitTestOk: placement
|
||||
? hitTestAt(placement.left, placement.top, { width: controlBox.width, height: controlBox.height })
|
||||
: false,
|
||||
});
|
||||
|
||||
const next = nextSlotModeState(state, evaluation.ok);
|
||||
const changed = next.slotted !== state.slotted;
|
||||
state = next;
|
||||
if (state.slotted && placement) applyPlacement(placement.left, placement.top);
|
||||
else clearPlacement();
|
||||
|
||||
const reason = evaluation.ok ? undefined : evaluation.reason;
|
||||
const mode = state.slotted ? "slotted" : "floating";
|
||||
if (changed || (mode === "floating" && reason !== lastReason)) {
|
||||
lastReason = reason;
|
||||
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Any unexpected error returns the capsule to the default corner. */
|
||||
function failSafe(): void {
|
||||
const wasSlotted = state.slotted;
|
||||
state = nextSlotModeState(state, false);
|
||||
clearPlacement();
|
||||
if (wasSlotted) onModeChange?.({ mode: "floating" });
|
||||
}
|
||||
|
||||
function schedule(): void {
|
||||
if (disposed || frame !== undefined) return;
|
||||
frame = requestFrame(() => {
|
||||
frame = undefined;
|
||||
try {
|
||||
evaluate();
|
||||
} catch {
|
||||
failSafe();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleTick(): void {
|
||||
if (disposed) return;
|
||||
timer = setTimeout(() => {
|
||||
if (disposed) return;
|
||||
// The periodic check is the safety net; one failing pass must not stop it.
|
||||
try {
|
||||
evaluate();
|
||||
} catch {
|
||||
failSafe();
|
||||
} finally {
|
||||
scheduleTick();
|
||||
}
|
||||
}, state.slotted ? HOST_SLOT_SLOTTED_INTERVAL_MS : HOST_SLOT_IDLE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
win.addEventListener("resize", schedule, { passive: true });
|
||||
win.addEventListener("scroll", schedule, { capture: true, passive: true });
|
||||
evaluate();
|
||||
scheduleTick();
|
||||
|
||||
return {
|
||||
revalidate: evaluate,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
if (frame !== undefined) cancelFrame(frame);
|
||||
if (timer) clearTimeout(timer);
|
||||
win.removeEventListener("resize", schedule);
|
||||
win.removeEventListener("scroll", schedule, { capture: true });
|
||||
clearPlacement();
|
||||
applyHostControlTokens(control, null);
|
||||
probe.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -53,6 +53,11 @@
|
||||
|
||||
.ws-plugin-toolbar{position:relative;display:flex;align-items:center;min-width:0}
|
||||
.ws-plugin-toolbar-fallback{position:fixed;z-index:1001;right:16px;bottom:calc(16px + env(safe-area-inset-bottom));padding:4px;border-radius:12px;background:var(--ws-panel,#fff);box-shadow:0 4px 20px #0003;color:#233049}
|
||||
/* Runtime collision avoidance (host-floating-placement.ts) moves the fallback toolbar off skin controls. */
|
||||
.ws-plugin-toolbar-fallback[data-ws-float$="left"]{right:auto;left:16px}
|
||||
.ws-plugin-toolbar-fallback[data-ws-float^="top"]{bottom:auto;top:calc(16px + env(safe-area-inset-top))}
|
||||
.ws-plugin-toolbar-fallback[data-ws-float^="middle"]{bottom:auto;top:50%;translate:0 -50%}
|
||||
.ws-plugin-toolbar-fallback[data-ws-float$="center"]{right:auto;left:50%;translate:-50% 0}
|
||||
.ws-plugin-toolbar[data-presentation="drawer-side"]{display:grid;width:100%;gap:4px;color:inherit}
|
||||
.ws-plugin-toolbar[data-presentation="drawer-side"] .ws-plugin-toolbar-trigger{justify-content:flex-start;width:100%;gap:8px;padding:7px 10px;color:inherit;background:transparent;border:1px solid transparent;font:inherit}
|
||||
.ws-plugin-drawer{position:absolute;top:calc(100% + 8px);right:0;z-index:60;width:min(280px,calc(100vw - 32px));max-height:min(380px,60dvh);overflow:auto;overscroll-behavior:contain;padding:8px;color:var(--plugin-drawer-text,#233049);background:var(--plugin-drawer-bg,#fff);border:1px solid var(--plugin-drawer-border,#dae1ef);border-radius:12px;box-shadow:0 12px 32px #17223430;text-align:left;font:13px/1.4 system-ui,sans-serif}
|
||||
|
||||
+4
@@ -26,6 +26,8 @@
|
||||
<div id="overlay" data-ws-part="host.plugins.overlay">Application library</div>
|
||||
<button type="button" id="launcher" data-ws-part="host.plugins.launcher">Plugins</button>
|
||||
</div>
|
||||
<!-- Decorative host chrome lives outside the skin root in the real client. -->
|
||||
<div id="watermark" data-ws-part="host.watermark" aria-hidden="true">Watermark</div>
|
||||
<div id="app"></div>
|
||||
<div id="auth-app"></div>
|
||||
<pre id="result" style="position:relative;z-index:5;background:#fff">pending</pre>
|
||||
@@ -76,7 +78,9 @@ if (!layer) {
|
||||
popoverOpen: popover.matches(":popover-open"),
|
||||
// elementFromPoint retargets nodes inside a closed shadow root to its
|
||||
// host, so either the inner button or the host proves the top layer won.
|
||||
// Slot placement compares strictly against the host; record that too.
|
||||
topLayerHit: hit === layer.host || hit === button || layer.container.contains(hit),
|
||||
hitIsLayerHost: hit === layer.host,
|
||||
hostileCovered: hit === dock,
|
||||
visible: computed.display !== "none" && computed.visibility !== "hidden"
|
||||
&& Number(computed.opacity) > 0.01 && computed.pointerEvents !== "none",
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host control theme fixture</title>
|
||||
<style>
|
||||
html, body { margin: 0; font: 12px/1.5 system-ui, sans-serif; }
|
||||
/* A skin-registered font: host-owned controls must refuse it. */
|
||||
@font-face { font-family: "Blank Glyphs"; src: url(data:font/woff2;base64,AAAA); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-skin="community.theme-fixture" data-ws-part="app"></div>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
|
||||
import { SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS, bindHostControlTheme, findSkinRoot } from "/src/services/host-control-tokens.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const frames = () => new Promise((resolve) => setTimeout(resolve, 120));
|
||||
const addSkinStyle = (css) => {
|
||||
const style = document.createElement("style");
|
||||
style.textContent = css;
|
||||
document.head.append(style);
|
||||
return style;
|
||||
};
|
||||
|
||||
(async () => {
|
||||
const layer = createHostOwnedLayer("theme-fixture", `.banner { background: var(--ws-control-background, #fffbeb); color: var(--ws-control-foreground, #78350f); font-family: var(--ws-control-font, serif); }`);
|
||||
const control = document.createElement("section");
|
||||
control.className = "banner";
|
||||
control.textContent = "Use built-in skin";
|
||||
layer.container.append(control);
|
||||
const theme = bindHostControlTheme({
|
||||
layer,
|
||||
control: () => control,
|
||||
part: "app.skin-load-recovery",
|
||||
defaults: SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot("community.theme-fixture"),
|
||||
});
|
||||
const snap = (name) => ({
|
||||
name,
|
||||
inlineBackground: control.style.getPropertyValue("--ws-control-background"),
|
||||
inlineFont: control.style.getPropertyValue("--ws-control-font"),
|
||||
background: getComputedStyle(control).backgroundColor,
|
||||
});
|
||||
const results = [];
|
||||
|
||||
// The stored skin id is known before its stylesheet arrives.
|
||||
theme.apply();
|
||||
results.push(snap("before-skin-css"));
|
||||
|
||||
// Late skin CSS: oklch() background must resolve to sRGB and theme the banner
|
||||
// without any caller re-applying the binding.
|
||||
addSkinStyle(`.ws-skin-root { --skin-host-background: oklch(0.25 0.05 250); --skin-host-foreground: #ffffff; --skin-host-accent: #47dcc4; --skin-host-font: "Blank Glyphs", sans-serif; }`);
|
||||
await frames();
|
||||
results.push(snap("late-skin-css"));
|
||||
|
||||
addSkinStyle(`.ws-skin-root { --skin-host-font: Tahoma, "Segoe UI", sans-serif; }`);
|
||||
await frames();
|
||||
results.push(snap("system-font"));
|
||||
|
||||
// A compiled skin face behind a non-matching @media is absent from
|
||||
// document.fonts; its scoped `ws-` name must still be refused.
|
||||
addSkinStyle(`@media (max-width: 1px) { @font-face { font-family: "ws-community-theme-fixture-blank"; src: url(data:font/woff2;base64,AAAA); } }
|
||||
.ws-skin-root { --skin-host-font: "ws-community-theme-fixture-blank", sans-serif; }`);
|
||||
await frames();
|
||||
results.push(snap("media-gated-skin-font"));
|
||||
|
||||
// Tokens declared inside @media follow the viewport without a DOM change.
|
||||
const viewportStyle = addSkinStyle(`@media (min-width: 1px) { .ws-skin-root { --skin-host-background: #102030; } }`);
|
||||
await frames();
|
||||
const beforeResize = control.style.getPropertyValue("--ws-control-background");
|
||||
viewportStyle.sheet.cssRules[0].media.mediaText = "(max-width: 1px)";
|
||||
window.dispatchEvent(new Event("resize"));
|
||||
await frames();
|
||||
results.push({ ...snap("media-token-resize"), beforeResize });
|
||||
|
||||
theme.dispose();
|
||||
addSkinStyle(`.ws-skin-root { --skin-host-background: #ffffff; --skin-host-foreground: #111111; }`);
|
||||
await frames();
|
||||
results.push(snap("after-dispose"));
|
||||
|
||||
output.textContent = JSON.stringify({ results });
|
||||
})().catch((error) => {
|
||||
output.textContent = JSON.stringify({ error: String(error && error.stack || error) });
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host floating placement fixture</title>
|
||||
<style>
|
||||
html, body { margin: 0; width: 100%; height: 100%; font: 12px/1.5 system-ui, sans-serif; }
|
||||
/* Skin audio dock in the bottom-left corner, where the capsule floats by default. */
|
||||
#mic { position: fixed; left: 20px; bottom: 40px; width: 120px; height: 34px; }
|
||||
/* Skin "Send" button (disabled until the user types) in the bottom-right corner. */
|
||||
#send { position: fixed; right: 20px; bottom: 20px; width: 60px; height: 34px; }
|
||||
/* A right-hand side sheet whose buttons sit where the capsule moved to. */
|
||||
#sheet { position: fixed; inset: 0 0 0 auto; width: 320px; background: #eee; }
|
||||
#sheet button { position: absolute; right: 8px; width: 280px; height: 40px; }
|
||||
#cancel { top: 8px; } #enter { bottom: 30px; }
|
||||
#backdrop { position: fixed; inset: 0; background: #0006; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-skin="community.float-fixture" data-ws-part="app">
|
||||
<div data-ws-part="voice.audio-dock.microphone"><button type="button" id="mic">Mic</button></div>
|
||||
<button type="button" id="send" disabled>Send</button>
|
||||
<button type="button" id="top-left" style="position:fixed;left:8px;top:8px;width:220px;height:44px">Server strip</button>
|
||||
</div>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
|
||||
import { bindFloatingAvoidance, collectFloatingObstacles } from "/src/services/host-floating-placement.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const CSS = `
|
||||
.cap { position: fixed; inset: auto auto 38px 12px; margin: 0; display: flex; gap: 4px; padding: 4px; border: 0; width: 200px; height: 30px; pointer-events: auto; }
|
||||
.cap[data-ws-float$="right"] { left: auto; right: 12px; }
|
||||
.cap[data-ws-float^="top"] { bottom: auto; top: 12px; }
|
||||
.cap[data-ws-float^="middle"] { bottom: auto; top: 50%; translate: 0 -50%; }
|
||||
.cap[data-ws-float$="center"] { left: 50%; translate: -50% 0; }
|
||||
.cap.compact { width: 30px; }
|
||||
`;
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
// Moves are confirmed after a short dwell and rate-limited (anti-flap).
|
||||
let binding;
|
||||
const settle = async () => { binding.revalidate(); await sleep(1400); binding.revalidate(); await sleep(50); };
|
||||
try {
|
||||
const layer = createHostOwnedLayer("recovery", CSS);
|
||||
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();
|
||||
const host = layer.host;
|
||||
let compact = false;
|
||||
binding = bindFloatingAvoidance({
|
||||
element: control,
|
||||
isSelf: (node) => node === host || host.contains(node),
|
||||
margins: { top: 12, right: 12, bottom: 38, left: 12 },
|
||||
apply: (position) => control.setAttribute("data-ws-float", position),
|
||||
compactSize: () => ({ width: 30, height: 38 }),
|
||||
onCompactChange: (next) => { compact = next; control.classList.toggle("compact", next); },
|
||||
});
|
||||
const covered = () => ["mic", "send", "top-left", "cancel", "enter"].filter((id) => {
|
||||
const element = document.getElementById(id);
|
||||
if (!element) return false;
|
||||
const r = element.getBoundingClientRect();
|
||||
if (!(r.width > 0)) return false;
|
||||
return document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) === host;
|
||||
});
|
||||
const snap = (name) => ({ name, position: binding.position, compact, covered: covered(), capsuleHit: (() => {
|
||||
const r = control.getBoundingClientRect();
|
||||
return document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) === host;
|
||||
})() });
|
||||
const results = [];
|
||||
await settle();
|
||||
results.push(snap("dock-and-send"));
|
||||
|
||||
// Stability: repeated re-checks (interval + manual) never move a settled capsule.
|
||||
const seen = new Set([binding.position]);
|
||||
for (let i = 0; i < 6; i++) { binding.revalidate(); seen.add(binding.position); await sleep(120); }
|
||||
await sleep(1300); seen.add(binding.position);
|
||||
results.push({ ...snap("stable"), positions: [...seen] });
|
||||
|
||||
// A full-screen click-away layer (role=button) is "covered" everywhere; a
|
||||
// sliver less of it is no reason to fold the capsule to its mark.
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="clickaway" role="button" tabindex="0" style="position:fixed;inset:0"></div>');
|
||||
await settle();
|
||||
results.push(snap("click-away"));
|
||||
document.getElementById("clickaway").remove();
|
||||
await settle();
|
||||
|
||||
// A second host floating control (like the application-library launcher):
|
||||
// the two never overlap and settle without flapping.
|
||||
const lib = document.createElement("div");
|
||||
lib.id = "lib";
|
||||
lib.style.cssText = "position:fixed;right:16px;bottom:16px;width:44px;height:44px;z-index:5";
|
||||
lib.innerHTML = '<button type="button" style="width:44px;height:44px">L</button>';
|
||||
document.body.append(lib);
|
||||
const libPositions = new Set();
|
||||
const libBinding = bindFloatingAvoidance({
|
||||
element: lib,
|
||||
isSelf: (node) => lib.contains(node),
|
||||
margins: (insets) => ({ top: 16 + insets.top, right: 16, bottom: 16 + insets.bottom, left: 16 }),
|
||||
defaultPosition: "bottom-right",
|
||||
apply: (position) => {
|
||||
libPositions.add(position);
|
||||
lib.style.left = position.endsWith("left") ? "16px" : position.endsWith("center") ? "calc(50% - 22px)" : "auto";
|
||||
lib.style.right = position.endsWith("right") ? "16px" : "auto";
|
||||
lib.style.top = position.startsWith("top") ? "16px" : position.startsWith("middle") ? "calc(50% - 22px)" : "auto";
|
||||
lib.style.bottom = position.startsWith("bottom") ? "16px" : "auto";
|
||||
},
|
||||
});
|
||||
const capPositions = new Set([binding.position]);
|
||||
for (let i = 0; i < 12; i++) { libBinding.revalidate(); binding.revalidate(); capPositions.add(binding.position); await sleep(400); }
|
||||
const cr = control.getBoundingClientRect(), lr = lib.getBoundingClientRect();
|
||||
const overlap = !(cr.right <= lr.left || lr.right <= cr.left || cr.bottom <= lr.top || lr.bottom <= cr.top);
|
||||
results.push({ ...snap("two-controls"), overlap, libPosition: libBinding.position, libMoves: libPositions.size, capMoves: capPositions.size, sendCovered: document.elementFromPoint(...(() => { const r = document.getElementById("send").getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; })())?.closest("#lib") != null });
|
||||
libBinding.dispose();
|
||||
lib.remove();
|
||||
await settle();
|
||||
|
||||
// A bottom sheet opens behind a backdrop: only its buttons count now.
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="backdrop"></div><div id="sheet" role="dialog" aria-modal="true"><button type="button" id="cancel">Cancel</button><button type="button" id="enter">Enter channel</button></div>');
|
||||
document.getElementById("cancel").click();
|
||||
await sleep(1400);
|
||||
results.push({ ...snap("after-click-sheet"), before: results[0].position });
|
||||
|
||||
// Everything is covered: the capsule folds to its mark at the least harmful spot.
|
||||
document.getElementById("sheet").remove();
|
||||
document.getElementById("backdrop").remove();
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="wall" style="position:fixed;inset:0;display:grid;grid-template-columns:repeat(20,1fr)">' + '<button type="button"></button>'.repeat(400) + "</div>");
|
||||
await settle();
|
||||
results.push(snap("wall"));
|
||||
|
||||
document.getElementById("wall").remove();
|
||||
await settle();
|
||||
results.push(snap("wall-removed"));
|
||||
|
||||
// Screen change (voice page -> home): the dock goes away and a new control
|
||||
// appears exactly where the capsule was parked. screenChanged() re-places it
|
||||
// at once (back to the now-free default corner), without the confirm delay.
|
||||
const away = binding.position;
|
||||
const capRect = control.getBoundingClientRect();
|
||||
document.getElementById("mic").style.display = "none";
|
||||
document.body.insertAdjacentHTML("beforeend", `<button type="button" id="export" style="position:fixed;left:${capRect.left}px;top:${capRect.top}px;width:${capRect.width}px;height:${capRect.height}px">Export identity</button>`);
|
||||
binding.screenChanged();
|
||||
await sleep(150);
|
||||
results.push({ ...snap("screen-change"), away, exportCovered: (() => {
|
||||
const r = document.getElementById("export").getBoundingClientRect();
|
||||
return document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) === host;
|
||||
})() });
|
||||
document.getElementById("export").remove();
|
||||
document.getElementById("mic").style.display = "";
|
||||
await settle();
|
||||
|
||||
// Weights: an unmarked skin button inside the protected "app" root is an
|
||||
// ordinary control; the microphone is protected; invisible controls do not
|
||||
// count; a custom div[tabindex] button does.
|
||||
document.querySelector(".ws-skin-root").insertAdjacentHTML("beforeend",
|
||||
'<button type="button" id="plain" style="position:fixed;left:600px;top:300px;width:60px;height:30px">Plain</button>'
|
||||
+ '<button type="button" id="ghost" style="position:fixed;left:700px;top:300px;width:60px;height:30px;opacity:0">Ghost</button>'
|
||||
+ '<div id="custom" tabindex="0" style="position:fixed;left:800px;top:300px;width:60px;height:30px">Custom</div>');
|
||||
const weightOf = (id) => {
|
||||
const r = document.getElementById(id).getBoundingClientRect();
|
||||
const hit = collectFloatingObstacles({ doc: document, isSelf: () => false, owner: document.body })
|
||||
.find((o) => Math.abs(o.rect.left - r.left) < 0.5 && Math.abs(o.rect.top - r.top) < 0.5);
|
||||
return hit ? hit.weight : 0;
|
||||
};
|
||||
results.push({ name: "weights", plain: weightOf("plain"), mic: weightOf("mic"), ghost: weightOf("ghost"), custom: weightOf("custom") });
|
||||
for (const id of ["plain", "ghost", "custom"]) document.getElementById(id).remove();
|
||||
|
||||
// Anti-flap: a skin control hopping between the free spots every 200 ms
|
||||
// (all other spots taken) cannot keep the capsule moving.
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="walls">'
|
||||
+ ["left:8px;top:8px", "right:8px;top:8px", "left:8px;top:380px", "right:8px;top:380px", "left:540px;top:8px", "left:540px;bottom:20px"]
|
||||
.map((pos) => `<button type="button" style="position:fixed;${pos};width:230px;height:44px"></button>`).join("") + "</div>");
|
||||
document.body.insertAdjacentHTML("beforeend", '<button type="button" id="hopper" style="position:fixed;bottom:40px;left:20px;width:220px;height:34px"></button>');
|
||||
const hopper = document.getElementById("hopper");
|
||||
const flapPositions = [];
|
||||
let last = binding.position;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
hopper.style.left = i % 2 ? "auto" : "20px";
|
||||
hopper.style.right = i % 2 ? "20px" : "auto";
|
||||
binding.revalidate();
|
||||
if (binding.position !== last) { flapPositions.push(binding.position); last = binding.position; }
|
||||
await sleep(200);
|
||||
}
|
||||
results.push({ name: "flap", moves: flapPositions.length, capsuleHit: snap("x").capsuleHit });
|
||||
hopper.remove();
|
||||
document.getElementById("walls").remove();
|
||||
|
||||
binding.dispose();
|
||||
results.push({ ...snap("disposed") });
|
||||
output.textContent = JSON.stringify({ results });
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error && error.stack || error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host floating placement: transient overlays and the flap freeze</title>
|
||||
<style>
|
||||
html, body { margin: 0; width: 100%; height: 100%; font: 12px/1.5 system-ui, sans-serif; }
|
||||
/* open-voice-surface desktop: "Share accompaniment" sits in the bottom-right
|
||||
corner, exactly where the application-library launcher floats by default. */
|
||||
#accompaniment { position: fixed; right: 20px; bottom: 20px; width: 34px; height: 34px; }
|
||||
#lib { position: fixed; width: 44px; height: 44px; z-index: 5; }
|
||||
#lib button { width: 44px; height: 44px; }
|
||||
.toast { position: fixed; right: 12px; bottom: 12px; width: 320px; height: 70px; z-index: 10; background: #222; color: #fff; }
|
||||
.wall { position: fixed; width: 60px; height: 60px; }
|
||||
#hopper { position: fixed; width: 60px; height: 60px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-skin="community.float-transient" data-ws-part="app">
|
||||
<div data-ws-part="voice.audio-dock"><button type="button" id="accompaniment" aria-label="Share accompaniment">♪</button></div>
|
||||
</div>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { bindFloatingAvoidance } from "/src/services/host-floating-placement.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const centre = (element) => { const r = element.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; };
|
||||
const coveredByLib = (element) => document.elementFromPoint(...centre(element))?.closest("#lib") != null;
|
||||
|
||||
function makeLauncher(onMove) {
|
||||
const lib = document.createElement("div");
|
||||
lib.id = "lib";
|
||||
lib.innerHTML = '<button type="button" aria-label="Plugins">L</button>';
|
||||
document.body.append(lib);
|
||||
let bound = false;
|
||||
const binding = bindFloatingAvoidance({
|
||||
element: lib,
|
||||
isSelf: (node) => lib.contains(node),
|
||||
margins: { top: 16, right: 16, bottom: 16, left: 16 },
|
||||
defaultPosition: "bottom-right",
|
||||
apply: (position) => {
|
||||
lib.style.left = position.endsWith("left") ? "16px" : position.endsWith("center") ? "calc(50% - 22px)" : "auto";
|
||||
lib.style.right = position.endsWith("right") ? "16px" : "auto";
|
||||
lib.style.top = position.startsWith("top") ? "16px" : position.startsWith("middle") ? "calc(50% - 22px)" : "auto";
|
||||
lib.style.bottom = position.startsWith("bottom") ? "16px" : "auto";
|
||||
if (bound) onMove?.(position);
|
||||
},
|
||||
});
|
||||
bound = true;
|
||||
return { lib, binding };
|
||||
}
|
||||
|
||||
try {
|
||||
const results = [];
|
||||
const accompaniment = document.getElementById("accompaniment");
|
||||
|
||||
// A. A toast keeps passing over the accompaniment button (every mic/output
|
||||
// toggle shows one), then a modal dialog hides it. The launcher must not
|
||||
// take the "free" default corner while the button is hidden, and must never
|
||||
// end up covering it.
|
||||
{
|
||||
const { lib, binding } = makeLauncher();
|
||||
binding.revalidate(); await sleep(1400); binding.revalidate(); await sleep(50);
|
||||
const settled = binding.position;
|
||||
const positions = new Set();
|
||||
let coveredSamples = 0;
|
||||
let samples = 0;
|
||||
for (let cycle = 0; cycle < 8; cycle++) {
|
||||
document.body.insertAdjacentHTML("beforeend", '<div class="toast" data-ws-part="app.toast" role="status">Microphone muted</div>');
|
||||
for (let i = 0; i < 9; i++) { binding.revalidate(); positions.add(binding.position); await sleep(100); }
|
||||
document.querySelector(".toast").remove();
|
||||
for (let i = 0; i < 6; i++) {
|
||||
binding.revalidate(); positions.add(binding.position);
|
||||
samples++; if (coveredByLib(accompaniment)) coveredSamples++;
|
||||
await sleep(100);
|
||||
}
|
||||
}
|
||||
await sleep(1500);
|
||||
// A modal dialog (audio settings) opens over everything: its backdrop
|
||||
// hides the accompaniment button, so the default corner looks free. On the
|
||||
// same screen that is no reason to go back there.
|
||||
const modalPositions = new Set();
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="backdrop" style="position:fixed;inset:0;z-index:20;background:#0006"></div>'
|
||||
+ '<div id="settings" role="dialog" aria-modal="true" style="position:fixed;left:440px;top:200px;width:400px;height:300px;z-index:21;background:#fff">'
|
||||
+ '<button type="button" id="close-settings" style="margin:16px">Close</button></div>');
|
||||
for (let i = 0; i < 20; i++) { binding.revalidate(); modalPositions.add(binding.position); await sleep(100); }
|
||||
document.getElementById("backdrop").remove();
|
||||
document.getElementById("settings").remove();
|
||||
binding.revalidate();
|
||||
await sleep(100);
|
||||
const afterModal = { positions: [...modalPositions], position: binding.position, accompanimentCovered: coveredByLib(accompaniment) };
|
||||
results.push({ name: "toast-transient", afterModal, settled, positions: [...positions], coveredSamples, samples, final: binding.position, finalCovered: coveredByLib(accompaniment) });
|
||||
binding.dispose();
|
||||
lib.remove();
|
||||
}
|
||||
|
||||
// B. Flap freeze: a skin control that always jumps under the launcher makes
|
||||
// it flap until it is parked at the default corner for 10 s. If the parked
|
||||
// spot covers a control, the launcher still steps off it once, then holds
|
||||
// still for the rest of the freeze (anti-jitter stays intact).
|
||||
{
|
||||
accompaniment.style.display = "none";
|
||||
const walls = ["left:8px;top:8px", "right:8px;top:8px", "left:8px;top:370px", "right:8px;top:370px", "left:610px;top:8px", "left:610px;bottom:8px"];
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="walls">' + walls.map((pos) => `<button type="button" class="wall" style="${pos}"></button>`).join("") + "</div>"
|
||||
+ '<button type="button" id="hopper"></button>');
|
||||
const hopper = document.getElementById("hopper");
|
||||
const chase = (lib) => {
|
||||
const r = lib.getBoundingClientRect();
|
||||
hopper.style.left = `${r.left - 8}px`;
|
||||
hopper.style.top = `${r.top - 8}px`;
|
||||
};
|
||||
const moves = [];
|
||||
const { lib, binding } = makeLauncher((position) => moves.push({ position, at: performance.now() }));
|
||||
const started = performance.now();
|
||||
while (moves.length < 6 && performance.now() - started < 20_000) { chase(lib); binding.revalidate(); await sleep(100); }
|
||||
const flapMoves = moves.length;
|
||||
// The 7th move within 10 s triggers the freeze; keep the control under the launcher.
|
||||
const pinnedAt = performance.now();
|
||||
while (performance.now() - pinnedAt < 3000) { chase(lib); binding.revalidate(); await sleep(100); }
|
||||
const escapes = moves.slice(flapMoves);
|
||||
const afterEscape = { position: binding.position, hopperCovered: coveredByLib(hopper) };
|
||||
// Still frozen (< 10 s since the freeze): the escape was the only move.
|
||||
const heldFrom = moves.length;
|
||||
const holdStart = performance.now();
|
||||
while (performance.now() - holdStart < 2500) { chase(lib); binding.revalidate(); await sleep(100); }
|
||||
results.push({
|
||||
name: "freeze-escape",
|
||||
flapMoves,
|
||||
parkedPosition: moves[flapMoves - 1]?.position,
|
||||
escapes: escapes.map((move) => ({ position: move.position, afterPinMs: Math.round(move.at - pinnedAt) })),
|
||||
afterEscape,
|
||||
movesWhileHeld: moves.length - heldFrom,
|
||||
sinceFreezeMs: Math.round(performance.now() - pinnedAt),
|
||||
});
|
||||
binding.dispose();
|
||||
lib.remove();
|
||||
hopper.remove();
|
||||
document.getElementById("walls").remove();
|
||||
accompaniment.style.display = "";
|
||||
}
|
||||
|
||||
output.textContent = JSON.stringify({ results });
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error && error.stack || error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host slot placement fixture</title>
|
||||
<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: 200px; width: 640px; height: 56px; }
|
||||
#anchor { position: absolute; left: 0; top: 4px; width: 320px; height: 48px; }
|
||||
#mic { position: absolute; right: 8px; top: 11px; width: 120px; height: 34px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- A skin surface: an empty anchor node on the left, a protected control on the right. -->
|
||||
<div class="ws-skin-root" data-ws-skin="community.slot-fixture" data-ws-part="app">
|
||||
<div id="dock" data-ws-part="voice.audio-dock">
|
||||
<div id="anchor" data-ws-part="skin.voice.dock.part-anchor"
|
||||
style="--skin-recovery-accent:#ffcc00;--skin-recovery-background:#102030;--skin-recovery-foreground:#ffffff;--skin-recovery-size:large"></div>
|
||||
<button type="button" id="mic" data-ws-part="voice.audio-dock.microphone">Mic</button>
|
||||
</div>
|
||||
</div>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
|
||||
import { bindHostSlot } from "/src/services/host-slot-placement.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const CSS = `
|
||||
.cap {
|
||||
position: fixed; inset: auto auto 12px 12px; margin: 0;
|
||||
display: flex; gap: 4px; padding: 4px; border: 0; pointer-events: auto;
|
||||
background: var(--ws-control-background, #fff);
|
||||
color: var(--ws-control-foreground, #31524f);
|
||||
}
|
||||
.cap button { min-height: var(--ws-control-hit, 28px); padding: 0 8px; }
|
||||
`;
|
||||
try {
|
||||
const layer = createHostOwnedLayer("recovery", CSS);
|
||||
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();
|
||||
|
||||
const anchor = document.getElementById("anchor");
|
||||
const mic = document.getElementById("mic");
|
||||
const changes = [];
|
||||
const binding = bindHostSlot({
|
||||
layer,
|
||||
control,
|
||||
anchor: "skin.voice.dock.part-anchor",
|
||||
skinId: "community.slot-fixture",
|
||||
align: "start",
|
||||
onModeChange: (change) => changes.push(change),
|
||||
});
|
||||
|
||||
const snap = (name) => {
|
||||
const rect = control.getBoundingClientRect();
|
||||
const anchorRect = anchor.getBoundingClientRect();
|
||||
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
|
||||
const style = getComputedStyle(control);
|
||||
return {
|
||||
name,
|
||||
mode: changes.at(-1)?.mode ?? "floating",
|
||||
reason: changes.at(-1)?.reason,
|
||||
inlineLeft: control.style.left,
|
||||
insideAnchor: rect.left >= anchorRect.left - 0.5 && rect.right <= anchorRect.right + 0.5
|
||||
&& rect.top >= anchorRect.top - 0.5 && rect.bottom <= anchorRect.bottom + 0.5,
|
||||
atDefaultCorner: Math.abs(rect.left - 12) < 1 && Math.abs(innerHeight - 12 - rect.bottom) < 1,
|
||||
hitIsLayerHost: hit === layer.host,
|
||||
background: style.backgroundColor,
|
||||
color: style.color,
|
||||
buttonHeight: control.querySelector("button").getBoundingClientRect().height,
|
||||
};
|
||||
};
|
||||
|
||||
const results = [];
|
||||
results.push(snap("initial"));
|
||||
|
||||
anchor.style.display = "none";
|
||||
binding.revalidate();
|
||||
results.push(snap("anchor-hidden"));
|
||||
|
||||
anchor.style.display = "";
|
||||
binding.revalidate();
|
||||
results.push(snap("restored-once"));
|
||||
binding.revalidate();
|
||||
results.push(snap("restored-twice"));
|
||||
|
||||
mic.style.left = "8px";
|
||||
mic.style.right = "auto";
|
||||
binding.revalidate();
|
||||
results.push(snap("covers-mic"));
|
||||
mic.style.left = "";
|
||||
mic.style.right = "";
|
||||
binding.revalidate();
|
||||
binding.revalidate();
|
||||
|
||||
anchor.style.transform = "translateX(-5000px)";
|
||||
binding.revalidate();
|
||||
results.push(snap("anchor-offscreen"));
|
||||
anchor.style.transform = "";
|
||||
binding.revalidate();
|
||||
binding.revalidate();
|
||||
|
||||
anchor.style.setProperty("--skin-recovery-foreground", "#102030");
|
||||
binding.revalidate();
|
||||
results.push(snap("unreadable-tokens"));
|
||||
|
||||
binding.dispose();
|
||||
results.push({
|
||||
...snap("disposed"),
|
||||
leftoverAccent: control.style.getPropertyValue("--ws-control-accent"),
|
||||
});
|
||||
output.textContent = JSON.stringify({ results, changes });
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error && error.stack || error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,202 +1,455 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { compileSkinCss } from "../../src/shared/skin-css.ts";
|
||||
|
||||
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
|
||||
const webRoot = fileURLToPath(new URL("../", import.meta.url));
|
||||
const CHROME = [process.env.WEBSPEAK_TEST_CHROME, "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"]
|
||||
.find((candidate) => candidate && existsSync(candidate));
|
||||
|
||||
const compileHostile = (css) => compileSkinCss(css, "community.hostile-fixture", {}, 3).css;
|
||||
|
||||
/**
|
||||
* Hostile rules that the compiler still accepts (they are legitimate page /
|
||||
* themable-host styling) but that must not be able to hide, cover, or disable
|
||||
* the recovery entry. `fullscreen-audio-dock` is the case the previous review
|
||||
* reproduced: a public part promoted to a `z-index: 2147483647` fullscreen layer.
|
||||
*/
|
||||
const scenarios = [
|
||||
{
|
||||
name: "fullscreen-audio-dock",
|
||||
css: compileHostile('[data-ws-part="voice.audio-dock"] { position: fixed; inset: 0; z-index: 2147483647; }'),
|
||||
},
|
||||
{
|
||||
name: "opacity-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { opacity: 0; }'),
|
||||
},
|
||||
{
|
||||
name: "filter-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { filter: opacity(0); }'),
|
||||
},
|
||||
{
|
||||
name: "display-none-overlay",
|
||||
css: compileHostile('[data-ws-part="host.plugins.overlay"] { display: none !important; }'),
|
||||
},
|
||||
{
|
||||
name: "pointer-events-none",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"], [data-ws-part="host.plugins.overlay"] { pointer-events: none !important; }'),
|
||||
},
|
||||
];
|
||||
|
||||
test("host chrome renders recovery and authorization in a closed-shadow top layer", async () => {
|
||||
const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin] = await Promise.all([
|
||||
read("../src/components/HostChrome.vue"),
|
||||
read("../src/components/InstanceAuthorization.vue"),
|
||||
read("../src/services/host-owned-layer.ts"),
|
||||
read("../src/services/host-chrome.ts"),
|
||||
read("../src/composables/usePublicSkin.ts"),
|
||||
]);
|
||||
|
||||
// Recovery: closed shadow root + manual popover + no skin hook.
|
||||
assert.match(hostChrome, /createHostOwnedLayer\("recovery"/);
|
||||
assert.match(hostChrome, /popover="manual"/);
|
||||
assert.match(hostChrome, /data-ws-recovery-action="built-in"/);
|
||||
assert.match(hostChrome, /requestBuiltInSkin/);
|
||||
assert.match(hostChrome, /isThirdPartySkinActive/);
|
||||
assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/);
|
||||
|
||||
// Authorization: showModal() inside the same host-owned mechanism.
|
||||
assert.match(authorization, /createHostOwnedLayer\('authorization'/);
|
||||
assert.match(authorization, /showModal\(\)/);
|
||||
assert.doesNotMatch(authorization, /data-ws-part="host\.permission"/);
|
||||
|
||||
// The layer itself: closed shadow root, no data-ws-part, fixed fallback.
|
||||
assert.match(ownedLayer, /attachShadow\(\{ mode: "closed" \}\)/);
|
||||
assert.match(ownedLayer, /data-ws-host-layer/);
|
||||
assert.doesNotMatch(ownedLayer, /setAttribute\("data-ws-part"/);
|
||||
|
||||
// The reset path is independent of the skinnable plugin overlay.
|
||||
assert.match(hostChromeService, /requestBuiltInSkin/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive/);
|
||||
assert.match(publicSkin, /hostBuiltInSkinRequests/);
|
||||
assert.match(publicSkin, /switchToBuiltIn/);
|
||||
|
||||
// Defense in depth: there is still no compiler route to a "host.recovery"
|
||||
// selector, even if a node ever regressed to carrying that attribute.
|
||||
for (const selector of ['[data-ws-part="host.recovery"]', '[data-ws-part="host.permission"]']) {
|
||||
assert.throws(() => compileSkinCss(`${selector} { display: none; }`, "community.evil", {}, 3), /Trusted or unknown host part/);
|
||||
}
|
||||
|
||||
// A leading `:root` must not reach body-level siblings (the host layer in the
|
||||
// preview/fixture topology) through `+` / `~`.
|
||||
for (const selector of [
|
||||
":root ~ [data-ws-host-layer]",
|
||||
":root ~ *",
|
||||
":root + [data-ws-host-layer]",
|
||||
":root:hover ~ *",
|
||||
]) {
|
||||
assert.throws(
|
||||
() => compileSkinCss(`${selector} { display: none !important; }`, "community.evil", {}, 3),
|
||||
/sibling combinator after :root/,
|
||||
selector,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("the themed preview keeps recovery in its own hookless top layer", async () => {
|
||||
const [preview, bridge] = await Promise.all([
|
||||
read("../host-chrome-preview.html"),
|
||||
read("../src/services/host-chrome-preview.ts"),
|
||||
]);
|
||||
assert.match(bridge, /resolveHiddenHostParts/);
|
||||
assert.match(preview, /host-chrome-preview\.ts/);
|
||||
assert.match(preview, /resolveHiddenHostParts\(chromeData, \[\]\)/);
|
||||
assert.match(preview, /hiddenParts\.has\(part\)/);
|
||||
assert.match(preview, /isHostPartReachable\(/);
|
||||
assert.match(preview, /launcherReachable/);
|
||||
assert.match(preview, /recoveryLayer\.remove\(\)/);
|
||||
assert.match(preview, /popover="manual"/);
|
||||
assert.doesNotMatch(preview, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(preview, /const watermarkHidden = getComputedStyle/);
|
||||
});
|
||||
|
||||
test("the public-skin composable opts in only through chrome.json#visibleParts", async () => {
|
||||
const usePublicSkin = await read("../src/composables/usePublicSkin.ts");
|
||||
assert.match(usePublicSkin, /setSkinHostChromeParts\(skin\?\.chromeData\)/);
|
||||
// Sniffing the combined stylesheet would match the importer-generated
|
||||
// hiddenParts/icon CSS and leak decorations for hiddenParts-only packs.
|
||||
assert.doesNotMatch(usePublicSkin, /\.test\(skin\.css\)/);
|
||||
});
|
||||
|
||||
async function dumpDom(url) {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(CHROME, [
|
||||
"--headless=new",
|
||||
"--no-sandbox",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--hide-scrollbars",
|
||||
"--dump-dom",
|
||||
url,
|
||||
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
reject(new Error(`Headless Chrome timed out.\n${stderr.slice(-2000)}`));
|
||||
}, 60000);
|
||||
child.on("error", (error) => { clearTimeout(timer); reject(error); });
|
||||
child.on("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (!stdout.includes('id="result"')) {
|
||||
reject(new Error(`Headless Chrome exited ${code} without a result.\n${stderr.slice(-2000)}`));
|
||||
return;
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("recovery stays visible and clickable under hostile compiled skins", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
|
||||
const server = await createServer({
|
||||
root: webRoot,
|
||||
configFile: path.join(webRoot, "vite.config.ts"),
|
||||
logLevel: "silent",
|
||||
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
|
||||
});
|
||||
t.after(() => server.close());
|
||||
await server.listen();
|
||||
const address = server.httpServer?.address();
|
||||
const port = address && typeof address === "object" ? address.port : 0;
|
||||
assert.ok(port, "Vite did not expose a listening port");
|
||||
|
||||
const hash = encodeURIComponent(JSON.stringify(scenarios));
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-chrome-recovery.html#${hash}`);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1]);
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
assert.equal(payload.results.length, scenarios.length);
|
||||
|
||||
assert.ok(payload.authorization, "the authorization dialog was not mounted");
|
||||
assert.equal(payload.authorization.modalOpen, true, "the authorization dialog is not modal / in the top layer");
|
||||
assert.equal(payload.authorization.topLayerHit, true, "the hostile layer covers the authorization dialog");
|
||||
assert.equal(payload.authorization.hostileCovered, false, "the hostile layer received the authorization hit test");
|
||||
assert.equal(payload.authorization.layerOutsideSkinRoot, true, "the authorization dialog was rendered inside .ws-skin-root");
|
||||
assert.equal(payload.authorization.sized, true, "the authorization dialog has no layout box");
|
||||
|
||||
// The pre-Popover / rejected-promotion fallback must actually lay the capsule
|
||||
// out: a closed [popover] is display:none !important until the attribute goes.
|
||||
assert.ok(payload.popoverFallback, "the fixture did not exercise the popover fallback");
|
||||
assert.equal(payload.popoverFallback.display, "flex", "the fallback capsule is not displayed");
|
||||
assert.equal(payload.popoverFallback.popoverAttribute, false, "the popover attribute still forces display:none");
|
||||
assert.equal(payload.popoverFallback.visible, true, "the fallback capsule has no layout box");
|
||||
|
||||
for (const result of payload.results) {
|
||||
assert.equal(result.popoverOpen, true, `${result.name}: recovery popover is not in the top layer`);
|
||||
assert.equal(result.topLayerHit, true, `${result.name}: recovery is covered by the hostile layer`);
|
||||
assert.equal(result.hostileCovered, false, `${result.name}: the hostile layer received the hit test`);
|
||||
assert.equal(result.visible, true, `${result.name}: recovery is visually hidden or non-interactive`);
|
||||
assert.equal(result.clicked, true, `${result.name}: clicking "use built-in skin" did not reach the handler`);
|
||||
assert.equal(result.layerOutsideSkinRoot, true, `${result.name}: recovery was rendered inside .ws-skin-root`);
|
||||
}
|
||||
});
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { compileSkinCss } from "../../src/shared/skin-css.ts";
|
||||
|
||||
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
|
||||
const webRoot = fileURLToPath(new URL("../", import.meta.url));
|
||||
const CHROME = [process.env.WEBSPEAK_TEST_CHROME, "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"]
|
||||
.find((candidate) => candidate && existsSync(candidate));
|
||||
|
||||
const compileHostile = (css) => compileSkinCss(css, "community.hostile-fixture", {}, 3).css;
|
||||
|
||||
/**
|
||||
* Hostile rules that the compiler still accepts (they are legitimate page /
|
||||
* themable-host styling) but that must not be able to hide, cover, or disable
|
||||
* the recovery entry. `fullscreen-audio-dock` is the case the previous review
|
||||
* reproduced: a public part promoted to a `z-index: 2147483647` fullscreen layer.
|
||||
*/
|
||||
const scenarios = [
|
||||
{
|
||||
name: "fullscreen-audio-dock",
|
||||
css: compileHostile('[data-ws-part="voice.audio-dock"] { position: fixed; inset: 0; z-index: 2147483647; }'),
|
||||
},
|
||||
{
|
||||
name: "opacity-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { opacity: 0; }'),
|
||||
},
|
||||
{
|
||||
name: "filter-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { filter: opacity(0); }'),
|
||||
},
|
||||
{
|
||||
name: "display-none-overlay",
|
||||
css: compileHostile('[data-ws-part="host.plugins.overlay"] { display: none !important; }'),
|
||||
},
|
||||
{
|
||||
name: "pointer-events-none",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"], [data-ws-part="host.plugins.overlay"] { pointer-events: none !important; }'),
|
||||
},
|
||||
{
|
||||
// Decorative host chrome may legitimately be a fixed, viewport-sized,
|
||||
// max-stacking decoration. Recovery lives in a closed-shadow top layer and
|
||||
// must still win the hit test.
|
||||
name: "decorative-watermark-overlay",
|
||||
css: compileHostile(`
|
||||
@keyframes drift { from { transform: translateX(0); } to { transform: translateX(12px); } }
|
||||
[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; background: #123; animation: drift 3s ease-in-out infinite alternate; }
|
||||
`),
|
||||
},
|
||||
];
|
||||
|
||||
test("host chrome renders recovery and authorization in a closed-shadow top layer", async () => {
|
||||
const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin, recoveryNotice, slotPlacement] = await Promise.all([
|
||||
read("../src/components/HostChrome.vue"),
|
||||
read("../src/components/InstanceAuthorization.vue"),
|
||||
read("../src/services/host-owned-layer.ts"),
|
||||
read("../src/services/host-chrome.ts"),
|
||||
read("../src/composables/usePublicSkin.ts"),
|
||||
read("../src/components/SkinLoadRecoveryNotice.vue"),
|
||||
read("../src/services/host-slot-placement.ts"),
|
||||
]);
|
||||
|
||||
// Recovery: closed shadow root + manual popover + no skin hook.
|
||||
assert.match(hostChrome, /createHostOwnedLayer\("recovery"/);
|
||||
assert.match(hostChrome, /popover="manual"/);
|
||||
assert.match(hostChrome, /data-ws-recovery-action="built-in"/);
|
||||
assert.match(hostChrome, /requestBuiltInSkin/);
|
||||
assert.match(hostChrome, /isThirdPartySkinActive/);
|
||||
// The shortcut runs in the capture phase so a plugin/skin capture listener
|
||||
// cannot swallow it with preventDefault().
|
||||
assert.match(hostChrome, /addEventListener\("keydown", onKeydown, true\)/);
|
||||
assert.match(hostChrome, /removeEventListener\("keydown", onKeydown, true\)/);
|
||||
// Escape closes the popover from inside its closed shadow root.
|
||||
assert.match(hostChrome, /@keydown\.escape="onRecoveryEscape"/);
|
||||
assert.match(hostChrome, /function onRecoveryEscape\(\) \{\s*shortcutOpen\.value = false;/);
|
||||
assert.doesNotMatch(hostChrome, /event\.defaultPrevented \|\| event\.repeat/);
|
||||
assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/);
|
||||
// Slots are a declarative anchor, not a skin hook: the host still binds the
|
||||
// capsule itself and switches back to the fixed position at runtime.
|
||||
assert.match(hostChrome, /activeHostSlot\("host\.recovery"\)/);
|
||||
assert.match(hostChrome, /bindHostSlot\(/);
|
||||
assert.match(hostChrome, /onModeChange/);
|
||||
assert.match(slotPlacement, /querySelectorAll\("\.ws-skin-root"\)/);
|
||||
assert.match(slotPlacement, /isHostPartReachable\(/);
|
||||
assert.match(slotPlacement, /evaluateSlottedControl/);
|
||||
assert.match(hostChromeService, /export function activeHostSlot/);
|
||||
assert.match(hostChromeService, /HOST_SLOTTABLE_PART_IDS\.has\(part\)/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive\(\)/);
|
||||
// Host-owned controls share one sanitized token reader; no per-control palette copy.
|
||||
assert.match(hostChrome, /bindHostControlTheme/);
|
||||
assert.match(hostChrome, /--ws-control-background/);
|
||||
assert.match(recoveryNotice, /SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS/);
|
||||
assert.match(recoveryNotice, /--ws-control-background/);
|
||||
assert.match(authorization, /PERMISSION_CONTROL_DEFAULTS/);
|
||||
assert.match(authorization, /--ws-control-background/);
|
||||
|
||||
// Authorization: showModal() inside the same host-owned mechanism.
|
||||
assert.match(authorization, /createHostOwnedLayer\('authorization'/);
|
||||
assert.match(authorization, /showModal\(\)/);
|
||||
assert.doesNotMatch(authorization, /data-ws-part="host\.permission"/);
|
||||
|
||||
// The load-failure banner is trusted UI too: closed shadow layer, stylesheet
|
||||
// inside the boundary, no document-level scoped stylesheet to override.
|
||||
assert.match(recoveryNotice, /createHostOwnedLayer\("skin-load"/);
|
||||
assert.match(recoveryNotice, /data-ws-part="app\.skin-load-recovery"/);
|
||||
assert.doesNotMatch(recoveryNotice, /<style scoped>/);
|
||||
|
||||
// The layer itself: closed shadow root, no data-ws-part, fixed fallback.
|
||||
assert.match(ownedLayer, /attachShadow\(\{ mode: "closed" \}\)/);
|
||||
assert.match(ownedLayer, /data-ws-host-layer/);
|
||||
assert.doesNotMatch(ownedLayer, /setAttribute\("data-ws-part"/);
|
||||
|
||||
// The reset path is independent of the skinnable plugin overlay.
|
||||
assert.match(hostChromeService, /requestBuiltInSkin/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive/);
|
||||
assert.match(publicSkin, /hostBuiltInSkinRequests/);
|
||||
assert.match(publicSkin, /switchToBuiltIn/);
|
||||
|
||||
// Defense in depth: there is still no compiler route to a "host.recovery"
|
||||
// selector, even if a node ever regressed to carrying that attribute.
|
||||
for (const selector of ['[data-ws-part="host.recovery"]', '[data-ws-part="host.permission"]']) {
|
||||
assert.throws(() => compileSkinCss(`${selector} { display: none; }`, "community.evil", {}, 3), /Trusted or unknown host part/);
|
||||
}
|
||||
|
||||
// A leading `:root` must not reach body-level siblings (the host layer in the
|
||||
// preview/fixture topology) through `+` / `~`.
|
||||
for (const selector of [
|
||||
":root ~ [data-ws-host-layer]",
|
||||
":root ~ *",
|
||||
":root + [data-ws-host-layer]",
|
||||
":root:hover ~ *",
|
||||
]) {
|
||||
assert.throws(
|
||||
() => compileSkinCss(`${selector} { display: none !important; }`, "community.evil", {}, 3),
|
||||
/sibling combinator after :root/,
|
||||
selector,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("the themed preview keeps recovery in its own hookless top layer", async () => {
|
||||
const [preview, bridge] = await Promise.all([
|
||||
read("../host-chrome-preview.html"),
|
||||
read("../src/services/host-chrome-preview.ts"),
|
||||
]);
|
||||
assert.match(bridge, /resolveHiddenHostParts/);
|
||||
assert.match(preview, /host-chrome-preview\.ts/);
|
||||
assert.match(preview, /resolveHiddenHostParts\(chromeData, \[\]\)/);
|
||||
assert.match(preview, /hiddenParts\.has\(part\)/);
|
||||
assert.match(preview, /isHostPartReachable\(/);
|
||||
assert.match(preview, /launcherReachable/);
|
||||
assert.match(preview, /recoveryLayer\.remove\(\)/);
|
||||
assert.match(preview, /popover="manual"/);
|
||||
assert.doesNotMatch(preview, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(preview, /const watermarkHidden = getComputedStyle/);
|
||||
});
|
||||
|
||||
test("the public-skin composable opts in only through chrome.json#visibleParts", async () => {
|
||||
const usePublicSkin = await read("../src/composables/usePublicSkin.ts");
|
||||
assert.match(usePublicSkin, /setSkinHostChromeParts\(skin\?\.chromeData\)/);
|
||||
// Sniffing the combined stylesheet would match the importer-generated
|
||||
// hiddenParts/icon CSS and leak decorations for hiddenParts-only packs.
|
||||
assert.doesNotMatch(usePublicSkin, /\.test\(skin\.css\)/);
|
||||
});
|
||||
|
||||
async function dumpDom(url, extraArgs = []) {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(CHROME, [
|
||||
"--headless=new",
|
||||
"--no-sandbox",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--hide-scrollbars",
|
||||
...extraArgs,
|
||||
"--dump-dom",
|
||||
url,
|
||||
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
reject(new Error(`Headless Chrome timed out.\n${stderr.slice(-2000)}`));
|
||||
}, 60000);
|
||||
child.on("error", (error) => { clearTimeout(timer); reject(error); });
|
||||
child.on("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (!stdout.includes('id="result"')) {
|
||||
reject(new Error(`Headless Chrome exited ${code} without a result.\n${stderr.slice(-2000)}`));
|
||||
return;
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("recovery stays visible and clickable under hostile compiled skins", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
|
||||
const server = await createServer({
|
||||
root: webRoot,
|
||||
configFile: path.join(webRoot, "vite.config.ts"),
|
||||
logLevel: "silent",
|
||||
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
|
||||
});
|
||||
t.after(() => server.close());
|
||||
await server.listen();
|
||||
const address = server.httpServer?.address();
|
||||
const port = address && typeof address === "object" ? address.port : 0;
|
||||
assert.ok(port, "Vite did not expose a listening port");
|
||||
|
||||
const hash = encodeURIComponent(JSON.stringify(scenarios));
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-chrome-recovery.html#${hash}`);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1]);
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
assert.equal(payload.results.length, scenarios.length);
|
||||
|
||||
assert.ok(payload.authorization, "the authorization dialog was not mounted");
|
||||
assert.equal(payload.authorization.modalOpen, true, "the authorization dialog is not modal / in the top layer");
|
||||
assert.equal(payload.authorization.topLayerHit, true, "the hostile layer covers the authorization dialog");
|
||||
assert.equal(payload.authorization.hostileCovered, false, "the hostile layer received the authorization hit test");
|
||||
assert.equal(payload.authorization.layerOutsideSkinRoot, true, "the authorization dialog was rendered inside .ws-skin-root");
|
||||
assert.equal(payload.authorization.sized, true, "the authorization dialog has no layout box");
|
||||
|
||||
// The pre-Popover / rejected-promotion fallback must actually lay the capsule
|
||||
// out: a closed [popover] is display:none !important until the attribute goes.
|
||||
assert.ok(payload.popoverFallback, "the fixture did not exercise the popover fallback");
|
||||
assert.equal(payload.popoverFallback.display, "flex", "the fallback capsule is not displayed");
|
||||
assert.equal(payload.popoverFallback.popoverAttribute, false, "the popover attribute still forces display:none");
|
||||
assert.equal(payload.popoverFallback.visible, true, "the fallback capsule has no layout box");
|
||||
|
||||
for (const result of payload.results) {
|
||||
assert.equal(result.popoverOpen, true, `${result.name}: recovery popover is not in the top layer`);
|
||||
assert.equal(result.topLayerHit, true, `${result.name}: recovery is covered by the hostile layer`);
|
||||
assert.equal(result.hitIsLayerHost, true, `${result.name}: elementFromPoint did not retarget the closed shadow root to the layer host`);
|
||||
assert.equal(result.hostileCovered, false, `${result.name}: the hostile layer received the hit test`);
|
||||
assert.equal(result.visible, true, `${result.name}: recovery is visually hidden or non-interactive`);
|
||||
assert.equal(result.clicked, true, `${result.name}: clicking "use built-in skin" did not reach the handler`);
|
||||
assert.equal(result.layerOutsideSkinRoot, true, `${result.name}: recovery was rendered inside .ws-skin-root`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a declared slot docks the capsule and falls back at runtime", { 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-placement.html`);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
|
||||
|
||||
const initial = byName.initial;
|
||||
assert.equal(initial.mode, "slotted", JSON.stringify(payload));
|
||||
assert.equal(initial.insideAnchor, true, "the capsule is not placed over the anchor");
|
||||
assert.equal(initial.hitIsLayerHost, true, "the docked capsule is not the hit-test target");
|
||||
assert.equal(initial.background, "rgb(16, 32, 48)", "skin background token was not applied");
|
||||
assert.equal(initial.color, "rgb(255, 255, 255)", "skin foreground token was not applied");
|
||||
assert.ok(initial.buttonHeight >= 36, "the large size tier minimum was not enforced");
|
||||
|
||||
assert.equal(byName["anchor-hidden"].mode, "floating");
|
||||
assert.equal(byName["anchor-hidden"].reason, "anchor-missing");
|
||||
assert.equal(byName["anchor-hidden"].inlineLeft, "");
|
||||
assert.equal(byName["anchor-hidden"].atDefaultCorner, true);
|
||||
|
||||
// Anti-flap: one good check after a fallback is not enough to re-dock.
|
||||
assert.equal(byName["restored-once"].mode, "floating");
|
||||
assert.equal(byName["restored-twice"].mode, "slotted");
|
||||
assert.equal(byName["restored-twice"].insideAnchor, true);
|
||||
|
||||
assert.equal(byName["covers-mic"].mode, "floating");
|
||||
assert.equal(byName["covers-mic"].reason, "covers-protected");
|
||||
assert.equal(byName["covers-mic"].atDefaultCorner, true);
|
||||
|
||||
assert.equal(byName["anchor-offscreen"].mode, "floating");
|
||||
// An invisible/off-screen element is never resolved as the anchor at all.
|
||||
assert.equal(byName["anchor-offscreen"].reason, "anchor-missing");
|
||||
assert.equal(byName["anchor-offscreen"].atDefaultCorner, true);
|
||||
|
||||
// Foreground equal to background: the whole colour group reverts.
|
||||
assert.equal(byName["unreadable-tokens"].background, "rgb(255, 255, 255)");
|
||||
assert.equal(byName["unreadable-tokens"].color, "rgb(49, 82, 79)");
|
||||
|
||||
assert.equal(byName.disposed.inlineLeft, "");
|
||||
assert.equal(byName.disposed.atDefaultCorner, true);
|
||||
assert.equal(byName.disposed.leftoverAccent, "");
|
||||
});
|
||||
|
||||
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,
|
||||
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-placement.html`, ["--virtual-time-budget=60000", "--window-size=1280,800"]);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
|
||||
|
||||
// Default corner covers the microphone, bottom-right covers the (disabled)
|
||||
// Send button and top-left a server strip: the capsule takes a free spot.
|
||||
const first = byName["dock-and-send"];
|
||||
assert.deepEqual(first.covered, [], JSON.stringify(payload));
|
||||
assert.notEqual(first.position, "bottom-left");
|
||||
assert.notEqual(first.position, "bottom-right");
|
||||
assert.equal(first.capsuleHit, true, "the moved capsule is not clickable");
|
||||
assert.equal(first.compact, false);
|
||||
|
||||
// Settled: repeated re-checks over ~2 s never move it again (no jitter).
|
||||
assert.deepEqual(byName.stable.positions, [first.position], JSON.stringify(byName.stable));
|
||||
// A full-screen click-away layer is no reason to fold to the mark.
|
||||
assert.equal(byName["click-away"].compact, false, JSON.stringify(byName["click-away"]));
|
||||
// Two host floating controls never overlap, settle, and neither covers Send.
|
||||
const two = byName["two-controls"];
|
||||
assert.equal(two.overlap, false, JSON.stringify(two));
|
||||
assert.equal(two.capMoves, 1, JSON.stringify(two));
|
||||
assert.ok(two.libMoves <= 2, JSON.stringify(two));
|
||||
assert.equal(two.sendCovered, false, JSON.stringify(two));
|
||||
assert.deepEqual(two.covered, [], JSON.stringify(two));
|
||||
|
||||
// A modal sheet opened by a click: its buttons are freed within one re-check.
|
||||
// Controls under the modal backdrop are not reachable anyway and do not count.
|
||||
assert.deepEqual(byName["after-click-sheet"].covered.filter((id) => id === "cancel" || id === "enter"), [], JSON.stringify(byName["after-click-sheet"]));
|
||||
assert.equal(byName["after-click-sheet"].capsuleHit, true);
|
||||
assert.notEqual(byName["after-click-sheet"].position, byName["after-click-sheet"].before, "the capsule did not move off the sheet");
|
||||
|
||||
// Nowhere is free: the capsule folds to its mark but stays clickable.
|
||||
assert.equal(byName.wall.compact, true, JSON.stringify(byName.wall));
|
||||
assert.equal(byName.wall.capsuleHit, true);
|
||||
|
||||
assert.equal(byName["wall-removed"].compact, false);
|
||||
// A screen change re-places the capsule within ~150 ms: back to the free
|
||||
// default corner, off the control that appeared under its old spot.
|
||||
const screen = byName["screen-change"];
|
||||
assert.notEqual(screen.away, "bottom-left", JSON.stringify(screen));
|
||||
assert.equal(screen.position, "bottom-left", JSON.stringify(screen));
|
||||
assert.equal(screen.exportCovered, false, JSON.stringify(screen));
|
||||
// Weighting: plain skin buttons are ordinary even inside the protected app root.
|
||||
assert.deepEqual(
|
||||
{ plain: byName.weights.plain, mic: byName.weights.mic, ghost: byName.weights.ghost, custom: byName.weights.custom },
|
||||
{ plain: 1, mic: 16, ghost: 0, custom: 1 },
|
||||
JSON.stringify(byName.weights),
|
||||
);
|
||||
// 12 s of a control hopping every 200 ms: at most a handful of moves, then the
|
||||
// capsule holds still (moves ≥ 1 s apart, frozen after 6 in 10 s).
|
||||
t.diagnostic(`flap ${JSON.stringify(byName.flap)} two ${JSON.stringify(byName["two-controls"])}`);
|
||||
assert.ok(byName.flap.moves <= 8, JSON.stringify(byName.flap));
|
||||
assert.equal(byName.flap.capsuleHit, true);
|
||||
assert.equal(byName.disposed.compact, false);
|
||||
});
|
||||
|
||||
test("floating host controls see through toasts and still step off a control while frozen", { 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-transient.html`, ["--virtual-time-budget=60000", "--window-size=1280,800"]);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
|
||||
t.diagnostic(JSON.stringify(payload.results));
|
||||
|
||||
// open-voice-surface desktop: toasts passing over "Share accompaniment" (or
|
||||
// the audio-settings modal) no longer make the default corner look free.
|
||||
const toast = byName["toast-transient"];
|
||||
assert.notEqual(toast.settled, "bottom-right", JSON.stringify(toast));
|
||||
assert.ok(!toast.positions.includes("bottom-right"), JSON.stringify(toast));
|
||||
assert.equal(toast.coveredSamples, 0, JSON.stringify(toast));
|
||||
assert.equal(toast.finalCovered, false, JSON.stringify(toast));
|
||||
// Same screen, modal backdrop over the corner: no return home, so the
|
||||
// button is usable the moment the dialog closes.
|
||||
assert.ok(!toast.afterModal.positions.includes("bottom-right"), JSON.stringify(toast));
|
||||
assert.equal(toast.afterModal.accompanimentCovered, false, JSON.stringify(toast));
|
||||
|
||||
// Parked at the default corner by the flap freeze on top of a control: one
|
||||
// escape about 1 s after the freeze (inside the 3 s pin), then still for the rest of it.
|
||||
const freeze = byName["freeze-escape"];
|
||||
assert.equal(freeze.flapMoves, 6, JSON.stringify(freeze));
|
||||
assert.equal(freeze.parkedPosition, "bottom-right", JSON.stringify(freeze));
|
||||
assert.equal(freeze.escapes.length, 1, JSON.stringify(freeze));
|
||||
assert.notEqual(freeze.escapes[0].position, "bottom-right", JSON.stringify(freeze));
|
||||
assert.ok(freeze.escapes[0].afterPinMs < 3000, JSON.stringify(freeze));
|
||||
assert.equal(freeze.movesWhileHeld, 0, JSON.stringify(freeze));
|
||||
});
|
||||
|
||||
test("host control tokens follow late skin CSS, resolve modern colours and refuse skin fonts", { 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");
|
||||
|
||||
// The fixture awaits animation frames, so give headless Chrome virtual time.
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-control-theme.html`, ["--virtual-time-budget=10000"]);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
|
||||
|
||||
assert.equal(byName["before-skin-css"].inlineBackground, "", "tokens were applied before the skin declared any");
|
||||
const late = byName["late-skin-css"];
|
||||
assert.match(late.inlineBackground, /^rgb\(\d+, \d+, \d+\)$/, "late skin CSS did not re-theme the control");
|
||||
assert.notEqual(late.inlineBackground, "rgb(255, 251, 235)", "the oklch() background fell back to the default palette");
|
||||
assert.equal(late.background, late.inlineBackground);
|
||||
assert.equal(late.inlineFont, "ui-sans-serif, system-ui, sans-serif", "a skin @font-face reached a host-owned control");
|
||||
assert.equal(byName["system-font"].inlineFont, 'Tahoma, "Segoe UI", sans-serif');
|
||||
assert.equal(byName["media-gated-skin-font"].inlineFont, "ui-sans-serif, system-ui, sans-serif", "a media-gated skin @font-face reached a host-owned control");
|
||||
const resized = byName["media-token-resize"];
|
||||
assert.equal(resized.beforeResize, "rgb(16, 32, 48)", "an @media token was not applied");
|
||||
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");
|
||||
});
|
||||
Reference in new issue
Block a user