diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index c841748..4a3d937 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -406,7 +406,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 | 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` | | 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` | | `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` | -| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠到皮肤布局,但仍无 CSS 钩子)/ `host.permission` / `app.skin-load-recovery` 仅为宿主内部标识(闭合 Shadow DOM,恢复入口与授权对话框还在顶层;无 CSS 钩子,见下文);`skin.library` 是皮肤菜单里的应用库入口 | +| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠,并可用 `--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`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。 @@ -453,7 +453,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 ### 恢复入口与授权对话框:结构上不可被皮肤触及 -`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接主题化的 CSS 钩子(`host.recovery` 只能通过下文的 `chrome.json#slots` 声明锚点和受限的 `--skin-recovery-*` 令牌间接参与布局):当前客户端把两者渲染在 `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"`,授权对话框是 `` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。 @@ -463,7 +463,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 **键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。 -`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),但它和恢复胶囊一样运行在闭合 Shadow DOM 宿主层中,编译后的皮肤 CSS 无法命中或改写它。`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"] ~ *` 一类兄弟选择器也碰不到它们。 @@ -492,13 +492,14 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 **这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。 -**样式令牌**:皮肤可在锚点或它的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。令牌只对声明了 `slots` 的皮肤生效(没有插槽的皮肤里写了也不会读取,胶囊保持默认外观)。锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。 +**样式令牌**:皮肤可在皮肤根(`: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-background` | 胶囊和按钮背景。宿主强制不透明(alpha 视为 1)。 | | `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 | +| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 | | `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 | | `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;其他值使用宿主默认字体。 | | `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 | @@ -509,6 +510,70 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 **键盘快捷键**:`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-` 前缀。 + +个别受保护部件的子元素(例如音频面板和音频设置里的 ``)由 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; +} +``` + +宿主从计算样式读取这些变量,通过影子根内的探针解析颜色,再写入控件自己的 `--ws-control-*` 变量;皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致: + +- 背景强制不透明(alpha 视为 1)。 +- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。 +- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。 +- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。 +- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符。 +- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。 +- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白,保证可读。 +- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。 + +`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`): diff --git a/docs/examples/host-chrome-demo.wskin b/docs/examples/host-chrome-demo.wskin index eaebaaa..45f8939 100644 Binary files a/docs/examples/host-chrome-demo.wskin and b/docs/examples/host-chrome-demo.wskin differ diff --git a/docs/examples/host-chrome-demo/manifest.json b/docs/examples/host-chrome-demo/manifest.json index ccac039..06f0305 100644 --- a/docs/examples/host-chrome-demo/manifest.json +++ b/docs/examples/host-chrome-demo/manifest.json @@ -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" diff --git a/docs/examples/host-chrome-demo/skin.css b/docs/examples/host-chrome-demo/skin.css index e2b9289..57ee104 100644 --- a/docs/examples/host-chrome-demo/skin.css +++ b/docs/examples/host-chrome-demo/skin.css @@ -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] { @@ -34,6 +54,43 @@ --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) --- */ [data-ws-part="host.plugins.launcher"] { background: #1d4f9c; diff --git a/docs/examples/host-chrome-themed.wskin b/docs/examples/host-chrome-themed.wskin index 8843ac7..927d40d 100644 Binary files a/docs/examples/host-chrome-themed.wskin and b/docs/examples/host-chrome-themed.wskin differ diff --git a/package.json b/package.json index ca63c7a..c6a147d 100644 --- a/package.json +++ b/package.json @@ -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/src/services/host-slot-placement.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/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", diff --git a/src/shared/skin-css.test.ts b/src/shared/skin-css.test.ts index 3b03c72..0c5d251 100644 --- a/src/shared/skin-css.test.ts +++ b/src/shared/skin-css.test.ts @@ -340,6 +340,57 @@ 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); }', + ]) { + assert.throws(() => compile(css), /must remain available|must remain on screen|cannot use indirect values/, css); + } +}); + 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; }'), diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts index c35e820..363fc9e 100644 --- a/src/shared/skin-css.ts +++ b/src/shared/skin-css.ts @@ -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", diff --git a/web/public/host-chrome-demo.wskin b/web/public/host-chrome-demo.wskin index eaebaaa..45f8939 100644 Binary files a/web/public/host-chrome-demo.wskin and b/web/public/host-chrome-demo.wskin differ diff --git a/web/public/host-chrome-themed.wskin b/web/public/host-chrome-themed.wskin index 8843ac7..927d40d 100644 Binary files a/web/public/host-chrome-themed.wskin and b/web/public/host-chrome-themed.wskin differ diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue index b7fb2fa..bf4ed35 100644 --- a/web/src/components/HostChrome.vue +++ b/web/src/components/HostChrome.vue @@ -85,6 +85,11 @@ import { import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js"; import { shouldShowRecovery } from "../services/host-chrome-visibility.js"; import { thirdPartyAllowed } from "../services/instance-authorization.js"; +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); @@ -102,12 +107,12 @@ const RECOVERY_LAYER_CSS = ` gap: 4px; max-width: calc(100vw - 24px); padding: 4px 5px 4px 9px; - border: 1px solid #9db6b2; - border-radius: var(--ws-recovery-radius, 999px); - background: var(--ws-recovery-background, color-mix(in srgb, #ffffff 92%, transparent)); - color: var(--ws-recovery-foreground, #31524f); - font-family: var(--ws-recovery-font, ui-sans-serif, system-ui, sans-serif); - font-size: var(--ws-recovery-font-size, 11px); + 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; } @@ -122,18 +127,18 @@ const RECOVERY_LAYER_CSS = ` .ws-host-recovery button { display: inline-flex; align-items: center; - min-height: var(--ws-recovery-hit, 28px); + min-height: var(--ws-control-hit, 28px); padding: 4px 9px; - border: 1px solid #9db6b2; - border-radius: var(--ws-recovery-radius, 999px); - background: var(--ws-recovery-background, #fff); - color: var(--ws-recovery-foreground, #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: var(--ws-recovery-builtin-border, #b45309); + border-color: var(--ws-control-builtin-border, #b45309); background: #fff7ed; color: #7c2d12; } @@ -142,10 +147,10 @@ const RECOVERY_LAYER_CSS = ` .ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) { gap: 0; padding: 4px; } .ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-action { display: none; } .ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-mark { - min-width: var(--ws-recovery-hit, 28px); - min-height: var(--ws-recovery-hit, 28px); + 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-recovery-accent, #4c8f88); outline-offset: 2px; } +.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; } } @@ -172,6 +177,21 @@ const showRecovery = computed(() => shouldShowRecovery({ // already reset). It never renders decoration on its own. const shortcutOpen = ref(false); const recoveryPopover = ref(null); + +/** + * Theme the capsule even when the skin does not declare a slot. `bindHostSlot` + * still reads the anchor first when a slot exists; this root-level pass covers + * the floating capsule and is overwritten by the anchor values on the next + * revalidation. + */ +const recoveryTheme = layer ? bindHostControlTheme({ + layer, + control: () => recoveryPopover.value, + part: "host.recovery", + defaults: RECOVERY_CONTROL_DEFAULTS, + source: () => findSkinRoot(hostChromeActiveSkinId.value), +}) : null; + const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value)); /** @@ -238,6 +258,9 @@ let slotBinding: HostSlotBinding | undefined; 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; @@ -294,6 +317,9 @@ watch([recoveryVisible, recoveryPopover], () => { slotBinding?.revalidate(); }); }, { flush: "post" }); +watch([recoveryPopover, hostChromeActiveSkinId], () => { + void nextTick(() => recoveryTheme?.apply()); +}, { flush: "post", immediate: true }); watch([slotConfig, hostChromeActiveSkinId], () => { void nextTick(() => { syncPopover(); @@ -317,6 +343,7 @@ onBeforeUnmount(() => { if (reachabilityTimer) clearInterval(reachabilityTimer); if (compactHoldTimer) clearTimeout(compactHoldTimer); slotBinding?.dispose(); + recoveryTheme?.dispose(); window.removeEventListener("resize", refreshLauncherReachability); window.removeEventListener("keydown", onKeydown, true); window.removeEventListener("pointerdown", onDocumentPointerDown, true); diff --git a/web/src/components/InstanceAuthorization.vue b/web/src/components/InstanceAuthorization.vue index f0c83c9..5676b90 100644 --- a/web/src/components/InstanceAuthorization.vue +++ b/web/src/components/InstanceAuthorization.vue @@ -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:color-mix(in srgb,var(--ws-control-foreground,#25324b) 76%,transparent)}.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,6 +45,17 @@ const layer: HostOwnedLayer | null = createHostOwnedLayer('authorization', AUTHO const props = defineProps<{ language: SiteLanguage }>(); const dialog = ref(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; @@ -50,5 +67,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(); }); diff --git a/web/src/components/SkinLoadRecoveryNotice.vue b/web/src/components/SkinLoadRecoveryNotice.vue index 69c464c..daf5bb1 100644 --- a/web/src/components/SkinLoadRecoveryNotice.vue +++ b/web/src/components/SkinLoadRecoveryNotice.vue @@ -1,6 +1,6 @@ diff --git a/web/src/services/host-control-tokens.test.ts b/web/src/services/host-control-tokens.test.ts new file mode 100644 index 0000000..5c89bcd --- /dev/null +++ b/web/src/services/host-control-tokens.test.ts @@ -0,0 +1,250 @@ +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, + hasHostControlTokens, + hostControlTokenKey, + hostControlTokenProperty, + parseCssColor, + relativeLuminance, + resolveHostControlTokens, + type HostControlRawTokens, +} from "./host-control-tokens.js"; + +type TokenMap = Record; + +const style = (tokens: TokenMap): Pick => ({ + 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); + + 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(); + 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); +}); diff --git a/web/src/services/host-control-tokens.ts b/web/src/services/host-control-tokens.ts new file mode 100644 index 0000000..fdf3bc1 --- /dev/null +++ b/web/src/services/host-control-tokens.ts @@ -0,0 +1,522 @@ +/** + * 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-- (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> = { + 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> = { + 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> = { + "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>; + /** 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}$/; + +/** 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; +} + +function sanitizeFont(value: string | undefined, fallback: string): 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; + } + return font; +} + +function readTokenSet( + style: Pick | 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; + +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; +} + +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 | 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--*` 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. + */ +export function resolveHostControlTokens( + style: Pick | null, + part: string, + probeColor: ColorProbe, + defaults: HostControlDefaults, +): 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), + 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; +} + +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 colour probe and never stores a token value on the + * skin side; callers re-apply it when the active skin or the control changes. + */ +export function bindHostControlTheme(options: HostControlThemeBindingOptions): HostControlThemeBinding { + let probe: HostControlColorProbe | null = null; + return { + apply() { + 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 ??= createHostControlColorProbe(options.layer.shadow); + applyHostControlTokens(control, resolveHostControlTokens(style, options.part, probe.probeColor, options.defaults)); + }, + dispose() { + probe?.dispose(); + probe = null; + }, + }; +} + +/** 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 HostControlColorProbe { + /** Resolve a CSS colour through the browser, inside the closed shadow root. */ + probeColor(raw: string | undefined): string | undefined; + dispose(): void; +} + +/** + * A hidden probe element for resolving arbitrary CSS colour syntax (for + * example `color-mix()` or `oklch()`) to a concrete `rgb()` value. + */ +export function createHostControlColorProbe(shadow: ShadowRoot): HostControlColorProbe { + const doc = shadow.ownerDocument; + const win = doc.defaultView; + 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; + }; + + return { + probeColor(raw) { + if (!raw) return undefined; + const first = resolveWith(raw, "rgb(1, 2, 3)"); + if (first !== "rgb(1, 2, 3)") return first; + const second = resolveWith(raw, "rgb(4, 5, 6)"); + return second === "rgb(4, 5, 6)" ? undefined : second; + }, + dispose() { + element.remove(); + }, + }; +} diff --git a/web/src/services/host-slot-placement.test.ts b/web/src/services/host-slot-placement.test.ts index 49faaad..6e2f114 100644 --- a/web/src/services/host-slot-placement.test.ts +++ b/web/src/services/host-slot-placement.test.ts @@ -2,22 +2,13 @@ import assert from "node:assert/strict"; import test from "node:test"; import { INITIAL_SLOT_MODE_STATE, - RECOVERY_BUILT_IN_BUTTON_BACKGROUND, - RECOVERY_MIN_ACCENT_CONTRAST, - RECOVERY_MIN_FONT_SIZE, - RECOVERY_MIN_FOREGROUND_CONTRAST, - RECOVERY_MIN_HIT_TARGET, - RECOVERY_SIZE_METRICS, computeSlotPlacement, - contrastRatio, evaluateSlottedControl, nextSlotModeState, - parseCssColor, rectsOverlap, - relativeLuminance, - resolveRecoveryTokens, 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 => ({ @@ -41,7 +32,7 @@ const baseEvaluation = { anchor: anchor(), controlRect: rect(180, 105, 120, 30), viewport: { width: 800, height: 600 }, - minHitTarget: RECOVERY_MIN_HIT_TARGET, + minHitTarget: HOST_CONTROL_MIN_HIT_TARGET, hitTestOk: true, }; @@ -135,90 +126,6 @@ test("control size, position and hit test are enforced", () => { ); }); -test("CSS colours parse to RGB and ignore alpha for contrast", () => { - assert.deepEqual(parseCssColor("#1d4f9c"), { r: 29, g: 79, b: 156 }); - assert.deepEqual(parseCssColor("#fff"), { r: 255, g: 255, b: 255 }); - assert.deepEqual(parseCssColor("#ffff"), { r: 255, g: 255, b: 255 }); - assert.deepEqual(parseCssColor("rgb(29, 79, 156)"), { r: 29, g: 79, b: 156 }); - assert.deepEqual(parseCssColor("rgb(29 79 156 / 50%)"), { r: 29, g: 79, b: 156 }); - assert.deepEqual(parseCssColor("rgba(255, 0, 0, .4)"), { r: 255, g: 0, b: 0 }); - assert.deepEqual(parseCssColor("rgb(300, -5, 0)"), { r: 255, g: 0, b: 0 }); - for (const invalid of ["", "red", "hsl(10, 20%, 30%)", "color(srgb 1 0 0)", "#12345", "rgb(1, 2)"]) { - assert.equal(parseCssColor(invalid), null, invalid); - } -}); - -test("WCAG contrast follows the relative-luminance formula", () => { - assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0); - assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1); - assert.equal(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }), 21); - assert.equal(contrastRatio({ r: 12, g: 34, b: 56 }, { r: 12, g: 34, b: 56 }), 1); -}); - -test("skin tokens default to the host palette", () => { - const tokens = resolveRecoveryTokens(); - assert.deepEqual(tokens, { - accent: "rgb(180, 83, 9)", - builtInBorder: "rgb(180, 83, 9)", - background: "rgb(255, 255, 255)", - foreground: "rgb(49, 82, 79)", - radius: 999, - font: "ui-sans-serif, system-ui, sans-serif", - size: "small", - hitTarget: 28, - fontSize: 11, - }); -}); - -test("a readable skin palette is kept and translucent backgrounds become opaque", () => { - const tokens = resolveRecoveryTokens({ - accent: "#47dcc4", - background: "rgba(9, 19, 23, 0.4)", - foreground: "#edf8f5", - }); - assert.equal(tokens.accent, "rgb(71, 220, 196)"); - assert.equal(tokens.background, "rgb(9, 19, 23)"); - assert.equal(tokens.foreground, "rgb(237, 248, 245)"); -}); - -test("an unreadable colour group falls back as a whole", () => { - const lowForeground = resolveRecoveryTokens({ background: "#777777", foreground: "#888888", accent: "#47dcc4" }); - assert.equal(lowForeground.background, "rgb(255, 255, 255)"); - assert.equal(lowForeground.foreground, "rgb(49, 82, 79)"); - assert.equal(lowForeground.accent, "rgb(180, 83, 9)"); - - const lowAccent = resolveRecoveryTokens({ background: "#ffffff", foreground: "#31524f", accent: "#eeeeee" }); - assert.equal(lowAccent.accent, "rgb(180, 83, 9)"); - assert.ok(contrastRatio(parseCssColor(lowAccent.accent)!, parseCssColor(lowAccent.background)!) >= RECOVERY_MIN_ACCENT_CONTRAST); - assert.ok(contrastRatio(parseCssColor(lowAccent.foreground)!, parseCssColor(lowAccent.background)!) >= RECOVERY_MIN_FOREGROUND_CONTRAST); -}); - -test("radius, font and size tokens are sanitized and host minimums win", () => { - assert.equal(resolveRecoveryTokens({ radius: "12px" }).radius, 12); - assert.equal(resolveRecoveryTokens({ radius: "2000px" }).radius, 999); - assert.equal(resolveRecoveryTokens({ radius: "-5px" }).radius, 0); - assert.equal(resolveRecoveryTokens({ radius: "1em" }).radius, 999); - assert.equal(resolveRecoveryTokens({ radius: "12" }).radius, 999); - - assert.equal( - resolveRecoveryTokens({ font: 'Tahoma, "Segoe UI", sans-serif' }).font, - 'Tahoma, "Segoe UI", sans-serif', - ); - for (const font of ["url(https://example.invalid/a.woff2)", "Tahoma; color: red", "x".repeat(121)]) { - assert.equal(resolveRecoveryTokens({ font }).font, "ui-sans-serif, system-ui, sans-serif", font); - } - - assert.equal(resolveRecoveryTokens({ size: "medium" }).hitTarget, 32); - assert.equal(resolveRecoveryTokens({ size: "medium" }).fontSize, 12); - assert.equal(resolveRecoveryTokens({ size: "large" }).hitTarget, 36); - assert.equal(resolveRecoveryTokens({ size: "large" }).fontSize, 13); - assert.equal(resolveRecoveryTokens({ size: "huge" }).size, "small"); - for (const metrics of Object.values(RECOVERY_SIZE_METRICS)) { - assert.ok(metrics.hitTarget >= RECOVERY_MIN_HIT_TARGET); - assert.ok(metrics.fontSize >= RECOVERY_MIN_FONT_SIZE); - } -}); - test("the mode gate does not flap between the anchor and the fallback", () => { let state = INITIAL_SLOT_MODE_STATE; // The first valid check slots immediately, even under the anti-flap rule. @@ -259,14 +166,3 @@ test("rect overlap ignores edge contact and sub-pixel slivers", () => { assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(99.5, 0, 50, 40)), false); assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(0, 60, 100, 40)), false); }); - -test("the built-in button border only uses an accent visible on its fixed light background", () => { - // Passes against the dark skin background, but vanishes on #fff7ed. - const pale = resolveRecoveryTokens({ background: "#141414", foreground: "#ffffff", accent: "#fff7ec" }); - assert.equal(pale.accent, "rgb(255, 247, 236)"); - assert.equal(pale.builtInBorder, "rgb(180, 83, 9)"); - assert.ok(contrastRatio(parseCssColor(pale.builtInBorder)!, RECOVERY_BUILT_IN_BUTTON_BACKGROUND) >= RECOVERY_MIN_ACCENT_CONTRAST); - - const strong = resolveRecoveryTokens({ background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" }); - assert.equal(strong.builtInBorder, "rgb(29, 78, 216)"); -}); diff --git a/web/src/services/host-slot-placement.ts b/web/src/services/host-slot-placement.ts index c061f66..c1b34e8 100644 --- a/web/src/services/host-slot-placement.ts +++ b/web/src/services/host-slot-placement.ts @@ -17,6 +17,15 @@ 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, + createHostControlColorProbe, + findSkinRoot, + resolveHostControlTokens, + type HostControlTokens, + type HostControlColorProbe, +} from "./host-control-tokens.js"; export interface SlotViewport { width: number; @@ -190,229 +199,6 @@ export function nextSlotModeState( }; } -/* ------------------------------------------------------------------ * - * Style tokens - * ------------------------------------------------------------------ */ - -export type RecoverySizeTier = "small" | "medium" | "large"; - -export interface RecoverySizeMetrics { - /** Host-enforced minimum button hit target in CSS pixels. */ - readonly hitTarget: number; - /** Host-enforced minimum font size in CSS pixels. */ - readonly fontSize: number; -} - -export const RECOVERY_MIN_HIT_TARGET = 28; -export const RECOVERY_MIN_FONT_SIZE = 11; -export const RECOVERY_MIN_FOREGROUND_CONTRAST = 4.5; -export const RECOVERY_MIN_ACCENT_CONTRAST = 3; - -/** Host-controlled metrics; a skin can choose a tier, never a smaller size. */ -export const RECOVERY_SIZE_METRICS: Readonly> = { - small: { hitTarget: RECOVERY_MIN_HIT_TARGET, fontSize: RECOVERY_MIN_FONT_SIZE }, - medium: { hitTarget: 32, fontSize: 12 }, - large: { hitTarget: 36, fontSize: 13 }, -}; - -export interface RecoveryRawTokens { - /** Computed-style colour values; unresolved CSS values are rejected. */ - accent?: string; - background?: string; - foreground?: string; - radius?: string; - font?: string; - size?: string; -} - -export interface RecoveryTokens { - accent: string; - /** - * Border of the built-in-skin button, which keeps its own fixed light - * background (`#fff7ed`). The skin accent is used only when it stays visible - * against that background; otherwise the host default accent is used there. - */ - builtInBorder: string; - background: string; - foreground: string; - radius: number; - font: string; - size: RecoverySizeTier; - hitTarget: number; - fontSize: number; -} - -export interface RgbColor { - r: number; - g: number; - b: number; -} - -/** CSS custom properties a skin declares on the anchor or an ancestor. */ -export const RECOVERY_SKIN_TOKEN_PROPERTIES = { - accent: "--skin-recovery-accent", - background: "--skin-recovery-background", - foreground: "--skin-recovery-foreground", - radius: "--skin-recovery-radius", - font: "--skin-recovery-font", - size: "--skin-recovery-size", -} as const; - -/** Host-owned variables set inside the closed shadow root. */ -export const RECOVERY_APPLIED_VARIABLES = { - accent: "--ws-recovery-accent", - builtInBorder: "--ws-recovery-builtin-border", - background: "--ws-recovery-background", - foreground: "--ws-recovery-foreground", - radius: "--ws-recovery-radius", - font: "--ws-recovery-font", - hitTarget: "--ws-recovery-hit", - fontSize: "--ws-recovery-font-size", -} as const; - -const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 }; -/** Fixed background of the built-in-skin button (`#fff7ed`). */ -export const RECOVERY_BUILT_IN_BUTTON_BACKGROUND: RgbColor = { r: 255, g: 247, b: 237 }; -const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 }; -const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 }; -const DEFAULT_RADIUS = 999; -const DEFAULT_FONT = "ui-sans-serif, system-ui, sans-serif"; -const MAX_RADIUS = 999; -const MAX_FONT_LENGTH = 120; -const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/; - -/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */ -export function parseCssColor(value: string | undefined | null): RgbColor | null { - if (!value) return null; - const text = value.trim().toLowerCase(); - const hex = /^#([0-9a-f]{3,8})$/.exec(text); - if (hex) { - const digits = hex[1]; - if (digits.length === 3 || digits.length === 4) { - return { - r: Number.parseInt(digits[0] + digits[0], 16), - g: Number.parseInt(digits[1] + digits[1], 16), - b: Number.parseInt(digits[2] + digits[2], 16), - }; - } - if (digits.length === 6 || digits.length === 8) { - return { - r: Number.parseInt(digits.slice(0, 2), 16), - g: Number.parseInt(digits.slice(2, 4), 16), - b: Number.parseInt(digits.slice(4, 6), 16), - }; - } - return null; - } - - const fn = /^rgba?\(([^()]*)\)$/.exec(text); - if (!fn) return null; - const parts = fn[1].replace(/\//g, " ").split(/[\s,]+/).filter(Boolean); - if (parts.length < 3 || parts.length > 4) return null; - const channels: number[] = []; - for (const part of parts.slice(0, 3)) { - const percent = part.endsWith("%"); - const parsed = Number.parseFloat(part); - if (!Number.isFinite(parsed)) return null; - const channel = percent ? parsed * 2.55 : parsed; - channels.push(Math.round(Math.min(255, Math.max(0, channel)))); - } - return { r: channels[0], g: channels[1], b: channels[2] }; -} - -export function formatRgb(color: RgbColor): string { - return `rgb(${color.r}, ${color.g}, ${color.b})`; -} - -/** WCAG 2.x relative luminance, 0 (black) to 1 (white). */ -export function relativeLuminance(color: RgbColor): number { - const channel = (value: number): number => { - const normalized = Math.min(255, Math.max(0, value)) / 255; - return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4; - }; - return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b); -} - -export function contrastRatio(first: RgbColor, second: RgbColor): number { - const lighter = Math.max(relativeLuminance(first), relativeLuminance(second)); - const darker = Math.min(relativeLuminance(first), relativeLuminance(second)); - return (lighter + 0.05) / (darker + 0.05); -} - -export function isRecoverySizeTier(value: unknown): value is RecoverySizeTier { - return value === "small" || value === "medium" || value === "large"; -} - -function sanitizeRadius(value: string | undefined): number { - if (!value) return DEFAULT_RADIUS; - const match = /^(-?\d+(?:\.\d+)?)px$/i.exec(value.trim()); - if (!match) return DEFAULT_RADIUS; - const radius = Number.parseFloat(match[1]); - return Number.isFinite(radius) ? Math.min(MAX_RADIUS, Math.max(0, radius)) : DEFAULT_RADIUS; -} - -function sanitizeFont(value: string | undefined): string { - if (!value) return DEFAULT_FONT; - const font = value.trim().replace(/\s+/g, " "); - if (!font || font.length > MAX_FONT_LENGTH || !FONT_FAMILY_PATTERN.test(font) || !/[A-Za-z0-9]/.test(font)) { - return DEFAULT_FONT; - } - return font; -} - -/** - * Sanitize skin-provided tokens. Colours are all-or-nothing: a readable - * foreground/background pair and a visible accent keep the skin palette; - * otherwise the whole colour group reverts to the host palette so a skin can - * never make the recovery action unreadable. - */ -export function resolveRecoveryTokens(raw: RecoveryRawTokens = {}): RecoveryTokens { - const accent = parseCssColor(raw.accent) ?? DEFAULT_ACCENT; - const background = parseCssColor(raw.background) ?? DEFAULT_BACKGROUND; - const foreground = parseCssColor(raw.foreground) ?? DEFAULT_FOREGROUND; - const readable = contrastRatio(foreground, background) >= RECOVERY_MIN_FOREGROUND_CONTRAST - && contrastRatio(accent, background) >= RECOVERY_MIN_ACCENT_CONTRAST; - const palette = readable ? { accent, background, foreground } : { - accent: DEFAULT_ACCENT, - background: DEFAULT_BACKGROUND, - foreground: DEFAULT_FOREGROUND, - }; - const sizeValue = raw.size?.trim(); - const size = isRecoverySizeTier(sizeValue) ? sizeValue : "small"; - const metrics = RECOVERY_SIZE_METRICS[size]; - const builtInBorder = contrastRatio(palette.accent, RECOVERY_BUILT_IN_BUTTON_BACKGROUND) >= RECOVERY_MIN_ACCENT_CONTRAST - ? palette.accent - : DEFAULT_ACCENT; - return { - accent: formatRgb(palette.accent), - builtInBorder: formatRgb(builtInBorder), - background: formatRgb(palette.background), - foreground: formatRgb(palette.foreground), - radius: sanitizeRadius(raw.radius), - font: sanitizeFont(raw.font), - size, - hitTarget: metrics.hitTarget, - fontSize: metrics.fontSize, - }; -} - -/** Apply (or clear) host-owned variables on the control inside the shadow root. */ -export function applyRecoveryTokens(control: HTMLElement, tokens: RecoveryTokens | null): void { - const style = control.style; - if (!tokens) { - for (const property of Object.values(RECOVERY_APPLIED_VARIABLES)) style.removeProperty(property); - return; - } - style.setProperty(RECOVERY_APPLIED_VARIABLES.accent, tokens.accent); - style.setProperty(RECOVERY_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder); - style.setProperty(RECOVERY_APPLIED_VARIABLES.background, tokens.background); - style.setProperty(RECOVERY_APPLIED_VARIABLES.foreground, tokens.foreground); - style.setProperty(RECOVERY_APPLIED_VARIABLES.radius, `${tokens.radius}px`); - style.setProperty(RECOVERY_APPLIED_VARIABLES.font, tokens.font); - style.setProperty(RECOVERY_APPLIED_VARIABLES.hitTarget, `${tokens.hitTarget}px`); - style.setProperty(RECOVERY_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`); -} - /* ------------------------------------------------------------------ * * DOM binding * ------------------------------------------------------------------ */ @@ -506,14 +292,6 @@ export function resolveSkinAnchor( return null; } -/** The active skin's root element; the token source while no anchor is usable. */ -export function findSkinRoot(skinId: string | undefined, doc: Document = document): Element | null { - for (const root of doc.querySelectorAll(".ws-skin-root")) { - if (!skinId || root.getAttribute("data-ws-skin") === skinId) return root; - } - return null; -} - export interface HostSlotModeChange { mode: "slotted" | "floating"; reason?: SlotFailureReason; @@ -560,7 +338,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding { let lastReason: SlotFailureReason | undefined; let currentAnchor: HTMLElement | null = null; let observer: ResizeObserver | null = null; - let probe: HTMLElement | null = null; + const colorProbe: HostControlColorProbe = createHostControlColorProbe(layer.shadow); let frame: number | undefined; let timer: ReturnType | undefined; let disposed = false; @@ -570,45 +348,14 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding { const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback); const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle); - function ensureProbe(): HTMLElement | null { - if (probe) return probe; - probe = doc.createElement("span"); - probe.setAttribute("aria-hidden", "true"); - probe.style.cssText = "position:absolute;left:-9999px;top:0;width:0;height:0;visibility:hidden;pointer-events:none;"; - layer.shadow.append(probe); - return probe; - } - - /** Resolve a CSS colour through the browser, inside the closed shadow root. */ - function probeColor(raw: string | undefined): string | undefined { - if (!raw) return undefined; - const element = ensureProbe(); - if (!element) return undefined; - // 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. - const resolveWith = (sentinel: string): string => { - element.style.color = sentinel; - element.style.color = raw; - return win.getComputedStyle(element).color; - }; - const first = resolveWith("rgb(1, 2, 3)"); - if (first !== "rgb(1, 2, 3)") return first; - const second = resolveWith("rgb(4, 5, 6)"); - return second === "rgb(4, 5, 6)" ? undefined : second; - } - - function readTokens(source: Element | null): RecoveryTokens { - if (!source) return resolveRecoveryTokens(); - const style = win.getComputedStyle(source); - const read = (property: string): string | undefined => style.getPropertyValue(property).trim() || undefined; - return resolveRecoveryTokens({ - accent: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.accent)), - background: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.background)), - foreground: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.foreground)), - radius: read(RECOVERY_SKIN_TOKEN_PROPERTIES.radius), - font: read(RECOVERY_SKIN_TOKEN_PROPERTIES.font), - size: read(RECOVERY_SKIN_TOKEN_PROPERTIES.size), - }); + function readTokens(source: Element | null): HostControlTokens { + if (!source) return resolveHostControlTokens(null, "host.recovery", colorProbe.probeColor, RECOVERY_CONTROL_DEFAULTS); + return resolveHostControlTokens( + win.getComputedStyle(source), + "host.recovery", + colorProbe.probeColor, + RECOVERY_CONTROL_DEFAULTS, + ); } function clearPlacement(): void { @@ -656,7 +403,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding { const tokenSource = anchorElement ?? (options.skinId ? findSkinRoot(options.skinId, doc) : null); const tokens = readTokens(tokenSource); - applyRecoveryTokens(control, tokenSource ? tokens : null); + applyHostControlTokens(control, tokenSource ? tokens : null); const controlBox = control.getBoundingClientRect(); maxSize = { @@ -783,9 +530,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding { win.removeEventListener("resize", schedule); win.removeEventListener("scroll", schedule, { capture: true }); clearPlacement(); - applyRecoveryTokens(control, null); - probe?.remove(); - probe = null; + applyHostControlTokens(control, null); + colorProbe.dispose(); }, }; } diff --git a/web/test/fixtures/host-slot-placement.html b/web/test/fixtures/host-slot-placement.html index 3970e48..7a57413 100644 --- a/web/test/fixtures/host-slot-placement.html +++ b/web/test/fixtures/host-slot-placement.html @@ -31,10 +31,10 @@ 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-recovery-background, #fff); - color: var(--ws-recovery-foreground, #31524f); + background: var(--ws-control-background, #fff); + color: var(--ws-control-foreground, #31524f); } -.cap button { min-height: var(--ws-recovery-hit, 28px); padding: 0 8px; } +.cap button { min-height: var(--ws-control-hit, 28px); padding: 0 8px; } `; try { const layer = createHostOwnedLayer("recovery", CSS); @@ -113,7 +113,7 @@ try { binding.dispose(); results.push({ ...snap("disposed"), - leftoverAccent: control.style.getPropertyValue("--ws-recovery-accent"), + leftoverAccent: control.style.getPropertyValue("--ws-control-accent"), }); output.textContent = JSON.stringify({ results, changes }); } catch (error) { diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs index 1a05e2c..e3e1b5a 100644 --- a/web/test/host-chrome-recovery.test.mjs +++ b/web/test/host-chrome-recovery.test.mjs @@ -92,6 +92,13 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye 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'/);