feat(skins): add component authoring workflow

This commit is contained in:
illusia committed 2026-10-10 15:53:51 +08:00
1 parent 96c29394f3
commit 0c4cc344ef
25 files changed
+2013 -58

No files matched your search

@@ -19,6 +19,7 @@ Use this skill when editing or authoring a WebSpeak `.wskin` package, a built-in
- Follow the schema-specific CSS rules: v1/v2 reject layout changes; v3 allows layout, placement, size, typography, and visibility changes within the skin root. Keep CSS package-local, scoped to public hooks, and free of external resources or executable values. Do not describe v3's fixed element, attribute, data, and action registries as complete customization; the target is a versioned, isolated plugin runtime with author-owned UI structure, CSS, and local logic.
- v3 can replace or obscure normal page controls. A surface must request `ui.surface.replace` and stays disabled until the user approves it. Custom interfaces can use their own declarative nodes and CSS; embed optional host widgets only when a trusted WebSpeak control is useful. Available widget IDs are registered in `src/shared/skin-plugin.ts`; each stateful host widget may appear once per page. Preserve usable microphone, disconnect, device-settings, screen-share and recovery paths at desktop and mobile sizes. Verify both the return-to-built-in-UI and restore-built-in-skin buttons. The host recovery and permission UI render outside the skin root. Keep `/admin/**` unskinned.
- `components.json` schema v1 is legacy; v2 adds `mode: "surface"` and optional allowlisted host-widget nodes; v3 expands bounded declarative composition, data bindings, events and permission-gated voice actions. v3 keeps its fixed tag/attribute/data/action registries; use v4 when a skin needs its own UI logic or generic HTML/SVG tree.
- For full-page custom interfaces, author the messages, composer, channel selection, audio controls and member presentation as skin-owned nodes wherever the safe data/action API supports them. Treat host widgets as optional trusted leaves for capabilities that must remain inside WebSpeak, such as screen capture and live media playback. Schema v3 conditions may compare local state with a permissioned repeated item and render explicit empty states; host actions may run on committed `change`, submit, or explicit activation, while live `input` remains local-only.
- The v4 runtime is enabled in production for Wasm only. A plugin must pass the local digest-bound approval before a disposable worker starts. The module has a 256 KiB source cap, 4 MiB linear-memory cap, 10,000,000 fuel cap, 100 ms execution deadline and a 64 MiB interpreter container cap; the WebClient governor allows two active jobs, up to 64 pending jobs, and a 120-second queue deadline. Each job may emit one UTF-8 JSON UI document of up to 256 KiB. The host validates schema v3/v4/v5/v6 and renders nodes itself; it never inserts plugin HTML. Standard tags and scalar attributes are allowed within size limits. Script, embedded browsing, navigation/external resource attributes, inline `style`, event-handler attributes and dangerous elements are rejected. Custom element names become inert `div` placeholders, so page-registered Web Components do not run.
- `env.ui_input_read` supplies at most 64 KiB per run, including plugin-local scalar state, a safe event record and a public-data projection capped at 48 KiB. The projection contains only fields permitted by the plugin manifest; never pass TeamSpeak addresses, credentials, SDK objects, media streams or private application objects. `ui.input.read` is a separate opt-in for text and checkbox/select values; tell users that browser autofill may be included, and never request password/file/hidden values. Keep server-list labels and opaque identifiers separate from addresses and credentials. Use `servers.quickList` plus `quickServers.switch` when a custom UI should show favorites and recent servers together.
- Host actions can be requested only by a run caused by a real browser-trusted UI event. The host rechecks the plugin grant, action permission, arguments and current session; a guest cannot supply its own trust flag. The first bridge permits one action per event run. Async Wasm cannot be assumed to preserve transient user activation: use the trusted `voice.screen-share-start` host widget for screen capture. Host widgets execute in WebSpeak and do not grant author code access to private widget state.
@@ -34,8 +35,19 @@ Use this skill when editing or authoring a WebSpeak `.wskin` package, a built-in
3. Run the relevant skin-package tests and application build after a related batch of changes. Fix validation failures rather than weakening v1/v2 boundaries, v3 permission and event checks, surface limits, or the host-widget allowlist.
4. Package the contents of the skin directory so `manifest.json` is at the archive root, then import it through `/admin/skins` and retest the installed `.wskin` in a visitor session.
Keep README files beside the package source instead of inside `.wskin`: the skin importer rejects undeclared files such as `README.zh-CN.md`.
The shipped default day, default night, and ILLUSIA skins are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them. A permission request is not a grant; verify the deny and revoke paths. Do not claim a skin was visually verified against an external reference unless that page was actually accessible.
## Current project sequencing
- The user has explicitly set the order: finish and stabilize the generic skin authoring system before implementing a reference skin. Do not keep browsing reference pages or redesigning the framework during skin implementation.
- The public-client component editor stores authoring overrides in per-skin/per-version local-storage keys. A malformed document must not render; allow that one version's saved edit to be cleared without disturbing other skins. Route every import and edit through the shared declarative component parser; never weaken the tag/attribute, data-path, permission, action, or host-widget checks to make an edit fit.
- Treat data-ws-* as host-reserved DOM metadata: preserve backward parsing of older skin packages, but strip those attributes at the rendering boundary and reject them in new authoring saves.
- Component-tree CRUD includes component creation, duplication, deletion and ordering; node creation, duplication, deletion and sibling ordering; JSON property edits; undo/redo; and components.json import/export. Give duplicated nodes fresh stable layout-part identifiers. Preserve a usable base page and host recovery controls when a custom surface is removed.
- Before beginning the reference skin, verify tree CRUD, empty documents, safe schema migration, version-scoped persistence, import/export round trips, rejection of unsafe/over-permissioned trees, skin/page switching, and recovery. Run the related tests and server/client builds as one batch, then retain a stable checkpoint.
- Once that gate passes, only make small framework fixes for concrete incompatibilities found while implementing the voice-only reference. Do not expand unrelated application code or repeat visual-reference collection without a specific unresolved question.
## Integration findings
- A full-page surface is a separate user-approved capability (`ui.surface.replace`); package installation alone must leave the built-in page visible.
+27 -5
View File
@@ -100,6 +100,14 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖
- 为队列顺序、容量、取消、重复释放和超时补充了单元测试。Wasm 已在生产构建开放;该节点完善了运行资源边界,但不代表独立安全审查已完成。
- 当前授权页中的“发现”路由展示了陪玩匹配、店铺列表、排行榜等运营内容;这些页面明确排除在 KOOK 语音客户端复刻范围之外。
### R3.7:完整 surface 的状态和表单交互(已实施首批)
- 复刻样例暴露了 v3 声明式界面的两个实际缺口:条件只能和静态常量比较,不能把用户选中的行与重复数据关联;宿主动作也被禁止绑定到提交后的 `change`,导致自定义滑杆等控件只能显示、无法驱动 TeamSpeak。
- 扩展 schema v3 条件,使其可将本地状态与权限化重复项字段比较,并可针对有读取权限的公开集合声明空态。v1/v2 不接受这些新增字段,既有包继续保持原边界。
- 允许 `change` 上的宿主动作,保留 `input` 仅更新本地状态的规则;滑杆松手、选择器提交等已提交交互可以调用权限内动作。WebClient 音量入口接受浏览器范围控件提交的数值字符串并在宿主端校验和夹限。
- Harbor Voice 首次把聊天消息/输入框、麦克风/扬声器/音量/断开、悄悄话和频道选中态改为皮肤自有结构与 CSS;单击仅选中,双击复用现有 TeamSpeak 切换流程。屏幕采集和实时视频仍由可信宿主控件执行,皮肤可重排并完全换肤。
- 已为条件解析、集合空态、表单事件及 Harbor `.wskin` 结构补回归测试;仍需在真实语音会话中验证控件行为和桌面/移动视觉效果。
### R4:整页皮肤界面和宿主控件组合(核心路径已接入,完整验收待完成)
- components.json schema v2 引入、schema v3 继续支持 `mode: "surface"`,允许替换首页或语音工作区的完整可见页面;旧 schema v1/v2 继续兼容。
@@ -124,21 +132,35 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖
## 下一阶段
### R5:KOOK 语音客户端体验复刻(参考采集与首版皮肤已完成,浏览器验收待进行)
### R5:通用组件作者编辑器与皮肤系统稳定门禁(进行中)
- 在开始移植任何外部语音客户端界面前,先完成皮肤系统自身的可用性和稳定性。此顺序由用户明确指定;系统完成后,参考皮肤阶段只允许为具体兼容问题做小修。
- 当前已接入本地组件编辑器首批能力:新建/复制/删除/排序组件,选中组件树节点,添加/复制/删除/排序节点,编辑完整组件或节点 JSON,撤销/重做,以及按皮肤 ID 和版本本地保存、导入导出 components.json。没有组件文件的皮肤也可以从空 schema v3 文档开始;复制节点时会重新生成稳定布局标识,避免两个节点共用同一编辑目标。
- 编辑器导入、每次保存和运行时渲染统一复用 components.json schema 校验。危险标签/属性、未注册数据路径、未声明权限、越权动作、重复状态型宿主控件、超深或超大的树都必须拒绝;本地编辑不能赋予包外权限,也不能访问管理员页面、服务器地址、口令或身份材料。
- 存储现按皮肤 ID 和版本分键;单份损坏数据可以单独清除并恢复原包,不影响其他皮肤。宿主保留的 data-ws-* 属性不会由作者节点写入渲染 DOM。
- 编辑器操作按钮和选择器现在保留至少 44 px 触控高度,支持 Escape 关闭并在打开/关闭时移动焦点;继续打磨窄屏布局和可理解的校验提示。组件新增权限仍由宿主按既有权限机制要求批准;删除整页 surface 后应自然回到 WebSpeak 页面和宿主恢复控件。
- 稳定门禁至少覆盖:组件/节点完整 CRUD 与撤销重做;导入导出往返;空组件文档;旧 schema v1/v2 只读兼容并在首次编辑时安全升到 v3;存储按皮肤版本隔离且坏数据可独立恢复;非法或越权文档不保存、不渲染;页面切换、皮肤切换及恢复入口不丢失。
- 2026-10-10 的统一验证通过:617 项测试通过,服务端 TypeScript 构建、前端类型检查与 Vite 生产构建通过。这确认了自动化核心 CRUD 路径,不代表作者体验、跨浏览器行为或插件安全边界已经验收。
- 当前补查发现客户端曾接受 v4 包级 `layout.json`,服务端却未读取该字段,造成同一个包本地可导入但服务端拒绝;已为校验一致性修复补充回归用例。后续只在整批修改后统一验证。
- R5 完成门槛包括:编辑器能完整管理组件和节点;更新后页面即时预览;导入、导出、版本隔离、坏数据恢复及旧格式迁移可靠;客户端与服务端对每种包格式采用一致校验;键盘与窄屏作者流程可用;授权拒绝/撤销、恢复原生页面、插件销毁与资源回收通过针对性验证;跨浏览器动作和资源边界完成独立复核。
- R5 门槛通过前暂停新增参考皮肤功能和视觉扩展。R6 现有样例作为回归材料保留,之后只因明确的样例阻塞做小范围系统修补,不再反复重做通用架构或重新采集参考页面。
### R6:KOOK 语音客户端体验复刻(等待 R5 通过)
- 已在用户授权范围内查看首两个语音频道;记录频道树、嵌套语音成员、中心聊天、成员栏与左下语音控制坞。麦克风保持关闭,未发送消息,也未使用管理员操作。
- 已创建可导入的 Harbor Voice `.wskin`,包含首页、收藏/历史服务器栏、频道树、当前频道语音成员、聊天、成员栏和音频/共享宿主控件;频道加入使用双击映射到现有 TeamSpeak 加入流程。该样例使用 v3 验证兼容 surface 与基础能力,v4 Wasm runtime 另由运行时测试验证。
- 移动布局保留服务器/频道导航、聊天、成员和语音控制;频道下的成员嵌套在窄屏隐藏,避免横向频道栏被撑高。当前已验证包导入与相关权限/交互结构,桌面/手机视觉比对、授权撤销和宿主恢复仍需在浏览器完成。
- Harbor Voice `.wskin` 已有首页和语音工作区 surface。本批由皮肤组件负责频道选中、消息渲染/输入和悄悄话界面;底部麦克风/扬声器嵌入经权限门控的 WebSpeak 音频控件,使用户继续使用既有灵敏度设置。频道单击仅选中,双击才通过宿主现有流程加入,屏幕采集按钮和视频流由 WebSpeak 执行并仍可由皮肤外观覆盖。频道缩进读取现有公开树深度,成员显示说话/静音/离开状态,服务器栏底部展示当前 TeamSpeak 昵称,未扩展宿主数据字段。修改源码后可用 `npm run skin:harbor:build` 重建导入包。
- 移动布局保留服务器/频道导航、聊天、成员和语音控制;频道下的成员嵌套在窄屏隐藏,避免横向频道栏被撑高。本轮在隔离预览中确认首页 surface 在桌面视口和 390×844 窄屏下均无裁切;语音 surface 尚未用 TeamSpeak 会话做端到端视觉验收,授权撤销和宿主恢复也仍待浏览器验收。
- 打包验证发现 `.wskin` 导入器拒绝包内 `README.zh-CN.md` 等未声明文件;说明文档需留在源码目录外,压缩包只收录清单及声明资源。
- 只复刻语音客户端体验;发现、陪玩、活动、广告、商城和管理后台页面明确排除。只记录可实际访问的授权页面,不保留服务器/房间标识、成员名单或聊天内容。
### R6:作者体验与兼容性
### R7:作者体验与兼容性
- 已提供可导入的完整 surface 示例,记录权限清单和桌面/移动布局:[`open-voice-surface.wskin`](./examples/OPEN-VOICE-SURFACE.md)。
- 对首页连接、收藏快速切换、频道切换、成员区、聊天、音频和屏幕共享进行端到端验收。
- 检查产品支持语言、键盘焦点、触屏、拒绝授权、撤销和恢复路径。
- 更新皮肤开发技能、公开控件索引和各语言用户文档。
### R7:皮肤商城与管理员面板重做时交付
### R8:皮肤商城与管理员面板重做时交付
- 商城目录、发现、安装、更新、回退、下架与撤销同管理员面板改造一起设计;后台本身保持不可皮肤化。
- 首选人工审查的静态清单和 Release 附件,列出来源、版本、许可证、包校验值和组件权限。
+3 -3
View File
@@ -6,7 +6,7 @@
完整目标中,皮肤作者可以用自己的插件组件、DOM、CSS 和本地逻辑排列、替换、隐藏或重做公开客户端界面中的任何视觉元素,也可以重建首页和完整语音工作区。连接、频道、聊天、音频、收藏/历史、共享等基础能力始终由 WebSpeak/TeamSpeak 宿主保留;皮肤能替换其展示和交互入口,但不能删除或篡改底层业务能力。宿主恢复入口、权限管理和安全提示位于皮肤之外,任何插件失效、拒绝授权或撤销后都能回到原生可用界面。
当前 v1/v2/v3 只能达到该目标的一部分:v3 组件依赖有限标签、属性、数据和动作白名单;v4 Wasm 已接入授权生命周期、宿主渲染、受限 UI 事件回路、按读取权限筛选的数据投影、首版 TeamSpeak 动作桥,以及插件布局根、组件根与节点的本地布局覆盖。插件整体和内部节点均可在 Flex/Grid 父容器中分别排序;widget 可声明公开页面挂载槽位,surface 可直接重做公开页面。尚待实现的是插件默认布局分发、专用安装/管理界面与作者工具;跨浏览器验证和独立安全审查也未完成。本规格区分已实现行为与后续工作,不以当前限制重新定义完成态。
当前 v1/v2/v3 只能达到该目标的一部分:v3 组件依赖有限标签、属性、数据和动作白名单;v4 Wasm 已接入授权生命周期、宿主渲染、受限 UI 事件回路、按读取权限筛选的数据投影、首版 TeamSpeak 动作桥,以及插件布局根、组件根与节点的布局覆盖。插件整体和内部节点均可在 Flex/Grid 父容器中分别排序;widget 可声明公开页面挂载槽位,surface 可直接重做公开页面。v3/v4 包可以通过可选 `layout.json` 提供作者默认布局,用户本地覆盖单独保存;v4 专用插件安装/管理界面、Wasm 作者工具和跨浏览器验证仍未完成,独立安全审查也尚未进行。本规格区分已实现行为与后续工作,不以当前限制重新定义完成态。
适用页面为连接首页、语音工作区和公开演示页。管理员面板及其数据、管理 API 明确排除,不读取皮肤包。语音服务的运营、广告、陪玩、活动和商店等页面不属于语音客户端皮肤范围。
@@ -16,7 +16,7 @@
v3 自定义组件不是脚本插件。components.json schema v1 是既有格式;schema v2 增加 `mode: "surface"` 与宿主控件节点;schema v3 扩大自定义节点、嵌套、重复列表和声明式交互的边界,并增加映射到现有语音功能的动作。宿主仍解析固定元素/属性白名单、固定数据集合、简单绑定与有限动作,再由 Vue 创建节点。每个自定义组件根和每个有 DOM 的节点都会作为独立本地布局项,可移动、调整尺寸、改变外观或隐藏。节点指定 `part` 后使用该标识;未指定时使用树路径,树结构调整后旧的本地覆盖可能要重新设置。可操作节点保留至少 44 px 的触控目标。作者不必使用固定宿主控件目录,但 v3 仍不足以表达任意自定义 UI 逻辑和完整插件生命周期。管理员面板和演示页不能被 surface 替换。
宿主控件通过固定 ID 嵌入,始终由 WebSpeak 代码运行。当前可选注册表包括 `home.connection-form`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls` 和 `voice.disconnect-control`。每个控件在同一页面最多出现一次;未知 ID 或重复的有状态控件会拒绝导入。`voice.screen-share-start` 仅限语音页,并要求插件声明 `voice.screenShare.control`;宿主按钮在可信点击处理器内直接开始屏幕采集,以保留浏览器要求的瞬时用户激活。作者可以不用这些控件,自行绘制界面并将点击、双击等事件绑定到公开数据与受权限保护的动作。
宿主控件通过固定 ID 嵌入,始终由 WebSpeak 代码运行。当前可选注册表包括 `home.connection-form`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls` 和 `voice.disconnect-control`。每个控件在同一页面最多出现一次;未知 ID 或重复的有状态控件会拒绝导入。schema v3 的受保护控件会在导入时验证完整权限集合:音频控件要求 `audio.status.read`、`audio.microphone.control` 与 `audio.output.control`;聊天控件要求 `chat.channel.read` 与 `chat.channel.send`;成员卡片要求 `session.members.read` 及 `voice.screenShare.read`、`voice.screenShare.control`;屏幕共享播放器要求后两者;悄悄话控件要求 `voice.whisper.status.read` 与 `voice.whisper.control`;连接/断开控件要求 `voice.disconnect`。既有 schema v2 包仍按此前规则校验,`voice.screen-share-start` 则保留原有 `voice.screenShare.control` 要求。该控件仅限语音页;宿主按钮在可信点击处理器内直接开始屏幕采集,以保留浏览器要求的瞬时用户激活。作者可以不用这些控件,自行绘制界面并将点击、双击等事件绑定到公开数据与受权限保护的动作。
v1-v3 包不能提交 HTML 字符串、事件处理代码、JavaScript、WebAssembly、远程脚本、任意 URL、表单导航、浏览器存储访问或网络调用。v4 可携带本地 JS/Wasm/CSS;JS 仍只校验和缓存,Wasm 在生产构建中经本地摘要授权后运行一次性有界任务,并经宿主解析、渲染动态 UI。运行时支持 `ui.surface.replace`、限定的公开只读数据权限和首版宿主动作效果;投影前由宿主按插件清单过滤字段,总快照最多 48 KiB,`ui_input_read` 输入最多 64 KiB。动作效果限于可信 UI 事件触发的同一轮调用、单个动作,并复用现有动作权限与参数校验。所有版本都拒绝未知协议字段、权限、动作和数据路径;v1-v3 拒绝未知节点/属性,v4 Wasm 输出则对标签名做语法验证、拒绝具备脚本/导航/嵌入能力的标签与属性,并将自定义标签惰性渲染为普通 `div`。
@@ -24,7 +24,7 @@ v1-v3 包不能提交 HTML 字符串、事件处理代码、JavaScript、WebAsse
已实现的 v4 包描述为 `plugins.json` schema v1:每包 1–64 个插件,每个插件指定唯一小写 ID、语义版本、API 版本 1、`home`/`voice` 页面、`widget`/`surface` 模式、`plugins/<id>/` 下入口 JS 或 Wasm/可选 CSS、该目录中的图片/woff2 素材和现有权限表中的权限。入口扩展名决定默认运行时,也可显式写 `runtime: "javascript"` 或 `runtime: "wasm"`,且必须匹配扩展名。每页至多一个 v4 surface,且必须申请 `ui.surface.replace`;导入器也拒绝与同页 v3 surface 冲突。清单最多 256 KiB、插件入口最多 256 KiB、插件样式最多 512 KiB、每插件最多 32 个素材;引用文件必须存在且路径不重复。客户端与服务端复用同一解析器;客户端还对 Wasm 入口做固定 ABI 预检。SHA-256 摘要覆盖描述字段和入口、样式、全部素材;本机授权按皮肤、插件 ID 保存并绑定皮肤/插件版本、API 版本、文件摘要及权限策略版本。该摘要仅用于检测本机授权后包内容是否变化,不是发布者签名或来源证明。WebClient 已有逐页授权、Wasm 生命周期、schema 校验后的安全 UI 渲染和插件 CSS 装载;Wasm 只会在用户明确批准后运行,且生产执行受全局 worker 上限控制。动态 UI 可使用经过 manifest 权限校验的 `voice.screen-share-start` 宿主按钮;异步 Wasm 动作桥本身不承载屏幕采集所需的瞬时用户激活。
descriptor 通过可选 `mount` 字段定义 widget 的语义挂载位置;未设置时挂在页面级插件宿主。descriptor 尚未定义默认显隐、布局位置/尺寸和同级顺序。每个运行时插件有独立布局根;用户可用通用布局编辑器本地覆盖插件整体、插件组件根和其节点的位置、尺寸、显隐、安全外观及 Flex/Grid 同级顺序。顺序只改视觉排列,不改变 DOM 与键盘焦点顺序。这些用户数据与作者文件分开存储。后续可为作者提供包内默认布局值,但必须保证沙箱内代码不能改动其他插件的宿主容器或恢复控件。
descriptor 通过可选 `mount` 字段定义 widget 的语义挂载位置;未设置时挂在页面级插件宿主。默认显隐、位置/尺寸和同级顺序不放进插件 descriptor,而由包级可选 `layout.json` 按 `skin.<page>.runtime_plugin_root_<plugin-id>` 等动态布局 ID 声明。通用布局编辑器可本地覆盖插件整体、插件组件根和其节点的位置、尺寸、显隐、安全外观及 Flex/Grid 同级顺序;用户本地覆盖优先于作者默认值。顺序只改视觉排列,不改变 DOM 与键盘焦点顺序。沙箱内代码不能改动其他插件的宿主容器或恢复控件。
v4 当前运行路径已不使用 v3 固定标签/属性/状态/动作表来构建插件 UI;插件可在受限输出协议内构建自定义 HTML/SVG 树、隔离 CSS 和本地交互,并把公开客户端页面替换或拆成可排序、显隐、独立授权和可回退的插件。危险的浏览器能力仍由标签/属性拒绝规则、字段限额与宿主权限桥约束;这不是不受限制的原始 DOM/JavaScript 环境。现有宿主控件只是可选的原生能力组件;连接/频道/聊天/音频等基础业务能力仍由 WebSpeak 保留、可由插件重新呈现,且始终能通过宿主恢复界面回到可信基础 UI。旧 v1/v2/v3 包继续按原验证与能力运行,不获得追溯性代码权限。
+16 -5
View File
@@ -6,7 +6,7 @@ KOOK 语音界面参考仅覆盖用户授权的语音频道,语音区结构记
可导入的 KOOK 风格完整语音工作区测试包见[Harbor Voice Workspace](./examples/harbor-voice/README.zh-CN.md);它只复用 WebSpeak 的可信宿主控件和公开会话数据,不包含站点素材、运营页或后台。
v3 的 HTML 标签、属性、可绑定数据集合和宿主动作仍是固定白名单;作者自定义 UI 逻辑由 v4 的有界 Wasm 路径提供。生产构建中的 v4 Wasm 运行时已接入本地摘要授权、页面生命周期、动态 HTML/SVG 节点渲染、插件 CSS、权限化只读数据投影、宿主动作桥、语义挂载槽位和全局 worker 资源治理;目前支持 `session.status.read`、频道/成员/聊天、收藏/最近列表和音频/共享状态读取权限,以及 `ui.surface.replace`、`ui.input.read`。每份公开数据投影最多 48 KiB,只传清单准许的字段;Wasm 可生成自定义节点树、有限本地状态并响应命名 UI 事件。宿主动作只接受可信 UI 事件触发的同一轮输出中的单个请求,并重新检查插件权限、参数和当前会话;`dblclick` 可绑定到加入频道等已授权宿主动作。JavaScript 仍只校验和缓存,不执行。每个 v4 插件有独立布局根,用户可调整插件整体、组件根和 DOM 节点的位置、尺寸、显隐、安全外观及 Flex/Grid 同级显示顺序;`plugins.json` 可将 widget 放到公开页面的注册槽位,也可通过 surface 重做整页。这个边界能承载完整自定义客户端界面,但不等于已完成插件商城和作者管理平台;跨浏览器测试与独立安全审查尚未完成。
v3 保留安全的标准元素和属性白名单;组件可通过完整页面 surface 自己构建界面,不需要把聊天、音频或成员 UI 锁在固定宿主面板里。条件可比较权限化公开数据、重复项和皮肤本地状态,也可判断已登记公开集合是否为空。表单输入先留在宿主渲染的本地状态;宿主动作不能在逐字输入时触发,可在已提交的 `change`、表单提交或显式点击上触发。作者自定义代码逻辑由 v4 有界 Wasm 路径提供。生产构建中的 v4 Wasm 运行时已接入本地摘要授权、页面生命周期、动态 HTML/SVG 节点渲染、插件 CSS、权限化只读数据投影、宿主动作桥、语义挂载槽位和全局 worker 资源治理;目前支持 `session.status.read`、频道/成员/聊天、收藏/最近列表和音频/共享状态读取权限,以及 `ui.surface.replace`、`ui.input.read`。每份公开数据投影最多 48 KiB,只传清单准许的字段;Wasm 可生成自定义节点树、有限本地状态并响应命名 UI 事件。宿主动作只接受可信 UI 事件触发的同一轮输出中的单个请求,并重新检查插件权限、参数和当前会话;`dblclick` 可绑定到加入频道等已授权宿主动作。JavaScript 仍只校验和缓存,不执行。每个 v4 插件有独立布局根,用户可调整插件整体、组件根和 DOM 节点的位置、尺寸、显隐、安全外观及 Flex/Grid 同级显示顺序;`plugins.json` 可将 widget 放到公开页面的注册槽位,也可通过 surface 重做整页。这个边界能承载完整自定义客户端界面,但不等于已完成插件商城和作者管理平台;跨浏览器测试与独立安全审查尚未完成。
`.wskin` 包可为公开页面定制艺术表现。v1 提供 CSS 与美术资源;v2 另外携带受校验的布局 JSON;v3 可自由安排公开组件,并用 components.json 声明由宿主渲染的安全组件。所有版本均由 WebSpeak 保留基础组件的业务逻辑和 TeamSpeak 行为。
@@ -39,7 +39,7 @@ plugins/<plugin-id>/style.css # v4 可选:插件样式,目前只校验和缓
plugins/<plugin-id>/assets/ # v4 插件专属的本地图片或字体素材
```
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。说明文档放在源码目录旁边,不能打进 `.wskin`;导入器会拒绝 `README.md` 等未声明文件。
### `manifest.json`
@@ -117,11 +117,11 @@ v1 和 v2 都只支持公开页面。`/admin/**` 不加载布局、用户覆盖
### schemaVersion 3:开放皮肤和完整声明式页面
v3 清单的 packageType 固定为 open-skin,entry 指向 CSS,components 指向 components.json;不含 v2 的 layout 或 permissions 字段。组件文件可以省略。仅 v3 开放公开页面的 CSS 排版能力,v1/v2 仍按旧 CSS 规则校验。客户端导入和服务端登记使用同一共享组件 schema 与权限白名单。
v3 清单的 packageType 固定为 open-skin,entry 指向 CSS,components 可选指向 components.json;与 v2 不同,v3 不声明 permissions,但可以可选声明 layout 指向作者默认布局 `layout.json`。组件文件可以省略。仅 v3 开放公开页面的 CSS 排版能力,v1/v2 仍按旧 CSS 规则校验。客户端导入和服务端登记使用同一共享组件 schema 与权限白名单。
components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。schema v1 维持旧兼容;schema v2 引入 `mode: "widget"`(默认)或 `mode: "surface"`,并提供可选宿主控件节点;schema v3 保持这些能力,扩大声明式 UI 的节点/状态/动作边界,并增加用户操作事件和语音功能动作。v3 仍使用固定元素/属性、公开数据集合和宿主动作白名单,不是任意 HTML 或任意脚本。每个组件需声明 id、name、page、accessibleName、permissions、actions 和 root,可选 state。page 接受 home、voice、demo;surface 仅可用于 home 和 voice,并且必须请求 `ui.surface.replace`。用户批准前不会显示 surface,撤销后宿主立即恢复普通页面。所有皮肤组件根节点及其中的每个可见元素都以动态布局项加入本地布局编辑器,可独立移动、缩放、改尺寸、改外观或隐藏。按钮、输入框及显式用户操作节点保留 44 px 最小触控区域。为让用户覆盖在树结构调整后仍能指向同一元素,请给重要节点设置稳定的 `part` 名称;未设置时按组件树位置生成标识。v4 包和插件运行时见[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md);Wasm 生产运行已开启,作者 JavaScript 仍关闭。
普通节点使用白名单 HTML/SVG 元素。节点可包含 text、part、className、受限 attributes、包内图片 asset、bindValue、本地 repeat/when、events 和 children。文本与属性支持简单的双大括号数据路径;不支持表达式、HTML 字符串或脚本。重复列表可使用注册的公开集合;频道重复项仅能再重复其 `channel.members`,并且需要额外批准 `session.members.read`。宿主每个组件的实际渲染节点最多 8192 个,防止嵌套集合放大界面。schema v2 另允许固定宿主控件节点,例如:
普通节点使用白名单 HTML/SVG 元素。节点可包含 text、part、className、受限 attributes、包内图片 asset、bindValue、本地 repeat/when、events 和 children。文本与属性支持简单的双大括号数据路径;不支持表达式、HTML 字符串或脚本。重复列表可使用注册的公开集合;频道重复项仅能再重复其 `channel.members`,并且需要额外批准 `session.members.read`。宿主每个组件的实际渲染节点最多 8192 个,防止嵌套集合放大界面。v3/v4 的作者默认布局使用与 v2 相同的有界 layout schema;可通过 `skin.<page>.<component-id>` 指定声明式自定义组件,通过 `skin.<page>.runtime_plugin_root_<plugin-id>` 指定 v4 插件根。用户的本地布局覆盖优先于包默认值。schema v2 另允许固定宿主控件节点,例如:
```json
{
@@ -148,7 +148,7 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s
}
```
当前可选宿主控件 ID:`home.connection-form`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls`、`voice.disconnect-control`。未知控件和同页重复控件会被拒绝;每个控件的状态和业务动作仍由 WebSpeak 内部处理。`voice.screen-share-start` 仅能放在语音页,并要求 `voice.screenShare.control`;宿主按钮在可信点击处理器内直接启动屏幕采集,避免异步 Wasm 回调丢失浏览器瞬时用户激活。自定义 UI 可以完全用普通声明式节点搭建,不需要采用这些控件。只显示收藏时可用 `favorites.items` 和 `favorites.switch`;若要将收藏与最近连接放在同一自定义栏,可用 `servers.quickList` 数据与 `quickServers.switch` 动作。服务器目标始终使用本机生成的不透明令牌,不把地址、密码或身份材料交给组件。频道行也可把 `voice.joinChannel` 绑定到双击事件,切房继续走 TeamSpeak 原有权限和密码流程。v3 还提供经独立权限保护的麦克风/扬声器、输出音量、离开状态、悄悄话、断开连接和屏幕共享动作;它们只调用 WebSpeak 已有操作,屏幕采集仍由浏览器或操作系统询问用户。
当前可选宿主控件 ID:`home.connection-form`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls`、`voice.disconnect-control`。未知控件和同页重复控件会被拒绝;每个控件的状态和业务动作仍由 WebSpeak 内部处理。schema v3 会检查受保护控件所需权限:音频控件需 `audio.status.read`、`audio.microphone.control` 和 `audio.output.control`;聊天需 `chat.channel.read` 与 `chat.channel.send`;成员卡片需 `session.members.read` 及屏幕共享读取/控制权限;屏幕共享播放器需 `voice.screenShare.read` 与 `voice.screenShare.control`;悄悄话控件需对应状态读取和控制权限;断开/连接控件需 `voice.disconnect`。既有 v2 包维持旧校验行为,`voice.screen-share-start` 仍像此前一样要求 `voice.screenShare.control`。该控件仅能放在语音页;宿主按钮在可信点击处理器内直接启动屏幕采集,避免异步 Wasm 回调丢失浏览器瞬时用户激活。自定义 UI 可以完全用普通声明式节点搭建,不需要采用这些控件。只显示收藏时可用 `favorites.items` 和 `favorites.switch`;若要将收藏与最近连接放在同一自定义栏,可用 `servers.quickList` 数据与 `quickServers.switch` 动作。服务器目标始终使用本机生成的不透明令牌,不把地址、密码或身份材料交给组件。频道行也可把 `voice.joinChannel` 绑定到双击事件,切房继续走 TeamSpeak 原有权限和密码流程。v3 还提供经独立权限保护的麦克风/扬声器、输出音量、离开状态、悄悄话、断开连接和屏幕共享动作;它们只调用 WebSpeak 已有操作,屏幕采集仍由浏览器或操作系统询问用户。
示例包见 [KAAK voice 示例](./examples/KAAK-VOICE.md),其 components.json 展示了公开频道列表和在线成员侧栏;[Open Voice Surface](./examples/OPEN-VOICE-SURFACE.md) 展示了完整首页和语音工作区 surface,是格式验证脚手架。KAAK 的语音视觉参考来自用户授权进入的前两个语音房间;只记录布局,不保留服务器/房间标识、成员名或聊天内容。当前数据权限和宿主动作以[开放皮肤规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)中的清单为准。组件按本地用户授权后才渲染;权限对每个皮肤版本、页面和组件分别保存,可在宿主权限入口撤销。页面替换时,宿主会额外显示“返回标准界面”和“恢复内置皮肤”入口;拒绝授权或离开 surface 后,普通页面可立即恢复。
@@ -158,9 +158,20 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s
注意:v3 CSS 和 surface 可以隐藏或遮挡普通语音控件。权限和返回标准界面提示由宿主在皮肤根之外绘制;其他界面控件仍受皮肤排版影响。测试时务必确保麦克风、设置、退出语音、屏幕共享操作和移动端导航仍有可达路径。组件演示页 /demo 使用合成数据,加入频道和聊天动作只更新演示状态;它不支持宿主控件或整页替换。
### 本地组件结构编辑器
公开客户端页可打开“组件结构”编辑器,直接管理当前皮肤版本的声明式组件树。它支持创建、复制、删除组件和节点、添加子节点或同级节点、调整顺序、编辑组件元数据与节点 JSON、撤销/重做,以及导入/导出 components.json。该编辑器不属于管理员面板,不加载到 /admin/**。
编辑器只保存本地 authoring 覆盖,键按皮肤 ID 和版本隔离;原始皮肤包不会被改写。导入及每次提交都会走 parseSkinPluginDocument 的同一 schema 和权限校验,运行时也再次验证从本地存储读出的文档。不能通过编辑器新增任意脚本、事件处理器属性、外部资源、未知数据路径、宿主保留的 data-ws-* 属性、未授权宿主动作或未登记的宿主控件。旧 v2 组件首次升级到 v3 时,编辑器会为受保护的内置宿主控件补齐对应权限声明;这不会自动批准权限,控件继续等待宿主授权 UI 明确确认。
旧 schema v1/v2 皮肤可以保持原样使用,第一次结构编辑时会把已验证的数据规范化为 schema v3;旧包自身不被升级或覆盖。schema v3 允许 components 为空:删除最后一个皮肤组件会恢复基础 WebSpeak 页面,宿主授权与恢复控件始终在皮肤内容之外。节点不能脱离组件根单独删除;重要节点应设置稳定 part 名称,避免树顺序变化后基于路径生成的布局覆盖指向其他节点。
系统开发顺序由用户明确指定:先完成并验证通用组件 CRUD、权限和数据边界、持久化及回退流程,并保存稳定检查点;之后才开始 KOOK 语音客户端皮肤。参考皮肤阶段只为具体兼容问题对框架做小修,不反复采集参考或重构框架。
### schemaVersion 4:插件包描述与有界 Wasm 运行时
v4 在 open-skin 包中增加必需的 `plugins` 路径。服务端登记和客户端导入共用 `plugins.json` schema v1 校验器;校验插件 ID、页面、模式、权限、文件归属、路径唯一性和包内文件大小,并将插件文件与普通皮肤素材分别缓存。客户端还会对 Wasm 入口执行固定导入/导出 ABI 预检。SHA-256 授权基础会绑定插件描述、入口、样式和全部素材;本机授权记录还会绑定皮肤/插件版本、API 版本和权限策略版本。摘要只能发现已授权内容被替换,不能证明发布者身份。WebClient 有本地授权对话框和 Wasm 运行生命周期;目前支持安全 UI 输出、可信 UI 事件回调、插件专属 CSS、按清单权限过滤的公开数据投影(单份最多 48 KiB)和首版单动作宿主桥。支持的数据读取权限包括 `session.status.read`、`session.channels.read`、`session.members.read`、`chat.channel.read`、`favorites.read`、`servers.quickList.read`、`audio.status.read`、`voice.whisper.status.read`、`voice.screenShare.status.read` 和 `voice.screenShare.read`,另支持 `ui.surface.replace`。`ui.input.read` 单独控制插件是否能收到用户在插件自有输入框中输入或被浏览器自动填入的值;未获授权时仍可收到事件类型,但不会收到文本或勾选值。密码、文件和隐藏输入始终拒绝。宿主动作仅可由可信 UI 事件触发,按清单权限、动作参数和会话状态再次校验;生产构建也有全局 worker 上限。跨浏览器验证和独立安全审查仍待完成。
v4 在 open-skin 包中增加必需的 `plugins` 路径,并允许沿用可选 `layout` 路径提供插件根和节点的作者默认布局。服务端登记和客户端导入共用 `plugins.json` schema v1 校验器;校验插件 ID、页面、模式、权限、文件归属、路径唯一性和包内文件大小,并将插件文件与普通皮肤素材分别缓存。客户端还会对 Wasm 入口执行固定导入/导出 ABI 预检。SHA-256 授权基础会绑定插件描述、入口、样式和全部素材;本机授权记录还会绑定皮肤/插件版本、API 版本和权限策略版本。摘要只能发现已授权内容被替换,不能证明发布者身份。WebClient 有本地授权对话框和 Wasm 运行生命周期;目前支持安全 UI 输出、可信 UI 事件回调、插件专属 CSS、按清单权限过滤的公开数据投影(单份最多 48 KiB)和首版单动作宿主桥。支持的数据读取权限包括 `session.status.read`、`session.channels.read`、`session.members.read`、`chat.channel.read`、`favorites.read`、`servers.quickList.read`、`audio.status.read`、`voice.whisper.status.read`、`voice.screenShare.status.read` 和 `voice.screenShare.read`,另支持 `ui.surface.replace`。`ui.input.read` 单独控制插件是否能收到用户在插件自有输入框中输入或被浏览器自动填入的值;未获授权时仍可收到事件类型,但不会收到文本或勾选值。密码、文件和隐藏输入始终拒绝。宿主动作仅可由可信 UI 事件触发,按清单权限、动作参数和会话状态再次校验;生产构建也有全局 worker 上限。跨浏览器验证和独立安全审查仍待完成。
```json
{
Binary file not shown.
+3 -3
View File
@@ -2,8 +2,8 @@
这是一个 KOOK 语音工作区风格的完整皮肤测试包,参考范围只限语音客户端:服务器快捷栏、频道列表、中央聊天、成员列表和底部语音控制。没有复用 KOOK 的图片、标志、广告或站点文案,也没有加入发现、陪玩、派对、商城、活动通知、排行榜或管理后台。
皮肤使用 `components.json` 的安全声明式 surface 和 WebSpeak 宿主控件。频道树会在当前频道下显示已连接成员;双击频道才请求 TeamSpeak 加入,避免单击选中与加入混为一谈。服务器与频道列表只读取已授权的公开标签和状态;切换服务器、静音和断开都由宿主执行并校验。皮肤不读取服务器地址、账号凭据或连接密钥,也不包含可执行 JavaScript/Wasm;这个样例用于验证 v3 兼容 surface,v4 Wasm 插件运行时另由运行时测试覆盖。
皮肤使用 `components.json` 的完整声明式 surface 自己构建频道树、聊天消息与输入框、成员状态和悄悄话控制;底部音频区嵌入 WebSpeak 的可信音频控件,继续使用现有麦克风/扬声器开关和音频设置(包括麦克风灵敏度)。样例隐藏与语音布局无关的伴奏开关;断开和频道控制仍由 WebSpeak 校验并执行。频道缩进直接映射 TeamSpeak 公开树深度;频道单击只改变皮肤本地选中态,双击才请求 TeamSpeak 切换频道。语音成员列表显示公开的说话、静音和离开状态。消息、频道和成员数据由权限筛选后提供。屏幕共享启动保留一个可自行排版和换肤的可信宿主按钮,以保留浏览器要求的真实用户手势;视频流和设备 API 不交给皮肤代码。皮肤不读取服务器地址、账号凭据或连接密钥,也不包含可执行 JavaScript/Wasm;这个样例用于验证 v3 surface 的可定制界面和交互,v4 Wasm 插件运行时另由运行时测试覆盖。
桌面布局保留四个区域:服务器快捷栏、频道树、聊天区和成员区;连接后语音控制坞固定在频道栏底部。窄屏下服务器栏保持可用,频道项转为横向滚动,成员与语音控制各自占一行,基础连接控制不被隐藏。
桌面布局保留四个区域:服务器快捷栏、频道树、聊天区和成员区;服务器栏底部展示当前 TeamSpeak 昵称,连接后语音控制坞固定在频道栏底部。昵称项只呈现当前会话身份,不模拟 KOOK 账号或资料运营功能。窄屏下服务器栏保持可用,频道项转为横向滚动,成员与语音控制各自占一行,基础连接控制不被隐藏。
`manifest.json`、`components.json` 与 `skin.css` 是可编辑源码。根目录的 `../harbor-voice.wskin` 是源码打包后的本地导入包;可在测试实例的皮肤管理页导入验证,当前没有加入公共皮肤目录或发布到服务器。
`manifest.json`、`components.json` 与 `skin.css` 是可编辑源码。根目录的 `../harbor-voice.wskin` 是源码打包后的本地导入包;源码修改后运行 `npm run skin:harbor:build` 重新打包,再在测试实例的皮肤管理页导入验证。当前没有加入公共皮肤目录或发布到服务器。
+169 -9
View File
@@ -54,18 +54,40 @@
"session.members.read",
"session.channel.join",
"servers.quickList.read",
"servers.quickList.switch"
"servers.quickList.switch",
"chat.channel.read",
"chat.channel.send",
"audio.status.read",
"audio.microphone.control",
"audio.output.control",
"voice.whisper.status.read",
"voice.whisper.control",
"voice.disconnect",
"voice.screenShare.read",
"voice.screenShare.control"
],
"actions": {
"switch-server": {
"type": "quickServers.switch",
"args": { "quickServerId": "{{server.id}}" }
},
"select-channel": {
"type": "ui.setState",
"args": { "key": "selectedchannel", "value": "{{channel.id}}" }
},
"join-channel": {
"type": "voice.joinChannel",
"args": { "channelId": "{{channel.id}}" }
}
},
"send-message": {
"type": "chat.sendMessage",
"args": { "text": "{{state.message}}" }
},
"disconnect": { "type": "voice.disconnect", "args": {} },
"whisper-on": { "type": "voice.setWhisperActive", "args": { "active": true } },
"whisper-off": { "type": "voice.setWhisperActive", "args": { "active": false } }
},
"state": { "selectedchannel": "", "message": "" },
"root": {
"tag": "main",
"part": "workspace",
@@ -150,13 +172,20 @@
"attributes": {
"type": "button",
"aria-current": "{{channel.current}}",
"aria-label": "Join {{channel.name}}"
"aria-label": "Double-click to join {{channel.name}}",
"data-depth": "{{channel.depth}}"
},
"events": { "dblclick": "join-channel" },
"events": { "click": "select-channel", "dblclick": "join-channel" },
"children": [
{ "tag": "span", "part": "channel-glyph", "children": [{ "text": "◉" }] },
{ "tag": "span", "part": "channel-name", "children": [{ "text": "{{channel.name}}" }] },
{ "tag": "small", "part": "channel-count", "children": [{ "text": "{{channel.memberCount}}" }] }
{ "tag": "small", "part": "channel-count", "children": [{ "text": "{{channel.memberCount}}" }] },
{
"tag": "span",
"part": "selected-channel-indicator",
"when": { "path": "state.selectedchannel", "equals": "{{channel.id}}" },
"attributes": { "aria-label": "Selected" }
}
]
},
{
@@ -172,6 +201,20 @@
"children": [
{ "tag": "span", "part": "channel-member-avatar", "children": [{ "text": "{{voicemember.name}}" }] },
{ "tag": "span", "part": "channel-member-name", "children": [{ "text": "{{voicemember.name}}" }] },
{
"tag": "span",
"part": "channel-member-muted",
"when": { "path": "voicemember.status", "equals": "muted" },
"attributes": { "aria-label": "Microphone muted" },
"children": [{ "text": "MIC OFF" }]
},
{
"tag": "span",
"part": "channel-member-away",
"when": { "path": "voicemember.status", "equals": "away" },
"attributes": { "aria-label": "Away" },
"children": [{ "text": "AWAY" }]
},
{
"tag": "span",
"part": "channel-member-state",
@@ -214,7 +257,66 @@
}
]
},
{ "widget": "voice.chat-panel", "part": "chat" },
{
"tag": "div",
"part": "chat",
"children": [
{
"tag": "div",
"part": "chat-message-list",
"attributes": { "aria-label": "Current channel messages", "role": "log", "aria-live": "polite" },
"children": [
{
"tag": "p",
"part": "chat-empty",
"when": { "path": "chat.messages", "empty": true },
"children": [{ "text": "No messages yet. Say hello to the channel." }]
},
{
"tag": "article",
"part": "chat-message",
"repeat": { "path": "chat.messages", "as": "message" },
"children": [
{
"tag": "header",
"part": "chat-message-heading",
"children": [
{ "tag": "strong", "part": "chat-message-author", "children": [{ "text": "{{message.author}}" }] },
{ "tag": "time", "part": "chat-message-time", "children": [{ "text": "{{message.time}}" }] }
]
},
{ "tag": "p", "part": "chat-message-text", "children": [{ "text": "{{message.text}}" }] }
]
}
]
},
{
"tag": "form",
"part": "chat-composer",
"events": { "submit": "send-message" },
"children": [
{
"tag": "input",
"part": "chat-input",
"bindValue": "message",
"attributes": {
"type": "text",
"maxlength": 1000,
"autocomplete": "off",
"placeholder": "Message this channel",
"aria-label": "Message this channel"
}
},
{
"tag": "button",
"part": "chat-send",
"attributes": { "type": "submit", "aria-label": "Send message" },
"children": [{ "text": "Send" }]
}
]
}
]
},
{ "widget": "voice.screen-share-player", "part": "screen-player" }
]
},
@@ -247,12 +349,47 @@
"when": { "path": "member.speaking", "equals": true },
"attributes": { "aria-label": "Speaking" },
"children": [{ "text": "SPEAKING" }]
},
{
"tag": "span",
"part": "member-muted-state",
"when": { "path": "member.status", "equals": "muted" },
"attributes": { "aria-label": "Microphone muted" },
"children": [{ "text": "MIC OFF" }]
},
{
"tag": "span",
"part": "member-away-state",
"when": { "path": "member.status", "equals": "away" },
"attributes": { "aria-label": "Away" },
"children": [{ "text": "AWAY" }]
}
]
}
]
},
{ "widget": "voice.whisper-controls", "part": "whisper-controls" }
{
"tag": "div",
"part": "whisper-controls",
"children": [
{
"tag": "button",
"part": "whisper-start",
"when": { "path": "whisper.status.active", "equals": false },
"attributes": { "type": "button", "aria-label": "Start whisper" },
"events": { "click": "whisper-on" },
"children": [{ "text": "Whisper" }]
},
{
"tag": "button",
"part": "whisper-stop",
"when": { "path": "whisper.status.active", "equals": true },
"attributes": { "type": "button", "aria-label": "Stop whisper" },
"events": { "click": "whisper-off" },
"children": [{ "text": "Whisper on" }]
}
]
}
]
},
{
@@ -269,8 +406,31 @@
{ "tag": "span", "part": "voice-dock-caption", "children": [{ "text": "VOICE CONNECTED" }] }
]
},
{ "widget": "voice.audio-controls", "part": "audio-controls" },
{ "widget": "voice.disconnect-control", "part": "disconnect-control" }
{
"tag": "div",
"part": "voice-dock-actions",
"children": [
{ "widget": "voice.screen-share-start", "part": "screen-share-start" },
{ "widget": "voice.audio-controls", "part": "audio-controls" },
{
"tag": "button",
"part": "disconnect-control",
"attributes": { "type": "button", "aria-label": "Disconnect voice" },
"events": { "click": "disconnect" },
"children": [{ "text": "Leave" }]
}
]
}
]
},
{
"tag": "div",
"part": "identity-entry",
"when": { "path": "session.status.userName" },
"attributes": { "role": "group", "aria-label": "Current TeamSpeak identity" },
"children": [
{ "tag": "span", "part": "identity-monogram", "children": [{ "text": "TS" }] },
{ "tag": "span", "part": "identity-name", "children": [{ "text": "{{session.status.userName}}" }] }
]
}
]
+1 -1
View File
@@ -3,7 +3,7 @@
"packageType": "open-skin",
"id": "community.harbor-voice",
"name": "Harbor Voice Workspace",
"version": "1.0.0",
"version": "1.1.0",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "A KOOK-inspired dark voice workspace using only WebSpeak host controls and public session data.",
+206 -5
View File
@@ -216,6 +216,39 @@
line-height: 1;
}
[data-ws-plugin-part="harbor-workspace.identity-entry"] {
display: grid;
justify-items: center;
gap: 4px;
width: 100%;
margin-top: auto;
padding: 9px 1px 1px;
border-top: 1px solid var(--skin-harbor-border);
}
[data-ws-plugin-part="harbor-workspace.identity-monogram"] {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border: 1px solid #ffffff18;
border-radius: 50%;
color: var(--skin-harbor-text);
background: linear-gradient(145deg, #4a4c53, #292a30);
font-size: 10px;
font-weight: 850;
}
[data-ws-plugin-part="harbor-workspace.identity-name"] {
display: block;
max-width: 100%;
overflow: hidden;
color: var(--skin-harbor-muted);
font-size: 8px;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.channel-panel"] {
z-index: 1;
grid-column: 2;
@@ -266,6 +299,7 @@
[data-ws-plugin-part="harbor-workspace.section-label"] { margin: 0 8px 7px; }
[data-ws-plugin-part="harbor-workspace.channel-row"] {
position: relative;
display: flex;
align-items: center;
gap: 9px;
@@ -280,6 +314,14 @@
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.selected-channel-indicator"] {
position: absolute;
inset: 0;
border: 1px solid var(--skin-harbor-accent);
border-radius: inherit;
pointer-events: none;
}
[data-ws-plugin-part="harbor-workspace.channel-row"]:hover,
[data-ws-plugin-part="harbor-workspace.channel-row"][aria-current="true"] {
color: var(--skin-harbor-text);
@@ -290,6 +332,15 @@
box-shadow: inset 2px 0 var(--skin-harbor-accent);
}
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="1"] { padding-inline-start: 19px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="2"] { padding-inline-start: 29px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="3"] { padding-inline-start: 39px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="4"] { padding-inline-start: 49px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="5"] { padding-inline-start: 59px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="6"] { padding-inline-start: 69px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="7"] { padding-inline-start: 79px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="8"] { padding-inline-start: 89px; }
[data-ws-plugin-part="harbor-workspace.channel-glyph"] {
display: grid;
place-items: center;
@@ -356,6 +407,19 @@
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.channel-member-muted"],
[data-ws-plugin-part="harbor-workspace.member-muted-state"] {
color: var(--skin-harbor-danger);
font-size: 8px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.channel-member-away"],
[data-ws-plugin-part="harbor-workspace.member-away-state"] {
color: var(--skin-harbor-dim);
font-size: 8px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.conversation"] {
grid-column: 3;
grid-row: 2;
@@ -406,6 +470,71 @@
border-color: transparent;
}
[data-ws-plugin-part="harbor-workspace.chat"] {
display: grid;
grid-template-rows: minmax(0, 1fr) auto;
min-width: 0;
min-height: 0;
overflow: hidden;
color: var(--skin-harbor-text);
}
[data-ws-plugin-part="harbor-workspace.chat-message-list"] {
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 14px;
min-height: 0;
overflow: auto;
padding: 8px 4px 16px;
}
[data-ws-plugin-part="harbor-workspace.chat-empty"] {
align-self: center;
margin: auto;
color: var(--skin-harbor-muted);
font-size: 13px;
}
[data-ws-plugin-part="harbor-workspace.chat-message"] { min-width: 0; }
[data-ws-plugin-part="harbor-workspace.chat-message-heading"] { display: flex; align-items: baseline; gap: 8px; }
[data-ws-plugin-part="harbor-workspace.chat-message-author"] { color: var(--skin-harbor-text); font-size: 12px; }
[data-ws-plugin-part="harbor-workspace.chat-message-time"] { color: var(--skin-harbor-dim); font-size: 10px; }
[data-ws-plugin-part="harbor-workspace.chat-message-text"] { margin: 3px 0 0; color: var(--skin-harbor-muted); font-size: 13px; overflow-wrap: anywhere; white-space: pre-wrap; }
[data-ws-plugin-part="harbor-workspace.chat-composer"] {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
padding: 8px;
border: 1px solid var(--skin-harbor-border);
border-radius: 9px;
background: var(--skin-harbor-panel);
}
[data-ws-plugin-part="harbor-workspace.chat-input"] {
flex: 1;
min-width: 0;
height: 38px;
padding: 0 10px;
border: 0;
outline: 0;
color: var(--skin-harbor-text);
background: transparent;
}
[data-ws-plugin-part="harbor-workspace.chat-send"] {
min-width: 54px;
min-height: 36px;
border: 0;
border-radius: 7px;
color: #111;
background: var(--skin-harbor-accent);
font-weight: 700;
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace"] .chat-panel { min-height: 0; background: transparent; }
[data-ws-plugin-part="harbor-workspace"] .chat-heading { border-color: var(--skin-harbor-border); }
[data-ws-plugin-part="harbor-workspace"] .message-bubble { color: var(--skin-harbor-text); background: var(--skin-harbor-panel); }
@@ -484,13 +613,17 @@
letter-spacing: .05em;
}
[data-ws-plugin-part="harbor-workspace.member-muted-state"],
[data-ws-plugin-part="harbor-workspace.member-away-state"],
[data-ws-plugin-part="harbor-workspace.speaking-indicator"] { grid-column: 2 / -1; }
[data-ws-plugin-part="harbor-workspace.voice-dock"] {
z-index: 4;
grid-column: 2;
grid-row: 2;
align-self: end;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-columns: minmax(0, 1fr);
gap: 6px 8px;
min-width: 0;
padding: 9px;
@@ -508,6 +641,15 @@
gap: 2px 7px;
}
[data-ws-plugin-part="harbor-workspace.voice-dock-actions"] {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
min-width: 0;
}
[data-ws-plugin-part="harbor-workspace.connection-indicator"] {
grid-row: span 2;
color: var(--skin-harbor-accent);
@@ -528,7 +670,55 @@
letter-spacing: .05em;
}
[data-ws-plugin-part="harbor-workspace"] [data-ws-part="voice.audio-controls"] { min-width: 0; }
[data-ws-plugin-part="harbor-workspace.audio-controls"] {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
}
[data-ws-plugin-part="harbor-workspace.microphone-control"],
[data-ws-plugin-part="harbor-workspace.output-control"],
[data-ws-plugin-part="harbor-workspace.disconnect-control"],
[data-ws-plugin-part="harbor-workspace.whisper-start"],
[data-ws-plugin-part="harbor-workspace.whisper-stop"] {
min-width: 38px;
min-height: 38px;
padding: 0 8px;
border: 1px solid var(--skin-harbor-border);
border-radius: 7px;
color: var(--skin-harbor-muted);
background: var(--skin-harbor-raised);
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.microphone-control"][aria-pressed="true"],
[data-ws-plugin-part="harbor-workspace.output-control"][aria-pressed="true"] { color: var(--skin-harbor-danger); }
[data-ws-plugin-part="harbor-workspace.disconnect-control"] { color: var(--skin-harbor-danger); }
[data-ws-plugin-part="harbor-workspace.output-volume"] { width: 72px; accent-color: var(--skin-harbor-accent); }
[data-ws-plugin-part="harbor-workspace.whisper-controls"] { display: flex; gap: 6px; margin-top: 12px; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] { flex: 0 0 auto; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button {
display: grid;
place-items: center;
width: 34px;
height: 34px;
padding: 0;
border: 1px solid var(--skin-harbor-border);
border-radius: 7px;
color: var(--skin-harbor-muted);
background: var(--skin-harbor-raised);
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button:hover:not(:disabled),
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button:focus-visible { color: var(--skin-harbor-accent); }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button:disabled { opacity: .45; cursor: not-allowed; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button span {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace"] .desktop-audio-dock {
min-width: 0;
margin: 0;
@@ -543,6 +733,7 @@
[data-ws-plugin-part="harbor-workspace"] .dock-audio-button { width: 34px; height: 34px; color: var(--skin-harbor-muted); }
[data-ws-plugin-part="harbor-workspace"] .dock-audio-button:hover,
[data-ws-plugin-part="harbor-workspace"] .dock-audio-button:focus-visible { color: var(--skin-harbor-accent); background: var(--skin-harbor-raised); border-color: var(--skin-harbor-border); }
[data-ws-plugin-part="harbor-workspace.audio-controls"] .accompaniment-toggle { display: none; }
[data-ws-plugin-part="harbor-workspace.disconnect-control"] {
display: grid;
@@ -591,6 +782,7 @@
[data-ws-plugin-part="harbor-workspace.server-rail"] { grid-column: 1; grid-row: 2 / 6; padding: 8px 3px; }
[data-ws-plugin-part="harbor-workspace.quick-server"] { width: 48px; min-height: 48px; }
[data-ws-plugin-part="harbor-workspace.server-monogram"] { width: 36px; height: 36px; }
[data-ws-plugin-part="harbor-workspace.identity-monogram"] { width: 34px; height: 34px; }
[data-ws-plugin-part="harbor-workspace.channel-panel"] {
grid-column: 2;
@@ -625,6 +817,7 @@
}
[data-ws-plugin-part="harbor-workspace.channel-item"] { flex: 0 0 auto; }
[data-ws-plugin-part="harbor-workspace.channel-row"] { width: max-content; min-width: 116px; min-height: 42px; margin: 0; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth] { padding-inline-start: 9px; }
[data-ws-plugin-part="harbor-workspace.channel-voice-members"] { display: none; }
[data-ws-plugin-part="harbor-workspace.conversation"] {
@@ -660,6 +853,8 @@
[data-ws-plugin-part="harbor-workspace.member-row"] { flex: 0 0 auto; grid-template-columns: 28px auto; min-height: 38px; padding: 2px 4px; }
[data-ws-plugin-part="harbor-workspace.member-avatar"] { width: 26px; height: 26px; }
[data-ws-plugin-part="harbor-workspace.speaking-indicator"] { display: none; }
[data-ws-plugin-part="harbor-workspace.member-muted-state"],
[data-ws-plugin-part="harbor-workspace.member-away-state"] { display: none; }
[data-ws-plugin-part="harbor-workspace.voice-dock"] {
grid-column: 2;
@@ -675,17 +870,23 @@
border-bottom: 0;
}
[data-ws-plugin-part="harbor-workspace.voice-dock-heading"] { grid-column: auto; grid-row: auto; }
[data-ws-plugin-part="harbor-workspace.voice-dock-actions"] { grid-column: 2; grid-row: 1; justify-content: flex-end; gap: 3px; }
[data-ws-plugin-part="harbor-workspace.voice-dock-caption"] { display: none; }
[data-ws-plugin-part="harbor-workspace.disconnect-control"] { grid-column: 2; grid-row: 1; }
[data-ws-plugin-part="harbor-workspace"] .mobile-voice-controls { gap: 5px; min-width: 0; }
[data-ws-plugin-part="harbor-workspace"] .mobile-voice-toggle { min-width: 44px; min-height: 44px; color: var(--skin-harbor-text); background: var(--skin-harbor-raised); }
[data-ws-plugin-part="harbor-workspace"] .ws-plugin-disconnect-control { width: 42px; height: 44px; }
[data-ws-plugin-part="harbor-workspace.audio-controls"] .mobile-voice-controls { display: flex; gap: 4px; }
[data-ws-plugin-part="harbor-workspace.audio-controls"] .mobile-voice-toggle { min-width: 44px; min-height: 44px; border-radius: 7px; color: var(--skin-harbor-muted); background: var(--skin-harbor-raised); }
[data-ws-plugin-part="harbor-workspace.microphone-control"],
[data-ws-plugin-part="harbor-workspace.output-control"],
[data-ws-plugin-part="harbor-workspace.disconnect-control"] { min-width: 42px; min-height: 44px; }
[data-ws-plugin-part="harbor-workspace.output-volume"] { width: 58px; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button { width: 42px; height: 44px; }
}
@media (max-width: 460px) {
[data-ws-plugin-part="harbor-workspace"] { grid-template-columns: 50px minmax(0, 1fr); }
[data-ws-plugin-part="harbor-workspace.server-rail"] { padding-inline: 1px; }
[data-ws-plugin-part="harbor-workspace.quick-server"] { width: 44px; }
[data-ws-plugin-part="harbor-workspace.identity-name"] { max-width: 43px; }
[data-ws-plugin-part="harbor-workspace.topbar"] { padding-inline: 5px; }
[data-ws-plugin-part="harbor-workspace.brand-name"] { display: none; }
[data-ws-plugin-part="harbor-workspace.server-title"] { max-width: 100px; }
+2 -1
View File
@@ -11,8 +11,9 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/skin-registry.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 src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.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/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-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-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-plugin-runtime.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-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/src/services/identity-import.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",
"test": "node --import tsx --test src/admin/skin-registry.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 src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.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/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-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-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-plugin-runtime.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-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/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",
"verify": "npm test && npm run build && npm run web:build",
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "npm --prefix web run build",
+28
View File
@@ -229,6 +229,34 @@ test("server validates v4 plugin manifests and package files without executing a
assert.equal(saved.id, "sample-skin");
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
const layout = {
schemaVersion: 1,
pages: { voice: { desktop: { "skin.voice.runtime_plugin_root_voice-toolbar": { order: 2, visible: true } } } },
};
const archiveWithLayout = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifestV4, layout: "layout.json" }))],
["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
["plugins/voice-toolbar/index.js", Buffer.from("export const render = () => document.createElement('button');")],
["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")],
["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])],
["layout.json", Buffer.from(JSON.stringify(layout))],
]);
const layoutSaved = await registry.save(archiveWithLayout, "sample-skin");
assert.equal(layoutSaved.id, "sample-skin");
assert.deepEqual(await registry.readArchive("sample-skin"), archiveWithLayout);
const invalidLayoutArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifestV4, layout: "layout.json" }))],
["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
["plugins/voice-toolbar/index.js", Buffer.from("export {}; ")],
["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")],
["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])],
["layout.json", Buffer.from(JSON.stringify({ schemaVersion: 1, pages: { voice: { desktop: { "voice.not-registered": { order: 2 } } } } }))],
]);
await assert.rejects(registry.save(invalidLayoutArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_LAYOUT_INVALID");
const wasmPlugins = {
schemaVersion: 1,
plugins: [{
+1 -1
View File
@@ -463,7 +463,7 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
const entry = read("entry", 120);
const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max);
const layout = schemaVersion === 2 ? read("layout", 120) : schemaVersion === 3 && value.layout != null ? read("layout", 120) : undefined;
const layout = schemaVersion === 2 ? read("layout", 120) : schemaVersion >= 3 ? readOptional("layout", 120) : undefined;
const content = readOptional("content", 120);
const components = schemaVersion >= 3 && value.components != null ? read("components", 120) : undefined;
const plugins = schemaVersion === 4 ? read("plugins", 120) : undefined;
+15 -3
View File
@@ -1,7 +1,7 @@
import {
SKIN_PLUGIN_PERMISSIONS,
SKIN_PLUGIN_HOST_WIDGETS,
SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS,
missingSkinPluginWidgetPermission,
parseSkinPluginRuntimeAction,
SKIN_PLUGIN_NODE_LIMIT,
SKIN_PLUGIN_TREE_DEPTH_LIMIT,
@@ -52,6 +52,12 @@ function assertLocalUiNode(node: SkinPluginNode): void {
node.children?.forEach(assertLocalUiNode);
}
function rejectExtensionHostWidgets(node: unknown): void {
if (!isRecord(node)) return;
if (node.widget !== undefined) fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "Extension UI output cannot embed privileged host widgets.");
if (Array.isArray(node.children)) node.children.forEach(rejectExtensionHostWidgets);
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
@@ -95,8 +101,8 @@ function generatedNode(
}
if (page !== "voice") fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "The screen-share host widget is available only on the voice page.");
const widget = input.widget as SkinPluginHostWidget;
const requiredPermission = SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[widget];
if (requiredPermission && !permissions.includes(requiredPermission)) {
const requiredPermission = missingSkinPluginWidgetPermission(widget, permissions);
if (requiredPermission) {
fail("SKIN_EXTENSION_UI_PERMISSION_MISSING", `The ${widget} widget requires ${requiredPermission}.`);
}
onlyKeys(input, ["widget", "part", "className"], "A generated host widget node");
@@ -275,6 +281,12 @@ export function parseSkinExtensionUiOutput(
return document;
}
if (input.schemaVersion === 3 && Array.isArray(input.components)) {
for (const rawComponent of input.components) {
if (isRecord(rawComponent)) rejectExtensionHostWidgets(rawComponent.root);
}
}
let document: SkinPluginDocument;
try { document = parseSkinPluginDocument(input); }
catch { fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Extension UI output does not match the safe component schema."); }
+228
View File
@@ -0,0 +1,228 @@
import {
SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS,
parseSkinPluginDocument,
type SkinPluginComponent,
type SkinPluginDocument,
type SkinPluginNode,
} from "./skin-plugin.js";
/** Normalize an older declarative package before editing while preserving its validated data. */
export function editableSkinPluginDocument(input: unknown): SkinPluginDocument {
const parsed = parseSkinPluginDocument(input);
if (parsed.schemaVersion === 3) return parsed;
const components = parsed.components.map((component) => {
const permissions = new Set(component.permissions);
const visit = (node: SkinPluginNode) => {
if (node.widget) SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[node.widget]?.forEach((permission) => permissions.add(permission));
node.children?.forEach(visit);
};
visit(component.root);
return { ...component, permissions: [...permissions] };
});
return parseSkinPluginDocument({ schemaVersion: 3, components });
}
export function assertSkinPluginAuthoringDocument(input: unknown): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const visit = (node: SkinPluginNode) => {
const reserved = Object.keys(node.attributes ?? {}).find((key) => key.startsWith("data-ws-"));
if (reserved) throw new Error("The " + reserved + " attribute is owned by WebSpeak and cannot be authored by a skin.");
node.children?.forEach(visit);
};
document.components.forEach((component) => visit(component.root));
return document;
}
function checked(input: unknown): SkinPluginDocument {
return editableSkinPluginDocument(input);
}
function componentIndex(document: SkinPluginDocument, id: string): number {
const index = document.components.findIndex((component) => component.id === id);
if (index < 0) throw new Error("The skin component no longer exists.");
return index;
}
function parentNode(component: SkinPluginComponent, path: readonly number[]): SkinPluginNode {
if (!path.length) return component.root;
let current = component.root;
for (const index of path) {
const child = current.children?.[index];
if (!child) throw new Error("The selected node no longer exists.");
current = child;
}
return current;
}
function nodeAt(component: SkinPluginComponent, path: readonly number[]): SkinPluginNode {
return parentNode(component, path);
}
function assertChildIndex(index: number, length: number): void {
if (!Number.isInteger(index) || index < 0 || index >= length) throw new Error("The selected node no longer exists.");
}
function updateTree(
input: SkinPluginDocument,
componentId: string,
update: (component: SkinPluginComponent) => SkinPluginComponent,
): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const index = componentIndex(document, componentId);
const components = [...document.components];
components[index] = update(components[index]);
return checked({ schemaVersion: 3, components });
}
export function addSkinPluginComponent(input: SkinPluginDocument, component: unknown): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
return checked({ schemaVersion: 3, components: [...document.components, component] });
}
export function replaceSkinPluginComponent(input: SkinPluginDocument, componentId: string, component: unknown): SkinPluginDocument {
return updateTree(input, componentId, () => component as SkinPluginComponent);
}
export function removeSkinPluginComponent(input: SkinPluginDocument, componentId: string): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
componentIndex(document, componentId);
return checked({ schemaVersion: 3, components: document.components.filter((component) => component.id !== componentId) });
}
export function moveSkinPluginComponent(
input: SkinPluginDocument,
componentId: string,
direction: -1 | 1,
): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const from = componentIndex(document, componentId);
const to = from + direction;
if (to < 0 || to >= document.components.length) return document;
const components = [...document.components];
[components[from], components[to]] = [components[to], components[from]];
return checked({ schemaVersion: 3, components });
}
export function addSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
parentPath: readonly number[],
node: unknown,
): SkinPluginDocument {
return updateTree(input, componentId, (component) => {
const parent = nodeAt(component, parentPath);
if (!parent.tag) throw new Error("Only element nodes can contain children.");
const children = [...(parent.children ?? []), node as SkinPluginNode];
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function addSkinPluginNodeSibling(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
node: unknown,
): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot have siblings.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
if (!parent.tag) throw new Error("Only element nodes can contain children.");
const index = path[path.length - 1];
const children = [...(parent.children ?? [])];
assertChildIndex(index, children.length);
children.splice(index + 1, 0, node as SkinPluginNode);
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function replaceSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
node: unknown,
): SkinPluginDocument {
return updateTree(input, componentId, (component) => ({
...component,
root: replaceNodeAtPath(component.root, path, node as SkinPluginNode),
}));
}
export function removeSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot be removed; delete the component instead.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
const index = path[path.length - 1];
const children = [...(parent.children ?? [])];
assertChildIndex(index, children.length);
children.splice(index, 1);
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function moveSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
direction: -1 | 1,
): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot be reordered.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
const children = [...(parent.children ?? [])];
const from = path[path.length - 1];
const to = from + direction;
assertChildIndex(from, children.length);
if (from < 0 || from >= children.length || to < 0 || to >= children.length) return component;
[children[from], children[to]] = [children[to], children[from]];
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function replaceNodeAtPath(root: SkinPluginNode, path: readonly number[], replacement: SkinPluginNode): SkinPluginNode {
if (!path.length) return replacement;
const [index, ...rest] = path;
const children = [...(root.children ?? [])];
assertChildIndex(index, children.length);
children[index] = replaceNodeAtPath(children[index], rest, replacement);
return { ...root, children };
}
export function getSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginNode {
const document = editableSkinPluginDocument(input);
return nodeAt(document.components[componentIndex(document, componentId)], path);
}
/** Give a duplicated subtree fresh stable layout parts so it cannot alias its source nodes. */
export function duplicateSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginNode {
const document = editableSkinPluginDocument(input);
const component = document.components[componentIndex(document, componentId)];
const source = nodeAt(component, path);
const usedParts = new Set<string>();
const exclude = (node: SkinPluginNode, currentPath: readonly number[]): void => {
if (currentPath.length === path.length && currentPath.every((index, position) => index === path[position])) return;
if (node.part) usedParts.add(node.part);
node.children?.forEach((child, index) => exclude(child, [...currentPath, index]));
};
exclude(component.root, []);
const copy = JSON.parse(JSON.stringify(source)) as SkinPluginNode;
const refreshParts = (node: SkinPluginNode): void => {
if (node.part) {
const stem = node.part.slice(0, 54) + "-copy";
let candidate = stem;
let suffix = 2;
while (usedParts.has(candidate)) {
const tail = "-" + suffix++;
candidate = stem.slice(0, 64 - tail.length) + tail;
}
node.part = candidate;
usedParts.add(candidate);
}
node.children?.forEach(refreshParts);
};
refreshParts(copy);
return copy;
}
+63 -2
View File
@@ -144,6 +144,25 @@ test("starting screen share from a skin host widget requires its own permission"
assert.equal(parsed.components[0].root.children?.[0].widget, "voice.screen-share-start");
});
test("schema v3 host audio controls require read and control permissions while v2 remains compatible", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].root = { tag: "main", children: [{ widget: "voice.audio-controls" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["audio.status.read", "audio.microphone.control"];
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["audio.status.read", "audio.microphone.control", "audio.output.control"];
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].widget, "voice.audio-controls");
const legacyDocument = structuredClone(document);
legacyDocument.schemaVersion = 2;
legacyDocument.components[0].permissions = [];
assert.equal(parseSkinPluginDocument(legacyDocument).components[0].root.children?.[0].widget, "voice.audio-controls");
});
test("KAAK v3 example splits validated channel and member data by component", async () => {
const source = await readFile(new URL("../../docs/examples/kaak-voice/components.json", import.meta.url), "utf8");
const parsed = parseSkinPluginJson(source);
@@ -229,10 +248,52 @@ test("skin plugins can repeat channel members only under a channel alias and wit
errorCode(() => parseSkinPluginDocument(outsideChannel), "SKIN_PLUGIN_REPEAT_INVALID");
});
test("skin plugin never dispatches host actions from typing or selection changes", () => {
test("skin plugins keep live typing local but can run host actions on committed changes", () => {
const document = validDocument();
document.components[0].root.children![0].events = { change: "join" };
const input = document.components[0].root.children![0];
input.events = { input: "join" };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_EVENT_INVALID");
input.events = { change: "join" };
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].events?.change, "join");
});
test("skin conditions can compare public repeated data with local component state", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].state = { selectedchannel: "" };
document.components[0].root.children![0].when = {
path: "state.selectedchannel",
equals: "{{channel.id}}",
};
const parsed = parseSkinPluginDocument(document);
assert.deepEqual(parsed.components[0].root.children?.[0].when, {
path: "state.selectedchannel",
equals: "{{channel.id}}",
});
const legacyDocument = structuredClone(document);
legacyDocument.schemaVersion = 2;
errorCode(() => parseSkinPluginDocument(legacyDocument), "SKIN_PLUGIN_SCHEMA_UNSUPPORTED");
document.components[0].root.children![0].when!.equals = "{{channel.address}}";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_BINDING_INVALID");
});
test("schema v3 can render empty states only for permissioned public collections", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions.push("chat.channel.read");
document.components[0].root.children = [{
tag: "p",
when: { path: "chat.messages", empty: true },
children: [{ text: "No messages yet" }],
}];
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].when?.empty, true);
document.components[0].permissions.push("session.status.read");
document.components[0].root.children[0].when!.path = "session.status.serverLabel";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_CONDITION_INVALID");
});
test("component schema v3 exposes composable interaction patterns and permission-gated voice actions", () => {
+40 -10
View File
@@ -55,9 +55,23 @@ export const SKIN_PLUGIN_HOST_WIDGETS = Object.freeze([
"voice.disconnect-control",
] as const);
export type SkinPluginHostWidget = typeof SKIN_PLUGIN_HOST_WIDGETS[number];
export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostWidget, SkinPluginPermission>> = Object.freeze({
"voice.screen-share-start": "voice.screenShare.control",
const widgetPermissions = (...permissions: SkinPluginPermission[]): readonly SkinPluginPermission[] => Object.freeze(permissions);
export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostWidget, readonly SkinPluginPermission[]>> = Object.freeze({
"voice.audio-controls": widgetPermissions("audio.status.read", "audio.microphone.control", "audio.output.control"),
"voice.chat-panel": widgetPermissions("chat.channel.read", "chat.channel.send"),
"voice.connection-controls": widgetPermissions("voice.disconnect"),
"voice.disconnect-control": widgetPermissions("voice.disconnect"),
"voice.member-cards": widgetPermissions("session.members.read", "voice.screenShare.read", "voice.screenShare.control"),
"voice.screen-share-player": widgetPermissions("voice.screenShare.read", "voice.screenShare.control"),
"voice.screen-share-start": widgetPermissions("voice.screenShare.control"),
"voice.whisper-controls": widgetPermissions("voice.whisper.status.read", "voice.whisper.control"),
});
export function missingSkinPluginWidgetPermission(
widget: SkinPluginHostWidget,
permissions: readonly SkinPluginPermission[],
): SkinPluginPermission | undefined {
return SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[widget]?.find((permission) => !permissions.includes(permission));
}
export type SkinPluginEvent =
| "click" | "dblclick" | "change" | "input" | "submit" | "keydown"
| "keyup" | "contextmenu" | "focus" | "blur" | "pointerdown" | "pointerup"
@@ -84,7 +98,7 @@ export interface SkinPluginNode {
asset?: string;
bindValue?: string;
repeat?: { path: string; as: string };
when?: { path: string; equals?: string | number | boolean };
when?: { path: string; equals?: string | number | boolean; empty?: boolean };
events?: Partial<Record<SkinPluginEvent, string>>;
children?: SkinPluginNode[];
}
@@ -130,7 +144,7 @@ const ELEMENTS = new Set([
const VOID_ELEMENTS = new Set(["br", "circle", "hr", "img", "input", "line", "path", "polyline", "rect", "wbr"]);
const ATTRIBUTES = new Set([
"alt", "aria-current", "aria-expanded", "aria-hidden", "aria-label", "aria-pressed", "aria-selected", "autocomplete", "checked", "class", "colspan", "disabled", "draggable", "fill", "height", "inputmode", "max", "maxlength", "min",
"minlength", "multiple", "name", "open", "placeholder", "required", "role", "rows", "rowspan", "stroke", "stroke-linecap", "stroke-linejoin",
"minlength", "multiple", "name", "open", "placeholder", "required", "role", "rows", "rowspan", "step", "stroke", "stroke-linecap", "stroke-linejoin",
"stroke-width", "tabindex", "title", "type", "value", "viewbox", "width", "x", "x1", "x2", "y", "y1", "y2",
]);
const EVENTS = new Set<string>([
@@ -274,7 +288,8 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
if (!isRecord(input)) fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json must contain an object.");
onlyKeys(input, new Set(["schemaVersion", "components"]), "components.json");
if (!SKIN_PLUGIN_SUPPORTED_SCHEMA_VERSIONS.includes(input.schemaVersion as 1 | 2 | 3) || !Array.isArray(input.components)
|| !input.components.length || input.components.length > (input.schemaVersion === 3 ? SKIN_PLUGIN_COMPONENT_LIMIT : 32)) {
|| (input.schemaVersion !== 3 && !input.components.length)
|| input.components.length > (input.schemaVersion === 3 ? SKIN_PLUGIN_COMPONENT_LIMIT : 32)) {
fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json uses an unsupported schema or component count.");
}
const ids = new Set<string>();
@@ -366,8 +381,12 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
if (rawNode.widget !== undefined) {
if (typeof rawNode.widget !== "string" || !HOST_WIDGETS.has(rawNode.widget)) fail("SKIN_PLUGIN_WIDGET_INVALID", "The component requests an unsupported host widget.");
if (page === "demo") fail("SKIN_PLUGIN_WIDGET_INVALID", "Host widgets are available only on the home and voice client pages.");
const requiredPermission = SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[rawNode.widget as SkinPluginHostWidget];
if (requiredPermission && !permissions.includes(requiredPermission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The ${rawNode.widget} widget requires ${requiredPermission}.`);
// Preserve existing schema v2 packages; newly authored v3 widgets must declare every
// permission needed by the trusted host UI they embed. Screen-share start was already gated.
const requiredPermission = inputSchemaVersion >= 3 || rawNode.widget === "voice.screen-share-start"
? missingSkinPluginWidgetPermission(rawNode.widget as SkinPluginHostWidget, permissions)
: undefined;
if (requiredPermission) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The ${rawNode.widget} widget requires ${requiredPermission}.`);
const widgetOnlyKeys = new Set(["widget", "part", "className", "when"]);
onlyKeys(rawNode, widgetOnlyKeys, "Host widget node");
node.widget = rawNode.widget as SkinPluginHostWidget;
@@ -436,14 +455,25 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
}
if (rawNode.when !== undefined) {
if (!isRecord(rawNode.when)) fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition must be an object.");
onlyKeys(rawNode.when, new Set(["path", "equals"]), "Component condition");
onlyKeys(rawNode.when, new Set(inputSchemaVersion >= 3 ? ["path", "equals", "empty"] : ["path", "equals"]), "Component condition");
const path = boundedText(rawNode.when.path, "condition.path", 120);
for (const permission of bindingPermissions(`{{${path}}}`, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The condition data requires ${permission}.`);
}
const equals = rawNode.when.equals;
if (equals !== undefined && typeof equals !== "string" && typeof equals !== "number" && typeof equals !== "boolean") fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition comparison must be scalar.");
node.when = { path, ...(equals === undefined ? {} : { equals }) };
const empty = rawNode.when.empty;
if (empty !== undefined && (inputSchemaVersion < 3 || typeof empty !== "boolean" || equals !== undefined)) fail("SKIN_PLUGIN_CONDITION_INVALID", "An empty-collection condition must be a schema v3 boolean and cannot also compare a scalar.");
if (typeof equals === "string") {
if (inputSchemaVersion < 3 && equals.includes("{{")) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Data-bound condition comparisons require schema v3.");
for (const permission of bindingPermissions(equals, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The condition comparison data requires ${permission}.`);
}
}
if (empty !== undefined && !["chat.messages", "session.channels", "session.members", "favorites.items", "servers.quickList", "screenShare.streams"].includes(path)) {
fail("SKIN_PLUGIN_CONDITION_INVALID", "An empty condition must reference a registered public collection.");
}
node.when = { path, ...(equals === undefined ? {} : { equals }), ...(empty === undefined ? {} : { empty }) };
}
if (rawNode.events !== undefined) {
if (!isRecord(rawNode.events) || Object.keys(rawNode.events).length > (inputSchemaVersion >= 3 ? 18 : 6)) fail("SKIN_PLUGIN_EVENT_INVALID", "Component events must be a small object.");
@@ -451,7 +481,7 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
for (const [event, actionIdValue] of Object.entries(rawNode.events)) {
if (!EVENTS.has(event) || (inputSchemaVersion < 3 && V3_EVENTS.has(event)) || typeof actionIdValue !== "string" || !actions[actionIdValue]) fail("SKIN_PLUGIN_EVENT_INVALID", "Each component event must refer to a declared host action supported by this schema.");
const action = actions[actionIdValue];
if (action.type !== "ui.setState" && (event === "input" || event === "change")) fail("SKIN_PLUGIN_EVENT_INVALID", "Host actions cannot run while a form value is being typed or changed.");
if (action.type !== "ui.setState" && event === "input") fail("SKIN_PLUGIN_EVENT_INVALID", "Host actions cannot run while a form value is being typed; use a committed change or submit event.");
if (action.type !== "ui.setState" && action.type !== "ui.toggleState" && PASSIVE_EVENTS.has(event)) {
fail("SKIN_PLUGIN_EVENT_INVALID", "Voice and host actions require an explicit user activation event.");
}
+12
View File
@@ -0,0 +1,12 @@
import { readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { zipSync } from "fflate";
const sourceDirectory = new URL("../../docs/examples/harbor-voice/", import.meta.url);
const outputPath = fileURLToPath(new URL("../../docs/examples/harbor-voice.wskin", import.meta.url));
const files = Object.fromEntries(await Promise.all(["manifest.json", "components.json", "skin.css"].map(async (name) => [
name,
await readFile(new URL(name, sourceDirectory)),
])));
await writeFile(outputPath, zipSync(files, { level: 9 }));
+512
View File
@@ -0,0 +1,512 @@
<template>
<div v-if="skinId" class="skin-plugin-editor" data-ws-plugin-editor>
<button ref="triggerButton" class="skin-plugin-trigger" type="button" aria-controls="skin-plugin-panel" :aria-expanded="open" @click="open = !open" @keydown.esc.stop.prevent="open = false">
{{ english ? "Components" : "组件结构" }}
</button>
<section v-if="open" id="skin-plugin-panel" class="skin-plugin-panel" role="dialog" aria-modal="false" tabindex="-1" :aria-label="english ? 'Skin component editor' : '皮肤组件编辑器'" @keydown.esc.stop.prevent="open = false">
<header class="skin-plugin-heading">
<div>
<h2>{{ english ? "Skin components" : "皮肤组件" }}</h2>
<p>{{ english ? "Edits are local to this skin version and use the same permission and markup checks as packages." : "修改保存在本机当前皮肤版本中,并继续使用皮肤包相同的权限和标记校验。" }}</p>
</div>
<button ref="closeButton" type="button" class="skin-plugin-close" :aria-label="english ? 'Close' : '关闭'" @click="open = false">×</button>
</header>
<div class="skin-plugin-actions">
<button type="button" :disabled="draftDirty || storageInvalid" @click="createComponent">{{ english ? "Add component" : "新增组件" }}</button>
<button type="button" :disabled="!canUndo || draftDirty || storageInvalid" @click="undo">{{ english ? "Undo" : "撤销" }}</button>
<button type="button" :disabled="!canRedo || draftDirty || storageInvalid" @click="redo">{{ english ? "Redo" : "重做" }}</button>
</div>
<label class="skin-plugin-label">
<span>{{ english ? "Components" : "组件列表" }}</span>
<select :value="selectedComponentId" :disabled="draftDirty || storageInvalid" @change="selectComponent(($event.target as HTMLSelectElement).value)">
<option value="">{{ english ? "Select a component" : "选择组件" }}</option>
<option v-for="component in document.components" :key="component.id" :value="component.id">{{ component.name }} · {{ component.page }} · {{ component.id }}</option>
</select>
</label>
<p v-if="!selectedComponent" class="skin-plugin-empty">{{ english ? "No skin components yet. Add one to begin." : "当前皮肤还没有自定义组件,可以从新增组件开始。" }}</p>
<template v-if="selectedComponent">
<div class="skin-plugin-actions">
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(-1)" :aria-label="english ? 'Move component up' : '组件上移'" @click="moveComponent(-1)">↑</button>
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(1)" :aria-label="english ? 'Move component down' : '组件下移'" @click="moveComponent(1)">↓</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="duplicateComponent">{{ english ? "Duplicate component" : "复制组件" }}</button>
<button type="button" class="is-danger" :disabled="draftDirty || storageInvalid" @click="deleteComponent">{{ english ? "Delete component" : "删除组件" }}</button>
</div>
<label class="skin-plugin-label">
<span>{{ english ? "Component tree" : "组件树" }}</span>
<select :value="selectedPathKey" :disabled="draftDirty || storageInvalid" @change="selectPath(($event.target as HTMLSelectElement).value)">
<option v-for="row in nodeRows" :key="row.key" :value="row.key" :style="{ paddingInlineStart: (row.depth * 12) + 'px' }">{{ row.label }}</option>
</select>
</label>
<div class="skin-plugin-actions">
<button type="button" :disabled="!canAddChild || draftDirty || storageInvalid" @click="addChild">{{ english ? "Add child" : "添加子节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="addSibling">{{ english ? "Add sibling" : "添加同级节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="duplicateNode">{{ english ? "Duplicate node" : "复制节点" }}</button>
<button type="button" :disabled="!selectedPath.length || !canMove(-1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node up' : '节点上移'" @click="moveNode(-1)">↑</button>
<button type="button" :disabled="!selectedPath.length || !canMove(1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node down' : '节点下移'" @click="moveNode(1)">↓</button>
<button type="button" class="is-danger" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="deleteNode">{{ english ? "Delete node" : "删除节点" }}</button>
</div>
<label class="skin-plugin-label skin-plugin-json-label">
<span>{{ editorTarget === "component" ? (english ? "Component definition" : "组件定义") : (english ? "Node definition" : "节点定义") }}</span>
<small>{{ english ? "JSON edits are validated before they are saved or rendered." : "JSON 修改会先经过 schema、权限和安全校验,再保存和渲染。" }}</small>
<textarea v-model="draftJson" :disabled="storageInvalid" spellcheck="false" :aria-label="english ? 'Component or node JSON' : '组件或节点 JSON'"></textarea>
</label>
<div class="skin-plugin-actions">
<button type="button" class="is-primary" :disabled="storageInvalid" @click="applyDraft">{{ english ? "Apply definition" : "应用定义" }}</button>
<button type="button" @click="resetDraft">{{ english ? "Discard draft" : "放弃草稿" }}</button>
</div>
</template>
<div class="skin-plugin-actions skin-plugin-file-actions">
<button type="button" @click="exportDocument">{{ english ? "Export components.json" : "导出 components.json" }}</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="importInput?.click()">{{ english ? "Import components.json" : "导入 components.json" }}</button>
<button type="button" :disabled="!hasLocalEdits || draftDirty" @click="resetAll">{{ english ? "Reset local edits" : "清除本地修改" }}</button>
<input ref="importInput" class="skin-plugin-file" type="file" accept="application/json,.json" @change="importDocument" />
</div>
<p v-if="errorMessage" class="skin-plugin-error" role="alert">{{ errorMessage }}</p>
<p v-else-if="draftDirty" class="skin-plugin-status" role="status">{{ english ? "Unapplied draft. Apply it or discard it before other edits." : "有尚未应用的草稿;请先应用或放弃,再进行其他修改。" }}</p>
<p v-else-if="statusMessage" class="skin-plugin-status" role="status">{{ statusMessage }}</p>
<p class="skin-plugin-context">{{ skinId }}@{{ skinVersion }}</p>
</section>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import {
addSkinPluginComponent,
addSkinPluginNode,
addSkinPluginNodeSibling,
editableSkinPluginDocument,
getSkinPluginNode,
moveSkinPluginComponent as movePluginComponent,
moveSkinPluginNode as movePluginNode,
duplicateSkinPluginNode,
removeSkinPluginComponent,
removeSkinPluginNode,
replaceSkinPluginComponent,
replaceSkinPluginNode,
} from "../../../src/shared/skin-plugin-editor.js";
import type { SkinPluginComponent, SkinPluginDocument, SkinPluginNode } from "../../../src/shared/skin-plugin.js";
import {
clearSkinPluginAuthoringDocument,
exportSkinPluginAuthoringDocument,
hasSkinPluginAuthoringDocument,
importSkinPluginAuthoringDocument,
loadSkinPluginAuthoringDocument,
saveSkinPluginAuthoringDocument,
} from "../services/skin-plugin-authoring.js";
const props = defineProps<{
skinId: string;
skinVersion: string;
baseDocument?: SkinPluginDocument;
page: "home" | "voice" | "demo";
lang?: string;
}>();
const emit = defineEmits<{ updated: [] }>();
type NodeRow = { key: string; label: string; depth: number };
const emptyDocument: SkinPluginDocument = { schemaVersion: 3, components: [] };
const voidNodeTags = new Set(["br", "circle", "hr", "img", "input", "line", "path", "polyline", "rect", "wbr"]);
const svgContainerTags = new Set(["svg", "g"]);
const open = ref(false);
const document = ref<SkinPluginDocument>(emptyDocument);
const selectedComponentId = ref("");
const selectedPath = ref<number[]>([]);
const editorTarget = ref<"component" | "node">("component");
const draftJson = ref("");
const errorMessage = ref("");
const statusMessage = ref("");
const importInput = ref<HTMLInputElement | null>(null);
const triggerButton = ref<HTMLButtonElement | null>(null);
const closeButton = ref<HTMLButtonElement | null>(null);
const history = ref<SkinPluginDocument[]>([]);
const historyIndex = ref(-1);
const editRevision = ref(0);
const storageInvalid = ref(false);
const english = computed(() => (props.lang ?? "").toLowerCase().startsWith("en"));
const selectedComponent = computed(() => document.value.components.find((component) => component.id === selectedComponentId.value) ?? null);
const selectedNode = computed(() => selectedComponent.value ? getSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value) : null);
const canAddChild = computed(() => Boolean(selectedNode.value?.tag && !voidNodeTags.has(selectedNode.value.tag)));
const selectedPathKey = computed(() => selectedPath.value.join("."));
const canUndo = computed(() => historyIndex.value > 0);
const canRedo = computed(() => historyIndex.value >= 0 && historyIndex.value < history.value.length - 1);
const canMoveComponent = (direction: -1 | 1) => {
const index = document.value.components.findIndex((component) => component.id === selectedComponentId.value);
return index >= 0 && index + direction >= 0 && index + direction < document.value.components.length;
};
const hasLocalEdits = computed(() => { editRevision.value; return hasSkinPluginAuthoringDocument(props.skinId, props.skinVersion); });
const draftDirty = computed(() => {
const current = editorTarget.value === "component" ? selectedComponent.value : selectedNode.value;
return Boolean(current && draftJson.value !== JSON.stringify(current, null, 2));
});
const nodeRows = computed<NodeRow[]>(() => {
const component = selectedComponent.value;
if (!component) return [];
const rows: NodeRow[] = [];
const visit = (node: SkinPluginNode, path: number[], depth: number) => {
const name = node.widget ? "widget: " + node.widget : node.tag ? "<" + node.tag + ">" : "text: " + (node.text ?? "").slice(0, 42);
const label = (path.length ? path.map((index) => index + 1).join(".") : "root") + " · " + name;
rows.push({ key: path.join("."), label, depth });
node.children?.forEach((child, index) => visit(child, [...path, index], depth + 1));
};
visit(component.root, [], 0);
return rows;
});
function activeBase(): SkinPluginDocument {
return editableSkinPluginDocument(props.baseDocument ?? emptyDocument);
}
function loadDocument(): void {
try {
const hasStoredDocument = hasSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
const savedDocument = loadSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
storageInvalid.value = hasStoredDocument && !savedDocument;
document.value = savedDocument ?? activeBase();
selectedPath.value = [];
editorTarget.value = "component";
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) {
selectedComponentId.value = document.value.components[0]?.id ?? "";
}
history.value = [document.value];
historyIndex.value = 0;
resetDraft();
errorMessage.value = storageInvalid.value
? (english.value ? "Saved edits are invalid. Clear this skin version's local edits to restore its package." : "本地修改无法通过校验。清除当前皮肤版本的本地修改即可恢复皮肤包。")
: "";
} catch (error) {
document.value = activeBase();
errorMessage.value = message(error);
}
}
function message(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function snapshot<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
function save(next: unknown): boolean {
try {
if (storageInvalid.value) throw new Error(english.value ? "Clear the invalid local edits before saving." : "请先清除无效的本地修改,再保存。");
const normalized = editableSkinPluginDocument(next);
saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, normalized);
const nextHistory = history.value.slice(0, historyIndex.value + 1);
nextHistory.push(snapshot(normalized));
history.value = nextHistory.slice(-50);
historyIndex.value = history.value.length - 1;
editRevision.value += 1;
document.value = normalized;
if (!normalized.components.some((component) => component.id === selectedComponentId.value)) {
selectedComponentId.value = normalized.components[0]?.id ?? "";
selectedPath.value = [];
}
if (editorTarget.value === "node" && selectedComponent.value) {
try { getSkinPluginNode(normalized, selectedComponentId.value, selectedPath.value); }
catch { selectedPath.value = []; editorTarget.value = "component"; }
}
statusMessage.value = english.value ? "Saved on this device." : "已保存到本机。";
errorMessage.value = "";
resetDraft();
emit("updated");
return true;
} catch (error) {
errorMessage.value = message(error);
statusMessage.value = "";
return false;
}
}
function selectComponent(id: string): void {
selectedComponentId.value = id;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
}
function selectPath(key: string): void {
selectedPath.value = key ? key.split(".").map(Number) : [];
editorTarget.value = "node";
resetDraft();
}
function resetDraft(): void {
const component = selectedComponent.value;
if (!component) { draftJson.value = ""; return; }
const current = editorTarget.value === "component" ? component : selectedNode.value;
draftJson.value = current ? JSON.stringify(current, null, 2) : "";
}
function applyDraft(): void {
try {
const parsed: unknown = JSON.parse(draftJson.value);
if (editorTarget.value === "component") {
const next = replaceSkinPluginComponent(document.value, selectedComponentId.value, parsed);
const nextComponent = (parsed as SkinPluginComponent).id;
if (save(next)) {
selectedComponentId.value = nextComponent;
selectedPath.value = [];
resetDraft();
}
} else {
const next = replaceSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value, parsed);
save(next);
}
} catch (error) { errorMessage.value = message(error); statusMessage.value = ""; }
}
function createComponent(): void {
const baseId = "custom-component";
const ids = new Set(document.value.components.map((component) => component.id));
let suffix = 1;
while (ids.has(baseId + "-" + suffix)) suffix += 1;
const id = baseId + "-" + suffix;
const component: SkinPluginComponent = {
id,
name: english.value ? "Custom component" : "自定义组件",
page: props.page === "demo" ? "home" : props.page,
accessibleName: english.value ? "Custom component" : "自定义组件",
permissions: [],
actions: {},
root: { tag: "section", children: [{ text: english.value ? "New component" : "新建组件" }] },
};
try {
if (!save(addSkinPluginComponent(document.value, component))) return;
selectedComponentId.value = id;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function duplicateComponent(): void {
const source = selectedComponent.value;
if (!source) return;
const stem = source.id.slice(0, 56);
let suffix = 2;
let id = stem + "-" + suffix;
const ids = new Set(document.value.components.map((component) => component.id));
while (ids.has(id)) id = stem + "-" + (++suffix);
const copy = { ...snapshot(source), id, name: source.name.slice(0, 72) + (english.value ? " copy" : " 副本"), accessibleName: source.accessibleName.slice(0, 108) + (english.value ? " copy" : " 副本") };
try {
if (!save(addSkinPluginComponent(document.value, copy))) return;
selectedComponentId.value = id;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function deleteComponent(): void {
if (!selectedComponentId.value) return;
try {
if (!save(removeSkinPluginComponent(document.value, selectedComponentId.value))) return;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
}
catch (error) { errorMessage.value = message(error); }
}
function moveComponent(direction: -1 | 1): void {
if (!selectedComponentId.value || !canMoveComponent(direction)) return;
try { save(movePluginComponent(document.value, selectedComponentId.value, direction)); }
catch (error) { errorMessage.value = message(error); }
}
function addChild(): void {
if (!selectedNode.value?.tag || voidNodeTags.has(selectedNode.value.tag)) return;
const parent = selectedPath.value;
const childIndex = selectedNode.value.children?.length ?? 0;
const tag = svgContainerTags.has(selectedNode.value.tag) ? "g" : "div";
try {
const next = addSkinPluginNode(document.value, selectedComponentId.value, parent, { tag, children: [{ text: english.value ? "New content" : "新建内容" }] });
if (!save(next)) return;
selectedPath.value = [...parent, childIndex];
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function addSibling(): void {
if (!selectedPath.value.length) return;
const path = [...selectedPath.value];
const parent = getSkinPluginNode(document.value, selectedComponentId.value, path.slice(0, -1));
const tag = parent.tag && svgContainerTags.has(parent.tag) ? "g" : "span";
try {
const next = addSkinPluginNodeSibling(document.value, selectedComponentId.value, path, { tag, children: [{ text: english.value ? "New content" : "新建内容" }] });
if (!save(next)) return;
path[path.length - 1] += 1;
selectedPath.value = path;
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function duplicateNode(): void {
if (!selectedPath.value.length || !selectedNode.value) return;
const path = [...selectedPath.value];
const copy = duplicateSkinPluginNode(document.value, selectedComponentId.value, path);
try {
const next = addSkinPluginNodeSibling(document.value, selectedComponentId.value, path, copy);
if (!save(next)) return;
path[path.length - 1] += 1;
selectedPath.value = path;
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function deleteNode(): void {
if (!selectedPath.value.length) return;
try {
const next = removeSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value);
if (!save(next)) return;
selectedPath.value = selectedPath.value.slice(0, -1);
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function canMove(direction: -1 | 1): boolean {
if (!selectedPath.value.length) return false;
const index = selectedPath.value[selectedPath.value.length - 1];
const parent = getSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value.slice(0, -1));
return index + direction >= 0 && index + direction < (parent.children?.length ?? 0);
}
function moveNode(direction: -1 | 1): void {
try {
const next = movePluginNode(document.value, selectedComponentId.value, selectedPath.value, direction);
if (!save(next)) return;
const path = [...selectedPath.value];
path[path.length - 1] += direction;
selectedPath.value = path;
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function undo(): void {
if (!canUndo.value) return;
historyIndex.value -= 1;
const value = history.value[historyIndex.value];
try {
document.value = saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, value);
editRevision.value += 1;
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) selectedComponentId.value = document.value.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
statusMessage.value = english.value ? "Change undone." : "已撤销。";
resetDraft();
emit("updated");
} catch (error) { historyIndex.value += 1; errorMessage.value = message(error); }
}
function redo(): void {
if (!canRedo.value) return;
historyIndex.value += 1;
const value = history.value[historyIndex.value];
try {
document.value = saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, value);
editRevision.value += 1;
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) selectedComponentId.value = document.value.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
statusMessage.value = english.value ? "Change redone." : "已重做。";
resetDraft();
emit("updated");
} catch (error) { historyIndex.value -= 1; errorMessage.value = message(error); }
}
function resetAll(): void {
try {
clearSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
storageInvalid.value = false;
editRevision.value += 1;
document.value = activeBase();
selectedComponentId.value = document.value.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
history.value = [document.value];
historyIndex.value = 0;
resetDraft();
errorMessage.value = "";
statusMessage.value = english.value ? "Local edits cleared." : "本地修改已清除。";
emit("updated");
} catch (error) { errorMessage.value = message(error); }
}
function download(source: string, filename: string): void {
const url = URL.createObjectURL(new Blob([source], { type: "application/json" }));
const anchor = window.document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.click();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
}
function exportDocument(): void {
try { download(exportSkinPluginAuthoringDocument(document.value), props.skinId + "-components.json"); }
catch (error) { errorMessage.value = message(error); }
}
async function importDocument(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
if (!file) return;
try {
if (file.size > 256 * 1024) throw new Error("components.json exceeds the 256 KiB limit.");
const imported = importSkinPluginAuthoringDocument(await file.text());
if (!save(imported)) return;
selectedComponentId.value = imported.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
} catch (error) { errorMessage.value = message(error); statusMessage.value = ""; }
}
watch(() => [props.skinId, props.skinVersion, props.baseDocument] as const, loadDocument, { immediate: true });
watch(() => [selectedComponentId.value, selectedPathKey.value, editorTarget.value] as const, resetDraft);
watch(open, async (isOpen) => {
await nextTick();
const target = isOpen ? closeButton.value : triggerButton.value;
target?.focus?.();
});
</script>
<style scoped>
.skin-plugin-editor { position: fixed; z-index: 2147482998; right: 14px; bottom: 72px; color: #172033; font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif; }
.skin-plugin-editor button, .skin-plugin-editor select, .skin-plugin-editor textarea { font: inherit; }
.skin-plugin-trigger { min-height: 44px; padding: 0 14px; border: 1px solid #cbd5e1; border-radius: 999px; color: #fff; background: #4f46e5; box-shadow: 0 5px 22px #0f172a55; cursor: pointer; }
.skin-plugin-panel { position: absolute; right: 0; bottom: 50px; display: grid; gap: 10px; width: min(460px, calc(100vw - 24px)); max-height: min(82vh, 820px); overflow: auto; padding: 14px; border: 1px solid #cbd5e1; border-radius: 15px; background: #fff; box-shadow: 0 18px 60px #0f172a44; }
.skin-plugin-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
.skin-plugin-heading h2 { margin: 0; font-size: 16px; }
.skin-plugin-heading p { margin: 5px 0 0; color: #475569; font-size: 11px; }
.skin-plugin-close { width: 44px; height: 44px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 21px !important; cursor: pointer; }
.skin-plugin-actions { display: flex; flex-wrap: wrap; gap: 6px; }
.skin-plugin-actions button { min-height: 44px; padding: 0 9px; border: 1px solid #cbd5e1; border-radius: 7px; color: #172033; background: #f8fafc; cursor: pointer; }
.skin-plugin-actions button:disabled { opacity: .45; cursor: not-allowed; }
.skin-plugin-actions .is-primary { color: #fff; border-color: #4338ca; background: #4f46e5; }
.skin-plugin-actions .is-danger { color: #991b1b; border-color: #fecaca; background: #fef2f2; }
.skin-plugin-label { display: grid; gap: 5px; color: #475569; font-size: 12px; }
.skin-plugin-label select { width: 100%; min-height: 44px; padding: 5px 8px; border: 1px solid #cbd5e1; border-radius: 7px; color: #172033; background: #fff; }
.skin-plugin-json-label small { color: #64748b; }
.skin-plugin-json-label textarea { width: 100%; min-height: 230px; resize: vertical; padding: 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; font: 12px/1.45 ui-monospace, SFMono-Regular, Consolas, monospace; tab-size: 2; }
.skin-plugin-file { display: none; }
.skin-plugin-error, .skin-plugin-status, .skin-plugin-context { margin: 0; overflow-wrap: anywhere; }
.skin-plugin-error { color: #b91c1c; }
.skin-plugin-status { color: #4338ca; }
.skin-plugin-context { color: #64748b; font-size: 10px; }
.skin-plugin-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
@media (max-width: 520px) { .skin-plugin-editor { right: 10px; bottom: 62px; } .skin-plugin-panel { max-height: 76vh; } }
</style>
+11 -2
View File
@@ -230,7 +230,10 @@ export default defineComponent({
if (node.widget) {
if (node.when) {
const value = resolvePath(node.when.path, context, state);
if (node.when.equals !== undefined ? value !== node.when.equals : !value) return null;
const expected = typeof node.when.equals === "string" ? interpolate(node.when.equals, context, state) : node.when.equals;
if (node.when.empty !== undefined) {
if (!Array.isArray(value) || (value.length === 0) !== node.when.empty) return null;
} else if (expected !== undefined ? value !== expected : !value) return null;
}
const widget = props.widgets[node.widget];
if (!widget) return null;
@@ -258,10 +261,16 @@ export default defineComponent({
}
if (node.when) {
const value = resolvePath(node.when.path, context, state);
if (node.when.equals !== undefined ? value !== node.when.equals : !value) return null;
const expected = typeof node.when.equals === "string" ? interpolate(node.when.equals, context, state) : node.when.equals;
if (node.when.empty !== undefined) {
if (!Array.isArray(value) || (value.length === 0) !== node.when.empty) return null;
} else if (expected !== undefined ? value !== expected : !value) return null;
}
const attrs: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node.attributes ?? {})) {
// data-ws-* belongs to host layout, page, and recovery machinery. Older
// packages remain loadable, but their nodes cannot impersonate host hooks.
if (key.startsWith("data-ws-")) continue;
attrs[svgAttributeNames[key] ?? key] = typeof value === "string" ? interpolate(value, context, state) : value;
}
if (node.asset) {
+31 -1
View File
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { createRenderer, createSSRApp, nextTick } from "vue";
import { renderToString } from "@vue/server-renderer";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { approveSkinPluginComponents } from "./skin-plugin-approval.js";
import {
parseSkinExtensionUiActionRequest,
@@ -556,3 +556,33 @@ test("skin-authored DOM nodes expose independent layout parts and retain touch b
assert.match(html, /data-ws-part="skin\.voice\.voice-toolbar\.control-part-disconnect"/);
assert.match(html, /data-ws-part="skin\.voice\.voice-toolbar\.part-caption"/);
});
test("skin nodes cannot impersonate WebSpeak page and layout hooks", async () => {
const document = parseSkinPluginDocument({
schemaVersion: 3,
components: [{
id: "hook-test",
name: "Hook test",
page: "voice",
accessibleName: "Hook test",
permissions: [],
actions: {},
root: {
tag: "section",
children: [{ tag: "div", attributes: { "data-ws-page": "admin", "data-ws-layout-hidden": true, "data-testid": "safe" } }],
},
}],
});
const html = await renderToString(createSSRApp(SkinPluginOutlet, {
skinId: "community.test",
skinVersion: "1.0.0",
document,
page: "voice",
data: {},
assets: {},
actions: {},
}));
assert.match(html, /data-testid="safe"/);
assert.doesNotMatch(html, /data-ws-page="admin"/);
assert.doesNotMatch(html, /data-ws-layout-hidden=/);
});
+37 -3
View File
@@ -375,7 +375,11 @@ test("schema version 3 accepts a schema v2 full-page surface with host widgets",
});
test("schema version 4 validates and caches isolated plugin package files without executing them", async () => {
const skin = await importSkinPack(makeSkinV4());
const defaultLayout = {
schemaVersion: 1,
pages: { voice: { desktop: { "skin.voice.runtime_plugin_root_voice-toolbar": { order: 2, visible: true } } } },
};
const skin = await importSkinPack(makeSkinV4(undefined, { layout: defaultLayout }));
const entry = "plugins/voice-toolbar/index.js";
const style = "plugins/voice-toolbar/style.css";
const icon = "plugins/voice-toolbar/assets/icon.png";
@@ -389,6 +393,7 @@ test("schema version 4 validates and caches isolated plugin package files withou
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /data-ws-runtime-plugin="voice-toolbar".*?\.toolbar/s);
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /color: teal/);
assert.match(skin.css, /position: fixed/);
assert.deepEqual(skin.layoutData?.pages.voice?.desktop?.["skin.voice.runtime_plugin_root_voice-toolbar"], { order: 2, visible: true });
await assert.rejects(
importSkinPack(makeSkinV4(undefined, { includeEntry: false })),
@@ -526,6 +531,11 @@ test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspac
assert.ok(voiceSurface?.permissions.includes("session.channel.join"));
assert.ok(voiceSurface?.permissions.includes("servers.quickList.switch"));
assert.ok(voiceSurface?.permissions.includes("session.members.read"));
assert.ok(voiceSurface?.permissions.includes("chat.channel.read"));
assert.ok(voiceSurface?.permissions.includes("chat.channel.send"));
assert.ok(voiceSurface?.permissions.includes("audio.microphone.control"));
assert.ok(voiceSurface?.permissions.includes("audio.output.control"));
assert.ok(voiceSurface?.permissions.includes("voice.screenShare.control"));
function findPart(node: SkinPluginNode | undefined, part: string): SkinPluginNode | undefined {
if (!node) return undefined;
if (node.part === part) return node;
@@ -536,11 +546,34 @@ test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspac
return undefined;
}
const channelRow = findPart(voiceSurface?.root, "channel-row");
assert.equal(channelRow?.events?.click, "select-channel", "single-click only selects a channel in this skin");
assert.equal(channelRow?.events?.dblclick, "join-channel", "channel switching follows TeamSpeak's double-click join behavior");
assert.equal(channelRow?.attributes?.["data-depth"], "{{channel.depth}}", "the channel hierarchy is represented without a new host API");
assert.equal(findPart(channelRow, "selected-channel-indicator")?.when?.equals, "{{channel.id}}");
const identityEntry = findPart(voiceSurface?.root, "identity-entry");
assert.equal(identityEntry?.attributes?.role, "group");
assert.equal(identityEntry?.when?.path, "session.status.userName");
assert.equal(findPart(identityEntry, "identity-name")?.children?.[0]?.text, "{{session.status.userName}}");
const channelVoiceMembers = findPart(voiceSurface?.root, "channel-voice-members");
assert.equal(channelVoiceMembers?.when?.path, "channel.current");
assert.equal(findPart(channelVoiceMembers, "channel-voice-member")?.repeat?.path, "channel.members");
assert.equal(findPart(channelVoiceMembers, "channel-member-muted")?.when?.path, "voicemember.status");
assert.equal(findPart(voiceSurface?.root, "member-away-state")?.when?.path, "member.status");
const voiceDockActions = findPart(voiceSurface?.root, "voice-dock-actions");
assert.equal(findPart(voiceDockActions, "screen-share-start")?.widget, "voice.screen-share-start");
assert.equal(findPart(voiceDockActions, "audio-controls")?.widget, "voice.audio-controls");
assert.equal(findPart(voiceDockActions, "disconnect-control")?.events?.click, "disconnect");
const chat = findPart(voiceSurface?.root, "chat");
assert.equal(findPart(chat, "chat-message")?.repeat?.path, "chat.messages");
assert.equal(findPart(chat, "chat-composer")?.events?.submit, "send-message");
assert.equal(findPart(chat, "chat-input")?.bindValue, "message");
assert.equal(findPart(chat, "chat-empty")?.when?.empty, true);
assert.equal(findPart(voiceSurface?.root, "whisper-start")?.events?.click, "whisper-on");
assert.ok(skin.css.includes("@media (max-width: 820px)"));
assert.ok(skin.css.includes('[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="1"]'));
assert.ok(skin.css.includes('[data-ws-plugin-part="harbor-workspace.identity-entry"]'));
assert.ok(skin.css.includes('data-ws-plugin-part="harbor-workspace.screen-share-start"'), "the host screen-share control uses the stable plugin part hook");
assert.ok(skin.css.includes(".accompaniment-toggle { display: none; }"));
assert.ok(!skin.css.includes("https://"), "the skin uses no remote artwork or font resources");
});
@@ -588,12 +621,13 @@ function makeSkinV4(
permissions: ["session.channels.read"],
}],
},
options: { includeEntry?: boolean; entryBytes?: Uint8Array; entryPath?: string; extra?: Record<string, Uint8Array> } = {},
options: { includeEntry?: boolean; entryBytes?: Uint8Array; entryPath?: string; layout?: unknown; extra?: Record<string, Uint8Array> } = {},
): File {
const packageFiles: Record<string, Uint8Array> = {
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", plugins: "plugins.json" })),
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", plugins: "plugins.json", ...(options.layout ? { layout: "layout.json" } : {}) })),
"skin.css": strToU8('[data-ws-part="app"] { position: fixed; color: teal; }'),
"plugins.json": strToU8(JSON.stringify(pluginDocument)),
...(options.layout ? { "layout.json": strToU8(JSON.stringify(options.layout)) } : {}),
"plugins/voice-toolbar/style.css": strToU8(".toolbar { color: teal; }"),
"plugins/voice-toolbar/assets/icon.png": new Uint8Array([1, 2, 3, 4]),
...options.extra,
@@ -0,0 +1,208 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
addSkinPluginComponent,
addSkinPluginNode,
addSkinPluginNodeSibling,
duplicateSkinPluginNode,
editableSkinPluginDocument,
getSkinPluginNode,
moveSkinPluginComponent,
moveSkinPluginNode,
removeSkinPluginComponent,
removeSkinPluginNode,
replaceSkinPluginNode,
} from "../../../src/shared/skin-plugin-editor.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
clearSkinPluginAuthoringDocument,
exportSkinPluginAuthoringDocument,
getSkinPluginAuthoringStorageKey,
hasSkinPluginAuthoringDocument,
importSkinPluginAuthoringDocument,
loadSkinPluginAuthoringDocument,
saveSkinPluginAuthoringDocument,
SKIN_PLUGIN_AUTHORING_STORAGE_KEY,
} from "./skin-plugin-authoring.js";
class MemoryStorage {
private readonly values = new Map<string, string>();
failWrites = false;
getItem(key: string): string | null { return this.values.get(key) ?? null; }
setItem(key: string, value: string): void {
if (this.failWrites) throw new Error("quota exceeded");
this.values.set(key, value);
}
removeItem(key: string): void { this.values.delete(key); }
}
function withLocalStorage<T>(run: (storage: MemoryStorage) => T): T {
const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const storage = new MemoryStorage();
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
try { return run(storage); }
finally {
if (previous) Object.defineProperty(globalThis, "localStorage", previous);
else Reflect.deleteProperty(globalThis, "localStorage");
}
}
function document(): SkinPluginDocument {
return {
schemaVersion: 3,
components: [{
id: "voice-panel",
name: "Voice panel",
page: "voice",
accessibleName: "Voice panel",
permissions: [],
actions: {},
root: { tag: "section", children: [{ tag: "p", children: [{ text: "Original" }] }, { tag: "button", attributes: { type: "button" } }] },
}],
};
}
test("component document editor supports add, update, reorder, delete, and an empty v3 document", () => {
const source = document();
const first = addSkinPluginNode(source, "voice-panel", [], { tag: "div", children: [{ text: "Added" }] });
assert.equal(getSkinPluginNode(first, "voice-panel", [2]).tag, "div");
assert.equal(source.components[0].root.children?.length, 2, "editing leaves the source tree unchanged");
const second = addSkinPluginNodeSibling(first, "voice-panel", [2], { tag: "small", children: [{ text: "Sibling" }] });
assert.equal(getSkinPluginNode(second, "voice-panel", [3]).tag, "small");
const reordered = moveSkinPluginNode(second, "voice-panel", [3], -1);
assert.equal(getSkinPluginNode(reordered, "voice-panel", [2]).tag, "small");
const updated = replaceSkinPluginNode(reordered, "voice-panel", [2, 0], { text: "Changed" });
assert.equal(getSkinPluginNode(updated, "voice-panel", [2, 0]).text, "Changed");
const withoutNode = removeSkinPluginNode(updated, "voice-panel", [2]);
assert.equal(withoutNode.components[0].root.children?.length, 3);
const withSecondComponent = addSkinPluginComponent(withoutNode, {
id: "extra-panel", name: "Extra panel", page: "voice", accessibleName: "Extra panel",
permissions: [], actions: {}, root: { tag: "aside" },
});
assert.equal(withSecondComponent.components.length, 2);
assert.equal(removeSkinPluginComponent(withSecondComponent, "voice-panel").components.length, 1);
assert.deepEqual(removeSkinPluginComponent(withSecondComponent, "voice-panel").components.map(({ id }) => id), ["extra-panel"]);
assert.deepEqual(removeSkinPluginComponent(document(), "voice-panel"), { schemaVersion: 3, components: [] });
});
test("component order is editable and stays within the selected skin document", () => {
const source = addSkinPluginComponent(document(), {
id: "second-panel", name: "Second panel", page: "voice", accessibleName: "Second panel",
permissions: [], actions: {}, root: { tag: "aside" },
});
const moved = moveSkinPluginComponent(source, "voice-panel", 1);
assert.deepEqual(moved.components.map((component) => component.id), ["second-panel", "voice-panel"]);
assert.deepEqual(moveSkinPluginComponent(moved, "voice-panel", 1), moved, "moving past the end is a no-op");
assert.deepEqual(source.components.map((component) => component.id), ["voice-panel", "second-panel"]);
});
test("duplicating a nested component node gives copied layout parts unique stable IDs", () => {
const source = document();
source.components[0].root.children![0] = {
tag: "div", part: "message", children: [{ tag: "span", part: "author", text: "Author" }],
};
const copy = duplicateSkinPluginNode(source, "voice-panel", [0]);
assert.equal(copy.part, "message-copy");
assert.equal(copy.children?.[0].part, "author-copy");
assert.throws(() => duplicateSkinPluginNode(source, "voice-panel", []), /root cannot be duplicated/i);
});
test("component editor rejects unsafe markup and invalid permission/action combinations", () => {
assert.throws(() => addSkinPluginNode(document(), "voice-panel", [], { tag: "script" }), /unsupported HTML element/i);
assert.throws(() => replaceSkinPluginNode(document(), "voice-panel", [0], {
tag: "button", events: { click: "disconnect" },
}), /refer to a declared host action/i);
assert.throws(() => addSkinPluginComponent(document(), {
id: "unsafe", name: "Unsafe", page: "voice", accessibleName: "Unsafe",
permissions: [], actions: { disconnect: { type: "voice.disconnect", args: {} } },
root: { tag: "button", events: { click: "disconnect" } },
}), /requires voice.disconnect/i);
assert.throws(() => removeSkinPluginNode(document(), "voice-panel", []), /root cannot be removed/i);
assert.throws(() => moveSkinPluginNode(document(), "voice-panel", [1.5], -1), /no longer exists/i);
});
test("older package trees upgrade to editable schema v3 without losing their component", () => {
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
const editable = editableSkinPluginDocument(legacy);
assert.equal(editable.schemaVersion, 3);
assert.equal(editable.components[0].root.tag, "section");
const legacyWithWidget = structuredClone(legacy);
legacyWithWidget.components[0].permissions = [];
legacyWithWidget.components[0].root = { tag: "section", children: [{ widget: "voice.audio-controls" }] };
const migratedWidget = editableSkinPluginDocument(legacyWithWidget);
assert.deepEqual(migratedWidget.components[0].permissions, ["audio.status.read", "audio.microphone.control", "audio.output.control"]);
});
test("component authoring saves are isolated by skin version and round-trip through export/import", () => {
withLocalStorage((storage) => {
const source = addSkinPluginNode(document(), "voice-panel", [], { tag: "strong", children: [{ text: "Local edit" }] });
saveSkinPluginAuthoringDocument("community.example", "1.2.3", source);
assert.notEqual(storage.getItem(getSkinPluginAuthoringStorageKey("community.example", "1.2.3")), null);
assert.equal(storage.getItem(SKIN_PLUGIN_AUTHORING_STORAGE_KEY), null);
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.2.3"), true);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.3")?.components[0].root.children?.length, 3);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.4"), null);
const exported = exportSkinPluginAuthoringDocument(source);
assert.deepEqual(importSkinPluginAuthoringDocument(exported), source);
clearSkinPluginAuthoringDocument("community.example", "1.2.3");
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), null);
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.2.3"), false);
const empty = removeSkinPluginComponent(source, "voice-panel");
saveSkinPluginAuthoringDocument("community.example", "1.2.3", empty);
assert.deepEqual(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), { schemaVersion: 3, components: [] });
assert.deepEqual(importSkinPluginAuthoringDocument(exportSkinPluginAuthoringDocument(empty)), empty);
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
saveSkinPluginAuthoringDocument("community.example", "1.2.4", legacy);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.4")?.schemaVersion, 3);
});
});
test("invalid component files and unsafe local edits are rejected before persistence", () => {
withLocalStorage((storage) => {
assert.throws(() => importSkinPluginAuthoringDocument(JSON.stringify({
schemaVersion: 3,
components: [{
id: "broken", name: "Broken", page: "voice", accessibleName: "Broken",
permissions: [], actions: {}, root: { tag: "iframe" },
}],
})));
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1", {
schemaVersion: 3, components: [{ ...document().components[0], root: { tag: "script" } }],
}));
const reservedHook = document();
reservedHook.components[0].root.children![0].attributes = { "data-ws-page": "admin" };
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1", reservedHook), /owned by WebSpeak/i);
assert.equal(storage.getItem(getSkinPluginAuthoringStorageKey("community.example", "1")), null);
});
});
test("a local-storage write failure preserves the last saved component document", () => {
withLocalStorage((storage) => {
const saved = document();
saveSkinPluginAuthoringDocument("community.example", "1.2.3", saved);
const key = getSkinPluginAuthoringStorageKey("community.example", "1.2.3");
const rawBeforeFailure = storage.getItem(key);
const changed = addSkinPluginNode(saved, "voice-panel", [], { text: "not committed" });
storage.failWrites = true;
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1.2.3", changed), /could not save/i);
assert.equal(storage.getItem(key), rawBeforeFailure);
assert.deepEqual(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), editableSkinPluginDocument(saved));
});
});
test("corrupt authoring data stays isolated and can be cleared without touching another skin", () => {
withLocalStorage((storage) => {
const corruptKey = getSkinPluginAuthoringStorageKey("community.example", "1.0.0");
saveSkinPluginAuthoringDocument("community.other", "1.0.0", document());
storage.setItem(corruptKey, "not json");
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.0.0"), true);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.0.0"), null);
clearSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.0.0"), false);
assert.equal(loadSkinPluginAuthoringDocument("community.other", "1.0.0")?.components[0].id, "voice-panel");
});
});
+78
View File
@@ -0,0 +1,78 @@
import { parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { assertSkinPluginAuthoringDocument, editableSkinPluginDocument } from "../../../src/shared/skin-plugin-editor.js";
export const SKIN_PLUGIN_AUTHORING_STORAGE_KEY = "webspeak:skin-plugin-authoring:v1";
const MAX_DOCUMENT_BYTES = 256 * 1024;
interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
function browserStorage(): StorageLike | null {
try { return typeof localStorage === "undefined" ? null : localStorage; }
catch { return null; }
}
export function getSkinPluginAuthoringStorageKey(skinId: string, skinVersion: string): string {
if (!/^[a-z0-9](?:[a-z0-9.-]{0,78}[a-z0-9])?$/.test(skinId)
|| !skinVersion || skinVersion.length > 32 || !/^[A-Za-z0-9.+_-]+$/.test(skinVersion)) {
throw new Error("Skin identity is invalid.");
}
return SKIN_PLUGIN_AUTHORING_STORAGE_KEY + ":" + skinId + "@" + skinVersion;
}
export function hasSkinPluginAuthoringDocument(skinId: string, skinVersion: string): boolean {
let key: string;
try { key = getSkinPluginAuthoringStorageKey(skinId, skinVersion); } catch { return false; }
const storage = browserStorage();
if (!storage) return false;
try { return storage.getItem(key) !== null; } catch { return false; }
}
export function loadSkinPluginAuthoringDocument(skinId: string, skinVersion: string): SkinPluginDocument | null {
let key: string;
try { key = getSkinPluginAuthoringStorageKey(skinId, skinVersion); } catch { return null; }
const storage = browserStorage();
if (!storage) return null;
let source: string | null;
try { source = storage.getItem(key); } catch { return null; }
if (!source) return null;
if (new TextEncoder().encode(source).byteLength > MAX_DOCUMENT_BYTES) return null;
try { return editableSkinPluginDocument(parseSkinPluginJson(source)); }
catch { return null; }
}
export function saveSkinPluginAuthoringDocument(skinId: string, skinVersion: string, document: unknown): SkinPluginDocument {
const key = getSkinPluginAuthoringStorageKey(skinId, skinVersion);
const validated = assertSkinPluginAuthoringDocument(document);
const serialized = JSON.stringify(validated);
if (new TextEncoder().encode(serialized).byteLength > MAX_DOCUMENT_BYTES) throw new Error("Saved component edits exceed the 256 KiB document limit.");
const storage = browserStorage();
if (!storage) throw new Error("Local browser storage is unavailable.");
try { storage.setItem(key, serialized); }
catch { throw new Error("Local browser storage could not save the component edits."); }
return validated;
}
export function clearSkinPluginAuthoringDocument(skinId: string, skinVersion: string): void {
const key = getSkinPluginAuthoringStorageKey(skinId, skinVersion);
const storage = browserStorage();
if (!storage) throw new Error("Local browser storage is unavailable.");
try { storage.removeItem(key); }
catch { throw new Error("Local browser storage could not clear the component edits."); }
}
export function importSkinPluginAuthoringDocument(source: string): SkinPluginDocument {
return assertSkinPluginAuthoringDocument(parseSkinPluginJson(source));
}
export function exportSkinPluginAuthoringDocument(document: unknown): string {
const validated = assertSkinPluginAuthoringDocument(document);
const readable = JSON.stringify(validated, null, 2);
if (new TextEncoder().encode(readable).byteLength <= MAX_DOCUMENT_BYTES) return readable;
const compact = JSON.stringify(validated);
if (new TextEncoder().encode(compact).byteLength > MAX_DOCUMENT_BYTES) throw new Error("components.json exceeds the 256 KiB document limit.");
return compact;
}
+27 -4
View File
@@ -12,10 +12,10 @@
:data-ws-page="showVoiceShell ? 'voice' : 'home'"
>
<SkinPluginOutlet
v-if="activeSkin?.pluginData"
v-if="activeSkin"
:skin-id="activeSkin.id"
:skin-version="activeSkin.version"
:document="activeSkin.pluginData"
:document="skinPluginDocument"
:page="showVoiceShell ? 'voice' : 'home'"
:data="skinPluginContext"
:assets="activeSkin.assets"
@@ -24,6 +24,15 @@
@surface-change="skinPluginSurfaceActive = $event"
@restore-skin="switchToBuiltIn"
/>
<SkinPluginEditor
v-if="activeSkin"
:skin-id="activeSkin.id"
:skin-version="activeSkin.version"
:base-document="activeSkin.pluginData"
:page="showVoiceShell ? 'voice' : 'home'"
:lang="language"
@updated="skinPluginDocumentRevision += 1"
/>
<SkinRuntimePluginHost
v-if="activeSkin?.runtimePlugins"
:skin-id="activeSkin.id"
@@ -966,6 +975,7 @@ import { observeMobileViewport } from "../services/mobile-viewport.js";
import { computed, h, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from "vue";
import Icon from "../components/Icon.vue";
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
import SkinPluginEditor from "../components/SkinPluginEditor.vue";
import SkinRuntimePluginHost from "../components/SkinRuntimePluginHost.js";
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
import VoiceMemberCards from "../components/web-client/VoiceMemberCards.vue";
@@ -1009,6 +1019,8 @@ import { applyTheme, getStoredTheme, type ThemeMode } from "../services/theme.js
import { createScreenWakeLockController, getScreenWakeLockApi, type ScreenWakeLockController, type ScreenWakeLockSnapshot } from "../services/screen-wake-lock.js";
import { createMobileAwayController, type MobileAwayController } from "../services/mobile-away.js";
import { createSkinPluginQuickServerProjection } from "../services/skin-plugin-context.js";
import { loadSkinPluginAuthoringDocument } from "../services/skin-plugin-authoring.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { combineTeamSpeakTarget, DEFAULT_TEAM_SPEAK_PORT, isValidTeamSpeakPort, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
const {
@@ -1133,6 +1145,14 @@ let toastTimer: ReturnType<typeof setTimeout> | undefined;
const language = ref<Language>(getInitialLanguage());
const activeSkin = shallowRef<InstalledSkin | null>(null);
const skinPluginDocumentRevision = ref(0);
const emptySkinPluginDocument: SkinPluginDocument = { schemaVersion: 3, components: [] };
const skinPluginDocument = computed<SkinPluginDocument>(() => {
skinPluginDocumentRevision.value;
const skin = activeSkin.value;
if (!skin) return emptySkinPluginDocument;
return loadSkinPluginAuthoringDocument(skin.id, skin.version) ?? skin.pluginData ?? emptySkinPluginDocument;
});
const skinPluginSurfaceActive = ref(false);
const skinRuntimePluginSurfaceActive = ref(false);
watch(activeSkin, () => {
@@ -1614,8 +1634,11 @@ const skinPluginActions = {
"voice.toggleMicrophone": () => { if (voiceState.connected) toggleMicrophone(); },
"voice.toggleOutputMute": () => { if (voiceState.connected) toggleOutputMute(); },
"voice.setOutputVolume": (args: Record<string, string | number | boolean>) => {
if (!voiceState.connected || typeof args.volume !== "number" || !Number.isFinite(args.volume)) return;
setOutputVolume(Math.max(0, Math.min(1, args.volume)));
if (!voiceState.connected) return;
const volume = typeof args.volume === "number" ? args.volume
: typeof args.volume === "string" && args.volume.trim() ? Number(args.volume) : Number.NaN;
if (!Number.isFinite(volume)) return;
setOutputVolume(Math.max(0, Math.min(1, volume)));
},
"voice.disconnect": () => { if (voiceState.connected || voiceState.connecting) doDisconnect(); },
"voice.setAway": (args: Record<string, string | number | boolean>) => {
+283
View File
@@ -0,0 +1,283 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { after, before, test } from "node:test";
import { fileURLToPath } from "node:url";
import * as Vue from "vue";
import { createRenderer, nextTick, ssrContextKey, createSSRApp } from "vue";
import { renderToString } from "@vue/server-renderer";
import { createServer } from "vite";
import vuePlugin from "@vitejs/plugin-vue";
let vite;
let SkinPluginEditor;
let authoring;
const localStorageDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
class MemoryStorage {
values = new Map();
getItem(key) { return this.values.get(key) ?? null; }
setItem(key, value) { this.values.set(key, value); }
removeItem(key) { this.values.delete(key); }
}
const hostNode = (tag, type = "element") => ({
tag, type, props: {}, text: "", children: [], parent: null, value: "", listeners: new Map(), focus() {},
addEventListener(name, listener) {
const listeners = this.listeners.get(name) ?? [];
listeners.push(listener);
this.listeners.set(name, listeners);
},
removeEventListener(name, listener) {
this.listeners.set(name, (this.listeners.get(name) ?? []).filter(candidate => candidate !== listener));
},
dispatchEvent(event) { for (const listener of this.listeners.get(event.type) ?? []) listener(event); },
});
function insert(child, parent, anchor = null) {
if (child.parent) {
const previous = child.parent.children.indexOf(child);
if (previous >= 0) child.parent.children.splice(previous, 1);
}
const index = anchor ? parent.children.indexOf(anchor) : -1;
child.parent = parent;
if (index < 0) parent.children.push(child);
else parent.children.splice(index, 0, child);
}
const renderer = createRenderer({
createElement: tag => hostNode(tag),
createText: text => Object.assign(hostNode("#text", "text"), { text }),
createComment: text => Object.assign(hostNode("#comment", "comment"), { text }),
setText(node, text) { node.text = text; },
setElementText(node, text) { node.children.forEach(child => { child.parent = null; }); node.children = []; node.text = text; },
patchProp(node, key, _previous, value) { node.props[key] = value; },
insert,
remove(node) {
if (!node.parent) return;
const index = node.parent.children.indexOf(node);
if (index >= 0) node.parent.children.splice(index, 1);
node.parent = null;
},
parentNode: node => node.parent,
nextSibling(node) {
if (!node.parent) return null;
return node.parent.children[node.parent.children.indexOf(node) + 1] ?? null;
},
insertStaticContent(content, parent, anchor) {
const node = Object.assign(hostNode("#static", "static"), { text: content });
insert(node, parent, anchor);
return [node, node];
},
});
const testVueRuntime = {
...Vue,
vModelText: {
created(element, binding, vnode) {
element.value = binding.value ?? "";
const assign = vnode.props?.["onUpdate:modelValue"];
if (assign) element.addEventListener("input", event => assign(event.target.value));
},
beforeUpdate(element, binding) { element.value = binding.value ?? ""; },
},
};
function visit(root, predicate) {
if (predicate(root)) return root;
for (const child of root.children) {
const found = visit(child, predicate);
if (found) return found;
}
return null;
}
function nodeText(node) {
return node.text + node.children.map(nodeText).join("");
}
function clickButton(root, label) {
const button = visit(root, node => node.tag === "button"
&& (node.props["aria-label"] === label || nodeText(node).trim() === label));
assert.ok(button, `button ${label} exists in the rendered editor; rendered text: ${nodeText(root)}`);
assert.equal(typeof button.props.onClick, "function", `button ${label} has a click handler`);
button.props.onClick({ type: "click", target: button });
}
function changeSelect(root, index, value) {
const selects = [];
const collect = node => {
if (node.tag === "select") selects.push(node);
node.children.forEach(collect);
};
collect(root);
const select = selects[index];
assert.ok(select, `select ${index} exists in the rendered editor`);
assert.equal(typeof select.props.onChange, "function");
select.props.onChange({ type: "change", target: { value } });
}
function editTextarea(root, value) {
const textarea = visit(root, node => node.tag === "textarea");
assert.ok(textarea, "JSON editor is rendered");
textarea.value = value;
textarea.dispatchEvent({ type: "input", target: textarea });
}
before(async () => {
vite = await createServer({
configFile: false,
root: fileURLToPath(new URL("../", import.meta.url)),
plugins: [vuePlugin()],
server: { middlewareMode: true, hmr: false, ws: false, watch: null },
optimizeDeps: { noDiscovery: true, include: [] },
appType: "custom",
});
({ default: SkinPluginEditor } = await vite.ssrLoadModule("/src/components/SkinPluginEditor.vue"));
const require = createRequire(import.meta.url);
const { parse, compileScript, compileTemplate } = require("../node_modules/@vue/compiler-sfc");
const filename = fileURLToPath(new URL("../src/components/SkinPluginEditor.vue", import.meta.url));
const source = readFileSync(filename, "utf8");
const { descriptor } = parse(source, { filename });
const script = compileScript(descriptor, { id: "skin-plugin-editor-test" });
const templateSource = descriptor.template.content.replaceAll("($event.target as HTMLSelectElement).value", "($event.target).value");
const template = compileTemplate({ source: templateSource, filename, id: "skin-plugin-editor-test", compilerOptions: { expressionPlugins: ["typescript"], bindingMetadata: script.bindings } });
assert.deepEqual(template.errors, [], "the editor template compiles for client rendering");
const vueImport = /^import \{([\s\S]*?)\} from "vue"\s*/.exec(template.code);
assert.ok(vueImport, "compiled template imports Vue runtime helpers");
const vueBindings = vueImport[1].split(",").map(binding => binding.trim().replace(" as ", ": ")).join(", ");
const clientRenderCode = `const { ${vueBindings} } = Vue;\n${template.code.slice(vueImport[0].length).replace("export function render", "return function render")}`;
SkinPluginEditor.render = new Function("Vue", clientRenderCode)(testVueRuntime);
authoring = await vite.ssrLoadModule("/src/services/skin-plugin-authoring.ts");
});
after(async () => {
await vite?.close();
if (localStorageDescriptor) Object.defineProperty(globalThis, "localStorage", localStorageDescriptor);
else Reflect.deleteProperty(globalThis, "localStorage");
});
test("component editor creates, changes, and deletes a skin component tree through its UI", async () => {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
const baseDocument = {
schemaVersion: 3,
components: [{
id: "base-panel",
name: "Base panel",
page: "voice",
accessibleName: "Base panel",
permissions: [],
actions: {},
root: { tag: "section", children: [{ text: "Base" }] },
}],
};
const props = {
skinId: "community.example",
skinVersion: "1.0.0",
baseDocument,
page: "voice",
lang: "zh",
};
const html = await renderToString(createSSRApp(SkinPluginEditor, props));
assert.match(html, /组件结构/);
const root = hostNode("root");
const app = renderer.createApp(SkinPluginEditor, props);
app.provide(ssrContextKey, { modules: new Set() });
app.mount(root);
try {
clickButton(root, "组件结构");
await nextTick();
assert.equal(app._instance.setupState.open, true, "the trigger opens the editor");
clickButton(root, "新增组件");
await nextTick();
const key = authoring.getSkinPluginAuthoringStorageKey("community.example", "1.0.0");
let edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components.length, 2);
assert.equal(edited.components[1].id, "custom-component-1");
clickButton(root, "组件上移");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["custom-component-1", "base-panel"]);
clickButton(root, "添加子节点");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children.length, 2);
assert.ok(localStorage.getItem(key));
changeSelect(root, 1, "0");
await nextTick();
editTextarea(root, JSON.stringify({ text: "Edited in the component editor" }, null, 2));
await nextTick();
clickButton(root, "应用定义");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children[0].text, "Edited in the component editor");
clickButton(root, "撤销");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children[0].text, "新建组件");
clickButton(root, "重做");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children[0].text, "Edited in the component editor");
clickButton(root, "删除组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["base-panel"]);
changeSelect(root, 0, "base-panel");
await nextTick();
clickButton(root, "复制组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["base-panel", "base-panel-2"]);
changeSelect(root, 0, "base-panel");
await nextTick();
changeSelect(root, 1, "0");
await nextTick();
clickButton(root, "删除组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["base-panel-2"]);
clickButton(root, "新增组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[1].id, "custom-component-1");
assert.match(nodeText(root), /组件定义/, "creating after deleting a component from node mode selects the component definition");
assert.match(visit(root, node => node.tag === "textarea").value, /"id": "custom-component-1"/);
changeSelect(root, 1, "0");
await nextTick();
const importInput = visit(root, node => node.tag === "input");
assert.ok(importInput);
const importedDocument = {
schemaVersion: 3,
components: [{
id: "imported-panel", name: "Imported panel", page: "voice", accessibleName: "Imported panel",
permissions: [], actions: {}, root: { tag: "section", children: [{ text: "Imported" }] },
}],
};
await importInput.props.onChange({ target: { files: [new File([JSON.stringify(importedDocument)], "components.json")], value: "components.json" } });
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["imported-panel"]);
assert.match(visit(root, node => node.tag === "textarea").value, /"id": "imported-panel"/,
"importing from node mode selects the imported component definition");
const panel = visit(root, node => node.tag === "section" && node.props.role === "dialog");
assert.ok(panel);
assert.equal(panel.props["aria-modal"], "false");
panel.props.onKeydown({ key: "Escape", preventDefault() {}, stopPropagation() {} });
await nextTick();
assert.equal(visit(root, node => node.tag === "section" && node.props.role === "dialog"), null,
"Escape closes the editor dialog");
} finally {
app.unmount();
}
});