diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 875fdd1..219b624 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -96,7 +96,7 @@ assets/preview.jpg # 可选:管理后台显示的预览图,也可 assets/background.webp # 可选:页面艺术素材 assets/brand.woff2 # 可选:自带字体 components.json # v3 可选:声明式组件或完整页面 surface -chrome.json # v3/v4 可选:宿主装饰隐藏与图标位图覆盖(见「chrome.json」章节) +chrome.json # v3/v4 可选:宿主装饰、图标位图与可信控件停靠(见「chrome.json」章节) assets/icons/language.png # v3/v4 可选:工具栏图标位图覆盖素材 plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件 plugins//index.js # v4 插件代码,目前只校验和缓存 @@ -406,7 +406,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 | 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` | | 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` | | `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` | -| 宿主外壳(皮肤根之外 / 宿主固定绘制) | `host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`、`app.skin-load-recovery`、`skin.library`;`host.recovery` / `host.permission` 仅为概念标识(闭合 Shadow DOM + 顶层,无 CSS 钩子,见下文) | +| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 | | 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) | `voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。 @@ -435,7 +435,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 - 皮肤激活时,宿主在 `documentElement` 上设置 `data-ws-host-skin="<皮肤 ID>"`;停用或回退到内置皮肤时立即移除。 - 编译 `skin.css` 时,**只**命中下列宿主部件的单个选择器会被限定到 `:root[data-ws-host-skin="<皮肤 ID>"] …`,其余规则仍限定到 `.ws-skin-root[data-ws-skin="…"]`。宿主部件的选择器必须**以可主题化的 `[data-ws-part="host.…"]` 开头**,不能把 `:root`、`html`、`body` 或 `*:has(…)` 作为规则主体;`:root:has([data-ws-part="host.watermark"])` 一类写法会被拒绝。皮肤作者不能自己写 `html`、`body`、`data-ws-host-skin`、`data-ws-route`、`data-theme` 或 `data-ws-skin` 选择器,也不能在同一选择器里混用宿主部件与页面部件;宿主部件只对 schema v3/v4 开放皮肤生效。 -- 宿主外壳的布局与层级由 WebSpeak 拥有:皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform` 等把 `host.plugins.overlay` 之类控件变成全屏遮罩。 +- 宿主外壳的布局与层级:应用库外壳 `host.plugins.overlay` 仍由 WebSpeak 拥有——皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform`、尺寸等把它或其子元素变成全屏遮罩。装饰性宿主部件(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)可以被重定位、改变尺寸和动画化;恢复路径不依赖它们。 - 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。 - 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。 - 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。 @@ -453,20 +453,129 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 ### 恢复入口与授权对话框:结构上不可被皮肤触及 -`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或主题化的 CSS 钩子:当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们: +`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局: 1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。 2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。 3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。 -**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角;它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。 +**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。 -**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。 +**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。 -`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅使用独立部件 `app.skin-load-recovery`(「切换到内置皮肤」),与恢复胶囊不是同一个钩子。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。 +`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。 恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。 +#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`) + +第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。 + +```json +"slots": { + "host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true } +} +``` + +| 字段 | 规则 | +| --- | --- | +| 键名 | 目前只接受 `host.recovery`(`src/shared/skin-visual-parts.ts` 的 `HOST_SLOTTABLE_PART_IDS`;后续可加入其他受保护控件)。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 | +| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称。不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。宿主只取第一个可见匹配;锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 | +| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;胶囊在锚点矩形内按此水平对齐,并垂直居中。 | +| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 | + +`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id: + +- v3 `components.json` 组件根:`skin..`。 +- v3 组件中带 `part` 的节点:`skin...part-`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin...control-part-`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。 +- v4 运行时插件生成的节点:`skin..runtime_plugin___.part-`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。 + +**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。 + +**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s(期间若默认角落盖住了控件,最多再挪开一次,之后保持不动);判断某个控件是否被盖住时会“看穿”短暂出现的提示条(`app.toast`)和另一个宿主浮动控件,提示条暂时挡住的控件仍按存在计算,不会因此把那个角落误判为空闲;同一页面内,当前位置不遮挡时不会为了回到默认角落而移动(默认角落“看起来空”可能只是被模态对话框的遮罩或提示条暂时挡住);进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,并在默认角落和当前位置都空闲(鼠标也不在那里)时回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。 + +**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。 + +| 令牌 | 规则 | +| --- | --- | +| `--skin-recovery-accent` | 强调色,用于紧凑模式焦点框和「使用内置皮肤」按钮的边框。与背景的对比度必须 ≥ 3,否则整组颜色回退。该按钮自身固定为浅色底 `#fff7ed`,如果强调色在这块浅底上对比度不足 3,只有这个按钮的边框改用宿主默认 `#b45309`,其余位置仍用皮肤强调色。 | +| `--skin-recovery-background` | 胶囊和按钮背景。宿主强制不透明(alpha 视为 1)。 | +| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 | +| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 | +| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 | +| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;列表中只要出现皮肤用 `@font-face` 注册的字体就整项忽略(只认系统已安装字体和通用族名);其他值使用宿主默认字体。 | +| `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 | + +颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。 + +**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停、键盘聚焦或点按/轻触 ◈ 时展开为完整按钮;点按展开会保持到焦点离开胶囊、在胶囊外按下指针或按 Escape。新皮肤激活后、胶囊首次成功停靠起的约 5 秒内始终显示完整胶囊(从停靠时刻开始计时,皮肤加载慢也不会提前收起),避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。 + +**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。 + +#### 受保护控件的主题化 + +28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。 + +**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`(字面值)、`outline` 等纯视觉属性都可以写: + +```css +[data-ws-part="voice.audio-dock.microphone"], +[data-ws-part="auth.password.dialog"], +[data-ws-part="home.footer.clear"] { + color: var(--skin-ink); + background: linear-gradient(135deg, #0f172a, #1e3a5f); + border: 2px solid var(--skin-accent); + border-radius: 16px; + font: 600 14px/1.4 Tahoma, "Segoe UI", sans-serif; + padding: 10px 16px; + min-width: 56px; + min-height: 56px; + box-shadow: 0 8px 24px #0006; +} +``` + +以下规则仍会被拒绝,因为它们会隐藏、禁用或把控件移出视口:`display:none`、`visibility:hidden/collapse`、`opacity:0`、`pointer-events:none`、使 `clip`/`clip-path`/`mask` 完全裁掉内容、`transform`/`scale` 缩到 0、`inset`/`top`/`left`/`margin` 等把控件推到视口外,以及在这些隐藏/移动属性上使用 `var()`/`attr()`。`margin` 仍算移动属性,所以 `margin: var(--skin-gap)` 会被拒绝;普通的小 `margin` 数值可以写。自定义变量仍然只能使用 `--skin-` 前缀。 + +个别受保护部件的子元素(例如音频面板和音频设置里的 ``)由 Vue 写入内联 `style`;要给滑轨本身换肤,用视觉属性的 `!important` 覆盖即可,受保护的外壳不受影响。 + +**宿主自有的受保护控件。** `host.recovery`、`app.skin-load-recovery` 横幅和授权对话框在闭合 Shadow DOM 内,皮肤 CSS 不能命中。宿主提供一组统一的令牌;皮肤把变量写在活动皮肤根(`:root`,编译后就是皮肤根)上即可,恢复胶囊也接受写在锚点或其祖先上的值: + +| 控件 | 每部件前缀 | 说明 | +| --- | --- | --- | +| `host.recovery` | `--skin-recovery-*` | 兼容原有令牌;写到锚点、锚点祖先或皮肤根上都有效 | +| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠。令牌取自横幅出现时的**活动**皮肤:加载失败后宿主会退回内置皮肤(内置皮肤不声明令牌),所以失败皮肤自己的值通常不会作用在自己的横幅上,横幅保持默认琥珀色 | +| 授权对话框(`host.permission` 概念) | `--skin-permission-*` | `host.permission` 没有 DOM 渲染点;令牌作用于宿主自己的授权对话框 | + +每个每部件令牌都有全局回退:`--skin-host-accent`、`--skin-host-background`、`--skin-host-foreground`、`--skin-host-border`、`--skin-host-radius`、`--skin-host-font`、`--skin-host-size`。每部件值优先于全局值。例如: + +```css +:root { + --skin-host-accent: #47dcc4; + --skin-host-background: #0b1418; + --skin-host-foreground: #edf8f5; + --skin-host-border: #2a5a54; + --skin-host-radius: 10px; + --skin-host-font: Tahoma, "Segoe UI", sans-serif; + --skin-host-size: medium; + + /* 只覆盖恢复胶囊,其他宿主控件继续使用全局值 */ + --skin-recovery-background: #102030; +} +``` + +宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式、窗口尺寸变化让 `@media` 里的令牌生效时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致: + +- 背景强制不透明(alpha 视为 1)。 +- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。 +- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。 +- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。 +- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`,或带有编译器给皮肤字体加的 `ws-` 作用域前缀(包括放在暂未生效的 `@media` 里的字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。 +- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。 +- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白;如果黑白两种文字在强调色上都达不到 4.5,这组颜色同样整体回退到宿主默认。 +- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。 + +`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)和「使用内置皮肤」的重置路径完全不受令牌影响。旧皮肤继续写 `--skin-recovery-*` 也能工作;新皮肤建议优先使用全局 `--skin-host-*`,只在需要区分具体控件时写每部件覆盖。 + `host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。 示例(v3 `skin.css`): @@ -494,7 +603,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 | `home.toolbar.settings` | 首页工具栏设置图标 | | `voice.performance` | 语音页 Voice status / 性能触发器图标 | -### `chrome.json`:声明式显示 / 隐藏与图标位图覆盖 +### `chrome.json`:声明式显示 / 隐藏、图标位图覆盖与控件停靠 v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根目录,最多 32 KiB: @@ -507,6 +616,9 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根 "language.trigger": "assets/icons/language.png", "skin.trigger": "assets/icons/skin.png", "host.plugins.launcher": "assets/icons/apps.png" + }, + "slots": { + "host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true } } } ``` @@ -516,6 +628,7 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根 | `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 | | `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 | | `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 | +| `slots` | 可选,最多 8 项;键名目前只能是 `host.recovery`,值只能包含 `anchor`、`align`、`compact`。详见上文「将恢复入口停靠到皮肤布局」。未知键、指向 `host.*` 或可信宿主部件的锚点会被拒绝。 | 图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。 @@ -618,9 +731,11 @@ v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显 [data-ws-part="host.plugins.launcher"] ``` -上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。 +上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。 -皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。 +关键帧与普通声明遵循同一套受保护控件检查,但只检查动画能够**停留**的帧:`to` / `100%` 始终检查;`from` / `0%` 仅在引用它的声明(含同一主体上另一条规则的方向 / 填充 / 播放状态长属性)使用 `reverse`、`alternate`、`alternate-reverse` 方向、`backwards` / `both` 填充模式或 `paused` 播放状态时检查;转义的 `to` / `from` 与 `1e2%` 这类写法按停留帧识别;`50%` 等中间帧不会因为过渡状态被拒绝,缺少 `to` / `100%` 时结束状态回到元素自身样式(`paused` 配合负延迟、或超长动画停在中间帧属于已知残留,由闭合 Shadow DOM 的恢复胶囊兜底)。受保护控件上被拒绝的写法包括 `display: none`、`visibility: hidden|collapse`、`opacity` ≤ 0.01(含 `0`、`0%`、`0e0`、`calc(0)` 等)、`pointer-events: none`、`filter` / `-webkit-filter` 的 `opacity(≤0.01)` / `brightness(0)`、`transform` / `scale` 的零缩放、`content-visibility: hidden`、`clip-path` 的 `inset(...)`(任一边对合计 ≥ 100%)、`circle(0)` / `ellipse(0 …)`、`clip: rect(0,0,0,0)`,以及 `mask` / `mask-image` 的 `alpha(0)` / `luminance(0)` 或全透明渐变色标;`polygon()` 等装饰性裁切不受限制。受保护主体的判定会展开 `:is()` / `:where()` 参数、双重否定 `:not(:not(X))` 与 `:nth-child(An+B of S)` / `:nth-last-child(...)` 的 `S`,`[data-ws-part="…" i]` 按不区分大小写匹配。把控件移出视口只在明显越界时拒绝:负向 ≤ -1000px 或 ≤ -100%,正向 ≥ 2000px 或 ≥ 200%(`margin` / `inset` / `left` / `right` / `top` / `bottom` / `translate` / `transform`,含简单 `calc()` 与 `matrix()` 平移);`scale`、`rotate` 和小幅平移不受影响。`host.plugins.overlay` 的布局锁在关键帧中复用普通声明的属性锁:停留帧里的定位、变换等锁定属性只能取中性或单位变换(`none`、`auto`、`static`、`0`、`scale(1)`、`translateY(0)`、`rotate(0deg)` 或 CSS 全局关键字),尺寸属性仅在达到视口尺寸时拒绝(含 `calc(50vw * 2)`);入场动画停在这些值时通过。受保护控件和 `host.plugins.overlay` 上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名;受保护控件上的 `filter` / `-webkit-filter`、`clip` 与 `content-visibility` 同样只接受字面值,不能用 `var()` / `attr()`(否则变量可以绕过上面的隐藏检查),其他部件不受影响。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。 + +皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。装饰性宿主外壳(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)和普通页面部件不受布局锁限制,可以自由使用 flex/grid、重定位、自定义尺寸、大背景和动画;固定定位或极端 `z-index` 只会给出提示。开放皮肤(v3/v4)的布局与视觉质量由官方库的人工审核保证,编译器不会阻止一般性的布局回归。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。 CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。 diff --git a/docs/examples/host-chrome-demo.wskin b/docs/examples/host-chrome-demo.wskin index 2947c16..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/chrome.json b/docs/examples/host-chrome-demo/chrome.json index c22b887..46b47f5 100644 --- a/docs/examples/host-chrome-demo/chrome.json +++ b/docs/examples/host-chrome-demo/chrome.json @@ -8,5 +8,8 @@ "host.plugins.launcher": "assets/icons/apps.png", "home.toolbar.settings": "assets/icons/settings.png", "voice.performance": "assets/icons/status.png" + }, + "slots": { + "host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true } } } 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 96c17a0..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] { @@ -25,6 +45,50 @@ [data-ws-part="voice.audio-dock"] { border-top: 1px solid var(--skin-border); background: #f7f9fb; + /* Fold the trusted recovery capsule into the audio dock (chrome.json#slots). */ + --skin-recovery-accent: #1d4f9c; + --skin-recovery-background: #ffffff; + --skin-recovery-foreground: #141414; + --skin-recovery-radius: 999px; + --skin-recovery-font: Tahoma, "Segoe UI", sans-serif; + --skin-recovery-size: small; +} + +/* --- Protected app-DOM controls: purely visual theming is allowed --- */ +[data-ws-part="voice.audio-dock.microphone"] button, +[data-ws-part="voice.audio-dock.output"] button, +[data-ws-part="voice.connection-status.reconnect"], +[data-ws-part="home.footer.clear"] { + color: #141414; + background: linear-gradient(180deg, #ffffff, #eef3fa); + border: 1px solid var(--skin-accent); + border-radius: 8px; + font-family: Tahoma, "Segoe UI", sans-serif; + font-size: 12px; + padding: 8px 12px; + min-height: 44px; + box-shadow: 0 2px 6px #1d4f9c22; +} + +[data-ws-part="voice.audio-dock.microphone"] button:hover, +[data-ws-part="voice.audio-dock.output"] button:hover, +[data-ws-part="voice.connection-status.reconnect"]:hover, +[data-ws-part="home.footer.clear"]:hover { + background: #e7eefb; +} + +[data-ws-part="auth.password.dialog"], +[data-ws-part="voice.audio-settings"] { + background: #ffffff; + border: 2px solid var(--skin-accent); + border-radius: 18px; + box-shadow: 0 18px 48px #1d4f9c33; +} + +[data-ws-part="auth.password.dialog"] h2, +[data-ws-part="voice.audio-settings"] h2 { + color: var(--skin-accent); + letter-spacing: .01em; } /* --- Host chrome (outside .ws-skin-root) --- */ diff --git a/docs/examples/host-chrome-themed.wskin b/docs/examples/host-chrome-themed.wskin index 2b0cd38..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 dece7cc..69e0fdb 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/test/host-chrome-recovery.test.mjs", + "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs", diff --git a/src/shared/skin-chrome.ts b/src/shared/skin-chrome.ts index ed626d9..9e55233 100644 --- a/src/shared/skin-chrome.ts +++ b/src/shared/skin-chrome.ts @@ -1,15 +1,25 @@ -import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./skin-visual-parts.js"; +import { + DECORATIVE_PART_IDS, + HOST_SKIN_ATTRIBUTE, + HOST_SLOTTABLE_PART_IDS, + SKIN_ICON_SLOT_IDS, + TRUSTED_PART_IDS, + isHostPart, +} from "./skin-visual-parts.js"; /** * `chrome.json` is an optional, declarative companion to an open skin. * - * It describes two host-chrome capabilities that CSS alone cannot express - * safely: + * It describes host-chrome capabilities that CSS alone cannot express safely: * - `visibleParts`: decorations the skin asks the host to render. This is the * only opt-in; official and built-in skins stay clean. * - `hiddenParts`: non-critical decorations the skin wants collapsed by * default. Only explicitly optional parts are accepted. * - `icons`: bitmap overrides for stable icon slots, keyed by part name. + * - `slots`: declarative anchors for trusted host controls. A skin never + * receives the control; it only names a part it already renders so the + * host can position its own top-layer capsule there and fall back to the + * default corner when the anchor stops being usable. * * Both the browser importer and the server-side registry parse the exact same * document, so a package accepted by one is accepted by the other. @@ -18,10 +28,21 @@ import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./ export const SKIN_CHROME_MAX_BYTES = 32 * 1024; export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32; export const SKIN_CHROME_MAX_ICONS = 16; +export const SKIN_CHROME_MAX_SLOTS = 8; export const SKIN_ICON_MAX_BYTES = 64 * 1024; export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024; export const SKIN_ICON_DIRECTORY = "assets/icons/"; +/** + * Anchor names are `data-ws-part` values, including host-rendered v3 component + * parts (`skin...part-`) and v4 runtime plugin parts + * (`skin..runtime_plugin___.part-`). Each + * dot-separated segment follows the same identifier grammar as other part + * names; the generous overall limit covers a namespaced runtime plugin. + */ +export const SKIN_SLOT_ANCHOR_MAX_LENGTH = 240; +const PART_NAME_SEGMENT = /^[-_a-z][-_a-z0-9]*$/i; + const SUPPORTED_ICON_EXTENSIONS = new Set(["png", "jpg", "jpeg", "webp", "avif", "gif"]); /** @@ -45,6 +66,19 @@ export interface SkinChromeDocument { */ visibleParts?: string[]; icons: Record; + /** Protected host controls folded into skin-owned layout anchors. */ + slots?: Partial>; +} + +export type SkinChromeSlotAlign = "start" | "center" | "end"; + +export interface SkinChromeSlot { + /** Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box. */ + anchor: string; + /** Horizontal alignment inside the anchor; the control is vertically centred. */ + align: SkinChromeSlotAlign; + /** Collapse to the mark only until hovered or focused. */ + compact: boolean; } export interface SkinChromeAssetInfo { @@ -94,6 +128,29 @@ export function normalizeSkinIconPath(raw: unknown): string { return path; } +/** + * A slot anchor is an existing part name, never host-owned UI: a skin must not + * be able to park a protected control on the launcher, the authorization + * dialog or another trusted element it could then cover or remove. + */ +function normalizeSlotAnchor(raw: unknown): string { + if (typeof raw !== "string" || !raw || raw.length > SKIN_SLOT_ANCHOR_MAX_LENGTH) { + return reject(`A slot anchor must be a part name of at most ${SKIN_SLOT_ANCHOR_MAX_LENGTH} characters.`, "SKIN_CHROME_SLOT_INVALID"); + } + const segments = raw.split("."); + if (segments.some((segment) => !PART_NAME_SEGMENT.test(segment))) { + return reject(`A slot anchor is not a valid part name: ${raw}.`, "SKIN_CHROME_SLOT_INVALID"); + } + if (isHostPart(raw) || TRUSTED_PART_IDS.has(raw)) { + return reject(`A slot anchor cannot point at trusted host UI: ${raw}.`, "SKIN_CHROME_SLOT_INVALID"); + } + return raw; +} + +function isSlotAlign(value: unknown): value is SkinChromeSlotAlign { + return value === "start" || value === "center" || value === "end"; +} + export function parseSkinChromeDocument(source: string): SkinChromeDocument { const bytes = new TextEncoder().encode(source).byteLength; if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) { @@ -104,7 +161,7 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument { catch { return reject("chrome.json is not valid JSON.", "SKIN_CHROME_INVALID"); } if (!isRecord(raw)) return reject("chrome.json must be an object.", "SKIN_CHROME_INVALID"); for (const key of Object.keys(raw)) { - if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons") { + if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons" && key !== "slots") { return reject(`chrome.json contains an unsupported field: ${key}.`, "SKIN_CHROME_INVALID"); } } @@ -151,7 +208,48 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument { icons[slot] = normalizeSkinIconPath(path); } } - return { schemaVersion: 1, hiddenParts, ...(visibleParts ? { visibleParts } : {}), icons }; + let slots: Partial> | undefined; + if (raw.slots !== undefined) { + if (!isRecord(raw.slots)) { + return reject("slots must be an object mapping protected part names to anchors.", "SKIN_CHROME_SLOT_INVALID"); + } + const entries = Object.entries(raw.slots); + if (entries.length > SKIN_CHROME_MAX_SLOTS) { + return reject(`A skin may declare at most ${SKIN_CHROME_MAX_SLOTS} slots.`, "SKIN_CHROME_SLOT_INVALID"); + } + slots = Object.create(null) as Partial>; + for (const [part, value] of entries) { + if (!HOST_SLOTTABLE_PART_IDS.has(part)) { + return reject(`Unknown slottable host part: ${part}.`, "SKIN_CHROME_SLOT_INVALID"); + } + if (!isRecord(value)) { + return reject(`Slot ${part} must be an object.`, "SKIN_CHROME_SLOT_INVALID"); + } + for (const key of Object.keys(value)) { + if (key !== "anchor" && key !== "align" && key !== "compact") { + return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID"); + } + } + const anchor = normalizeSlotAnchor(value.anchor); + const align = value.align === undefined ? "end" : value.align; + if (!isSlotAlign(align)) { + return reject(`Slot ${part} has an invalid align value: ${String(align)}.`, "SKIN_CHROME_SLOT_INVALID"); + } + const compact = value.compact === undefined ? false : value.compact; + if (typeof compact !== "boolean") { + return reject(`Slot ${part} compact must be a boolean.`, "SKIN_CHROME_SLOT_INVALID"); + } + slots[part] = { anchor, align, compact }; + } + } + + return { + schemaVersion: 1, + hiddenParts, + ...(visibleParts ? { visibleParts } : {}), + icons, + ...(slots ? { slots } : {}), + }; } /** diff --git a/src/shared/skin-css.test.ts b/src/shared/skin-css.test.ts index 3cb73db..6943b80 100644 --- a/src/shared/skin-css.test.ts +++ b/src/shared/skin-css.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { compileSkinCss, OPTIONAL_VISUAL_PARTS } from "./skin-css.js"; import { DECORATIVE_PART_IDS as LAYOUT_DECORATIVE, PROTECTED_PART_IDS } from "./skin-layout.js"; -import { DECORATIVE_PART_IDS } from "./skin-visual-parts.js"; +import { DECORATIVE_PART_IDS, HOST_SLOTTABLE_PART_IDS } from "./skin-visual-parts.js"; import { compileSkinChromeCss, DEFAULT_HIDDEN_HOST_PARTS, @@ -196,6 +196,62 @@ test("chrome.json declares hidden parts and icon bitmaps, with path and size val assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: 10, mime: "text/plain" })), /raster image/); }); +test("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => { + assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], ["host.recovery"]); + + const explicit = parseSkinChromeDocument(JSON.stringify({ + schemaVersion: 1, + slots: { + "host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true }, + }, + })); + assert.deepEqual(explicit.slots?.["host.recovery"], { + anchor: "voice.audio-dock", + align: "start", + compact: true, + }); + + // Defaults: align "end", compact off. Component and runtime-plugin parts are + // ordinary anchors; only host/trusted parts are off limits. + const defaults = parseSkinChromeDocument(JSON.stringify({ + schemaVersion: 1, + slots: { + "host.recovery": { anchor: "skin.voice.harbor-dock.part-anchor" }, + }, + })); + assert.deepEqual(defaults.slots?.["host.recovery"], { + anchor: "skin.voice.harbor-dock.part-anchor", + align: "end", + compact: false, + }); + assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({ + schemaVersion: 1, + slots: { "host.recovery": { anchor: "skin.voice.runtime_plugin_voice-surface__dock.part-anchor" } }, + }))); + + // Slot declarations are runtime input, not compiled CSS: the generated host + // stylesheet must stay exactly as empty as before. + assert.equal(compileSkinChromeCss(explicit, "demo-skin"), ""); + + const invalidDocuments: Array<[unknown, RegExp]> = [ + [{ schemaVersion: 1, slots: [] }, /must be an object/], + [{ schemaVersion: 1, slots: { "host.permission": { anchor: "voice.audio-dock" } } }, /Unknown slottable host part/], + [{ schemaVersion: 1, slots: { "host.recovery": "voice.audio-dock" } }, /must be an object/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "host.plugins.launcher" } } }, /trusted host UI/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.connection-status" } } }, /trusted host UI/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "app" } } }, /trusted host UI/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", align: "left" } } }, /invalid align/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", compact: "yes" } } }, /compact must be a boolean/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", extra: true } } }, /unsupported field/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "../escape" } } }, /not a valid part name/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "Voice Audio Dock" } } }, /not a valid part name/], + [{ schemaVersion: 1, slots: { "host.recovery": { anchor: "" } } }, /at most 240 characters/], + ]; + for (const [value, message] of invalidDocuments) { + assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value)); + } +}); + test("instance-level hidden parts ignore unknown and protected names", () => { assert.deepEqual(parseHiddenHostParts("host.watermark, host.hint voice.audio-dock home.footer"), ["host.watermark", "host.hint"]); assert.deepEqual(parseHiddenHostParts(["host.hint", "host.hint", "nope"]), ["host.hint"]); @@ -247,10 +303,12 @@ test("protected controls cannot be hidden through variables or moved off-screen" '[data-ws-part="voice.audio-dock"] { margin-left: -9999px; }', '[data-ws-part="voice.audio-dock"] { margin-inline: -9999px; }', '[data-ws-part="voice.audio-dock"] { margin-block-start: -1200px; }', - '[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }', + '[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -1000px; }', '[data-ws-part="voice.audio-dock"] { margin-left: -100vw; }', - '[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }', + '[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 5000px); }', '[data-ws-part="voice.audio-dock"] { transform: matrix(1, 0, 0, 1, -4000, 0); }', + '[data-ws-part="voice.audio-dock"] { margin-left: -1e4px; }', + '[data-ws-part="voice.audio-dock"] { transform: translateX(calc(2px*-1000)); }', ]) { assert.throws(() => compile(css), /must remain on screen/, css); } @@ -263,8 +321,18 @@ test("protected controls cannot be hidden through variables or moved off-screen" assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { background: var(--skin-panel); }')); assert.doesNotThrow(() => compile(':root { --skin-hide: none; } [data-ws-part="host.watermark"] { display: var(--skin-hide); }')); // A small margin on a protected control and a decorative dock child are still - // legitimate v3 theming. + // legitimate v3 theming. Ordinary placement is no longer mistaken for a + // yeet: only values clearly beyond a viewport are rejected. assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: -6px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-top: 120px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 auto 120px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { top: 100%; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { scale: 100%; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { rotate: 4deg; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { transform: rotate(8deg); }')); assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }')); // The off-screen guard only protects the subject, not decorative or // non-protected parts. @@ -272,12 +340,76 @@ test("protected controls cannot be hidden through variables or moved off-screen" assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { margin-left: -9999px; }')); }); +test("protected controls accept every purely visual property", () => { + const themed = compileSkinCss(` + :root { + --skin-ink: #f8fafc; + --skin-card: #0f172a; + --skin-line: #38bdf8; + --skin-pad: 14px; + --skin-size: 56px; + --skin-shadow: 0 10px 30px #0006; + } + [data-ws-part="voice.audio-dock.microphone"], + [data-ws-part="voice.connection-status.reconnect"], + [data-ws-part="home.footer.clear"], + [data-ws-part="auth.password.dialog"] { + color: var(--skin-ink); + background-color: var(--skin-card); + background-image: linear-gradient(135deg, #123456, #654321), url("assets/protected-pattern.png"); + border: 2px solid var(--skin-line); + border-radius: 18px; + font-family: var(--skin-font, Tahoma, "Segoe UI", sans-serif); + font-size: 15px; + padding: var(--skin-pad); + width: var(--skin-size); + height: var(--skin-size); + box-shadow: var(--skin-shadow); + text-shadow: 0 1px 2px #0008; + } + [data-ws-part="voice.audio-dock.microphone-panel"]::before, + [data-ws-part="auth.password.actions"] > button { + background: var(--skin-line); + border-color: var(--skin-line); + border-radius: 12px; + } + `, "demo-skin", new Set(["assets/protected-pattern.png"]), 3); + + assert.match(themed.css, /\[data-ws-part="voice\.audio-dock\.microphone"\]/); + assert.match(themed.css, /wskin-asset:assets%2Fprotected-pattern\.png/); + // The hide/move guarantees are unchanged. + for (const css of [ + '[data-ws-part="voice.audio-dock.microphone"] { display: none; }', + '[data-ws-part="voice.audio-dock.microphone"] { visibility: hidden; }', + '[data-ws-part="voice.audio-dock.microphone"] { opacity: 0; }', + '[data-ws-part="voice.audio-dock.microphone"] { pointer-events: none; }', + '[data-ws-part="voice.audio-dock.microphone"] { clip-path: inset(100%); }', + '[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }', + ':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock.microphone"] { margin-left: var(--skin-pull); }', + // Literal filter/clip/content-visibility hiding is rejected, so a variable + // must not smuggle the same value past the check. + ':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { filter: var(--skin-x); }', + ':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { -webkit-filter: var(--skin-x); }', + ':root { --skin-x: rect(0, 0, 0, 0); } [data-ws-part="voice.audio-dock.microphone"] { clip: var(--skin-x); }', + ':root { --skin-x: hidden; } [data-ws-part="voice.audio-dock.microphone"] { content-visibility: var(--skin-x); }', + ]) { + assert.throws(() => compile(css), /must remain available|must remain on screen|cannot use indirect values/, css); + } +}); + +test("indirect filter values stay free outside protected controls", () => { + for (const version of [2, 3] as const) { + assert.doesNotThrow(() => compileSkinCss(':root { --skin-glow: drop-shadow(0 0 4px #0ff); } [data-ws-part="voice.header"] { filter: var(--skin-glow); }', "demo-skin", new Set(), version)); + } + // Literal visual filters remain allowed on protected controls. + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock.microphone"] { filter: drop-shadow(0 0 4px #0ff) saturate(1.2); }')); +}); + test("host chrome cannot be restyled into a viewport-sized overlay", () => { assert.throws( () => compile('[data-ws-part="host.plugins.overlay"] { position: fixed; inset: 0; z-index: 2147483647; }'), /layout is owned by WebSpeak/, ); - assert.throws(() => compile('[data-ws-part="host.watermark"] { position: fixed; }'), /layout is owned by WebSpeak/); assert.throws(() => compile('[data-ws-part="host.plugins.overlay"] { width: 100vw; height: 100vh; }'), /fullscreen overlay/); // Descendant rules are the same escape: `*` can turn the library contents @@ -286,7 +418,6 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => { '[data-ws-part="host.plugins.overlay"] * { position: fixed; inset: 0; z-index: 2147483647; }', '[data-ws-part="host.plugins.overlay"] * { width: 100vw; height: 100vh; }', '[data-ws-part="host.plugins.overlay"] .ws-plugin-library { position: fixed; top: 0; left: 0; }', - '[data-ws-part="host.watermark"] * { z-index: 2147483647; }', ]) { assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css); } @@ -299,12 +430,290 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => { assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css); } + // Decorative host chrome is not on the recovery path: it may be repositioned, + // resized, restacked and animated, at most with a warning. + for (const css of [ + '[data-ws-part="host.watermark"] { position: fixed; }', + '[data-ws-part="host.watermark"] * { z-index: 2147483647; }', + '[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; }', + '[data-ws-part="host.plugins.launcher"] { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; }', + '[data-ws-part="host.hint"] { position: absolute; transform: translateX(-10px); }', + '[data-ws-part="host.voice-status-decoration"] { position: fixed; inset: 0; pointer-events: none; }', + ]) { + assert.doesNotThrow(() => compile(css), css); + } + // Colors, borders, radius, shadows and artwork stay available, including on // descendants of the overlay. const themed = compile('[data-ws-part="host.plugins.overlay"] { border: 2px solid #1d4f9c; border-radius: 4px; background: #fff; box-shadow: 0 2px 8px #0003; }'); assert.match(themed.css, /data-ws-part="host\.plugins\.overlay"/); assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { color: #fff; border-color: #1d4f9c; border-radius: 6px; }')); assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }')); + // Overlay contents may use normal sizing and margins; only a viewport-sized + // box would turn the library contents into a fullscreen mask. + assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] button { min-width: 44px; min-height: 44px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { margin: 0; }')); +}); + +test("keyframes follow the same protected-control rules as regular declarations", () => { + const rejected: Array<[string, RegExp]> = [ + ['@keyframes k { to { display: none; opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { to { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { to { transform: translateX(-9999px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/], + ['@keyframes k { to { inset: 0 0 0 -120vw; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/], + ['@keyframes k { to { filter: opacity(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/], + ['@keyframes k { to { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/], + // A variable animation name must not hide the name from the walk. + [':root { --skin-anim: k; } @keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: var(--skin-anim) 1s forwards; }', /cannot use indirect values/], + ['@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { --skin-anim: k; } [data-ws-part="voice.audio-dock"] { animation-name: var(--skin-anim); }', /cannot use indirect values/], + ]; + for (const [css, message] of rejected) { + assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css); + } + // A keyframe shared by a protected and a non-protected part is judged by the + // protected reference. + assert.throws( + () => compile('@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation: k 1s; }'), + /must remain available/, + ); + + // Harmless fades, color tweens and gentle motion on non-protected parts, and + // visual / motion keyframes on decorative host parts, still compile. + for (const css of [ + '@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: fade 2s ease; }', + '@keyframes tint { from { color: #fff; } to { color: #1d4f9c; } } [data-ws-part="home.header"] { animation: tint 1.2s; }', + '@keyframes drift { from { transform: translateY(0); } to { transform: translateY(-6px); } } [data-ws-part="home.hero.eyebrow"] { animation: drift 3s infinite alternate; }', + '@keyframes wm { from { opacity: .1; color: #8ab9cf; transform: translateX(0); } to { opacity: .3; color: #2b6d8a; transform: translateX(20px); } } [data-ws-part="host.watermark"] { animation: wm 4s infinite alternate; }', + '@keyframes big { to { width: 100vw; height: 100vh; opacity: .2; } } [data-ws-part="host.watermark"] { animation: big 1s forwards; }', + '@keyframes hide { to { display: none; } } [data-ws-part="host.hint"] { animation: hide 1s forwards; }', + ]) { + assert.doesNotThrow(() => compile(css), css); + } +}); + +test("keyframes hide protected parts only when the animation can rest there", () => { + // Entrances and pulses that merely pass through a hidden/intermediate state + // are legitimate: only `to`/`100%` (and a genuinely resting `from`) count. + for (const css of [ + '@keyframes in { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="app"] { animation: in .3s; }', + '@keyframes toastIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } } [data-ws-part="app.toast"] { animation: toastIn .3s; }', + '@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: fade .4s; }', + '@keyframes slide { from { transform: translateX(-100%); } to { transform: none; } } [data-ws-part="voice.mobile-nav"] { animation: slide .25s; }', + '@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="app.toast"] { animation: pop .2s; }', + '@keyframes pulse { 50% { opacity: 0; } 100% { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: pulse 2s infinite; }', + '@keyframes in { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } } [data-ws-part="host.plugins.overlay"] { animation: in .2s; }', + '@keyframes pop { from { scale: 0; } to { scale: 1; } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }', + '@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }', + '@keyframes slide { from { transform: translateY(8px); } to { transform: translateY(0); } } [data-ws-part="host.plugins.overlay"] { animation: slide .2s; }', + // A keyframe without a `to` frame ends on the element's own style. + '@keyframes tint { 50% { opacity: 0; } } [data-ws-part="voice.connection-status"] { animation: tint 2s; }', + ]) { + assert.doesNotThrow(() => compile(css), css); + } + + const rejected: Array<[string, RegExp]> = [ + ['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { 100% { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { to { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/], + // Reverse/alternate/fill-backwards animations can end (or hold) on `from`. + ['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/], + ['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s alternate; }', /must remain available/], + ['@keyframes k { from { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-direction: alternate-reverse; }', /must remain available/], + ['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-fill-mode: both; }', /must remain available/], + ['@keyframes k { 0% { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/], + // Declaration order cannot hide a reverse direction behind a longhand. + ['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-direction: normal; animation: k 1s reverse; }', /must remain available/], + // A variable fill mode is unknowable, so the start frame is treated as resting. + ['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-fill-mode: var(--skin-fill); }', /must remain available/], + // A paused animation renders its start frame from the first paint. + ['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s paused; }', /must remain available/], + ['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-play-state: paused; }', /must remain available/], + // Escaped `to`/`from` and `1e2%` must still be recognised as resting steps. + ['@keyframes k { \\74 o { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { t\\6f { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/], + ['@keyframes k { \\66 rom { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/], + ['@keyframes k { 1e2% { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + // Direction/fill longhands in a sibling rule on the same subject still rest on `from`. + ['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation-direction: reverse; animation-fill-mode: both; }', /must remain available/], + ]; + for (const [css, message] of rejected) { + assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css); + } +}); + +test("escaped animation names are matched and rewritten", () => { + const escaped = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation-name: p\\75 lse; }'); + assert.match(escaped.css, /animation-name: ws-demo-skin-pulse/); + assert.doesNotMatch(escaped.css, /p\\75 lse/); + + const shorthand = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: p\\75 lse .3s ease; }'); + assert.match(shorthand.css, /animation: ws-demo-skin-pulse \.3s ease/); + + // Only the name slot is rewritten: a keyframe named like a timing keyword + // must not turn the timing function into a keyframe reference. + const timing = compile('@keyframes linear { from { opacity: 1; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: linear 1s linear; }'); + assert.match(timing.css, /animation: linear 1s ws-demo-skin-linear/); +}); + +test("keyword-shaped animation tokens do not become keyframe references", () => { + const named = compile('@keyframes alternate { from { opacity: 1; } to { opacity: 1; } } @keyframes bob { from { transform: translateY(0); } to { transform: translateY(4px); } } [data-ws-part="voice.audio-dock"] { animation: bob 2s alternate; }'); + assert.match(named.css, /@keyframes ws-demo-skin-alternate/); + assert.match(named.css, /animation: ws-demo-skin-bob 2s alternate/); + assert.doesNotMatch(named.css, /animation: bob 2s ws-demo-skin-alternate/); +}); + +test("normalised hidden values cannot hide protected parts", () => { + const hidden: Array<[string, string]> = [ + ["display", "none"], + ["visibility", "hidden"], + ["visibility", "collapse"], + ["opacity", ".0"], + ["opacity", "+0"], + ["opacity", "-1"], + ["opacity", "0%"], + ["opacity", "0.5%"], + ["opacity", "0.001"], + ["opacity", "calc(0)"], + ["filter", "opacity(0.0)"], + ["filter", "brightness(0)"], + ["-webkit-filter", "opacity(0)"], + ["pointer-events", "none"], + ["transform", "scale(0)"], + ["transform", "scaleX(0)"], + ["transform", "scaleY(0)"], + ["transform", "scale3d(0, 1, 1)"], + ["transform", "scale(0 0)"], + ["scale", "0"], + ["scale", "0%"], + ["scale", "0 0"], + ["content-visibility", "hidden"], + ["clip-path", "inset(50%)"], + ["clip-path", "inset(60% 0)"], + ["clip-path", "inset(0 60%)"], + ["clip-path", "circle(0)"], + ["clip-path", "ellipse(0 10px)"], + ["clip", "rect(0,0,0,0)"], + ["clip", "rect(0 0 0 0)"], + ["mask", "alpha(0)"], + ["mask-image", "luminance(0)"], + ["mask-image", "linear-gradient(transparent, transparent)"], + ["mask-image", "linear-gradient(#0000, #0000)"], + ["mask-image", "linear-gradient(rgb(0 0 0 / 0), rgb(0 0 0 / 0))"], + ["mask-image", "conic-gradient(from 0deg, transparent, transparent)"], + ["opacity", "0e0"], + ["opacity", "1e-3"], + ["filter", "opacity(1e-2)"], + ["transform", "scale(0e0)"], + ["scale", "1e-9"], + ]; + for (const [property, value] of hidden) { + const direct = `[data-ws-part="voice.audio-dock"] { ${property}: ${value}; }`; + assert.throws(() => compile(direct), /must remain available/, direct); + const frame = `@keyframes k { to { ${property}: ${value}; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; }`; + assert.throws(() => compile(frame), /must remain available/, frame); + } + // Partial effects and artwork clipping remain legitimate. + for (const css of [ + '[data-ws-part="voice.audio-dock"] { opacity: .5; }', + '[data-ws-part="voice.audio-dock"] { filter: opacity(.4); }', + '[data-ws-part="voice.audio-dock"] { transform: scale(.5); }', + '[data-ws-part="voice.audio-dock"] { scale: .8; }', + '[data-ws-part="voice.audio-dock"] { clip-path: polygon(0 0, 100% 0, 100% 80%, 0 100%); }', + '[data-ws-part="voice.audio-dock"] { clip-path: inset(20%); }', + '[data-ws-part="voice.audio-dock"] { mask-image: linear-gradient(transparent, red); }', + ]) { + assert.doesNotThrow(() => compile(css), css); + } +}); + +test("selector variants cannot disguise a protected subject", () => { + for (const css of [ + '[data-ws-part="VOICE.AUDIO-DOCK" i] { display: none; }', + '[data-ws-part="voice.audio-dock" I] { opacity: 0; }', + ':not(:not([data-ws-part="voice.audio-dock"])) { display: none; }', + ':not(:not([data-ws-part="voice.audio-dock"]):hover) { visibility: hidden; }', + ':nth-child(2n of [data-ws-part="voice.audio-dock"]) { display: none; }', + ':nth-last-child(odd of .member, [data-ws-part="voice.audio-dock"]) { pointer-events: none; }', + ':not(:not([data-ws-part="voice.audio-dock"]), [data-ws-part="home.title"]) { display: none; }', + ':not(:is(:not([data-ws-part="voice.audio-dock"]))) { display: none; }', + ]) { + assert.throws(() => compile(css), /must remain available/, css); + } + // The `s` flag keeps matching case-sensitive, so this selects nothing. + assert.doesNotThrow(() => compile('[data-ws-part="VOICE.AUDIO-DOCK" s] { display: none; }')); + // A single :not() still means "every other element". + assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }')); +}); + +test("escaped, namespaced and :is()/:where() animation names cannot bypass the protected-control locks", () => { + const rejected: Array<[string, RegExp]> = [ + // Escaped property name used to skip the keyframe mapping walk. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { anim\\61 tion: k 1s forwards; }', /must remain available/], + // A pack can predict the namespace and reference the already-renamed keyframe. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-k 1s forwards; }', /must remain available/], + // The protected subject can be wrapped in a functional pseudo-class. + [':is([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/], + [':where([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/], + ['@keyframes k { to { opacity: 0; } } :is([data-ws-part="voice.audio-dock"]) { animation: k 1s forwards; }', /must remain available/], + // -webkit-* animation longhands participate in the same walks. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation-name: k; }', /must remain available/], + ['[data-ws-part="voice.audio-dock"] { -webkit-animation: var(--skin-a); }', /cannot use indirect values/], + // Escaped *values* used to bail out of the mapping walk on a backslash and + // still resolve to the renamed keyframe in the browser. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\6b 1s forwards; }', /must remain available/], + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\00006b 1s forwards; }', /must remain available/], + ['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: \\6b; }', /must remain available/], + // Prefixed visual-removal properties must use the same checks as the unprefixed form. + ['[data-ws-part="voice.audio-dock"] { -webkit-filter: opacity(0); }', /must remain available/], + ['[data-ws-part="voice.audio-dock"] { -webkit-transform: scale(0); }', /must remain available/], + ]; + for (const [css, message] of rejected) { + assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css); + } + + // `:not()` does not make the protected part the subject; only a v3 warning. + assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }')); + + // A harmless -webkit-animation on a non-protected part still compiles and its + // keyframe name is rewritten into the skin namespace. + const webkit = compile('@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { -webkit-animation: fade 2s ease; }'); + assert.match(webkit.css, /@keyframes ws-demo-skin-fade/); + assert.match(webkit.css, /-webkit-animation: ws-demo-skin-fade 2s ease/); +}); + +test("keyframes cannot turn the plugin overlay into a fullscreen layer", () => { + for (const css of [ + '@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }', + '@keyframes k { to { width: 100vw; height: 100vh; } } [data-ws-part="host.plugins.overlay"] * { animation: k 1s forwards; }', + '@keyframes k { to { zoom: 10; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }', + '@keyframes k { to { transform: scale(10); } } [data-ws-part="host.plugins.overlay"] { animation-name: k; }', + '@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { --skin-a: ws-demo-skin-k; animation: var(--skin-a) 1s forwards; }', + '[data-ws-part="host.plugins.overlay"] * { width: calc(50vw * 2); }', + '[data-ws-part="host.plugins.overlay"] * { width: calc(99vw + 1vw); }', + ]) { + assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css); + } + // The same animation is harmless on decorative host chrome. + assert.doesNotThrow(() => compile('@keyframes k { to { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; } } [data-ws-part="host.watermark"] { animation: k 1s forwards; }')); +}); + +test("large layout restyles of non-protected parts and decorative host chrome compile", () => { + for (const css of [ + '[data-ws-part="home.header"] { display: grid; grid-template-columns: 1fr 2fr; gap: 16px; position: relative; width: 80vw; height: 50vh; }', + '[data-ws-part="home.header"] { display: flex; flex-direction: column; align-items: stretch; translate: 24px 0; }', + '[data-ws-part="voice.audio-dock"] > div:first-child { position: absolute; width: 100vw; height: 100vh; }', + // Whole-page and protected-part layout rewrites are the owner's explicit + // use case; placement is no longer mistaken for a yeet. + '[data-ws-part="app"] { display: grid; grid-template-areas: "rail main"; grid-template-columns: 72px 1fr; position: relative; }', + '[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; display: flex; flex-direction: column; gap: 10px; }', + '[data-ws-part="home"] { display: flex; flex-direction: column; align-items: stretch; min-height: 100vh; }', + // Official example skins (harbor, kaak) clip their own artwork. + '[data-ws-part="home.header"] { clip-path: polygon(0 0, 100% 0, 100% 82%, 0 100%); }', + '[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; transform: rotate(-8deg); }', + ]) { + assert.doesNotThrow(() => compile(css), css); + } }); test("official and built-in skins hide host decorations unless the active skin opts in", () => { diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts index 543d340..384a49d 100644 --- a/src/shared/skin-css.ts +++ b/src/shared/skin-css.ts @@ -1,6 +1,6 @@ import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss"; -import selectorParser from "postcss-selector-parser"; -import valueParser from "postcss-value-parser"; +import selectorParser, { type Node as SelectorNode, type Pseudo as SelectorPseudo } from "postcss-selector-parser"; +import valueParser, { type Node as ValueNode } from "postcss-value-parser"; import { DECORATIVE_PART_IDS as OPTIONAL_VISUAL_PARTS, HOST_CHROME_PART_IDS, @@ -67,7 +67,12 @@ const HOST_OVERLAY_LOCKED_PROPERTIES = new Set([ "aspect-ratio", "margin", "margin-block", "margin-inline", "margin-block-start", "margin-block-end", "margin-inline-start", "margin-inline-end", ]); -/** Properties whose indirect values could smuggle a hidden or moved control past the static checks. */ +/** + * Properties whose indirect values could smuggle a hidden or moved control past + * the static checks. Purely visual properties (colour, background, border, + * radius, font, shadow, padding, width/height) are deliberately absent: a + * protected control may theme them with `var()`. + */ const INDIRECT_VALUE_PROPERTIES = new Set([ "all", "display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image", "position", "top", "right", "bottom", "left", "inset", @@ -79,6 +84,14 @@ const INDIRECT_VALUE_PROPERTIES = new Set([ "margin-block", "margin-block-start", "margin-block-end", "margin-inline", "margin-inline-start", "margin-inline-end", ]); +/** + * Visual properties whose literal hiding values (`filter: opacity(0)`, + * `clip: rect(0 0 0 0)`, `content-visibility: hidden`) are rejected on + * protected controls. They stay free on every other part, but a protected + * control may not take them from `var()`/`attr()`, which would hide the + * same value from the static check. + */ +const PROTECTED_INDIRECT_HIDE_PROPERTIES = new Set(["filter", "clip", "content-visibility"]); /** Attributes a skin author must never use to reach outside the public hooks. */ const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([ HOST_SKIN_ATTRIBUTE, @@ -94,6 +107,19 @@ const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([ "data-ws-host-layer-content", "data-ws-recovery-action", ]); +/** CSS-wide keywords never name a keyframe and reset an animatable slot. */ +const CSS_WIDE_KEYWORDS = new Set(["initial", "inherit", "unset", "revert", "revert-layer"]); +/** Shorthand keyword slots; a repeated category frees the word to be the name. */ +const ANIMATION_KEYWORD_CATEGORIES = new Map([ + ["linear", "timing"], ["ease", "timing"], ["ease-in", "timing"], ["ease-out", "timing"], + ["ease-in-out", "timing"], ["step-start", "timing"], ["step-end", "timing"], + ["normal", "direction"], ["reverse", "direction"], ["alternate", "direction"], ["alternate-reverse", "direction"], + ["none", "fill"], ["forwards", "fill"], ["backwards", "fill"], ["both", "fill"], + ["running", "play"], ["paused", "play"], ["infinite", "iteration"], +]); +/** Words that let an animation hold its `from`/`0%` frame. */ +const RESTING_START_KEYWORDS = new Set(["reverse", "alternate", "alternate-reverse", "backwards", "both", "paused"]); + export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } { const size = new TextEncoder().encode(source).byteLength; if (!size || size > MAX_CSS_BYTES) throw new SkinCssValidationError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE"); @@ -105,10 +131,8 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets const scope = pluginId ? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]` : skinScope; - // Host chrome is Teleported outside `.ws-skin-root`. Rules that target only - // registered host parts use a second, document-level scope anchored to an - // attribute the host sets while this exact skin is active. Author CSS never - // names html/body: the host generates the scope itself. + // Host chrome is Teleported outside `.ws-skin-root`; these rules get their own + // document-level scope, which the host anchors to the active skin attribute. const hostSkinScope = `:root[${HOST_SKIN_ATTRIBUTE}="${id}"]`; const hostScopeNodes = selectorParser().astSync(hostSkinScope).first!.nodes.map((node) => node.clone()); const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`; @@ -180,48 +204,100 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets const referencedKeyframes = new Set(); const nonOptionalKeyframes = new Set(); + // Keyframes inherit the protected/locked status of their referencing rules; + // params are namespaced here, and `from`/`0%` only rests for some rules. + const protectedKeyframeParts = new Map(); + const lockedHostKeyframeParts = new Map>(); + const restingFromKeyframes = new Set(); + // Direction/fill/play-state longhands may sit in a sibling rule on the same + // subject; collect names per subject, then mark resting-from afterwards. + const subjectKeyframes = new Map>(); + const restingSubjects = new Set(); root.walkRules((rule: Rule) => { if (hasKeyframesAncestor(rule)) return; const optionalTarget = hideableRules.has(rule); + const protectedTarget = selectorSubjectProtectedPart(rule.selector); + const lockedHostParts = selectorLockedHostParts(rule.selector); + const subjects = [ + ...selectorSubjectParts(rule.selector, PROTECTED_PART_IDS), + ...selectorSubjectParts(rule.selector, HOST_CHROME_PART_IDS).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part)), + ]; + const restsAtStart = subjects.length > 0 && ruleCanRestAtStart(rule); + if (restsAtStart) for (const subject of subjects) restingSubjects.add(subject); rule.walkDecls((declaration: Declaration) => { - const property = declaration.prop.toLowerCase(); + // Decode the property like the enforcement walk (`anim\61 tion`), and the + // value so escaped identifiers match their declared names. + const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase()); if (property !== "animation" && property !== "animation-name") return; - const value = declaration.value; - if (/\b(?:var|attr)\s*\(|\\/i.test(value)) { + const decodedValue = decodeCssEscapes(declaration.value); + if (/\b(?:var|attr)\s*\(/i.test(decodedValue)) { keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name)); return; } - for (const name of keyframeNames.keys()) { - if (!referencesCssIdentifier(value, name)) continue; - referencedKeyframes.add(name); - if (!optionalTarget) nonOptionalKeyframes.add(name); + const { names } = parseAnimationLayers(decodedValue, property); + for (const nameNode of names) { + if (!nameNode) continue; + const name = nameNode.value; + for (const [original, scopedName] of keyframeNames) { + if (name !== original && name !== scopedName) continue; + referencedKeyframes.add(original); + if (!optionalTarget) nonOptionalKeyframes.add(original); + if (protectedTarget && !protectedKeyframeParts.has(scopedName)) { + protectedKeyframeParts.set(scopedName, protectedTarget); + } + if (lockedHostParts.length) { + const parts = lockedHostKeyframeParts.get(scopedName) ?? new Set(); + for (const part of lockedHostParts) parts.add(part); + lockedHostKeyframeParts.set(scopedName, parts); + } + if (restsAtStart) restingFromKeyframes.add(scopedName); + for (const subject of subjects) { + const names = subjectKeyframes.get(subject) ?? new Set(); + names.add(scopedName); + subjectKeyframes.set(subject, names); + } + } } }); }); + for (const subject of restingSubjects) { + for (const name of subjectKeyframes.get(subject) ?? []) restingFromKeyframes.add(name); + } const optionalOnlyKeyframes = new Set([...referencedKeyframes] .filter((name) => !nonOptionalKeyframes.has(name)) .map((name) => keyframeNames.get(name)!)); root.walkDecls((declaration: Declaration) => { const property = decodeCssEscapes(declaration.prop).toLowerCase(); - const unprefixedProperty = property.replace(/^-(?:webkit|moz|ms|o)-/, ""); + const unprefixedProperty = unprefixed(property); const value = declaration.value.trim(); const decodedValue = decodeCssEscapes(value); const owningRule = findOwningRule(declaration); const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null; + const keyframeScope = keyframesRule?.params.trim() ?? null; + // `to`/`100%` always rest, and `from`/`0%` when the rule can rest at start. + const restingFrame = !keyframesRule + || (keyframeScope !== null && keyframeStepCanRest(owningRule!.selector, restingFromKeyframes.has(keyframeScope))); const canHideTarget = owningRule ? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim())) : false; - // Trusted UI and essential audio/recovery controls stay available even for - // open skins. The host also draws authorization and recovery UI outside the - // skin root, so a container-level hide cannot remove them either. - const protectedTarget = owningRule && !keyframesRule ? selectorSubjectProtectedPart(owningRule.selector) : null; - // Every themeable host part referenced anywhere in the selector. A rule may - // target a descendant of the overlay (for example with `*`), so the subject - // alone is not enough to decide whether host chrome layout is at stake. - const hostChromeParts = owningRule && !keyframesRule ? selectorHostChromeParts(owningRule.selector) : []; + // A keyframe inherits the protected status of its referencing rules. + const protectedTarget = owningRule + ? keyframesRule + ? (keyframeScope ? protectedKeyframeParts.get(keyframeScope) ?? null : null) + : selectorSubjectProtectedPart(owningRule.selector) + : null; + // Every locked host part in the selector, not just the subject: `*` under + // the overlay is still host chrome. Decorative parts are excluded. + const hostChromeParts = owningRule + ? keyframesRule + ? (keyframeScope ? [...(lockedHostKeyframeParts.get(keyframeScope) ?? [])] : []) + : selectorLockedHostParts(owningRule.selector) + : []; const inHostChromeScope = hostChromeParts.length > 0; const inOverlayScope = hostChromeParts.includes("host.plugins.overlay"); + const overlaySubject = Boolean(!keyframesRule && owningRule + && selectorSubjectPart(owningRule.selector, HOST_CHROME_PART_IDS) === "host.plugins.overlay"); if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property) && !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) { throw declaration.error(pluginId @@ -231,55 +307,60 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets if (schemaVersion < 3 && isLayoutAffectingProperty(property)) { throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry."); } - // Host chrome lives outside the skin root and owns its own placement. A - // skin may repaint it (colors, borders, radius, artwork) but must not turn - // it — or any of its descendants — into a viewport-sized overlay above - // authorization/recovery UI. - if (inHostChromeScope && HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) { - throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls."); - } - if (inOverlayScope && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) { - throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead."); + // Host chrome keeps its placement and footprint; decorative host parts skip + // this lock. Overlay contents may size themselves unless viewport-sized. + if (inHostChromeScope && !keyframesRule) { + if (HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) { + throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls."); + } + if (overlaySubject && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) { + throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead."); + } + // Overlay contents may size themselves, but not to the viewport. + if (inOverlayScope && !overlaySubject && OVERLAY_SIZE_PROPERTIES.has(unprefixedProperty) && valueIsViewportSized(decodedValue)) { + throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead."); + } + } else if (inHostChromeScope && restingFrame && keyframeEscapesHostLock(unprefixedProperty, decodedValue)) { + throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition, restack or resize host controls into a fullscreen layer."); } if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing."); if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) { throw declaration.error("Executable CSS values are not allowed."); } - const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase(); - if (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) { + const indirectValue = restingFrame && /\b(?:var|attr)\s*\(/i.test(decodedValue); + if (indirectValue && protectedTarget + && (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) || PROTECTED_INDIRECT_HIDE_PROPERTIES.has(unprefixedProperty))) { + throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`); + } + if (indirectValue && !protectedTarget && INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && !canHideTarget && schemaVersion < 3) { + throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts."); + } + // An indirect animation name is checked at the declaration site. Locked + // host chrome (the plugin overlay) uses the same rule, otherwise a + // variable could point at a fullscreen keyframe. + if (!keyframesRule && (unprefixedProperty === "animation" || unprefixedProperty === "animation-name") + && /\b(?:var|attr)\s*\(/i.test(decodedValue)) { if (protectedTarget) { throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`); } - if (!canHideTarget && schemaVersion < 3) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts."); + if (inHostChromeScope) { + throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls through an indirect animation name."); + } } - const removesVisual = property === "all" - || (property === "display" && compactValue === "none") - || (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue)) - || (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue)) - || (property === "pointer-events" && compactValue === "none") - || (property === "clip-path" && /inset\(\s*50%/.test(compactValue)) - || (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue)); - if (removesVisual && protectedTarget) { + // One predicate for every way a declaration can hide or disable a part. + const hidesVisual = restingFrame && hidesVisually(unprefixedProperty, decodedValue); + if (hidesVisual && protectedTarget) { throw declaration.error(`The required control "${protectedTarget}" must remain available; permission, recovery and essential audio paths cannot be hidden.`); } - if (removesVisual && !canHideTarget && schemaVersion < 3) { + if (hidesVisual && !canHideTarget && schemaVersion < 3) { throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available."); } - const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue)) - || (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue)) - || (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue)); - if (visuallyRemoves && protectedTarget) { - throw declaration.error(`The required control "${protectedTarget}" must remain visible.`); - } - if (visuallyRemoves && !canHideTarget && schemaVersion < 3) { - throw declaration.error("Only explicitly optional visual parts may be visually removed."); - } - if (protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) { + if (restingFrame && protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) { throw declaration.error(`The required control "${protectedTarget}" must remain on screen and reachable.`); } - if (schemaVersion >= 3 && removesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls."); + if (schemaVersion >= 3 && hidesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls."); if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile."); - const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames); + const withScopedNames = rewriteScopedNames(value, unprefixedProperty, keyframeNames, fontFamilyNames); declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => { if (!hasSkinCssAsset(assets, assetPath)) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`); return `wskin-asset:${encodeURIComponent(assetPath)}`; @@ -427,24 +508,87 @@ function assertHostChromeSubject(parsed: selectorParser.Root): void { } } -/** Find a protected part in the subject (last compound) of any selector in a rule. */ -function selectorSubjectProtectedPart(selector: string): string | null { +/** Functional pseudo-classes whose arguments keep the subject role. */ +const SUBJECT_PSEUDO_CLASSES = new Set([":is", ":where", ":matches", ":-webkit-any", ":-moz-any"]); + +/** The nodes after the last combinator, i.e. the subject compound. */ +function lastCompound(nodes: SelectorNode[]): SelectorNode[] { + let start = 0; + for (let index = nodes.length - 1; index >= 0; index -= 1) { + if (nodes[index].type === "combinator") { start = index + 1; break; } + } + return nodes.slice(start); +} + +/** Find a part in a compound; `:is()`/`:where()`/`:nth-child(… of S)` and + * `:not(:not(X))` keep the subject role, a single `:not()` does not. */ +function compoundPart(nodes: SelectorNode[], parts: ReadonlySet): string | null { + for (const node of nodes) { + if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) { + const value = node.value.replace(/^['"]|['"]$/g, ""); + if (node.insensitive) { + const lower = value.toLowerCase(); + for (const part of parts) if (part.toLowerCase() === lower) return part; + } else if (parts.has(value)) { + return value; + } + } + if (node.type !== "pseudo" || !node.nodes) continue; + const pseudo = node.value.toLowerCase(); + if (SUBJECT_PSEUDO_CLASSES.has(pseudo) || pseudo === ":nth-child" || pseudo === ":nth-last-child") { + for (const nested of node.nodes) { + const part = compoundPart(lastCompound(nested.nodes), parts); + if (part) return part; + } + } else if (pseudo === ":not") { + // `:not(:not(X))` and `:not(:not(X), Y)` are `X`; wrappers like + // `:not(:is(:not(X)))` unwrap the same way. A single `:not(X)` is skipped. + for (const argument of node.nodes) { + const inner = nestedNegation(lastCompound(argument.nodes)); + if (!inner) continue; + for (const nested of inner.nodes) { + const part = compoundPart(lastCompound(nested.nodes), parts); + if (part) return part; + } + } + } + } + return null; +} + +/** A `:not(...)` argument that is itself a `:not`, possibly wrapped in `:is()`. */ +function nestedNegation(nodes: SelectorNode[]): SelectorPseudo | null { + const direct = nodes.find((node): node is SelectorPseudo => node.type === "pseudo" && node.value.toLowerCase() === ":not"); + if (direct) return direct; + for (const node of nodes) { + if (node.type !== "pseudo" || !node.nodes || !SUBJECT_PSEUDO_CLASSES.has(node.value.toLowerCase())) continue; + for (const nested of node.nodes) { + const found = nestedNegation(lastCompound(nested.nodes)); + if (found) return found; + } + } + return null; +} + +/** Every matching part in the subject of any selector in a rule. */ +function selectorSubjectParts(selector: string, parts: ReadonlySet): string[] { + const found: string[] = []; try { const parsed = selectorParser().astSync(selector); for (const item of parsed.nodes) { - let start = 0; - for (let index = item.nodes.length - 1; index >= 0; index -= 1) { - if (item.nodes[index].type === "combinator") { start = index + 1; break; } - } - for (let index = start; index < item.nodes.length; index += 1) { - const node = item.nodes[index]; - if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) continue; - const part = node.value.replace(/^['"]|['"]$/g, ""); - if (PROTECTED_PART_IDS.has(part)) return part; - } + const part = compoundPart(lastCompound(item.nodes), parts); + if (part && !found.includes(part)) found.push(part); } } catch { /* A malformed selector is rejected elsewhere. */ } - return null; + return found; +} + +function selectorSubjectPart(selector: string, parts: ReadonlySet): string | null { + return selectorSubjectParts(selector, parts)[0] ?? null; +} + +function selectorSubjectProtectedPart(selector: string): string | null { + return selectorSubjectPart(selector, PROTECTED_PART_IDS); } /** Find every themeable host part referenced by a selector, in any compound. */ @@ -460,71 +604,396 @@ function selectorHostChromeParts(selector: string): string[] { return parts; } +/** Host parts whose layout stays locked; decorative chrome is excluded. */ +function selectorLockedHostParts(selector: string): string[] { + return selectorHostChromeParts(selector).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part)); +} + +function unprefixed(property: string): string { + return property.replace(/^-(?:webkit|moz|ms|o)-/, ""); +} + function isLayoutAffectingProperty(property: string): boolean { - const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, ""); - if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true; - if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true; - if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true; - if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true; - return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed); + const local = unprefixed(property); + if (LAYOUT_AFFECTING_PROPERTIES.has(local)) return true; + if (/^(?:margin|padding)(?:-|$)/.test(local)) return true; + if (/^border(?:-|$)/.test(local) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(local)) return true; + if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(local)) return true; + return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(local); } /** * True when a positioning/margin/transform value can push a protected control - * off-screen. Thresholds are deliberately low: a protected control has a - * minimum 44 px hit target, so an offset of a hundred pixels is already enough - * to make it unreachable. Percentages and viewport units are compared against a - * full viewport/containing block. + * clearly off-screen: -1000 px / -100 % or +2000 px / +200 %. Ordinary layout + * moves are legitimate, so only viewport-ejecting values are rejected. */ -const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform|scale|rotate)(?:-|$)/; -const ABSOLUTE_OFFSET_LIMIT_PX = 100; -const RELATIVE_OFFSET_LIMIT = 100; +const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform)(?:-|$)/; +const OFFSET_LIMITS = { negativePx: 1000, positivePx: 2000, negativePercent: 100, positivePercent: 200 }; -function absoluteLengthToPixels(magnitude: number, unit: string): number | null { - switch (unit) { - case "px": return magnitude; - case "rem": case "em": return magnitude * 16; - case "ex": case "rex": case "ch": return magnitude * 8; - case "cm": return magnitude * 37.8; - case "mm": return magnitude * 3.78; - case "q": return magnitude * 0.945; - case "in": return magnitude * 96; - case "pt": return magnitude * 1.333; - case "pc": return magnitude * 16; - default: return null; +type Dimension = { value: number; unit: string }; + +const ABSOLUTE_UNIT_PIXELS: Record = { px: 1, rem: 16, em: 16, ex: 8, rex: 8, ch: 8, cm: 37.8, mm: 3.78, q: 0.945, in: 96, pt: 1.333, pc: 16 }; +function absoluteLengthToPixels(value: number, unit: string): number | null { + const factor = ABSOLUTE_UNIT_PIXELS[unit]; + return factor ? value * factor : null; +} + +type OffsetMeasurement = { kind: "pixels" | "percent"; value: number }; + +const VIEWPORT_UNIT_PATTERN = /^(?:s|l|d)?v(?:w|h|i|min|max)$|^cq(?:w|h|min|max|i|b)$/; + +/** CSS `` including a scientific-notation exponent. */ +const CSS_NUMBER_PATTERN = "[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?"; + +/** One CSS number, percentage or length, including a flat `calc()`. */ +function parseDimension(text: string): Dimension | null { + const compact = text.trim().toLowerCase(); + const calc = /^calc\(([\s\S]*)\)$/.exec(compact); + if (calc) return evaluateCalc(calc[1]); + const match = new RegExp(`^(${CSS_NUMBER_PATTERN})([a-z%]*)$`).exec(compact); + return match ? { value: Number(match[1]), unit: match[2] } : null; +} + +/** Flat `calc()`: sums of products over numbers and one unit; nested or mixed + * input is unknown (`null` → allowed). A sign after `*`/`/` is a factor, + * so `calc(2px*-1000)` is -2000px, not 2px + -1000. */ +function evaluateCalc(text: string): Dimension | null { + const compact = text.replace(/\s+/g, ""); + const tokens = compact.match(new RegExp(`[*/]|${CSS_NUMBER_PATTERN}(?:[a-z%]+)?`, "g")); + if (!tokens || tokens.join("") !== compact) return null; + const total: Dimension = { value: 0, unit: "" }; + let term: Dimension | null = null; + let pending: "*" | "/" | null = null; + const addTerm = (): boolean => { + if (!term || (total.unit && term.unit && total.unit !== term.unit)) return false; + total.value += term.value; + total.unit ||= term.unit; + return true; + }; + for (const token of tokens) { + if (token === "*" || token === "/") { pending = token; continue; } + const factor = parseDimension(token); + if (!factor) return null; + if (pending && term) { + if (factor.unit && (term.unit || pending === "/")) return null; + term = { value: pending === "/" ? term.value / factor.value : term.value * factor.value, unit: term.unit || factor.unit }; + pending = null; + continue; + } + if (term && !addTerm()) return null; + term = factor; + pending = null; } + return !pending && addTerm() ? total : null; +} + +/** Normalise one length for comparison; a bare number is not a length. */ +function lengthMeasurement(value: string): OffsetMeasurement | null { + const dimension = parseDimension(value); + if (!dimension?.unit) return null; + if (dimension.unit === "%" || VIEWPORT_UNIT_PATTERN.test(dimension.unit)) return { kind: "percent", value: dimension.value }; + const pixels = absoluteLengthToPixels(dimension.value, dimension.unit); + return pixels === null ? null : { kind: "pixels", value: pixels }; +} + +function exceedsOffset(measurement: OffsetMeasurement | null): boolean { + if (!measurement) return false; + const [negative, positive] = measurement.kind === "percent" + ? [OFFSET_LIMITS.negativePercent, OFFSET_LIMITS.positivePercent] + : [OFFSET_LIMITS.negativePx, OFFSET_LIMITS.positivePx]; + return measurement.value <= -negative || measurement.value >= positive; } function valueMovesOffscreen(property: string, value: string): boolean { if (!OFFSET_PROPERTY_PATTERN.test(property)) return false; let offscreen = false; valueParser(value).walk((node) => { - if (node.type !== "word") return; - const match = /^(-?(?:\d+|\d*\.\d+))(px|rem|em|r?ex|ch|%|cm|mm|q|in|pt|pc|(?:s|l|d)?v(?:w|h|min|max)|cq(?:w|h|min|max|i|b))$/i.exec(node.value); - if (!match) return; - const magnitude = Math.abs(Number(match[1])); - const unit = match[2].toLowerCase(); - if (unit === "%" || /^(?:s|l|d)?v(?:w|h|min|max)$/.test(unit) || /^cq(?:w|h|min|max|i|b)$/.test(unit)) { - if (magnitude >= RELATIVE_OFFSET_LIMIT) offscreen = true; - return; + const name = node.type === "function" ? node.value.toLowerCase() : ""; + if (node.type === "word") offscreen ||= exceedsOffset(lengthMeasurement(node.value)); + else if (name === "calc") { + offscreen ||= exceedsOffset(lengthMeasurement(valueParser.stringify(node))); + return false; + } else if (node.type === "function" && (name === "matrix" || name === "matrix3d")) { + // A matrix can smuggle a large translation in unitless numbers. + const items = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim())); + offscreen ||= (name === "matrix" ? [items[4], items[5]] : [items[12], items[13]]) + .some((item) => item <= -OFFSET_LIMITS.negativePx || item >= OFFSET_LIMITS.positivePx); + return false; } - const pixels = absoluteLengthToPixels(magnitude, unit); - if (pixels !== null && pixels >= ABSOLUTE_OFFSET_LIMIT_PX) offscreen = true; + return undefined; }); - // A matrix transform can smuggle a large translation in unitless numbers. - if (property === "transform") { - valueParser(value).walk((node) => { - if (node.type !== "function") return; - const name = node.value.toLowerCase(); - if (name !== "matrix" && name !== "matrix3d") return; - const numbers = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim())); - const translations = name === "matrix" ? [numbers[4], numbers[5]] : [numbers[12], numbers[13]]; - if (translations.some((translation) => Number.isFinite(translation) && Math.abs(translation) >= ABSOLUTE_OFFSET_LIMIT_PX)) offscreen = true; - }); - } return offscreen; } +/** This declaration removes the element from view; partial effects stay allowed. */ +function hidesVisually(property: string, value: string): boolean { + if (property === "all") return true; + const text = decodeCssEscapes(value).trim().toLowerCase(); + if ((property === "display" && text === "none") || (property === "visibility" && /^(?:hidden|collapse)$/.test(text)) + || (property === "pointer-events" && text === "none") || (property === "content-visibility" && text === "hidden")) return true; + if (property === "opacity") return (numericValue(text) ?? 1) <= 0.01; + if (property === "filter") return filterHides(text); + if (property === "transform") return transformHides(text); + if (property === "scale") return scalePropertyHides(text); + if (property === "clip-path") return clipPathHides(text); + if (property === "clip") return clipHides(text); + return property === "mask" || property === "mask-image" ? maskHides(text) : false; +} + +/** Visit every function node; `test` gets the lower-cased name and its arguments. */ +function anyFunction(value: string, test: (name: string, args: string) => boolean): boolean { + let hit = false; + valueParser(value).walk((node) => { + if (node.type === "function" && test(node.value.toLowerCase(), valueParser.stringify(node.nodes))) hit = true; + }); + return hit; +} + +/** A number, a percentage as 0–1, or a flat `calc()` of numbers. */ +function numericValue(value: string): number | null { + const dimension = parseDimension(value); + if (!dimension) return null; + return dimension.unit === "%" ? dimension.value / 100 : dimension.unit === "" ? dimension.value : null; +} + +function filterHides(value: string): boolean { + return anyFunction(value, (name, args) => { + const amount = numericValue(args); + return amount !== null && (name === "opacity" ? amount <= 0.01 : name === "brightness" && amount <= 0); + }); +} + +function numbers(text: string): number[] { + return text.split(/[\s,]+/).map(numericValue).filter((item): item is number => item !== null); +} + +function isZeroFactor(value: number): boolean { + return Math.abs(value) <= 0.001; +} + +function transformHides(value: string): boolean { + return anyFunction(value, (name, args) => { + const factors = numbers(args); + if (name === "scale" || name === "scale3d") return factors.slice(0, 2).some(isZeroFactor); + return (name === "scalex" || name === "scaley") && isZeroFactor(factors[0] ?? 1); + }); +} + +function scalePropertyHides(value: string): boolean { + const factors = numbers(value); + return factors.length > 0 && (isZeroFactor(factors[0]) || (factors.length > 1 && isZeroFactor(factors[1]))); +} + +function zeroLength(value: string | undefined): boolean { + const dimension = value ? parseDimension(value) : null; + return dimension !== null && isZeroFactor(dimension.value); +} + +function insetHides(args: string): boolean { + const sides = args.split(/\bround\b/i)[0].trim().split(/\s+/).map(parseDimension); + if (sides.some((side) => !side || (side.unit !== "" && side.unit !== "%"))) return false; + const values = sides.map((side) => side!.value); + const [top, right = top, bottom = top, left = right] = values; + return top + bottom >= 100 || left + right >= 100; +} + +function clipPathHides(value: string): boolean { + return anyFunction(value, (name, args) => { + const shape = args.split(/\bat\b/i)[0].trim(); + if (name === "inset") return insetHides(args); + if (name === "circle") return zeroLength(shape.split(/\s+/)[0]); + return name === "ellipse" && shape.split(/\s+/).filter(Boolean).slice(0, 2).some(zeroLength); + }); +} + +function clipHides(value: string): boolean { + const match = /^rect\(([\s\S]*)\)$/i.exec(value.trim()); + if (!match) return false; + const sides = match[1].split(/[\s,]+/).filter(Boolean); + return sides.length === 4 && sides.every(zeroLength); +} + +const GRADIENT_PRELUDE_KEYWORDS = new Set([ + "from", "to", "left", "right", "top", "bottom", "center", "at", "circle", "ellipse", + "closest-side", "closest-corner", "farthest-side", "farthest-corner", "in", +]); + +/** `#rgb0` / `#rrggbb00`, `transparent`, or a colour function with alpha ≤ 0.01. */ +function colorIsTransparent(text: string): boolean { + const value = text.trim().toLowerCase(); + if (value === "transparent" || /^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(value)) return true; + return anyFunction(value, (name, args) => { + if (!/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)$/.test(name)) return false; + const slash = args.split("/"); + if (slash.length > 1) return (numericValue(slash[slash.length - 1].trim()) ?? 1) <= 0.01; + const channels = numbers(args); + return (name === "rgba" || name === "hsla") && channels.length >= 4 && channels[3] <= 0.01; + }); +} + +/** A gradient is a full mask only when every colour stop is fully transparent. */ +function gradientIsAllTransparent(args: string): boolean { + let transparent = false; + for (const segment of args.split(/,(?![^(]*\))/)) { + const text = segment.trim().toLowerCase(); + if (!text) continue; + const first = valueParser(text).nodes.find((node) => node.type !== "space" && node.type !== "comment"); + if (!first) continue; + if (first.type === "function" ? colorIsTransparent(valueParser.stringify([first])) : colorIsTransparent(first.value)) { + transparent = true; + continue; + } + if (first.type === "word" && (GRADIENT_PRELUDE_KEYWORDS.has(first.value.toLowerCase()) || parseDimension(first.value)?.unit)) continue; + return false; + } + return transparent; +} + +function maskHides(value: string): boolean { + return anyFunction(value, (name, args) => + name === "alpha" || name === "luminance" + ? (numericValue(args) ?? 1) <= 0 + : name.endsWith("gradient") && gradientIsAllTransparent(args)); +} + +/** + * Name token per layer. In the shorthand a keyword fills the first slot of its + * category; a repeated category (or any other word) is the name, so + * `bob 2s alternate` references `bob`. Times, numbers and functions are skipped. + */ +function parseAnimationLayers(value: string, property: string): { parsed: ReturnType; names: Array } { + const parsed = valueParser(value); + const groups: ValueNode[][] = [[]]; + for (const node of parsed.nodes) { + if (node.type === "div" && node.value === ",") groups.push([]); + else if (node.type !== "space" && node.type !== "comment") groups[groups.length - 1].push(node); + } + const names = groups.map((nodes) => { + const words = nodes.filter((node) => node.type === "word" || node.type === "string"); + if (property === "animation-name") { + const name = words[0] ? decodeCssEscapes(words[0].value).toLowerCase() : ""; + return words[0] && name !== "none" && !CSS_WIDE_KEYWORDS.has(name) ? words[0] : null; + } + const used = new Set(); + for (const node of words) { + const token = decodeCssEscapes(node.value).toLowerCase(); + const dimension = parseDimension(token); + if (dimension && ["", "s", "ms"].includes(dimension.unit)) continue; + const category = ANIMATION_KEYWORD_CATEGORIES.get(token); + if (category && used.has(category)) return node; + if (category) used.add(category); + else if (node.type === "word" && CSS_WIDE_KEYWORDS.has(token)) continue; + else return node; + } + return null; + }); + return { parsed, names }; +} + +/** Any restart/alternate/fill keyword or indirect value can hold the start frame. + * Multi-layer rules are judged as a whole, which errs towards checking `from`. */ +function ruleCanRestAtStart(rule: Rule): boolean { + let resting = false; + rule.walkDecls((declaration: Declaration) => { + const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase()); + if (!["animation", "animation-direction", "animation-fill-mode", "animation-play-state"].includes(property)) return; + const value = decodeCssEscapes(declaration.value).toLowerCase(); + resting ||= /\b(?:var|attr)\s*\(/.test(value) + || valueParser(value).nodes.some((node) => node.type === "word" && RESTING_START_KEYWORDS.has(node.value)); + }); + return resting; +} + +/** `to`/`100%` always rest; `from`/`0%` rest for reverse/alternate, a + * backwards/both fill, or a paused start. A long animation or a pause mid-way + * (negative delay) can linger on an unchecked intermediate frame — accepted, + * because recovery lives in a closed-shadow top-layer capsule. */ +function keyframeStepCanRest(selector: string, restsAtStart: boolean): boolean { + return selector.split(",").some((step) => { + const value = decodeCssEscapes(step).trim().toLowerCase(); + if (value === "to") return true; + if (value === "from") return restsAtStart; + const position = parseDimension(value); + return position?.unit === "%" && (position.value >= 100 || (restsAtStart && position.value <= 0)); + }); +} + +const OVERLAY_SIZE_PROPERTIES = new Set([ + "width", "height", "min-width", "min-height", "max-width", "max-height", + "inline-size", "block-size", "min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", +]); + +function isViewportSizedDimension(dimension: Dimension | null): boolean { + return Boolean(dimension && VIEWPORT_UNIT_PATTERN.test(dimension.unit) && Math.abs(dimension.value) >= 100); +} + +function valueIsViewportSized(value: string): boolean { + let sized = false; + valueParser(value).walk((node) => { + if (node.type === "word") sized ||= isViewportSizedDimension(parseDimension(node.value)); + else if (node.type === "function" && node.value.toLowerCase() === "calc") { + sized ||= isViewportSizedDimension(parseDimension(valueParser.stringify(node))); + return false; + } + return undefined; + }); + return sized; +} + +function isIdentityNumber(value: number): boolean { + return Math.abs(value - 1) <= 0.001; +} + +function isZeroAngleOrLength(value: string): boolean { + return zeroLength(value); +} + +/** Identity transforms (`none`, `scale(1)`, `translate(0)`, `rotate(0deg)`). */ +function transformIsIdentity(value: string): boolean { + const compact = value.trim().toLowerCase(); + if (compact === "none") return true; + let seen = false; + let identity = true; + valueParser(compact).walk((node) => { + if (node.type !== "function") return; + seen = true; + const name = node.value.toLowerCase(); + const args = valueParser.stringify(node.nodes); + const factors = numbers(args); + if (name === "scale" || name === "scale3d") identity &&= factors.length > 0 && factors.every(isIdentityNumber); + else if (name === "scalex" || name === "scaley" || name === "scalez") identity &&= factors.length > 0 && isIdentityNumber(factors[0]); + else if (/^translate(?:3d|[xyz])?$/.test(name)) identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength); + else if (/^rotate(?:3d|[xyz])?$/.test(name) || name === "skew" || name === "skewx" || name === "skewy") { + identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength); + } else identity = false; + }); + return seen && identity; +} + +function isNeutralLockValue(property: string, value: string): boolean { + const compact = value.trim().toLowerCase(); + if (["none", "auto", "static"].includes(compact) || CSS_WIDE_KEYWORDS.has(compact)) return true; + if (property === "scale" || property === "zoom") { + const factors = numbers(compact); + return factors.length > 0 && factors.every(isIdentityNumber); + } + if (property === "rotate") return isZeroAngleOrLength(compact); + if (property === "transform") return transformIsIdentity(compact); + if (property === "translate" || property.startsWith("inset") || /^(?:top|right|bottom|left)$/.test(property)) { + return compact.split(/\s+/).every((token) => token === "auto" || isZeroAngleOrLength(token)); + } + return compact === "0" || isZeroAngleOrLength(compact); +} + +/** Resting host-chrome keyframes reuse the direct lock per property: locked + * properties only accept identity/neutral values; sizes only reject viewport sizes. */ +function keyframeEscapesHostLock(property: string, value: string): boolean { + const compact = decodeCssEscapes(value).trim().toLowerCase(); + if (isNeutralLockValue(property, compact)) return false; + if (OVERLAY_SIZE_PROPERTIES.has(property)) return valueIsViewportSized(value); + return HOST_CHROME_LOCKED_PROPERTIES.has(property); +} + function findOwningRule(node: Node): Rule | null { let parent = node.parent; while (parent && parent.type !== "root") { @@ -543,11 +1012,6 @@ function findKeyframesRule(rule: Rule): AtRule | null { return null; } -function referencesCssIdentifier(value: string, identifier: string): boolean { - const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value); -} - export function rewriteAssetUrls(value: string, resolve: (path: string) => string): string { const parsed = valueParser(value); const resolvePackageAsset = (rawValue: string): string => { @@ -605,16 +1069,24 @@ function parseSingleFontFamily(value: string): string { } function rewriteScopedNames(value: string, property: string, keyframes: Map, fontFamilies: Map): string { - const parsed = valueParser(value); - if (["animation", "animation-name", "font", "font-family"].includes(property)) { - parsed.walk((node) => { - if (node.type !== "word" && node.type !== "string") return; - const keyframe = keyframes.get(node.value); - if (keyframe) node.value = keyframe; - const family = fontFamilies.get(node.value.toLowerCase()); - if (family) node.value = family; - }); + if (!["animation", "animation-name", "font", "font-family"].includes(property)) return value; + // Rewrite against the decoded value: `p\75 lse` must become the scoped name + // of `@keyframes pulse`, exactly like the matching walk above. + const decoded = decodeCssEscapes(value); + if (property === "animation" || property === "animation-name") { + const { parsed, names } = parseAnimationLayers(decoded, property); + for (const node of names) { + const scoped = node ? keyframes.get(node.value) : undefined; + if (node && scoped) node.value = scoped; + } + return parsed.toString(); } + const parsed = valueParser(decoded); + parsed.walk((node) => { + if (node.type !== "word" && node.type !== "string") return; + const family = fontFamilies.get(node.value.toLowerCase()); + if (family) node.value = family; + }); return parsed.toString(); } diff --git a/src/shared/skin-visual-parts.ts b/src/shared/skin-visual-parts.ts index 76301a1..853546d 100644 --- a/src/shared/skin-visual-parts.ts +++ b/src/shared/skin-visual-parts.ts @@ -43,6 +43,17 @@ export const HOST_TRUSTED_PART_IDS: ReadonlySet = new Set([ "host.permission", ]); +/** + * Trusted host controls that an open skin may fold into its own layout through + * `chrome.json#slots`. The key names the protected part, not a CSS hook: the + * skin only declares an anchor rectangle, the host still owns, paints and + * hit-tests the control. Extend this set (for example with `host.permission`) + * when another protected control learns the same runtime placement. + */ +export const HOST_SLOTTABLE_PART_IDS: ReadonlySet = new Set([ + "host.recovery", +]); + /** All host-owned parts (used by the part registry and documentation). */ export const HOST_PART_IDS: ReadonlySet = new Set([ ...HOST_CHROME_PART_IDS, diff --git a/web/public/host-chrome-demo.wskin b/web/public/host-chrome-demo.wskin index 2947c16..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 2b0cd38..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 09d81d7..c44d765 100644 --- a/web/src/components/HostChrome.vue +++ b/web/src/components/HostChrome.vue @@ -33,7 +33,13 @@