Compare commits

...
8 Commits
68 changed files with 9923 additions and 3803 deletions

No files matched your search

@@ -0,0 +1,32 @@
---
name: webspeak-skin-development
description: Create, refine, package, and verify WebSpeak visual skins while preserving the product's translated content, fixed component geometry, and interactions.
---
# WebSpeak skin development
Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSIA built-in skin, or skin-facing UI hooks. A skin changes artwork and visual treatment; WebSpeak owns page structure, text, and behavior. The administrator console is deliberately outside the skin scope.
## Before editing
- Read [`docs/SKIN_DEVELOPMENT.md`](../../../docs/SKIN_DEVELOPMENT.md) for the current package validator and public hooks.
- Use [`docs/examples/illusia-voice/`](../../../docs/examples/illusia-voice/) and [`docs/examples/ILLUSIA-VOICE.md`](../../../docs/examples/ILLUSIA-VOICE.md) as the reference implementation. Do not restore the removed Aurora Voice sample.
- Inspect the actual component markup for `data-ws-page`, `data-ws-part`, and `data-ws-state` hooks. Treat Vue classes and incidental DOM structure as private.
## Preserve the interface
- Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork.
- Skin only with supported visual CSS and package-local images/fonts. The upload validator rejects layout, positioning, sizing, spacing, clipping, text-flow, and interaction-geometry changes. Do not work around it with selectors, pseudo-elements, or animation.
- Never hide or obstruct critical controls, make a card or player move/resize, change a floating menu into a modal, or make artwork intercept pointer input. Keep `/admin/**` unskinned.
- Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry.
- Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states.
- Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights.
## Verify and package
1. Compare the implementation with its visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap.
2. Check all five interface languages, day/night modes, keyboard focus, and reduced-motion behavior. Confirm the admin console is unchanged.
3. Run `npm test` and `npm --prefix web run build`. Fix validator or build failures rather than weakening the layout guardrails.
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.
The three shipped skins—default day, default night, and ILLUSIA—are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them.
+42
View File
@@ -1,5 +1,47 @@
# Changelog
## [0.2.5] — 2026-09-27(相对 0.2.4)
### 中文
- 新增 `.wskin` 视觉皮肤系统:用户可在首页、语音工作区和 `/demo` 选择外观;皮肤可更换背景、美术素材与组件视觉,但页面结构、排版空间、控件位置和交互仍由 WebSpeak 固定提供,管理后台不受皮肤影响。
- 管理员可在皮肤库启用/停用自定义皮肤并指定实例默认皮肤;访客手动选择会保留,未手动选择的访客采用实例默认。默认日间、默认夜间和 ILLUSIA 风是受保护内置皮肤,不能删除、停用或替换。
- 将完成度不足的 Aurora Voice 示例移除,以 ILLUSIA 风作为完整皮肤开发样例;细化首页装饰、语音区跨层级立绘、耳机场景、聊天空状态和屏幕播放器表现,并修复深色模式控件可读性、组件溢出和皮肤加载闪烁。
- 新增官方仓库皮肤开发 Agent Skill,配套更新开发规范与多语言功能说明;访客总数在统计暂不可用时也不会低于当前访客序号。
- 缩小 ILLUSIA 语音活动立绘并固定在容器右下角,避免遮挡成员名单和屏幕共享播放器。
### English
- Added the `.wskin` visual skin system. Visitors can choose appearances on the home page, voice workspace, and `/demo`; skins may customize artwork and component visuals while WebSpeak retains page structure, layout, control placement, and behavior. The administration console remains unskinned.
- Administrators can enable/disable custom skins and set an instance default. Deliberate visitor choices are preserved; visitors without an explicit choice receive the instance default. Default Day, Default Night, and ILLUSIA are protected built-ins that cannot be removed, disabled, or replaced.
- Removed the unfinished Aurora Voice sample and made ILLUSIA the complete reference skin. Refined homepage artwork, layered voice-room character art and headphone scene, the empty-chat backdrop, and the screen-share player; fixed dark-mode control contrast, overflow, and skin-load flashes.
- Added the repository's official skin-development Agent Skill and synchronized the guide and localized feature notes. The displayed visitor total also remains at least as high as the current visitor ordinal when the counter is unavailable.
- Reduced and anchored the ILLUSIA voice-activity artwork to the lower-right corner so it no longer obscures member cards or the screen-share player.
### Deutsch
- Das visuelle `.wskin`-System wurde ergänzt. Besucher können das Design auf der Startseite, im Sprachbereich und unter `/demo` wählen. Skins dürfen Grafiken und die visuelle Darstellung anpassen; Seitenstruktur, Layout, Positionen der Bedienelemente und Verhalten bleiben von WebSpeak vorgegeben. Die Administrationskonsole bleibt ungestaltet.
- Administratoren können eigene Skins aktivieren/deaktivieren und ein Standarddesign für die Instanz festlegen. Eine bewusst getroffene Besucherauswahl bleibt erhalten; ohne eigene Auswahl gilt der Instanzstandard. Tagesmodus, Nachtmodus und ILLUSIA sind geschützte integrierte Skins und können weder gelöscht noch deaktiviert oder ersetzt werden.
- Das unfertige Aurora-Voice-Beispiel wurde entfernt; ILLUSIA ist nun das vollständige Referenzdesign. Startseitenkunst, Ebenenillustration und Kopfhörerszene im Sprachbereich, leerer Chat-Hintergrund und Bildschirmfreigabe-Player wurden verfeinert. Außerdem wurden dunkle Bedienelemente, Überläufe und Skin-Ladeblitze korrigiert.
- Der offizielle Skin-Entwicklungs-Agent-Skill des Repositorys wurde ergänzt; Anleitung und lokalisierte Funktionsübersichten wurden aktualisiert. Die Besucher-Gesamtzahl fällt bei nicht verfügbarem Zähler nicht unter die aktuelle Besuchernummer.
- Die ILLUSIA-Illustration im Sprachbereich wurde verkleinert und unten rechts verankert, damit sie weder Mitgliederkarten noch den Bildschirmfreigabe-Player verdeckt.
### Русский
- Добавлена визуальная система скинов `.wskin`: посетители могут выбирать оформление на главной странице, в голосовом пространстве и в `/demo`. Скины меняют иллюстрации и внешний вид компонентов, а структуру, компоновку, расположение элементов управления и поведение задаёт WebSpeak. Панель администратора не оформляется скинами.
- Администраторы могут включать и отключать пользовательские скины и задавать оформление по умолчанию для экземпляра. Явный выбор посетителя сохраняется; без него используется настройка экземпляра. Дневная тема, ночная тема и ILLUSIA — защищённые встроенные скины, которые нельзя удалить, отключить или заменить.
- Удалён незавершённый пример Aurora Voice; полной эталонной темой стала ILLUSIA. Улучшены иллюстрации главной страницы, многослойный персонаж и сцена с наушниками в голосовой комнате, фон пустого чата и проигрыватель трансляции экрана. Исправлены контраст элементов в тёмном режиме, переполнение и вспышки при загрузке скина.
- В официальный репозиторий добавлен Agent Skill для разработки скинов, обновлены руководство и локализованные описания функций. При недоступности счётчика общее число посетителей не опускается ниже текущего номера посетителя.
- Иллюстрация ILLUSIA в голосовой активности уменьшена и закреплена внизу справа, чтобы не перекрывать список участников и проигрыватель трансляции экрана.
### 日本語
- `.wskin` ビジュアルスキン機能を追加しました。ホーム、音声ワークスペース、`/demo` で外観を選択できます。背景や素材、コンポーネントの見た目を変更できますが、ページ構造、レイアウト、操作部品の位置と動作は WebSpeak が管理します。管理コンソールには適用されません。
- 管理者はカスタムスキンの有効/無効と、インスタンスのデフォルトスキンを設定できます。訪問者が明示的に選んだスキンは維持され、未選択の場合はインスタンスのデフォルトを使用します。昼、夜、ILLUSIA の3種類は保護された内蔵スキンで、削除・無効化・置換できません。
- 未完成の Aurora Voice サンプルを削除し、ILLUSIA を完成版のリファレンスにしました。ホームのアート、音声画面の重ね合わせ立ち絵とヘッドホン背景、空のチャット背景、画面共有プレーヤーを調整し、ダークモードの視認性、はみ出し、読み込み時のちらつきを修正しました。
- 公式リポジトリにスキン開発 Agent Skill を追加し、ガイドと各言語の機能説明を更新しました。カウンターを取得できない場合も、訪問者総数が現在の訪問者番号を下回らないようにしました。
- 音声アクティビティの ILLUSIA 立ち絵を縮小して右下に固定し、メンバー一覧や画面共有プレーヤーを隠さないようにしました。
## [0.2.4] — 2026-09-22
### 中文
+2
View File
@@ -43,6 +43,8 @@
- [Deutsch](./docs/README.de.md)
- [Русский](./docs/README.ru.md)
- [日本語](./docs/README.ja.md)
- [皮肤开发规范](./docs/SKIN_DEVELOPMENT.md)
- [WebSpeak 皮肤开发 Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
## 社区 · Community
+3 -1
View File
@@ -25,7 +25,8 @@ Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung kö
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele und widerrufbare Einladungslinks mit Ablaufzeit. |
| Administration | Ziele, Zugriff, WebRTC, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche, helle/dunkle Designs sowie responsive Desktop-/Mobilansicht. |
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
| Selbsthosting | Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Bereitstellung sind verfügbar. |
## 🖼️ Screenshots
@@ -153,6 +154,7 @@ Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entf
| Version | Datum | Zusammenfassung |
| --- | --- | --- |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin`-Skins, Aktivierungs-/Standardverwaltung und geschützte Tages-, Nacht- und ILLUSIA-Skins ergänzt; unfertiges Aurora-Voice-Beispiel entfernt, Skin-Ladeblitze, dunkle Bedienelemente und Artwork-Ebenen im Sprachbereich korrigiert sowie offiziellen Skin-Entwicklungs-Agent-Skill hinzugefügt; ILLUSIA-Sprachillustration verkleinert und rechts unten verankert, damit Mitglieder und geteilte Videos sichtbar bleiben. |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Plattformübergreifendes P2P-Bildschirmteilen zwischen Browsern und nativen TeamSpeak-6-Clients ergänzt; STUN-/externes-TURN-Konfiguration, Live-Player und Zuschauerstatus, Aufnahmeoptionen bis 1080p/60 FPS und WebRTC-Statistiken hinzugefügt; Bildschirmfreigabe-Interaktion verbessert und Besucherzählung ergänzt. |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Mitgliederplanung und direkte Verschiebung nach Berechtigung ergänzt; Avatar-, Stummschaltstatus- und Identitätsunterstützung hinzugefügt; Screenshots und Dokumentation für alle fünf Sprachen aktualisiert. |
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Browserseitige Mikrofon-Geräuschunterdrückung, russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt; Lautstärkeinteraktion und Fehlertexte/-codes auf Basis von PR #2 verbessert. |
+3 -1
View File
@@ -25,7 +25,8 @@ The public demo is hosted in Hong Kong and its network conditions and load may b
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
| Identity and access | Remembered identity, visitor-defined targets, and revocable expiring invite links. |
| Administration | Manage targets, access policy, WebRTC, relays, invites, sessions, logs, diagnostics, and backups. |
| User experience | Chinese, English, German, Russian, and Japanese UI, light/dark themes, and responsive desktop/mobile layouts. |
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
| Self-hosting | Data stays with the operator; Docker, Windows x64, and Linux x64 deployment options are provided. |
## 🖼️ Screenshots
@@ -153,6 +154,7 @@ Disable and save the relay configuration to remove the relay option from the wel
| Version | Date | Summary |
| --- | --- | --- |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Added `.wskin` skins, administrator enable/default controls, and protected Day/Night/ILLUSIA built-ins; removed the unfinished Aurora Voice sample, fixed skin-load flashes, dark-control contrast, and voice-room artwork layering, and added the official skin-development Agent Skill; reduced and anchored the ILLUSIA voice artwork to avoid covering members or shared video. |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Added cross-platform P2P screen sharing between browsers and native TeamSpeak 6 clients; added STUN/external-TURN configuration, live player and viewer state, 1080p/60 FPS capture settings, and WebRTC statistics; refined screen-share interactions and added visitor numbering. |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Added channel member scheduling and permission-aware direct moves; added avatar, mute-state, and remembered-identity support; refreshed feature screenshots and documentation for all five languages. |
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Added browser-side microphone noise suppression, Russian and Japanese UI, and per-language welcome text; refined volume interaction and error messages/codes on top of PR #2. |
+3 -1
View File
@@ -31,7 +31,8 @@
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
| インターフェース | 中文、English、Deutsch、Русский、日本語、ライト/ダークテーマ、レスポンシブ表示。 |
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
## 🖼️ インターフェースのスクリーンショット
@@ -134,6 +135,7 @@ npm start
| バージョン | 内容 |
| --- | --- |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin` スキン、管理者向けの有効化/デフォルト設定、保護された昼・夜・ILLUSIA 内蔵スキンを追加。未完成の Aurora Voice サンプルを削除し、読み込み時のちらつき、ダークモードの視認性、音声画面のアートレイヤーを修正。公式スキン開発 Agent Skill も追加し、音声アクティビティの立ち絵を縮小して右下に固定し、メンバーや共有動画を隠さないようにしました。 |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | ブラウザと TeamSpeak 6 ネイティブクライアント間のクロスプラットフォーム P2P 画面共有を追加しました。STUN/外部 TURN 設定、プレーヤーと視聴者状態、1080p/60 FPS 取得設定、WebRTC 統計に対応し、共有操作と訪問者番号も改善しました。 |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | チャンネルメンバーの移動操作と権限に応じた直接移動を追加し、アバター表示、ミュート状態の同期、保存 ID の復元に対応しました。5 言語のスクリーンショットとドキュメントも更新しました。 |
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | ブラウザ側マイクノイズ抑制、ロシア語・日本語 UI、言語別ウェルカム文を追加。音量操作と PR #2 を基にしたエラー表示・エラーコードを改善しました。 |
+3 -1
View File
@@ -31,7 +31,8 @@
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, светлая/тёмная тема и адаптивная верстка. |
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
## 🖼️ Скриншоты интерфейса
@@ -134,6 +135,7 @@ npm start
| Версия | Изменения |
| --- | --- |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Добавлены скины `.wskin`, управление включением и темой по умолчанию, а также защищённые темы «День», «Ночь» и ILLUSIA; удалён незавершённый пример Aurora Voice, исправлены мерцание при загрузке скина, контраст элементов в тёмном режиме и слои иллюстраций в голосовом пространстве; добавлен официальный Agent Skill; иллюстрация ILLUSIA уменьшена и закреплена справа внизу, чтобы не перекрывать участников и видео. |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | Добавлена кроссплатформенная P2P-трансляция экрана между браузерами и нативными клиентами TeamSpeak 6; добавлены настройка STUN/внешнего TURN, проигрыватель и состояние зрителей, захват до 1080p/60 FPS и статистика WebRTC; улучшено управление трансляцией и добавлен номер посетителя. |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | Добавлены управление перемещением участников и прямое перемещение с учётом прав; поддержаны аватары, синхронизация микрофона и восстановление идентичности; обновлены скриншоты и документация для пяти языков. |
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | Добавлены браузерное шумоподавление микрофона, русский и японский интерфейсы и отдельные тексты приветствия; улучшены управление громкостью и сообщения/коды ошибок на основе PR #2. |
+3 -1
View File
@@ -25,7 +25,8 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語、浅色/深色主题及响应式桌面/移动布局。 |
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
| 自托管 | 数据由部署者保存,提供 Docker、Windows x64 和 Linux x64 方案。 |
## 🖼️ 界面截图
@@ -153,6 +154,7 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
| 版本 | 日期 | 摘要 |
| --- | --- | --- |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | 新增 `.wskin` 皮肤系统、管理员启用/默认管理和受保护的日间/夜间/ILLUSIA 内置皮肤;移除未完成 Aurora Voice 样例,修复皮肤加载闪烁、暗色控件可读性与语音界面美术层级,并加入官方皮肤开发 Agent Skill;缩小 ILLUSIA 语音立绘并固定在右下角,避免遮挡成员与共享画面。 |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | 新增浏览器与 TeamSpeak 6 原生客户端之间的跨端 P2P 屏幕共享;提供 STUN/外部 TURN 配置、直播播放器、观众状态、1080p/60 FPS 采集设置和 WebRTC 统计;优化屏幕共享交互并新增访客编号。 |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | 新增频道成员调度与按权限直接移动;支持头像、静音状态同步和身份恢复;更新五种语言的功能截图与文档。 |
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | 提供浏览器端麦克风降噪、俄语和日语支持及按语言欢迎词配置;优化音量交互和 PR #2 基础上的错误提示与错误代码。 |
+249
View File
@@ -0,0 +1,249 @@
# WebSpeak 皮肤开发规范
本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可为公开页面逐个部件定制二次元美术表现:背景、素材、配色、轮廓、圆角、阴影、头像装饰、按钮质感、滚动条颜色和播放器外观都可以自定义;但组件的位置、尺寸、排列、文字排版空间及交互结构由 WebSpeak 固定提供,皮肤不得重排或覆盖。
页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。**
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
## 使用与发布
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
## 包结构
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
```text
manifest.json # 必需:身份、版本与入口
skin.css # 必需:皮肤样式
content.json # 可选:首页内容与多语言界面文案
assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用
assets/background.webp # 可选:页面艺术素材
assets/brand.woff2 # 可选:自带字体
```
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。
### `manifest.json`
```json
{
"schemaVersion": 1,
"id": "community.illusia-voice",
"name": "ILLUSIA风",
"version": "1.0.25",
"author": "WebSpeak Project",
"license": "All rights reserved",
"description": "A visual-only art skin using the WebSpeak interface translations.",
"entry": "skin.css",
"preview": "assets/background-composite.webp",
"minAppVersion": "0.2.5"
}
```
| 字段 | 规则 |
| --- | --- |
| `schemaVersion` | 当前必须为数字 `1`。 |
| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头,也不能使用受保护 ID `builtin.light`、`builtin.dark` 或 `community.illusia-voice`。发布后不要更改。 |
| `name`、`author`、`license` | 必需,各最多 80 个字符。资源授权由作者负责确认。 |
| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 |
| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 |
| `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 |
| `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 |
| `description` | 可选,最多 400 个字符。 |
清单不得重复声明同一个文件为 CSS、内容或预览入口。
## 首页内容和文案
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
```json
{
"defaultLocale": "en",
"locales": {
"en": {
"home": {
"eyebrow": "A room of your own",
"title": "Talk",
"titleAccent": "together",
"description": "Join a voice room from your browser.",
"welcomeTitle": "Join the room",
"welcomeDescription": "Choose a name and connect.",
"features": [
{ "title": "Clear voice", "description": "Low-latency Opus audio." }
]
},
"messages": {
"home.connect": "Enter the room",
"voice.activity-heading": "Voice activity",
"demo.heroLead": "A preview customized by this skin."
}
}
}
}
```
`home` 支持 `brandName`、`eyebrow`、`title`、`titleAccent`、`description`、`welcomeTitle`、`welcomeDescription` 和 `features`。普通文字最多 500 个字符;`features` 最多 8 项,每项的 `title` 最多 80 个字符、`description` 最多 240 个字符。功能卡片图标和状态由应用提供,皮肤不能通过 JSON 注入节点。
`messages` 的键是公开页面中翻译调用使用的键;首页/语音页键可在 `web/src/i18n/web-client.ts` 查找,演示页键使用 `demo.` 前缀加字段名(例如 `demo.heroLead`、`demo.speakingNow`)。每个 locale 最多覆盖 200 条,每条文案最多 500 个字符。键只能由小写字母开头,并包含字母、数字或点。语言回退顺序为默认 locale、当前语言和更具体的 locale;之后回退到 WebSpeak 原文。
管理后台的文字不读取皮肤包,不能通过 `messages` 修改。
## CSS 皮肤接口
### 自动隔离
运行时把 `skin.css` 的每个选择器限定在皮肤自己的公开页面根节点内:
```css
/* 选择器必须使用公开的页面/部件钩子;运行时再加上皮肤根作用域。 */
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"] {
outline: 2px solid var(--skin-accent);
outline-offset: 4px;
}
```
实际规则会被限定在类似下面的根节点内,不会匹配 `/admin/**`:
```css
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"]
```
也可以写 `:root { --skin-accent: ... }` 设置皮肤自己的变量;`:root` 会被转换成当前皮肤根。选择器必须包含 `:root`、`[data-ws-page]` 或 `[data-ws-part]`。不要写 `:global()`、`html`、`body` 或 Vue 内部 class 作为公开接口。组件 class 可能随版本调整,`data-ws-part` 才是皮肤作者接口。自定义变量名必须使用 `--skin-` 前缀,不能覆盖 WebSpeak 的内部令牌。
页面根节点使用 `data-ws-page` 区分 `home`、`voice` 和 `demo`。使用 `data-ws-state` 选择明确状态,如 `active`、`idle`、`current`、`open`、`closed`、`drag-over`、`dragging`、`speaking`、`connected`、`self`、`mine` 或 `other`。语音成员还提供 `data-ws-speaking="true|false"` 和 `data-ws-self="true|false"`。交互元素会带有 `data-ws-critical="true"`;没有专属部件名称的按钮、链接、输入框、滑块和可拖动成员会使用通用部件 `data-ws-part="control"`,并以 `data-ws-control-kind` 标出 `button`、`link`、`input`、`checkbox`、`range`、`select`、`textarea`、`menuitem` 或 `draggable`。
### 已发布的部件名称
下列名称来自当前前端模板。对新功能,作者可以先用通用 `control` 部件;后续新增稳定部件会更新本目录。
| 页面区域 | `data-ws-part` |
| --- | --- |
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.mobile-more`、`voice.mobile-nav` |
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
`voice.member.avatar` 是语音活动区头像;`voice.member-row.avatar` 是右侧成员树头像。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
`voice.activity.artwork` 是位于语音活动区内容上方的固定装饰平面。皮肤可以在其上绘制带透明背景的立绘,让角色压住成员卡片或直播画面的边缘;平面本身不占布局空间、不拦截点击,成员和播放器控件仍保持可交互。只通过背景图及背景定位/缩放来适配素材,不改变其定位和层级。
`voice.member-panel` 的 `::before` 是成员栏耳机/场景插画层,宿主已固定它的尺寸、位置、透视和前后层级;皮肤只需提供透明背景素材并调整背景显示、滤镜或阴影,不能自行定位或改变尺寸。消息空状态的 `::before` / `::after` 预留给气泡等小型装饰,宿主负责形状位置;皮肤可以绘制边框、底色和点状背景,但标题和说明文字仍由 WebSpeak 翻译并保持可见。
皮肤与语言选择器的触发按钮、菜单和每个选项都提供上述通用部件钩子。`skin.option` 另带有 `data-ws-skin-id`(内置项为 `builtin.light`、`builtin.dark` 和 `community.illusia-voice`,实例皮肤项为其清单 ID);`language.option` 带有 `data-ws-language`。皮肤可以据此只装饰自己的选择项,而不影响其他皮肤、语言选项或选择器交互。例如:
```css
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
background-image: linear-gradient(110deg, #efffff, #c8f3f2);
}
```
### 令牌、字体、动效和图片
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
```css
:root {
--skin-page-bg: #091317;
--skin-panel: #142329;
--skin-text: #edf8f5;
--skin-muted: #9db5af;
--skin-accent: #47dcc4;
--skin-card-radius: 20px;
}
[data-ws-part="voice.screen-player"] {
border-radius: var(--skin-card-radius);
box-shadow: 0 18px 50px #0008, inset 0 0 0 1px color-mix(in srgb, var(--skin-accent) 50%, transparent);
}
```
`url()` 只允许引用包内图片或 WOFF2 字体。支持 PNG、JPG/JPEG、WebP、AVIF、GIF 和 WOFF2;SVG 不接受。自带字体示例:
```css
@font-face {
font-family: "ILLUSIA Sans";
src: url("assets/illusia-sans.woff2") format("woff2");
font-display: swap;
}
[data-ws-page="voice"] { font-family: "ILLUSIA Sans", sans-serif; }
```
字体必须随包附带并拥有可再分发许可。自定义字体可能改变不同语言的字宽,因此校验器会给出提示;发布前必须检查中文、英语、德语、俄语和日语下的标题、按钮和长文案是否仍完整可读。字体族名和 `@keyframes` / `@layer` 名称会自动隔离,避免与其他皮肤冲突。请支持 `prefers-reduced-motion`,并确保焦点、错误、静音、正在说话等状态仍容易辨认。
### 固定布局与交互边界
皮肤校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。
因此,皮肤可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材,但不能移动播放器、压缩文字、扩大/缩小成员卡片、把锚定浮层改成模态弹窗,或挪动按钮的点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。
外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。上线前仍需预览桌面与窄屏、所有五种语言、日夜基础主题、键盘焦点、减少动效偏好,并确认浮层和必要控件保持在原位、文字未被裁切。
## 安全边界和限制
校验在上传端和服务端执行;服务端只登记有效皮肤包,访客只能下载登记的包。当前限制如下:
| 项目 | 上限 |
| --- | ---: |
| ZIP `.wskin` | 20 MiB |
| 解压总大小 | 50 MiB |
| ZIP 条目数 | 128 |
| 单个 CSS 文件 | 512 KiB |
| `content.json` | 256 KiB |
| 单张图片(包括预览) | 16 MiB |
| 单个 WOFF2 字体 | 4 MiB |
| 每实例皮肤数 | 50 |
| 每实例皮肤包总存储 | 200 MiB |
压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。
必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。只有下列明确标记为可选的装饰部件,才允许通过不改变排版盒子的透明度效果淡出:
```css
[data-ws-part="home.hero.eyebrow"]
[data-ws-part="home.gateway-status"]
[data-ws-part="home.features"]
[data-ws-part="home.feature"]
[data-ws-part="home.visitors"]
[data-ws-part="voice.activity-heading"]
[data-ws-part="voice.member.avatar"]
[data-ws-part="voice.member.live-indicator"]
[data-ws-part="voice.member-row.avatar"]
[data-ws-part="voice.screen-player.viewer-avatar"]
[data-ws-part="voice.screen-player.live"]
[data-ws-part="demo.badge"]
[data-ws-part="demo.wave"]
[data-ws-part="demo.avatar"]
[data-ws-part="demo.member-status"]
[data-ws-part="demo.note"]
```
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
皮肤可以重画控制外观,但不能重新布置或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、日夜基础主题、键盘焦点与减少动效设置。
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
## 制作与验收
1. 复制 `docs/examples/illusia-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是完整的美术参考,不是必须沿用的角色或配色。
2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。
3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。
4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例:
```powershell
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\illusia-voice.zip -Force
Rename-Item .\illusia-voice.zip illusia-voice.wskin
```
5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置,确认组件位置、尺寸、排列与未启用皮肤时一致。
6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。
当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。
+14
View File
@@ -0,0 +1,14 @@
# ILLUSIA风
ILLUSIA风 is a visual-only `.wskin` example built from the local artwork in `illusia-voice/assets/`. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls.
This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. Its CSS is visual-only: WebSpeak retains its component positions, dimensions, text flow, and interactions. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element.
The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root:
```powershell
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force
Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force
```
Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1014 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 365 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 738 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 249 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

+12
View File
@@ -0,0 +1,12 @@
{
"schemaVersion": 1,
"id": "community.illusia-voice",
"name": "ILLUSIA风",
"version": "1.0.27",
"author": "WebSpeak Project",
"license": "All rights reserved",
"description": "A bright original-character art skin for the home, voice room, and demo pages.",
"entry": "skin.css",
"preview": "assets/background-composite.webp",
"minAppVersion": "0.2.5"
}
+972
View File
@@ -0,0 +1,972 @@
/* ILLUSIA风: bright glass surfaces, cyan accents, and project artwork. */
:root {
--skin-illusia-ink: #123849;
--skin-illusia-muted: #4f6974;
--skin-illusia-teal: #087e86;
--skin-illusia-aqua: #47c9d4;
--skin-illusia-glass: rgba(250, 254, 255, .96);
--skin-illusia-line: rgba(115, 205, 218, .38);
--skin-illusia-shadow: 0 20px 56px rgba(29, 91, 113, .16);
}
/* Homepage uses the full-resolution original-character composition. */
[data-ws-part="home"] {
color: var(--skin-illusia-ink);
background-color: #eaf7fc;
background-image:
radial-gradient(ellipse at 14% 78%, rgba(90, 222, 230, .28), transparent 34%),
radial-gradient(ellipse at 83% 21%, rgba(94, 190, 255, .24), transparent 30%),
radial-gradient(ellipse at 52% 56%, rgba(190, 239, 255, .16), transparent 42%),
linear-gradient(90deg, rgba(246, 252, 255, .91) 0%, rgba(246, 252, 255, .82) 33%, rgba(246, 252, 255, .32) 60%, rgba(246, 252, 255, .08) 100%),
url("assets/background-composite.webp");
background-position: 0% 100%, 100% 0%, 50% 50%, center, center;
background-repeat: no-repeat;
background-size: 132% 130%, 122% 124%, 116% 116%, cover, cover;
animation: illusia-home-aura 18s ease-in-out infinite alternate;
}
@keyframes illusia-home-aura {
from { background-position: 0% 100%, 100% 0%, 50% 50%, center, center; }
to { background-position: 20% 82%, 78% 18%, 55% 45%, center, center; }
}
[data-ws-part="home.header"] {
border-color: rgba(255, 255, 255, .85);
border-radius: 999px;
background: linear-gradient(135deg, rgba(255, 255, 255, .8), rgba(255, 255, 255, .45));
box-shadow: 0 26px 80px rgba(78, 150, 173, .17), inset 0 1px 0 rgba(255, 255, 255, .9);
backdrop-filter: blur(22px) saturate(1.18);
}
[data-ws-part="home.header"] [data-ws-part="control"] {
color: var(--skin-illusia-ink);
border-color: rgba(255, 255, 255, .76);
border-radius: 999px;
background: rgba(250, 254, 255, .84);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .42);
}
[data-ws-part="home.header"] [data-ws-part="control"]:hover {
background: rgba(255, 255, 255, .98);
}
/* ARIA selectors raise specificity over component defaults without private classes. */
[data-ws-part="skin.trigger"][aria-haspopup="listbox"] {
color: var(--skin-illusia-ink);
border-color: rgba(255, 255, 255, .82);
border-radius: 999px;
background: rgba(250, 254, 255, .86);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
}
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:hover,
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:focus-visible,
[data-ws-part="skin.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
color: var(--skin-illusia-teal);
border-color: rgba(71, 201, 212, .52);
background: rgba(255, 255, 255, .98);
}
[data-ws-part="skin.menu"][role="listbox"] {
color: var(--skin-illusia-ink);
border-color: rgba(104, 196, 211, .58);
border-radius: 15px;
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
backdrop-filter: blur(18px) saturate(1.18);
}
[data-ws-part="skin.option"][role="option"] {
color: var(--skin-illusia-ink);
border-radius: 9px;
background: rgba(255, 255, 255, .54);
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
}
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
color: #075e68;
border-color: rgba(82, 195, 204, .46);
background-image: linear-gradient(112deg, rgba(255, 255, 255, .96), rgba(225, 250, 249, .96), rgba(188, 241, 237, .94), rgba(255, 255, 255, .96));
background-position: 0% 50%;
background-size: 240% 100%;
box-shadow: 0 4px 14px rgba(30, 170, 184, .17), inset 0 0 0 1px rgba(255, 255, 255, .86);
animation: illusia-option-gradient 8s ease-in-out infinite alternate;
}
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] > :first-child {
color: #07858a;
filter: drop-shadow(0 0 5px rgba(71, 201, 212, .54));
}
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:hover,
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:focus-visible,
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"][aria-selected="true"] {
color: #056e76;
border-color: rgba(44, 186, 197, .7);
background-image: linear-gradient(112deg, #faffff 0%, #c8f5f1 36%, #82e2dc 70%, #d9fbf8 100%);
background-position: 100% 50%;
box-shadow: 0 5px 18px rgba(30, 170, 184, .23), inset 0 0 0 1px rgba(255, 255, 255, .94);
}
@keyframes illusia-option-gradient {
from { background-position: 0% 50%; }
to { background-position: 100% 50%; }
}
[data-ws-part="language.trigger"][aria-haspopup="listbox"] {
color: var(--skin-illusia-ink);
border-color: rgba(255, 255, 255, .82);
border-radius: 999px;
background: rgba(250, 254, 255, .86);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
}
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:hover,
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:focus-visible,
[data-ws-part="language.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
color: var(--skin-illusia-teal);
border-color: rgba(71, 201, 212, .52);
background: rgba(255, 255, 255, .98);
}
[data-ws-part="language.menu"][role="listbox"] {
color: var(--skin-illusia-ink);
border-color: rgba(104, 196, 211, .58);
border-radius: 15px;
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
backdrop-filter: blur(18px) saturate(1.18);
}
[data-ws-part="language.option"][role="option"] {
color: var(--skin-illusia-ink);
border-radius: 9px;
background: rgba(255, 255, 255, .54);
}
[data-ws-part="language.option"][role="option"]:hover,
[data-ws-part="language.option"][role="option"]:focus-visible,
[data-ws-part="language.option"][role="option"][aria-selected="true"] {
color: var(--skin-illusia-teal);
border-color: rgba(71, 201, 212, .42);
background: rgba(211, 245, 248, .92);
}
[data-ws-part="skin.option"][role="option"]:hover,
[data-ws-part="skin.option"][role="option"]:focus-visible,
[data-ws-part="skin.option"][role="option"][aria-selected="true"] {
color: #087e86;
border-color: rgba(71, 201, 212, .42);
background: rgba(211, 245, 248, .92);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .82);
}
[data-ws-part="home.brand"] {
color: var(--skin-illusia-teal);
}
[data-ws-part="home.brand"] strong,
[data-ws-part="home.hero.title"] {
color: var(--skin-illusia-ink);
}
[data-ws-part="home.brand"] small,
[data-ws-part="home.hero.description"],
[data-ws-part="home.join-description"] {
color: var(--skin-illusia-muted);
}
[data-ws-part="home.hero.title"] em {
color: var(--skin-illusia-teal);
text-shadow: 0 8px 28px rgba(47, 192, 202, .2);
}
[data-ws-part="home.hero.eyebrow"] {
color: #087a76;
}
[data-ws-part="home.feature"] {
border-color: rgba(255, 255, 255, .94);
border-radius: 18px;
background: rgba(255, 255, 255, .79);
box-shadow: 0 14px 28px rgba(68, 158, 173, .12), inset 0 0 0 1px rgba(255, 255, 255, .42);
backdrop-filter: blur(12px) saturate(1.08);
}
[data-ws-part="home.feature"] > span:first-child {
box-shadow: 0 5px 14px rgba(43, 157, 167, .12), inset 0 0 0 1px rgba(255, 255, 255, .56);
}
[data-ws-part="home.feature"] b {
color: var(--skin-illusia-ink);
}
[data-ws-part="home.feature"] small {
color: var(--skin-illusia-muted);
}
[data-ws-part="home.visitors"] {
color: #075c67;
border-color: var(--skin-illusia-line);
background-color: rgba(247, 254, 255, .9);
background-image: linear-gradient(105deg, rgba(247, 254, 255, .98), rgba(237, 252, 253, .84));
background-position: center;
background-repeat: no-repeat;
background-size: cover;
box-shadow: 0 10px 28px rgba(19, 142, 157, .14), inset 0 0 0 1px rgba(255, 255, 255, .72);
backdrop-filter: blur(14px) saturate(1.12);
}
[data-ws-part="home.visitors"] > span:nth-child(2) {
color: transparent;
background-color: transparent;
background-image: url("assets/visitor-avatar.webp");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
box-shadow: 0 0 0 3px rgba(71, 201, 212, .26), 0 5px 16px rgba(19, 142, 157, .2);
}
[data-ws-part="home.visitors"] > span:nth-child(2) svg {
color: transparent;
}
[data-ws-part="home.visitors"] > span:last-child {
color: #41bdcc;
text-shadow: 0 0 12px rgba(71, 201, 212, .42);
}
[data-ws-part="home.join-card"] {
color: var(--skin-illusia-ink);
border-color: rgba(255, 255, 255, .9);
border-radius: 26px;
background-color: var(--skin-illusia-glass);
background-image: url("assets/banner-mascot-blob.webp");
background-position: right 18px top 10px;
background-repeat: no-repeat;
background-size: 96px 68px;
box-shadow: var(--skin-illusia-shadow), 0 0 15px rgba(71, 201, 212, .14), inset 0 0 0 1px rgba(255, 255, 255, .84);
backdrop-filter: blur(22px);
}
[data-ws-part="home.join-card.waveform"] {
color: #47c9d4;
}
[data-ws-part="home.join-card.waveform"] i {
box-shadow: 0 0 8px rgba(71, 201, 212, .52);
}
[data-ws-part="home.join-card.sonar"] {
color: rgba(71, 201, 212, .72);
}
[data-ws-part="home.join-card.sonar"] i {
box-shadow: 0 0 12px rgba(71, 201, 212, .16);
}
@media (prefers-reduced-motion: reduce) {
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
animation: none;
}
}
[data-ws-part="home.join-title"] {
color: var(--skin-illusia-ink);
}
[data-ws-part="home.field"] {
color: #4f6974;
border-color: rgba(134, 190, 200, .42);
border-radius: 12px;
background: rgba(232, 244, 247, .96);
box-shadow: inset 0 0 0 1px rgba(134, 190, 200, .24);
}
[data-ws-part="home.field"] input {
color: var(--skin-illusia-ink);
}
[data-ws-part="home.field"] input::placeholder {
color: #8ba4aa;
}
[data-ws-part="home.field-label"] {
color: var(--skin-illusia-ink);
}
[data-ws-part="home"] [data-ws-part="home.connect"] {
color: #fff;
border-radius: 14px;
background-color: var(--skin-illusia-teal);
background:
url("assets/button-mascot.webp") right 4px center / 112px 74px no-repeat,
linear-gradient(100deg, #38d6d0 0%, #0c9caf 62%, #08788d 100%) center / cover no-repeat;
box-shadow: 0 12px 22px rgba(16, 181, 192, .24), inset 0 1px 0 rgba(255, 255, 255, .55), inset 0 0 0 1px rgba(141, 255, 255, .52);
}
[data-ws-part="home"] [data-ws-part="home.connect"]:hover {
background-color: #087078;
box-shadow: 0 14px 30px rgba(8, 126, 134, .3);
}
[data-ws-part="home.security-note"],
[data-ws-part="home.footer"] {
color: var(--skin-illusia-muted);
}
[data-ws-part="home.footer"] {
color: var(--skin-illusia-muted);
border-color: transparent;
background-color: transparent;
background-image: url("assets/footer-wave.png");
background-position: center top;
background-repeat: no-repeat;
background-size: 100% 58px;
box-shadow: none;
backdrop-filter: blur(8px) saturate(1.04);
}
/* Voice room: let the artwork flow through the UI instead of stacking opaque cards. */
:root {
--skin-room-line: rgba(76, 176, 193, .3);
}
[data-ws-part="voice.shell"] {
color-scheme: light;
color: var(--skin-illusia-ink);
background-color: #dff4f8;
background-image:
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.55px),
radial-gradient(circle at 100% 0%, transparent 0 188px, rgba(71, 201, 212, .13) 189px 190px, transparent 191px 229px, rgba(71, 201, 212, .09) 230px 231px, transparent 232px),
radial-gradient(ellipse at 13% 5%, rgba(107, 226, 232, .2), transparent 36%),
linear-gradient(125deg, rgba(229, 248, 251, .19), rgba(239, 251, 253, .06) 48%, rgba(190, 235, 242, .22)),
url("assets/bg-room-main.webp");
background-position: 0 0, right top, left top, center, center;
background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat;
background-size: 24px 24px, 560px 450px, auto, auto, cover;
}
[data-ws-part="voice.workspace"] {
background: linear-gradient(145deg, rgba(239, 251, 253, .22), rgba(218, 244, 248, .12) 48%, rgba(245, 253, 254, .2));
backdrop-filter: blur(2px);
}
[data-ws-part="voice.activity"] {
border-color: rgba(113, 211, 222, .62);
border-radius: 24px;
background-color: rgba(227, 247, 250, .64);
background-image:
radial-gradient(ellipse at 82% 48%, rgba(91, 215, 224, .19), rgba(91, 215, 224, .04) 34%, transparent 65%),
linear-gradient(90deg, rgba(230, 248, 251, .78), rgba(230, 248, 251, .36) 38%, rgba(230, 248, 251, .08) 72%),
url("assets/bg-room-main.webp");
background-position: right 5% center, center, center 48%;
background-repeat: no-repeat;
background-size: 48% 100%, 100% 100%, cover;
box-shadow: 0 15px 38px rgba(30, 111, 132, .13), inset 0 0 0 1px rgba(255, 255, 255, .7);
backdrop-filter: blur(10px) saturate(1.08);
}
[data-ws-part="voice.activity.artwork"] {
background-image: url("assets/banner-character-main.webp");
background-position: right 16px bottom 8px;
background-size: auto 150px;
filter: drop-shadow(0 18px 22px rgba(30, 113, 134, .2));
}
[data-ws-part="voice.header"] {
border-color: rgba(126, 191, 203, .36);
background: linear-gradient(105deg, rgba(249, 254, 255, .76), rgba(222, 246, 250, .57) 56%, rgba(247, 253, 254, .72));
box-shadow: 0 8px 28px rgba(27, 92, 112, .08), inset 0 1px 0 rgba(255, 255, 255, .62);
backdrop-filter: blur(16px);
}
[data-ws-part="voice.member-panel"] {
color: var(--skin-illusia-ink);
border-color: var(--skin-room-line);
background-color: rgba(221, 245, 249, .66);
background-image:
radial-gradient(circle at 1px 1px, rgba(25, 145, 161, .065) 1px, transparent 1.5px),
radial-gradient(circle at 100% 0%, transparent 0 86px, rgba(71, 201, 212, .16) 87px 88px, transparent 89px 119px, rgba(71, 201, 212, .1) 120px 121px, transparent 122px),
radial-gradient(ellipse at 100% 0%, rgba(107, 226, 232, .2), transparent 43%),
linear-gradient(155deg, rgba(248, 254, 255, .75), rgba(222, 246, 249, .58) 48%, rgba(213, 241, 246, .7));
background-position: 0 0, right top, right top, center;
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
background-size: 22px 22px, 360px 320px, auto, auto;
backdrop-filter: blur(18px);
}
/* Keep the headset as an independent foreground object instead of flattening
it into the member rail's background. Its slight perspective and shadow
make it sit in front of the room, while the actual controls remain above it. */
[data-ws-part="voice.member-panel"]::before {
background-image: url("assets/foreground-headphone.webp");
background-position: left bottom;
background-repeat: no-repeat;
background-size: contain;
filter: drop-shadow(16px 18px 17px rgba(36, 105, 119, .24));
}
[data-ws-part="voice.member-panel.search"] {
color: #4f7982;
border-color: rgba(103, 186, 198, .28);
background: linear-gradient(110deg, rgba(232, 249, 251, .86), rgba(216, 242, 247, .68));
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .58);
}
[data-ws-part="voice.member-panel.search"] input {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.member-panel.search"] input::placeholder {
color: #78979d;
}
[data-ws-part="voice.channel-group"] {
border-color: rgba(8, 126, 134, .32);
}
[data-ws-part="voice.channel-group"][data-ws-state="current"] {
border-color: rgba(8, 126, 134, .48);
}
[data-ws-part="voice.channel-group.heading"] {
color: #386b75;
border-radius: 10px;
background: linear-gradient(100deg, rgba(223, 246, 249, .68), rgba(237, 250, 251, .34));
}
[data-ws-part="voice.channel-group.heading"][data-ws-state="current"] {
color: #087e86;
background: linear-gradient(100deg, rgba(179, 235, 239, .78), rgba(224, 248, 249, .5));
box-shadow: inset 3px 0 0 rgba(37, 175, 188, .74);
}
[data-ws-part="voice.member-row"] {
border-radius: 11px;
transition: background .16s ease, box-shadow .16s ease;
}
[data-ws-part="voice.member-row"]:hover,
[data-ws-part="voice.member-row"][data-ws-state="speaking"] {
background: linear-gradient(100deg, rgba(198, 240, 243, .38), rgba(238, 251, 252, .28));
box-shadow: inset 0 0 0 1px rgba(92, 190, 202, .16);
}
[data-ws-part="voice.member"] {
border-color: rgba(91, 184, 198, .36);
border-radius: 20px;
background-color: rgba(222, 246, 249, .7);
background-image:
radial-gradient(ellipse at 100% 0%, rgba(102, 220, 226, .24), transparent 62%),
linear-gradient(145deg, rgba(250, 255, 255, .72), rgba(224, 246, 249, .62) 56%, rgba(210, 241, 246, .66));
box-shadow: 0 12px 32px rgba(31, 99, 123, .12), inset 0 1px 0 rgba(255, 255, 255, .76);
backdrop-filter: blur(12px) saturate(1.08);
}
[data-ws-part="voice.member.avatar"] {
outline: 2px solid rgba(71, 201, 212, .8);
outline-offset: 4px;
box-shadow: 0 0 24px rgba(71, 201, 212, .28);
}
[data-ws-part="voice.member.live-indicator"] {
color: #08706f;
border-radius: 999px;
background: rgba(237, 255, 251, .96);
box-shadow: 0 6px 20px rgba(42, 160, 162, .18), inset 0 0 0 1px rgba(71, 201, 212, .5);
}
[data-ws-part="voice.audio-dock"] {
color: var(--skin-illusia-muted);
border-color: rgba(116, 194, 205, .42);
border-radius: 22px;
background-color: rgba(222, 246, 249, .8);
background-image:
radial-gradient(circle at 0% 100%, transparent 0 35px, rgba(71, 201, 212, .16) 36px 37px, transparent 38px 57px, rgba(71, 201, 212, .1) 58px 59px, transparent 60px),
linear-gradient(125deg, rgba(250, 255, 255, .76), rgba(222, 246, 249, .68) 55%, rgba(205, 238, 244, .76));
box-shadow: 0 12px 34px rgba(28, 91, 111, .16), inset 0 1px 0 rgba(255, 255, 255, .74);
backdrop-filter: blur(18px);
}
[data-ws-part="voice.chat"] {
border-color: rgba(100, 184, 198, .34);
border-radius: 20px;
background-color: rgba(221, 245, 249, .58);
background-image:
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .055) 1px, transparent 1.5px),
radial-gradient(ellipse at 0% 100%, rgba(102, 220, 226, .16), transparent 42%),
linear-gradient(145deg, rgba(249, 254, 255, .72), rgba(226, 247, 250, .48) 52%, rgba(214, 242, 247, .62));
background-position: 0 0, left bottom, center;
background-repeat: repeat, no-repeat, no-repeat;
background-size: 24px 24px, auto, auto;
backdrop-filter: blur(14px) saturate(1.05);
}
[data-ws-part="voice.chat.tab"] {
color: #547780;
border-color: rgba(95, 180, 193, .24);
background: linear-gradient(115deg, rgba(242, 252, 253, .72), rgba(217, 243, 247, .56));
}
[data-ws-part="voice.chat.tab"]:hover,
[data-ws-part="voice.chat.tab"][data-ws-state="active"] {
color: #087e86;
border-color: rgba(71, 201, 212, .48);
background: linear-gradient(115deg, rgba(207, 242, 245, .86), rgba(232, 250, 251, .72));
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .6);
}
[data-ws-part="voice.chat.empty"] {
color: var(--skin-illusia-muted);
background-color: rgba(218, 244, 248, .4);
background-image:
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
linear-gradient(100deg, rgba(237, 250, 252, .76), rgba(228, 247, 250, .38) 52%, rgba(205, 240, 245, .26)),
url("assets/chat-empty-chibi.webp");
background-position: 0 0, right center, center, center 10px;
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
backdrop-filter: blur(8px);
}
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
color: var(--skin-illusia-muted);
background-color: rgba(218, 244, 248, .4);
background-image:
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
linear-gradient(100deg, rgba(237, 250, 252, .68), rgba(228, 247, 250, .34) 50%, rgba(205, 240, 245, .08)),
url("assets/chat-empty-chibi.webp");
background-position: 0 0, right center, center, center 8px;
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
}
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::before {
color: rgba(71, 126, 148, .9);
border-radius: 50%;
background-color: rgba(250, 255, 255, .66);
background-image:
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px);
background-position: 12px 16px, 22px 12px, 32px 9px;
background-repeat: no-repeat;
box-shadow: 0 3px 8px rgba(48, 115, 132, .1);
}
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::after {
color: rgba(71, 126, 148, .9);
background: rgba(250, 255, 255, .7);
}
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > strong,
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > span {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.chat.empty"] strong {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.chat.empty"] span {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.members.empty"] {
color: #587a82;
border-color: rgba(78, 176, 191, .38);
background: linear-gradient(120deg, rgba(223, 247, 249, .68), rgba(235, 250, 251, .42));
}
[data-ws-part="voice.members.empty"] strong {
color: #315c66;
}
[data-ws-part="voice.chat.message-bubble"] {
color: #315360;
background: linear-gradient(135deg, rgba(250, 255, 255, .78), rgba(216, 243, 247, .68));
box-shadow: 0 4px 14px rgba(34, 117, 136, .08), inset 0 0 0 1px rgba(255, 255, 255, .54);
}
[data-ws-part="voice.chat.message"][data-ws-state="mine"] [data-ws-part="voice.chat.message-bubble"] {
color: #fff;
background: linear-gradient(130deg, #0b9da1, #087985);
box-shadow: 0 5px 16px rgba(8, 126, 134, .2);
}
[data-ws-part="voice.activity-heading"] h2,
[data-ws-part="voice.chat.heading"] h2 {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.activity-heading"] span,
[data-ws-part="voice.chat.heading"] span {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.member.name"] {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.member.status"] {
color: var(--skin-illusia-muted);
}
/* These controls use the active day/night palette by default. Give them the
same readable glass treatment as the rest of this intentionally bright skin. */
[data-ws-part="voice.performance"] > [data-ws-part="control"] {
color: var(--skin-illusia-teal);
border-color: rgba(115, 205, 218, .42);
background: rgba(249, 253, 255, .9);
box-shadow: 0 5px 16px rgba(29, 91, 113, .1), inset 0 1px 0 rgba(255, 255, 255, .9);
}
[data-ws-part="voice.performance"] > [data-ws-part="control"]:hover,
[data-ws-part="voice.performance"] > [data-ws-part="control"][aria-expanded="true"] {
color: #075f69;
border-color: rgba(71, 201, 212, .72);
background: rgba(255, 255, 255, .98);
}
[data-ws-part="voice.performance.panel"] {
color: var(--skin-illusia-ink);
border-color: rgba(115, 205, 218, .4);
background-color: rgba(223, 246, 249, .96);
background-image:
radial-gradient(circle at 100% 0%, rgba(71, 201, 212, .16), transparent 52%),
linear-gradient(145deg, rgba(250, 255, 255, .96), rgba(224, 246, 249, .94));
box-shadow: var(--skin-illusia-shadow);
backdrop-filter: blur(18px);
}
[data-ws-part="voice.performance.panel"] small,
[data-ws-part="voice.performance.status"] {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.performance.panel"] [data-ws-part="control"] {
color: var(--skin-illusia-teal);
border-color: rgba(115, 205, 218, .36);
background: rgba(232, 247, 248, .9);
}
[data-ws-part="voice.performance.route"] {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.performance.route"] span,
[data-ws-part="voice.performance.metrics"] article,
[data-ws-part="voice.performance.webrtc-stats"] [data-ws-part="control"] {
color: var(--skin-illusia-muted);
border-color: rgba(115, 205, 218, .28);
background: linear-gradient(135deg, rgba(232, 248, 250, .88), rgba(212, 241, 245, .72));
}
[data-ws-part="voice.performance.metrics"] strong,
[data-ws-part="voice.performance.webrtc-stats"] strong {
color: var(--skin-illusia-teal);
}
[data-ws-part="voice.performance.metrics"] small,
[data-ws-part="voice.performance.metrics"] span,
[data-ws-part="voice.performance.webrtc-stats"] small,
[data-ws-part="voice.performance.webrtc-stats"] span {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.audio-dock"] strong {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.audio-dock"] span {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"] {
color: var(--skin-illusia-teal);
border-color: transparent;
background: transparent;
}
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:hover,
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:focus-visible {
color: #075f69;
border-color: rgba(71, 201, 212, .4);
background: rgba(221, 246, 247, .86);
}
[data-ws-part="voice.audio-dock.microphone-panel"],
[data-ws-part="voice.audio-dock.output-panel"] {
color: var(--skin-illusia-ink);
border-color: rgba(115, 205, 218, .38);
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(221, 246, 249, .96));
box-shadow: var(--skin-illusia-shadow);
}
[data-ws-part="voice.audio-dock.microphone-panel"] strong,
[data-ws-part="voice.audio-dock.output-panel"] strong {
color: var(--skin-illusia-teal);
}
[data-ws-part="voice.chat.composer"] {
background: linear-gradient(110deg, rgba(249, 254, 255, .82), rgba(225, 247, 250, .76) 58%, rgba(214, 242, 247, .82));
box-shadow: inset 0 0 0 1px rgba(115, 205, 218, .32), 0 5px 18px rgba(36, 130, 148, .07);
}
[data-ws-part="voice.chat.composer"]:focus-within {
background: linear-gradient(110deg, rgba(250, 255, 255, .9), rgba(211, 242, 246, .82));
box-shadow: inset 0 0 0 1px rgba(71, 201, 212, .55), 0 6px 20px rgba(36, 130, 148, .11);
}
[data-ws-part="voice.chat.composer"] input {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.chat.composer"] input::placeholder {
color: #718b92;
}
[data-ws-part="voice.chat.composer"] button[data-ws-part="control"] {
color: #fff;
border-color: rgba(8, 126, 134, .18);
background: linear-gradient(135deg, #0a9291, #087580);
box-shadow: 0 5px 13px rgba(8, 126, 134, .2);
}
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"] {
color: #086b72;
border-color: rgba(71, 201, 212, .45);
background: rgba(237, 252, 251, .96);
box-shadow: 0 3px 10px rgba(29, 120, 130, .12);
}
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:hover,
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:focus-visible {
color: #064f59;
border-color: rgba(8, 126, 134, .58);
background: rgba(219, 247, 246, .98);
}
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"][data-ws-state="viewing"] {
color: #fff;
border-color: #087e86;
background: linear-gradient(135deg, #0a9291, #087580);
}
[data-ws-part="voice.member.stop-share"] {
color: #a43e48;
border-color: rgba(255, 255, 255, .96);
background: #fff6f5;
}
[data-ws-part="voice.screen-share-settings"] {
color: var(--skin-illusia-ink);
border-color: rgba(115, 205, 218, .42);
background: rgba(250, 254, 255, .98);
box-shadow: var(--skin-illusia-shadow);
backdrop-filter: blur(18px);
}
[data-ws-part="voice.screen-share-settings.heading"] h2 {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.screen-share-settings.heading"] p,
[data-ws-part="voice.screen-share-settings.fields"] label,
[data-ws-part="voice.screen-share-settings.note"] {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.screen-share-settings"] select {
color: var(--skin-illusia-ink);
border-color: rgba(115, 205, 218, .42);
background: rgba(235, 247, 248, .94);
}
[data-ws-part="voice.screen-share-settings"] [data-ws-part="control"] {
color: var(--skin-illusia-teal);
border-color: rgba(115, 205, 218, .38);
background: rgba(232, 247, 248, .92);
}
[data-ws-part="voice.screen-share-settings.actions"] [data-ws-part="control"] {
color: #fff;
border-color: rgba(8, 126, 134, .2);
background: linear-gradient(135deg, #0a9291, #087580);
}
@media (max-width: 1100px) {
[data-ws-part="voice.chat.empty"] {
background-position: 0 0, right 8px center, center, center 8px;
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
}
[data-ws-part="voice.activity"] {
background-position: right 1% center, center, center 48%;
background-size: 56% 100%, 100% 100%, cover;
}
[data-ws-part="voice.activity.artwork"] {
background-position: right 12px bottom 6px;
background-size: auto 118px;
}
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
background-position: 0 0, right center, center, center 8px;
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
}
}
@media (max-width: 740px) {
[data-ws-part="voice.activity"] {
background-image: none;
}
[data-ws-part="voice.activity.artwork"] {
background-image: none;
}
}
[data-ws-part="voice.screen-player"] {
border-radius: 24px;
color: var(--skin-illusia-ink);
border-color: rgba(115, 205, 218, .58);
background: linear-gradient(135deg, rgba(250, 255, 255, .96), rgba(220, 245, 250, .94));
box-shadow: 0 22px 60px rgba(10, 68, 88, .3), inset 0 0 0 1px rgba(185, 246, 249, .55);
}
[data-ws-part="voice.screen-player.stage"] {
border-radius: 22px;
background: radial-gradient(ellipse at 50% 38%, rgba(248, 255, 255, .98), rgba(220, 246, 250, .92) 58%, rgba(202, 237, 244, .9));
}
[data-ws-part="voice.screen-player.video"] {
background: #e5f4f8;
}
[data-ws-part="voice.screen-player.placeholder"] {
color: var(--skin-illusia-muted);
}
[data-ws-part="voice.screen-player.placeholder"] strong {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.screen-player.exit"],
[data-ws-part="voice.screen-player.fullscreen"] {
color: var(--skin-illusia-ink);
border-color: rgba(115, 205, 218, .62);
background: rgba(250, 255, 255, .9);
box-shadow: 0 5px 18px rgba(40, 126, 148, .18);
}
[data-ws-part="voice.screen-player.viewers"],
[data-ws-part="voice.screen-player.volume"],
[data-ws-part="voice.screen-player.source"] {
color: var(--skin-illusia-ink);
border-color: rgba(115, 205, 218, .58);
background: rgba(250, 255, 255, .88);
box-shadow: 0 5px 18px rgba(40, 126, 148, .16);
backdrop-filter: blur(12px);
}
[data-ws-part="voice.screen-player.viewer-avatar"] {
border-color: rgba(250, 255, 255, .96);
}
[data-ws-part="voice.screen-player.live"] {
border-radius: 999px;
color: #075e68;
border-color: rgba(82, 195, 204, .56);
background: rgba(239, 253, 254, .94);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .76), 0 5px 18px rgba(40, 126, 148, .16);
text-shadow: none;
backdrop-filter: blur(12px);
}
[data-ws-part="voice.screen-player.viewer-avatar"] {
box-shadow: 0 0 0 2px rgba(255, 255, 255, .94), 0 0 0 4px rgba(71, 201, 212, .72);
}
/* The demo keeps its original controls, labels, and interactions. */
[data-ws-page="demo"] {
color: var(--skin-illusia-ink);
background-color: #eaf7fc;
background-image: url("assets/foreground-headphone.webp"), linear-gradient(rgba(239, 250, 253, .7), rgba(239, 250, 253, .82)), url("assets/bg-room-main.webp");
background-position: left bottom, center, center;
background-repeat: no-repeat, no-repeat, no-repeat;
background-size: min(34vw, 430px) auto, auto, cover;
background-attachment: fixed, scroll, scroll;
}
[data-ws-part="demo.header"] {
border-color: rgba(126, 191, 203, .3);
background: rgba(250, 254, 255, .72);
backdrop-filter: blur(16px);
}
[data-ws-part="demo.channels"],
[data-ws-part="demo.actions"],
[data-ws-part="demo.main"] {
border-color: rgba(255, 255, 255, .8);
border-radius: 20px;
background: rgba(249, 253, 255, .84);
box-shadow: var(--skin-illusia-shadow);
backdrop-filter: blur(18px);
}
[data-ws-part="demo.hero"] {
color: var(--skin-illusia-ink);
border-radius: 22px;
background-color: #d7f3f7;
background-image: linear-gradient(90deg, rgba(239, 251, 254, .94), rgba(227, 248, 251, .48)), url("assets/banner-character-main.webp"), url("assets/banner-mascot-blob.webp");
background-position: center, right 46px bottom, right 16px center;
background-repeat: no-repeat;
background-size: cover, auto 112%, auto 72%;
box-shadow: 0 14px 38px rgba(31, 99, 123, .12), inset 0 0 0 1px rgba(255, 255, 255, .8);
}
[data-ws-part="demo.voice-card"] {
border-color: rgba(115, 205, 218, .35);
border-radius: 19px;
background: rgba(255, 255, 255, .76);
box-shadow: 0 10px 28px rgba(31, 99, 123, .1);
}
[data-ws-part="demo.avatar"] {
outline: 2px solid rgba(71, 201, 212, .7);
outline-offset: 4px;
}
[data-ws-part="demo.chat.send"] {
color: #fff;
border-radius: 12px;
background: linear-gradient(110deg, #0a9291, #087580);
}
@media (max-width: 740px) {
[data-ws-page="demo"] {
background-size: min(62vw, 300px) auto, auto, cover;
background-attachment: scroll, scroll, scroll;
}
[data-ws-part="demo.hero"] {
background-position: center, right center;
background-size: cover, auto 65%;
}
}
@media (prefers-reduced-motion: reduce) {
[data-ws-part="home"] {
animation: none;
}
[data-ws-part="home.connect"],
[data-ws-part="voice.member"],
[data-ws-part="demo.voice-card"] {
transition-duration: .01ms;
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "webspeak-webclient",
"version": "0.2.4",
"version": "0.2.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.2.4",
"version": "0.2.5",
"license": "AGPL-3.0-only",
"dependencies": {
"@discordjs/opus": "^0.10.0",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "webspeak-webclient",
"version": "0.2.4",
"version": "0.2.5",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
@@ -11,6 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/skin-registry.test.ts src/server/visitor-count.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts",
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "cd web && npx vite build",
+100
View File
@@ -0,0 +1,100 @@
Add-Type -AssemblyName System.Drawing
$width = 3200
$height = 116
$outputPath = Join-Path $PSScriptRoot "..\docs\examples\illusia-voice\assets\footer-wave.png"
$bitmap = [System.Drawing.Bitmap]::new($width, $height, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
$graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
$graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::HighQuality
$graphics.Clear([System.Drawing.Color]::Transparent)
$topEdge = [System.Drawing.Drawing2D.GraphicsPath]::new()
$topEdge.StartFigure()
$topEdge.AddBezier(
[System.Drawing.PointF]::new(0, 20),
[System.Drawing.PointF]::new(240, 4),
[System.Drawing.PointF]::new(460, 0),
[System.Drawing.PointF]::new(700, 10)
)
$topEdge.AddBezier(
[System.Drawing.PointF]::new(700, 10),
[System.Drawing.PointF]::new(1000, 26),
[System.Drawing.PointF]::new(1200, 36),
[System.Drawing.PointF]::new(1600, 36)
)
$topEdge.AddBezier(
[System.Drawing.PointF]::new(1600, 36),
[System.Drawing.PointF]::new(2000, 36),
[System.Drawing.PointF]::new(2200, 26),
[System.Drawing.PointF]::new(2500, 10)
)
$topEdge.AddBezier(
[System.Drawing.PointF]::new(2500, 10),
[System.Drawing.PointF]::new(2740, 0),
[System.Drawing.PointF]::new(2960, 4),
[System.Drawing.PointF]::new(3200, 20)
)
$surface = [System.Drawing.Drawing2D.GraphicsPath]::new()
$surface.AddPath($topEdge, $false)
$surface.AddLine(3200, 20, 3200, $height)
$surface.AddLine(3200, $height, 0, $height)
$surface.CloseFigure()
$brush = [System.Drawing.Drawing2D.LinearGradientBrush]::new(
[System.Drawing.Rectangle]::new(0, 0, $width, $height),
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
[System.Drawing.Color]::FromArgb(245, 252, 255, 255),
[System.Drawing.Drawing2D.LinearGradientMode]::Vertical
)
$blend = [System.Drawing.Drawing2D.ColorBlend]::new(3)
$blend.Colors = [System.Drawing.Color[]]@(
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
[System.Drawing.Color]::FromArgb(194, 248, 253, 254),
[System.Drawing.Color]::FromArgb(245, 252, 255, 255)
)
$blend.Positions = [single[]]@(0.0, 0.58, 1.0)
$brush.InterpolationColors = $blend
$pen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(118, 103, 210, 221), 1.5)
$pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round
$accentBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(150, 99, 216, 225))
$accentPath = [System.Drawing.Drawing2D.GraphicsPath]::new()
$leftDiamond = [System.Drawing.PointF[]]@(
[System.Drawing.PointF]::new(126, 47),
[System.Drawing.PointF]::new(136, 58),
[System.Drawing.PointF]::new(126, 69),
[System.Drawing.PointF]::new(116, 58)
)
$rightDiamond = [System.Drawing.PointF[]]@(
[System.Drawing.PointF]::new(3074, 47),
[System.Drawing.PointF]::new(3084, 58),
[System.Drawing.PointF]::new(3074, 69),
[System.Drawing.PointF]::new(3064, 58)
)
$accentPen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(94, 91, 211, 223), 1.2)
$accentPen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
$accentPen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
$graphics.FillPath($brush, $surface)
$graphics.DrawPath($pen, $topEdge)
$graphics.DrawLine($accentPen, 82, 58, 116, 58)
$graphics.DrawLine($accentPen, 136, 58, 170, 58)
$graphics.DrawLine($accentPen, 3030, 58, 3064, 58)
$graphics.DrawLine($accentPen, 3084, 58, 3118, 58)
$accentPath.AddPolygon($leftDiamond)
$accentPath.AddPolygon($rightDiamond)
$graphics.FillPath($accentBrush, $accentPath)
[System.IO.Directory]::CreateDirectory((Split-Path -Parent $outputPath)) | Out-Null
$bitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Png)
$accentPen.Dispose()
$accentBrush.Dispose()
$accentPath.Dispose()
$pen.Dispose()
$brush.Dispose()
$surface.Dispose()
$topEdge.Dispose()
$graphics.Dispose()
$bitmap.Dispose()
+94 -1
View File
@@ -1,4 +1,4 @@
import { Router, type NextFunction, type Request, type Response } from "express";
import { Router, raw as expressRaw, type NextFunction, type Request, type Response } from "express";
import { existsSync, readFileSync } from "node:fs";
import type { Logger } from "../logger.js";
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
@@ -6,6 +6,7 @@ import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
import type { AdminSessionSummary } from "../server/voice-bridge.js";
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
export interface AdminConnectionRecord {
id: string;
@@ -34,6 +35,7 @@ export interface AdminRouterOptions {
terminateSession?: (id: string) => Promise<boolean>;
version?: string;
logFile?: string;
skinRegistry?: SkinRegistry;
startedAt: number;
}
@@ -120,6 +122,81 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
response.json(options.service.getAdminSettings());
});
router.get("/skins", async (_request, response) => {
response.json({
skins: await options.skinRegistry?.list() ?? [],
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
});
});
router.put("/skins/default", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
try {
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
const id = typeof asRecord(request.body).id === "string" ? (asRecord(request.body).id as string).trim() : "";
const settings = await options.skinRegistry.setDefaultSkin(id);
response.json({ ok: true, defaultSkinId: settings.defaultSkinId });
} catch (error: unknown) {
if (error instanceof SkinRegistryError) {
response.status(error.code === "SKIN_DEFAULT_INVALID" ? 400 : 409).json({ ok: false, code: error.code, message: error.message });
return;
}
sendAdminError(response, error);
}
});
router.put("/skins/:id/enabled", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
try {
const id = typeof request.params.id === "string" ? request.params.id : "";
const body = asRecord(request.body);
if (!options.skinRegistry || typeof body.enabled !== "boolean") throw new SkinRegistryError("A skin and boolean enabled value are required.", "SKIN_ENABLE_INVALID");
const skin = await options.skinRegistry.setEnabled(id, body.enabled);
options.service.database.addAudit(body.enabled ? "ADMIN_SKIN_ENABLED" : "ADMIN_SKIN_DISABLED", { id });
response.json({ ok: true, skin, defaultSkinId: await options.skinRegistry.getDefaultSkinId() });
} catch (error: unknown) {
if (error instanceof SkinRegistryError) {
const status = error.code === "SKIN_NOT_FOUND" ? 404 : error.code === "SKIN_ENABLE_INVALID" ? 400 : 409;
response.status(status).json({ ok: false, code: error.code, message: error.message });
return;
}
sendAdminError(response, error);
}
});
router.put("/skins/:id", requireSameOriginBinary, requireCsrf(options.sessions), expressRaw({ type: "application/octet-stream", limit: "20mb" }), async (request, response) => {
try {
const id = typeof request.params.id === "string" ? request.params.id : "";
if (!options.skinRegistry || !Buffer.isBuffer(request.body)) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
const skin = await options.skinRegistry.save(request.body, id);
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version });
response.status(201).json({ ok: true, skin });
} catch (error: unknown) {
if (error instanceof SkinRegistryError) {
const status = error.code === "SKIN_LIMIT" || error.code === "SKIN_STORAGE_LIMIT" || error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400;
response.status(status).json({ ok: false, code: error.code, message: error.message });
return;
}
sendAdminError(response, error);
}
});
router.delete("/skins/:id", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
const id = typeof request.params.id === "string" ? request.params.id : "";
try {
if (!options.skinRegistry || !await options.skinRegistry.remove(id)) {
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
return;
}
options.service.database.addAudit("ADMIN_SKIN_REMOVED", { id });
response.json({ ok: true });
} catch (error: unknown) {
if (error instanceof SkinRegistryError) {
response.status(error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400).json({ ok: false, code: error.code, message: error.message });
return;
}
sendAdminError(response, error);
}
});
router.get("/sessions", (_request, response) => {
response.json({ sessions: options.getSessionSummaries?.() ?? [] });
});
@@ -327,6 +404,22 @@ function requireSameOrigin(request: Request, response: Response, next: NextFunct
next();
}
function requireSameOriginBinary(request: Request, response: Response, next: NextFunction): void {
if (!request.is("application/octet-stream")) {
response.status(415).json({ ok: false, code: "BINARY_REQUIRED" });
return;
}
const origin = request.header("origin");
const host = request.header("host");
try {
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
} catch {
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
return;
}
next();
}
async function runProbe(
service: AdminService,
response: Response,
+173
View File
@@ -0,0 +1,173 @@
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
const manifest = {
schemaVersion: 1,
id: "sample-skin",
name: "Sample skin",
version: "1.0.0",
author: "WebSpeak test",
license: "MIT",
minAppVersion: "0.2.4",
entry: "skin.css",
content: "content.json",
preview: "assets/preview.png",
};
test("skin registry validates, lists, replaces, serves, and removes packages", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-registry-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
assert.equal(await registry.readArchive("sample-skin"), null);
const firstArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifest))],
["skin.css", Buffer.from(".voice-card { background: url(assets/background.png); }")],
["content.json", Buffer.from(JSON.stringify({ defaultLocale: "en", locales: { en: { home: { title: "Hello" } } } }))],
["assets/background.png", Buffer.from([1, 2, 3, 4])],
["assets/preview.png", Buffer.from([5, 6, 7, 8])],
]);
const first = await registry.save(firstArchive, "sample-skin");
assert.equal(first.id, "sample-skin");
assert.equal(first.previewUrl, "/api/skins/sample-skin/preview");
assert.equal((await registry.list()).length, 1);
assert.deepEqual(await registry.readArchive("sample-skin"), firstArchive);
assert.deepEqual((await registry.readPreview("sample-skin"))?.bytes, Buffer.from([5, 6, 7, 8]));
await registry.setEnabled("sample-skin", false);
assert.equal(await registry.readArchive("sample-skin"), null);
assert.equal(await registry.readPreview("sample-skin"), null);
await registry.setEnabled("sample-skin", true);
const replacement = { ...manifest, version: "2.0.0", content: undefined, preview: undefined };
const secondArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify(replacement))],
["skin.css", Buffer.from(".voice-card { border-radius: 0; }")],
]);
const second = await registry.save(secondArchive, "sample-skin");
assert.equal(second.version, "2.0.0");
assert.equal(second.installedAt, first.installedAt);
assert.equal(await registry.readPreview("sample-skin"), null);
assert.deepEqual(await registry.readArchive("sample-skin"), secondArchive);
assert.equal(await registry.remove("sample-skin"), true);
assert.deepEqual(await registry.list(), []);
assert.equal(await registry.readArchive("sample-skin"), null);
assert.equal(await registry.remove("sample-skin"), false);
});
test("custom skins can be enabled, disabled, and selected as the instance default", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-settings-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const archive = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
["skin.css", Buffer.from("[data-ws-part=\"demo.voice-card\"] { color: teal; }")],
]);
const skin = await registry.save(archive, "sample-skin");
assert.equal(skin.enabled, true);
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
await registry.setDefaultSkin("sample-skin");
assert.equal(await registry.getDefaultSkinId(), "sample-skin");
const disabled = await registry.setEnabled("sample-skin", false);
assert.equal(disabled.enabled, false);
assert.equal(await registry.readArchive("sample-skin"), null);
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
await assert.rejects(registry.setDefaultSkin("sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_DEFAULT_INVALID");
await registry.setEnabled("sample-skin", true);
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
await registry.setDefaultSkin("sample-skin");
assert.equal(await registry.remove("sample-skin"), true);
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
});
test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const goodFiles: Array<[string, Buffer]> = [
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
["skin.css", Buffer.from(".voice-card { color: teal; }")],
];
await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID");
const mismatched = createZip(goodFiles);
mismatched[30] ^= 1;
await assert.rejects(registry.save(mismatched, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ZIP_INVALID");
await writeFile(path.join(directory, "orphan.wskin"), createZip(goodFiles));
assert.equal(await registry.readArchive("orphan"), null);
assert.deepEqual(await registry.list(), []);
});
test("the three bundled skins cannot be replaced or removed through the registry", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-builtins-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
for (const id of ["builtin.light", "builtin.dark", "community.illusia-voice"]) {
await assert.rejects(registry.save(Buffer.alloc(22), id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
await assert.rejects(registry.remove(id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
await assert.rejects(registry.setEnabled(id, false), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
}
});
function createZip(files: Array<[string, Buffer]>): Buffer {
const localRecords: Buffer[] = [];
const centralRecords: Buffer[] = [];
let localOffset = 0;
for (const [name, bytes] of files) {
const filename = Buffer.from(name, "utf8");
const checksum = crc32(bytes);
const local = Buffer.alloc(30 + filename.length + bytes.length);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0, 6);
local.writeUInt16LE(0, 8);
local.writeUInt32LE(checksum, 14);
local.writeUInt32LE(bytes.length, 18);
local.writeUInt32LE(bytes.length, 22);
local.writeUInt16LE(filename.length, 26);
filename.copy(local, 30);
bytes.copy(local, 30 + filename.length);
localRecords.push(local);
const central = Buffer.alloc(46 + filename.length);
central.writeUInt32LE(0x02014b50, 0);
central.writeUInt16LE(0x0314, 4);
central.writeUInt16LE(20, 6);
central.writeUInt16LE(0, 8);
central.writeUInt16LE(0, 10);
central.writeUInt32LE(checksum, 16);
central.writeUInt32LE(bytes.length, 20);
central.writeUInt32LE(bytes.length, 24);
central.writeUInt16LE(filename.length, 28);
central.writeUInt32LE(0x81a40000, 38);
central.writeUInt32LE(localOffset, 42);
filename.copy(central, 46);
centralRecords.push(central);
localOffset += local.length;
}
const centralDirectory = Buffer.concat(centralRecords);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(centralDirectory.length, 12);
end.writeUInt32LE(localOffset, 16);
return Buffer.concat([...localRecords, centralDirectory, end]);
}
function crc32(bytes: Buffer): number {
let crc = 0xffffffff;
for (const byte of bytes) {
crc ^= byte;
for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
}
return (crc ^ 0xffffffff) >>> 0;
}
+464
View File
@@ -0,0 +1,464 @@
import { randomBytes } from "node:crypto";
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { inflateRawSync } from "node:zlib";
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
const MAX_FILE_COUNT = 128;
const MAX_CSS_BYTES = 512 * 1024;
const MAX_CONTENT_BYTES = 256 * 1024;
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
const MAX_FONT_BYTES = 4 * 1024 * 1024;
const MAX_SKINS = 50;
const MAX_TOTAL_ARCHIVES = 200 * 1024 * 1024;
export const BUILTIN_SKIN_IDS = ["builtin.light", "builtin.dark", "community.illusia-voice"] as const;
const BUILTIN_SKIN_ID_SET = new Set<string>(BUILTIN_SKIN_IDS);
const EOCD_SIGNATURE = 0x06054b50;
const CENTRAL_SIGNATURE = 0x02014b50;
const LOCAL_SIGNATURE = 0x04034b50;
export interface SkinCatalogEntry {
id: string;
name: string;
version: string;
author: string;
license: string;
description?: string;
minAppVersion: string;
previewUrl?: string;
previewMimeType?: string;
installedAt: number;
enabled: boolean;
}
export interface SkinRegistrySettings {
defaultSkinId: string;
}
interface SkinArchiveEntry {
path: string;
compressedSize: number;
expandedSize: number;
compression: number;
crc: number;
localOffset: number;
flags: number;
isDirectory: boolean;
unixFileType: number;
}
type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" | "previewMimeType" | "enabled"> & {
entry: string;
content?: string;
preview?: string;
};
export class SkinRegistryError extends Error {
constructor(message: string, readonly code: string) {
super(message);
this.name = "SkinRegistryError";
}
}
export function isBuiltinSkinId(id: string): boolean {
return BUILTIN_SKIN_ID_SET.has(id);
}
export class SkinRegistry {
constructor(private readonly directory: string) {}
async list(): Promise<SkinCatalogEntry[]> {
await mkdir(this.directory, { recursive: true });
const names = await readdir(this.directory);
const entries: SkinCatalogEntry[] = [];
for (const filename of names.filter((item) => item.endsWith(".json"))) {
try {
const value: unknown = JSON.parse(await readFile(path.join(this.directory, filename), "utf8"));
if (!isCatalogEntry(value) || filename !== `${value.id}.json`) continue;
const archiveInfo = await stat(path.join(this.directory, `${value.id}.wskin`)).catch(() => null);
if (!archiveInfo?.isFile() || archiveInfo.size < 22 || archiveInfo.size > MAX_ARCHIVE_BYTES) continue;
entries.push({ ...value, enabled: value.enabled !== false });
} catch {
// Ignore incomplete or stale metadata. The archive itself remains untouched.
}
}
return entries.sort((left, right) => left.name.localeCompare(right.name));
}
async save(bytes: Buffer, expectedId: string): Promise<SkinCatalogEntry> {
if (isBuiltinSkinId(expectedId)) throw new SkinRegistryError("Built-in skins cannot be replaced.", "SKIN_BUILTIN_PROTECTED");
if (!isSafeSkinId(expectedId)) throw new SkinRegistryError("Skin ID is invalid.", "SKIN_ID_INVALID");
const parsed = validateSkinArchive(bytes, expectedId);
await mkdir(this.directory, { recursive: true });
const current = await this.list();
const replacing = current.some((entry) => entry.id === expectedId);
if (!replacing && current.length >= MAX_SKINS) throw new SkinRegistryError("The instance already has the maximum number of skins.", "SKIN_LIMIT");
const archivePaths = await Promise.all(current.map(async (entry) => ({ id: entry.id, size: (await stat(path.join(this.directory, `${entry.id}.wskin`)).catch(() => ({ size: 0 }))).size })));
const totalBytes = archivePaths.reduce((sum, entry) => sum + (entry.id === expectedId ? 0 : entry.size), bytes.byteLength);
if (totalBytes > MAX_TOTAL_ARCHIVES) throw new SkinRegistryError("The total skin storage limit is 200 MiB.", "SKIN_STORAGE_LIMIT");
const previous = current.find((entry) => entry.id === expectedId);
const installedAt = previous?.installedAt ?? Date.now();
const catalog: SkinCatalogEntry = {
...parsed.manifest,
installedAt,
enabled: previous?.enabled ?? true,
...(parsed.previewMime ? { previewUrl: `/api/skins/${expectedId}/preview`, previewMimeType: parsed.previewMime } : {}),
};
const nonce = randomBytes(6).toString("hex");
const archiveTemp = path.join(this.directory, `.${expectedId}.${nonce}.tmp`);
const catalogTemp = path.join(this.directory, `.${expectedId}.${nonce}.json.tmp`);
const previewTemp = path.join(this.directory, `.${expectedId}.${nonce}.preview.tmp`);
try {
await writeFile(archiveTemp, bytes, { flag: "wx", mode: 0o600 });
await writeFile(catalogTemp, JSON.stringify(catalog), { flag: "wx", mode: 0o600 });
if (parsed.previewBytes) await writeFile(previewTemp, parsed.previewBytes, { flag: "wx", mode: 0o600 });
await rename(archiveTemp, path.join(this.directory, `${expectedId}.wskin`));
await rename(catalogTemp, path.join(this.directory, `${expectedId}.json`));
const previewPath = path.join(this.directory, `${expectedId}.preview`);
if (parsed.previewBytes) await rename(previewTemp, previewPath);
else await unlink(previewPath).catch(() => undefined);
} catch (error) {
await Promise.all([archiveTemp, catalogTemp, previewTemp].map((file) => unlink(file).catch(() => undefined)));
throw error;
}
return catalog;
}
async readArchive(id: string): Promise<Buffer | null> {
if (!isSafeSkinId(id)) return null;
if (!(await this.list()).some((entry) => entry.id === id && entry.enabled)) return null;
try { return await readFile(path.join(this.directory, `${id}.wskin`)); }
catch { return null; }
}
async readPreview(id: string): Promise<{ bytes: Buffer; mimeType: string } | null> {
if (!isSafeSkinId(id)) return null;
const catalog = (await this.list()).find((entry) => entry.id === id);
if (!catalog?.enabled || !catalog.previewUrl) return null;
const mimeType = catalog.previewMimeType || "application/octet-stream";
try {
const bytes = await readFile(path.join(this.directory, `${id}.preview`));
return { bytes, mimeType };
} catch { return null; }
}
async remove(id: string): Promise<boolean> {
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be removed.", "SKIN_BUILTIN_PROTECTED");
if (!isSafeSkinId(id)) return false;
const wasDefault = await this.getDefaultSkinId() === id;
const archive = path.join(this.directory, `${id}.wskin`);
const catalog = path.join(this.directory, `${id}.json`);
const preview = path.join(this.directory, `${id}.preview`);
const present = await Promise.all([archive, catalog, preview].map((file) => stat(file).then(() => true).catch(() => false))).then((items) => items.some(Boolean));
if (!present) return false;
await Promise.all([archive, catalog, preview].map((file) => unlink(file).catch((error: unknown) => {
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
})));
if (wasDefault) await this.setDefaultSkin("builtin.light");
return true;
}
async setEnabled(id: string, enabled: boolean): Promise<SkinCatalogEntry> {
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be disabled.", "SKIN_BUILTIN_PROTECTED");
const entry = (await this.list()).find((item) => item.id === id);
if (!entry) throw new SkinRegistryError("The skin was not found.", "SKIN_NOT_FOUND");
const wasDefault = await this.getDefaultSkinId() === id;
const updated = { ...entry, enabled };
await writeAtomicJson(path.join(this.directory, `${id}.json`), updated);
if (!enabled && wasDefault) await this.setDefaultSkin("builtin.light");
return updated;
}
async getDefaultSkinId(): Promise<string> {
try {
const value: unknown = JSON.parse(await readFile(path.join(this.directory, "settings.json"), "utf8"));
const id = value && typeof value === "object" ? (value as Record<string, unknown>).defaultSkinId : null;
if (typeof id !== "string") return "builtin.light";
if (isBuiltinSkinId(id)) return id;
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
return entry ? id : "builtin.light";
} catch {
return "builtin.light";
}
}
async setDefaultSkin(id: string): Promise<SkinRegistrySettings> {
if (!isBuiltinSkinId(id)) {
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
if (!entry) throw new SkinRegistryError("The default skin must be enabled and installed.", "SKIN_DEFAULT_INVALID");
}
await mkdir(this.directory, { recursive: true });
const settings = { defaultSkinId: id };
await writeAtomicJson(path.join(this.directory, "settings.json"), settings);
return settings;
}
}
async function writeAtomicJson(filename: string, value: unknown): Promise<void> {
const temporary = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
try {
await writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
await rename(temporary, filename);
} catch (error) {
await unlink(temporary).catch(() => undefined);
throw error;
}
}
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
const entries = inspectArchive(bytes);
const regularEntries = entries.filter((entry) => !entry.isDirectory);
const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path));
const fileBytes = new Map<string, Buffer>();
for (const entry of regularEntries) {
const packagePath = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path;
if (!isSafePackagePath(packagePath)) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
const content = extractEntry(bytes, entry);
if (content.byteLength !== entry.expandedSize || crc32(content) !== entry.crc) throw new SkinRegistryError("The package has a damaged file entry.", "SKIN_ZIP_INVALID");
if (fileBytes.has(packagePath.toLowerCase())) throw new SkinRegistryError("The package contains duplicate paths.", "SKIN_PATH_DUPLICATE");
fileBytes.set(packagePath, content);
}
const manifestBytes = fileBytes.get("manifest.json");
if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinRegistryError("The package needs a small root-level manifest.json.", "SKIN_MANIFEST_MISSING");
const manifest = parseManifest(manifestBytes);
if (expectedId && manifest.id !== expectedId) throw new SkinRegistryError("The skin ID does not match the upload target.", "SKIN_ID_MISMATCH");
const cssBytes = fileBytes.get(manifest.entry);
if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8.");
let previewBytes: Buffer | undefined;
let previewMime: string | undefined;
for (const [packagePath, data] of fileBytes) {
if (["manifest.json", manifest.entry, manifest.content, manifest.preview].includes(packagePath)) continue;
const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null);
if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED");
if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
}
if (manifest.content) {
const content = fileBytes.get(manifest.content);
if (!content || content.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
decodeUtf8(content, "content.json is not valid UTF-8.");
try { JSON.parse(content.toString("utf8")); }
catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); }
}
if (manifest.preview) {
previewBytes = fileBytes.get(manifest.preview);
previewMime = imageMime(manifest.preview) ?? undefined;
if (!previewBytes || !previewMime || previewBytes.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID");
}
return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) };
}
function inspectArchive(bytes: Buffer): SkinArchiveEntry[] {
if (bytes.byteLength < 22 || bytes.byteLength > MAX_ARCHIVE_BYTES) throw new SkinRegistryError("A skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
let endOffset = -1;
for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) {
if (bytes.readUInt32LE(offset) === EOCD_SIGNATURE) { endOffset = offset; break; }
}
if (endOffset < 0) throw new SkinRegistryError("The upload is not a valid ZIP package.", "SKIN_ZIP_INVALID");
const disk = bytes.readUInt16LE(endOffset + 4);
const centralDisk = bytes.readUInt16LE(endOffset + 6);
const entriesOnDisk = bytes.readUInt16LE(endOffset + 8);
const entryCount = bytes.readUInt16LE(endOffset + 10);
const centralSize = bytes.readUInt32LE(endOffset + 12);
const centralOffset = bytes.readUInt32LE(endOffset + 16);
const commentLength = bytes.readUInt16LE(endOffset + 20);
if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || endOffset + 22 + commentLength !== bytes.byteLength) {
throw new SkinRegistryError("Multi-disk and ZIP64 packages are not supported.", "SKIN_ZIP_FORMAT");
}
if (!entryCount || entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== endOffset) throw new SkinRegistryError("The ZIP directory is invalid or contains too many files.", "SKIN_FILE_COUNT");
const decoder = new TextDecoder("utf-8", { fatal: true });
const entries: SkinArchiveEntry[] = [];
const seenPaths = new Set<string>();
let offset = centralOffset;
let totalExpanded = 0;
for (let index = 0; index < entryCount; index += 1) {
if (offset + 46 > endOffset || bytes.readUInt32LE(offset) !== CENTRAL_SIGNATURE) throw new SkinRegistryError("The ZIP directory entry is invalid.", "SKIN_ZIP_INVALID");
const madeBy = bytes.readUInt16LE(offset + 4);
const flags = bytes.readUInt16LE(offset + 8);
const compression = bytes.readUInt16LE(offset + 10);
const crc = bytes.readUInt32LE(offset + 16);
const compressedSize = bytes.readUInt32LE(offset + 20);
const expandedSize = bytes.readUInt32LE(offset + 24);
const nameLength = bytes.readUInt16LE(offset + 28);
const extraLength = bytes.readUInt16LE(offset + 30);
const fileCommentLength = bytes.readUInt16LE(offset + 32);
const diskStart = bytes.readUInt16LE(offset + 34);
const externalAttributes = bytes.readUInt32LE(offset + 38);
const localOffset = bytes.readUInt32LE(offset + 42);
const recordEnd = offset + 46 + nameLength + extraLength + fileCommentLength;
if (recordEnd > endOffset || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) {
throw new SkinRegistryError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT");
}
let entryPath: string;
try { entryPath = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); }
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
if (!(flags & 0x800) && /[^\x00-\x7f]/.test(entryPath)) throw new SkinRegistryError("Non-ASCII ZIP filenames must be encoded as UTF-8.", "SKIN_PATH_INVALID");
if (!isSafePackagePath(entryPath, entryPath.endsWith("/"))) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
const normalizedPath = entryPath.toLowerCase();
if (seenPaths.has(normalizedPath)) throw new SkinRegistryError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE");
seenPaths.add(normalizedPath);
const unixFileType = madeBy >> 8 === 3 ? (externalAttributes >>> 16) & 0xf000 : 0;
if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinRegistryError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE");
const isDirectory = entryPath.endsWith("/");
if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinRegistryError("ZIP file type does not match its path.", "SKIN_FILE_TYPE");
if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinRegistryError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID");
if (compression === 0 && compressedSize !== expandedSize) throw new SkinRegistryError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID");
if (!isDirectory) {
totalExpanded += expandedSize;
if (totalExpanded > MAX_EXPANDED_BYTES) throw new SkinRegistryError("The expanded package exceeds 50 MiB.", "SKIN_EXPANDED_SIZE");
if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinRegistryError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO");
}
entries.push({ path: entryPath, compressedSize, expandedSize, compression, crc, localOffset, flags, isDirectory, unixFileType });
offset = recordEnd;
}
if (offset !== centralOffset + centralSize) throw new SkinRegistryError("The ZIP directory length is inconsistent.", "SKIN_ZIP_INVALID");
validateLocalEntries(bytes, entries, centralOffset, decoder);
return entries;
}
function validateLocalEntries(bytes: Buffer, entries: SkinArchiveEntry[], centralOffset: number, decoder: TextDecoder): void {
const spans: Array<{ start: number; end: number }> = [];
for (const entry of entries) {
const offset = entry.localOffset;
if (offset + 30 > centralOffset || bytes.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
const flags = bytes.readUInt16LE(offset + 6);
const compression = bytes.readUInt16LE(offset + 8);
const crc = bytes.readUInt32LE(offset + 14);
const compressedSize = bytes.readUInt32LE(offset + 18);
const expandedSize = bytes.readUInt32LE(offset + 22);
const nameLength = bytes.readUInt16LE(offset + 26);
const extraLength = bytes.readUInt16LE(offset + 28);
const headerEnd = offset + 30 + nameLength + extraLength;
if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) {
throw new SkinRegistryError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID");
}
let localPath: string;
try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); }
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
if (localPath !== entry.path) throw new SkinRegistryError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID");
const end = headerEnd + entry.compressedSize;
if (end > centralOffset) throw new SkinRegistryError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID");
spans.push({ start: offset, end });
}
spans.sort((left, right) => left.start - right.start);
for (let index = 1; index < spans.length; index += 1) {
if (spans[index].start < spans[index - 1].end) throw new SkinRegistryError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID");
}
}
function extractEntry(archive: Buffer, entry: SkinArchiveEntry): Buffer {
const offset = entry.localOffset;
if (offset + 30 > archive.byteLength || archive.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
const flags = archive.readUInt16LE(offset + 6);
const compression = archive.readUInt16LE(offset + 8);
const nameLength = archive.readUInt16LE(offset + 26);
const extraLength = archive.readUInt16LE(offset + 28);
if (flags !== entry.flags || compression !== entry.compression) throw new SkinRegistryError("ZIP headers disagree about file compression.", "SKIN_ZIP_INVALID");
const dataStart = offset + 30 + nameLength + extraLength;
const dataEnd = dataStart + entry.compressedSize;
if (dataEnd > archive.byteLength) throw new SkinRegistryError("A ZIP entry extends past the archive.", "SKIN_ZIP_INVALID");
const compressed = archive.subarray(dataStart, dataEnd);
if (entry.compression === 0) return Buffer.from(compressed);
try { return inflateRawSync(compressed, { maxOutputLength: entry.expandedSize + 1 }); }
catch { throw new SkinRegistryError("A ZIP entry could not be safely decompressed.", "SKIN_ZIP_INVALID"); }
}
function parseManifest(bytes: Buffer): ParsedSkinManifest {
let raw: unknown;
try { raw = JSON.parse(decodeUtf8(bytes, "manifest.json is not valid UTF-8.")); }
catch { throw new SkinRegistryError("manifest.json must contain valid JSON.", "SKIN_MANIFEST_INVALID"); }
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
const value = raw as Record<string, unknown>;
const read = (key: string, max: number): string => {
const item = value[key];
if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
return item.trim();
};
const id = read("id", 80);
if (value.schemaVersion !== 1 || !isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
const version = read("version", 32);
const minAppVersion = read("minAppVersion", 32);
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 content = readOptional("content", 120);
const preview = readOptional("preview", 120);
for (const candidate of [entry, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
if (new Set(["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase())).size !== 2 + Number(Boolean(content)) + Number(Boolean(preview))) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
const description = readOptional("description", 400);
return { id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
}
function singleRootPrefix(paths: string[]): string {
if (!paths.length) return "";
const firstSlash = paths[0].indexOf("/");
if (firstSlash < 1) return "";
const prefix = paths[0].slice(0, firstSlash + 1);
return paths.every((item) => item.startsWith(prefix)) ? prefix : "";
}
function isSafePackagePath(value: string, allowDirectory = false): boolean {
const candidate = allowDirectory ? value.slice(0, -1) : value;
return Boolean(candidate) && !candidate.startsWith("/") && !candidate.includes("\\") && !candidate.includes("\0") && !/^[a-z]:/i.test(candidate)
&& candidate.split("/").every((part) => Boolean(part) && part !== "." && part !== ".." && !part.includes(":"));
}
function isSafeSkinId(value: unknown): value is string {
return typeof value === "string" && value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value) && !value.startsWith("builtin.");
}
function imageMime(filename: string): string | null {
switch (path.extname(filename).toLowerCase()) {
case ".png": return "image/png";
case ".jpg": case ".jpeg": return "image/jpeg";
case ".webp": return "image/webp";
case ".avif": return "image/avif";
case ".gif": return "image/gif";
default: return null;
}
}
function decodeUtf8(bytes: Buffer, message: string): string {
try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
catch { throw new SkinRegistryError(message, "SKIN_ENCODING_INVALID"); }
}
function isCatalogEntry(value: unknown): value is SkinCatalogEntry {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const item = value as Record<string, unknown>;
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
if (!isSafeSkinId(item.id) || !isShortText(item.name, 80) || !isShortText(item.author, 80) || !isShortText(item.license, 80)) return false;
if (typeof item.version !== "string" || !semver.test(item.version) || typeof item.minAppVersion !== "string" || !semver.test(item.minAppVersion)) return false;
if (!Number.isSafeInteger(item.installedAt) || (item.installedAt as number) < 0) return false;
if (item.enabled !== undefined && typeof item.enabled !== "boolean") return false;
if (item.description !== undefined && (typeof item.description !== "string" || item.description.length > 400)) return false;
const hasPreview = item.previewUrl !== undefined || item.previewMimeType !== undefined;
return !hasPreview || (item.previewUrl === `/api/skins/${item.id}/preview` && ["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"].includes(String(item.previewMimeType)));
}
function isShortText(value: unknown, limit: number): value is string {
return typeof value === "string" && value.trim().length > 0 && value.length <= limit;
}
const crcTable = (() => {
const table = new Uint32Array(256);
for (let index = 0; index < table.length; index += 1) {
let value = index;
for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
table[index] = value >>> 0;
}
return table;
})();
function crc32(bytes: Buffer): number {
let value = 0xffffffff;
for (const byte of bytes) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
return (value ^ 0xffffffff) >>> 0;
}
+2
View File
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
import { SkinRegistry } from "./admin/skin-registry.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
@@ -67,6 +68,7 @@ async function main() {
accelerationName: () => adminService.getAccelerationRelayName(),
},
adminService,
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
logger,
nextVisitorNumber: () => database.nextVisitorNumber(),
visitorCount: () => database.getVisitorCount(),
+41 -3
View File
@@ -13,6 +13,8 @@ import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
import { identityFromString } from "@echosixhiya/teamspeak-client";
import { JoinRateLimiter } from "./join-rate-limit.js";
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
import type { SkinRegistry } from "../admin/skin-registry.js";
import { resolveVisitorTotal } from "./visitor-count.js";
export interface WebServerOptions {
port: number;
@@ -22,6 +24,7 @@ export interface WebServerOptions {
certDir?: string; // path to cert.pem + key.pem for HTTPS
voiceBridgeOptions: VoiceBridgeOptions;
adminService: AdminService;
skinRegistry?: SkinRegistry;
logger: Logger;
nextVisitorNumber?: () => number;
visitorCount?: () => number;
@@ -77,11 +80,10 @@ export function createWebServer(options: WebServerOptions): WebServer {
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor number could not be assigned");
}
}
let visitorTotal: number | null = null;
let visitorTotal = resolveVisitorTotal(visitorNumber, null);
if (options.visitorCount) {
try {
const count = options.visitorCount();
if (Number.isSafeInteger(count) && count >= 0) visitorTotal = count;
visitorTotal = resolveVisitorTotal(visitorNumber, options.visitorCount());
} catch (error: unknown) {
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor total could not be read");
}
@@ -97,6 +99,41 @@ export function createWebServer(options: WebServerOptions): WebServer {
});
});
app.get("/api/skins", async (_request, response) => {
response.setHeader("Cache-Control", "no-cache");
response.json({
skins: await options.skinRegistry?.list() ?? [],
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
});
});
app.get("/api/skins/:id/package", async (request, response) => {
const id = typeof request.params.id === "string" ? request.params.id : "";
const archive = await options.skinRegistry?.readArchive(id);
if (!archive) {
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
return;
}
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", `attachment; filename="${id}.wskin"`);
response.setHeader("X-Content-Type-Options", "nosniff");
response.send(archive);
});
app.get("/api/skins/:id/preview", async (request, response) => {
const id = typeof request.params.id === "string" ? request.params.id : "";
const preview = await options.skinRegistry?.readPreview(id);
if (!preview) {
response.status(404).end();
return;
}
response.setHeader("Cache-Control", "public, max-age=300");
response.setHeader("Content-Type", preview.mimeType);
response.setHeader("X-Content-Type-Options", "nosniff");
response.send(preview.bytes);
});
app.post("/api/join-ticket", async (request, response) => {
response.setHeader("Cache-Control", "no-store");
if (!request.is("application/json") || !isSameOrigin(request)) {
@@ -194,6 +231,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
getCreatedSessions: () => voiceBridge.getCreatedCount(),
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
terminateSession: (id) => voiceBridge.terminateSession(id),
skinRegistry: options.skinRegistry,
version: options.version,
logFile: options.logFile,
startedAt,
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveVisitorTotal } from "./visitor-count.js";
test("visitor total never disappears or falls below the current visitor ordinal", () => {
assert.equal(resolveVisitorTotal(3, 0), 3);
assert.equal(resolveVisitorTotal(3, 5), 5);
assert.equal(resolveVisitorTotal(3, undefined), 3);
assert.equal(resolveVisitorTotal(null, 8), 8);
assert.equal(resolveVisitorTotal(null, -1), null);
assert.equal(resolveVisitorTotal(0, 2), 2);
});
+11
View File
@@ -0,0 +1,11 @@
export function resolveVisitorTotal(visitorNumber: number | null, recordedTotal: unknown): number | null {
const currentVisitor = Number.isSafeInteger(visitorNumber) && Number(visitorNumber) > 0
? Number(visitorNumber)
: null;
const total = typeof recordedTotal === "number" && Number.isSafeInteger(recordedTotal) && recordedTotal >= 0
? recordedTotal
: null;
if (total === null) return currentVisitor;
return Math.max(total, currentVisitor ?? 0);
}
+55 -4
View File
@@ -7,7 +7,11 @@
"name": "webspeak-webclient-frontend",
"dependencies": {
"@sapphi-red/web-noise-suppressor": "^0.4.0",
"fflate": "^0.8.3",
"pinia": "^3.0.2",
"postcss": "^8.5.28",
"postcss-selector-parser": "^7.1.6",
"postcss-value-parser": "^4.2.0",
"vue": "^3.5.13",
"vue-router": "^4.5.1"
},
@@ -1139,6 +1143,18 @@
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/cssesc": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
"integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
"license": "MIT",
"bin": {
"cssesc": "bin/cssesc"
},
"engines": {
"node": ">=4"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -1230,6 +1246,12 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -1354,6 +1376,7 @@
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -1383,9 +1406,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
"integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
"funding": [
{
"type": "opencollective",
@@ -1402,7 +1425,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.17",
"nanoid": "^3.3.18",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -1410,6 +1433,25 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/postcss-selector-parser": {
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz",
"integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==",
"license": "MIT",
"dependencies": {
"cssesc": "^3.0.0",
"util-deprecate": "^1.0.2"
},
"engines": {
"node": ">=4"
}
},
"node_modules/postcss-value-parser": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"license": "MIT"
},
"node_modules/rfdc": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
@@ -1514,6 +1556,7 @@
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -1522,12 +1565,19 @@
"node": ">=14.17"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/vite": {
"version": "6.4.3",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@@ -1609,6 +1659,7 @@
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.34.tgz",
"integrity": "sha512-WdLBG9gm02OgJIG9axd5Hpx0TFLdzVgfG2evFFu8Rur5O/IoGc5cMjnjh3tPL6GnRGsYvUhBSKVPYVcxRKpMCA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.34",
"@vue/compiler-sfc": "3.5.34",
+4
View File
@@ -9,7 +9,11 @@
},
"dependencies": {
"@sapphi-red/web-noise-suppressor": "^0.4.0",
"fflate": "^0.8.3",
"pinia": "^3.0.2",
"postcss": "^8.5.28",
"postcss-selector-parser": "^7.1.6",
"postcss-value-parser": "^4.2.0",
"vue": "^3.5.13",
"vue-router": "^4.5.1"
},
Binary file not shown.

After

Width:  |  Height:  |  Size: 1014 KiB

Binary file not shown.
+21 -17
View File
@@ -3,9 +3,11 @@
<button
type="button"
class="language-trigger"
data-ws-part="language.trigger"
:aria-label="menuLabel"
aria-haspopup="listbox"
:aria-expanded="open"
:data-ws-state="open ? 'open' : 'closed'"
:aria-controls="menuId"
@click.stop="toggle"
>
@@ -14,12 +16,14 @@
<Icon name="chevron-down" :size="13" />
</button>
<div v-if="open" :id="menuId" class="language-dropdown" role="listbox" :aria-label="menuLabel" @click.stop>
<div v-if="open" :id="menuId" class="language-dropdown" data-ws-part="language.menu" role="listbox" :aria-label="menuLabel" @click.stop>
<button
v-for="option in options"
:key="option.value"
type="button"
class="language-option"
data-ws-part="language.option"
:data-ws-language="option.value"
:class="{ selected: modelValue === option.value }"
role="option"
:aria-selected="modelValue === option.value"
@@ -239,40 +243,40 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
to { opacity: 1; transform: translateY(0) scale(1); }
}
:global(html[data-theme="dark"]) .language-trigger,
:global(:root[data-theme="dark"]) .language-trigger {
:global(html[data-theme="dark"] .admin-root) .language-trigger,
:global(:root[data-theme="dark"] .admin-root) .language-trigger {
color: #a9d9d1;
background: #203531;
border-color: #38564f;
}
:global(html[data-theme="dark"]) .language-trigger:hover,
:global(html[data-theme="dark"]) .language-switcher.open .language-trigger,
:global(:root[data-theme="dark"]) .language-trigger:hover,
:global(:root[data-theme="dark"]) .language-switcher.open .language-trigger {
:global(html[data-theme="dark"] .admin-root) .language-trigger:hover,
:global(html[data-theme="dark"] .admin-root) .language-switcher.open .language-trigger,
:global(:root[data-theme="dark"] .admin-root) .language-trigger:hover,
:global(:root[data-theme="dark"] .admin-root) .language-switcher.open .language-trigger {
color: #10201d;
background: #69d2c7;
border-color: #69d2c7;
}
:global(html[data-theme="dark"]) .language-dropdown,
:global(:root[data-theme="dark"]) .language-dropdown {
:global(html[data-theme="dark"] .admin-root) .language-dropdown,
:global(:root[data-theme="dark"] .admin-root) .language-dropdown {
background: #172321;
border-color: #30413d;
box-shadow: 0 16px 36px rgba(0, 0, 0, .32);
}
:global(html[data-theme="dark"]) .language-option,
:global(:root[data-theme="dark"]) .language-option {
:global(html[data-theme="dark"] .admin-root) .language-option,
:global(:root[data-theme="dark"] .admin-root) .language-option {
color: #d7e7e3;
}
:global(html[data-theme="dark"]) .language-option:hover,
:global(html[data-theme="dark"]) .language-option:focus-visible,
:global(html[data-theme="dark"]) .language-option.selected,
:global(:root[data-theme="dark"]) .language-option:hover,
:global(:root[data-theme="dark"]) .language-option:focus-visible,
:global(:root[data-theme="dark"]) .language-option.selected {
:global(html[data-theme="dark"] .admin-root) .language-option:hover,
:global(html[data-theme="dark"] .admin-root) .language-option:focus-visible,
:global(html[data-theme="dark"] .admin-root) .language-option.selected,
:global(:root[data-theme="dark"] .admin-root) .language-option:hover,
:global(:root[data-theme="dark"] .admin-root) .language-option:focus-visible,
:global(:root[data-theme="dark"] .admin-root) .language-option.selected {
color: #69d2c7;
background: #203531;
border-color: #38564f;
+211
View File
@@ -0,0 +1,211 @@
<template>
<div ref="root" class="skin-switcher" :class="{ open }" @keydown.esc="close">
<button
type="button"
class="skin-trigger"
data-ws-part="skin.trigger"
:aria-label="menuLabel"
:title="`${menuLabel}: ${selectedOption.label}`"
aria-haspopup="listbox"
:aria-expanded="open"
:data-ws-state="open ? 'open' : 'closed'"
:aria-controls="menuId"
@click.stop="toggle"
>
<Icon :name="selectedOption.icon || 'compass'" :size="15" />
<span>{{ menuLabel }}</span>
<Icon name="chevron-down" :size="12" />
</button>
<div v-if="open" :id="menuId" class="skin-dropdown" data-ws-part="skin.menu" role="listbox" :aria-label="menuLabel" @click.stop>
<button
v-for="option in options"
:key="option.value"
type="button"
class="skin-option"
data-ws-part="skin.option"
:data-ws-skin-id="option.value"
:class="{ selected: modelValue === option.value }"
role="option"
:aria-selected="modelValue === option.value"
@click="select(option.value)"
>
<Icon :name="option.icon || 'compass'" :size="16" />
<span>{{ option.label }}</span>
<Icon v-if="modelValue === option.value" name="check" :size="14" />
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import Icon from "./Icon.vue";
export interface SkinOption {
value: string;
label: string;
icon?: string;
}
const props = defineProps<{
modelValue: string;
menuLabel: string;
options: SkinOption[];
}>();
const emit = defineEmits<{
"update:modelValue": [value: string];
change: [value: string];
}>();
const options = computed(() => props.options);
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0]);
const root = ref<HTMLElement | null>(null);
const open = ref(false);
const menuId = `skin-menu-${Math.random().toString(36).slice(2, 9)}`;
function toggle() { open.value = !open.value; }
function close() { open.value = false; }
function select(value: string) {
emit("update:modelValue", value);
emit("change", value);
close();
}
function onDocumentPointerDown(event: PointerEvent) {
if (root.value && !root.value.contains(event.target as Node)) close();
}
onMounted(() => document.addEventListener("pointerdown", onDocumentPointerDown));
onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerDown));
</script>
<style scoped>
.skin-switcher {
position: relative;
z-index: 20;
flex: 0 0 auto;
color: var(--text-muted);
}
.skin-trigger {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 5px;
min-width: 34px;
min-height: 32px;
padding: 0 8px;
color: #08766f;
background: rgba(250, 254, 255, .94);
border: 1px solid #c8e6e1;
border-radius: 8px;
font: inherit;
font-size: 10px;
font-weight: 700;
white-space: nowrap;
cursor: pointer;
box-shadow: 0 4px 12px rgba(8, 126, 134, .08);
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
}
.skin-trigger:hover,
.skin-switcher.open .skin-trigger {
color: #056e76;
background: #edfafa;
border-color: #8fd7d9;
box-shadow: 0 6px 16px rgba(30, 170, 184, .14);
}
.skin-trigger > .ui-icon:last-child { margin-left: 1px; }
.skin-dropdown {
position: absolute;
top: calc(100% + 7px);
right: 0;
display: grid;
gap: 3px;
min-width: 176px;
padding: 6px;
color: #123849;
background: linear-gradient(145deg, rgba(250, 255, 255, .99), rgba(232, 249, 250, .98));
border: 1px solid rgba(104, 196, 211, .58);
border-radius: 11px;
box-shadow: 0 18px 42px rgba(29, 115, 139, .2), inset 0 1px 0 rgba(255, 255, 255, .96);
backdrop-filter: blur(18px) saturate(1.12);
}
.skin-option {
display: flex;
align-items: center;
gap: 9px;
min-height: 36px;
padding: 0 9px;
color: #123849;
background: linear-gradient(112deg, rgba(255, 255, 255, .96), rgba(225, 250, 249, .96), rgba(188, 241, 237, .94), rgba(255, 255, 255, .96));
background-size: 240% 100%;
border: 1px solid rgba(139, 218, 216, .46);
border-radius: 7px;
font: inherit;
font-size: 11px;
text-align: left;
cursor: pointer;
animation: skin-option-gradient 8s ease-in-out infinite alternate;
transition: color .18s, border-color .18s, box-shadow .18s, background-position .4s ease;
}
.skin-option > .ui-icon:first-child { color: #64858a; }
.skin-option > .ui-icon:last-child { margin-left: auto; color: #087e86; }
.skin-option:hover,
.skin-option:focus-visible {
color: #087e86;
border-color: rgba(57, 195, 193, .74);
background-position: 100% 50%;
box-shadow: 0 4px 13px rgba(43, 179, 181, .16), inset 0 0 0 1px rgba(255, 255, 255, .84);
}
.skin-option.selected {
color: #056f73;
border-color: rgba(44, 183, 181, .78);
background-image: linear-gradient(112deg, #faffff 0%, #c8f5f1 36%, #82e2dc 70%, #d9fbf8 100%);
background-position: 100% 50%;
box-shadow: 0 5px 16px rgba(37, 170, 171, .22), inset 0 0 0 1px rgba(255, 255, 255, .94), inset 0 -1px 0 rgba(31, 164, 163, .12);
}
.skin-option.selected > .ui-icon:first-child,
.skin-option.selected > .ui-icon:last-child { color: #087e86; }
@keyframes skin-option-gradient {
from { background-position: 0% 50%; }
to { background-position: 100% 50%; }
}
@media (prefers-reduced-motion: reduce) {
.skin-option { animation: none; }
}
@media (max-width: 520px) {
.skin-trigger { min-height: 36px; }
.skin-dropdown { min-width: 190px; }
}
.skin-switcher.mobile-skin-switcher .skin-trigger {
width: 100%;
min-height: 44px;
justify-content: flex-start;
padding-inline: 12px;
font-size: 12px;
}
@media (max-width: 420px) {
.skin-switcher.join-skin-switcher .skin-trigger {
width: 28px;
min-width: 28px;
min-height: 28px;
padding: 0;
}
.skin-switcher.join-skin-switcher .skin-trigger > span,
.skin-switcher.join-skin-switcher .skin-trigger > .ui-icon:last-child { display: none; }
}
</style>
@@ -0,0 +1,209 @@
import { computed, ref, watch, type Ref } from "vue";
interface UseWebClientAudioControlsOptions {
settingsOpen: Ref<boolean>;
microphoneMuted: Readonly<Ref<boolean>>;
inputVolume: Readonly<Ref<number>>;
voxThreshold: Readonly<Ref<number>>;
notificationVolume: Readonly<Ref<number>>;
micLevel: Readonly<Ref<number>>;
microphoneTestActive: Readonly<Ref<boolean>>;
accompanimentActive: Readonly<Ref<boolean>>;
accompanimentErrorCode: Readonly<Ref<string>>;
whisperTargetIds: Set<number>;
prepareInputDevices: () => Promise<void>;
setInputVolume: (value: number) => void;
setNoiseSuppressionEnabled: (enabled: boolean) => Promise<void>;
setOutputVolume: (value: number) => void;
setVoxThreshold: (value: number) => void;
setNotificationVolume: (value: number) => void;
setInputDevice: (deviceId: string) => Promise<void>;
setOutputDevice: (deviceId: string) => Promise<void>;
setMicrophoneMuted: (muted: boolean) => void;
startMicrophoneTest: () => Promise<void>;
stopMicrophoneTest: () => void;
startAccompaniment: () => Promise<void>;
stopAccompaniment: () => Promise<void>;
setWhisperActive: (active: boolean) => void;
localizedMessage: (message: string) => string;
showToast: (message: string) => void;
t: (key: string) => string;
}
export function useWebClientAudioControls({
settingsOpen,
microphoneMuted,
inputVolume,
voxThreshold,
notificationVolume,
micLevel,
microphoneTestActive,
accompanimentActive,
accompanimentErrorCode,
whisperTargetIds,
prepareInputDevices,
setInputVolume,
setNoiseSuppressionEnabled,
setOutputVolume,
setVoxThreshold,
setNotificationVolume,
setInputDevice,
setOutputDevice,
setMicrophoneMuted,
startMicrophoneTest,
stopMicrophoneTest,
startAccompaniment,
stopAccompaniment,
setWhisperActive,
localizedMessage,
showToast,
t,
}: UseWebClientAudioControlsOptions) {
const settingsError = ref("");
const whisperPttActive = ref(false);
const micMeterBars = computed(() => Math.round(micLevel.value * 24));
function microphoneErrorMessage(error: unknown, fallback = "请检查浏览器权限"): string {
const name = error instanceof DOMException ? error.name : "";
const reasons: Record<string, string> = {
NotAllowedError: "浏览器未授予麦克风权限",
NotFoundError: "未找到可用的麦克风",
NotReadableError: "麦克风可能正被其他程序占用",
OverconstrainedError: "所选麦克风当前不可用",
SecurityError: "浏览器阻止了麦克风访问",
};
return `麦克风访问失败:${reasons[name] ?? fallback}`;
}
function onInputVolume(event: Event): void {
setInputVolume(Number((event.target as HTMLInputElement).value) / 100);
}
function onNoiseSuppressionToggle(event: Event): void {
void setNoiseSuppressionEnabled((event.target as HTMLInputElement).checked);
}
function onOutputVolume(event: Event): void {
setOutputVolume(Number((event.target as HTMLInputElement).value) / 100);
}
function onVoxThreshold(event: Event): void {
setVoxThreshold(Number((event.target as HTMLInputElement).value) / 1000);
}
function onNotificationVolume(event: Event): void {
setNotificationVolume(Number((event.target as HTMLInputElement).value) / 100);
}
async function onInputDeviceChange(event: Event): Promise<void> {
settingsError.value = "";
try {
await setInputDevice((event.target as HTMLSelectElement).value);
} catch (error: unknown) {
settingsError.value = microphoneErrorMessage(error, "无法切换麦克风");
}
}
async function onOutputDeviceChange(event: Event): Promise<void> {
settingsError.value = "";
try {
await setOutputDevice((event.target as HTMLSelectElement).value);
} catch (error: unknown) {
settingsError.value = localizedMessage(error instanceof Error ? error.message : "无法切换扬声器");
}
}
async function toggleMicTest(): Promise<void> {
settingsError.value = "";
try {
if (microphoneTestActive.value) stopMicrophoneTest();
else await startMicrophoneTest();
} catch (error: unknown) {
settingsError.value = microphoneErrorMessage(error);
}
}
function meterBarHeight(index: number): number {
if (!microphoneTestActive.value) return 5;
const intensity = Math.max(0, micLevel.value - (index / 24) * 0.65);
return 5 + Math.round(intensity * 34);
}
function toggleMicrophone(): void {
setMicrophoneMuted(!microphoneMuted.value);
showToast(t(microphoneMuted.value ? "microphoneMuted" : "microphoneActive"));
}
async function toggleAccompaniment(): Promise<void> {
try {
if (accompanimentActive.value) {
await stopAccompaniment();
showToast(t("accompanimentStopped"));
return;
}
await startAccompaniment();
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
} catch {
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
? "accompanimentNeedsWebRtc"
: accompanimentErrorCode.value === "noAudio"
? "accompanimentNoAudio"
: accompanimentErrorCode.value === "unsupported"
? "accompanimentUnsupported"
: "accompanimentPermissionDenied";
showToast(t(messageKey));
}
}
function onWhisperPttDown(event: PointerEvent): void {
if (!whisperTargetIds.size) return;
const target = event.currentTarget as HTMLElement | null;
if (target?.setPointerCapture && !target.hasPointerCapture(event.pointerId)) target.setPointerCapture(event.pointerId);
whisperPttActive.value = true;
setWhisperActive(true);
}
function onWhisperPttUp(event: PointerEvent): void {
const target = event.currentTarget as HTMLElement | null;
if (target?.releasePointerCapture && target.hasPointerCapture(event.pointerId)) target.releasePointerCapture(event.pointerId);
stopWhisperTalk();
}
function stopWhisperTalk(): void {
if (!whisperPttActive.value) return;
whisperPttActive.value = false;
setWhisperActive(false);
}
watch(settingsOpen, (open) => {
if (open) {
settingsError.value = "";
prepareInputDevices().catch((error: unknown) => {
settingsError.value = microphoneErrorMessage(error);
});
} else {
stopMicrophoneTest();
}
});
return {
settingsError,
whisperPttActive,
micMeterBars,
onInputVolume,
onNoiseSuppressionToggle,
onOutputVolume,
onVoxThreshold,
onNotificationVolume,
onInputDeviceChange,
onOutputDeviceChange,
toggleMicTest,
microphoneErrorMessage,
meterBarHeight,
toggleMicrophone,
toggleAccompaniment,
onWhisperPttDown,
onWhisperPttUp,
stopWhisperTalk,
};
}
+155
View File
@@ -0,0 +1,155 @@
import { computed, watch, type Ref } from "vue";
import type { ChannelInfo, ChannelMember } from "./useVoiceWebSocket.js";
export interface TreeChannel extends ChannelInfo {
depth: number;
members: ChannelMember[];
}
interface UseWebClientChannelsOptions {
channels: ChannelInfo[];
members: ChannelMember[];
clientId: Readonly<Ref<number>>;
selectedChannelId: Ref<string>;
channelName: Ref<string>;
memberQuery: Ref<string>;
whisperTargetIds: Set<number>;
t: (key: string) => string;
}
export function useWebClientChannels({
channels,
members,
clientId,
selectedChannelId,
channelName,
memberQuery,
whisperTargetIds,
t,
}: UseWebClientChannelsOptions) {
const channelTree = computed<TreeChannel[]>(() => {
const source = [...channels];
const sourceIndex = new Map(source.map((item, index) => [item.id, index]));
const enriched = source.map((item) => ({
...item,
members: (item.members ?? []).map((member) => ({ ...member, isSelf: member.id === clientId.value })),
}));
const byId = new Map(enriched.map((item) => [item.id, item]));
const depthCache = new Map<string, number>();
function depthOf(item: ChannelInfo, visiting = new Set<string>()): number {
if (depthCache.has(item.id)) return depthCache.get(item.id)!;
if (!item.parentID || item.parentID === "0" || visiting.has(item.id)) return 0;
const parent = byId.get(item.parentID);
const depth = parent ? depthOf(parent, new Set(visiting).add(item.id)) + 1 : 0;
depthCache.set(item.id, depth);
return depth;
}
const childrenByParent = new Map<string, TreeChannel[]>();
for (const item of enriched) {
const treeChannel = { ...item, depth: depthOf(item) };
const siblings = childrenByParent.get(treeChannel.parentID) ?? [];
siblings.push(treeChannel);
childrenByParent.set(treeChannel.parentID, siblings);
}
function orderSiblings(siblings: TreeChannel[]): TreeChannel[] {
const bySiblingId = new Map(siblings.map((item) => [item.id, item]));
const successors = new Map<string, TreeChannel[]>();
const roots: TreeChannel[] = [];
const sourceOrder = (left: TreeChannel, right: TreeChannel) =>
(sourceIndex.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (sourceIndex.get(right.id) ?? Number.MAX_SAFE_INTEGER);
for (const item of siblings) {
const predecessor = item.order && item.order !== "0" && bySiblingId.has(item.order) ? item.order : "";
if (!predecessor) roots.push(item);
else successors.set(predecessor, [...(successors.get(predecessor) ?? []), item]);
}
roots.sort(sourceOrder);
for (const items of successors.values()) items.sort(sourceOrder);
const ordered: TreeChannel[] = [];
const visited = new Set<string>();
const append = (item: TreeChannel) => {
if (visited.has(item.id)) return;
visited.add(item.id);
ordered.push(item);
for (const successor of successors.get(item.id) ?? []) append(successor);
};
for (const root of roots) append(root);
for (const item of [...siblings].sort(sourceOrder)) append(item);
return ordered;
}
const orderedTree: TreeChannel[] = [];
const visit = (parentID: string) => {
for (const treeChannel of orderSiblings(childrenByParent.get(parentID) ?? [])) {
orderedTree.push(treeChannel);
visit(treeChannel.id);
}
};
visit("0");
for (const item of enriched) {
if (!orderedTree.some((treeChannel) => treeChannel.id === item.id)) {
orderedTree.push({ ...item, depth: depthOf(item) });
visit(item.id);
}
}
return orderedTree;
});
const currentChannel = computed<TreeChannel | undefined>(() => {
const explicitlySelected = channelTree.value.find((item) => item.id === selectedChannelId.value);
if (explicitlySelected) return explicitlySelected;
const fromSelf = channelTree.value.find((item) => item.members.some((member) => member.id === clientId.value));
if (fromSelf) return fromSelf;
return channelTree.value.find((item) => item.name === channelName.value) ?? channelTree.value[0];
});
const currentChannelName = computed(() => (currentChannel.value?.name ?? channelName.value) || t("voiceLobby"));
const currentChannelDescription = computed(() => currentChannel.value?.description ?? "");
const currentMembers = computed<ChannelMember[]>(() => {
const source = currentChannel.value ? currentChannel.value.members : members;
return source.map((member) => ({ ...member, isSelf: member.isSelf || member.id === clientId.value }));
});
const memberChannels = computed<TreeChannel[]>(() => {
if (channelTree.value.length) return channelTree.value;
return [{
id: "__current__",
parentID: "0",
name: currentChannelName.value,
description: currentChannelDescription.value,
members: currentMembers.value,
depth: 0,
}];
});
const filteredMemberChannels = computed(() => {
const search = memberQuery.value.trim().toLowerCase();
if (!search) return memberChannels.value;
return memberChannels.value.filter((item) => item.name.toLowerCase().includes(search)
|| item.members.some((member) => member.nickname.toLowerCase().includes(search)));
});
const whisperTargets = computed(() => [...whisperTargetIds]
.map((id) => members.find((member) => member.id === id))
.filter((member): member is ChannelMember => Boolean(member)));
watch(channelTree, (list) => {
if (!selectedChannelId.value && list[0]) {
selectedChannelId.value = list.find((item) => item.name === channelName.value)?.id
?? list.find((item) => item.members.some((member) => member.id === clientId.value))?.id
?? "";
}
}, { deep: true });
return {
channelTree,
currentChannel,
currentChannelName,
currentChannelDescription,
currentMembers,
memberChannels,
filteredMemberChannels,
whisperTargets,
};
}
+127
View File
@@ -0,0 +1,127 @@
import { computed, nextTick, ref, watch, type Ref } from "vue";
import type { ChannelInfo, ChannelMember, ChatMessage } from "./useVoiceWebSocket.js";
export type WebClientChatTab = "channel" | "server" | "private" | "events";
interface PrivateConversation {
id: number;
name: string;
lastMessage: number;
}
interface UseWebClientChatOptions {
messages: ChatMessage[];
members: ChannelMember[];
currentChannel: Readonly<Ref<ChannelInfo | undefined>>;
currentChannelName: Readonly<Ref<string>>;
selectedChannelId: Ref<string>;
clientId: Readonly<Ref<number>>;
isMobileViewport: Readonly<Ref<boolean>>;
mobileSection: Ref<"channels" | "chat" | "voice" | "more">;
closeMemberMenu: () => void;
sendTextMessage: (text: string, targetId?: string) => void;
sendServerMessage: (text: string) => void;
sendPrivateMessage: (clientId: number, text: string, conversationId?: string) => void;
notifyPrivateMessage: () => void;
t: (key: string, variables?: Record<string, string | number>) => string;
}
export function useWebClientChat({
messages,
members,
currentChannel,
currentChannelName,
selectedChannelId,
clientId,
isMobileViewport,
mobileSection,
closeMemberMenu,
sendTextMessage,
sendServerMessage,
sendPrivateMessage,
notifyPrivateMessage,
t,
}: UseWebClientChatOptions) {
const tab = ref<WebClientChatTab>("channel");
const privateClientId = ref(0);
const messageDraft = ref("");
const listElement = ref<HTMLElement | null>(null);
const conversations = computed<PrivateConversation[]>(() => {
const byConversation = new Map<string, PrivateConversation>();
for (const message of messages) {
if (message.scope !== "private" || !message.conversationId) continue;
const id = Number(message.conversationId);
if (!id) continue;
const member = members.find((candidate) => candidate.id === id);
const existing = byConversation.get(message.conversationId);
byConversation.set(message.conversationId, {
id,
name: member?.nickname ?? existing?.name ?? message.invokerName,
lastMessage: Math.max(existing?.lastMessage ?? 0, message.timestamp),
});
}
return [...byConversation.values()].sort((left, right) => right.lastMessage - left.lastMessage);
});
const visibleMessages = computed(() => {
if (tab.value === "server") return messages.filter((message) => message.scope === "server");
if (tab.value === "private") return messages.filter((message) => message.scope === "private" && message.conversationId === String(privateClientId.value));
if (tab.value !== "channel") return [];
const channelId = currentChannel.value?.id;
return messages.filter((message) => message.scope === "channel" && (!message.targetId || message.targetId === "0" || !channelId || message.targetId === channelId));
});
const tabLabel = computed(() => tab.value === "channel" ? t("textChannel") : tab.value === "server" ? t("serverChat") : tab.value === "private" ? t("privateMessage") : t("eventLog"));
const title = computed(() => tab.value === "channel"
? t("channelChat", { channel: currentChannelName.value })
: tab.value === "server"
? t("serverChat")
: tab.value === "events"
? t("eventLog")
: conversations.value.find((conversation) => conversation.id === privateClientId.value)?.name ?? t("privateMessage"));
const placeholder = computed(() => tab.value === "private" ? t("privateMessagePlaceholder") : tab.value === "server" ? t("serverMessagePlaceholder") : t("sendMessagePlaceholder"));
function scrollToEnd(): void {
const list = listElement.value;
if (list) list.scrollTo({ top: list.scrollHeight, behavior: "smooth" });
}
function openPrivateChat(targetClientId: number): void {
if (!targetClientId || targetClientId === clientId.value) return;
privateClientId.value = targetClientId;
tab.value = "private";
if (isMobileViewport.value) mobileSection.value = "chat";
closeMemberMenu();
void nextTick(scrollToEnd);
}
function submitMessage(): void {
if (!messageDraft.value.trim()) return;
if (tab.value === "channel") sendTextMessage(messageDraft.value, currentChannel.value?.id ?? selectedChannelId.value);
else if (tab.value === "server") sendServerMessage(messageDraft.value);
else if (tab.value === "private" && privateClientId.value) sendPrivateMessage(privateClientId.value, messageDraft.value, String(privateClientId.value));
messageDraft.value = "";
}
watch([() => messages.length, tab, privateClientId], () => { void nextTick(scrollToEnd); });
watch(() => messages.length, (length, previousLength) => {
const latest = messages[length - 1];
if (latest && length > previousLength && latest.scope === "private" && !latest.isSelf) notifyPrivateMessage();
});
return {
tab,
privateClientId,
messageDraft,
listElement,
conversations,
visibleMessages,
tabLabel,
title,
placeholder,
openPrivateChat,
submitMessage,
scrollToEnd,
};
}
@@ -0,0 +1,204 @@
import { computed, nextTick, watch, type Ref } from "vue";
import type { WebClientChatTab } from "./useWebClientChat.js";
import type { TreeChannel } from "./useWebClientChannels.js";
import { combineTeamSpeakTarget, isValidTeamSpeakPort } from "../services/teamspeak-target.js";
interface ChannelPasswordDialogState {
open: boolean;
channelId: string;
password: string;
error: string;
submitting: boolean;
}
interface ServerPasswordDialogState {
open: boolean;
password: string;
errorCode: string;
}
interface UseWebClientConnectionOptions {
initialized: Readonly<Ref<boolean>>;
accessMode: Readonly<Ref<string>>;
isConnecting: Readonly<Ref<boolean>>;
errorCode: Readonly<Ref<string>>;
channelSwitchedChannelId: Readonly<Ref<string>>;
nickname: Ref<string>;
channelName: Ref<string>;
serverHost: Ref<string>;
serverPort: Ref<string>;
serverPassword: Ref<string>;
rememberIdentity: Readonly<Ref<boolean>>;
identityMaterial: Ref<string>;
accelerationRelayId: Ref<string>;
inviteToken: string;
selectedChannelId: Ref<string>;
channels: Readonly<Ref<TreeChannel[]>>;
clientId: Readonly<Ref<number>>;
channelPasswordDialog: ChannelPasswordDialogState;
serverPasswordDialog: ServerPasswordDialogState;
chatTab: Ref<WebClientChatTab>;
connect: (target: string, channel: string, nickname: string, password: string, identity: string, remember: boolean, invite: string, useRelay: boolean, relayId: string) => void;
disconnect: () => void;
switchChannel: (channelId: string, password?: string) => void;
clearError: () => void;
saveNickname: (nickname: string) => void;
showToast: (message: string) => void;
t: (key: string) => string;
}
export function useWebClientConnection({
initialized,
accessMode,
isConnecting,
errorCode,
channelSwitchedChannelId,
nickname,
channelName,
serverHost,
serverPort,
serverPassword,
rememberIdentity,
identityMaterial,
accelerationRelayId,
inviteToken,
selectedChannelId,
channels,
clientId,
channelPasswordDialog,
serverPasswordDialog,
chatTab,
connect,
disconnect,
switchChannel,
clearError,
saveNickname,
showToast,
t,
}: UseWebClientConnectionOptions) {
const canJoin = computed(() => Boolean(
initialized.value
&& nickname.value.trim()
&& (accessMode.value === "fixed" || (serverHost.value.trim() && isValidTeamSpeakPort(serverPort.value))),
));
function currentServerTarget(): string {
return combineTeamSpeakTarget(serverHost.value, serverPort.value);
}
function doConnect(): void {
if (!canJoin.value || isConnecting.value) return;
clearError();
nickname.value = nickname.value.trim();
saveNickname(nickname.value);
if (accessMode.value === "open") {
serverHost.value = serverHost.value.trim();
serverPort.value = serverPort.value.trim();
}
selectedChannelId.value = "";
// Keep the password available for retry even if the target is administrator-managed.
connect(
currentServerTarget(),
channelName.value.trim(),
nickname.value,
serverPassword.value,
rememberIdentity.value ? identityMaterial.value : "",
rememberIdentity.value,
inviteToken,
Boolean(accelerationRelayId.value),
accelerationRelayId.value,
);
}
function doDisconnect(): void {
disconnect();
selectedChannelId.value = "";
showToast(t("leftToast"));
}
function submitServerPassword(): void {
if (!serverPasswordDialog.open || !serverPasswordDialog.password) return;
serverPassword.value = serverPasswordDialog.password;
serverPasswordDialog.open = false;
serverPasswordDialog.password = "";
serverPasswordDialog.errorCode = "";
doConnect();
}
function cancelServerPassword(): void {
serverPasswordDialog.open = false;
serverPasswordDialog.password = "";
serverPasswordDialog.errorCode = "";
clearError();
}
function selectChannel(channel: TreeChannel): void {
selectedChannelId.value = channel.id;
channelName.value = channel.name;
chatTab.value = "channel";
switchChannel(channel.id);
}
function submitChannelPassword(): void {
if (!channelPasswordDialog.open || !channelPasswordDialog.channelId || !channelPasswordDialog.password) return;
channelPasswordDialog.error = "";
channelPasswordDialog.submitting = true;
switchChannel(channelPasswordDialog.channelId, channelPasswordDialog.password);
}
function cancelChannelPassword(): void {
const ownChannel = channels.value.find((item) => item.members.some((member) => member.id === clientId.value));
if (ownChannel) selectedChannelId.value = ownChannel.id;
channelPasswordDialog.open = false;
channelPasswordDialog.channelId = "";
channelPasswordDialog.password = "";
channelPasswordDialog.error = "";
channelPasswordDialog.submitting = false;
clearError();
}
function selectChannelById(): void {
const channel = channels.value.find((item) => item.id === selectedChannelId.value);
if (channel) selectChannel(channel);
}
watch(errorCode, (code) => {
if (code !== "CHANNEL_PASSWORD_REQUIRED" || !selectedChannelId.value) return;
channelPasswordDialog.open = true;
channelPasswordDialog.channelId = selectedChannelId.value;
channelPasswordDialog.password = "";
channelPasswordDialog.error = t("channelPasswordRetry");
channelPasswordDialog.submitting = false;
clearError();
void nextTick(() => document.getElementById("channel-password-input")?.focus());
});
watch(errorCode, (code) => {
if (code !== "SERVER_PASSWORD_REQUIRED" && code !== "INVALID_SERVER_PASSWORD") return;
serverPasswordDialog.open = true;
serverPasswordDialog.password = "";
serverPasswordDialog.errorCode = code;
clearError();
void nextTick(() => document.getElementById("retry-server-password-input")?.focus());
});
watch(channelSwitchedChannelId, (channelId) => {
if (!channelPasswordDialog.open || !channelId || channelId !== channelPasswordDialog.channelId) return;
channelPasswordDialog.open = false;
channelPasswordDialog.channelId = "";
channelPasswordDialog.password = "";
channelPasswordDialog.error = "";
channelPasswordDialog.submitting = false;
});
return {
canJoin,
currentServerTarget,
doConnect,
doDisconnect,
submitServerPassword,
cancelServerPassword,
selectChannel,
submitChannelPassword,
cancelChannelPassword,
selectChannelById,
};
}
+277
View File
@@ -0,0 +1,277 @@
import type { Ref } from "vue";
import { webClientTranslations, type Language } from "../i18n/web-client.js";
export function useWebClientI18n(language: Ref<Language>) {
function t(key: string, variables: Record<string, string | number> = {}) {
let value = webClientTranslations[language.value][key] ?? webClientTranslations.en[key] ?? webClientTranslations.zh[key] ?? key;
for (const [name, replacement] of Object.entries(variables)) value = value.replaceAll(`{{${name}}}`, String(replacement));
return value;
}
function localizedMessage(message: string) {
if (language.value === "zh") return message;
const localizedExact: Record<string, string> = language.value === "ru" ? {
"该服务器需要密码,请输入密码后重试": "Для этого сервера требуется пароль. Введите его и повторите попытку",
"服务器密码错误,请重新输入": "Неверный пароль сервера. Введите его ещё раз",
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "Длина имени не соответствует требованиям TeamSpeak (не менее 3 символов). Измените имя и повторите попытку",
"TeamSpeak 服务器地址无效": "Неверный адрес сервера TeamSpeak",
"找不到 TeamSpeak 服务器主机名,请检查地址": "Не удалось найти сервер TeamSpeak. Проверьте адрес",
"无法到达 TeamSpeak 服务器,请检查网络或地址": "Сервер TeamSpeak недоступен. Проверьте сеть или адрес",
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "Сервер TeamSpeak отклонил подключение. Проверьте порт и состояние службы",
"连接 TeamSpeak 超时,请检查网络或服务器状态": "Истекло время подключения к TeamSpeak. Проверьте сеть и состояние сервера",
"你没有执行此操作的权限": "У вас нет права выполнять это действие",
} : {
"该服务器需要密码,请输入密码后重试": "このサーバーにはパスワードが必要です。入力して再試行してください",
"服务器密码错误,请重新输入": "サーバーパスワードが正しくありません。もう一度入力してください",
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "ニックネームの長さが TeamSpeak の要件を満たしていません(3文字以上)。変更して再試行してください",
"TeamSpeak 服务器地址无效": "TeamSpeak サーバーアドレスが正しくありません",
"找不到 TeamSpeak 服务器主机名,请检查地址": "TeamSpeak サーバーが見つかりません。アドレスを確認してください",
"无法到达 TeamSpeak 服务器,请检查网络或地址": "TeamSpeak サーバーに到達できません。ネットワークまたはアドレスを確認してください",
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "TeamSpeak サーバーが接続を拒否しました。ポートとサービスの状態を確認してください",
"连接 TeamSpeak 超时,请检查网络或服务器状态": "TeamSpeak への接続がタイムアウトしました。ネットワークとサーバーの状態を確認してください",
"你没有执行此操作的权限": "この操作を実行する権限がありません",
};
if ((language.value === "ru" || language.value === "ja") && localizedExact[message]) return localizedExact[message];
const errorCodeMatch = message.match(/错误代码:([A-Z0-9_-]{1,64}))(?::([^,。]+))?/);
if (errorCodeMatch) {
const code = errorCodeMatch[1];
const detail = errorCodeMatch[2] ? `: ${errorCodeMatch[2]}` : "";
const operation = message.startsWith("操作失败");
if (language.value === "de") return `${operation ? "Vorgang" : "TeamSpeak-Verbindung"} fehlgeschlagen (Fehlercode: ${code})${detail}. Prüfe Eingaben, Netzwerk und Serverstatus`;
if (language.value === "ru") return `${operation ? "Операция" : "Подключение TeamSpeak"} не выполнена (код ошибки: ${code})${detail}. Проверьте ввод, сеть и состояние сервера`;
if (language.value === "ja") return `${operation ? "操作" : "TeamSpeak 接続"}に失敗しました(エラーコード: ${code})${detail}。入力、ネットワーク、サーバーの状態を確認してください`;
return `${operation ? "Operation" : "TeamSpeak connection"} failed (error code: ${code})${detail}. Check your input, network, and server status`;
}
const exact: Record<string, string> = {
"语音功能需要 HTTPS 安全连接": "Voice requires a secure HTTPS connection",
"当前浏览器不支持麦克风访问": "This browser does not support microphone access",
"当前浏览器不支持 Web Audio 音频处理": "This browser does not support Web Audio processing",
"当前浏览器不支持音频解码,请使用最新版 Chrome 或 Edge": "Audio decoding is unavailable. Use the latest Chrome or Edge",
"当前浏览器不支持扬声器设备选择,将使用默认输出设备": "Output device selection is not supported by this browser. Using the default output device",
"所选扬声器当前不可用": "The selected speaker is not available",
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
"请求来源不受信任,请从正确的网站入口重新打开": "The request origin is not trusted. Reopen the official WebSpeak page",
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak has not been configured yet. Contact the administrator",
"请求过于频繁,请稍后重试": "Too many requests. Try again shortly",
"当前中继加速不可用,请关闭加速或联系管理员": "The selected relay is unavailable. Turn off relay mode or contact the administrator",
"邀请链接已失效或已被撤销": "The invite link is invalid, expired, or revoked",
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
"连接已断开": "The connection was closed",
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "This TeamSpeak identity is already used by another browser page. Close that connection or clear ‘Remember identity’ and try again",
"TeamSpeak 服务器地址无效": "The TeamSpeak server address is invalid",
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "The nickname length does not meet the TeamSpeak server requirements (at least 3 characters). Change it and try again",
"TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server",
"找不到 TeamSpeak 服务器主机名,请检查地址": "The TeamSpeak server hostname could not be resolved. Check the address",
"无法到达 TeamSpeak 服务器,请检查网络或地址": "The TeamSpeak server is unreachable. Check the network or address",
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "The TeamSpeak server refused the connection. Check the port and server status",
"TeamSpeak 连接被服务器或网络重置,请稍后重试": "The TeamSpeak connection was reset by the server or network. Try again shortly",
"连接 TeamSpeak 超时,请检查网络或服务器状态": "The TeamSpeak connection timed out. Check the network or server status",
"该服务器需要密码,请输入密码后重试": "This server requires a password. Enter it and try again",
"服务器密码错误,请重新输入": "The server password is incorrect. Enter it again",
"TeamSpeak 协议协商失败": "TeamSpeak protocol negotiation failed",
"TeamSpeak 服务器拒绝了连接": "The TeamSpeak server rejected the connection",
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "TeamSpeak connection failed. Check the address, network, or server status",
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
"服务器当前已满或拒绝了连接,请稍后重试": "The server is full or rejected the connection. Try again shortly",
"WebSpeak 尚未配置 TeamSpeak 目标。": "The WebSpeak TeamSpeak target has not been configured",
"此 TeamSpeak 服务器地址不允许连接": "This TeamSpeak server address is not allowed",
"请输入有效的昵称": "Enter a valid nickname",
"消息格式无效": "The message format is invalid",
"请求标识无效": "The request id is invalid",
"不支持的操作": "This operation is not supported",
"操作参数无效": "The operation payload is invalid",
"频道标识无效": "The channel id is invalid",
"成员标识无效": "The member id is invalid",
"频道密码无效": "The channel password is invalid",
"文字消息无效": "The text message is invalid",
"戳一戳消息无效": "The poke message is invalid",
"离开状态无效": "The away status is invalid",
"音频帧格式无效": "The audio frame is invalid",
"私语目标无效": "The whisper targets are invalid",
"私语状态无效": "The whisper state is invalid",
"请先选择私语目标": "Choose a whisper target first",
"私语目标已离线": "A whisper target is offline",
"TeamSpeak 会话尚未就绪": "The TeamSpeak session is not ready",
"频道切换失败": "Channel switch failed",
"该频道需要密码": "This channel requires a password",
"该频道已满": "This channel is full",
"你没有执行此操作的权限": "You do not have permission to perform this action",
"不能移动自己的客户端": "You cannot move yourself",
"目标频道不可用": "The target channel is unavailable",
"成员已离线或当前不可见": "The member is offline or no longer visible",
"成员已离线": "This member is offline",
"操作失败": "The operation failed",
"语音会话票据缺失或已过期,请返回列表重新进入语音空间": "The voice session token is missing or expired. Return to the list and enter the voice space again",
"语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入": "The voice gateway rejected the connection because the identity is invalid. Clear ‘Remember identity’ and try again",
"语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入": "The voice gateway rejected the connection because the identity is invalid or unavailable on this page. Clear ‘Remember identity’ and try again",
"当前中继加速不可用,请关闭加速后重试或联系管理员": "The selected relay is unavailable. Turn off relay mode and try again, or contact the administrator",
"与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入": "The voice gateway connection was interrupted (offline or proxy disconnected); the TeamSpeak server did not reject it. Check your network and enter again",
"语音网关会话意外结束,请重新进入语音空间": "The voice gateway session ended unexpectedly. Enter the voice space again",
"语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试": "The voice gateway could not create a TeamSpeak client. The server may be offline or unreachable; check the address and try again",
"该昵称已被服务器上的其他用户占用,请更换昵称": "This nickname is already in use on the server. Choose another one",
"该昵称已被占用,请更换昵称": "This nickname is already in use. Choose another one",
"你的身份安全等级低于该服务器要求,请提升后重试": "Your identity security level is below what this server requires. Raise it and try again",
"该身份建立的连接数已达上限,请关闭其他连接后重试": "This identity reached its connection limit. Close the other connections and try again",
"客户端版本过旧,服务器拒绝连接,请升级后重试": "Your client version is outdated and the server rejected the connection. Update and try again",
"客户端版本过旧,服务器拒绝了该操作": "Your client version is outdated, so the server rejected this action",
"操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Too many requests: the server flood protection rejected you temporarily. Try again shortly",
"操作过于频繁,请稍后重试": "Too many requests. Try again shortly",
"你已被该服务器封禁,无法连接": "You are banned from this server, so the connection is refused",
"你已被该服务器封禁": "You are banned from this server",
"你已被服务器移出": "You were removed from the server",
"TeamSpeak 服务器正在关闭,暂时无法连接": "The TeamSpeak server is shutting down and is unreachable right now",
"TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "The TeamSpeak server could not finish initialising the connection. Check the address and port, or try again shortly",
"TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "The TeamSpeak server rejected the parameters, usually because the nickname length or format is invalid",
};
if (language.value === "en" && exact[message]) return exact[message];
if (message.startsWith("麦克风访问失败:")) {
const detail = message.slice(8);
if (language.value === "ru") return `Не удалось получить доступ к микрофону: ${detail}`;
if (language.value === "ja") return `マイクへのアクセスに失敗しました: ${detail}`;
return language.value === "de" ? `Mikrofonzugriff fehlgeschlagen: ${detail}` : `Microphone access failed: ${detail}`;
}
if (message.startsWith("切换失败:")) {
const detail = message.slice(5);
if (language.value === "ru") return `Не удалось переключить канал: ${detail}`;
if (language.value === "ja") return `チャンネルの切り替えに失敗しました: ${detail}`;
return language.value === "de" ? `Kanalwechsel fehlgeschlagen: ${detail}` : `Channel switch failed: ${detail}`;
}
if (language.value === "de") {
const german: Record<string, string> = {
"语音功能需要 HTTPS 安全连接": "Für Sprachfunktionen ist eine sichere HTTPS-Verbindung erforderlich",
"当前浏览器不支持麦克风访问": "Dieser Browser unterstützt keinen Mikrofonzugriff",
"当前浏览器不支持 Web Audio 音频处理": "Dieser Browser unterstützt keine Web-Audio-Verarbeitung",
"连接服务器失败,请检查邀请链接或服务器状态": "Verbindung fehlgeschlagen. Prüfe den Einladungslink oder den Serverstatus",
"请求来源不受信任,请从正确的网站入口重新打开": "Die Anfragequelle ist nicht vertrauenswürdig. Öffne die offizielle WebSpeak-Seite erneut",
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak wurde noch nicht konfiguriert. Wende dich an den Administrator",
"请求过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut",
"当前中继加速不可用,请关闭加速或联系管理员": "Das ausgewählte Relay ist nicht verfügbar. Deaktiviere den Relay-Modus oder wende dich an den Administrator",
"邀请链接已失效或已被撤销": "Der Einladungslink ist ungültig, abgelaufen oder widerrufen",
"TeamSpeak 连接已断开": "Die TeamSpeak-Verbindung wurde getrennt",
"连接已断开": "Die Verbindung wurde getrennt",
"TeamSpeak 服务器地址无效": "Die TeamSpeak-Serveradresse ist ungültig",
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "Die Länge des Spitznamens entspricht nicht den Anforderungen des TeamSpeak-Servers (mindestens 3 Zeichen). Ändere ihn und versuche es erneut",
"请输入有效的昵称": "Gib einen gültigen Nicknamen ein",
"找不到 TeamSpeak 服务器主机名,请检查地址": "Der TeamSpeak-Servername konnte nicht aufgelöst werden. Prüfe die Adresse",
"无法到达 TeamSpeak 服务器,请检查网络或地址": "Der TeamSpeak-Server ist nicht erreichbar. Prüfe Netzwerk und Adresse",
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "Der TeamSpeak-Server hat die Verbindung abgelehnt. Prüfe Port und Serverstatus",
"TeamSpeak 连接被服务器或网络重置,请稍后重试": "Die TeamSpeak-Verbindung wurde vom Server oder Netzwerk zurückgesetzt. Versuche es später erneut",
"连接 TeamSpeak 超时,请检查网络或服务器状态": "Die TeamSpeak-Verbindung hat das Zeitlimit überschritten. Prüfe Netzwerk und Serverstatus",
"该服务器需要密码,请输入密码后重试": "Dieser Server benötigt ein Passwort. Gib es ein und versuche es erneut",
"服务器密码错误,请重新输入": "Das Serverpasswort ist falsch. Gib es erneut ein",
"TeamSpeak 协议协商失败": "Die Aushandlung des TeamSpeak-Protokolls ist fehlgeschlagen",
"TeamSpeak 服务器拒绝了连接": "Der TeamSpeak-Server hat die Verbindung abgelehnt",
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "Die TeamSpeak-Verbindung ist fehlgeschlagen. Prüfe Adresse, Netzwerk und Serverstatus",
"服务器当前已满或拒绝了连接,请稍后重试": "Der Server ist voll oder hat die Verbindung abgelehnt. Versuche es später erneut",
"服务器当前已满,请稍后重试": "Der Server ist derzeit voll. Versuche es später erneut",
"该昵称已被服务器上的其他用户占用,请更换昵称": "Dieser Spitzname wird auf dem Server bereits verwendet. Wähle einen anderen",
"该昵称已被占用,请更换昵称": "Dieser Spitzname wird bereits verwendet. Wähle einen anderen",
"你的身份安全等级低于该服务器要求,请提升后重试": "Deine Sicherheitsstufe liegt unter der Anforderung dieses Servers. Erhöhe sie und versuche es erneut",
"该身份建立的连接数已达上限,请关闭其他连接后重试": "Diese Identität hat ihr Verbindungslimit erreicht. Schließe die anderen Verbindungen und versuche es erneut",
"客户端版本过旧,服务器拒绝连接,请升级后重试": "Deine Client-Version ist veraltet und der Server hat die Verbindung abgelehnt. Aktualisiere und versuche es erneut",
"客户端版本过旧,服务器拒绝了该操作": "Deine Client-Version ist veraltet, daher hat der Server diese Aktion abgelehnt",
"操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Zu viele Anfragen: Der Flood-Schutz des Servers hat dich vorübergehend abgewiesen. Versuche es gleich erneut",
"操作过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut",
"你已被该服务器封禁,无法连接": "Du wurdest von diesem Server gebannt und kannst nicht verbinden",
"你已被该服务器封禁": "Du wurdest von diesem Server gebannt",
"你已被服务器移出": "Du wurdest vom Server entfernt",
"TeamSpeak 服务器正在关闭,暂时无法连接": "Der TeamSpeak-Server wird heruntergefahren und ist derzeit nicht erreichbar",
"TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "Der TeamSpeak-Server konnte die Verbindungsinitialisierung nicht abschließen. Prüfe Adresse und Port oder versuche es später erneut",
"TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "Der TeamSpeak-Server hat die Parameter abgelehnt, meist wegen ungültiger Länge oder ungültigen Formats des Spitznamens",
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "Diese TeamSpeak-Identität wird bereits in einem anderen Browser-Tab verwendet. Schließe die andere Verbindung oder deaktiviere „Identität merken“ und versuche es erneut",
"语音会话票据缺失或已过期,请返回列表重新进入语音空间": "Der Sprachsitzungs-Token fehlt oder ist abgelaufen. Kehre zur Liste zurück und tritt dem Sprachraum erneut bei",
"语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig. Deaktiviere „Identität merken“ und tritt erneut bei",
"语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig oder kann auf dieser Seite nicht verwendet werden. Deaktiviere „Identität merken“ und tritt erneut bei",
"当前中继加速不可用,请关闭加速后重试或联系管理员": "Der beschleunigte Relay-Modus ist nicht verfügbar. Deaktiviere ihn und versuche es erneut oder wende dich an den Administrator",
"与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入": "Die Verbindung zum Sprach-Gateway wurde unerwartet unterbrochen (Offline oder Proxy getrennt) – der TeamSpeak-Server hat die Verbindung nicht abgelehnt. Prüfe deine Netzwerkverbindung und tritt erneut bei",
"语音网关会话意外结束,请重新进入语音空间": "Die Sprach-Gateway-Sitzung wurde unerwartet beendet. Tritt dem Sprachraum erneut bei",
"语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试": "Das Sprach-Gateway konnte keinen TeamSpeak-Client erstellen (der Server ist möglicherweise aus oder nicht erreichbar). Prüfe die Serveradresse oder versuche es später erneut",
"消息格式无效": "Ungültiges Nachrichtenformat",
"请求标识无效": "Ungültige Anforderungs-ID",
"不支持的操作": "Nicht unterstützte Operation",
"操作参数无效": "Ungültige Operationsparameter",
"频道标识无效": "Ungültige Kanal-ID",
"频道密码无效": "Ungültiges Kanalpasswort",
"成员标识无效": "Ungültige Mitglieds-ID",
"文字消息无效": "Ungültige Textnachricht",
"戳一戳消息无效": "Ungültige Poke-Nachricht",
"离开状态无效": "Ungültiger Abwesenheitsstatus",
"音频帧格式无效": "Ungültiges Audio-Frame-Format",
"成员音量无效": "Ungültige Mitgliedslautstärke",
"私语目标无效": "Ungültige Flüsterziele",
"私语状态无效": "Ungültiger Flüsterstatus",
"请先选择私语目标": "Wähle zuerst ein Flüsterziel",
"TeamSpeak 会话尚未就绪": "Die TeamSpeak-Sitzung ist noch nicht bereit",
"频道切换失败": "Kanalwechsel fehlgeschlagen",
"该频道需要密码": "Dieser Kanal erfordert ein Passwort",
"该频道已满": "Dieser Kanal ist voll",
"你没有执行此操作的权限": "Du hast keine Berechtigung für diese Aktion",
"不能移动自己的客户端": "Du kannst dich nicht selbst verschieben",
"目标频道不可用": "Der Zielkanal ist nicht verfügbar",
"成员已离线或当前不可见": "Das Mitglied ist offline oder nicht mehr sichtbar",
"成员已离线": "Das Mitglied ist offline",
"操作失败": "Operation fehlgeschlagen",
};
if (german[message]) return german[message];
if (message.startsWith("麦克风访问失败:")) return `Mikrofonzugriff fehlgeschlagen: ${message.slice(8)}`;
if (message.startsWith("麦克风声音未能发送:")) return `Mikrofon-Audio konnte nicht gesendet werden: ${message.slice(10)}`;
if (message.startsWith("音频链路异常")) return message.replace("音频链路异常", "Audioverbindung fehlerhaft");
}
if (language.value === "ru") return exact[message] ?? "Не удалось выполнить операцию. Проверьте ввод, сеть и состояние сервера";
if (language.value === "ja") return exact[message] ?? "操作に失敗しました。入力、ネットワーク、サーバーの状態を確認してください";
return exact[message] ?? message;
}
function localizedAudioNotice(code: string, message: string) {
if (language.value === "zh") return message;
const normalizedCode = visibleErrorCode(code || "AUDIO_NOTICE");
const messages: Record<string, { en: string; de: string; ru: string; ja: string }> = {
WEBRTC_FALLBACK: {
en: `WebRTC realtime voice is unavailable (error code: ${normalizedCode}). Compatibility transport is active; latency and audio quality may be lower`,
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${normalizedCode}). Der Kompatibilitätstransport ist aktiv; Latenz und Audioqualität können schlechter sein`,
ru: `Голосовая связь WebRTC недоступна (код ошибки: ${normalizedCode}). Используется совместимый транспорт; задержка и качество звука могут быть ниже`,
ja: `WebRTC のリアルタイム音声は利用できません(エラーコード: ${normalizedCode})。互換トランスポートを使用するため、遅延や音質が低下する場合があります`,
},
PLAYBACK_BLOCKED: {
en: "The browser blocked automatic audio playback. Click the page or allow audio playback for this site",
de: "Der Browser hat die automatische Audiowiedergabe blockiert. Klicke auf die Seite oder erlaube die Audiowiedergabe für diese Website",
ru: "Браузер заблокировал автоматическое воспроизведение. Нажмите на страницу или разрешите воспроизведение для этого сайта",
ja: "ブラウザが自動再生をブロックしました。ページをクリックするか、このサイトの再生を許可してください",
},
DEVICE_LIST_UNAVAILABLE: {
en: "Audio devices could not be listed. The browser default devices will be used",
de: "Audiogeräte konnten nicht aufgelistet werden. Die Standardgeräte des Browsers werden verwendet",
ru: "Не удалось получить список аудиоустройств. Будут использованы устройства браузера по умолчанию",
ja: "オーディオデバイスを一覧表示できません。ブラウザのデフォルトデバイスを使用します",
},
AUDIO_CONTEXT_SUSPENDED: {
en: "Browser audio processing is paused. Click the page once to resume microphone and speaker audio",
de: "Die Audioverarbeitung des Browsers ist pausiert. Klicke einmal auf die Seite, um Mikrofon und Lautsprecher fortzusetzen",
ru: "Обработка звука браузером приостановлена. Нажмите на страницу, чтобы возобновить работу микрофона и динамиков",
ja: "ブラウザの音声処理が一時停止しています。ページを一度クリックしてマイクとスピーカーを再開してください",
},
AUDIO_ENCODER_UNAVAILABLE: {
en: `Microphone audio could not be encoded (error code: ${normalizedCode}). Other members may not hear you`,
de: `Mikrofon-Audio konnte nicht kodiert werden (Fehlercode: ${normalizedCode}). Andere Mitglieder hören dich möglicherweise nicht`,
ru: `Не удалось кодировать звук микрофона (код ошибки: ${normalizedCode}). Другие участники могут вас не слышать`,
ja: `マイク音声をエンコードできませんでした(エラーコード: ${normalizedCode})。他のメンバーに音声が届かない可能性があります`,
},
};
const locale = language.value === "de" ? "de" : language.value === "ru" ? "ru" : language.value === "ja" ? "ja" : "en";
return messages[code]?.[locale] ?? localizedMessage(message);
}
function visibleErrorCode(code: string): string {
const normalized = String(code || "CONNECTION_FAILED")
.trim()
.toUpperCase()
.replace(/[^A-Z0-9_-]+/g, "_")
.replace(/^_+|_+$/g, "");
return (normalized || "CONNECTION_FAILED").slice(0, 64);
}
return { t, localizedMessage, localizedAudioNotice, visibleErrorCode };
}
+290
View File
@@ -0,0 +1,290 @@
import { computed, reactive, ref, type Ref } from "vue";
import type { ChannelMember } from "./useVoiceWebSocket.js";
import type { TreeChannel } from "./useWebClientChannels.js";
export interface MemberMenuState {
member: ChannelMember;
x: number;
y: number;
}
interface UseWebClientMembersOptions {
channels: Readonly<Ref<TreeChannel[]>>;
currentChannel: Readonly<Ref<TreeChannel | undefined>>;
members: ChannelMember[];
speakingIds: Set<number>;
whisperTargetIds: Set<number>;
moveClient: (clientId: number, targetChannelId: string) => Promise<void>;
setWhisperTargets: (clientIds: number[]) => void;
sendPoke: (clientId: number, message: string) => void;
setAway: (away: boolean, message: string) => void;
stopWhisperTalk: () => void;
localizedMessage: (message: string) => string;
showToast: (message: string) => void;
t: (key: string) => string;
}
export function useWebClientMembers({
channels,
currentChannel,
members,
speakingIds,
whisperTargetIds,
moveClient,
setWhisperTargets,
sendPoke,
setAway,
stopWhisperTalk,
localizedMessage,
showToast,
t,
}: UseWebClientMembersOptions) {
const away = ref(false);
const awayMessage = ref("");
const memberMenu = ref<MemberMenuState | null>(null);
const memberMoveMenuOpen = ref(false);
const draggedMember = ref<ChannelMember | null>(null);
const dragOverChannelId = ref("");
const memberPointerDrag = reactive({
member: null as ChannelMember | null,
pointerId: null as number | null,
startX: 0,
startY: 0,
active: false,
targetChannelId: "",
});
const memberMoveMenuCurrentChannel = computed<TreeChannel | null>(() => {
const member = memberMenu.value?.member;
const selected = currentChannel.value;
if (!member || !selected || selected.id === "__current__") return null;
return selected;
});
const memberMoveMenuCurrentSameChannel = computed(() => {
const member = memberMenu.value?.member;
const currentId = memberMoveMenuCurrentChannel.value?.id;
if (!member || !currentId) return false;
return channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id))?.id === currentId;
});
const memberMoveMenuOtherChannels = computed<TreeChannel[]>(() => {
const member = memberMenu.value?.member;
if (!member) return [];
const sourceChannelId = channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id))?.id ?? "";
const currentChannelId = memberMoveMenuCurrentChannel.value?.id;
return channels.value.filter((item) => item.id !== "__current__" && item.id !== sourceChannelId && item.id !== currentChannelId);
});
function openMemberMenu(member: ChannelMember, event: Event): void {
if (member.isSelf) return;
memberMoveMenuOpen.value = false;
const point = event instanceof MouseEvent ? event : undefined;
memberMenu.value = {
member,
x: Math.min(point?.clientX ?? 20, Math.max(12, window.innerWidth - 210)),
y: Math.min(point?.clientY ?? 20, Math.max(12, window.innerHeight - 170)),
};
}
function openMemberActions(member: ChannelMember): void {
if (member.isSelf) return;
memberMoveMenuOpen.value = false;
memberMenu.value = { member, x: 0, y: 0 };
}
function toggleMemberMoveMenu(): void {
memberMoveMenuOpen.value = true;
}
async function moveMemberDirect(member: ChannelMember, targetChannelId: string): Promise<void> {
if (member.isSelf || !targetChannelId || targetChannelId === "__current__") return;
const sourceChannel = channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id));
if (sourceChannel?.id === targetChannelId) {
memberMenu.value = null;
memberMoveMenuOpen.value = false;
return;
}
memberMenu.value = null;
memberMoveMenuOpen.value = false;
try {
// Member moves are server-admin operations; never request or forward a channel password.
await moveClient(member.id, targetChannelId);
showToast(t("moveMemberSuccess"));
} catch (error: unknown) {
showToast(localizedMessage(error instanceof Error ? error.message : "操作失败"));
}
}
function onMemberDragStart(member: ChannelMember, event: DragEvent): void {
if (member.isSelf) {
event.preventDefault();
return;
}
draggedMember.value = member;
dragOverChannelId.value = "";
event.dataTransfer?.setData("text/plain", String(member.id));
if (event.dataTransfer) event.dataTransfer.effectAllowed = "move";
}
function onMemberDragEnd(): void {
draggedMember.value = null;
dragOverChannelId.value = "";
}
function onMemberPointerDown(member: ChannelMember, event: PointerEvent): void {
if (member.isSelf || event.button !== 0) return;
const target = event.target instanceof Element ? event.target : null;
if (target?.closest("input,button")) return;
event.preventDefault();
memberPointerDrag.member = member;
memberPointerDrag.pointerId = event.pointerId;
memberPointerDrag.startX = event.clientX;
memberPointerDrag.startY = event.clientY;
memberPointerDrag.active = false;
memberPointerDrag.targetChannelId = "";
const currentTarget = event.currentTarget as HTMLElement | null;
currentTarget?.setPointerCapture?.(event.pointerId);
}
function onMemberPointerMove(event: PointerEvent): void {
if (!memberPointerDrag.member || memberPointerDrag.pointerId !== event.pointerId) return;
const distance = Math.hypot(event.clientX - memberPointerDrag.startX, event.clientY - memberPointerDrag.startY);
if (!memberPointerDrag.active && distance < 6) return;
event.preventDefault();
memberPointerDrag.active = true;
draggedMember.value = memberPointerDrag.member;
const target = document.elementFromPoint(event.clientX, event.clientY)?.closest<HTMLElement>("[data-member-channel-id]");
const targetChannelId = target?.dataset.memberChannelId ?? "";
const sourceChannel = channels.value.find((item) => item.members.some((candidate) => candidate.id === memberPointerDrag.member?.id));
if (!sourceChannel || !targetChannelId || targetChannelId === sourceChannel.id) {
memberPointerDrag.targetChannelId = "";
dragOverChannelId.value = "";
return;
}
memberPointerDrag.targetChannelId = targetChannelId;
dragOverChannelId.value = targetChannelId;
}
function onMemberPointerUp(event: PointerEvent): void {
if (!memberPointerDrag.member || memberPointerDrag.pointerId !== event.pointerId) return;
const member = memberPointerDrag.member;
const targetChannelId = memberPointerDrag.targetChannelId;
const currentTarget = event.currentTarget as HTMLElement | null;
currentTarget?.releasePointerCapture?.(event.pointerId);
memberPointerDrag.member = null;
memberPointerDrag.pointerId = null;
memberPointerDrag.active = false;
memberPointerDrag.targetChannelId = "";
draggedMember.value = null;
dragOverChannelId.value = "";
if (targetChannelId) void moveMemberDirect(member, targetChannelId);
}
function onMemberPointerCancel(event: PointerEvent): void {
if (!memberPointerDrag.member || memberPointerDrag.pointerId !== event.pointerId) return;
const currentTarget = event.currentTarget as HTMLElement | null;
currentTarget?.releasePointerCapture?.(event.pointerId);
memberPointerDrag.member = null;
memberPointerDrag.pointerId = null;
memberPointerDrag.active = false;
memberPointerDrag.targetChannelId = "";
draggedMember.value = null;
dragOverChannelId.value = "";
}
function onChannelDragOver(channel: TreeChannel, event: DragEvent): void {
const member = draggedMember.value;
if (!member || channel.id === "__current__") return;
const sourceChannel = channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id));
if (!sourceChannel || sourceChannel.id === channel.id) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
dragOverChannelId.value = channel.id;
}
function onChannelDragLeave(channel: TreeChannel, event: DragEvent): void {
const currentTarget = event.currentTarget;
const relatedTarget = event.relatedTarget;
if (currentTarget instanceof HTMLElement && relatedTarget instanceof Node && currentTarget.contains(relatedTarget)) return;
if (dragOverChannelId.value === channel.id) dragOverChannelId.value = "";
}
function onChannelDrop(channel: TreeChannel, event: DragEvent): void {
event.preventDefault();
const member = draggedMember.value;
onMemberDragEnd();
if (!member || channel.id === "__current__") return;
void moveMemberDirect(member, channel.id);
}
function toggleWhisperTarget(member: ChannelMember): void {
if (member.isSelf) return;
const targets = new Set(whisperTargetIds);
if (targets.has(member.id)) targets.delete(member.id);
else if (targets.size < 8) targets.add(member.id);
setWhisperTargets([...targets]);
showToast(t(targets.has(member.id) ? "setWhisperTarget" : "removeWhisperTarget"));
}
function clearWhisperTargets(): void {
stopWhisperTalk();
setWhisperTargets([]);
}
function pokeMember(member: ChannelMember): void {
sendPoke(member.id, window.prompt(t("pokeMessagePrompt"), "") ?? "");
showToast(t("pokeSent"));
}
function copyMemberName(member: ChannelMember): void {
navigator.clipboard?.writeText(member.nickname).then(
() => showToast(t("copiedNickname")),
() => showToast(t("copyFailedToast")),
);
}
function toggleAway(): void {
away.value = !away.value;
awayMessage.value = away.value ? (window.prompt(t("awayPrompt"), awayMessage.value) ?? "") : "";
setAway(away.value, awayMessage.value);
}
function isSpeaking(member: ChannelMember): boolean {
return speakingIds.has(member.id);
}
function memberDisplayName(member: ChannelMember): string {
return member.isSelf ? `${member.nickname}${t("selfSuffix")}` : member.nickname;
}
return {
away,
memberMenu,
memberMoveMenuOpen,
draggedMember,
dragOverChannelId,
memberPointerDrag,
memberMoveMenuCurrentChannel,
memberMoveMenuCurrentSameChannel,
memberMoveMenuOtherChannels,
openMemberMenu,
openMemberActions,
toggleMemberMoveMenu,
moveMemberDirect,
onMemberDragStart,
onMemberDragEnd,
onMemberPointerDown,
onMemberPointerMove,
onMemberPointerUp,
onMemberPointerCancel,
onChannelDragOver,
onChannelDragLeave,
onChannelDrop,
toggleWhisperTarget,
clearWhisperTargets,
pokeMember,
copyMemberName,
toggleAway,
isSpeaking,
memberDisplayName,
};
}
@@ -0,0 +1,101 @@
import { computed, onUnmounted, ref, watch, type Ref } from "vue";
import type { LatencyProbeResult } from "./useVoiceWebSocket.js";
const SAMPLE_INTERVAL_MS = 3_000;
const SAMPLE_WINDOW_SIZE = 20;
export function useWebClientPerformance(
connected: Readonly<Ref<boolean>>,
measureLatency: () => Promise<LatencyProbeResult | null>,
) {
const panelOpen = ref(false);
const running = ref(false);
const samples = ref<LatencyProbeResult[]>([]);
const probeResults = ref<Array<LatencyProbeResult | null>>([]);
const attempts = ref(0);
let timer: number | null = null;
let generation = 0;
const median = (values: number[]) => {
const sorted = [...values].sort((left, right) => left - right);
return sorted.length ? sorted[Math.floor(sorted.length / 2)] : null;
};
const stats = computed(() => {
const gatewaySamples = samples.value.map((sample) => sample.browserRttMs);
const teamSpeakSamples = samples.value
.filter((sample) => sample.teamSpeakReachable && sample.teamSpeakLatencyMs != null)
.map((sample) => sample.teamSpeakLatencyMs as number);
return {
gatewayLatencyMs: median(gatewaySamples),
gatewayLossPercent: attempts.value > 0 ? Math.round(((attempts.value - samples.value.length) / attempts.value) * 100) : null,
teamSpeakLatencyMs: median(teamSpeakSamples),
teamSpeakLossPercent: attempts.value > 0 ? Math.round(((attempts.value - teamSpeakSamples.length) / attempts.value) * 100) : null,
ready: attempts.value > 0,
};
});
function resetSamples(): void {
probeResults.value = [];
samples.value = [];
attempts.value = 0;
}
function stop(): void {
if (timer !== null) {
clearInterval(timer);
timer = null;
}
generation += 1;
running.value = false;
}
async function runProbe(expectedGeneration = generation): Promise<void> {
if (running.value || !connected.value || !panelOpen.value) return;
running.value = true;
try {
const sample = await measureLatency();
if (expectedGeneration !== generation || !panelOpen.value) return;
probeResults.value.push(sample);
if (probeResults.value.length > SAMPLE_WINDOW_SIZE) probeResults.value.shift();
attempts.value = probeResults.value.length;
samples.value = probeResults.value.filter((result): result is LatencyProbeResult => result !== null);
} finally {
if (expectedGeneration === generation) running.value = false;
}
}
function start(): void {
if (timer !== null || !connected.value) return;
resetSamples();
const activeGeneration = ++generation;
void runProbe(activeGeneration);
timer = window.setInterval(() => {
void runProbe(activeGeneration);
}, SAMPLE_INTERVAL_MS);
}
function refresh(): void {
void runProbe();
}
function togglePanel(): void {
panelOpen.value = !panelOpen.value;
}
watch([connected, panelOpen], ([isConnected, isOpen]) => {
if (isConnected && isOpen) start();
else stop();
}, { immediate: true });
onUnmounted(stop);
return {
panelOpen,
running,
stats,
togglePanel,
refresh,
};
}
@@ -0,0 +1,108 @@
import { computed, reactive, ref, type Ref } from "vue";
import { splitTeamSpeakTarget } from "../services/teamspeak-target.js";
import type { Language } from "../i18n/web-client.js";
interface RelayOption {
id: string;
name: string;
}
type Translator = (key: string, variables?: Record<string, string | number>) => string;
interface UseWebClientPublicConfigOptions {
serverHost: Ref<string>;
serverPort: Ref<string>;
accelerationRelayId: Ref<string>;
language: Ref<Language>;
t: Translator;
}
export function useWebClientPublicConfig({
serverHost,
serverPort,
accelerationRelayId,
language,
t,
}: UseWebClientPublicConfigOptions) {
const accessMode = ref<"fixed" | "open">("fixed");
const initialized = ref(false);
const siteName = ref("WebSpeak");
const appVersion = ref("0.2.5");
const visitorNumber = ref<number | null>(null);
const visitorTotal = ref<number | null>(null);
const accelerationRelays = ref<RelayOption[]>([]);
const serverConfigLoading = ref(true);
const welcomeTexts = reactive<Record<Language, string>>({ zh: "", en: "", de: "", ru: "", ja: "" });
const accelerationAvailable = computed(() => accelerationRelays.value.length > 0);
const localizedWelcomeText = computed(() => welcomeTexts[language.value] || t("joinDescription"));
async function loadPublicConfig(): Promise<void> {
const query = new URLSearchParams(location.search);
try {
const response = await fetch("/api/public-config", { headers: { accept: "application/json" } });
if (!response.ok) return;
const config = await response.json() as {
version?: unknown;
initialized?: unknown;
siteName?: unknown;
welcomeText?: unknown;
welcomeTextEn?: unknown;
welcomeTexts?: unknown;
accessMode?: unknown;
target?: unknown;
visitorNumber?: unknown;
visitorTotal?: unknown;
accelerationRelays?: unknown;
};
if (typeof config.version === "string" && config.version.trim()) appVersion.value = config.version.trim();
visitorNumber.value = Number.isSafeInteger(config.visitorNumber) && Number(config.visitorNumber) > 0 ? Number(config.visitorNumber) : null;
visitorTotal.value = Number.isSafeInteger(config.visitorTotal) && Number(config.visitorTotal) > 0 ? Number(config.visitorTotal) : null;
initialized.value = config.initialized === true;
if (typeof config.siteName === "string" && config.siteName.trim()) siteName.value = config.siteName.trim();
if (typeof config.welcomeText === "string") welcomeTexts.zh = config.welcomeText;
if (typeof config.welcomeTextEn === "string") welcomeTexts.en = config.welcomeTextEn;
if (config.welcomeTexts && typeof config.welcomeTexts === "object" && !Array.isArray(config.welcomeTexts)) {
const configuredTexts = config.welcomeTexts as Record<string, unknown>;
for (const languageCode of ["zh", "en", "de", "ru", "ja"] as const) {
const text = configuredTexts[languageCode];
if (typeof text === "string") welcomeTexts[languageCode] = text;
}
}
accessMode.value = config.accessMode === "open" ? "open" : "fixed";
accelerationRelays.value = Array.isArray(config.accelerationRelays)
? config.accelerationRelays.flatMap((value) => {
if (!value || typeof value !== "object") return [];
const relay = value as { id?: unknown; name?: unknown };
return typeof relay.id === "string" && typeof relay.name === "string" && relay.id && relay.name
? [{ id: relay.id, name: relay.name }]
: [];
})
: [];
if (!accelerationAvailable.value || !accelerationRelays.value.some((relay) => relay.id === accelerationRelayId.value)) accelerationRelayId.value = "";
const hasInviteTarget = query.has("server") || query.has("target") || query.has("tsHost") || query.has("tsPort");
if (!hasInviteTarget && typeof config.target === "string" && config.target.trim()) {
const target = splitTeamSpeakTarget(config.target);
serverHost.value = target.address;
serverPort.value = target.port;
}
} catch {
// Keep joining disabled until the gateway confirms its initialized policy.
} finally {
serverConfigLoading.value = false;
}
}
return {
accessMode,
initialized,
siteName,
appVersion,
visitorNumber,
visitorTotal,
accelerationRelays,
accelerationAvailable,
serverConfigLoading,
localizedWelcomeText,
loadPublicConfig,
};
}
@@ -0,0 +1,157 @@
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import type { ChannelMember, ScreenShareOutputSettings, ScreenShareStream } from "./useVoiceWebSocket.js";
export type ScreenShareResolutionPreset = "source" | "720p" | "1080p";
interface ScreenShareResolutionOption {
value: ScreenShareResolutionPreset;
width?: number;
height?: number;
label: string;
}
interface UseWebClientScreenShareOptions {
streams: ScreenShareStream[];
viewing: Ref<boolean>;
viewingStreamId: Ref<string>;
remoteStream: Ref<MediaStream | null>;
remoteVolume: Ref<number>;
error: Ref<string>;
errorCode: Ref<string>;
startScreenShare: (audio?: boolean, settings?: ScreenShareOutputSettings) => Promise<void>;
joinScreenShare: (streamId: string) => void;
leaveScreenShare: () => void;
nickname: Ref<string>;
avatarStyle: (name: string, isSelf?: boolean, avatar?: string) => Record<string, string>;
t: (key: string) => string;
}
export function useWebClientScreenShare({
streams,
viewing,
viewingStreamId,
remoteStream,
remoteVolume,
error,
errorCode,
startScreenShare,
joinScreenShare,
leaveScreenShare,
nickname,
avatarStyle,
t,
}: UseWebClientScreenShareOptions) {
const videoElement = ref<HTMLVideoElement | null>(null);
const playerElement = ref<HTMLElement | null>(null);
const fullscreen = ref(false);
const resolutionOptions: ScreenShareResolutionOption[] = [
{ value: "source", label: "screenShareResolutionSource" },
{ value: "720p", width: 1280, height: 720, label: "screenShareResolution720p" },
{ value: "1080p", width: 1920, height: 1080, label: "screenShareResolution1080p" },
];
const frameRateOptions = [5, 10, 15, 24, 30, 60];
const storedResolution = localStorage.getItem("webspeak:screen-share-resolution") as ScreenShareResolutionPreset | null;
const resolutionPreset = ref<ScreenShareResolutionPreset>(resolutionOptions.some((option) => option.value === storedResolution) ? storedResolution! : "1080p");
const storedFrameRate = Number(localStorage.getItem("webspeak:screen-share-framerate"));
const frameRate = ref(frameRateOptions.includes(storedFrameRate) ? storedFrameRate : 15);
const settingsOpen = ref(false);
const activeStream = computed<ScreenShareStream | null>(() => streams.find((stream) => stream.streamId === viewingStreamId.value) ?? null);
const viewers = computed(() => activeStream.value?.viewers.slice(-5) ?? []);
const viewerCount = computed(() => activeStream.value?.viewerCount ?? activeStream.value?.viewers.length ?? 0);
const ownerName = computed(() => activeStream.value?.ownerNickname ?? t("screenShare"));
const errorText = computed(() => errorCode.value === "SCREEN_SHARE_NATIVE_BRIDGE_REQUIRED" ? t("screenShareNativeUnavailable") : error.value);
function setVideoElement(element: unknown): void {
videoElement.value = element instanceof HTMLVideoElement ? element : null;
}
function streamForMember(member: ChannelMember): ScreenShareStream | null {
return streams.find((stream) => {
if (typeof stream.ownerClientId === "number" && stream.ownerClientId === member.id) return true;
if (stream.source === "teamspeak" && stream.ownerPeerId === `ts-${member.id}`) return true;
return stream.ownerNickname === member.nickname;
}) ?? null;
}
function toggleForMember(member: ChannelMember): void {
const stream = streamForMember(member);
if (!stream) return;
if (viewingStreamId.value === stream.streamId) leaveScreenShare();
else joinScreenShare(stream.streamId);
}
function viewerStyle(viewer: { nickname: string; avatar?: string }) {
return avatarStyle(viewer.nickname, viewer.nickname === nickname.value, viewer.avatar ?? "");
}
function setVolume(event: Event): void {
remoteVolume.value = Math.max(0, Math.min(1, Number((event.target as HTMLInputElement).value) / 100));
}
function syncFullscreen(): void {
fullscreen.value = document.fullscreenElement === playerElement.value;
}
async function toggleFullscreen(): Promise<void> {
const player = playerElement.value;
if (!player) return;
try {
if (document.fullscreenElement === player) await document.exitFullscreen();
else if (player.requestFullscreen) await player.requestFullscreen();
} catch {
fullscreen.value = false;
}
}
async function startWithSettings(): Promise<void> {
const preset = resolutionOptions.find((option) => option.value === resolutionPreset.value);
const settings: ScreenShareOutputSettings = {
...(preset?.width && preset.height ? { maxWidth: preset.width, maxHeight: preset.height } : {}),
maxFrameRate: frameRate.value,
};
localStorage.setItem("webspeak:screen-share-resolution", resolutionPreset.value);
localStorage.setItem("webspeak:screen-share-framerate", String(frameRate.value));
settingsOpen.value = false;
await startScreenShare(true, settings);
}
watch([remoteStream, remoteVolume], ([stream, volume]) => {
void nextTick(() => {
const video = videoElement.value;
if (!video) return;
if (video.srcObject !== stream) video.srcObject = stream;
video.volume = Math.max(0, Math.min(1, volume ?? 1));
if (stream) void video.play().catch(() => undefined);
});
});
watch(viewing, (isViewing) => {
if (!isViewing && document.fullscreenElement === playerElement.value) void document.exitFullscreen().catch(() => undefined);
});
onMounted(() => document.addEventListener("fullscreenchange", syncFullscreen));
onUnmounted(() => document.removeEventListener("fullscreenchange", syncFullscreen));
return {
videoElement,
playerElement,
fullscreen,
resolutionOptions,
frameRateOptions,
resolutionPreset,
frameRate,
settingsOpen,
activeStream,
viewers,
viewerCount,
ownerName,
errorText,
setVideoElement,
streamForMember,
toggleForMember,
viewerStyle,
setVolume,
syncFullscreen,
toggleFullscreen,
startWithSettings,
};
}
@@ -0,0 +1,111 @@
import { computed, ref, type Ref } from "vue";
import {
listFavorites,
listRecentServers,
recordRecentServer,
removeFavorite,
saveFavorite,
type FavoriteServer,
type RecentServer,
} from "../services/local-persistence.js";
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
type Translator = (key: string, variables?: Record<string, string | number>) => string;
interface UseWebClientServerHistoryOptions {
serverHost: Ref<string>;
serverPort: Ref<string>;
nickname: Ref<string>;
channel: Ref<string>;
rememberIdentity: Ref<boolean>;
identityMaterial: Ref<string>;
t: Translator;
showToast: (message: string) => void;
}
export function useWebClientServerHistory({
serverHost,
serverPort,
nickname,
channel,
rememberIdentity,
identityMaterial,
t,
showToast,
}: UseWebClientServerHistoryOptions) {
const favoriteServers = ref<FavoriteServer[]>([]);
const recentServers = ref<RecentServer[]>([]);
const currentTarget = computed(() => combineTeamSpeakTarget(serverHost.value, serverPort.value));
const isFavorite = computed(() => favoriteServers.value.some((favorite) => favorite.id === serverKey(currentTarget.value)));
async function loadSavedServers(): Promise<void> {
const [favorites, recent] = await Promise.all([listFavorites(), listRecentServers()]);
favoriteServers.value = favorites;
recentServers.value = recent;
}
function recordCurrentServer(): void {
const address = currentTarget.value;
if (!address) return;
const recent: RecentServer = {
id: serverKey(address),
address,
...(nickname.value.trim() ? { nickname: nickname.value.trim() } : {}),
...(rememberIdentity.value && identityMaterial.value ? { identityId: "current" } : {}),
lastConnectedAt: Date.now(),
...(channel.value.trim() ? { lastChannelHint: { name: channel.value.trim() } } : {}),
};
void recordRecentServer(recent).then(() => listRecentServers().then((items) => { recentServers.value = items; }));
}
function selectLocalServer(address: string, savedNickname?: string): void {
const target = splitTeamSpeakTarget(address);
serverHost.value = target.address;
serverPort.value = target.port;
if (savedNickname && !nickname.value.trim()) nickname.value = savedNickname;
}
async function toggleFavorite(): Promise<void> {
const address = currentTarget.value;
if (!address) return;
const id = serverKey(address);
const existing = favoriteServers.value.find((favorite) => favorite.id === id);
if (existing) {
await removeFavorite(id);
favoriteServers.value = favoriteServers.value.filter((favorite) => favorite.id !== id);
showToast(t("removedFavoriteToast"));
return;
}
const favorite: FavoriteServer = {
id,
label: address,
address,
...(nickname.value.trim() ? { nickname: nickname.value.trim() } : {}),
...(rememberIdentity.value && identityMaterial.value ? { identityId: "current" } : {}),
...(channel.value.trim() ? { lastChannelHint: { name: channel.value.trim() } } : {}),
};
await saveFavorite(favorite);
favoriteServers.value = [...favoriteServers.value, favorite].sort((left, right) => left.label.localeCompare(right.label));
showToast(t("savedFavoriteToast"));
}
function clearServerHistory(): void {
favoriteServers.value = [];
recentServers.value = [];
}
return {
favoriteServers,
recentServers,
isFavorite,
loadSavedServers,
recordCurrentServer,
selectLocalServer,
toggleFavorite,
clearServerHistory,
};
}
function serverKey(address: string): string {
return address.trim().toLocaleLowerCase();
}
File diff suppressed because it is too large. Load diff
+47 -2
View File
@@ -1,8 +1,10 @@
const DB_NAME = "webspeak-local";
const DB_VERSION = 1;
const DB_VERSION = 2;
const CURRENT_IDENTITY_KEY = "current";
const PREFERENCES_KEY = "singleton";
import type { InstalledSkin } from "./skin-pack.js";
export interface StoredIdentity {
id: string;
label?: string;
@@ -33,6 +35,7 @@ export interface LocalPreferences {
schemaVersion: 1;
locale?: "auto" | "zh-CN" | "en";
theme?: "system" | "light" | "dark";
skinId?: string;
microphoneMuted?: boolean;
noiseSuppressionEnabled?: boolean;
voxThreshold?: number;
@@ -65,6 +68,7 @@ function openDatabase(): Promise<IDBDatabase> {
if (!database.objectStoreNames.contains("preferences")) database.createObjectStore("preferences", { keyPath: "id" });
if (!database.objectStoreNames.contains("favorites")) database.createObjectStore("favorites", { keyPath: "id" });
if (!database.objectStoreNames.contains("recent")) database.createObjectStore("recent", { keyPath: "id" });
if (!database.objectStoreNames.contains("skins")) database.createObjectStore("skins", { keyPath: "id" });
};
request.onsuccess = () => {
const database = request.result;
@@ -164,6 +168,47 @@ export async function saveLocalPreferences(preferences: LocalPreferences): Promi
}
}
export async function listInstalledSkins(): Promise<InstalledSkin[]> {
try {
const skins = await request<InstalledSkin[]>("skins", "readonly", (store, resolve, reject) => {
const get = store.getAll();
get.onsuccess = () => resolve(get.result as InstalledSkin[]);
get.onerror = () => reject(get.error);
});
return skins.sort((a, b) => a.name.localeCompare(b.name));
} catch {
return [];
}
}
export async function getInstalledSkin(id: string): Promise<InstalledSkin | null> {
try {
return await request<InstalledSkin | null>("skins", "readonly", (store, resolve, reject) => {
const get = store.get(id);
get.onsuccess = () => resolve((get.result as InstalledSkin | undefined) ?? null);
get.onerror = () => reject(get.error);
});
} catch {
return null;
}
}
export async function saveInstalledSkin(skin: InstalledSkin): Promise<void> {
await request("skins", "readwrite", (store, resolve, reject) => {
const put = store.put(skin);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
}
export async function removeInstalledSkin(id: string): Promise<void> {
await request("skins", "readwrite", (store, resolve, reject) => {
const remove = store.delete(id);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
}
export async function listFavorites(): Promise<FavoriteServer[]> {
try {
return await request<FavoriteServer[]>("favorites", "readonly", (store, resolve, reject) => {
@@ -243,7 +288,7 @@ async function removeRecentServer(id: string): Promise<void> {
export async function clearLocalData(): Promise<void> {
try {
const database = await openDatabase();
await Promise.all(["identities", "preferences", "favorites", "recent"].map((storeName) => new Promise<void>((resolve, reject) => {
await Promise.all(["identities", "preferences", "favorites", "recent", "skins"].map((storeName) => new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.objectStore(storeName).clear();
transaction.oncomplete = () => resolve();
+9
View File
@@ -0,0 +1,9 @@
/** Reduce built-in theme specificity while a community skin is active.
* The community skin is loaded after this stylesheet and should own appearance
* without needing !important or private component selectors.
*/
export function scopeBuiltinThemeForCustomSkin(css: string, theme: "light" | "dark", skinId: string): string {
const sourceRoot = `.ws-skin-root[data-ws-skin="builtin.${theme}"]`;
const customRoot = `:where(.ws-skin-root[data-ws-skin="${skinId}"])`;
return css.replaceAll(sourceRoot, customRoot);
}
+53
View File
@@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
BUILTIN_SKIN_CATALOG,
getPublicDefaultSkinId,
isPublicSkinEnabled,
listPublicSkins,
} from "./skin-catalog.js";
test("skin catalog always includes the three protected built-ins and exposes only enabled custom skins", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response(JSON.stringify({
defaultSkinId: "sample-skin",
skins: [
{ id: "sample-skin", name: "Sample", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5", installedAt: 1, enabled: true },
{ id: "disabled-skin", name: "Disabled", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5", installedAt: 2, enabled: false },
{ id: "community.illusia-voice", name: "Spoofed", version: "9.9.9", author: "Other", license: "MIT", minAppVersion: "0.0.1", installedAt: 3 },
],
}), { status: 200, headers: { "content-type": "application/json" } });
try {
const skins = await listPublicSkins();
assert.deepEqual(skins.map((skin) => skin.id), [
"builtin.light",
"builtin.dark",
"community.illusia-voice",
"sample-skin",
]);
assert.deepEqual(BUILTIN_SKIN_CATALOG.map((skin) => skin.id), skins.slice(0, 3).map((skin) => skin.id));
assert.equal(getPublicDefaultSkinId(), "sample-skin");
assert.equal(isPublicSkinEnabled("sample-skin"), true);
assert.equal(isPublicSkinEnabled("disabled-skin"), false);
assert.equal(isPublicSkinEnabled("community.illusia-voice"), true);
} finally {
globalThis.fetch = originalFetch;
}
});
test("invalid or disabled instance defaults safely fall back to the protected day skin", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response(JSON.stringify({
defaultSkinId: "disabled-skin",
skins: [{ id: "disabled-skin", name: "Disabled", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5", installedAt: 2, enabled: false }],
}), { status: 200, headers: { "content-type": "application/json" } });
try {
const skins = await listPublicSkins();
assert.equal(skins.length, 3);
assert.equal(getPublicDefaultSkinId(), "builtin.light");
} finally {
globalThis.fetch = originalFetch;
}
});
+144
View File
@@ -0,0 +1,144 @@
export interface SkinCatalogEntry {
id: string;
name: string;
version: string;
author: string;
license: string;
description?: string;
minAppVersion: string;
previewUrl?: string;
installedAt: number;
builtIn?: boolean;
enabled?: boolean;
previewKind?: "day" | "night" | "illusia";
}
export const BUILTIN_ILLUSIA_SKIN_ID = "community.illusia-voice";
export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
{
id: "builtin.light",
name: "Day mode",
version: "1.0.0",
author: "WebSpeak",
license: "AGPL-3.0-only",
description: "The default light appearance.",
minAppVersion: "0.2.5",
installedAt: 0,
builtIn: true,
previewKind: "day",
},
{
id: "builtin.dark",
name: "Night mode",
version: "1.0.0",
author: "WebSpeak",
license: "AGPL-3.0-only",
description: "The default dark appearance.",
minAppVersion: "0.2.5",
installedAt: 0,
builtIn: true,
previewKind: "night",
},
{
id: BUILTIN_ILLUSIA_SKIN_ID,
name: "ILLUSIA风",
version: "1.0.27",
author: "WebSpeak Project",
license: "All rights reserved",
description: "A bright original-character art skin for the home, voice room, and demo pages.",
minAppVersion: "0.2.5",
previewUrl: "/skins/illusia-voice-preview.webp",
installedAt: 0,
builtIn: true,
previewKind: "illusia",
},
];
const BUILTIN_ILLUSIA_PACKAGE_URL = "/skins/illusia-voice.wskin";
let publicDirectoryLoaded = false;
let publicEnabledSkinIds = new Set<string>(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
let publicDefaultSkinId = "builtin.light";
export function getPublicDefaultSkinId(): string {
return isPublicSkinEnabled(publicDefaultSkinId) ? publicDefaultSkinId : "builtin.light";
}
export function isPublicSkinEnabled(id: string): boolean {
if (BUILTIN_SKIN_CATALOG.some((skin) => skin.id === id)) return true;
return !publicDirectoryLoaded || publicEnabledSkinIds.has(id);
}
export function getBundledSkinPackageUrl(id: string): string | null {
return id === BUILTIN_ILLUSIA_SKIN_ID ? BUILTIN_ILLUSIA_PACKAGE_URL : null;
}
export async function listPublicSkins(): Promise<SkinCatalogEntry[]> {
publicDirectoryLoaded = false;
publicEnabledSkinIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
publicDefaultSkinId = "builtin.light";
try {
const response = await fetch("/api/skins", { headers: { accept: "application/json" }, cache: "no-cache" });
if (!response.ok) return BUILTIN_SKIN_CATALOG;
const payload: unknown = await response.json();
if (!payload || typeof payload !== "object" || !Array.isArray((payload as { skins?: unknown }).skins)) return BUILTIN_SKIN_CATALOG;
const directorySkins = (payload as { skins: unknown[] }).skins.flatMap((value) => {
if (!value || typeof value !== "object") return [];
const skin = value as Record<string, unknown>;
if (typeof skin.id !== "string" || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(skin.id) || skin.id.startsWith("builtin.") || skin.id === BUILTIN_ILLUSIA_SKIN_ID) return [];
if ([skin.name, skin.version, skin.author, skin.license, skin.minAppVersion].some((field) => typeof field !== "string")) return [];
const previewUrl = typeof skin.previewUrl === "string" && skin.previewUrl === `/api/skins/${skin.id}/preview` ? skin.previewUrl : undefined;
return [{
id: skin.id,
name: skin.name as string,
version: skin.version as string,
author: skin.author as string,
license: skin.license as string,
minAppVersion: skin.minAppVersion as string,
...(typeof skin.description === "string" ? { description: skin.description } : {}),
...(previewUrl ? { previewUrl } : {}),
installedAt: Number.isFinite(skin.installedAt) ? Number(skin.installedAt) : 0,
enabled: skin.enabled !== false,
}];
});
publicDirectoryLoaded = true;
publicEnabledSkinIds = new Set([
...BUILTIN_SKIN_CATALOG.map((skin) => skin.id),
...directorySkins.filter((skin) => skin.enabled).map((skin) => skin.id),
]);
const requestedDefault = (payload as { defaultSkinId?: unknown }).defaultSkinId;
publicDefaultSkinId = typeof requestedDefault === "string" && publicEnabledSkinIds.has(requestedDefault) ? requestedDefault : "builtin.light";
return [...BUILTIN_SKIN_CATALOG, ...directorySkins.filter((skin) => skin.enabled)];
} catch {
publicDirectoryLoaded = false;
publicEnabledSkinIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
publicDefaultSkinId = "builtin.light";
return BUILTIN_SKIN_CATALOG;
}
}
export async function uploadSkinPackage(file: File, csrfToken: string, confirmReplace?: (id: string) => boolean): Promise<SkinCatalogEntry | null> {
const { importSkinPack } = await import("./skin-pack.js");
const skin = await importSkinPack(file);
if (confirmReplace && !confirmReplace(skin.id)) return null;
const response = await fetch(`/api/admin/skins/${encodeURIComponent(skin.id)}`, {
method: "PUT",
headers: { "content-type": "application/octet-stream", "x-csrf-token": csrfToken, accept: "application/json" },
body: file,
});
const payload = await response.json().catch(() => null) as { skin?: SkinCatalogEntry; message?: string; code?: string } | null;
if (!response.ok || !payload?.skin) throw new Error(payload?.message || payload?.code || `HTTP_${response.status}`);
return payload.skin;
}
export async function deleteSkinPackage(id: string, csrfToken: string): Promise<void> {
const response = await fetch(`/api/admin/skins/${encodeURIComponent(id)}`, {
method: "DELETE",
headers: { "content-type": "application/json", "x-csrf-token": csrfToken, accept: "application/json" },
body: "{}",
});
if (!response.ok) {
const payload = await response.json().catch(() => null) as { code?: string } | null;
throw new Error(payload?.code || `HTTP_${response.status}`);
}
}
+234
View File
@@ -0,0 +1,234 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { strToU8, zipSync } from "fflate";
import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js";
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
const manifest = {
schemaVersion: 1,
id: "ocean-night",
name: "Ocean Night",
version: "1.0.0",
author: "WebSpeak test",
license: "MIT",
minAppVersion: "0.2.4",
entry: "skin.css",
};
test("skin CSS is scoped, local artwork and fonts work, and global names are isolated", async () => {
const skin = await importSkinPack(makeSkin(`
@font-face { font-family: "Wave Font"; src: url("assets/wave.woff2") format("woff2"); }
@keyframes shimmer { from { opacity: .4; } to { opacity: 1; } }
:root { --skin-accent: #00a99d; }
[data-ws-part="voice.member"] { font-family: "Wave Font", sans-serif; animation: shimmer 1s ease-in-out; background-image: image-set("assets/backdrop.png" 1x); }
`));
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="ocean-night"\] \{ --skin-accent: #00a99d; \}/);
assert.match(skin.css, /@keyframes ws-ocean-night-shimmer/);
assert.match(skin.css, /animation: ws-ocean-night-shimmer/);
assert.match(skin.css, /font-family: "ws-ocean-night-Wave-Font"/);
assert.match(skin.css, /url\("wskin-asset:assets%2Fwave\.woff2"\)/);
assert.match(skin.css, /image-set\("wskin-asset:assets%2Fbackdrop\.png" 1x\)/);
assert.ok(skin.warnings.some((warning) => warning.includes("localized text wrapping")));
assert.equal(skin.contentData, undefined, "skin content is optional; WebSpeak supplies the base interface translations");
const resolved = resolveSkinCssAssets(skin.css, skin.assets);
assert.match(resolved.css, /blob:/);
resolved.objectUrls.forEach((url) => URL.revokeObjectURL(url));
});
test("skin CSS permits visual decoration but prevents layout, text-flow, and control-geometry changes", async () => {
const skin = await importSkinPack(makeSkin('@keyframes fade-wave { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="demo.wave"] { opacity: var(--skin-decoration-opacity); animation: fade-wave 1s; box-shadow: 0 0 14px #4ff; }'));
assert.match(skin.css, /opacity: var\(--skin-decoration-opacity\)/);
assert.match(skin.css, /box-shadow: 0 0 14px #4ff/);
assert.match(skin.css, /from \{ opacity: 0; \}/);
assert.match(skin.css, /animation: ws-ocean-night-fade-wave 1s/);
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { position: fixed; inset: 0; z-index: 99999; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.member"] { padding: 30px; transform: scale(1.2); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { font-size: 3rem; line-height: 1; white-space: nowrap; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { text-transform: uppercase; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { opacity: 0; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.wave"] span { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: var(--skin-hidden); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { all: unset; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="voice.screen-player.exit"] { animation: hide-control 1s infinite; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="control"] { animation: var(--custom-animation); }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { --accent: red; }')), (error: unknown) => error instanceof Error && error.message.includes("--skin- prefix"));
await assert.rejects(importSkinPack(makeSkin(".internal-class { color: red; }")), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.voice-card"].private-component { color: red; }')), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: image-set("https://example.invalid/remote.png" 1x); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
});
test("custom skins can override theme appearance without !important or private class selectors", () => {
const css = '.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card { color: white; }';
assert.equal(
scopeBuiltinThemeForCustomSkin(css, "dark", "community.illusia-voice"),
':where(.ws-skin-root[data-ws-skin="community.illusia-voice"]) .join-page .join-card { color: white; }',
);
});
test("community skins use a scoped light fallback instead of inheriting the night skin", async () => {
const lightCss = await readFile(new URL("../skins/builtin/light/skin.css", import.meta.url), "utf8");
const scoped = scopeBuiltinThemeForCustomSkin(lightCss, "light", "community.illusia-voice");
assert.match(scoped, /:where\(\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]\) \{\s*color-scheme: light;/);
assert.match(scoped, /:where\(\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]\) \.settings-content/);
});
test("all public skin parts are documented and the admin console is outside skin scope", async () => {
const [webClient, demo, skinSwitcher, languageSwitcher, admin, documentation] = await Promise.all([
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
readFile(new URL("../views/DemoView.vue", import.meta.url), "utf8"),
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../views/AdminView.vue", import.meta.url), "utf8"),
readFile(new URL("../../../docs/SKIN_DEVELOPMENT.md", import.meta.url), "utf8"),
]);
const publicParts = new Set([...`${webClient}\n${demo}\n${skinSwitcher}\n${languageSwitcher}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
for (const part of publicParts) assert.ok(documentation.includes(`\`${part}\``), `Undocumented skin part: ${part}`);
assert.match(skinSwitcher, /data-ws-skin-id/);
assert.match(skinSwitcher, /data-ws-state/);
assert.match(languageSwitcher, /data-ws-language/);
assert.doesNotMatch(admin, /ws-skin-root|data-ws-page=/);
assert.doesNotMatch(demo, /:global\(:root\[data-theme="dark"\]\)/);
assert.match(demo, /\.demo-page\[data-ws-skin="builtin\.dark"\]/);
});
test("public skin and language selectors keep readable light surfaces in dark mode", async () => {
const [skinSwitcher, languageSwitcher, darkSkin] = await Promise.all([
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../skins/builtin/dark/skin.css", import.meta.url), "utf8"),
]);
assert.match(skinSwitcher, /\.skin-trigger\s*\{[^}]*background:\s*rgba\(250,\s*254,\s*255/i);
assert.match(skinSwitcher, /\.skin-dropdown\s*\{[^}]*background:\s*linear-gradient/i);
assert.match(skinSwitcher, /\.skin-option\s*\{[^}]*color:\s*#123849/i);
assert.match(languageSwitcher, /\.language-dropdown\s*\{[^}]*background:\s*#fff/i);
assert.doesNotMatch(darkSkin, /\.language-switcher\s+\.language-(?:trigger|dropdown|option)/);
});
test("skin content supports localized interface message overrides and includes the preview as an asset", async () => {
const content = { defaultLocale: "en", locales: { en: { home: { title: "Welcome" }, messages: { speakingNow: "Live now" } } } };
const skin = await importSkinPack(makeSkin('[data-ws-part="demo.voice-card"] { background: url(assets/preview.png); }', content));
assert.equal(skin.contentData?.locales.en?.messages?.speakingNow, "Live now");
assert.equal(skin.previewBlob?.type, "image/png");
assert.ok(skin.assets["assets/preview.png"]);
});
test("the ILLUSIA visual-only example imports without replacing WebSpeak's base translations", async () => {
const bytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
const skin = await importSkinPack(new File([bytes], "illusia-voice.wskin", { type: "application/octet-stream" }));
assert.equal(skin.id, "community.illusia-voice");
assert.equal(skin.name, "ILLUSIA风");
assert.equal(skin.version, "1.0.27");
assert.equal(skin.contentData, undefined);
assert.equal(skin.previewBlob?.type, "image/webp");
assert.ok(skin.assets["assets/background-composite.webp"]);
assert.ok(skin.assets["assets/bg-room-main.webp"]);
assert.ok(skin.assets["assets/banner-character-main.webp"]);
assert.ok(skin.assets["assets/foreground-headphone.webp"]);
assert.ok(skin.assets["assets/chat-empty-chibi.webp"]);
assert.ok(skin.assets["assets/visitor-avatar.webp"]);
assert.ok(skin.assets["assets/button-mascot.webp"]);
assert.ok(skin.assets["assets/footer-wave.png"]);
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]/);
assert.match(skin.css, /home\.visitors.*?nth-child\(2\)/s);
assert.match(skin.css, /skin\.menu/);
assert.match(skin.css, /skin\.menu[^{}]*\[role="listbox"\]/);
assert.match(skin.css, /skin\.option/);
assert.match(skin.css, /language\.trigger/);
assert.match(skin.css, /language\.menu[^{}]*\[role="listbox"\]/);
assert.match(skin.css, /language\.option/);
assert.match(skin.css, /data-ws-skin-id="community\.illusia-voice"/);
assert.match(skin.css, /data-ws-part="home\.join-card\.waveform"/);
assert.match(skin.css, /data-ws-part="home\.join-card\.sonar"/);
assert.match(skin.css, /data-ws-part="home\.join-card"\]\s*\{[^}]*background-image:\s*url\("wskin-asset:assets%2Fbanner-mascot-blob\.webp"\)/s);
assert.doesNotMatch(skin.css, /data-ws-part="home\.join-card"\]\s*\{[^}]*radial-gradient/s);
assert.match(skin.css, /data-ws-part="voice\.member-panel"\]\s*\{[^}]*background-position:\s*0 0, right top, right top, center/s);
assert.match(skin.css, /data-ws-part="voice\.member-panel"\]\s*::before\s*\{[^}]*background-image:\s*url\("wskin-asset:assets%2Fforeground-headphone\.webp"\)[^}]*filter:\s*drop-shadow/s);
assert.doesNotMatch(skin.css, /illusia-card-signal|illusia-card-glow/);
assert.match(skin.css, /illusia-home-aura/);
assert.match(skin.css, /voice\.activity[\s\S]*?wskin-asset:assets%2Fbanner-character-main\.webp/);
assert.match(skin.css, /voice\.activity\.artwork[\s\S]*?wskin-asset:assets%2Fbanner-character-main\.webp/);
assert.match(skin.css, /data-ws-part="voice\.activity"\]\s*\{[^}]*border-color:\s*rgba\(113, 211, 222, \.62\);[^}]*border-radius:\s*24px;[^}]*background-image:[\s\S]*?bg-room-main\.webp[^}]*backdrop-filter:\s*blur\(10px\)/);
assert.match(skin.css, /voice\.activity\.artwork[^{}]*\{[^}]*background-position:\s*right 16px bottom 8px;[^}]*background-size:\s*auto 150px;[^}]*filter:\s*drop-shadow\(0 18px 22px/);
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.activity\.artwork[^{}]*\{[^}]*background-position:\s*right 12px bottom 6px;[^}]*background-size:\s*auto 118px/);
assert.doesNotMatch(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"\]\s*> :first-child/);
assert.match(skin.css, /data-ws-part="voice\.channel-group"\]\s*\{[^}]*border-color:\s*rgba\(8, 126, 134, \.32\)/);
assert.match(skin.css, /data-ws-part="voice\.channel-group"\]\[data-ws-state="current"\]\s*\{[^}]*border-color:\s*rgba\(8, 126, 134, \.48\)/);
assert.match(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[\s\S]*?wskin-asset:assets%2Fchat-empty-chibi\.webp/);
assert.match(skin.css, /voice\.chat\.empty[^{}]*\{[^}]*background-size:\s*22px 22px, 300px 250px, cover, min\(340px, 46vw\) auto/s);
assert.match(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[^{}]*\{[^}]*background-position:\s*0 0, right center, center, center 8px;[^}]*background-size:\s*22px 22px, 300px 250px, cover, min\(340px, 46vw\) auto/s);
assert.match(skin.css, /data-ws-state="messages-empty"\]::before\s*\{[^}]*color:\s*rgba\(71, 126, 148, \.9\);[^}]*radial-gradient\(circle, #527f91 0 1\.6px/s);
assert.match(skin.css, /data-ws-state="messages-empty"\]::after\s*\{[^}]*color:\s*rgba\(71, 126, 148, \.9\)/s);
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*\{[^}]*background-position:\s*0 0, right 8px center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s);
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[^{}]*\{[^}]*background-position:\s*0 0, right center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s);
assert.doesNotMatch(skin.css, /data-ws-state="messages-empty"[^{}]*\{[^}]*color: transparent/s);
assert.doesNotMatch(skin.css, /(?:^|[;{\s])(?:position|inset|top|right|bottom|left|width|height|min-height|padding|z-index|transform)\s*:/);
assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{[^}]*animation:/);
assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{\s*animation: none;/);
assert.match(skin.css, /home\.footer[\s\S]*?footer-wave\.png/);
assert.match(skin.css, /\[data-ws-part="home"\] \[data-ws-part="home\.connect"\]/);
assert.doesNotMatch(skin.css, /\[data-ws-page="home"\] \[data-ws-part="home\.connect"\]/);
assert.match(skin.css, /home\.connect[\s\S]*?wskin-asset:assets%2Fbutton-mascot\.webp/);
assert.match(skin.css, /data-ws-page="demo"[^{}]*\{[^}]*wskin-asset:assets%2Fforeground-headphone\.webp[^}]*background-position:\s*left bottom, center, center;[^}]*background-size:\s*min\(34vw, 430px\) auto, auto, cover/s);
assert.match(skin.css, /voice\.screen-player[\s\S]*?background: linear-gradient\(135deg, rgba\(250, 255, 255, \.96\), rgba\(220, 245, 250, \.94\)\)/);
assert.doesNotMatch(skin.css, /voice\.screen-player[^{}]*\{[^}]*background: rgba\(10, 34, 45, \.96\)/);
});
test("the activity artwork layer floats above room content without intercepting controls", async () => {
const css = await readFile(new URL("../styles/web-client.css", import.meta.url), "utf8");
assert.match(css, /\.app-shell \.workspace-content\s*\{\s*position: relative;\s*isolation: isolate;/);
assert.match(css, /\.voice-activity-artwork\s*\{\s*position: absolute;\s*z-index: 2;\s*inset: -26px 0 -48px;[^}]*pointer-events: none;/);
assert.match(css, /\.voice-activity-artwork\s*\{[^}]*transform: perspective\(1100px\) rotateY\(-2\.5deg\) translateZ\(22px\)/);
assert.match(css, /\.app-shell \.member-panel::before\s*\{\s*content: "";\s*position: absolute;\s*z-index: 1;\s*left: -28px;\s*bottom: 18px;\s*width: min\(430px, calc\(100vw - 24px\)\);\s*aspect-ratio: 3 \/ 2;[^}]*perspective\(1100px\) rotateY\(-8deg\)/);
assert.match(css, /\.app-shell \.chat-empty\[data-ws-state="messages-empty"\]\s*\{[^}]*min-height: 210px;\s*padding: 126px 12px 10px;/);
assert.match(css, /\.app-shell \.chat-panel \.section-heading,[\s\S]*?\.app-shell \.chat-panel \.message-composer\s*\{\s*position: relative;\s*z-index: 3;/);
assert.match(css, /\.screen-share-player\s*\{[^}]*background: var\(--surface-1\)/);
assert.match(css, /\.screen-share-player-exit\s*\{[^}]*z-index: 3;/);
assert.match(css, /\.screen-share-player-stage\s*\{[^}]*var\(--accent\)[^}]*var\(--surface-2\)/);
assert.match(css, /\.screen-share-player-video\s*\{[^}]*background: var\(--surface-2\)/);
assert.match(css, /@media \(min-width: 741px\)\s*\{\s*\/\* Keep header menus above the independently stacked screen-share stage\. \*\/\s*\.app-shell \.workspace-header\s*\{\s*position: relative;\s*z-index: 40;/);
});
test("channel empty state removes its bubble ornament and keeps the text-channel label", async () => {
const [view, chat] = await Promise.all([
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
readFile(new URL("../composables/useWebClientChat.ts", import.meta.url), "utf8"),
]);
assert.doesNotMatch(view, /data-ws-state="messages-empty"><div class="chat-empty-icon"/);
assert.match(view, /class="section-kicker">\{\{ chatTabLabel \}\}/);
assert.match(chat, /tab\.value === "channel" \? t\("textChannel"\)/);
});
test("homepage motion and room content spacing preserve the ILLUSIA layout", async () => {
const css = await readFile(new URL("../styles/web-client.css", import.meta.url), "utf8");
assert.ok(css.includes('.join-page *:not([data-ws-part="home.join-card"])'));
assert.ok(css.includes("animation: none !important"));
assert.doesNotMatch(css, /\.join-page \*, \.join-page \*::before, \.join-page \*::after\s*\{\s*animation: none !important/);
assert.ok(css.includes("padding: 0 clamp(12px, 1.4vw, 22px);"), "homepage header contents keep an inset from their container edge");
assert.ok(css.includes(".chat-panel { margin-top: 34px; padding: 0 clamp(14px, 1.8vw, 24px) 20px;"), "chat children keep horizontal and bottom breathing room");
assert.match(css, /\.app-shell \.voice-section \{\s*position: relative;\s*padding: clamp\(14px, 1\.8vw, 24px\);/);
assert.match(css, /@media \(max-width: 740px\) \{\s*\.app-shell \.voice-section \{\s*padding: 14px 10px 16px;/);
assert.match(css, /\.promise-list \{\s*display: grid;\s*width: 100%;\s*grid-template-columns: repeat\(3, minmax\(0, 1fr\)\);/);
assert.match(css, /\.promise-item \{\s*min-width: 0;\s*min-height: 58px;[\s\S]*?padding: 9px 11px;/);
assert.match(css, /@media \(max-width: 420px\) \{\s*\.promise-list \{\s*grid-template-columns: minmax\(0, 1fr\);/);
assert.match(css, /\.join-card-waveform i \{[^}]*animation: screen-share-wave 1\.1s ease-in-out infinite alternate;/);
assert.match(css, /@keyframes join-card-sonar-ring[\s\S]*?transform: scale\(\.6\); opacity: \.62;[\s\S]*?transform: scale\(1\); opacity: 0;/);
});
function makeSkin(css: string, content?: unknown): File {
const packageFiles: Record<string, Uint8Array> = {
"manifest.json": strToU8(JSON.stringify({ ...manifest, ...(content ? { content: "content.json" } : {}), preview: "assets/preview.png" })),
"skin.css": strToU8(css),
"assets/backdrop.png": new Uint8Array([1, 2, 3, 4]),
"assets/preview.png": new Uint8Array([5, 6, 7, 8]),
"assets/wave.woff2": new Uint8Array([9, 10, 11, 12]),
};
if (content) packageFiles["content.json"] = strToU8(JSON.stringify(content));
const bytes = zipSync(packageFiles);
return new File([bytes.slice().buffer as ArrayBuffer], "skin.wskin", { type: "application/octet-stream" });
}
+718
View File
@@ -0,0 +1,718 @@
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
import { unzipSync } from "fflate";
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
const MAX_FILE_COUNT = 128;
const MAX_CSS_BYTES = 512 * 1024;
const MAX_CONTENT_BYTES = 256 * 1024;
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
const MAX_FONT_BYTES = 4 * 1024 * 1024;
const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]);
const LAYOUT_AFFECTING_PROPERTIES = new Set([
"all", "display", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline",
"width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size",
"min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", "box-sizing",
"gap", "row-gap", "column-gap", "grid", "flex", "order", "float", "clear", "overflow", "overflow-x",
"overflow-y", "overflow-block", "overflow-inline", "overscroll-behavior", "z-index", "visibility",
"pointer-events", "clip", "clip-path", "mask", "mask-image", "transform", "transform-origin", "transform-style", "translate", "scale", "rotate",
"perspective", "perspective-origin", "contain", "content-visibility", "container", "container-name",
"container-type", "contain-intrinsic-size", "resize", "columns", "column-count", "column-width", "scrollbar-width", "font",
"font-size", "line-height", "letter-spacing", "word-spacing", "white-space", "word-break", "overflow-wrap", "word-wrap",
"text-wrap", "text-overflow", "text-indent", "text-transform", "text-combine-upright", "text-autospace", "text-spacing-trim",
"line-clamp", "tab-size", "hyphens", "line-break", "text-size-adjust", "initial-letter", "shape-outside", "baseline-shift",
"box-orient", "box-direction", "box-lines", "ruby-position", "caption-side", "table-layout", "border-collapse", "border-spacing",
"writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content",
"position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope",
]);
const OPTIONAL_VISUAL_PARTS = new Set([
"home.hero.eyebrow",
"home.gateway-status",
"home.features",
"home.feature",
"home.visitors",
"home.join-card.waveform",
"home.join-card.sonar",
"voice.activity-heading",
"voice.member.avatar",
"voice.member.live-indicator",
"voice.member-row.avatar",
"voice.screen-player.viewer-avatar",
"voice.screen-player.live",
"demo.badge",
"demo.wave",
"demo.avatar",
"demo.member-status",
"demo.note",
]);
const ZIP_EOCD = 0x06054b50;
const ZIP_CENTRAL_FILE = 0x02014b50;
export interface SkinManifest {
schemaVersion: 1;
id: string;
name: string;
version: string;
author: string;
license: string;
description?: string;
entry: string;
content?: string;
minAppVersion: string;
preview?: string;
}
export interface SkinFeatureCopy {
title: string;
description: string;
}
export interface SkinHomeCopy {
brandName?: string;
eyebrow?: string;
title?: string;
titleAccent?: string;
description?: string;
welcomeTitle?: string;
welcomeDescription?: string;
features?: SkinFeatureCopy[];
}
export interface SkinContent {
defaultLocale: string;
locales: Record<string, { home?: SkinHomeCopy; messages?: Record<string, string> }>;
}
export interface InstalledSkin extends SkinManifest {
css: string;
assets: Record<string, Blob>;
contentData?: SkinContent;
previewBlob?: Blob;
warnings: string[];
installedAt: number;
}
export class SkinPackError extends Error {
constructor(message: string, readonly code: string) {
super(message);
this.name = "SkinPackError";
}
}
interface ZipEntryMetadata {
path: string;
compressedSize: number;
expandedSize: number;
compression: number;
isDirectory: boolean;
flags: number;
crc: number;
localOffset: number;
}
const decoder = new TextDecoder("utf-8", { fatal: true });
export async function importSkinPack(file: File): Promise<InstalledSkin> {
if (!file.name.toLowerCase().endsWith(".wskin")) throw new SkinPackError("Choose a .wskin skin package.", "SKIN_FILE_TYPE");
if (!file.size || file.size > MAX_ARCHIVE_BYTES) throw new SkinPackError("The skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
const archiveBytes = new Uint8Array(await file.arrayBuffer());
const metadata = inspectZip(archiveBytes);
let unpacked: Record<string, Uint8Array>;
try {
unpacked = unzipSync(archiveBytes);
} catch {
throw new SkinPackError("The skin package is damaged or uses an unsupported ZIP format.", "SKIN_ZIP_INVALID");
}
const regularFiles = metadata.filter((entry) => !entry.isDirectory);
const rootPrefix = findSingleRootFolder(regularFiles.map((entry) => entry.path));
const files = new Map<string, Uint8Array>();
for (const entry of regularFiles) {
const path = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path;
if (!path || path.startsWith("/") || path.split("/").some((part) => !part || part === "." || part === "..")) {
throw new SkinPackError("The package contains an unsafe file path.", "SKIN_PATH_INVALID");
}
const bytes = unpacked[entry.path];
if (!bytes || bytes.byteLength !== entry.expandedSize) throw new SkinPackError("A package file failed its size check.", "SKIN_ZIP_INVALID");
files.set(path, bytes);
}
const manifestBytes = files.get("manifest.json");
if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinPackError("The package must contain a small root-level manifest.json.", "SKIN_MANIFEST_MISSING");
const manifest = parseManifest(manifestBytes);
const cssBytes = files.get(manifest.entry);
if (!cssBytes || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
for (const [path, bytes] of files) {
if (["manifest.json", manifest.entry, manifest.content].includes(path)) continue;
const mimeType = assetMimeType(path);
if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED");
if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
if (mimeType.startsWith("image/") && bytes.byteLength > MAX_IMAGE_BYTES) throw new SkinPackError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
assets[path] = new Blob([bytes], { type: mimeType });
}
let contentData: SkinContent | undefined;
if (manifest.content) {
const contentBytes = files.get(manifest.content);
if (!contentBytes || contentBytes.byteLength > MAX_CONTENT_BYTES) throw new SkinPackError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
contentData = parseContent(contentBytes);
}
let previewBlob: Blob | undefined;
if (manifest.preview) {
const previewBytes = files.get(manifest.preview);
const previewMime = assetMimeType(manifest.preview);
if (!previewBytes || !previewMime?.startsWith("image/") || previewBytes.byteLength > MAX_IMAGE_BYTES) {
throw new SkinPackError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID");
}
previewBlob = new Blob([previewBytes], { type: previewMime });
}
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets);
return { ...manifest, css: compiled.css, assets, contentData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
}
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
const objectUrls: string[] = [];
try {
const root = postcss.parse(css, { from: undefined });
root.walkDecls((declaration) => {
declaration.value = rewriteAssetUrls(declaration.value, (assetPath) => {
const blob = assets[assetPath];
if (!blob) throw new SkinPackError(`Skin asset is missing: ${assetPath}`, "SKIN_ASSET_MISSING");
const url = URL.createObjectURL(blob);
objectUrls.push(url);
return url;
});
});
return { css: root.toString(), objectUrls };
} catch (error) {
objectUrls.forEach((url) => URL.revokeObjectURL(url));
throw error;
}
}
function inspectZip(bytes: Uint8Array): ZipEntryMetadata[] {
if (bytes.byteLength < 22) throw new SkinPackError("The selected file is not a valid ZIP package.", "SKIN_ZIP_INVALID");
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
let eocd = -1;
for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) {
if (view.getUint32(offset, true) === ZIP_EOCD) { eocd = offset; break; }
}
if (eocd < 0) throw new SkinPackError("The selected file is not a valid ZIP package.", "SKIN_ZIP_INVALID");
const disk = view.getUint16(eocd + 4, true);
const centralDisk = view.getUint16(eocd + 6, true);
const entriesOnDisk = view.getUint16(eocd + 8, true);
const entryCount = view.getUint16(eocd + 10, true);
const centralSize = view.getUint32(eocd + 12, true);
const centralOffset = view.getUint32(eocd + 16, true);
const commentLength = view.getUint16(eocd + 20, true);
if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || !entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || eocd + 22 + commentLength !== bytes.byteLength) {
throw new SkinPackError("Multi-disk and ZIP64 skin packages are not supported.", "SKIN_ZIP_FORMAT");
}
if (entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== eocd) throw new SkinPackError("The package contains too many files or an invalid directory.", "SKIN_FILE_COUNT");
const entries: ZipEntryMetadata[] = [];
const seenPaths = new Set<string>();
let expandedTotal = 0;
let compressedTotal = 0;
let offset = centralOffset;
for (let index = 0; index < entryCount; index += 1) {
if (offset + 46 > eocd || view.getUint32(offset, true) !== ZIP_CENTRAL_FILE) throw new SkinPackError("The package has an invalid ZIP directory entry.", "SKIN_ZIP_INVALID");
const flags = view.getUint16(offset + 8, true);
const compression = view.getUint16(offset + 10, true);
const compressedSize = view.getUint32(offset + 20, true);
const expandedSize = view.getUint32(offset + 24, true);
const nameLength = view.getUint16(offset + 28, true);
const extraLength = view.getUint16(offset + 30, true);
const commentSize = view.getUint16(offset + 32, true);
const diskStart = view.getUint16(offset + 34, true);
const externalAttributes = view.getUint32(offset + 38, true);
const localOffset = view.getUint32(offset + 42, true);
const recordEnd = offset + 46 + nameLength + extraLength + commentSize;
if (recordEnd > eocd || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) throw new SkinPackError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT");
const unixFileType = (externalAttributes >>> 16) & 0xf000;
if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinPackError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE");
let rawName: string;
try { rawName = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); }
catch { throw new SkinPackError("A package path is not valid UTF-8.", "SKIN_PATH_INVALID"); }
const path = validateArchivePath(rawName);
const isDirectory = path.endsWith("/");
if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinPackError("ZIP file type does not match its path.", "SKIN_FILE_TYPE");
if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinPackError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID");
if (compression === 0 && compressedSize !== expandedSize) throw new SkinPackError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID");
if (seenPaths.has(path.toLowerCase())) throw new SkinPackError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE");
seenPaths.add(path.toLowerCase());
expandedTotal += expandedSize;
compressedTotal += compressedSize;
if (expandedTotal > MAX_EXPANDED_BYTES) throw new SkinPackError("The expanded skin package must be smaller than 50 MiB.", "SKIN_EXPANDED_SIZE");
if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinPackError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO");
entries.push({ path, compressedSize, expandedSize, compression, isDirectory, flags, crc: view.getUint32(offset + 16, true), localOffset });
offset = recordEnd;
}
if (offset !== centralOffset + centralSize || compressedTotal > bytes.byteLength) throw new SkinPackError("The package directory is inconsistent.", "SKIN_ZIP_INVALID");
validateLocalEntries(bytes, entries, centralOffset);
return entries;
}
function validateLocalEntries(bytes: Uint8Array, entries: ZipEntryMetadata[], centralOffset: number): void {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const spans: Array<{ start: number; end: number }> = [];
for (const entry of entries) {
const offset = entry.localOffset;
if (offset + 30 > centralOffset || view.getUint32(offset, true) !== 0x04034b50) throw new SkinPackError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
const flags = view.getUint16(offset + 6, true);
const compression = view.getUint16(offset + 8, true);
const crc = view.getUint32(offset + 14, true);
const compressedSize = view.getUint32(offset + 18, true);
const expandedSize = view.getUint32(offset + 22, true);
const nameLength = view.getUint16(offset + 26, true);
const extraLength = view.getUint16(offset + 28, true);
const headerEnd = offset + 30 + nameLength + extraLength;
if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) {
throw new SkinPackError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID");
}
let localPath: string;
try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); }
catch { throw new SkinPackError("A package path is not valid UTF-8.", "SKIN_PATH_INVALID"); }
if (localPath !== entry.path) throw new SkinPackError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID");
const end = headerEnd + entry.compressedSize;
if (end > centralOffset) throw new SkinPackError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID");
spans.push({ start: offset, end });
}
spans.sort((left, right) => left.start - right.start);
for (let index = 1; index < spans.length; index += 1) {
if (spans[index].start < spans[index - 1].end) throw new SkinPackError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID");
}
}
function validateArchivePath(rawPath: string): string {
if (!rawPath || rawPath.includes("\\") || rawPath.startsWith("/") || /^[a-z]:/i.test(rawPath) || rawPath.includes("\0")) {
throw new SkinPackError("The package contains an absolute or unsafe path.", "SKIN_PATH_INVALID");
}
const segments = rawPath.split("/");
const directory = segments.at(-1) === "";
const usableSegments = directory ? segments.slice(0, -1) : segments;
if (!usableSegments.length || usableSegments.some((segment) => !segment || segment === "." || segment === ".." || segment.includes(":"))) {
throw new SkinPackError("The package contains an unsafe path segment.", "SKIN_PATH_INVALID");
}
return usableSegments.join("/") + (directory ? "/" : "");
}
function findSingleRootFolder(paths: string[]): string {
if (paths.includes("manifest.json")) return "";
const firstSegments = paths.map((path) => path.split("/")[0]);
const candidate = firstSegments[0];
if (!candidate || !paths.every((path) => path.startsWith(`${candidate}/`))) return "";
return `${candidate}/`;
}
function parseManifest(bytes: Uint8Array): SkinManifest {
let value: unknown;
try { value = JSON.parse(decoder.decode(bytes)); }
catch { throw new SkinPackError("manifest.json must contain valid UTF-8 JSON.", "SKIN_MANIFEST_INVALID"); }
if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
const raw = value as Record<string, unknown>;
const stringField = (key: string, max: number, required = true): string | undefined => {
const field = raw[key];
if (field == null && !required) return undefined;
if (typeof field !== "string" || !field.trim() || field.length > max) throw new SkinPackError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
return field.trim();
};
if (raw.schemaVersion !== 1) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
const id = stringField("id", 80)!;
if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID");
const entry = stringField("entry", 120)!;
const content = stringField("content", 120, false);
const preview = stringField("preview", 120, false);
for (const path of [entry, content, preview].filter((item): item is string => Boolean(item))) {
if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID");
}
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
const version = stringField("version", 32)!;
const minAppVersion = stringField("minAppVersion", 32)!;
if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
const declaredFiles = ["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
return {
schemaVersion: 1,
id,
name: stringField("name", 80)!,
version,
author: stringField("author", 80)!,
license: stringField("license", 80)!,
description: stringField("description", 400, false),
entry,
content,
minAppVersion,
preview,
};
}
function parseContent(bytes: Uint8Array): SkinContent {
let raw: unknown;
try { raw = JSON.parse(decoder.decode(bytes)); }
catch { throw new SkinPackError("content.json must contain valid UTF-8 JSON.", "SKIN_CONTENT_INVALID"); }
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinPackError("content.json must be an object.", "SKIN_CONTENT_INVALID");
const root = raw as Record<string, unknown>;
if (typeof root.defaultLocale !== "string" || !/^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(root.defaultLocale) || !root.locales || typeof root.locales !== "object" || Array.isArray(root.locales)) throw new SkinPackError("content.json needs a valid defaultLocale and locales.", "SKIN_CONTENT_INVALID");
const localeEntries = Object.entries(root.locales as Record<string, unknown>);
if (!localeEntries.length || localeEntries.length > 20) throw new SkinPackError("content.json must contain between 1 and 20 locales.", "SKIN_CONTENT_INVALID");
const allowed = new Set<keyof SkinHomeCopy>(["brandName", "eyebrow", "title", "titleAccent", "description", "welcomeTitle", "welcomeDescription", "features"]);
const locales: SkinContent["locales"] = {};
for (const [locale, entry] of localeEntries) {
if (!/^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(locale) || !entry || typeof entry !== "object" || Array.isArray(entry)) throw new SkinPackError("content.json contains an invalid locale entry.", "SKIN_CONTENT_INVALID");
const localeValue = entry as Record<string, unknown>;
const localeCopy: SkinContent["locales"][string] = {};
if (localeValue.home !== undefined) {
if (!localeValue.home || typeof localeValue.home !== "object" || Array.isArray(localeValue.home)) throw new SkinPackError("A locale home section must be an object.", "SKIN_CONTENT_INVALID");
const homeCopy: SkinHomeCopy = {};
for (const [key, field] of Object.entries(localeValue.home as Record<string, unknown>)) {
if (!allowed.has(key as keyof SkinHomeCopy)) throw new SkinPackError(`Unknown homepage content field: ${key}`, "SKIN_CONTENT_INVALID");
if (key === "features") {
if (!Array.isArray(field) || field.length > 8) throw new SkinPackError("Each locale may define up to 8 homepage features.", "SKIN_CONTENT_INVALID");
homeCopy.features = field.map((item) => {
if (!item || typeof item !== "object" || Array.isArray(item)) throw new SkinPackError("A homepage feature must be an object.", "SKIN_CONTENT_INVALID");
const feature = item as Record<string, unknown>;
if (typeof feature.title !== "string" || typeof feature.description !== "string" || feature.title.length > 80 || feature.description.length > 240) throw new SkinPackError("Homepage feature text is too long or invalid.", "SKIN_CONTENT_INVALID");
return { title: feature.title, description: feature.description };
});
} else if (typeof field === "string" && field.length <= 500) {
homeCopy[key as Exclude<keyof SkinHomeCopy, "features">] = field;
} else {
throw new SkinPackError(`Invalid or oversized homepage content field: ${key}`, "SKIN_CONTENT_INVALID");
}
}
localeCopy.home = homeCopy;
}
if (localeValue.messages !== undefined) {
if (!localeValue.messages || typeof localeValue.messages !== "object" || Array.isArray(localeValue.messages)) throw new SkinPackError("Locale messages must be an object.", "SKIN_CONTENT_INVALID");
const messageEntries = Object.entries(localeValue.messages as Record<string, unknown>);
if (messageEntries.length > 200) throw new SkinPackError("Each locale may override up to 200 interface strings.", "SKIN_CONTENT_INVALID");
const messages: Record<string, string> = {};
for (const [key, text] of messageEntries) {
if (!/^[a-z][a-zA-Z0-9.]*$/.test(key) || typeof text !== "string" || text.length > 500) throw new SkinPackError("A locale message key or value is invalid or too long.", "SKIN_CONTENT_INVALID");
messages[key] = text;
}
localeCopy.messages = messages;
}
if (!localeCopy.home && !localeCopy.messages) throw new SkinPackError("Each locale must define home content or messages.", "SKIN_CONTENT_INVALID");
locales[locale] = localeCopy;
}
if (!locales[root.defaultLocale]) throw new SkinPackError("defaultLocale must have a matching content entry.", "SKIN_CONTENT_INVALID");
return { defaultLocale: root.defaultLocale, locales };
}
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
let root: postcss.Root;
try { root = postcss.parse(source, { from: undefined }); }
catch (error) { throw new SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); }
const scope = `.ws-skin-root[data-ws-skin="${id}"]`;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
const keyframeNames = new Map<string, string>();
const fontFamilyNames = new Map<string, string>();
const hideableRules = new WeakSet<Rule>();
let nodeCount = 0;
root.walk((node) => {
nodeCount += 1;
if (nodeCount > 12000) throw new SkinPackError("The CSS file contains too many rules.", "SKIN_CSS_COMPLEXITY");
});
root.walkAtRules((rule: AtRule) => {
const name = rule.name.toLowerCase();
if (!ALLOWED_AT_RULES.has(name)) throw rule.error(`The @${rule.name} rule is not allowed in a skin package.`);
if (name.endsWith("keyframes")) {
const keyframeName = rule.params.trim();
if (!/^[-_a-z][-_a-z0-9]*$/i.test(keyframeName)) throw rule.error("Keyframe names must be simple CSS identifiers.");
keyframeNames.set(keyframeName, `${namespace}-${keyframeName}`);
rule.params = `${namespace}-${keyframeName}`;
} else if (name === "layer") {
const layers = rule.params.split(",").map((layer) => layer.trim());
if (!layers.length || layers.some((layer) => !layer || !layer.split(".").every((part) => /^[-_a-z][-_a-z0-9]*$/i.test(part)))) {
throw rule.error("Skin CSS must use named @layer values so layer names can be isolated.");
}
rule.params = layers.map((layer) => `${namespace}-${layer.split(".").join(`.${namespace}-`)}`).join(", ");
} else if (name === "font-face") {
if (/\blocal\s*\(/i.test(rule.toString())) throw rule.error("@font-face local() is not allowed; include a WOFF2 file in the package.");
const family = rule.nodes?.find((node): node is Declaration => node.type === "decl" && node.prop.toLowerCase() === "font-family");
if (!family) throw rule.error("Each @font-face rule must declare font-family.");
const originalFamily = parseSingleFontFamily(family.value);
const scopedFamily = `${namespace}-${originalFamily.replace(/[^a-z0-9_-]/gi, "-")}`;
fontFamilyNames.set(originalFamily.toLowerCase(), scopedFamily);
family.value = `"${scopedFamily}"`;
}
});
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors.");
if (!selectorUsesPublicHook(rule.selector)) throw rule.error("Skin selectors must use :root, [data-ws-page], or [data-ws-part] so they stay attached to WebSpeak's stable visual interface.");
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
try {
rule.selector = selectorParser((selectors) => {
selectors.each((selector) => {
const text = selector.toString().trim();
if (!text) throw new SkinPackError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinPackError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/^:root\b/.test(text)) {
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone());
return;
}
selector.prepend(selectorParser.combinator({ value: " " }));
for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone());
});
}).processSync(rule.selector);
} catch (error) {
if (error instanceof SkinPackError) throw error;
throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`);
}
});
const referencedKeyframes = new Set<string>();
const nonOptionalKeyframes = new Set<string>();
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
const optionalTarget = hideableRules.has(rule);
rule.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
if (property !== "animation" && property !== "animation-name") return;
const value = declaration.value;
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
return;
}
for (const name of keyframeNames.keys()) {
if (!referencesCssIdentifier(value, name)) continue;
referencedKeyframes.add(name);
if (!optionalTarget) nonOptionalKeyframes.add(name);
}
});
});
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
.filter((name) => !nonOptionalKeyframes.has(name))
.map((name) => keyframeNames.get(name)!));
root.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
const value = declaration.value.trim();
const owningRule = findOwningRule(declaration);
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)) {
throw declaration.error("Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
}
if (isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
}
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(value)) {
throw declaration.error("Executable CSS values are not allowed.");
}
const compactValue = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("").toLowerCase();
if (["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) {
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
}
const removesVisual = property === "all"
|| (property === "display" && compactValue === "none")
|| (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue))
|| (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue))
|| (property === "pointer-events" && compactValue === "none")
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
if (removesVisual && !canHideTarget) {
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
}
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(value))
|| (property === "clip-path" && /inset\(\s*50%/i.test(value))
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(value));
if (visuallyRemoves && !canHideTarget) {
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
}
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${value}`) || (property === "position" && value === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
const blob = assets[assetPath];
if (!blob) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
return `wskin-asset:${encodeURIComponent(assetPath)}`;
});
});
return { css: root.toString(), warnings: [...warnings] };
}
function targetsOnlyOptionalVisualParts(selector: string): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
if (item.nodes.length !== 1 || item.nodes[0].type !== "attribute") return false;
const attribute = item.nodes[0];
if (attribute.attribute.toLowerCase() !== "data-ws-part" || attribute.operator !== "=") return false;
const part = (attribute.value ?? "").replace(/^['"]|['"]$/g, "");
return OPTIONAL_VISUAL_PARTS.has(part);
});
} catch {
return false;
}
}
function selectorUsesPublicHook(selector: string): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
let scoped = false;
let usesPrivateName = false;
item.walk((node) => {
if (node.type === "attribute" && ["data-ws-part", "data-ws-page"].includes(node.attribute.toLowerCase())) scoped = true;
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true;
if (node.type === "class" || node.type === "id") usesPrivateName = true;
});
return scoped && !usesPrivateName;
});
} catch {
return false;
}
}
function isLayoutAffectingProperty(property: string): boolean {
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
}
function findOwningRule(node: Node): Rule | null {
let parent = node.parent;
while (parent && parent.type !== "root") {
if (parent.type === "rule") return parent as Rule;
parent = parent.parent;
}
return null;
}
function findKeyframesRule(rule: Rule): AtRule | null {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /(?:^|-)?keyframes$/i.test(parent.name)) return parent as AtRule;
parent = parent.parent;
}
return null;
}
function referencesCssIdentifier(value: string, identifier: string): boolean {
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
}
function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
const parsed = valueParser(value);
const resolvePackageAsset = (rawValue: string): string => {
const raw = rawValue.trim();
if (!raw || raw.startsWith("#")) throw new SkinPackError("CSS images and fonts must point to assets inside this skin package.", "SKIN_EXTERNAL_RESOURCE");
const isInternalMarker = raw.startsWith("wskin-asset:");
if (!isInternalMarker && /^(?:data:|blob:|https?:|\/\/|file:|javascript:)/i.test(raw)) throw new SkinPackError("Only relative paths to assets inside this skin package are allowed in url().", "SKIN_EXTERNAL_RESOURCE");
let path: string;
try { path = isInternalMarker ? decodeURIComponent(raw.slice("wskin-asset:".length)) : normalizeAssetPath(raw); }
catch { throw new SkinPackError("A skin asset reference is invalid.", "SKIN_ASSET_PATH"); }
return resolve(path);
};
const visit = (nodes: typeof parsed.nodes, inImageSet = false): void => {
for (const node of nodes) {
if (node.type === "function" && node.value.toLowerCase() === "url") {
const raw = valueParser.stringify(node.nodes).trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2").trim();
node.nodes = [{ type: "string", quote: '"', value: resolvePackageAsset(raw), sourceIndex: 0, sourceEndIndex: 0, unclosed: undefined }];
node.before = "";
node.after = "";
continue;
}
if (node.type === "function" && (node.value.toLowerCase() === "image-set" || node.value.toLowerCase() === "-webkit-image-set")) {
for (const child of node.nodes) {
if (child.type === "string") child.value = resolvePackageAsset(child.value);
else if (child.type === "function") visit([child]);
}
continue;
}
if (node.type === "function") visit(node.nodes, inImageSet);
else if (inImageSet && node.type === "string") node.value = resolvePackageAsset(node.value);
}
};
visit(parsed.nodes);
return parsed.toString();
}
function parseSingleFontFamily(value: string): string {
const parsed = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment");
if (parsed.length !== 1 || (parsed[0].type !== "string" && parsed[0].type !== "word") || !parsed[0].value.trim()) {
throw new SkinPackError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY");
}
return parsed[0].value.trim();
}
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
const parsed = valueParser(value);
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
parsed.walk((node) => {
if (node.type !== "word" && node.type !== "string") return;
const keyframe = keyframes.get(node.value);
if (keyframe) node.value = keyframe;
const family = fontFamilies.get(node.value.toLowerCase());
if (family) node.value = family;
});
}
return parsed.toString();
}
function normalizeAssetPath(raw: string): string {
let path = raw.split(/[?#]/, 1)[0];
try { path = decodeURIComponent(path); } catch { throw new SkinPackError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); }
if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinPackError("An asset URL must be a relative package path.", "SKIN_ASSET_PATH");
const segments: string[] = [];
for (const segment of path.split("/")) {
if (!segment || segment === ".") continue;
if (segment === "..") {
if (!segments.length) throw new SkinPackError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH");
segments.pop();
} else {
segments.push(segment);
}
}
if (!segments.length) throw new SkinPackError("An asset URL must point to a package file.", "SKIN_ASSET_PATH");
return segments.join("/");
}
function hasKeyframesAncestor(rule: Rule): boolean {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /keyframes$/i.test(parent.name)) return true;
parent = parent.parent;
}
return false;
}
function assetMimeType(path: string): string | null {
const extension = path.split(".").at(-1)?.toLowerCase();
switch (extension) {
case "png": return "image/png";
case "jpg": case "jpeg": return "image/jpeg";
case "webp": return "image/webp";
case "avif": return "image/avif";
case "gif": return "image/gif";
case "woff2": return "font/woff2";
default: return null;
}
}
+158
View File
@@ -0,0 +1,158 @@
import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js";
import type { InstalledSkin } from "./skin-pack.js";
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
export const BUILTIN_LIGHT_SKIN = "builtin.light";
export const BUILTIN_DARK_SKIN = "builtin.dark";
const CUSTOM_STYLE_ID = "webspeak-active-custom-skin";
const CUSTOM_BASE_STYLE_ID = "webspeak-active-custom-skin-base";
let activeAssetUrls: string[] = [];
let criticalControlObserver: MutationObserver | null = null;
export function getStoredSkinId(): string | null {
return typeof localStorage === "undefined" ? null : localStorage.getItem(ACTIVE_SKIN_KEY);
}
export function storeSkinId(id: string): void {
if (typeof localStorage !== "undefined") localStorage.setItem(ACTIVE_SKIN_KEY, id);
}
export async function activateStoredSkin(): Promise<InstalledSkin | null> {
const storedId = getStoredSkinId();
const legacyTheme = getStoredTheme();
const selectedId = storedId || (isDarkTheme(legacyTheme) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN);
storeSkinId(selectedId);
return activateSkin(selectedId);
}
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.5"): Promise<InstalledSkin | null> {
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
clearCustomSkinStyle();
applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light");
markCoreControls();
storeSkinId(id);
return null;
}
if (!isPublicSkinEnabled(id)) {
if (typeof localStorage !== "undefined") localStorage.removeItem("webspeak:skin-choice");
return fallBackToBuiltin();
}
let skin = await getInstalledSkin(id);
if (!skin || (expectedVersion && skin.version !== expectedVersion)) {
try {
const packageUrl = getBundledSkinPackageUrl(id) ?? `/api/skins/${encodeURIComponent(id)}/package`;
const response = await fetch(packageUrl, { cache: "no-cache" });
if (!response.ok) throw new Error("Skin package is no longer available.");
const archive = await response.blob();
const file = new File([archive], `${id}.wskin`, { type: "application/octet-stream" });
const { importSkinPack } = await import("./skin-pack.js");
const downloaded = await importSkinPack(file);
if (downloaded.id !== id) throw new Error("Skin package ID does not match its catalog entry.");
if (expectedVersion && downloaded.version !== expectedVersion) throw new Error("Skin package version does not match its catalog entry.");
skin = downloaded;
await saveInstalledSkin(downloaded).catch(() => undefined);
} catch {
if (!skin) return fallBackToBuiltin();
}
}
if (!isVersionCompatible(appVersion, skin.minAppVersion)) return fallBackToBuiltin();
try {
const { resolveSkinCssAssets } = await import("./skin-pack.js");
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
// A community skin is a complete appearance choice, not an overlay on the
// previously selected day/night skin. Keep the document theme (used by the
// independent admin appearance) but give unstyled public parts a light,
// neutral fallback. A custom skin can opt into dark colors itself.
applyTheme(getStoredTheme());
let baseStyle = document.getElementById(CUSTOM_BASE_STYLE_ID) as HTMLStyleElement | null;
if (!baseStyle) {
baseStyle = document.createElement("style");
baseStyle.id = CUSTOM_BASE_STYLE_ID;
document.head.append(baseStyle);
}
baseStyle.dataset.skinPackage = skin.id;
baseStyle.textContent = scopeBuiltinThemeForCustomSkin(getBuiltinSkinCss("light"), "light", skin.id);
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
clientRoot.dataset.wsSkin = skin!.id;
});
markCoreControls();
let style = document.getElementById(CUSTOM_STYLE_ID) as HTMLStyleElement | null;
if (!style) {
style = document.createElement("style");
style.id = CUSTOM_STYLE_ID;
document.head.append(style);
}
style.dataset.skinPackage = skin.id;
style.textContent = compiled.css;
const previousAssetUrls = activeAssetUrls;
activeAssetUrls = compiled.objectUrls;
previousAssetUrls.forEach((url) => URL.revokeObjectURL(url));
storeSkinId(id);
return skin;
} catch {
return fallBackToBuiltin();
}
}
function fallBackToBuiltin(): null {
const fallback = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
clearCustomSkinStyle();
applyTheme(fallback === BUILTIN_DARK_SKIN ? "dark" : "light");
storeSkinId(fallback);
return null;
}
export function clearCustomSkinStyle(): void {
document.getElementById(CUSTOM_STYLE_ID)?.remove();
document.getElementById(CUSTOM_BASE_STYLE_ID)?.remove();
activeAssetUrls.forEach((url) => URL.revokeObjectURL(url));
activeAssetUrls = [];
}
function isVersionCompatible(current: string, minimum: string): boolean {
const parse = (value: string) => /^(\d+)\.(\d+)\.(\d+)/.exec(value)?.slice(1).map(Number);
const currentParts = parse(current);
const minimumParts = parse(minimum);
if (!currentParts || !minimumParts) return false;
for (let index = 0; index < 3; index += 1) {
if (currentParts[index] > minimumParts[index]) return true;
if (currentParts[index] < minimumParts[index]) return false;
}
return true;
}
function markCoreControls(): void {
const roots = [...document.querySelectorAll<HTMLElement>(".ws-skin-root")];
const selector = "button, a[href], input, select, textarea, [role='button'], [role='menuitem'], [draggable='true']";
const markElement = (element: HTMLElement) => {
element.dataset.wsCritical = "true";
element.dataset.wsPart ||= "control";
const role = element.getAttribute("role");
const type = element instanceof HTMLInputElement ? element.type : "";
element.dataset.wsControlKind = role === "menuitem" ? "menuitem" : role === "button" ? "button" : element instanceof HTMLInputElement && type === "range" ? "range" : element instanceof HTMLInputElement && type === "checkbox" ? "checkbox" : element instanceof HTMLInputElement ? "input" : element instanceof HTMLTextAreaElement ? "textarea" : element instanceof HTMLSelectElement ? "select" : element instanceof HTMLAnchorElement ? "link" : element instanceof HTMLButtonElement ? "button" : "draggable";
};
const mark = (root: ParentNode) => {
if (root instanceof HTMLElement && root.matches(selector)) markElement(root);
root.querySelectorAll<HTMLElement>(selector).forEach(markElement);
};
roots.forEach(mark);
if (!criticalControlObserver) {
criticalControlObserver = new MutationObserver((records) => {
for (const record of records) for (const node of record.addedNodes) {
if (!(node instanceof HTMLElement)) continue;
const clientRoot = node.matches(".ws-skin-root") ? node : node.closest<HTMLElement>(".ws-skin-root");
if (!clientRoot) continue;
mark(node);
}
});
criticalControlObserver.observe(document.getElementById("app") ?? document.body, { childList: true, subtree: true });
}
}
+49 -2
View File
@@ -1,15 +1,53 @@
export type ThemeMode = "system" | "light" | "dark";
import lightManifest from "../skins/builtin/light/manifest.json";
import lightCss from "../skins/builtin/light/skin.css?inline";
import darkManifest from "../skins/builtin/dark/manifest.json";
import darkCss from "../skins/builtin/dark/skin.css?inline";
const THEME_KEY = "webspeak:theme";
const SKIN_STYLE_ELEMENT_ID = "webspeak-active-built-in-skin";
let activeThemeMode: ThemeMode = "system";
const builtinSkins = {
light: { manifest: lightManifest, css: lightCss },
dark: { manifest: darkManifest, css: darkCss },
} as const;
export function getBuiltinSkinCss(theme: Exclude<ThemeMode, "system">): string {
return theme === "dark" ? builtinSkins.dark.css : builtinSkins.light.css;
}
export function getStoredTheme(): ThemeMode {
const value = typeof localStorage === "undefined" ? "" : localStorage.getItem(THEME_KEY);
return value === "light" || value === "dark" || value === "system" ? value : "system";
}
export function applyTheme(theme: ThemeMode): void {
export function applyTheme(theme: ThemeMode, options: { preserveCustomSkins?: boolean } = {}): void {
if (typeof document === "undefined") return;
document.documentElement.dataset.theme = theme;
activeThemeMode = theme;
const root = document.documentElement;
const activeSkin = isDarkTheme(theme) ? builtinSkins.dark : builtinSkins.light;
// Keep data-theme for the admin console's independent appearance rules.
// Built-in skin CSS is scoped to public roots and can never restyle /admin.
root.dataset.theme = theme;
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
const currentSkin = clientRoot.dataset.wsSkin;
const isCustomSkin = currentSkin !== builtinSkins.light.manifest.id && currentSkin !== builtinSkins.dark.manifest.id;
if (options.preserveCustomSkins && currentSkin && isCustomSkin) return;
clientRoot.dataset.wsSkin = activeSkin.manifest.id;
});
let style = document.getElementById(SKIN_STYLE_ELEMENT_ID) as HTMLStyleElement | null;
if (!style) {
style = document.createElement("style");
style.id = SKIN_STYLE_ELEMENT_ID;
style.dataset.skinPackage = activeSkin.manifest.id;
document.head.append(style);
}
style.dataset.skinPackage = activeSkin.manifest.id;
style.textContent = activeSkin.css;
}
export function saveTheme(theme: ThemeMode): void {
@@ -30,3 +68,12 @@ export function nextTheme(theme: ThemeMode): ThemeMode {
}
applyTheme(getStoredTheme());
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
const systemColorScheme = window.matchMedia("(prefers-color-scheme: dark)");
const updateSystemSkin = () => {
if (activeThemeMode === "system") applyTheme("system", { preserveCustomSkins: true });
};
if (systemColorScheme.addEventListener) systemColorScheme.addEventListener("change", updateSystemSkin);
else systemColorScheme.addListener?.(updateSystemSkin);
}
+11
View File
@@ -0,0 +1,11 @@
{
"schemaVersion": 1,
"id": "builtin.dark",
"name": "WebSpeak Dark",
"version": "1.0.0",
"author": "WebSpeak",
"license": "AGPL-3.0-only",
"description": "The built-in dark appearance for public WebSpeak pages.",
"entry": "skin.css",
"minAppVersion": "0.2.5"
}
+282
View File
@@ -0,0 +1,282 @@
/* Built-in package: builtin.dark. Scoped to public WebSpeak pages only. */
.ws-skin-root[data-ws-skin="builtin.dark"] {
color-scheme: dark;
--ws-page-bg: #101918;
--ws-surface-1: #172321;
--ws-surface-2: #202f2c;
--ws-text: #e8f3f0;
--ws-text-muted: #9bb0aa;
--ws-accent: #69d2c7;
--ws-success: #78e489;
--ws-warning: #e2b36c;
--ws-danger: #ee8a82;
--ws-border: #30413d;
--surface-0: var(--ws-page-bg);
--surface-1: var(--ws-surface-1);
--surface-2: var(--ws-surface-2);
--text-primary: var(--ws-text);
--text-muted: var(--ws-text-muted);
--accent: var(--ws-accent);
--success: var(--ws-success);
--warning: var(--ws-warning);
--danger: var(--ws-danger);
--border: var(--ws-border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] {
background: var(--surface-0);
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page {
color: var(--text-primary);
background-color: var(--surface-0);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .app-shell,
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace {
background: var(--surface-1);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-header,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel,
.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-modal {
background: var(--surface-1);
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-header {
border-bottom-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-content {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-card {
background: color-mix(in srgb, var(--surface-1) 94%, transparent);
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .field-wrap,
.ws-skin-root[data-ws-skin="builtin.dark"] .message-composer,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-search,
.ws-skin-root[data-ws-skin="builtin.dark"] .mic-mode-switch,
.ws-skin-root[data-ws-skin="builtin.dark"] .mode-note {
background: var(--surface-2);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .field-wrap input,
.ws-skin-root[data-ws-skin="builtin.dark"] .message-composer input,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-search input,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-select {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .room-hero {
background: linear-gradient(110deg, color-mix(in srgb, var(--accent) 18%, var(--surface-1)), var(--surface-1) 75%);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-modal {
box-shadow: 0 7px 18px color-mix(in srgb, var(--text-primary) 8%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .section-heading h2,
.ws-skin-root[data-ws-skin="builtin.dark"] .room-hero h1,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-card h2,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel-heading h2,
.ws-skin-root[data-ws-skin="builtin.dark"] .message-meta strong,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-copy strong {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .section-kicker,
.ws-skin-root[data-ws-skin="builtin.dark"] .card-kicker,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-label,
.ws-skin-root[data-ws-skin="builtin.dark"] .header-note,
.ws-skin-root[data-ws-skin="builtin.dark"] .section-counter,
.ws-skin-root[data-ws-skin="builtin.dark"] .message-meta time,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-copy span,
.ws-skin-root[data-ws-skin="builtin.dark"] .chat-empty,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-description,
.ws-skin-root[data-ws-skin="builtin.dark"] .card-lead {
color: var(--text-muted);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .chat-panel,
.ws-skin-root[data-ws-skin="builtin.dark"] .chat-heading,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-header,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-footer,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-separator {
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .message-bubble {
color: var(--text-primary);
background: var(--surface-2);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-content,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-nav {
background: var(--surface-1);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-nav {
border-right-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-section h3,
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-header h2 {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-select {
color: var(--text-primary);
background: var(--surface-2);
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .audio-level-track,
.ws-skin-root[data-ws-skin="builtin.dark"] .meter i {
background: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .member-presence {
border-color: var(--surface-1);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .member-row:hover,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-row:focus-within {
background: color-mix(in srgb, var(--accent) 10%, var(--surface-1));
box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 8%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] :focus-visible {
outline-color: color-mix(in srgb, var(--accent) 55%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal {
color: var(--text-primary);
border-color: var(--border);
background: var(--surface-1);
box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal h2 { color: var(--text-primary); }
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal > p { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-icon {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 13%, var(--surface-2));
}
.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice {
color: #b8eee3;
background: #183530;
border-color: #2b645b;
}
.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice small { color: #91b9b0; }
.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice select {
color: #d9f8f1;
background: #203f39;
border-color: #3b766d;
}
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-panel {
color: var(--text-primary);
background: var(--surface-1);
border-color: var(--border);
box-shadow: 0 18px 42px color-mix(in srgb, #000 38%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu strong { color: var(--text-primary); }
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu button { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu button:hover {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 14%, var(--surface-2));
}
.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-panel button small,
.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-empty { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .breadcrumbs { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .breadcrumbs strong,
.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card > strong { color: var(--text-primary); }
.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-heading { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-group.current .member-channel-heading {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 14%, var(--surface-1));
}
.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-group.current .member-channel-heading small { color: var(--accent); }
.ws-skin-root[data-ws-skin="builtin.dark"] .brand-lockup strong { color: var(--accent); }
.ws-skin-root[data-ws-skin="builtin.dark"] .brand-lockup strong span { color: var(--text-primary); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .brand-lockup small,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .header-note,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-description,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item small,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .card-lead,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-hint,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-meta,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count {
color: #b7fff0;
border-color: rgba(105, 210, 199, .42);
background: linear-gradient(110deg, #173b36, #1c2d2a);
box-shadow: 0 10px 28px rgba(0, 0, 0, .24), inset 0 0 0 1px rgba(105, 210, 199, .08);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count::before {
background: linear-gradient(105deg, transparent, rgba(125, 255, 174, .18), transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count-orbit { border-color: rgba(105, 210, 199, .34); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card h2,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item b,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-label { color: var(--text-primary); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 em,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .eyebrow,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .card-kicker,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-label span,
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer a { color: var(--accent); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card {
background: color-mix(in srgb, var(--surface-1) 94%, transparent);
border-color: var(--border);
box-shadow: 0 20px 52px color-mix(in srgb, var(--text-primary) 14%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap { color: var(--text-muted); background: var(--surface-2); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap input { color: var(--text-primary); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-card {
color: var(--text-primary);
border-color: var(--border);
background: var(--surface-1);
box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-heading h2 { color: var(--text-primary); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-direct-join { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-close {
color: var(--text-muted);
background: var(--surface-2);
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-join-link {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, var(--surface-2));
border-color: color-mix(in srgb, var(--accent) 30%, var(--border));
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-join-link:hover {
color: var(--surface-1);
background: var(--accent);
border-color: var(--accent);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap input::placeholder { color: var(--text-muted); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer { border-top-color: var(--border); }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 {
color: #f3fffb;
text-shadow: 0 1px 0 #07100f, 0 0 9px rgba(243, 255, 251, .16);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 em {
color: #7dffae;
text-shadow: 0 0 10px rgba(125, 255, 174, .38), 0 0 22px rgba(105, 210, 199, .18);
animation-name: join-accent-breathe-dark;
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-description {
color: #c4d9d3;
text-shadow: 0 0 8px rgba(196, 217, 211, .12);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item b {
color: #f0fff9;
text-shadow: 0 0 7px rgba(240, 255, 249, .14);
}
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item small { color: #a9c6be; }
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-icon { box-shadow: 0 0 12px rgba(105, 210, 199, .14); }
.ws-skin-root[data-ws-skin="builtin.dark"],
.ws-skin-root[data-ws-skin="builtin.dark"] * {
scrollbar-color: #438f88 transparent;
scrollbar-width: thin;
}
.ws-skin-root[data-ws-skin="builtin.dark"] *::-webkit-scrollbar-thumb {
background: #438f88;
border-color: transparent;
}
.ws-skin-root[data-ws-skin="builtin.dark"] *::-webkit-scrollbar-thumb:hover { background: #69c7bc; }
@keyframes join-accent-breathe-dark {
0%, 100% { transform: translateY(0); text-shadow: 0 0 8px rgba(125, 255, 174, .28), 0 0 18px rgba(105, 210, 199, .14); }
50% { transform: translateY(-2px); text-shadow: 0 0 13px rgba(125, 255, 174, .5), 0 0 26px rgba(105, 210, 199, .22); }
}
+11
View File
@@ -0,0 +1,11 @@
{
"schemaVersion": 1,
"id": "builtin.light",
"name": "WebSpeak Light",
"version": "1.0.0",
"author": "WebSpeak",
"license": "AGPL-3.0-only",
"description": "The built-in light appearance for public WebSpeak pages.",
"entry": "skin.css",
"minAppVersion": "0.2.5"
}
+150
View File
@@ -0,0 +1,150 @@
/* Built-in package: builtin.light. All rules stay inside the public client. */
.ws-skin-root[data-ws-skin="builtin.light"] {
color-scheme: light;
--ws-page-bg: #f7f9f8;
--ws-surface-1: #fff;
--ws-surface-2: #f1f6f4;
--ws-text: #192120;
--ws-text-muted: #71807c;
--ws-accent: #006a64;
--ws-success: #65d879;
--ws-warning: #c89143;
--ws-danger: #c95a54;
--ws-border: #e4ece9;
--surface-0: var(--ws-page-bg);
--surface-1: var(--ws-surface-1);
--surface-2: var(--ws-surface-2);
--text-primary: var(--ws-text);
--text-muted: var(--ws-text-muted);
--accent: var(--ws-accent);
--success: var(--ws-success);
--warning: var(--ws-warning);
--danger: var(--ws-danger);
--border: var(--ws-border);
}
.ws-skin-root[data-ws-skin="builtin.light"] {
background: var(--surface-0);
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.light"] .join-page {
color: var(--text-primary);
background-color: var(--surface-0);
}
.ws-skin-root[data-ws-skin="builtin.light"] .app-shell,
.ws-skin-root[data-ws-skin="builtin.light"] .workspace {
background: var(--surface-1);
}
.ws-skin-root[data-ws-skin="builtin.light"] .workspace-header,
.ws-skin-root[data-ws-skin="builtin.light"] .member-panel,
.ws-skin-root[data-ws-skin="builtin.light"] .voice-card,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-modal {
background: var(--surface-1);
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.light"] .workspace-header {
border-bottom-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.light"] .workspace-content {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.light"] .join-card {
background: color-mix(in srgb, var(--surface-1) 92%, transparent);
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.light"] .field-wrap,
.ws-skin-root[data-ws-skin="builtin.light"] .message-composer,
.ws-skin-root[data-ws-skin="builtin.light"] .member-search,
.ws-skin-root[data-ws-skin="builtin.light"] .mic-mode-switch,
.ws-skin-root[data-ws-skin="builtin.light"] .mode-note {
background: var(--surface-2);
}
.ws-skin-root[data-ws-skin="builtin.light"] .field-wrap input,
.ws-skin-root[data-ws-skin="builtin.light"] .message-composer input,
.ws-skin-root[data-ws-skin="builtin.light"] .member-search input,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-select {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.light"] .room-hero {
background: linear-gradient(110deg, color-mix(in srgb, var(--accent) 18%, var(--surface-1)), var(--surface-1) 75%);
}
.ws-skin-root[data-ws-skin="builtin.light"] .voice-card,
.ws-skin-root[data-ws-skin="builtin.light"] .member-panel,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-modal {
box-shadow: 0 7px 18px color-mix(in srgb, var(--text-primary) 8%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.light"] .section-heading h2,
.ws-skin-root[data-ws-skin="builtin.light"] .room-hero h1,
.ws-skin-root[data-ws-skin="builtin.light"] .join-card h2,
.ws-skin-root[data-ws-skin="builtin.light"] .member-panel-heading h2,
.ws-skin-root[data-ws-skin="builtin.light"] .message-meta strong,
.ws-skin-root[data-ws-skin="builtin.light"] .member-copy strong {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.light"] .section-kicker,
.ws-skin-root[data-ws-skin="builtin.light"] .card-kicker,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-label,
.ws-skin-root[data-ws-skin="builtin.light"] .header-note,
.ws-skin-root[data-ws-skin="builtin.light"] .section-counter,
.ws-skin-root[data-ws-skin="builtin.light"] .message-meta time,
.ws-skin-root[data-ws-skin="builtin.light"] .member-copy span,
.ws-skin-root[data-ws-skin="builtin.light"] .chat-empty,
.ws-skin-root[data-ws-skin="builtin.light"] .join-description,
.ws-skin-root[data-ws-skin="builtin.light"] .card-lead {
color: var(--text-muted);
}
.ws-skin-root[data-ws-skin="builtin.light"] .chat-panel,
.ws-skin-root[data-ws-skin="builtin.light"] .chat-heading,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-header,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-footer,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-separator {
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.light"] .message-bubble {
color: var(--text-primary);
background: var(--surface-2);
}
.ws-skin-root[data-ws-skin="builtin.light"] .settings-content,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-nav {
background: var(--surface-1);
}
.ws-skin-root[data-ws-skin="builtin.light"] .settings-nav {
border-right-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.light"] .settings-section h3,
.ws-skin-root[data-ws-skin="builtin.light"] .settings-header h2 {
color: var(--text-primary);
}
.ws-skin-root[data-ws-skin="builtin.light"] .settings-select {
color: var(--text-primary);
background: var(--surface-2);
border-color: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.light"] .audio-level-track,
.ws-skin-root[data-ws-skin="builtin.light"] .meter i {
background: var(--border);
}
.ws-skin-root[data-ws-skin="builtin.light"] .member-presence {
border-color: var(--surface-1);
}
.ws-skin-root[data-ws-skin="builtin.light"] .member-row:hover,
.ws-skin-root[data-ws-skin="builtin.light"] .member-row:focus-within {
background: color-mix(in srgb, var(--accent) 10%, var(--surface-1));
box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 8%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.light"] :focus-visible {
outline-color: color-mix(in srgb, var(--accent) 55%, transparent);
}
.ws-skin-root[data-ws-skin="builtin.light"],
.ws-skin-root[data-ws-skin="builtin.light"] * {
scrollbar-color: #8fcfc7 transparent;
scrollbar-width: thin;
}
.ws-skin-root[data-ws-skin="builtin.light"] *::-webkit-scrollbar-thumb {
background: #a7d9d2;
background-clip: padding-box;
border-color: transparent;
}
.ws-skin-root[data-ws-skin="builtin.light"] *::-webkit-scrollbar-thumb:hover {
background: #6bbab1;
}
File diff suppressed because it is too large. Load diff
+660 -154
View File
@@ -23,7 +23,7 @@
<div v-else class="admin-shell">
<aside class="admin-sidebar">
<div class="admin-brand"><span><Icon name="waveform" :size="22" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
<nav><RouterLink to="/admin" exact-active-class="active"><Icon name="activity" :size="18" />{{ tr('overview') }}</RouterLink><RouterLink to="/admin/server" active-class="active"><Icon name="server" :size="18" />{{ tr('server') }}</RouterLink><RouterLink to="/admin/operations" active-class="active"><Icon name="users" :size="18" />{{ tr('operations') }}</RouterLink></nav>
<nav><RouterLink to="/admin" exact-active-class="active"><Icon name="activity" :size="18" />{{ tr('overview') }}</RouterLink><RouterLink to="/admin/server" active-class="active"><Icon name="server" :size="18" />{{ tr('server') }}</RouterLink><RouterLink to="/admin/operations" active-class="active"><Icon name="users" :size="18" />{{ tr('operations') }}</RouterLink><RouterLink to="/admin/skins" active-class="active"><Icon name="compass" :size="18" />{{ tr('skinLibrary') }}</RouterLink></nav>
<div class="sidebar-bottom"><a href="/" target="_blank"><Icon name="share" :size="16" />{{ tr('openGuest') }}</a><button type="button" @click="logout"><Icon name="door" :size="16" />{{ tr('logout') }}</button></div>
</aside>
@@ -34,12 +34,58 @@
<section v-if="route.path === '/admin/server'" class="page-content server-page">
<div class="page-heading"><div><h2>{{ tr('serverSettings') }}</h2><p>{{ tr('serverSettingsLead') }}</p></div><button class="primary-button" :disabled="submitting" @click="saveServerSettings">{{ submitting ? tr('saving') : tr('saveChanges') }}</button></div>
<div class="settings-grid">
<article class="settings-card"><h3>{{ tr('teamSpeakTarget') }}</h3><div class="target-fields"><label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.address" :placeholder="tr('serverPlaceholder')" /></label><label><span>{{ tr('serverPort') }}</span><input v-model.trim="serverForm.port" inputmode="numeric" type="text" maxlength="5" :placeholder="tr('serverPortPlaceholder')" /></label></div><div class="password-row"><label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label><div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div></div><button class="secondary-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button><div v-if="testResult" :class="['test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResultTitle }}</strong><small>{{ testResultText }}</small></div></div></article>
<article class="settings-card"><h3>{{ tr('accessAndIdentity') }}</h3><fieldset><legend>{{ tr('accessMode') }}</legend><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset><label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label><div class="welcome-editor"><div class="welcome-editor-heading"><label><span>{{ tr('welcomeLanguage') }}</span><select v-model="welcomeLanguage"><option v-for="option in welcomeLanguageOptions" :key="option.value" :value="option.value">{{ option.label }}</option></select></label><small>{{ tr('welcomeLanguageHint') }}</small></div><label><span>{{ tr('welcomeText') }} · {{ selectedWelcomeLanguageLabel }}</span><textarea v-model="selectedWelcomeText" maxlength="500" rows="4" :placeholder="selectedWelcomeDefault"></textarea></label><small class="field-help">{{ tr('welcomeFallbackHint') }}</small></div></article>
<article class="settings-card advanced-card"><div><h3>{{ tr('advancedSettings') }}</h3><p class="card-help">{{ tr('advancedSettingsLead') }}</p></div><label class="choice toggle-choice"><input v-model="serverForm.webRtcEnabled" type="checkbox" @change="handleWebRtcToggle" /><span><strong>{{ tr('webrtcEnabled') }}</strong><small>{{ tr('webrtcEnabledLead') }}</small></span></label><div class="webrtc-port-fields"><div class="port-fields-heading"><strong>{{ tr('webrtcPortRange') }}</strong><small>{{ tr('webrtcPortRangeLead') }}</small></div><div class="port-inputs"><label><span>{{ tr('webrtcPortStart') }}</span><input v-model.number="serverForm.webRtcUdpStart" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label><label><span>{{ tr('webrtcPortEnd') }}</span><input v-model.number="serverForm.webRtcUdpEnd" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label></div></div><small class="field-help">{{ tr('webrtcApplyHint') }}</small></article>
<article class="settings-card relay-card"><div><h3>{{ tr('relaySettings') }}</h3><p class="card-help">{{ tr('relaySettingsLead') }}</p></div><div v-if="!serverForm.relayNodes.length" class="relay-empty">{{ tr('relayNodeEmpty') }}</div><div class="relay-node-list"><div v-for="(relay, index) in serverForm.relayNodes" :key="relay.id" class="relay-node"><div class="relay-node-heading"><label class="relay-enabled"><input v-model="relay.enabled" type="checkbox" /><strong>{{ relay.name || tr('relayUnnamed') }}</strong></label><button class="text-danger" type="button" @click="removeRelayNode(index)">{{ tr('remove') }}</button></div><div class="relay-fields"><label><span>{{ tr('relayName') }}</span><input v-model.trim="relay.name" maxlength="80" :placeholder="tr('relayNamePlaceholder')" /></label><label><span>{{ tr('relayTarget') }}</span><input v-model.trim="relay.target" maxlength="300" :placeholder="tr('relayTargetPlaceholder')" /></label><div class="password-row"><label><span>{{ tr('relayToken') }}</span><input v-model="relay.token" type="password" autocomplete="off" :disabled="relay.tokenAction !== 'replace'" :placeholder="relay.hasToken ? tr('relayTokenConfigured') : tr('relayTokenPlaceholder')" /></label><div class="password-actions"><button type="button" :class="{ active: relay.tokenAction === 'replace' }" @click="relay.tokenAction = 'replace'">{{ tr('change') }}</button><button v-if="relay.hasToken" type="button" :class="{ danger: relay.tokenAction === 'remove' }" @click="relay.tokenAction = 'remove'">{{ tr('remove') }}</button></div></div></div></div></div><button class="secondary-button relay-add" type="button" @click="addRelayNode">{{ tr('relayAdd') }}</button><small class="field-help">{{ tr('relayManagedHint') }}</small></article>
<details class="settings-card settings-accordion target-accordion" open>
<summary class="settings-accordion-header">
<span class="settings-accordion-heading"><strong>{{ tr('teamSpeakTarget') }}</strong><small>{{ serverForm.address || '—' }} · {{ serverForm.port || '—' }}</small></span>
<Icon name="chevron-down" :size="18" />
</summary>
<div class="settings-accordion-content">
<div class="target-settings-layout">
<div class="target-fields">
<label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.address" :placeholder="tr('serverPlaceholder')" /></label>
<label><span>{{ tr('serverPort') }}</span><input v-model.trim="serverForm.port" inputmode="numeric" type="text" maxlength="5" :placeholder="tr('serverPortPlaceholder')" /></label>
</div>
<div class="password-row">
<label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label>
<div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div>
</div>
<button class="secondary-button target-test-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button>
<div v-if="testResult" :class="['test-result', 'target-test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResultTitle }}</strong><small>{{ testResultText }}</small></div></div>
<div class="target-runtime-block"><h4>{{ tr('runtimeFacts') }}</h4><dl class="target-runtime-facts"><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(serverForm.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}</dd></div><div><dt>{{ tr('internalPort') }}</dt><dd>3040</dd></div></dl></div>
</div>
</div>
</details>
<details class="settings-card settings-accordion">
<summary class="settings-accordion-header">
<span class="settings-accordion-heading"><strong>{{ tr('accessAndIdentity') }}</strong><small>{{ serverForm.accessMode === 'fixed' ? tr('fixedMode') : tr('openMode') }} · {{ serverForm.siteName || 'WebSpeak' }}</small></span>
<Icon name="chevron-down" :size="18" />
</summary>
<div class="settings-accordion-content">
<div class="access-settings-layout">
<fieldset class="access-mode-fieldset"><legend>{{ tr('accessMode') }}</legend><label class="choice" :class="{ selected: serverForm.accessMode === 'fixed' }"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice" :class="{ selected: serverForm.accessMode === 'open' }"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset>
<div class="site-identity-fields">
<label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label>
<div class="welcome-editor"><div class="welcome-editor-heading"><label><span>{{ tr('welcomeLanguage') }}</span><select v-model="welcomeLanguage"><option v-for="option in welcomeLanguageOptions" :key="option.value" :value="option.value">{{ option.label }}</option></select></label><small>{{ tr('welcomeLanguageHint') }}</small></div><label><span>{{ tr('welcomeText') }} · {{ selectedWelcomeLanguageLabel }}</span><textarea v-model="selectedWelcomeText" maxlength="500" rows="4" :placeholder="selectedWelcomeDefault"></textarea></label><small class="field-help">{{ tr('welcomeFallbackHint') }}</small></div>
</div>
</div>
</div>
</details>
<details class="settings-card settings-accordion advanced-card">
<summary class="settings-accordion-header">
<span class="settings-accordion-heading"><strong>{{ tr('advancedSettings') }}</strong><small>{{ tr('advancedSettingsLead') }}</small></span>
<span class="settings-accordion-statuses"><span class="settings-summary-chip"><i :class="{ active: serverForm.webRtcEnabled }"></i>{{ tr('webrtcSettings') }} · {{ serverForm.webRtcEnabled ? tr('enabledStatus') : tr('disabledStatus') }}</span><span class="settings-summary-chip"><i :class="{ active: serverForm.relayNodes.some((relay) => relay.enabled) }"></i>{{ tr('relaySettings') }} · {{ tr('relayNodeCount', { count: serverForm.relayNodes.length }) }}</span></span>
<Icon name="chevron-down" :size="18" />
</summary>
<div class="settings-accordion-content">
<div class="advanced-settings-grid">
<section class="settings-subsection webrtc-card"><header class="settings-subsection-heading"><div><h4>{{ tr('webrtcSettings') }}</h4><p class="card-help">{{ tr('webrtcLead') }}</p></div></header><label class="choice toggle-choice" :class="{ selected: serverForm.webRtcEnabled }"><input v-model="serverForm.webRtcEnabled" type="checkbox" @change="handleWebRtcToggle" /><span><strong>{{ tr('webrtcEnabled') }}</strong><small>{{ tr('webrtcEnabledLead') }}</small></span></label><div class="webrtc-port-fields"><div class="port-fields-heading"><strong>{{ tr('webrtcPortRange') }}</strong><small>{{ tr('webrtcPortRangeLead') }}</small></div><div class="port-inputs"><label><span>{{ tr('webrtcPortStart') }}</span><input v-model.number="serverForm.webRtcUdpStart" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label><label><span>{{ tr('webrtcPortEnd') }}</span><input v-model.number="serverForm.webRtcUdpEnd" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label></div></div><small class="field-help">{{ tr('webrtcApplyHint') }}</small></section>
<section class="settings-subsection relay-card"><header class="settings-subsection-heading"><div><h4>{{ tr('relaySettings') }}</h4><p class="card-help">{{ tr('relaySettingsLead') }}</p></div></header><div v-if="!serverForm.relayNodes.length" class="relay-empty">{{ tr('relayNodeEmpty') }}</div><div class="relay-node-list"><div v-for="(relay, index) in serverForm.relayNodes" :key="relay.id" class="relay-node"><div class="relay-node-heading"><label class="relay-enabled"><input v-model="relay.enabled" type="checkbox" /><strong>{{ relay.name || tr('relayUnnamed') }}</strong></label><button class="text-danger" type="button" @click="removeRelayNode(index)">{{ tr('remove') }}</button></div><div class="relay-fields"><label><span>{{ tr('relayName') }}</span><input v-model.trim="relay.name" maxlength="80" :placeholder="tr('relayNamePlaceholder')" /></label><label><span>{{ tr('relayTarget') }}</span><input v-model.trim="relay.target" maxlength="300" :placeholder="tr('relayTargetPlaceholder')" /></label><div class="password-row"><label><span>{{ tr('relayToken') }}</span><input v-model="relay.token" type="password" autocomplete="off" :disabled="relay.tokenAction !== 'replace'" :placeholder="relay.hasToken ? tr('relayTokenConfigured') : tr('relayTokenPlaceholder')" /></label><div class="password-actions"><button type="button" :class="{ active: relay.tokenAction === 'replace' }" @click="relay.tokenAction = 'replace'">{{ tr('change') }}</button><button v-if="relay.hasToken" type="button" :class="{ danger: relay.tokenAction === 'remove' }" @click="relay.tokenAction = 'remove'">{{ tr('remove') }}</button></div></div></div></div></div><button class="secondary-button relay-add" type="button" @click="addRelayNode">{{ tr('relayAdd') }}</button><small class="field-help">{{ tr('relayManagedHint') }}</small></section>
</div>
</div>
</details>
</div>
<article class="readonly-card"><h3>{{ tr('runtimeFacts') }}</h3><dl><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(serverForm.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}</dd></div><div><dt>{{ tr('internalPort') }}</dt><dd>3040</dd></div></dl></article>
</section>
<section v-else-if="route.path === '/admin/operations'" class="page-content operations-page">
@@ -56,6 +102,23 @@
</div>
</section>
<section v-else-if="route.path === '/admin/skins'" class="page-content skin-library-page">
<div class="page-heading"><div><h2>{{ tr('skinLibrary') }}</h2><p>{{ tr('skinLibraryLead') }}</p></div><button class="primary-button" type="button" :disabled="skinUploading" @click="skinFileInput?.click()"><span v-if="skinUploading" class="spinner small"></span><Icon v-else name="share" :size="16" />{{ skinUploading ? tr('skinUploading') : tr('skinUpload') }}</button></div>
<input ref="skinFileInput" class="skin-file-input" type="file" accept=".wskin,application/zip" @change="onSkinFileChanged" />
<div class="alert info skin-library-scope"><Icon name="info" :size="16" /><span>{{ tr('skinLibraryScope') }}</span></div>
<section class="skin-default-control"><div><strong>{{ tr('skinDefault') }}</strong><p>{{ tr('skinDefaultLead') }}</p></div><select v-model="skinDefaultId" :disabled="skinLoading || skinDefaultSaving" :aria-label="tr('skinDefault')" @change="saveSkinDefault"><option v-for="skin in enabledSkinEntries" :key="skin.id" :value="skin.id">{{ skinName(skin) }}</option></select></section>
<div v-if="skinManagerError" class="alert error" role="alert">{{ skinManagerError }}</div>
<div v-if="skinManagerNotice" class="alert success" role="status">{{ skinManagerNotice }}</div>
<div v-if="skinLoading" class="skin-library-loading"><span class="spinner"></span>{{ tr('loading') }}</div>
<div v-else-if="skinEntries.length" class="skin-library-grid">
<article v-for="skin in skinEntries" :key="skin.id" class="skin-library-card">
<div class="skin-preview" :class="`skin-preview--${skin.previewKind || 'custom'}`"><img v-if="skin.previewUrl" :src="skin.previewUrl" :alt="skinName(skin)" /><span v-else><Icon :name="skin.previewKind === 'night' ? 'moon' : 'sun'" :size="28" /></span><small>v{{ skin.version }}</small><b v-if="skin.builtIn" class="skin-builtin-badge">{{ tr('skinBuiltin') }}</b></div>
<div class="skin-library-copy"><div class="skin-library-title"><h3>{{ skinName(skin) }}</h3><span>{{ skin.id }}</span></div><p v-if="skinDescription(skin)">{{ skinDescription(skin) }}</p><dl><div><dt>{{ tr('skinAuthor') }}</dt><dd>{{ skin.author }}</dd></div><div><dt>{{ tr('skinLicense') }}</dt><dd>{{ skin.license }}</dd></div><div><dt>{{ tr('skinMinVersion') }}</dt><dd>{{ skin.minAppVersion }}</dd></div></dl><div class="skin-library-actions"><a v-if="skin.previewUrl" :href="skin.previewUrl" target="_blank" rel="noreferrer" class="text-link">{{ tr('skinPreview') }}</a><label v-if="!skin.builtIn" class="skin-enabled-control"><span>{{ skin.enabled === false ? tr('skinDisabled') : tr('skinEnabled') }}</span><input type="checkbox" :checked="skin.enabled !== false" :disabled="updatingSkinId === skin.id" @change="toggleSkinEnabled(skin)" /></label><span v-else class="skin-protected-label">{{ tr('skinProtected') }}</span><button v-if="!skin.builtIn" class="text-danger" type="button" :disabled="removingSkinId === skin.id" @click="removeSkin(skin)">{{ removingSkinId === skin.id ? tr('skinRemoving') : tr('skinRemove') }}</button></div></div>
</article>
</div>
<div v-else class="skin-library-empty"><span><Icon name="compass" :size="24" /></span><strong>{{ tr('skinEmpty') }}</strong><p>{{ tr('skinEmptyLead') }}</p></div>
</section>
<section v-else class="page-content overview-page">
<div v-if="overview.legacyConfigImported" class="alert info import-notice"><span>{{ tr('legacyImported') }}</span><button type="button" @click="dismissLegacyNotice">{{ tr('gotIt') }}</button></div>
<div class="hero-status"><div><small>{{ tr('systemStatus') }}</small><h2>{{ tr('everythingRunning') }}</h2><p>{{ tr('overviewLead') }}</p></div><span class="status-badge"><i></i>{{ tr('running') }}</span></div>
@@ -74,6 +137,7 @@ import { RouterLink, useRoute, useRouter } from "vue-router";
import Icon from "../components/Icon.vue";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
import { BUILTIN_SKIN_CATALOG, deleteSkinPackage, uploadSkinPackage, type SkinCatalogEntry } from "../services/skin-catalog.js";
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
type Language = "zh" | "en" | "de" | "ru" | "ja";
@@ -121,6 +185,17 @@ interface AdminLog { timestamp: string | null; level: string; message: string; c
interface AdminConnectionRecord { id: string; nickname: string; clientIp: string; target: string; relayName: string | null; relayTarget: string | null; startedAt: string; connectedAt: string | null; disconnectedAt: string | null; durationSeconds: number | null; status: "active" | "connecting" | "disconnected" | "failed"; reason: string | null; failureDetail: string | null }
const operationsLoading = ref(false);
const terminatingSession = ref("");
const skinFileInput = ref<HTMLInputElement | null>(null);
const skinEntries = ref<SkinCatalogEntry[]>([]);
const skinLoading = ref(false);
const skinUploading = ref(false);
const removingSkinId = ref("");
const updatingSkinId = ref("");
const skinDefaultId = ref("builtin.light");
const skinDefaultSaving = ref(false);
const enabledSkinEntries = computed(() => skinEntries.value.filter((skin) => skin.builtIn || skin.enabled !== false));
const skinManagerError = ref("");
const skinManagerNotice = ref("");
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
const createdInvite = ref<{ token: string; link: string } | null>(null);
const webrtcPortNoticeOpen = ref(false);
@@ -154,6 +229,38 @@ const copy = {
overview: "概览",
server: "服务器",
operations: "运维",
skinLibrary: "皮肤",
skinLibraryLead: "查看访客可选的默认皮肤和实例自定义皮肤;支持导入皮肤包。",
skinDay: "默认日间模式",
skinNight: "默认夜间模式",
skinIllusia: "ILLUSIA风",
skinBuiltin: "内置",
skinProtected: "内置皮肤,不可移除",
skinDefault: "默认皮肤",
skinDefaultLead: "访客首次访问时使用;访客已有选择时保留其偏好。",
skinEnabled: "已启用",
skinDisabled: "已停用",
skinDefaultSaved: "默认皮肤已更新。",
skinEnabledNotice: "皮肤已启用并向访客开放。",
skinDisabledNotice: "皮肤已停用,不再向访客提供。",
skinDayDescription: "WebSpeak 默认的明亮日间外观。",
skinNightDescription: "WebSpeak 默认的深色夜间外观。",
skinIllusiaDescription: "覆盖首页、语音房间和演示页的 ILLUSIA 美术皮肤。",
skinLibraryScope: "皮肤会作为可选项提供给访客;每位访客可在前台自行选择。管理后台始终保持原样式。",
skinUpload: "导入皮肤包",
skinUploading: "正在校验并导入…",
skinEmpty: "尚未导入自定义皮肤",
skinEmptyLead: "选择符合 WebSpeak 皮肤规范的 .wskin 文件开始使用。",
skinAuthor: "作者",
skinLicense: "许可证",
skinMinVersion: "最低版本",
skinPreview: "查看预览",
skinRemove: "移除",
skinRemoving: "正在移除…",
skinConfirmRemove: "确定从此实例中移除此皮肤吗?已选择该皮肤的访客会在下次加载时回退。",
skinReplaceConfirm: "已有同 ID 皮肤。要用这个版本替换吗?",
skinImported: "皮肤已导入并向访客开放。",
skinRemoved: "皮肤已从实例中移除。",
openGuest: "打开访客页面",
logout: "退出登录",
gatewayRunning: "网关运行中",
@@ -196,6 +303,9 @@ const copy = {
accessAndIdentity: "访问与站点信息",
advancedSettings: "高级参数",
advancedSettingsLead: "仅在需要时调整网关的高级传输参数。",
enabledStatus: "已启用",
disabledStatus: "未启用",
relayNodeCount: "{{count}} 个节点",
webrtcSettings: "WebRTC 语音",
webrtcLead: "由当前 WebSpeak 网关直接提供低延迟语音传输,无需配置其他服务器。",
webrtcEnabled: "启用 WebRTC",
@@ -358,6 +468,38 @@ const copy = {
overview: "Overview",
server: "Server",
operations: "Operations",
skinLibrary: "Skins",
skinLibraryLead: "View the default and custom skins available to visitors; import instance-wide skin packages.",
skinDay: "Default day mode",
skinNight: "Default night mode",
skinIllusia: "ILLUSIA style",
skinBuiltin: "Built in",
skinProtected: "Built-in skin · cannot be removed",
skinDefault: "Default skin",
skinDefaultLead: "Used for first-time visitors; existing visitor choices are preserved.",
skinEnabled: "Enabled",
skinDisabled: "Disabled",
skinDefaultSaved: "Default skin updated.",
skinEnabledNotice: "Skin enabled and available to visitors.",
skinDisabledNotice: "Skin disabled and hidden from visitors.",
skinDayDescription: "WebSpeak's default light appearance.",
skinNightDescription: "WebSpeak's default dark appearance.",
skinIllusiaDescription: "ILLUSIA artwork for the home, voice room, and demo pages.",
skinLibraryScope: "Skins are offered as visitor-selectable options. Each visitor chooses a skin on the public page; the admin console always keeps its own appearance.",
skinUpload: "Import skin package",
skinUploading: "Validating and importing…",
skinEmpty: "No custom skins yet",
skinEmptyLead: "Choose a .wskin package that follows the WebSpeak skin specification.",
skinAuthor: "Author",
skinLicense: "License",
skinMinVersion: "Minimum version",
skinPreview: "Preview",
skinRemove: "Remove",
skinRemoving: "Removing…",
skinConfirmRemove: "Remove this skin from the instance? Visitors using it will fall back the next time they load the page.",
skinReplaceConfirm: "A skin with this ID already exists. Replace it with this package?",
skinImported: "Skin imported and made available to visitors.",
skinRemoved: "Skin removed from the instance.",
openGuest: "Open guest page",
logout: "Log out",
gatewayRunning: "Gateway running",
@@ -400,6 +542,9 @@ const copy = {
accessAndIdentity: "Access and site identity",
advancedSettings: "Advanced settings",
advancedSettingsLead: "Adjust gateway transport options only when needed.",
enabledStatus: "Enabled",
disabledStatus: "Disabled",
relayNodeCount: "{{count}} nodes",
webrtcSettings: "WebRTC audio",
webrtcLead: "Low-latency voice is provided by this WebSpeak gateway; no extra server is required.",
webrtcEnabled: "Enable WebRTC",
@@ -560,6 +705,38 @@ const germanCopy = {
overview: "Übersicht",
server: "Server",
operations: "Betrieb",
skinLibrary: "Skins",
skinLibraryLead: "Standard- und benutzerdefinierte Skins für Besucher anzeigen und instanzweite Skin-Pakete importieren.",
skinDay: "Standard-Tagesmodus",
skinNight: "Standard-Nachtmodus",
skinIllusia: "ILLUSIA-Stil",
skinBuiltin: "Integriert",
skinProtected: "Integrierter Skin · nicht entfernbar",
skinDefault: "Standard-Skin",
skinDefaultLead: "Wird bei neuen Besuchern verwendet; bestehende Auswahl bleibt erhalten.",
skinEnabled: "Aktiviert",
skinDisabled: "Deaktiviert",
skinDefaultSaved: "Standardskin aktualisiert.",
skinEnabledNotice: "Skin aktiviert und für Besucher verfügbar.",
skinDisabledNotice: "Skin deaktiviert und für Besucher ausgeblendet.",
skinDayDescription: "Das standardmäßige helle WebSpeak-Design.",
skinNightDescription: "Das standardmäßige dunkle WebSpeak-Design.",
skinIllusiaDescription: "ILLUSIA-Grafiken für Startseite, Sprachraum und Demo.",
skinLibraryScope: "Skins werden Besuchern zur Auswahl angeboten. Jeder Besucher wählt das Design auf der öffentlichen Seite; die Administrationsoberfläche bleibt unverändert.",
skinUpload: "Skin-Paket importieren",
skinUploading: "Wird geprüft und importiert…",
skinEmpty: "Noch keine benutzerdefinierten Skins",
skinEmptyLead: "Wähle ein .wskin-Paket nach der WebSpeak-Skin-Spezifikation aus.",
skinAuthor: "Autor",
skinLicense: "Lizenz",
skinMinVersion: "Mindestversion",
skinPreview: "Vorschau",
skinRemove: "Entfernen",
skinRemoving: "Wird entfernt…",
skinConfirmRemove: "Diesen Skin aus der Instanz entfernen? Besucher wechseln beim nächsten Laden zurück.",
skinReplaceConfirm: "Ein Skin mit dieser ID ist bereits vorhanden. Durch dieses Paket ersetzen?",
skinImported: "Skin importiert und für Besucher freigegeben.",
skinRemoved: "Skin aus der Instanz entfernt.",
openGuest: "Gastseite öffnen",
logout: "Abmelden",
gatewayRunning: "Gateway läuft",
@@ -601,6 +778,9 @@ const germanCopy = {
accessAndIdentity: "Zugriff und Website-Informationen",
advancedSettings: "Erweiterte Einstellungen",
advancedSettingsLead: "Erweiterte Gateway-Transportparameter nur bei Bedarf ändern.",
enabledStatus: "Aktiviert",
disabledStatus: "Deaktiviert",
relayNodeCount: "{{count}} Knoten",
webrtcSettings: "WebRTC-Audio",
webrtcEnabled: "WebRTC aktivieren",
webrtcPortRange: "WebRTC-UDP-Portbereich",
@@ -714,6 +894,38 @@ const russianCopy = {
overview: "Обзор",
server: "Сервер",
operations: "Операции",
skinLibrary: "Оформление",
skinLibraryLead: "Просматривайте стандартное и пользовательское оформление и импортируйте пакеты для всего экземпляра.",
skinDay: "Стандартная дневная тема",
skinNight: "Стандартная ночная тема",
skinIllusia: "Стиль ILLUSIA",
skinBuiltin: "Встроено",
skinProtected: "Встроенная тема · нельзя удалить",
skinDefault: "Тема по умолчанию",
skinDefaultLead: "Используется при первом посещении; сохранённый выбор пользователя не меняется.",
skinEnabled: "Включена",
skinDisabled: "Отключена",
skinDefaultSaved: "Тема по умолчанию обновлена.",
skinEnabledNotice: "Тема включена и доступна посетителям.",
skinDisabledNotice: "Тема отключена и скрыта от посетителей.",
skinDayDescription: "Стандартное светлое оформление WebSpeak.",
skinNightDescription: "Стандартное тёмное оформление WebSpeak.",
skinIllusiaDescription: "Иллюстрации ILLUSIA для главной страницы, голосовой комнаты и демо.",
skinLibraryScope: "Оформление предлагается посетителям на выбор; каждый выбирает его на публичной странице. Панель администратора сохраняет собственный стиль.",
skinUpload: "Импортировать пакет оформления",
skinUploading: "Проверка и импорт…",
skinEmpty: "Пользовательское оформление ещё не добавлено",
skinEmptyLead: "Выберите файл .wskin, соответствующий спецификации WebSpeak.",
skinAuthor: "Автор",
skinLicense: "Лицензия",
skinMinVersion: "Мин. версия",
skinPreview: "Предпросмотр",
skinRemove: "Удалить",
skinRemoving: "Удаление…",
skinConfirmRemove: "Удалить оформление из этого экземпляра? При следующей загрузке посетители вернутся к стандартному.",
skinReplaceConfirm: "Оформление с таким ID уже существует. Заменить его этим пакетом?",
skinImported: "Оформление импортировано и доступно посетителям.",
skinRemoved: "Оформление удалено из экземпляра.",
openGuest: "Открыть страницу гостя",
logout: "Выйти",
gatewayRunning: "Шлюз работает",
@@ -739,6 +951,9 @@ const russianCopy = {
accessAndIdentity: "Доступ и данные сайта",
advancedSettings: "Расширенные настройки",
advancedSettingsLead: "Изменяйте расширенные параметры передачи только при необходимости.",
enabledStatus: "Включено",
disabledStatus: "Выключено",
relayNodeCount: "Узлов: {{count}}",
webrtcEnabled: "Включить WebRTC",
relaySettings: "Сервер ретрансляции",
relaySettingsLead: "Настройте узлы ретрансляции для ускоренных подключений.",
@@ -833,6 +1048,38 @@ const japaneseCopy = {
overview: "概要",
server: "サーバー",
operations: "運用",
skinLibrary: "スキン",
skinLibraryLead: "訪問者向けの標準スキンとカスタムスキンを表示し、インスタンス共通のパッケージを読み込みます。",
skinDay: "標準の昼モード",
skinNight: "標準の夜モード",
skinIllusia: "ILLUSIA スタイル",
skinBuiltin: "組み込み",
skinProtected: "組み込みスキン · 削除不可",
skinDefault: "デフォルトスキン",
skinDefaultLead: "初回訪問時に適用します。訪問者が選択済みの場合はその設定を維持します。",
skinEnabled: "有効",
skinDisabled: "無効",
skinDefaultSaved: "デフォルトスキンを更新しました。",
skinEnabledNotice: "スキンを有効にし、訪問者に公開しました。",
skinDisabledNotice: "スキンを無効にし、訪問者の選択肢から隠しました。",
skinDayDescription: "WebSpeak の標準ライト外観です。",
skinNightDescription: "WebSpeak の標準ダーク外観です。",
skinIllusiaDescription: "ホーム、ボイスルーム、デモ用の ILLUSIA アートです。",
skinLibraryScope: "スキンは訪問者向けの選択肢として公開され、各訪問者が公開ページで選択します。管理画面の外観は変更されません。",
skinUpload: "スキンパッケージを読み込む",
skinUploading: "検証・読み込み中…",
skinEmpty: "カスタムスキンはまだありません",
skinEmptyLead: "WebSpeak スキン仕様に準拠した .wskin ファイルを選択してください。",
skinAuthor: "作者",
skinLicense: "ライセンス",
skinMinVersion: "最低バージョン",
skinPreview: "プレビュー",
skinRemove: "削除",
skinRemoving: "削除中…",
skinConfirmRemove: "このインスタンスからスキンを削除しますか?利用中の訪問者は次回読み込み時に標準へ戻ります。",
skinReplaceConfirm: "同じ ID のスキンがあります。このパッケージで置き換えますか?",
skinImported: "スキンを読み込み、訪問者が選択できるようにしました。",
skinRemoved: "インスタンスからスキンを削除しました。",
openGuest: "ゲストページを開く",
logout: "ログアウト",
gatewayRunning: "ゲートウェイ稼働中",
@@ -858,6 +1105,9 @@ const japaneseCopy = {
accessAndIdentity: "アクセスとサイト情報",
advancedSettings: "詳細設定",
advancedSettingsLead: "必要な場合だけゲートウェイの詳細な転送設定を変更します。",
enabledStatus: "有効",
disabledStatus: "無効",
relayNodeCount: "{{count}} ノード",
webrtcEnabled: "WebRTC を有効化",
relaySettings: "中継サーバー",
relaySettingsLead: "高速接続で使用する中継ノードを設定します。",
@@ -961,7 +1211,7 @@ const selectedWelcomeDefault = computed(() => serverForm.welcomeDefaults[welcome
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : language.value === "de" ? germanCopy[key] ?? copy.en[key] ?? copy.zh[key] : language.value === "ru" ? russianCopy[key] ?? copy.en[key] ?? copy.zh[key] : language.value === "ja" ? japaneseCopy[key] ?? copy.en[key] ?? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; }
const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0))));
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : tr('overview'));
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : route.path === "/admin/skins" ? tr('skinLibrary') : tr('overview'));
const testResultTitle = computed(() => {
const result = testResult.value;
if (!result) return "";
@@ -988,9 +1238,9 @@ const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${ser
onMounted(loadAdminView);
watch(() => [serverForm.address, serverForm.port, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; });
watch(() => route.path, () => { if (screen.value === "admin" && route.path === "/admin/operations") void loadOperations(); });
watch(() => route.path, () => { if (screen.value === "admin" && route.path === "/admin/operations") void loadOperations(); else if (screen.value === "admin" && route.path === "/admin/skins") void loadSkinCatalog(); });
async function loadAdminView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else if (session.mustChangePassword) { csrfToken.value = String(session.csrfToken || ""); screen.value = "change-password"; if (route.path !== "/admin/change-password") await router.replace("/admin/change-password"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/change-password") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); if (route.path === "/admin/operations") await loadOperations(); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } }
async function loadAdminView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else if (session.mustChangePassword) { csrfToken.value = String(session.csrfToken || ""); screen.value = "change-password"; if (route.path !== "/admin/change-password") await router.replace("/admin/change-password"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/change-password") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); if (route.path === "/admin/operations") await loadOperations(); if (route.path === "/admin/skins") await loadSkinCatalog(); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } }
async function login() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/login", "POST", { username: loginUsername.value, password: loginPassword.value }, false); csrfToken.value = String(result.csrfToken || ""); loginPassword.value = ""; if (result.mustChangePassword) { screen.value = "change-password"; await router.replace("/admin/change-password"); } else { screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } }
@@ -1009,6 +1259,99 @@ function addRelayNode() { serverForm.relayNodes.push(createRelayNode()); serverF
function removeRelayNode(index: number) { serverForm.relayNodes.splice(index, 1); serverForm.relaySettingsTouched = true; }
async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", welcomeTextDe: String(value.welcomeTextDe || ""), welcomeTextRu: String(value.welcomeTextRu || ""), welcomeTextJa: String(value.welcomeTextJa || ""), welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS, ...(value.welcomeDefaults && typeof value.welcomeDefaults === "object" ? value.welcomeDefaults : {}) }, webRtcEnabled: value.webRtcEnabled === true, webRtcUdpStart: Number(value.webRtcUdpStart || 40000), webRtcUdpEnd: Number(value.webRtcUdpEnd || 40099), relayConfigured: value.relayConfigured === true, relayEnabled: value.relayEnabled === true, relayName: String(value.relayName || ""), relayTarget: String(value.relayTarget || ""), relayToken: "", relayTokenAction: "keep", hasRelayToken: value.hasRelayToken === true, relaySettingsTouched: false, relayNodes: mapRelayNodes(value.relayNodes) }); }
async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [], sessions: Array.isArray(logs.sessions) ? logs.sessions : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } }
async function loadSkinCatalog() {
skinLoading.value = true;
skinManagerError.value = "";
try {
const value = await getJson("/api/admin/skins");
const uploaded = Array.isArray(value.skins) ? value.skins as SkinCatalogEntry[] : [];
const protectedIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
skinEntries.value = [...BUILTIN_SKIN_CATALOG, ...uploaded.filter((skin) => !protectedIds.has(skin.id))];
skinDefaultId.value = typeof value.defaultSkinId === "string" ? value.defaultSkinId : "builtin.light";
} catch {
skinManagerError.value = tr("requestFailed");
} finally {
skinLoading.value = false;
}
}
function skinName(skin: SkinCatalogEntry): string {
if (skin.id === "builtin.light") return tr("skinDay");
if (skin.id === "builtin.dark") return tr("skinNight");
if (skin.id === "community.illusia-voice") return tr("skinIllusia");
return skin.name;
}
function skinDescription(skin: SkinCatalogEntry): string {
if (skin.id === "builtin.light") return tr("skinDayDescription");
if (skin.id === "builtin.dark") return tr("skinNightDescription");
if (skin.id === "community.illusia-voice") return tr("skinIllusiaDescription");
return skin.description || "";
}
async function saveSkinDefault() {
skinDefaultSaving.value = true;
skinManagerError.value = "";
skinManagerNotice.value = "";
try {
const result = await sendJson("/api/admin/skins/default", "PUT", { id: skinDefaultId.value });
skinDefaultId.value = typeof result.defaultSkinId === "string" ? result.defaultSkinId : "builtin.light";
skinManagerNotice.value = tr("skinDefaultSaved");
} catch {
skinManagerError.value = tr("operationFailed");
await loadSkinCatalog();
} finally {
skinDefaultSaving.value = false;
}
}
async function toggleSkinEnabled(skin: SkinCatalogEntry) {
updatingSkinId.value = skin.id;
skinManagerError.value = "";
skinManagerNotice.value = "";
try {
const result = await sendJson(`/api/admin/skins/${encodeURIComponent(skin.id)}/enabled`, "PUT", { enabled: skin.enabled === false });
const updated = result.skin as SkinCatalogEntry | undefined;
if (updated) Object.assign(skin, updated);
if (typeof result.defaultSkinId === "string") skinDefaultId.value = result.defaultSkinId;
skinManagerNotice.value = tr(skin.enabled === false ? "skinDisabledNotice" : "skinEnabledNotice");
} catch {
skinManagerError.value = tr("operationFailed");
await loadSkinCatalog();
} finally {
updatingSkinId.value = "";
}
}
async function onSkinFileChanged(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
skinManagerError.value = "";
skinManagerNotice.value = "";
skinUploading.value = true;
try {
const result = await uploadSkinPackage(file, csrfToken.value, (id) => !skinEntries.value.some((entry) => entry.id === id) || window.confirm(`${tr("skinReplaceConfirm")}\n${id}`));
if (!result) return;
skinManagerNotice.value = tr("skinImported");
await loadSkinCatalog();
} catch (error) {
skinManagerError.value = error instanceof Error ? error.message : tr("operationFailed");
} finally {
input.value = "";
skinUploading.value = false;
}
}
async function removeSkin(skin: SkinCatalogEntry) {
if (!window.confirm(`${tr("skinConfirmRemove")}\n${skin.name} (${skin.id})`)) return;
removingSkinId.value = skin.id;
skinManagerError.value = "";
skinManagerNotice.value = "";
try {
await deleteSkinPackage(skin.id, csrfToken.value);
skinManagerNotice.value = tr("skinRemoved");
await loadSkinCatalog();
} catch {
skinManagerError.value = tr("operationFailed");
} finally {
removingSkinId.value = "";
}
}
async function terminateSession(session: AdminSession) { if (!window.confirm(tr('confirmTerminate', { nickname: session.nickname }))) return; terminatingSession.value = session.id; errorMessage.value = ""; try { await sendJson(`/api/admin/sessions/${encodeURIComponent(session.id)}/terminate`, "POST", {}); await Promise.all([loadOperations(), loadOverview()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { terminatingSession.value = ""; } }
async function createInvite() { submitting.value = true; errorMessage.value = ""; createdInvite.value = null; try { const result = await sendJson("/api/admin/invites", "POST", { channel: inviteForm.channel, expiresInHours: inviteForm.expiresInHours, maxUses: inviteForm.maxUses }); if (typeof result.token !== "string") throw new Error("INVITE_CREATE_FAILED"); createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` }; inviteForm.channel = ""; await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('confirmRevoke'))) return; try { await sendJson(`/api/admin/invites/${encodeURIComponent(invite.id)}/revoke`, "POST", {}); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
@@ -1128,77 +1471,6 @@ async function parseResponse(response: Response) { const value = await response.
.webrtc-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.toggle-choice{margin:0}.webrtc-card>.field-help{margin-top:-8px}
@media(max-width:520px){.target-fields{grid-template-columns:1fr}}
/* Keep administration inside the browser viewport. Long data sets scroll in
their own cards instead of pushing the whole page below the fold. */
.admin-shell{height:100dvh;min-height:100dvh;overflow:hidden}
.admin-main{min-height:0;display:flex;flex-direction:column;overflow:hidden}
.admin-topbar{flex:0 0 auto}
.page-content{flex:1 1 auto;min-height:0;overflow-y:auto}
.operations-page{display:flex;flex-direction:column;width:min(1400px,calc(100% - 48px));height:calc(100dvh - 82px);overflow:hidden;padding-top:28px;padding-bottom:18px}
.operations-page .page-heading{flex:0 0 auto;margin-bottom:16px}
.operations-page .system-notice{flex:0 0 auto;margin-bottom:12px}
.operations-page .operations-grid{min-width:0;min-height:0}
.operations-primary{flex:0 0 auto;grid-template-columns:minmax(0,1.2fr) minmax(360px,.8fr)}
.operations-primary>.operation-card{min-height:0;overflow:hidden}
.operations-primary .table-wrap{max-height:190px}
.operations-primary .invite-list{max-height:132px;overflow-y:auto}
.lower-operations{flex:1 1 0;grid-template-columns:minmax(210px,.9fr) minmax(0,1.1fr) minmax(210px,.9fr);margin-top:14px}
.lower-operations>.operation-card{min-height:0}
.diagnostics-card,.logs-card,.audit-card{overflow:hidden}
.diagnostics-card{display:flex;flex-direction:column;overflow-y:auto}
.diagnostics-card .secondary-button{margin-top:auto}
.logs-card,.audit-card{display:flex;flex-direction:column}
.logs-card .log-list,.audit-card .event-list{flex:1 1 0;min-height:0;max-height:none;overflow-y:auto}
@media(max-width:850px){
.admin-main{height:100%}
.operations-page{width:min(100% - 28px,700px);height:auto;min-height:calc(100dvh - 82px);overflow:visible}
.operations-page .lower-operations{flex:none}
}
/* Keep every admin surface inside the viewport. The page content and data
lists are the scroll containers, never the document body. */
:global(html),:global(body),:global(#app){width:100%;height:100dvh;min-height:0;max-height:100dvh;overflow:hidden}
.admin-root{height:100dvh;min-height:0;overflow:hidden}
.login-page{height:100dvh;min-height:0;overflow:hidden}
.login-card{max-height:calc(100dvh - 50px);overflow-y:auto}
@media(max-width:850px){
.admin-shell{display:flex;flex-direction:column}
.admin-main{height:auto;flex:1 1 auto}
}
/* Keep static admin cards at their own height. Only long data collections
become scroll surfaces, so a busy event feed cannot stretch its neighbour
or turn the whole admin view into a second page. */
.admin-main>.page-alert{flex:0 0 auto}
.page-content{display:flex;flex:1 1 auto;min-height:0;flex-direction:column;overflow:hidden}
.overview-page{padding:28px 0 18px}
.overview-page .import-notice{flex:0 0 auto;margin-top:0;margin-bottom:12px}
.overview-page .hero-status{flex:0 0 auto;padding:24px}
.overview-page .metric-grid{flex:0 0 auto;gap:12px;margin:14px 0}
.overview-page .metric-grid article{padding:18px}
.overview-page .overview-columns{flex:1 1 0;min-height:0;align-items:stretch;gap:14px}
.target-health-card{align-self:start}
.recent-events-card{display:flex;height:100%;min-height:0;flex-direction:column;overflow:hidden}
.recent-events-card .event-list{flex:1 1 auto;min-height:0;max-height:none;overflow-y:auto}
.server-page{padding:28px 0 18px}
.server-page .page-heading{flex:0 0 auto;margin-bottom:14px}
.server-page .settings-grid{flex:1 1 auto;min-height:0;align-items:stretch;gap:14px}
.server-page .settings-card{min-height:0;overflow-y:auto;padding:20px}
.server-page .readonly-card{flex:0 0 auto;margin-top:14px;padding:16px 20px}
.server-page .readonly-card dl{gap:10px;margin-top:12px}
.operations-page{height:auto;min-height:0}
.operations-primary{flex:0 0 250px}
.operations-primary>.operation-card{overflow-y:auto}
.operations-primary>.operation-card{padding:14px 16px}
.operations-primary .operation-card header p{line-height:1.3}
.operations-primary .invite-form{gap:6px;margin-top:8px}
.operations-primary label>span{margin-bottom:4px}
.operations-primary input{height:34px;padding:7px 10px}
.operations-primary .field-help{margin-top:-4px}
.operations-primary .primary-button{min-height:34px}
/* Theme all native scrollbars used by the admin surfaces. */
:global(*){scrollbar-color:#8fcfc7 transparent;scrollbar-width:thin}
:global(*::-webkit-scrollbar){width:8px;height:8px}
@@ -1209,25 +1481,6 @@ async function parseResponse(response: Response) { const value = await response.
:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb){background:#438f88;border-color:transparent}
:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb:hover){background:#69c7bc}
@media(max-width:850px){
.page-content{width:min(100% - 28px,700px);padding-top:20px;padding-bottom:14px}
.overview-page .hero-status{padding:18px}
.overview-page .hero-status h2{font-size:24px}
.overview-page .metric-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:7px;margin:10px 0}
.overview-page .metric-grid article{padding:12px}
.overview-page .metric-grid article>span{top:10px;right:10px;width:28px;height:28px}
.overview-page .metric-grid strong{margin-top:9px;font-size:15px}
.overview-page .overview-columns{grid-template-rows:minmax(0,1fr) minmax(0,1fr);overflow:hidden}
.overview-page .target-health-card{align-self:stretch;min-height:0;overflow-y:auto}
.overview-page .recent-events-card{height:100%}
.server-page .settings-grid{grid-template-columns:1fr;grid-auto-rows:minmax(190px,1fr);overflow-y:auto}
.server-page .readonly-card dl{grid-template-columns:repeat(2,minmax(0,1fr))}
.operations-page{height:100%;overflow:hidden}
.operations-page .operations-primary,.operations-page .lower-operations{grid-template-columns:1fr;min-height:0;overflow-y:auto;align-content:start}
.operations-page .operations-primary{grid-auto-rows:240px}
.operations-page .lower-operations{grid-auto-rows:190px}
.operations-page .lower-operations{flex:1 1 0}
}
.advanced-card{grid-column:1 / -1}
.advanced-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}
.advanced-card .toggle-choice{margin:0}
@@ -1277,63 +1530,21 @@ async function parseResponse(response: Response) { const value = await response.
@media(max-width:520px){.advanced-card{grid-column:auto}.port-inputs{grid-template-columns:1fr}}
@media(max-width:520px){.welcome-editor-heading{grid-template-columns:1fr;gap:6px}}
/* Server settings are a short form, not a set of independent data feeds.
Let each card keep its natural height so a few extra pixels do not create
three nested scrollbars. The section itself is the only fallback scroll
surface when a small viewport cannot show the complete form. */
.server-page{overflow-x:hidden;overflow-y:auto}
/* Server settings keep their natural height; the main content area owns scrolling. */
.server-page{min-width:0}
.server-page .settings-grid{flex:0 0 auto;min-height:auto;align-items:start;overflow:visible;grid-auto-rows:auto}
.server-page .settings-card{height:auto;min-height:0;overflow:visible;padding:16px;gap:12px}
.server-page .settings-card input{height:40px}
.server-page .settings-card .choice{padding:10px;gap:8px}
.server-page .settings-card .choice small{margin-top:3px}
.server-page .webrtc-port-fields{padding:12px;gap:8px}
.server-page .readonly-card{margin-top:12px;padding:14px 16px}
.server-page .readonly-card dl{gap:8px;margin-top:10px}
@media(max-width:850px){
.server-page .settings-grid{overflow:visible;grid-auto-rows:auto}
.server-page .settings-card{overflow:visible}
}
/* Mobile admin pages should read like one continuous form. Keep the desktop
viewport shell untouched, but let the document grow vertically on narrow
screens instead of trapping content inside cards and nested panes. */
@media(max-width:850px){
:global(html),:global(body),:global(#app){height:auto;min-height:100%;max-height:none;overflow:auto}
.admin-root{height:auto;min-height:100dvh;overflow:visible}
.admin-shell{height:auto;min-height:100dvh;overflow:visible}
.admin-main{height:auto;min-height:0;overflow:visible}
.page-content{display:block;height:auto;min-height:0;overflow:visible}
.login-page{height:auto;min-height:100dvh;overflow:visible}
.login-card{max-height:none;overflow:visible}
.overview-page{height:auto;min-height:0;overflow:visible}
.overview-page .overview-columns{grid-template-rows:auto;overflow:visible}
.overview-page .target-health-card,.overview-page .recent-events-card{height:auto;min-height:0;overflow:visible}
.overview-page .recent-events-card .event-list{max-height:none;overflow:visible}
.server-page{height:auto;min-height:0;overflow:visible}
.server-page .settings-grid{height:auto;overflow:visible}
.operations-page{height:auto;min-height:0;overflow:visible}
.operations-page .operations-primary,.operations-page .lower-operations{height:auto;min-height:0;overflow:visible;grid-auto-rows:auto;flex:none}
.operations-page .operation-card{height:auto;min-height:0;overflow:visible}
.operations-primary .table-wrap{max-height:none;overflow-x:auto;overflow-y:visible}
.operations-primary .invite-list{max-height:none;overflow:visible}
.logs-card .log-list,.audit-card .event-list{max-height:none;overflow:visible;flex:none}
.logs-card .log-list{width:100%;min-width:0}
.logs-card .log-row{min-width:0;max-width:100%;overflow:hidden}
.logs-card .log-row>div{width:0;max-width:100%;flex:1 1 auto;min-width:0;overflow:hidden}
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
}
/* Long log messages should wrap on every screen size instead of widening the
log card or introducing page-level horizontal scrolling. */
.logs-card .log-row{min-width:0}
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
.connection-list{display:grid;gap:7px;max-height:180px;margin-top:12px;overflow-y:auto}
.connection-list{display:grid;gap:7px;margin-top:12px}
.connection-history-heading{display:grid;gap:3px;padding:0 0 6px;border-bottom:1px solid #edf1ef}
.connection-history-heading strong{font-size:10px}
.connection-history-heading small{color:#899792;font-size:8px}
@@ -1363,21 +1574,12 @@ async function parseResponse(response: Response) { const value = await response.
.language-link{margin-top:20px!important;padding:0!important;background:transparent!important;border:0!important;border-radius:0!important}
.login-actions .language-link{margin-top:0!important}
/* Desktop server settings must keep their own scroll surface. The admin shell
is viewport-locked, so an unconstrained flex item can otherwise push the
relay card below the clipped page-content area. */
/* Flexible fields must be allowed to shrink within responsive columns. */
.settings-card,.relay-card,.relay-node,.relay-fields,.relay-node-heading,.relay-enabled,.relay-fields>label,.password-row,.password-row>label{min-width:0}
.relay-enabled strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.relay-fields input{min-width:0}
.password-actions{flex:0 0 auto}
@media(min-width:851px){
.server-page{flex:1 1 auto;min-width:0;min-height:0;overflow-x:hidden;overflow-y:auto}
.server-page .settings-grid{min-width:0}
.settings-grid{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
.relay-fields{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
}
/* The application is zoomed up on large displays so the 1920×1080 layout
stays readable. Compensate viewport heights for that zoom; otherwise a
2K viewport becomes a 1920px-tall admin shell and clips its lower cards. */
@@ -1386,4 +1588,308 @@ async function parseResponse(response: Response) { const value = await response.
:global(#app),.admin-root,.admin-shell,.admin-sidebar{height:calc(100dvh / var(--ui-scale));min-height:calc(100dvh / var(--ui-scale));max-height:calc(100dvh / var(--ui-scale))}
.admin-main{height:100%;min-height:0}
}
/* Server settings: stacked, independently collapsible groups with related
controls arranged in columns when there is enough room. */
.server-page .settings-grid{display:grid;grid-template-columns:minmax(0,1fr);align-content:start;gap:12px;flex:0 0 auto;min-height:0;overflow:visible}
.server-page .settings-accordion{display:block;min-width:0;height:auto;overflow:visible;padding:0;border-radius:13px}
.settings-accordion-header{display:flex;min-height:70px;align-items:center;gap:18px;padding:14px 18px;list-style:none;cursor:pointer}
.settings-accordion-header::-webkit-details-marker{display:none}
.settings-accordion-header:focus-visible{outline:3px solid color-mix(in srgb,var(--admin-accent) 42%,transparent);outline-offset:3px;border-radius:10px}
.settings-accordion-heading{display:grid;min-width:0;flex:1 1 auto;gap:4px}
.settings-accordion-heading strong{overflow:hidden;color:var(--admin-text);font-size:14px;font-weight:800;text-overflow:ellipsis;white-space:nowrap}
.settings-accordion-heading small{overflow:hidden;color:var(--admin-muted);font-size:10px;line-height:1.45;text-overflow:ellipsis;white-space:nowrap}
.settings-accordion-header>.ui-icon{flex:none;color:var(--admin-muted);transition:transform .18s ease}
.settings-accordion[open]>.settings-accordion-header{border-bottom:1px solid var(--admin-border)}
.settings-accordion[open]>.settings-accordion-header>.ui-icon{transform:rotate(180deg)}
.settings-accordion-statuses{display:flex;align-items:center;justify-content:flex-end;gap:7px;flex:0 1 auto;flex-wrap:wrap}
.settings-summary-chip{display:inline-flex;align-items:center;gap:6px;padding:6px 9px;color:var(--admin-muted);background:var(--admin-raised);border:1px solid var(--admin-border);border-radius:999px;font-size:10px;line-height:1.2;white-space:nowrap}
.settings-summary-chip i{width:7px;height:7px;flex:0 0 7px;border-radius:50%;background:#87958f}
.settings-summary-chip i.active{background:#50c879;box-shadow:0 0 0 3px color-mix(in srgb,#50c879 16%,transparent)}
.settings-accordion-content{min-width:0;padding:16px 18px 18px}
.target-settings-layout{display:grid;min-width:0;grid-template-columns:minmax(0,1fr) minmax(220px,280px);align-items:end;gap:12px}
.access-settings-layout,.advanced-settings-grid{display:grid;min-width:0;grid-template-columns:minmax(0,1fr);align-items:start;gap:14px}
.site-identity-fields{display:grid;min-width:0;align-content:start;gap:13px}
.target-fields{grid-column:1;grid-row:1;grid-template-columns:minmax(0,1fr) 150px;gap:12px}
.target-settings-layout>.password-row{grid-column:1/-1;grid-row:2;align-self:end}
.target-settings-layout>.target-test-button{grid-column:2;grid-row:1;justify-self:stretch;width:100%;min-width:0;min-height:40px;align-self:end}
.target-test-result{grid-column:1/-1;min-width:0;margin:0}
.target-runtime-block{display:grid;grid-column:1/-1;grid-template-columns:max-content minmax(0,1fr);align-items:center;gap:12px;padding-top:2px}
.target-runtime-block h4{margin:0;color:var(--admin-text);font-size:11px}
.target-runtime-facts{display:grid;grid-column:2;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:0}
.target-runtime-facts>div{min-width:0;padding:9px;background:var(--admin-surface);border:1px solid var(--admin-border);border-radius:8px}
.target-runtime-facts>div:first-child{grid-column:auto}
.target-runtime-facts dt{color:var(--admin-muted);font-size:9px}
.target-runtime-facts dd{margin:4px 0 0;overflow-wrap:anywhere;color:var(--admin-text);font-size:11px;font-weight:700}
.access-settings-layout{grid-template-columns:minmax(0,1fr)}
.access-mode-fieldset{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr));align-content:start;gap:9px;min-width:0;margin:0;padding:0;border:0}
.access-mode-fieldset legend{grid-column:1/-1;margin-bottom:2px;color:var(--admin-muted);font-size:10px;font-weight:700}
.site-identity-fields>label{display:grid;gap:6px}
.site-identity-fields>label>span,.access-mode-fieldset .choice strong{color:var(--admin-text)}
.site-identity-fields .welcome-editor{min-width:0;margin:0}
.settings-subsection{display:grid;min-width:0;align-content:start;gap:12px;padding:15px;background:var(--admin-raised);border:1px solid var(--admin-border);border-radius:11px}
.settings-subsection-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}
.settings-subsection-heading h4{margin:0;color:var(--admin-text);font-size:13px}
.settings-subsection-heading .card-help{margin:4px 0 0;color:var(--admin-muted);font-size:10px;line-height:1.5}
.settings-subsection .choice{margin:0;background:var(--admin-surface);border-color:var(--admin-border)}
.settings-subsection .choice strong{color:var(--admin-text)}
.settings-subsection .choice small{color:var(--admin-muted)}
.settings-subsection .field-help{margin:0;color:var(--admin-muted);line-height:1.5}
.settings-subsection .relay-fields{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr))}
.settings-subsection .relay-fields .password-row{grid-column:1/-1}
.advanced-settings-grid>.relay-card,.advanced-settings-grid>.webrtc-card{grid-column:auto}
.settings-subsection .relay-node{background:var(--admin-surface);border-color:var(--admin-border)}
.settings-subsection .relay-empty{color:var(--admin-muted);background:var(--admin-surface);border-color:var(--admin-border)}
/* One palette is shared by explicit dark mode and system dark mode. */
.admin-root{--admin-page:#f4f8f6;--admin-surface:#fff;--admin-raised:#f6f9f8;--admin-field:#fff;--admin-text:#20302c;--admin-muted:#657873;--admin-border:#dfe8e5;--admin-accent:#087d74;--admin-accent-soft:#e4f3ef;color:var(--admin-text);background:var(--admin-page)}
:global(html[data-theme="dark"] .admin-root){--admin-page:#101918;--admin-surface:#172321;--admin-raised:#202f2c;--admin-field:#111d1b;--admin-text:#e8f3f0;--admin-muted:#b6c8c2;--admin-border:#3a514b;--admin-accent:#79ddd1;--admin-accent-soft:#1b3935}
@media(prefers-color-scheme:dark){:global(html[data-theme="system"] .admin-root){--admin-page:#101918;--admin-surface:#172321;--admin-raised:#202f2c;--admin-field:#111d1b;--admin-text:#e8f3f0;--admin-muted:#b6c8c2;--admin-border:#3a514b;--admin-accent:#79ddd1;--admin-accent-soft:#1b3935}}
.admin-root .admin-main{color:var(--admin-text);background:var(--admin-page)}
.admin-root .admin-topbar,.admin-root .settings-card,.admin-root .readonly-card,.admin-root .overview-card,.admin-root .operation-card,.admin-root .metric-grid article,.admin-root .setup-card,.admin-root .login-card{color:var(--admin-text);background:var(--admin-surface);border-color:var(--admin-border)}
.admin-root .settings-card h3,.admin-root .settings-card h4,.admin-root .readonly-card h3,.admin-root .overview-card h3,.admin-root .operation-card h3,.admin-root .page-heading h2,.admin-root .admin-topbar h1,.admin-root .settings-card label>span,.admin-root .settings-card legend,.admin-root .settings-card .choice strong{color:var(--admin-text)}
.admin-root .page-heading p,.admin-root .admin-topbar small,.admin-root .settings-card .card-help,.admin-root .settings-card .field-help,.admin-root .settings-card .choice small,.admin-root .settings-card .welcome-editor-heading>small,.admin-root .settings-card .port-fields-heading small,.admin-root .readonly-card dt,.admin-root .overview-card dt,.admin-root .metric-grid small,.admin-root .metric-grid em,.admin-root .overview-card header p,.admin-root .operation-card header p{color:var(--admin-muted)}
.admin-root input:not([type="checkbox"]):not([type="radio"]),.admin-root textarea,.admin-root select{color:var(--admin-text);background:var(--admin-field);border-color:var(--admin-border)}
.admin-root input::placeholder,.admin-root textarea::placeholder{color:var(--admin-muted);opacity:1}
.admin-root input:disabled,.admin-root textarea:disabled,.admin-root select:disabled{color:var(--admin-muted);background:var(--admin-raised);border-color:var(--admin-border);opacity:1}
.admin-root input[type="checkbox"],.admin-root input[type="radio"]{accent-color:var(--admin-accent)}
.admin-root .settings-card .choice{color:var(--admin-text);background:var(--admin-raised);border-color:var(--admin-border)}
.admin-root .settings-card .choice.selected{background:color-mix(in srgb,var(--admin-accent) 10%,var(--admin-surface));border-color:color-mix(in srgb,var(--admin-accent) 48%,var(--admin-border))}
.admin-root .welcome-editor,.admin-root .webrtc-port-fields,.admin-root .relay-node,.admin-root .relay-empty,.admin-root .readonly-card dl div,.admin-root .overview-card dl div,.admin-root .event-list li,.admin-root .connection-row,.admin-root .connection-history-heading,.admin-root .diagnostic-list div,.admin-root .log-row,.admin-root .invite-row{color:var(--admin-text);background:var(--admin-raised);border-color:var(--admin-border)}
.admin-root .welcome-editor select,.admin-root .welcome-editor textarea{color:var(--admin-text);background:var(--admin-field);border-color:var(--admin-border)}
.admin-root .welcome-editor-heading>small,.admin-root .port-fields-heading small,.admin-root .field-help,.admin-root .relay-empty,.admin-root .target-runtime-facts dt,.admin-root .connection-person small,.admin-root .connection-detail small,.admin-root .connection-history-heading small,.admin-root .diagnostic-list dt,.admin-root .log-row small,.admin-root .invite-row small{color:var(--admin-muted)}
.admin-root .settings-subsection{color:var(--admin-text);background:var(--admin-raised);border-color:var(--admin-border)}
.admin-root .target-runtime-facts>div,.admin-root .settings-subsection .choice,.admin-root .settings-subsection .relay-node,.admin-root .settings-subsection .relay-empty{background:var(--admin-surface);border-color:var(--admin-border)}
.admin-root .password-actions button{color:var(--admin-accent);background:var(--admin-accent-soft)}
.admin-root .password-actions button.active,.admin-root .primary-button{color:#fff;background:#087d74}
.admin-root .password-actions button.danger,.admin-root .danger-button,.admin-root .text-danger{color:#d66d65;background:color-mix(in srgb,#d66d65 12%,var(--admin-surface));border-color:color-mix(in srgb,#d66d65 30%,var(--admin-border))}
.admin-root .secondary-button,.admin-root .admin-topbar button,.admin-root .admin-topbar .language-select,.admin-root .home-link{color:var(--admin-accent);background:var(--admin-accent-soft);border-color:var(--admin-border)}
.admin-root .settings-accordion-header>.ui-icon{color:var(--admin-muted)}
.admin-root .settings-summary-chip{color:var(--admin-muted);background:var(--admin-raised);border-color:var(--admin-border)}
.admin-root .admin-sidebar nav a{color:#c2d8d3}
.admin-root .admin-sidebar nav a.active{color:#eafffb;background:#0d615a}
@media(max-width:1050px){
.target-settings-layout{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
.target-fields,.target-test-result,.target-runtime-block{grid-column:1/-1}
.target-settings-layout>.password-row{grid-column:1}
.target-settings-layout>.target-test-button{grid-column:2}
.access-settings-layout,.advanced-settings-grid{grid-template-columns:minmax(0,1fr)}
}
@media(max-width:850px){
.server-page .settings-grid{grid-template-columns:minmax(0,1fr);grid-auto-rows:auto;overflow:visible}
.settings-accordion-header{min-height:64px;gap:10px;padding:12px 14px}
.settings-accordion-statuses{justify-content:flex-start}
.settings-accordion-content{padding:13px 14px 15px}
.settings-subsection .relay-fields{grid-template-columns:minmax(0,1fr)}
.settings-subsection .relay-fields .password-row{grid-column:auto}
}
@media(max-width:560px){
.settings-accordion-header{align-items:flex-start;flex-wrap:wrap}
.settings-accordion-heading{flex-basis:calc(100% - 34px)}
.settings-accordion-statuses{order:3;width:100%;padding-right:25px}
.settings-accordion-header>.ui-icon{margin-left:auto}
.target-settings-layout{grid-template-columns:minmax(0,1fr)}
.target-fields,.port-inputs,.target-runtime-facts{grid-template-columns:minmax(0,1fr)}
.target-settings-layout>.password-row,.target-settings-layout>.target-test-button,.target-test-result,.target-runtime-block{grid-column:1}
.target-runtime-facts>div:first-child{grid-column:auto}
.target-runtime-block{grid-template-columns:minmax(0,1fr)}
.target-runtime-facts{grid-column:auto}
.target-settings-layout,.access-settings-layout,.advanced-settings-grid{gap:11px}
.access-mode-fieldset .choice{padding:10px}
}
/* Admin layout contract: the desktop shell stays in the viewport, the main
content is the only page-level scroller, and cards size to their content. */
:global(html),:global(body),:global(#app){width:100%;height:100dvh;min-height:0;max-height:100dvh;overflow:hidden}
.admin-root{min-height:0;overflow:hidden}
.admin-shell{display:grid;min-height:0;grid-template-columns:236px minmax(0,1fr);overflow:hidden}
.admin-main{display:flex;min-width:0;min-height:0;flex-direction:column;overflow:hidden}
.admin-topbar{flex:0 0 auto}
.admin-main>.page-alert{flex:0 0 auto;margin:12px clamp(18px,2.4vw,44px) 0}
.page-content{display:block;flex:1 1 auto;width:100%;max-width:none;min-width:0;min-height:0;margin:0;padding:clamp(18px,2vw,32px) clamp(18px,2.4vw,44px) 34px;overflow-x:hidden;overflow-y:auto}
.login-page{height:100dvh;min-height:0;overflow:hidden}
.login-card{max-height:calc(100dvh - 50px);overflow-y:auto}
.overview-page{display:grid;align-content:start;grid-template-columns:minmax(0,1fr);gap:14px}
.overview-page .import-notice,.overview-page .metric-grid{margin:0}
.overview-page .hero-status{padding:clamp(18px,2vw,28px)}
.overview-page .metric-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
.overview-page .overview-columns{display:grid;grid-template-columns:minmax(0,1fr);align-content:start;gap:14px}
.overview-page .overview-card{min-width:0;height:auto;min-height:0;overflow:visible}
.overview-page .target-health-card dl{grid-template-columns:repeat(3,minmax(0,1fr))}
.overview-page .recent-events-card .event-list{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr));max-height:none;overflow:visible}
.server-page{min-width:0}
.server-page .settings-grid{grid-template-columns:minmax(0,1fr);align-content:start;gap:12px}
.server-page .settings-card{height:auto;min-height:0;overflow:visible}
.operations-page{display:grid;align-content:start;gap:14px;width:auto;height:auto;min-height:0;padding-top:0;padding-bottom:0}
.operations-page .page-heading,.operations-page .system-notice{margin:0}
.operations-page .operations-grid{min-width:0;align-items:start;gap:14px}
.operations-primary{grid-template-columns:repeat(auto-fit,minmax(min(100%,400px),1fr))}
.lower-operations{grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr));margin-top:0}
.operation-card{height:auto;min-height:0;overflow:visible}
.operation-empty{min-height:84px}
.operations-primary .table-wrap{max-height:min(42vh,420px);overflow:auto}
.operations-primary .invite-list{max-height:min(32vh,280px);overflow-y:auto}
.connection-list{max-height:min(34vh,280px);overflow-y:auto}
.logs-card .log-list,.audit-card .event-list{max-height:min(38vh,340px);overflow-y:auto}
.logs-card,.audit-card{min-height:0}
.logs-card .log-row{min-width:0;max-width:100%}
.logs-card .log-row>div{min-width:0;flex:1 1 auto}
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
@media(min-width:1101px){
.operations-page .invite-form{grid-template-columns:minmax(220px,1.2fr) minmax(280px,1fr) auto;align-items:end;gap:12px 16px}
.operations-page .invite-form>label{grid-column:1;grid-row:1}
.operations-page .invite-form-grid{grid-column:2;grid-row:1;align-self:end}
.operations-page .invite-form>.field-help{grid-column:1/3;grid-row:2}
.operations-page .invite-form>.primary-button{grid-column:3;grid-row:1;white-space:nowrap}
.operations-page .diagnostics-card{display:grid;grid-template-columns:minmax(0,1fr)}
.operations-page .diagnostics-card>header{grid-column:1/-1}
.operations-page .diagnostics-card>.diagnostic-list{grid-column:1;grid-row:2}
.operations-page .diagnostics-card>.secondary-button{grid-column:1;grid-row:3;justify-self:end;white-space:nowrap}
}
@media(max-width:1100px){
.target-settings-layout{grid-template-columns:minmax(0,1fr) minmax(180px,.42fr)}
.target-fields{grid-column:1;grid-row:1;grid-template-columns:minmax(0,1fr) 132px}
.target-settings-layout>.password-row{grid-column:1/-1;grid-row:2}
.target-settings-layout>.target-test-button{grid-column:2;grid-row:1}
.access-settings-layout,.advanced-settings-grid{grid-template-columns:minmax(0,1fr)}
}
@media(max-width:850px){
:global(html),:global(body),:global(#app){height:auto;min-height:100%;max-height:none;overflow:auto}
.admin-root{height:auto;min-height:100dvh;overflow:visible}
.admin-shell{display:flex;height:auto;min-height:100dvh;flex-direction:column;overflow:visible}
.admin-sidebar{position:static;width:100%;height:auto;min-height:0;flex-direction:row;align-items:center;padding:12px 16px}
.admin-sidebar .admin-brand{padding:0}
.admin-sidebar .admin-brand small{display:none}
.admin-sidebar nav{display:flex;margin-left:auto}
.sidebar-bottom{display:flex;margin:0 0 0 8px;padding:0;border:0}
.sidebar-bottom a{display:none}
.sidebar-bottom button{font-size:0}
.admin-main{height:auto;min-height:0;overflow:visible}
.admin-topbar{min-height:68px;padding:0 18px}
.admin-main>.page-alert{margin:10px 14px 0}
.page-content{display:block;width:100%;height:auto;min-height:0;padding:20px clamp(14px,3vw,28px) 28px;overflow:visible}
.login-page{height:auto;min-height:100dvh;overflow:visible}
.login-card{max-height:none;overflow:visible}
.overview-page{min-height:0}
.overview-page .metric-grid{grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));gap:9px}
.overview-page .overview-columns{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr))}
.operations-page .operations-primary{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr))}
.operations-page .lower-operations{grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr))}
.operations-page .operation-card{height:auto;min-height:0;overflow:visible}
.operations-primary .table-wrap{max-height:min(48vh,420px);overflow:auto}
.operations-primary .invite-list{max-height:min(38vh,320px);overflow-y:auto}
.connection-list{max-height:min(38vh,320px);overflow-y:auto}
.logs-card .log-list,.audit-card .event-list{max-height:min(45vh,380px);overflow-y:auto}
}
@media(max-width:560px){
.admin-topbar{gap:8px}
.admin-topbar>div:last-child{gap:5px}
.overview-page .hero-status{padding:18px}
.overview-page .hero-status h2{font-size:24px}
.overview-page .metric-grid article{padding:14px}
.overview-page .metric-grid article>span{top:11px;right:11px;width:30px;height:30px}
.overview-page .metric-grid strong{margin-top:10px;font-size:16px}
.overview-page .target-health-card dl{grid-template-columns:repeat(auto-fit,minmax(min(100%,190px),1fr))}
.operations-page .operations-primary,.operations-page .lower-operations{grid-template-columns:minmax(0,1fr)}
.operations-page .operation-card{padding:16px}
.operations-page .table-wrap{margin-right:-16px;margin-left:-16px;margin-bottom:-16px}
.operations-page .invite-form-grid,.operations-page .diagnostic-list{grid-template-columns:minmax(0,1fr)}
.operations-page .generated-link{display:grid}
.operations-page .invite-row{align-items:flex-start;flex-direction:column}
.operations-page .invite-row-meta{width:100%;justify-content:flex-end}
.operations-page .connection-row{display:grid;gap:7px}
.operations-page .connection-detail{justify-items:start;text-align:left}
.target-settings-layout{grid-template-columns:minmax(0,1fr)}
.target-fields,.port-inputs,.target-runtime-facts{grid-template-columns:minmax(0,1fr)}
.target-fields{grid-column:1;grid-row:1}
.target-settings-layout>.password-row{grid-column:1;grid-row:2}
.target-settings-layout>.target-test-button{grid-column:1;grid-row:3;justify-self:stretch;width:100%}
.target-test-result{grid-column:1;grid-row:4}
.target-runtime-block{grid-column:1;grid-row:5}
.target-runtime-block{grid-template-columns:minmax(0,1fr)}
.target-runtime-facts{grid-column:auto}
}
</style>
<style scoped>
.skin-file-input{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;clip-path:inset(50%)}
.skin-library-page{display:grid;align-content:start;gap:16px}
.skin-library-page>.page-heading,.skin-library-page>.skin-library-scope{margin:0}
.skin-library-scope{display:flex;align-items:center;gap:9px}
.skin-default-control{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:15px 17px;background:var(--admin-surface,#fff);border:1px solid var(--admin-border,#dce7e3);border-radius:12px}
.skin-default-control strong{color:var(--admin-text,#20312d);font-size:13px}
.skin-default-control p{margin:4px 0 0;color:var(--admin-muted,#687a74);font-size:11px}
.skin-default-control select{min-width:min(100%,270px);padding:10px 12px;color:var(--admin-text,#20312d);background:var(--admin-input,#fff);border:1px solid var(--admin-border,#dce7e3);border-radius:9px;font:inherit}
.skin-library-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,360px),1fr));gap:14px;align-content:start}
.skin-library-card{display:grid;grid-template-columns:minmax(140px,.78fr) minmax(0,1.22fr);min-width:0;overflow:hidden;background:var(--admin-surface,#fff);border:1px solid var(--admin-border,#dce7e3);border-radius:14px;box-shadow:0 6px 20px rgba(20,60,53,.04)}
.skin-preview{position:relative;display:grid;place-items:center;min-height:180px;overflow:hidden;color:#5f9f97;background:linear-gradient(145deg,#e5f5f1,#f5f8f7)}
.skin-preview--day{color:#087e86;background:linear-gradient(145deg,#e8fbfb 0%,#c7f0ed 52%,#fff 100%)}
.skin-preview--night{color:#b5e8df;background:linear-gradient(145deg,#122320 0%,#223a37 55%,#0b1514 100%)}
.skin-preview img{width:100%;height:100%;position:absolute;inset:0;object-fit:cover}
.skin-preview>span{display:grid;place-items:center;width:54px;height:54px;border:1px solid #cde8e2;border-radius:16px;background:rgba(255,255,255,.68)}
.skin-preview--night>span{border-color:rgba(181,232,223,.32);background:rgba(225,255,249,.1)}
.skin-preview small{position:absolute;right:9px;bottom:9px;padding:4px 7px;color:#f7fffd;background:rgba(17,40,37,.72);border-radius:6px;font-size:10px}
.skin-builtin-badge{position:absolute;top:9px;left:9px;padding:4px 7px;color:#075f5d;background:rgba(240,255,252,.92);border:1px solid rgba(255,255,255,.72);border-radius:6px;font-size:10px}
.skin-library-copy{display:flex;min-width:0;flex-direction:column;padding:14px}
.skin-library-title{display:grid;gap:3px;min-width:0}
.skin-library-title h3{margin:0;color:var(--admin-text,#20312d);font-size:15px}
.skin-library-title>span{overflow:hidden;color:var(--admin-muted,#7d8d88);font-size:10px;text-overflow:ellipsis;white-space:nowrap}
.skin-library-copy>p{margin:10px 0 0;color:var(--admin-muted,#687a74);font-size:11px;line-height:1.5}
.skin-library-copy dl{display:grid;gap:5px;margin:12px 0 0}
.skin-library-copy dl>div{display:flex;justify-content:space-between;gap:12px;font-size:10px}
.skin-library-copy dt{color:var(--admin-muted,#879590)}
.skin-library-copy dd{margin:0;color:var(--admin-text,#30423d);text-align:right;overflow-wrap:anywhere}
.skin-library-actions{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:auto;padding-top:13px}
.skin-library-actions button,.skin-library-actions a{font-size:11px}
.skin-protected-label{color:var(--admin-muted,#687a74);font-size:10px}
.skin-enabled-control{display:inline-flex;align-items:center;gap:6px;color:var(--admin-muted,#687a74);font-size:10px;white-space:nowrap}
.skin-enabled-control input{width:16px;height:16px;margin:0;accent-color:#07877e}
.skin-library-empty,.skin-library-loading{display:grid;justify-items:center;gap:9px;padding:48px 18px;color:var(--admin-muted,#7d8d88);text-align:center;background:var(--admin-surface,#fff);border:1px dashed var(--admin-border,#dce7e3);border-radius:14px}
.skin-library-empty>span{display:grid;place-items:center;width:46px;height:46px;color:#0b8075;background:#e5f5f1;border-radius:14px}
.skin-library-empty strong{color:var(--admin-text,#263a35);font-size:14px}
.skin-library-empty p{margin:0;font-size:11px}
.skin-library-loading{display:flex;justify-content:center}
@media(max-width:620px){.skin-library-card{grid-template-columns:minmax(0,1fr)}.skin-preview{min-height:190px;aspect-ratio:16/9}.skin-library-page>.page-heading{align-items:flex-start}.skin-library-page>.page-heading .primary-button{white-space:nowrap}.skin-default-control{align-items:flex-start;flex-direction:column}.skin-default-control select{width:100%}}
</style>
<style scoped>
.operations-page .operations-grid{grid-template-columns:minmax(0,1fr);align-items:start;gap:14px}
.operations-page .operations-primary,.operations-page .lower-operations{grid-template-columns:minmax(0,1fr);margin-top:0}
.operations-page .operation-card{height:auto;min-height:0;overflow:visible}
.operations-page .operation-empty{min-height:84px}
.operations-page .diagnostic-list{grid-template-columns:repeat(auto-fit,minmax(min(100%,140px),1fr))}
.operations-page .audit-card .event-list{grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr))}
@media(min-width:1101px){
.operations-page .invite-form{grid-template-columns:minmax(220px,1.2fr) minmax(280px,1fr) auto;align-items:end;gap:12px 16px}
.operations-page .invite-form>label{grid-column:1;grid-row:1}
.operations-page .invite-form-grid{grid-column:2;grid-row:1;align-self:end}
.operations-page .invite-form>.field-help{grid-column:1/3;grid-row:2}
.operations-page .invite-form>.primary-button{grid-column:3;grid-row:1;white-space:nowrap}
.operations-page .diagnostics-card{display:grid;grid-template-columns:minmax(0,1fr)}
.operations-page .diagnostics-card>header{grid-column:1/-1}
.operations-page .diagnostics-card>.diagnostic-list{grid-column:1;grid-row:2;grid-template-columns:repeat(5,minmax(0,1fr))}
.operations-page .diagnostics-card>.secondary-button{grid-column:1;grid-row:3;justify-self:end;white-space:nowrap}
}
@media(max-width:1100px){
.operations-page .diagnostic-list{grid-template-columns:repeat(auto-fit,minmax(min(100%,140px),1fr))}
}
@media(max-width:850px){
.operations-page .operations-primary,.operations-page .lower-operations{grid-template-columns:minmax(0,1fr)}
.operations-page .invite-form{grid-template-columns:minmax(0,1fr)}
.operations-page .invite-form>label,.operations-page .invite-form-grid,.operations-page .invite-form>.field-help,.operations-page .invite-form>.primary-button{grid-column:1;grid-row:auto}
.operations-page .diagnostics-card{display:block}
}
@media(max-width:560px){
.operations-page .diagnostic-list{grid-template-columns:minmax(0,1fr)}
}
</style>
+114 -39
View File
@@ -1,47 +1,82 @@
<template>
<div class="demo-page">
<header class="demo-header">
<div class="demo-brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
<div class="demo-tools"><span class="demo-badge">{{ copy.demoBadge }}</span><LanguageSwitcher v-model="language" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/">{{ copy.back }}</a></div>
<div :class="['demo-page', 'ws-skin-root', { 'skin-initializing': !skinReady }]" data-ws-part="app" data-ws-page="demo">
<header class="demo-header" data-ws-part="demo.header">
<div class="demo-brand" data-ws-part="demo.brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
<div class="demo-tools" data-ws-part="demo.header-tools"><span class="demo-badge" data-ws-part="demo.badge">{{ copy.demoBadge }}</span><SkinSwitcher v-model="activeSkinId" data-ws-part="demo.skin-switcher" :menu-label="copy.skinSelector" :options="skinOptions" @change="onSkinChange" /><LanguageSwitcher v-model="language" data-ws-part="demo.language-switcher" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/" data-ws-part="demo.home-link">{{ copy.back }}</a></div>
</header>
<div v-if="reconnecting" class="demo-reconnect" role="status"><Icon name="refresh" :size="17" /><span>{{ copy.reconnecting }}</span><button type="button" @click="reconnecting = false">{{ copy.restore }}</button></div>
<main class="demo-shell">
<aside class="demo-channel-panel">
<div class="demo-panel-title"><span>{{ copy.channels }}</span><strong>{{ selectedChannel.name }}</strong></div>
<div v-for="channel in channels" :key="channel.id" :class="['demo-channel', { active: selectedChannelId === channel.id }]">
<button type="button" @click="selectChannel(channel.id)"><Icon name="volume" :size="16" /><span>{{ channel.name }}</span><small>{{ channel.members.length }}</small></button>
<div class="demo-channel-members"><span v-for="member in channel.members" :key="member.id" :class="{ speaking: speakingId === member.id }"><i :style="avatarStyle(member.name)">{{ member.name[0] }}</i>{{ member.name }}</span></div>
<div v-if="reconnecting" class="demo-reconnect" data-ws-part="demo.reconnect" role="status"><Icon name="refresh" :size="17" /><span>{{ copy.reconnecting }}</span><button type="button" data-ws-part="demo.reconnect.restore" @click="reconnecting = false">{{ copy.restore }}</button></div>
<main class="demo-shell" data-ws-part="demo.layout">
<aside class="demo-channel-panel" data-ws-part="demo.channels">
<div class="demo-panel-title" data-ws-part="demo.channels.heading"><span>{{ copy.channels }}</span><strong>{{ selectedChannel.name }}</strong></div>
<div v-for="channel in channels" :key="channel.id" :class="['demo-channel', { active: selectedChannelId === channel.id }]" data-ws-part="demo.channel" :data-ws-state="selectedChannelId === channel.id ? 'active' : 'idle'">
<button type="button" data-ws-part="demo.channel.select" @click="selectChannel(channel.id)"><Icon name="volume" :size="16" /><span>{{ channel.name }}</span><small>{{ channel.members.length }}</small></button>
<div class="demo-channel-members" data-ws-part="demo.channel.members"><span v-for="member in channel.members" :key="member.id" :class="{ speaking: speakingId === member.id }"><i :style="avatarStyle(member.name)">{{ member.name[0] }}</i>{{ member.name }}</span></div>
</div>
</aside>
<section class="demo-main">
<div class="demo-hero"><div><span class="demo-live"><i></i>{{ copy.simulated }}</span><h1><Icon name="volume" :size="24" /> {{ selectedChannel.name }}</h1><p>{{ copy.heroLead }}</p><small><Icon name="users" :size="14" /> {{ selectedChannel.members.length }} {{ copy.online }}</small></div><div class="demo-wave" aria-hidden="true"><i v-for="bar in bars" :key="bar" :style="{ height: `${bar}px` }"></i></div></div>
<div class="demo-section-heading"><span>{{ copy.voiceActivity }}</span><strong>{{ copy.speakingNow }}</strong></div>
<div class="demo-voice-grid"><article v-for="member in selectedChannel.members" :key="member.id" :class="['demo-voice-card', { speaking: speakingId === member.id }]" @click="speakingId = member.id"><i :style="avatarStyle(member.name)">{{ member.name[0] }}</i><strong>{{ member.name }}</strong><span>{{ speakingId === member.id ? copy.speaking : copy.connected }}</span></article></div>
<section class="demo-main" data-ws-part="demo.main">
<div class="demo-hero" data-ws-part="demo.hero"><div><span class="demo-live" data-ws-part="demo.live"><i></i>{{ copy.simulated }}</span><h1 data-ws-part="demo.hero.title"><Icon name="volume" :size="24" /> {{ selectedChannel.name }}</h1><p data-ws-part="demo.hero.description">{{ copy.heroLead }}</p><small data-ws-part="demo.hero.online"><Icon name="users" :size="14" /> {{ selectedChannel.members.length }} {{ copy.online }}</small></div><div class="demo-wave" data-ws-part="demo.wave" aria-hidden="true"><i v-for="bar in bars" :key="bar" :style="{ height: `${bar}px` }"></i></div></div>
<div class="demo-section-heading" data-ws-part="demo.voice-heading"><span>{{ copy.voiceActivity }}</span><strong>{{ copy.speakingNow }}</strong></div>
<div class="demo-voice-grid" data-ws-part="demo.voice-grid"><article v-for="member in selectedChannel.members" :key="member.id" :class="['demo-voice-card', { speaking: speakingId === member.id }]" data-ws-part="demo.voice-card" :data-ws-state="speakingId === member.id ? 'speaking' : 'connected'" @click="speakingId = member.id"><i data-ws-part="demo.avatar" :style="avatarStyle(member.name)">{{ member.name[0] }}</i><strong data-ws-part="demo.member-name">{{ member.name }}</strong><span data-ws-part="demo.member-status">{{ speakingId === member.id ? copy.speaking : copy.connected }}</span></article></div>
<div class="demo-chat-head"><div><span>{{ copy.textChannel }}</span><strong># {{ selectedChannel.name }} {{ copy.chat }}</strong></div><div class="demo-tabs"><button v-for="tab in tabs" :key="tab.id" type="button" :class="{ active: activeTab === tab.id }" @click="activeTab = tab.id">{{ tab.label }}</button></div></div>
<div class="demo-messages"><div v-for="message in visibleMessages" :key="message.id" :class="['demo-message', { mine: message.mine }]" @dblclick="message.mine = !message.mine"><i :style="avatarStyle(message.author)">{{ message.author[0] }}</i><div><small>{{ message.author }} · {{ message.time }}</small><p>{{ messageText(message) }}</p></div></div><div v-if="!visibleMessages.length" class="demo-empty"><Icon name="message" :size="22" /><strong>{{ copy.emptyChat }}</strong></div></div>
<form class="demo-composer" @submit.prevent="sendMessage"><input v-model="draft" :placeholder="copy.placeholder" :aria-label="copy.placeholder" /><button type="submit" :disabled="!draft.trim()"><Icon name="send" :size="17" /></button></form>
<div class="demo-chat-head" data-ws-part="demo.chat.heading"><div><span>{{ copy.textChannel }}</span><strong># {{ selectedChannel.name }} {{ copy.chat }}</strong></div><div class="demo-tabs" data-ws-part="demo.chat.tabs"><button v-for="tab in tabs" :key="tab.id" type="button" :class="{ active: activeTab === tab.id }" data-ws-part="demo.chat.tab" :data-ws-state="activeTab === tab.id ? 'active' : 'idle'" @click="activeTab = tab.id">{{ tab.label }}</button></div></div>
<div class="demo-messages" data-ws-part="demo.chat.messages"><div v-for="message in visibleMessages" :key="message.id" :class="['demo-message', { mine: message.mine }]" data-ws-part="demo.chat.message" :data-ws-state="message.mine ? 'mine' : 'other'" @dblclick="message.mine = !message.mine"><i :style="avatarStyle(message.author)">{{ message.author[0] }}</i><div><small>{{ message.author }} · {{ message.time }}</small><p>{{ messageText(message) }}</p></div></div><div v-if="!visibleMessages.length" class="demo-empty" data-ws-part="demo.chat.empty"><Icon name="message" :size="22" /><strong>{{ copy.emptyChat }}</strong></div></div>
<form class="demo-composer" data-ws-part="demo.chat.composer" @submit.prevent="sendMessage"><input v-model="draft" data-ws-part="demo.chat.input" :placeholder="copy.placeholder" :aria-label="copy.placeholder" /><button type="submit" data-ws-part="demo.chat.send" :disabled="!draft.trim()"><Icon name="send" :size="17" /></button></form>
</section>
<aside class="demo-actions-panel"><div class="demo-panel-title"><span>{{ copy.voice }}</span><strong>{{ copy.simulationControls }}</strong></div><button type="button" @click="toggleSpeaking"><Icon name="mic" :size="17" /> {{ speakingId ? copy.stopSpeaking : copy.simulateSpeaking }}</button><button type="button" @click="poke = !poke"><Icon name="bell" :size="17" /> {{ copy.poke }}</button><button type="button" @click="reconnecting = true"><Icon name="refresh" :size="17" /> {{ copy.simulateReconnect }}</button><div class="demo-note"><Icon name="shield" :size="16" /><span>{{ copy.demoNote }}</span></div><div class="demo-user"><i :style="avatarStyle('illusia')">I</i><div><strong>illusia</strong><small>{{ copy.you }} · {{ copy.ready }}</small></div><span class="demo-green-dot"></span></div></aside>
<aside class="demo-actions-panel" data-ws-part="demo.actions"><div class="demo-panel-title" data-ws-part="demo.actions.heading"><span>{{ copy.voice }}</span><strong>{{ copy.simulationControls }}</strong></div><button type="button" data-ws-part="demo.action.speaking" @click="toggleSpeaking"><Icon name="mic" :size="17" /> {{ speakingId ? copy.stopSpeaking : copy.simulateSpeaking }}</button><button type="button" data-ws-part="demo.action.poke" @click="poke = !poke"><Icon name="bell" :size="17" /> {{ copy.poke }}</button><button type="button" data-ws-part="demo.action.reconnect" @click="reconnecting = true"><Icon name="refresh" :size="17" /> {{ copy.simulateReconnect }}</button><div class="demo-note" data-ws-part="demo.note"><Icon name="shield" :size="16" /><span>{{ copy.demoNote }}</span></div><div class="demo-user" data-ws-part="demo.user"><i :style="avatarStyle('illusia')">I</i><div><strong>illusia</strong><small>{{ copy.you }} · {{ copy.ready }}</small></div><span class="demo-green-dot"></span></div></aside>
</main>
<div v-if="poke" class="demo-poke" role="status"><Icon name="bell" :size="17" /><span><strong>msicbot</strong> {{ copy.pokedYou }}</span><button type="button" @click="poke = false"><Icon name="close" :size="14" /></button></div>
<div v-if="poke" class="demo-poke" data-ws-part="demo.poke-notification" role="status"><Icon name="bell" :size="17" /><span><strong>msicbot</strong> {{ copy.pokedYou }}</span><button type="button" data-ws-part="demo.poke.dismiss" @click="poke = false"><Icon name="close" :size="14" /></button></div>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { computed, onMounted, ref, shallowRef } from "vue";
import Icon from "../components/Icon.vue";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
import SkinSwitcher, { type SkinOption } from "../components/SkinSwitcher.vue";
import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
import { BUILTIN_ILLUSIA_SKIN_ID, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, getStoredSkinId } from "../services/skin-runtime.js";
import type { InstalledSkin } from "../services/skin-pack.js";
import { getStoredTheme, isDarkTheme } from "../services/theme.js";
type Language = "zh" | "en" | "de" | "ru" | "ja";
const illusiaSkinLabels: Record<Language, string> = { zh: "ILLUSIA 风", en: "ILLUSIA style", de: "ILLUSIA-Stil", ru: "Стиль ILLUSIA", ja: "ILLUSIA スタイル" };
interface DemoMessage { id: number; author: string; time: string; text: string; zhText?: string; enText?: string; ruText?: string; jaText?: string; mine: boolean }
type Tab = "channel" | "server";
const storedLanguage = localStorage.getItem("webspeak:language");
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" || storedLanguage === "ru" || storedLanguage === "ja" ? storedLanguage : "zh");
const copy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : language.value === "ru" ? ru : language.value === "ja" ? ja : en);
const baseCopy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : language.value === "ru" ? ru : language.value === "ja" ? ja : en);
const activeSkin = shallowRef<InstalledSkin | null>(null);
const storedSkinId = getStoredSkinId();
const activeSkinId = ref(storedSkinId ?? (isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN));
const skinReady = ref(storedSkinId === BUILTIN_LIGHT_SKIN || storedSkinId === BUILTIN_DARK_SKIN);
const installedSkins = ref<InstalledSkin[]>([]);
const catalogSkins = ref<SkinCatalogEntry[]>([]);
const skinOptions = computed<SkinOption[]>(() => [
...catalogSkins.value.map((skin) => ({
value: skin.id,
label: skin.id === BUILTIN_LIGHT_SKIN ? copy.value.skinDay : skin.id === BUILTIN_DARK_SKIN ? copy.value.skinNight : skin.id === BUILTIN_ILLUSIA_SKIN_ID ? illusiaSkinLabels[language.value] : skin.name,
icon: skin.id === BUILTIN_LIGHT_SKIN ? "sun" : skin.id === BUILTIN_DARK_SKIN ? "moon" : "compass",
})),
...installedSkins.value.filter((skin) => !catalogSkins.value.some((item) => item.id === skin.id) && isPublicSkinEnabled(skin.id)).map((skin) => ({ value: skin.id, label: skin.name, icon: "compass" })),
]);
const copy = computed(() => {
const result = { ...baseCopy.value };
const content = activeSkin.value?.contentData;
if (!content) return result;
const fullLocale = language.value === "zh" ? "zh-CN" : language.value === "en" ? "en-US" : language.value === "de" ? "de-DE" : language.value === "ru" ? "ru-RU" : "ja-JP";
for (const locale of [...new Set([content.defaultLocale, language.value, fullLocale])]) {
for (const [key, value] of Object.entries(content.locales[locale]?.messages ?? {})) {
if (!key.startsWith("demo.")) continue;
const copyKey = key.slice("demo.".length) as keyof typeof result;
if (Object.prototype.hasOwnProperty.call(result, copyKey) && value.trim()) result[copyKey] = value;
}
}
return result;
});
const selectedChannelId = ref("quiet");
const activeTab = ref<Tab>("channel");
const speakingId = ref("illusia");
@@ -58,16 +93,56 @@ const messages = ref<DemoMessage[]>([
{ id: 1, author: "illusia", time: "10:24", text: "", zhText: "大家好,欢迎来到 WebSpeak。", enText: "Hello everyone, welcome to WebSpeak.", mine: true },
{ id: 2, author: "msicbot", time: "10:25", text: "", zhText: "语音和文字频道都已同步。", enText: "Voice and text channels are in sync.", mine: false },
]);
const zh = { languageMenu: "语言", browserClient: "浏览器语音工作台", demoBadge: "演示 — 模拟数据", languageSwitch: "English", back: "返回主页", reconnecting: "连接中断,正在恢复…", restore: "恢复连接", channels: "频道", channel: "频道", simulated: "演示状态", heroLead: "这里展示 WebSpeak 的频道、语音和聊天交互。", online: "人在线", voiceActivity: "语音活动", speakingNow: "正在语音中", speaking: "正在说话…", connected: "已连接", textChannel: "文字频道", chat: "聊天", server: "服务器", emptyChat: "暂无消息", placeholder: "发送一条消息…", voice: "语音", simulationControls: "模拟控制", stopSpeaking: "停止说话", simulateSpeaking: "模拟发言", poke: "戳一戳", simulateReconnect: "模拟重连", demoNote: "此页面不会连接真实 TeamSpeak 服务器。", you: "你", ready: "已就绪", pokedYou: "戳了你一下" };
const en = { languageMenu: "Language", browserClient: "Browser voice workspace", demoBadge: "Demo — simulated data", languageSwitch: "中文", back: "Back home", reconnecting: "Connection interrupted, recovering…", restore: "Restore", channels: "Channels", channel: "Channel", simulated: "Simulation", heroLead: "A preview of WebSpeak channels, voice, and chat interactions.", online: "online", voiceActivity: "VOICE ACTIVITY", speakingNow: "Speaking now", speaking: "Speaking…", connected: "Connected", textChannel: "TEXT CHANNEL", chat: "chat", server: "Server", emptyChat: "No messages yet", placeholder: "Send a message…", voice: "Voice", simulationControls: "Simulation controls", stopSpeaking: "Stop speaking", simulateSpeaking: "Simulate speaking", poke: "Poke", simulateReconnect: "Simulate reconnect", demoNote: "This page never connects to a real TeamSpeak server.", you: "You", ready: "Ready", pokedYou: "poked you" };
const de = { languageMenu: "Sprache", browserClient: "Sprachbereich im Browser", demoBadge: "Demo — simulierte Daten", languageSwitch: "中文", back: "Zur Startseite", reconnecting: "Verbindung unterbrochen, Wiederherstellung…", restore: "Wiederherstellen", channels: "Kanäle", channel: "Kanal", simulated: "Simulation", heroLead: "Eine Vorschau auf Kanäle, Sprache und Chat von WebSpeak.", online: "online", voiceActivity: "SPRACHAKTIVITÄT", speakingNow: "Spricht gerade", speaking: "Spricht…", connected: "Verbunden", textChannel: "TEXTKANAL", chat: "Chat", server: "Server", emptyChat: "Noch keine Nachrichten", placeholder: "Nachricht senden…", voice: "Sprache", simulationControls: "Simulation steuern", stopSpeaking: "Sprechen stoppen", simulateSpeaking: "Sprechen simulieren", poke: "Anstupsen", simulateReconnect: "Verbindung simulieren", demoNote: "Diese Seite verbindet sich nie mit einem echten TeamSpeak-Server.", you: "Du", ready: "Bereit", pokedYou: "hat dich angestupst" };
const ru = { languageMenu: "Язык", browserClient: "Голосовое пространство в браузере", demoBadge: "Демо — симуляция", languageSwitch: "中文", back: "На главную", reconnecting: "Соединение прервано, восстановление…", restore: "Восстановить", channels: "Каналы", channel: "Канал", simulated: "Симуляция", heroLead: "Предпросмотр каналов, голоса и чата WebSpeak.", online: "онлайн", voiceActivity: "ГОЛОСОВАЯ АКТИВНОСТЬ", speakingNow: "Сейчас говорят", speaking: "Говорит…", connected: "Подключён", textChannel: "ТЕКСТОВЫЙ КАНАЛ", chat: "чат", server: "Сервер", emptyChat: "Сообщений пока нет", placeholder: "Написать сообщение…", voice: "Голос", simulationControls: "Управление симуляцией", stopSpeaking: "Остановить речь", simulateSpeaking: "Симулировать речь", poke: "Толкнуть", simulateReconnect: "Симулировать переподключение", demoNote: "Эта страница не подключается к реальному серверу TeamSpeak.", you: "Вы", ready: "Готово", pokedYou: "толкнул вас" };
const ja = { languageMenu: "言語", browserClient: "ブラウザ音声ワークスペース", demoBadge: "デモ — シミュレーション", languageSwitch: "中文", back: "ホームに戻る", reconnecting: "接続が中断されました。復旧中…", restore: "復旧", channels: "チャンネル", channel: "チャンネル", simulated: "シミュレーション", heroLead: "WebSpeak のチャンネル、音声、チャットのプレビューです。", online: "人がオンライン", voiceActivity: "音声アクティビティ", speakingNow: "発話中", speaking: "発話中…", connected: "接続済み", textChannel: "テキストチャンネル", chat: "チャット", server: "サーバー", emptyChat: "メッセージはありません", placeholder: "メッセージを送信…", voice: "音声", simulationControls: "シミュレーション操作", stopSpeaking: "発話を停止", simulateSpeaking: "発話をシミュレート", poke: "つつく", simulateReconnect: "再接続をシミュレート", demoNote: "このページは実際の TeamSpeak サーバーには接続しません。", you: "あなた", ready: "準備完了", pokedYou: "あなたをつつきました" };
const zh = { languageMenu: "语言", skinSelector: "皮肤", skinDay: "日间", skinNight: "夜间", browserClient: "浏览器语音工作台", demoBadge: "演示 — 模拟数据", back: "返回主页", reconnecting: "连接中断,正在恢复…", restore: "恢复连接", channels: "频道", channel: "频道", simulated: "演示状态", heroLead: "这里展示 WebSpeak 的频道、语音和聊天交互。", online: "人在线", voiceActivity: "语音活动", speakingNow: "正在语音中", speaking: "正在说话…", connected: "已连接", textChannel: "文字频道", chat: "聊天", server: "服务器", emptyChat: "暂无消息", placeholder: "发送一条消息…", voice: "语音", simulationControls: "模拟控制", stopSpeaking: "停止说话", simulateSpeaking: "模拟发言", poke: "戳一戳", simulateReconnect: "模拟重连", demoNote: "此页面不会连接真实 TeamSpeak 服务器。", you: "你", ready: "已就绪", pokedYou: "戳了你一下" };
const en = { languageMenu: "Language", skinSelector: "Skin", skinDay: "Day", skinNight: "Night", browserClient: "Browser voice workspace", demoBadge: "Demo — simulated data", back: "Back home", reconnecting: "Connection interrupted, recovering…", restore: "Restore", channels: "Channels", channel: "Channel", simulated: "Simulation", heroLead: "A preview of WebSpeak channels, voice, and chat interactions.", online: "online", voiceActivity: "VOICE ACTIVITY", speakingNow: "Speaking now", speaking: "Speaking…", connected: "Connected", textChannel: "TEXT CHANNEL", chat: "chat", server: "Server", emptyChat: "No messages yet", placeholder: "Send a message…", voice: "Voice", simulationControls: "Simulation controls", stopSpeaking: "Stop speaking", simulateSpeaking: "Simulate speaking", poke: "Poke", simulateReconnect: "Simulate reconnect", demoNote: "This page never connects to a real TeamSpeak server.", you: "You", ready: "Ready", pokedYou: "poked you" };
const de = { languageMenu: "Sprache", skinSelector: "Design", skinDay: "Tag", skinNight: "Nacht", browserClient: "Sprachbereich im Browser", demoBadge: "Demo — simulierte Daten", back: "Zur Startseite", reconnecting: "Verbindung unterbrochen, Wiederherstellung…", restore: "Wiederherstellen", channels: "Kanäle", channel: "Kanal", simulated: "Simulation", heroLead: "Eine Vorschau auf Kanäle, Sprache und Chat von WebSpeak.", online: "online", voiceActivity: "SPRACHAKTIVITÄT", speakingNow: "Spricht gerade", speaking: "Spricht…", connected: "Verbunden", textChannel: "TEXTKANAL", chat: "Chat", server: "Server", emptyChat: "Noch keine Nachrichten", placeholder: "Nachricht senden…", voice: "Sprache", simulationControls: "Simulation steuern", stopSpeaking: "Sprechen stoppen", simulateSpeaking: "Sprechen simulieren", poke: "Anstupsen", simulateReconnect: "Verbindung simulieren", demoNote: "Diese Seite verbindet sich nie mit einem echten TeamSpeak-Server.", you: "Du", ready: "Bereit", pokedYou: "hat dich angestupst" };
const ru = { languageMenu: "Язык", skinSelector: "Оформление", skinDay: "День", skinNight: "Ночь", browserClient: "Голосовое пространство в браузере", demoBadge: "Демо — симуляция", back: "На главную", reconnecting: "Соединение прервано, восстановление…", restore: "Восстановить", channels: "Каналы", channel: "Канал", simulated: "Симуляция", heroLead: "Предпросмотр каналов, голоса и чата WebSpeak.", online: "онлайн", voiceActivity: "ГОЛОСОВАЯ АКТИВНОСТЬ", speakingNow: "Сейчас говорят", speaking: "Говорит…", connected: "Подключён", textChannel: "ТЕКСТОВЫЙ КАНАЛ", chat: "чат", server: "Сервер", emptyChat: "Сообщений пока нет", placeholder: "Написать сообщение…", voice: "Голос", simulationControls: "Управление симуляцией", stopSpeaking: "Остановить речь", simulateSpeaking: "Симулировать речь", poke: "Толкнуть", simulateReconnect: "Симулировать переподключение", demoNote: "Эта страница не подключается к реальному серверу TeamSpeak.", you: "Вы", ready: "Готово", pokedYou: "толкнул вас" };
const ja = { languageMenu: "言語", skinSelector: "スキン", skinDay: "昼", skinNight: "夜", browserClient: "ブラウザ音声ワークスペース", demoBadge: "デモ — シミュレーション", back: "ホームに戻る", reconnecting: "接続が中断されました。復旧中…", restore: "復旧", channels: "チャンネル", channel: "チャンネル", simulated: "シミュレーション", heroLead: "WebSpeak のチャンネル、音声、チャットのプレビューです。", online: "人がオンライン", voiceActivity: "音声アクティビティ", speakingNow: "発話中", speaking: "発話中…", connected: "接続済み", textChannel: "テキストチャンネル", chat: "チャット", server: "サーバー", emptyChat: "メッセージはありません", placeholder: "メッセージを送信…", voice: "音声", simulationControls: "シミュレーション操作", stopSpeaking: "発話を停止", simulateSpeaking: "発話をシミュレート", poke: "つつく", simulateReconnect: "再接続をシミュレート", demoNote: "このページは実際の TeamSpeak サーバーには接続しません。", you: "あなた", ready: "準備完了", pokedYou: "あなたをつつきました" };
const tabs = computed(() => [{ id: "channel" as const, label: copy.value.channel }, { id: "server" as const, label: copy.value.server }]);
const selectedChannel = computed(() => channels.find((channel) => channel.id === selectedChannelId.value) ?? channels[0]);
const visibleMessages = computed(() => activeTab.value === "channel" ? messages.value : []);
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); }
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); void saveLocalPreferences({ schemaVersion: 1, language: language.value }); }
async function onSkinChange(skinId: string) {
localStorage.setItem("webspeak:skin-choice", skinId);
const catalogSkin = catalogSkins.value.find((skin) => skin.id === skinId);
activeSkin.value = await activateSkin(skinId, catalogSkin?.version);
activeSkinId.value = getStoredSkinId() ?? skinId;
void saveLocalPreferences({ schemaVersion: 1, skinId: activeSkinId.value });
}
onMounted(async () => {
const catalogPromise = listPublicSkins().catch(() => []);
try {
const [preferences, installed, available] = await Promise.all([loadLocalPreferences(), listInstalledSkins(), catalogPromise]);
installedSkins.value = installed;
catalogSkins.value = available;
// Only a deliberate choice should override the instance default. The active
// skin and local preference also contain automatically applied defaults.
const savedSkinId = localStorage.getItem("webspeak:skin-choice");
const selectedId = savedSkinId && isPublicSkinEnabled(savedSkinId) ? savedSkinId : getPublicDefaultSkinId();
const selectedSkin = available.find((skin) => skin.id === selectedId);
activeSkinId.value = selectedId;
activeSkin.value = await activateSkin(selectedId, selectedSkin?.version);
activeSkinId.value = getStoredSkinId() ?? selectedId;
} catch {
activeSkin.value = null;
activeSkinId.value = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
await activateSkin(activeSkinId.value).catch(() => undefined);
} finally {
skinReady.value = true;
}
void catalogPromise.then(async (available) => {
catalogSkins.value = available;
const selected = available.find((skin) => skin.id === activeSkinId.value);
const installed = installedSkins.value.find((skin) => skin.id === activeSkinId.value);
if (!selected || !installed || installed.version === selected.version) return;
activeSkin.value = await activateSkin(selected.id, selected.version);
if (getStoredSkinId() !== selected.id) return;
activeSkinId.value = getStoredSkinId() ?? selected.id;
installedSkins.value = await listInstalledSkins();
}).catch(() => undefined);
});
function selectChannel(id: string) { selectedChannelId.value = id; activeTab.value = "channel"; }
function toggleSpeaking() { speakingId.value = speakingId.value ? "" : selectedChannel.value.members[0]?.id ?? ""; }
function messageText(message: DemoMessage): string { return language.value === "zh" ? message.zhText ?? message.text : language.value === "ru" ? message.ruText ?? message.enText ?? message.text : language.value === "ja" ? message.jaText ?? message.enText ?? message.text : message.enText ?? message.text; }
@@ -76,9 +151,10 @@ function avatarStyle(name: string) { let hash = 0; for (const char of name) hash
</script>
<style scoped>
:global(*) { box-sizing: border-box; }
:global(body) { margin: 0; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f7f9f8; color: #1c2b28; }
.demo-page { min-height: 100dvh; padding: 0 28px 38px; background: radial-gradient(circle at 72% 12%, rgba(126, 213, 205, .18), transparent 26rem), #f7f9f8; }
.demo-page, .demo-page * { box-sizing: border-box; }
.demo-page.skin-initializing { visibility: hidden; }
.demo-page { min-height: 100dvh; padding: 0 28px 38px; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: radial-gradient(circle at 72% 12%, rgba(126, 213, 205, .18), transparent 26rem), #f7f9f8; color: #1c2b28; }
.demo-page button, .demo-page input { font: inherit; }
.demo-header { display: flex; align-items: center; justify-content: space-between; width: min(1380px, 100%); min-height: 82px; margin: 0 auto; }
.demo-brand, .demo-tools, .demo-brand > div, .demo-tools { display: flex; align-items: center; }.demo-brand { gap: 10px; }.demo-brand > span { display: grid; place-items: center; width: 39px; height: 39px; color: #fff; background: #006a64; border-radius: 12px; }.demo-brand strong, .demo-brand small { display: block; }.demo-brand strong { color: #006a64; font-size: 18px; }.demo-brand small { margin-top: 2px; color: #84938e; font-size: 10px; }.demo-tools { gap: 15px; color: #68807a; font-size: 12px; }.demo-tools button, .demo-tools a { padding: 7px 10px; color: #006a64; background: #e1f2ee; border: 1px solid #cbe6e0; border-radius: 7px; font-size: 11px; font-weight: 700; text-decoration: none; cursor: pointer; }.demo-badge { color: #2d7d50; font-weight: 700; }
.demo-reconnect { display: flex; align-items: center; gap: 9px; width: min(1380px, 100%); margin: 0 auto 14px; padding: 11px 14px; color: #8b6537; background: #fff8e9; border: 1px solid #efd9aa; border-radius: 10px; }.demo-reconnect span { flex: 1; }.demo-reconnect button { padding: 6px 10px; color: #7d5d35; background: #fff; border: 1px solid #ead0a0; border-radius: 6px; cursor: pointer; }
@@ -92,12 +168,11 @@ function avatarStyle(name: string) { let hash = 0; for (const char of name) hash
divide the fixed poke banner offsets back to CSS pixels so it stays at the
intended 82px/25px margin instead of drifting by the zoom factor. */
@media (min-width: 851px) { .demo-poke { top: calc(82px / var(--ui-scale)); right: calc(25px / var(--ui-scale)); } }
:global(:root[data-theme="dark"]) .demo-page { color: #e8f3f0; background: #101918; }
:global(:root[data-theme="dark"]) .demo-channel-panel, :global(:root[data-theme="dark"]) .demo-actions-panel, :global(:root[data-theme="dark"]) .demo-main, :global(:root[data-theme="dark"]) .demo-voice-card { background: #172321; border-color: #30413d; }
:global(:root[data-theme="dark"]) .demo-panel-title strong, :global(:root[data-theme="dark"]) .demo-hero h1, :global(:root[data-theme="dark"]) .demo-section-heading strong, :global(:root[data-theme="dark"]) .demo-chat-head strong, :global(:root[data-theme="dark"]) .demo-voice-card strong, :global(:root[data-theme="dark"]) .demo-user strong { color: #e8f3f0; }
:global(:root[data-theme="dark"]) .demo-hero { background: linear-gradient(112deg, #173e3a, #172321); }
:global(:root[data-theme="dark"]) .demo-message p, :global(:root[data-theme="dark"]) .demo-composer, :global(:root[data-theme="dark"]) .demo-actions-panel > button { background: #202f2c; color: #d7e7e3; }
:global(:root[data-theme="dark"]) .demo-chat-head, :global(:root[data-theme="dark"]) .demo-user { border-color: #30413d; }
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .demo-channel-panel, :global(:root[data-theme="system"]) .demo-actions-panel, :global(:root[data-theme="system"]) .demo-main, :global(:root[data-theme="system"]) .demo-voice-card { background: #172321; border-color: #30413d; } }
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible), :global(select:focus-visible) { outline: 3px solid #69d2c7; outline-offset: 2px; }
.demo-page[data-ws-skin="builtin.dark"] { color: #e8f3f0; background: #101918; }
.demo-page[data-ws-skin="builtin.dark"] .demo-channel-panel, .demo-page[data-ws-skin="builtin.dark"] .demo-actions-panel, .demo-page[data-ws-skin="builtin.dark"] .demo-main, .demo-page[data-ws-skin="builtin.dark"] .demo-voice-card { background: #172321; border-color: #30413d; }
.demo-page[data-ws-skin="builtin.dark"] .demo-panel-title strong, .demo-page[data-ws-skin="builtin.dark"] .demo-hero h1, .demo-page[data-ws-skin="builtin.dark"] .demo-section-heading strong, .demo-page[data-ws-skin="builtin.dark"] .demo-chat-head strong, .demo-page[data-ws-skin="builtin.dark"] .demo-voice-card strong, .demo-page[data-ws-skin="builtin.dark"] .demo-user strong { color: #e8f3f0; }
.demo-page[data-ws-skin="builtin.dark"] .demo-hero { background: linear-gradient(112deg, #173e3a, #172321); }
.demo-page[data-ws-skin="builtin.dark"] .demo-message p, .demo-page[data-ws-skin="builtin.dark"] .demo-composer, .demo-page[data-ws-skin="builtin.dark"] .demo-actions-panel > button { background: #202f2c; color: #d7e7e3; }
.demo-page[data-ws-skin="builtin.dark"] .demo-chat-head, .demo-page[data-ws-skin="builtin.dark"] .demo-user { border-color: #30413d; }
.demo-page :where(button, a, input, select):focus-visible { outline: 3px solid #69d2c7; outline-offset: 2px; }
</style>
+548 -3573
View File
File diff suppressed because it is too large. Load diff