Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

feat: launch Piik with a unified interface and public website

AAAf92162b3bb2e
diff --git a/.env.example b/.env.example
index 8867ceb1..3e7a5bcd 100644
--- a/.env.example
+++ b/.env.example
@@ -6,8 +6,9 @@ PORT=8787
PUBLIC_BASE_URL=http://localhost:8787
# Include both the host browser origin and PUBLIC_BASE_URL when they differ.
ALLOWED_ORIGINS=http://localhost:8787
-# Production-required site access secret. Local development/tests may leave it
-# empty. A non-empty value must contain 8-128 visible ASCII bytes (0x21-0x7e).
+# Optional site access password in every environment. Unset or empty allows
+# entry without a site password; room ownership and invitations still apply.
+# A non-empty value must contain 8-128 visible ASCII bytes (0x21-0x7e).
SITE_ACCESS_PASSWORD=
# Rooms persist in rooms.sqlite under the working directory by default (also
# when blank). Set :memory: explicitly for process-memory rooms. Deployments
@@ -23,7 +24,8 @@ ENDPOINT_MEDIA_COPY_CAPACITY=2
# PIIK_DEBUG=route
# Optional in-process automatic SFU fallback. Set SFU_UDP_PORT=7882 to enable;
-# unset or empty keeps it disabled. Local Client modes never create this listener.
+# unset or empty disables it and fixes Privacy mode on for every room.
+# STUN/signaling/P2P remain available. Local App modes never create this listener.
# Ingress uses the 9000-room code capacity; egress uses that capacity times the
# configured per-room Viewer admission.
SFU_UDP_PORT=
@@ -38,11 +40,12 @@ SFU_PUBLIC_IP=
STUN_URLS=
# Hosted STUN is in-process. With STUN_URLS configured, bind this IPv4 address
# on UDP 3478 (also 3479/3480 below). It is independent of HTTP LISTEN_HOST.
-# Local Client modes never create these listeners, even with public discovery.
+# Local App modes never create these listeners, even with public discovery.
STUN_LISTEN_HOST=0.0.0.0
-# Optional bounded NAT traversal support. When enabled, Hosts see a per-share
-# switch that defaults on after all three local STUN listeners bind. Browser
+# Optional bounded NAT traversal support. The per-share switch stays visible;
+# it is locked off when disabled, and defaults on when enabled after all three
+# local STUN listeners bind. Browser
# P2P derives UDP 3479/3480 from the first STUN_URLS endpoint on UDP 3478.
# Cloud security-group and host firewall rules must also allow these UDP ports.
NAT_PREDICTION_ENABLED=false
@@ -53,9 +56,11 @@ NAT_PREDICTION_ENABLED=false
# PIIK_ENV=development
# PORT=8788
-# Minimal production example (use independent untracked secrets):
+# Production example (keep any chosen password in an untracked environment):
# PIIK_ENV=production
-# SITE_ACCESS_PASSWORD=replace-with-an-independent-access-key
+# PUBLIC_BASE_URL=https://share.example.com
+# ALLOWED_ORIGINS=https://share.example.com
+# SITE_ACCESS_PASSWORD=
# STUN_URLS=stun:stun.example.com:3478
# NAT_PREDICTION_ENABLED=true
# Automatic SFU fallback (does not replace STUN above):
diff --git a/.gitattributes b/.gitattributes
index 77c86f4f..446e711e 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -13,6 +13,7 @@
*.ico binary
*.jpg binary
*.jpeg binary
+*.mp3 binary
*.png binary
*.webp binary
*.woff binary
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 00000000..127eeb6b
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,23 @@
+---
+name: Bug report / 问题反馈
+about: Report a reproducible problem / 反馈可复现的问题
+---
+
+## Environment / 环境
+
+- Piik version and build SHA / Piik 版本与构建 SHA:
+- Browser, App, or Server / 使用端:
+- OS and browser versions / 系统与浏览器版本:
+
+## Steps to reproduce / 复现步骤
+
+1.
+
+## Expected and actual behavior / 预期与实际结果
+
+- Expected / 预期:
+- Actual / 实际:
+
+## Optional evidence / 可选证据
+
+<!-- Screenshots or a local Debug export may help. Review artifacts before attaching; remove credentials and private content. 可附截图或本地 Debug 导出;分享前移除凭据与隐私内容。 -->
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 00000000..f0ada69b
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,12 @@
+---
+name: Feature request / 功能建议
+about: Describe a use case and desired outcome / 说明使用场景与期望结果
+---
+
+## Problem or use case / 问题或场景
+
+<!-- Who needs this, and what cannot they do today? 谁在什么场景遇到了什么限制? -->
+
+## Desired outcome / 期望结果
+
+<!-- Describe the behavior that would solve the problem; alternatives are optional. 说明怎样的行为能解决问题,可补充替代方案。 -->
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 362d1632..2b81a7dc 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,20 +1,17 @@
-## Summary
+<!-- Title: type(scope): outcome. One accepted phase per squash PR. 标题遵循提交命名,一次 PR 完成一个阶段。 -->
-Describe the problem and the outcome of this change.
+## Problem and outcome / 问题与结果
-## Verification
+<!-- Describe the trigger and resulting behavior. Link a related issue or decision when useful. 说明问题、结果及相关依据。 -->
-List automated tests, manual checks, environments, and meaningful measurements.
+## Release notes
-## Research And Decisions
+<!-- Public copy, automatically published in GitHub Releases. Keep this exact heading; use ### for subsections. Describe user benefits, fixes and any required upgrade action in concise Chinese and English. Omit internal logs, audit prompts and unverified claims. 更新说明将直接公开:写清用户可感知的变化与升级事项,提供简洁的中英文文案。首次发布介绍当前产品,不罗列内部开发历史。 -->
-Link the relevant product owner, research note, issue, and ADR, or explain why none is needed.
+## Verification / 验证
-## Checklist
+<!-- List exact local checks and results, relevant environments, and material untested cases. 列出检查命令、结果与未验证项。 -->
-- [ ] The branch contains one coherent change and no unrelated churn.
-- [ ] Required local tests and repository hygiene checks pass, and their exact evidence is listed above.
-- [ ] Security, privacy, compatibility, and licensing effects were considered.
-- [ ] Product owners, operational docs, ADRs, project memory, and status were updated only where their facts changed.
-- [ ] Stale or conflicting memory and documentation were removed rather than preserved as a diary.
-- [ ] No credentials, personal data, machine-specific paths, or required untracked artifacts are included.
+## Impact / 影响
+
+<!-- Note relevant compatibility, release interruption/recovery, and updated owner docs. Explain any breaking change marked by ! in the title; write “None” if not applicable. 说明兼容、发布及文档影响,解释标题中 ! 标记的破坏性变更;不适用填“无”。 -->
diff --git a/.github/workflows/repository-hygiene.yml b/.github/workflows/repository-hygiene.yml
index 9b1cd4f7..86cfeb26 100644
--- a/.github/workflows/repository-hygiene.yml
+++ b/.github/workflows/repository-hygiene.yml
@@ -11,13 +11,25 @@ on:
required: false
default: false
type: boolean
+ candidate_version:
+ description: Optional candidate version (vMAJOR.MINOR.PATCH); never publishes
+ required: false
+ type: string
permissions:
contents: read
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: false
+ queue: max
+
jobs:
validate:
runs-on: ubuntu-latest
+ outputs:
+ version: ${{ steps.release.outputs.version }}
+ publish: ${{ steps.release.outputs.publish }}
steps:
- name: Check out repository
uses: actions/checkout@v6
@@ -34,9 +46,26 @@ jobs:
PIIK_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
- name: Install dependencies
run: npm ci
+ - name: Determine release identity
+ id: release
+ env:
+ PIIK_BUILD_VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.candidate_version || '' }}
+ run: >-
+ node scripts/release-version.mjs
+ ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && vars.PIIK_RELEASES_ENABLED == 'true' && 'plan' || 'build' }}
+ --github-output
+ - name: Preview release notes
+ if: steps.release.outputs.publish == 'true' || inputs.candidate_version != ''
+ run: node scripts/release-notes.mjs "$PIIK_RELEASE_VERSION" "$GITHUB_SHA" --github-summary
+ env:
+ PIIK_RELEASE_VERSION: ${{ steps.release.outputs.version }}
# The Go build embeds internal/server/webassets/dist, so Vite runs first.
- name: Build the Browser client
run: npm run build:client
+ env:
+ PIIK_BUILD_VERSION: ${{ steps.release.outputs.version }}
+ VITE_PIIK_VERSION: ${{ steps.release.outputs.version }}
+ VITE_PIIK_REVISION: ${{ github.sha }}
- name: Cache Go toolchain
uses: actions/cache@v4
with:
@@ -49,15 +78,22 @@ jobs:
cache-dependency-path: go.sum
- name: Check Go core
run: npm run check:client-core
- - name: Type-check, test, and build
- run: npm run check
+ - name: Type-check and test
+ run: npm run typecheck && npm test
+ env:
+ PIIK_BUILD_VERSION: ${{ steps.release.outputs.version }}
+ VITE_PIIK_VERSION: ${{ steps.release.outputs.version }}
+ VITE_PIIK_REVISION: ${{ github.sha }}
release-application:
needs: validate
if: >-
- github.event_name == 'workflow_dispatch' && inputs.client_checks == true
+ needs.validate.outputs.publish == 'true' ||
+ (github.event_name == 'workflow_dispatch' && inputs.client_checks == true)
runs-on: ubuntu-latest
timeout-minutes: 15
+ env:
+ PIIK_BUILD_VERSION: ${{ needs.validate.outputs.version }}
steps:
- name: Check out repository
uses: actions/checkout@v6
@@ -93,7 +129,8 @@ jobs:
- validate
- release-application
if: >-
- github.event_name == 'workflow_dispatch' && inputs.client_checks == true
+ needs.validate.outputs.publish == 'true' ||
+ (github.event_name == 'workflow_dispatch' && inputs.client_checks == true)
strategy:
fail-fast: false
matrix:
@@ -106,6 +143,8 @@ jobs:
runner: macos-15
runs-on: ${{ matrix.runner }}
timeout-minutes: 20
+ env:
+ PIIK_BUILD_VERSION: ${{ needs.validate.outputs.version }}
steps:
- name: Check out repository
uses: actions/checkout@v6
@@ -158,3 +197,52 @@ jobs:
if-no-files-found: error
compression-level: 0
retention-days: 14
+
+ publish:
+ needs:
+ - validate
+ - release-application
+ - release-clients
+ if: needs.validate.outputs.publish == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: write
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ - name: Set up Node.js
+ uses: actions/setup-node@v6
+ with:
+ node-version-file: .node-version
+ cache: npm
+ - name: Install dependencies
+ run: npm ci --ignore-scripts
+ - name: Download application release
+ uses: actions/download-artifact@v8
+ with:
+ name: piik-server-${{ github.sha }}
+ path: ${{ runner.temp }}/publish-release
+ - name: Download App release candidates
+ uses: actions/download-artifact@v8
+ with:
+ pattern: piik-app-*-${{ github.sha }}
+ path: ${{ runner.temp }}/publish-release
+ merge-multiple: true
+ - name: Publish verified release
+ run: >-
+ node scripts/publish-release.mjs
+ "$RUNNER_TEMP/publish-release" "$PIIK_RELEASE_VERSION" "$GITHUB_SHA"
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PIIK_RELEASE_VERSION: ${{ needs.validate.outputs.version }}
+ - name: Mirror verified release to Gitee
+ run: >-
+ node scripts/mirror-release.mjs
+ "$RUNNER_TEMP/publish-release" "$PIIK_RELEASE_VERSION" "$GITHUB_SHA"
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
+ PIIK_RELEASE_VERSION: ${{ needs.validate.outputs.version }}
diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml
new file mode 100644
index 00000000..73734167
--- /dev/null
+++ b/.github/workflows/website.yml
@@ -0,0 +1,39 @@
+name: Website
+
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: github-pages
+ cancel-in-progress: false
+
+jobs:
+ deploy:
+ if: github.ref == 'refs/heads/main'
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ pages: write
+ id-token: write
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-node@v6
+ with:
+ node-version-file: .node-version
+ cache: npm
+ - run: npm ci
+ - run: npm run build:website
+ - uses: actions/configure-pages@v5
+ - uses: actions/upload-pages-artifact@v4
+ with:
+ path: build/site
+ retention-days: 1
+ - uses: actions/deploy-pages@v4
+ id: deployment
diff --git a/AGENTS.md b/AGENTS.md
index 62ff490d..08a8ae02 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -23,7 +23,7 @@
## Product Contract
-- Piik is private game screen sharing for one Host and up to 20 authenticated
+- Piik is private screen sharing for one Host and up to 20 authenticated
Viewers, with Web Host/Viewer/relay as the current product surface.
- Current product truth is split by owner:
[rooms/access](./docs/product/rooms-access.md),
@@ -45,10 +45,9 @@
[status](./docs/status.md), [TODO](./docs/todo.md), and only the relevant
product module, ADR, research, or operations document. Then inspect branch,
HEAD, status, staged diff, and worktrees.
-- Product modules own current behavior; ADRs own non-obvious decisions and
- consequences; research owns evidence and license boundaries; deployment owns
- operational reference. Status is the current execution/deployment index, TODO
- is the only work ledger, and Git/PRs own completed history.
+- Use the [documentation owner map](./docs/maintenance.md#owners): product
+ behavior, engineering, visual language, versions, evidence and operations each
+ have one owner. TODO is the only work ledger; Git/PRs own completed history.
- Give every durable fact one owner. Update memory or status only when its compact
snapshot materially changes. Ordinary UI detail, protocol field listings,
self-evident code, test inventories, routine validation, and agent process do
@@ -71,40 +70,28 @@
- Canonical root must be clean current `main` at audit/integration boundaries.
Create branches/worktrees from that exact commit; old branches and worktrees
are never truth sources.
-- `main` is a low-frequency integration branch, never a workbench. Keep work on
- branches/worktrees and merge only one complete, user-accepted phase per PR,
- after its related implementation, tests, documentation, and acceptance are
- complete. Use one squash commit and leave `main` unchanged between phases.
- Do not merge intermediate checkpoints, release records, metadata-only edits,
- or follow-up cleanup; fold them into the next phase. A P0/P1 emergency may
- bypass batching only when the user explicitly authorizes it, still through
- one coherent PR.
+- `main` remains low-frequency: one complete, user-accepted phase per squash PR,
+ with no intermediate release-record or cleanup commits. Keep implementation
+ on worktrees; [CONTRIBUTING.md](./CONTRIBUTING.md#full-integration-and-release-workflow)
+ owns the full workflow and explicit emergency exception.
- Preserve user work. Branch, truth-checkpoint, PR, release, recovery, and
cleanup rules are owned by [CONTRIBUTING.md](./CONTRIBUTING.md); do not mirror
that workflow here.
## Engineering Defaults
-- Prefer the simplest cohesive design that is easy to use and maintain. Reuse
- mature components, keep ownership explicit, and remove superseded paths in
- the same change instead of retaining speculative flexibility or technical debt.
-- Apply good coding practice to every change: split modules around clear
- responsibilities and state/lifecycle ownership, with cohesive internals and
- narrow interfaces. Reuse proven shared behavior and abstract stable common
- responsibilities; avoid both duplicate implementations and needless wrappers.
- Review coupling and readability, not only file size or line count.
-- Judge a change by evidenced user value against its full implementation,
- maintenance, compatibility, and failure cost. A large measured gain may
- justify broad or breaking work; a small or speculative gain does not justify
- material complexity or risk.
-- After completing a material module, run one ablation pass and remove every new
- component, state, dependency, or branch that is not needed for the verified
- result or an accepted contract. Its primary goal is lower total system
- complexity, not perfect performance; marginal gains do not justify permanent
- mechanisms or a materially larger maintenance surface.
+- UI changes must follow the shared [visual language](./docs/design/visual-language.md):
+ cast, semantic colours, result panels and motion have one owner. Extend the
+ existing preview when adding a new meaning; do not invent scene-local rules.
+- Follow [engineering and interface boundaries](./docs/reference/engineering.md):
+ simple cohesive modules, clear state/resource owners, mature reuse and narrow
+ contracts. After a material module, remove additions that the accepted result
+ does not need; total complexity matters more than marginal performance gains.
+- [Versioning](./docs/reference/versioning.md) separates build identity, wire,
+ storage and live generations, and owns the public compatibility design.
+ Its pending public-release policy does not replace today's private contract.
- Use primary sources for non-trivial design and bugs. Add focused tests in
proportion to risk; batch full browser/network/endurance checks at acceptance.
-- Keep scripts deterministic, fast, cross-platform, and CI-runnable. Support
- Windows, macOS, and Linux; use LF and ASCII filenames for new files.
+- Keep scripts deterministic, fast, cross-platform and CI-runnable.
- Before finishing material work, inspect status, report untracked artifacts,
and stage requested files unless told otherwise.
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 100644
index 4a7a4a65..00000000
--- a/CLAUDE.md
+++ /dev/null
@@ -1,5 +0,0 @@
-
-# Claude Code
-
-This file intentionally imports the repository-wide agent instructions instead of duplicating them. Keep durable project guidance in `AGENTS.md` and the referenced bounded project documents.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 883a3e72..2a4d9af2 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -23,7 +23,7 @@ leave `main` alone until the next material phase. Only a user-authorized P0/P1
emergency may use a separate PR, and that PR must still contain one coherent
fix.
-1. Create one short-lived branch/worktree from exact canonical `main`; use `feat/`, `fix/`, `docs/`, `refactor/`, `test/`, `chore/`, or `spike/` followed by a short description.
+1. Create one short-lived branch/worktree from exact canonical `main`, following the [branch naming convention](#commit-pr-and-branch-names).
2. Update only the single durable owner for changed semantics and any materially changed current snapshot. If semantics remain disputed, record a hold and stop dependent work.
3. Implement and run repository hygiene, `npm run check`, the relevant browser/network gates, and review in proportion to the whole acceptance boundary.
4. Keep accepted truth checkpoints and dependent candidates on branches until the phase is complete. Rebase or rebuild a retained candidate from exact `main` only when starting a new phase, preserving main's owning truth on conflicts and transplanting only approved scoped code, tests, and new facts.
@@ -37,20 +37,24 @@ the repository. Exact deployment identity belongs to the immutable release
descriptor, runtime `REVISION`, and deployment record. Preserve separate commits
only when they carry independently useful history.
-Direct commits to `main` are reserved for an explicit user-approved exception. Never force-push shared branches or rewrite shared history without explicit approval.
+Update `main` through PRs only; branch checkpoints and generated release metadata
+do not bypass that boundary. Never force-push shared branches or rewrite shared
+history without explicit approval.
For deployment work, a routine application-only release verifies a new immutable artifact, switches to it atomically, and guarantees the pre-cutover application release only through bounded health and postflight checks; it has no retention contract afterward and is not a maintained backup. Define recovery only for the infrastructure, configuration, secrets, persistent state, or irreversible surfaces the task actually touches, before changing them.
-Do not change `SIGNALING_PROTOCOL` for compatible internal, UI, routing, or
-release work. A wire change makes existing pages stale and forces an active
-Browser Host to reload, which ends its capture. Bump it only for an actually
-incompatible message contract whose atomic cutover and capture interruption are
-explicitly accepted.
+Use the [version/compatibility policy](./docs/reference/versioning.md) to classify
+release changes. In today's private contract an incompatible signaling cutover
+forces old pages to reload and ends Browser capture; include that interruption
+in the accepted cutover. Compatible UI/internal work does not require a wire bump.
Clean up worktrees and branches only after semantic review and integration are complete and the normal merged-head, open-reference, clean-tree, and non-following link checks pass. Never merge an old branch wholesale after a newer truth checkpoint.
## Research Standard
+The [engineering reference](./docs/reference/engineering.md) owns module and
+interface discipline, including the post-change ablation pass.
+
Follow the [naming convention](./docs/reference/naming.md) for product copy,
commands, packages and code ownership. Keep display names separate from stable
protocol identifiers; use normal language-specific identifier conventions.
@@ -65,6 +69,10 @@ protocol identifiers; use normal language-specific identifier conventions.
## Verification Entrypoints
+Every retained test must be collected by a documented verification entry point.
+Confirm runner inclusion when adding or moving a test; a file's presence alone
+does not establish coverage.
+
- `npm run check` owns deterministic Web type-check, unit, and build acceptance.
- `npm run check:client` owns Go formatting, unit tests, vet, three-platform
builds, and the Windows capture compile/probe when run on Windows. The server
@@ -80,16 +88,44 @@ protocol identifiers; use normal language-specific identifier conventions.
identities; do not run network tests with a changing temporary executable
path. Keep browser profiles isolated and consider the active firewall when
diagnosing connection failures rather than changing global firewall rules.
-- Server and three-platform Client candidates run only from an explicit manual
- workflow dispatch with `client_checks=true`. Ordinary `main` pushes validate
- source without running the expensive packaging matrix.
- Publishing a tag or GitHub Release remains an explicit release decision rather
- than a side effect of every merge.
+- CI, versioning and release automation belong to complete, accepted squash
+ merges into `main`; ordinary branch pushes and PRs stay quiet. The
+ [versioning policy](./docs/reference/versioning.md) owns version selection,
+ publication and activation state. Package the merged SHA without writing
+ version-record commits back to `main`.
+
+## Commit, PR And Branch Names
+
+Use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/):
+`type(scope): outcome`. Scope is optional. Use `feat` for new behavior, `fix`
+for repairs, or `docs`, `refactor`, `test`, `build`, `ci`, and `chore` for their
+named purpose. Keep the outcome short and concrete; English is the default,
+and a Chinese explanation may follow in the body.
+
+The PR title names the complete phase and becomes its single squash commit on
+`main`, for example `fix(app): restore sharing after a source change`. Working
+commits should follow the same form where useful; no history rewrite is needed
+just to rename commits that will be squashed. Add `!` before the colon for a
+breaking change, such as `feat(protocol)!: replace the join handshake`, and
+explain its effect in the body. The final squash title and body supply release
+intent; the [versioning policy](./docs/reference/versioning.md) owns version
+selection and publication behavior.
+
+Name branches `<type>/<short-kebab-case-description>`, using the same types;
+reserve `spike/` for experiments. No issue number is required. 中文说明:PR 标题
+与最终 squash 提交使用上述格式;分支用英文短名,破坏性变更标记 `!` 并说明影响。
## Pull Request Scope
A pull request should explain the problem, the chosen design, verification performed, user-visible or operational effects, and remaining risks.
+Before an integration PR is accepted, fill its exact `## Release notes` section
+with concise public copy in Chinese and English: user-visible changes, fixes and
+required upgrade actions. Use `###` for subsections. Review this text as product
+copy; it is published automatically from the squash commit, without PR discussion
+or verification logs. The [release-note policy](./docs/reference/versioning.md#release-notes)
+owns aggregation and preview. Do not add a changelog file or release-note archive.
+
Durable semantic or current-snapshot changes must update their single owner in the same integration boundary. Ordinary implementation and bug fixes may be complete with code plus focused evidence.
## Local Hooks
diff --git a/LICENSE.zh-CN.md b/LICENSE.zh-CN.md
deleted file mode 100644
index 30716557..00000000
--- a/LICENSE.zh-CN.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# MIT 许可证中文参考译文
-
-The authoritative license is the English [LICENSE](./LICENSE).
-This translation is for convenience and adds no terms or restrictions.
-
-本文件为方便阅读提供中文参考译文,不替代英文 [LICENSE](./LICENSE),
-也不增加条件或限制。Piik 自有代码的 MIT 许可不替代
-[第三方组件的许可与声明](./licenses/README.md)。
-
-版权所有 (c) 2026 TNTcraft 和 Piik 贡献者
-
-特此免费授予任何获得本软件及相关文档文件(以下简称“软件”)副本的人,
-不受限制地处置本软件的权利,包括但不限于使用、复制、修改、合并、出版、
-分发、再许可和/或销售本软件副本,并允许获得软件的人这样做,
-但须遵守以下条件:
-
-上述版权声明和本许可声明应包含在本软件的所有副本或实质部分中。
-
-本软件按“原样”提供,不作任何明示或默示保证,包括但不限于适销性、
-特定用途适用性和不侵权的保证。在任何情况下,无论依据合同、侵权或其他
-法律理论,作者或版权持有人均不对因软件、软件的使用或其他处置而产生、
-源自或与之有关的任何索赔、损害或其他责任负责。
diff --git a/README.md b/README.md
index ba6a51f2..b4b958e8 100644
--- a/README.md
+++ b/README.md
@@ -1,83 +1,109 @@
-<img src="./public/favicon.svg" width="64" height="64" alt="Piik TV logo">
-
-# Piik
-
-English | [简体中文](./README.zh-CN.md)
-
-Share your screen. Bring your friends.
-
-Piik is private screen sharing for one Host and up to 20 invited friends.
-Friends watch in their browsers, with no installation.
-
-```mermaid
-flowchart LR
- Browser[Browser] --> Host[Host a room]
- App[Piik App] --> Host
- Host -->|Invite link| Friends[Friends watch in browsers]
-```
-
-## Join a friend
-
-1. Open the invitation your friend sent.
-2. Press Play if your browser asks. Use the video's sound and fullscreen controls.
-
-Got a room code instead? Open the same Piik site and choose **Join a room**.
-Site access and the room's password settings still apply.
+<p align="center"><img src="./public/favicon.svg" width="64" height="64" alt="Piik mascot"></p>
+<h1 align="center">Piik</h1>
+<p align="center"><strong>Share the good stuff.</strong><br>Private screen sharing for you and up to 20 friends.</p>
+<p align="center">
+ <a href="https://piik.tv">Website</a> ·
+ <a href="https://github.com/TNTcraftHIM/Piik/releases">Download</a> ·
+ <a href="https://gitee.com/TNTcraftHIM/Piik/releases">Gitee mirror</a> ·
+ <a href="https://demo.piik.tv">Try the demo</a> ·
+ <a href="./docs/README.md">Documentation</a>
+</p>
+<p align="center">
+ <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-36564f?style=flat-square" alt="License: MIT"></a>
+ <img src="https://img.shields.io/badge/viewers-up_to_20-36564f?style=flat-square" alt="Up to 20 viewers">
+ <img src="https://img.shields.io/badge/media-P2P_first-36564f?style=flat-square" alt="P2P-first media">
+</p>
+<p align="center">English · <a href="./README.zh-CN.md">简体中文</a></p>
+
+Piik is a free, open-source screen sharing tool for games, movie nights,
+drawings and photos. Choose what to share and send an invitation. Your friends
+watch in their browsers.
+
+<details open>
+<summary>A little room · Show / hide animation</summary>
+
+<p align="center"><img src="./site/assets/living-room.svg" width="720" height="472" alt="A host with a small gold crown shares an RPG, a drawing, photos and an animated film while friends watch from the sofa."></p>
+
+</details>
+
+[Features](#features) · [Get started](#get-started) · [Self-hosting](#self-hosting) · [Contributing](#contributing)
+
+## Features
+
+- **Watch without installing.** Friends join by invitation in a desktop or mobile browser.
+- **Share from Piik App or an existing Piik site.** Capture a screen, window or browser tab; available sources and audio depend on the platform.
+- **Direct connections first.** Media travels between participants where possible (P2P). A self-hosted server can provide automatic media forwarding (SFU) as a fallback.
+- **Rooms you control.** Invitations, room codes and optional room passwords, for one host and up to 20 viewers.
+- **Flexible viewing.** Light and dark themes, playback controls, picture-in-picture and a connection topology view.
+- **One program to host a site.** Web UI, room management and optional media forwarding are packaged together.
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="./docs/assets/room-en-dark.png">
+ <img src="./docs/assets/room-en-light.png" width="860" alt="Piik room: a shared game, playback controls and friends on a sofa. The host wears a small gold crown.">
+ </picture><br>
+ <sub>Interface preview · Sample room with a generated game scene</sub>
+</p>
+
+## Get started
+
+**To watch:** open the invitation your friend sends you. Select **Play** if the
+picture does not start automatically.
+
+**To share:**
+
+| Start here | What you need to do |
+| --- | --- |
+| [Try the online demo](https://demo.piik.tv) | Open it in a desktop browser and start sharing. |
+| [Download Piik App](https://piik.tv/#download) | Extract and open the App, choose **Public invite**, then **Open Piik** to create a temporary room. |
+| Use an existing Piik site | Open the address your friend or administrator provides. [Hosting your own](./docs/operations/self-hosting.md) is an advanced option. |
-## Share from your browser
+<p align="center"><img src="./docs/assets/quickstart.svg" width="640" alt="Choose a screen, send an invitation, watch together."></p>
-1. Open the Piik site your group uses. Enter its site password if asked.
-2. Choose **Start sharing**, pick a screen, window or tab, and check the sound switch.
-3. Send the room's invitation link to your friends. Keep the sharing tab open.
+1. Select **Start sharing**, then choose the picture and audio to share.
+2. Select **Copy invite link** and send it to your friends. Keep the sharing tab open.
-Capture needs HTTPS or `localhost`; available sources and sound depend on the
-browser and platform. English, Chinese and an illustrated visual mode share the
-same controls, with light and dark themes.
+Piik uses icon controls by default; select **EN** in the header to show labels.
+The App offers a local room, a temporary public link, or a connection to your own
+site. Keep the App running while sharing through it.
-## Start your own room with Piik App
+Download an archive beginning with **`piik-app`**. The filename also identifies the platform:
-With the Piik App package for your platform:
+| Filename contains | Platform |
+| --- | --- |
+| `windows-amd64` | Windows x64 |
+| `darwin-arm64` | Apple silicon; native capture requires macOS 13+ |
+| `linux-amd64` | Linux x64 |
-1. Extract the whole package, keeping `runtime` beside the executable.
-2. Open `piik-app.exe` on Windows, `Piik App.app` on macOS, or
- `./piik-app` on Linux.
-3. Choose a mode, pick what to share, and send the invitation. Keep the app running.
+[**Full setup guide →**](./docs/guide/getting-started.md) · [**Open the demo →**](https://demo.piik.tv)
-| Mode | Use it for |
-| --- | --- |
-| **Local room** | Friends on the same local network. An optional site password controls access. |
-| **Public invite** | A temporary Internet invitation. The link lasts for this App run; media remains P2P. |
-| **Connect to Site** | An existing Piik site, with App capture and media capabilities available in the same browser UI. |
+Browser capture requires HTTPS or `localhost`. Windows App and desktop browser
+sharing are the primary tested paths. The macOS and Linux apps have not yet been
+tested on physical devices; [test results and feedback are welcome](https://github.com/TNTcraftHIM/Piik/issues).
+P2P-only modes, including the App's temporary public
+link and the demo, may not connect on restrictive networks.
-Piik App opens your system browser. Its package includes the Go application and
-capture/link helpers; running it needs no Node.js, npm or Go installation.
-Linux native capture uses the system Portal, PipeWire and GStreamer stack.
-See the [App guide](./cmd/piik-app/README.md) for platform details.
+## Self-hosting
-Temporary public links use Cloudflare Quick Tunnel, which has no uptime guarantee.
-Media needs a working UDP path; restrictive networks or browser/OS suspension
-can interrupt sharing. Windows App and Browser are the current acceptance
-focus; macOS/Linux physical capture checks remain separate. See
-[current status](./docs/status.md) for candidate and release readiness.
+Piik Server is a standalone binary with the web interface built in.
+Download the Linux x64 Server package, extract it, and run:
-## Host a site or contribute
+```sh
+./piik-server
+```
-The Server package is one Go executable with the Web UI embedded. It owns room
-signaling, STUN and optional embedded SFU fallback. Follow the
-[self-hosting guide](./docs/operations/self-hosting.md) to set up your own site.
+Open `http://localhost:8787` to try it locally. For a public site, configure your
+domain, HTTPS reverse proxy and STUN address. Room data is stored in SQLite.
-For source builds, tests and architecture, start with the
-[documentation map](./docs/README.md). [Contributing](./CONTRIBUTING.md) covers the workflow.
+[**Deploy your own site →**](./docs/operations/self-hosting.md) · [Configuration](./docs/reference/configuration.md) · [Run from source](./docs/README.md#run-from-source)
-## Something went wrong?
+## Contributing
-Include your version, OS/browser, expected result and steps to reproduce.
-For a local report, start Piik App with `--debug` and press `D`, or add `?debug=1`
-before any `#` in the Browser page URL and use its header download button. Review reports before
-sharing; see [diagnostics and export](./docs/reference/configuration.md#diagnostics).
-Connection trouble? Try the [Chromium WebRTC FAQ](./cmd/piik-app/README.md#chromium-webrtc-connections).
+Bug reports, documentation improvements and pull requests are welcome.
+Start with [CONTRIBUTING.md](./CONTRIBUTING.md), or see the
+[repository layout](./docs/reference/engineering.md#repository-layout) to find your way around.
## License
-Piik-owned code is [MIT licensed](./LICENSE). Third-party components retain
-their own licenses and notices: [licensing guide](./licenses/README.md).
+Piik-owned code is [MIT licensed](./LICENSE). Dependencies retain their own
+[licenses and notices](./licenses/README.md).
diff --git a/README.zh-CN.md b/README.zh-CN.md
index d47ee0d3..971d2754 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -1,79 +1,104 @@
-<img src="./public/favicon.svg" width="64" height="64" alt="Piik 小电视标志">
-
-# Piik
-
-[English](./README.md) | 简体中文
-
-分享你的屏幕,叫上朋友一起看。
-
-Piik 是一个私密屏幕分享工具:一位房主,最多 20 位受邀好友。
-朋友用浏览器就能观看,无须安装。
-
-```mermaid
-flowchart LR
- Browser[浏览器] --> Host[开房分享]
- App[Piik App] --> Host
- Host -->|邀请链接| Friends[好友用浏览器观看]
-```
-
-## 去朋友的房间
-
-1. 打开朋友发来的邀请链接。
-2. 如果浏览器提示,点击播放。声音和全屏由视频控件控制。
-
-只有房间号?打开同一个 Piik 站点,选择 **加入房间**。
-站点访问权限和房间密码设置仍然适用。
+<p align="center"><img src="./public/favicon.svg" width="64" height="64" alt="Piik 吉祥物"></p>
+<h1 align="center">Piik</h1>
+<p align="center"><strong>来,看点<br>好康的。</strong><br>私密屏幕共享,邀请最多 20 位朋友观看。</p>
+<p align="center">
+ <a href="https://piik.tv/?lang=zh-CN">官网</a> ·
+ <a href="https://github.com/TNTcraftHIM/Piik/releases">下载</a> ·
+ <a href="https://gitee.com/TNTcraftHIM/Piik/releases">Gitee 镜像</a> ·
+ <a href="https://demo.piik.tv">在线演示</a> ·
+ <a href="./docs/README.md">文档</a>
+</p>
+<p align="center">
+ <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-36564f?style=flat-square" alt="MIT 许可"></a>
+ <img src="https://img.shields.io/badge/viewers-up_to_20-36564f?style=flat-square" alt="最多 20 位观众">
+ <img src="https://img.shields.io/badge/media-P2P_first-36564f?style=flat-square" alt="优先使用 P2P 连接">
+</p>
+<p align="center"><a href="./README.md">English</a> · 简体中文</p>
+
+Piik 是一个免费开源的屏幕共享工具,适合游戏围观、一起看电影、展示绘画或分享照片。
+选择画面,把邀请链接发给朋友,对方用浏览器即可观看。
+
+<details open>
+<summary>客厅小剧场 · 展开 / 收起动画</summary>
+
+<p align="center"><img src="./site/assets/living-room.svg" width="720" height="472" alt="戴着小金冠的房主分享 RPG 游戏、绘画、照片和动画电影,朋友们坐在沙发上观看。"></p>
+
+</details>
+
+[功能](#功能) · [开始使用](#开始使用) · [自行部署](#自行部署) · [参与贡献](#参与贡献)
+
+## 功能
+
+- **观看无须安装。** 朋友通过邀请链接,用电脑或手机浏览器加入。
+- **用客户端或已有 Piik 站点分享。** 支持屏幕、窗口和浏览器标签页;可选来源与音频能力取决于平台。
+- **优先直接连接。** 画面优先在设备之间传输(P2P),自建站点可启用媒体转发(SFU)自动兜底。
+- **房间由你管理。** 支持邀请链接、房间号和可选的房间密码,一位房主、最多 20 位观众。
+- **灵活的观看方式。** 支持深浅主题、播放控制、画中画和连接拓扑查看。
+- **一个程序就能建站。** 网页、房间管理和可选的媒体转发打包在同一服务端程序中。
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="./docs/assets/room-zh-dark.png">
+ <img src="./docs/assets/room-zh-light.png" width="860" alt="Piik 房间:共享的游戏画面、播放控件和坐在沙发上的朋友,房主戴着小金冠。">
+ </picture><br>
+ <sub>界面预览 · 示例房间与生成的游戏画面</sub>
+</p>
+
+## 开始使用
+
+**观看分享:** 打开朋友发来的邀请链接。画面没有自动播放时,点击**播放**即可。
+
+**分享画面:**
+
+| 从这里开始 | 需要做什么 |
+| --- | --- |
+| [体验在线 Demo](https://demo.piik.tv) | 在电脑浏览器打开,开始分享。 |
+| [下载 Piik App](https://piik.tv/?lang=zh-CN#download) | 解压并启动客户端,选择**公网邀请**,点击**进入 Piik**,创建临时房间。 |
+| 使用已有 Piik 站点 | 打开朋友或管理员提供的地址。[自行部署](./docs/operations/self-hosting.zh-CN.md)属于进阶操作。 |
-## 用浏览器分享
+<p align="center"><img src="./docs/assets/quickstart.svg" width="640" alt="选择画面,发送邀请,一起观看。"></p>
-1. 打开你们使用的 Piik 站点,按提示输入站点密码。
-2. 点击 **开始分享**,选择屏幕、窗口或标签页,并检查声音开关。
-3. 把房间邀请链接发给朋友,保持分享标签页打开。
+1. 点击**开始分享**,选择要分享的画面和声音。
+2. 点击**复制邀请链接**,发给朋友。分享期间保持标签页打开。
-浏览器采集需要 HTTPS 或 `localhost`;可选来源和声音支持取决于浏览器与平台。
-界面提供中文、英文和图示模式,以及明暗主题。
+Piik 默认使用图示按钮;点击顶部的**中**可显示文字。
+客户端提供本地房间、临时公网邀请和连接已有站点三种模式,分享期间需保持 App 运行。
-## 用 App 自己开房
+下载以 **`piik-app`** 开头的压缩包,再按文件名中的平台标识选择:
-拿到对应平台的 App 程序包后:
+| 文件名包含 | 适用平台 |
+| --- | --- |
+| `windows-amd64` | Windows x64 |
+| `darwin-arm64` | Apple 芯片;原生采集需 macOS 13 及以上 |
+| `linux-amd64` | Linux x64 |
-1. 完整解压,保留可执行文件旁的 `runtime` 目录。
-2. Windows 打开 `piik-app.exe`,macOS 打开 `Piik App.app`,
- Linux 运行 `./piik-app`。
-3. 选择模式和分享来源,发出邀请。分享期间保持 App 运行。
+[**完整使用教程 →**](./docs/guide/getting-started.zh-CN.md) · [**打开在线演示 →**](https://demo.piik.tv)
-| 模式 | 适合什么情况 |
-| --- | --- |
-| **本地房间** | 与同一局域网内的好友分享,可设置站点访问密码。 |
-| **公网邀请** | 生成本次 App 运行期间有效的临时邀请链接;媒体仍走 P2P。 |
-| **连接站点** | 使用已有 Piik 站点,并在同一浏览器界面使用 App 的采集与媒体能力。 |
+浏览器采集需要 HTTPS 或 `localhost`。目前主要测试 Windows 客户端和桌面浏览器分享。
+macOS 和 Linux 客户端尚未经过实机测试,欢迎有设备的朋友试用并[反馈问题](https://github.com/TNTcraftHIM/Piik/issues)。
+客户端公网邀请和演示站使用纯 P2P 连接,
+在受限网络下可能无法连通。
-App 会打开系统浏览器。程序包包含 Go 应用和采集、临时链接辅助程序,
-运行时无须安装 Node.js、npm 或 Go。Linux 原生采集使用系统的 Portal、PipeWire
-和 GStreamer,平台细节见 [App 指南](./cmd/piik-app/README.md)。
+## 自行部署
-临时公网链接使用 Cloudflare Quick Tunnel,不保证持续可用。
-媒体需要可用的 UDP 路径;网络限制、浏览器或系统挂起都可能中断分享。
-当前以 Windows App 和浏览器为验收重点,macOS/Linux 原生采集的实机验证另行进行。
-候选版本与发布准备情况见 [当前状态](./docs/status.md)。
+Piik Server 是一个内置网页界面的独立程序。
+下载 Linux x64 服务端程序包,解压后运行:
-## 自建站点或参与开发
+```sh
+./piik-server
+```
-Server 是一个内嵌 Web 界面的 Go 可执行文件,负责房间信令、STUN 和可选的内置
-SFU 后备路径。搭建自己的站点,请看 [自托管指南](./docs/operations/self-hosting.md)。
+打开 `http://localhost:8787` 即可在本机试用。对外提供服务时,
+再配置域名、HTTPS 反向代理和 STUN 地址。房间数据保存在 SQLite 中。
-源码运行、测试和架构从 [文档地图](./docs/README.md) 开始;
-[贡献指南](./CONTRIBUTING.md) 说明协作流程。
+[**部署自己的站点 →**](./docs/operations/self-hosting.zh-CN.md) · [配置参考](./docs/reference/configuration.md) · [从源码运行](./docs/README.md#run-from-source)
-## 遇到问题?
+## 参与贡献
-反馈时附上版本、系统与浏览器、预期结果和复现步骤。
-App 可用 `--debug` 启动后按 `D` 导出本地报告;浏览器网址加上 `?debug=1`
-后(放在 `#` 之前),可点击顶部下载按钮。分享前请检查报告内容,详见
-[诊断与导出](./docs/reference/configuration.md#diagnostics)。
-连接不上时,也可以查看 [Chromium WebRTC 常见问题](./cmd/piik-app/README.md#chromium-webrtc-connections)。
+欢迎提交问题、改进文档或参与开发。
+修改前请阅读[贡献指南](./CONTRIBUTING.md),也可以从
+[项目目录说明](./docs/reference/engineering.md#repository-layout)了解代码结构。
## 许可
-Piik 自有代码采用 [MIT 许可](./LICENSE),提供 [中文参考译文](./LICENSE.zh-CN.md)。
-第三方组件保留各自的许可与声明,详见 [许可说明](./licenses/README.md)。
+Piik 自有代码采用 [MIT 许可](./LICENSE),依赖保留各自的[许可与声明](./licenses/README.md)。
diff --git a/cmd/piik-app/README.md b/cmd/piik-app/README.md
index c37a393c..bcd5b37a 100644
--- a/cmd/piik-app/README.md
+++ b/cmd/piik-app/README.md
@@ -1,21 +1,20 @@
# Piik App
-Piik App is the self-contained and native-capability runtime for the same
-Browser application used by Hosted Piik. It does not implement another UI,
-room store, signaling protocol, or route controller.
+Piik App provides local rooms and native screen capture through the Piik web
+interface in your system Browser.
## Run A Package
Extract the matching platform bundle in full and keep `runtime` beside the
App executable. Run `piik-app.exe` on Windows, `./piik-app` on
-Linux, or `Piik App.app` on macOS. The launcher opens in the system Browser;
-the App does not embed a browser UI. Packaged execution needs no Node.js, npm,
-or Go installation. Linux native capture uses the system dependencies described
+Linux, or `Piik App.app` on macOS. The launcher opens in the system Browser.
+Linux native capture uses the system dependencies described
in the [Linux capture guide](../../native/capture/linux/README.md).
-Windows App and Browser are this phase's acceptance targets. Other platform
-builds do not establish physical capture/audio acceptance; see
-[current status](../../docs/status.md). Package construction and public Release
+Windows App and browser sharing are the primary tested paths. The macOS and
+Linux apps have not yet been tested on physical devices; test results and
+[feedback](https://github.com/TNTcraftHIM/Piik/issues) are welcome. macOS native
+capture requires Apple silicon and macOS 13 or newer. Package construction and public Release
publication are separate steps in [deployment](../../docs/deployment.md).
## Modes
@@ -25,14 +24,12 @@ publication are separate steps in [deployment](../../docs/deployment.md).
Site, then enters the normal Host page.
- The launcher remembers the Site address but keeps the per-run room source
separate. The App RPC starts before this choice and accepts the saved Site
- alongside the Local Host origin, so Local or Public invite does not disable
- Site enhancement. An App-opened Site remembers the opt-in in that Browser
+ alongside the Local Host origin. An App-opened Site remembers the opt-in in that Browser
origin; later manually opened Host pages may reuse the running App.
-- `--site`, `--local`, and `--link` remain deterministic automation inputs for
- CI and development. They are not required for normal use.
-- The default launcher checks the official GitHub Releases metadata after it
- opens and shows a notice when a newer full-SHA release exists. The check is
- best-effort and never installs or replaces the App.
+- The `--site`, `--local`, and `--link` flags select a mode for CI and development.
+- The default launcher checks official releases after it opens, using GitHub
+ first and Gitee if GitHub is unavailable. It links to an available release
+ without installing or replacing the App.
Local mode uses memory-only rooms, P2P relay, no SFU listener, and no public
discovery. Ordinary Local works on a reachable LAN. The **Public invite** mode
@@ -72,9 +69,8 @@ reuse suitable H.264/VP8 outputs and derive a missing lower output only for
direct-child demand. Compatible children share that output; each edge receives
only its selected representation. SFU publication combines its requested output
prefix with one aggregate upstream budget. A lower-output constraint does not
-replace the original input or higher sibling outputs. The existing route
-controller still owns persistent quality evidence and any route replacement;
-there is no room-wide score or periodic rebalance. See
+replace the original input or higher sibling outputs. The route controller owns
+persistent quality evidence and route replacement. See
[media quality](../../docs/product/media-quality.md) for the implemented behavior
and [status](../../docs/status.md) for its acceptance limits.
@@ -89,7 +85,7 @@ The terminal shows the current mode, entry links and startup state; its language
follows the launcher and App-enabled pages.
Press `o` to reopen the Browser, or `q` / Ctrl+C to end Local
rooms and stop the local server and temporary public link. Plain-text output
-uses Ctrl+C. A Site-loaded Browser tab does not own the App process.
+uses Ctrl+C. The App keeps running after a Site tab closes.
For one-link Internet sharing, open the App launcher, choose **Public invite**,
create a room in the opened Browser, and send its normal invitation link. The
@@ -106,8 +102,7 @@ use a configured Site when persistent control availability or SFU fallback matte
Chromium-based Browsers can restrict WebRTC UDP through Browser settings,
extensions or managed policies. Disabling non-proxied UDP can prevent even the
local Browser-to-App media connection; successful capture or page loading
-does not prove that this separate connection is available. This is not specific
-to one Browser brand or to VPN use.
+does not prove that this separate connection is available.
Check the Browser's WebRTC/IP-handling policy and any extension's WebRTC or
IP-leak protection setting. Restore a policy that permits WebRTC UDP, reload
@@ -170,12 +165,21 @@ admits at most two independent strict v9 control sessions. After `hello`, each
session may list local capture choices, own one generation-fenced Host share,
or receive one native Viewer source and its bounded encoded child edges. Closing
one session retires only its resources. Its public `instanceToken`
-distinguishes the discovered process but is not authentication; room authority
-and remote signaling remain in the Browser. Viewer receive/relay remains
+distinguishes the discovered process but is not authentication. The shared Go
+service owns room authority; the Browser owns the room protocol client and
+orchestrates native media through this control session. Viewer receive/relay remains
available even when this machine has no accepted native capture encoder.
Capture sidecars must match the App's current probe/encoded-output contract;
the package-candidate wrapper validates that version before accepting its artifact.
+Packaged builds report the product version and source SHA in the terminal and
+diagnostic context. The launcher uses that identity to distinguish a newer
+version, a different build of the same version, and an official release offered
+to a development build; the link never installs or interrupts a share.
+[Versioning](../../docs/reference/versioning.md)
+owns these meanings and [GitHub operations](../../docs/operations/github.md)
+owns automatic publication.
+
## Packaging
From a clean revision, build the application release and run the platform's
diff --git a/cmd/piik-server/main.go b/cmd/piik-server/main.go
index ae18948a..43cfe90e 100644
--- a/cmd/piik-server/main.go
+++ b/cmd/piik-server/main.go
@@ -1,10 +1,10 @@
// Command piik-server is the Hosted Piik entry point: it loads the
// environment, serves the embedded Browser UI together with the signaling and
-// room API, and stops on SIGINT or SIGTERM. It replaces src/server/index.ts.
+// room API, and stops on SIGINT or SIGTERM.
//
// Two maintenance modes exit without serving: --check-config validates the
// environment (the release wrapper runs it as the service user before cutover)
-// and --check-release compares the deployed revision with the latest published
+// and --check-release compares this binary with the latest published
// release (see release.go).
package main
@@ -37,17 +37,16 @@ const shutdownTimeout = 15 * time.Second
// release directory. Hosted keeps its real values in the service secret store.
const environmentFile = ".env"
-// BuildRevision is the full Git revision the release packager links in with
-// -ldflags. It matches the REVISION file shipped beside the binary and is
-// reported at startup so one journal line identifies the running release.
-var BuildRevision = "development"
+// The packager injects the product version and full source revision together.
+var (
+ BuildVersion = "development"
+ BuildRevision = "development"
+)
func main() {
checkConfig := flag.Bool("check-config", false, "validate the environment and exit")
checkRelease := flag.Bool("check-release", false,
"report whether a newer published release exists and exit")
- currentFile := flag.String("current-file", "",
- "path to the deployed REVISION file read by --check-release")
apiURL := flag.String("api-url", defaultReleaseAPIURL,
"release metadata endpoint used by --check-release")
debug := flag.Bool("debug", false, "save opt-in server diagnostics to rotated files")
@@ -58,7 +57,7 @@ func main() {
}
switch {
case *checkRelease:
- os.Exit(checkDeployedRelease(context.Background(), *currentFile, *apiURL, os.Stdout))
+ os.Exit(checkDeployedRelease(context.Background(), *apiURL, os.Stdout))
case *checkConfig:
if _, err := config.Load(environment()); err != nil {
fail(err)
@@ -98,14 +97,16 @@ func serve(debug bool) (returnedErr error) {
defer func() {
stopExport()
_ = dependencyLog.Close()
- logger.Info("piik-server", "event", "stopped", "failed", returnedErr != nil, diagnostics.Error(returnedErr))
returnedErr = errors.Join(returnedErr, exportServerDiagnostics(recorder), recorder.Close())
slog.SetDefault(previous)
log.SetOutput(previousWriter)
log.SetFlags(previousFlags)
}()
- logger.Info("piik-server", "event", "start", "revision", BuildRevision)
+ logger.Info("piik-server", "event", "start", "version", BuildVersion, "revision", BuildRevision)
}
+ defer func() {
+ logger.Info("piik-server", "event", "stopped", "failed", returnedErr != nil, diagnostics.Error(returnedErr))
+ }()
configuration, err := config.Load(environment())
if err != nil {
return err
@@ -133,11 +134,26 @@ func serve(debug bool) (returnedErr error) {
if err != nil {
return err
}
- fmt.Printf("Piik %s is listening on %s:%d; public URL %s\n",
- BuildRevision, configuration.ListenHost, port, config.Origin(configuration.PublicBaseURL))
+ logger.Info("Piik server is listening", "event", "ready", "version", BuildVersion, "revision", BuildRevision,
+ "host", configuration.ListenHost, "port", port, "publicUrl", config.Origin(configuration.PublicBaseURL),
+ "sqlite", configuration.RoomDatabasePath != "", "siteAccessProtected", configuration.SiteAccessPassword != "",
+ "sfu", configuration.SFU != nil, "natPrediction", configuration.NATPredictionEnabled)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
- defer stop()
+ // One bounded background lookup never delays serving. Join it before closing
+ // diagnostic outputs so shutdown cannot leave a late writer behind.
+ releaseChecked := make(chan struct{})
+ go func() {
+ defer close(releaseChecked)
+ result := checkRelease(ctx, BuildVersion, BuildRevision, defaultReleaseAPIURL, os.Getenv("GITHUB_TOKEN"), mirrorReleaseAPIURL)
+ if ctx.Err() == nil {
+ logReleaseNotice(logger, result)
+ }
+ }()
+ defer func() {
+ stop()
+ <-releaseChecked
+ }()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
@@ -185,9 +201,9 @@ func environment() map[string]string {
return values
}
-// loadEnvironmentFile ports the src/server/index.ts loadEnvFile() call: an
-// absent file is the ordinary case and every other read failure stops startup.
-// Like Node, a name the process already carries is never overwritten, so a
+// loadEnvironmentFile reads optional startup overrides. An absent file is the
+// ordinary case and every other read failure stops startup. A name the process
+// already carries is never overwritten, so a
// systemd EnvironmentFile still wins over a stale file in the release
// directory. The accepted syntax is DECISIONS D8: KEY=value lines, whole-line
// '#' comments, an optional 'export ' prefix, and a single- or double-quoted
diff --git a/cmd/piik-server/release.go b/cmd/piik-server/release.go
index eb4d1883..e9c818ed 100644
--- a/cmd/piik-server/release.go
+++ b/cmd/piik-server/release.go
@@ -6,86 +6,66 @@ import (
"errors"
"fmt"
"io"
+ "log/slog"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
+
+ "golang.org/x/mod/semver"
)
-// defaultReleaseAPIURL is DEFAULT_RELEASE_API_URL: the same published release
-// contract the Browser update notice uses (src/client/lib/release-update.ts).
+// The Browser notice and operator checker read the same published release.
const defaultReleaseAPIURL = "https://api.github.com/repos/TNTcraftHIM/Piik/releases/latest"
+const mirrorReleaseAPIURL = "https://gitee.com/api/v5/repos/TNTcraftHIM/Piik/releases"
-// Exit codes are UPDATE_EXIT_CODES. deploy/check-release.sh forwards them, so a
-// checker failure stays distinguishable from "an update exists".
+// deploy/check-release.sh forwards these codes without installing anything.
const (
exitUpToDate = 0
exitUpdateAvailable = 10
exitUpdateUnavailable = 20
- // exitUsage is the exit code parseArguments set when --current-file was
- // missing. Without it a forgotten argument reads as an unavailable check.
- exitUsage = 2
-)
-
-// releaseUsage is the usage string parseArguments threw, with this binary's
-// name in place of the script's.
-const releaseUsage = "Usage: piik-server --check-release --current-file <REVISION> [--api-url <URL>]"
-
-const (
- // releaseTimeout bounds the whole check; an operator runs it interactively.
- releaseTimeout = 5 * time.Second
- // releasePathPrefix is RELEASE_PATH_PREFIX: the only accepted release page.
- releasePathPrefix = "/TNTcraftHIM/Piik/releases/tag/"
- releaseHost = "github.com"
- releaseAPIHost = "api.github.com"
+ releaseTimeout = 5 * time.Second
+ releaseURLPrefix = "https://github.com/TNTcraftHIM/Piik/releases/tag/"
+ releaseAPIHost = "api.github.com"
+ mirrorReleasePrefix = "https://gitee.com/TNTcraftHIM/Piik/releases/tag/"
)
-// fullRevisionPattern is FULL_REVISION applied to an already lowercased value,
-// which is why the JavaScript case-insensitive flag has no counterpart here.
var fullRevisionPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
+var mirrorSourcePattern = regexp.MustCompile(`(?m)^<!-- piik-source: ([0-9a-f]{40}) -->\r?$`)
-// Release status values are the "status" field of the printed JSON line, which
-// deploy/check-release.sh reads; each maps to one exit code above.
const (
statusUpToDate = "up-to-date"
statusUpdateAvailable = "update-available"
+ statusDifferentBuild = "different-build"
+ statusOfficialRelease = "official-release"
statusUnavailable = "unavailable"
)
-// releaseResult is the single JSON line the checker prints. Field order is the
-// JSON.stringify order of the ported object, and the pointers are the nulls: a
-// value the check could not establish is present and null, never omitted.
+// Unknown identity fields are explicit nulls in the single printed JSON line.
type releaseResult struct {
Status string `json:"status"`
+ CurrentVersion *string `json:"currentVersion"`
+ LatestVersion *string `json:"latestVersion"`
CurrentRevision *string `json:"currentRevision"`
LatestRevision *string `json:"latestRevision"`
ReleaseURL *string `json:"releaseUrl"`
}
-// checkDeployedRelease is the --check-release entry point. It writes one JSON
-// line and returns the process exit code. An unreadable revision file is an
-// unavailable check rather than an update, which is what the ported script's
-// silently swallowed read failure meant; an absent --current-file is a usage
-// error, which is what parseArguments made it.
-func checkDeployedRelease(ctx context.Context, currentFile, apiURL string, out io.Writer) int {
- if currentFile == "" {
- fmt.Fprintln(os.Stderr, releaseUsage)
- return exitUsage
- }
- current := ""
- if content, err := os.ReadFile(currentFile); err == nil {
- current = string(content)
- }
- result := checkRelease(ctx, current, apiURL, os.Getenv("GITHUB_TOKEN"))
+func checkDeployedRelease(ctx context.Context, apiURL string, out io.Writer) int {
+ mirrorURL := ""
+ if apiURL == defaultReleaseAPIURL {
+ mirrorURL = mirrorReleaseAPIURL
+ }
+ result := checkRelease(ctx, BuildVersion, BuildRevision, apiURL, os.Getenv("GITHUB_TOKEN"), mirrorURL)
encoder := json.NewEncoder(out)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(result); err != nil {
return exitUpdateUnavailable
}
switch result.Status {
- case statusUpdateAvailable:
+ case statusUpdateAvailable, statusDifferentBuild, statusOfficialRelease:
return exitUpdateAvailable
case statusUpToDate:
return exitUpToDate
@@ -94,149 +74,213 @@ func checkDeployedRelease(ctx context.Context, currentFile, apiURL string, out i
}
}
-// checkRelease ports checkRelease. Every failure - an unusable current
-// revision, an unusable endpoint, a redirect, a timeout, a non-2xx reply or
-// metadata that fails validation - collapses to the same unavailable result:
-// the checker never guesses that an update exists.
-func checkRelease(ctx context.Context, currentRevision, apiURL, token string) releaseResult {
- current := normalizeRevision(currentRevision)
- if current == "" {
- return unavailableResult(currentRevision)
+func checkRelease(ctx context.Context, currentVersion, currentRevision, apiURL, token, mirrorURL string) releaseResult {
+ result := unavailableResult(currentVersion, currentRevision)
+ comparableVersion := result.CurrentVersion != nil && semver.IsValid(*result.CurrentVersion)
+ if !comparableVersion && result.CurrentRevision == nil {
+ return result
+ }
+ version, revision, releaseURL, ok := fetchLatestRelease(ctx, apiURL, token, false)
+ if !ok && mirrorURL != "" {
+ version, revision, releaseURL, ok = fetchLatestRelease(ctx, mirrorURL, "", true)
+ }
+ if !ok {
+ return result
+ }
+ result.LatestVersion = &version
+ result.LatestRevision = revisionOrNull(revision)
+ result.ReleaseURL = &releaseURL
+ if comparableVersion {
+ result.Status = statusUpToDate
+ order := semver.Compare(version, *result.CurrentVersion)
+ if order > 0 {
+ result.Status = statusUpdateAvailable
+ } else if order == 0 && result.CurrentRevision != nil && result.LatestRevision != nil &&
+ *result.CurrentRevision != *result.LatestRevision {
+ result.Status = statusDifferentBuild
+ }
+ } else if result.CurrentRevision != nil && result.LatestRevision != nil {
+ result.Status = statusOfficialRelease
+ if *result.CurrentRevision == *result.LatestRevision {
+ result.Status = statusUpToDate
+ }
}
+ return result
+}
+
+// Routine startup only announces actionable release choices. An unavailable
+// provider is not a server failure, and never changes the running installation.
+func logReleaseNotice(logger *slog.Logger, result releaseResult) {
+ var message string
+ switch result.Status {
+ case statusUpdateAvailable:
+ message = "A newer Piik release is available"
+ case statusDifferentBuild:
+ message = "This Piik build differs from the official release"
+ case statusOfficialRelease:
+ message = "An official Piik release is available"
+ default:
+ return
+ }
+ current := "development"
+ if result.CurrentVersion != nil {
+ current = *result.CurrentVersion
+ }
+ logger.Info(message, "event", "release-check", "status", result.Status,
+ "currentVersion", current, "latestVersion", *result.LatestVersion, "releaseUrl", *result.ReleaseURL)
+}
+
+func fetchLatestRelease(ctx context.Context, apiURL, token string, mirror bool) (version, revision, releaseURL string, ok bool) {
endpoint, err := url.Parse(apiURL)
if err != nil || (endpoint.Scheme != "https" && endpoint.Scheme != "http") {
- return unavailableResult(current)
+ return "", "", "", false
}
-
ctx, cancel := context.WithTimeout(ctx, releaseTimeout)
defer cancel()
+ for page := 1; page <= 10; page++ {
+ if mirror {
+ query := endpoint.Query()
+ query.Set("per_page", "100")
+ query.Set("page", fmt.Sprint(page))
+ query.Set("direction", "desc")
+ endpoint.RawQuery = query.Encode()
+ }
+ body, err := readReleaseResponse(ctx, endpoint, token, mirror)
+ if err != nil {
+ return "", "", "", false
+ }
+ if !mirror {
+ return parseReleaseMetadata(body)
+ }
+ var releases []json.RawMessage
+ if err := json.Unmarshal(body, &releases); err != nil || releases == nil || len(releases) > 100 {
+ return "", "", "", false
+ }
+ for _, payload := range releases {
+ candidateVersion, candidateRevision, candidateURL, valid := parseMirrorReleaseMetadata(payload)
+ if valid && (!ok || semver.Compare(candidateVersion, version) > 0) {
+ version, revision, releaseURL, ok = candidateVersion, candidateRevision, candidateURL, true
+ }
+ }
+ if len(releases) < 100 {
+ return
+ }
+ }
+ // Incomplete pagination cannot establish the highest stable version.
+ return "", "", "", false
+}
+
+func readReleaseResponse(ctx context.Context, endpoint *url.URL, token string, mirror bool) ([]byte, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
- return unavailableResult(current)
+ return nil, err
}
- request.Header.Set("Accept", "application/vnd.github+json")
- request.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+ request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", "Piik-release-check")
- if authorizesGitHub(endpoint, token) {
- request.Header.Set("Authorization", "Bearer "+strings.TrimSpace(token))
+ if !mirror {
+ request.Header.Set("Accept", "application/vnd.github+json")
+ request.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+ if authorizesGitHub(endpoint, token) {
+ request.Header.Set("Authorization", "Bearer "+strings.TrimSpace(token))
+ }
}
-
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error {
- // The ported redirect: "error" policy. A moved release endpoint is not
- // followed, so the Authorization header cannot travel to another origin.
return errors.New("release endpoint redirected")
}}
response, err := client.Do(request)
if err != nil {
- return unavailableResult(current)
+ return nil, err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
- return unavailableResult(current)
- }
- body, err := io.ReadAll(response.Body)
- if err != nil {
- return unavailableResult(current)
- }
- latest, releaseURL, ok := parseReleaseMetadata(body)
- if !ok {
- return unavailableResult(current)
+ return nil, errors.New("release endpoint unavailable")
}
- status := statusUpdateAvailable
- if latest == current {
- status = statusUpToDate
- }
- return releaseResult{
- Status: status,
- CurrentRevision: &current,
- LatestRevision: &latest,
- ReleaseURL: &releaseURL,
+ const limit = 4 << 20
+ body, err := io.ReadAll(io.LimitReader(response.Body, limit+1))
+ if err != nil || len(body) > limit {
+ return nil, errors.New("release metadata unreadable or too large")
}
+ return body, nil
}
-// authorizesGitHub reports whether the operator token may be sent to endpoint.
-// A fixture, mirror or plaintext endpoint must never receive it, which is why
-// the scheme and the host are both part of the rule.
+// Only the HTTPS GitHub API receives an operator token, and redirects are refused.
func authorizesGitHub(endpoint *url.URL, token string) bool {
return endpoint.Scheme == "https" &&
strings.ToLower(endpoint.Hostname()) == releaseAPIHost &&
strings.TrimSpace(token) != ""
}
-// unavailableResult is unavailableResult: the current revision is reported when
-// it is well formed and null otherwise.
-func unavailableResult(currentRevision string) releaseResult {
- return releaseResult{Status: statusUnavailable, CurrentRevision: revisionOrNull(currentRevision)}
-}
-
-func revisionOrNull(value string) *string {
- revision := normalizeRevision(value)
- if revision == "" {
- return nil
+func unavailableResult(currentVersion, currentRevision string) releaseResult {
+ currentVersion = strings.TrimSpace(currentVersion)
+ if canonical := semver.Canonical(currentVersion); canonical != "" {
+ currentVersion = canonical
}
- return &revision
+ result := releaseResult{Status: statusUnavailable, CurrentRevision: revisionOrNull(currentRevision)}
+ if currentVersion != "" {
+ result.CurrentVersion = &currentVersion
+ }
+ return result
}
-// normalizeRevision ports normalizeRevision, returning "" where it returned
-// null: only a full 40-hex commit identifies a release.
-func normalizeRevision(value string) string {
+func revisionOrNull(value string) *string {
revision := strings.ToLower(strings.TrimSpace(value))
if !fullRevisionPattern.MatchString(revision) {
- return ""
+ return nil
}
- return revision
+ return &revision
}
-// releaseMetadata is the subset of the GitHub release payload that is read.
-// A tag_name or html_url of another type fails to decode, which is the
-// rejection the JavaScript reached through typeof. Deviation: the JavaScript
-// tested `draft === true`, so it read a draft of another type as "not a
-// draft"; here such a payload fails to decode and the check reports
-// unavailable. Only stricter, and a release payload the checker cannot
-// understand must never be reported as an update.
type releaseMetadata struct {
- TagName *string `json:"tag_name"`
- HTMLURL *string `json:"html_url"`
- Draft *bool `json:"draft"`
- Prerelease *bool `json:"prerelease"`
+ TagName string `json:"tag_name"`
+ HTMLURL string `json:"html_url"`
+ TargetCommitish string `json:"target_commitish"`
+ Draft bool `json:"draft"`
+ Prerelease bool `json:"prerelease"`
}
-// parseReleaseMetadata ports parseReleaseMetadata. It accepts one shape only: a
-// published, non-draft release whose tag is a full commit revision and whose
-// page is exactly https://github.com/TNTcraftHIM/Piik/releases/tag/<that
-// revision> with no credentials, port, query or fragment. The returned URL is
-// rebuilt from the validated parts so nothing unverified reaches the operator.
-func parseReleaseMetadata(payload []byte) (revision string, releaseURL string, ok bool) {
+// A branch-valued target_commitish is unknown provenance, never a source SHA.
+func parseReleaseMetadata(payload []byte) (version, revision, releaseURL string, ok bool) {
var metadata releaseMetadata
if err := json.Unmarshal(payload, &metadata); err != nil {
- return "", "", false
+ return "", "", "", false
}
- if (metadata.Draft != nil && *metadata.Draft) ||
- (metadata.Prerelease != nil && *metadata.Prerelease) {
- return "", "", false
+ return normalizeReleaseMetadata(metadata)
+}
+
+func normalizeReleaseMetadata(metadata releaseMetadata) (version, revision, releaseURL string, ok bool) {
+ if metadata.Draft || metadata.Prerelease {
+ return "", "", "", false
}
- if metadata.TagName == nil || metadata.HTMLURL == nil {
- return "", "", false
+ version = metadata.TagName
+ if version == "" || semver.Canonical(version) != version || semver.Prerelease(version) != "" ||
+ metadata.HTMLURL != releaseURLPrefix+version {
+ return "", "", "", false
}
- revision = normalizeRevision(*metadata.TagName)
- if revision == "" {
- return "", "", false
+ if source := revisionOrNull(metadata.TargetCommitish); source != nil {
+ revision = *source
}
- parsed, err := url.Parse(*metadata.HTMLURL)
- if err != nil || parsed.Scheme != "https" ||
- strings.ToLower(parsed.Hostname()) != releaseHost || parsed.User != nil ||
- parsed.Port() != "" || parsed.RawQuery != "" || parsed.Fragment != "" {
- return "", "", false
+ return version, revision, metadata.HTMLURL, true
+}
+
+func parseMirrorReleaseMetadata(payload []byte) (version, revision, releaseURL string, ok bool) {
+ var metadata struct {
+ TagName string `json:"tag_name"`
+ Body string `json:"body"`
+ Prerelease *bool `json:"prerelease"`
}
- // The escaped path is compared, so an encoded separator such as %2F cannot
- // smuggle another path past the prefix the way the decoded form would.
- path := parsed.EscapedPath()
- if !strings.HasPrefix(path, releasePathPrefix) {
- return "", "", false
+ if err := json.Unmarshal(payload, &metadata); err != nil || metadata.Prerelease == nil || *metadata.Prerelease {
+ return "", "", "", false
}
- tag, err := url.PathUnescape(strings.TrimPrefix(path, releasePathPrefix))
- if err != nil || normalizeRevision(tag) != revision {
- return "", "", false
+ sources := mirrorSourcePattern.FindAllStringSubmatch(metadata.Body, -1)
+ if len(sources) != 1 {
+ return "", "", "", false
+ }
+ // The mirror's target_commitish identifies its README, not the original source.
+ version, revision, _, ok = normalizeReleaseMetadata(releaseMetadata{
+ TagName: metadata.TagName, TargetCommitish: sources[0][1], HTMLURL: releaseURLPrefix + metadata.TagName,
+ })
+ if !ok {
+ return "", "", "", false
}
- return revision, "https://" + releaseHost + path, true
+ return version, revision, mirrorReleasePrefix + version, true
}
diff --git a/cmd/piik-server/release_test.go b/cmd/piik-server/release_test.go
index 53f9e52a..0a0feb99 100644
--- a/cmd/piik-server/release_test.go
+++ b/cmd/piik-server/release_test.go
@@ -4,202 +4,174 @@ import (
"bytes"
"context"
"encoding/json"
+ "log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
- "path/filepath"
"strings"
"testing"
)
const (
+ deployedVersion = "v1.9.0"
+ latestVersion = "v1.10.0"
deployedRevision = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
latestRevision = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
- latestReleaseURL = "https://github.com/TNTcraftHIM/Piik/releases/tag/" + latestRevision
- latestRelease = `{"tag_name":"` + latestRevision + `","html_url":"` + latestReleaseURL + `"}`
+ latestReleaseURL = "https://github.com/TNTcraftHIM/Piik/releases/tag/" + latestVersion
+ latestRelease = `{"tag_name":"` + latestVersion + `","html_url":"` + latestReleaseURL + `","target_commitish":"` + latestRevision + `"}`
)
+func TestReleaseNoticeUsesOperatorLogsOnlyForAvailableChoices(t *testing.T) {
+ for _, status := range []string{statusUpdateAvailable, statusDifferentBuild, statusOfficialRelease, statusUpToDate, statusUnavailable} {
+ t.Run(status, func(t *testing.T) {
+ var output bytes.Buffer
+ version, releaseURL := latestVersion, latestReleaseURL
+ logReleaseNotice(slog.New(slog.NewJSONHandler(&output, nil)), releaseResult{
+ Status: status, LatestVersion: &version, ReleaseURL: &releaseURL,
+ })
+ if status == statusUpToDate || status == statusUnavailable {
+ if output.Len() != 0 {
+ t.Fatalf("non-actionable check produced a notice: %s", output.String())
+ }
+ return
+ }
+ var entry map[string]any
+ if err := json.Unmarshal(output.Bytes(), &entry); err != nil {
+ t.Fatal(err)
+ }
+ if entry["status"] != status || entry["currentVersion"] != "development" ||
+ entry["latestVersion"] != latestVersion || entry["releaseUrl"] != latestReleaseURL || entry["level"] != "INFO" {
+ t.Fatalf("release notice lost its version or download action: %v", entry)
+ }
+ if status == statusDifferentBuild && strings.Contains(entry["msg"].(string), "newer") {
+ t.Fatal("SHA inequality was presented as release ordering")
+ }
+ })
+ }
+}
+
func TestParseReleaseMetadataAcceptsOnlyTheStrictReleaseIdentity(t *testing.T) {
- tagged := func(page string) string {
- return `{"tag_name":"` + latestRevision + `","html_url":"` + page + `"}`
+ tagged := func(version, page string) string {
+ return `{"tag_name":"` + version + `","html_url":"` + page + `"}`
}
testCases := []struct {
- name string
- payload string
- revision string
- url string
+ name, payload, version, revision, url string
}{
- {"published release", latestRelease, latestRevision, latestReleaseURL},
- {
- "uppercase tag normalizes",
- `{"tag_name":"` + strings.ToUpper(latestRevision) + `","html_url":"` + latestReleaseURL + `"}`,
- latestRevision, latestReleaseURL,
- },
- {"short tag", `{"tag_name":"short","html_url":"` + latestReleaseURL + `"}`, "", ""},
- {"other host", tagged("https://evil.example"), "", ""},
- {
- "userinfo",
- tagged("https://[email protected]/TNTcraftHIM/Piik/releases/tag/" + latestRevision),
- "", "",
- },
- {
- "port",
- tagged("https://github.com:8443/TNTcraftHIM/Piik/releases/tag/" + latestRevision),
- "", "",
- },
- {
- "plaintext page",
- tagged("http://github.com/TNTcraftHIM/Piik/releases/tag/" + latestRevision),
- "", "",
- },
- {"query", tagged(latestReleaseURL + "?asset=1"), "", ""},
- {"fragment", tagged(latestReleaseURL + "#assets"), "", ""},
- {
- "encoded path separator",
- tagged("https://github.com/TNTcraftHIM%2FPiik/releases/tag/" + latestRevision),
- "", "",
- },
- {
- "page tag disagrees with the release tag",
- tagged("https://github.com/TNTcraftHIM/Piik/releases/tag/" + deployedRevision),
- "", "",
- },
- {
- "draft",
- `{"tag_name":"` + latestRevision + `","html_url":"` + latestReleaseURL + `","draft":true}`,
- "", "",
- },
- {
- "prerelease",
- `{"tag_name":"` + latestRevision + `","html_url":"` + latestReleaseURL + `","prerelease":true}`,
- "", "",
- },
- {"missing page", `{"tag_name":"` + latestRevision + `"}`, "", ""},
- {"array payload", `[]`, "", ""},
- {"not an object", `"released"`, "", ""},
- {"not json", `nonsense`, "", ""},
+ {"published release", latestRelease, latestVersion, latestRevision, latestReleaseURL},
+ {"uppercase source normalizes", strings.Replace(latestRelease, latestRevision, strings.ToUpper(latestRevision), 1), latestVersion, latestRevision, latestReleaseURL},
+ {"branch source is unknown", strings.Replace(latestRelease, latestRevision, "main", 1), latestVersion, "", latestReleaseURL},
+ {"missing source is unknown", tagged(latestVersion, latestReleaseURL), latestVersion, "", latestReleaseURL},
+ {"short source is unknown", strings.Replace(latestRelease, latestRevision, "bbbbbbb", 1), latestVersion, "", latestReleaseURL},
+ {"old SHA tag", tagged(latestRevision, releaseURLPrefix+latestRevision), "", "", ""},
+ {"short version", tagged("v1", releaseURLPrefix+"v1"), "", "", ""},
+ {"missing v prefix", tagged("1.10.0", releaseURLPrefix+"1.10.0"), "", "", ""},
+ {"prerelease version", tagged("v1.10.0-rc.1", releaseURLPrefix+"v1.10.0-rc.1"), "", "", ""},
+ {"build suffix", tagged("v1.10.0+build", releaseURLPrefix+"v1.10.0+build"), "", "", ""},
+ {"other host", tagged(latestVersion, "https://evil.example"), "", "", ""},
+ {"userinfo", tagged(latestVersion, "https://[email protected]/TNTcraftHIM/Piik/releases/tag/"+latestVersion), "", "", ""},
+ {"port", tagged(latestVersion, "https://github.com:8443/TNTcraftHIM/Piik/releases/tag/"+latestVersion), "", "", ""},
+ {"plaintext page", tagged(latestVersion, "http://github.com/TNTcraftHIM/Piik/releases/tag/"+latestVersion), "", "", ""},
+ {"query", tagged(latestVersion, latestReleaseURL+"?asset=1"), "", "", ""},
+ {"fragment", tagged(latestVersion, latestReleaseURL+"#assets"), "", "", ""},
+ {"encoded path separator", tagged(latestVersion, "https://github.com/TNTcraftHIM%2FPiik/releases/tag/"+latestVersion), "", "", ""},
+ {"mismatched page tag", tagged(latestVersion, releaseURLPrefix+deployedVersion), "", "", ""},
+ {"draft", strings.TrimSuffix(latestRelease, "}") + `,"draft":true}`, "", "", ""},
+ {"prerelease", strings.TrimSuffix(latestRelease, "}") + `,"prerelease":true}`, "", "", ""},
+ {"missing page", `{"tag_name":"` + latestVersion + `"}`, "", "", ""},
+ {"array payload", `[]`, "", "", ""},
+ {"not an object", `"released"`, "", "", ""},
+ {"not json", `nonsense`, "", "", ""},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
- revision, releaseURL, ok := parseReleaseMetadata([]byte(testCase.payload))
- if ok != (testCase.revision != "") || revision != testCase.revision ||
- releaseURL != testCase.url {
- t.Fatalf("parseReleaseMetadata(%s) = %q, %q, %t; want %q, %q",
- testCase.payload, revision, releaseURL, ok, testCase.revision, testCase.url)
+ version, revision, releaseURL, ok := parseReleaseMetadata([]byte(testCase.payload))
+ if ok != (testCase.version != "") || version != testCase.version || revision != testCase.revision || releaseURL != testCase.url {
+ t.Fatalf("parseReleaseMetadata = %q, %q, %q, %t; want %q, %q, %q",
+ version, revision, releaseURL, ok, testCase.version, testCase.revision, testCase.url)
}
})
}
}
func TestCheckReleaseReportsTheDeployedComparison(t *testing.T) {
+ branchRelease := strings.Replace(latestRelease, latestRevision, "main", 1)
testCases := []struct {
- name string
- current string
- status int
- body string
- wantStatus string
- wantCurrent string
- wantLatest string
- wantReleaseURL string
- wantRequestSent bool
+ name, version, revision, body, wantStatus, wantLatest string
}{
- {
- name: "newer release", current: deployedRevision, status: http.StatusOK,
- body: latestRelease, wantStatus: "update-available", wantCurrent: deployedRevision,
- wantLatest: latestRevision, wantReleaseURL: latestReleaseURL, wantRequestSent: true,
- },
- {
- name: "same release", current: latestRevision, status: http.StatusOK,
- body: latestRelease, wantStatus: "up-to-date", wantCurrent: latestRevision,
- wantLatest: latestRevision, wantReleaseURL: latestReleaseURL, wantRequestSent: true,
- },
- {
- name: "endpoint unavailable", current: deployedRevision,
- status: http.StatusServiceUnavailable, body: "offline",
- wantStatus: "unavailable", wantCurrent: deployedRevision, wantRequestSent: true,
- },
- {
- name: "unusable metadata", current: deployedRevision, status: http.StatusOK,
- body: `{"tag_name":"v1","html_url":"https://evil.example"}`,
- // The published page failed validation, so no update is claimed.
- wantStatus: "unavailable", wantCurrent: deployedRevision, wantRequestSent: true,
- },
- {
- name: "deployed revision is not a release", current: "development",
- status: http.StatusOK, body: latestRelease,
- // No request at all: the check cannot compare an unknown deployment.
- wantStatus: "unavailable", wantCurrent: "", wantRequestSent: false,
- },
+ {"newer numeric version", deployedVersion, deployedRevision, latestRelease, statusUpdateAvailable, latestRevision},
+ {"newer version of same source", deployedVersion, latestRevision, latestRelease, statusUpdateAvailable, latestRevision},
+ {"older version", "v2.0.0", deployedRevision, latestRelease, statusUpToDate, latestRevision},
+ {"same version and source", latestVersion, latestRevision, latestRelease, statusUpToDate, latestRevision},
+ {"same version with different source", latestVersion, deployedRevision, latestRelease, statusDifferentBuild, latestRevision},
+ {"development has an official choice", "development", deployedRevision, latestRelease, statusOfficialRelease, latestRevision},
+ {"development has same source", "development", latestRevision, latestRelease, statusUpToDate, latestRevision},
+ {"other unversioned build", "custom-build", deployedRevision, latestRelease, statusOfficialRelease, latestRevision},
+ {"local prerelease", "v1.10.0-rc.1", deployedRevision, latestRelease, statusUpdateAvailable, latestRevision},
+ {"newer version without known remote source", deployedVersion, deployedRevision, branchRelease, statusUpdateAvailable, ""},
+ {"same version without known remote source", latestVersion, deployedRevision, branchRelease, statusUpToDate, ""},
+ {"development without known remote source", "development", deployedRevision, branchRelease, statusUnavailable, ""},
+ {"newer version without known local source", deployedVersion, "", latestRelease, statusUpdateAvailable, latestRevision},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
- requested := false
- server := httptest.NewServer(http.HandlerFunc(
- func(writer http.ResponseWriter, request *http.Request) {
- requested = true
- if got := request.Header.Get("Accept"); got != "application/vnd.github+json" {
- t.Errorf("Accept = %q", got)
- }
- if got := request.Header.Get("X-GitHub-Api-Version"); got != "2022-11-28" {
- t.Errorf("X-GitHub-Api-Version = %q", got)
- }
- if got := request.Header.Get("User-Agent"); got != "Piik-release-check" {
- t.Errorf("User-Agent = %q", got)
- }
- writer.WriteHeader(testCase.status)
- _, _ = writer.Write([]byte(testCase.body))
- }))
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ if request.Header.Get("Accept") != "application/vnd.github+json" ||
+ request.Header.Get("X-GitHub-Api-Version") != "2022-11-28" || request.Header.Get("User-Agent") != "Piik-release-check" {
+ t.Error("release request headers changed")
+ }
+ _, _ = writer.Write([]byte(testCase.body))
+ }))
defer server.Close()
-
- result := checkRelease(t.Context(), testCase.current, server.URL, "")
- if requested != testCase.wantRequestSent {
- t.Fatalf("endpoint requested = %t; want %t", requested, testCase.wantRequestSent)
- }
- assertResult(t, result, testCase.wantStatus, testCase.wantCurrent,
- testCase.wantLatest, testCase.wantReleaseURL)
+ result := checkRelease(t.Context(), testCase.version, testCase.revision, server.URL, "", "")
+ assertResult(t, result, testCase.wantStatus, testCase.version, latestVersion, testCase.revision, testCase.wantLatest, latestReleaseURL)
})
}
}
func TestCheckReleaseFailsClosedWithoutAUsableEndpoint(t *testing.T) {
- redirect := httptest.NewServer(http.HandlerFunc(
- func(writer http.ResponseWriter, request *http.Request) {
- http.Redirect(writer, request, "https://evil.example/releases", http.StatusFound)
- }))
+ redirect := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ http.Redirect(writer, request, "https://evil.example/releases", http.StatusFound)
+ }))
defer redirect.Close()
- reachable := httptest.NewServer(http.HandlerFunc(
- func(writer http.ResponseWriter, _ *http.Request) {
- _, _ = writer.Write([]byte(latestRelease))
- }))
+ reachable := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ _, _ = writer.Write([]byte(latestRelease))
+ }))
defer reachable.Close()
-
+ unavailable := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ writer.WriteHeader(http.StatusServiceUnavailable)
+ }))
+ defer unavailable.Close()
+ malformed := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ _, _ = writer.Write([]byte(`{"tag_name":"v1","html_url":"https://evil.example"}`))
+ }))
+ defer malformed.Close()
cancelled, cancel := context.WithCancel(t.Context())
cancel()
- testCases := []struct {
- name string
- ctx context.Context
- apiURL string
+ for _, testCase := range []struct {
+ name, apiURL string
+ ctx context.Context
}{
- {"redirected endpoint", t.Context(), redirect.URL},
- {"unsupported scheme", t.Context(), "file:///etc/passwd"},
- {"relative endpoint", t.Context(), "releases/latest"},
- {"cancelled check", cancelled, reachable.URL},
- }
- for _, testCase := range testCases {
+ {"redirected endpoint", redirect.URL, t.Context()},
+ {"unsupported scheme", "file:///etc/passwd", t.Context()},
+ {"relative endpoint", "releases/latest", t.Context()},
+ {"cancelled check", reachable.URL, cancelled},
+ {"server unavailable", unavailable.URL, t.Context()},
+ {"unusable metadata", malformed.URL, t.Context()},
+ } {
t.Run(testCase.name, func(t *testing.T) {
- result := checkRelease(testCase.ctx, deployedRevision, testCase.apiURL, "")
- assertResult(t, result, "unavailable", deployedRevision, "", "")
+ result := checkRelease(testCase.ctx, deployedVersion, deployedRevision, testCase.apiURL, "", "")
+ assertResult(t, result, statusUnavailable, deployedVersion, "", deployedRevision, "", "")
})
}
+ result := checkRelease(t.Context(), "development", "unknown", "", "", "")
+ assertResult(t, result, statusUnavailable, "development", "", "", "", "")
}
func TestOperatorTokenReachesGitHubOnly(t *testing.T) {
- endpoints := []struct {
- name string
- url string
- token string
- authorized bool
+ for _, endpoint := range []struct {
+ name, url, token string
+ authorized bool
}{
{"github api", defaultReleaseAPIURL, "operator-token", true},
{"github api with padded token", defaultReleaseAPIURL, " operator-token ", true},
@@ -208,95 +180,143 @@ func TestOperatorTokenReachesGitHubOnly(t *testing.T) {
{"release host", "https://github.com/repos", "operator-token", false},
{"local fixture", "http://127.0.0.1:8787/releases/latest", "operator-token", false},
{"lookalike host", "https://api.github.com.evil.example/x", "operator-token", false},
- }
- for _, endpoint := range endpoints {
+ } {
t.Run(endpoint.name, func(t *testing.T) {
parsed, err := url.Parse(endpoint.url)
if err != nil {
t.Fatal(err)
}
if got := authorizesGitHub(parsed, endpoint.token); got != endpoint.authorized {
- t.Fatalf("authorizesGitHub(%q) = %t; want %t",
- endpoint.url, got, endpoint.authorized)
+ t.Fatalf("authorizesGitHub(%q) = %t; want %t", endpoint.url, got, endpoint.authorized)
}
})
}
var received http.Header
- fixture := httptest.NewServer(http.HandlerFunc(
- func(writer http.ResponseWriter, request *http.Request) {
- received = request.Header.Clone()
- _, _ = writer.Write([]byte(latestRelease))
- }))
+ fixture := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ received = request.Header.Clone()
+ _, _ = writer.Write([]byte(latestRelease))
+ }))
defer fixture.Close()
- checkRelease(t.Context(), deployedRevision, fixture.URL, "fixture-secret")
+ checkRelease(t.Context(), deployedVersion, deployedRevision, fixture.URL, "fixture-secret", "")
if authorization := received.Get("Authorization"); authorization != "" {
t.Fatalf("fixture endpoint received %q", authorization)
}
}
-func TestCheckDeployedReleasePrintsOneLineAndTheOperatorExitCode(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(
- func(writer http.ResponseWriter, _ *http.Request) {
- _, _ = writer.Write([]byte(latestRelease))
- }))
+func TestCheckDeployedReleaseUsesTheBinaryIdentityAndOperatorExitCode(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ _, _ = writer.Write([]byte(latestRelease))
+ }))
defer server.Close()
-
- testCases := []struct {
- name string
- revision string
- wantCode int
- wantJSON string
+ originalVersion, originalRevision := BuildVersion, BuildRevision
+ t.Cleanup(func() { BuildVersion, BuildRevision = originalVersion, originalRevision })
+ for _, testCase := range []struct {
+ name, version, revision, status string
+ code int
}{
- {
- "update available", deployedRevision + "\n", exitUpdateAvailable,
- `{"status":"update-available","currentRevision":"` + deployedRevision +
- `","latestRevision":"` + latestRevision +
- `","releaseUrl":"` + latestReleaseURL + `"}`,
- },
- {
- "up to date", latestRevision, exitUpToDate,
- `{"status":"up-to-date","currentRevision":"` + latestRevision +
- `","latestRevision":"` + latestRevision +
- `","releaseUrl":"` + latestReleaseURL + `"}`,
- },
- {
- "unreadable deployment", "", exitUpdateUnavailable,
- `{"status":"unavailable","currentRevision":null,` +
- `"latestRevision":null,"releaseUrl":null}`,
- },
- }
- for _, testCase := range testCases {
+ {"newer release", deployedVersion, deployedRevision, statusUpdateAvailable, exitUpdateAvailable},
+ {"different build", latestVersion, deployedRevision, statusDifferentBuild, exitUpdateAvailable},
+ {"official release", "development", deployedRevision, statusOfficialRelease, exitUpdateAvailable},
+ {"up to date", latestVersion, latestRevision, statusUpToDate, exitUpToDate},
+ {"unknown build", "development", "development", statusUnavailable, exitUpdateUnavailable},
+ } {
t.Run(testCase.name, func(t *testing.T) {
- currentFile := filepath.Join(t.TempDir(), "REVISION")
- if testCase.revision != "" {
- if err := os.WriteFile(currentFile, []byte(testCase.revision), 0o600); err != nil {
- t.Fatal(err)
- }
- }
+ BuildVersion, BuildRevision = testCase.version, testCase.revision
var out bytes.Buffer
- code := checkDeployedRelease(t.Context(), currentFile, server.URL, &out)
- if code != testCase.wantCode || out.String() != testCase.wantJSON+"\n" {
- t.Fatalf("checkDeployedRelease = %d, %q; want %d, %q",
- code, out.String(), testCase.wantCode, testCase.wantJSON+"\n")
+ code := checkDeployedRelease(t.Context(), server.URL, &out)
+ if code != testCase.code || strings.Count(out.String(), "\n") != 1 {
+ t.Fatalf("checkDeployedRelease = %d, %q; want code %d and one line", code, out.String(), testCase.code)
+ }
+ var result releaseResult
+ if err := json.Unmarshal(out.Bytes(), &result); err != nil {
+ t.Fatal(err)
+ }
+ if testCase.status == statusUnavailable {
+ assertResult(t, result, testCase.status, testCase.version, "", "", "", "")
+ } else {
+ assertResult(t, result, testCase.status, testCase.version, latestVersion, testCase.revision, latestRevision, latestReleaseURL)
}
})
}
}
-// assertResult compares the whole result through its JSON form so a value that
-// must be null is distinguished from one that is merely empty.
-func assertResult(t *testing.T, result releaseResult, status, current, latest, releaseURL string) {
+func TestMirrorFallbackUsesOriginalSourceAndCompleteStablePagination(t *testing.T) {
+ payload, err := os.ReadFile("../../tests/fixtures/mirror-releases.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var releases []json.RawMessage
+ if err := json.Unmarshal(payload, &releases); err != nil {
+ t.Fatal(err)
+ }
+ for i, raw := range releases {
+ _, revision, _, ok := parseMirrorReleaseMetadata(raw)
+ if ok != (i < 2) || (ok && revision != latestRevision) {
+ t.Fatalf("mirror fixture %d: accepted=%t revision=%s", i, ok, revision)
+ }
+ }
+ primaryAvailable, truncate := false, false
+ primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if primaryAvailable {
+ _, _ = w.Write([]byte(latestRelease))
+ } else {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }
+ }))
+ defer primary.Close()
+ mirrorCalls := 0
+ mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mirrorCalls++
+ if r.Header.Get("Authorization") != "" || r.Header.Get("X-GitHub-Api-Version") != "" ||
+ r.Header.Get("Accept") != "application/json" {
+ t.Error("mirror received credentials or GitHub headers")
+ }
+ if r.URL.Query().Get("per_page") != "100" || r.URL.Query().Get("direction") != "desc" {
+ t.Error("mirror pagination missing")
+ }
+ if r.URL.Query().Get("page") == "1" || truncate {
+ page := make([]json.RawMessage, 100)
+ for i := range page {
+ page[i] = releases[0]
+ }
+ _ = json.NewEncoder(w).Encode(page)
+ } else {
+ _, _ = w.Write(payload)
+ }
+ }))
+ defer mirror.Close()
+ result := checkRelease(t.Context(), deployedVersion, deployedRevision, primary.URL, "operator-secret", mirror.URL)
+ assertResult(t, result, statusUpdateAvailable, deployedVersion, latestVersion, deployedRevision, latestRevision, mirrorReleasePrefix+latestVersion)
+ if mirrorCalls != 2 {
+ t.Fatalf("mirror calls = %d", mirrorCalls)
+ }
+ result = checkRelease(t.Context(), "v2.0.0", deployedRevision, primary.URL, "", mirror.URL)
+ if result.Status != statusUpToDate {
+ t.Fatal("a lagging mirror offered a downgrade")
+ }
+ truncate = true
+ result = checkRelease(t.Context(), deployedVersion, deployedRevision, primary.URL, "", mirror.URL)
+ if result.Status != statusUnavailable {
+ t.Fatal("an incomplete mirror list was accepted")
+ }
+ primaryAvailable = true
+ mirrorCalls = 0
+ result = checkRelease(t.Context(), latestVersion, latestRevision, primary.URL, "", mirror.URL)
+ if result.Status != statusUpToDate || mirrorCalls != 0 {
+ t.Fatal("a usable primary release consulted the mirror")
+ }
+}
+
+func assertResult(t *testing.T, result releaseResult, status, currentVersion, latestVersion, currentRevision, latestRevision, releaseURL string) {
t.Helper()
payload, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
expected, err := json.Marshal(releaseResult{
- Status: status,
- CurrentRevision: reported(current),
- LatestRevision: reported(latest),
- ReleaseURL: reported(releaseURL),
+ Status: status, CurrentVersion: reported(currentVersion), LatestVersion: reported(latestVersion),
+ CurrentRevision: reported(currentRevision), LatestRevision: reported(latestRevision), ReleaseURL: reported(releaseURL),
})
if err != nil {
t.Fatal(err)
@@ -306,24 +326,9 @@ func assertResult(t *testing.T, result releaseResult, status, current, latest, r
}
}
-// reported turns the empty test expectation into the JSON null the result uses.
func reported(value string) *string {
if value == "" {
return nil
}
return &value
}
-
-// release-update.mjs parseArguments threw the usage string and set
-// process.exitCode = 2 when --current-file was absent, so the operator could
-// tell a forgotten argument from a check that could not reach GitHub.
-func TestCheckDeployedReleaseWithoutACurrentFileIsAUsageError(t *testing.T) {
- var out bytes.Buffer
- code := checkDeployedRelease(context.Background(), "", defaultReleaseAPIURL, &out)
- if code != exitUsage {
- t.Fatalf("exit code = %d, want %d", code, exitUsage)
- }
- if out.Len() != 0 {
- t.Fatalf("a usage error wrote %q, want no result line", out.String())
- }
-}
diff --git a/deploy/check-release.sh b/deploy/check-release.sh
index a800fd0a..148fc789 100644
--- a/deploy/check-release.sh
+++ b/deploy/check-release.sh
@@ -1,11 +1,9 @@
#!/bin/bash
set -Eeuo pipefail
-if [ "$#" -gt 1 ]; then
- printf 'usage: %s [current-revision-file]\n' "$0" >&2
+if [ "$#" -ne 0 ]; then
+ printf 'usage: %s\n' "$0" >&2
exit 2
fi
-current_file="${1:-/opt/piik/current/REVISION}"
-
-exec /opt/piik/current/piik-server --check-release --current-file "$current_file"
+exec /opt/piik/current/piik-server --check-release
diff --git a/deploy/nginx/share.bonfire.icu.conf.example b/deploy/nginx/piik.conf.example
similarity index 88%
rename from deploy/nginx/share.bonfire.icu.conf.example
rename to deploy/nginx/piik.conf.example
index c920c936..a0bfb3f5 100644
--- a/deploy/nginx/share.bonfire.icu.conf.example
+++ b/deploy/nginx/piik.conf.example
@@ -8,7 +8,7 @@ limit_req_zone $binary_remote_addr zone=piik_site_access:10m rate=5r/m;
server {
listen 80;
listen [::]:80;
- server_name share.bonfire.icu;
+ server_name share.example.com;
location ^~ /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
@@ -16,17 +16,17 @@ server {
}
location / {
- return 301 https://share.bonfire.icu$request_uri;
+ return 301 https://share.example.com$request_uri;
}
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
- server_name share.bonfire.icu;
+ server_name share.example.com;
- ssl_certificate /etc/letsencrypt/live/share.bonfire.icu/fullchain.pem;
- ssl_certificate_key /etc/letsencrypt/live/share.bonfire.icu/privkey.pem;
+ ssl_certificate /etc/letsencrypt/live/share.example.com/fullchain.pem;
+ ssl_certificate_key /etc/letsencrypt/live/share.example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
diff --git a/deploy/release-app.sh b/deploy/release-app.sh
index 9b4434a5..fe83d7d7 100644
--- a/deploy/release-app.sh
+++ b/deploy/release-app.sh
@@ -26,7 +26,8 @@ descriptor_text() {
sed -n "s|^ \"$1\": \"\([A-Za-z0-9._/-]*\)\",\{0,1\}\$|\1|p" "$descriptor"
}
-grep -qx ' "schema": 1,' "$descriptor"
+grep -qx ' "schema": 2,' "$descriptor"
+version="$(descriptor_text version)"
revision="$(descriptor_text revision)"
release_id="$(descriptor_text releaseId)"
artifact_name="$(descriptor_text artifact)"
@@ -37,6 +38,7 @@ file_count="$(sed -n 's|^ "fileCount": \([0-9]\{1,\}\),\{0,1\}$|\1|p' "$descrip
main_asset="$(descriptor_text mainAsset)"
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
+[[ "$version" = development || "$version" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]
[[ "$release_id" =~ ^[0-9a-f]{7}$ ]]
test "$release_id" = "${revision:0:7}"
test "$artifact_name" = "piik-${release_id}-runtime.tar.gz"
@@ -232,7 +234,8 @@ test -d "$release"
test ! -L "$release"
test "$(stat -c '%U:%G %a' "$release")" = 'root:root 755'
-firewall_before="$(nft list table inet bonfire_filter | sha256sum | awk '{print $1}')"
+# Compare rules without traffic counters; no operator-specific table name.
+firewall_before="$(nft --stateless list ruleset | sha256sum | awk '{print $1}')"
nginx_restarts="$(systemctl show nginx.service -p NRestarts --value)"
cutover_since="$(date '+%Y-%m-%d %H:%M:%S')"
cutover_start="$(date +%s%3N)"
@@ -249,7 +252,7 @@ health_ready="$(date +%s%3N)"
test "$(systemctl show piik.service -p ActiveState --value)" = 'active'
test "$(systemctl show piik.service -p NRestarts --value)" = '0'
test "$(systemctl show nginx.service -p NRestarts --value)" = "$nginx_restarts"
-test "$(nft list table inet bonfire_filter | sha256sum | awk '{print $1}')" = "$firewall_before"
+test "$(nft --stateless list ruleset | sha256sum | awk '{print $1}')" = "$firewall_before"
test "$(readlink -f -- "$current")" = "$release"
pid="$(systemctl show piik.service -p MainPID --value)"
test "$pid" -gt 1
diff --git a/docs/README.md b/docs/README.md
index c012a176..1b7e90ca 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,32 +1,36 @@
-# Documentation
+# Piik Documentation
-[English Quick Start](../README.md) · [中文快速开始](../README.zh-CN.md)
+[About Piik](../README.md) · [中文介绍](../README.zh-CN.md) · [中文上手指南](./guide/getting-started.zh-CN.md)
-## Use Piik
+## Guides And References
-| What you need | Start here |
+| Task | Guide |
| --- | --- |
-| Join a friend or share a screen | [Quick Start](../README.md) |
-| Run App, choose a mode, or fix capture trouble | [App guide](../cmd/piik-app/README.md) |
-| Collect a useful bug report | [Diagnostics and export](./reference/configuration.md#diagnostics) |
-| Host your own site | [Self-hosting](./operations/self-hosting.md) |
-| Configure ports, access or persistence | [Configuration reference](./reference/configuration.md) |
-| Update an existing deployment | [Deployment and recovery](./deployment.md) |
-| Check platform and release readiness | [Current status](./status.md) |
-
-The public entry points have English and Chinese versions. Technical references
-keep one owner rather than duplicate the full documentation tree.
-
-Contributors should follow the [naming convention](./reference/naming.md) for
-display names, commands, packages and App/Server/Browser code boundaries.
+| Try the online demo | [Online demo](https://demo.piik.tv) · [Demo steps](./guide/getting-started.md#try-the-online-demo) |
+| Watch a friend or share my first screen | [Getting started](./guide/getting-started.md) |
+| Choose an App mode or fix sound and connection trouble | [First-use help](./guide/getting-started.md#choose-an-app-mode) |
+| Run Piik App, check platform requirements, or build a package | [App guide](../cmd/piik-app/README.md) |
+| Try or change the source code | [Run from source](#run-from-source) |
+| Find a directory or the module responsible for a behavior | [Repository layout and module map](./reference/engineering.md#repository-layout) |
+| Host a site for my group | [Self-hosting](./operations/self-hosting.md) · [中文部署](./operations/self-hosting.zh-CN.md) |
+| Keep a server running with systemd or Docker | [Service management](./operations/service-management.md) |
+| Set passwords, ports, or room storage | [Configuration](./reference/configuration.md) |
+| Update my server | [Server updates](./operations/self-hosting.md#keep-it-running-and-update) |
+| Build, publish or recover a maintained release | [Maintainer release tooling](./deployment.md) |
+| Send a useful bug report | [Diagnostics and export](./reference/configuration.md#diagnostics) |
+| Check release and platform readiness | [Current status](./status.md) |
+
+The introduction, getting-started and self-hosting guides are available in English and Chinese.
+Technical references keep one shared version.
## Run from source
-Use Node from [.node-version](../.node-version), npm from
-[package.json](../package.json), and Go 1.26 as specified by [go.mod](../go.mod).
-Node builds and serves the development UI; the application server runs in Go.
+You can try the Browser application locally with Node from
+[.node-version](../.node-version), npm from
+[package.json](../package.json), and Go 1.26 from [go.mod](../go.mod).
+Run these commands from the repository root.
-Start the UI:
+Start the web UI:
```sh
npm ci
@@ -49,49 +53,58 @@ go build -o build/dev/piik-server.exe ./cmd/piik-server
```
The fixed Windows executable path avoids repeated firewall prompts from `go run`.
+Open [localhost:8787](http://localhost:8787), start sharing, and open the invitation
+in another browser tab to try watching. This localhost invitation stays on your
+computer; remote invitations need a reachable origin as described in
+[configuration](./reference/configuration.md).
+Browser capture requires `localhost` or HTTPS.
-Open `http://localhost:8787`. The development UI also listens on the LAN;
-screen capture requires `localhost` or HTTPS. For another invitation origin,
-follow the [configuration reference](./reference/configuration.md).
+For the self-contained App, follow [App development](../cmd/piik-app/README.md#development)
+and [packaging](../cmd/piik-app/README.md#packaging), including the platform's
+native capture requirements.
-The standard checks are:
+## Work on Piik
+
+[Contributing](../CONTRIBUTING.md) covers the workflow and choosing focused checks.
+The main verification commands are:
```sh
npm run check
npm run check:client
```
-The [contributing guide](../CONTRIBUTING.md#verification-entrypoints) explains
-native build prerequisites, focused checks and separate physical gates.
-
-## Product and design
+Use the [naming and copy guide](./reference/naming.md) for product names,
+commands, role labels and Chinese/English voice.
+Piik-owned code uses [MIT](../LICENSE); see the
+[licensing guide](../licenses/README.md) for third-party components.
-Current behavior belongs to four product modules:
+For the public website, see the [introduction design](./design/public-introduction.md)
+and [website preview and publishing](./operations/website.md).
-- [Rooms and access](./product/rooms-access.md)
-- [Routing and transport](./product/routing-transport.md)
-- [Capture, audio and media quality](./product/media-quality.md)
-- [Presentation and lifecycle](./product/presentation-lifecycle.md)
+## Understand the product
-Key decisions cover [automatic routing](./adr/0005-automatic-hybrid-media-routing.md),
-the [shared Go core](./adr/0012-shared-go-backend-core.md),
-[embedded media and Native output groups](./adr/0013-embedded-node-local-media.md),
-and the [Browser encoding-pool candidate](./adr/0014-browser-node-local-encoding-pool.md).
-Browse [all ADRs](./adr/) for their context and consequences.
-
-## Evidence and current work
+| Topic | Its reference |
+| --- | --- |
+| Invitations, room codes and passwords | [Rooms and access](./product/rooms-access.md) |
+| How viewers connect | [Routing and transport](./product/routing-transport.md) |
+| Screen capture, quality controls and sound | [Media quality](./product/media-quality.md) |
+| Host and viewer behavior | [Presentation and lifecycle](./product/presentation-lifecycle.md) |
+| Why a design was chosen | [Architecture decisions](./adr/) |
+| Measurements and platform limits | [Research](./research/) and [verification status](./verification-status.md) |
-- [Project memory](./project-memory.md): compact product map and invariants.
-- [Status](./status.md): current source, production and acceptance boundaries.
-- [TODO](./todo.md): the only work ledger.
-- [Verification status](./verification-status.md): remaining physical evidence.
-- [Native encoding research](./research/webrtc-encoder-pool.md) and
- [Browser pooling research](./research/browser-local-encoding-pool.md): measured
- results, failed controls and limits; neither promises universal performance.
-- [Research directory](./research/): transport, capture, platform and backend evidence.
-- [Maintenance](./maintenance.md): document ownership and repository lifecycle.
-- [Licensing](../licenses/README.md): Piik's MIT scope and third-party notices.
+## Shared conventions
-Research distinguishes observations from assumptions. Product modules own
-accepted behavior, source and tests own implementation detail, and Git/PRs own
-completed history.
+| When changing… | Follow this owner |
+| --- | --- |
+| Module responsibilities or interfaces | [Engineering and contract map](./reference/engineering.md) |
+| Product/tool names, role labels or copy | [Naming and copy](./reference/naming.md) |
+| UI colour, illustration, motion or layout | [Visual language](./design/visual-language.md) |
+| Overlays, titles or state indicators | [Media status](./design/media-status.md) |
+| Releases, protocols or stored formats | [Versions and compatibility](./reference/versioning.md) |
+| Main protection or automatic publishing | [GitHub operations](./operations/github.md) |
+| Documentation or a duplicated rule | [Documentation ownership](./maintenance.md) |
+| Checks, PRs, integration or cleanup | [Contributing](../CONTRIBUTING.md) |
+
+For ongoing work, use [TODO](./todo.md). [Project memory](./project-memory.md)
+provides the compact product map; [status](./status.md) indexes current source
+and deployment boundaries. Completed work lives in Git history and pull requests.
diff --git a/docs/adr/0001-p2p-first-media-topology.md b/docs/adr/0001-p2p-first-media-topology.md
index 0b8e7022..a0b6e386 100644
--- a/docs/adr/0001-p2p-first-media-topology.md
+++ b/docs/adr/0001-p2p-first-media-topology.md
@@ -25,7 +25,7 @@ browser-first product surface but did not establish a sustainable fanout,
fallback order, or server-resource policy.
The MVP explicitly excluded always-SFU conferencing, public-broadcast scaling,
-MCU transcoding, and a custom Parsec-like transport. Those workloads either
+MCU transcoding, and a custom low-latency media transport. Those workloads either
contradict the private-room cost model or duplicate mature WebRTC capabilities.
## Current Ownership
diff --git a/docs/adr/0009-optional-nat-prediction.md b/docs/adr/0009-optional-nat-prediction.md
index 5f6ff429..98d8c765 100644
--- a/docs/adr/0009-optional-nat-prediction.md
+++ b/docs/adr/0009-optional-nat-prediction.md
@@ -107,6 +107,8 @@ RTP packets to an independent Linux Pion Viewer over a selected direct
host-to-srflx pair. This proves the shared-socket candidate carries DTLS-SRTP;
the tested TUN network exposed only one distinct public mapping, so it does not
prove a predicted candidate win.
+Survey inputs, platform limits and the measured boundaries live in
+[NAT traversal research](../research/nat-traversal.md).
The current Native path maps selected Pion candidate foundations to the same
anonymous `ordinary | predicted | unknown` evidence as Browser ICE.
diff --git a/docs/adr/0012-shared-go-backend-core.md b/docs/adr/0012-shared-go-backend-core.md
index 0bb496eb..a60ee8d0 100644
--- a/docs/adr/0012-shared-go-backend-core.md
+++ b/docs/adr/0012-shared-go-backend-core.md
@@ -56,18 +56,19 @@ the same Browser build.
stay synchronous inside the lock and keep the current fail-fast storage
policy: an unrecoverable authority write ends the process instead of
continuing on divergent state.
-6. LiveKit access uses the standard library: HS256 participant and service tokens
- plus Twirp JSON RoomService calls over `net/http`, with the current grants,
- bounded per-request timeout, per-managed-room serialization, and not-found
- rule. No LiveKit SDK is added.
+6. Superseded by [ADR-0013](./0013-embedded-node-local-media.md): the port initially
+ used standard-library tokens and Twirp calls for external LiveKit. Current
+ App/Server media adapters share embedded Pion/LiveKit forwarding and the
+ authenticated room signaling path; that external service/token layer is gone.
7. Room persistence uses the pure-Go `modernc.org/sqlite` driver over the schema,
pragmas, single exclusive connection, and recovery accepted in
[ADR-0002](./0002-memory-resident-protected-rooms.md). Both storage modes,
their validation, and their failure policy are unchanged, and no build
requires a C toolchain.
-8. The port changed no contract. Signaling stayed on its then-current v21 wire; the App
- loopback stays v8, capture framing stays v4, and the HTTP API, cookies, error
- codes, and close codes keep their exact shapes. No compatibility alias, dual
+8. The port changed no contract. At that boundary signaling was v21, App loopback
+ v8 and the capture probe v4; the HTTP API, cookies, error codes and close codes
+ retained their shapes. [Status](../status.md#accepted-release-contract) owns
+ the current contract tuple. No compatibility alias, dual
reader, or migration is added for a change of implementation language.
## Consequences
@@ -91,7 +92,7 @@ the same Browser build.
production host need no Node; [deployment](../deployment.md) owns their exact
commands.
- Development runs two processes: the Vite dev server for the Browser bundle and
- the Go application server behind it. The [README](../../README.md) owns those
+ the Go application server behind it. The [development guide](../README.md#run-from-source) owns those
commands.
- ADR-0010 items 1, 5, 7, 12 (its supervisor sentence), 13, 14, and its
two-internal-process consequence are superseded and amended in place. The rest
diff --git a/docs/adr/0013-embedded-node-local-media.md b/docs/adr/0013-embedded-node-local-media.md
index a7845cbc..7e3012e2 100644
--- a/docs/adr/0013-embedded-node-local-media.md
+++ b/docs/adr/0013-embedded-node-local-media.md
@@ -120,3 +120,4 @@ is introduced.
- [RTP switching and source projection, RFC 7667](https://www.rfc-editor.org/rfc/rfc7667)
- [LiveKit demand envelope](https://github.com/livekit/livekit/blob/v1.13.6/pkg/rtc/dynacast/dynacastmanagervideo.go)
- [Implementation proposal and reuse map](../research/node-local-media-design.md)
+- [Embedded media evaluation](../research/embedded-media.md)
diff --git a/docs/assets/quickstart.svg b/docs/assets/quickstart.svg
new file mode 100644
index 00000000..d94aaac4
--- /dev/null
+++ b/docs/assets/quickstart.svg
@@ -0,0 +1,63 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="900" height="192" viewBox="0 0 900 192" role="img" aria-labelledby="title desc">
+ <title id="title">Pick a screen, send an invitation, watch together</title>
+ <desc id="desc">Three illustrated steps: choose a window, send its room invitation, and join friends on the sofa. Each loop pauses to let the scene settle.</desc>
+ <style>
+ :root { --drawing:#22303e; --panel:#fafaf3; --line:#c6d6cc; --label:#256b47; --art-mint:#c4e3ce; --art-paper:#fffdf4; --art-blue:#a2c8e8; --art-yellow:#f5d37a; --art-orange:#ee8955; --art-pink:#e9b1bb; --couch:#edbb72; --couch-dark:#d99a56; }
+ @media (prefers-color-scheme:dark) { :root { --panel:#1b2d34; --line:#3b5155; --label:#9bdbb2; } }
+ text { fill:var(--label); font:600 13px system-ui,sans-serif; letter-spacing:2px; }
+ @media (prefers-reduced-motion:no-preference) {
+ g[class] { transform-box:fill-box; transform-origin:center; }
+ .screen-cursor { animation:choose-screen 6.4s ease-in-out infinite both; }
+ .chosen-window { animation:window-response 6.4s ease-in-out infinite both; }
+ .invite-plane { animation:send-invite 6.4s ease-in-out .2s infinite both; }
+ .invite-note { animation:note-response 6.4s ease-in-out .2s infinite both; }
+ .sofa-friend { animation:take-a-seat 6.4s ease-out .4s infinite both; }
+ .sofa-friend + .sofa-friend { animation-delay:.52s; }
+ }
+ @keyframes choose-screen {
+ 0%, 8%, 48%, 100% { transform: none; }
+ 22%, 34% { transform: translate(-62px, -19px); }
+ 28% { transform: translate(-62px, -19px) scale(.85); }
+}
+@keyframes window-response { 0%, 22%, 46%, 100% { transform: none; } 30% { transform: scale(1.07); } 38% { transform: scale(.99); } }
+@keyframes send-invite {
+ 0%, 6%, 48%, 100% { transform: none; opacity: 1; }
+ 12% { transform: translate(-4px, 3px) rotate(7deg); opacity: 1; }
+ 32% { transform: translate(42px, -36px) rotate(-12deg); opacity: 0; }
+ 33% { transform: translate(-8px, 8px); opacity: 0; }
+}
+@keyframes note-response { 0%, 10%, 42%, 100% { transform: none; } 20% { transform: translateY(1px) rotate(-4deg); } 32% { transform: rotate(1deg); } }
+@keyframes take-a-seat { 0% { transform: translateY(-8px); } 22% { transform: translateY(2px); } 32%, 100% { transform: none; } }
+ </style>
+ <g transform="translate(0 2)">
+ <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--panel)" stroke="var(--line)" stroke-width="1.5"/>
+ <text x="20" y="28">01</text>
+ <g transform="translate(15 40)"><g fill="none" stroke="var(--drawing)" stroke-width="3" stroke-linejoin="round">
+ <rect x="47" y="17" width="141" height="90" rx="12" fill="var(--art-mint)"/><path d="M105 108v14m-20 0h65"/>
+ <g class="chosen-window"><rect x="64" y="31" width="64" height="57" rx="7" fill="var(--art-paper)"/><path d="m79 76 12-15 9 7 12-19"/></g>
+ <rect x="137" y="31" width="34" height="23" rx="5" fill="var(--art-blue)"/><rect x="137" y="64" width="34" height="24" rx="5" fill="var(--art-yellow)"/>
+ <g class="screen-cursor"><path d="m172 82 3 33 9-8 8 13 9-5-8-13 11-2Z" fill="var(--art-orange)"/></g>
+ </g><path d="m33 35-8-4m12-8-4-8m169 22 9-5" stroke="var(--drawing)" stroke-width="3" stroke-linecap="round"/></g>
+ </g>
+ <g transform="translate(310 2)">
+ <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--panel)" stroke="var(--line)" stroke-width="1.5"/>
+ <text x="20" y="28">02</text>
+ <g transform="translate(15 40)"><g stroke="var(--drawing)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
+ <g class="invite-note"><rect x="44" y="31" width="143" height="73" rx="16" fill="var(--art-paper)" transform="rotate(-5 115 67)"/><path d="m80 77-6-6a13 13 0 0 1 0-18l10-10a13 13 0 0 1 18 0l6 6m-10 8 6 6a13 13 0 0 1 0 18L94 91a13 13 0 0 1-18 0l-6-6m11-10 16-16" fill="none"/><path d="M125 58h38m-38 15h24"/></g>
+ <circle cx="191" cy="96" r="25" fill="var(--art-blue)"/><g class="invite-plane"><path d="m174 94 34-12-12 33-7-14Z" fill="var(--art-paper)"/><path d="m189 101 8-9"/></g>
+ <path class="invite-spark" d="M190 24v10m-5-5h10M33 93v8m-4-4h8"/>
+ </g></g>
+ </g>
+ <g transform="translate(620 2)">
+ <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--panel)" stroke="var(--line)" stroke-width="1.5"/>
+ <text x="20" y="28">03</text>
+ <g transform="translate(15 40)"><g stroke="var(--drawing)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M55 112v9m139-9v9"/><rect x="46" y="63" width="157" height="50" rx="17" fill="var(--couch)" stroke="none"/>
+ <g class="sofa-friend"><g fill="var(--art-blue)" stroke="none"><circle cx="99" cy="39" r="12"/><path d="M78 88c0-19.5 7.5-30 21-30s21 10.5 21 30q0 4.5-4.5 4.5h-33Q78 92.5 78 88Z"/></g><path d="M95 39v1m8-1v1"/></g>
+ <g class="sofa-friend"><g fill="var(--art-pink)" stroke="none"><circle cx="150" cy="37" r="12"/><path d="M129 88c0-19.5 7.5-30 21-30s21 10.5 21 30q0 4.5-4.5 4.5h-33Q129 92.5 129 88Z"/></g><path d="M146 37v1m8-1v1"/></g>
+ <path d="M125 99v10M46 73h18a10 10 0 0 1 10 10v26m129-36h-18a10 10 0 0 0-10 10v26" fill="none" stroke="var(--couch-dark)"/>
+ <g class="sofa-spark"><path d="m185 20 3 8 8 3-8 3-3 8-3-8-8-3 8-3Z" fill="var(--art-yellow)"/></g>
+ </g></g>
+ </g>
+ <path d="M288 102h15m-5-5 5 5-5 5m300-5h15m-5-5 5 5-5 5" fill="none" stroke="var(--label)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/docs/assets/room-en-dark.png b/docs/assets/room-en-dark.png
new file mode 100644
index 00000000..39b41717
Binary files /dev/null and b/docs/assets/room-en-dark.png differ
diff --git a/docs/assets/room-en-light.png b/docs/assets/room-en-light.png
new file mode 100644
index 00000000..84d778e7
Binary files /dev/null and b/docs/assets/room-en-light.png differ
diff --git a/docs/assets/room-zh-dark.png b/docs/assets/room-zh-dark.png
new file mode 100644
index 00000000..3b79ae48
Binary files /dev/null and b/docs/assets/room-zh-dark.png differ
diff --git a/docs/assets/room-zh-light.png b/docs/assets/room-zh-light.png
new file mode 100644
index 00000000..bedfc10d
Binary files /dev/null and b/docs/assets/room-zh-light.png differ
diff --git a/docs/deployment.md b/docs/deployment.md
index cf157889..2c9270cf 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -12,6 +12,9 @@ media, bare-metal nginx, nftables, and application port 8787. It requires an
existing running Go release. Another proxy, firewall owner, application port,
first installation, or initial embedded-media cutover needs its own scoped
bootstrap/updater; do not call this wrapper generic.
+Its firewall check compares the nftables ruleset without traffic counters; it
+does not depend on a particular table name. Coordinate other firewall writers
+outside the cutover window. See [nft output options](https://netfilter.org/projects/nftables/manpage.html).
## Release Boundary
@@ -95,11 +98,12 @@ Retain the descriptor and successful deployment output as release metadata. Do
not create a follow-up source commit solely to duplicate their revision, asset,
or hashes.
-After `validate` succeeds on an explicit workflow dispatch with
-`client_checks=true`, CI packages the Server application release and the
-three-platform App candidates that consume it. The artifacts are retained
-for 14 days. Ordinary `main` pushes do not run these packaging jobs. This
-workflow does not create a tag, public GitHub Release, or deployment.
+Manual `client_checks=true` dispatch packages Server and three-platform App
+candidates after validation. Once [automatic publication](./operations/github.md)
+is explicitly enabled, accepted main merges run that same pipeline and publish
+the verified artifacts. Candidate artifacts are retained for 14 days. Branches
+and PRs do not start cloud CI; no release-record commit is written back to main.
+The workflow does not deploy into a running application service.
Do not build or run the full repository check on a constrained production host.
That host runs only the packaged binary and needs no Node, npm, or dependency
@@ -107,15 +111,19 @@ install.
## Update Check
-The application, Server deployment, and platform App all use the full Git
-revision as their release identity. A formal GitHub Release must use that exact
-40-character revision as its tag and keep the corresponding release URL. The
-current CI workflow produces short-lived candidates but does not publish a
-GitHub Release; publication remains an explicit distribution decision.
-
-The default App launcher starts immediately, then performs one background
-request to the official Piik GitHub Releases API. It shows a link only when
-the latest release has a valid full revision different from the packaged one.
+Builds carry a product version plus full source revision. Packagers use one
+release plan or exact Git tag and inject its identity into Server, App and Web;
+untagged local candidates use `development`. Schema-2 package descriptors carry
+the same pair and artifact hashes. The [version policy](./reference/versioning.md)
+owns ordering and first-public-release readiness.
+
+The default App launcher starts immediately, then checks GitHub Releases in the
+background, falling back to the Gitee mirror if GitHub is unavailable. The
+[release-source policy](./reference/versioning.md#release-sources) owns selection
+and provenance checks. It shows a link only when
+the latest stable release is newer, the same version has a known different source
+SHA, or a development build can choose the official release. These notices are
+distinct; a different SHA alone is not called newer.
The request sends no current revision, credentials, room data, or media data;
network errors, private-repository responses, and missing releases are treated
as no notice. It never downloads, replaces, or interrupts a running share.
@@ -126,62 +134,26 @@ An operator can perform the corresponding read-only Server check:
bash deploy/check-release.sh
```
-The script runs the deployed binary's release check, which reads
-`/opt/piik/current/REVISION` and prints one JSON result.
-Exit status `0` means the deployed revision is current, `10` means a newer
-release is available, and `20` means the check could not establish a valid
-release identity. For a private repository, inject a short-lived `GITHUB_TOKEN`
+The Server also checks once in the background after startup and logs an available
+release with its download URL. It does not delay startup, periodically poll,
+notify room participants or install anything.
+
+The script runs the deployed binary's `--check-release`, using that binary's
+injected identity, and prints one JSON result with versions, available source
+SHAs and the release URL. Exit `0` means no newer/different official build,
+`10` means `update-available`, `different-build` or `official-release`, and `20`
+means the check is unavailable. It does not accept a separate revision file.
+For a private repository, inject a short-lived `GITHUB_TOKEN`
through the operator environment; never place it in the repository or command
line. The command does not mutate files, services, containers, or persistent
-state. A different current-revision file may be supplied as its only argument.
-
-## Permanent-Room Schema Cutover
-
-The schema 2 / signaling v23 cutover required matching Web/App/Server builds
-and an accepted active-session interruption. Native control stayed v9; that
-schema change preserved Browser credential keys. It was not an app-only release.
-The separate [brand cutover](./research/piik-rename-plan.md) must preserve this
-database rather than repeat the schema change.
-
-1. Verify the candidate; record the current release, environment, absolute DB
- path and ownership. Stop ingress and the old application; take and retain a
- SQLite backup. Require `application_id=1396920910`, `user_version=1`, expected
- columns and `PRAGMA quick_check='ok'` before touching a separate protected copy.
-2. On that copy, use SQLite with `DROP COLUMN` support and stop on SQL errors:
-
- ```sql
- BEGIN EXCLUSIVE;
- ALTER TABLE rooms DROP COLUMN lease_expires_at_ms;
- PRAGMA user_version = 2;
- COMMIT;
- ```
-
-3. Verify integrity, exact columns/version and equal row counts. Compare retained
- columns in both directions against the backup using `EXCEPT`; both must be
- empty. Record only counts/pass/fail, not private verifiers. The candidate must
- open this copy successfully; no room is dropped because of its former deadline.
-4. Retain the absolute `ROOM_DATABASE_PATH`; remove `ROOM_LEASE_SECONDS`. Install
- the verified copy and release while stopped, retaining permissions/ownership.
- Start; check health and Host/Viewer reauthentication before reopening ingress.
-5. On failure, stop and restore prior database, environment and release together.
- Once new authority mutations are accepted, restoring the backup could revive
- revoked grants: preserve those changes or make an explicit recovery decision.
-
-The runtime reads only schema 2. SQLite's [column removal](https://www.sqlite.org/lang_altertable.html#altertabdropcol)
-and [backup guidance](https://www.sqlite.org/backup.html) define this offline operation.
+state.
## Atomic Cutover
-### First embedded-media cutover prerequisite
-
-The first move from external services to embedded STUN/SFU is a coordinated
-infrastructure and protocol transaction, including Node-to-Go where still
-needed. Complete the [self-hosting cutover procedure](./operations/self-hosting.md#coordinated-embedded-media-cutover)
-with matching Web/Server signaling and native protocol v9 App builds,
-accepted active-session interruption, released UDP ports, and exact
-unit/environment/proxy/service recovery. The routine wrapper does not perform
-that transaction; it requires an already running packaged Go release and cannot
-restore the previous infrastructure.
+The wrapper requires an already running packaged Go release and the service
+layout described above. For a new installation, use the
+[self-hosting guide](./operations/self-hosting.md). Infrastructure changes need
+their own scoped recovery procedure under [CONTRIBUTING](../CONTRIBUTING.md).
Run the tracked server entry with the uploaded descriptor:
@@ -249,3 +221,8 @@ operator intervention; it must not silently report the new release as active.
Infrastructure or persistent-state recovery is separate and limited to the
surfaces changed by that task. Do not restore an entire server, old firewall, or
old secret set for an application-only failure.
+
+If a task changes persistent room data, prepare and verify a separate
+[SQLite backup](https://www.sqlite.org/backup.html) and recover matching data,
+configuration and application together. Restoring old data can revive revoked
+credentials; account for later authority changes before reopening ingress.
diff --git a/docs/design/media-status.md b/docs/design/media-status.md
new file mode 100644
index 00000000..edaf5452
--- /dev/null
+++ b/docs/design/media-status.md
@@ -0,0 +1,113 @@
+# Media Status
+
+`src/client/ui/media-status.ts` owns the shared visual projection, demonstrated
+by `/__status-preview`. It is not a routing or quality controller. The existing
+presentation reducer continues to own playback facts; roster and quality
+evidence retain their own authority. Overlay, indicators, notices and title are
+consumers, not truth sources.
+
+Frontend controls, names and details share `Tooltip`, following the
+[visual language](./visual-language.md). Its native Popover top layer escapes scrolling
+containers, with viewport-relative placement. Hover, keyboard focus and touch
+hold share one visibility owner; Escape dismisses even a mouse-only hint.
+`/__tooltip-preview` shows the catalogue. Playback actions and their local audio
+ownership are defined in [presentation lifecycle](../product/presentation-lifecycle.md#playback-ownership);
+`/__playback-preview` exercises the actual control bar with generated local media.
+
+## Status Meaning
+
+Keep three questions separate: is the media path available, is this picture
+playing, and is this particular stream limited? An available path does not
+prove excellent quality. One weak child does not make its parent's received
+picture or a healthy sibling unhealthy.
+
+The shared [visual language](./visual-language.md) owns colours, cast, shapes,
+panel accents and motion. This document owns the evidence and scope that select
+those meanings. Current `StatusDescriptor` tone and progress take precedence
+over a reused comic's default; text and pure-visual tooltips retain that context.
+
+## Projection Rules
+
+- Overlay: appears when there is no usable picture, an intentional Host pause,
+ or a required user action. Ordinary quality warnings never cover playback.
+ Initial connection guidance is not an error even though it occupies the stage.
+- Television: one media-status icon sits inside the lower television frame
+ (`lr-tv-chin`). Visual mode explains it with the existing comic tooltip;
+ text modes expose the specific localized status in the same paper tooltip.
+ Both reuse `Tooltip` for hover, keyboard focus, touch hold and viewport
+ placement; no native `title` competes with the custom status hint. There is no
+ permanent text bubble, additional round lamp, or repeated control-menu caption.
+ The Host television describes its local source, not an arbitrary outbound
+ child. A confirmed limitation may colour the relevant icon amber while the
+ page title still says watching.
+- Host couch: each Viewer has one round lamp. Grey means waiting for the share,
+ blue means waiting for the media path, green means committed `mediaReady`, and
+ amber means a recent receive freeze. The Host's own pawn has no duplicate
+ lamp. `deriveParticipantStatus` supplies both the couch and Host overview;
+ neither stores another copy of the status.
+- Viewer couch: pawns have no round lamps. While awaiting media readiness a
+ pawn's body breathes gently; it becomes still when ready. This expresses the
+ same roster fact without claiming to know other Viewers' quality.
+- Header: the page's connection to the room server. Its control-link comics
+ show a Browser and server, not a failed video path. A media-route failure can
+ coexist with a healthy server connection, and vice versa.
+- Connection notice: signaling recovery may coexist with healthy media. It
+ cannot convert proved playback into waiting.
+- Notices: necessary coexisting issues and operation feedback use the existing
+ pills near the stage; they are not another primary media status. Raw
+ PeerConnection errors remain diagnostic observations, not persistent red
+ warnings after media recovers. The control menu does not repeat the television
+ status or aggregate the first weak outbound edge into a global quality warning.
+- Title: keeps the primary activity, with a compact warning for an applicable
+ problem. Losing focus alone never means waiting for media.
+- Recovery: every projection is recomputed from current facts. A warning requires
+ current evidence; an expired or mismatched sample becomes unknown, not healthy
+ or disconnected. A ready participant can therefore return to a green readiness
+ lamp without claiming that its quality has recovered. No warning latch or
+ additional timer is needed.
+
+## Evidence And Integration Boundary
+
+Use WebRTC `connectionState` for transport explanation, not first-frame proof.
+`disconnected` may recover; `failed` is terminal for that connection. Closing a
+retired connection is not an error in the replacement connection.
+`qualityLimitationReason` describes an **outbound** encoder. A relay's sender
+warning must never become a warning about its own inbound picture. Low FPS,
+resolution or bitrate alone does not prove poor quality; a static screen or a
+small source can legitimately need little data. Do not introduce UI thresholds
+or a new quality score.
+
+Current roster messages expose committed `mediaReady` to both roles, not a
+complete remote quality/failure state. Missing readiness means waiting or
+recovery, not confirmed disconnection; departed participants leave the roster.
+Viewer receive evidence is shared with its parent and the Host, not with every
+other Viewer. No additional remote-quality broadcast is needed.
+
+The Host's amber participant lamp requires an active share, committed readiness,
+fresh receive evidence for the current upstream, and a positive
+`freezeCountDelta` or `freezeDurationMsDelta`. The existing evidence-expiry path
+clears stale warnings. Hidden, paused and other diagnostic-only windows provide
+no freeze proof; low FPS, resolution or bitrate is not a substitute.
+
+All `*Delta` metrics describe one observation window and never inherit an older
+non-null value. Non-window fields retain the existing details-display cache.
+Participant status reads the current evidence directly; it adds no stored
+status, timer, threshold or score. Detailed sender/receiver metrics
+remain available in connection details and Debug with their original scope.
+
+The preview labels supplied example quality facts for the displayed stream.
+Examples do not authorize guessing unavailable production facts.
+
+## References
+
+- [W3C WebRTC connection states](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnectionstate):
+ transport lifecycle is distinct from receiving and presenting media.
+- [W3C WebRTC statistics](https://www.w3.org/TR/webrtc-stats/#dom-rtcoutboundrtpstreamstats-qualitylimitationreason):
+ native `none`, `bandwidth`, `cpu`, `other` describe outbound limitations.
+- [LiveKit connection quality](https://docs.livekit.io/intro/basics/rooms-participants-tracks/webhooks-events/#connection-quality):
+ quality and connection events are separate; unknown is an explicit value.
+- [LiveKit reconnection](https://docs.livekit.io/intro/basics/connect/#network-changes-and-reconnection):
+ transient signaling/media recovery does not always interrupt the picture.
+
+We reuse these distinctions and the existing Piik owners, not a new SDK, scoring
+algorithm or transport policy.
diff --git a/docs/design/piik-brand.html b/docs/design/piik-brand.html
deleted file mode 100644
index d7f10e20..00000000
--- a/docs/design/piik-brand.html
+++ /dev/null
@@ -1,239 +0,0 @@
-<!doctype html>
-<html lang="en">
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<meta name="color-scheme" content="light dark">
-<title>Piik · Brand study / 品牌预览</title>
-<style>
- :root { color-scheme: light; --wall:#e9f2ee; --wall2:#dcebe4; --ink:#22303e; --paper:#fff; --orange:#e4572e; --green:#1f7a4a; --spark:#d08a22; }
- :root[data-theme="dark"] { color-scheme:dark; --wall:#141e29; --wall2:#0e1620; --ink:#dde8f3; --paper:#22303e; --green:#9de8bf; --spark:#f4c14d; }
- * { box-sizing:border-box; }
- body { margin:0; background:var(--wall); color:var(--ink); font:16px/1.55 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif; }
- a { color:inherit; text-underline-offset:3px; }
- main { max-width:1100px; margin:auto; padding:28px 28px 44px; }
- header, .controls, .section-head, .card-heading, footer { display:flex; align-items:center; justify-content:space-between; gap:16px; }
- header { padding-bottom:27px; border-bottom:1px solid color-mix(in srgb,var(--ink) 18%,transparent); }
- .identity { display:flex; align-items:center; gap:10px; font-weight:750; letter-spacing:-.03em; }
- .identity svg { width:32px; height:32px; }
- .eyebrow, .number, .small-label { font-size:12px; font-weight:650; letter-spacing:.09em; text-transform:uppercase; }
- .eyebrow { color:var(--green); }
- h1,h2,h3,p { margin:0; }
- h1 { font-size:clamp(32px,4.5vw,52px); line-height:1.1; letter-spacing:-.055em; max-width:520px; margin:12px 0 16px; }
- h2 { font-size:25px; letter-spacing:-.035em; }
- h3 { font-size:17px; letter-spacing:-.02em; }
- .intro { display:grid; grid-template-columns:1fr 1fr; align-items:center; gap:32px; margin:44px 0 32px; }
- .intro p { max-width:440px; }
- .muted { opacity:.73; }
- .hero { border:2px solid var(--ink); border-radius:22px; background:var(--paper); overflow:hidden; box-shadow:0 6px 0 var(--wall2); }
- .stage { position:relative; padding:12px 16px 0; background:radial-gradient(ellipse at center,var(--wall2),transparent 70%); }
- #morph { display:block; width:100%; height:auto; max-height:275px; overflow:visible; }
- .caption { text-align:center; font-size:13px; padding:0 18px 17px; }
- .controls { flex-wrap:wrap; justify-content:center; gap:8px; padding:15px; border-top:1px solid color-mix(in srgb,var(--ink) 15%,transparent); }
- button { font:inherit; font-size:13px; font-weight:650; cursor:pointer; color:var(--ink); background:var(--paper); border:1.5px solid var(--ink); border-radius:9px; min-height:38px; padding:7px 12px; }
- button:hover { background:var(--wall2); }
- button:active { transform:translateY(1px); }
- button:disabled { opacity:.45; cursor:default; }
- button.primary { background:var(--ink); color:var(--paper); }
- button:focus-visible,input:focus-visible { outline:3px solid var(--orange); outline-offset:3px; }
- .motion-option { display:flex; align-items:center; justify-content:center; gap:7px; font-size:12px; padding:0 12px 13px; }
- input { accent-color:var(--green); }
- .section-head { margin:39px 0 15px; align-items:baseline; }
- .section-head p { font-size:13px; }
- .choices { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:16px; }
- article { padding:20px; border:1px solid color-mix(in srgb,var(--ink) 24%,transparent); border-radius:15px; background:var(--paper); }
- article.recommended { border:2px solid var(--ink); padding:19px; }
- .tag { padding:3px 8px; border-radius:20px; font-size:11px; color:var(--green); background:var(--wall); white-space:nowrap; }
- .word { display:block; width:100%; height:105px; margin:10px 0 8px; }
- article p { font-size:13px; margin-top:7px; }
- .detail { display:grid; grid-template-columns:1fr 1.2fr; gap:30px; align-items:center; padding:24px; margin-top:18px; background:var(--wall2); border-radius:15px; }
- .detail p { font-size:14px; margin-top:10px; }
- .samples { width:100%; border-collapse:collapse; table-layout:fixed; text-align:left; }
- th,td { border-bottom:1px solid color-mix(in srgb,var(--ink) 15%,transparent); padding:9px 6px; vertical-align:middle; }
- th { font-size:12px; font-weight:650; }
- th:first-child { width:58px; }
- td svg { display:block; max-width:100%; }
- .size { font-size:12px; white-space:nowrap; opacity:.7; }
- .aside { display:flex; align-items:center; gap:12px; margin-top:15px; padding-top:13px; border-top:1px solid color-mix(in srgb,var(--ink) 15%,transparent); }
- .aside svg { width:32px; height:32px; flex:none; }
- .aside span { font-size:12px; }
- .zh { display:block; margin-top:6px; font-size:13px; font-weight:400; letter-spacing:0; line-height:1.6; opacity:.75; }
- .application { margin-top:18px; border:2px solid var(--ink); border-radius:18px; overflow:hidden; background:var(--paper); }
- .application header { padding:16px 24px; }
- .lockup { display:flex; align-items:center; gap:12px; }
- .lockup .tv { width:36px; height:36px; }
- .lockup .word { width:68px; height:38px; margin:0; }
- .sample-nav { display:flex; flex-wrap:wrap; gap:16px; font-size:12px; opacity:.75; }
- .site-hero { display:grid; grid-template-columns:1fr auto; align-items:center; gap:24px; padding:36px 32px; }
- .site-hero h3 { font-size:clamp(25px,3vw,38px); line-height:1.2; letter-spacing:-.04em; }
- .site-hero p { max-width:430px; margin-top:12px; font-size:14px; }
- .site-hero > .tv { width:128px; height:128px; color:var(--ink); }
- .steps { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); border-top:1px solid color-mix(in srgb,var(--ink) 18%,transparent); }
- .steps > div { padding:18px 24px; }
- .steps > div + div { border-left:1px solid color-mix(in srgb,var(--ink) 18%,transparent); }
- .steps p { font-size:13px; margin-top:6px; }
- .implementation { display:flex; flex-wrap:wrap; gap:10px 24px; margin:14px 0 0; font-size:12px; }
- code { font-family:ui-monospace,"Cascadia Mono",monospace; }
- footer { margin-top:27px; padding-top:18px; border-top:1px solid color-mix(in srgb,var(--ink) 18%,transparent); font-size:12px; flex-wrap:wrap; }
- .fallback { font-weight:750; font-size:42px; letter-spacing:-.045em; }
- .js .fallback { display:none; }
- .no-js { font-size:13px; }
- @media(max-width:760px) { main { padding:20px 18px 32px; } .intro { grid-template-columns:1fr; gap:24px; margin-top:30px; } .intro p { max-width:560px; } .hero { max-width:550px; width:100%; } .detail { grid-template-columns:1fr; gap:15px; } }
- @media(max-width:500px) { .choices { grid-template-columns:1fr; gap:10px; } article { display:grid; grid-template-columns:1fr 1.3fr; column-gap:14px; align-items:center; } .card-heading { grid-column:1/-1; } .word { height:90px; grid-row:2/4; } article h3 { margin-top:12px; } article p { margin:4px 0; } .section-head { align-items:start; flex-direction:column; gap:3px; } .detail { padding:18px; } .eyebrow { font-size:11px; } .application header { padding:14px; } .sample-nav { gap:9px; font-size:11px; } .site-hero { padding:24px 18px; gap:12px; } .site-hero > .tv { width:70px; height:70px; } .steps { grid-template-columns:1fr; } .steps > div + div { border-left:0; border-top:1px solid color-mix(in srgb,var(--ink) 18%,transparent); } }
- @media(prefers-reduced-motion:reduce) { button:active { transform:none; } }
-</style>
-<main>
- <header>
- <div class="identity"><svg class="tv" aria-hidden="true" viewBox="0 0 32 32"></svg><span>Piik / 品牌预览</span></div>
- <button id="theme" type="button" aria-label="Switch to dark theme">Dark room</button>
- </header>
- <section class="intro" aria-labelledby="intro-title">
- <div>
- <div class="eyebrow">01 / A name taking shape</div>
- <h1 id="intro-title">A little peek.<br>A familiar face.</h1>
- <p>From <strong>“Peek” in games</strong> to a little TV for watching together. Keep the wink. Give it a name.</p>
- <p class="muted" style="font-size:14px;margin-top:14px" lang="zh-CN">探个头,看看朋友在玩什么。名字换了,小电视还是那个小电视。</p>
- </div>
- <div class="hero">
- <div class="stage">
- <span class="fallback">Piik → TV</span>
- <svg id="morph" viewBox="70 20 330 210" role="img" aria-labelledby="morph-title morph-desc">
- <title id="morph-title">Piik becomes the winking TV</title>
- <desc id="morph-desc">The P bowl opens into the screen, with the outer letter stems joining its sides. The two i dots become eyes, their stems become feet, and the k arms open into the TV antennae.</desc>
- </svg>
- </div>
- <p class="caption">Same strokes. Familiar wink.<span class="zh" lang="zh-CN">P 撑开屏幕,ii 变成眼睛和脚,k 的两笔转成电视天线。</span></p>
- <div class="controls">
- <button id="replay" class="primary" type="button">重播 / Replay</button>
- <button id="pause" type="button">暂停 / Pause</button>
- <button id="word-state" type="button">字标 / Wordmark</button>
- <button id="tv-state" type="button">电视 / TV</button>
- </div>
- <label class="motion-option"><input id="reduce" type="checkbox"> 减少动态 / Reduced motion</label>
- </div>
- </section>
- <noscript><p class="no-js">Motion is optional. Piik is the recommended spelling; PiiK and piik are the two alternatives below. The original TV remains the small icon.</p></noscript>
- <div class="section-head"><h2>Three ways to write it<span class="zh" lang="zh-CN">三个名字写法,同一套笔画</span></h2><p class="muted">One drawing style. Only the casing changes.</p></div>
- <section class="choices" aria-label="Casing comparison">
- <article class="recommended">
- <div class="card-heading"><span class="number">01</span><span class="tag">Recommended</span></div>
- <span class="fallback">Piik</span><svg class="word" data-case="Piik" role="img" aria-label="Piik, with an uppercase P and lowercase i i k"></svg>
- <h3>Piik</h3><p>A clear name, with two curious eyes.<span class="zh" lang="zh-CN">主方案。首字母清楚,两个 i 留一点好奇心。</span></p>
- </article>
- <article>
- <div class="card-heading"><span class="number">02</span><span class="tag">More contrast</span></div>
- <span class="fallback">PiiK</span><svg class="word" data-case="PiiK" role="img" aria-label="PiiK, with uppercase P and K"></svg>
- <h3>PiiK</h3><p>A stronger K gives the name a sharper silhouette.<span class="zh" lang="zh-CN">两侧更高、更硬朗,也更抢眼。</span></p>
- </article>
- <article>
- <div class="card-heading"><span class="number">03</span><span class="tag">Softer</span></div>
- <span class="fallback">piik</span><svg class="word" data-case="piik" role="img" aria-label="piik, all lowercase"></svg>
- <h3>piik</h3><p>Relaxed and compact, with a lower centre of gravity.<span class="zh" lang="zh-CN">更轻松。小写 p 会伸到基线下方。</span></p>
- </article>
- </section>
- <section class="detail" aria-labelledby="detail-title">
- <div>
- <div class="eyebrow">02 / The two little details</div>
- <h2 id="detail-title">Two dots. Two curious eyes.</h2>
- <p>Round dots keep the <strong>ii</strong> easy to read, then become the familiar TV eyes.</p>
- <p class="muted">The wordmark below is shown at everyday sizes.</p>
- <p class="zh" lang="zh-CN">两个圆点保留 ii 的辨识度,再变成小电视的眼睛。下面按实际尺寸查看。</p>
- <div class="aside"><svg class="tv" aria-hidden="true" viewBox="0 0 32 32"></svg><span>Keep the existing TV for the tiny icon.<br>No four-letter favicon puzzle.</span></div>
- </div>
- <table class="samples" aria-label="Piik at actual sizes">
- <thead><tr><th>Height</th><th>Piik</th></tr></thead>
- <tbody>
- <tr><td class="size">64 px</td><td><svg data-size="64" role="img" aria-label="Piik at 64 pixels"></svg></td></tr>
- <tr><td class="size">32 px</td><td><svg data-size="32" role="img" aria-label="Piik at 32 pixels"></svg></td></tr>
- <tr><td class="size">24 px</td><td><svg data-size="24" role="img" aria-label="Piik at 24 pixels"></svg></td></tr>
- </tbody>
- </table>
- </section>
- <div class="section-head"><h2>At home on a page<span class="zh" lang="zh-CN">放到页面上:官网首屏的方向草图</span></h2><p class="muted">A static website. The sharing app stays a tool.</p></div>
- <section class="application" aria-label="Static homepage composition, not a live sharing service">
- <header>
- <div class="lockup" role="img" aria-label="TV mascot and Piik wordmark"><svg class="tv" aria-hidden="true" viewBox="0 0 32 32"></svg><svg class="word" data-case="Piik" aria-hidden="true"></svg></div>
- <div class="sample-nav"><span>Download</span><span>Guide</span><span>GitHub</span></div>
- </header>
- <div class="site-hero">
- <div><h3>Your game.<br>Their front row.</h3><p>Share your screen. Bring your friends.<br>They watch right in their browsers.</p><p class="zh" lang="zh-CN">开一局,朋友坐前排。<br>发个邀请,打开浏览器就能看。</p></div>
- <svg class="tv" aria-hidden="true" viewBox="0 0 32 32"></svg>
- </div>
- <div class="steps">
- <div><span class="number">01 / Pick</span><p>A screen, a window, a game.<span class="zh" lang="zh-CN">选好想分享的画面。</span></p></div>
- <div><span class="number">02 / Invite</span><p>Send a link to your friends.<span class="zh" lang="zh-CN">把邀请链接发给朋友。</span></p></div>
- <div><span class="number">03 / Hang out</span><p>A little room for your people.<span class="zh" lang="zh-CN">人到齐,就一起看。</span></p></div>
- </div>
- </section>
- <div class="implementation"><span>Display / 显示名称 <strong>Piik</strong></span><span>Technical / 技术名称 <code>piik-app</code></span><span>Website / 官网 <code>piik.tv</code></span><span>Page title / 页签 <code>Piik | 6020 · 📺</code></span></div>
- <footer><span>Design study · 09 Sep 2026 · 待讨论,尚未替换产品</span><span>Layout references: <a href="https://localsend.org/">LocalSend</a> · <a href="https://rustdesk.com/">RustDesk</a></span></footer>
-</main>
-<script>
- const $ = (id) => document.getElementById(id);
- const ns = 'http://www.w3.org/2000/svg';
- const tv = '<g fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m11 4 5 4 5-4"/><rect x="4" y="8" width="24" height="18" rx="4"/><circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none"/><path d="M19 17c1.5-1.8 3.2-1.8 4.7 0M10 29l2-3m10 3-2-3"/></g>';
- document.querySelectorAll('.tv').forEach((svg) => svg.innerHTML = tv);
- // The k diagonals become antennae; the outer stems join the screen edges.
- const parts = [
- ['rect', {x:108,y:72,width:58,height:48,rx:20}, {x:172,y:76,width:136,height:102,rx:22.667}],
- ['line', {x1:108,y1:72,x2:108,y2:164}, {x1:172,y1:98.667,x2:172,y2:155.333}],
- ['line', {x1:194,y1:118,x2:194,y2:164}, {x1:217.333,y1:178,x2:206,y2:195}],
- ['line', {x1:236,y1:118,x2:236,y2:164}, {x1:262.667,y1:178,x2:274,y2:195}],
- ['line', {x1:282,y1:72,x2:282,y2:164}, {x1:308,y1:98.667,x2:308,y2:155.333}],
- ['line', {x1:284,y1:139,x2:318,y2:111}, {x1:240,y1:76,x2:268.333,y2:53.333}],
- ['line', {x1:294,y1:131,x2:326,y2:164}, {x1:211.667,y1:53.333,x2:240,y2:76}],
- ];
- const attributes = (node, values) => Object.entries(values).forEach(([key,value]) => node.setAttribute(key,String(value)));
- function element(parent, tag, values) { const node = document.createElementNS(ns,tag); attributes(node,values); parent.append(node); return node; }
- function animate(node, name, from, to, begin=.65, dur=1.25) {
- return element(node,'animate',{attributeName:name,from,to,begin:begin+'s',dur:dur+'s',fill:'freeze',calcMode:'spline',keyTimes:'0;1',keySplines:'.4 0 .2 1'});
- }
- function drawWord(svg, casing='Piik', moving=false) {
- if (!moving) svg.setAttribute('viewBox','96 58 244 138');
- const group = element(svg,'g',{fill:'none',stroke:'currentColor','stroke-width':10,'stroke-linecap':'round','stroke-linejoin':'round'});
- parts.forEach(([tag,start,end],index) => {
- const shape = {...start};
- if (casing === 'piik') { if(index===0) {shape.y=112;shape.height=48;} if(index===1) {shape.y1=112;shape.y2=188;} }
- if (casing === 'PiiK') { if(index===5) {shape.y1=122;shape.y2=72;} if(index===6) {shape.x1=286;shape.y1=120;} }
- const node = element(group,tag,shape);
- if(moving) Object.keys(end).forEach(key => animate(node,key,shape[key],end[key]));
- });
- [194,236].forEach((cx,index) => {
- const eyeX = index?270.317:214.5;
- const eye = element(group,'ellipse',{cx,cy:95,rx:6.5,ry:6.5,fill:'currentColor',stroke:'none'});
- if(moving) { animate(eye,'cx',cx,eyeX); animate(eye,'cy',95,124.167); animate(eye,'rx',6.5,7.083); animate(eye,'ry',6.5,7.083); if(index) animate(eye,'ry',7.083,0,2.2,.16); }
- });
- if(moving) {
- animate(group,'stroke-width',10,13.6);
- const wink = element(group,'path',{d:'M257 127c8.5-10.2 18.133-10.2 26.633 0',pathLength:1,'stroke-dasharray':1,'stroke-dashoffset':1});
- animate(wink,'stroke-dashoffset',1,0,2.3,.23);
- const sparkles = element(group,'g',{stroke:'var(--spark)','stroke-width':7.933,opacity:0});
- element(sparkles,'path',{d:'M291 95.8L295.5 106.6L306.3 111.1L295.5 115.7L291 126.4L286.5 115.7L275.7 111.1L286.5 106.6Z'});
- element(sparkles,'path',{d:'M291 128.1L293.6 134.4L299.8 136.9L293.6 139.5L291 145.7L288.5 139.5L282.2 136.9L288.5 134.4Z'});
- animate(sparkles,'opacity',0,1,2.4,.15);
- animate(sparkles,'opacity',1,0,2.8,.4);
- }
- }
- drawWord($('morph'),'Piik',true);
- document.querySelectorAll('[data-case]').forEach(svg => drawWord(svg,svg.dataset.case));
- document.querySelectorAll('[data-size]').forEach(svg => { const height=Number(svg.dataset.size); attributes(svg,{height,width:height*244/138}); drawWord(svg); });
- const morph=$('morph'), reduce=$('reduce'), pause=$('pause'), motion=matchMedia('(prefers-reduced-motion: reduce)');
- const duration=3.3;
- let frame;
- function still(at) { cancelAnimationFrame(frame); morph.pauseAnimations(); morph.setCurrentTime(at); pause.textContent='继续 / Resume'; pause.disabled=reduce.checked||at>=duration; }
- function watch() { if(morph.getCurrentTime()>=duration) { still(duration); return; } frame=requestAnimationFrame(watch); }
- function replay() { still(0); if(reduce.checked) { still(duration); return; } pause.textContent='暂停 / Pause'; pause.disabled=false; morph.unpauseAnimations(); watch(); }
- $('replay').onclick=replay;
- pause.onclick=() => { if(morph.animationsPaused()) { pause.textContent='暂停 / Pause'; morph.unpauseAnimations(); watch(); } else still(morph.getCurrentTime()); };
- $('word-state').onclick=() => still(0);
- $('tv-state').onclick=() => still(duration);
- reduce.checked=motion.matches;
- reduce.onchange=() => still(reduce.checked?duration:0);
- motion.addEventListener('change',event => { reduce.checked=event.matches; reduce.onchange(); });
- const dark=matchMedia('(prefers-color-scheme: dark)');
- function theme(isDark) { document.documentElement.dataset.theme=isDark?'dark':'light'; $('theme').textContent=isDark?'Light room':'Dark room'; $('theme').setAttribute('aria-label',isDark?'Switch to light theme':'Switch to dark theme'); }
- theme(dark.matches);
- $('theme').onclick=() => theme(document.documentElement.dataset.theme!=='dark');
- document.documentElement.classList.add('js');
- if(reduce.checked) still(0); else replay();
-</script>
-</html>
diff --git a/docs/design/public-introduction.md b/docs/design/public-introduction.md
new file mode 100644
index 00000000..a5cb3d8e
--- /dev/null
+++ b/docs/design/public-introduction.md
@@ -0,0 +1,148 @@
+# Public introduction
+
+This file owns the website and README content structure. The
+[visual language](./visual-language.md) owns their shared illustration and motion.
+
+## One story, three readers
+
+Lead with friends sharing something worth seeing: a game, a drawing, a film or
+travel photos. The [copy guide](../reference/naming.md#voice-and-terminology) owns
+Chinese/English voice and role labels. A visitor should
+understand what Piik does, choose an entry and complete the first useful action.
+
+| Surface | Reader's question | Content |
+| --- | --- | --- |
+| README, English and Chinese | What is this, and how do I start? | Brand introduction and interface preview, features, getting started, self-hosting, contribution and license |
+| `site/`, for GitHub Pages | What does using it feel like, and how do I start? | Room illustration and primary download link, illustrated steps, demo/App/existing-site walkthroughs, FAQ, platform downloads, documentation and source |
+| Getting-started guides | Which button or mode do I use? | Browser invitation, sharing, App setup and three mode choices |
+| Self-hosting guides | How do I put my own site online? | Run the binary, set the domain and HTTPS proxy, open ports and verify; service management remains a separate reference |
+| Developer and operations docs | How do I build or host it? | Existing configuration, deployment, architecture and diagnostic owners |
+
+The [documentation map](../README.md) is the Wiki-style entry. Link it from the
+website navigation and footer, with direct self-hosting, configuration and
+update/recovery links in the documentation section. Keep the guides in this
+repository; do not maintain a second GitHub Wiki copy of the same instructions.
+
+## Presentation
+
+Keep three presentation responsibilities distinct:
+
+| Layer | Owns | Review question |
+| --- | --- | --- |
+| Shared identity | Mascot geometry and wink, gold sparkle, wordmark/orange dot, public-page brand control | Does this read as the same Piik at every size and entry? |
+| Product demonstration | Actual components, labels, source selection, room controls and participants with sample data | Does the pictured action still match the current product? |
+| Promotional composition | Original scenery, large typography, framing, transitions and optional music | Does the spectacle help a newcomer understand the product and find the next action? |
+
+Use one public-page brand component for the homepage and film. The mascot's
+curved wink and gold sparkle are recognizable features; a prop or a pictured
+game does not replace its face with another expression. Original RPG scenery
+can suggest exploration through terrain, ruins and small discoveries without
+borrowing another product's characters, named places, logos or artwork.
+
+Homepage sections follow the visitor's decisions: understand Piik and find the
+primary download action, see the sharing steps, choose a short tutorial, resolve
+questions, then find platform downloads, detailed documentation and source.
+The primary download link lets returning visitors skip the tutorials. Guide
+choices run from online demo to App to an existing site, with only the demo
+expanded initially. Watching requires no installation. Explain where an existing
+site comes from; mark self-hosting as advanced and link its complete guide.
+Platform download cards share one App tutorial entry. Keep section navigation
+available on phones rather than hiding the only route to documentation.
+The film can use bolder composition, but must show real operations and concrete
+benefits before its closing action. The [copy guide](../reference/naming.md#voice-and-terminology)
+owns technical disclosure; a dramatic heading does not exempt copy from it.
+
+Review whole Chinese phrases, English meaning and adjacent number labels in
+finished frames, not just the source string. Recheck the smallest viewport and
+both languages when changing a title or its timing. Keep enough still time to
+read it; do not solve overflow by shrinking an important caption beyond legibility.
+
+Use the [shared visual language](./visual-language.md) for cast, objects,
+accessible interaction and motion. This document owns the website's editorial
+layout and introduction, not a separate product-status vocabulary.
+
+Each section needs one reader question, evidence that answers it and a clear
+next action. A scene should demonstrate one action or benefit before changing
+the topic. Keep decorative words and transitions away from control labels and
+the primary action; sound and motion must not carry essential instructions alone.
+Gameplay reactions follow a visible result: establish the action, show its
+success, then celebrate. Keep enough of the play visible to make the reaction
+understandable; a genre label or a score burst does not replace the action.
+
+Use mint walls, clear control edges, a warm orange/yellow sofa and the curious TV
+mascot. The site is a welcoming room, not a monitoring dashboard. Keep one
+primary action, native navigation and short instructions. English is the first
+view with an explicit Chinese choice; theme follows the system unless changed.
+Respect reduced motion and retain useful content without JavaScript.
+
+The room illustration cycles through four distinct uses: an RPG, drawing,
+travel photos and a movie. Treat coding and design as creative work rather than
+proliferating overlapping examples. The host holds a gamepad during the game;
+the role badge identifies the host independently of the activity.
+Keep participant drawings consistent across the site, READMEs,
+interface captures and tooltip/status comics.
+
+Present Piik as an open-source project: plain explanations, room for tinkering,
+and an invitation to contribute. Keep the friendly illustration and avoid
+company-style pitches, repeated slogans or claims about a support team.
+The short comics illustrate choosing, inviting and joining, following the
+shared motion grammar and whole-control replay rule. The optional film starts
+only after an explicit action and has native buttons and a seek slider. Open it
+within the homepage, loading its single player on demand; closing it unloads
+playback. The standalone page serves recording and direct links. Fullscreen
+watching keeps touch controls available; hiding them is an explicit recording action.
+Both READMEs share the friendly opening and room illustration. Their feature,
+limitation and setup sections use the factual register in the copy guide.
+
+Use a consistent README structure:
+a distinct brand opening, bold headings and key phrases, regular explanatory
+text, quiet captions and optional detail. Use images and short demonstrations
+to explain different things rather than filling space. Keep essential setup and
+availability in readable text, and distinguish generated demo content from a
+real captured workload. GitHub-native Markdown/HTML must remain useful on mobile
+and in both themes without custom CSS.
+
+The product UI remains mascot-only. On the website, keep the header's TV
+mascot before the Piik name. The wordmark and mascot do not transform
+into one another. Match the product's
+playful style through the mascot's wink and short comic interactions. An
+original room illustration is shared by the site and READMEs. Interface previews
+use generated scenes and sample participants. Keep private invitations,
+user identities and personal media out of published assets; no external fonts
+or tracking are needed.
+
+## Small implementation
+
+The website and film initially follow the browser's primary language: Chinese
+uses Chinese copy, and other languages use English. An explicit language choice
+is shared between these two pages and remembered; linked language choices take
+precedence when following a link.
+
+Use static HTML, CSS, SVG and small scripts for the public pages; no router,
+CMS, translation dependency or new application backend. The film's isolated
+demonstration frame bundles the existing React product components and styles,
+using staged inputs. It cannot access storage, run capture or contact the room
+service. The film clock owns its actions and decorative CSS animation positions.
+Rebuilding the site picks up component/style/copy changes; changes to the actual
+workflow still require reviewing the sequence and camera framing. Do not replace
+shared controls with a second hand-drawn UI or retain obsolete screenshot plates.
+The existing App/Web
+continues to own sharing. The homepage explains it rather than simulating a
+second room authority. Public copies of advanced product/research documents
+are not automatically included in the website artifact.
+
+The [website operations guide](../operations/website.md) owns Pages publication,
+public destinations and the separate P2P-only demo. The primary action leads
+to the platform download section. Use permanent release-page links for downloads;
+archive names include a revision. Verify destinations as part of publication.
+Demo, App and existing-site walkthroughs
+use real action names and explain the first sharing and viewing steps. Keep
+platform requirements and connection limitations beside the relevant steps.
+
+## Review boundary
+
+Review desktop/mobile, English/Chinese, light/dark, keyboard navigation,
+reduced motion, no JavaScript and a nested project URL. Check links, accurate
+platform/connection claims and a single copy of each responsibility. Remove
+decorative controls or code that do not improve understanding. This is a public
+introduction overhaul, not an excuse to change configuration or media policy.
diff --git a/docs/design/visual-language.md b/docs/design/visual-language.md
new file mode 100644
index 00000000..b1bcf155
--- /dev/null
+++ b/docs/design/visual-language.md
@@ -0,0 +1,210 @@
+# Visual Language
+
+This is the single design requirement for Piik's shared Web/App interface:
+illustration, semantic colour, panel grammar, motion and tooltip presentation.
+New UI work follows this file and the local `/__tooltip-preview` catalogue.
+[Media status](./media-status.md) owns which facts justify each status;
+[presentation lifecycle](../product/presentation-lifecycle.md) owns interaction
+and playback. Neither an illustration nor its colour creates product state.
+
+Use one stroke language for single concepts, small panel comics for causes and
+sequences, and literal scene objects for people, rooms and media. Glyphs do not
+form sentences. The same meaning and visual hierarchy must work in Chinese,
+English and pure-visual modes, in both themes and at narrow widths.
+
+Piik's living room uses simple silhouettes, generous space, rounded controls
+and a small responsive bounce. Clear hierarchy and legible interaction keep
+the playful details easy to use.
+The [copy guide](../reference/naming.md#voice-and-terminology) owns its voice.
+The [public introduction guide](./public-introduction.md) owns website and film
+hierarchy: shared identity, current product demonstrations and promotional
+composition. It applies the copy guide's audience and technical-detail layers.
+
+Keep playfulness restrained: clean silhouettes, balanced proportions, quiet
+expressions and brief gestures. Keep the interface approachable; avoid
+pushing ordinary characters toward infant proportions, exaggerated
+grins, dense cute decoration or children's picture-book styling.
+
+## Layout And Input
+
+Present a small shared living room: the television is the media stage, the
+couch and pawns make presence spatial, and the four-digit room code stays
+prominent. Decoration must clarify product facts without creating another state
+model. Universal digits, transport symbols, URLs and measured values remain
+literal when the user needs the data.
+
+Functional controls use native buttons/inputs and localized accessible names.
+Hover, keyboard focus and touch receive equivalent guidance. Keep information
+order and interaction ownership consistent across languages, themes and viewport
+sizes. Reflow or bounded scrolling must not hide a primary action, truncate an
+essential value, overlap controls or change meaning.
+
+Shared buttons and chips use pill shapes, a quiet lower edge and a short lift
+on hover or keyboard focus, then compress on press. Inputs and option tiles
+share softer corners. Keep a distinct focus ring and a persistent selected
+state; disabled controls must not pretend to activate. Reduced motion keeps
+the colour, outline and selected position without decorative displacement.
+
+## Cast And Objects
+
+The brand mascot keeps its own identity, separate from ordinary participants.
+Participant characters should leave room for that distinctive presence.
+
+| Meaning | Representation |
+| --- | --- |
+| The person using the pictured action | Green pawn (`YOU` / `--you`), in every panel |
+| Somebody else | Blue pawn (`SKY`), or another distinct non-green illustration colour |
+| Host role | Gold crown above the head: rounded three-point outline, dark gold edge and a quiet lower rim; the standalone absent-Host symbol uses the same outline, unfilled and dashed |
+| Shared or watched media | Small television, including antenna, body and feet |
+| Browser application | Browser chrome around content; not a second design of television |
+| A captured window or display | Window title bar or display stand, with the shared media metaphor kept distinct |
+| Server forwarding media | A server on the media path; opening a Site alone does not imply SFU |
+
+These are **identity/object colours**, not status. A green pawn remains green
+in a failed scene; a successful scene does not turn other people green. Real
+roster identities retain the shared UUID colour function, not the illustrative
+"you versus others" palette. Actor positions and identities remain stable from
+the first panel to the result.
+
+Room pawns, tooltip/status comics and introduction participants use
+a round head, half-oval body and two restrained eyes. Reuse the shared
+figure and face geometry in product illustrations so expressions stay inside
+the head as it scales. Larger scenes can add a small lean; small status panels
+may omit facial detail to keep the action clear. When a gesture needs hands,
+use small floating round shapes. A held gamepad is a scene prop; a separate role
+crown identifies the host and moves with the body. Its gold is an identity colour,
+not a warning or achievement. The share control retains its
+cast icon. The cast represents friends sharing games, drawings
+and other screen content. Exploratory figures are not alternate
+participant identities. Keep the brand mascot distinct.
+
+The couch has a back, seat, arms and feet. A full room reflows into rows of seats
+without hiding people or requiring horizontal scrolling. Topology preserves
+each participant and actual parent edge at a readable scale; reduce spare
+spacing, then use a vertical outline when depth exceeds the available width.
+
+Couch upholstery uses the fixed warm orange/yellow `--couch` / `--couch-dark`
+palette. Never draw upholstery from the participant palette or randomize it by
+room. Keep automatic participant colours outside the upholstery's amber/orange
+range and the crown's gold; check all eight tokens against both objects in light
+and dark themes. The crown retains a bright gold fill with a dark gold edge.
+Figures and exterior upholstery use flat fills without outline strokes.
+Use differences in tone, spacing and name tags to keep people readable; retain
+only the few interior seams that clarify cushions. Apply this convention to
+the website and README cast as well as the product UI.
+
+## Semantic Colour And Shape
+
+Use the existing theme tokens in `src/client/styles.css`. The shared
+`comic-presentation.ts` maps meanings to those tokens for tooltip outlines,
+carets, result panels and verdict marks. Do not choose independent hex colours
+or animation rules inside an individual scene.
+
+| Meaning | Token / code tone | Panel and symbol |
+| --- | --- | --- |
+| Explanation, preference, ordinary action, intentional closure or unknown state | Neutral ink / `off` | Neutral panels; illustrate the action/object without a success stamp |
+| Confirmed completion or delivered media | Green `--live` / `live` | Neutral before, green result; check or completed object |
+| Still usable with a limitation, unavailable optional capability, or intentional media pause | Amber `--warn` / `warn` | Neutral before, amber result; limit, pause, lock or unavailable mark on the affected part |
+| Confirmed failed or blocked action | Red `--danger` / `bad` | Neutral before, red result; cross, broken path or other explicit failure mark |
+| Work in progress or awaiting an action/frame | Blue `--action` / `busy` | Neutral before, blue current/result panel; connection, progress or play symbol |
+
+Recovery retains amber because service is interrupted while work continues.
+Waiting for a Host and unknown observations remain neutral. A control's
+prospective action is not proof of success: opening details, switching theme,
+adjusting volume or offering P2P stays neutral. Actual copy feedback can change
+that same hint to green or red, using the existing operation result.
+
+Two-panel comics always read before/context on the left and result/current
+condition on the right. Only the result carries the semantic accent; a single
+panel carries the current condition. Tooltip outline and caret use that same
+tone in Chinese, English and visual modes. Neutral uses theme ink, not literal
+white. Keep paper fills quiet; do not tint the whole scene green/yellow/red.
+Meaning must also survive without colour through objects, symbols and accessible
+localized names. Never show celebration or a completed live path as the verdict
+of a failed or unavailable operation.
+
+A missing optional feature is not a failed media path. For example, unavailable
+NAT prediction marks only extra candidate paths; ordinary P2P remains a neutral
+possibility. A rejected PiP request is failure; lack of PiP support is a limitation.
+
+## Motion Grammar
+
+| Presentation | Rule |
+| --- | --- |
+| Action demonstration (`demo`) | Play one meaningful transition when shown, then hold its result |
+| Work actually continuing (`progress`) | Repeat a gentle connection/recovery beat while that state exists |
+| Settled success, failure, limitation, pause or idle (`still`) | Show the informative final pose immediately; no repeated stamping, shaking, blinking or celebration |
+
+Demonstrations and progress share the existing 3.2-second comic beat. The main
+action belongs in its first half, followed by a readable hold; small internal
+staggering is allowed. At most two independent movers per panel. An explanatory
+slider describes purpose and available range, not its live numeric value.
+Decorative sparkle must support the pictured action, never fake current success.
+
+Reduced motion and settled states reuse each scene's **same explicit final
+pose**. Disabling animation alone is insufficient if the base SVG hides the
+result or shows a misleading starting pose. Static styling is scoped to its SVG;
+one still tooltip must not freeze another progress scene. New keyframes must end
+in the documented result rather than reset for an obsolete loop.
+
+The tooltip panel itself uses the same restrained entrance/exit for every tone.
+Replay belongs to opening/hovering/focusing the whole control, not just its SVG.
+Ordinary controls keep their icons visible during hover and keyboard focus;
+surface colour, lift, focus and press feedback carry the interaction. Reserve
+icon drawing/replay for primary actions such as starting a share or joining a
+room, and for explicit state-entry feedback. The whole control owns the trigger.
+Stroke and solid drawings share one total duration and easing; stroke count
+must not lengthen the animation. Disabled controls and passive status icons
+retain their informative pose; busy indicators retain their progress beat.
+Do not add a per-scene timer or another interaction/state owner. Outside status
+comics, the brand mascot and participant figures may blink or glance occasionally;
+a pictured screen can guide the Host's gaze. Keep eye gestures and small body
+leans brief, separated by long pauses and offset between people. A participant's
+UUID seeds the cadence; align its phase to wall time in every view, including
+later mounts and return from background. Names, roster order and the observer's
+role do not reseed it. Device clock skew bounds cross-device precision; cosmetic
+motion adds no signaling or media state. They express personality independently
+of connection feedback. Follow the system's reduced-motion preference, keeping a
+natural, open-eyed pose when enabled; participant gestures have no separate
+product playback control. Status comics still follow the table above.
+
+Introduction artwork is separate from product status. Website/README scenes may
+repeat a short action with a generous pause. Keep broad movement to one or two
+focal elements; small participant gestures follow the quiet cadence above.
+Provide a pause or hide control for automatic loops, and a useful static pose
+for reduced motion. Product-state comics still follow the table above.
+
+Entry screens may carry one quiet, original welcome line in Chinese or English
+text mode. Pure-visual mode pairs familiar pictograms with static pixel
+pseudo-lettering tied to the same line. This decoration is hidden from assistive
+technology. The selected line stays stable during that visit, including mode
+changes, and never replaces an action, error, loading message or connection
+progress. Keep it on one line, apart from the actions; primary controls take
+precedence when space is tight.
+
+## Ownership And Incremental Review
+
+- Existing status/operation facts outrank the scene default. Reused `warning`
+ artwork can represent a warning or a confirmed failure; pass the actual tone.
+- `comic-presentation.ts` owns defaults and semantic tokens; `Frame`, `RedX`,
+ `rmBlock`, `Comic` and `HintComic` apply the shared grammar. Scenes own only
+ their cast, causal illustration and final pose. `Tooltip` owns interaction
+ and placement. Do not duplicate these rules in each scene or page.
+- Keep the semantic kind and tone in all languages; localized text changes
+ expression, not severity. Symbol-only controls retain accessible names.
+- For each changed scene inspect its start, transition and settled pose in
+ both themes, reduced motion and narrow layouts. Compare success, failure,
+ limitation and neutral neighbours in the catalogue. Code-level tests do not
+ establish visual clarity.
+- Update this owner when accepting a new convention. Product documents link
+ here instead of copying the palette, cast or animation table.
+
+## Interaction References
+
+[Carbon status indicators](https://v10.carbondesignsystem.com/patterns/status-indicator-pattern/)
+supports combining semantic colour with shape and symbols;
+[Carbon motion](https://carbondesignsystem.com/elements/motion/overview/)
+distinguishes functional feedback from occasional expressive movement.
+
+[Web Animations start time](https://developer.mozilla.org/en-US/docs/Web/API/Animation/startTime)
+provides the native timeline alignment used by participant gestures.
diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md
new file mode 100644
index 00000000..0e2a4ce5
--- /dev/null
+++ b/docs/guide/getting-started.md
@@ -0,0 +1,133 @@
+# Your first Piik room
+
+English · [简体中文](./getting-started.zh-CN.md) · [Back to Piik](../../README.md)
+
+Piik shares one person's screen with up to 20 invited viewers. This guide covers
+watching, trying the online demo, using Piik App and sharing through an existing site.
+
+[Join a room](#join-a-friends-room) · [Online demo](#try-the-online-demo) ·
+[Piik App](#share-with-piik-app) · [Existing site](#share-from-your-browser) ·
+[Troubleshooting](#when-something-gets-in-the-way)
+
+Viewers need a browser and an invitation. To try sharing, use the online demo
+or **Public invite** in Piik App.
+
+If Piik shows icons only, choose **EN** in the header to show the labels
+used below. **中** switches to Chinese; **✦** returns to the illustrations.
+
+## Join a friend's room
+
+1. Open the invitation link your friend sent in a desktop or mobile browser.
+2. Wait for their screen to appear. If the browser blocks autoplay, press **Play**.
+3. Move the pointer over the picture or tap it to show the playback bar.
+
+The playback bar controls only your own picture and sound.
+
+<details>
+<summary>Playback controls, at a glance</summary>
+
+| Control | What it does |
+| --- | --- |
+| **Theater mode** | Expands the picture inside the browser tab. |
+| **Fullscreen** | Fills your screen. |
+| **Picture in picture** | Opens a floating video where supported. |
+| **Volume** | Goes up to 200% with audio boost, or 100% otherwise. Lower it if the sound distorts. |
+
+</details>
+
+With just a four-digit room code, open the same Piik site and choose
+**Join a room**. You may need the site's passphrase and the room's password.
+The host decides whether code entry is available; ask for an invitation link if
+you cannot join by code.
+
+If an old link no longer works, ask the host for the current invitation.
+App Local rooms and temporary public invitations end when that App run stops.
+
+## Try the online demo
+
+1. Open [demo.piik.tv](https://demo.piik.tv) in a desktop browser that supports
+ screen sharing.
+2. Select **Start sharing**, choose a screen, window or tab, and enable audio if
+ needed and offered by the browser.
+3. Confirm the preview and select **Copy invite link**. Open that link on a
+ second device or send it to a friend.
+4. Select **Stop sharing** when finished.
+
+The project hosts this site for you. It uses direct media connections (P2P);
+restrictive networks may load the page but block video.
+
+## Share with Piik App
+
+1. Download a **`piik-app`** archive for your platform from
+ [GitHub Releases](https://github.com/TNTcraftHIM/Piik/releases) or the
+ [Gitee mirror](https://gitee.com/TNTcraftHIM/Piik/releases). Extract the whole
+ archive and keep its directory structure intact.
+2. Open `piik-app.exe` on Windows, `Piik App.app` on macOS, or `./piik-app` on Linux.
+ The launcher opens in your system browser.
+3. Choose **Public invite** for friends outside your local network, then select
+ **Open Piik**. Other modes are explained below.
+4. Choose **Start sharing**, then select **Browser**, **Apps / Windows**, or
+ **Screens** as available. Pick the actual source and sound option.
+5. Copy and send the room invitation. Keep both the App and sharing tab open.
+
+| Filename contains | Platform |
+| --- | --- |
+| `windows-amd64` | Windows x64 |
+| `darwin-arm64` | Apple silicon; native capture requires macOS 13+ |
+| `linux-amd64` | Linux x64 |
+
+Windows App and browser sharing are the primary tested paths. The macOS and
+Linux apps have not yet been tested on physical devices;
+[test results and feedback are welcome](https://github.com/TNTcraftHIM/Piik/issues).
+Linux native capture also needs [system components](../../native/capture/linux/README.md).
+See the [App guide](../../cmd/piik-app/README.md) for package and runtime details.
+
+### Choose an App mode
+
+| Mode | When to choose it | What to keep in mind |
+| --- | --- | --- |
+| **Local room** | Friends are on the same local network. | Your computer must be reachable from theirs. A local site passphrase is optional. |
+| **Public invite** | Friends are elsewhere and you want a temporary invitation. | Needs Internet access. The public address lasts for this App run. |
+| **Connect to Site** | Your group already has a Piik site. | Enter its address; the App adds capture capabilities to the site's sharing page. |
+
+**A page that opens does not guarantee a video connection.** Public invite gives
+your room a temporary web address; picture and sound still travel between
+participants. This mode has no media-server fallback, and the temporary address
+has no uptime guarantee. All modes need a working UDP media path.
+The [App guide](../../cmd/piik-app/README.md#modes) explains the connection setup.
+
+## Share from your browser
+
+You need an existing HTTPS site running Piik Server, provided by a friend or
+administrator. If you do not have one, start with the [demo](#try-the-online-demo)
+or [Piik App](#share-with-piik-app). Hosting a site yourself is an advanced option:
+follow the [self-hosting guide](../operations/self-hosting.md) for server, HTTPS
+and network setup.
+
+1. Open your group's Piik site on your computer. Enter its site passphrase if asked.
+2. Choose **Start sharing**. In the browser picker, select the screen, window or
+ tab you want friends to see, and enable audio if offered.
+3. Check the preview, then choose **Copy invite link** and send it to your friends.
+4. Keep the sharing tab open. Use **Pause sharing**, **Switch source**, or
+ **Stop sharing** when you need them.
+
+Screen capture requires an HTTPS site or `localhost`. The sources and audio
+offered by the picker depend on your browser and operating system.
+Invitation links grant access to that room; share them with the people you want there.
+
+## When something gets in the way
+
+| What you see | Try this |
+| --- | --- |
+| Picture but no sound | Unmute the video. The host should choose a source with shareable audio; if sound was disabled, stop and start sharing with it enabled. App window/screen capture keeps that setting when switching sources. |
+| No screen picker | Allow the browser or App to record the screen when the OS asks. Browser capture needs HTTPS or `localhost`; try sharing from a desktop computer. |
+| Local invitation will not open | Check that both devices are on the same network and can reach each other. Guest Wi-Fi or firewall rules can block local access. |
+| Page opens but video will not connect | Choose **Reconnect** in the playback bar. If it still fails, check [WebRTC connection settings](../../cmd/piik-app/README.md#chromium-webrtc-connections) or try a site with media fallback. |
+| Sharing stops after sleep or suspension | Wake the device and return to the sharing tab; start sharing again if needed. Browser and OS suspension can interrupt capture or playback. |
+
+For a bug report, include the version, OS/browser, what you expected, and how
+to reproduce it. [Diagnostics and export](../reference/configuration.md#diagnostics)
+explains how to collect a local report and what to review before sharing it.
+
+Ready to host a site for your group? Follow [self-hosting](../operations/self-hosting.md).
+For everything else, use the [documentation map](../README.md).
diff --git a/docs/guide/getting-started.zh-CN.md b/docs/guide/getting-started.zh-CN.md
new file mode 100644
index 00000000..51936274
--- /dev/null
+++ b/docs/guide/getting-started.zh-CN.md
@@ -0,0 +1,122 @@
+# 第一次用 Piik
+
+[English](./getting-started.md) · 简体中文 · [回到 Piik](../../README.zh-CN.md)
+
+Piik 支持一位房主分享屏幕,最多 20 位受邀观众通过浏览器观看。
+本指南介绍加入房间、体验在线 Demo、使用客户端,以及通过已有站点分享的方法。
+
+[加入房间](#加入朋友的房间) · [在线 Demo](#体验在线-demo) ·
+[Piik App](#用-piik-app-分享) · [已有站点](#用浏览器分享) · [问题排查](#遇到问题了)
+
+观众只需要浏览器和邀请链接。
+初次体验分享,可以使用在线 Demo 或客户端的 **公网邀请**。
+
+如果 Piik 只显示图示,点击顶部的 **中** 即可显示下文提到的按钮文字。
+**EN** 切换到英文,**✦** 返回图示模式。
+
+## 加入朋友的房间
+
+1. 用电脑或手机浏览器打开朋友发来的邀请链接。
+2. 等待画面出现。如果浏览器没有自动播放,点击 **播放**。
+3. 将鼠标移到画面上,或轻点画面,显示播放控制栏。
+
+播放控制栏只改变你自己看到的画面和听到的声音。
+
+<details>
+<summary>播放按钮分别做什么?</summary>
+
+| 按钮 | 作用 |
+| --- | --- |
+| **剧场模式** | 在浏览器标签页内展开画面。 |
+| **全屏观看** | 让画面铺满屏幕。 |
+| **悬浮小窗** | 浏览器支持时,把视频放进独立小窗。 |
+| **音量** | 支持增强时最高 200%,否则最高 100%;声音失真时调低一些。 |
+
+</details>
+
+只有四位房间号时,打开同一个 Piik 站点,选择 **加入房间**。
+你可能需要站点口令和房间密码。能否通过房间号加入由房主决定;
+无法加入时,请朋友发邀请链接。
+
+旧链接失效了,就请房主重新发一份当前邀请。
+App 的本地房间和临时公网邀请会随本次 App 退出而结束。
+
+## 体验在线 Demo
+
+1. 在支持屏幕共享的电脑浏览器中打开 [demo.piik.tv](https://demo.piik.tv)。
+2. 点击 **开始分享**,选择屏幕、窗口或标签页;如需声音且浏览器提供该选项,启用音频。
+3. 确认预览后,点击 **复制邀请链接**,用另一台设备打开,或发送给朋友。
+4. 体验结束后,点击 **停止分享**。
+
+演示站由项目提供,画面通过设备间直连(P2P)传输。
+在受限网络下,可能出现页面能打开、画面无法连接的情况。
+
+## 用 Piik App 分享
+
+1. 从 [GitHub Releases](https://github.com/TNTcraftHIM/Piik/releases) 或
+ [Gitee 镜像](https://gitee.com/TNTcraftHIM/Piik/releases)下载以 **`piik-app`** 开头、
+ 对应平台的压缩包,完整解压并保留目录结构。
+2. Windows 打开 `piik-app.exe`,macOS 打开 `Piik App.app`,Linux 运行 `./piik-app`。
+ 启动页会在系统浏览器里打开。
+3. 邀请不在同一局域网的朋友时,选择 **公网邀请**,再点击 **进入 Piik**。
+ 其他模式的用途见下表。
+4. 点击 **开始分享**,按可用选项选择 **浏览器**、**程序 / 窗口** 或 **屏幕**,
+ 然后选定要分享的画面与声音。
+5. 复制房间邀请发给朋友。分享期间保持 App 和分享标签页打开。
+
+| 文件名包含 | 适用平台 |
+| --- | --- |
+| `windows-amd64` | Windows x64 |
+| `darwin-arm64` | Apple 芯片;原生采集需 macOS 13 及以上 |
+| `linux-amd64` | Linux x64 |
+
+目前主要测试 Windows 客户端和浏览器分享。macOS 和 Linux 客户端尚未经过实机测试,
+欢迎有设备的朋友试用并[反馈问题](https://github.com/TNTcraftHIM/Piik/issues)。
+Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)。
+程序包与启动参数的细节见 [App 指南](../../cmd/piik-app/README.md)。
+
+### 选择 App 模式
+
+| 模式 | 什么时候用 | 需要知道 |
+| --- | --- | --- |
+| **本地房间** | 朋友和你在同一个局域网。 | 对方需要能连接到你的电脑,可以设置本地站点口令。 |
+| **公网邀请** | 朋友在别处,想临时发个邀请。 | 需要互联网连接;公网地址只在本次 App 运行期间有效。 |
+| **连接站点** | 你们已经有一个 Piik 站点。 | 输入站点地址,在原有分享页面使用 App 的采集能力。 |
+
+**网页能打开,不代表视频一定能连通。** 公网邀请为房间提供临时网页地址,
+画面和声音仍靠参与者之间的连接传输。此模式没有媒体服务器兜底,
+临时地址也不保证持续可用。所有模式都需要可用的 UDP 媒体路径。
+具体连接方式见 [App 指南](../../cmd/piik-app/README.md#modes)。
+
+## 用浏览器分享
+
+需要先有一个运行 Piik Server 的 HTTPS 站点,可以使用朋友或管理员提供的地址。
+还没有站点时,请先体验[在线 Demo](#体验在线-demo) 或使用[客户端](#用-piik-app-分享)。
+自建站点属于进阶操作,服务器、HTTPS 和网络端口的配置步骤见[部署指南](../operations/self-hosting.zh-CN.md)。
+
+1. 在电脑上打开 Piik 站点。如果站点设置了口令,先输入口令。
+2. 点击 **开始分享**,在浏览器弹窗里选择屏幕、窗口或标签页;
+ 如需声音且浏览器提供该选项,启用音频。
+3. 确认预览画面后,点击 **复制邀请链接** 发给朋友。
+4. 保持分享标签页打开。需要时使用 **暂停分享**、**切换来源** 或 **停止分享**。
+
+浏览器屏幕采集需要 HTTPS 站点或 `localhost`。
+弹窗里有哪些画面和声音可选,取决于浏览器与操作系统。
+拿到邀请链接的人可以进入这个房间,请把它发给你想邀请的人。
+
+## 遇到问题了
+
+| 你遇到的情况 | 可以先试什么 |
+| --- | --- |
+| 有画面,没声音 | 先取消视频静音。房主应选择支持分享声音的来源;如果开始时关闭了声音,请停止后重新开始并打开声音。通过 App 采集窗口或屏幕时,切换来源会保留原来的声音设置。 |
+| 没有屏幕选择弹窗 | 按系统提示允许浏览器或 App 录制屏幕。浏览器采集需要 HTTPS 或 `localhost`,请在电脑上尝试分享。 |
+| 本地邀请打不开 | 确认两台设备在同一网络且可以互相访问。访客 Wi-Fi 或防火墙规则可能阻止本地连接。 |
+| 网页能打开,画面连不上 | 点击播放控制栏的 **重新连接**;仍然失败时,检查 [WebRTC 连接设置](../../cmd/piik-app/README.md#chromium-webrtc-connections),或尝试有媒体服务器兜底的站点。 |
+| 休眠或挂起后分享中断 | 唤醒设备,回到分享标签页,必要时重新开始分享。浏览器或系统挂起可能中断采集和播放。 |
+
+反馈问题时,请附上版本、系统与浏览器、预期结果和复现步骤。
+[诊断与导出](../reference/configuration.md#diagnostics)
+说明如何收集本地报告,以及分享前需要检查哪些内容。
+
+想为朋友搭一个站点?从 [部署指南](../operations/self-hosting.zh-CN.md) 开始。
+其他内容可在 [文档导航](../README.md) 找到。
diff --git a/docs/maintenance.md b/docs/maintenance.md
index 3a7f429a..59423019 100644
--- a/docs/maintenance.md
+++ b/docs/maintenance.md
@@ -1,68 +1,95 @@
-# 项目维护与上下文治理
+# Documentation Ownership
-## 目标
+The repository is the durable source across sessions, devices and agents.
+Use [the documentation map](./README.md) to find a topic, then update its owner.
+Chat, agent summaries and an old branch do not replace current code, contracts
+and evidence. Task authority stays in [AGENTS.md](../AGENTS.md); delivery and
+verification procedures stay in [CONTRIBUTING.md](../CONTRIBUTING.md).
-仓库是跨 session、设备和 agent 的持久事实源。会影响后续工作的结论必须先进入其权威文档;聊天、agent 摘要、旧分支和临时计划都不能替代仓库真相。
+## Owners
-常驻上下文只保留每次工作都需要的边界和导航。细节按需读取,完成历史交给 Git。任务范围和交付遵循 `AGENTS.md`,最小正确结果遵循仓库内的 [`ponytail` skill](../.agents/skills/ponytail/SKILL.md);本文件只维护仓库特有的事实治理规则。
-
-## 事实分层
-
-| 内容 | 权威归属 | 维护方式 |
+| Topic | Owner | Keep here |
| --- | --- | --- |
-| 每次都必须遵守的硬约束和导航 | `AGENTS.md` | 保持短、单义、稳定;不复制流程手册或临时状态 |
-| 分支、研究、验证、PR、合并和清理流程 | `CONTRIBUTING.md` | 维护可执行的日常流程 |
-| 产品总览和领域导航 | `docs/project-memory.md` | 只保留每次 substantial task 都需要的摘要与链接 |
-| 当前生产、里程碑、阻塞项和明细索引 | `docs/status.md` | 只保留 current/index;接近 120 行或 12 KB 时提示园艺审查 |
-| 当前未决、已授权或待用户决策的工作 | `docs/todo.md` | 不是完成记录;不把 checkbox、实验或 agent 建议自动升级为 TODO |
-| 当前产品合同 | `docs/product/` | 每个领域一个 owner;只写行为、边界和非显然不变量 |
-| 架构取舍 | `docs/adr/` | 明确状态;新决定替代冲突旧决定 |
-| 可复核证据和研究结论 | `docs/research/` | 标日期、来源、推断、适用边界和许可证 |
-| 当前验证与部署边界 | `docs/verification-status.md`、`docs/deployment.md`、`docs/operations/`、`docs/reference/` | 按需读取,不保存发布流水账 |
-| 已完成工作的时间线 | commit、PR、issue | 不复制进常驻 memory 或 status |
-
-每个事实只有一个 owner。顶层文件提供链接和当前结论,不复制深层正文;`docs/README.md` 维护完整文档索引。
-
-## 顶级指令卫生
-
-[官方调研](./research/agent-context-governance.md)的共同结论是:顶层指令应是短而稳定的地图,流程和专业细节按需加载,并定期删除冲突或陈旧规则。检查器把官方边界分成推荐线和硬顶:Codex 项目指令链在默认 32 KiB 上限的 80% 提示、到上限失败;Claude 的有效启动指令在官方建议的 200 行提示,并容许到 250 行的项目缓冲;Hermes 在动态下限 20,000 字符的 80% 提示、到下限失败。`CLAUDE.md` 导入的 `AGENTS.md` 计入有效行数;必读的 repo Ponytail skill 使用同一保守包络。
-
-推荐线只触发园艺提醒,不是压缩目标。硬顶失败时应把目录专属规则迁到嵌套或 path-scoped context,把流程和参考资料迁到按需 skill/文档,简化重复措辞,并删除已完成历史或陈旧结论;不要为了过闸损失仍有消费者的约束。模块特有规则只有在对应代码存在且每次读取确有必要时,才放到最近目录的 `AGENTS.md`;流程说明进入 `CONTRIBUTING.md`,当前工作进入 `docs/todo.md`,证据与理由进入其 owner。
-
-## 真相更新顺序
-
-1. 按 [`AGENTS.md`](../AGENTS.md) 的 authority 和 scope 规则,对照完整产品模型、当前代码、测试和证据确定目标;语义未定时只冻结依赖项。
-2. 就地更新受影响的 product、ADR 或 research owner;仅在快照确实变化时同步 memory/status,未决执行项进入 TODO。
-3. 检查各 current owner 一致并形成 Git-tracked truth checkpoint,再开始依赖该结论的实现或派发。
-
-语义仍未决定时,在 TODO 记录 hold,只冻结依赖项。具体 Git、worktree、checkpoint 和 integration 流程由 `CONTRIBUTING.md` 拥有。
-
-## 机制减负审查
-
-机制减负遵循 [`ponytail`](../.agents/skills/ponytail/SKILL.md) 的最小正确结果原则,范围由 `AGENTS.md` 约束。本仓库的审查先只读清点机制服务的用户行为,量化移除后的真实退让,并与代码、配置、迁移、测试、运行时状态、部署和故障面的整体成本比较。文档也是需要同步和审查的机制:长期真相只保留产品合同、非显然不变量、算法/模型、关键取舍和外部证据,普通 UI 与实现细节由代码、测试和 PR 持有。若 owner 接受有界退让,先更新产品合同再删除失去必要性的完整表面;否则保留合同并寻找更小实现。审查不以行数为目标,也不授权无边界重构。
-
-TURN 的减负证据由 [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md) 和相关 transport research 持有;轻量/SQLite 房间取舍由 [ADR-0002](./adr/0002-memory-resident-protected-rooms.md) 持有。这些案例只证明应按当前消费者重审完整成本,不能被推广为永远删除或永远保留某类机制的规则。
-
-## 检查点与恢复
-
-在需求或优先级被接受、设计或研究结论改变、实质阶段切换、分支/PR/agent 交接、可能 compaction 或长暂停前更新事实 owner。不要为每个函数、工具调用或未形成结论的探索建立检查点。
-
-检查点按 [`AGENTS.md`](../AGENTS.md) 的 durable-truth 规则,只保存以后仍需要的结论、当前状态、下一步和真实阻塞;不保存原始对话或工具输出、完整日志、临时路径、可廉价重查的事实和过程性 TODO 流水账。
-
-恢复上下文时依次读取 `AGENTS.md`、project memory、status、TODO、相关 product/ADR/research,然后检查当前分支、`git status`、近期 commit 和 PR。摘要与仓库冲突时,以当前代码、测试和权威文档为准。
-
-## 清理规则
-
-- `project-memory.md` 和 `status.md` 接近预算时,先删除可从代码或 Git 恢复的完成/失效内容,再把仍需保留的细节迁到现有 owner;不要反复微压缩句子。
-- `todo.md` 只保留真实未完工作、明确 hold 和待用户决策,不保留完成清单或一次性审计过程。
-- `verification-status.md` 只保留仍影响验收的跨模块证据;成熟结论迁回 product、ADR、research 或 operations,过期结果删除。
-- Product 合同不追加确认流水;研究失效时更新正文及最后验证日期;只有仍有解释价值的历史取舍进入 ADR。
-- 每个重要 PR 检查 current 文档是否互相矛盾、链接是否有效、memory/status/TODO 是否仍代表现在。
-
-## 验证与自动化
-
-- 迭代中运行覆盖当前改动的最小定向检查;完整套件、真实浏览器矩阵、网络整形、跨设备、长时稳定性和部署检查在相关候选的验收边界批量运行。
-- 文档改动默认运行本地 Markdown 链接、whitespace、diff 和 repository-hygiene 检查;不因无关文档变化重跑媒体基准。
-- 断链、缺失必需 owner 和格式损坏是 hard failure。每次注入的有效 `AGENTS.md`/`CLAUDE.md` 上下文与必读的 repo Ponytail skill 使用“推荐线 warning、硬顶 failure”,避免把建议值误当死线,也避免超过工具加载边界。Product、ADR、research、operations 等按需文档的行数/字节阈值始终只是 warning:它提示检查是否应拆分二级 owner、删除历史或移出过程信息,不要求为通过门禁压缩合理正文,也不是交付质量指标。
-- 昂贵证据记录 commit、环境、结果和适用边界。只有相关路径、协议、配置、依赖、环境或门槛改变,或旧证据失败/含糊时才重跑。
-- `.githooks/pre-commit`、`scripts/check-project-state.sh` 和 PowerShell 等价入口共享 `scripts/required-project-paths.txt`。Hook 只做快速、确定、可复现的检查;工程判断留给评审和测试。
+| Universal constraints and navigation | `AGENTS.md` | Short mandatory boundaries and links; no procedure manual |
+| Branches, review, validation, PRs, releases and cleanup | `CONTRIBUTING.md` | Executable workflow |
+| Module boundaries, interface discipline and ablation | [Engineering](./reference/engineering.md) | Current responsibility map and shared coding rules |
+| Names, terminology and voice | [Naming and copy](./reference/naming.md) | Product/tool names, role labels and Chinese/English writing conventions |
+| Illustration, palette, motion and accessible layout | [Visual language](./design/visual-language.md) | Shared Browser/App design grammar |
+| Status projection | [Media status](./design/media-status.md) | Which facts each display surface may express |
+| Release identity and compatibility | [Versioning](./reference/versioning.md) | Version roles, protected interfaces and public-readiness boundary |
+| Current product behavior | `docs/product/` | One owner per domain; promises, boundaries and non-obvious invariants |
+| Architecture decisions | `docs/adr/` | Decision status, rationale and consequences; explicitly supersede changed clauses |
+| Measurements and external evidence | `docs/research/` | Date, sources, observations, inference, limits and license scope |
+| Deployment and configuration | `docs/deployment.md`, `docs/operations/`, `docs/reference/configuration.md` | Runnable operator reference; no per-release diary |
+| Compact product map | `docs/project-memory.md` | Stable summaries and domain navigation, not implementation inventories |
+| Current execution/deployment index | `docs/status.md` | Current boundaries and pointers; exact artifact identity stays in release metadata |
+| Remaining work and decisions | `docs/todo.md` | One task ledger, with executable work separated from parked ideas |
+| Unresolved physical acceptance | `docs/verification-status.md` | Still-relevant evidence gaps across modules |
+| Completed history | Git commits and PRs | Changes and outcomes; do not reproduce them in memory or TODO |
+
+Source schemas and existing conformance fixtures own exact interface fields;
+package comments own local lock/resource invariants. The engineering reference
+links to them instead of copying every field. README and guides explain how to
+use the product; technical details link to the relevant owner. English/Chinese
+entry guides are intentional translations and must change together; technical
+references keep one version.
+
+## Updating A Rule
+
+1. Trace the current product contract, actual callers and relevant evidence.
+ Search hits are leads, not proof of a defect. Separate an implementation
+ mismatch from a historical decision or a still-unaccepted proposal.
+2. Update the existing owner first. Add a new owner only for a distinct topic
+ with real consumers; give it an entry in the documentation map. Delete
+ replaced normative text elsewhere and link to the owner.
+3. Keep current owners consistent. Update memory/status only when their compact
+ snapshot materially changes; put unresolved work in TODO. Checkpoint and
+ integration timing follows CONTRIBUTING, not an automatic extra commit for
+ every small edit.
+
+When semantics are disputed, record the decision needed and hold only dependent
+implementation. At handoff or a material phase change, persist accepted rules,
+remaining work and actual blockers before relying on a conversation summary.
+Do not store tool transcripts, raw logs, temporary paths or repeated completed
+checklists as product truth.
+After an audit, put accepted constraints in their existing owners and unresolved
+work in TODO, then remove the report and handoff bundle. Do not create dated
+audit-summary directories or replacement archives of completed work.
+
+Published copy describes Piik's behavior and design directly. Remove discarded
+design labels, private operational details and conversational comparisons to
+other products. Retain primary technical evidence and required attribution or
+license notices; rewriting prose must not obscure the origin of reused work.
+
+## Consolidation And Ablation
+
+Keep one owner per fact, with short summaries where navigation needs them.
+Consolidation is not concatenating documents into one giant manual. Remove
+stale procedures and duplicated prescriptions; preserve still-consumed behavior,
+failure boundaries, reasoning and reproducible evidence. An ADR can retain a
+historical decision when its superseded status is clear.
+
+Document cost is part of [engineering ablation](./reference/engineering.md#ablation-and-review).
+Do not delete a product promise solely to shrink a file. Archive completed work
+in Git, keep candidate ideas out of active instructions, and never promote an
+agent suggestion to accepted policy simply by writing it in a checklist.
+
+The top-level context stays a map. Directory-specific instructions belong near
+the code only when that module exists and the rule is needed every time.
+The [context-governance research](./research/agent-context-governance.md) owns
+the external rationale; the existing hygiene scripts own executable limits.
+Their gardening warnings invite review, not arbitrary compression; hard failures
+for broken links, required owners and instruction-loading limits remain binding.
+
+## Checks
+
+For documentation work use the existing link, whitespace and repository-hygiene
+checks; do not rerun unrelated media benchmarks. The shared
+[`required-project-paths.txt`](../scripts/required-project-paths.txt) lists durable
+owners for both hygiene entry points. No additional checker is needed for each
+new convention.
+
+At a meaningful integration boundary check that current documents agree, links
+resolve, and memory/status/TODO still describe what remains. Expensive evidence
+retains its measured revision, environment and limits; rerun it when a relevant
+contract, dependency, platform, workload or unexplained failure changes.
diff --git a/docs/operations/github.md b/docs/operations/github.md
new file mode 100644
index 00000000..64add0c1
--- /dev/null
+++ b/docs/operations/github.md
@@ -0,0 +1,94 @@
+# GitHub Repository And Releases
+
+[Versioning](../reference/versioning.md) owns release meaning and compatibility;
+[CONTRIBUTING](../../CONTRIBUTING.md) owns review and local validation. This file
+owns the one-time GitHub settings. The source repository is public; automatic
+package publication has its own activation gate below.
+
+## Main And Pull Requests
+
+Use squash merging only, with the PR title and body as the squash commit. These
+repository settings are applied. Keep automatic branch deletion off: the normal
+cleanup step checks local worktrees and remaining references first.
+
+Protect `main` with PRs required, zero mandatory peer approvals for the solo
+maintainer, administrator enforcement, linear history, and no force pushes or
+deletions. Do not require cloud PR checks while branch/PR CI is intentionally
+quiet; local validation and acceptance precede the squash merge. PR/issue
+templates live in `.github/`; [naming](../../CONTRIBUTING.md#commit-pr-and-branch-names)
+is shared with automatic version selection.
+
+These protections are active, including conversation resolution. GitHub Pages
+uses the **GitHub Actions** publishing source and the `piik.tv` custom domain;
+the repository homepage points to `https://piik.tv`. The dedicated Website
+workflow publishes the static site under [website operations](./website.md).
+
+## Enable Automatic Publication Once
+
+Before enabling, accept the release packages, compatibility baseline, public
+copy and repository visibility; finish main protection. Then set repository
+Actions variable `PIIK_RELEASES_ENABLED` to `true`. This is a repository setting,
+not an environment variable for Piik App or Server.
+
+Subsequent accepted PRs merged to main use the existing CI workflow: calculate
+one version, validate, package Server and all App targets, and publish the same
+artifacts. Runs queue rather than overlap or cancel one another. Branches/PRs
+stay quiet; manual `client_checks` dispatch remains available for candidates.
+Writing a new version back to main is unnecessary and prohibited.
+
+For a complete publisher rehearsal, dispatch with `client_checks: true` and an
+explicit `candidate_version` such as `v1.0.0`. This builds genuine Server and
+native App artifacts under one revision and version without tagging or
+publishing. Prepare its [release-note section](../reference/versioning.md#release-notes)
+and inspect the generated preview in the run summary. For a local preview, run
+`node scripts/release-notes.mjs v1.0.0 FULL_SOURCE_SHA` from the checkout with
+full history and tags. Download that run's artifacts and pass their directory, version and
+full revision to `scripts/publish-release.mjs --dry-run` (put the flag after
+the three positional arguments). An omitted candidate version keeps the usual
+development/exact-tag identity.
+
+Enable GitHub's built-in release immutability for formal publication where
+available. Upload all assets to the draft before publishing. A failed upload can
+resume its same-source draft; a published version is never clobbered. If its
+files are wrong or incomplete, publish a corrected new version. An older retry
+must not replace a newer release's `latest` designation.
+
+To stop future automatic publication, remove/set false the activation variable;
+this does not alter existing releases or a currently running workflow. Inspect
+the active run separately. No pipeline step changes visibility or installs an
+update into a running Piik deployment.
+
+## Gitee Download Mirror
+
+[TNTcraftHIM/Piik](https://gitee.com/TNTcraftHIM/Piik) is a public README/Release
+mirror. Source, documentation and issues stay on GitHub. The publishing job uses
+the repository Actions secret `GITEE_TOKEN`, which is configured; rotate it there
+when needed. Never put it in source, a remote URL or a distributed package.
+GitHub publication continues to use the workflow's scoped token.
+
+After GitHub publication, the same job runs `scripts/mirror-release.mjs` on the
+original artifacts. Upload failure leaves the Gitee release marked as a preview.
+Rerun the failed publishing job to verify existing files and upload only missing
+ones. GitHub's published release remains unchanged. Both publishers reject
+changing a published package; use a corrected new version if its bytes are wrong.
+
+If the original Actions artifacts have expired, download that release's files
+from GitHub into an external working directory, then run:
+
+```sh
+gh release download v1.0.0 --repo TNTcraftHIM/Piik --dir /tmp/piik-mirror
+node scripts/mirror-release.mjs /tmp/piik-mirror v1.0.0 FULL_SOURCE_SHA
+```
+
+Use the release's actual version and full `target_commitish` SHA, with
+`GITEE_TOKEN` supplied through the publisher environment. `--dry-run` after the
+three arguments checks local identity, checksums and attachment sizes without
+publishing. The [release-source policy](../reference/versioning.md#release-sources)
+owns provenance, selection and quota limits. Small-file upload/download acceptance
+has passed; full-package mirror acceptance remains part of release readiness.
+
+## Platform References
+
+- [Protected branch availability](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches)
+- [Workflow concurrency and queued runs](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#example-queueing-multiple-pending-runs)
+- [Immutable release workflow](https://docs.github.com/en/code-security/concepts/supply-chain-security/immutable-releases)
diff --git a/docs/operations/self-hosting.md b/docs/operations/self-hosting.md
index f6b2b8af..e54be750 100644
--- a/docs/operations/self-hosting.md
+++ b/docs/operations/self-hosting.md
@@ -1,226 +1,93 @@
-# Self-Hosting Operations
-
-This runbook owns initial single-host service setup. Application releases use
-[deployment](../deployment.md); accepted environment values and ports are in
-[configuration reference](../reference/configuration.md).
-
-## Embedded Media Configuration
-
-The current source embeds STUN and SFU in the Piik process under
-[ADR-0013](../adr/0013-embedded-node-local-media.md). Hosted `STUN_URLS`
-advertises ordinary discovery and enables the UDP 3478 listener on
-`STUN_LISTEN_HOST` (IPv4, default `0.0.0.0`). Enabling
-`NAT_PREDICTION_ENABLED` also binds UDP 3479/3480 on that address. Local and
-public-link App modes use discovery without creating media-service listeners.
-
-Set `SFU_UDP_PORT=7882` to enable automatic embedded SFU fallback. Its IPv4 bind
-address is `SFU_LISTEN_HOST`, default `0.0.0.0`; `SFU_PUBLIC_IP` optionally
-overrides the advertised IPv4 address when the host is behind NAT. Unset or
-blank `SFU_UDP_PORT` keeps SFU disabled. SFU control uses authenticated Piik
-signaling through the Web origin. No separate media-service executable, control
-origin, or API credentials are needed by this source contract.
-
-These templates describe the embedded deployment. Its first cutover requires
-the active-session check, matching artifacts and public media verification below.
-
-## Single-Host Topology
-
-```text
-Browser -- HTTPS/WSS --> nginx :443 --> Piik :8787
-Browser <---------- DTLS-SRTP P2P ----------> Browser
-Browser -------- ordinary STUN/UDP --------> Piik :3478
-Browser -------- optional STUN/UDP --------> Piik :3479/3480
-Browser <--------- DTLS-SRTP/UDP ----------> Piik :7882
-```
+# Deploy Piik Server
+
+English · [简体中文](./self-hosting.zh-CN.md) · [Documentation](../README.md)
+
+Piik Server packages the web interface, room management and optional media
+forwarding in **one server binary**. Extract and run it; room data is stored in SQLite.
-The public baseline uses one Piik Go binary, nginx, a valid Web TLS
-certificate, and time synchronization. nginx terminates Web HTTPS/WSS and
-proxies only to Piik's private application listener; media UDP reaches the
-Go process directly. There is no separate SFU token endpoint or TCP 7880 service.
-Web and STUN may use different DNS names on the same public IP. Another proxy or
-firewall owner needs its own matching updater and recovery checks.
-
-Expose only the public listeners in
-[configuration reference](../reference/configuration.md). Piik TCP 8787 stays
-private. STUN answers Binding requests only; TURN allocations remain unavailable.
-
-## Templates
-
-- [Piik systemd unit](../../deploy/systemd/piik.service.example)
-- [nginx site](../../deploy/nginx/share.bonfire.icu.conf.example)
-
-Copy templates outside the repository, inject independent secrets through an
-access-restricted environment file or service manager, and adapt only addresses,
-domains, certificates, users, and resource limits required by the host.
-
-## Initial Setup
-
-1. Configure DNS and TLS for the Web origin and STUN name.
-2. Install nginx. The Piik release is one static binary and needs no
- language runtime or separate media-service executable.
-3. Create an unprivileged `piik` service account, `/opt/piik/releases`,
- `/opt/piik/uploads`, and an access-restricted environment file.
-4. Provision one verified initial immutable release and atomically point
- `/opt/piik/current` to it before enabling the unit. The tracked release
- wrapper is upgrade-only and deliberately refuses a missing prior release;
- this repository does not provide a generic first-install transaction.
-5. SQLite is the Hosted default. The service template selects
- `/var/lib/piik/rooms.sqlite` in its service-owned StateDirectory; retain
- that absolute path in the environment file and include it in the host's
- backup/recovery policy. Use `ROOM_DATABASE_PATH=:memory:` only for intentional
- process-only rooms. Do not leave an empty override in a service environment.
-6. Install the tracked service and proxy templates. Bind HTTP to loopback on
- bare metal; STUN and SFU retain their independent public IPv4 binds.
- Containers may bind HTTP to `0.0.0.0` only when publishing/firewall rules
- preserve the private application boundary.
-7. Apply the public-port allowlist and confirm every retired TURN/TCP port
- is closed.
-8. Start Piik, then nginx. Piik binds its configured media listeners
- before accepting signaling and closes them with the application; a listener
- bind failure rolls back startup. Verify public UDP reachability separately.
-
-## Optional Container
-
-The [runtime-only Dockerfile](../../deploy/container/Dockerfile) consumes the
-existing linux/amd64 Server release; it does not rebuild Go or Browser assets.
-Its pinned [Distroless static non-root base](https://github.com/GoogleContainerTools/distroless)
-includes CA certificates for HTTPS release checks and has no shell or package
-manager. This is an optional recipe, not a published image or automatic installer.
-On the local Linux Docker runtime, non-root/read-only startup, both persistence
-modes, diagnostics export, STUN Binding and media listener cleanup pass. That
-check covers the container lifecycle, not public-network SFU media or the host's
-proxy/firewall configuration; verify those on the target deployment.
-
-Verify the release archive against its descriptor and manifest using the
-[release procedure](../deployment.md), then extract its four files into a new
-build-context directory: `piik-server`, `LICENSE`, `THIRD-PARTY-NOTICES.txt`
-and `REVISION`. Use that directory, not the repository or a secrets directory:
+## Try it locally
+
+These server instructions use a Linux x64 machine.
+
+Download the **Linux x64 Server** archive from [GitHub Releases](https://github.com/TNTcraftHIM/Piik/releases)
+or the [Gitee mirror](https://gitee.com/TNTcraftHIM/Piik/releases),
+extract it, and run the following in its directory:
```sh
-docker build --platform linux/amd64 \
- -f /path/to/Piik/deploy/container/Dockerfile \
- -t piik:<full-revision> /path/to/extracted-runtime
-docker run --rm --env-file /path/to/piik.env \
- piik:<full-revision> --check-config
+./piik-server
```
-Use the existing [production configuration](../reference/configuration.md).
-Keep `LISTEN_HOST=0.0.0.0` inside the container and retain the host's existing
-HTTPS/WebSocket proxy. With Docker port mapping, set `SFU_PUBLIC_IP` to the
-reachable server IPv4 address when SFU is enabled; container-private candidates
-are not Internet-reachable. Advertised STUN names must resolve to the server's
-public address, and UDP must reach the container directly.
+Open `http://localhost:8787`. This is a local trial; use the configuration below
+to let friends connect over the internet. To start a temporary room on your computer,
+use the [Piik App guide](../guide/getting-started.md).
+
+## Put it online
-The following example publishes the standard listeners and keeps HTTP private
-to a proxy running on the same host. Omit UDP publish options for disabled SFU
-or auxiliary STUN listeners; use the matching port if configuration changes it.
+You need a Linux x64 server and a domain pointing to its public IP.
+The example uses `share.example.com`; replace it with your domain.
+
+### 1. Configure and start Piik
+
+Create a `.env` file next to the binary:
+
+```dotenv
+PIIK_ENV=production
+LISTEN_HOST=127.0.0.1
+PUBLIC_BASE_URL=https://share.example.com
+STUN_URLS=stun:share.example.com:3478
+MAX_VIEWERS_PER_ROOM=20
+SITE_ACCESS_PASSWORD=
+```
+
+Run these commands from that directory as a regular user:
```sh
-docker run -d --name piik --restart unless-stopped --stop-timeout 20 \
- --read-only --cap-drop ALL --security-opt no-new-privileges \
- --env-file /path/to/piik.env \
- --mount type=volume,source=piik-data,target=/home/nonroot \
- -e ROOM_DATABASE_PATH=/home/nonroot/rooms.sqlite \
- -p 127.0.0.1:8787:8787/tcp \
- -p 3478:3478/udp -p 3479:3479/udp -p 3480:3480/udp -p 7882:7882/udp \
- piik:<full-revision>
+./piik-server --check-config
+./piik-server
+```
+
+The server reads `.env` automatically and stores rooms in `rooms.sqlite` in the
+working directory. A blank `SITE_ACCESS_PASSWORD` allows
+entry without a site passphrase; set 8–128 visible ASCII characters to require
+one. Room invitations and access settings still apply.
+
+### 2. Enable HTTPS
+
+Use your existing HTTPS reverse proxy to forward to `127.0.0.1:8787` with
+WebSocket support. If you do not have one, [install Caddy](https://caddyserver.com/docs/install)
+and add this to its Caddyfile:
+
+```caddyfile
+share.example.com {
+ reverse_proxy 127.0.0.1:8787
+}
```
-The image's `/home/nonroot` is owned by UID/GID `65532:65532` with mode `0700`.
-A new named volume inherits that directory; an existing volume or bind mount
-must already be writable by that identity. Keep this volume when replacing the
-container. Set `ROOM_DATABASE_PATH=:memory:` for memory-only room authority. Diagnostics
-remain opt-in and use `/home/nonroot/logs`; [export and retention](../reference/configuration.md#diagnostics)
-remain the operator's responsibility. Do not mount application files writable.
-With diagnostics enabled, `docker kill --signal=USR1 piik` requests a local
-export without stopping the container; the ZIP remains in the mounted log directory.
-
-Check `/healthz` from the host and public proxy, then verify configured STUN/SFU
-UDP and room/media behavior using [operational verification](#operational-verification).
-There is no shell-based healthcheck in the image. Retain the previous image,
-environment and volume backup before replacement. Stop the old container before
-reusing its listeners or SQLite volume, and recreate with the previous image and
-environment if verification fails. The bare-metal `release-app.sh` wrapper does
-not manage containers. The first move from external media services still follows
-the coordinated cutover below; this recipe changes no proxy or firewall itself.
-
-## Coordinated Embedded-Media Cutover
-
-Replacing the external STUN/SFU services, including Node-to-Go where still
-needed, is one explicitly authorized infrastructure and protocol transaction.
-The routine application wrapper cannot perform or recover it.
-
-1. Prepare and verify matching Web/Server signaling and native protocol v9
- App artifacts. Check active sessions and obtain the owner's acceptance of
- share interruption before cutover; old pages and Apps must reload or
- update together.
-2. Retain the exact prior release path, Piik unit and drop-ins, environment,
- nginx configuration, and external media-service units, configuration, secrets,
- and enabled/active state for rollback. Keep this material access-restricted
- outside the repository. Define recovery for any persistent-state or firewall
- surface the transaction actually changes.
-3. Stage the current unit with
- `ExecStart=/opt/piik/current/piik-server` and
- `PIIK_ENV=production`. Remove retired `NODE_ENV`, `PEER_ASSISTED_MEDIA`
- and external `LIVEKIT_*` configuration; use the current
- [environment contract](../reference/configuration.md), including
- `SFU_UDP_PORT=7882` when fallback is enabled. Replace route `NODE_DEBUG` with
- `PIIK_DEBUG=route` when needed. Validate the new binary's production
- configuration as the service user before switching.
-4. Stop Piik and the old coturn/LiveKit services. Disable those old media
- services and remove the installed Piik LiveKit-readiness drop-in so they
- cannot reclaim ports or delay startup. Verify that UDP 3478/3479/3480/7882
- are released before the new Go process binds them. Install the current unit,
- environment and nginx template, remove the old RTC proxy locations, validate
- nginx, and reload systemd. Preserve unrelated proxy headers, limits, TLS,
- asset handling, and firewall rules.
-5. Atomically point the current release at the verified candidate, start
- Piik, and reload nginx. Verify the actual unit command and environment,
- local/public health, the matching Web asset, UDP listener ownership, public
- STUN Binding and admitted SFU media, and the agreed active-session outcome.
-6. On failure, stop the new Go process and confirm it released its UDP sockets.
- Restore the exact prior application path, unit/drop-ins, environment, proxy
- and changed infrastructure configuration; reload systemd and validate nginx.
- Restore the previous external service states before starting the previous
- application with its matching unit, then prove health and media. Restore
- matching pages and Apps as part of protocol rollback. A symlink-only
- rollback cannot recover this transaction.
-
-Retain the recovery material through the agreed acceptance window. This is a
-single replacement contract with no permanent legacy aliases or migration mode.
-Later application-only releases use the ordinary
-[release wrapper](../deployment.md#atomic-cutover).
-
-## Optional NAT Prediction
-
-Allow UDP 3479 and 3480 in both the cloud security group and the existing
-nftables input rule, validating the complete ruleset with
-`nft -c -f /etc/nftables.conf`. Set `NAT_PREDICTION_ENABLED=true` and restart
-Piik within an accepted service window. Verify `ss -lunp` shows all three
-Piik STUN listeners and that a public Binding request succeeds on each.
-Do not add auxiliary URLs to `STUN_URLS`; enabled connections derive them from
-the ordinary STUN authority. Keep both firewall rules while the capability is
-enabled. Set `NAT_PREDICTION_ENABLED=false` and restart Piik before removing
-the auxiliary firewall rules. Avoid verbose STUN/ICE logging because those
-requests contain client IP addresses.
-
-These same-IP auxiliary ports measure destination-port mapping behavior. They
-are not a full RFC 5780 alternate-address deployment; that requires a second
-public IPv4.
-
-## Operational Verification
-
-- `/healthz` returns `{"status":"ok"}` locally and through the public origin.
-- Piik and nginx are active with expected restart counts and bounded
- logs/resources; Piik owns the configured STUN/SFU UDP listeners.
-- The official Trickle ICE sample obtains an ordinary UDP `srflx` candidate from
- the configured STUN service and no relay candidate.
-- A direct room presents media on two networks when Peer ICE succeeds.
-- A constrained route creates one managed Host publication and only admitted
- subscriptions over embedded SFU UDP; Peer descendants remain ordinary P2P.
-- Blocking all UDP reaches a clear bounded failure.
-- Restarting Piik in stable mode retains room authority while Browser
- sessions and media reconnect from fresh process state.
-
-Representative network, mobile, audio, 20-Viewer, and long-running evidence is
-tracked in [verification status](../verification-status.md), not in this runbook.
+Reload Caddy. It obtains and renews the certificate automatically when DNS points
+to the server and TCP 80/443 are reachable. See [Caddy's HTTPS proxy guide](https://caddyserver.com/docs/quick-starts/reverse-proxy#https).
+
+### 3. Open the ports and verify
+
+Allow **TCP 80/443** for HTTPS and **UDP 3478** for STUN in the server firewall
+and cloud security group. Keep TCP 8787 private. The STUN hostname must resolve
+directly to the server; a CDN HTTP proxy does not forward its UDP traffic.
+
+Open `https://share.example.com/healthz`; it should return `{"status":"ok"}`.
+Then open the site, share a screen and join from another device. This initial
+configuration uses P2P media, so participants need a usable UDP path.
+
+## Optional: media fallback
+
+Add `SFU_UDP_PORT=7882` to `.env`, allow UDP 7882, and restart Piik to enable
+automatic SFU fallback. When the server is behind NAT, also set `SFU_PUBLIC_IP`
+to its reachable public IPv4 address. The same binary provides the fallback.
+
+## Keep it running and update
+
+For automatic startup, use the [systemd or container guide](./service-management.md).
+Keep `.env` and `rooms.sqlite` across updates. Back up room data while the server is
+stopped, replace the executable with the new release, then restart and check
+health and room access. Read release notes before an upgrade that changes data formats.
+
+[All settings and ports](../reference/configuration.md) ·
+[Maintainer release tooling](../deployment.md)
diff --git a/docs/operations/self-hosting.zh-CN.md b/docs/operations/self-hosting.zh-CN.md
new file mode 100644
index 00000000..98a19ed6
--- /dev/null
+++ b/docs/operations/self-hosting.zh-CN.md
@@ -0,0 +1,87 @@
+# 部署 Piik Server
+
+[English](./self-hosting.md) · 简体中文 · [文档导航](../README.md)
+
+Piik Server 将网页、房间管理和可选的媒体转发打包在**一个服务端程序**中。
+解压后即可运行,房间数据保存在 SQLite 中。
+
+## 先在本机试用
+
+以下服务端操作在 Linux x64 环境中执行。
+
+从 [GitHub Releases](https://github.com/TNTcraftHIM/Piik/releases) 或
+[Gitee 镜像](https://gitee.com/TNTcraftHIM/Piik/releases)下载 **Linux x64 服务端**程序包,
+解压后,在该目录运行:
+
+```sh
+./piik-server
+```
+
+打开 `http://localhost:8787` 即可试用。需要让朋友通过互联网访问时,
+继续完成下方配置。如果只想在自己的电脑上临时开房间,可直接使用 [Piik App](../guide/getting-started.zh-CN.md#用-piik-app-分享)。
+
+## 对外提供服务
+
+准备一台 Linux x64 服务器,以及一个指向服务器公网 IP 的域名。
+下文以 `share.example.com` 为例,请替换成自己的域名。
+
+### 1. 配置并启动 Piik
+
+在程序旁新建 `.env` 文件:
+
+```dotenv
+PIIK_ENV=production
+LISTEN_HOST=127.0.0.1
+PUBLIC_BASE_URL=https://share.example.com
+STUN_URLS=stun:share.example.com:3478
+MAX_VIEWERS_PER_ROOM=20
+SITE_ACCESS_PASSWORD=
+```
+
+使用普通用户,在该目录执行:
+
+```sh
+./piik-server --check-config
+./piik-server
+```
+
+程序会自动读取 `.env`,并将房间数据保存在工作目录的 `rooms.sqlite` 中。
+`SITE_ACCESS_PASSWORD` 留空时,进入站点无须口令;
+如需设置口令,可填写 8–128 个可见 ASCII 字符。房间邀请与加入权限仍由房主管理。
+
+### 2. 配置 HTTPS
+
+如果已有 HTTPS 反向代理,将请求转发到 `127.0.0.1:8787`,并启用 WebSocket 支持。
+如果还没有,可以[安装 Caddy](https://caddyserver.com/docs/install),在 Caddyfile 中加入:
+
+```caddyfile
+share.example.com {
+ reverse_proxy 127.0.0.1:8787
+}
+```
+
+重新加载 Caddy。域名解析正确且 TCP 80/443 可访问时,它会自动申请和续期证书。
+具体操作见 [Caddy 的 HTTPS 代理说明](https://caddyserver.com/docs/quick-starts/reverse-proxy#https)。
+
+### 3. 放行端口并检查
+
+在服务器防火墙和云平台安全组中放行 **TCP 80/443**(HTTPS)和 **UDP 3478**(STUN)。
+TCP 8787 仅供本机反向代理访问。STUN 域名需要直接解析到服务器,不能只经过 CDN 的 HTTP 代理。
+
+打开 `https://share.example.com/healthz`,应返回 `{"status":"ok"}`。
+随后打开站点,分享一个画面,并用另一台设备加入验证。
+上述基础配置使用 P2P 传输,参与者之间需要可用的 UDP 通路。
+
+## 可选:启用媒体兜底
+
+在 `.env` 中添加 `SFU_UDP_PORT=7882`,放行 UDP 7882,再重启 Piik,即可启用自动 SFU 兜底。
+如果服务器处于 NAT 后方,还需将 `SFU_PUBLIC_IP` 设置为外部可达的公网 IPv4 地址。
+这项功能由同一个服务端程序提供。
+
+## 长期运行与更新
+
+需要开机启动时,参阅 [systemd 与容器配置](./service-management.md)。
+更新时保留 `.env` 和 `rooms.sqlite`:停止服务、备份房间数据、替换新版程序,再启动并检查健康状态和房间访问。
+涉及数据格式变化的版本,请先阅读发布说明。
+
+[全部配置与端口](../reference/configuration.md) · [维护者发版工具](../deployment.md)
diff --git a/docs/operations/service-management.md b/docs/operations/service-management.md
new file mode 100644
index 00000000..12fafda9
--- /dev/null
+++ b/docs/operations/service-management.md
@@ -0,0 +1,104 @@
+# Service Management
+
+For first installation, use the [short self-hosting guide](./self-hosting.md).
+This reference covers a persistent Linux service and the optional container recipe.
+
+## systemd
+
+The [service template](../../deploy/systemd/piik.service.example) runs as the
+`piik` user, reads `/etc/piik/piik.env`, and starts
+`/opt/piik/current/piik-server`. Create the service account and place the extracted
+release at that path, or point `current` at its release directory. Copy your
+configuration to `/etc/piik/piik.env` and set
+`ROOM_DATABASE_PATH=/var/lib/piik/rooms.sqlite`; the unit creates this state directory.
+Keep the environment file readable only by its operator.
+
+Install the template as `/etc/systemd/system/piik.service`, then run:
+
+```sh
+sudo systemctl daemon-reload
+sudo systemctl enable --now piik
+sudo systemctl status piik
+```
+
+Keep HTTP bound to loopback when the HTTPS proxy runs on the same host.
+STUN and optional SFU use their own public UDP listeners. An existing nginx
+installation can use the [proxy example](../../deploy/nginx/piik.conf.example)
+after adapting the domain and certificate paths.
+
+## Container
+
+The [runtime-only Dockerfile](../../deploy/container/Dockerfile) consumes the
+existing linux/amd64 Server release; it does not rebuild Go or Browser assets.
+Its pinned [Distroless static non-root base](https://github.com/GoogleContainerTools/distroless)
+includes CA certificates for HTTPS release checks and has no shell or package
+manager. This is an optional recipe, not a published image or automatic installer.
+
+Verify the release archive against its descriptor and manifest using the
+[release procedure](../deployment.md), then extract its four files into a new
+build-context directory: `piik-server`, `LICENSE`, `THIRD-PARTY-NOTICES.txt`
+and `REVISION`. Use that directory, not the repository or a secrets directory:
+
+```sh
+docker build --platform linux/amd64 \
+ -f /path/to/Piik/deploy/container/Dockerfile \
+ -t piik:<full-revision> /path/to/extracted-runtime
+docker run --rm --env-file /path/to/piik.env \
+ piik:<full-revision> --check-config
+```
+
+Use the existing [production configuration](../reference/configuration.md).
+Keep `LISTEN_HOST=0.0.0.0` inside the container and retain the host's existing
+HTTPS/WebSocket proxy. With Docker port mapping, set `SFU_PUBLIC_IP` to the
+reachable server IPv4 address when SFU is enabled; container-private candidates
+are not Internet-reachable. Advertised STUN names must resolve to the server's
+public address, and UDP must reach the container directly.
+
+The following example publishes the standard listeners and keeps HTTP private
+to a proxy running on the same host. Omit UDP publish options for disabled SFU
+or auxiliary STUN listeners; use the matching port if configuration changes it.
+
+```sh
+docker run -d --name piik --restart unless-stopped --stop-timeout 20 \
+ --read-only --cap-drop ALL --security-opt no-new-privileges \
+ --env-file /path/to/piik.env \
+ --mount type=volume,source=piik-data,target=/home/nonroot \
+ -e ROOM_DATABASE_PATH=/home/nonroot/rooms.sqlite \
+ -p 127.0.0.1:8787:8787/tcp \
+ -p 3478:3478/udp -p 3479:3479/udp -p 3480:3480/udp -p 7882:7882/udp \
+ piik:<full-revision>
+```
+
+The image's `/home/nonroot` is owned by UID/GID `65532:65532` with mode `0700`.
+A new named volume inherits that directory; an existing volume or bind mount
+must already be writable by that identity. Keep this volume when replacing the
+container. Set `ROOM_DATABASE_PATH=:memory:` for memory-only room authority. Diagnostics
+remain opt-in and use `/home/nonroot/logs`; [export and retention](../reference/configuration.md#diagnostics)
+remain the operator's responsibility. Do not mount application files writable.
+With diagnostics enabled, `docker kill --signal=USR1 piik` requests a local
+export without stopping the container; the ZIP remains in the mounted log directory.
+
+Check `/healthz` from the host and public proxy, then verify configured STUN/SFU
+UDP and room/media behavior using [operational verification](#operational-verification).
+There is no shell-based healthcheck in the image. Retain the previous image,
+environment and volume backup before replacement. Stop the old container before
+reusing its listeners or SQLite volume, and recreate with the previous image and
+environment if verification fails. The bare-metal `release-app.sh` wrapper does
+not manage containers. This recipe changes no proxy or firewall itself.
+
+## Operational Verification
+
+- `/healthz` returns `{"status":"ok"}` locally and through the public origin.
+- Piik and the HTTPS proxy are active with expected restart counts and bounded
+ logs/resources; Piik owns the configured STUN/SFU UDP listeners.
+- The official Trickle ICE sample obtains an ordinary UDP `srflx` candidate from
+ the configured STUN service and no relay candidate.
+- A direct room presents media on two networks when Peer ICE succeeds.
+- A constrained route creates one managed Host publication and only admitted
+ subscriptions over embedded SFU UDP; Peer descendants remain ordinary P2P.
+- Blocking all UDP reaches a clear bounded failure.
+- Restarting Piik in stable mode retains room authority while Browser
+ sessions and media reconnect from fresh process state.
+
+Representative network, mobile, audio, 20-Viewer, and long-running evidence is
+tracked in [verification status](../verification-status.md), not in this runbook.
diff --git a/docs/operations/website.md b/docs/operations/website.md
new file mode 100644
index 00000000..1f32a226
--- /dev/null
+++ b/docs/operations/website.md
@@ -0,0 +1,93 @@
+# Public website
+
+The website source is `site/`. It explains Piik; it does not run rooms, signaling
+or media. The [public introduction guide](../design/public-introduction.md) owns
+its content and design boundary.
+
+## Public Destinations
+
+| Entry | Destination |
+| --- | --- |
+| Website | [piik.tv](https://piik.tv) |
+| P2P-only demo on the separate US server | [demo.piik.tv](https://demo.piik.tv) |
+| App downloads and release notes | [GitHub Releases](https://github.com/TNTcraftHIM/Piik/releases) |
+| Download mirror for domestic access | [Gitee Releases](https://gitee.com/TNTcraftHIM/Piik/releases) |
+| Documentation index | [Repository documentation](../README.md) |
+
+The introduction is prepared with these links. DNS, deployment and release
+publication must be verified when publishing.
+
+GitHub Pages can serve the complete website: it hosts
+[static HTML, CSS and JavaScript](https://docs.github.com/en/pages/getting-started-with-github-pages/what-is-github-pages).
+The demo also needs the Go service for room authority, WebSocket signaling and
+UDP STUN, so it runs on the separate US server rather than Pages.
+
+## Public Demo Configuration
+
+The chosen demo allows entry without a site password and provides P2P sharing
+without SFU fallback. Use the [self-hosting runbook](./self-hosting.md) with:
+
+```dotenv
+PIIK_ENV=production
+LISTEN_HOST=127.0.0.1
+PORT=8787
+PUBLIC_BASE_URL=https://demo.piik.tv
+ALLOWED_ORIGINS=https://demo.piik.tv
+SITE_ACCESS_PASSWORD=
+ROOM_DATABASE_PATH=/var/lib/piik/rooms.sqlite
+MAX_VIEWERS_PER_ROOM=20
+STUN_URLS=stun:demo.piik.tv:3478
+NAT_PREDICTION_ENABLED=true
+SFU_UDP_PORT=
+```
+
+Point `demo.piik.tv` directly at the US server so UDP reaches its STUN listeners;
+allow UDP 3478/3479/3480 and terminate HTTPS/WSS at Caddy. The demo uses the
+standard [systemd service](./service-management.md#systemd), with its release
+under `/opt/piik/current` and configuration at `/etc/piik/piik.env`. The service
+unit provides the SQLite state directory. Room ownership, invitations and private-room
+admission still apply. The [configuration reference](../reference/configuration.md)
+owns each setting and its bounds.
+
+For updates, verify the release descriptor and manifest before placing a new
+release under `/opt/piik/releases/`. Stop Piik, back up its SQLite state, switch
+`current` to the verified release, and restart. Check local/public health,
+WebSocket room access and STUN. Keep the previous release and state backup until
+acceptance; restore both with Piik stopped if rollback is needed. The nginx-specific
+maintainer wrapper does not manage this Caddy installation.
+
+## Preview
+
+With the repository's development dependencies installed:
+
+```sh
+npm run build:website
+npm run preview:website
+```
+
+Open `http://127.0.0.1:18890`. Rebuild after editing source. The build bundles the
+film's real product components into an isolated demonstration frame; publishing
+`build/site/` needs no Node runtime or backend. Vite preview supplies HTTP byte
+ranges for seeking the soundtrack. Keep asset links relative so both a custom
+domain and GitHub's `/Piik/` project path work.
+
+## Publish when approved
+
+1. Verify the public copy and destinations above, publish the release artifacts
+ and open the source repository as part of the approved public launch.
+2. In repository **Settings > Pages**, choose **GitHub Actions** as the source.
+ Use the dedicated Pages workflow, not publication of the repository root or
+ all of `docs/`, which includes developer research and operational reference.
+3. Set the approved `piik.tv` custom domain in Pages settings and configure its
+ DNS using GitHub's [current domain instructions](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site).
+ Actions publishing does not need a `CNAME` file in the source tree.
+4. Dispatch **Website** from `main` after the reviewed site is merged. The
+ workflow builds and uploads only `build/site/`; no App/Server packaging is run. Verify the
+ domain, HTTPS, both languages, relative asset paths and primary links.
+
+There is no automatic deployment on branch pushes. The workflow is prepared,
+but writing it does not enable Pages or change DNS. The private production
+site and the US P2P-only demo remain separate deployments.
+
+For rollback, dispatch the previously accepted site revision from a reviewed
+revert on `main`; runtime App/Server binaries and databases are unaffected.
diff --git a/docs/product/media-quality.md b/docs/product/media-quality.md
index f3b95e93..51ad88b4 100644
--- a/docs/product/media-quality.md
+++ b/docs/product/media-quality.md
@@ -4,7 +4,8 @@ This file owns the current Browser and App media contract. Detailed measurements
platform limits live in [realtime quality research](../research/realtime-quality-adaptation.md)
and [screen-audio research](../research/browser-screen-audio-quality.md).
[ADR-0007](../adr/0007-path-isolated-representation-quality.md) owns Browser
-source intent and codec selection; [ADR-0013](../adr/0013-embedded-node-local-media.md)
+source intent and codec selection, [ADR-0008](../adr/0008-window-scoped-audio-capture.md)
+owns screen-audio scope, and [ADR-0013](../adr/0013-embedded-node-local-media.md)
owns the current candidate's shared Native/SFU output model. This file describes
that source contract. [Status](../status.md) separates it from the last known
production behavior and remaining acceptance.
diff --git a/docs/product/presentation-lifecycle.md b/docs/product/presentation-lifecycle.md
index 14ae661e..3894c5bd 100644
--- a/docs/product/presentation-lifecycle.md
+++ b/docs/product/presentation-lifecycle.md
@@ -11,6 +11,13 @@ available, starting a share and joining a room are equally discoverable actions;
joining expands the four-digit room form in place, while `/join` remains a direct
entry route. Users never choose a media topology.
+Host entry requires both site access and a validated capability description.
+Initial entry, retry and password recovery load the same prerequisites; failed
+authentication cannot leave a later successful entry using absent capability
+state. A capability-load failure remains retryable and does not imply that a
+service is available or disabled. Viewer/Join entry does not need this Host-only
+description.
+
The Host workspace centers the capture preview, room code, invitation and common
share controls. The Viewer workspace centers one persistent 16:9 video stage,
room identity, current state, roster, and one manual media-reconnect action.
@@ -25,6 +32,13 @@ Browser picker and any exact App-owned native windows. It never chooses a
window automatically. A reproduced Browser-window, capture, or background
failure is required before introducing an embedded Web runtime.
+Server and App share one control layout and vocabulary. Deployment capabilities
+may fix a control on or off, but do not remove its place in the interface;
+disabled controls explain their reason in text and pure-visual modes. Real
+workflow differences remain explicit: site authorization, opt-in diagnostics
+and the capture/audio capabilities of the connected device are not alternate
+versions of the product UI.
+
A remembered App activation permits discovery when choosing a source or
receiving media; it does not make App a prerequisite for sharing. Idle Host
pages hold no App control session. Ordinary Web entry opens the Browser picker
@@ -38,47 +52,69 @@ retire another operation's media. Optional native ingress uses an already
available connection without another scan. If it is not ready at Browser
startup, that share keeps Browser senders.
-## Visual Language
+A reachable Piik App with an incompatible control protocol is distinct from an
+absent App. Discovery continues looking for a compatible process before reporting
+the mismatch; the source selector retains Browser operation and offers update/
+refresh guidance. Discovery metadata may grow, while known identity and capability
+types remain validated. Missing optional capabilities are unavailable; control
+commands and responses retain their strict protocol contract.
-The interface presents one small shared living room rather than an operations
-dashboard. The television is the media stage, the couch and pawns make presence
-spatial, the shelf separates watching from controls, and the room display keeps
-the four-digit code prominent. This metaphor must clarify the same product
-state on Host and Viewer pages; decoration never creates a second state model.
+## Visual Language
Chinese, English, and pure-visual modes are three expressions of the same typed
-state and command catalog. A fresh Browser starts in visual mode and persists
-an explicit later choice. Text modes use concise copy. Visual mode uses one
-consistent stroke language for single concepts, small panel comics for causes
-and sequences, and literal scene objects for people, rooms, and media. Glyphs do
-not form sentences. Universal digits, transport symbols, URLs, and measured
-values remain literal when users need the data.
-
-Control hints and state comics use the same television for shared or watched
-media. Browser chrome identifies the application UI; a window title bar or a
-display stand identifies the capture target. A server in a media path means
-actual SFU relay, not merely opening a configured Site.
-
-Motion explains entry, transition, progress, and control feedback. Operational
-status stays still; ambient motion is limited to the App brand mark's
-occasional idle wink.
-All meaning remains available with reduced motion. Functional
-controls remain native buttons or inputs with localized accessible names, and
-hover, keyboard focus, and touch receive equivalent guidance.
-
-The visual hierarchy, interaction ownership, and information order remain the
-same across themes and viewport sizes. Responsive layout may reflow or scroll a
-bounded visualization, but it must not hide a primary action, truncate an
-essential value, overlap controls, or change product semantics.
+state and command catalog. On first use, the App and Server UI follow the
+Browser's primary system language: Chinese uses Chinese text, and other
+languages use English. Pure-visual mode remains an explicit choice. An explicit
+later choice is persisted and takes precedence over that default. Text modes
+use concise copy.
-## Playback Ownership
+The [visual language](../design/visual-language.md) is the single owner of
+illustrative roles and objects, semantic colour, panel grammar, motion,
+accessible input and responsive hierarchy.
-One native `<video>` element owns Viewer play/pause, volume, mute, and fullscreen.
-Those actions are local and never change Host capture, room state, routing, or
-other Viewers. The Host preview has no media controls; explicit Host actions own
-authoritative share pause and stop.
+## Playback Ownership
-Autoplay rejection exposes the native play action. A connection, track object,
+One `<video>` element owns Viewer playback and frame proof. The shared playback
+bar reflects that element and provides local play/pause, mute, volume, theater,
+picture-in-picture, fullscreen and the existing reconnect action. It stays reachable while waiting
+or disconnected. Theater and fullscreen are separate modes; fullscreen includes
+the playback bar. Identity, connection details and topology stay in the deck.
+
+The bar spans the screen's lower edge. Narrow screens separate audio controls
+from window actions into two rows and retain 44px action targets. Playing video hides the bar
+after two idle seconds, following [Media Chrome's default](https://github.com/muxinc/media-chrome/blob/main/docs/src/pages/docs/en/components/media-controller.md#autohide).
+Pause or unavailable playback keeps it visible. Control hover, keyboard focus,
+dragging and an open tooltip hold it open; mouse movement reveals it, and a
+touch tap on the picture toggles only visibility. One presentation-only idle
+timer owns this behavior; it never changes playback or route state. Controls
+follow the shared [motion grammar](../design/visual-language.md#motion-grammar).
+
+Volume starts on native audio output. An explicit setting away from 100% activates
+a local Web Audio stream source and gain, from silence to 200% amplitude. This also
+avoids iPhone's system-owned `video.volume`. This output
+exclusively owns sound while running, follows video pause and user mute, and
+rebinds when the audio track changes. It never modifies the received track or
+the stream relayed downstream. Unmount closes the graph. Browsers without gain
+support retain 0–100%; video-only system fullscreen also hands audio back to the
+native controls at at most 100%, rather than running two outputs.
+
+This uses the standard [Web Audio stream-source and gain nodes](https://www.w3.org/TR/webaudio/).
+The gain is amplitude scaling, so loud source peaks can clip above 100%.
+
+Picture-in-picture uses the browser's native video window, including Safari's
+presentation-mode API. Native enter/leave events own its displayed state; closing
+the window or replacing the received stream does not create another playback
+owner. Successful entry exits this video's other fullscreen mode, and unmount
+closes only this video's window. Unavailable capabilities remain disabled with
+an explanation. The native window contains video and system controls, not page
+overlays or the custom bar. See the [PiP specification](https://w3c.github.io/picture-in-picture/)
+and [Safari integration](https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls).
+
+Local playback actions never change Host capture or another Viewer. Reconnect
+retains the existing route-operation owner. The Host preview remains muted and
+has no media controls; explicit Host actions own authoritative pause and stop.
+
+Autoplay rejection exposes the play action. A connection, track object,
or `playing` event alone is not proof that the current route is visible. The
Viewer removes its blocking presentation only after a current-generation frame
is composited, using `requestVideoFrameCallback()` where available and a decoded-
@@ -97,9 +133,12 @@ a replacement controller restarted revision numbering; ordinary updates remain
monotonic within that authority. A Viewer frame belongs to its local media generation and remains
current across unrelated graph revisions until that exact binding is replaced,
invalidated, or terminally failed. Pending candidates never own the primary
-badge, status line, or overlay while committed media remains proved. Those
-surfaces share the presentation reducer; raw transport snapshots provide route
-labels, reconnect authority, and diagnostics only.
+badge, status line, or overlay while committed media remains proved. A shared
+visual projection maps those facts to title, media status, notices and
+overlays. None of these views owns state for another. Connection availability,
+actual playback and quality limitation remain separate; raw transport snapshots
+do not prove playback or quality. The [status preview](../design/media-status.md)
+records the visual vocabulary and the evidence needed for participant lamps.
Excluding time spent in the Browser's capture/play authorization UI, a Viewer
request targets a first visible frame within three seconds. Until then, the page
@@ -107,9 +146,17 @@ must continuously show a truthful accessible connection stage rather than a
black screen, ICE-connected state, or unproved `playing` event.
- A proved current frame remains visible behind non-terminal recovery state.
-- Host roster connection state follows the server's committed physical media
- path. A pending candidate or temporarily stale quality sample may annotate
- optimization, but cannot downgrade an active Viewer to routing.
+- The [status projection](../design/media-status.md#projection-rules) owns the
+ television, Header, notices, participant lamps and title. These consumers
+ cannot turn an unproved frame into playback or ordinary quality into failure.
+- The Host's couch and Viewer overview share the
+ [participant projection](../design/media-status.md#projection-rules). The
+ Host's own pawn has no additional lamp. Committed `mediaReady` owns readiness;
+ transport diagnostics and quality samples cannot override it in either direction.
+- Viewers do not infer another Viewer's quality or diagnose missing readiness
+ as terminal failure; roster readiness and quality evidence remain distinct.
+- An overlay explains the absence of a usable picture, authoritative Host pause,
+ or a required user action. Ordinary quality warnings never cover playback.
- Host pause retains the current frame and waits for resume.
- Host signaling loss alone does not invalidate media that is still healthy.
- Exact media failure or terminal route failure invalidates current-frame proof
@@ -121,10 +168,11 @@ black screen, ICE-connected state, or unproved `playing` event.
state never forces the user out of fullscreen.
Visibility, page freeze, and pagehide suppress application decoded-stall
-authority. Returning to the page rebaselines time and proves a current frame
-again before clearing recovery. SFU media is retained independently of transient
-room-signaling loss, but Browser or OS suspension and page reclamation remain
-outside Web guarantees.
+authority and invalidate quality observations, not already-proved playback.
+Returning to the page rebaselines time and re-arms frame observation; an existing
+recovery state still requires a fresh current frame to clear. SFU media is
+retained independently of transient room-signaling loss, but Browser or OS
+suspension and page reclamation remain outside Web guarantees.
Failure of the local Native media bridge disables Native reception for the
current Viewer session before route recovery runs. Future peers in that session
@@ -147,6 +195,13 @@ loss; deeper fields appear only when meaningful. Topology is a separate view.
Native bandwidth or CPU limitation warnings describe the exact outbound sender
that reported adaptation; they do not by themselves locate the physical
bottleneck or describe the Viewer's receive path.
+The Host's participant freeze warning requires fresh receive evidence matching
+the current upstream and a positive freeze count or duration for that window.
+Window `*Delta` fields never inherit older values; other fields may retain their
+existing details-display cache. The existing evidence expiry removes stale
+warnings. No additional participant state, broadcast, timer or quality score is
+introduced. Detailed per-edge observations remain available without a global
+warning selected from the first limited child.
Locally exposed selected-candidate addresses may be shown only on the Browser
that owns that PeerConnection and are never uploaded, persisted, or used for
identity or route selection. Explicit Debug mode can export a bounded diagnostic
diff --git a/docs/product/rooms-access.md b/docs/product/rooms-access.md
index 92e168b4..2a3be4fd 100644
--- a/docs/product/rooms-access.md
+++ b/docs/product/rooms-access.md
@@ -35,8 +35,10 @@ the storage decision; implementation detail belongs in code and tests.
Three independent authorities exist:
-1. **Site access.** Production requires an independent
- `SITE_ACCESS_PASSWORD`. Successful entry creates a stateless, HttpOnly,
+1. **Site access.** `SITE_ACCESS_PASSWORD` is optional in every environment,
+ including production. Unset or empty makes site access immediate without a
+ cookie; room ownership and Viewer admission still apply. When configured,
+ successful password entry creates a stateless, HttpOnly,
`SameSite=Strict` cookie with a 24-hour rolling idle lifetime. An already
authorized page renews it through the site-access check while it remains
active. It authorizes room creation, Host role, and code-only Viewer
@@ -90,6 +92,9 @@ code-only attempts and does not silently revoke invitations.
choice and optional Local site-access password, not rooms or media state. A
blank password leaves that local site open.
+Persistence evidence, limits and the earlier cross-restart evaluation live in
+[cross-restart recovery research](../research/cross-restart-room-recovery.md).
+
The App opens its own localhost Host page with the configured password, when
present, in a fragment. The page removes the fragment and uses the existing
SiteAccess endpoint; this does not create a fourth admission authority. LAN and
diff --git a/docs/product/routing-transport.md b/docs/product/routing-transport.md
index 9d0f92e9..784f9924 100644
--- a/docs/product/routing-transport.md
+++ b/docs/product/routing-transport.md
@@ -17,14 +17,17 @@ owns ports and [self-hosting](../operations/self-hosting.md) owns service setup.
- A route ends in usable media, explicit bounded waiting, or clear failure.
Every deployment uses this controller. Leaving embedded SFU disabled keeps the
-same bounded P2P graph without its SFU fallback; there is no separate Host-star mode.
+same bounded P2P graph without its SFU fallback and fixes Privacy mode on for all
+rooms, including App Local and public-link rooms. The server enforces that policy
+for waiting and active participants; there is no separate Host-star mode.
## Per-Share Route Policy
The Host chooses route policy before sharing and it remains fixed for that
share generation:
-- default hybrid mode keeps P2P first and permits the bounded SFU suffix;
+- when SFU is available, default hybrid mode keeps P2P first and permits the
+ bounded SFU suffix;
- peer-only mode excludes SFU publication, subscription, bootstrap, and quality
candidates, while retaining the same bounded Peer graph and clear exhausted
failure; and
diff --git a/docs/project-memory.md b/docs/project-memory.md
index 82207e74..bfaf773c 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -1,8 +1,8 @@
# Project Memory
-Last updated: 2026-09-10
+Last updated: 2026-09-11
-Piik is private, low-latency game screen sharing for one Host and up to 20
+Piik is private, low-latency screen sharing for one Host and up to 20
authenticated friends. The current product surface is Web Host, Web Viewer, and
Browser relay; desktop and mobile Browsers are Viewer targets. It is not a
public broadcast service. Hosted and App run one shared Go core
@@ -94,8 +94,8 @@ implementation and routine UI detail.
## Current Snapshot
-The current contract uses strict `piik-v23` Browser/server signaling,
-Native control v9 and capture v7 together. Embedded SFU SDP/ICE and demand travel over the
+The current contract tuple is owned by [status](./status.md#accepted-release-contract).
+Embedded SFU SDP/ICE and demand travel over the
authenticated room WebSocket, without an external room service or media token.
Committed first-frame readiness, bounded candidate-relative progress, durable
room authority and the H.264/VP8 sender gate remain. [Status](./status.md)
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 2fc5dff0..a52a900f 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -4,6 +4,18 @@ The tracked [`.env.example`](../../.env.example) is the executable schema
companion; `internal/server/config` is validation truth. Keep real values in the
service secret store or an untracked access-restricted environment file.
+## Ownership
+
+- Deployment configuration owns listeners, advertised origins, persistence,
+ admission, capacity and optional services. Change it before starting the process.
+- The Host owns share settings and the available per-share route switches in the
+ shared Web UI. Server and App use the same controls, order and semantics;
+ configuration changes availability, not which controls exist. A fixed switch
+ remains visible and explains the reason in text or its pure-visual hint.
+- Protocol versions, queue bounds and routing/adaptation constants stay in code.
+ They are not deployment tuning knobs. Debug and report destinations are
+ explicit diagnostic options, not normal share settings.
+
## Application Environment
| Variable | Contract |
@@ -13,19 +25,19 @@ service secret store or an untracked access-restricted environment file.
| `PORT` | Positive TCP port, default `8787`; the tracked release wrapper supports only that default. |
| `PUBLIC_BASE_URL` | Exact public HTTP(S) origin; production requires HTTPS. |
| `ALLOWED_ORIGINS` | Comma-separated exact HTTP(S) origins; wildcard is invalid. |
-| `SITE_ACCESS_PASSWORD` | Production-required independent 8-128 visible-ASCII byte secret. |
+| `SITE_ACCESS_PASSWORD` | Optional in every environment. Unset or empty allows entry without a site password. A non-empty value must contain 8-128 visible ASCII bytes; room ownership and Viewer admission remain independent. |
| `ROOM_DATABASE_PATH` | Hosted defaults to `rooms.sqlite` in its working directory when unset or blank. An explicit absolute file path selects another SQLite file; `:memory:` opts into process-memory room authority. App Local remains in memory. |
| `MAX_VIEWERS_PER_ROOM` | `1..20`, default `8`. |
| `ENDPOINT_MEDIA_COPY_CAPACITY` | Shared endpoint steady-copy cap `1..3`, default `2`. |
| `STUN_URLS` | Comma-separated advertised `stun:` discovery URLs; at least one is required in production. These are not local bind addresses and may use an unproxied DNS name separate from the Web origin. |
| `STUN_LISTEN_HOST` | Hosted IPv4 STUN bind address, default `0.0.0.0` when `STUN_URLS` is configured; independent of HTTP `LISTEN_HOST`. Local App construction creates no STUN listeners. |
-| `NAT_PREDICTION_ENABLED` | Optional bounded NAT prediction capability, default `false`; requires an ordinary `STUN_URLS` endpoint on UDP 3478. Hosted startup binds UDP 3479/3480 before advertising the capability. Firewall reachability remains an operator requirement. |
+| `NAT_PREDICTION_ENABLED` | Optional bounded NAT prediction capability, default `false`; requires an ordinary `STUN_URLS` endpoint on UDP 3478. Hosted startup binds UDP 3479/3480 before advertising the capability. When unavailable, the visible NAT switch is locked off; ordinary ICE remains. Firewall reachability remains an operator requirement. |
Automatic SFU fallback runs inside the Hosted process when `SFU_UDP_PORT` is set:
| Variable | Contract |
| --- | --- |
-| `SFU_UDP_PORT` | Optional UDP media port `1..65535`; unset or blank disables SFU. Set `7882` for the standard public listener. |
+| `SFU_UDP_PORT` | Optional UDP media port `1..65535`; unset or blank disables SFU and fixes Privacy mode on for every room. Set `7882` for the standard public listener and allow the Host to choose Privacy mode. |
| `SFU_LISTEN_HOST` | IPv4 bind address, default `0.0.0.0`; independent of HTTP `LISTEN_HOST`. Read only when SFU is enabled. |
| `SFU_PUBLIC_IP` | Optional explicit IPv4 advertised-address override for a host behind NAT. Read only when SFU is enabled. |
@@ -34,6 +46,11 @@ separate control origin or infrastructure credentials are configured. Local and
public-link App construction create no SFU listener. The relay does not
provide application E2EE.
+For a P2P-only Server, leave `SFU_UDP_PORT` blank. Room authority, signaling,
+configured STUN and peer relays remain; no media-server fallback is possible.
+The server enforces this even if a Host requests hybrid mode. There is no
+separate `SFU_ENABLED` flag to conflict with the listener configuration.
+
The SQLite parent directory must exist and be writable. The systemd template
sets `/var/lib/piik/rooms.sqlite` under its managed state directory; the
container image sets `/home/nonroot/rooms.sqlite` under its writable data
@@ -45,10 +62,41 @@ Removed access, room TTL/lease, endpoint-tier, room-rollout, and TURN variables
startup even when blank. A present `NODE_ENV` fails the same way, so a stale
environment file cannot silently drop a deployment out of production. The
private deployment is upgraded atomically; there are no compatibility aliases or
-dual configuration readers.
+dual configuration readers. [Versioning](./versioning.md) owns the planned public
+upgrade promise and the work required before its first release.
+
+## Piik App Configuration
+
+Piik App stores `Piik/client.json` under the operating system's user configuration
+directory (`%APPDATA%` on Windows, `~/Library/Application Support` on macOS,
+and `$XDG_CONFIG_HOME` or `~/.config` on Linux). The App manages its `version`
+schema field. The user settings are:
+
+| Setting | Contract |
+| --- | --- |
+| `site` | Saved Piik Site origin; omit it for Local mode. The launcher or `--site` updates it. |
+| `localAccessPassword` | Empty by default. Optional password for the App's Local room authority, using the same 8-128 visible ASCII bounds. It is separate from a hosted site's password. |
+
+Command-line options select entry and local runtime behavior:
+
+| Option | Purpose |
+| --- | --- |
+| `--site <origin>` / `--local` | Save and use a Site, or select the self-contained Local mode. Mutually exclusive. |
+| `--link` | Create a public Viewer invitation for Local mode. |
+| `--config <path>` | Select another App configuration file. |
+| `--lan-address <IPv4>` / `--port <port>` | Override the Local invitation address or HTTP port (default `8787`). |
+| `--capture-process <path>` / `--tunnel-process <path>` | Override packaged native capture or public tunnel helpers. Ordinary installations use the packaged paths. |
+| `--debug` / `--log-dir <path>` | Enable diagnostics or choose their destination as described below. |
+
+Share quality, room access policy, language, theme and motion are configured in
+the shared Web UI, not through Server environment variables or App JSON.
## Diagnostics
+Normal Server logs record startup identity, listener and enabled services,
+unexpected failures, orderly shutdown and any available release found by the
+single background startup check. Detailed room/ICE/media traces require Debug.
+
Diagnostics are local and opt-in. Enable them **before** reproducing the problem:
| Surface | Enable | Export |
@@ -57,6 +105,11 @@ Diagnostics are local and opt-in. Enable them **before** reproducing the problem
| Browser Host/Viewer | Add `?debug=1` to the page URL, before any invitation fragment | Use the download button beside language/theme controls |
| Hosted Server | Start with `--debug`, `PIIK_DEBUG=server` or `PIIK_DEBUG=route` | On Unix, `kill -USR1 <pid>`; also exported at orderly shutdown |
+Server Debug is controlled by its startup environment or CLI, never by a remote
+page or room role. Browser `?debug=1` only enables that page's local collection;
+it cannot change Server logging or download Server reports. The Server exposes
+no HTTP diagnostic export or pprof endpoint.
+
App/Server ZIP and Browser JSON reports are separate: when investigating
Browser/App cooperation, include both from the same reproduction. Neither
action stops an active share or uploads anything. Browser export also remains
diff --git a/docs/reference/engineering.md b/docs/reference/engineering.md
new file mode 100644
index 00000000..582c7693
--- /dev/null
+++ b/docs/reference/engineering.md
@@ -0,0 +1,199 @@
+# Engineering And Interface Boundaries
+
+This is the shared engineering convention for Browser, App and Server work.
+[AGENTS.md](../../AGENTS.md) owns task authority and hard product constraints;
+[CONTRIBUTING.md](../../CONTRIBUTING.md) owns the delivery workflow. The required
+[ponytail guidance](../../.agents/skills/ponytail/SKILL.md) selects the smallest
+correct implementation. This file owns module responsibilities and interface
+discipline, not a second copy of the product contracts or wire fields.
+
+## Repository Layout
+
+Keep conventional project entry points and tool-discovered configuration at the
+root. Scope-specific configuration belongs with its owner: `src/tsconfig.json`
+checks the Browser, `scripts/tsconfig.json` checks tooling/tests, and root
+`tsconfig.json` only connects those projects.
+
+| Location | What belongs here |
+| --- | --- |
+| Root README, contribution and agent files | Project introduction and shared working constraints; detailed documents live in `docs/` |
+| Root manifests, lockfiles, Vite/Vitest config, `index.html` | Go/npm entry points and Browser build/test startup; root `LICENSE` is authoritative |
+| `src/client`, `src/shared` | Browser UI/media orchestration and its shared wire types; the same UI serves Hosted and App modes |
+| `public/` | Static assets shipped with that Browser application |
+| `cmd/`, `internal/` | Go executable composition and private application, server, media and diagnostics packages |
+| `native/capture`, `native/fixtures`, `native/probes` | Platform capture implementations, synthetic workloads and standalone capability probes |
+| `site/` | Independently published static introduction; its assets do not implement product behavior |
+| `scripts/` | Development checks, browser/media gates, dependency assembly and release packaging/publishing tools |
+| `tests/` | TypeScript/tooling tests and cross-language fixtures; Go tests stay beside their packages |
+| `deploy/` | Operator scripts and container, proxy, service and certificate templates |
+| `docs/` | User guides, contracts, decisions and operations; [documentation ownership](../maintenance.md) defines each owner |
+| `licenses/` | Third-party license texts, pinned notice sources and their redistribution reference |
+| `.github/`, `.githooks/`, `.agents/`, `.codex/` | Platform automation and scoped agent/tool integration |
+| `build/`, `node_modules/`, `coverage/` | Ignored local output and dependencies; never current product truth |
+
+`site/` introduces Piik; `src/client/` is Piik's interactive application.
+`internal/app/nativecapture` adapts the capture contract in Go; `native/capture/`
+implements it using platform APIs. `scripts/` prepares and verifies artifacts;
+`deploy/` operates them. Move files with their actual consumers, and update paths
+and checks together; a smaller root alone does not justify another abstraction.
+
+## Module Map
+
+| Owner | Responsibility and dependency boundary |
+| --- | --- |
+| `cmd/piik-server`, `cmd/piik-app` | Thin entry points: defaults, startup and shutdown; compose the same Go room service |
+| `internal/server/app` | HTTP, site access, runtime capabilities, static assets and listener lifecycle; room mutations go through `signal` |
+| `internal/server/signal` | Authenticated command/effect owner; serializes room, session and route mutations and executes controller decisions |
+| `internal/server/room` | Room authority, credentials and persistence; caller holds the signaling lock, durable writes precede in-memory changes |
+| `internal/server/route` | Synchronous room graph and single-operation decisions; returns resource effects to `signal`, owns no locks or timers, and calls its optional diagnostic sink synchronously |
+| `internal/server/sfu`, `internal/app/mediaedge` | Server forwarding and native peer adapters over the shared `internal/media/forwarding`; Pion/LiveKit own transport and adaptation |
+| `internal/app` | Local/public-link/Site composition, loopback service, native sessions and App lifecycle; never a second room backend |
+| `internal/app/nativecapture`, `native/capture/*` | App-side capture contract and minimal platform adapters; platform-specific capture/encoding stays here |
+| `src/client/pages`, `lib`, `media`, `native` | Browser orchestration and endpoint adapters; bind current media and retire owned resources |
+| `src/client/media/viewer-presentation.ts`, `ui/media-status.ts` | Playback facts and their derived status projection; UI indicators do not create recovery or quality policy |
+| `src/client/components`, `locales`, `ui` | Shared interaction, visual primitives and localized copy; same product interface for Server and App |
+| `internal/server/webassets` | One built Browser bundle embedded by both binaries; Node/Vite are development tooling |
+
+Names follow [naming](./naming.md). Architecture decisions explain why these
+boundaries exist: [shared core](../adr/0012-shared-go-backend-core.md),
+[embedded media](../adr/0013-embedded-node-local-media.md) and
+[Browser pooling](../adr/0014-browser-node-local-encoding-pool.md).
+Directory names are a map, not a requirement to introduce another layer.
+
+## Contract Map
+
+| Boundary | Schema/validation owners |
+| --- | --- |
+| Room HTTP and Browser/Server signaling | `src/shared/protocol.ts` and `internal/server/protocol`; HTTP dispatch in `internal/server/app`, WS dispatch in `signal` |
+| Site access HTTP | `src/client/lib/api.ts` and `internal/server/app/json.go`; cookies and access behavior belong to [rooms/access](../product/rooms-access.md) |
+| Browser/App discovery and control | `src/client/native/wire.ts`, `internal/app/loopback/protocol.go`, `internal/app/nativecontrol/wire.go` |
+| App/capture sidecar | `internal/app/nativecapture` and each platform capture adapter; probe/commands and encoded-frame envelope are distinct formats |
+| Configuration and persistence | `internal/server/config`, `internal/app/config`, `internal/server/room/database.go`; operator semantics in [configuration](./configuration.md) |
+| Release and update metadata | Existing packaging scripts, `src/client/lib/release-update.ts`, `cmd/piik-server/release.go`; identity/compatibility in [versioning](./versioning.md), operations in [deployment](../deployment.md) |
+
+The shared `tests/fixtures/wire-samples.json` is consumed by TypeScript and Go
+fixture tests. It covers room requests and signaling; it is not a universal
+schema for all HTTP, Native or capture traffic. Change the actual two ends and
+the relevant existing fixture/check together. Do not create another handwritten
+field list in documentation, parallel DTO hierarchy or schema generator without
+a demonstrated reduction in ownership or drift.
+
+## Runtime Lifecycles
+
+Read each runtime as acquisition, the authoritative commit that makes its work
+visible, and the retirement that ends it. Revalidate the acquiring identity
+after every await or callback; presentation derives from the committed fact
+instead of mirroring it.
+
+| Runtime | Acquire | Commit | Retire |
+| --- | --- | --- | --- |
+| Browser Host share | `pages/HostPage.tsx` captures one source and creates its peers and route | current generation plus the owning identity: local-offer epoch, publisher slot revision, source-switch and quality-change tokens | `disposeResources` stops owned tracks, disposes peers and sends `stop-sharing`; a replaced source retires through `retiringStreamRef` |
+| Browser Viewer route | `pages/ViewerPage.tsx` binds one parent peer (Browser or Native) and its relay children | parent, connection and message identity, then playback facts | a new viewer generation retires the old binding; relay children follow `activateChildren` revisions |
+| Browser relay fanout | `webrtc/viewer-relay.ts` prepares a child before it is needed | `activateChildren(revision, childPeerIds)` commits the prepared set | replaced or emptied sets disconnect the child peers they own |
+| Browser local encoding pool | `webrtc/host-peer.ts` attaches a pool carrier when capture and APIs support it ([ADR-0014](../adr/0014-browser-node-local-encoding-pool.md)) | the carrier binding owns its pooled producer while attached | source change or disposal releases the carrier; unsupported APIs keep ordinary senders |
+| App native session | the loopback service admits native control sessions and the Web UI selects the native path | session identity plus the explicit media-path choice | session end, share end or process exit retires that edge and its capture sidecar |
+| Server room authority | `signal` authenticates one Host or Viewer command | `room` writes durably before the in-memory commit; the signaling lock serializes mutations | explicit replacement or deletion, grant rotation or revocation, or process exit for memory-mode rooms |
+| Server route and SFU | `signal` feeds `route` one serial child operation; `sfu/admission.go` accepts one bounded publication | one committed graph per controller and the forwarding publication | superseded assignments retire inside the same operation; deactivate retires the publication |
+
+## Source Index
+
+Start a change at the owning entry point, then follow the interfaces listed
+above rather than searching the tree.
+
+| Change | Start at |
+| --- | --- |
+| Host workflow, share lifecycle, notices | `src/client/pages/HostPage.tsx`, `src/client/pages/host-page-notices.ts` |
+| Viewer workflow, playback, status projection | `src/client/pages/ViewerPage.tsx`, `src/client/media/viewer-presentation.ts`, `src/client/ui/media-status.ts` |
+| Browser peer and route mechanics | `src/client/webrtc/host-peer.ts`, `viewer-peer.ts`, `viewer-relay.ts`, `src/client/media/host-sfu-route.ts`, `viewer-sfu-route.ts`, `route-transition.ts` |
+| Capture, profiles and sender parameters | `src/client/media/quality.ts`, `src/client/media/browser-encoding-pool.ts`, `browser-encoding-output.ts` |
+| SFU endpoints | `src/client/sfu/publisher.ts`, `subscriber.ts`, `peer.ts`, `internal/server/sfu` |
+| Localized copy and failure facts | `src/client/locales`, `src/client/ui/copy.ts`, `src/client/ui/media-failure.ts` |
+| Native bridge, capture and media edges | `src/client/native`, `internal/app/loopback`, `internal/app/nativecontrol`, `nativehost`, `nativeviewer`, `nativecapture` |
+| Room authority, persistence and graph | `internal/server/signal`, `internal/server/room`, `internal/server/route` |
+| Shared wire contract | `src/shared/protocol.ts`, `internal/server/protocol`, `tests/fixtures/wire-samples.json` |
+| Diagnostics and logging | `src/client/lib/debug.ts`, `internal/diagnostics`, [configuration](./configuration.md#diagnostics) |
+| Configuration and deployment | `internal/server/config`, `internal/app/config`, [configuration](./configuration.md), [deployment](../deployment.md) |
+
+## Implementation Rules
+
+- Reuse a current owner, standard API or mature dependency before adding a
+ mechanism. Extract around a responsibility shared by real callers; file size
+ alone does not justify wrappers, a generic manager or a framework.
+ Remove superseded paths in the same change; retain no unused legacy copy.
+ Keep test-only state seeding and setup in test harnesses.
+ Do not export mutable resources solely for tests; preserve the production
+ construction path when verifying defaults or restoration.
+- Review dependency direction for source/type imports as well as runtime
+ imports. Shared types belong to a common owner. A type-only cycle is an
+ ownership concern; it does not by itself establish a runtime or performance
+ defect.
+- State has one writer and a clear lifetime. Separate permission, capability,
+ connection readiness, requested settings, applied settings and observation.
+ Derive presentation from facts; do not synchronize parallel booleans or let
+ a cached failure outlive its evidence.
+- The operation that acquires a connection, clone, listener or queue owns its
+ retirement. After an await/callback, and inside cleanup, validate the original
+ operation/resource identity before changing current state. Cancellation,
+ failure, missing observation and success must retain distinct meanings.
+- Keep decisions separate from effects. Respect documented lock ordering and
+ revalidate after unlocked work. Local native capability never grants room
+ authority; the shared Go service remains authoritative.
+ Injected callbacks still execute in their caller's context; include their
+ blocking I/O in the caller's lock and latency analysis.
+- Validate input at the boundary, keep domain error meanings stable, and map
+ them into shared localized UI. [Versioning](./versioning.md) determines which
+ extensions are compatible; an optional field is not automatically compatible.
+ Retained media state carries failure facts; the presentation layer resolves
+ localized copy during render. Keep raw exceptions in diagnostics. Transient
+ event notices may resolve once when the event occurs.
+ Values with a defined canonical form, such as HTTP origins, use one shared
+ normalizer before storage and comparison. Verify the actual producer and
+ consumer together instead of weakening an authorization comparison.
+- Deployment configuration describes available services; room preferences
+ request allowed behavior. The server enforces the policy even when a client
+ requests more. The UI retains the same controls and explains locked choices.
+ See [configuration](./configuration.md); avoid a second flag with the same job.
+- Browser/App/Server share [visual language](../design/visual-language.md) and
+ [status projection](../design/media-status.md). A new page, locale or deployment
+ does not invent a new palette, status model or user-role metaphor.
+- Keep package comments about current responsibilities and invariants. Historical
+ migration paths belong in ADR/research unless they explain a surviving constraint.
+ Support Windows, macOS and Linux; new text files use LF and new filenames use
+ ASCII, with format exceptions in [`.gitattributes`](../../.gitattributes).
+ Scripts use stable executable paths; physical confidence stays explicit in
+ [verification status](../verification-status.md).
+- Retained tools declare their direct package dependencies. Documented TypeScript
+ tools join the normal type-check entry point; a transitive dependency or a
+ one-off manual check is not an owned toolchain contract.
+ Shipped templates use reserved example values. Checks provision isolated
+ resources or require explicit targets; they must not depend on a maintainer's
+ workstation, private deployment or machine-specific infrastructure names.
+
+## Ablation And Review
+
+Judge a change by verified user value against implementation, maintenance,
+compatibility, runtime and failure cost. After a material module, remove any
+new state, dependency, branch or abstraction that the accepted behavior does
+not need. A small performance gain does not justify permanent complexity;
+do not reduce viewing quality or requested functionality merely to save lines.
+
+A concrete reduction in duplicated writers, cross-module dependencies or
+repeated edit sites can justify structural refactoring without a reproduced
+runtime failure. Name that gain and its regression risk. A completed audit is
+bounded evidence, not a claim that every current module boundary is optimal.
+
+Before changing production recovery or state, trace the real request producers
+and their guards. A test that bypasses disabled controls or writes private state
+does not alone establish a reachable product defect. Reference scans, including
+hits from tests and previews, are leads rather than proof of product use or
+absence. Follow the actual producer-to-consumer path and check the changed
+boundary; isolated helper tests can miss a mismatch between the two ends.
+
+Trace acquisition, use, commit and retirement, including replacement and failure.
+For async ownership, check A starting, B replacing it, then A completing or
+cleaning up. Where compatibility is promised or being established for public
+release, check actual old/new readers as well as the happy path. Ordinary private
+changes do not require support for stale private clients. Run proportionate checks through
+[the standard entry points](../../CONTRIBUTING.md#verification-entrypoints).
+This discipline does not authorize an unrelated repository rewrite or a new
+test suite for every helper.
diff --git a/docs/reference/naming.md b/docs/reference/naming.md
index 70954722..067d45f2 100644
--- a/docs/reference/naming.md
+++ b/docs/reference/naming.md
@@ -1,8 +1,116 @@
-# Naming
+# Naming And Copy
This is the naming convention for new and changed Piik code, UI and packaging.
Use the brand for people and predictable lowercase identifiers for tools.
+## Voice And Terminology
+
+Use the same role and action vocabulary in the App, Browser, website and guides.
+Role labels describe permission; a person's chosen nickname stays unchanged.
+
+| Meaning | English | Chinese |
+| --- | --- | --- |
+| Person sharing and controlling the room | Host | 房主 |
+| Person watching | Viewer | 观众 |
+| Product capability | Screen sharing | 屏幕共享 |
+| Start sending a chosen screen/window | Start sharing | 开始分享 |
+| Enter another person's room | Join a room | 加入房间 |
+| Site-wide access secret | Site passphrase | 站点口令 |
+| Room-specific access secret | Room password | 房间密码 |
+
+Write each language for its own audience. Chinese headings and welcomes may
+sound like friends inviting each other: “叫朋友来一起看。” or “沙发给你留着呢。”
+Do not translate English sentence structure or possessive screen metaphors
+literally (“和朋友一起看你的屏幕”). Use familiar Chinese verbs and a light touch;
+forced memes, baby talk and repeated slogans quickly become tiring.
+
+The brand line is “Share the good stuff.” in English and “来,看点好康的。” in
+Chinese. Display the Chinese headline on two lines: “来,看点” / “好康的。”
+Keep metadata and ordinary prose as the continuous sentence.
+
+Keep the public brand line consistent in the homepage, film ending and README
+opening, beside a plain screen-sharing description. Scene titles should name
+the action or benefit; do not turn every section into another slogan. Games, drawings, photos and
+movie nights show the range of screen sharing without implying voice chat,
+shared input or synchronized playback controls. Each locale must read naturally
+as a complete sequence, without depending on a pun from the other language.
+
+Set the register by the reader's task:
+
+| Surface | Register |
+| --- | --- |
+| Website | Light, everyday language in introductions and illustration captions; keep the current restraint |
+| README | A friendly introduction, followed by direct explanations of features, limits and first steps |
+| Documentation index | Clear topic names and short descriptions that help readers choose a guide |
+| Deployment, configuration and maintenance guides | Formal, precise instructions: prerequisites, actions, expected results and recovery steps |
+
+Formal means clear and factual, not bureaucratic. Keep detailed procedures free
+of jokes and promotional slogans; do not carry the website's playful headings
+into technical instructions.
+
+State the requirement, action or result directly. Omit negative comparisons that
+answer an abandoned design or an internal discussion: “解压后运行” is enough;
+listing the runtimes a packaged App does not require adds no useful next step.
+Include an exclusion only when it resolves a real reader choice or limitation.
+
+Write tutorials from an explicit starting point: what the reader needs, which
+visible action to take, and what appears next. Distinguish watching an invitation,
+creating an App room, using an existing site, and deploying a server. Say where
+the site or download comes from; “follow the prompts” cannot stand in for a
+missing prerequisite. Mark passwords and audio options as conditional when they
+are optional. Keep App and Server package names distinguishable at download links.
+Public platform notes say what has been tested and invite useful feedback;
+internal phrases such as “this phase's acceptance target” belong in status.
+
+Use progressive disclosure on the website and in the film:
+
+| Information layer | Reader's question | Content |
+| --- | --- | --- |
+| First view: navigation, headings, feature cards, film titles | What does it do, how do I start, what does it cost? | Familiar actions and concrete benefits: “开箱即用”, “免费使用”, “朋友点开就能看” |
+| Expanded details, supporting text and FAQ answers | Will this work for me, and why? | Platform/network conditions, explained technical terms and links to the relevant guide |
+| README, wiki and operational guides | How do I configure, verify or troubleshoot it? | Exact action names, prerequisites, commands, configuration and evidence limits |
+
+The layer follows the reader's task, not font size alone. Keep material costs,
+availability and limitations beside the claim or action they qualify; do not
+hide them behind a collapse. Never promote an implementation mechanism such as
+encoding reuse or STUN as an unexplained headline. Explain technical terms on
+first use even in detailed documentation. Plain wording must preserve the
+original bounds: “开箱即用” does not promise offline use or guaranteed connection,
+and reduced repeated work does not establish a universal CPU saving.
+Lead performance copy with the user benefit (low latency, efficient sharing),
+then explain the supporting mechanism and its conditions. “Lowest latency”,
+“zero delay” and comparative resource savings require matching measurements;
+an architectural preference alone does not establish a benchmark result.
+
+Write Chinese and English headings independently. Break lines at complete
+phrases, never inside a short action such as “画上两笔”. A decorative number must
+have an adjacent meaning/unit (“使用费用 0 元”), and its label must remain visible
+in both languages and at the smallest supported width. Check the actual rendered
+headline after rotation and animation settle: all meaningful words need room
+inside the frame. Oversized background lettering may crop; primary copy may not.
+
+Download/availability labels, platform requirements, instructions, permission
+prompts, status and errors stay plain and specific. Use the exact visible action
+names in tutorials; a playful caption never replaces “Download”, “Join a room”
+or a platform/connection limitation. Explain what happened, what the user can do
+next, and any real limitation. Jokes belong
+in the welcome or illustration caption. Do not soften a failure into a joke,
+invent connection progress or promise guaranteed connectivity or absolute privacy.
+Screen sharing includes games, creative work and showing a useful discovery.
+
+Operational pages omit introductory sentences that repeat their controls.
+Helper text should explain a meaningful choice or prevent an error.
+
+Use short, contextual references in opening lines and illustration reactions.
+A familiar expression may work when its ordinary meaning still makes sense to
+someone who does not recognize it. Keep each language independent and avoid
+long dialogue, borrowed brand slogans or a stream of unrelated memes. Match a
+celebration to a visible successful action; it must not precede the result.
+Keep the small bilingual set local, without a quotation service.
+The [visual language](../design/visual-language.md) owns where these lines appear.
+
+## Product And Tool Names
+
| Surface | Convention | Example |
| --- | --- | --- |
| Product and repository | `Piik` | `TNTcraftHIM/Piik` |
@@ -18,11 +126,9 @@ Use the brand for people and predictable lowercase identifiers for tools.
| Environment variables | Uppercase snake case | `PIIK_DEBUG`, `PIIK_LOG_DIR` |
| Go module path | Exact repository spelling | `github.com/TNTcraftHIM/Piik` |
-An `.exe` is lowercase on Windows too; `.app` is a user-facing bundle, not the
-raw executable. There is no universal OS rule requiring lowercase binaries:
-this project chooses one spelling across platforms for predictable commands.
-Archive contents and directory layout are owned by the existing packager; a
-name change does not change that layout.
+Use the same lowercase binary names across platforms for predictable commands.
+`Piik App.app` is the user-facing macOS bundle. The packager owns archive contents
+and directory layout.
Keep platform/standard spellings such as `Info.plist`, `LICENSE`, `README.md`
and `REVISION`. Do not change third-party names or notices to fit this table.
Immutable measurement records keep the paths and hashes of their measured
@@ -30,25 +136,31 @@ revision; they are evidence rather than current command examples.
## Code ownership and vocabulary
-- `internal/app` owns the standalone application and its native/launcher
- components; `cmd/piik-app` is its thin command entry.
-- `internal/server` owns the reusable room service and Hosted runtime;
- `cmd/piik-server` is its command entry. The App runs that same service for
- Local/public-link rooms, without a second backend implementation.
-- `src/client` is the Browser frontend. HTTP/WebSocket clients, signaling
- `clientId`, protocol clients and similar connection roles remain `client`.
+The [engineering module map](./engineering.md#module-map) owns directory
+responsibilities. HTTP/WebSocket clients, signaling `clientId`, protocol clients
+and similar connection roles remain `client`; they do not name the standalone App.
+
- Follow each language's semantics: lowercase Go packages, exported `PascalCase`
and unexported `camelCase`; existing TypeScript component/type conventions.
Brand casing must not change visibility or create unnecessary name prefixes.
Renaming the standalone product is not a protocol or persistence change.
-Keep `piik-client-v9`, the discovery service name, Browser activation/storage
-keys, the `Piik` configuration directory and diagnostic categories at their
-current exact contracts. Change such identifiers only with a separate behavior
-or contract decision; do not add aliases or dual readers for display renames.
+Keep discovery, wire and stored identifiers at their current contracts. Their
+change rules belong to [versioning](./versioning.md); do not add aliases or dual
+readers merely for a display rename.
## Basis
+Content layering reviewed 2026-09-12:
+[NN/g's progressive disclosure](https://www.nngroup.com/articles/progressive-disclosure/)
+defers secondary detail while preserving the primary task;
+[GOV.UK's clear-language guidance](https://guidance.publishing.service.gov.uk/writing-to-gov-uk-standards/writing-guidelines/clear-language/)
+keeps specialist content understandable. The layer assignments and Chinese
+examples above are Piik's application of those principles.
+[NN/g's microcopy guidance](https://www.nngroup.com/articles/3-cs-microcopy/)
+puts clarity before concision and character; this also guides the balance
+between Piik's playful introductions and factual instructions.
+
Reviewed 2026-09-10. Desktop standards explicitly separate display names from
executable identifiers; lowercase executable names are our portability convention.
diff --git a/docs/reference/versioning.md b/docs/reference/versioning.md
new file mode 100644
index 00000000..88b08f9f
--- /dev/null
+++ b/docs/reference/versioning.md
@@ -0,0 +1,238 @@
+# Versions And Compatibility
+
+Reviewed 2026-09-12. Release identity, update comparisons and descriptive metadata
+rules are implemented; the public compatibility promise starts with the first
+declared public release. Use `v1.0.0` for it, with one product version for App,
+Server and the embedded Web build, plus the full Git SHA for source provenance.
+Automatic publication remains disabled until the readiness boundary below.
+
+## Give Each Identifier One Job
+
+| Identifier | Meaning and owner | Change rule |
+| --- | --- | --- |
+| `vMAJOR.MINOR.PATCH` | Public Git tag/product release | Patch: compatible fixes; minor: compatible features; major: incompatible public contract |
+| Full Git SHA / `REVISION` | Exact source revision | Changes with the source commit; never use SHA inequality as release ordering or compatibility proof |
+| Artifact SHA-256 | Exact packaged bytes in the release descriptor | Each artifact; one source SHA can produce different platform/toolchain binaries |
+| Platform application version fields | Generated package metadata | Product version in the platform's numeric format; source SHA stays separate. XML/desktop-format versions remain specification values |
+| Browser/Server signaling identifier | WS contract in `src/shared/protocol.ts` and Go protocol constants | Change for an incompatible wire contract, not UI edits or every release |
+| Browser/App control identifier | `src/client/native/wire.ts` and App loopback/control | Independent compatibility boundary; installed App and Site can update separately |
+| Capture probe and encoded-frame envelope | `internal/app/nativecapture` and platform adapters | Internal matched bundle; change only the affected format |
+| SQLite schema, App config format, Browser storage-key format | Their storage/parser owners | Change with the actual stored representation; preserve accepted authority across a compatible upgrade |
+| Release descriptor schema | Packager and descriptor readers | Describes metadata format, not the product release |
+| Room authorization generation, share/route/publication/media generations, connection IDs | Current authority and resource owners | Runtime identity/freshness only; never reset or align them with release numbers |
+
+Current numeric values are in source and [status](../status.md#accepted-release-contract).
+Keep those internal values at the first public release: resetting schema or
+authorization counters for visual consistency can invalidate data or stale-work
+fences. A room number is a user-facing address, not a software version.
+The private tooling-only npm package carries no independent product version.
+
+## Public Compatibility Promise
+
+The protected surface is documented App/Server startup and configuration, room
+and invitation behavior, persisted authority, and the Browser/Server/App
+interfaces needed for established sharing and viewing. Internal Go/TypeScript
+symbols, capture sidecar details within a matched bundle, and undocumented
+diagnostic fields are not separately supported public APIs.
+
+- Within a public major, newer releases preserve established workflows and
+ accepted configuration/data for older public releases in that major. New features
+ require support at the receiving end; they are not sent speculatively.
+- A Site serves its own Web build, but an already-open page or installed App
+ can be older. Compatibility is checked at their actual contracts, not by
+ requiring identical product versions or SHAs. New App with older Site keeps
+ established compatible functionality; newly added features may be unavailable.
+- A patch/minor cannot remove a documented command, require a new field from an
+ old peer, change an existing field's meaning, revoke valid room authority, or
+ turn an incompatible HTTP response into a supposedly compatible WS release.
+ Deliberate public breakage needs a major and clear upgrade instructions.
+- Same-major forward upgrades preserve existing durable authority. Arbitrary
+ binary/database downgrades, cross-major interoperability, process restart
+ without media interruption, and identical performance on every OS/browser
+ are not promised. A security repair may restrict previously unsafe behavior;
+ explain the impact rather than silently redefining compatibility.
+
+This does not require retaining every historical implementation. Keep one stable
+baseline contract; introduce a small optional capability only for a concrete
+new feature. Do not add a version-range solver, general adapter framework,
+parallel authority writers or blanket old-client fallback paths.
+
+## Extending Interfaces
+
+Command/event JSON objects still reject unknown keys and enums, and required
+fields reject omissions. Therefore even adding a field can break the other side.
+The former required `sfu` addition to strict `/api/capabilities` demonstrated
+both directions of this problem; an unchanged signaling identifier does not
+cover HTTP compatibility.
+
+Runtime capabilities and App discovery now ignore unknown descriptive fields
+while validating known types, bounds and required identity. An absent optional
+capability means unavailable. Commands, credentials and authority checks remain
+strict. A new
+message type, enum value or behavior-changing field is emitted only after the
+other side advertises support; accepting unknown metadata is not permission to
+execute unknown commands. Verify both readers before calling a change additive.
+
+Native discovery distinguishes an incompatible Piik App from an absent App and
+reports protocol numbers to local diagnostics; the source picker offers update/
+refresh guidance and Browser operation. Do not reload, reinstall or interrupt
+an active share just because an unrelated product/build label changed.
+
+## Release And Recovery
+
+A single release plan computes the next tag and full source SHA. Packagers inject
+both into binaries, embedded Web/debug metadata and the schema-2 release descriptors.
+Local candidates use an exact release tag, `development` or an explicit candidate
+version. An explicit version labels an unpublished test artifact; it does not
+declare or freeze a public release. It cannot reuse a tag owned by another source
+revision. Do not maintain independent hand-edited App/Server/Web version files.
+Archive layout and checks stay in the
+existing packagers; a new build never replaces an already-published package.
+
+Update checks compare actual release precedence and link to the matching release.
+Newer version wins even when the source SHA is unchanged. Same version with a
+different known SHA reports a different official build, not a newer one. A
+development build with a known differing SHA offers the official release as a
+manual choice; it makes no ordering claim. Older releases never cause an update
+notice. Unknown SHA is not inferred from a branch name in GitHub metadata.
+The publisher records a full SHA in `target_commitish` and verifies actual tag
+identity separately. Stable update notices ignore prereleases.
+
+## Automatic Publication
+
+After one-time activation, a complete squash PR merged to main runs the existing
+CI and packaging pipeline. `scripts/release-version.mjs` examines unreleased
+first-parent commit messages: `feat` selects minor, `!` or `BREAKING CHANGE`
+selects major, and other accepted changes select patch. The first release is
+`v1.0.0`. PR/commit naming is owned by [CONTRIBUTING](../../CONTRIBUTING.md#commit-pr-and-branch-names).
+Code size or an internal refactor does not itself imply a breaking release.
+
+No version/changelog commit is written back to main. The workflow queues main
+runs, uses the same source SHA for Server and all App targets, and publishes only
+after all required artifacts and checks pass. The publisher verifies matching
+version, source SHA and checksums, then creates/uploads/publishes one GitHub draft.
+Failed draft uploads can resume; published artifacts are never overwritten.
+An older draft retried after a newer release cannot take over `latest`.
+
+`PIIK_RELEASES_ENABLED` is a GitHub repository activation variable, not a product
+setting. Until the first release is explicitly enabled,
+main runs validation and manual `client_checks` dispatches create candidates only.
+Ordinary branches and PRs do not run cloud CI. [GitHub operations](../operations/github.md)
+owns activation and main protection; no workflow changes repository visibility.
+
+Updates remain explicit, outside an active share, using complete matching
+packages. [Deployment](../deployment.md) owns artifact verification, cutover and
+recovery. A changed storage format needs its own upgrade and rollback treatment;
+restoring an old authority database after newer grants/revocations is not a safe
+routine downgrade. No automatic updater or generic migration framework is
+introduced by this policy.
+
+## Release Notes
+
+GitHub Releases owns the published changelog. Each accepted PR supplies reviewed
+Chinese and English user-facing copy under the exact `## Release notes` heading
+in its squash commit; `###` headings structure that copy. Explain benefits,
+fixes and required upgrade actions, including breaking changes. Keep internal
+work logs, audit handoffs and unverified claims outside this public section.
+
+`scripts/release-notes.mjs` collects these sections from all unreleased
+first-parent commits since the previous stable tag. The first release uses
+only its launch commit's product introduction; private development history is
+not a launch changelog. Missing, empty or duplicate sections fail validation
+before packaging/publication. GitHub Actions shows the generated text in its
+run summary. A manual candidate with an explicit version also previews it, so
+prepare its commit text before dispatching a release rehearsal.
+
+The publisher passes the same text through a temporary notes file to GitHub,
+then removes that file. Gitee copies the GitHub description. Retrying the same
+release preserves its draft/published description; an exact tag does not move
+the changelog's starting point. Keep no `CHANGELOG.md`, versioned note directory
+or generated history commits. PRs and Git retain editorial provenance.
+
+## Release Sources
+
+GitHub Releases is the primary publication; Gitee is an optional official mirror
+for domestic access, with a minimal README pointing development and documentation
+back to GitHub. The Gitee repository need not copy the source tree. Its README/tag
+commit is not the Piik source revision; release metadata retains the original
+GitHub SHA. Build each target once and copy the same archives, notices,
+version, full source SHA and artifact hashes to both. A Git repository mirror
+alone does not synchronize Release attachments. Keep one release description and
+machine-readable metadata, generated by the existing packaging pipeline.
+
+The two providers only adapt API fields and download locations into the same
+release model. Share version comparison, channel filtering and package validation.
+The normal background check tries GitHub, then Gitee if the primary is unavailable;
+download links may expose both verified locations. A lagging mirror must not
+cause a downgrade or a version/hash disagreement to be silently accepted.
+Gitee's documented latest endpoint means last updated, so provider normalization
+must select stable release precedence explicitly, not equate provider ordering.
+
+Synchronize only an explicitly published release; branch pushes stay quiet.
+Retrying a failed mirror upload reuses the original package. Advertise a mirrored
+package as available only after its required attachments and matching metadata
+are present. Tokens belong only to publishing, never the distributed Browser/App.
+The public mirror is [TNTcraftHIM/Piik](https://gitee.com/TNTcraftHIM/Piik).
+The publisher reuses the shared artifact validator, checks every local file
+against GitHub's published asset digest, then uploads and verifies anonymous
+Gitee downloads. Gitee has no draft API: an incomplete mirror remains a preview
+release, and becomes stable only after every file passes. A source marker in
+the release body (`<!-- piik-source: <full-SHA> -->`) preserves the GitHub revision;
+the mirror's `target_commitish` identifies only its own README commit.
+App notices and the operator check share their existing version comparison
+across providers. Each provider has its own deadline; the mirror checks at most
+ten pages of 100 releases and rejects an incomplete listing. An explicit operator
+`--api-url` override checks that endpoint alone. A valid primary result, including
+an up-to-date result, does not consult the mirror.
+
+Gitee currently documents 100 MB per attachment and 1 GB total repository
+attachments for ordinary projects. The mirror rejects files above 100,000,000
+bytes before writing. Check aggregate capacity before each release; exhausted
+storage leaves a pending preview rather than deleting older downloads.
+Target authentication, uploads, anonymous metadata/CORS and a small download's
+SHA-256 have been verified. Acceptance of the full matching release packages
+remains pending with the first public release.
+Use API metadata in the Browser; ordinary asset-link redirects are not guaranteed
+to permit cross-origin fetch, even when a normal download works.
+
+## First Public Release Readiness
+
+The current private single-contract rule remains until this boundary is ready:
+
+1. Accept real target packages and the queued GitHub publication path before
+ enabling automatic releases. Current local checks exercise planning, identity
+ injection, update decisions and publisher failure/retry paths without publishing.
+2. Freeze the first public baseline and explicit feature-support rules after
+ checking the implemented discovery and descriptive-metadata behavior above.
+3. Exercise the first supported old/new App-Site pair in both directions,
+ a stale open page, incompatible-contract recovery and retained room/config
+ authority. Bundled capture checks remain within their existing package gate.
+4. Freeze the supported baseline and release notes, then explicitly declare
+ `v1.0.0`. Do not manufacture compatibility by merely renumbering private builds.
+
+These implementation tasks are tracked in [TODO](../todo.md). Their absence is
+a public-release gap, not evidence that the current matched private build fails.
+
+## References
+
+- [SemVer 2.0.0](https://semver.org/spec/v2.0.0.html): release meaning follows a
+ declared public API; build metadata does not determine precedence.
+- [Syncthing releases](https://docs.syncthing.net/users/releases.html) and
+ [BEP](https://docs.syncthing.net/specs/bep-v1.html): product versions, peer
+ protocol and storage/upgrade behavior are distinct. Piik does not adopt its
+ minor-release REST-breaking exception for the protected interfaces above.
+- [Go compatibility](https://go.dev/doc/go1compat): name the protected contract
+ and its limits instead of promising universal binary/runtime compatibility.
+- [Debug Adapter Protocol evolution](https://microsoft.github.io/debug-adapter-protocol/overview.html):
+ stable baseline messages and explicit optional capabilities allow independent
+ endpoints to evolve. Piik uses that principle within its existing WebSocket/JSON
+ contracts; it does not replace them with DAP or a generic negotiation framework.
+- [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) provides
+ the small release-intent vocabulary; standard SemVer libraries perform ordering.
+- Apple's [bundle build version](https://developer.apple.com/documentation/bundleresources/information-property-list/cfbundleversion)
+ and [release version](https://developer.apple.com/documentation/bundleresources/information-property-list/cfbundleshortversionstring)
+ are numeric; package generation derives both from the release and keeps SHA separately.
+- [GitHub Releases API](https://docs.github.com/en/rest/releases/releases) and
+ [Gitee's official API SDK reference](https://gitee.com/sdk/gitee5j/blob/main/docs/RepositoriesApi.md):
+ provider endpoints and metadata. [Gitee Release documentation](https://help.gitee.com/repository/release/intro)
+ owns its current attachment limits. Provider checks were made on 2026-09-12.
diff --git a/docs/research/agent-context-governance.md b/docs/research/agent-context-governance.md
index cdcef1b5..0de1f99a 100644
--- a/docs/research/agent-context-governance.md
+++ b/docs/research/agent-context-governance.md
@@ -18,12 +18,6 @@ cross-links, and mechanical freshness/structure checks. Codex concatenates the
applicable project instruction chain until `project_doc_max_bytes`, whose
default is 32 KiB.
-Anthropic likewise recommends concise, specific project instructions and moves
-multi-step procedures or path-specific rules to on-demand skills or scoped rule
-files. Claude Code's stated target is under 200 lines per `CLAUDE.md`; imported
-files still enter the startup context, so an import is organization rather than
-context reduction.
-
Hermes distinguishes project conventions (`AGENTS.md`) from user preference,
personality, and learned memory. Its persistent memory is deliberately bounded
and curated; full session history remains searchable on demand rather than being
@@ -34,10 +28,8 @@ below that value and using nested context for genuinely distinct subtrees. Its
bounded-memory guidance starts consolidation at 80% rather than treating the
hard limit as the normal operating target.
-Piik therefore warns at the published recommendation or 80% of a loader
-limit, then fails only at a real loading boundary or a small explicit buffer:
-32 KiB for the Codex chain, 20,000 characters for Hermes, and 250 effective
-Claude lines above the 200-line recommendation. The same envelope applies to the
+Piik therefore warns at 80% of a loader limit, then fails at the loading boundary:
+32 KiB for the Codex chain and 20,000 characters for Hermes. The same envelope applies to the
repo Ponytail skill because `AGENTS.md` requires it for coding work. A failure tells the
maintainer to use nested/path-scoped context, on-demand skills or linked docs,
remove duplication and completed history, and delete stale conclusions; raising
@@ -47,7 +39,6 @@ Sources:
- [OpenAI Harness engineering](https://openai.com/index/harness-engineering/)
- [OpenAI Codex `AGENTS.md`](https://learn.chatgpt.com/docs/agent-configuration/agents-md)
-- [Claude Code memory](https://code.claude.com/docs/en/memory)
- [Hermes file ownership](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/which-file-does-what.md)
- [Hermes context files](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/context-files.md)
- [Hermes persistent memory](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/memory.md)
diff --git a/docs/research/backend-audit-1b01048.md b/docs/research/backend-audit-1b01048.md
deleted file mode 100644
index f8b3861f..00000000
--- a/docs/research/backend-audit-1b01048.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# Backend Audit Reconciliation
-
-- Reviewed: 2026-09-06
-- External evidence baseline: `1b01048e558cfa69b2c8216e658374d06037bfe4`.
-- Integration baseline: `d3232cfd2929eafc94a0e3f003cd2bcdcd47089c`.
-- Scope: verified lifecycle fixes and removal of the optional Host-star route.
- This is not the Go server rewrite or a new physical-media acceptance claim.
-
-The external package contains 244 raw claims, not 244 confirmed defects.
-Its handoff, source patch, and machine-readable findings remain external
-evidence. This document records the independent reconciliation; the
-[TODO ledger](../todo.md) alone owns remaining work.
-
-## Accepted Corrections
-
-- A quality candidate rejected before preparation consumes its existing
- opportunity, preventing an identical prepare/deny loop.
-- Disposing a Native media bridge settles its pending start. Native relay
- callbacks bind the actual peer, including prepared children.
-- A failed Native pause remains paused locally; a failed resume returns to the
- paused intent. No new pause protocol or parallel state owner is introduced.
-- Prepared Native receive deadlines follow the server operation. Viewer teardown
- retires pending candidates and their recovery timers; terminal signaling
- teardown uses its existing stop owner.
-- Authentication is an authoritative route snapshot, even when a replacement
- controller restarts revision numbering. Ordinary route updates retain their
- monotonic fence; session and media identities still reject stale callbacks.
-- Only explicit `committed: true` publishes a newly committed connection
- identity. Stop-sharing presence is emitted after graph teardown.
-- Room expiry and explicit abandonment share termination cleanup. Shutdown
- closes Vite before its shared listener and attempts every SFU drain even when
- one fails. Hosted shutdown reports failure explicitly.
-- Native Receiver creation releases its unused GCC observer-map entry. Local
- startup rejects an already occupied health port; this is a duplicate-instance
- guard, not atomic socket handoff or cryptographic process identity.
-- Native control keeps one reader, a bounded queue, and serial handling so socket
- close can cancel an outstanding system-picker operation. Explicit share close
- is a clean end; natural capture-process EOF still needs cause attribution.
-- Gates use current loopback constants and explicit test STUN configuration.
- Packagers reject in-repository output. Deployment templates specify production
- mode and failed cutover cleanup removes its temporary links.
-- Hygiene skips only GitHub's all-zero base SHA; a missing nonzero commit remains
- an error. Uncalled exports and obsolete gate aliases are removed.
-
-## Resolved Decisions
-
-The owner removed `PEER_ASSISTED_MEDIA`. Hosted and Local now use the same
-bounded graph controller; absent LiveKit configuration still means P2P-only
-service. Room privacy and topology-optimization controls remain independent.
-The old environment variable must be removed before the next deployment.
-There is no Host-star compatibility path to port. Removing the unused
-authentication fields required the coordinated private signaling v21 release;
-rollback to the prior server must also restore its environment configuration.
-
-[ADR-0009](../adr/0009-optional-nat-prediction.md) distinguishes server-owned
-three-attempt NAT acquisition from active Browser edge recovery. Active recovery
-first restarts ICE, then rebuilds the connection if needed. Uncommitted candidates
-return failure to their route operation; the unreachable extra local restart
-branch was removed. Neither kind of restart guarantees a new NAT mapping.
-
-The App launch marker remains origin activation, not proof that the process
-is alive. One failed discovery can mean contention or a permission delay, so
-automatically deleting the marker would break the accepted saved-Site workflow.
-Browser capture remains available in the existing picker.
-
-## Claims Not Adopted Wholesale
-
-- Catching every SQLite exception and continuing is not a complete recovery
- strategy: failed disconnect persistence can leave an active room indefinitely.
- Keep failure observable; design storage failure handling with its authority,
- rather than adding scattered catch-and-continue guards.
-- A Local public invitation URL does not identify the transport used by a LAN
- visitor. Cookie issuance must support both HTTP LAN and HTTPS public access;
- globally dropping Secure or trusting arbitrary forwarded headers is not an
- acceptable shortcut.
-- Audio capture can end silently while video continues. Ending healthy video is
- not accepted as the fix; explicit audio availability/recovery needs a coherent
- media contract. Native prepared-bridge fallback likewise needs a shared
- session-level failure owner, not a per-candidate flag that is immediately lost.
-- Registering Receivers with Engine, deduplicating media ledgers, splitting page
- owners, and replacing full graph snapshots are refactor candidates, not proven
- present-day leaks or measured performance wins.
-- No replacement media pipeline, custom scoring, periodic retries, TURN, IDL
- framework, compatibility readers, or new revision namespace was accepted.
-
-## Refactor Direction
-
-The [consolidation research](./server-consolidation.md) owns the shared Go module
-layout that replaced the single TypeScript backend. Hosted and Local preserve
-one graph/operation owner, with the Node runtime and superseded server packaging
-removed in that same boundary.
-Browser UI and native capture adapters are reuse boundaries, not rewrite targets.
-
-Use the current behavioral tests as an oracle, not a requirement to preserve
-private class structure. Extract cohesive packages without duplicating mutable
-state; neither a file split nor one interface per old file is inherently an
-improvement. Measure package size, startup, memory, and contract parity.
-
-## Sources
-
-- [WebRTC restartICE](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-restartice)
- defines ICE restart, not a promise of different network mappings.
-- [coder/websocket](https://pkg.go.dev/github.com/coder/websocket)
- documents the connection read and cancellation contract.
-- [Go module layout](https://go.dev/doc/modules/layout)
- supports multiple commands and shared internal packages.
diff --git a/docs/research/cross-platform-client-runtime.md b/docs/research/cross-platform-client-runtime.md
index 5490c122..440d3548 100644
--- a/docs/research/cross-platform-client-runtime.md
+++ b/docs/research/cross-platform-client-runtime.md
@@ -71,6 +71,13 @@ A local page completed discovery and the full control exchange in Chromium
its `loopback-network` permission; without that permission the cross-origin
request was blocked. The gate checks both expected outcomes.
+Run `npm run probe:client-loopback` with `PIIK_CLIENT_LOOPBACK_GATE=true`,
+`CHROME_PATH`, `PIIK_CLIENT_EXE`, and `PIIK_CLIENT_GATE_SITE_URL` pointing to
+the reachable HTTPS Site being tested. Use `PIIK_CLIENT_GATE_GRANT_LOOPBACK=true`
+for the permission-granted run; omit it for the permission-blocked run. The gate
+uses an isolated App configuration and Browser profile, and rejects navigation
+failures or redirects to another origin as acceptance evidence.
+
A self-contained LAN room uses a localhost Host URL and a selected LAN IPv4
Viewer URL backed by the same local App process. The App persists an
optional user-chosen access password and passes it only to its Host page in a
diff --git a/docs/research/cross-restart-room-recovery.md b/docs/research/cross-restart-room-recovery.md
index 280d8674..f7321ac8 100644
--- a/docs/research/cross-restart-room-recovery.md
+++ b/docs/research/cross-restart-room-recovery.md
@@ -83,8 +83,8 @@ For the permanent-room revision, an offline `DROP COLUMN` transaction on a
copy of the prior synthetic database preserved both active and formerly expired
rooms. All six remaining authority fields matched exactly; the source backup
was unchanged. The current reader accepted the converted schema without a
-compatibility path. The [deployment procedure](../deployment.md#permanent-room-schema-cutover)
-owns the operational steps and recovery boundary.
+compatibility path. The completed cutover is retained in Git; current
+[deployment recovery](../deployment.md#recovery) owns the operational boundary.
## Acceptance Matrix
diff --git a/docs/research/piik-rename-plan.md b/docs/research/piik-rename-plan.md
deleted file mode 100644
index 243eada7..00000000
--- a/docs/research/piik-rename-plan.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# Piik rename
-
-Status: accepted rename and coordinated cutover plan.
-Last reviewed: 2026-09-10.
-
-## Accepted identity
-
-Display `Piik`; use `piik` for executable, package, environment and service
-identifiers. GitHub is `TNTcraftHIM/Piik`; the Go module follows that exact case.
-The [naming convention](../reference/naming.md) owns current App display and package names.
-The product keeps its TV mascot. The wordmark and morph animation remain in the
-[brand study](../design/piik-brand.html) for the future public website.
-
-This is a private pre-release rename. It changes names and deployment identity,
-not media policy, routing, capture behavior or SQLite room semantics.
-
-## Recovery and local metadata
-
-The external `Piik-recovery/rename-20260910` directory contains a verified
-`repository.bundle` and a complete `git-metadata` copy. The latter preserves
-reflogs and all ten stash entries, which a bundle of ordinary refs alone does
-not capture. Earlier recovery bundles also remain outside the repository.
-Backups keep their original names and contents so they remain identifiable.
-
-The main directory is `Piik`; preparation worktrees are `Piik-appearance` and
-`Piik-rename`, with `Piik-external-audit` retained separately. Their private Git
-registration names, backlinks and shared remote are updated. The hook path is
-relative `.githooks`. Retire integrated preparation worktrees after cutover.
-The audit worktree's branch and source revision remain untouched. Integration
-keeps one complete phase commit on main.
-
-On Windows, a terminal can hold the repository directory open. Move the entries
-into an empty verified destination and run `git worktree repair` from the new
-main directory. Do not terminate the user's terminal to release a path.
-Existing firewall rules name executable paths, so moved build binaries require
-their corresponding path rules to be reviewed before network acceptance.
-
-## Runtime and data boundary
-
-`piik-v23` and `piik-client-v9` are new exact protocol labels. Their message
-schemas retain versions 23 and 9; the full label, not only its numeric suffix,
-is checked. Native capture remains v7. Release Web, Server, App and capture
-artifacts together; old pages and installed Apps cannot interoperate across
-the renamed control boundary. No alternate protocol reader is introduced.
-
-SQLite schema 2, its application ID, room codes, token/grant digests and password
-material remain unchanged. The four-byte database file identity is a format
-constant, not display branding. Copy the database only while the old process is
-stopped, verify integrity and retained columns, and preserve the original for
-rollback. Do not recreate rooms or repeat the earlier schema-1 cutover.
-
-The implementation renames Browser storage prefixes, the site-access cookie
-and the App configuration/cache directory. The owner accepts a clean break:
-copy directly compatible, accessible settings once during cutover; discard
-unavailable or incompatible settings. The product reads only Piik names, with
-no migration code, alternate reader or old-name alias.
-
-The local App configuration is unchanged JSON version 1 and can be copied
-byte-for-byte into the Piik directory without replacing an existing new config.
-Browser credentials and settings are origin/session-owned. Transfer them only
-through an available original Browser session; do not modify a live Browser's
-storage database or introduce a product bridge to recover them. Otherwise the
-new namespace starts empty, requiring login, room creation and preference setup.
-Old room authority remains in SQLite, but an unavailable Host credential cannot
-be reconstructed from its stored digest. Site-access cookies and remembered
-App activation are renewed normally under the new contract.
-
-## Git history
-
-The owner authorized replacing the old name in Git history. Use the maintained
-`git-filter-repo` tool in a fresh, separate bare clone, never in the working
-repository. Scope this to commit/tag **messages**: historical source snapshots,
-authorship, dates and topology remain factual. Current tracked prose and code
-use the accepted identity; old snapshots remain recoverable at their mapped
-commits and in the original archive.
-
-The initial inventory found two matching commit bodies and no matching commit
-subjects or tag names. A small text change still changes descendant SHAs and
-invalidates their commit signatures. Preserve `commit-map` and `ref-map`; verify
-equal commit counts, identical source trees, mapped parents, authors and dates,
-no dropped commits and a clean repository integrity check. No replacement refs,
-duplicate compatibility branches or history-rewriting tool enter the product.
-
-The rehearsal verified all 546 reachable branch/tag commits: exactly two messages
-changed, all file trees and mapped parent relationships match, and authors/dates
-are preserved. Standard filtering rewrote 545 IDs and removed 374 signatures.
-Those signatures remain verifiable only in the original archive; a rewritten
-commit must not be presented as preserving its earlier GitHub verification.
-
-Apply a reviewed message rewrite only with the coordinated brand integration,
-using explicit ref targets and old-SHA leases. Do not use `push --mirror` from
-the rehearsal: it could overwrite unrelated refs. Preserve the external audit
-branch and stash history in the original repository. Old audit/deployment SHAs
-remain evidence identifiers, interpreted through the archive and commit map.
-
-## Operational cutover
-
-The following old identifiers are retained here only as operator recovery
-inputs, not as runtime aliases:
-
-| Surface | Before | After |
-| --- | --- | --- |
-| Service, user and group | `screener` | `piik` |
-| Installation root | `/opt/screener` | `/opt/piik` |
-| Environment file | `/etc/screener/screener.env` | `/etc/piik/piik.env` |
-| Branded environment prefix | `SCREENER_` | `PIIK_` |
-| Browser storage prefix | `screener:` | `piik:` |
-| App config directory | `Screener` | `Piik` |
-
-Prepare the new immutable artifacts, service/environment/proxy configuration,
-permissions and database path before stopping the old service. Record original
-configuration and ownership for recovery. Do not run two room authorities on
-the same database or two media services on the same UDP ports.
-
-The routine `deploy/release-app.sh` assumes an existing **Piik** installation.
-It is not the first brand migration tool: its old-release checks and recovery
-target the Piik service/binary. Perform the first name cutover as one explicit
-infrastructure operation, then use the ordinary wrapper for future releases.
-On failure, stop the candidate and restore the old binary, service, environment,
-proxy and data together before reopening ingress.
-
-GitHub is already renamed and the remote works. There are no published releases
-or Pages site to migrate. Keep repository visibility private; `piik.tv` DNS and
-Pages publication remain a separate website task. Old GitHub deployment/PR
-records describe earlier operations and are not rewritten as new releases.
-
-## Validation and references
-
-Acceptance covers the tracked-name inventory, Web type/build checks, relevant
-contract/storage tests, native compilation, App/Server packaging and a
-controlled local launch. Production release additionally requires the accepted
-best-effort settings transfer, configuration/database recovery and postflight.
-
-Primary references, checked 2026-09-10:
-
-- [Git worktree repair](https://git-scm.com/docs/git-worktree): repair both
- directions after moving the main repository or linked worktrees.
-- [git-filter-repo](https://github.com/newren/git-filter-repo/blob/main/Documentation/git-filter-repo.txt):
- message replacement, fresh clones and old/new commit maps.
-- [GitHub repository rename](https://docs.github.com/en/repositories/creating-and-managing-repositories/renaming-a-repository):
- ordinary URL redirects do not cover repository-hosted Actions or project Pages.
diff --git a/docs/research/server-consolidation.md b/docs/research/server-consolidation.md
index a543c158..809bedc2 100644
--- a/docs/research/server-consolidation.md
+++ b/docs/research/server-consolidation.md
@@ -32,9 +32,8 @@ remove.
and exact direct/peer-relayed evidence sources.
These are structural simplifications, not reproduced functional failures.
-The [audit reconciliation](./backend-audit-1b01048.md) separates verified fixes
-from disputed recommendations. Its external staged plan is not an instruction
-to perform extractions for their own sake.
+The [engineering reference](../reference/engineering.md#ablation-and-review)
+requires a concrete ownership gain before further extraction.
## Product Choice
diff --git a/docs/status.md b/docs/status.md
index 0dde926d..4f665a8d 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -1,6 +1,6 @@
# Current Status
-Last updated: 2026-09-10
+Last updated: 2026-09-12
This is the compact execution/deployment index. Product modules own behavior,
[verification status](./verification-status.md) owns unresolved physical limits,
@@ -8,9 +8,9 @@ and Git/PRs own completed history.
## Accepted Release Contract
-- Browser/server v23, Native control v9 and capture v7 form one private contract.
- The release requires matching Web/App/Server artifacts and a reload of old
- active pages at cutover.
+- Browser/server v23, Native control v9 and capture v7 form the current contract.
+ The coordinated brand/protocol cutover requires matching Web/App/Server
+ artifacts and a reload of incompatible active pages.
- Hosted Server defaults to SQLite schema 2. Room authority has no inactivity
expiry; explicit replacement/deletion or grant rotation/revocation ends the
corresponding authority. Explicit memory mode and App Local end rooms at
@@ -24,23 +24,40 @@ and Git/PRs own completed history.
## Deployment
Source, package identity, GitHub repository and local worktree paths use Piik.
-The strict wire labels and stored keys move together at the coordinated
-[brand cutover](./research/piik-rename-plan.md). Directly compatible, accessible
-settings are transferred once; unavailable settings start fresh. Runtime code
-keeps only the Piik contract.
+Runtime code keeps only the Piik wire labels and stored keys. The coordinated
+private cutover requires matching App/Server/Web packages; unavailable old
+Browser credentials cannot be reconstructed from stored digests.
The immutable release descriptor, runtime `REVISION` and operator deployment
-record own exact identity and postflight results. The
-[schema cutover](./deployment.md#permanent-room-schema-cutover) preserved existing
-room authority and Browser credential keys. Old active pages reload at the
-signaling v23 boundary.
+record own exact identity and postflight results. Old active pages reload at
+the signaling v23 boundary.
The existing deployment uses one Go process for Web, room authority/signaling,
Binding-only STUN on UDP 3478/3479/3480 and optional SFU on UDP 7882. nginx owns
HTTPS; external LiveKit/coturn services remain disabled. Participants, routes and
media remain process-only. This private service is not a public demonstration.
-[TODO](./todo.md) owns rename acceptance, distribution and ablation work.
-The public website is a later phase.
+The separate US [public demo](https://demo.piik.tv) is deployed with open site
+entry, persistent room authority and P2P-only media. Caddy owns HTTPS, and the
+standard systemd service runs the verified Server test candidate. Public DNS,
+HTTPS, runtime assets, all three STUN listeners and a bounded browser P2P
+sharing/stop check passed; the browser check used synthetic video on one network.
+The operator record owns exact identity and postflight evidence.
+
+[TODO](./todo.md) owns remaining publication work. The owner accepted the public
+introduction and authorized launch on 2026-09-12. The source repository is public,
+main protection is active, and GitHub Pages is configured for `piik.tv`. The
+private service remains a separate deployment. Release descriptors and GitHub
+deployment records identify published artifacts and website revisions.
+
+The Windows test archive passed complete anonymous Gitee download, checksum,
+App entry/presentation and update-link acceptance. Bounded two-build
+interoperability also passed. The complete publisher rehearsal previously hit
+the private repository's Actions artifact quota and must complete on the public
+repository before package publication. GitHub/Gitee release comparison, mirror
+publishing and PR-sourced release notes are implemented under
+[versioning](./reference/versioning.md). [Verification status](./verification-status.md#candidate-evidence-boundary)
+owns the remaining physical limits; shared lessons live in
+[engineering](./reference/engineering.md).
## Media Evidence And Limits
diff --git a/docs/todo.md b/docs/todo.md
index f11b4463..8f830611 100644
--- a/docs/todo.md
+++ b/docs/todo.md
@@ -1,95 +1,48 @@
# Current TODO Ledger
-Last reviewed: 2026-09-10
+Last reviewed: 2026-09-12
-Only **Now** is executable. Product modules own behavior, research owns evidence,
-and Git/PRs own completed history. A parked idea is not implementation authority.
+Only **Now** is executable. Product modules own behavior; Git/PRs own completed
+history. A parked idea is not implementation authority.
## Now
-After the accepted App naming release, draft the English/Chinese README,
-onboarding and GitHub Pages website as one coherent public introduction.
-Use the [naming convention](./reference/naming.md), the existing mascot and
-the accepted website-only brand animation. Preview locally before publication;
-keep private deployment details out of the public site. Preserve the rename
-recovery archive and external-audit worktree. Release metadata owns deployed identity.
-
-## Next — Awaiting Owner Direction
-
-The owner owns **piik.tv**.
-Review deployment feature switches, starting with an explicit P2P-only mode:
-the operator must be able to disable SFU in configuration while retaining STUN,
-room authority/signaling and P2P viewing. Current `SFU_UDP_PORT` already controls
-SFU availability; inspect that contract and the forced-private-mode UI before
-adding a second boolean with potentially conflicting meaning. Review which
-other options belong to deployment configuration, runtime parameters or fixed
-implementation constants. Keep this separate from public-facing documentation drafting.
-
-The owner proposes GitHub Pages for the public website and the dedicated US
-test server for a separate P2P-only demonstration site. Plan this after naming
-and configuration review; no public demo is deployed yet. The existing private
-production site remains private. P2P-only has no SFU fallback when direct/peer
-paths cannot connect; the demonstration must describe that actual capability.
-
-Redesign the README, onboarding guides and Wiki/documentation navigation as one
-coherent release-preparation task. The owner is dissatisfied with the current
-structure; do not keep polishing it piecemeal. Until then, change only necessary
-names, runnable commands and links. Keep the new public entry brief, visual and
-easy to follow, with deeper technical detail in developer guides.
-
-Design the GitHub Pages website around the accepted brand study. Keep one
-current internal contract; third-party names/notices remain accurate. DNS/Pages
-and public publication are separate from the repository rename. The private
-production service is not a public demo.
-
-Include the owner-requested frontend/backend ablation review in that phase.
-Review duplicated behavior/state, module boundaries, interface clarity, lifecycle
-ownership, cohesion and coupling. Reuse mature modules and stable shared behavior.
-The primary goal is lower total complexity, not perfect performance: small gains
-do not justify permanent mechanisms or larger maintenance cost. Preserve viewing
-quality and product behavior; fewer lines alone do not justify a rewrite.
-
-Use the App discovery and settings-ownership findings as leads for a
-repository-wide lifecycle audit across Web UI, shared Go server, App and
-media adapters. This is future work, not an expansion of the current entry fix.
-Look for these recurring patterns:
-
-- Permission, remembered activation, capability, connection readiness and live
- operation ownership represented by the same flag or inferred from UI state.
-- Cached promises retaining `null`, rejection or a closed resource indefinitely;
- failure latches whose lifetime exceeds the evidence that justified them.
-- Results after `await`, callbacks and `finally` writing shared state or closing
- the current resource without checking the original operation/resource owner.
-- Cancellation, failure and absent observation sharing a return value that a
- caller interprets as success; review the complete caller chain.
-- Connections, slots, listeners and queues acquired before actual demand, kept
- after their consumer ends, or retired while another consumer still owns them.
-- Draft, requested, applied and server-acknowledged settings overwriting one
- another; duplicated writers or status models that can contradict real media.
-
-Search results are leads, not defect evidence. Trace acquisition through use,
-commit and retirement, including error paths and shared consumers. Reproduce
-representative interleavings: A starts, is cancelled/replaced, B starts, then A
-completes or fails. Check both obsolete writes and obsolete cleanup, plus
-stop/restart and transient-failure recovery. Fix the owning boundary and remove
-redundant state rather than add case-specific flags, timers or a generic manager.
-Keep confirmed repairs separate from documented tradeoffs and unsupported
-suspicions; retain only focused checks that demonstrate a meaningful failure.
-
-English/Chinese Quick Start, documentation map and license guidance are prepared.
-Keep the README short and friendly, with the logo and a small usage illustration;
-detailed deployment/development guidance belongs in the linked guides. Draft a
-static GitHub Pages homepage with tutorials and self-contained demonstrations
-matching the living-room UI. Review final release assets, update/replacement
-guidance and public distribution alongside the new brand; existing packagers and
-Docker recipe are the baseline.
-Keep expensive packaging manual and branch CI quiet. No broad media redesign is
-part of naming or documentation work.
-
-[Verification status](./verification-status.md) owns broader physical limits.
-NAT and Auto are complete features; further statistical/hardware research is not
-required to finish this phase. Run any new physical workload serially, with stable
-executable paths and cleanup before the next.
+- [ ] **Release and repository readiness.** Review the prepared Windows test
+ candidate. Run native CI on the now-public repository, then
+ rehearse the publisher with genuine matching Server and App packages. Old cloud
+ artifacts have already been removed; if quota rejection persists, inspect
+ account billing and Packages usage with credentials that can read those scopes.
+ Run the final source's required regression checks, prepare one coherent squash
+ PR, accept the [first public release](./reference/versioning.md#first-public-release-readiness),
+ and finish [publishing activation](./operations/github.md).
+ Test-candidate checks do not accept the public release. Keep the owner's
+ [device/network deferrals](./verification-status.md#candidate-evidence-boundary).
+- [ ] **Gitee package acceptance.** The public README mirror, publisher secret,
+ upload pipeline and App/Server update fallback are implemented. The complete
+ Windows test archive passed anonymous download, checksum and App entry
+ acceptance. Verify the complete matching Server and three-platform
+ App release, total attachment capacity and real update/download flow
+ under the [release model](./reference/versioning.md#release-sources) before launch.
+- [ ] **Website launch.** Publish the accepted website through GitHub Pages
+ and verify piik.tv under
+ [website operations](./operations/website.md). Verify all public destinations,
+ including the deployed password-free, P2P-only demo.piik.tv;
+ the current private production service remains private.
+
+Keep implementation on the existing phase branch. Main and the private service stay
+unchanged until the related acceptance and delivery actions are complete.
+
+## Next: P2P Connection And Feedback Review
+
+After the current phase, measure connection success, time to first picture and
+failure causes on representative networks, especially App and P2P-only sites.
+Review user progress/failure feedback and useful privacy-conscious diagnostics.
+Trace the existing ICE and P2P/SFU handoffs, including background P2P attempts
+behind working SFU media; compare SFU-first startup with measured current behavior
+before choosing changes. Preserve one graph and one operation under the
+[routing contract](./product/routing-transport.md) and
+[ADR-0005](./adr/0005-automatic-hybrid-media-routing.md). Prior ownership audits do
+not establish better connection success or speed; this note adds no retry policy.
## Parked Product Work
@@ -101,41 +54,56 @@ reproduce them. Missing NAT attempt text alone does not prove skipped attempts.
If Native adaptation is implicated, compare actual VSE limitations with sender
quality evidence before changing policy. Do not add retry budgets, visibility
resets or resolution heuristics without proof. Sanitized aggregates and the
-isolated reconnect reproduction remain locally in `build/room7534-investigation/`.
-
-1. **Public distribution and updates.** Candidate packagers, immutable descriptors,
- notices, the runtime-only OCI recipe and release checks exist. Choose the
- public asset set and release notes before publishing a full-SHA GitHub Release
- or image. Do not add automatic installation, container self-update, Watchtower,
- compatibility ranges or active-share interruption without distribution and
- recovery evidence. Ordinary branch pushes must not run expensive CI packaging.
-2. **Representative device/network acceptance.** Exercise public-network direct
- and relay paths, two-room SFU, real-game A/V, twenty-Viewer endurance,
- sustained loss/recovery and all-UDP-blocked bounded failure. Correlate freezes
- with publisher/receiver evidence before changing representation policy.
- Physical Android/iOS work includes autoplay, background/lock, rotation,
- network migration and relay survival. Secondary desktop platform matrices
- remain explicitly deferred; compilation does not prove capture.
-3. **Broader quality work.** Reopen from measured benefit at acceptable complexity.
+isolated reconnect reproductions are diagnostic evidence, not a recovery policy.
+Game/background settings behavior also remains an unconfirmed incident lead;
+reopen from actual control actions and matching requested/applied media evidence.
+Clarify whether Viewer-local pause should survive replacement media before
+adding playback-intent state; the current binding starts new media unless the
+Host is paused. No preservation policy has been accepted for that transition.
+
+1. **Representative device/network acceptance.** Resume the remaining matrix in
+ [verification status](./verification-status.md#remaining-device-and-network-acceptance)
+ when directed, preserving the owner's platform deferrals. Correlate freezes
+ with publisher/receiver evidence before changing media policy. Run physical
+ workloads serially from stable executable paths with cleanup between runs.
+2. **Broader quality work.** Reopen from measured benefit at acceptable complexity.
Preserve chosen profiles, bitrate ceilings, endpoint capacity and P2P-first
routing unless a new accepted decision supports changing them. No weighted
score, all-pairs probes, periodic rebalancing, parent-wide prediction or
room-wide minimum. Check whether a quality move merely shifts pressure to
another parent's siblings before widening policy.
-4. **Control/resource fairness and input review.** Reassess the authenticated
+3. **Control/resource fairness and input review.** Reassess the authenticated
WebSocket/SFU owner, HTTP/body/resource bounds, authorization and error/log
handling before adding a queue or limiter. No parallel security framework,
accounts, risk score or speculative policy layer.
-5. **Reachable ownership/refactor work.** Extract page media-session owners only
- alongside behavior changes; file size alone is not a rewrite reason. Reopen
- C=3 structural-intent retention, SFU failure during unrelated prepare and
- multi-child evidence ownership only with current-contract reproductions.
+ Measure signaling-lock contention and synchronous diagnostic I/O before
+ changing the lock or execution model; their cost remains a tradeoff.
+4. **Reachable ownership/refactor work.** Retain Host/Viewer page media-session
+ extraction as a candidate alongside related behavior changes. Evaluate clear
+ resource owners, fewer shared writers and a smaller change surface under
+ [engineering review](./reference/engineering.md#ablation-and-review); file
+ size alone does not justify a split. The completed audits do not close this
+ candidate. Reopen C=3 structural-intent retention, SFU failure during unrelated
+ prepare and multi-child evidence ownership only with current-contract
+ reproductions.
No new revision namespace, failure-state mirror or topology queue by default.
-6. **Storage fault recovery.** Ordinary transactions persist before memory
- changes; failures must preserve authority. Message-handler panics must unwind
- locks. Damaged-disk/COMMIT/ROLLBACK recovery is not established; choose its
- policy explicitly rather than adding catch-and-continue or retries.
-7. **Platform output.** System/tab mirroring needs no adapter. Remote Playback,
- Cast and AirPlay do not provide a portable live MediaStream receiver.
- Reopen for a registered receiver acting as an ordinary Viewer after the
- [platform-output gate](./research/platform-output.md) passes.
+5. **Storage fault recovery.** Choose and verify a damaged-disk/COMMIT/ROLLBACK
+ recovery policy before adding catch-and-continue or retries. This failure
+ boundary remains unestablished after ordinary persistence checks.
+6. **Platform output.** Reopen for a registered receiver acting as an ordinary
+ Viewer only after the [platform-output gate](./research/platform-output.md)
+ passes.
+7. **Full UI themes.** After the base version, research themes that can change
+ layout, composition and motion, including a restrained graphic/cinematic
+ direction with original Piik assets. Assess extension boundaries and cost
+ before scheduling any theme/plugin API. Design experiments remain in Git
+ history, outside the main source tree.
+8. **Visual presentation and community translations.** In a later version,
+ explore bringing the pure-visual mode's illustrations and motion into the
+ Chinese and English interfaces. Evaluate whether a separate pure-visual mode
+ remains useful, and prepare the existing locale catalogs for community
+ translations. No removal or new translation framework is scheduled for this
+ release.
+9. **Website illustration polish.** Match the Host's held prop to the four
+ existing hero activities: gamepad, paintbrush, camera and remote. Keep the
+ accepted bright cast, floating hands and shared activity timing.
diff --git a/docs/verification-status.md b/docs/verification-status.md
index 7a009215..497c040d 100644
--- a/docs/verification-status.md
+++ b/docs/verification-status.md
@@ -1,6 +1,6 @@
# Verification Status
-Last updated: 2026-09-09
+Last updated: 2026-09-11
This file owns physical evidence limits that change how the product may be
described. [Status](./status.md) owns the execution/deployment index.
@@ -11,8 +11,7 @@ implementation and obsolete package history.
Windows App and Browser are the owner's primary acceptance targets. Current
Go packages embed their Web assets and do not run a Node backend. The current
-contract is Browser/server v22, Native control v9 and capture v7; pre-port
-App/Node package checks do not prove this package.
+contract is Browser/server v23, Native control v9 and capture v7.
Bounded current checks cover:
@@ -41,6 +40,29 @@ Neither a statistical NAT campaign nor exhaustive Auto hardware benchmarking
is required to close this phase. Investigate further only from a new failure
or a measured improvement worth its implementation and maintenance cost.
+## Candidate Evidence Boundary
+
+The 2026-09-11 functional test acceptance used two genuine Windows App packages
+and matching Server source/Web builds under the same private contract. Both App/Site version
+directions delivered decoded 1080p H264 from an isolated native test window.
+Replacing the Server process preserved SQLite Host authority, private code-entry
+policy, Viewer grant/password authorization and App configuration. Already-open
+Host/Viewer pages reauthenticated without reloading and completed subsequent
+sharing. Exact measured identity belongs to the package descriptors and local
+structured acceptance result; Git retains the preparation history.
+
+This is bounded single-machine Windows evidence. The local Server executables
+were built for Windows from the matching source; this run did not execute the
+Linux release archives. Process replacement used a forced stop on Windows and
+does not promise uninterrupted media. It does not cover game/audio endurance,
+storage faults, the wider device/network matrix or Go race detection.
+
+The full publisher dry run with genuine matching target artifacts remains
+unverified. The native CI candidate run passed validation and Server packaging
+but hit the Actions artifact-storage quota before App jobs could start. Native
+macOS tooling remains necessary. [TODO](./todo.md) owns the remaining publisher
+rehearsal and owner acceptance; the broader platform deferrals below still apply.
+
## Remaining Device And Network Acceptance
The following are broader coverage and endurance tasks, not automatically new
diff --git a/go.mod b/go.mod
index f0cd37a1..436b133d 100644
--- a/go.mod
+++ b/go.mod
@@ -28,6 +28,7 @@ require (
github.com/thesyncim/gopus v0.1.1
go.uber.org/zap v1.28.0
golang.org/x/crypto v0.54.0
+ golang.org/x/mod v0.38.0
golang.org/x/text v0.41.0
google.golang.org/protobuf v1.36.11
modernc.org/sqlite v1.58.0
diff --git a/index.html b/index.html
index a5f78731..e57d60cf 100644
--- a/index.html
+++ b/index.html
@@ -8,11 +8,17 @@
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>Piik</title>
<script>
- try {
- var theme = localStorage.getItem("piik:ui-theme") ||
- (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
- document.documentElement.dataset.theme = theme;
- } catch (e) {}
+ var systemTheme = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
+ var theme;
+ try { theme = localStorage.getItem("piik:ui-theme"); } catch (e) {}
+ var launch = new URLSearchParams(location.hash.slice(1));
+ var launchTheme = launch.get("piik-theme");
+ if (launch.get("piik-client") === "1" &&
+ (launchTheme === "light" || launchTheme === "dark" || launchTheme === "system")) {
+ theme = launchTheme === "system" ? systemTheme : launchTheme;
+ }
+ document.documentElement.dataset.theme =
+ theme === "light" || theme === "dark" ? theme : systemTheme;
</script>
</head>
<body>
diff --git a/internal/app/app.go b/internal/app/app.go
index fc4ac3b3..b5c5d2e9 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -28,6 +28,7 @@ import (
serverapp "github.com/TNTcraftHIM/Piik/internal/server/app"
serverconfig "github.com/TNTcraftHIM/Piik/internal/server/config"
"github.com/TNTcraftHIM/Piik/internal/server/webassets"
+ "golang.org/x/mod/semver"
)
const (
@@ -41,8 +42,17 @@ const (
localShutdownTimeout = 5 * time.Second
)
+var BuildVersion = "development"
var BuildRevision = "development"
+func buildVersion() string {
+ version := strings.TrimSpace(BuildVersion)
+ if version != "" && semver.Canonical(version) == version && semver.Prerelease(version) == "" {
+ return version
+ }
+ return "development"
+}
+
type Options struct {
Site string
SiteSet bool
@@ -87,6 +97,7 @@ func Run(ctx context.Context, options Options) (returnedErr error) {
if err != nil {
return fmt.Errorf("Piik App diagnostics are unavailable: %w", err)
}
+ recorder.Context("build", map[string]any{"version": buildVersion(), "revision": BuildRevision})
previous, previousWriter, previousFlags := slog.Default(), log.Writer(), log.Flags()
var dependencyLog *diagnostics.LineWriter
restoreLogger = func() {
@@ -102,7 +113,7 @@ func Run(ctx context.Context, options Options) (returnedErr error) {
log.SetFlags(previousFlags)
options.console.send(consoleDebug{logPath: recorder.LogPath(), export: recorder.Export})
}
- slog.Debug("piik-client", "event", "start", "revision", BuildRevision)
+ slog.Debug("piik-client", "event", "start", "version", buildVersion(), "revision", BuildRevision)
options.console.show(consoleView{state: "starting"})
if err := validateMode(options); err != nil {
return err
@@ -192,6 +203,7 @@ func runLauncher(
ctx,
webassets.FS(),
config.Site,
+ buildVersion(),
BuildRevision,
config.LocalAccessPassword,
)
diff --git a/internal/app/app_test.go b/internal/app/app_test.go
index 94eb35a1..5850d420 100644
--- a/internal/app/app_test.go
+++ b/internal/app/app_test.go
@@ -3,20 +3,74 @@ package app
import (
"bytes"
"errors"
+ "fmt"
"log"
"log/slog"
"net"
+ "net/http"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"testing"
+ "time"
appconfig "github.com/TNTcraftHIM/Piik/internal/app/config"
+ "github.com/TNTcraftHIM/Piik/internal/app/loopback"
serverconfig "github.com/TNTcraftHIM/Piik/internal/server/config"
)
+func TestSavedSiteAllowsBrowserOriginAtNativeControl(t *testing.T) {
+ for _, site := range []struct{ input, origin string }{
+ {"https://Share.Example:443", "https://share.example"},
+ {"http://share.example:80", "http://share.example"},
+ {"http://share.example:8787", "http://share.example:8787"},
+ } {
+ t.Run(site.input, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "client.json")
+ payload := fmt.Sprintf(`{"version":1,"localAccessPassword":"","site":%q}`, site.input)
+ if err := os.WriteFile(path, []byte(payload), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ configuration, err := appconfig.LoadOrCreate(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ control, err := loopback.Start(t.Context(), loopback.Options{
+ AllowedOrigins: allowedOrigins(configuration.Site, 8787),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = control.Close() })
+ client := &http.Client{Timeout: 3 * time.Second}
+ for _, probe := range []struct {
+ method, origin string
+ status int
+ }{
+ {http.MethodOptions, site.origin, http.StatusNoContent},
+ {http.MethodGet, site.origin, http.StatusOK},
+ {http.MethodOptions, "https://other.example", http.StatusForbidden},
+ } {
+ request, err := http.NewRequest(probe.method, control.Endpoint().URL+"/health", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Origin", probe.origin)
+ response, err := client.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != probe.status {
+ t.Fatalf("%s health from %q = %d, want %d", probe.method, probe.origin, response.StatusCode, probe.status)
+ }
+ }
+ })
+ }
+}
+
func TestOccupiedPortRejectsLinkBeforeStartingATunnel(t *testing.T) {
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero})
if err != nil {
@@ -83,6 +137,7 @@ func TestAppDiagnosticsUseFilesOnlyWhenEnabled(t *testing.T) {
continue
}
if readErr != nil || !strings.Contains(string(content), `"event":"start"`) ||
+ !strings.Contains(string(content), `"version":"`+buildVersion()+`"`) ||
!strings.Contains(string(content), `"revision":`) ||
!strings.Contains(string(content), `"event":"stopped","failed":true`) {
t.Fatalf("missing file lifecycle events: %s, %v", content, readErr)
diff --git a/internal/app/config/config.go b/internal/app/config/config.go
index 01ca04b5..30b7aa17 100644
--- a/internal/app/config/config.go
+++ b/internal/app/config/config.go
@@ -11,6 +11,8 @@ import (
"path/filepath"
"regexp"
"strings"
+
+ serverconfig "github.com/TNTcraftHIM/Piik/internal/server/config"
)
const (
@@ -101,7 +103,7 @@ func NormalizeSite(value string) (string, error) {
parsed.RawQuery != "" || parsed.Fragment != "" {
return "", errors.New("Piik Site must be an HTTP or HTTPS origin")
}
- return parsed.Scheme + "://" + parsed.Host, nil
+ return serverconfig.Origin(parsed), nil
}
// NormalizeLocalAccessPassword keeps the local authority open by default while
diff --git a/internal/app/config/config_test.go b/internal/app/config/config_test.go
index 5057a580..a395af6e 100644
--- a/internal/app/config/config_test.go
+++ b/internal/app/config/config_test.go
@@ -57,12 +57,17 @@ func TestSavePersistsOneNormalizedSiteChoice(t *testing.T) {
}
func TestNormalizeSiteAcceptsOnlyAPlainWebOrigin(t *testing.T) {
- for _, value := range []string{
- "https://share.example",
- "http://192.168.1.4:8787/",
+ for value, want := range map[string]string{
+ "https://share.example": "https://share.example",
+ "https://Share.Example:443/": "https://share.example",
+ "http://Share.Example:80": "http://share.example",
+ "https://share.example:0443": "https://share.example",
+ "http://192.168.1.4:8787/": "http://192.168.1.4:8787",
+ "http://share.example:443": "http://share.example:443",
+ "https://[::1]:443": "https://[::1]",
} {
- if _, err := NormalizeSite(value); err != nil {
- t.Fatalf("NormalizeSite(%q) = %v", value, err)
+ if got, err := NormalizeSite(value); err != nil || got != want {
+ t.Fatalf("NormalizeSite(%q) = %q, %v; want %q", value, got, err, want)
}
}
for _, value := range []string{
diff --git a/internal/app/console.go b/internal/app/console.go
index a0ed9e33..f10845bc 100644
--- a/internal/app/console.go
+++ b/internal/app/console.go
@@ -281,7 +281,11 @@ func (model consoleModel) content(styled bool) string {
revision = revision[:7]
}
var out strings.Builder
- heading := "Piik\nApp\n" + muted.Render(revision)
+ version := buildVersion()
+ heading := "Piik\nApp\n" + muted.Render(version)
+ if revision != "" && revision != version {
+ heading = "Piik App\n" + muted.Render(version) + "\n" + muted.Render(revision)
+ }
animated := styled && model.animating()
mascot := accent.Render(consoleTV(model.frame, animated, compact || width < 34))
if styled && model.colors && width >= 36 && !compactDebug {
diff --git a/internal/app/console_test.go b/internal/app/console_test.go
index 5d55635f..cd521e17 100644
--- a/internal/app/console_test.go
+++ b/internal/app/console_test.go
@@ -111,6 +111,27 @@ func TestConsolePresentationAndShutdown(t *testing.T) {
}
}
+func TestConsoleBuildVersionAndRevision(t *testing.T) {
+ previousVersion, previousRevision := BuildVersion, BuildRevision
+ t.Cleanup(func() { BuildVersion, BuildRevision = previousVersion, previousRevision })
+ BuildRevision = strings.Repeat("a", 40)
+ for _, test := range []struct{ version, want string }{
+ {"v1.2.3", "v1.2.3"},
+ {"development", "development"},
+ {"", "development"},
+ {"v01.2.3", "development"},
+ {"v1.2", "development"},
+ {"v1.2.3-preview.1", "development"},
+ {"v1.2.3+build", "development"},
+ } {
+ BuildVersion = test.version
+ content := (consoleModel{width: 80, language: "en", view: consoleView{state: "ready"}}).content(false)
+ if !strings.Contains(content, test.want) || !strings.Contains(content, "aaaaaaa") || strings.Contains(content, BuildRevision) {
+ t.Fatalf("console identity for %q: %s", test.version, content)
+ }
+ }
+}
+
func TestConsoleDiagnosticExportRunsOutsideUpdate(t *testing.T) {
called := 0
path := filepath.Join(t.TempDir(), "client-report.zip")
diff --git a/internal/app/launcher/server.go b/internal/app/launcher/server.go
index 8dfd8fe6..cdf69937 100644
--- a/internal/app/launcher/server.go
+++ b/internal/app/launcher/server.go
@@ -48,6 +48,7 @@ type Server struct {
static http.Handler
site string
localAccessPassword string
+ version string
revision string
selection chan Selection
resultReady chan struct{}
@@ -68,7 +69,7 @@ type Server struct {
// Start serves the launcher page and its API on a loopback port. assets is the
// built Browser UI, which the App embeds; a nil file system means the binary
// carries no build and the launcher cannot run.
-func Start(parent context.Context, assets fs.FS, site, revision, localAccessPassword string) (*Server, error) {
+func Start(parent context.Context, assets fs.FS, site, version, revision, localAccessPassword string) (*Server, error) {
if parent == nil {
parent = context.Background()
}
@@ -100,6 +101,7 @@ func Start(parent context.Context, assets fs.FS, site, revision, localAccessPass
static: http.FileServer(http.FS(assets)),
site: site,
localAccessPassword: normalizedPassword,
+ version: version,
revision: strings.TrimSpace(revision),
selection: make(chan Selection, 1),
resultReady: make(chan struct{}),
@@ -201,6 +203,7 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Re
writeJSON(response, http.StatusOK, map[string]any{
"site": server.site,
"localAccessPassword": server.localAccessPassword,
+ "version": server.version,
"revision": server.revision,
"defaultMode": func() Mode {
if server.site != "" {
diff --git a/internal/app/launcher/server_test.go b/internal/app/launcher/server_test.go
index 3205ec62..7dc22b03 100644
--- a/internal/app/launcher/server_test.go
+++ b/internal/app/launcher/server_test.go
@@ -31,11 +31,12 @@ func TestLauncherServesStateAndCompletesOneSelection(t *testing.T) {
Site string `json:"site"`
LocalAccessPassword string `json:"localAccessPassword"`
DefaultMode Mode `json:"defaultMode"`
+ Version string `json:"version"`
Revision string `json:"revision"`
}
if response.StatusCode != http.StatusOK || json.NewDecoder(response.Body).Decode(&state) != nil ||
state.Site != "https://share.example" || state.DefaultMode != ModeSite ||
- state.Revision != "" || state.LocalAccessPassword != "" {
+ state.Version != "development" || state.Revision != "" || state.LocalAccessPassword != "" {
t.Fatalf("launcher state = %d, %+v", response.StatusCode, state)
}
@@ -80,9 +81,10 @@ func TestLauncherServesStateAndCompletesOneSelection(t *testing.T) {
}
}
-func TestLauncherIncludesTheInjectedBuildRevision(t *testing.T) {
+func TestLauncherIncludesTheInjectedBuildVersionAndRevision(t *testing.T) {
+ const version = "v1.2.3"
const revision = "0123456789abcdef0123456789abcdef01234567"
- server := startFixtureWithRevision(t, "", revision)
+ server := startFixtureWithBuildAndPassword(t, "", version, revision, "")
origin := strings.TrimSuffix(server.URL(), "/client")
response, err := http.Get(origin + "/api/client-launcher")
if err != nil {
@@ -90,11 +92,12 @@ func TestLauncherIncludesTheInjectedBuildRevision(t *testing.T) {
}
defer response.Body.Close()
var state struct {
+ Version string `json:"version"`
Revision string `json:"revision"`
}
if response.StatusCode != http.StatusOK || json.NewDecoder(response.Body).Decode(&state) != nil ||
- state.Revision != revision {
- t.Fatalf("launcher revision = %d, %+v", response.StatusCode, state)
+ state.Version != version || state.Revision != revision {
+ t.Fatalf("launcher build = %d, %+v", response.StatusCode, state)
}
}
@@ -147,17 +150,17 @@ func TestLauncherCarriesAndNormalizesAnOptionalLocalPassword(t *testing.T) {
}
func TestLauncherRejectsAnInvalidSavedSite(t *testing.T) {
- if _, err := Start(t.Context(), appAssets(), "https://example.test/path", "", ""); err == nil {
+ if _, err := Start(t.Context(), appAssets(), "https://example.test/path", "development", "", ""); err == nil {
t.Fatal("launcher accepted a Site path")
}
}
// A binary built without the Browser build has nothing to launch.
func TestLauncherRequiresTheEmbeddedBrowserBuild(t *testing.T) {
- if _, err := Start(t.Context(), nil, "", "", ""); err == nil {
+ if _, err := Start(t.Context(), nil, "", "development", "", ""); err == nil {
t.Fatal("launcher started without embedded assets")
}
- if _, err := Start(t.Context(), fstest.MapFS{}, "", "", ""); err == nil {
+ if _, err := Start(t.Context(), fstest.MapFS{}, "", "development", "", ""); err == nil {
t.Fatal("launcher started without an index document")
}
}
@@ -238,23 +241,19 @@ func TestLauncherRejectsCrossOriginControl(t *testing.T) {
}
func startFixture(t *testing.T, site string) *Server {
- return startFixtureWithRevisionAndPassword(t, site, "", "")
-}
-
-func startFixtureWithRevision(t *testing.T, site, revision string) *Server {
- return startFixtureWithRevisionAndPassword(t, site, revision, "")
+ return startFixtureWithBuildAndPassword(t, site, "development", "", "")
}
func startFixtureWithPassword(t *testing.T, site, password string) *Server {
- return startFixtureWithRevisionAndPassword(t, site, "", password)
+ return startFixtureWithBuildAndPassword(t, site, "development", "", password)
}
-func startFixtureWithRevisionAndPassword(
+func startFixtureWithBuildAndPassword(
t *testing.T,
- site, revision, password string,
+ site, version, revision, password string,
) *Server {
t.Helper()
- server, err := Start(t.Context(), appAssets(), site, revision, password)
+ server, err := Start(t.Context(), appAssets(), site, version, revision, password)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/app/loopback/server_test.go b/internal/app/loopback/server_test.go
index 14cfa9f5..af814ac7 100644
--- a/internal/app/loopback/server_test.go
+++ b/internal/app/loopback/server_test.go
@@ -17,7 +17,7 @@ import (
"github.com/coder/websocket/wsjson"
)
-const testOrigin = "https://share.bonfire.icu"
+const testOrigin = "https://share.example.com"
func TestStartServesHealthAndStrictControlHandshake(t *testing.T) {
expectedMedia := NativeMediaCapabilities{
diff --git a/internal/server/app/access.go b/internal/server/app/access.go
index a73d1fb6..37026592 100644
--- a/internal/server/app/access.go
+++ b/internal/server/app/access.go
@@ -17,20 +17,17 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
-// Ported from src/server/access-session.ts.
const (
defaultSessionTTLSeconds = 24 * 60 * 60
cookieVersion = "v1"
)
var (
- // TS: /^\d+$/ over the expiry segment.
- accessExpiresPattern = regexp.MustCompile(`^[0-9]+$`)
- // TS: /^[A-Za-z0-9_-]{43}$/ — base64url of a 32-byte HMAC, unpadded.
+ accessExpiresPattern = regexp.MustCompile(`^[0-9]+$`)
accessSignaturePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)
)
-// siteAccessOptions mirrors SiteAccessOptions in access-session.ts.
+// siteAccessOptions configures cookie lifetime, signing and transport policy.
type siteAccessOptions struct {
// Password empty means site access is not required.
Password string
@@ -38,7 +35,7 @@ type siteAccessOptions struct {
Secure bool
// Now returns Unix milliseconds; nil uses the wall clock.
Now func() int64
- // TTLSeconds of 0 stands for TS's absent `ttlSeconds`, i.e. 24 hours.
+ // TTLSeconds of 0 selects the default 24-hour lifetime.
TTLSeconds int
}
@@ -75,7 +72,6 @@ func newSiteAccess(options siteAccessOptions) (*siteAccessGate, error) {
if ttlSeconds == 0 {
ttlSeconds = defaultSessionTTLSeconds
}
- // TS: !Number.isSafeInteger(ttlSeconds) || ttlSeconds <= 0.
if ttlSeconds < 0 || int64(ttlSeconds) > protocol.MaxSafeInteger {
return nil, errors.New("Access session TTL must be a positive integer")
}
@@ -111,9 +107,6 @@ func (a *siteAccessGate) isAuthenticated(cookieHeader string) bool {
if value == "" {
return false
}
- // TS: const [version, expiresText, signature, ...extra] = value.split(".")
- // Fewer than three segments fail the two regexes below (an absent segment
- // is tested as ""), more than three fill `extra`.
segments := strings.Split(value, ".")
if len(segments) != 3 ||
segments[0] != cookieVersion ||
@@ -121,8 +114,7 @@ func (a *siteAccessGate) isAuthenticated(cookieHeader string) bool {
!accessSignaturePattern.MatchString(segments[2]) {
return false
}
- // TS: Number(expiresText) then Number.isSafeInteger. The segment is all
- // digits, so only an out-of-range value can fail here.
+ // Expiry is already decimal; parsing still enforces integer bounds.
expiresAt, err := strconv.ParseInt(segments[1], 10, 64)
if err != nil || expiresAt > protocol.MaxSafeInteger {
return false
diff --git a/internal/server/app/app.go b/internal/server/app/app.go
index 830d6d45..7c0f2465 100644
--- a/internal/server/app/app.go
+++ b/internal/server/app/app.go
@@ -1,6 +1,5 @@
-// Package app ports src/server/app.ts: the HTTP composition, the startup and
-// shutdown lifecycle, and the request router. access.go ports
-// src/server/access-session.ts and static.go the sirv frontend handler.
+// Package app composes the shared HTTP service, site access, embedded assets,
+// media listeners, and startup/shutdown lifecycle for Hosted Server and App.
//
// # Locking
//
@@ -208,13 +207,6 @@ func newRoomStore(options Options) (*room.Store, error) {
})
}
-// Handler is the composed router, exposed so a host process can mount it.
-func (s *Server) Handler() http.Handler { return s }
-
-// Store is PiikServer.roomStore. The signaling server's mutex guards it, so
-// callers outside that lock may only read it while no request is in flight.
-func (s *Server) Store() *room.Store { return s.store }
-
// Listen binds application sockets before recovering room authority and accepting traffic.
func (s *Server) Listen(ctx context.Context) (int, error) {
s.mu.Lock()
diff --git a/internal/server/app/app_test.go b/internal/server/app/app_test.go
index 40f154cd..4834831c 100644
--- a/internal/server/app/app_test.go
+++ b/internal/server/app/app_test.go
@@ -348,11 +348,11 @@ func expectGoroutinesSettled(t *testing.T, before int) {
// --- runtime capabilities -------------------------------------------------
-func TestCapabilitiesKeepNATPredictionAbsentByDefault(t *testing.T) {
+func TestCapabilitiesReportServicesDisabledByDefault(t *testing.T) {
server := start(t, Options{Config: testConfig(t)})
server.do(http.MethodGet, "/api/capabilities").
- expect(http.StatusOK, `{"natPrediction":false}`)
+ expect(http.StatusOK, `{"sfu":false,"natPrediction":false}`)
}
func TestCapabilitiesReportOptionalNATPredictionWithoutExposingConfiguration(t *testing.T) {
@@ -363,7 +363,7 @@ func TestCapabilitiesReportOptionalNATPredictionWithoutExposingConfiguration(t *
server := start(t, Options{Config: configuration})
server.do(http.MethodGet, "/api/capabilities").
- expect(http.StatusOK, `{"natPrediction":true}`).
+ expect(http.StatusOK, `{"sfu":false,"natPrediction":true}`).
expectHeader("Cache-Control", "no-store").
expectHeader("X-Content-Type-Options", "nosniff")
@@ -405,6 +405,8 @@ func TestSFUListenerFollowsApplicationCloseAndEnd(t *testing.T) {
if server.signaling.Load() == nil || server.media == nil {
t.Fatal("missing runtime owner")
}
+ server.do(http.MethodGet, "/api/capabilities").
+ expect(http.StatusOK, `{"sfu":true,"natPrediction":false}`)
var err error
if ending {
err = server.End(context.Background())
@@ -671,16 +673,21 @@ func TestSiteAccessRejectsAnExpiredOrModifiedCookie(t *testing.T) {
}
func TestSiteAccessIsImmediateWhenTheAccessPasswordIsEmpty(t *testing.T) {
- configuration := testConfig(t)
- configuration.SiteAccessPassword = ""
- server := start(t, Options{Config: configuration})
+ for _, environment := range []config.Environment{config.EnvironmentDevelopment, config.EnvironmentProduction} {
+ t.Run(string(environment), func(t *testing.T) {
+ configuration := testConfig(t)
+ configuration.Env = environment
+ configuration.SiteAccessPassword = ""
+ server := start(t, Options{Config: configuration})
- server.do(http.MethodGet, "/api/site-access").
- expect(http.StatusOK, `{"required":false,"authenticated":true}`).
- expectHeader("Set-Cookie", "")
- server.do(http.MethodPost, "/api/site-access", withOrigin(allowedOrigin)).
- expect(http.StatusOK, `{"required":false,"authenticated":true}`).
- expectHeader("Set-Cookie", "")
+ server.do(http.MethodGet, "/api/site-access").
+ expect(http.StatusOK, `{"required":false,"authenticated":true}`).
+ expectHeader("Set-Cookie", "")
+ server.do(http.MethodPost, "/api/site-access", withOrigin(allowedOrigin)).
+ expect(http.StatusOK, `{"required":false,"authenticated":true}`).
+ expectHeader("Set-Cookie", "")
+ })
+ }
}
// --- room HTTP API --------------------------------------------------------
@@ -749,7 +756,7 @@ func TestRoomCreationPassesTheSharedViewerCeilingToRoomAdmission(t *testing.T) {
server := start(t, Options{Config: configuration})
server.createRoom(roomRequest{}).expectStatus(http.StatusCreated)
- if got := server.Store().MaxViewersPerRoom(); got != protocol.MaxViewersPerRoomLimit {
+ if got := server.store.MaxViewersPerRoom(); got != protocol.MaxViewersPerRoomLimit {
t.Fatalf("maxViewersPerRoom = %d, want %d", got, protocol.MaxViewersPerRoomLimit)
}
}
@@ -774,8 +781,9 @@ func TestRoomCreationCreatesPrivateRoomsWithOptionalPasswordsAtomically(t *testi
}
}
-func TestRoomCreationAllowsExplicitOpenCreationWithoutSiteAccess(t *testing.T) {
+func TestProductionAllowsRoomCreationWithoutSiteAccessButRequiresRoomOwnership(t *testing.T) {
configuration := testConfig(t)
+ configuration.Env = config.EnvironmentProduction
configuration.SiteAccessPassword = ""
server := start(t, Options{Config: configuration})
@@ -787,6 +795,14 @@ func TestRoomCreationAllowsExplicitOpenCreationWithoutSiteAccess(t *testing.T) {
if !strings.Contains(created.InviteURL, "#v=") {
t.Fatalf("inviteUrl = %q", created.InviteURL)
}
+ server.updateRoomAccess(accessRequest{
+ roomID: created.RoomID, hostToken: "wrong-token",
+ body: `{"action":"set-code-entry-policy","policy":"private"}`,
+ }).expectStatus(http.StatusNotFound)
+ server.updateRoomAccess(accessRequest{
+ roomID: created.RoomID, hostToken: created.HostToken,
+ body: `{"action":"set-code-entry-policy","policy":"private"}`,
+ }).expectStatus(http.StatusOK)
}
func TestRoomCreationAllocatesUniqueFourDigitCodesConcurrently(t *testing.T) {
@@ -840,7 +856,7 @@ func TestRoomReplacementReplacesAuthorityAndClosesOldMembership(t *testing.T) {
password: &password, preferredRoomID: "4321",
}).expectStatus(http.StatusCreated).room()
- store := server.Store()
+ store := server.store
host, err := store.ConnectParticipant(room.ConnectParticipantInput{
RoomID: original.RoomID, Role: protocol.RoleHost, Token: original.HostToken,
ClientID: "host-client", SessionID: "host-session",
@@ -999,7 +1015,7 @@ func TestRoomAccessManagesADormantRoomWithoutStartingSharing(t *testing.T) {
!strings.Contains(revoked.body, `"type":"viewer-grant-updated"`) {
t.Fatalf("revocation body = %s", revoked.body)
}
- if _, connected := server.Store().GetConnectedHost(created.RoomID); connected {
+ if _, connected := server.store.GetConnectedHost(created.RoomID); connected {
t.Fatal("managing access started a sharing session")
}
@@ -1153,7 +1169,7 @@ func TestRestoresStableRoomAuthorityAcrossAnApplicationRestart(t *testing.T) {
now.Store(30 * 24 * 60 * 60 * 1_000)
second := start(t, Options{Config: configuration, Now: now.Load})
- if size := second.Store().Size(); size != 1 {
+ if size := second.store.Size(); size != 1 {
t.Fatalf("restored room count = %d, want 1", size)
}
second.updateRoomAccess(accessRequest{
diff --git a/internal/server/app/json.go b/internal/server/app/json.go
index 736a28d0..1650e4f9 100644
--- a/internal/server/app/json.go
+++ b/internal/server/app/json.go
@@ -10,10 +10,7 @@ import (
"strings"
)
-// Request and response helpers ported from src/server/app.ts.
-
-// maxJSONRequestBytes is the readJsonBody(request, 1_024) budget every JSON
-// route shares.
+// maxJSONRequestBytes bounds the body every JSON route accepts.
const maxJSONRequestBytes = 1024
// errorBody is the { error } shape every failing route answers with.
@@ -26,13 +23,13 @@ type healthBody struct {
Status string `json:"status"`
}
-// siteAccessBody is siteAccessStatus(); the key order is the TS literal's.
+// siteAccessBody reports whether site access is required and already granted.
type siteAccessBody struct {
Required bool `json:"required"`
Authenticated bool `json:"authenticated"`
}
-// sendJSON always sets the exact Content-Length and the charset, as app.ts did.
+// sendJSON sets the exact Content-Length and the JSON charset.
// Encoding one of this package's own values cannot fail, so a marshal error is
// a programming error and reaches the recover wrapper.
func sendJSON(writer http.ResponseWriter, status int, body any) {
diff --git a/internal/server/app/routes.go b/internal/server/app/routes.go
index ba32ccb6..e6072c33 100644
--- a/internal/server/app/routes.go
+++ b/internal/server/app/routes.go
@@ -13,16 +13,15 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/signal"
)
-// The request router of src/server/app.ts. Route order is a contract (map
-// section 4.3, O34): the first match wins and the /api/ catch-all sits after
-// every concrete route.
+// The first matching route wins. The /api/ catch-all follows every concrete
+// route so unknown API requests cannot fall through to the frontend.
var (
roomReplacementPath = regexp.MustCompile(`^/api/rooms/([1-9][0-9]{3})/replacement$`)
roomAccessPath = regexp.MustCompile(`^/api/rooms/([1-9][0-9]{3})/access$`)
)
-// ServeHTTP is the createServer request listener of app.ts.
+// ServeHTTP dispatches requests and contains handler panics at the HTTP boundary.
func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
recorder := &responseRecorder{ResponseWriter: writer}
defer func() {
@@ -77,6 +76,7 @@ func (s *Server) route(
return
}
sendJSON(writer, http.StatusOK, protocol.RuntimeCapabilities{
+ Sfu: s.config.SFU != nil,
NatPrediction: s.config.NATPredictionEnabled,
})
return
diff --git a/internal/server/app/static.go b/internal/server/app/static.go
index 864e2574..9c17f117 100644
--- a/internal/server/app/static.go
+++ b/internal/server/app/static.go
@@ -10,11 +10,11 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
-// staticContentTypes freezes mrmime's answers for the extensions a Vite build
-// of this repo can emit. Go's mime.TypeByExtension overlays the Windows
+// staticContentTypes fixes the MIME types for this repository's Web assets.
+// Go's mime.TypeByExtension overlays the Windows
// registry or /etc/mime.types, so the served Content-Type would otherwise
// depend on the machine; with X-Content-Type-Options: nosniff a wrong type on a
-// font or a webmanifest is user visible. See evidence/runtime.md section 4.2.
+// font or a webmanifest is user visible.
var staticContentTypes = map[string]string{
".html": "text/html;charset=utf-8", // sirv appends ";charset=utf-8" with no space
".htm": "text/html;charset=utf-8",
@@ -42,20 +42,16 @@ var staticContentTypes = map[string]string{
".ico": "", // mrmime has no .ico, so sirv sends an EMPTY Content-Type
}
-// staticHandler reproduces `sirv(directory, { single: true, setHeaders })` as
-// src/server/app.ts used it, over an fs.FS instead of a directory walk.
-// notFound is the app's JSON 404, which sirv reached through its next()
-// callback. Verified against [email protected] in evidence/runtime.md section 4.4.
+// staticHandler serves embedded assets and falls back to index.html for SPA
+// routes. Missing files use the application's JSON 404 handler.
func staticHandler(assets fs.FS, notFound http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
- // sirv never inspects req.method: app.ts routes /healthz and /api/**
- // first, so everything else reaches the frontend handler as-is.
+ // API and health routes have already been handled by ServeHTTP.
cleaned := path.Clean("/" + request.URL.Path)
name := strings.TrimPrefix(cleaned, "/")
serve := func(candidate string) bool {
- // path.Clean already dropped any "..", and totalist never indexed a
- // dot-prefixed segment, so neither can be served.
+ // Clean traversal segments and exclude hidden assets before opening.
if candidate == "" || hasDotSegment(candidate) {
return false
}
@@ -72,15 +68,12 @@ func staticHandler(assets fs.FS, notFound http.Handler) http.Handler {
if !ok {
return false
}
- // app.ts setHeaders.
writer.Header().Set("X-Content-Type-Options", "nosniff")
writer.Header().Set("Referrer-Policy", "no-referrer")
// Set Content-Type explicitly, possibly to "", so ServeContent
// never sniffs; the empty name keeps it from guessing either.
writer.Header()["Content-Type"] = []string{staticContentTypes[strings.ToLower(path.Ext(candidate))]}
- // embed.FS reports a zero ModTime, so no Last-Modified is emitted
- // and no conditional request is honoured. sirv sends
- // Last-Modified but never answers 304 either; do not fabricate one.
+ // embed.FS reports a zero ModTime; do not fabricate Last-Modified.
http.ServeContent(writer, request, "", info.ModTime(), seeker)
return true
}
diff --git a/internal/server/config/config.go b/internal/server/config/config.go
index 4d33ab8d..36c6852d 100644
--- a/internal/server/config/config.go
+++ b/internal/server/config/config.go
@@ -1,7 +1,5 @@
-// Package config ports src/server/config.ts, src/server/local-config.ts and
-// src/server/ice.ts: the Hosted environment contract, the Client's local
-// composition, and the ICE configuration derived from either. The caller
-// supplies the environment as a map; loading opens no runtime resources.
+// Package config owns Hosted and App Local configuration and ICE discovery.
+// Callers provide configuration inputs; loading opens no runtime resources.
package config
import (
@@ -18,8 +16,8 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
-// Environment ports RuntimeEnvironment. DECISIONS D8 renames NODE_ENV to
-// PIIK_ENV and drops "test".
+// Environment selects development-only behavior. A stale unit file must fail
+// closed rather than fall back to development.
type Environment string
// The two accepted PIIK_ENV values.
@@ -28,7 +26,7 @@ const (
EnvironmentProduction Environment = "production"
)
-// Bounds and defaults from src/server/config.ts.
+// Bounds and defaults for Hosted configuration.
const (
minSiteAccessPasswordBytes = 8
maxSiteAccessPasswordBytes = 128
@@ -42,9 +40,8 @@ var visibleASCIIPattern = regexp.MustCompile(`^[\x21-\x7e]+$`)
const removedTurnReason = "ordinary ICE accepts STUN_URLS only"
-// removedEnvironmentVariables ports REMOVED_ENVIRONMENT_VARIABLES together with
-// the two names the TypeScript checked separately, and NODE_ENV (DECISIONS D8:
-// a stale unit file must not fail open). An empty reason takes the TURN default.
+// removedEnvironmentVariables names settings with no current equivalent. An
+// empty reason takes the TURN default.
// The order is the report order when several removed names are present.
var removedEnvironmentVariables = []struct{ name, reason string }{
{"TURN_URLS", ""},
@@ -74,17 +71,14 @@ type SFUConfig struct {
PublicIP string
}
-// Config ports ServerConfig. Fields the TypeScript left `undefined` are the
-// zero value here: an empty SiteAccessPassword means site access is open, an
-// empty RoomDatabasePath means memory mode, and a nil SFU means no SFU
-// fallback.
+// Config describes runtime configuration. Zero values mean open site
+// access, process-memory rooms, and no SFU fallback.
type Config struct {
Env Environment
Port int
ListenHost string
PublicBaseURL *url.URL
- // AllowedOrigins is a membership test only; Go map order is not observable
- // here (src/server/app.ts only ever calls `allowedOrigins.has(origin)`).
+ // AllowedOrigins is a membership test only; map order is not observable.
AllowedOrigins map[string]struct{}
SiteAccessPassword string
RoomDatabasePath string
@@ -96,15 +90,14 @@ type Config struct {
// discovery URLs do not make the Client an externally reachable STUN server.
STUNListenAddresses []string
NATPredictionEnabled bool
- // NATPredictionSTUNURLs is nil where the TypeScript left it `undefined`,
- // which IceConfig distinguishes from a configured empty list.
+ // NATPredictionSTUNURLs is nil when unset, which IceConfig distinguishes
+ // from a configured empty list.
NATPredictionSTUNURLs []string
}
-// Load ports loadConfig. env is the whole process environment: cmd passes
-// os.Environ() as a map, tests pass a literal. A key present with an empty
-// value is `""` in TypeScript too, so presence is the only distinction that
-// needs the two-value lookup.
+// Load validates the whole process environment. Presence, not emptiness,
+// distinguishes an explicit value from an unset value where that distinction
+// is part of the contract.
func Load(env map[string]string) (Config, error) {
for _, removed := range removedEnvironmentVariables {
if _, present := env[removed.name]; present {
@@ -132,8 +125,8 @@ func Load(env map[string]string) (Config, error) {
listenHost = "0.0.0.0"
}
- // TS: environment.PUBLIC_BASE_URL ?? `http://localhost:${port}` — only an
- // absent variable takes the default.
+ // Only an absent variable takes the default; an explicit empty value is
+ // invalid below.
rawPublicBaseURL, present := env["PUBLIC_BASE_URL"]
if !present {
rawPublicBaseURL = fmt.Sprintf("http://localhost:%d", port)
@@ -200,9 +193,6 @@ func Load(env map[string]string) (Config, error) {
return Config{}, fmt.Errorf("SITE_ACCESS_PASSWORD must contain %d to %d visible ASCII bytes",
minSiteAccessPasswordBytes, maxSiteAccessPasswordBytes)
}
- if environment == EnvironmentProduction && siteAccessPassword == "" {
- return Config{}, errors.New("SITE_ACCESS_PASSWORD is required in production")
- }
if environment == EnvironmentProduction && len(stunURLs) == 0 {
return Config{}, errors.New("STUN is required in production")
}
@@ -231,8 +221,6 @@ func Load(env map[string]string) (Config, error) {
// parseEnvironment ports parseEnvironment for PIIK_ENV.
func parseEnvironment(env map[string]string) (Environment, error) {
- // TS: value ?? "development" — a present empty value is not nullish and so
- // reaches the check below.
value, present := env["PIIK_ENV"]
if !present {
return EnvironmentDevelopment, nil
@@ -342,8 +330,7 @@ func parseURLList(value string, name string) ([]string, error) {
return list, nil
}
-// parseStunURLList ports parseStunUrlList. The TypeScript `maximum` parameter
-// was only ever the default.
+// parseStunURLList validates the bounded ordinary-STUN list.
func parseStunURLList(value string, name string) ([]string, error) {
values, err := parseURLList(value, name)
if err != nil {
@@ -380,8 +367,7 @@ func parseOrigins(value string, fallback string) (map[string]struct{}, error) {
return set, nil
}
-// toOrigin ports toOrigin. The TypeScript let an unparsable entry escape as a
-// raw TypeError from `new URL`; it fails startup here with a message instead.
+// toOrigin validates one allowed HTTP(S) origin.
func toOrigin(value string) (string, error) {
parsed, err := url.Parse(value)
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
@@ -405,8 +391,7 @@ func parseOriginURL(value, name, scheme, alternative string) (*url.URL, error) {
if parsed.Scheme != scheme && parsed.Scheme != alternative {
return nil, fmt.Errorf("%s must use %s or %s", name, scheme, alternative)
}
- // TS: url.username || url.password || url.pathname !== "/" || url.search ||
- // url.hash. WHATWG reports "/" for an empty path, which net/url leaves "".
+ // WHATWG reports "/" for an empty path, while net/url leaves it "".
if hasUserinfo(parsed) || (parsed.Path != "" && parsed.Path != "/") ||
parsed.RawQuery != "" || parsed.Fragment != "" {
return nil, fmt.Errorf(
diff --git a/internal/server/config/config_test.go b/internal/server/config/config_test.go
index 01864db1..7296ca29 100644
--- a/internal/server/config/config_test.go
+++ b/internal/server/config/config_test.go
@@ -98,6 +98,21 @@ func TestLoadDevelopmentDefaults(t *testing.T) {
}
}
+func TestLoadProductionAllowsAnUnsetOrEmptySiteAccessPassword(t *testing.T) {
+ for _, name := range []string{"unset", "empty"} {
+ t.Run(name, func(t *testing.T) {
+ environment := env(productionBase, map[string]string{"SITE_ACCESS_PASSWORD": ""})
+ if name == "unset" {
+ delete(environment, "SITE_ACCESS_PASSWORD")
+ }
+ configuration := mustLoad(t, environment)
+ if configuration.Env != EnvironmentProduction || configuration.SiteAccessPassword != "" {
+ t.Fatal("expected a production site without an access password")
+ }
+ })
+ }
+}
+
func TestLoadRoomStorage(t *testing.T) {
directory := t.TempDir()
t.Chdir(directory)
@@ -377,10 +392,6 @@ func TestLoadRejects(t *testing.T) {
"PIIK_ENV": "production", "PUBLIC_BASE_URL": "https://share.test",
"SITE_ACCESS_PASSWORD": "host-password-12",
}, "STUN is required in production"},
- {"production without a site password", map[string]string{
- "PIIK_ENV": "production", "PUBLIC_BASE_URL": "https://share.test",
- "STUN_URLS": "stun:stun.test:3478",
- }, "SITE_ACCESS_PASSWORD is required in production"},
// Site access password bounds (UTF-8 bytes).
{"site password too short", map[string]string{"SITE_ACCESS_PASSWORD": strings.Repeat("x", 7)},
diff --git a/internal/server/config/ice.go b/internal/server/config/ice.go
index 6e6441c4..b9fd700d 100644
--- a/internal/server/config/ice.go
+++ b/internal/server/config/ice.go
@@ -10,12 +10,11 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
-// Ported from src/server/ice.ts.
const natPredictionBasePort = 3478
-// natPredictionAuxiliaryPorts are NAT_PREDICTION_AUXILIARY_PORTS: the two
-// listeners a NAT-prediction STUN deployment binds beside the base port, whose
-// answers reveal the peer's port-allocation stride.
+// natPredictionAuxiliaryPorts are the two listeners a NAT-prediction STUN
+// deployment binds beside the base port; their answers reveal the peer's
+// port-allocation stride.
var natPredictionAuxiliaryPorts = [...]int{natPredictionBasePort + 1, natPredictionBasePort + 2}
func stunListenAddresses(host string, prediction bool) ([]string, error) {
@@ -40,8 +39,6 @@ func stunListenAddresses(host string, prediction bool) ([]string, error) {
// listeners derived from the first ordinary STUN authority on UDP 3478.
func NATPredictionStunURLs(stunURLs []string) []string {
for _, stunURL := range stunURLs {
- // TS: stunUrl.slice(stunUrl.indexOf(":") + 1) — a URL without a colon
- // keeps its whole text, which then fails to yield a host below.
authorityText := stunURL[strings.IndexByte(stunURL, ':')+1:]
authority, err := url.Parse("http://" + authorityText)
if err != nil || authority.Hostname() == "" {
@@ -77,8 +74,7 @@ func NATPredictionStunURLs(stunURLs []string) []string {
// IceConfig ports createIceConfig.
func IceConfig(c Config) protocol.IceConfig {
- // TS: options.natPredictionStunUrls ?? natPredictionStunUrls(stunUrls). A
- // configured empty list (Local without prediction) is kept as-is; only an
+ // A configured empty list (Local without prediction) is kept as-is; only an
// absent one is derived, so nil and empty differ here.
prediction := c.NATPredictionSTUNURLs
if prediction == nil {
diff --git a/internal/server/config/local.go b/internal/server/config/local.go
index c8784cd3..b8936577 100644
--- a/internal/server/config/local.go
+++ b/internal/server/config/local.go
@@ -12,18 +12,13 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
-// localPasswordPattern is VISIBLE_ASCII_PATTERN from local-config.ts. Because
-// it admits one byte per character the TypeScript's extra Buffer.byteLength
-// bounds are already implied by {8,128}.
+// localPasswordPattern admits 8..128 one-byte visible ASCII characters.
var localPasswordPattern = regexp.MustCompile(`^[\x21-\x7e]{8,128}$`)
-// LocalOptions ports LocalServerConfigOptions. loadLocalServerConfig, the
-// environment form, went away with the Node child process, so Local never
-// reads the process environment.
+// LocalOptions describes App-selected Local composition. It never reads the
+// process environment.
type LocalOptions struct {
- // Port of 0 selects the default 8787, as TypeScript's absent `port` did.
- // An explicit 0 is indistinguishable from absent here, where TypeScript
- // rejected it; 0 is not a usable port either way.
+ // Port 0 selects the default 8787.
Port int
PublicAddress string
PublicOrigin string
@@ -65,8 +60,7 @@ func Local(options LocalOptions) (Config, error) {
}
}
- // TS spreads `?? []`, so both lists are always arrays; keeping them non-nil
- // is what tells IceConfig that NAT prediction URLs were configured.
+ // Copy non-nil lists so configured-empty prediction does not derive auxiliary URLs.
stunURLs := append([]string{}, options.STUNURLs...)
natPredictionSTUNURLs := append([]string{}, options.NATPredictionSTUNURLs...)
if len(stunURLs)+len(natPredictionSTUNURLs) > protocol.MaxIceServerURLs ||
@@ -78,9 +72,7 @@ func Local(options LocalOptions) (Config, error) {
return Config{}, errors.New("Local STUN URLs are invalid")
}
- // TS builds these with a template string, so a non-default port is always
- // spelled out and port 80 would produce "http://host:80", which is not the
- // serialised origin. Kept as-is: Local never runs on 80.
+ // Local is loopback/LAN HTTP; its origin always spells out the port.
origin := func(host string) string { return fmt.Sprintf("http://%s:%d", host, port) }
publicBaseURL := &url.URL{Scheme: "http", Host: fmt.Sprintf("%s:%d", publicAddress, port), Path: "/"}
if options.PublicOrigin != "" {
diff --git a/internal/server/ordered/map.go b/internal/server/ordered/map.go
index 78033cce..2b8cb5bc 100644
--- a/internal/server/ordered/map.go
+++ b/internal/server/ordered/map.go
@@ -1,7 +1,6 @@
-// Package ordered provides an insertion-ordered map with the iteration
-// semantics of a JavaScript Map. The TypeScript server relied on those
-// semantics wherever it iterated a Map or Set: wire-visible participant order,
-// candidate ordering, round-robin state, and delete-during-iteration loops.
+// Package ordered provides an insertion-ordered map with live iteration.
+// Wire-visible participant order, candidate ordering, round-robin state and
+// deletion during iteration depend on those semantics.
package ordered
import "iter"
@@ -13,9 +12,9 @@ type entry[K comparable, V any] struct {
}
// Map keeps keys in first-insertion order. Set on an existing key keeps its
-// position; MoveToBack reproduces the JavaScript delete-then-set idiom.
-// Iteration is live: an entry deleted before it is visited is skipped and an
-// entry appended during iteration is visited, exactly like a JavaScript Map.
+// position; MoveToBack removes and reinserts it at the end. Iteration is live:
+// an entry deleted before it is visited is skipped and an entry appended
+// during iteration is visited.
// The zero value is ready to use.
type Map[K comparable, V any] struct {
entries []entry[K, V]
diff --git a/internal/server/protocol/constants.go b/internal/server/protocol/constants.go
index 2ec3064b..d70fded9 100644
--- a/internal/server/protocol/constants.go
+++ b/internal/server/protocol/constants.go
@@ -1,14 +1,13 @@
-// Package protocol is the Go owner of the Piik wire contract. It mirrors
-// src/shared/protocol.ts (zod schemas) plus the four shared scalar helpers
-// (media-copy-accounting.ts, nat-candidate.ts, packet-loss.ts,
-// video-codec-evidence.ts). The package performs no I/O and imports nothing
-// from other internal packages.
+// Package protocol is the Go owner of the Piik wire contract. Its shared
+// fixtures and scalar helpers are kept semantics-compatible with the Browser
+// implementation. The package performs no I/O and imports nothing from other
+// internal packages.
package protocol
// MaxSafeInteger is JavaScript's Number.MAX_SAFE_INTEGER.
const MaxSafeInteger = 9007199254740991
-// Limits and identifiers mirrored from src/shared/protocol.ts.
+// Limits and identifiers in the Piik wire contract.
const (
MaxViewersPerRoomLimit = 20
MaxParticipantsPerRoomLimit = MaxViewersPerRoomLimit + 1
@@ -27,7 +26,7 @@ const (
MaxDisplayNameCodePoints = 24
DefaultViewerDisplayName = "观众"
- DefaultHostDisplayNamePrefix = "分享者"
+ DefaultHostDisplayNamePrefix = "房主"
MinViewerPasswordLength = 1
MaxViewerPasswordLength = 64
diff --git a/internal/server/protocol/contract_test.go b/internal/server/protocol/contract_test.go
index e3864696..a07d5aab 100644
--- a/internal/server/protocol/contract_test.go
+++ b/internal/server/protocol/contract_test.go
@@ -8,6 +8,33 @@ import (
"testing"
)
+func TestRuntimeCapabilities(t *testing.T) {
+ for _, test := range []struct {
+ data string
+ want RuntimeCapabilities
+ }{
+ {`{}`, RuntimeCapabilities{}},
+ {`{"sfu":true,"extra":{"enabled":true}}`, RuntimeCapabilities{Sfu: true}},
+ {`{"natPrediction":true,"SFU":true}`, RuntimeCapabilities{NatPrediction: true}},
+ {`{"sfu":true,"natPrediction":true}`, RuntimeCapabilities{Sfu: true, NatPrediction: true}},
+ {`{"sfu":"ignored duplicate","sfu":true}`, RuntimeCapabilities{Sfu: true}},
+ } {
+ got := RuntimeCapabilities{Sfu: true, NatPrediction: true}
+ if err := json.Unmarshal([]byte(test.data), &got); err != nil || got != test.want {
+ t.Errorf("decode %s = %+v, %v; want %+v", test.data, got, err, test.want)
+ }
+ }
+ for _, data := range []string{
+ `null`, `[]`, `true`, `{"sfu":null}`, `{"sfu":"true"}`,
+ `{"natPrediction":null}`, `{"natPrediction":1}`,
+ } {
+ var got RuntimeCapabilities
+ if err := json.Unmarshal([]byte(data), &got); err == nil {
+ t.Errorf("expected %s to be rejected", data)
+ }
+ }
+}
+
// member is one JSON object key with its raw encoded value, so the tests can
// reproduce the exact wire shapes from tests/protocol.test.ts (including key
// presence, which a Go map cannot express).
diff --git a/internal/server/protocol/server.go b/internal/server/protocol/server.go
index 9804e528..2d0d3b46 100644
--- a/internal/server/protocol/server.go
+++ b/internal/server/protocol/server.go
@@ -11,10 +11,7 @@ type ServerMessage interface {
isServerMessage()
}
-// AuthenticatedHostMessage is the host member of authenticatedMessageSchema.
-// The field order is the emission order of the object literal in
-// src/server/signaling.ts (`role` and `viewerPasswordEnabled` are appended
-// after the shared base spread).
+// AuthenticatedHostMessage returns the Host's current room and transport facts.
type AuthenticatedHostMessage struct {
Type string `json:"type"`
Protocol string `json:"protocol"`
diff --git a/internal/server/protocol/types.go b/internal/server/protocol/types.go
index 30e00f14..d51b8506 100644
--- a/internal/server/protocol/types.go
+++ b/internal/server/protocol/types.go
@@ -168,18 +168,33 @@ func (v *RoutePolicy) UnmarshalJSON(data []byte) error {
// RuntimeCapabilities mirrors runtimeCapabilitiesSchema.
type RuntimeCapabilities struct {
+ Sfu bool `json:"sfu"`
NatPrediction bool `json:"natPrediction"`
}
// UnmarshalJSON implements json.Unmarshaler.
func (v *RuntimeCapabilities) UnmarshalJSON(data []byte) error {
*v = RuntimeCapabilities{}
- type raw RuntimeCapabilities
- present, err := decodeObject(data, (*raw)(v))
- if err != nil {
+ var present fields
+ if err := json.Unmarshal(data, &present); err != nil {
+ return err
+ }
+ if present == nil {
+ return errors.New("runtime capabilities must be an object")
+ }
+ if err := present.optional("sfu", "natPrediction"); err != nil {
return err
}
- return present.require("natPrediction")
+ for key, target := range map[string]*bool{
+ "sfu": &v.Sfu, "natPrediction": &v.NatPrediction,
+ } {
+ if value, ok := present[key]; ok {
+ if err := json.Unmarshal(value, target); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
}
// ---------------------------------------------------------------------------
diff --git a/internal/server/room/doc.go b/internal/server/room/doc.go
index b5a62142..31d84eed 100644
--- a/internal/server/room/doc.go
+++ b/internal/server/room/doc.go
@@ -1,87 +1,27 @@
-// Package room ports the room authority: src/server/room-store.ts (rooms,
-// participants, room codes, viewer credentials, the four-digit code pool) and
-// src/server/room-database.ts (the SQLite stable authority). Authority mutations
-// write SQLite before memory and return the write error unchanged. Participants
-// remain process-only.
+// Package room owns room codes, Host/Viewer credentials, participant membership
+// and persistent room authority. Durable mutations write SQLite before memory;
+// participants and live connections remain process-only.
//
-// # Locking
+// # Locking And Password Work
//
-// Store has no mutex. The signaling layer's single global lock guards it, which
-// is what Node's single thread did: nothing interleaved except at an await. The
-// caller must hold that lock for every method below except the two derive
-// methods, which run the password KDF and must NOT be called under the lock.
+// Store has no mutex. The caller holds the signaling server's global lock for
+// store operations, except password derivation, which must run unlocked.
//
-// The TypeScript methods that await the KDF are split into a locked "begin",
-// an unlocked derive, and a locked "commit" so that the guards the TypeScript
-// re-ran after its await are re-run here after the relock, in the same order.
-// The commit takes the derive result as (material, derived error) because the
-// TypeScript inspected the gate outcome (busy/cancelled) only after re-reading
-// the room: forward both values unchanged and the commit reproduces the order.
+// Password changes use a locked begin, unlocked derive, then locked commit.
+// Pass both material and error from DeriveViewerPasswordMaterial unchanged;
+// the commit revalidates room ownership/capacity before mapping gate outcomes.
+// Viewer login instead returns derivation errors before committing credentials.
//
-// POST /api/rooms (createRoom):
+// A derivation admission predicate runs outside the signaling lock and must
+// acquire that lock when consulting room/session state. ConnectViewerWithPassword
+// also calls its predicate during the locked commit, so that call needs the
+// already-locked form. Both must express the same current-session condition.
//
-// mu.Lock()
-// if err := store.BeginCreateRoom(); err != nil { mu.Unlock(); return err }
-// var material []byte
-// var derived error
-// if password != "" {
-// mu.Unlock()
-// material, derived = store.DeriveViewerPasswordMaterial(password, nil)
-// mu.Lock()
-// }
-// created, err := store.CreateRoom(policy, material, derived, preferredRoomID)
-// mu.Unlock()
+// HostManagedRoom and ViewerPasswordChallenge return a room reference for
+// identity checks after unlocked work. A removed room is never reused as its
+// replacement; a stale reference cannot authorize mutation of the new room.
+// Do not inspect a retained room's mutable state without the lock.
//
-// replaceRoom and set-viewer-password (the mayStart closure is the TypeScript
-// `rooms.get(roomId) === current && verifyDigest(hostToken, ...)`; it runs on
-// the derive goroutine, so it takes the lock itself):
-//
-// mu.Lock()
-// current, err := store.HostManagedRoom(roomID, hostToken) // may fail INVALID_TOKEN
-// if err != nil { mu.Unlock(); return err }
-// var material []byte
-// var derived error
-// if password != "" {
-// mu.Unlock()
-// material, derived = store.DeriveViewerPasswordMaterial(password, func() bool {
-// mu.Lock()
-// defer mu.Unlock()
-// return store.HostStillOwnsRoom(roomID, hostToken, current)
-// })
-// mu.Lock()
-// }
-// replaced, err := store.ReplaceRoom(roomID, hostToken, policy, material, derived, current)
-// mu.Unlock()
-//
-// Viewer password login (signaling authenticate). mayConnect is the TypeScript
-// closure `!closing && socketStates.get(socket) === state && !state.revoked &&
-// !state.authenticated && socket.readyState === OPEN`. It is evaluated twice,
-// once on the derive goroutine (gate admission) and once under the lock inside
-// the commit, so the caller needs both a locking and a non-locking form of the
-// same predicate:
-//
-// mu.Lock()
-// salt, expected, ref, err := store.ViewerPasswordChallenge(input.RoomID)
-// mu.Unlock()
-// if err != nil { return err } // not initialized
-// derivedKey, err := store.DeriveViewerPassword(input.Password, salt, func() bool {
-// mu.Lock()
-// defer mu.Unlock()
-// return mayConnectLocked()
-// })
-// mu.Lock()
-// if err != nil { mu.Unlock(); return err } // ROOM_BUSY or INVALID_TOKEN
-// participant, err := store.ConnectViewerWithPassword(
-// input, derivedKey, expected, ref, mayConnectLocked)
-// mu.Unlock()
-//
-// The room reference handed back by HostManagedRoom and ViewerPasswordChallenge
-// is only ever compared for pointer identity, reproducing the TypeScript
-// `currentRoom !== room` checks that detect a room replaced while the KDF ran.
-// Holding it across the unlock is safe: an abandoned room is dropped from the
-// map, never mutated into another room.
-//
-// Options.Random is called both under the caller's lock and from the derive
-// goroutine (the 16-byte salt), so it must be safe for concurrent use;
-// crypto/rand is.
+// Options.Random is used under the caller's lock and by derivation goroutines,
+// so it must be concurrency-safe; crypto/rand satisfies this requirement.
package room
diff --git a/internal/server/room/password.go b/internal/server/room/password.go
index db4d6ad0..17841d26 100644
--- a/internal/server/room/password.go
+++ b/internal/server/room/password.go
@@ -19,8 +19,7 @@ const (
viewerPasswordScryptR = 8
viewerPasswordScryptP = 1
- // AsyncGate bounds from src/server/room-store.ts (DECISIONS D11): scrypt at
- // N=16384 costs ~16 MiB and tens of milliseconds, so two concurrent
+ // Scrypt at N=16384 costs ~16 MiB per derivation, so two concurrent
// derivations bound the memory and CPU a room burst can claim, and sixteen
// waiters bound the queue before the next caller is told ROOM_BUSY.
gateActiveLimit = 2
diff --git a/internal/server/route/api.go b/internal/server/route/api.go
index 3681dbf1..c6a0199c 100644
--- a/internal/server/route/api.go
+++ b/internal/server/route/api.go
@@ -229,20 +229,6 @@ type CommittedEdge struct {
Resource *Resource
}
-// committedEdgeSeed is CommittedEdge without the session fields the
-// controller derives at hydrateEdge. TS: CommittedEdgeSeed, which like
-// hydrateEdge only ever had test callers.
-type committedEdgeSeed struct {
- Kind UpstreamKind
- ParentPeerID string
- PublicationGeneration string
- Transport Transport
- ConnectionID string
- Usable bool
- PhysicalActive bool
- Resource *Resource
-}
-
// HostPublication is the single live SFU ingress. TS: HostPublication.
type HostPublication struct {
Generation string
@@ -288,7 +274,6 @@ type OperationSnapshot struct {
// RouteSnapshot is the committed graph as the router reads it.
// UpstreamByViewer is a fresh insertion-ordered copy (child peerId -> edge);
// HostPublication is a shallow copy or nil; Operation is nil when idle.
-// TS: RouteSnapshot.
type RouteSnapshot struct {
Revision int64
Paused bool
@@ -323,7 +308,6 @@ type SettleResult struct {
type SenderQualityEvidenceResult = SettleResult
// BeginResult is the outcome of the cursor-guarded candidate calls.
-// TS: BeginResult.
type BeginResult struct {
Accepted bool
Operation *OperationSnapshot
@@ -351,7 +335,6 @@ type EdgeGuard struct {
}
// ParentEdgeGuard identifies a direct edge from the parent's side.
-// TS: the inline input of invalidateDirectEdgeFromParent.
type ParentEdgeGuard struct {
ParentPeerID string
ParentSessionID string
@@ -410,7 +393,6 @@ type BeginInput struct {
}
// CandidateProof carries the Viewer's one-shot relative quality approval.
-// TS: the proof parameter of candidateReady ({ relativeQualityApproved? }).
type CandidateProof struct {
RelativeQualityApproved bool
}
@@ -425,7 +407,6 @@ type QualityUpstream struct {
// RouteQualityEvidenceInput is one receiver-side quality window. Only
// FramesDecodedDelta, FreezeCountDelta, FreezeDurationMsDelta,
// PauseCountDelta and PauseDurationMsDelta of Metrics are read.
-// TS: RouteQualityEvidenceInput.
type RouteQualityEvidenceInput struct {
ChildPeerID string
ChildSessionID string
@@ -440,7 +421,6 @@ type RouteQualityEvidenceInput struct {
// SenderQualityEvidenceInput is one sender-side health sample from a parent
// about one child. SenderIdentity and SampleTimestampMs are nullable.
-// TS: SenderQualityEvidenceInput.
type SenderQualityEvidenceInput struct {
ParentPeerID string
ParentSessionID string
@@ -454,7 +434,6 @@ type SenderQualityEvidenceInput struct {
}
// SfuPublisherQualityEvidenceInput is one Host->SFU ingress health sample.
-// TS: SfuPublisherQualityEvidenceInput.
type SfuPublisherQualityEvidenceInput struct {
HostPeerID string
HostSessionID string
@@ -468,8 +447,11 @@ type SfuPublisherQualityEvidenceInput struct {
// Options configures a Controller. DebugRoomID empty disables the sanitised
// route debug events. TS: ControllerOptions.
type Options struct {
- HostPeerID string
- DebugRoomID string
+ HostPeerID string
+ DebugRoomID string
+ // DebugLog receives sanitized route events. nil disables them; the effect
+ // layer owns environment, logger and retention policy.
+ DebugLog func(string, ...any)
EndpointMediaCopyCapacity int
OperationTimeoutMs int64
SfuEnabled bool
@@ -487,6 +469,7 @@ type Controller struct {
// options are copied once and never change.
hostPeerID string
debugRoomID string
+ debugLog func(string, ...any)
endpointMediaCopyCapacity int
operationTimeoutMs int64
sfuEnabled bool
diff --git a/internal/server/route/controller.go b/internal/server/route/controller.go
index cc647a66..f164b316 100644
--- a/internal/server/route/controller.go
+++ b/internal/server/route/controller.go
@@ -275,6 +275,7 @@ func New(options Options) *Controller {
c := &Controller{
hostPeerID: options.HostPeerID,
debugRoomID: options.DebugRoomID,
+ debugLog: options.DebugLog,
endpointMediaCopyCapacity: options.EndpointMediaCopyCapacity,
operationTimeoutMs: options.OperationTimeoutMs,
sfuEnabled: options.SfuEnabled,
@@ -642,68 +643,6 @@ func (c *Controller) TouchExternalFacts() {
c.touchFacts()
}
-// hydrateEdge installs a committed edge for a connected viewer while no
-// operation is active, without changing revision or fact version. Panics
-// on an active operation, a non-viewer child or a child without a session.
-func (c *Controller) hydrateEdge(childPeerID string, edge committedEdgeSeed) {
- if c.operation != nil {
- panic(errors.New("Cannot hydrate while an operation is active"))
- }
- c.assertViewer(childPeerID)
- child, _ := c.participants.Get(childPeerID)
- childSessionID := child.sessionID
- if childSessionID == "" {
- panic(errors.New("Route child has no current session"))
- }
- committed := &CommittedEdge{
- Kind: edge.Kind,
- ChildSessionID: childSessionID,
- ParentPeerID: edge.ParentPeerID,
- PublicationGeneration: edge.PublicationGeneration,
- Transport: edge.Transport,
- ConnectionID: edge.ConnectionID,
- Usable: edge.Usable,
- PhysicalActive: edge.PhysicalActive,
- Resource: edge.Resource,
- }
- if edge.Kind == UpstreamPeer {
- // TS 750: `this.participants.get(edge.parentPeerId)?.sessionId ?? ""`.
- if parent, ok := c.participants.Get(edge.ParentPeerID); ok {
- committed.ParentSessionID = parent.sessionID
- }
- }
- // Map.set keeps the position of an existing child (§4.2 #15).
- c.upstreamByViewer.Set(childPeerID, committed)
- c.requireSenderQualityBaseline(childPeerID, false)
- c.assertGraph()
-}
-
-// hydrateHostPublication installs a usable, physically active publication
-// while no operation is active; connectionID empty selects the TS default
-// "publication:<generation>". Panics on an active operation or a Host
-// without a session.
-func (c *Controller) hydrateHostPublication(generation string, resource *Resource, connectionID string) {
- if c.operation != nil {
- panic(errors.New("Cannot hydrate while an operation is active"))
- }
- host, _ := c.participants.Get(c.hostPeerID)
- if host == nil || host.sessionID == "" {
- panic(errors.New("Route Host has no current session"))
- }
- if connectionID == "" {
- connectionID = "publication:" + generation
- }
- c.hostPublication = &HostPublication{
- Generation: generation,
- HostSessionID: host.sessionID,
- ConnectionID: connectionID,
- Usable: true,
- PhysicalActive: true,
- Resource: resource,
- }
- c.assertGraph()
-}
-
// InvalidateEdge marks the exactly identified edge unusable and records an
// "edge-unavailable" demand; true when the guard matched (idempotent).
func (c *Controller) InvalidateEdge(guard EdgeGuard, nowMs *int64) bool {
diff --git a/internal/server/route/debug.go b/internal/server/route/debug.go
index 7f6e32b1..ed3c7943 100644
--- a/internal/server/route/debug.go
+++ b/internal/server/route/debug.go
@@ -1,40 +1,26 @@
package route
import (
- "context"
- "log/slog"
- "os"
"strconv"
- "strings"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
-func debugEnabled() bool {
- return routeDebugEnabled(os.Getenv("PIIK_DEBUG")) ||
- slog.Default().Enabled(context.Background(), slog.LevelDebug)
-}
-
-func routeDebugEnabled(value string) bool {
- for _, section := range strings.Split(value, ",") {
- if strings.TrimSpace(section) == "route" {
- return true
- }
- }
- return false
-}
-
// debugCandidate is the `{route, transition}` item of "operation-started".
type debugCandidate struct {
Route string
Transition TransitionKind
}
+func (c *Controller) debugEnabled() bool {
+ return c.debugLog != nil && c.debugRoomID != ""
+}
+
// debug emits one sanitized event with a diagnostic room ID and current facts.
// Never pass raw peer IDs, session IDs or connection IDs; use debugPeer and
-// debugTuple. The environment or diagnostic logger enables these Info events.
+// debugTuple. The effect layer injects the sink and owns its enabling policy.
func (c *Controller) debug(event string, details ...any) {
- if !debugEnabled() || c.debugRoomID == "" {
+ if !c.debugEnabled() {
return
}
args := make([]any, 0, 8+len(details))
@@ -44,7 +30,7 @@ func (c *Controller) debug(event string, details ...any) {
"revision", c.revision,
"factVersion", c.factVersion)
args = append(args, details...)
- slog.Info("piik-route", args...)
+ c.debugLog("piik-route", args...)
}
// debugPeer ports 4895: "host", "viewer-<joinOrder>" or "viewer-unknown".
diff --git a/internal/server/route/debug_test.go b/internal/server/route/debug_test.go
index ebeded63..fca92ed2 100644
--- a/internal/server/route/debug_test.go
+++ b/internal/server/route/debug_test.go
@@ -1,24 +1,26 @@
package route
-import (
- "io"
- "log/slog"
- "testing"
-)
+import "testing"
-func TestDebugUsesCurrentEnvironmentAndLogger(t *testing.T) {
- previous := slog.Default()
- t.Cleanup(func() { slog.SetDefault(previous) })
- slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
- for value, want := range map[string]bool{"": false, "client": false, "route": true, "client, route": true} {
- t.Setenv("PIIK_DEBUG", value)
- if got := debugEnabled(); got != want {
- t.Fatalf("debugEnabled with %q = %v, want %v", value, got, want)
+func TestControllerDebugRequiresInjectedSinkAndRoom(t *testing.T) {
+ var kinds, events []string
+ sink := func(kind string, args ...any) {
+ kinds = append(kinds, kind)
+ if len(args) >= 2 {
+ if event, ok := args[1].(string); ok {
+ events = append(events, event)
+ }
}
}
- t.Setenv("PIIK_DEBUG", "")
- slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelDebug})))
- if !debugEnabled() {
- t.Fatal("the active diagnostic logger did not enable route events")
+ c := &Controller{debugRoomID: "1234", debugLog: sink}
+ c.debug("operation-started", "child", "viewer-1")
+ if len(kinds) != 1 || kinds[0] != "piik-route" ||
+ len(events) != 1 || events[0] != "operation-started" {
+ t.Fatalf("injected sink received kinds=%v events=%v", kinds, events)
+ }
+ (&Controller{debugRoomID: "1234"}).debug("no-sink")
+ (&Controller{debugLog: sink}).debug("no-room")
+ if len(kinds) != 1 {
+ t.Fatalf("disabled controller emitted %v", kinds)
}
}
diff --git a/internal/server/route/doc.go b/internal/server/route/doc.go
index 2b450e93..876b94f0 100644
--- a/internal/server/route/doc.go
+++ b/internal/server/route/doc.go
@@ -1,15 +1,14 @@
-// Package route ports src/server/room-route-controller.ts: the pure,
-// synchronous decision logic that owns one room's media route graph, its
+// Package route owns synchronous decisions over one room's media route graph, its
// single in-flight route operation, the quality/opportunity ledgers and the
// privacy-safe diagnostic snapshot.
//
-// The controller performs no I/O, starts no timers and never locks. Every
-// method is a state transition over the nowMs the caller passes in; the
+// The controller starts no timers, never locks and returns resource effects
+// to its caller. Optional diagnostics invoke the injected sink synchronously.
+// Every method is a state transition over the nowMs the caller passes in; the
// caller (signal.Server) holds the global mutex around every call and
// releases exactly the *Resource values a method returns, in order.
//
-// Resources are compared by pointer identity, mirroring the JS Set semantics
-// of the TypeScript source. Programming-error throws in the source
-// (assertGraph, bad reservations, bad options) become panics with the same
-// messages.
+// Resources are compared by pointer identity. Invalid graphs, reservations or
+// constructor options are programming errors and panic; ordinary unavailable
+// routes remain decision outcomes.
package route
diff --git a/internal/server/route/harness_test.go b/internal/server/route/harness_test.go
index 746cd8af..82261b1f 100644
--- a/internal/server/route/harness_test.go
+++ b/internal/server/route/harness_test.go
@@ -212,6 +212,69 @@ func sfuCreateOverlap(edge, publication, overlap string) CandidateReservation {
return reservation
}
+type committedEdgeSeed struct {
+ Kind UpstreamKind
+ ParentPeerID string
+ PublicationGeneration string
+ Transport Transport
+ ConnectionID string
+ Usable bool
+ PhysicalActive bool
+ Resource *Resource
+}
+
+func (c *Controller) hydrateEdge(childPeerID string, edge committedEdgeSeed) {
+ if c.operation != nil {
+ panic("Cannot hydrate while an operation is active")
+ }
+ c.assertViewer(childPeerID)
+ child, _ := c.participants.Get(childPeerID)
+ if child.sessionID == "" {
+ panic("Route child has no current session")
+ }
+ committed := &CommittedEdge{
+ Kind: edge.Kind,
+ ChildSessionID: child.sessionID,
+ ParentPeerID: edge.ParentPeerID,
+ PublicationGeneration: edge.PublicationGeneration,
+ Transport: edge.Transport,
+ ConnectionID: edge.ConnectionID,
+ Usable: edge.Usable,
+ PhysicalActive: edge.PhysicalActive,
+ Resource: edge.Resource,
+ }
+ if edge.Kind == UpstreamPeer {
+ if parent, ok := c.participants.Get(edge.ParentPeerID); ok {
+ committed.ParentSessionID = parent.sessionID
+ }
+ }
+ c.upstreamByViewer.Set(childPeerID, committed)
+ c.requireSenderQualityBaseline(childPeerID, false)
+ c.assertGraph()
+}
+
+func (c *Controller) hydrateHostPublication(generation string, resource *Resource, connectionID string) {
+ if c.operation != nil {
+ panic("Cannot hydrate while an operation is active")
+ }
+ host, _ := c.participants.Get(c.hostPeerID)
+ if host == nil || host.sessionID == "" {
+ panic("Route Host has no current session")
+ }
+ if connectionID == "" {
+ connectionID = "publication:" + generation
+ }
+ c.hostPublication = &HostPublication{
+ Generation: generation,
+ HostSessionID: host.sessionID,
+ ConnectionID: connectionID,
+ Usable: true,
+ PhysicalActive: true,
+ Resource: resource,
+ }
+ c.assertGraph()
+}
+
func peerEdge(parentPeerID, connectionID string) committedEdgeSeed {
return committedEdgeSeed{
Kind: UpstreamPeer,
diff --git a/internal/server/route/operation.go b/internal/server/route/operation.go
index 954f5e12..ea65278f 100644
--- a/internal/server/route/operation.go
+++ b/internal/server/route/operation.go
@@ -214,7 +214,7 @@ func (c *Controller) Reconcile(nowMs int64) ReconcileResult {
deferredParentPeerIDs: []string{},
qualitySource: qualitySource,
}
- if debugEnabled() {
+ if c.debugEnabled() {
routes := make([]debugCandidate, 0, len(candidates))
for _, candidate := range candidates {
routes = append(routes, debugCandidate{Route: c.debugTuple(candidate.Tuple), Transition: candidate.EndpointTransition.Kind})
@@ -318,7 +318,7 @@ func (c *Controller) BeginCurrentCandidate(input BeginInput) BeginResult {
mediaReady: false,
connectionAttempt: c.startCandidateOpportunity(op, *plan),
}
- if debugEnabled() {
+ if c.debugEnabled() {
details := []any{
"child", c.debugPeer(op.childPeerID),
"candidate", c.debugTuple(tuple),
@@ -689,7 +689,7 @@ func (c *Controller) CandidateFailed(guard CandidateGuard, nowMs int64) SettleRe
// OperationExpired applies head-start and deadline expiry at nowMs;
// Accepted reports whether something expired.
func (c *Controller) OperationExpired(nowMs int64) SettleResult {
- if op := c.operation; op != nil && debugEnabled() {
+ if op := c.operation; op != nil && c.debugEnabled() {
current := op.current
noProgress := current != nil &&
current.tuple.Kind == UpstreamPeer &&
diff --git a/internal/server/signal/presence.go b/internal/server/signal/presence.go
index 8e3a955c..74abea04 100644
--- a/internal/server/signal/presence.go
+++ b/internal/server/signal/presence.go
@@ -1,10 +1,7 @@
package signal
-// Viewer presence, host status, disconnect handling and room termination of
-// src/server/signaling.ts (sendViewerPresence 1594, broadcastHostStatus
-// 1683, handleDisconnect 1397, stopSharing 1466, closeRoom,
-// revokeGrantViewers 1016, closeRevokedViewerSession 1697 and the
-// viewer-keyed map helpers). Every function here runs with mu held.
+// Viewer presence, Host status, disconnect handling and room termination run
+// with Server.mu held, so each effect observes the current room membership.
import (
"fmt"
diff --git a/internal/server/signal/router.go b/internal/server/signal/router.go
index 78598a9e..c869f84f 100644
--- a/internal/server/signal/router.go
+++ b/internal/server/signal/router.go
@@ -1,13 +1,10 @@
package signal
-// Ported from src/server/hybrid-media-router.ts (baseline b20fd88).
-//
// The router owns no lock. signal.Server.mu (routerOptions.mu) is held by the
// caller of every method except close, hooks are called with it held, and the
// goroutines the router starts (pump driver, media prepares, drains and timer
-// callbacks) take it themselves. Every I/O window is an
-// unlock / I/O / lock window followed by exactly the guard the TS code ran
-// after that await (map C:/tmp/piik-go/maps/effect-layer.md, section 2.2).
+// callbacks) take it themselves. After unlocked I/O, revalidate the owning
+// room, operation and resource before committing effects under the lock.
import (
"context"
@@ -46,6 +43,15 @@ func routeDebugFlag(value string) bool {
return false
}
+// routeDebugSink is the injected route-diagnostic sink; nil disables route
+// events. The signaling effect layer owns environment and logger policy.
+func routeDebugSink() func(string, ...any) {
+ if !routeDebugEnabled() {
+ return nil
+ }
+ return slog.Info
+}
+
// sfuFallback is SfuFallbackOptions. A zero timeout means the TS default.
type sfuFallback struct {
media sfu.Runtime
@@ -299,7 +305,6 @@ func (r *router) completeAuthentication(participant authenticatedRouteParticipan
return
}
r.broadcastActive(participant.roomID, rm)
- // TS: void this.sendFreshSfuConfig(participant).catch(() => undefined)
r.sendFreshSfuConfig(participant)
r.requestPump(participant.roomID)
}
@@ -1002,6 +1007,7 @@ func (r *router) createController(roomID string, rm *roomRuntime, host authentic
rm.controller = route.New(route.Options{
HostPeerID: host.peerID,
DebugRoomID: roomID,
+ DebugLog: routeDebugSink(),
EndpointMediaCopyCapacity: r.capacity,
OperationTimeoutMs: operationTimeoutMs,
SfuEnabled: r.sfu != nil && !(routePolicy != nil && routePolicy.PeerOnly),
diff --git a/internal/server/signal/router_pump.go b/internal/server/signal/router_pump.go
index 89e249a2..73c086c9 100644
--- a/internal/server/signal/router_pump.go
+++ b/internal/server/signal/router_pump.go
@@ -279,7 +279,6 @@ func (r *router) selectCandidate(
return pumpCandidate{}, true
}
if operation.Cursor < 0 || operation.Cursor >= len(operation.Candidates) {
- // TS: `if (!plan)` -- note: no clearDeadline here.
r.resourceWaiters.Delete(roomID)
return pumpCandidate{}, true
}
diff --git a/internal/server/signal/router_sfu.go b/internal/server/signal/router_sfu.go
index f8593ec0..bc13fd4c 100644
--- a/internal/server/signal/router_sfu.go
+++ b/internal/server/signal/router_sfu.go
@@ -185,7 +185,6 @@ func (r *router) scheduleSfuDrain(kind drainKind, fence sfu.SubscriptionFence) {
r.sfuDrainTasks.Set(key, task)
}
if task.operation == nil {
- // TS: void this.runSfuDrain(key, task).catch(() => undefined)
r.runSfuDrain(key, task)
}
}
diff --git a/internal/server/signal/server.go b/internal/server/signal/server.go
index 5e6ab765..10ccb074 100644
--- a/internal/server/signal/server.go
+++ b/internal/server/signal/server.go
@@ -1,17 +1,14 @@
-// Package signal ports src/server/signaling.ts (SignalingServer) and
-// src/server/hybrid-media-router.ts (HybridMediaRouter) from baseline
-// b20fd88. server.go is the signaling server's lifecycle, upgrade ladder,
-// HTTP-facing room mutations and message dispatch; session.go the
-// per-connection state; presence.go the viewer presence, host status and
-// room termination paths; router*.go the media router.
+// Package signal owns authenticated signaling and room/media effects. It
+// serializes session and presence changes, HTTP-facing room mutations, and
+// execution of the synchronous route controller's decisions.
//
// # Locking
//
// Server.mu is the one lock of the effect layer: it guards every field of
// the server and the router, the room.Store and the route controllers. Every
// handler, timer callback and goroutine takes it; it is released only around
-// I/O (the password KDF and media transport), after which exactly the guard
-// the TypeScript ran after its await is re-run. Router methods and hooks are
+// I/O (the password KDF and media transport), after which current session,
+// room and operation identities must be revalidated. Router methods and hooks are
// called with mu held and never lock.
package signal
@@ -35,9 +32,8 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/sfu"
)
-// Ceilings and option defaults ported from src/server/signaling.ts. The first
-// five are its module constants; the last four are the `??` defaults of
-// SignalingOptions.
+// Connection admission, queue and timeout bounds limit the signaling resources
+// a stalled or unauthenticated peer can retain.
const (
// maxBufferedSignalBytes is MAX_BUFFERED_SIGNAL_BYTES: once a connection's
// unsent queue passes it the peer is not draining and the connection is
@@ -60,16 +56,15 @@ const (
defaultHeartbeatIntervalMs = 30_000
)
-// SfuFallback is the embedded media runtime the media router
-// may use. A zero timeout means the TypeScript default.
+// SfuFallback configures embedded media; a zero prepare timeout selects the
+// router's default.
type SfuFallback struct {
Media sfu.Runtime
Admission *sfu.Admission
PrepareTimeoutMs int64
}
-// Options is SignalingOptions. Every zero value is the TypeScript `undefined`
-// and takes the same default.
+// Options supplies room authority, runtime capabilities and signaling limits.
type Options struct {
Store *room.Store
EndpointMediaCopyCapacity int
@@ -336,7 +331,6 @@ func InviteURL(publicBaseURL *url.URL, roomID, viewerGrant string) string {
// ServeHTTP is the "upgrade" listener: the TS rejection ladder, then the
// accept (D4).
func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
- // TS: new URL(request.url ?? "/", "http://localhost") throws. net/http
// accepts a scheme-relative target such as "//[" as a plain path, so
// the WHATWG authority parse is re-run on the raw target.
if _, err := url.Parse(request.RequestURI); err != nil {
@@ -381,7 +375,6 @@ func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
InsecureSkipVerify: true,
CompressionMode: websocket.CompressionDisabled,
OnPongReceived: func(context.Context, []byte) {
- // TS: socket.on("pong", () => { state.alive = true })
s.mu.Lock()
if sess != nil {
sess.alive = true
@@ -1073,7 +1066,7 @@ func (s *Server) settleHostShare(roomID, sessionID string, request authRequest)
}
}
if currentGeneration != shareGeneration || share.routePolicy == nil {
- routePolicy := configuredRoutePolicy(request.routePolicy, s.natPredictionEnabled)
+ routePolicy := s.configuredRoutePolicy(request.routePolicy)
share.routePolicy = &routePolicy
for _, viewer := range s.store.GetConnectedViewers(roomID) {
message := protocol.RoutePolicyMessage{
@@ -1127,12 +1120,13 @@ func (s *Server) routePolicyOf(roomID string) protocol.RoutePolicy {
if policy := s.shares[roomID].routePolicy; policy != nil {
return *policy
}
- return protocol.DefaultRoutePolicy
+ return s.configuredRoutePolicy(protocol.DefaultRoutePolicy)
}
-// configuredRoutePolicy ports configuredRoutePolicy.
-func configuredRoutePolicy(policy protocol.RoutePolicy, natPredictionEnabled bool) protocol.RoutePolicy {
- policy.NatPrediction = natPredictionEnabled && policy.NatPrediction
+// configuredRoutePolicy restricts share preferences to the services this runtime owns.
+func (s *Server) configuredRoutePolicy(policy protocol.RoutePolicy) protocol.RoutePolicy {
+ policy.PeerOnly = s.router.sfu == nil || policy.PeerOnly
+ policy.NatPrediction = s.natPredictionEnabled && policy.NatPrediction
return policy
}
@@ -1245,7 +1239,7 @@ func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authen
s.sendViewerPresence(authenticated.roomID)
case protocol.SetSharingPausedMessage:
if authenticated.role != protocol.RoleHost {
- s.sendError(sess, "FORBIDDEN", "只有当前分享者可以暂停分享")
+ s.sendError(sess, "FORBIDDEN", "只有当前房主可以暂停分享")
return
}
connectedHost, hasHost := s.store.GetConnectedHost(authenticated.roomID)
@@ -1267,7 +1261,7 @@ func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authen
s.broadcastHostStatus(authenticated.roomID, true, m.Paused)
case protocol.StopSharingMessage:
if authenticated.role != protocol.RoleHost {
- s.sendError(sess, "FORBIDDEN", "只有当前分享者可以停止分享")
+ s.sendError(sess, "FORBIDDEN", "只有当前房主可以停止分享")
return
}
if authenticated.shareGeneration == "" ||
diff --git a/internal/server/signal/server_test.go b/internal/server/signal/server_test.go
index 914058c9..e04cbc4f 100644
--- a/internal/server/signal/server_test.go
+++ b/internal/server/signal/server_test.go
@@ -1062,23 +1062,37 @@ func expectTrue(t *testing.T, name string, condition bool) {
// ---------------------------------------------------------------------------
func TestSignalEchoesExactPerShareRoutePolicyAuthority(t *testing.T) {
- h := startHarness(t, harnessOptions{
- stunURLs: []string{"stun:share.example.test:3478"},
- natPredictionEnabled: true,
- })
- viewer := openClient(t, h)
- waiting := authenticate(t, viewer, h.room, protocol.RoleViewer, "route-policy-viewer", 1, "", presenceOptions{})
- expectTrue(t, "waiting shareGeneration must be null", waiting.ShareGeneration == nil)
- host := openClient(t, h)
- routePolicy := protocol.RoutePolicy{PeerOnly: true, TopologyOptimization: true, NatPrediction: true}
- authenticated := authenticate(t, host, h.room, protocol.RoleHost, "route-policy-host", 1,
- "route_policy_share_generation_12345678", presenceOptions{routePolicy: &routePolicy})
- if authenticated.RoutePolicy != routePolicy {
- t.Fatalf("routePolicy: %+v", authenticated.RoutePolicy)
+ for _, sfuEnabled := range []bool{false, true} {
+ for _, peerOnly := range []bool{false, true} {
+ t.Run(fmt.Sprintf("sfu=%t/peerOnly=%t", sfuEnabled, peerOnly), func(t *testing.T) {
+ options := harnessOptions{natPredictionEnabled: true}
+ if sfuEnabled {
+ options.sfu = &SfuFallback{
+ Media: sfutest.New(),
+ Admission: sfu.NewAdmission(sfu.AdmissionOptions{IngressCapacity: 2, EgressCapacity: 20}),
+ }
+ }
+ h := startHarness(t, options)
+ viewer := openClient(t, h)
+ waiting := authenticate(t, viewer, h.room, protocol.RoleViewer, "route-policy-viewer", 1, "", presenceOptions{})
+ if waiting.ShareGeneration != nil || waiting.RoutePolicy.PeerOnly != !sfuEnabled {
+ t.Fatalf("waiting policy: %+v", waiting.RoutePolicy)
+ }
+ host := openClient(t, h)
+ requested := protocol.RoutePolicy{PeerOnly: peerOnly, TopologyOptimization: true, NatPrediction: true}
+ expected := requested
+ expected.PeerOnly = !sfuEnabled || peerOnly
+ authenticated := authenticate(t, host, h.room, protocol.RoleHost, "route-policy-host", 1,
+ "route_policy_share_generation_12345678", presenceOptions{routePolicy: &requested})
+ if authenticated.RoutePolicy != expected {
+ t.Fatalf("routePolicy: %+v; want %+v", authenticated.RoutePolicy, expected)
+ }
+ expectTrue(t, "sfuStandbyUrl must be absent", !hasKey(t, authenticated.raw, "sfuStandbyUrl"))
+ expectEqual(t, viewer.next("route-policy").raw, fmt.Sprintf(
+ `{"type":"route-policy","shareGeneration":"route_policy_share_generation_12345678","routePolicy":{"peerOnly":%t,"topologyOptimization":true,"natPrediction":true}}`, expected.PeerOnly))
+ })
+ }
}
- expectTrue(t, "sfuStandbyUrl must be absent", !hasKey(t, authenticated.raw, "sfuStandbyUrl"))
- expectEqual(t, viewer.next("route-policy").raw,
- `{"type":"route-policy","shareGeneration":"route_policy_share_generation_12345678","routePolicy":{"peerOnly":true,"topologyOptimization":true,"natPrediction":true}}`)
}
func TestSignalBroadcastsConfiguredNatPredictionInLightweightRooms(t *testing.T) {
@@ -1095,11 +1109,12 @@ func TestSignalBroadcastsConfiguredNatPredictionInLightweightRooms(t *testing.T)
routePolicy.NatPrediction = true
hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "ordinary-nat-host", -1,
"ordinary_nat_share_generation_12345678", presenceOptions{routePolicy: &routePolicy})
+ routePolicy.PeerOnly = true
if hostAuth.RoutePolicy != routePolicy {
t.Fatalf("routePolicy: %+v", hostAuth.RoutePolicy)
}
expectMatch(t, waitingViewer.next("route-policy").raw,
- `{"routePolicy":{"peerOnly":false,"topologyOptimization":true,"natPrediction":true}}`)
+ `{"routePolicy":{"peerOnly":true,"topologyOptimization":true,"natPrediction":true}}`)
joiningViewer := openClient(t, h)
joined := authenticate(t, joiningViewer, h.room, protocol.RoleViewer, "ordinary-nat-joining-viewer", -1, "", presenceOptions{})
diff --git a/internal/server/signal/session.go b/internal/server/signal/session.go
index 3c4b4fdd..eff1479d 100644
--- a/internal/server/signal/session.go
+++ b/internal/server/signal/session.go
@@ -1,10 +1,7 @@
package signal
-// The per-connection state of src/server/signaling.ts (SocketState,
-// accept(), the socket event handlers, send()/sendEncodedToSession(),
-// heartbeat()). One reader goroutine and one writer goroutine per
-// connection; the writer drains an outbound queue that handlers fill under
-// mu, which is what the ws library's own send buffer did (D4).
+// Each connection has one reader and one writer goroutine. Handlers enqueue
+// outgoing frames under Server.mu; only the writer drains that bounded queue.
import (
"context"
@@ -15,10 +12,9 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
-// authenticatedSession is AuthenticatedSession. Handlers compare it by
-// pointer (hazard 1): `state.authenticated !== authenticated` detects a
-// re-authentication between dispatch and use. shareGeneration is "" where
-// the TS had null; displayName is nil where the TS had null.
+// Handlers compare authenticatedSession pointers to reject work from an
+// authentication replaced between dispatch and use. Empty shareGeneration
+// means no share; nil displayName means the participant has no display name.
type authenticatedSession struct {
roomID string
role protocol.Role
@@ -195,7 +191,6 @@ func (s *Server) handleIncoming(sess *session, kind websocket.MessageType, data
s.mu.Lock()
defer s.mu.Unlock()
if kind == websocket.MessageBinary {
- // TS: if (isBinary) rejectInvalidMessage(socket)
s.rejectInvalidMessage(sess)
} else {
s.handleMessage(sess, data)
diff --git a/package-lock.json b/package-lock.json
index 47cfb1bc..d977f81d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,27 +1,28 @@
{
"name": "piik",
- "version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "piik",
- "version": "0.1.0",
"license": "MIT",
"devDependencies": {
"@types/node": "24.13.3",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@types/sdp-transform": "3.0.0",
+ "@types/semver": "7.8.0",
"@types/ws": "8.18.1",
"@vitejs/plugin-react": "6.0.5",
+ "esbuild": "0.28.2",
"react": "19.2.8",
"react-dom": "19.2.8",
"sdp-transform": "3.0.0",
+ "semver": "7.8.5",
"tsx": "4.23.12",
"typescript": "~6.0.3",
"vite": "8.2.1",
- "vitest": "4.1.10",
+ "vitest": "4.1.11",
"ws": "8.21.3",
"zod": "4.4.3"
},
@@ -472,9 +473,9 @@
}
},
"node_modules/@jridgewell/sourcemap-codec": {
- "version": "1.5.5",
- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
- "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"dev": true,
"license": "MIT"
},
@@ -820,6 +821,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/semver": {
+ "version": "7.8.0",
+ "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz",
+ "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
@@ -857,16 +865,16 @@
}
},
"node_modules/@vitest/expect": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",
- "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
+ "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
- "@vitest/spy": "4.1.10",
- "@vitest/utils": "4.1.10",
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
"chai": "^6.2.2",
"tinyrainbow": "^3.1.0"
},
@@ -875,13 +883,13 @@
}
},
"node_modules/@vitest/mocker": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",
- "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
+ "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/spy": "4.1.10",
+ "@vitest/spy": "4.1.11",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.21"
},
@@ -902,9 +910,9 @@
}
},
"node_modules/@vitest/pretty-format": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
- "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
+ "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -915,13 +923,13 @@
}
},
"node_modules/@vitest/runner": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
- "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
+ "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/utils": "4.1.10",
+ "@vitest/utils": "4.1.11",
"pathe": "^2.0.3"
},
"funding": {
@@ -929,14 +937,14 @@
}
},
"node_modules/@vitest/snapshot": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
- "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
+ "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/pretty-format": "4.1.10",
- "@vitest/utils": "4.1.10",
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/utils": "4.1.11",
"magic-string": "^0.30.21",
"pathe": "^2.0.3"
},
@@ -945,9 +953,9 @@
}
},
"node_modules/@vitest/spy": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",
- "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
+ "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
"dev": true,
"license": "MIT",
"funding": {
@@ -955,13 +963,13 @@
}
},
"node_modules/@vitest/utils": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
- "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
+ "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/pretty-format": "4.1.10",
+ "@vitest/pretty-format": "4.1.11",
"convert-source-map": "^2.0.0",
"tinyrainbow": "^3.1.0"
},
@@ -1560,6 +1568,19 @@
"sdp-verify": "checker.js"
}
},
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
@@ -1754,19 +1775,19 @@
}
},
"node_modules/vitest": {
- "version": "4.1.10",
- "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",
- "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
+ "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/expect": "4.1.10",
- "@vitest/mocker": "4.1.10",
- "@vitest/pretty-format": "4.1.10",
- "@vitest/runner": "4.1.10",
- "@vitest/snapshot": "4.1.10",
- "@vitest/spy": "4.1.10",
- "@vitest/utils": "4.1.10",
+ "@vitest/expect": "4.1.11",
+ "@vitest/mocker": "4.1.11",
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/runner": "4.1.11",
+ "@vitest/snapshot": "4.1.11",
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
"es-module-lexer": "^2.0.0",
"expect-type": "^1.3.0",
"magic-string": "^0.30.21",
@@ -1794,12 +1815,12 @@
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
- "@vitest/browser-playwright": "4.1.10",
- "@vitest/browser-preview": "4.1.10",
- "@vitest/browser-webdriverio": "4.1.10",
- "@vitest/coverage-istanbul": "4.1.10",
- "@vitest/coverage-v8": "4.1.10",
- "@vitest/ui": "4.1.10",
+ "@vitest/browser-playwright": "4.1.11",
+ "@vitest/browser-preview": "4.1.11",
+ "@vitest/browser-webdriverio": "4.1.11",
+ "@vitest/coverage-istanbul": "4.1.11",
+ "@vitest/coverage-v8": "4.1.11",
+ "@vitest/ui": "4.1.11",
"happy-dom": "*",
"jsdom": "*",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
diff --git a/package.json b/package.json
index 99af5dc3..6cb2eb53 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,5 @@
{
"name": "piik",
- "version": "0.1.0",
"license": "MIT",
"private": true,
"type": "module",
@@ -11,6 +10,8 @@
"scripts": {
"dev": "node scripts/package-licenses.mjs public/third-party-licenses.txt && vite",
"build": "npm run build:client",
+ "build:website": "node scripts/update-website-hero.mjs --check && node scripts/build-website.mjs",
+ "preview:website": "vite preview --outDir build/site --host 127.0.0.1 --port 18890",
"build:client": "node scripts/package-licenses.mjs public/third-party-licenses.txt && node --input-type=module -e \"import { readdirSync, rmSync } from 'node:fs'; const dir = 'internal/server/webassets/dist'; for (const entry of readdirSync(dir)) { if (entry !== '.gitkeep') rmSync(dir + '/' + entry, { recursive: true, force: true }); }\" && vite build",
"package:client": "node scripts/assemble-client.mjs",
"package:client-candidate": "node scripts/package-client-candidate.mjs",
@@ -32,21 +33,23 @@
"test:watch": "vitest",
"check": "npm run typecheck && npm test && npm run build"
},
- "dependencies": {},
"devDependencies": {
"@types/node": "24.13.3",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@types/sdp-transform": "3.0.0",
+ "@types/semver": "7.8.0",
"@types/ws": "8.18.1",
"@vitejs/plugin-react": "6.0.5",
+ "esbuild": "0.28.2",
"react": "19.2.8",
"react-dom": "19.2.8",
"sdp-transform": "3.0.0",
+ "semver": "7.8.5",
"tsx": "4.23.12",
"typescript": "~6.0.3",
"vite": "8.2.1",
- "vitest": "4.1.10",
+ "vitest": "4.1.11",
"ws": "8.21.3",
"zod": "4.4.3"
}
diff --git a/scripts/access-privacy-gate.ts b/scripts/access-privacy-gate.ts
index 7bbf776f..e272dc6f 100644
--- a/scripts/access-privacy-gate.ts
+++ b/scripts/access-privacy-gate.ts
@@ -33,7 +33,7 @@ import {
withDeadline,
} from "./browser-gate-harness";
const root = resolve(import.meta.dirname, "..");
-const nginxConfigPath = resolve(root, "deploy/nginx/share.bonfire.icu.conf.example");
+const nginxConfigPath = resolve(root, "deploy/nginx/piik.conf.example");
const serverExecutable = join(root, "build", "client-check",
process.platform === "win32" ? "piik-server.exe" : "piik-server");
// PIIK_ENV=production refuses to start without STUN. Nothing listens on
@@ -122,7 +122,7 @@ function upgradeStatus(chunk: Buffer): number {
return match ? Number(match[1]) : 0;
}
// startProxy stands in for the nginx reverse proxy the deployment runs in
-// front of the server (deploy/nginx/share.bonfire.icu.conf.example). It
+// front of the server (deploy/nginx/piik.conf.example). It
// observes every request line the browser and the gate emit, which is what the
// in-process httpServer.prependListener("request") hook used to do, and it is
// the only origin the browser ever sees.
diff --git a/scripts/assemble-client.mjs b/scripts/assemble-client.mjs
index 0cb75427..969ed851 100644
--- a/scripts/assemble-client.mjs
+++ b/scripts/assemble-client.mjs
@@ -25,6 +25,7 @@ import { writeClientPlatformAssets } from "./client-icons.mjs";
import { writeClientLicenseNotices } from "./package-licenses.mjs";
import { tarExecutable } from "./archive-tool.mjs";
import { resetBuildWorkspace } from "./build-workspace.mjs";
+import { isReleaseVersion } from "./release-version.mjs";
function fail(message) {
throw new Error(message);
@@ -114,7 +115,8 @@ function readDescriptor(path) {
fail("Application release descriptor is invalid");
}
if (
- value?.schema !== 1 ||
+ value?.schema !== 2 ||
+ (value.version !== "development" && !isReleaseVersion(value.version)) ||
typeof value.revision !== "string" ||
!/^[0-9a-f]{40}$/.test(value.revision) ||
typeof value.artifactSha256 !== "string" ||
@@ -123,6 +125,7 @@ function readDescriptor(path) {
fail("Application release descriptor is invalid");
}
return {
+ version: value.version,
revision: value.revision,
artifact: plainName(value.artifact, "artifact"),
artifactSha256: value.artifactSha256,
@@ -198,6 +201,9 @@ if (capturePath) assertTargetExecutable(capturePath, target, "Capture runtime");
if (tunnelPath) assertTargetExecutable(tunnelPath, target, "Public tunnel runtime");
const descriptor = readDescriptor(descriptorPath);
+const version = descriptor.version;
+process.env.VITE_PIIK_VERSION = version;
+process.env.VITE_PIIK_REVISION = descriptor.revision;
const revision = run("git", ["rev-parse", "HEAD"], repositoryRoot).toLowerCase();
if (revision !== descriptor.revision) {
fail("Client source and application release revisions do not match");
@@ -253,7 +259,7 @@ try {
"build",
"-trimpath",
"-ldflags",
- `-s -w -X github.com/TNTcraftHIM/Piik/internal/app.BuildRevision=${revision}`,
+ `-s -w -X github.com/TNTcraftHIM/Piik/internal/app.BuildRevision=${revision} -X github.com/TNTcraftHIM/Piik/internal/app.BuildVersion=${version}`,
"-o",
clientPath,
"./cmd/piik-app",
@@ -265,6 +271,7 @@ try {
const platformAssets = writeClientPlatformAssets({
packageRoot,
target,
+ version,
revision,
iconPath: join(repositoryRoot, "cmd", "piik-app", "piik.ico"),
});
@@ -277,6 +284,7 @@ try {
});
process.stdout.write(`${JSON.stringify({
root: outputRoot,
+ version,
revision,
target: target.id,
platform: target.goos,
diff --git a/scripts/build-website.mjs b/scripts/build-website.mjs
new file mode 100644
index 00000000..52ed56a9
--- /dev/null
+++ b/scripts/build-website.mjs
@@ -0,0 +1,74 @@
+import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import { build } from "esbuild";
+import { writeWebLicenseNotices } from "./package-licenses.mjs";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { tsImport } from "tsx/esm/api";
+
+const source = new URL("../site/", import.meta.url);
+const output = new URL("../build/site/", import.meta.url);
+await rm(output, { recursive: true, force: true });
+await mkdir(output, { recursive: true });
+await cp(source, output, {
+ recursive: true,
+ filter: (path) =>
+ !path.endsWith(".ts") &&
+ !path.endsWith(".tsx") &&
+ !path.endsWith("tsconfig.json") &&
+ !path.endsWith("README.md"),
+});
+await cp(new URL("../LICENSE", import.meta.url), new URL("LICENSE", output));
+// The opening shot uses the current homepage, with only its film clock adapter
+// substituted for the ordinary page script. Keep its layout and copy in one place.
+await writeFile(new URL("film/ui/website.html", output),
+ (await readFile(new URL("index.html", source), "utf8"))
+ .replace('<head>', '<head><base href="../../" />')
+ .replace('<script type="module" src="./main.js"></script>', '<script src="./film/ui/website.js" defer></script>')
+ .replace('</body>', (await readFile(new URL("film/ui/index.html", source), "utf8")).match(/<svg id="cursor"[\s\S]*?<\/svg>/)[0] + '</body>'),
+);
+// Static controls use the product icon owner without shipping another React
+// runtime to the film page. The live demonstration remains its isolated bundle.
+const filmPage = new URL("film/index.html", output);
+const { Glyph } = await tsImport("../src/client/ui/icons.tsx", {
+ parentURL: import.meta.url,
+ tsconfig: fileURLToPath(new URL("../src/tsconfig.json", import.meta.url)),
+});
+await writeFile(filmPage, (await readFile(filmPage, "utf8")).replace(
+ /<span data-glyph="([a-zA-Z]+)"><\/span>/g,
+ (_, name) => renderToStaticMarkup(createElement(Glyph, { name, size: 21 })),
+));
+await cp(
+ new URL("../src/client/components/living/playback-controls.css", import.meta.url),
+ new URL("film/playback-controls.css", output),
+);
+await cp(
+ new URL("../src/client/components/living/brand-mark.css", import.meta.url),
+ new URL("film/brand-mark.css", output),
+);
+writeWebLicenseNotices(
+ fileURLToPath(new URL("../", import.meta.url)),
+ fileURLToPath(new URL("film/ui/third-party-licenses.txt", output)),
+);
+await build({
+ entryPoints: {
+ ui: fileURLToPath(new URL("../site/film/ui/main.tsx", import.meta.url)),
+ website: fileURLToPath(new URL("../site/film/ui/website.ts", import.meta.url)),
+ },
+ outdir: fileURLToPath(new URL("film/ui/", output)),
+ bundle: true,
+ format: "iife",
+ jsx: "automatic",
+ minify: true,
+ legalComments: "linked",
+ define: {
+ "import.meta": "piikFilmBuild",
+ "process.env.NODE_ENV": '"production"',
+ },
+ banner: {
+ js: "const piikFilmBuild = { url: document.currentScript.src, env: { DEV: false } };",
+ },
+});
+console.log(
+ "Website built in build/site (static files, including the shared product UI).",
+);
diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs
index d789eb6f..b7682652 100644
--- a/scripts/check-docs.mjs
+++ b/scripts/check-docs.mjs
@@ -24,14 +24,9 @@ const contextBudgetRemediation =
"simplify repeated wording, and remove completed history or stale conclusions.";
const contextWarningRatio = 0.8;
const codexProjectDocMaxBytes = 32 * 1_024;
-const claudeRecommendedLines = 200;
const hermesMinimumContextChars = 20_000;
const agentInstructions = readFileSync(resolve(root, "AGENTS.md"), "utf8");
-const claudeWrapper = readFileSync(resolve(root, "CLAUDE.md"), "utf8").replace(
- /^@AGENTS\.md\s*(?:\r?\n)?/u,
- "",
-);
const ponytailInstructions = readFileSync(
resolve(root, ".agents/skills/ponytail/SKILL.md"),
"utf8",
@@ -45,14 +40,6 @@ const topLevelContextBudgets = [
},
hard: { bytes: codexProjectDocMaxBytes },
},
- {
- name: "Claude effective project instructions",
- text: `${agentInstructions}\n${claudeWrapper}`,
- recommended: { lines: claudeRecommendedLines },
- hard: {
- lines: Math.ceil(claudeRecommendedLines / contextWarningRatio),
- },
- },
{
name: "Hermes root project context",
text: agentInstructions,
@@ -65,12 +52,10 @@ const topLevelContextBudgets = [
name: "Required ponytail skill",
text: ponytailInstructions,
recommended: {
- lines: claudeRecommendedLines,
chars: Math.floor(hermesMinimumContextChars * contextWarningRatio),
bytes: Math.floor(codexProjectDocMaxBytes * contextWarningRatio),
},
hard: {
- lines: Math.ceil(claudeRecommendedLines / contextWarningRatio),
chars: hermesMinimumContextChars,
bytes: codexProjectDocMaxBytes,
},
diff --git a/scripts/check-website-film.js b/scripts/check-website-film.js
new file mode 100644
index 00000000..5d52f7c3
--- /dev/null
+++ b/scripts/check-website-film.js
@@ -0,0 +1,501 @@
+// Run in a freshly opened local /film/ page using agent-browser eval --stdin.
+// This exercises the real document/module; it does not mock its scene renderer.
+// First click #language with agent-browser to grant native audio user activation.
+(async () => {
+ const assert = (ok, message) => {
+ if (!ok) throw new Error(message);
+ };
+ const el = (id) => document.getElementById(id);
+ const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));
+ const settle = async () => {
+ for (let i = 0; i < 4; i++) await nextFrame();
+ };
+ const until = async (test, message) => {
+ const deadline = performance.now() + 6000;
+ while (!test() && performance.now() < deadline) await nextFrame();
+ assert(test(), message);
+ };
+ const media = el('soundtrack');
+ const seek = (value) => {
+ el('seek').value = String(value);
+ el('seek').dispatchEvent(new Event('input'));
+ };
+ const position = () => Number(el('seek').value);
+ const playing = () => document.body.hasAttribute('data-playing');
+ const scene = () => [...document.querySelectorAll('#film-art > g')].filter((g) => g.style.display !== 'none').map((g) => g.id);
+ const gamePose = () =>
+ [...el('scene-game').children]
+ .filter((g) => g.style.display !== 'none')
+ .map((g) => g.outerHTML)
+ .join('');
+ assert(media && !media.getAttribute('src'), 'The poster must not request music');
+ assert(!playing() && !el('curtain').hidden, 'The poster must wait for an explicit play action');
+ assert(navigator.userActivation.hasBeenActive, 'Click #language with real browser input before running the audible check');
+
+ el('start-muted').click();
+ const deadline = performance.now() + 1500;
+ while (position() < 0.02 && performance.now() < deadline) await nextFrame();
+ assert(playing() && position() > 0, 'Muted playback must advance');
+ assert(!media.getAttribute('src'), 'Muted playback must not request music');
+ el('play').click();
+ const paused = position();
+ await settle();
+ assert(position() === paused && !playing(), 'Pause must freeze the picture');
+
+ // Seeking out of order and returning to a frame must produce the same pose.
+ seek(20);
+ const firstPose = gamePose();
+ seek(40);
+ assert(scene().includes('scene-people'), 'Seeking must select the correct scene');
+ assert(document.querySelectorAll('[id^="seat-"]:not([id^="seat-row"]):not([id$="-eyes"])').length === 20, 'The room must have exactly twenty viewer figures');
+ seek(68);
+ assert(scene().includes('scene-end'), 'Seeking to the ending must render the ending');
+ seek(20);
+ assert(gamePose() === firstPose, 'Revisiting a frame must not depend on earlier scenes');
+ for (const [time, name] of [
+ [7, 'website'],
+ [9.8, 'desktop'],
+ [12, 'launch'],
+ [15, 'share'],
+ [33, 'invite'],
+ [49, 'features'],
+ ]) {
+ seek(time);
+ assert(scene().includes(`scene-${name}`), `The product sequence must show ${name}`);
+ }
+ const {BEAT,BAR,DOWNLOAD_AT,DURATION} = await import('./score.js');
+ for (const [bar, feature] of [[19.5, 'free'], [20.5, 'p2p'], [21.5, 'encode'], [23, 'devices']]) {
+ seek(bar * BAR);
+ const visible = [...el('scene-features').children].filter(node => node.style.display !== 'none');
+ assert(visible.length === 1 && visible[0].id === `feature-${feature}`, 'The four benefits must advance within the same musical phrase');
+ }
+ seek(22.5 * BAR + BEAT / 2);
+ const devices = () => ['laptop', 'tablet', 'phone'].map(id => el(`devices-${id}`).outerHTML).join('');
+ const arrivingDevices = devices();
+ seek(23.5 * BAR);
+ assert(devices() !== arrivingDevices && ['laptop', 'tablet', 'phone'].every(id => el(`devices-${id}`).getAttribute('opacity') === '1'), 'The devices must enter in sequence and settle into a readable frame');
+ seek(22.5 * BAR + BEAT / 2);
+ assert(devices() === arrivingDevices, 'Device arrival must be deterministic after reverse seeking');
+ for (const bar of [3.5, 4.5, 6]) {
+ seek(bar * BAR - .1);
+ const beforeHandoff = el('ui-placement').transform.baseVal.consolidate().matrix;
+ seek(bar * BAR + BEAT / 2);
+ const afterHandoff = el('ui-placement').transform.baseVal.consolidate().matrix;
+ assert(['a','b','c','d','e','f'].every(key=>Math.abs(beforeHandoff[key]-afterHandoff[key])<.01), 'The desktop, App and source steps must keep a continuous window position');
+ }
+ const gameKinds = ['rpg', 'fps', 'platform', 'rts', 'moba', 'fighting'];
+ const gameCut = 5 * BAR / gameKinds.length;
+ for (const [index, kind] of gameKinds.entries()) {
+ seek(8 * BAR + (index + .35) * gameCut);
+ const shown = [...document.querySelectorAll('#scene-game > g[id^="montage-"]')].filter((g) => g.style.display !== 'none');
+ assert(
+ shown.some((g) => g.id === `montage-${kind}`),
+ `The game montage must show ${kind}`,
+ );
+ assert(el('montage-cheer').style.opacity === '0', 'Applause must not precede the successful play');
+ }
+ assert(!document.querySelector('#montage-label, [id^="montage-kind-"], [id^="fps-count-"]'), 'The games must read through their action without category or practice labels');
+ for (const [index, shot] of [.55, 1.1, 1.65].entries()) {
+ const at = local => seek(8 * BAR + gameCut * (1 + local / BAR));
+ at(shot - .04);
+ const aim = el('fps-tool').style.transform;
+ at(shot + .025);
+ assert(Number(el('fps-muzzle').style.opacity) > 0 && Number(el('fps-tracer').style.opacity) > 0 && el('fps-tool').style.transform !== aim, 'The foreground weapon must fire and recoil toward its crosshair');
+ at(shot + .19);
+ assert(el(`fps-target-${index}`).style.opacity === '0' && el('fps-muzzle').style.opacity === '0', 'Each shot must leave a clear hit after the flash');
+ }
+ seek(8 * BAR + 4.5 * gameCut);
+ const health = () => new DOMMatrix(getComputedStyle(el('moba-health-0')).transform).a;
+ assert(health() > 0 && el('montage-cheer').style.opacity === '0', 'The counterattack must leave time to see its target before the hit');
+ seek(8 * BAR + 4.85 * gameCut);
+ assert(
+ health() === 0 && el('moba-result').style.opacity === '1',
+ 'The skill shot must resolve before celebrating',
+ );
+ seek(8 * BAR + 5.48 * gameCut);
+ const fighterHealth = () => new DOMMatrix(getComputedStyle(el('fighting-health')).transform).a;
+ assert(fighterHealth() > 0 && el('montage-cheer').style.opacity === '0', 'The guard must leave time to see the counterattack before the hit');
+ const finalHit = 8 * BAR + 5.85 * gameCut;
+ seek(finalHit);
+ assert(fighterHealth() === 0 && el('montage-cheer').style.opacity === '1', 'The reaction must follow the successful counterattack');
+ const finishPose = gamePose();
+ seek(22);
+ seek(finalHit);
+ assert(gamePose() === finishPose, 'Montage effects must remain deterministic after seeking backwards');
+ const product = el('product-ui');
+ assert([product, el('website-ui')].every(frame => frame.sandbox.value === 'allow-scripts' && frame.hasAttribute('inert')), 'Both real pages must remain isolated, non-interactive frames');
+ seek(33);
+ await settle();
+ assert(
+ !el('film-ui').hasAttribute('hidden') && el('ui-placement').getAttribute('transform').startsWith('matrix('),
+ 'The invitation must frame the shared product UI',
+ );
+ seek(49);
+ assert(el('film-ui').hasAttribute('hidden'), 'The product UI must not cover other scenes');
+ el('replay').click();
+ await settle();
+ assert(position() < 1 && playing() && scene().includes('scene-hello'), 'Replay must start a fresh film');
+ seek(Number(el('seek').max));
+ assert(!playing() && scene().includes('scene-end') && el('download-banner').style.display !== 'none', 'Seeking to the end must hold the download overlay on the original ending');
+ assert(el('time').textContent === '1:16 / 1:16', 'The player must format durations longer than one minute');
+ assert(!el('download').hidden && new URL(el('download').href).hash === '#download' && el('download').target === '_top', 'The final action must reach the homepage downloads, including from the embedded player');
+ const endingPose = () => el('scene-end').outerHTML;
+ const lastPose = endingPose();
+ seek(DOWNLOAD_AT-BEAT);
+ assert(el('download').hidden, 'Rewinding must hide the ending action');
+ seek(DURATION - 3 * BEAT);
+ const endingAnimations = () => el('end-tv').getAnimations({subtree:true});
+ assert(endingAnimations().length === 5 && endingAnimations().every(animation => animation.playState === 'paused' && animation.effect.getTiming().duration === 3600), 'The ending must reuse the loading mascot loop, held at the requested film frame');
+ assert(getComputedStyle(el('end-tv-wink')).opacity === '1' && Number(getComputedStyle(el('end-tv-sparkles').firstElementChild).opacity) > .5, 'The loading mascot must wink with its gold sparkles');
+ for (const time of [DURATION - BEAT / 2, DURATION - 1 / 60]) {
+ seek(time);
+ assert(getComputedStyle(el('end-tv-wink')).opacity === '0' && getComputedStyle(el('end-tv-open')).opacity === '1' && [...el('end-tv-sparkles').children].every(star => getComputedStyle(star).opacity === '0'), 'The final wink and both sparkles must settle before the music and last exported frame');
+ }
+ assert(!el('scene-download') && el('download-banner').closest('#scene-end') && el('end-brand').checkVisibility(), 'The download must overlay the existing brand and room instead of starting another scene');
+ seek(Number(el('seek').max));
+ assert(endingPose() === lastPose, 'The final pose must survive reverse seeking');
+ const endingPhase = endingAnimations().map(animation => animation.currentTime);
+ seek(DURATION - .1);
+ el('play').click();
+ await until(() => !playing(), 'The film must finish naturally');
+ await settle();
+ assert(endingAnimations().every(animation => animation.playState === 'running'), 'Natural completion must leave only the mascot idle loop running');
+ assert(endingAnimations().every((animation, index) => animation.currentTime >= endingPhase[index] && animation.currentTime < endingPhase[index] + 250), 'Natural completion must continue the same phase without restarting the wink');
+ seek(DURATION);
+ const frozenEnding = endingAnimations().map(animation => animation.currentTime);
+ await settle();
+ assert(endingAnimations().every((animation, index) => animation.playState === 'paused' && animation.currentTime === frozenEnding[index]), 'Seeking after completion must freeze the mascot again');
+ seek(DOWNLOAD_AT + BAR);
+ el('play').click();
+ el('download').addEventListener('click', event => event.preventDefault(), {once:true});
+ el('download').click();
+ assert(!playing() && media.paused, 'The ending action must pause playback before navigation');
+ seek(Number(el('seek').max));
+
+ // The language switch must preserve the frame and keep return links current.
+ const beforeLanguage = document.documentElement.lang;
+ el('language').click();
+ assert(document.documentElement.lang !== beforeLanguage && scene().includes('scene-end'), 'Language changes must preserve playback position');
+ assert(
+ [...document.querySelectorAll('[data-home]')].every((a) => new URL(a.href).searchParams.get('lang') === document.documentElement.lang),
+ 'Return links must carry the current language',
+ );
+ el('language').click();
+ assert(
+ [...document.querySelectorAll('[data-home]')].every((a) => new URL(a.href).searchParams.get('lang') === beforeLanguage),
+ 'Return links must update on subsequent language changes',
+ );
+ const previousTheme = document.documentElement.dataset.theme;
+ document.documentElement.dataset.theme = 'dark';
+ el('language').click();
+ delete document.documentElement.dataset.theme;
+ el('language').click();
+ assert([...document.querySelectorAll('[data-home]')].every(a => !new URL(a.href).searchParams.has('theme')), 'Returning to system theme must clear the old explicit theme from links');
+ if (previousTheme) document.documentElement.dataset.theme = previousTheme;
+ el('language').click();
+ el('language').click();
+
+ // Rotated primary copy needs a safe frame, not just an overflow-free page.
+ for (let language = 0; language < 2; language++) {
+ for (const [time, selector] of [
+ [1.4, '#hello-word text'], [4.3, '#discover-ticket text'],
+ [7, '#website-type text'], [9.8, '#desktop-type text'],
+ [12, '#launch-type text'], [15, '#share-type text'], [35, '#invite-type text'],
+ [44, '#people-close-type text'], [46.5, '#free-type text'],
+ [48.8, '#p2p-type text, #feature-p2p > text'], [52, '#encode-type text, #feature-encode > text'],
+ [55.5, '#devices-type text, #feature-devices > text'],
+ [58.3, '#more-game > g > text'], [60, '#more-art-type text'],
+ [61.8, '#more-photos-type text'], [63.6, '#more-movie-type text'],
+ [68, '#end-type text'], [71.5, '#download-banner text'],
+ ]) {
+ seek(time);
+ for (const text of document.querySelectorAll(selector)) {
+ const b = text.getBBox(), m = el('film-art').getCTM().inverse().multiply(text.getCTM());
+ for (const [x,y] of [[b.x,b.y],[b.x+b.width,b.y],[b.x,b.y+b.height],[b.x+b.width,b.y+b.height]]) {
+ const p = new DOMPoint(x,y).matrixTransform(m);
+ assert(p.x >= 20 && p.x <= 1580 && p.y >= 20 && p.y <= 880, `Headline clipped: ${text.textContent}`);
+ }
+ }
+ }
+ // Stable corner labels share a baseline even when nearby artwork moves.
+ for (const [time, selector] of [
+ [1.4, '#hello-label'], [4.3, '#discover-label'],
+ [7, '#scene-website'], [9.8, '#scene-desktop'], [12, '#scene-launch'],
+ [15, '#share-label'], [17.9, '#share-label'], [35, '#scene-invite'],
+ [40, '#scene-people'], [44, '#people-close'], [46.5, '#feature-free'],
+ [48.8, '#feature-p2p'], [52, '#feature-encode'], [55.5, '#feature-devices'],
+ [58.3, '#more-game'], [60, '#more-art'], [61.8, '#more-photos'],
+ [63.6, '#more-movie'], [68, '#end-label'], [71.5, '#end-label'],
+ ]) {
+ seek(time);
+ const label = document.querySelector(`${selector} > .scene-label`);
+ const matrix = el('film-art').getCTM().inverse().multiply(label.getCTM());
+ const baseline = label.getStartPositionOfChar(0).matrixTransform(matrix);
+ const style = getComputedStyle(label);
+ assert(Math.abs(baseline.x-64)<.01 && Math.abs(baseline.y-64)<.01, `Scene label moved: ${label.textContent}`);
+ assert(Math.abs(matrix.a-1)<.01 && Math.abs(matrix.b)<.01 && Math.abs(matrix.c)<.01 && Math.abs(matrix.d-1)<.01, `Scene label rotated or scaled: ${label.textContent}`);
+ assert(style.fontSize==='19px' && style.fontWeight==='650' && Math.abs(parseFloat(style.letterSpacing)-1.9)<.01, `Scene label typography differs: ${label.textContent}`);
+ }
+ el('language').click();
+ }
+
+ const bounds = (node) => {
+ const b = node.getBBox(), m = el('film-art').getScreenCTM().inverse().multiply(node.getScreenCTM());
+ const points = [[b.x,b.y],[b.x+b.width,b.y],[b.x,b.y+b.height],[b.x+b.width,b.y+b.height]]
+ .map(([x,y]) => new DOMPoint(x,y).matrixTransform(m));
+ return {left:Math.min(...points.map(p=>p.x)),right:Math.max(...points.map(p=>p.x))};
+ };
+ for (const [time,title,object] of [
+ [48.8, 'p2p-type', '#p2p-source, #p2p-viewer'],
+ [52, 'encode-type', '#encode-picture, #encode-audience'],
+ [55.5, 'devices-type', '#devices-laptop, #devices-tablet, #devices-phone'],
+ [60, 'more-art-type', '#sketch-paper'],
+ // The card frames bound the visible crop; nested scenery extends behind it.
+ [61.8, 'more-photos-type', '#more-photos-picture > svg > g > rect'],
+ [63.6, 'more-movie-type', '#movie-answer-machine'],
+ ]) {
+ seek(time);
+ for (const subject of document.querySelectorAll(object))
+ assert(bounds(el(title)).right + 20 < bounds(subject).left, `Scenario caption must leave room for its main object: ${title}`);
+ }
+ seek(48.8);
+ const link = el('p2p-link'), length = link.getTotalLength();
+ for (let i=0;i<=20;i++) {
+ const point = link.getPointAtLength(length*i/20).matrixTransform(link.getScreenCTM());
+ // The moving marker deliberately follows this line; SVG still hits it at opacity 0.
+ const hit = document.elementsFromPoint(point.x,point.y).find(node=>!el('p2p-packet').contains(node));
+ assert(hit===link, 'The direct connection arrow must remain fully visible between its windows');
+ }
+ seek(59.8);
+ const sketchPose = () => el('sketch-paper').outerHTML + el('more-pencil').outerHTML;
+ const firstSketch = sketchPose();
+ seek(60.2);
+ assert(sketchPose() !== firstSketch, 'The sketch must develop with the film clock');
+ seek(20);
+ seek(59.8);
+ assert(sketchPose() === firstSketch, 'Sketch and pencil must survive seeking in either direction');
+
+ // A separate instance makes the real staged controls observable, while the
+ // presented film iframe keeps its opaque sandbox and non-interactive contract.
+ const demo = document.createElement('iframe');
+ const websiteDemo = document.createElement('iframe');
+ let demoReady = false, websiteReady = false;
+ const ready = event => {
+ if (event.data?.type !== 'piik-film-ui-ready') return;
+ if (event.source===demo.contentWindow) demoReady=true;
+ if (event.source===websiteDemo.contentWindow) websiteReady=true;
+ };
+ window.addEventListener('message',ready);
+ demo.style.cssText = 'position:absolute;left:-10000px;width:1100px;height:740px';
+ demo.src = new URL('./ui/index.html', location.href).href;
+ websiteDemo.style.cssText = demo.style.cssText;
+ websiteDemo.src = new URL('./ui/website.html', location.href).href;
+ document.body.append(demo, websiteDemo);
+ try {
+ await until(() => demoReady && websiteReady, 'The staged App and actual homepage must load');
+ const doc = demo.contentDocument, win = demo.contentWindow;
+ const at = async (scene,local,lang) => {
+ const frame = {type:'piik-film-ui',scene,local,time:({website:2,desktop:3.5,launch:4.5,share:6,invite:13}[scene])*BAR+local,lang};
+ const target = scene === 'website' ? websiteDemo : demo;
+ target.contentWindow.postMessage(frame, '*');
+ await settle();
+ const pointer = target.contentDocument.getElementById('cursor'), box = pointer.getBoundingClientRect();
+ return {x:box.x,y:box.y,pan:scene==='website'?0:new DOMMatrix(doc.getElementById('camera').style.transform).f,visible:!pointer.hidden && Number(pointer.style.opacity)>.05};
+ };
+ for (const lang of ['zh-CN','en']) {
+ await at('website',0,lang);
+ const homepage = websiteDemo.contentDocument;
+ assert(homepage.documentElement.lang === lang && homepage.defaultView.scrollY === 0, 'The opening must show the actual homepage in the film language');
+ const downloaded = await at('website',4.5*BEAT,lang);
+ const downloadButton = homepage.querySelector('#download .download-button').getBoundingClientRect();
+ assert(homepage.defaultView.scrollY > 1000 && downloaded.visible &&
+ downloaded.x >= downloadButton.left && downloaded.x <= downloadButton.right &&
+ downloaded.y >= downloadButton.top && downloaded.y <= downloadButton.bottom && downloadButton.bottom < 740,
+ 'The website must scroll to a visible system download button before clicking');
+ await at('website',0,lang);
+ const downloadedAgain = await at('website',4.5*BEAT,lang);
+ assert(Math.hypot(downloadedAgain.x-downloaded.x, downloadedAgain.y-downloaded.y)<.01, 'The website scroll and click must survive reverse seeking');
+ await at('launch',5*BEAT,lang);
+ assert(doc.querySelector('.lr-room') && doc.body.textContent.includes('9527'), 'Opening Piik must reveal the sample room before the next step');
+ await at('invite',4.5*BEAT,lang);
+ assert(doc.querySelector('#chat-draft').value.includes('/r/9527') && doc.querySelector('.film-chat'), 'The invite must be pasted into an external chat example');
+ await at('invite',7*BEAT,lang);
+ assert(doc.querySelector('.chat-mine').textContent.includes('/r/9527') && !doc.querySelector('#chat-draft').value, 'The chat must show the sent link before friends enter');
+ const beforeViewer = await at('invite',8*BEAT-1/60,lang);
+ const afterViewer = await at('invite',8*BEAT+1/60,lang);
+ assert(Math.abs(beforeViewer.pan-afterViewer.pan)<2, 'The camera must return smoothly before the viewer joins');
+ for (const [scene,beat,selector] of [
+ ['desktop',2.5,'#desktop-app'],
+ ['launch',1.5,'[role="radio"]'], ['launch',4,'button[type="submit"]'],
+ ['share',1.5,'.lr-entry-action button'], ['share',4,'.lr-source-option'],
+ ['invite',1.5,'.lr-invite-url'], ['invite',4,'#chat-draft'], ['invite',6,'#chat-send'],
+ ]) {
+ const p = await at(scene,beat*BEAT,lang);
+ const element = doc.querySelectorAll(selector)[selector==='[role="radio"]'?1:0];
+ const target = selector==='.lr-invite-url' ? element.closest('.lr-row').querySelector('button') : element;
+ const b = target.getBoundingClientRect();
+ assert(p.visible && p.x>=b.left && p.x<=b.right && p.y>=b.top && p.y<=b.bottom, 'Clicks must land on visible controls');
+ }
+ for (const [scene,moment] of [
+ ['launch',1.75*BEAT], ['launch',2*BEAT], ['launch',3.5*BEAT],
+ ['share',1.75*BEAT], ['share',2.25*BEAT], ['share',3.5*BEAT],
+ ['invite',1.75*BEAT], ['invite',3*BEAT], ['invite',4*BEAT], ['invite',4.5*BEAT], ['invite',6.25*BEAT],
+ ]) {
+ let previous;
+ for (const offset of [-2,-1,0,1,2]) {
+ const p = await at(scene,moment+offset/60,lang);
+ assert(p.visible, `The cursor must remain visible across ${scene} at ${moment.toFixed(3)}s (${offset} frames)`);
+ if (previous) assert(Math.hypot(p.x-previous.x,p.y-previous.y)<30, 'The cursor must not teleport between controls');
+ previous=p;
+ }
+ await at('launch',0,lang);
+ const revisited=await at(scene,moment+2/60,lang);
+ assert(Math.hypot(revisited.x-previous.x,revisited.y-previous.y)<.01, 'Cursor paths must not depend on playback history');
+ }
+ }
+ } finally { window.removeEventListener('message',ready); demo.remove(); websiteDemo.remove(); }
+
+ el('capture').click();
+ await settle();
+ assert(document.body.classList.contains('fullscreen') && el('transport').checkVisibility(), 'Fullscreen must retain touch playback controls');
+ const exitBounds = el('capture').getBoundingClientRect();
+ assert(exitBounds.top >= 0 && exitBounds.bottom <= innerHeight, 'Exit fullscreen must remain within reach');
+ el('capture').click();
+ await settle();
+ assert(!document.body.classList.contains('fullscreen'), 'The fullscreen button must also exit');
+
+ // The README img uses native SVG/CSS, not the film's JavaScript renderer.
+ // Check shared poses at sampled frames and that only one activity is visible.
+ const hero = document.createElement('iframe');
+ hero.style.cssText = 'position:absolute;left:-10000px;width:900px;height:590px';
+ const loaded = new Promise(resolve => { hero.onload = resolve; });
+ hero.src = new URL('../assets/living-room.svg', location.href).href;
+ document.body.append(hero);
+ try {
+ await loaded;
+ const {HERO_KINDS,HERO_CUT,heroFrame} = await import('../assets/activities.js');
+ const doc = hero.contentDocument, win = hero.contentWindow;
+ assert(!doc.getElementById('montage-cheer'), 'The homepage and README hero must omit the film reaction caption');
+ const animations = doc.getAnimations();
+ assert(animations.length > 0, 'Run this check with normal motion enabled');
+ for (const [index,kind] of HERO_KINDS.entries()) {
+ for (const animation of animations) { animation.pause(); animation.currentTime = (index+.5)*HERO_CUT*1000; }
+ const shown = HERO_KINDS.filter(name=>win.getComputedStyle(doc.getElementById('activity-'+name)).opacity==='1');
+ assert(shown.length===1 && shown[0]===kind, `The hero must show only ${kind}`);
+ assert(win.getComputedStyle(doc.getElementById('hero-gamepad')).opacity==='1' && doc.querySelectorAll('#hero-gamepad .game-hand').length===2, 'The original controller and floating hands must stay visible throughout the activity loop');
+ for (const [id,style] of Object.entries(heroFrame(kind,.5))) {
+ const actual = win.getComputedStyle(doc.getElementById(id));
+ if (style.opacity !== undefined) assert(Math.abs(Number(actual.opacity)-Number(style.opacity))<.01, `Hero visibility differs: ${id}`);
+ if (style.transform) {
+ const a=new DOMMatrix(actual.transform), b=new DOMMatrix(style.transform);
+ assert(['a','b','c','d','e','f'].every(key=>Math.abs(a[key]-b[key])<.03), `Hero pose differs: ${id}`);
+ }
+ }
+ }
+ for(const time of Array.from({length:HERO_KINDS.length+1},(_,i)=>i*HERO_CUT*1000)) {
+ for(const animation of animations) animation.currentTime=time;
+ const shown=HERO_KINDS.filter(kind=>win.getComputedStyle(doc.getElementById('activity-'+kind)).opacity==='1');
+ assert(shown.length===1 && shown[0]===HERO_KINDS[(time/(HERO_CUT*1000))%HERO_KINDS.length], 'Hero cuts must not show a blank or overlapping frame');
+ }
+ win.location.hash='still';
+ await settle();
+ assert(doc.getAnimations().length===0, 'The still image must stop every decorative animation');
+ assert(win.getComputedStyle(doc.getElementById('activity-rpg')).opacity==='1', 'The still image must retain a useful game scene');
+ } finally { hero.remove(); }
+
+ // Use the real audio element and server: a muted-only check misses broken
+ // byte-range hosting that resets the film to zero while scrubbing with sound.
+ seek(2);
+ el('sound').click();
+ el('play').click();
+ await until(() => !media.paused && media.currentTime >= 2, 'The soundtrack must start at the selected position');
+ for (const target of [25, 8, 41]) {
+ seek(target);
+ await until(() => !media.seeking && media.currentTime >= target, 'Audible seeking must reach the selected position');
+ assert(media.currentTime < target + 1 && playing(), 'Audible seeking must continue from the selected position');
+ }
+ el('play').click();
+ seek(17);
+ el('play').click();
+ await until(() => !media.seeking && media.currentTime >= 17, 'A paused seek must resume at the selected position');
+ assert(media.currentTime < 18, 'Resume must not return to the previous audio position');
+ el('play').click();
+ el('sound').click();
+
+ // Hold two native play promises: a cancelled attempt must not mute its successor.
+ const nativePlay = media.play;
+ const pending = [];
+ Object.defineProperty(media, 'paused', {
+ configurable: true,
+ get: () => false,
+ });
+ media.play = () => new Promise((resolve, reject) => pending.push({ resolve, reject }));
+ try {
+ seek(2);
+ el('sound').click();
+ el('play').click();
+ assert(pending.length === 1, 'An audible start must call native play');
+ el('play').click();
+ el('play').click();
+ assert(pending.length === 2, 'A new start must own its own play result');
+ pending[0].reject(new DOMException('Cancelled', 'AbortError'));
+ await settle();
+ assert(playing() && el('sound').getAttribute('aria-pressed') === 'true', 'A stale rejection must not mute current playback');
+ pending[1].reject(new DOMException('Blocked', 'NotAllowedError'));
+ await settle();
+ assert(playing() && el('sound').getAttribute('aria-pressed') === 'false', 'A current audio failure must continue the visual film');
+ assert(el('player-status').textContent.length > 0, 'An audio failure must be explained');
+ el('play').click();
+ el('sound').click();
+ el('replay').click();
+ media.currentTime = Number(el('seek').max) - 0.005;
+ media.dispatchEvent(new Event('ended'));
+ pending[2].resolve();
+ await settle();
+ assert(!playing() && position() === Number(el('seek').max), 'Native audio ending must hold the final frame');
+ assert(el('sound').getAttribute('aria-pressed') === 'true', 'Finishing the soundtrack must preserve sound for replay');
+ el('replay').click();
+ Object.defineProperty(media, 'paused', {
+ configurable: true,
+ get: () => true,
+ });
+ media.dispatchEvent(new Event('pause'));
+ pending[3].resolve();
+ await settle();
+ const playLabel = document.documentElement.lang === 'zh-CN' ? '播放' : 'Play';
+ assert(!playing() && el('play').getAttribute('aria-label') === playLabel, 'Native media pause must pause the picture and its controls');
+ } finally {
+ media.play = nativePlay;
+ delete media.paused;
+ if (playing()) el('play').click();
+ media.pause();
+ }
+ assert(document.documentElement.scrollWidth <= innerWidth, 'The page must not overflow horizontally');
+ return {
+ passed: [
+ 'lazy audio',
+ 'muted play',
+ 'pause',
+ 'seek/replay determinism',
+ 'game montage and reaction timing',
+ 'bilingual headline bounds',
+ 'bilingual scene label alignment',
+ 'four benefit cuts and seekable device arrivals',
+ 'scenario composition and seekable sketch',
+ 'website download, desktop launch, chat sending and continuous cursor paths',
+ 'standalone hero montage, shared poses and still image',
+ 'isolated product sequence',
+ 'touch-accessible fullscreen',
+ 'native audible seek/resume',
+ 'twenty viewers',
+ 'download overlay, shared mascot idle/pause/seek and minute formatting',
+ 'download pause and preference round trip',
+ 'language round trip',
+ 'stale play rejection',
+ 'audio failure',
+ 'native ending',
+ 'native media pause',
+ 'page width',
+ ],
+ };
+})();
diff --git a/scripts/client-icons.mjs b/scripts/client-icons.mjs
index a26f74df..c5a550cb 100644
--- a/scripts/client-icons.mjs
+++ b/scripts/client-icons.mjs
@@ -114,7 +114,8 @@ function writeLinuxAssets(packageRoot, entries) {
);
}
-function writeMacAssets(packageRoot, revision, entries) {
+function writeMacAssets(packageRoot, version, revision, entries) {
+ const bundleVersion = version === "development" ? "0.0.0" : version.slice(1);
const bundleRoot = join(packageRoot, "Piik App.app");
const contents = join(bundleRoot, "Contents");
const macos = join(contents, "MacOS");
@@ -136,10 +137,11 @@ function writeMacAssets(packageRoot, revision, entries) {
"<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>",
"<key>CFBundleName</key><string>Piik App</string>",
"<key>CFBundlePackageType</key><string>APPL</string>",
- "<key>CFBundleShortVersionString</key><string>1.0</string>",
+ `<key>CFBundleShortVersionString</key><string>${bundleVersion}</string>`,
"<key>NSScreenCaptureUsageDescription</key><string>Share a screen or application selected by you.</string>",
"<key>NSAudioCaptureUsageDescription</key><string>Share sound from the selected screen or application.</string>",
- `<key>CFBundleVersion</key><string>${revision}</string>`,
+ `<key>CFBundleVersion</key><string>${bundleVersion}</string>`,
+ `<key>PiikSourceRevision</key><string>${revision}</string>`,
"</dict></plist>",
"",
].join("\n"),
@@ -163,12 +165,13 @@ function writeMacAssets(packageRoot, revision, entries) {
export function writeClientPlatformAssets({
packageRoot,
target,
+ version,
revision,
iconPath,
}) {
const entries = readPngEntries(iconPath);
if (target.goos === "linux") writeLinuxAssets(packageRoot, entries);
- if (target.goos === "darwin") writeMacAssets(packageRoot, revision, entries);
+ if (target.goos === "darwin") writeMacAssets(packageRoot, version, revision, entries);
return target.goos === "linux"
? "share/applications/piik-app.desktop"
: target.goos === "darwin"
diff --git a/scripts/client-loopback-gate.ts b/scripts/client-loopback-gate.ts
index f4480552..4f821416 100644
--- a/scripts/client-loopback-gate.ts
+++ b/scripts/client-loopback-gate.ts
@@ -23,7 +23,6 @@ import {
NATIVE_CLIENT_SUBPROTOCOL,
} from "../src/client/native/wire";
-const PAGE_URL = "https://share.bonfire.icu/";
const NATIVE_PROTOCOL = NATIVE_CLIENT_PROTOCOL;
const NATIVE_SUBPROTOCOL = NATIVE_CLIENT_SUBPROTOCOL;
@@ -142,9 +141,11 @@ async function main(): Promise<void> {
}
const browserPath = process.env.CHROME_PATH?.trim();
const clientPath = process.env.PIIK_CLIENT_EXE?.trim();
- if (!browserPath || !clientPath) {
- throw new Error("CHROME_PATH and PIIK_CLIENT_EXE are required");
+ const pageUrl = process.env.PIIK_CLIENT_GATE_SITE_URL?.trim();
+ if (!browserPath || !clientPath || !pageUrl) {
+ throw new Error("CHROME_PATH, PIIK_CLIENT_EXE and PIIK_CLIENT_GATE_SITE_URL are required");
}
+ const pageOrigin = new URL(pageUrl).origin;
const disposableNoSandbox =
process.env.PIIK_CLIENT_GATE_NO_SANDBOX === "true";
const grantLoopback =
@@ -175,7 +176,7 @@ async function main(): Promise<void> {
try {
profile = await mkdtemp(join(tmpdir(), "piik-client-loopback-"));
client = spawn(clientPath, [
- "--site", PAGE_URL,
+ "--site", pageUrl,
"--config", join(profile, "client.json"),
], {
stdio: "pipe",
@@ -216,7 +217,7 @@ async function main(): Promise<void> {
{
permission: { name: "loopback-network" },
setting: "granted",
- origin: PAGE_URL,
+ origin: pageOrigin,
},
undefined,
Date.now() + 5_000,
@@ -230,7 +231,11 @@ async function main(): Promise<void> {
report.localPageError = localResult.error;
report.localPageEvents = localResult.events;
- const hostedPage = await createPage(cdp, PAGE_URL);
+ const hostedPage = await createPage(cdp, pageUrl);
+ // A failed navigation or cross-origin redirect is not LNA rejection evidence.
+ if (await evaluate(cdp, hostedPage, "location.origin", Date.now() + 5_000) !== pageOrigin) {
+ throw new Error("Hosted page did not load at the configured Site origin");
+ }
const hostedResult = await browserHandshake(cdp, hostedPage, endpoint);
report.hostedPageConnected = hostedResult.health &&
hostedResult.responses.join(",") === "ready,pong";
diff --git a/scripts/client-package-targets.test.mjs b/scripts/client-package-targets.test.mjs
deleted file mode 100644
index 89bb34b5..00000000
--- a/scripts/client-package-targets.test.mjs
+++ /dev/null
@@ -1,25 +0,0 @@
-import assert from "node:assert/strict";
-import { test } from "node:test";
-import { CLIENT_PACKAGE_TARGETS, clientGoEnvironment } from "./client-package-targets.mjs";
-
-test("build and license discovery use the same explicit target cgo policy", () => {
- const previous = process.env.CGO_ENABLED;
- try {
- process.env.CGO_ENABLED = "unexpected-inherited-value";
- const settings = CLIENT_PACKAGE_TARGETS.map((target) => {
- const env = clientGoEnvironment(target);
- const pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === "path");
- if (pathKey) assert.equal(env[pathKey], process.env[pathKey]);
- assert.equal(process.env.CGO_ENABLED, "unexpected-inherited-value");
- return [target.id, env.GOOS, env.GOARCH, env.CGO_ENABLED];
- });
- assert.deepEqual(settings, [
- ["windows-amd64", "windows", "amd64", "0"],
- ["linux-amd64", "linux", "amd64", "0"],
- ["darwin-arm64", "darwin", "arm64", "1"],
- ]);
- } finally {
- if (previous === undefined) delete process.env.CGO_ENABLED;
- else process.env.CGO_ENABLED = previous;
- }
-});
diff --git a/scripts/mirror-release.mjs b/scripts/mirror-release.mjs
new file mode 100644
index 00000000..80852f1c
--- /dev/null
+++ b/scripts/mirror-release.mjs
@@ -0,0 +1,105 @@
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { openAsBlob } from "node:fs";
+import { readReleaseArtifacts } from "./release-artifacts.mjs";
+
+const [directory, version, revision, option] = process.argv.slice(2);
+if (option && option !== "--dry-run") {
+ throw new Error("Use mirror-release.mjs <artifacts> <version> <full-SHA> [--dry-run]");
+}
+const { files } = readReleaseArtifacts(directory, version, revision);
+if (files.some((file) => file.size > 100_000_000)) throw new Error("Gitee's 100 MB attachment limit is exceeded");
+const repository = "TNTcraftHIM/Piik";
+const api = `https://gitee.com/api/v5/repos/${repository}`;
+const marker = `<!-- piik-source: ${revision} -->`;
+const token = process.env.GITEE_TOKEN?.trim();
+
+async function request(path, method = "GET", body) {
+ const multipart = body instanceof FormData;
+ const response = await fetch(api + path, {
+ method, redirect: "error", signal: AbortSignal.timeout(multipart ? 180_000 : 20_000),
+ headers: { Accept: "application/json", Authorization: `Bearer ${token}`,
+ ...(!body || multipart ? {} : { "Content-Type": "application/json" }) },
+ body: body ? multipart ? body : JSON.stringify(body) : undefined,
+ });
+ if (response.status === 404 && method === "GET") return null;
+ if (!response.ok) throw new Error(`Gitee ${method} ${path}: HTTP ${response.status}`);
+ return response.json();
+}
+
+// Verify anonymously: credentials are never forwarded to attachment redirects.
+async function verifyDownload(uploaded, file) {
+ const expectedURL = `https://gitee.com/${repository}/releases/download/${version}/${file.name}`;
+ if (uploaded?.size !== file.size || uploaded.browser_download_url !== expectedURL) {
+ throw new Error(`Mirror attachment metadata mismatch: ${file.name}`);
+ }
+ const response = await fetch(expectedURL, { signal: AbortSignal.timeout(180_000) });
+ if (!response.ok || !response.body) throw new Error(`Mirror attachment is not anonymously downloadable: ${file.name}`);
+ const hash = createHash("sha256");
+ let size = 0;
+ for await (const chunk of response.body) {
+ size += chunk.length;
+ if (size > file.size) throw new Error(`Mirror attachment size mismatch: ${file.name}`);
+ hash.update(chunk);
+ }
+ if (size !== file.size || hash.digest("hex") !== file.sha256) {
+ throw new Error(`Mirror attachment checksum mismatch: ${file.name}`);
+ }
+}
+
+if (option === "--dry-run") {
+ console.log(JSON.stringify({ version, revision, files: files.length, bytes: files.reduce((sum, file) => sum + file.size, 0) }));
+} else {
+ if (!token) throw new Error("GITEE_TOKEN must be supplied by the publisher's environment");
+ const source = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/tags/${version}`],
+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }));
+ if (source.draft !== false || source.prerelease !== false || source.tag_name !== version || source.target_commitish !== revision ||
+ source.html_url !== `https://github.com/${repository}/releases/tag/${version}`) {
+ throw new Error("Only an already-published matching GitHub stable release can be mirrored");
+ }
+ // Compare every byte identity with GitHub before creating or changing the mirror.
+ for (const file of files) {
+ const asset = source.assets.find((asset) => asset.name === file.name);
+ if (asset?.state !== "uploaded" || asset.size !== file.size || asset.digest !== `sha256:${file.sha256}`) {
+ throw new Error(`GitHub attachment checksum mismatch or unavailable: ${file.name}`);
+ }
+ }
+ let release = await request(`/releases/tags/${version}`);
+ if (release && (release.tag_name !== version ||
+ (release.prerelease !== false && release.prerelease !== true) ||
+ !release.body?.split(/\r?\n/).includes(marker))) {
+ throw new Error("Existing mirror release belongs to a different or unknown source revision");
+ }
+ const body = `${source.body ?? ""}\n\nSource: https://github.com/${repository}/commit/${revision}\n\n${marker}\n`;
+ if (!release) {
+ const repo = await request("");
+ if (!repo || repo.private || !repo.default_branch) throw new Error("A public initialized Gitee mirror is required");
+ release = await request("/releases", "POST", {
+ tag_name: version, name: source.name || `Piik ${version}`, body, prerelease: true,
+ target_commitish: repo.default_branch,
+ });
+ }
+ if (!Number.isSafeInteger(release.id) || release.id <= 0) throw new Error("Invalid Gitee release identity");
+ const attachments = await request(`/releases/${release.id}/attach_files?per_page=100`);
+ if (!Array.isArray(attachments) || attachments.length >= 100) throw new Error("Unexpected mirror attachment list");
+ for (const file of files) {
+ let uploaded = attachments.find((asset) => asset.name === file.name);
+ if (!uploaded) {
+ if (!release.prerelease) throw new Error("Published mirror is incomplete; publish a corrected new version");
+ const form = new FormData();
+ form.append("file", await openAsBlob(file.path), file.name);
+ uploaded = await request(`/releases/${release.id}/attach_files`, "POST", form);
+ }
+ await verifyDownload(uploaded, file);
+ }
+ // Gitee has no draft API. Its preview flag fences incomplete uploads from checks.
+ if (release.prerelease) {
+ const completed = await request(`/releases/${release.id}`, "PATCH", {
+ tag_name: version, name: source.name || `Piik ${version}`, body, prerelease: false,
+ });
+ if (completed.prerelease !== false || completed.tag_name !== version) {
+ throw new Error("Gitee did not confirm the completed stable mirror");
+ }
+ }
+ console.log(`Verified Gitee mirror ${version} from ${revision} (${files.length} attachments).`);
+}
diff --git a/scripts/package-app-release.mjs b/scripts/package-app-release.mjs
index d396c447..a1133fb4 100644
--- a/scripts/package-app-release.mjs
+++ b/scripts/package-app-release.mjs
@@ -21,6 +21,7 @@ import { fileURLToPath } from "node:url";
import { writeServerLicenseNotices } from "./package-licenses.mjs";
import { tarExecutable } from "./archive-tool.mjs";
import { resetBuildWorkspace } from "./build-workspace.mjs";
+import { buildVersion } from "./release-version.mjs";
// The Hosted deployment target. deploy/release-app.sh runs the archived binary
// as the service user, so the release is always built for linux/amd64, and
@@ -184,6 +185,9 @@ if (relativeOutput === "" || (relativeOutput.split(/[\\/]/)[0] !== ".." && !isAb
if (existsSync(outputRoot)) fail("Output directory must not already exist");
const revision = assertCleanRevision(repositoryRoot);
+const version = buildVersion(repositoryRoot, revision);
+process.env.VITE_PIIK_VERSION = version;
+process.env.VITE_PIIK_REVISION = revision;
if (!existsSync(join(repositoryRoot, "LICENSE"))) fail("Missing release input: LICENSE");
buildClient(repositoryRoot);
@@ -204,7 +208,7 @@ try {
"build",
"-trimpath",
"-ldflags",
- `-s -w -X main.BuildRevision=${revision}`,
+ `-s -w -X main.BuildRevision=${revision} -X main.BuildVersion=${version}`,
"-o",
serverPath,
"./cmd/piik-server",
@@ -246,7 +250,8 @@ try {
compareRecords(records, recordsFor(verifyRoot));
const descriptor = {
- schema: 1,
+ schema: 2,
+ version,
revision,
releaseId,
artifact: artifactName,
diff --git a/scripts/package-client-candidate.mjs b/scripts/package-client-candidate.mjs
index 830150e3..1121d695 100644
--- a/scripts/package-client-candidate.mjs
+++ b/scripts/package-client-candidate.mjs
@@ -323,6 +323,8 @@ if (process.platform !== target.nodePlatform || process.arch !== target.nodeArch
assertOutsideRepository(repositoryRoot, outputRoot);
const revision = run("git", ["rev-parse", "HEAD"], repositoryRoot).toLowerCase();
+const descriptorPath = applicationDescriptor(applicationRoot);
+const { version } = JSON.parse(readFileSync(descriptorPath, "utf8"));
const temporaryRoot = resetBuildWorkspace(repositoryRoot, "client-package", target.id, "candidate");
try {
const tunnelDownload = join(temporaryRoot, target.tunnelAsset);
@@ -355,7 +357,7 @@ try {
const packageRoot = join(temporaryRoot, `piik-app-${target.id}`);
const assembleArguments = [
join(repositoryRoot, "scripts", "assemble-client.mjs"),
- applicationDescriptor(applicationRoot),
+ descriptorPath,
packageRoot,
"--target",
target.id,
@@ -373,8 +375,12 @@ try {
run(tarExecutable(), ["-czf", archive, "-C", packageRoot, "."], repositoryRoot);
const digest = sha256(archive);
writeFileSync(join(outputRoot, `${archiveName}.sha256`), `${digest} ${archiveName}\n`, "ascii");
+ writeFileSync(join(outputRoot, archiveName.replace(/\.tar\.gz$/, ".release.json")),
+ `${JSON.stringify({ schema: 2, version, revision, target: target.id,
+ artifact: archiveName, artifactSha256: digest }, null, 2)}\n`);
process.stdout.write(`${JSON.stringify({
target: target.id,
+ version,
revision,
archive,
sha256: digest,
diff --git a/scripts/publish-release.mjs b/scripts/publish-release.mjs
new file mode 100644
index 00000000..69a30ebf
--- /dev/null
+++ b/scripts/publish-release.mjs
@@ -0,0 +1,73 @@
+import { execFileSync } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+import semver from "semver";
+import { readReleaseArtifacts } from "./release-artifacts.mjs";
+import { releaseNotes } from "./release-notes.mjs";
+
+const [directory, version, revision, option] = process.argv.slice(2);
+if (option && option !== "--dry-run") {
+ throw new Error("Use publish-release.mjs <artifacts> <version> <full-SHA> [--dry-run]");
+}
+const artifacts = readReleaseArtifacts(directory, version, revision);
+const files = artifacts.files.map((file) => file.path);
+if (option === "--dry-run") {
+ process.stdout.write(`${JSON.stringify({ version, revision, targets: artifacts.targets, files: files.length })}\n`);
+} else {
+ const repository = process.env.GITHUB_REPOSITORY || "TNTcraftHIM/Piik";
+ const gh = (...args) => execFileSync("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
+ function verifyTag(required = false) {
+ // A successful empty match is absence; API/authentication errors must fail.
+ const references = JSON.parse(gh("api", `repos/${repository}/git/matching-refs/tags/${version}`));
+ const tag = references.find((reference) => reference.ref === `refs/tags/${version}`);
+ if (!tag) {
+ if (required) throw new Error("Published release tag is missing");
+ return;
+ }
+ let object = tag.object;
+ while (object.type === "tag") {
+ object = JSON.parse(gh("api", `repos/${repository}/git/tags/${object.sha}`)).object;
+ }
+ if (object.type !== "commit" || object.sha !== revision) {
+ throw new Error("Release tag belongs to a different source revision");
+ }
+ }
+ verifyTag();
+ const releases = gh("api", `repos/${repository}/releases?per_page=100`, "--paginate", "--jq",
+ ".[] | {tag_name,target_commitish,draft,prerelease,assets:[.assets[] | {name,state}]} | @json")
+ .trim().split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
+ const existing = releases.find((release) => release.tag_name === version);
+ if (existing) {
+ if (existing.target_commitish !== revision) throw new Error("Existing release belongs to a different source revision");
+ if (!existing.draft) {
+ verifyTag(true);
+ if ([...files].some((path) => !existing.assets.some((uploaded) =>
+ uploaded.name === basename(path) && uploaded.state === "uploaded"))) {
+ throw new Error("Published release is incomplete; publish a new version instead of modifying it");
+ }
+ process.stdout.write(`Release ${version} is already published; left unchanged.\n`);
+ process.exit(0);
+ }
+ } else {
+ const body = releaseNotes(process.cwd(), version, revision, repository);
+ const notes = join(tmpdir(), `piik-release-notes-${randomUUID()}.md`);
+ writeFileSync(notes, body, { flag: "wx" });
+ try {
+ gh("release", "create", version, "--repo", repository, "--target", revision,
+ "--draft", "--title", `Piik ${version}`, "--notes-file", notes);
+ } finally {
+ rmSync(notes);
+ }
+ }
+ // Clobber is limited to our same-revision draft; published versions are never changed.
+ gh("release", "upload", version, "--repo", repository, "--clobber", ...files);
+ const latest = !releases.some((release) => !release.draft && !release.prerelease &&
+ /^v\d+\.\d+\.\d+$/.test(release.tag_name) && semver.valid(release.tag_name) &&
+ semver.gt(release.tag_name, version));
+ verifyTag();
+ gh("release", "edit", version, "--repo", repository, "--draft=false", `--latest=${latest}`);
+ verifyTag(true);
+ process.stdout.write(`Published ${version} from ${revision}.\n`);
+}
diff --git a/scripts/release-artifacts.mjs b/scripts/release-artifacts.mjs
new file mode 100644
index 00000000..41cc8e11
--- /dev/null
+++ b/scripts/release-artifacts.mjs
@@ -0,0 +1,49 @@
+import { createHash } from "node:crypto";
+import { readFileSync, readdirSync } from "node:fs";
+import { basename, join, resolve } from "node:path";
+
+export function readReleaseArtifacts(directory, version, revision) {
+ if (!directory || !/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version ?? "") ||
+ !/^[0-9a-f]{40}$/.test(revision ?? "")) {
+ throw new Error("An artifact directory, stable version and full source SHA are required");
+ }
+ const root = resolve(directory);
+ const files = new Map();
+ const targets = new Set();
+ function asset(name) {
+ if (typeof name !== "string" || basename(name) !== name || !/^[a-zA-Z0-9._-]+$/.test(name)) {
+ throw new Error("Release asset name is invalid");
+ }
+ const path = join(root, name);
+ if (!files.has(name)) {
+ const bytes = readFileSync(path);
+ files.set(name, { name, path, size: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") });
+ }
+ return files.get(name);
+ }
+ for (const name of readdirSync(root).filter((name) => name.endsWith(".release.json"))) {
+ const descriptor = JSON.parse(readFileSync(asset(name).path, "utf8"));
+ if (descriptor.schema !== 2 || descriptor.version !== version || descriptor.revision !== revision) {
+ throw new Error(`Release identity mismatch: ${name}`);
+ }
+ const target = descriptor.target ?? "server";
+ if (targets.has(target)) throw new Error(`Duplicate release target: ${target}`);
+ targets.add(target);
+ if (asset(descriptor.artifact).sha256 !== descriptor.artifactSha256) {
+ throw new Error(`Release artifact checksum mismatch: ${name}`);
+ }
+ if (target === "server") {
+ if (asset(descriptor.manifest).sha256 !== descriptor.manifestSha256) {
+ throw new Error("Server manifest checksum mismatch");
+ }
+ } else if (readFileSync(asset(`${descriptor.artifact}.sha256`).path, "utf8").trim() !==
+ `${descriptor.artifactSha256} ${descriptor.artifact}`) {
+ throw new Error(`App checksum file mismatch: ${target}`);
+ }
+ }
+ const expected = ["server", "windows-amd64", "linux-amd64", "darwin-arm64"];
+ if (targets.size !== expected.length || expected.some((target) => !targets.has(target))) {
+ throw new Error("Publication requires one matching Server and every App target");
+ }
+ return { files: [...files.values()], targets: [...targets] };
+}
diff --git a/scripts/release-notes.mjs b/scripts/release-notes.mjs
new file mode 100644
index 00000000..a473e52d
--- /dev/null
+++ b/scripts/release-notes.mjs
@@ -0,0 +1,51 @@
+import { execFileSync } from "node:child_process";
+import { appendFileSync } from "node:fs";
+import { pathToFileURL } from "node:url";
+import semver from "semver";
+import { isReleaseVersion, stableTags } from "./release-version.mjs";
+
+// The reviewed PR body survives the squash commit. Only its public section is
+// release copy; implementation details and verification logs stay in the PR.
+export function releaseNotes(root, version, revision, repository) {
+ if (!isReleaseVersion(version) || !/^[a-f0-9]{40}$/.test(revision) ||
+ !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) {
+ throw new Error("Release notes require a stable version, full SHA and owner/repository");
+ }
+ // Exclude this release's tag so retrying after publication keeps the same range.
+ const previous = stableTags(root, "--merged", revision).find((tag) => semver.lt(tag, version));
+ const log = execFileSync("git", ["log", "--first-parent", "--reverse", "--format=%H%x00%B%x00",
+ ...(previous ? [`${previous}..${revision}`] : ["-1", revision])], { cwd: root, encoding: "utf8" });
+ const records = log.split("\0");
+ const bodies = [];
+ for (let index = 0; index + 1 < records.length; index += 2) {
+ const sections = records[index + 1].replace(/\r\n/g, "\n").split(/^## /m).slice(1)
+ .filter((section) => section.split("\n", 1)[0].trim() === "Release notes");
+ const body = sections.length === 1
+ ? sections[0].split("\n").slice(1).join("\n").replace(/<!--[\s\S]*?-->/g, "").trim()
+ : "";
+ if (!body || !body.split("\n").some((line) => line.trim() && !/^#{1,6}(\s|$)/.test(line))) {
+ throw new Error(`Commit ${records[index].trim()} needs one nonempty ## Release notes section`);
+ }
+ bodies.push(body);
+ }
+ if (!bodies.length) throw new Error("No release changes found");
+ const url = `https://github.com/${repository}`;
+ const source = previous
+ ? `[完整变更 / Full changelog](${url}/compare/${previous}...${revision})`
+ : `[源代码 / Source](${url}/tree/${revision})`;
+ return `${bodies.join("\n\n")}\n\n---\n\n${source}\n`;
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const [version, revision, option] = process.argv.slice(2);
+ if (option && option !== "--github-summary") {
+ throw new Error("Use release-notes.mjs <version> <full-SHA> [--github-summary]");
+ }
+ const body = releaseNotes(process.cwd(), version, revision,
+ process.env.GITHUB_REPOSITORY || "TNTcraftHIM/Piik");
+ if (option) {
+ if (!process.env.GITHUB_STEP_SUMMARY) throw new Error("GITHUB_STEP_SUMMARY is missing");
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, `## Release notes preview: Piik ${version}\n\n${body}`);
+ }
+ process.stdout.write(body);
+}
diff --git a/scripts/release-version.mjs b/scripts/release-version.mjs
new file mode 100644
index 00000000..fe2cf618
--- /dev/null
+++ b/scripts/release-version.mjs
@@ -0,0 +1,60 @@
+import { execFileSync } from "node:child_process";
+import { appendFileSync } from "node:fs";
+import { pathToFileURL } from "node:url";
+import semver from "semver";
+
+const git = (root, ...args) => execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
+export const isReleaseVersion = (value) => typeof value === "string" &&
+ /^v\d+\.\d+\.\d+$/.test(value) && semver.valid(value) !== null;
+
+export function stableTags(root, ...filter) {
+ return git(root, "tag", ...filter).split("\n").filter(isReleaseVersion).sort(semver.rcompare);
+}
+
+// One input for packagers: a planned CI version, an exact public tag, or a dev build.
+export function buildVersion(root, revision, requested = process.env.PIIK_BUILD_VERSION) {
+ const version = requested || stableTags(root, "--points-at", revision)[0] || "development";
+ if (version === "development") return version;
+ if (!isReleaseVersion(version)) throw new Error("Build version must be vMAJOR.MINOR.PATCH or development");
+ if (git(root, "tag", "--list", version) &&
+ git(root, "rev-parse", `${version}^{commit}`) !== revision) {
+ throw new Error("A release version cannot identify two source revisions");
+ }
+ return version;
+}
+
+export function planRelease(root) {
+ const revision = git(root, "rev-parse", "HEAD");
+ const previous = stableTags(root, "--merged", "HEAD")[0];
+ if (previous && git(root, "rev-parse", `${previous}^{commit}`) === revision) {
+ // A tag may predate its Release. Draft creation itself does not create a tag.
+ return { version: previous, revision, publish: true };
+ }
+ let version = "v1.0.0";
+ if (previous) {
+ // Main contains one squash commit per accepted PR. A rerun includes any
+ // unreleased commits, so a later fix cannot hide an earlier breaking change.
+ const messages = git(root, "log", "--first-parent", "--format=%B%x00", `${previous}..HEAD`).split("\0");
+ const subjects = messages.map((message) => message.trim().split(/\r?\n/, 1)[0]);
+ const breaking = subjects.some((subject) => /^[a-z]+(?:\([^\r\n)]+\))?!: /i.test(subject)) ||
+ messages.some((message) => /^BREAKING[ -]CHANGE: /m.test(message));
+ const feature = subjects.some((subject) => /^feat(?:\([^\r\n)]+\))?: /i.test(subject));
+ version = `v${semver.inc(previous, breaking ? "major" : feature ? "minor" : "patch")}`;
+ }
+ return { version: buildVersion(root, revision, version), revision, publish: true };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const mode = process.argv[2] ?? "build";
+ if (mode !== "plan" && mode !== "build") throw new Error("Use release-version.mjs plan|build [--github-output]");
+ const root = process.cwd();
+ const revision = git(root, "rev-parse", "HEAD");
+ const identity = mode === "plan" ? planRelease(root)
+ : { version: buildVersion(root, revision), revision, publish: false };
+ if (process.argv.includes("--github-output")) {
+ if (!process.env.GITHUB_OUTPUT) throw new Error("GITHUB_OUTPUT is missing");
+ appendFileSync(process.env.GITHUB_OUTPUT,
+ Object.entries(identity).map(([key, value]) => `${key}=${value}\n`).join(""));
+ }
+ process.stdout.write(`${JSON.stringify(identity)}\n`);
+}
diff --git a/scripts/required-project-paths.txt b/scripts/required-project-paths.txt
index 438f6872..3bd4127e 100644
--- a/scripts/required-project-paths.txt
+++ b/scripts/required-project-paths.txt
@@ -1,5 +1,4 @@
AGENTS.md
-CLAUDE.md
CONTRIBUTING.md
LICENSE
README.md
@@ -32,8 +31,16 @@ docs/product/media-quality.md
docs/product/presentation-lifecycle.md
docs/deployment.md
docs/operations/self-hosting.md
+docs/operations/github.md
docs/reference/configuration.md
+docs/reference/naming.md
+docs/reference/engineering.md
+docs/reference/versioning.md
+docs/design/visual-language.md
+docs/design/media-status.md
scripts/package-app-release.mjs
+scripts/release-version.mjs
+scripts/publish-release.mjs
scripts/assemble-client.mjs
scripts/client-icons.mjs
scripts/package-client-candidate.mjs
diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json
new file mode 100644
index 00000000..cb039c7d
--- /dev/null
+++ b/scripts/tsconfig.json
@@ -0,0 +1,39 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "../node_modules/.cache/tsconfig.tools.tsbuildinfo",
+ "target": "ES2023",
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ // Tests import the plain-ESM tooling modules under scripts/.
+ "allowJs": true,
+ "jsx": "react-jsx",
+ "types": ["node", "vitest/globals", "vite/client"],
+ "skipLibCheck": true,
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true
+ },
+ "include": [
+ "../vite.config.ts",
+ "../vitest.config.ts",
+ "../site/film/ui/main.tsx",
+ "../site/film/ui/website.ts",
+ "access-privacy-gate.ts",
+ "browser-local-pool-probe.ts",
+ "client-browser-fanout-gate.ts",
+ "client-media-gate.ts",
+ "client-native-host-gate.ts",
+ "embedded-sfu-gate.ts",
+ "embedded-sfu-page.ts",
+ "client-loopback-gate.ts",
+ "client-local-gate.ts",
+ "client-link-gate.ts",
+ "peer-assisted-benchmark.ts",
+ "../tests"
+ ]
+}
diff --git a/scripts/update-website-hero.mjs b/scripts/update-website-hero.mjs
new file mode 100644
index 00000000..7245138e
--- /dev/null
+++ b/scripts/update-website-hero.mjs
@@ -0,0 +1,57 @@
+import { readFile, writeFile } from 'node:fs/promises';
+import { HERO_KINDS, HERO_CUT, heroFrame, heroMarkup } from '../site/assets/activities.js';
+
+// The image stays self-contained for README/img consumers. Bake the shared
+// activity poses with interpolation between samples.
+const LOOP = HERO_CUT * HERO_KINDS.length, SAMPLES = HERO_CUT * 12;
+const span = 100 / HERO_KINDS.length;
+const round = n => Math.round(n * 1000) / 1000;
+const declaration = style => Object.entries(style).map(([key,value])=>`${key}:${value}`).join(';');
+const tracks = new Map();
+for(const [index,kind] of HERO_KINDS.entries()) {
+ for(let i=0;i<=SAMPLES;i++) {
+ const progress=i/SAMPLES;
+ const frame=heroFrame(kind,progress);
+ const percent=round((index+progress)/HERO_KINDS.length*100);
+ for(const [id,style] of Object.entries(frame)) {
+ if(!tracks.has(id)) tracks.set(id,new Map());
+ tracks.get(id).set(percent,declaration(style));
+ }
+ }
+}
+const initial = Object.assign({},...HERO_KINDS.map(kind=>heroFrame(kind,0)));
+const base = Object.entries(initial).map(([id,style])=>`#${id}{${declaration(style)}}`).join('')+
+ HERO_KINDS.map((kind,i)=>`#activity-${kind}{opacity:${i===0?1:0}}`).join('');
+const keyframes = [...tracks].map(([id,track])=>{
+ const entries=[...track];
+ // Keep both ends of a hold, but remove its repeated samples. Reset at the
+ // loop boundary, after the last visible frame, instead of fading into it.
+ if(!track.has(0)) entries.unshift([0,entries[0][1]]);
+ if(!track.has(100)) entries.push([100,entries.at(-1)[1]]);
+ else entries.splice(-1,1,[99.999,entries.at(-1)[1]],[100,declaration(initial[id])]);
+ const compact=entries.filter((entry,i)=>i===0||i===entries.length-1||entry[1]!==entries[i-1][1]||entry[1]!==entries[i+1][1]);
+ return `@keyframes ${id}{${compact.map(([p,value])=>`${p}%{${value}}`).join('')}}`;
+}).join('');
+const cuts = HERO_KINDS.map((kind,i)=>{
+ const points=new Map([[0,0],[i*span,1],[(i+1)*span,0],[100,0]]);
+ return `@keyframes activity-${kind}{${[...points].sort((a,b)=>a[0]-b[0]).map(([p,value])=>`${p}%{opacity:${value}}`).join('')}}`;
+}).join('');
+// The host keeps its controller while the screen cycles through activities.
+const animated = [...tracks.keys(),...HERO_KINDS.map(kind=>'activity-'+kind)];
+const animation = [...tracks.keys()].map(id=>`#${id}{animation:${id} ${LOOP}s linear infinite}`).join('')+
+ HERO_KINDS.map(kind=>`#activity-${kind}{animation:activity-${kind} ${LOOP}s steps(1,end) infinite}`).join('');
+const loopMarkup = `${heroMarkup()}<style>${base}
+ @media(prefers-reduced-motion:no-preference){${animation}}
+ ${animated.map(id=>`:root:target #${id}`).join(',')}{animation:none}
+ ${keyframes}${cuts}</style>`;
+
+const path = new URL('../site/assets/living-room.svg', import.meta.url);
+const before = await readFile(path, 'utf8');
+const start = '<!-- Shared activities: generated by scripts/update-website-hero.mjs. -->';
+const end = '<!-- /Shared activities -->';
+const content = `${start}\n <svg x="284" y="111" width="370" height="190" viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice" stroke="none" font-family="ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif">${loopMarkup}</svg>\n ${end}`;
+const after = before.replace(new RegExp(`${start}[\\s\\S]*?${end}`), content);
+if (!before.includes(start) || !before.includes(end)) throw new Error('Missing hero activity markers');
+if (process.argv.includes('--check')) {
+ if (before !== after) throw new Error('Run node scripts/update-website-hero.mjs to refresh the hero');
+} else if (before !== after) await writeFile(path, after);
diff --git a/site/assets/activities.js b/site/assets/activities.js
new file mode 100644
index 00000000..5686e2b0
--- /dev/null
+++ b/site/assets/activities.js
@@ -0,0 +1,137 @@
+import { gameMarkup, poses } from './game.js';
+import { sketchMarkup } from './sketch.js';
+
+// Original screen content shared by the film and the standalone room image.
+const INK = '#203037', PAPER = '#faf5e7';
+export const HERO_KINDS = ['rpg', 'drawing', 'photos', 'movie'];
+export const HERO_CUT = 5;
+
+export function photoMarkup() {
+ return `<rect width="1600" height="900" fill="${INK}"/>
+ <path d="M148 683q-49-268 192-414t595-108 502 112" fill="none" stroke="#6a8b80" stroke-width="5" stroke-dasharray="11 16"/>
+ <path d="m1339 258 14 29 31 4-23 22 6 31-28-15-28 15 5-31-22-22 31-4Z" fill="#f3cc68"/>
+ <path d="m236 696 153 23-21 117-153-23Z" fill="#df9c6c"/>
+ <path d="m255 726 86 13m-90 10 70 11m-74 11 81 12" stroke="${INK}" stroke-width="6" opacity=".55"/>
+ <text x="267" y="807" transform="rotate(9 267 807)" fill="${INK}" font-family="ui-monospace,monospace" font-size="25" font-weight="700">9527</text>
+ <g transform="translate(206 72) rotate(-12 410 300)">
+ <rect x="11" y="15" width="820" height="645" rx="12" fill="#111f26" opacity=".35"/>
+ <rect width="820" height="645" rx="12" fill="${PAPER}"/>
+ <svg x="24" y="24" width="772" height="516" viewBox="0 0 772 516" overflow="hidden">
+ <rect width="772" height="516" fill="#b7d6d2"/>
+ <circle cx="600" cy="106" r="62" fill="#f3cc68"/>
+ <path d="M-45 375 197 94 381 327 529 157 826 455v100H-45Z" fill="#85a99a"/>
+ <path d="m124 178 73-84 85 107-46-13-38 26-29-32Z" fill="${PAPER}"/>
+ <path d="M-43 504 185 320 365 384 486 268 833 473v96H-43Z" fill="#557f70"/>
+ <path d="M-60 438q178-51 316 11t296-4 268 21v90H-60Z" fill="#8caa79"/>
+ <path d="m0 474 176-3 55-63 203-1 74 91 267-9v50H0Z" fill="#c9c399"/>
+ <g transform="translate(275 351) rotate(-5)"><path d="M-29 62q0-70 29-70t29 70Z" fill="#8ebbd6"/><circle cy="-33" r="23" fill="#8ebbd6"/><path d="M-29-45q29-39 58 0Z" fill="#e9d2a0"/><path d="M-38-43h76" stroke="#c6a774" stroke-width="8" stroke-linecap="round"/><path d="M-7-31v3m14-3v3" stroke="${INK}" stroke-width="4" stroke-linecap="round"/></g>
+ <g transform="translate(348 365) rotate(9)"><path d="M-27 53q0-60 27-60t27 60Z" fill="#d6958c"/><circle cy="-31" r="22" fill="#d6958c"/><path d="M-8-30v3m15-3v3" stroke="${INK}" stroke-width="4" stroke-linecap="round"/><circle cx="45" cy="-40" r="7" fill="#d6958c"/><path d="m40-45 4-11m5 14 9-5" stroke="#d6958c" stroke-width="6" stroke-linecap="round"/></g>
+ <g transform="translate(138 437) rotate(22)"><path d="M-22 45q0-52 22-52t22 52Z" fill="#e8bf6c"/><circle cy="-26" r="19" fill="#e8bf6c"/><path d="m-7-28 4 3m8-1 4-3" stroke="${INK}" stroke-width="3" stroke-linecap="round"/><path d="M26-5 10 9 44 45" fill="none" stroke="#6c7052" stroke-width="5" stroke-linecap="round"/><circle cx="10" cy="9" r="6" fill="#e8bf6c"/></g>
+ <path d="m-5 482 44-57-9 66 28-33-12 65m621-6 9-51 15 44 16-22 3 50" fill="#355e50"/>
+ </svg>
+ <path d="M61 580h226m-225 16h146" stroke="#b2b5a3" stroke-width="6" stroke-linecap="round"/>
+ <text x="725" y="602" fill="#597b69" font-family="ui-monospace,monospace" font-size="36" font-weight="700">01</text>
+ <path d="m319-7 155 8-10 42-153-9Z" fill="#d7b179" opacity=".9"/>
+ </g>
+ <g transform="translate(644 245) rotate(9 360 255)">
+ <rect x="12" y="14" width="720" height="562" rx="12" fill="#111f26" opacity=".3"/>
+ <rect width="720" height="562" rx="12" fill="${PAPER}"/>
+ <svg x="24" y="24" width="672" height="440" viewBox="0 0 672 440" overflow="hidden">
+ <rect width="672" height="440" fill="#b9d4d8"/>
+ <path d="M0 228h672v212H0Z" fill="#6f9d9f"/>
+ <path d="M0 246h83m25 17h91m52-20h69m44 5h112m19 21h51m53-23h73" stroke="#dbe8dc" stroke-width="5" stroke-linecap="round"/>
+ <svg width="328" height="440" viewBox="0 0 328 440" overflow="hidden">
+ <path d="M-37 471q10-118 78-173 28-23 28-73-3-49 37-62 49-18 82 11 24 22 27 60l-3 53q34 53 46 184Z" fill="#faf5e7"/>
+ <path d="M-30 414q29-55 91-63 60-6 89 104H-30Z" fill="#8fa8aa"/>
+ <path d="M14 391q27-28 55-22m-69 46q31-24 67-21" fill="none" stroke="#64878b" stroke-width="5" stroke-linecap="round"/>
+ <path d="M178 221q56-6 100 32l-15 17q-39-24-84-22Z" fill="#e2b64c"/>
+ <path d="m183 260 78 30q-34 10-71-4Z" fill="#c6993b"/>
+ <path d="M183 245q49-1 83 20" fill="none" stroke="#657064" stroke-width="4"/>
+ <circle cx="160" cy="201" r="11" fill="#e0ba57"/><circle cx="160" cy="201" r="5" fill="${INK}"/>
+ <path d="m123 188 10-3m-24 22 10 1m-24 18 12 4m-13 19 11 2" stroke="#b7c6ba" stroke-width="3" stroke-linecap="round"/>
+ <path d="M39 21h233q20 0 20 20v62q0 20-20 20H115l-29 28 5-28H39q-20 0-20-20V41q0-20 20-20Z" fill="#faf5e7"/>
+ <circle cx="153" cy="71" r="25" fill="#60868b"/><ellipse cx="153" cy="71" rx="51" ry="11" transform="rotate(-24 153 71)" fill="none" stroke="#e0b858" stroke-width="7"/>
+ <path d="m224 43 3 8 8 3-8 3-3 8-3-8-8-3 8-3Zm-127-1 2 5 5 2-5 2-2 5-2-5-5-2 5-2Z" fill="#60868b"/>
+ </svg>
+ <rect x="328" width="16" height="440" fill="#faf5e7"/>
+ <svg x="344" width="328" height="440" viewBox="0 0 328 440" overflow="hidden">
+ <path d="M-44 471q0-110 77-143 31-14 37-73l29-68 128 51-4 81q70 32 89 152Z" fill="#9cafb0"/>
+ <path d="M50 291q21-23 22-62-3-47 29-68 36-24 73-8 41 17 40 71l-2 50q-64-19-89 5-41 38-73 12Z" fill="#faf5e7"/>
+ <path d="M204 211q53 0 99 31l-7 13q-49-22-93-19Z" fill="#e2b64c"/>
+ <path d="m205 247 92 23q-31 10-87-6Z" fill="#c6993b"/>
+ <path d="M212 231q44 1 85 18" fill="none" stroke="#657064" stroke-width="4"/>
+ <circle cx="185" cy="198" r="10" fill="#e0ba57"/><circle cx="185" cy="198" r="5" fill="${INK}"/>
+ <path d="M79 315q69 3 91 70m-149-27q77 4 98 82m45-95q55 22 60 83" fill="none" stroke="#6e8a8f" stroke-width="6" stroke-linecap="round"/>
+ <path d="M67 20h197q22 0 22 22v61q0 22-22 22h-47l-20 29-5-29H67q-22 0-22-22V42q0-22 22-22Z" fill="#faf5e7"/>
+ <g transform="translate(167 75) rotate(-8)">
+ <path d="M-22 2v-33m12 31v-42m12 42v-32m12 32v-39m12 38v-27" stroke="#e1b449" stroke-width="9" stroke-linecap="round"/>
+ <path d="m-35-4 10 44q24 9 46 0l11-44q-35 13-67 0Z" fill="#df8a57"/><circle cy="23" r="7" fill="#faf5e7"/>
+ </g>
+ </svg>
+ </svg>
+ <path d="M60 501h181m-181 17h114" stroke="#b2b5a3" stroke-width="6" stroke-linecap="round"/>
+ <text x="625" y="523" fill="#597b69" font-family="ui-monospace,monospace" font-size="36" font-weight="700">02</text>
+ <path d="m663-8 59 66-34 24-57-66Z" fill="#d7b179" opacity=".9"/>
+ </g>`;
+}
+
+export function movieMarkup(answerId) {
+ return `<rect width="1600" height="900" fill="#293e50"/>
+ <circle cx="1220" cy="387" r="302" fill="#516d76"/>
+ <path d="M1108 105a298 298 0 0 1 403 331" fill="none" stroke="#83938a" stroke-width="2"/>
+ ${[150,365,632,859,1042,1491].map((x,i)=>`<path d="M${x} ${107+i%3*66}v10m-5-5h10" stroke="#b5c9c1" stroke-width="3" stroke-linecap="round"/>`).join('')}
+ <path d="M0 631 244 465 415 579 681 425 911 586 1211 466 1600 589v311H0Z" fill="#385661"/>
+ <path d="M0 728 312 650 594 700 859 616 1142 740 1600 644v256H0Z" fill="#233a47"/>
+ <path d="M837 805h727l-22-38H868Z" fill="#91a499"/>
+ <path d="M870 763h670l-24-37H902Z" fill="#a4b0a0"/>
+ <path d="M904 722h610l-29-38H936Z" fill="#bbc0a5"/>
+ <path d="M938 681h545l-25-38H970Z" fill="#d2ccb0"/>
+ <g id="${answerId}-machine">
+ <path d="m1112 581-68 67h321l-77-67Z" fill="#b69360"/>
+ <path d="m1164 478-42 132h155l-29-121Z" fill="#a48150"/>
+ <path d="m1137 535 11 66 19-42 29-2 45 54 9-84Z" fill="#354851"/>
+ <path d="m999 176 52-45 424 43q17 2 15 19l-28 290-56 53Z" fill="#a7804d"/>
+ <path d="m1001 176 50-45 422 44-50 46Z" fill="#efd78f"/>
+ <path d="M1009 176 1420 219q15 1 13 18l-26 294q-2 16-18 14L987 499q-17-2-16-20l22-287q1-18 16-16Z" fill="#d6ae65"/>
+ <path d="m1010 194 399 42-22 289-397-44Z" fill="#e6c580"/>
+ <path d="M1067 285 1349 314l-12 139-282-30Z" fill="#263d43"/>
+ <path d="m1077 297 258 27-8 113-260-28Z" fill="#365654"/>
+ <path d="m1016 241 76 8m235 25 65 7m-376 209 58 6m192 21 77 8" stroke="#b49155" stroke-width="5" stroke-linecap="round"/>
+ <path d="m1456 225-19 213m6-160-12 134" stroke="#806843" stroke-width="6" stroke-linecap="round"/>
+ <circle cx="1304" cy="487" r="6" fill="#9bba93"/><circle cx="1327" cy="490" r="6" fill="#9bba93"/><circle cx="1350" cy="493" r="6" fill="#9bba93"/>
+ <g id="${answerId}" transform="translate(1202 368) rotate(6)" fill="none" stroke="#f3d786" stroke-width="15" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M-51-42-80 13h59m-14-55v89M4-23q0-26 27-26t27 24q0 13-16 27L7 42h54"/>
+ </g>
+ </g>
+ ${[[907,753,'#97bbad'],[1031,784,'#d69883'],[1410,738,'#a6b9cf'],[1514,790,'#d7bb7c']].map(([x,y,colour],i)=>`<g transform="translate(${x} ${y}) rotate(${i%2?-7:6})"><path d="M-14 45q0-37 14-37t14 37Z" fill="${colour}"/><circle cy="-7" r="10" fill="${colour}"/><path d="M-4-8v2m8-2v2" stroke="#263b43" stroke-width="2" stroke-linecap="round"/></g>`).join('')}
+ <path d="M0 28h1600M0 873h1600" stroke="#152b3b" stroke-width="56"/>`;
+}
+
+export function movieAnswerPose(progress) {
+ const p = Math.min(1, Math.max(0, progress)/.36), reveal = 1-(1-p)**3;
+ return `translate(1202px,${368+12*(1-reveal)}px) rotate(6deg) scale(${.92+.08*reveal},${.08+.92*reveal})`;
+}
+
+
+export function heroMarkup() {
+ return `<g id="activity-rpg">${gameMarkup('hero-rpg')}</g>
+ <g id="activity-drawing">
+ <rect width="1600" height="900" fill="#f3cc68"/>
+ <path d="M-130 750Q220-60 600 580T1720 300" fill="none" stroke="#f47843" stroke-width="190"/>
+ <g id="hero-paper"><g transform="translate(490 85) rotate(8 310 360)">${sketchMarkup('hero-sketch')}</g></g>
+ <g id="hero-pencil"><path d="M-11-255h22v217l-11 38-11-38Z" fill="${INK}"/><path d="m-11-38 11 38 11-38Z" fill="#d6b68b"/><path d="M-3-10 0 0 3-10Z" fill="${INK}"/><path d="M-4-240v188" stroke="${PAPER}" stroke-width="3"/></g>
+ </g>
+ <g id="activity-photos"><rect width="1600" height="900" fill="${INK}"/><g id="hero-photos">${photoMarkup()}</g></g>
+ <g id="activity-movie"><rect width="1600" height="900" fill="#324458"/>${movieMarkup('hero-answer')}</g>`;
+}
+
+// The generator samples this score into CSS, so README images need no script.
+export function heroFrame(kind, progress) {
+ if (kind === 'rpg') return Object.fromEntries(Object.entries(poses(6.8+progress*3.45)).map(([id,transform])=>['hero-rpg-'+id,{transform}]));
+ if (kind === 'drawing') return {
+ 'hero-paper': {transform:`translate(0px,${6*Math.sin(progress*Math.PI*2)}px)`},
+ 'hero-pencil': {transform:`translate(${1160+18*Math.sin(progress*Math.PI*2)}px,${660+10*Math.cos(progress*Math.PI*2)}px) rotate(${28+3*Math.sin(progress*Math.PI*2)}deg)`},
+ };
+ if (kind === 'photos') return {'hero-photos':{transform:`translate(800px,450px) scale(${.97+progress*.045}) translate(-800px,-450px)`}};
+ return {'hero-answer':{transform:movieAnswerPose(progress)}};
+}
diff --git a/site/assets/brand.css b/site/assets/brand.css
new file mode 100644
index 00000000..b0f65c8d
--- /dev/null
+++ b/site/assets/brand.css
@@ -0,0 +1,25 @@
+.identity { display:flex; gap:11px; align-items:center; text-decoration:none; font-size:32px; font-weight:800; letter-spacing:-.065em; line-height:1; color:inherit; }
+.identity .mascot { width:37px; height:37px; overflow:visible; }
+.identity-dot { color:#e4572e; }
+.identity .mascot-face,.identity .mascot-eye-open,.identity .mascot-sparkles { transform-box:fill-box; transform-origin:center; }
+@media (prefers-reduced-motion:no-preference) {
+ .identity .mascot-shell > * { stroke-dasharray:1; animation:brand-draw .38s cubic-bezier(.45,.05,.35,1) both; }
+ .identity .mascot-antenna { animation-duration:.26s; animation-delay:.26s; }
+ .identity .mascot-feet { animation-duration:.22s; animation-delay:.36s; }
+ .identity .mascot-face { animation:brand-face .18s ease-out .5s both; }
+ .identity .mascot-eye-open { animation:brand-open 1.6s ease-in-out both; }
+ .identity .mascot-eye-wink { animation:brand-wink 1.6s ease-in-out both; }
+ .identity .mascot-sparkles { animation:brand-sparkle 1.6s cubic-bezier(.3,1.45,.45,1) both; }
+}
+@keyframes brand-draw { from { stroke-dashoffset:1; } to { stroke-dashoffset:0; } }
+@keyframes brand-face { from { opacity:0; transform:scale(.35); } to { opacity:1; transform:scale(1); } }
+@keyframes brand-open { 0%,34% { opacity:1; } 38%,100% { opacity:0; } }
+@keyframes brand-wink { 0%,34% { opacity:0; } 38%,100% { opacity:1; } }
+@keyframes brand-sparkle {
+ 0%,42% { opacity:0; transform:translate(-1px,2px) scale(.12) rotate(-20deg); }
+ 48% { opacity:1; transform:translate(0,0) scale(.85); }
+ 60% { opacity:1; transform:translate(5px,-5px) scale(1) rotate(18deg); }
+ 74% { opacity:.35; transform:translate(9px,-9px) scale(.55) rotate(34deg); }
+ 82%,100% { opacity:0; transform:translate(12px,-12px) scale(.2) rotate(48deg); }
+}
+@media(max-width:740px) { .identity { font-size:28px; gap:7px; } .identity .mascot { width:30px; height:30px; } }
diff --git a/site/assets/brand.js b/site/assets/brand.js
new file mode 100644
index 00000000..c2594636
--- /dev/null
+++ b/site/assets/brand.js
@@ -0,0 +1,25 @@
+// Shared geometry for the website, film and original demonstration scenes.
+export function mascotMarkup(id, fill = 'none') {
+ return `<g fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
+ <g class="mascot-shell"><rect pathLength="1" x="4" y="8" width="24" height="18" rx="4" fill="${fill}"/>
+ <path class="mascot-antenna" pathLength="1" d="m11 4 5 4 5-4"/>
+ <path class="mascot-feet" pathLength="1" d="M10 29l2-3m10 3-2-3"/></g>
+ <g id="${id}-eyes" class="mascot-face">
+ <circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none"/>
+ <circle id="${id}-open" class="mascot-eye-open" cx="21.35" cy="16.5" r="1.25" fill="currentColor" stroke="none" opacity="0"/>
+ <path id="${id}-wink" class="mascot-eye-wink" pathLength="1" d="M19 17c1.5-1.8 3.2-1.8 4.7 0"/>
+ </g>
+ <g id="${id}-sparkles" class="mascot-sparkles" stroke="#d7982b" stroke-width="1.2" fill="#f4c14d" opacity="0">
+ <path d="m25 11.5 .8 1.9 1.9.8-1.9.8-.8 1.9-.8-1.9-1.9-.8 1.9-.8.8-1.9Z"/>
+ <path d="m25 17.2 .45 1.1 1.1.45-1.1.45-.45 1.1-.45-1.1-1.1-.45 1.1-.45.45-1.1Z"/>
+ </g></g>`;
+}
+
+export function mountBrands() {
+ document.querySelectorAll('[data-brand]').forEach((link, index) => {
+ link.innerHTML = `<svg class="mascot" viewBox="0 0 32 32" aria-hidden="true">${mascotMarkup(`brand-${index}`)}</svg><span>Piik<span class="identity-dot">.</span></span>`;
+ const replay = () => link.getAnimations({ subtree: true }).forEach(animation => { animation.currentTime = 0; });
+ link.addEventListener('pointerenter', replay);
+ link.addEventListener('focus', replay);
+ });
+}
diff --git a/site/assets/favicon.svg b/site/assets/favicon.svg
new file mode 100644
index 00000000..822f8adb
--- /dev/null
+++ b/site/assets/favicon.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
+ <style>svg { color: #22303e; } @media (prefers-color-scheme: dark) { svg { color: #eef4eb; } }</style>
+ <path d="m11 4 5 4 5-4"/>
+ <rect x="4" y="8" width="24" height="18" rx="4"/>
+ <circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none"/>
+ <path d="M19 17c1.5-1.8 3.2-1.8 4.7 0M10 29l2-3m10 3-2-3"/>
+</svg>
diff --git a/site/assets/game.js b/site/assets/game.js
new file mode 100644
index 00000000..9cd8204b
--- /dev/null
+++ b/site/assets/game.js
@@ -0,0 +1,69 @@
+import { mascotMarkup } from './brand.js';
+
+// One original RPG scene and score, shared by the film and generated hero SVG.
+export const GAME_LOOP = 12;
+const INK = '#203037';
+const round = n => Math.round(n * 100) / 100;
+const clamp = n => Math.min(1, Math.max(0, n));
+const ease = n => { const t = clamp(n); return t * t * (3 - 2 * t); };
+
+export function gameMarkup(prefix) {
+ const tree = (x,y,s=1) => `<g transform="translate(${x} ${y}) scale(${s})"><ellipse cy="65" rx="73" ry="23" fill="#31594b" opacity=".18"/><path d="M-7 9h14v57H-7Z" fill="#816947"/><path d="M-69 12q-2-48 38-46 6-66 54-38 43-3 40 40 42 36 4 65-24 24-57 3-46 13-79-24Z" fill="#428570"/><path d="M-58-6q-9-32 29-32 11-45 44-34 37 8 35 35-21 29-47 14-20 36-61 17Z" fill="#72aa7e"/></g>`;
+ return `<style>${Object.entries(poses(6.8)).map(([key,value])=>`#${prefix}-${key}{transform:${value}}`).join('')}</style><rect width="1600" height="900" fill="#bbd596"/>
+ <path d="M0 0h1600v240q-263-98-520-33T480 181 0 280Z" fill="#91b780"/>
+ <path d="M0 567q224-38 290 148t227 185H0Z" fill="#91c9c6"/>
+ <path d="M0 558q224-38 299 158t230 184" fill="none" stroke="#eef0bd" stroke-width="18"/>
+ <g id="${prefix}-water" fill="none" stroke="#d4ece0" stroke-width="5" stroke-linecap="round"><path d="M33 690h102m-75 60h109m50 90h111M28 845h76"/></g>
+ <path d="M436 934q78-205 231-276t386-179 230-229" fill="none" stroke="#d7cc99" stroke-width="94"/>
+ <path d="M436 934q78-205 231-276t386-179 230-229" fill="none" stroke="#e9dfb1" stroke-width="65"/>
+ <g fill="#a3bd7c">${[[391,330,230,100],[740,167,220,72],[1110,740,310,90]].map(([x,y,rx,ry])=>`<ellipse cx="${x}" cy="${y}" rx="${rx}" ry="${ry}"/>`).join('')}</g>
+ <g fill="none" stroke="#86aa74" stroke-width="5" stroke-linecap="round">${[[330,400],[580,302],[910,699],[1080,643],[715,786],[1440,566],[469,626]].map(([x,y])=>`<path d="m${x} ${y} -5-12m11 11 5-15m7 18 6-9"/>`).join('')}</g>
+ <g transform="translate(1240 276)"><ellipse cy="83" rx="150" ry="32" fill="#31594b" opacity=".16"/>
+ <path d="M-114 82V-97q0-41 40-41H71q40 0 40 41V82H63V-85H-65V82Z" fill="#758d83"/>
+ <path d="M-105 67V-102q0-26 29-26H73q29 0 29 26v24H-105Z" fill="#b5c6aa"/>
+ <path d="M-63-78H63V74H-63Z" fill="#355e56"/>
+ <path d="m0-111 11 15-11 15-11-15Z" fill="#e9dfb1"/>
+ <path d="m-104 8 35 1m35-125 4 36m73-33-7 36m68 6-35 2" stroke="#607f73" stroke-width="4"/>
+ <path d="m-122 64 25-3 8 21h-42Zm218 13 17-19 24 13 6 16h-48Z" fill="#9eaf99"/></g>
+ ${tree(172,302,1.35)}${tree(380,155,.92)}${tree(1460,335,1.2)}${tree(969,96,.9)}
+ <g id="${prefix}-flowers" fill="#faf5e7">${[[467,205],[478,222],[745,717],[777,745],[1340,661],[1370,679]].map(([x,y])=>`<path d="m${x} ${y} -7-5 1-7 7 3 5-5 5 4-4 7 6 4-3 5-7-3-5 4-5-5Z"/>`).join('')}</g>
+ <g transform="translate(1028 477)"><ellipse cy="63" rx="87" ry="21" fill="#31594b" opacity=".18"/>
+ <path d="m-66 5 115 29 36-38-114-29Z" fill="#503e36" stroke="#f0c66d" stroke-width="7" stroke-linejoin="round"/>
+ <path d="m-66 5 115 29v47L-66 52Z" fill="#b37748"/><path d="m49 34 36-38v47L49 81Z" fill="#805337"/>
+ <path d="m-45 13v45m70-27v45" stroke="#edbf64" stroke-width="11"/><path d="m-64 49 112 28 35-37" fill="none" stroke="#d9a34f" stroke-width="5"/>
+ <path d="m-29 20 45 12v8l-45-12Z" fill="#996139"/><path d="m-15 20 20 5v24l-20-5Z" fill="#ffe1a0"/><path d="m-7 30 5 1v8l-5-1Z" fill="#815b37"/>
+ <g transform="translate(-29 -33) rotate(14)"><g id="${prefix}-lid">
+ <path d="M0 0h119l-26 46H-27Z" fill="#c58950" stroke="#f0c66d" stroke-width="6" stroke-linejoin="round"/>
+ <path d="M21 1-5 45m97-44L66 45" stroke="#ffe1a0" stroke-width="11"/>
+ <path d="M44 10h29l-12 24H31Z" fill="#a86f45"/>
+ </g></g>
+ </g>
+ <ellipse id="${prefix}-shadow" rx="46" ry="13" fill="#31594b" opacity=".22"/>
+ <g id="${prefix}-player" style="color:${INK}"><g transform="translate(-36 -44) scale(2.4)"><rect x="1" y="13" width="10" height="14" rx="3" fill="#db8755"/>${mascotMarkup(prefix+'-hero','#faf5e7')}</g></g>
+ <g id="${prefix}-treasure"><circle r="53" fill="#fff3bd" opacity=".22"/><path d="m0-31 24 31-24 31-24-31Z" fill="#ffe391" stroke="#bb8537" stroke-width="3"/><path d="m0-31 0 62-24-31Z" fill="#fff5cd"/><path d="m-45-8-12-6m11 37-10 9m102-40 12-6m-11 37 10 9M0-55v-12" stroke="#fff5ce" stroke-width="5" stroke-linecap="round"/></g>
+ ${tree(1435,779,1.6)}${tree(744,952,1.22)}
+ <g transform="translate(63 56)"><rect width="253" height="56" rx="28" fill="${INK}"/><text x="126.5" y="36" text-anchor="middle" font-family="ui-sans-serif,system-ui,sans-serif" font-size="22" font-weight="750" fill="#faf5e7" letter-spacing="2">LITTLE WANDER</text></g>
+ <g transform="translate(1415 94)" stroke="#faf5e7" stroke-width="4" fill="none"><circle r="32"/><path d="m0-19 8 19-8 19-8-19Z" fill="#faf5e7"/><path d="M0-41v-8m41 49h8m-49 41v8m-41-49h-8"/></g>`;
+}
+
+export function poses(time) {
+ const p = time === GAME_LOOP ? 1 : ((time % GAME_LOOP) + GAME_LOOP) % GAME_LOOP / GAME_LOOP;
+ const walk = ease(p / .67), back = ease((p - .88) / .12);
+ const progress = walk * (1-back);
+ const x = 567 + 364 * progress, y = 684 - 169 * progress;
+ const bounce = Math.sin(progress * Math.PI * 22);
+ const reveal = ease((p - .7) / .05) * (1-ease((p - .855) / .025));
+ return {
+ water:`translate(${round(Math.sin(p*Math.PI*2)*14)}px,0px)`,
+ flowers:`skewX(${round(Math.sin(p*Math.PI*2)*3)}deg)`,
+ shadow:`translate(${round(x)}px,${round(y+19)}px)`,
+ player:`translate(${round(x)}px,${round(y-3*Math.abs(bounce))}px) rotate(${round(bounce*3)}deg)`,
+ lid:`scaleY(${round(1-ease((p-.68)/.035)*(1-ease((p-.86)/.025))*1.7)})`,
+ treasure:`translate(1028px,${round(457-105*ease((p-.7)/.08))}px) scale(${round(reveal)})`,
+ };
+}
+
+export function createGame(svg,prefix) {
+ const nodes=Object.fromEntries(Object.keys(poses(0)).map(key=>[key,svg.querySelector(`#${prefix}-${key}`)]));
+ return time=>{ for(const [key,transform] of Object.entries(poses(time))) nodes[key].style.transform=transform; };
+}
diff --git a/site/assets/games.js b/site/assets/games.js
new file mode 100644
index 00000000..05aab06b
--- /dev/null
+++ b/site/assets/games.js
@@ -0,0 +1,350 @@
+import { gameMarkup, poses } from "./game.js";
+import { mascotMarkup } from "./brand.js";
+
+// One set of original game scenes and poses for the film and standalone hero.
+// Renderers supply a time; no vignette owns a clock or incremental state.
+const INK = "#203037",
+ PAPER = "#faf5e7",
+ GOLD = "#f3cc68",
+ CORAL = "#f47843";
+const clamp = (n) => Math.min(1, Math.max(0, n));
+const ease = (n) => {
+ const p = clamp(n);
+ return p * p * (3 - 2 * p);
+};
+const mix = (a, b, p) => a + (b - a) * p;
+export const GAME_KINDS = ["rpg", "fps", "platform", "rts", "moba", "fighting"];
+// Actions are authored over one bar; each surface chooses its playback speed.
+export const GAME_CUT = 240 / 101;
+const round = n => Math.round(n * 100) / 100;
+const hero = (id, size = 3) =>
+ `<g id="${id}" style="color:${INK}"><g transform="scale(${size}) translate(-16 -16)">${mascotMarkup(id + "-tv", PAPER)}</g></g>`;
+const burst = (id, x, y, colour = GOLD) =>
+ `<g transform="translate(${x} ${y})"><g id="${id}" fill="none" stroke="${colour}" stroke-width="8" stroke-linecap="round"><circle r="35"/>${[0, 60, 120, 180, 240, 300].map((a) => `<path d="M49 0h25" transform="rotate(${a})"/>`).join("")}</g></g>`;
+const unit = (id, colour) =>
+ `<g id="${id}"><ellipse cy="19" rx="27" ry="11" fill="${INK}" opacity=".2"/><path d="M-23 11q0-33 23-33t23 33Z" fill="${colour}" stroke="${INK}" stroke-width="3"/><path d="M-8-6H8" stroke="${PAPER}" stroke-width="5" stroke-linecap="round"/></g>`;
+const fighter = (id, colour, direction) => `<g id="${id}"><g transform="scale(${direction} 1)">
+ <path d="M-34 95-51 184h-35m119-89 32 89h35" fill="none" stroke="${INK}" stroke-width="23" stroke-linecap="round"/>
+ <path d="M-58 55h116v58H-58Z" fill="${colour}"/><path d="M-58 70h116" stroke="${INK}" stroke-width="10"/>
+ ${hero(id+'-head',5)}
+ <circle cx="-103" cy="61" r="29" fill="${colour}" stroke="${INK}" stroke-width="6"/>
+ <path id="${id}-arm" d="M0 0h100" stroke="${colour}" stroke-width="24" stroke-linecap="round"/>
+ <g id="${id}-glove"><circle cx="106" cy="4" r="30" fill="${colour}" stroke="${INK}" stroke-width="6"/><path d="M93-8h21" stroke="${PAPER}" stroke-width="7" stroke-linecap="round"/></g>
+</g></g>`;
+
+export function montageMarkup() {
+ return `<g id="montage-rpg">${gameMarkup("full-game")}</g>
+ <g id="montage-fps">
+ <rect width="1600" height="900" fill="#91afba"/>
+ <path d="M0 116h300V56h266v96h522V77h295v78h217v481H0Z" fill="#536e7b"/>
+ <path d="M344 138h770v356H344Z" fill="#405965"/><path d="M728 243h249v251H728Z" fill="${INK}"/>
+ <path d="M378 189h221v41H378Zm657 0h46v220h-46Z" fill="#adc6c9"/>
+ <path d="M0 489h1600v411H0Z" fill="#768c94"/><path d="M650 489 170 900m316-250h775m-221-161 477 411" fill="none" stroke="#a6b4b3" stroke-width="5"/>
+ <path d="M0 251 257 348v552H0Zm1600-74-229 93v630h229Z" fill="#344d5c"/>
+ <path d="m0 251 257 97v43L0 299Zm1600-74-229 93v44l229-96Z" fill="#b5c7c5"/>
+ ${[
+ [610, 477],
+ [863, 358],
+ [1120, 484],
+ ]
+ .map(
+ ([x, y], i) =>
+ `<g transform="translate(${x} ${y})"><g id="fps-target-${i}"><g transform="scale(2.4)">${unit('fps-opponent-'+i,CORAL)}</g></g></g>${burst("fps-hit-" + i, x, y)}`,
+ )
+ .join("")}
+ <g fill="#486472" stroke="#8ba5ad" stroke-width="5"><path d="M469 535h274v225H469Z"/><path d="M746 419h249v155H746Z"/><path d="M1023 552h305v213h-305Z"/></g>
+ <path d="M489 557h233M508 557v178M605 557v178M766 443h209M790 443v106M882 443v106M1043 574h265M1068 574v166M1185 574v166" fill="none" stroke="#718b95" stroke-width="8"/>
+ <path id="fps-tracer" d="M0 0h100" fill="none" stroke="${GOLD}" stroke-width="8" stroke-linecap="round"/>
+ <g id="fps-tool">
+ <path d="M-257 250-130 23-56 40-67 250Z" fill="${CORAL}"/><path d="m-134 18 49-51 47 40-24 77-49-6Z" fill="${INK}"/>
+ <path d="M253 250 67 43-6 73 62 250Z" fill="#d5b68a"/><path d="m57 35-51-14-24 57 45 53 44-45Z" fill="${INK}"/>
+ <path d="M-71 213-68 42h132l56 171Z" fill="${INK}"/>
+ <path d="M-45-148h90V50L22 99h-67Z" fill="#81989f" stroke="${INK}" stroke-width="9"/>
+ <path d="M-17-145v-172h34v172" fill="#b8c8c9" stroke="${INK}" stroke-width="10"/>
+ <rect x="-28" y="-340" width="56" height="40" rx="7" fill="${INK}"/>
+ <path d="M-31-145v-53q0-12 12-12h38q12 0 12 12v53Z" fill="${INK}" stroke="${PAPER}" stroke-width="6"/><circle cy="-177" r="5" fill="${CORAL}"/>
+ <path d="m15 47 49-10 29 103-47 12Z" fill="${INK}"/><path d="M-46-111h24m-24 24h24m-24 24h24" stroke="${INK}" stroke-width="7"/>
+ <g id="fps-muzzle"><path d="m0-338-15-28-21 4 7-25-17-18 31-3 15-35 14 35 31 3-17 18 7 25-21-4Z" fill="${GOLD}"/><path d="m0-344-13-33 13-35 13 35Z" fill="${PAPER}"/></g>
+ </g>
+ <g id="fps-crosshair" fill="none" stroke="${PAPER}" stroke-width="4"><path d="M-27-11v-16h16m22 0h16v16m0 22v16H11m-22 0h-16V11"/><circle r="3" fill="${PAPER}"/></g>
+ </g>
+ <g id="montage-platform">
+ <rect width="1600" height="900" fill="#b9dbdc"/>
+ <circle cx="1190" cy="181" r="110" fill="#faf1ca"/>
+ <g fill="#edf1dc"><path d="M85 290q-19-43 28-52 19-59 68-18 59-12 66 42 40 1 39 28Z"/><path d="M753 179q-14-34 24-42 24-51 63-11 61-6 65 53Z"/></g>
+ <path d="M-100 785 250 365 666 833 1035 393 1490 783 1730 456v500H-100Z" fill="#8bb8ad"/>
+ <path d="M-100 873 250 535 500 801 741 605l420 329Z" fill="#6a9c91"/>
+ <g fill="#bf9066"><path d="M0 690h450v210H0Z"/><path d="M940 540h660v360H870Z"/></g>
+ <g fill="#477a69"><path d="M0 690h450v26H0Z"/><path d="M932 540h668v27H928Z"/></g>
+ <g fill="#dcb181"><path d="M0 743h395v36H0Zm988-151h612v33H980Zm-18 105h570v34H962Z"/></g>
+ <path d="M65 861h207m856-69h227" stroke="#a97856" stroke-width="8" stroke-linecap="round"/>
+ ${[
+ [625, 351],
+ [764, 307],
+ [889, 371],
+ ]
+ .map(
+ ([x, y], i) =>
+ `<g transform="translate(${x} ${y})"><g id="platform-coin-${i}"><circle r="25" fill="${GOLD}" stroke="#b7803d" stroke-width="5"/><path d="M0-11v22" stroke="#fff3bd" stroke-width="6"/></g></g>${burst("platform-hit-" + i, x, y)}`,
+ )
+ .join("")}
+ <ellipse id="platform-shadow" rx="41" ry="10" fill="${INK}" opacity=".2"/>
+ ${hero("platform-player")}
+ <g transform="translate(1325 540)"><path d="M0 0v-223" stroke="${INK}" stroke-width="8" stroke-linecap="round"/><circle cy="-225" r="9" fill="${GOLD}"/><g id="platform-flag"><path d="M5-214h110l-25 37 25 37H5Z" fill="${CORAL}"/><path d="m24-176 15 14 30-30" fill="none" stroke="${PAPER}" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/></g></g>
+ </g>
+ <g id="montage-rts">
+ <rect width="1600" height="900" fill="#cbd0ae"/>
+ <path d="M-100 500 375 196 1650 515v200L369 389-100 703Z" fill="#91b6b6"/>
+ <path d="m-100 499 475-303 1275 319m-1750 188L369 389l1281 326" fill="none" stroke="#eae1b6" stroke-width="15"/>
+ <ellipse cx="1115" cy="500" rx="244" ry="203" fill="#eae1b6"/><ellipse cx="1115" cy="500" rx="233" ry="189" fill="#cbd0ae"/>
+ <path d="m433 182-74 210 173 50 77-216Z" fill="#bcaa7e" stroke="#897e65" stroke-width="6"/>
+ ${[
+ [1270, 744],
+ [261, 681],
+ [782, 563],
+ ]
+ .map(
+ ([x, y]) =>
+ `<g transform="translate(${x} ${y})"><ellipse rx="91" ry="36" fill="#9faf88"/><path d="M-60-10-15-69 33-56 78-7 35 19-37 20Z" fill="#6d8c7b"/><path d="M-15-69 33-56 16-15-60-10Z" fill="#91aa8c"/></g>`,
+ )
+ .join("")}
+ <path id="rts-route" d="M453 645Q570 47 1100 328" fill="none" stroke="${INK}" stroke-width="5" stroke-dasharray="15 13" opacity=".5"/>
+ <path d="m1065 332 35-4-18-30" fill="none" stroke="${INK}" stroke-width="5" stroke-linecap="round"/>
+ <g transform="translate(1115 510)"><ellipse rx="137" ry="81" fill="#b3bb96"/><path d="m-72 26 8-88 64-35 68 35 8 88-76 40Z" fill="#69857a"/><path d="m-64-62 64-35 68 35L0-22Z" fill="#9bac98"/><path d="M0-22v88" stroke="#496d62" stroke-width="5"/><path d="M0-22v-110" stroke="${INK}" stroke-width="7"/><path id="rts-banner" d="M4-132h76l-21 25 21 25H4Z" fill="${CORAL}"/></g>
+ ${Array.from({ length: 6 }, (_, i) => `<g id="rts-ally-${i}"><ellipse rx="37" ry="23" cy="15" fill="none" stroke="#f5f2cc" stroke-width="4"/>${unit("rts-ally-body-" + i, "#528f86")}</g>${unit("rts-enemy-" + i, CORAL)}${burst("rts-hit-" + i, 1040 + (i % 3) * 72, 431 + Math.floor(i / 3) * 139)}`).join("")}
+ <g fill="none" stroke="${PAPER}" stroke-width="8" stroke-linecap="round">${Array.from({ length: 6 }, (_, i) => `<path id="rts-shot-${i}" d="M0 0h100"/>`).join("")}</g>
+ <g id="rts-command" transform="translate(849 186)" fill="none" stroke="${PAPER}" stroke-width="6"><ellipse rx="48" ry="24"/><path d="M0-45v16m0 58v16m-70-45h20m100 0h20"/></g>
+ </g>
+ <g id="montage-moba">
+ <rect width="1600" height="900" fill="#5c8577"/>
+ <path d="M104 900 1140-70h445L541 900Z" fill="#a7b5a0"/>
+ <path d="M-15 863 1112-112m-515 1061L1660-65" fill="none" stroke="#d2cdb0" stroke-width="19"/>
+ <g stroke="#8d9f90" stroke-width="4">${Array.from({ length: 8 }, (_, i) => `<path d="m${390 + i * 125} ${900 - i * 125} 180-170"/>`).join("")}</g>
+ ${[
+ [189, 350],
+ [290, 174],
+ [1417, 690],
+ [1315, 824],
+ ]
+ .map(
+ ([x, y]) =>
+ `<g transform="translate(${x} ${y})"><ellipse cy="50" rx="92" ry="29" fill="#355e56"/><path d="M-70 36-59-40 5-90 66-46 83 35 0 66Z" fill="#3f7060"/><path d="M-59-40 5-90 66-46 7-9Z" fill="#71977a"/></g>`,
+ )
+ .join("")}
+ <g transform="translate(1370 198)"><ellipse cy="50" rx="95" ry="45" fill="#718e7f"/><path d="M-60 20-45-42 0-76 46-42 59 20 0 54Z" fill="#b0bda5"/><path d="m0-76 46 34-46 26-45-26Z" fill="#dfdec3"/><path d="m0-47 20 32-20 35-20-35Z" fill="${CORAL}"/></g>
+ <path id="moba-warning" d="M1197 315 1173 354 588 651 612 612Z" fill="${CORAL}" opacity=".35"/>
+ <path id="moba-enemy-shot" d="M0 0h100" stroke="${CORAL}" stroke-width="20" stroke-linecap="round"/>
+ <path id="moba-dash" d="M600 630 760 416" stroke="#bde7db" stroke-width="66" stroke-linecap="round" opacity=".4"/>
+ ${[
+ [1110, 355],
+ [1220, 475],
+ [1090, 600],
+ ]
+ .map(
+ ([x, y], i) =>
+ `<g transform="translate(${x} ${y})"><g id="moba-enemy-${i}"><ellipse cy="31" rx="47" ry="18" fill="${INK}" opacity=".2"/><path d="M-35 23q-6-61 35-65t35 65Z" fill="${CORAL}" stroke="${INK}" stroke-width="4"/><path d="M-12-11h24" stroke="${PAPER}" stroke-width="6" stroke-linecap="round"/><rect x="-43" y="-74" width="86" height="9" rx="4.5" fill="${INK}"/><rect id="moba-health-${i}" x="-41" y="-72" width="82" height="5" rx="2.5" fill="${GOLD}"/></g></g>${burst("moba-hit-" + i, x, y, PAPER)}`,
+ )
+ .join("")}
+ <g transform="translate(1140 470)"><circle id="moba-impact" r="175" fill="#e8efd0" fill-opacity=".2" stroke="${PAPER}" stroke-width="10"/></g>
+ <ellipse id="moba-shadow" rx="48" ry="15" fill="${INK}" opacity=".2"/>
+ ${hero("moba-player", 3.2)}
+ <path id="moba-shot" d="M0 0h100" stroke="${PAPER}" stroke-width="27" stroke-linecap="round"/>
+ <g id="moba-result" transform="translate(1402 772)"><circle r="56" fill="${INK}"/><text y="20" text-anchor="middle" font-size="58" font-weight="900" fill="${GOLD}">×3</text></g>
+ </g>
+ <g id="montage-fighting">
+ <rect width="1600" height="900" fill="#c6b7c7"/><circle cx="800" cy="298" r="213" fill="#f4d79e"/>
+ <path d="M0 486 205 337 428 486l232-144 292 144 205-115 443 115v183H0Z" fill="#879aa1"/>
+ <path d="M197 194h72v445h-72Zm1134 0h72v445h-72Z" fill="#526773"/><path d="M163 193h141v31H163Zm1131 0h141v31h-141Z" fill="#758996"/>
+ <path d="M0 647h1600v253H0Z" fill="#344c5a"/><path d="M0 647h1600M0 775h1600M431 647 240 900m937-253 190 253" fill="none" stroke="#728993" stroke-width="6"/>
+ <ellipse cx="611" cy="647" rx="137" ry="27" fill="${INK}" opacity=".25"/><ellipse cx="1080" cy="647" rx="166" ry="27" fill="${INK}" opacity=".25"/>
+ <rect x="146" y="75" width="542" height="37" rx="12" fill="${INK}"/><rect x="157" y="84" width="520" height="19" rx="8" fill="#83c4a5"/>
+ <rect x="912" y="75" width="542" height="37" rx="12" fill="${INK}"/><rect id="fighting-health" x="923" y="84" width="520" height="19" rx="8" fill="${CORAL}"/>
+ <path d="m777 61 46 0-23 39h24l-47 51 17-42h-20Z" fill="${INK}"/>
+ ${fighter('fighting-opponent',CORAL,-1)}${fighter('fighting-player','#83c4a5',1)}
+ <g id="fighting-guard"><path d="M0-55q35 51 0 105" fill="none" stroke="${PAPER}" stroke-width="13" stroke-linecap="round"/><path d="M18-38 39-48M22 0h29m-33 34 23 15" stroke="${GOLD}" stroke-width="8" stroke-linecap="round"/></g>
+ ${burst('fighting-hit',976,488)}
+ </g>`;
+}
+
+export function gameFrame(kind, t, rpgTime) {
+ const frame = {};
+ const style = (id, property, value) => { (frame[id] ??= {})[property] = String(value); };
+ const transform = (id, value) => style(id, 'transform', value);
+ const show = (id, yes) => style(id, 'opacity', yes ? 1 : 0);
+ const opacity = (id, n) => style(id, 'opacity', round(clamp(n)));
+ const position = (id, x, y, scale = 1) =>
+ transform(id, `translate(${round(x)}px,${round(y)}px) scale(${round(scale)})`);
+ const pulse = (id, t) => {
+ const p = clamp(t / 0.45);
+ transform(id, `scale(${round(0.5 + p * 1.4)})`);
+ opacity(id, t >= 0 ? 1 - p : 0);
+ };
+ const line = (id, a, b) => transform(id,
+ `translate(${round(a[0])}px,${round(a[1])}px) rotate(${round(Math.atan2(b[1]-a[1],b[0]-a[0])*180/Math.PI)}deg) scaleX(${round(Math.hypot(b[0]-a[0],b[1]-a[1])/100)})`);
+
+ function fps(t) {
+ const targets = [
+ [610, 477],
+ [863, 358],
+ [1120, 484],
+ ],
+ shots = [0.55, 1.1, 1.65];
+ const count = shots.filter((s) => t >= s).length;
+ const next = Math.min(count, 2),
+ from = next ? targets[next - 1] : [405, 565];
+ const aim = ease((t - (next ? shots[next - 1] + 0.09 : 0)) / 0.34);
+ const aimPoint = from.map((n,i)=>mix(n,targets[next][i],aim));
+ position("fps-crosshair", ...aimPoint);
+ const last = count ? t - shots[count - 1] : -1;
+ const kick = last >= 0 ? Math.sin(clamp(last/.18)*Math.PI) : 0;
+ const origin = [1180,810+18*kick], weaponScale=.85;
+ const angle = Math.atan2(aimPoint[1]-origin[1],aimPoint[0]-origin[0])+Math.PI/2;
+ transform('fps-tool',`translate(${origin[0]}px,${round(origin[1])}px) rotate(${round(angle*180/Math.PI-3*kick)}deg) scale(${weaponScale})`);
+ const muzzleAngle=angle-3*kick*Math.PI/180;
+ const muzzle=[origin[0]+340*weaponScale*Math.sin(muzzleAngle),origin[1]-340*weaponScale*Math.cos(muzzleAngle)];
+ line("fps-tracer", muzzle, targets[Math.max(0, count - 1)]);
+ opacity("fps-tracer", last >= 0 ? 1 - last / 0.1 : 0);
+ opacity('fps-muzzle',last>=0?1-last/.09:0);
+ targets.forEach((_, i) => {
+ const fall=ease((t-shots[i])/.18);
+ transform("fps-target-" + i, `translate(0px,${round(75*fall)}px) rotate(${round(-24*fall)}deg)`);
+ opacity('fps-target-'+i,1-fall);
+ pulse("fps-hit-" + i, t - shots[i]);
+ });
+ }
+
+ function platform(t) {
+ const leap = clamp((t - 0.32) / 1.22),
+ run = ease((t - 1.54) / 0.6);
+ const x =
+ t < 0.32
+ ? mix(295, 422, ease(t / 0.32))
+ : mix(422, 1080, leap) + 245 * run;
+ const ground = mix(645, 495, leap),
+ y = ground - 278 * Math.sin(leap * Math.PI);
+ transform(
+ "platform-player",
+ `translate(${round(x)}px,${round(y)}px) rotate(${round(leap > 0 && leap < 1 ? -9 : 3 * Math.sin(t * 19))}deg)`,
+ );
+ position(
+ "platform-shadow",
+ x,
+ ground + 43,
+ 1 - 0.5 * Math.sin(leap * Math.PI),
+ );
+ [0.7, 0.955, 1.185].forEach((hit, i) => {
+ transform("platform-coin-" + i, `scale(${round(1 - ease((t - hit) / 0.12))})`);
+ pulse("platform-hit-" + i, t - hit);
+ });
+ position("platform-flag", 0, 126 * (1 - ease((t - 2) / 0.2)));
+ }
+
+ function rts(t) {
+ const p = ease((t - 0.12) / 1.18),
+ u = 1 - p;
+ // A curved flank around the rocks, followed by the capture flag.
+ const x = u * u * 453 + 2 * u * p * 570 + p * p * 1100,
+ y = u * u * 645 + 2 * u * p * 47 + p * p * 328;
+ for (let i = 0; i < 6; i++) {
+ position(
+ "rts-ally-" + i,
+ x + (i % 3) * 64 - 64,
+ y + Math.floor(i / 3) * 65 - 30,
+ );
+ position(
+ "rts-enemy-" + i,
+ 1040 + (i % 3) * 72,
+ 431 + Math.floor(i / 3) * 139,
+ 1 - ease((t - 1.52 - i * 0.025) / 0.17),
+ );
+ pulse("rts-hit-" + i, t - 1.52 - i * 0.025);
+ const shot = clamp((t - 1.28 - i * 0.025) / 0.24),
+ start = [1036 + (i % 3) * 64, 298 + Math.floor(i / 3) * 65],
+ end = [1040 + (i % 3) * 72, 431 + Math.floor(i / 3) * 139];
+ line(
+ "rts-shot-" + i,
+ start.map((n, j) => mix(n, end[j], shot)),
+ start.map((n, j) => mix(n, end[j], Math.max(0, shot - 0.25))),
+ );
+ opacity(
+ "rts-shot-" + i,
+ t >= 1.28 + i * 0.025 && t < 1.52 + i * 0.025 ? 1 : 0,
+ );
+ }
+ style("rts-banner", "fill", t >= 1.74 ? "#528f86" : CORAL);
+ opacity("rts-command", 1 - ease((t - 0.55) / 0.3));
+ opacity("rts-route", 0.5 * (1 - ease((t - 1.4) / 0.3)));
+ }
+
+ function moba(t) {
+ const dash = ease((t - 0.57) / 0.26),
+ x = mix(600, 760, dash),
+ y = mix(630, 416, dash);
+ position("moba-player", x, y);
+ position("moba-shadow", x, y + 49);
+ opacity("moba-warning", 0.35 * (1 - ease((t - 0.6) / 0.15)));
+ opacity("moba-dash", t >= 0.57 ? 0.45 * (1 - ease((t - 0.83) / 0.3)) : 0);
+ const enemy = clamp((t - 0.61) / 0.45);
+ line(
+ "moba-enemy-shot",
+ [mix(1185, 570, enemy), mix(335, 645, enemy)],
+ [mix(1185, 670, enemy), mix(335, 595, enemy)],
+ );
+ opacity("moba-enemy-shot", t >= 0.61 && t < 1.08 ? 1 : 0);
+ const shot = clamp((t - 1.06) / 0.34);
+ line(
+ "moba-shot",
+ [mix(760, 1140, shot), mix(416, 470, shot)],
+ [mix(760, 1045, shot), mix(416, 456, shot)],
+ );
+ opacity("moba-shot", t >= 1.06 && t < 1.4 ? 1 : 0);
+ transform("moba-impact", `scale(${round(ease((t - 1.4) / 0.16))})`);
+ opacity("moba-impact", 1 - ease((t - 1.57) / 0.35));
+ for (let i = 0; i < 3; i++) {
+ transform("moba-enemy-" + i, `scale(${round(1 - ease((t - 1.44) / 0.15))})`);
+ transform("moba-health-" + i, `translate(-41px,0px) scaleX(${round(1 - ease((t - 1.4) / 0.09))}) translate(41px,0px)`);
+ pulse("moba-hit-" + i, t - 1.44);
+ }
+ show("moba-result", t >= 1.6);
+ }
+
+ function fighting(t) {
+ const p=clamp(t/GAME_CUT), approach=ease(p/.18);
+ const jab=ease((p-.21)/.1)*(1-ease((p-.34)/.12));
+ const guard=ease((p-.27)/.035)*(1-ease((p-.39)/.08));
+ const counter=ease((p-.44)/.11)*(1-ease((p-.59)/.15));
+ const recoil=ease((p-.55)/.13);
+ const playerX=mix(460,610,approach)+55*counter, opponentX=mix(1140,965,approach)+185*recoil;
+ transform('fighting-player',`translate(${round(playerX)}px,452px) rotate(${round(-4*guard+6*counter)}deg)`);
+ transform('fighting-opponent',`translate(${round(opponentX)}px,452px) rotate(${round(22*recoil-4*jab)}deg)`);
+ position('fighting-player-glove',205*counter,-12*guard);
+ position('fighting-opponent-glove',145*jab,0);
+ line('fighting-player-arm',[57,71],[106+205*counter,4-12*guard]);
+ line('fighting-opponent-arm',[57,71],[106+145*jab,4]);
+ position('fighting-guard',716,448);
+ opacity('fighting-guard',guard);
+ pulse('fighting-hit',(p-.55)*GAME_CUT);
+ transform('fighting-health',`translate(1443px,0px) scaleX(${round(1-ease((p-.55)/.08))}) translate(-1443px,0px)`);
+ show('fighting-player-head-tv-open',p<.76);
+ show('fighting-player-head-tv-wink',p>=.76);
+ }
+
+ if(kind === 'rpg') for(const [key,value] of Object.entries(poses(rpgTime))) transform('full-game-'+key,value);
+ else ({fps,platform,rts,moba,fighting})[kind](t);
+ return frame;
+}
+
+export function createMontage(svg, bar) {
+ const nodes = new Map(Array.from(svg.querySelectorAll('#scene-game [id]'),el=>[el.id,el]));
+ return (time,filmTime) => {
+ const cut = Math.min(GAME_KINDS.length-1,Math.floor(Math.max(0,time)/bar));
+ GAME_KINDS.forEach((kind,i)=>{nodes.get('montage-'+kind).style.display=i===cut?'':'none';});
+ const kind = GAME_KINDS[cut], local = (time-cut*bar)/bar*GAME_CUT;
+ for(const [id,style] of Object.entries(gameFrame(kind,local,filmTime))) Object.assign(nodes.get(id).style,style);
+ // The full film adds a friend's reaction; the standalone hero is just play.
+ const cheerAt=GAME_CUT*.74;
+ const cheer = kind==='fighting' && local>=cheerAt;
+ nodes.get('montage-cheer').style.opacity = cheer?'1':'0';
+ nodes.get('montage-cheer').style.transform = `translate(${round(-980*(1-ease((local-cheerAt)/(GAME_CUT/8))))}px,0px) translate(435px,670px) rotate(-8deg) translate(-435px,-670px)`;
+ };
+}
diff --git a/site/assets/language.js b/site/assets/language.js
new file mode 100644
index 00000000..2a9912d5
--- /dev/null
+++ b/site/assets/language.js
@@ -0,0 +1,22 @@
+const storageKey = 'piik:site-language';
+const languages = ['en', 'zh-CN'];
+
+export function initialLanguage() {
+ const requested = new URLSearchParams(location.search).get('lang');
+ if (languages.includes(requested)) return requested;
+ try {
+ const stored = localStorage.getItem(storageKey);
+ if (languages.includes(stored)) return stored;
+ } catch {
+ // Restricted storage does not prevent automatic language selection.
+ }
+ return navigator.language?.split('-')[0]?.toLowerCase() === 'zh' ? 'zh-CN' : 'en';
+}
+
+export function rememberLanguage(language) {
+ try {
+ localStorage.setItem(storageKey, language);
+ } catch {
+ // The current page keeps its explicit choice without persistence.
+ }
+}
diff --git a/site/assets/living-room.svg b/site/assets/living-room.svg
new file mode 100644
index 00000000..2eb5943e
--- /dev/null
+++ b/site/assets/living-room.svg
@@ -0,0 +1,258 @@
+<svg xmlns="http://www.w3.org/2000/svg" id="still" width="900" height="590" viewBox="0 0 900 590" fill="none" role="img" aria-labelledby="title desc">
+ <title id="title">Share the good stuff</title>
+ <desc id="desc">A host with a small gold crown shares an RPG, a pencil drawing, travel photos and a movie. Three friends watch from a warm orange sofa, with the Piik mascot nearby.</desc>
+ <defs>
+ <g id="person" fill="currentColor" stroke="none">
+ <circle cx="0" cy="-31" r="20"/>
+ <path d="M-35 51.5c0-32.5 12.5-50 35-50s35 17.5 35 50q0 7.5-7.5 7.5h-55Q-35 59-35 51.5Z"/>
+ </g>
+ <g id="eyes" fill="#22303e" stroke="none"><ellipse cx="-7" cy="-30.75" rx="2.75" ry="3.75"/><ellipse cx="7" cy="-30.75" rx="2.75" ry="3.75"/></g>
+ <clipPath id="screen"><rect x="284" y="111" width="370" height="190" rx="13"/></clipPath>
+ </defs>
+ <style>
+ .person-body { transform-origin:0 59px; }
+ .person-eyes { transform-origin:0 -30.75px; }
+ @media (prefers-reduced-motion:no-preference) {
+ .person-body { animation:lean var(--pace) ease-in-out var(--phase) infinite; }
+ .person-eyes { animation:look var(--pace) ease-in-out var(--phase) infinite; }
+ .game-hand { animation:play 7.4s ease-in-out var(--tap-delay,0s) infinite; }
+ }
+ :root:target .person-body, :root:target .person-eyes, :root:target .game-hand { animation:none; }
+ @keyframes lean { 0%,36%,43%,100%{transform:none} 38%,41%{transform:rotate(3deg)} }
+ @keyframes look { 0%,3%,3.6%,12%,16%,47%,47.6%,61%,67%,100%{transform:none} 3.3%,47.3%{transform:scaleY(.14)} 13%,15%{transform:translate(2px,-2px)} 62%,63%{transform:translateX(-2px)} 65%,66%{transform:translateX(2px)} }
+ @keyframes play { 0%,19%,27%,54%,64%,100%{transform:none} 22%,25%{transform:translate(-2px,-2px)} 57%,61%{transform:translate(2px,-1px)} }
+ </style>
+ <path d="M78 277C63 147 164 70 302 62c127-8 186-50 314-20 130 30 214 127 216 249 3 159-91 247-245 252l-292-3C145 536 70 457 78 277Z" fill="#f7f4e9"/>
+ <path d="M122 267c2-113 90-171 211-171 138 0 163-39 277 5 101 39 149 104 158 216H122Z" fill="#dcebe1"/>
+ <ellipse cx="460" cy="504" rx="350" ry="48" fill="#c8dccf"/>
+ <ellipse cx="460" cy="504" rx="296" ry="30" stroke="#f7f4e9" stroke-width="3"/>
+ <g stroke="#22303e" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round">
+ <!-- Original screen content; room figures follow the shared UI identity. -->
+ <path d="m439 52 30 25 30-25"/><path d="m331 324-14 22m289-22 14 22" stroke-width="6"/>
+ <rect x="264" y="78" width="410" height="248" rx="29" fill="#22303e"/>
+ <rect x="279" y="93" width="380" height="211" rx="16" fill="#fffdf5" stroke="none"/>
+ <g stroke="none"><circle cx="292" cy="103" r="2.5" fill="#e58b69"/><circle cx="301" cy="103" r="2.5" fill="#edc969"/><circle cx="310" cy="103" r="2.5" fill="#77b29a"/><rect x="434" y="100" width="70" height="4" rx="2" fill="#dce7df"/></g>
+ <g clip-path="url(#screen)" stroke="none">
+ <!-- Shared activities: generated by scripts/update-website-hero.mjs. -->
+ <svg x="284" y="111" width="370" height="190" viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice" stroke="none" font-family="ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif"><g id="activity-rpg"><style>#hero-rpg-water{transform:translate(-5.69px,0px)}#hero-rpg-flowers{transform:skewX(-1.22deg)}#hero-rpg-shadow{transform:translate(907.7px,544.82px)}#hero-rpg-player{transform:translate(907.7px,522.94px) rotate(2.88deg)}#hero-rpg-lid{transform:scaleY(1)}#hero-rpg-treasure{transform:translate(1028px,457px) scale(0)}</style><rect width="1600" height="900" fill="#bbd596"/>
+ <path d="M0 0h1600v240q-263-98-520-33T480 181 0 280Z" fill="#91b780"/>
+ <path d="M0 567q224-38 290 148t227 185H0Z" fill="#91c9c6"/>
+ <path d="M0 558q224-38 299 158t230 184" fill="none" stroke="#eef0bd" stroke-width="18"/>
+ <g id="hero-rpg-water" fill="none" stroke="#d4ece0" stroke-width="5" stroke-linecap="round"><path d="M33 690h102m-75 60h109m50 90h111M28 845h76"/></g>
+ <path d="M436 934q78-205 231-276t386-179 230-229" fill="none" stroke="#d7cc99" stroke-width="94"/>
+ <path d="M436 934q78-205 231-276t386-179 230-229" fill="none" stroke="#e9dfb1" stroke-width="65"/>
+ <g fill="#a3bd7c"><ellipse cx="391" cy="330" rx="230" ry="100"/><ellipse cx="740" cy="167" rx="220" ry="72"/><ellipse cx="1110" cy="740" rx="310" ry="90"/></g>
+ <g fill="none" stroke="#86aa74" stroke-width="5" stroke-linecap="round"><path d="m330 400 -5-12m11 11 5-15m7 18 6-9"/><path d="m580 302 -5-12m11 11 5-15m7 18 6-9"/><path d="m910 699 -5-12m11 11 5-15m7 18 6-9"/><path d="m1080 643 -5-12m11 11 5-15m7 18 6-9"/><path d="m715 786 -5-12m11 11 5-15m7 18 6-9"/><path d="m1440 566 -5-12m11 11 5-15m7 18 6-9"/><path d="m469 626 -5-12m11 11 5-15m7 18 6-9"/></g>
+ <g transform="translate(1240 276)"><ellipse cy="83" rx="150" ry="32" fill="#31594b" opacity=".16"/>
+ <path d="M-114 82V-97q0-41 40-41H71q40 0 40 41V82H63V-85H-65V82Z" fill="#758d83"/>
+ <path d="M-105 67V-102q0-26 29-26H73q29 0 29 26v24H-105Z" fill="#b5c6aa"/>
+ <path d="M-63-78H63V74H-63Z" fill="#355e56"/>
+ <path d="m0-111 11 15-11 15-11-15Z" fill="#e9dfb1"/>
+ <path d="m-104 8 35 1m35-125 4 36m73-33-7 36m68 6-35 2" stroke="#607f73" stroke-width="4"/>
+ <path d="m-122 64 25-3 8 21h-42Zm218 13 17-19 24 13 6 16h-48Z" fill="#9eaf99"/></g>
+ <g transform="translate(172 302) scale(1.35)"><ellipse cy="65" rx="73" ry="23" fill="#31594b" opacity=".18"/><path d="M-7 9h14v57H-7Z" fill="#816947"/><path d="M-69 12q-2-48 38-46 6-66 54-38 43-3 40 40 42 36 4 65-24 24-57 3-46 13-79-24Z" fill="#428570"/><path d="M-58-6q-9-32 29-32 11-45 44-34 37 8 35 35-21 29-47 14-20 36-61 17Z" fill="#72aa7e"/></g><g transform="translate(380 155) scale(0.92)"><ellipse cy="65" rx="73" ry="23" fill="#31594b" opacity=".18"/><path d="M-7 9h14v57H-7Z" fill="#816947"/><path d="M-69 12q-2-48 38-46 6-66 54-38 43-3 40 40 42 36 4 65-24 24-57 3-46 13-79-24Z" fill="#428570"/><path d="M-58-6q-9-32 29-32 11-45 44-34 37 8 35 35-21 29-47 14-20 36-61 17Z" fill="#72aa7e"/></g><g transform="translate(1460 335) scale(1.2)"><ellipse cy="65" rx="73" ry="23" fill="#31594b" opacity=".18"/><path d="M-7 9h14v57H-7Z" fill="#816947"/><path d="M-69 12q-2-48 38-46 6-66 54-38 43-3 40 40 42 36 4 65-24 24-57 3-46 13-79-24Z" fill="#428570"/><path d="M-58-6q-9-32 29-32 11-45 44-34 37 8 35 35-21 29-47 14-20 36-61 17Z" fill="#72aa7e"/></g><g transform="translate(969 96) scale(0.9)"><ellipse cy="65" rx="73" ry="23" fill="#31594b" opacity=".18"/><path d="M-7 9h14v57H-7Z" fill="#816947"/><path d="M-69 12q-2-48 38-46 6-66 54-38 43-3 40 40 42 36 4 65-24 24-57 3-46 13-79-24Z" fill="#428570"/><path d="M-58-6q-9-32 29-32 11-45 44-34 37 8 35 35-21 29-47 14-20 36-61 17Z" fill="#72aa7e"/></g>
+ <g id="hero-rpg-flowers" fill="#faf5e7"><path d="m467 205 -7-5 1-7 7 3 5-5 5 4-4 7 6 4-3 5-7-3-5 4-5-5Z"/><path d="m478 222 -7-5 1-7 7 3 5-5 5 4-4 7 6 4-3 5-7-3-5 4-5-5Z"/><path d="m745 717 -7-5 1-7 7 3 5-5 5 4-4 7 6 4-3 5-7-3-5 4-5-5Z"/><path d="m777 745 -7-5 1-7 7 3 5-5 5 4-4 7 6 4-3 5-7-3-5 4-5-5Z"/><path d="m1340 661 -7-5 1-7 7 3 5-5 5 4-4 7 6 4-3 5-7-3-5 4-5-5Z"/><path d="m1370 679 -7-5 1-7 7 3 5-5 5 4-4 7 6 4-3 5-7-3-5 4-5-5Z"/></g>
+ <g transform="translate(1028 477)"><ellipse cy="63" rx="87" ry="21" fill="#31594b" opacity=".18"/>
+ <path d="m-66 5 115 29 36-38-114-29Z" fill="#503e36" stroke="#f0c66d" stroke-width="7" stroke-linejoin="round"/>
+ <path d="m-66 5 115 29v47L-66 52Z" fill="#b37748"/><path d="m49 34 36-38v47L49 81Z" fill="#805337"/>
+ <path d="m-45 13v45m70-27v45" stroke="#edbf64" stroke-width="11"/><path d="m-64 49 112 28 35-37" fill="none" stroke="#d9a34f" stroke-width="5"/>
+ <path d="m-29 20 45 12v8l-45-12Z" fill="#996139"/><path d="m-15 20 20 5v24l-20-5Z" fill="#ffe1a0"/><path d="m-7 30 5 1v8l-5-1Z" fill="#815b37"/>
+ <g transform="translate(-29 -33) rotate(14)"><g id="hero-rpg-lid">
+ <path d="M0 0h119l-26 46H-27Z" fill="#c58950" stroke="#f0c66d" stroke-width="6" stroke-linejoin="round"/>
+ <path d="M21 1-5 45m97-44L66 45" stroke="#ffe1a0" stroke-width="11"/>
+ <path d="M44 10h29l-12 24H31Z" fill="#a86f45"/>
+ </g></g>
+ </g>
+ <ellipse id="hero-rpg-shadow" rx="46" ry="13" fill="#31594b" opacity=".22"/>
+ <g id="hero-rpg-player" style="color:#203037"><g transform="translate(-36 -44) scale(2.4)"><rect x="1" y="13" width="10" height="14" rx="3" fill="#db8755"/><g fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
+ <g class="mascot-shell"><rect pathLength="1" x="4" y="8" width="24" height="18" rx="4" fill="#faf5e7"/>
+ <path class="mascot-antenna" pathLength="1" d="m11 4 5 4 5-4"/>
+ <path class="mascot-feet" pathLength="1" d="M10 29l2-3m10 3-2-3"/></g>
+ <g id="hero-rpg-hero-eyes" class="mascot-face">
+ <circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none"/>
+ <circle id="hero-rpg-hero-open" class="mascot-eye-open" cx="21.35" cy="16.5" r="1.25" fill="currentColor" stroke="none" opacity="0"/>
+ <path id="hero-rpg-hero-wink" class="mascot-eye-wink" pathLength="1" d="M19 17c1.5-1.8 3.2-1.8 4.7 0"/>
+ </g>
+ <g id="hero-rpg-hero-sparkles" class="mascot-sparkles" stroke="#d7982b" stroke-width="1.2" fill="#f4c14d" opacity="0">
+ <path d="m25 11.5 .8 1.9 1.9.8-1.9.8-.8 1.9-.8-1.9-1.9-.8 1.9-.8.8-1.9Z"/>
+ <path d="m25 17.2 .45 1.1 1.1.45-1.1.45-.45 1.1-.45-1.1-1.1-.45 1.1-.45.45-1.1Z"/>
+ </g></g></g></g>
+ <g id="hero-rpg-treasure"><circle r="53" fill="#fff3bd" opacity=".22"/><path d="m0-31 24 31-24 31-24-31Z" fill="#ffe391" stroke="#bb8537" stroke-width="3"/><path d="m0-31 0 62-24-31Z" fill="#fff5cd"/><path d="m-45-8-12-6m11 37-10 9m102-40 12-6m-11 37 10 9M0-55v-12" stroke="#fff5ce" stroke-width="5" stroke-linecap="round"/></g>
+ <g transform="translate(1435 779) scale(1.6)"><ellipse cy="65" rx="73" ry="23" fill="#31594b" opacity=".18"/><path d="M-7 9h14v57H-7Z" fill="#816947"/><path d="M-69 12q-2-48 38-46 6-66 54-38 43-3 40 40 42 36 4 65-24 24-57 3-46 13-79-24Z" fill="#428570"/><path d="M-58-6q-9-32 29-32 11-45 44-34 37 8 35 35-21 29-47 14-20 36-61 17Z" fill="#72aa7e"/></g><g transform="translate(744 952) scale(1.22)"><ellipse cy="65" rx="73" ry="23" fill="#31594b" opacity=".18"/><path d="M-7 9h14v57H-7Z" fill="#816947"/><path d="M-69 12q-2-48 38-46 6-66 54-38 43-3 40 40 42 36 4 65-24 24-57 3-46 13-79-24Z" fill="#428570"/><path d="M-58-6q-9-32 29-32 11-45 44-34 37 8 35 35-21 29-47 14-20 36-61 17Z" fill="#72aa7e"/></g>
+ <g transform="translate(63 56)"><rect width="253" height="56" rx="28" fill="#203037"/><text x="126.5" y="36" text-anchor="middle" font-family="ui-sans-serif,system-ui,sans-serif" font-size="22" font-weight="750" fill="#faf5e7" letter-spacing="2">LITTLE WANDER</text></g>
+ <g transform="translate(1415 94)" stroke="#faf5e7" stroke-width="4" fill="none"><circle r="32"/><path d="m0-19 8 19-8 19-8-19Z" fill="#faf5e7"/><path d="M0-41v-8m41 49h8m-49 41v8m-41-49h-8"/></g></g>
+ <g id="activity-drawing">
+ <rect width="1600" height="900" fill="#f3cc68"/>
+ <path d="M-130 750Q220-60 600 580T1720 300" fill="none" stroke="#f47843" stroke-width="190"/>
+ <g id="hero-paper"><g transform="translate(490 85) rotate(8 310 360)"><rect width="620" height="720" rx="5" fill="#faf7ed"/>
+ <g fill="none" stroke="#bdbaac" stroke-width="1.5" opacity=".65">
+ <path d="m138 197 312-36 61 341-312 31Zm33-19 63 376m193-415 62 371M123 331l390-45M304 123l59 424"/>
+ <ellipse cx="336" cy="327" rx="138" ry="161" transform="rotate(-8 336 327)"/>
+ <path d="M176 246q-11-48 16-55l225-27q49-3 57 42l25 201q5 51-35 49l-235 28q-46-1-49-44ZM242 184l-38-40m62 44 43-58"/>
+ <ellipse cx="276" cy="300" rx="24" ry="29"/><ellipse cx="379" cy="288" rx="26" ry="28"/>
+ <path d="m88 590 63-7m-45 14 119-12m273-469 38-9m-35 19 53-11"/>
+ </g>
+ <g fill="none" stroke="#edbc7b" stroke-width="2" opacity=".75">
+ <path d="M133 471Q80 224 215 147m269 61q89 174 15 284M132 552q187 50 391-40"/>
+ <path d="m121 540 11 12-16 7m384-56 23 9-16 14"/>
+ </g>
+ <g fill="none" stroke="#414842" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round">
+ <path id="hero-sketch-stroke-0" d="M177 245Q160 203 195 195L414 171Q455 164 467 206L492 406Q500 445 463 451L231 477Q190 482 187 444Z" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-1" d="M189 246Q179 214 211 211L414 187Q444 184 450 213L476 405Q480 432 453 438L231 461Q207 465 204 439Z" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-2" d="M256 189 210 151" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-3" d="M257 185 298 134" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-4" d="M270 288Q282 284 285 296T278 312Q266 315 265 303T270 288" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-5" d="M362 296Q377 271 398 291" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-6" d="M242 475 222 506" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-7" d="M432 455 453 486" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-8" d="M216 221 229 441" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-9" d="M226 447 454 426" pathLength="1" stroke-dasharray="1"/><path id="hero-sketch-stroke-10" d="M166 523Q307 544 499 500" pathLength="1" stroke-dasharray="1"/>
+ </g>
+ <g fill="none" stroke="#657066" stroke-width="1.5" opacity=".7">
+ <path d="m213 488 20 15"/><path d="m220 487.2 20 15"/><path d="m227 486.4 20 15"/><path d="m234 485.6 20 15"/><path d="m241 484.8 20 15"/><path d="m248 484 20 15"/><path d="m255 483.2 20 15"/><path d="m262 482.4 20 15"/><path d="m269 481.6 20 15"/><path d="m276 480.8 20 15"/><path d="m283 480 20 15"/><path d="m290 479.2 20 15"/>
+ <path d="m471 342 12-17"/><path d="m473 353 12-17"/><path d="m475 364 12-17"/><path d="m477 375 12-17"/><path d="m479 386 12-17"/><path d="m481 397 12-17"/><path d="m483 408 12-17"/><path d="m485 419 12-17"/>
+ <path d="m151 598 160-19m-144 27 66-11m169-5 119-20"/>
+ </g>
+ <path d="M44 54h66m-66 10h37M491 645h69m-35-8v16" stroke="#a3a699" stroke-width="2"/>
+ </g></g>
+ <g id="hero-pencil"><path d="M-11-255h22v217l-11 38-11-38Z" fill="#203037"/><path d="m-11-38 11 38 11-38Z" fill="#d6b68b"/><path d="M-3-10 0 0 3-10Z" fill="#203037"/><path d="M-4-240v188" stroke="#faf5e7" stroke-width="3"/></g>
+ </g>
+ <g id="activity-photos"><rect width="1600" height="900" fill="#203037"/><g id="hero-photos"><rect width="1600" height="900" fill="#203037"/>
+ <path d="M148 683q-49-268 192-414t595-108 502 112" fill="none" stroke="#6a8b80" stroke-width="5" stroke-dasharray="11 16"/>
+ <path d="m1339 258 14 29 31 4-23 22 6 31-28-15-28 15 5-31-22-22 31-4Z" fill="#f3cc68"/>
+ <path d="m236 696 153 23-21 117-153-23Z" fill="#df9c6c"/>
+ <path d="m255 726 86 13m-90 10 70 11m-74 11 81 12" stroke="#203037" stroke-width="6" opacity=".55"/>
+ <text x="267" y="807" transform="rotate(9 267 807)" fill="#203037" font-family="ui-monospace,monospace" font-size="25" font-weight="700">9527</text>
+ <g transform="translate(206 72) rotate(-12 410 300)">
+ <rect x="11" y="15" width="820" height="645" rx="12" fill="#111f26" opacity=".35"/>
+ <rect width="820" height="645" rx="12" fill="#faf5e7"/>
+ <svg x="24" y="24" width="772" height="516" viewBox="0 0 772 516" overflow="hidden">
+ <rect width="772" height="516" fill="#b7d6d2"/>
+ <circle cx="600" cy="106" r="62" fill="#f3cc68"/>
+ <path d="M-45 375 197 94 381 327 529 157 826 455v100H-45Z" fill="#85a99a"/>
+ <path d="m124 178 73-84 85 107-46-13-38 26-29-32Z" fill="#faf5e7"/>
+ <path d="M-43 504 185 320 365 384 486 268 833 473v96H-43Z" fill="#557f70"/>
+ <path d="M-60 438q178-51 316 11t296-4 268 21v90H-60Z" fill="#8caa79"/>
+ <path d="m0 474 176-3 55-63 203-1 74 91 267-9v50H0Z" fill="#c9c399"/>
+ <g transform="translate(275 351) rotate(-5)"><path d="M-29 62q0-70 29-70t29 70Z" fill="#8ebbd6"/><circle cy="-33" r="23" fill="#8ebbd6"/><path d="M-29-45q29-39 58 0Z" fill="#e9d2a0"/><path d="M-38-43h76" stroke="#c6a774" stroke-width="8" stroke-linecap="round"/><path d="M-7-31v3m14-3v3" stroke="#203037" stroke-width="4" stroke-linecap="round"/></g>
+ <g transform="translate(348 365) rotate(9)"><path d="M-27 53q0-60 27-60t27 60Z" fill="#d6958c"/><circle cy="-31" r="22" fill="#d6958c"/><path d="M-8-30v3m15-3v3" stroke="#203037" stroke-width="4" stroke-linecap="round"/><circle cx="45" cy="-40" r="7" fill="#d6958c"/><path d="m40-45 4-11m5 14 9-5" stroke="#d6958c" stroke-width="6" stroke-linecap="round"/></g>
+ <g transform="translate(138 437) rotate(22)"><path d="M-22 45q0-52 22-52t22 52Z" fill="#e8bf6c"/><circle cy="-26" r="19" fill="#e8bf6c"/><path d="m-7-28 4 3m8-1 4-3" stroke="#203037" stroke-width="3" stroke-linecap="round"/><path d="M26-5 10 9 44 45" fill="none" stroke="#6c7052" stroke-width="5" stroke-linecap="round"/><circle cx="10" cy="9" r="6" fill="#e8bf6c"/></g>
+ <path d="m-5 482 44-57-9 66 28-33-12 65m621-6 9-51 15 44 16-22 3 50" fill="#355e50"/>
+ </svg>
+ <path d="M61 580h226m-225 16h146" stroke="#b2b5a3" stroke-width="6" stroke-linecap="round"/>
+ <text x="725" y="602" fill="#597b69" font-family="ui-monospace,monospace" font-size="36" font-weight="700">01</text>
+ <path d="m319-7 155 8-10 42-153-9Z" fill="#d7b179" opacity=".9"/>
+ </g>
+ <g transform="translate(644 245) rotate(9 360 255)">
+ <rect x="12" y="14" width="720" height="562" rx="12" fill="#111f26" opacity=".3"/>
+ <rect width="720" height="562" rx="12" fill="#faf5e7"/>
+ <svg x="24" y="24" width="672" height="440" viewBox="0 0 672 440" overflow="hidden">
+ <rect width="672" height="440" fill="#b9d4d8"/>
+ <path d="M0 228h672v212H0Z" fill="#6f9d9f"/>
+ <path d="M0 246h83m25 17h91m52-20h69m44 5h112m19 21h51m53-23h73" stroke="#dbe8dc" stroke-width="5" stroke-linecap="round"/>
+ <svg width="328" height="440" viewBox="0 0 328 440" overflow="hidden">
+ <path d="M-37 471q10-118 78-173 28-23 28-73-3-49 37-62 49-18 82 11 24 22 27 60l-3 53q34 53 46 184Z" fill="#faf5e7"/>
+ <path d="M-30 414q29-55 91-63 60-6 89 104H-30Z" fill="#8fa8aa"/>
+ <path d="M14 391q27-28 55-22m-69 46q31-24 67-21" fill="none" stroke="#64878b" stroke-width="5" stroke-linecap="round"/>
+ <path d="M178 221q56-6 100 32l-15 17q-39-24-84-22Z" fill="#e2b64c"/>
+ <path d="m183 260 78 30q-34 10-71-4Z" fill="#c6993b"/>
+ <path d="M183 245q49-1 83 20" fill="none" stroke="#657064" stroke-width="4"/>
+ <circle cx="160" cy="201" r="11" fill="#e0ba57"/><circle cx="160" cy="201" r="5" fill="#203037"/>
+ <path d="m123 188 10-3m-24 22 10 1m-24 18 12 4m-13 19 11 2" stroke="#b7c6ba" stroke-width="3" stroke-linecap="round"/>
+ <path d="M39 21h233q20 0 20 20v62q0 20-20 20H115l-29 28 5-28H39q-20 0-20-20V41q0-20 20-20Z" fill="#faf5e7"/>
+ <circle cx="153" cy="71" r="25" fill="#60868b"/><ellipse cx="153" cy="71" rx="51" ry="11" transform="rotate(-24 153 71)" fill="none" stroke="#e0b858" stroke-width="7"/>
+ <path d="m224 43 3 8 8 3-8 3-3 8-3-8-8-3 8-3Zm-127-1 2 5 5 2-5 2-2 5-2-5-5-2 5-2Z" fill="#60868b"/>
+ </svg>
+ <rect x="328" width="16" height="440" fill="#faf5e7"/>
+ <svg x="344" width="328" height="440" viewBox="0 0 328 440" overflow="hidden">
+ <path d="M-44 471q0-110 77-143 31-14 37-73l29-68 128 51-4 81q70 32 89 152Z" fill="#9cafb0"/>
+ <path d="M50 291q21-23 22-62-3-47 29-68 36-24 73-8 41 17 40 71l-2 50q-64-19-89 5-41 38-73 12Z" fill="#faf5e7"/>
+ <path d="M204 211q53 0 99 31l-7 13q-49-22-93-19Z" fill="#e2b64c"/>
+ <path d="m205 247 92 23q-31 10-87-6Z" fill="#c6993b"/>
+ <path d="M212 231q44 1 85 18" fill="none" stroke="#657064" stroke-width="4"/>
+ <circle cx="185" cy="198" r="10" fill="#e0ba57"/><circle cx="185" cy="198" r="5" fill="#203037"/>
+ <path d="M79 315q69 3 91 70m-149-27q77 4 98 82m45-95q55 22 60 83" fill="none" stroke="#6e8a8f" stroke-width="6" stroke-linecap="round"/>
+ <path d="M67 20h197q22 0 22 22v61q0 22-22 22h-47l-20 29-5-29H67q-22 0-22-22V42q0-22 22-22Z" fill="#faf5e7"/>
+ <g transform="translate(167 75) rotate(-8)">
+ <path d="M-22 2v-33m12 31v-42m12 42v-32m12 32v-39m12 38v-27" stroke="#e1b449" stroke-width="9" stroke-linecap="round"/>
+ <path d="m-35-4 10 44q24 9 46 0l11-44q-35 13-67 0Z" fill="#df8a57"/><circle cy="23" r="7" fill="#faf5e7"/>
+ </g>
+ </svg>
+ </svg>
+ <path d="M60 501h181m-181 17h114" stroke="#b2b5a3" stroke-width="6" stroke-linecap="round"/>
+ <text x="625" y="523" fill="#597b69" font-family="ui-monospace,monospace" font-size="36" font-weight="700">02</text>
+ <path d="m663-8 59 66-34 24-57-66Z" fill="#d7b179" opacity=".9"/>
+ </g></g></g>
+ <g id="activity-movie"><rect width="1600" height="900" fill="#324458"/><rect width="1600" height="900" fill="#293e50"/>
+ <circle cx="1220" cy="387" r="302" fill="#516d76"/>
+ <path d="M1108 105a298 298 0 0 1 403 331" fill="none" stroke="#83938a" stroke-width="2"/>
+ <path d="M150 107v10m-5-5h10" stroke="#b5c9c1" stroke-width="3" stroke-linecap="round"/><path d="M365 173v10m-5-5h10" stroke="#b5c9c1" stroke-width="3" stroke-linecap="round"/><path d="M632 239v10m-5-5h10" stroke="#b5c9c1" stroke-width="3" stroke-linecap="round"/><path d="M859 107v10m-5-5h10" stroke="#b5c9c1" stroke-width="3" stroke-linecap="round"/><path d="M1042 173v10m-5-5h10" stroke="#b5c9c1" stroke-width="3" stroke-linecap="round"/><path d="M1491 239v10m-5-5h10" stroke="#b5c9c1" stroke-width="3" stroke-linecap="round"/>
+ <path d="M0 631 244 465 415 579 681 425 911 586 1211 466 1600 589v311H0Z" fill="#385661"/>
+ <path d="M0 728 312 650 594 700 859 616 1142 740 1600 644v256H0Z" fill="#233a47"/>
+ <path d="M837 805h727l-22-38H868Z" fill="#91a499"/>
+ <path d="M870 763h670l-24-37H902Z" fill="#a4b0a0"/>
+ <path d="M904 722h610l-29-38H936Z" fill="#bbc0a5"/>
+ <path d="M938 681h545l-25-38H970Z" fill="#d2ccb0"/>
+ <g id="hero-answer-machine">
+ <path d="m1112 581-68 67h321l-77-67Z" fill="#b69360"/>
+ <path d="m1164 478-42 132h155l-29-121Z" fill="#a48150"/>
+ <path d="m1137 535 11 66 19-42 29-2 45 54 9-84Z" fill="#354851"/>
+ <path d="m999 176 52-45 424 43q17 2 15 19l-28 290-56 53Z" fill="#a7804d"/>
+ <path d="m1001 176 50-45 422 44-50 46Z" fill="#efd78f"/>
+ <path d="M1009 176 1420 219q15 1 13 18l-26 294q-2 16-18 14L987 499q-17-2-16-20l22-287q1-18 16-16Z" fill="#d6ae65"/>
+ <path d="m1010 194 399 42-22 289-397-44Z" fill="#e6c580"/>
+ <path d="M1067 285 1349 314l-12 139-282-30Z" fill="#263d43"/>
+ <path d="m1077 297 258 27-8 113-260-28Z" fill="#365654"/>
+ <path d="m1016 241 76 8m235 25 65 7m-376 209 58 6m192 21 77 8" stroke="#b49155" stroke-width="5" stroke-linecap="round"/>
+ <path d="m1456 225-19 213m6-160-12 134" stroke="#806843" stroke-width="6" stroke-linecap="round"/>
+ <circle cx="1304" cy="487" r="6" fill="#9bba93"/><circle cx="1327" cy="490" r="6" fill="#9bba93"/><circle cx="1350" cy="493" r="6" fill="#9bba93"/>
+ <g id="hero-answer" transform="translate(1202 368) rotate(6)" fill="none" stroke="#f3d786" stroke-width="15" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M-51-42-80 13h59m-14-55v89M4-23q0-26 27-26t27 24q0 13-16 27L7 42h54"/>
+ </g>
+ </g>
+ <g transform="translate(907 753) rotate(6)"><path d="M-14 45q0-37 14-37t14 37Z" fill="#97bbad"/><circle cy="-7" r="10" fill="#97bbad"/><path d="M-4-8v2m8-2v2" stroke="#263b43" stroke-width="2" stroke-linecap="round"/></g><g transform="translate(1031 784) rotate(-7)"><path d="M-14 45q0-37 14-37t14 37Z" fill="#d69883"/><circle cy="-7" r="10" fill="#d69883"/><path d="M-4-8v2m8-2v2" stroke="#263b43" stroke-width="2" stroke-linecap="round"/></g><g transform="translate(1410 738) rotate(6)"><path d="M-14 45q0-37 14-37t14 37Z" fill="#a6b9cf"/><circle cy="-7" r="10" fill="#a6b9cf"/><path d="M-4-8v2m8-2v2" stroke="#263b43" stroke-width="2" stroke-linecap="round"/></g><g transform="translate(1514 790) rotate(-7)"><path d="M-14 45q0-37 14-37t14 37Z" fill="#d7bb7c"/><circle cy="-7" r="10" fill="#d7bb7c"/><path d="M-4-8v2m8-2v2" stroke="#263b43" stroke-width="2" stroke-linecap="round"/></g>
+ <path d="M0 28h1600M0 873h1600" stroke="#152b3b" stroke-width="56"/></g><style>#hero-rpg-water{transform:translate(-5.69px,0px)}#hero-rpg-flowers{transform:skewX(-1.22deg)}#hero-rpg-shadow{transform:translate(907.7px,544.82px)}#hero-rpg-player{transform:translate(907.7px,522.94px) rotate(2.88deg)}#hero-rpg-lid{transform:scaleY(1)}#hero-rpg-treasure{transform:translate(1028px,457px) scale(0)}#hero-paper{transform:translate(0px,0px)}#hero-pencil{transform:translate(1160px,670px) rotate(28deg)}#hero-photos{transform:translate(800px,450px) scale(0.97) translate(-800px,-450px)}#hero-answer{transform:translate(1202px,380px) rotate(6deg) scale(0.92,0.08)}#activity-rpg{opacity:1}#activity-drawing{opacity:0}#activity-photos{opacity:0}#activity-movie{opacity:0}
+ @media(prefers-reduced-motion:no-preference){#hero-rpg-water{animation:hero-rpg-water 20s linear infinite}#hero-rpg-flowers{animation:hero-rpg-flowers 20s linear infinite}#hero-rpg-shadow{animation:hero-rpg-shadow 20s linear infinite}#hero-rpg-player{animation:hero-rpg-player 20s linear infinite}#hero-rpg-lid{animation:hero-rpg-lid 20s linear infinite}#hero-rpg-treasure{animation:hero-rpg-treasure 20s linear infinite}#hero-paper{animation:hero-paper 20s linear infinite}#hero-pencil{animation:hero-pencil 20s linear infinite}#hero-photos{animation:hero-photos 20s linear infinite}#hero-answer{animation:hero-answer 20s linear infinite}#activity-rpg{animation:activity-rpg 20s steps(1,end) infinite}#activity-drawing{animation:activity-drawing 20s steps(1,end) infinite}#activity-photos{animation:activity-photos 20s steps(1,end) infinite}#activity-movie{animation:activity-movie 20s steps(1,end) infinite}}
+ :root:target #hero-rpg-water,:root:target #hero-rpg-flowers,:root:target #hero-rpg-shadow,:root:target #hero-rpg-player,:root:target #hero-rpg-lid,:root:target #hero-rpg-treasure,:root:target #hero-paper,:root:target #hero-pencil,:root:target #hero-photos,:root:target #hero-answer,:root:target #activity-rpg,:root:target #activity-drawing,:root:target #activity-photos,:root:target #activity-movie{animation:none}
+ @keyframes hero-rpg-water{0%{transform:translate(-5.69px,0px)}0.417%{transform:translate(-6.08px,0px)}0.833%{transform:translate(-6.45px,0px)}1.25%{transform:translate(-6.82px,0px)}1.667%{transform:translate(-7.19px,0px)}2.083%{transform:translate(-7.55px,0px)}2.5%{transform:translate(-7.9px,0px)}2.917%{transform:translate(-8.24px,0px)}3.333%{transform:translate(-8.58px,0px)}3.75%{transform:translate(-8.91px,0px)}4.167%{transform:translate(-9.23px,0px)}4.583%{transform:translate(-9.54px,0px)}5%{transform:translate(-9.85px,0px)}5.417%{transform:translate(-10.14px,0px)}5.833%{transform:translate(-10.43px,0px)}6.25%{transform:translate(-10.7px,0px)}6.667%{transform:translate(-10.97px,0px)}7.083%{transform:translate(-11.23px,0px)}7.5%{transform:translate(-11.48px,0px)}7.917%{transform:translate(-11.71px,0px)}8.333%{transform:translate(-11.94px,0px)}8.75%{transform:translate(-12.15px,0px)}9.167%{transform:translate(-12.36px,0px)}9.583%{transform:translate(-12.55px,0px)}10%{transform:translate(-12.73px,0px)}10.417%{transform:translate(-12.9px,0px)}10.833%{transform:translate(-13.06px,0px)}11.25%{transform:translate(-13.2px,0px)}11.667%{transform:translate(-13.34px,0px)}12.083%{transform:translate(-13.46px,0px)}12.5%{transform:translate(-13.57px,0px)}12.917%{transform:translate(-13.67px,0px)}13.333%{transform:translate(-13.75px,0px)}13.75%{transform:translate(-13.82px,0px)}14.167%{transform:translate(-13.88px,0px)}14.583%{transform:translate(-13.93px,0px)}15%{transform:translate(-13.97px,0px)}15.417%{transform:translate(-13.99px,0px)}15.833%{transform:translate(-14px,0px)}16.25%{transform:translate(-14px,0px)}16.667%{transform:translate(-13.98px,0px)}17.083%{transform:translate(-13.95px,0px)}17.5%{transform:translate(-13.91px,0px)}17.917%{transform:translate(-13.86px,0px)}18.333%{transform:translate(-13.79px,0px)}18.75%{transform:translate(-13.71px,0px)}19.167%{transform:translate(-13.62px,0px)}19.583%{transform:translate(-13.52px,0px)}20%{transform:translate(-13.4px,0px)}20.417%{transform:translate(-13.27px,0px)}20.833%{transform:translate(-13.13px,0px)}21.25%{transform:translate(-12.98px,0px)}21.667%{transform:translate(-12.82px,0px)}22.083%{transform:translate(-12.64px,0px)}22.5%{transform:translate(-12.46px,0px)}22.917%{transform:translate(-12.26px,0px)}23.333%{transform:translate(-12.05px,0px)}23.75%{transform:translate(-11.83px,0px)}24.167%{transform:translate(-11.6px,0px)}24.583%{transform:translate(-11.36px,0px)}25%{transform:translate(-11.11px,0px)}100%{transform:translate(-11.11px,0px)}}@keyframes hero-rpg-flowers{0%{transform:skewX(-1.22deg)}0.417%{transform:skewX(-1.3deg)}0.833%{transform:skewX(-1.38deg)}1.25%{transform:skewX(-1.46deg)}1.667%{transform:skewX(-1.54deg)}2.083%{transform:skewX(-1.62deg)}2.5%{transform:skewX(-1.69deg)}2.917%{transform:skewX(-1.77deg)}3.333%{transform:skewX(-1.84deg)}3.75%{transform:skewX(-1.91deg)}4.167%{transform:skewX(-1.98deg)}4.583%{transform:skewX(-2.05deg)}5%{transform:skewX(-2.11deg)}5.417%{transform:skewX(-2.17deg)}5.833%{transform:skewX(-2.23deg)}6.25%{transform:skewX(-2.29deg)}6.667%{transform:skewX(-2.35deg)}7.083%{transform:skewX(-2.41deg)}7.5%{transform:skewX(-2.46deg)}7.917%{transform:skewX(-2.51deg)}8.333%{transform:skewX(-2.56deg)}8.75%{transform:skewX(-2.6deg)}9.167%{transform:skewX(-2.65deg)}9.583%{transform:skewX(-2.69deg)}10%{transform:skewX(-2.73deg)}10.417%{transform:skewX(-2.76deg)}10.833%{transform:skewX(-2.8deg)}11.25%{transform:skewX(-2.83deg)}11.667%{transform:skewX(-2.86deg)}12.083%{transform:skewX(-2.88deg)}12.5%{transform:skewX(-2.91deg)}12.917%{transform:skewX(-2.93deg)}13.333%{transform:skewX(-2.95deg)}13.75%{transform:skewX(-2.96deg)}14.167%{transform:skewX(-2.98deg)}14.583%{transform:skewX(-2.99deg)}15%{transform:skewX(-2.99deg)}15.417%{transform:skewX(-3deg)}16.667%{transform:skewX(-3deg)}17.083%{transform:skewX(-2.99deg)}17.5%{transform:skewX(-2.98deg)}17.917%{transform:skewX(-2.97deg)}18.333%{transform:skewX(-2.96deg)}18.75%{transform:skewX(-2.94deg)}19.167%{transform:skewX(-2.92deg)}19.583%{transform:skewX(-2.9deg)}20%{transform:skewX(-2.87deg)}20.417%{transform:skewX(-2.84deg)}20.833%{transform:skewX(-2.81deg)}21.25%{transform:skewX(-2.78deg)}21.667%{transform:skewX(-2.75deg)}22.083%{transform:skewX(-2.71deg)}22.5%{transform:skewX(-2.67deg)}22.917%{transform:skewX(-2.63deg)}23.333%{transform:skewX(-2.58deg)}23.75%{transform:skewX(-2.54deg)}24.167%{transform:skewX(-2.49deg)}24.583%{transform:skewX(-2.43deg)}25%{transform:skewX(-2.38deg)}100%{transform:skewX(-2.38deg)}}@keyframes hero-rpg-shadow{0%{transform:translate(907.7px,544.82px)}0.417%{transform:translate(909.69px,543.89px)}0.833%{transform:translate(911.61px,543px)}1.25%{transform:translate(913.45px,542.15px)}1.667%{transform:translate(915.21px,541.33px)}2.083%{transform:translate(916.88px,540.55px)}2.5%{transform:translate(918.47px,539.82px)}2.917%{transform:translate(919.97px,539.12px)}3.333%{transform:translate(921.39px,538.46px)}3.75%{transform:translate(922.71px,537.85px)}4.167%{transform:translate(923.94px,537.28px)}4.583%{transform:translate(925.08px,536.75px)}5%{transform:translate(926.12px,536.26px)}5.417%{transform:translate(927.07px,535.82px)}5.833%{transform:translate(927.92px,535.43px)}6.25%{transform:translate(928.67px,535.08px)}6.667%{transform:translate(929.32px,534.78px)}7.083%{transform:translate(929.86px,534.53px)}7.5%{transform:translate(930.3px,534.32px)}7.917%{transform:translate(930.64px,534.17px)}8.333%{transform:translate(930.86px,534.06px)}8.75%{transform:translate(930.98px,534.01px)}9.167%{transform:translate(931px,534px)}100%{transform:translate(931px,534px)}}@keyframes hero-rpg-player{0%{transform:translate(907.7px,522.94px) rotate(2.88deg)}0.417%{transform:translate(909.69px,522.53px) rotate(2.36deg)}0.833%{transform:translate(911.61px,522.46px) rotate(1.54deg)}1.25%{transform:translate(913.45px,522.58px) rotate(0.57deg)}1.667%{transform:translate(915.21px,521.9px) rotate(-0.43deg)}2.083%{transform:translate(916.88px,520.22px) rotate(-1.34deg)}2.5%{transform:translate(918.47px,518.74px) rotate(-2.07deg)}2.917%{transform:translate(919.97px,517.52px) rotate(-2.6deg)}3.333%{transform:translate(921.39px,516.56px) rotate(-2.9deg)}3.75%{transform:translate(922.71px,515.85px) rotate(-3deg)}4.167%{transform:translate(923.94px,515.36px) rotate(-2.92deg)}4.583%{transform:translate(925.08px,515.04px) rotate(-2.71deg)}5%{transform:translate(926.12px,514.87px) rotate(-2.4deg)}5.417%{transform:translate(927.07px,514.79px) rotate(-2.04deg)}5.833%{transform:translate(927.92px,514.77px) rotate(-1.66deg)}6.25%{transform:translate(928.67px,514.8px) rotate(-1.29deg)}6.667%{transform:translate(929.32px,514.84px) rotate(-0.94deg)}7.083%{transform:translate(929.86px,514.89px) rotate(-0.64deg)}7.5%{transform:translate(930.3px,514.93px) rotate(-0.4deg)}7.917%{transform:translate(930.64px,514.96px) rotate(-0.21deg)}8.333%{transform:translate(930.86px,514.99px) rotate(-0.08deg)}8.75%{transform:translate(930.98px,515px) rotate(-0.01deg)}9.167%{transform:translate(931px,515px) rotate(0deg)}100%{transform:translate(931px,515px) rotate(0deg)}}@keyframes hero-rpg-lid{0%{transform:scaleY(1)}9.583%{transform:scaleY(1)}10%{transform:scaleY(0.99)}10.417%{transform:scaleY(0.85)}10.833%{transform:scaleY(0.59)}11.25%{transform:scaleY(0.26)}11.667%{transform:scaleY(-0.09)}12.083%{transform:scaleY(-0.4)}12.5%{transform:scaleY(-0.62)}12.917%{transform:scaleY(-0.7)}100%{transform:scaleY(-0.7)}}@keyframes hero-rpg-treasure{0%{transform:translate(1028px,457px) scale(0)}11.25%{transform:translate(1028px,457px) scale(0)}11.667%{transform:translate(1028px,456.97px) scale(0)}12.083%{transform:translate(1028px,455.52px) scale(0.04)}12.5%{transform:translate(1028px,452.12px) scale(0.11)}12.917%{transform:translate(1028px,447.06px) scale(0.22)}13.333%{transform:translate(1028px,440.59px) scale(0.35)}13.75%{transform:translate(1028px,433px) scale(0.49)}14.167%{transform:translate(1028px,424.54px) scale(0.64)}14.583%{transform:translate(1028px,415.5px) scale(0.77)}15%{transform:translate(1028px,406.14px) scale(0.88)}15.417%{transform:translate(1028px,396.73px) scale(0.96)}15.833%{transform:translate(1028px,387.55px) scale(1)}16.25%{transform:translate(1028px,378.86px) scale(1)}16.667%{transform:translate(1028px,370.93px) scale(1)}17.083%{transform:translate(1028px,364.04px) scale(1)}17.5%{transform:translate(1028px,358.46px) scale(1)}17.917%{transform:translate(1028px,354.46px) scale(1)}18.333%{transform:translate(1028px,352.3px) scale(1)}18.75%{transform:translate(1028px,352px) scale(1)}100%{transform:translate(1028px,352px) scale(1)}}@keyframes hero-paper{0%{transform:translate(0px,0px)}25%{transform:translate(0px,0px)}25.417%{transform:translate(0px,0.6271707796059207px)}25.833%{transform:translate(0px,1.247470144906556px)}26.25%{transform:translate(0px,1.8541019662496843px)}26.667%{transform:translate(0px,2.440419858454801px)}27.083%{transform:translate(0px,2.9999999999999996px)}27.5%{transform:translate(0px,3.526711513754839px)}27.917%{transform:translate(0px,4.014783638153149px)}28.333%{transform:translate(0px,4.458868952864366px)}28.75%{transform:translate(0px,4.854101966249685px)}29.167%{transform:translate(0px,5.196152422706632px)}29.583%{transform:translate(0px,5.481272745855605px)}30%{transform:translate(0px,5.706339097770921px)}30.417%{transform:translate(0px,5.868885604402834px)}30.833%{transform:translate(0px,5.967131372209639px)}31.25%{transform:translate(0px,6px)}31.667%{transform:translate(0px,5.96713137220964px)}32.083%{transform:translate(0px,5.868885604402834px)}32.5%{transform:translate(0px,5.706339097770922px)}32.917%{transform:translate(0px,5.481272745855605px)}33.333%{transform:translate(0px,5.196152422706632px)}33.75%{transform:translate(0px,4.854101966249685px)}34.167%{transform:translate(0px,4.458868952864367px)}34.583%{transform:translate(0px,4.014783638153148px)}35%{transform:translate(0px,3.5267115137548393px)}35.417%{transform:translate(0px,2.9999999999999996px)}35.833%{transform:translate(0px,2.4404198584548px)}36.25%{transform:translate(0px,1.8541019662496852px)}36.667%{transform:translate(0px,1.247470144906556px)}37.083%{transform:translate(0px,0.6271707796059224px)}37.5%{transform:translate(0px,7.347880794884119e-16px)}37.917%{transform:translate(0px,-0.6271707796059209px)}38.333%{transform:translate(0px,-1.2474701449065544px)}38.75%{transform:translate(0px,-1.8541019662496865px)}39.167%{transform:translate(0px,-2.440419858454799px)}39.583%{transform:translate(0px,-3.000000000000001px)}40%{transform:translate(0px,-3.5267115137548384px)}40.417%{transform:translate(0px,-4.014783638153149px)}40.833%{transform:translate(0px,-4.458868952864364px)}41.25%{transform:translate(0px,-4.854101966249684px)}41.667%{transform:translate(0px,-5.196152422706631px)}42.083%{transform:translate(0px,-5.481272745855605px)}42.5%{transform:translate(0px,-5.706339097770921px)}42.917%{transform:translate(0px,-5.868885604402833px)}43.333%{transform:translate(0px,-5.967131372209639px)}43.75%{transform:translate(0px,-6px)}44.167%{transform:translate(0px,-5.967131372209639px)}44.583%{transform:translate(0px,-5.868885604402833px)}45%{transform:translate(0px,-5.706339097770922px)}45.417%{transform:translate(0px,-5.481272745855606px)}45.833%{transform:translate(0px,-5.196152422706632px)}46.25%{transform:translate(0px,-4.854101966249686px)}46.667%{transform:translate(0px,-4.458868952864364px)}47.083%{transform:translate(0px,-4.014783638153153px)}47.5%{transform:translate(0px,-3.52671151375484px)}47.917%{transform:translate(0px,-3.0000000000000027px)}48.333%{transform:translate(0px,-2.440419858454801px)}48.75%{transform:translate(0px,-1.8541019662496856px)}49.167%{transform:translate(0px,-1.2474701449065593px)}49.583%{transform:translate(0px,-0.6271707796059258px)}50%{transform:translate(0px,-1.4695761589768238e-15px)}100%{transform:translate(0px,-1.4695761589768238e-15px)}}@keyframes hero-pencil{0%{transform:translate(1160px,670px) rotate(28deg)}25%{transform:translate(1160px,670px) rotate(28deg)}25.417%{transform:translate(1161.8815123388179px,669.9452189536827px) rotate(28.31358538980296deg)}25.833%{transform:translate(1163.7424104347197px,669.781476007338px) rotate(28.62373507245328deg)}26.25%{transform:translate(1165.562305898749px,669.5105651629515px) rotate(28.927050983124843deg)}26.667%{transform:translate(1167.3212595753644px,669.135454576426px) rotate(29.2202099292274deg)}27.083%{transform:translate(1169px,668.6602540378444px) rotate(29.5deg)}27.5%{transform:translate(1170.5801345412644px,668.0901699437495px) rotate(29.76335575687742deg)}27.917%{transform:translate(1172.0443509144595px,667.431448254774px) rotate(30.007391819076574deg)}28.333%{transform:translate(1173.376606858593px,666.6913060635886px) rotate(30.229434476432182deg)}28.75%{transform:translate(1174.562305898749px,665.8778525229247px) rotate(30.427050983124843deg)}29.167%{transform:translate(1175.5884572681198px,665px) rotate(30.598076211353316deg)}29.583%{transform:translate(1176.4438182375668px,664.067366430758px) rotate(30.740636372927803deg)}30%{transform:translate(1177.1190172933127px,663.0901699437495px) rotate(30.85316954888546deg)}30.417%{transform:translate(1177.6066568132085px,662.0791169081776px) rotate(30.934442802201417deg)}30.833%{transform:translate(1177.9013941166288px,661.0452846326765px) rotate(30.983565686104818deg)}31.25%{transform:translate(1178px,660px) rotate(31deg)}31.667%{transform:translate(1177.901394116629px,658.9547153673235px) rotate(30.98356568610482deg)}32.083%{transform:translate(1177.6066568132085px,657.9208830918224px) rotate(30.934442802201417deg)}32.5%{transform:translate(1177.1190172933127px,656.9098300562505px) rotate(30.85316954888546deg)}32.917%{transform:translate(1176.4438182375668px,655.932633569242px) rotate(30.740636372927803deg)}33.333%{transform:translate(1175.5884572681198px,655px) rotate(30.598076211353316deg)}33.75%{transform:translate(1174.562305898749px,654.1221474770753px) rotate(30.427050983124843deg)}34.167%{transform:translate(1173.376606858593px,653.3086939364114px) rotate(30.229434476432182deg)}34.583%{transform:translate(1172.0443509144595px,652.568551745226px) rotate(30.007391819076574deg)}35%{transform:translate(1170.5801345412644px,651.9098300562505px) rotate(29.76335575687742deg)}35.417%{transform:translate(1169px,651.3397459621556px) rotate(29.5deg)}35.833%{transform:translate(1167.3212595753644px,650.864545423574px) rotate(29.2202099292274deg)}36.25%{transform:translate(1165.562305898749px,650.4894348370485px) rotate(28.927050983124843deg)}36.667%{transform:translate(1163.7424104347197px,650.218523992662px) rotate(28.62373507245328deg)}37.083%{transform:translate(1161.8815123388179px,650.0547810463173px) rotate(28.31358538980296deg)}37.5%{transform:translate(1160px,650px) rotate(28deg)}37.917%{transform:translate(1158.1184876611821px,650.0547810463173px) rotate(27.68641461019704deg)}38.333%{transform:translate(1156.2575895652803px,650.218523992662px) rotate(27.37626492754672deg)}38.75%{transform:translate(1154.437694101251px,650.4894348370485px) rotate(27.072949016875157deg)}39.167%{transform:translate(1152.6787404246356px,650.864545423574px) rotate(26.7797900707726deg)}39.583%{transform:translate(1151px,651.3397459621556px) rotate(26.5deg)}40%{transform:translate(1149.4198654587356px,651.9098300562505px) rotate(26.23664424312258deg)}40.417%{transform:translate(1147.9556490855405px,652.568551745226px) rotate(25.992608180923426deg)}40.833%{transform:translate(1146.623393141407px,653.3086939364114px) rotate(25.770565523567818deg)}41.25%{transform:translate(1145.437694101251px,654.1221474770753px) rotate(25.572949016875157deg)}41.667%{transform:translate(1144.4115427318802px,655px) rotate(25.401923788646684deg)}42.083%{transform:translate(1143.5561817624332px,655.932633569242px) rotate(25.259363627072197deg)}42.5%{transform:translate(1142.8809827066873px,656.9098300562505px) rotate(25.14683045111454deg)}42.917%{transform:translate(1142.3933431867915px,657.9208830918224px) rotate(25.065557197798583deg)}43.333%{transform:translate(1142.0986058833712px,658.9547153673235px) rotate(25.016434313895182deg)}43.75%{transform:translate(1142px,660px) rotate(25deg)}44.167%{transform:translate(1142.0986058833712px,661.0452846326765px) rotate(25.016434313895182deg)}44.583%{transform:translate(1142.3933431867915px,662.0791169081776px) rotate(25.065557197798583deg)}45%{transform:translate(1142.8809827066873px,663.0901699437495px) rotate(25.14683045111454deg)}45.417%{transform:translate(1143.5561817624332px,664.0673664307579px) rotate(25.259363627072197deg)}45.833%{transform:translate(1144.4115427318802px,665px) rotate(25.401923788646684deg)}46.25%{transform:translate(1145.437694101251px,665.8778525229247px) rotate(25.572949016875157deg)}46.667%{transform:translate(1146.623393141407px,666.6913060635886px) rotate(25.770565523567818deg)}47.083%{transform:translate(1147.9556490855405px,667.431448254774px) rotate(25.992608180923423deg)}47.5%{transform:translate(1149.4198654587356px,668.0901699437495px) rotate(26.23664424312258deg)}47.917%{transform:translate(1151px,668.6602540378444px) rotate(26.5deg)}48.333%{transform:translate(1152.6787404246356px,669.135454576426px) rotate(26.7797900707726deg)}48.75%{transform:translate(1154.437694101251px,669.5105651629515px) rotate(27.072949016875157deg)}49.167%{transform:translate(1156.2575895652803px,669.781476007338px) rotate(27.37626492754672deg)}49.583%{transform:translate(1158.1184876611821px,669.9452189536827px) rotate(27.686414610197037deg)}50%{transform:translate(1160px,670px) rotate(28deg)}100%{transform:translate(1160px,670px) rotate(28deg)}}@keyframes hero-photos{0%{transform:translate(800px,450px) scale(0.97) translate(-800px,-450px)}50%{transform:translate(800px,450px) scale(0.97) translate(-800px,-450px)}50.417%{transform:translate(800px,450px) scale(0.97075) translate(-800px,-450px)}50.833%{transform:translate(800px,450px) scale(0.9714999999999999) translate(-800px,-450px)}51.25%{transform:translate(800px,450px) scale(0.97225) translate(-800px,-450px)}51.667%{transform:translate(800px,450px) scale(0.973) translate(-800px,-450px)}52.083%{transform:translate(800px,450px) scale(0.97375) translate(-800px,-450px)}52.5%{transform:translate(800px,450px) scale(0.9744999999999999) translate(-800px,-450px)}52.917%{transform:translate(800px,450px) scale(0.97525) translate(-800px,-450px)}53.333%{transform:translate(800px,450px) scale(0.976) translate(-800px,-450px)}53.75%{transform:translate(800px,450px) scale(0.97675) translate(-800px,-450px)}54.167%{transform:translate(800px,450px) scale(0.9774999999999999) translate(-800px,-450px)}54.583%{transform:translate(800px,450px) scale(0.97825) translate(-800px,-450px)}55%{transform:translate(800px,450px) scale(0.979) translate(-800px,-450px)}55.417%{transform:translate(800px,450px) scale(0.97975) translate(-800px,-450px)}55.833%{transform:translate(800px,450px) scale(0.9804999999999999) translate(-800px,-450px)}56.25%{transform:translate(800px,450px) scale(0.98125) translate(-800px,-450px)}56.667%{transform:translate(800px,450px) scale(0.982) translate(-800px,-450px)}57.083%{transform:translate(800px,450px) scale(0.98275) translate(-800px,-450px)}57.5%{transform:translate(800px,450px) scale(0.9834999999999999) translate(-800px,-450px)}57.917%{transform:translate(800px,450px) scale(0.98425) translate(-800px,-450px)}58.333%{transform:translate(800px,450px) scale(0.985) translate(-800px,-450px)}58.75%{transform:translate(800px,450px) scale(0.98575) translate(-800px,-450px)}59.167%{transform:translate(800px,450px) scale(0.9864999999999999) translate(-800px,-450px)}59.583%{transform:translate(800px,450px) scale(0.98725) translate(-800px,-450px)}60%{transform:translate(800px,450px) scale(0.988) translate(-800px,-450px)}60.417%{transform:translate(800px,450px) scale(0.98875) translate(-800px,-450px)}60.833%{transform:translate(800px,450px) scale(0.9894999999999999) translate(-800px,-450px)}61.25%{transform:translate(800px,450px) scale(0.99025) translate(-800px,-450px)}61.667%{transform:translate(800px,450px) scale(0.991) translate(-800px,-450px)}62.083%{transform:translate(800px,450px) scale(0.99175) translate(-800px,-450px)}62.5%{transform:translate(800px,450px) scale(0.9924999999999999) translate(-800px,-450px)}62.917%{transform:translate(800px,450px) scale(0.99325) translate(-800px,-450px)}63.333%{transform:translate(800px,450px) scale(0.994) translate(-800px,-450px)}63.75%{transform:translate(800px,450px) scale(0.99475) translate(-800px,-450px)}64.167%{transform:translate(800px,450px) scale(0.9954999999999999) translate(-800px,-450px)}64.583%{transform:translate(800px,450px) scale(0.99625) translate(-800px,-450px)}65%{transform:translate(800px,450px) scale(0.997) translate(-800px,-450px)}65.417%{transform:translate(800px,450px) scale(0.99775) translate(-800px,-450px)}65.833%{transform:translate(800px,450px) scale(0.9984999999999999) translate(-800px,-450px)}66.25%{transform:translate(800px,450px) scale(0.99925) translate(-800px,-450px)}66.667%{transform:translate(800px,450px) scale(1) translate(-800px,-450px)}67.083%{transform:translate(800px,450px) scale(1.00075) translate(-800px,-450px)}67.5%{transform:translate(800px,450px) scale(1.0015) translate(-800px,-450px)}67.917%{transform:translate(800px,450px) scale(1.00225) translate(-800px,-450px)}68.333%{transform:translate(800px,450px) scale(1.003) translate(-800px,-450px)}68.75%{transform:translate(800px,450px) scale(1.00375) translate(-800px,-450px)}69.167%{transform:translate(800px,450px) scale(1.0045) translate(-800px,-450px)}69.583%{transform:translate(800px,450px) scale(1.00525) translate(-800px,-450px)}70%{transform:translate(800px,450px) scale(1.006) translate(-800px,-450px)}70.417%{transform:translate(800px,450px) scale(1.00675) translate(-800px,-450px)}70.833%{transform:translate(800px,450px) scale(1.0075) translate(-800px,-450px)}71.25%{transform:translate(800px,450px) scale(1.0082499999999999) translate(-800px,-450px)}71.667%{transform:translate(800px,450px) scale(1.009) translate(-800px,-450px)}72.083%{transform:translate(800px,450px) scale(1.00975) translate(-800px,-450px)}72.5%{transform:translate(800px,450px) scale(1.0105) translate(-800px,-450px)}72.917%{transform:translate(800px,450px) scale(1.01125) translate(-800px,-450px)}73.333%{transform:translate(800px,450px) scale(1.012) translate(-800px,-450px)}73.75%{transform:translate(800px,450px) scale(1.01275) translate(-800px,-450px)}74.167%{transform:translate(800px,450px) scale(1.0135) translate(-800px,-450px)}74.583%{transform:translate(800px,450px) scale(1.0142499999999999) translate(-800px,-450px)}75%{transform:translate(800px,450px) scale(1.015) translate(-800px,-450px)}100%{transform:translate(800px,450px) scale(1.015) translate(-800px,-450px)}}@keyframes hero-answer{0%{transform:translate(1202px,380px) rotate(6deg) scale(0.92,0.08)}75%{transform:translate(1202px,380px) rotate(6deg) scale(0.92,0.08)}75.417%{transform:translate(1202px,378.409303078799px) rotate(6deg) scale(0.9306046461413403,0.20195343062541277)}75.833%{transform:translate(1202px,376.96578265508305px) rotate(6deg) scale(0.9402281156327796,0.31262332977696483)}76.25%{transform:translate(1202px,375.6622942386831px) rotate(6deg) scale(0.9489180384087792,0.4125574417009602)}76.667%{transform:translate(1202px,374.49169333942996px) rotate(6deg) scale(0.9567220444038003,0.5023035106437027)}77.083%{transform:translate(1202px,373.4468354671544px) rotate(6deg) scale(0.963687763552304,0.5824092808514962)}77.5%{transform:translate(1202px,372.5205761316872px) rotate(6deg) scale(0.9698628257887517,0.6534224965706447)}77.917%{transform:translate(1202px,371.7057708428593px) rotate(6deg) scale(0.9752948610476045,0.7158909020474521)}78.333%{transform:translate(1202px,370.99527511050144px) rotate(6deg) scale(0.9800314992633238,0.7703622415282224)}78.75%{transform:translate(1202px,370.38194444444446px) rotate(6deg) scale(0.9841203703703705,0.8173842592592594)}79.167%{transform:translate(1202px,369.85863435451915px) rotate(6deg) scale(0.9876091043032058,0.8575046994868669)}79.583%{transform:translate(1202px,369.41820035055633px) rotate(6deg) scale(0.9905453309962913,0.891271306457349)}80%{transform:translate(1202px,369.05349794238685px) rotate(6deg) scale(0.9929766803840878,0.9192318244170096)}80.417%{transform:translate(1202px,368.75738263984147px) rotate(6deg) scale(0.9949507824010568,0.9419339976121527)}80.833%{transform:translate(1202px,368.5227099527511px) rotate(6deg) scale(0.9965152669816594,0.959925570289082)}81.25%{transform:translate(1202px,368.3423353909465px) rotate(6deg) scale(0.9977177640603567,0.9737542866941016)}81.667%{transform:translate(1202px,368.2091144642585px) rotate(6deg) scale(0.99860590357161,0.9839678910735152)}82.083%{transform:translate(1202px,368.1159026825179px) rotate(6deg) scale(0.9992273154498806,0.9911141276736269)}82.5%{transform:translate(1202px,368.05555555555554px) rotate(6deg) scale(0.9996296296296296,0.9957407407407407)}82.917%{transform:translate(1202px,368.02092859320226px) rotate(6deg) scale(0.9998604760453184,0.9983954745211604)}83.333%{transform:translate(1202px,368.0048773052888px) rotate(6deg) scale(0.9999674846314078,0.9996260732611898)}83.75%{transform:translate(1202px,368.0002572016461px) rotate(6deg) scale(0.9999982853223595,0.9999802812071331)}84.167%{transform:translate(1202px,368px) rotate(6deg) scale(1,1)}99.999%{transform:translate(1202px,368px) rotate(6deg) scale(1,1)}100%{transform:translate(1202px,380px) rotate(6deg) scale(0.92,0.08)}}@keyframes activity-rpg{0%{opacity:1}25%{opacity:0}100%{opacity:0}}@keyframes activity-drawing{0%{opacity:0}25%{opacity:1}50%{opacity:0}100%{opacity:0}}@keyframes activity-photos{0%{opacity:0}50%{opacity:1}75%{opacity:0}100%{opacity:0}}@keyframes activity-movie{0%{opacity:0}75%{opacity:1}100%{opacity:0}}</style></svg>
+ <!-- /Shared activities -->
+ </g>
+ <circle cx="470" cy="316" r="2.5" fill="#f7f4e9" stroke="none"/>
+ <rect x="245" y="346" width="447" height="18" rx="9" fill="#d6b58d"/><path d="M267 365v47m403-47v47"/>
+ <!-- Familiar room objects and the Piik mascot. -->
+ <path d="M126 343v-76m0 45c-27-3-40-18-36-38 25 3 36 17 36 38Zm0-22c28-3 39-19 35-37-24 2-34 18-35 37Z" fill="#79b398"/>
+ <path d="M126 272c-21-8-27-26-17-42 19 11 24 25 17 42Z" fill="#a0c7a2"/>
+ <path d="m103 334 6 40c2 9 32 9 34 0l6-40Z" fill="#e0bd99"/><path d="M103 334h46"/>
+ <g transform="rotate(8 746 154)">
+ <rect x="702" y="109" width="88" height="79" rx="26" fill="#fffdf5" stroke="none"/>
+ <g transform="translate(715 117) scale(1.9)" stroke-width="2.3"><path d="m11 4 5 4 5-4"/><rect x="4" y="8" width="24" height="18" rx="5"/><circle cx="11.5" cy="16.5" r="1.25" fill="#22303e" stroke="none"/><path d="M19 17q2.3-3 4.7 0M10 29l2-3m10 3-2-3"/></g>
+ </g>
+ <path d="m749 237 5 11 12 3-12 4-5 11-3-12-11-3 11-4Z" fill="#f4cc74" stroke="none"/>
+ <!-- The same simple figures as the UI; each has its own quiet cadence. -->
+ <path d="m355 490-5 29m387-29 5 29M162 482v28m128-28v28" stroke-width="5"/>
+ <rect x="322" y="373" width="453" height="115" rx="39" fill="#e9ad63" stroke="none"/>
+ <path d="M474 382v99m148-99v99" stroke="#cd8845" stroke-width="2.5"/>
+ <rect x="119" y="366" width="196" height="125" rx="40" fill="#cd8845" stroke="none"/>
+ <rect x="137" y="379" width="160" height="98" rx="30" fill="#e9ad63" stroke="none"/>
+ <g transform="translate(216 362) rotate(6 0 59)" color="#83c4a5" style="--pace:43s;--phase:-4s">
+ <g class="person-body"><use href="#person"/><g transform="translate(3 -2)"><g class="person-eyes"><use href="#eyes"/></g></g>
+ <!-- Crown geometry and colours match the shared UI HostMark. -->
+ <g transform="translate(-15 -66) scale(2.5)" stroke="#705025" stroke-width="1">
+ <path d="m1.2 6.3-1.2-3.7q-.2-.7.5-.4L3 3.6l2.4-2.5q.6-.7 1.2 0L9 3.6l2.5-1.4q.7-.3.5.4l-1.2 3.7q-.2.9-1.2.9H2.4q-1 0-1.2-.9Z" fill="#f7d861"/>
+ <path d="M2.1 6.5h7.8" stroke="#b58a2f" stroke-width="1"/>
+ </g>
+ <g id="hero-gamepad" transform="translate(3 40) rotate(-10) scale(.68)">
+ <path d="M-29-20h58c9 0 15 7 18 20l3 14c2 10-9 15-15 7l-12-13h-46l-12 13c-6 8-17 3-15-7l3-14c3-13 9-20 18-20Z" fill="#fffdf5" stroke-width="3"/>
+ <path d="M-28-7V6m-6.5-6.5h13" stroke-width="3.5"/>
+ <g stroke="none"><circle cx="28" cy="-8" r="3" fill="#e58b69"/><circle cx="36" cy="0" r="3" fill="#7eadde"/><circle cx="20" cy="0" r="3" fill="#74b297"/><circle cx="28" cy="8" r="3" fill="#edc969"/></g>
+ <path d="M-6-6h4m4 0h4" stroke-width="2"/>
+ <g fill="currentColor" stroke="none"><circle class="game-hand" cx="-34" cy="5" r="8" style="--tap-delay:-3.2s"/><circle class="game-hand" cx="31" cy="4" r="8"/></g>
+ </g>
+ </g>
+ </g>
+ <g transform="translate(414 371) rotate(-3)" color="#9ac8e4" style="--pace:47s;--phase:-17s">
+ <g class="person-body"><use href="#person"/><g class="person-eyes"><use href="#eyes"/></g></g>
+ <path d="M-21 39h43l-7 24h-29Z" fill="#fff5d4"/><path d="M-17 38q-4-12 6-11 1-12 10-5 9-8 11 2 12-2 9 14" fill="#fff9de" stroke-width="2.5"/>
+ <g fill="currentColor" stroke="none"><circle cx="-24" cy="45" r="6.5"/><circle cx="24" cy="45" r="6.5"/></g>
+ </g>
+ <g transform="translate(552 370) rotate(2)" color="#b6addc" style="--pace:53s;--phase:-29s">
+ <g class="person-body"><use href="#person"/><g class="person-eyes"><use href="#eyes"/></g></g>
+ </g>
+ <g transform="translate(694 369) rotate(-2)" color="#e9adc1" style="--pace:59s;--phase:-9s">
+ <g class="person-body"><use href="#person"/><g class="person-eyes"><use href="#eyes"/></g></g>
+ </g>
+ <path d="M322 434c0-13 8-21 19-21s20 8 20 21v40h376v-40c0-13 8-21 19-21s19 8 19 21v44c0 17-13 29-30 29H352c-17 0-30-12-30-29Z" fill="#cd8845" stroke="none"/>
+ <path d="M130 431c0-12 7-20 17-20s18 8 18 20v51h-12c-13 0-23-11-23-24Z" fill="#cd8845" stroke="none"/>
+ </g>
+</svg>
diff --git a/site/assets/sketch.js b/site/assets/sketch.js
new file mode 100644
index 00000000..ab41060e
--- /dev/null
+++ b/site/assets/sketch.js
@@ -0,0 +1,65 @@
+// A pencil study, shared by the source thumbnail and the film. Construction
+// lines stay visible; the film traces the darker contours with its own clock.
+const strokes = [
+ 'M177 245Q160 203 195 195L414 171Q455 164 467 206L492 406Q500 445 463 451L231 477Q190 482 187 444Z',
+ 'M189 246Q179 214 211 211L414 187Q444 184 450 213L476 405Q480 432 453 438L231 461Q207 465 204 439Z',
+ 'M256 189 210 151M257 185 298 134',
+ 'M270 288Q282 284 285 296T278 312Q266 315 265 303T270 288',
+ 'M362 296Q377 271 398 291',
+ 'M242 475 222 506M432 455 453 486',
+ 'M216 221 229 441M226 447 454 426M166 523Q307 544 499 500',
+].flatMap(d => d.match(/M[^M]+/g));
+
+export function sketchMarkup(prefix) {
+ return `<rect width="620" height="720" rx="5" fill="#faf7ed"/>
+ <g fill="none" stroke="#bdbaac" stroke-width="1.5" opacity=".65">
+ <path d="m138 197 312-36 61 341-312 31Zm33-19 63 376m193-415 62 371M123 331l390-45M304 123l59 424"/>
+ <ellipse cx="336" cy="327" rx="138" ry="161" transform="rotate(-8 336 327)"/>
+ <path d="M176 246q-11-48 16-55l225-27q49-3 57 42l25 201q5 51-35 49l-235 28q-46-1-49-44ZM242 184l-38-40m62 44 43-58"/>
+ <ellipse cx="276" cy="300" rx="24" ry="29"/><ellipse cx="379" cy="288" rx="26" ry="28"/>
+ <path d="m88 590 63-7m-45 14 119-12m273-469 38-9m-35 19 53-11"/>
+ </g>
+ <g fill="none" stroke="#edbc7b" stroke-width="2" opacity=".75">
+ <path d="M133 471Q80 224 215 147m269 61q89 174 15 284M132 552q187 50 391-40"/>
+ <path d="m121 540 11 12-16 7m384-56 23 9-16 14"/>
+ </g>
+ <g fill="none" stroke="#414842" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round">
+ ${strokes.map((d,i)=>`<path id="${prefix}-stroke-${i}" d="${d}" pathLength="1" stroke-dasharray="1"/>`).join('')}
+ </g>
+ <g fill="none" stroke="#657066" stroke-width="1.5" opacity=".7">
+ ${Array.from({length:12},(_,i)=>`<path d="m${213+i*7} ${488-i*.8} 20 15"/>`).join('')}
+ ${Array.from({length:8},(_,i)=>`<path d="m${471+i*2} ${342+i*11} 12-17"/>`).join('')}
+ <path d="m151 598 160-19m-144 27 66-11m169-5 119-20"/>
+ </g>
+ <path d="M44 54h66m-66 10h37M491 645h69m-35-8v16" stroke="#a3a699" stroke-width="2"/>
+ `;
+}
+
+export function createSketch(svg, prefix) {
+ const paths = strokes.map((_,i)=>svg.querySelector(`#${prefix}-stroke-${i}`));
+ let distance = 0, previous = paths[0].getPointAtLength(0);
+ const segments = paths.map(path => {
+ const length = path.getTotalLength(), start = path.getPointAtLength(0);
+ const travel = Math.hypot(start.x-previous.x,start.y-previous.y);
+ const segment = { path, length, start, previous, at: distance, travel };
+ distance += travel + length;
+ previous = path.getPointAtLength(length);
+ return segment;
+ });
+ return progress => {
+ const p = Math.min(1,Math.max(0,progress))*distance;
+ let tip = segments[0].start;
+ for (const segment of segments) {
+ const {path,length,start,previous,at,travel} = segment;
+ const drawn = Math.min(length,Math.max(0,p-at-travel));
+ path.style.strokeDashoffset = String(1-drawn/length);
+ if (p < at) continue;
+ // Lift and travel between disconnected strokes instead of teleporting.
+ const move = travel ? Math.min(1,(p-at)/travel) : 1;
+ tip = move < 1
+ ? {x:previous.x+(start.x-previous.x)*move,y:previous.y+(start.y-previous.y)*move}
+ : path.getPointAtLength(drawn);
+ }
+ return tip;
+ };
+}
diff --git a/site/film/README.md b/site/film/README.md
new file mode 100644
index 00000000..d85e8a98
--- /dev/null
+++ b/site/film/README.md
@@ -0,0 +1,114 @@
+# Piik film
+
+The homepage expands this optional, 76-second introduction in an iframe loaded
+only on request. Closing it unloads playback; the standalone page remains useful
+for recording. Both entries use the same player. From the repository
+root, run `npm run build:website` and `npm run preview:website`, then open
+`http://127.0.0.1:18890/film/`. Publish the static `build/site/` output. A project
+prefix such as `/Piik/film/` also works; GitHub Pages needs no application server.
+
+`score.js` owns the 101 BPM beat/bar grid used by cuts and staged UI actions.
+`art.js` owns the original SVG artwork and seekable sequence; `../assets/games.js`
+owns the six original gameplay vignettes and their action/result sequence. `player.js`
+owns playback, sound and controls. Audible playback follows the audio element's
+clock, including buffering. The host must support HTTP byte ranges for seeking;
+the Vite preview command does. Muted playback uses a monotonic clock and does not
+request the soundtrack. Artwork and the demonstration's CSS animations follow
+this same position, including pause, seek and replay. After natural completion,
+only the closing mascot continues its native idle loop; an explicit pause or
+seek freezes it, and reduced motion keeps it still.
+
+The film follows the App flow in five steps: scroll to the website downloads,
+unpack the complete package and open the App, choose **Public invite**, select a
+source, then copy and send the invite through an external chat example before
+friends watch in a browser. Public invitations
+need Internet access and a temporary control tunnel. The public pages use the
+[copy guide's information layers](../../docs/reference/naming.md#voice-and-terminology).
+
+`ui/main.tsx` uses the product's actual launcher form, source picker, TV, sofa and
+control primitives with sample inputs. The build also supplies the current
+homepage HTML and styles to `ui/website.ts`, whose scrolling follows the same
+film position; the desktop is an illustration of the unpacked Windows package.
+The website and App run in separate opaque, inert iframes with
+script permission only; they cannot persist preferences to the App or request
+capture. No room connection, API interception or media permission is simulated.
+The existing build dependency bundles these components; rebuilding the website
+picks up their styling and copy. Review scene selection and camera framing when
+the product workflow changes. Cursor targets follow component elements, not
+screenshot coordinates.
+
+Each cursor movement starts at the preceding control and has its own travel
+interval. Derive the entire pose from the requested time; do not accumulate
+cursor history or start a second animation clock. The source preview and drawing
+scene share `../assets/sketch.js`, including a seekable pencil trace.
+Opening the App leads to its mode form and then the room. Keep the window's
+position continuous through these steps. The neutral chat example retains the
+copy control beneath it to anchor the next cursor movement, with its own title
+and sample message clearly outside Piik's interface.
+
+The film reuses the product's playback control and `BrandMark` CSS, plus `Glyph` icons rendered
+to static markup during the website build. Its score and audio remain owned by
+`player.js`; the live viewer's stream binding, audio gain, reconnect and picture
+in picture remain in `PlaybackControls`. A shared appearance does not require
+giving a recorded sequence live-room state.
+
+[`../assets/game.js`](../assets/game.js) owns the original **LITTLE WANDER** RPG
+scene. The film and demonstration TV render it using the film clock.
+The film's six game vignettes share pure poses in `../assets/games.js`.
+`../assets/activities.js` composes the homepage's RPG, drawing, photos and movie
+from shared artwork. Its standalone SVG embeds sampled CSS at five seconds per
+activity, and also serves as the README image. The build tool removes repeated
+samples during holds.
+After changing the artwork, run `node scripts/update-website-hero.mjs` from the
+repository root; `--check` detects an out-of-date hero. Its `#still` fragment
+and the system reduced-motion preference disable the loop.
+
+The poster waits for an explicit play action. System reduced-motion preferences
+keep a still preview, with manual playback available. System colour preference
+styles the surrounding page; the film retains its authored colours. The homepage
+and film carry explicit language/theme choices through their links. No cookies,
+external fonts, analytics or new runtime dependencies are used.
+
+## Recording
+
+1. Open the standalone film in the desired language, start playback and select
+ fullscreen. Normal fullscreen keeps playback and exit controls available.
+ Press **C** to hide or restore controls for recording.
+2. Capture browser video and audio at **1920 × 1080, 60 fps**. Press **R** to
+ restart from the first frame; **Space** pauses and **M** toggles sound.
+ Switching away from the page pauses playback.
+3. Press **Escape** to leave the clean view. Retain the music attribution in the
+ end card and in the published recording's description.
+
+## Music
+
+“[Funkorama](https://incompetech.com/music/royalty-free/index.html?Search=Search&isrc=USUAN1100474)”
+by Kevin MacLeod (incompetech.com), under
+[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
+The excerpt uses the opening 76.039604 seconds (32 bars), fading out over the
+last two beats from 74.851485 seconds. At bar 29, the download banner enters over
+the existing brand and living room. Its link uses the homepage's platform downloads;
+the mascot uses the loading screen's repeating wink and gold sparkles.
+[The asset notice](./assets/NOTICE.txt) retains source, attribution and modification
+details. The music keeps its own license, separate from Piik's MIT license.
+
+To reproduce the audio edit from the linked original:
+
+```sh
+ffmpeg -i Funkorama.mp3 -vn -t 76.039604 \
+ -af afade=t=out:st=74.851485:d=1.188119 \
+ -c:a libmp3lame -b:a 160k -map_metadata -1 funkorama.mp3
+```
+
+## Focused check
+
+Open a fresh local film page in a named `agent-browser` session and run
+`agent-browser --session <session> click '#language'` to grant the user gesture
+required by native audio. Then evaluate
+[`scripts/check-website-film.js`](../../scripts/check-website-film.js) using
+`agent-browser --session <session> eval --stdin`. The browser check covers lazy
+audio, playback/seek/replay, language links, obsolete play promises, native media
+pause, audio failure/ending, bilingual headline bounds, unobscured scenario
+objects, cursor continuity/reverse seeking and the standalone hero's CSS poses
+against the shared game score. Visual acceptance still requires watching the
+complete film, checking both languages, narrow layouts and the clean recording view.
diff --git a/site/film/art.js b/site/film/art.js
new file mode 100644
index 00000000..72e179e3
--- /dev/null
+++ b/site/film/art.js
@@ -0,0 +1,597 @@
+// One seekable score, measured in musical bars. No scene owns a timer.
+import { gameMarkup, createGame } from '../assets/game.js';
+import { mascotMarkup } from '../assets/brand.js';
+import { GAME_KINDS, montageMarkup, createMontage } from '../assets/games.js';
+import { sketchMarkup, createSketch } from '../assets/sketch.js';
+import { photoMarkup, movieMarkup, movieAnswerPose } from '../assets/activities.js';
+import { BEAT, BAR, INVITE_CUES, DOWNLOAD_AT, DURATION } from './score.js';
+export { DURATION } from './score.js';
+
+const INK = '#203037';
+const PAPER = '#faf5e7';
+const ORANGE = '#f47843';
+const MINT = '#b8e2c9';
+const YELLOW = '#f3cc68';
+const clamp = (n, a = 0, b = 1) => Math.min(b, Math.max(a, n));
+const ease = (n) => 1 - (1 - clamp(n)) ** 4;
+const mix = (a, b, n) => a + (b - a) * n;
+const pop = (n) => { const t = clamp(n) - 1; return 1 + 2.5 * t ** 3 + 1.5 * t ** 2; };
+const colours = ['#99c9e6', '#e6a8bc', '#9cb9cf', '#b6addc', '#85baa8'];
+const rect = (x, y, w, h, r, fill, extra = '') => `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${r}" fill="${fill}" ${extra}/>`;
+const circle = (x, y, r, fill, extra = '') => `<circle cx="${x}" cy="${y}" r="${r}" fill="${fill}" ${extra}/>`;
+const text = (x, y, value, size, fill = INK, extra = '') => `<text x="${x}" y="${y}" font-size="${size}" font-weight="900" letter-spacing="-.06em" fill="${fill}" ${extra}>${value}</text>`;
+const small = (x, y, value, fill = INK, extra = '') => text(x, y, value, 19, fill, `style="letter-spacing:.1em;font-weight:650" ${extra}`);
+const sceneLabel = (value, fill = INK) => small(64, 64, value, fill, 'class="scene-label"');
+const field = (fill) => rect(0, 0, 1600, 900, 0, fill);
+
+function person(id, x, y, scale, colour, host = false) {
+ return `<g transform="translate(${x} ${y}) scale(${scale})"><g id="${id}">
+ <use href="#pawn" fill="${colour}"/>
+ <g id="${id}-eyes" fill="${INK}"><ellipse cx="-7" cy="-30.75" rx="2.75" ry="3.75"/><ellipse cx="7" cy="-30.75" rx="2.75" ry="3.75"/></g>
+ ${host ? '<use href="#crown" transform="translate(-15 -70) scale(2.5)"/>' : ''}
+ </g></g>`;
+}
+
+function mascot(id,x,y,scale,colour=PAPER) {
+ return `<g transform="translate(${x} ${y}) scale(${scale})"><g id="${id}" style="color:${INK}"><g transform="translate(-16 -16)">${mascotMarkup(id,colour)}</g></g></g>`;
+}
+
+function couch(x, y, width) {
+ return `<g transform="translate(${x} ${y})">
+ <path d="M24 77v20m${width - 48}-20v20" stroke="${INK}" stroke-width="8" stroke-linecap="round"/>
+ ${rect(0, 0, width, 86, 28, '#e9ad63')}${rect(12, 62, width - 24, 27, 13, '#cd8845')}
+ ${rect(-7, 35, 26, 58, 13, '#cd8845')}${rect(width - 19, 35, 26, 58, 13, '#cd8845')}
+ </g>`;
+}
+
+function screen(id, x, y, width, content, angle = 0) {
+ const height = (width - 24) * 9 / 16;
+ return `<g transform="translate(${x} ${y})"><g id="${id}"><g id="${id}-tilt" transform="rotate(${angle})">
+ ${rect(13, 18, width, height + 56, 24, INK)}${rect(0, 0, width, height + 56, 24, PAPER)}
+ ${[23, 37, 51].map((cx, i) => circle(cx, 23, 4, [ORANGE, YELLOW, '#85baa8'][i])).join('')}
+ ${rect(width * .4, 19, width * .2, 7, 3.5, '#b8c9bf')}
+ <svg x="12" y="44" width="${width - 24}" height="${height}" viewBox="0 0 1600 900" overflow="hidden">${content}</svg>
+ </g></g></g>`;
+}
+
+export function createArt(svg, language, onUI = () => {}) {
+ const zh = language === 'zh-CN';
+ const say = (en, cn) => zh ? cn : en;
+ const appWindow = (id, title = 'Piik') => `<g transform="translate(540 144)"><g id="${id}">
+ ${rect(17, 20, 1010, 726, 23, INK)}${rect(0, 0, 1010, 726, 23, PAPER, `stroke="${INK}" stroke-width="3"`)}
+ ${[26, 43, 60].map((cx, i) => circle(cx, 24, 5, [ORANGE, YELLOW, '#85baa8'][i])).join('')}
+ ${small(499, 31, title, INK, `id="${id}-title" text-anchor="middle"`)}
+ <svg id="${id}-camera" x="12" y="47" width="986" height="663.31" viewBox="0 0 1100 740" overflow="hidden">${rect(-1000, -1000, 4000, 4000, 0, '#e8f3ef')}</svg>
+ </g></g>`;
+ const chapter = (first, second, note) => `${text(57, 286, first, zh ? 112 : 92)}${text(57, 419, second, zh ? 112 : 92)}
+ ${text(62, 533, note, zh ? 29 : 26, INK, 'style="letter-spacing:-.02em;font-weight:650"')}`;
+ const game = '<use href="#game-still"/>';
+ const drawing = `${field(YELLOW)}<path d="M-130 750Q220-60 600 580T1720 300" fill="none" stroke="${ORANGE}" stroke-width="190"/>
+ <g transform="translate(490 85) rotate(8 310 360)">${sketchMarkup('card-sketch')}</g>`;
+ // Captions have a fixed left column; the objects on the right stay unobscured.
+ const scenarioTitle = (id, first, second, cn, fill) => `<g id="${id}" transform="rotate(-8 380 450)">
+ ${rect(-100, 270, 815, 342, 0, fill)}
+ ${zh ? text(43, 492, cn, 126, fill===INK?PAPER:INK) : text(43,413,first,140,fill===INK?PAPER:INK)+text(43,555,second,140,fill===INK?PAPER:INK)}
+ </g>`;
+ const photos = photoMarkup();
+
+ svg.innerHTML = `<defs>
+ <pattern id="dots" width="18" height="18" patternUnits="userSpaceOnUse">${circle(4, 4, 2, INK)}</pattern>
+ <clipPath id="slash"><path id="slash-path"/></clipPath>
+ <clipPath id="title-top"><rect x="-1600" y="-900" width="4800" height="1226"/></clipPath>
+ <clipPath id="title-bottom"><rect x="-1600" y="324" width="4800" height="1476"/></clipPath>
+ <g id="wordmark">${text(85, 477, 'Piik', 407, PAPER)}</g>
+ <g id="pawn"><circle cy="-31" r="20"/><path d="M-35 51.5c0-32.5 12.5-50 35-50s35 17.5 35 50q0 7.5-7.5 7.5h-55Q-35 59-35 51.5Z"/></g>
+ <g id="crown" fill="#f7d861" stroke="#705025" stroke-width="1" stroke-linejoin="round"><path d="m1.2 6.3-1.2-3.7q-.2-.7.5-.4L3 3.6l2.4-2.5q.6-.7 1.2 0L9 3.6l2.5-1.4q.7-.3.5.4l-1.2 3.7q-.2.9-1.2.9H2.4q-1 0-1.2-.9Z"/><path d="M2.1 6.5h7.8" stroke="#b58a2f" stroke-width="1"/></g>
+ <g id="game-still">${gameMarkup('card-game')}</g>
+ <g id="pad">
+ <path d="M-115-52h230q47 0 66 61l20 74q12 49-34 49-29 0-72-55H-95q-43 55-72 55-46 0-34-49l20-74q19-61 66-61Z" fill="${PAPER}"/>
+ <path d="M-103-9v58m-29-29h58" fill="none" stroke="${INK}" stroke-width="15" stroke-linecap="round"/>
+ ${circle(104, 0, 12, ORANGE)}${circle(134, 29, 12, '#8bbedb')}${circle(74, 29, 12, '#85baa8')}${circle(104, 58, 12, YELLOW)}
+ ${rect(-26, 28, 15, 6, 3, INK)}${circle(24, 31, 5, INK)}
+ </g>
+ </defs>
+
+ <g id="scene-hello">
+ ${field(INK)}
+ <g id="hello-slab"><path d="M980-100h890v1080H665Z" fill="${ORANGE}"/>${circle(1430, 430, 480, 'url(#dots)', 'opacity=".25"')}</g>
+ <g id="hello-echo" fill="none" stroke="${MINT}" stroke-width="1.5" opacity=".3">
+ ${text(-75, 396, 'PIIK', 535, 'none')}${text(-75, 864, 'PIIK', 535, 'none')}
+ </g>
+ <g id="hello-word" transform="rotate(-12 740 450)">
+ <path d="M-70 171h945l-34 386H-105Z" fill="${PAPER}"/>
+ ${text(70, 465, say('LOOK!', '快看!'), zh ? 248 : 270)}
+ ${small(92, 640, say('PIIK / SCREEN SHARING FOR FRIENDS', 'PIIK / 和朋友分享屏幕'), PAPER)}
+ </g>
+ <g id="hello-character"><g transform="translate(1190 436) rotate(14)">
+ ${mascot('hello-tv', 0, -15, 21, PAPER)}
+ ${small(0, 294, 'PIIK / HELLO THERE', INK, 'text-anchor="middle"')}
+ </g></g>
+ <g id="hello-label">${sceneLabel('PIIK / SHARE THE GOOD STUFF', MINT)}${small(1536, 836, 'PIIK.TV', INK, 'text-anchor="end"')}</g>
+ ${circle(800, 450, 0, ORANGE, 'id="hello-dot"')}
+ </g>
+
+ <g id="scene-discover">
+ ${field(PAPER)}
+ <g id="discover-type" transform="rotate(-12 800 450)">
+ <g id="discover-line-top">${text(-70, 180, say('MOMENTS', '这一刻'), zh ? 345 : 265, 'none', `stroke="${INK}" stroke-width="2"`)}</g>
+ <g id="discover-line-middle">${text(-60, 533, say('MOMENTS', '这一刻'), zh ? 345 : 265)}</g>
+ <g id="discover-line-bottom">${text(-60, 886, say('MOMENTS', '这一刻'), zh ? 345 : 265, ORANGE)}</g>
+ </g>
+ <g id="discover-photo">
+ ${rect(910, -170, 580, 1210, 0, MINT, 'transform="rotate(12 1200 450)"')}
+ ${screen('discover-drawing', 976, -134, 530, drawing, 12)}
+ ${screen('discover-game', 842, 310, 655, game, -12)}
+ ${screen('discover-photos', 1025, 798, 530, photos, 12)}
+ </g>
+ <g id="discover-ticket" transform="translate(130 632) rotate(-12)">
+ ${rect(12, 13, zh ? 661 : 795, 159, 0, ORANGE)}${rect(0, 0, zh ? 661 : 795, 159, 0, INK)}
+ ${text(28, 120, say('SHARE IT.', '一起看。'), zh ? 125 : 150, PAPER)}
+ </g>
+ <g id="discover-label">${sceneLabel(say('SOME MOMENTS DESERVE AN AUDIENCE.', '这一刻,想让朋友也看看。'))}</g>
+ <g id="discover-pointer"><path d="M0 0v91l25-24 21 43 23-11-22-43 39-5Z" fill="${INK}" stroke="${PAPER}" stroke-width="6" stroke-linejoin="round"/></g>
+ </g>
+
+ <g id="scene-game">
+ ${montageMarkup()}
+ <g id="montage-cheer" transform="rotate(-8 435 670)"><path d="M-70 552h945l-34 227H-105Z" fill="${YELLOW}"/>${text(63,736,say('NICE!','漂亮!'),zh?180:206)}</g>
+ </g>
+
+ <g id="scene-website">
+ ${field(YELLOW)}<path d="m1170-50 230 0-254 1000H870Z" fill="${ORANGE}"/>
+ ${sceneLabel('PIIK / 01')}
+ <g id="website-type">${chapter(say('Get', '官网'), say('Piik.', '下载。'), say('Choose your system.', '选好对应系统的程序包。'))}
+ ${small(62, 587, 'PIIK.TV')}
+ ${text(55, 788, '01', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}
+ </g>
+ ${appWindow('website-window', 'piik.tv')}
+ </g>
+
+ <g id="scene-desktop">
+ ${field(YELLOW)}<path d="m1170-50 230 0-254 1000H870Z" fill="${ORANGE}"/>
+ ${sceneLabel('PIIK / 02')}
+ <g id="desktop-type">${chapter(say('Unpack.', '解压,'), say('Open.', '打开。'), say('Keep the full package together.', '保留程序包的完整目录。'))}
+ ${small(62, 587, say('OPEN PIIK APP', '打开 Piik App'))}
+ ${text(55, 788, '02', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}
+ </g>
+ ${appWindow('desktop-window', say('Desktop', '桌面'))}
+ </g>
+
+ <g id="scene-launch">
+ ${field(YELLOW)}<path d="m1170-50 230 0-254 1000H870Z" fill="${ORANGE}"/>
+ ${sceneLabel('PIIK / 03')}
+ <g id="launch-type">${chapter(say('Pick a', '选好'), say('mode.', '模式。'), say('Public invite for distant friends.', '异地朋友,选「公网邀请」。'))}
+ ${small(62, 587, say('CONTROLS OPEN IN YOUR BROWSER', '在浏览器里,开始分享。'))}
+ ${text(55, 788, '03', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}
+ </g>
+ ${appWindow('launch-window')}
+ </g>
+
+ <g id="scene-share">
+ <g id="share-picture">
+ ${field(PAPER)}<path d="M960-100h770v1100H640Z" fill="${MINT}"/>
+ <g id="share-type">${chapter(say('Pick.', '选个'), say('Share.', '画面。'), say('A window. A screen. Your call.', '窗口、屏幕,都能分享。'))}
+ ${small(62, 587, say('PICTURE + SOUND', '画面与声音,一起分享'))}
+ ${text(55, 788, '04', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}
+ </g>
+ ${appWindow('share-window')}
+ </g>
+ <g id="share-label">${sceneLabel('PIIK / 04')}</g>
+ </g>
+
+ <g id="scene-invite">
+ ${field(ORANGE)}<path d="M1060-100h650v1100H760Z" fill="${YELLOW}"/>
+ ${sceneLabel('PIIK / 05')}
+ <g id="invite-type">${chapter(say('Send a', '发个'), say('link.', '邀请。'), say('Paste it into your chat.', '把链接发到你们的聊天里。'))}
+ ${small(62, 587, say('FRIENDS WATCH IN THEIR BROWSER', '朋友用浏览器就能看。'))}
+ ${text(55, 788, '05', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}
+ </g>
+ ${appWindow('invite-window')}
+ </g>
+
+ <g id="scene-features">
+ <g id="feature-free">${field(INK)}
+ <path d="m1030-100 750 0-220 1100H820Z" fill="${ORANGE}"/>
+ ${text(805, 874, '0', 1070, YELLOW, 'transform="rotate(12 1160 470)"')}
+ ${text(1220, 151, say('COST TO USE', '使用费用'), 42, INK, 'text-anchor="middle" style="letter-spacing:0;font-weight:800"')}
+ ${zh ? text(1418, 800, '元', 87, INK) : ''}
+ <g id="free-type" transform="rotate(-12 740 450)">${text(82, 370, say('FREE.', '免费。'), 248, PAPER)}${zh ? text(57, 628, '开源。', 248, MINT) : text(57, 525, 'OPEN', 160, MINT) + text(57, 680, 'SOURCE.', 160, MINT)}</g>
+ ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'), PAPER)}${small(64, 833, say('MIT LICENSE / MAKE IT YOUR OWN', 'MIT 许可 / 按自己的想法改。'), PAPER)}
+ </g>
+ <g id="feature-p2p">${field(MINT)}
+ <path d="M1255-80h475v1080H929Z" fill="${PAPER}"/>
+ <g id="p2p-diagram">
+ <path id="p2p-link" d="M1087 399 1347 506m-47 9 47-9-27-39" fill="none" stroke="${INK}" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"/>
+ <g id="p2p-packet">${rect(-22,-14,44,28,8,ORANGE,`stroke="${PAPER}" stroke-width="4"`)}</g>
+ ${screen('p2p-source',900,181,274,game,-8)}
+ ${screen('p2p-viewer',1226,559,274,game,-8)}
+ </g>
+ <g id="p2p-type" transform="rotate(-8 600 450)">
+ ${text(74,315,say('DIRECT.','直连。'),zh?202:184)}
+ ${rect(-115,383,950,200,0,INK)}${text(57,538,say('LOW LATENCY.','低延迟。'),zh?160:106,PAPER)}
+ </g>
+ ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'))}
+ ${text(65,793,say('A direct path, so friends can keep up.','画面优先直达朋友,精彩及时跟上。'),30,INK,'style="letter-spacing:0;font-weight:650"')}
+ </g>
+ <g id="feature-encode">${field(YELLOW)}
+ <path d="M1200-100h580v1100H871Z" fill="${ORANGE}"/>
+ <g id="encode-pictures">
+ <path d="M1220 429v111M990 627v-87h426v87m-284-87v87m142-87v87" fill="none" stroke="${INK}" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/>
+ ${screen('encode-picture',1000,168,410,drawing,-5)}
+ <g id="encode-audience">
+ ${[colours[0],colours[1],colours[3],colours[4]].map((colour,i)=>`<g transform="translate(${990+i*142} 690)"><circle cy="-5" r="61" fill="${PAPER}"/>${person(`encode-person-${i}`,0,1,1.1,colour)}</g>`).join('')}
+ </g>
+ ${[0,1,2,3].map(i=>`<g id="encode-packet-${i}">${rect(-12,-9,24,18,5,PAPER,`stroke="${INK}" stroke-width="3"`)}</g>`).join('')}
+ ${small(1220,110,say('ONE PICTURE, SHARED.','一份画面,多人共享。'),INK,'text-anchor="middle"')}
+ </g>
+ <g id="encode-type" transform="rotate(-8 600 450)">
+ ${text(62,321,say('EFFICIENT','高效分享。'),zh?155:140)}
+ ${rect(-110,388,945,197,0,INK)}${text(48,541,say('SHARING.','轻负担。'),zh?164:153,PAPER)}
+ </g>
+ ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'))}
+ ${text(65,793,say('Lighter on resources, with more power left for games and creative work.','少占些资源,给游戏和创作多留些性能。'),30,INK,'style="letter-spacing:0;font-weight:650"')}
+ </g>
+ <g id="feature-devices">${field(INK)}
+ <path d="M1210-80h480v1060H908Z" fill="${MINT}"/>
+ ${circle(1250,422,274,ORANGE)}
+ <g id="devices-laptop"><g transform="translate(922 225) rotate(-8)">
+ ${screen('devices-browser',0,0,480,game)}
+ <path d="M-25 313h530v10q-6 15-28 15H3q-22 0-28-15Z" fill="${PAPER}"/>
+ <path d="M190 314h100l-7 8h-86Z" fill="#b8c9bf"/>
+ </g></g>
+ <g id="devices-tablet"><g transform="translate(976 568) rotate(-8)">
+ ${rect(10,12,310,194,24,INK)}${rect(0,0,310,194,24,PAPER)}
+ ${rect(12,12,286,170,14,INK)}
+ <svg x="14" y="18" width="282" height="158.625" viewBox="0 0 1600 900">${game}</svg>
+ ${rect(124,183,62,4,2,'#b8c9bf')}
+ </g></g>
+ <g id="devices-phone"><g transform="translate(1352 380) rotate(9)">
+ ${rect(10,12,174,330,28,INK)}${rect(0,0,174,330,28,PAPER)}
+ ${rect(11,32,152,266,15,INK)}${rect(62,14,50,5,2.5,'#b8c9bf')}
+ <svg x="11" y="122" width="152" height="85.5" viewBox="0 0 1600 900">${game}</svg>
+ ${rect(58,312,58,5,2.5,'#b8c9bf')}
+ </g></g>
+ <g id="devices-type" transform="rotate(-8 600 450)">
+ ${text(62,321,say('DESKTOP.','电脑手机。'),zh?155:146,PAPER)}
+ ${rect(-110,388,945,197,0,YELLOW)}${text(48,541,say('MOBILE.','都能看。'),zh?180:174)}
+ </g>
+ ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'),PAPER)}
+ ${text(65,793,say('Open the invite. Watch in your browser.','点开邀请链接,用浏览器加入。'),30,PAPER,'style="letter-spacing:0;font-weight:650"')}
+ </g>
+ </g>
+
+ <g id="scene-people">
+ ${field(MINT)}
+ <g id="people-backdrop" transform="rotate(-12 800 450)">
+ ${text(-160, 263, 'TOGETHER', 325, PAPER)}${text(-160, 918, 'TOGETHER', 325, 'none', `stroke="${INK}" stroke-width="2"`)}
+ <path d="M640-200h300v1320H640Z" fill="${INK}" opacity=".08"/>
+ </g>
+ <g id="people-type" transform="rotate(-12 280 450)">
+ ${text(76, 301, '1', 254)}${text(251, 290, '+', 141)}
+ ${text(33, 708, '20', 409)}
+ ${small(60, 790, say('ONE HOST', '一位房主'))}${small(60, 824, say('UP TO 20 VIEWERS', '最多二十位观众'))}
+ </g>
+ <g transform="rotate(-12 1120 450)"><g id="people-seats">
+ ${[0, 1, 2, 3].map((row) => `<g id="seat-row-${row}" transform="translate(${674 + row * 15} ${167 + row * 180})">
+ ${couch(0, 0, 790)}
+ ${[0, 1, 2, 3, 4].map((col) => person(`seat-${row * 5 + col}`, 79 + col * 157, -11, 1.02, colours[(row + col) % colours.length])).join('')}
+ </g>`).join('')}
+ </g></g>
+ <g id="people-host"><g transform="translate(495 379) rotate(-12)">${couch(-61, 9, 122)}${person('host', 0, -7, .91, '#83c4a5', true)}</g></g>
+ ${sceneLabel(say('SAVE YOUR FRIENDS A SEAT.', '给朋友留个位置。'))}
+ <g id="people-close">
+ ${field(INK)}
+ ${[PAPER, ORANGE, MINT].map((colour, i) => `<g id="close-panel-${i}">
+ ${rect(i * 536, 0, 538, 900, 0, colour)}
+ <g transform="translate(${267 + i * 536} 591)">
+ ${person(`close-person-${i}`, 0, 0, 5.1, colours[i])}
+ </g>
+ ${text(66 + i * 536, 180, ['01', '02', '03'][i], 159, 'none', `stroke="${INK}" stroke-width="2" opacity=".28"`)}
+ </g>`).join('')}
+ <g id="people-close-type" transform="rotate(-8 800 650)">${rect(-50, 590, 1710, 190, 0, INK)}${text(150, 736, say('ALL TOGETHER.', '朋友到齐。'), zh ? 175 : 159, PAPER)}</g>
+ ${sceneLabel(say('THAT’S MORE LIKE IT.', '这下热闹了。'))}
+ </g>
+ </g>
+
+ <g id="scene-more">
+ <g id="more-game">${field(ORANGE)}
+ <g transform="rotate(-12 800 450)">${text(85, 358, say('ONE MORE', '再开一局。'), 230)}
+ ${rect(-240, 450, 2120, 320, 0, INK)}
+ </g>
+ <g id="more-game-picture"><g transform="translate(1270 425) rotate(14) scale(1.2)"><use href="#pad"/></g></g>
+ <g transform="rotate(-12 800 450)">${text(zh ? 130 : 95, 660, say('ROUND.', '叫上朋友。'), zh ? 168 : 210, PAPER)}</g>
+ ${sceneLabel(say('PLAY / GIVE YOUR FRIENDS A FRONT-ROW SEAT', '这一把,让朋友也看看。'))}
+ </g>
+ <g id="more-art">${field(YELLOW)}
+ <path d="M140-40q-89 356 207 441T246 981" fill="none" stroke="${ORANGE}" stroke-width="118"/>
+ <g id="more-art-picture"><g transform="translate(844 110) rotate(8 310 360)">
+ ${rect(13, 17, 620, 720, 5, INK, 'opacity=".16"')}
+ <g id="sketch-paper">${sketchMarkup('film-sketch')}</g>
+ <g id="more-pencil"><g transform="rotate(35)">${rect(-10, -188, 20, 160, 4, INK)}<path d="m-10-28 10 28 10-28Z" fill="#d6b68b"/><path d="M-3-9 0 0 3-9Z" fill="${INK}"/><path d="M-4-172v133" stroke="${PAPER}" stroke-width="2" opacity=".4"/></g></g>
+ </g></g>
+ ${scenarioTitle('more-art-type','MAKE A','MARK.','画上两笔。',INK)}
+ ${sceneLabel(say('DRAW / FROM FIRST LINE TO FINAL TOUCH', '从第一笔,看到最后一笔。'))}
+ </g>
+ <g id="more-photos">${field(INK)}
+ <g id="more-photos-picture"><svg x="746" y="74" width="810" height="748" viewBox="100 0 1380 900">${photos}</svg></g>
+ ${scenarioTitle('more-photos-type','PHOTO','TIME.','翻翻相册。',MINT)}
+ ${sceneLabel(say('BY THE PIER / KEEP AN EYE ON YOUR FRIES.', '去码头整点薯条。'), PAPER)}
+ </g>
+ <g id="more-movie">${field('#324458')}
+ <g id="more-movie-picture">${movieMarkup('movie-answer')}</g>
+ ${scenarioTitle('more-movie-type','MOVIE','NIGHT.','看场电影。',PAPER)}
+ ${sceneLabel(say('MOVIE NIGHT / THE ANSWER IS 42.', '宇宙终极答案,是 42。'), PAPER)}
+ </g>
+ </g>
+
+ <g id="scene-end">
+ ${field(MINT)}
+ <g id="end-slab"><path d="M-60-60h1160L859 940H-60Z" fill="${INK}"/></g>
+ <g id="end-echo" transform="rotate(-12 1100 450)">${text(974, 720, 'PIIK', 390, 'none', `stroke="${INK}" stroke-width="2" opacity=".15"`)}</g>
+ <g id="end-brand">
+ <g clip-path="url(#title-top)"><use id="end-brand-top" href="#wordmark"/></g>
+ <g clip-path="url(#title-bottom)"><use id="end-brand-bottom" href="#wordmark"/></g>
+ <g id="end-brand-dot">${circle(809, 442, 33, ORANGE)}</g>
+ </g>
+ <g id="end-type">${text(96, 604, say('Share the', '来,看点'), zh ? 114 : 112, PAPER)}${text(96, 734, say('good stuff.', '好康的。'), zh ? 114 : 112, MINT)}</g>
+ <g id="end-character"><g transform="translate(1290 294) rotate(14)">
+ ${circle(0, 0, 242, ORANGE)}${circle(35, 24, 242, 'url(#dots)', 'opacity=".25"')}${mascot('end-tv', 0, 0, 15, PAPER)}
+ </g></g>
+ <g id="end-room"><g transform="translate(961 637) rotate(-12)">
+ ${couch(0, 0, 577)}
+ ${person('end-host', 77, -13, 1.25, '#83c4a5', true)}
+ ${person('end-friend-0', 221, -13, 1.25, colours[0])}${person('end-friend-1', 365, -13, 1.25, colours[3])}${person('end-friend-2', 509, -13, 1.25, colours[1])}
+ <g id="end-gamepad" transform="translate(77 32) rotate(-9) scale(.25)"><use href="#pad"/>${circle(-167, 70, 35, '#83c4a5')}${circle(167, 70, 35, '#83c4a5')}</g>
+ </g></g>
+ <g id="end-label">${sceneLabel(say('SCREEN SHARING FOR FRIENDS', '开个房间,叫朋友来。'), MINT)}</g>
+ <g id="end-url">${text(1500, 799, 'piik.tv', 46, INK, 'text-anchor="end"')}${small(98, 802, say('FREE & OPEN SOURCE / GET PIIK', '免费开源 · 下载 PIIK'), PAPER)}</g>
+ <g id="download-banner">
+ ${rect(0,762,1600,84,0,ORANGE)}
+ ${text(76,821,say('Download Piik ↗','下载 Piik ↗'),48,INK,'style="letter-spacing:-.02em"')}
+ ${small(780,814,'Windows · macOS · Linux',INK,'text-anchor="middle"')}
+ ${text(1500,823,'piik.tv',60,INK,'text-anchor="end"')}
+ </g>
+ <g id="download-credit">${rect(0,846,1600,54,0,PAPER)}${text(800,869,'Music: “Funkorama” — Kevin MacLeod · incompetech.com · CC BY 4.0 · edited excerpt',15,INK,'text-anchor="middle" style="letter-spacing:0;font-weight:450"')}${text(800,890,'creativecommons.org/licenses/by/4.0/',14,INK,'text-anchor="middle" style="letter-spacing:0;font-weight:450"')}</g>
+ </g>`;
+
+ const nodes = new Map(Array.from(svg.querySelectorAll('[id]'), (el) => [el.id, el]));
+ const node = (id) => nodes.get(id);
+ const endMark = node('end-tv').querySelector('.mascot-shell').parentElement;
+ endMark.classList.add('lr-brand-mark');
+ for (const [part, className] of [['open', 'eye-open'], ['wink', 'eye-wink'], ['sparkles', 'sparkles']]) {
+ node(`end-tv-${part}`).classList.add(`lr-brand-${className}`);
+ }
+ const drawGame = createGame(svg, 'card-game');
+ const drawMontage = createMontage(svg, 5 * BAR / GAME_KINDS.length);
+ const drawSketch = createSketch(svg, 'film-sketch');
+ const attr = (id, key, value) => node(id).setAttribute(key, String(value));
+ const transform = (id, value) => attr(id, 'transform', value);
+ const opacity = (id, value) => attr(id, 'opacity', clamp(value));
+ const slide = (id, progress, x, y, base = '') => {
+ const p = ease(progress);
+ transform(id, `translate(${x * (1 - p)} ${y * (1 - p)}) ${base}`);
+ };
+ const scaleAt = (id, scale, x = 800, y = 450, angle = 0) => transform(id, `translate(${x} ${y}) rotate(${angle}) scale(${scale}) translate(${-x} ${-y})`);
+ const blink = (id, t, phase) => {
+ const pulse = clamp(1 - Math.abs(t - phase) / .075);
+ transform(`${id}-eyes`, `translate(0 ${-30.75 * pulse * .86}) scale(1 ${1 - pulse * .86})`);
+ };
+
+ function hello(t) {
+ slide('hello-slab', t / (BEAT / 2), 1100, 0);
+ slide('hello-word', (t - BEAT / 4) / (BEAT / 2), -1380, 265, 'rotate(-12 740 450)');
+ const arrive = pop((t - BEAT / 2) / BEAT);
+ scaleAt('hello-character', mix(2.7, 1, arrive), 1190, 436, mix(-19, 0, arrive));
+ opacity('hello-character', (t - BEAT / 2) / (BEAT / 4));
+ opacity('hello-tv-open',t<1.5*BEAT?1:0);
+ opacity('hello-tv-wink',t<1.5*BEAT?0:1);
+ const wink=clamp((t-1.5*BEAT)/BEAT);
+ opacity('hello-tv-sparkles',Math.sin(wink*Math.PI));
+ transform('hello-tv-sparkles',`translate(${wink*5} ${wink*-5})`);
+ transform('hello-echo', `translate(${-18 * t} 0)`);
+ opacity('hello-label', (t - BEAT) / (BEAT / 2));
+ // The brand dot begins the film and opens the next cut, like an aperture.
+ attr('hello-dot', 'r', t < BEAT / 2 ? 19 * (1 - ease(t / (BEAT / 2))) : 1080 * ease((t - 3.5 * BEAT) / (BEAT / 2)));
+ }
+
+ function discover(t) {
+ transform('discover-type', `translate(${-60 * t} ${24 * t}) rotate(-12 800 450)`);
+ slide('discover-line-top', t / (BEAT / 2), -920, 0);
+ slide('discover-line-middle', (t - BEAT / 8) / (BEAT / 2), 1230, 0);
+ slide('discover-line-bottom', (t - BEAT / 4) / (BEAT / 2), -1380, 0);
+ slide('discover-photo', t / BEAT, 770, -160);
+ slide('discover-ticket', (t - BEAT) / (BEAT / 2), -1100, 220, 'translate(130 632) rotate(-12)');
+ const click = ease((t - 2 * BEAT) / (BEAT / 2));
+ transform('discover-pointer', `translate(${mix(1640, 1230, click)} ${mix(940, 586, click)}) scale(${1 - .22 * Math.sin(clamp((t - 3 * BEAT) / (BEAT / 2)) * Math.PI)})`);
+ opacity('discover-pointer', click * (1 - ease((t - 3.5 * BEAT) / (BEAT / 2))));
+ }
+
+ function website(t) {
+ slide('website-window',t/BEAT,1150,190);
+ slide('website-type',t/(BEAT/2),-610,130);
+ }
+ function desktop(t) {
+ transform('desktop-window','translate(0 0)');
+ slide('desktop-type',t/(BEAT/2),-610,130);
+ }
+ function launch(t) {
+ transform('launch-window','translate(0 0)');
+ slide('launch-type',t/(BEAT/2),-610,130);
+ }
+ function share(t) {
+ // The same product window stays in place as the chapter changes.
+ transform('share-window','translate(0 0)');
+ slide('share-type',t/(BEAT/2),-610,130);
+ const zoom=ease((t-6*BEAT)/(2*BEAT));
+ const scale=mix(1,1600/(930*986/1100),zoom);
+ opacity('share-label',1-ease((t-5.5*BEAT)/(BEAT/2)));
+ transform('share-picture',`translate(${-628.19*scale*zoom} ${-270.78*scale*zoom}) scale(${scale})`);
+ }
+
+ function gameScene(t) {
+ drawMontage(t, 8 * BAR + t);
+ }
+
+ function invite(t) {
+ node('invite-window-title').textContent = t >= INVITE_CUES.chat && t < INVITE_CUES.viewer ? say('Chat', '聊天') : 'Piik';
+ slide('invite-window',t/BEAT,1140,140);
+ slide('invite-type',t/(BEAT/2),-610,130);
+ }
+
+ function features(t) {
+ // Four benefits fit the same five bars; no long hold after the direct hop.
+ const cut = t < BAR ? 0 : t < 2 * BAR ? 1 : t < 3.5 * BAR ? 2 : 3;
+ const local = t - [0, BAR, 2 * BAR, 3.5 * BAR][cut];
+ ['free', 'p2p', 'encode', 'devices'].forEach((name, i) => { node(`feature-${name}`).style.display = i === cut ? '' : 'none'; });
+ slide('free-type', local / (BEAT / 2), -1500, 290, 'rotate(-12 740 450)');
+ slide('p2p-type', local / (BEAT / 2), -1150, 180, 'rotate(-8 600 450)');
+ slide('p2p-diagram',local/BEAT,600,0);
+ const packet=clamp((local-1.5*BEAT)/(1.5*BEAT));
+ transform('p2p-packet',`translate(${mix(1087,1347,packet)} ${mix(399,506,packet)}) rotate(22)`);
+ opacity('p2p-packet',local>=1.5*BEAT&&local<3*BEAT?1:0);
+ slide('encode-type', local / (BEAT / 2), -1200, 180, 'rotate(-8 600 450)');
+ slide('encode-pictures',local/BEAT,610,0);
+ for(let i=0;i<4;i++) {
+ const p=clamp((local-(1.5+i*.2)*BEAT)/(2*BEAT));
+ const x=990+i*142;
+ // One frame leaves the source and follows the shared trunk to each viewer.
+ const point=p<.35?[1220,mix(429,540,p/.35)]:p<.72?[mix(1220,x,(p-.35)/.37),540]:[x,mix(540,620,(p-.72)/.28)];
+ transform(`encode-packet-${i}`,`translate(${point[0]} ${point[1]})`);
+ opacity(`encode-packet-${i}`,p>0&&p<1?1:0);
+ const arrive=pop((local-(3.5+i*.2)*BEAT)/BEAT);
+ transform(`encode-person-${i}`,`translate(0 ${-9*Math.sin(clamp(arrive)*Math.PI)})`);
+ blink(`encode-person-${i}`,local,3.1+i*.23);
+ }
+ slide('devices-type',local/(BEAT/2),-1200,180,'rotate(-8 600 450)');
+ ['laptop','tablet','phone'].forEach((device,i) => {
+ const progress=pop((local-i*BEAT*.65)/BEAT);
+ transform(`devices-${device}`,`translate(${420*(1-progress)} ${110*(1-progress)})`);
+ opacity(`devices-${device}`,progress);
+ });
+ }
+
+ function people(t) {
+ slide('people-type', (t - BEAT / 2) / (BEAT / 2), -640, 140, 'rotate(-12 280 450)');
+ slide('people-host', (t - BEAT) / (BEAT / 2), 0, 700);
+ const zoom = mix(2.6, 1, ease(t / (2.5 * BEAT)));
+ scaleAt('people-seats', zoom, 1100, 300);
+ transform('people-backdrop', `translate(${-13 * t} 0) rotate(-12 800 450)`);
+ for (let i = 0; i < 20; i++) {
+ const p = pop((t - BEAT / 2 - i * BEAT / 16) / (BEAT / 2));
+ const wave = Math.sin(clamp((t - 4 * BEAT - i * BEAT / 8) / BEAT) * Math.PI);
+ transform(`seat-${i}`, `translate(0 ${-135 * (1 - p) - wave * 10}) rotate(${wave * (i % 2 ? -5 : 5)} 0 59)`);
+ opacity(`seat-${i}`, p);
+ blink(`seat-${i}`, t, 4.2 + i * .103);
+ }
+ transform('host', `rotate(${Math.sin(clamp((t - 4.6) / .9) * Math.PI) * -5} 0 59)`);
+ blink('host', t, 4.8);
+ const close = t - 7 * BEAT;
+ node('people-close').style.display = close >= 0 ? '' : 'none';
+ for (let i = 0; i < 3; i++) {
+ slide(`close-panel-${i}`, (close - i * BEAT / 4) / (BEAT / 2), 0, i % 2 ? 980 : -980);
+ const lean = Math.sin(clamp((close - .7 - i * .19) / 1.1) * Math.PI) * (i % 2 ? -5 : 5);
+ transform(`close-person-${i}`, `rotate(${lean} 0 59)`);
+ blink(`close-person-${i}`, close, 1.5 + i * .2);
+ }
+ slide('people-close-type', (close - BEAT) / (BEAT / 2), -1740, 240, 'rotate(-8 800 650)');
+ }
+
+ function more(t) {
+ const cut = Math.min(3, Math.floor(t / (BAR * 3 / 4)));
+ const local = t - cut * BAR * 3 / 4;
+ ['game', 'art', 'photos', 'movie'].forEach((name, index) => { node(`more-${name}`).style.display = index === cut ? '' : 'none'; });
+ const hit = pop(local / (BEAT / 2));
+ scaleAt('more-game-picture', mix(1.75, 1, hit), 1270, 425, mix(-22, 0, hit));
+ slide('more-art-picture',local/(BEAT/2),480,80);
+ slide('more-art-type', local / (BEAT/2), -850, 120, 'rotate(-8 380 450)');
+ const tip=drawSketch((local-BEAT/4)/(2*BEAT));
+ transform('more-pencil',`translate(${tip.x} ${tip.y})`);
+ opacity('more-pencil',1-ease((local-2.5*BEAT)/(BEAT/2)));
+ scaleAt('more-photos-picture', 1 + .015 * local,1200,450);
+ slide('more-photos-type', local / (BEAT/2), -850, 120, 'rotate(-8 380 450)');
+ slide('more-movie-type', local / (BEAT/2), -850, 120, 'rotate(-8 380 450)');
+ node('movie-answer').style.transform = movieAnswerPose(local/(3*BEAT));
+ }
+
+ function end(t, poster) {
+ endMark.classList.toggle('is-animated', !poster);
+ endMark.classList.toggle('is-loop-active', !poster);
+ const p = poster ? 1 : ease(t / BEAT);
+ slide('end-slab', poster ? 1 : t / BEAT, -1200, 0);
+ scaleAt('end-brand', mix(2.15, 1, p), 510, 420, mix(-12, 0, p));
+ slide('end-brand-top', poster ? 1 : (t - BEAT / 4) / BEAT, -800, 0);
+ slide('end-brand-bottom', poster ? 1 : (t - BEAT / 2) / BEAT, 800, 0);
+ const dot = poster ? 1 : pop((t - BEAT) / BEAT);
+ transform('end-brand-dot', `translate(0 ${-450 * (1 - dot)})`);
+ slide('end-type', poster ? 1 : (t - BEAT) / (BEAT / 2), -1040, 0);
+ const character = poster ? 1 : pop((t - BEAT) / BEAT);
+ scaleAt('end-character', mix(2, 1, character), 1290, 294, mix(-25, 0, character));
+ opacity('end-character', poster ? 1 : (t - .75 * BEAT) / (BEAT / 2));
+ slide('end-room', poster ? 1 : (t - 2 * BEAT) / BEAT, 600, 400);
+ opacity('end-label', poster ? 1 : (t - BEAT) / (BEAT / 2));
+ const outro = poster ? -1 : t - (DOWNLOAD_AT - 27 * BAR);
+ opacity('end-url', (poster ? 1 : clamp((t - 3 * BEAT) / (BEAT / 2))) * (1 - ease(outro / BEAT)));
+ transform('end-echo', `translate(${poster ? 0 : -12 * t} 0) rotate(-12 1100 450)`);
+ transform('end-tv', `rotate(${poster ? 0 : -6 * Math.sin(clamp((t - 2.8) / 1.1) * Math.PI)})`);
+ transform('end-host', `rotate(${poster ? 0 : 4 * Math.sin(clamp((t - 2) / 1.1) * Math.PI)} 0 59)`);
+ blink('end-host', poster ? 0 : t, 3.3);
+ for (let i = 0; i < 3; i++) blink(`end-friend-${i}`, poster ? 0 : t, 4.1 + i * .42);
+ node('download-banner').style.display = outro < 0 ? 'none' : '';
+ slide('download-banner',outro/BEAT,-1600,0);
+ opacity('download-credit',(outro-BEAT)/BEAT);
+ }
+
+ const scenes = [
+ { id: 'hello', start: 0, render: hello },
+ { id: 'discover', start: BAR, render: discover },
+ { id: 'website', start: 2 * BAR, render: website },
+ { id: 'desktop', start: 3.5 * BAR, render: desktop },
+ { id: 'launch', start: 4.5 * BAR, render: launch },
+ { id: 'share', start: 6 * BAR, render: share },
+ { id: 'game', start: 8 * BAR, render: gameScene },
+ { id: 'invite', start: 13 * BAR, render: invite },
+ { id: 'people', start: 16 * BAR, render: people },
+ { id: 'features', start: 19 * BAR, render: features },
+ { id: 'more', start: 24 * BAR, render: more },
+ { id: 'end', start: 27 * BAR, render: end },
+ ];
+ function render(time, poster = false, idle = false) {
+ const t = clamp(time, 0, DURATION);
+ drawGame(poster ? 1.7 : t);
+ const index = poster ? scenes.findIndex(scene => scene.id === 'end') : scenes.findLastIndex((scene) => t >= scene.start);
+ const incoming = scenes[index];
+ const local = poster ? 5 : t - incoming.start;
+ // The shared preview fills the frame before the game; other edits use a
+ // short diagonal cut. Long holds between edits keep the score from flickering.
+ const cut = poster || index === 0 || incoming.id === 'game' ? 1 : ease(local / (BEAT / 2));
+ scenes.forEach((scene, i) => {
+ const visible = i === index || (i === index - 1 && cut < 1);
+ node(`scene-${scene.id}`).style.display = visible ? '' : 'none';
+ node(`scene-${scene.id}`).removeAttribute('clip-path');
+ if (visible) scene.render(i === index ? local : incoming.start - scene.start, poster);
+ });
+ if (cut < 1) {
+ const edge = mix(1960, 0, cut);
+ attr('slash-path', 'd', `M${edge} 0H1600V900H${edge - 360}Z`);
+ node(`scene-${incoming.id}`).setAttribute('clip-path', 'url(#slash)');
+ }
+ // Fit three loading-mascot loops into the settled closing card. End in the
+ // loop's quiet tail so both sparkles finish before the music, including the
+ // last exported frame. Native idle playback continues from this same phase.
+ const closingProgress = clamp((t - (27 * BAR + BEAT)) / (DURATION - (27 * BAR + BEAT)));
+ endMark.getAnimations({subtree: true}).forEach(animation => {
+ if (idle) {
+ if (animation.playState !== 'running') animation.play();
+ } else {
+ animation.pause();
+ animation.currentTime = closingProgress * (3 * Number(animation.effect.getTiming().duration) - BEAT * 250);
+ }
+ });
+ const product=!poster&&['website','desktop','launch','share','invite'].includes(incoming.id);
+ const camera=product?node(`${incoming.id}-window-camera`):null;
+ const matrix=camera?svg.getCTM()?.inverse().multiply(camera.getCTM()):null;
+ onUI({scene:product?incoming.id:null,local,time:t,matrix});
+ }
+ render(0, true);
+ return { render };
+}
diff --git a/site/film/assets/NOTICE.txt b/site/film/assets/NOTICE.txt
new file mode 100644
index 00000000..f3b86669
--- /dev/null
+++ b/site/film/assets/NOTICE.txt
@@ -0,0 +1,14 @@
+Funkorama — Kevin MacLeod (incompetech.com)
+ISRC: USUAN1100474
+Licensed under Creative Commons Attribution 4.0 International (CC BY 4.0).
+https://creativecommons.org/licenses/by/4.0/
+
+Original track and attribution (verified 2026-09-12):
+https://incompetech.com/music/royalty-free/index.html?Search=Search&isrc=USUAN1100474
+https://incompetech.com/music/royalty-free/mp3-royaltyfree/Funkorama.mp3
+
+Piik uses the opening 76.04 seconds, with a fade-out from 74.85 seconds,
+re-encoded as a 160 kbit/s MP3. No endorsement by the composer is implied.
+The music retains its CC BY 4.0 license; Piik's MIT license does not replace it.
+Keep attribution, the source/license links and this modification notice when
+redistributing the audio or a film recording containing it.
diff --git a/site/film/assets/funkorama.mp3 b/site/film/assets/funkorama.mp3
new file mode 100644
index 00000000..11aca3eb
Binary files /dev/null and b/site/film/assets/funkorama.mp3 differ
diff --git a/site/film/film.css b/site/film/film.css
new file mode 100644
index 00000000..e16d14a4
--- /dev/null
+++ b/site/film/film.css
@@ -0,0 +1,109 @@
+:root { color-scheme: light; --wall:#e9f2ee; --paper:#fafaf3; --ink:#22303e; --muted:#52635e; --line:#c6d6cc; --accent:#e4572e; }
+@media (prefers-color-scheme:dark) { :root { color-scheme:dark; --wall:#14232b; --paper:#1b2d34; --ink:#eef4eb; --muted:#b3c4bd; --line:#3b5155; --accent:#f28d66; } }
+:root[data-theme="light"] { color-scheme:light; --wall:#e9f2ee; --paper:#fafaf3; --ink:#22303e; --muted:#52635e; --line:#c6d6cc; --accent:#e4572e; }
+:root[data-theme="dark"] { color-scheme:dark; --wall:#14232b; --paper:#1b2d34; --ink:#eef4eb; --muted:#b3c4bd; --line:#3b5155; --accent:#f28d66; }
+* { box-sizing:border-box; }
+:root { --spring:cubic-bezier(.3,1.45,.45,1); }
+body { margin:0; background:var(--wall); color:var(--ink); font:15px/1.6 ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; -webkit-font-smoothing:antialiased; }
+[hidden] { display:none !important; }
+html[lang="en"] [lang="zh-CN"], html[lang="zh-CN"] [lang="en"] { display:none; }
+button,a,input { -webkit-tap-highlight-color:transparent; touch-action:manipulation; }
+button,a { color:inherit; }
+button { font:inherit; cursor:pointer; }
+a { text-underline-offset:4px; }
+button { border:0; background:none; }
+button:disabled { cursor:wait; }
+button,a,input { outline-offset:5px; }
+:focus-visible { outline:3px solid var(--accent); }
+.sr-only { position:absolute; width:1px; height:1px; margin:-1px; padding:0; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
+.masthead { width:calc(100% - 96px); max-width:1600px; margin:auto; height:90px; display:flex; align-items:center; justify-content:space-between; gap:20px; }
+.masthead nav { display:flex; align-items:center; gap:28px; font-size:13px; font-weight:650; }
+.masthead nav a,.masthead button { min-height:44px; display:inline-flex; align-items:center; text-decoration:none; }
+.masthead button { font-size:12px; }
+.masthead nav :is(a,button):hover { color:var(--accent); }
+main { width:calc(100% - 64px); max-width:min(1664px,calc((100svh - 248px) * 16 / 9)); margin:auto; }
+.cinema { position:relative; background:#f7f4e9; color:#22303e; border-radius:24px; box-shadow:0 6px 0 #22303e12; overflow:hidden; isolation:isolate; }
+.picture { position:relative; aspect-ratio:16/9; }
+#film-art { display:none; width:100%; height:100%; }
+.fallback { display:block; width:100%; height:100%; object-fit:contain; }
+body[data-ready] #film-art { display:block; }
+body[data-ready] .fallback { display:none; }
+.curtain { display:flex; align-items:center; justify-content:center; flex-wrap:wrap; gap:9px 18px; padding:18px 24px; }
+.play-film { display:flex; align-items:center; gap:14px; padding:15px 25px; min-height:56px; border-radius:999px; background:#22303e; color:#fafaf3; box-shadow:0 5px 0 #22303e20; font-weight:700; }
+.play-film svg { width:23px; height:23px; }
+.duration { padding-left:14px; border-left:1px solid #ffffff45; color:#b6c9c2; font-size:12px; font-weight:500; font-variant-numeric:tabular-nums; }
+.quiet-play { min-height:44px; padding:6px 14px; font-size:12px; color:#52635e; }
+.play-film { transition:transform .22s cubic-bezier(.2,.9,.3,1.4),background .2s; }
+.play-film:hover { transform:translateY(-3px); background:#314557; }
+.play-film:active { transform:translateY(2px); }
+#reduced-note { flex-basis:100%; text-align:center; font-size:12px; margin:0; }
+.transport { --wall-2:#ffffff18; position:relative; display:flex; align-items:center; gap:4px; width:min(620px,calc(100% - 48px)); margin:12px auto 14px; border:1px solid #ffffff20; border-radius:16px; padding:4px 10px; background:rgb(34 48 62 / 78%); color:#fafaf3; box-shadow:0 4px 20px #14232b15; }
+.lr-btn svg { display:block; }
+.play-icon,.sound-off,.contract-icon { display:none; }
+body:not([data-playing]) .pause-icon { display:none; }
+body:not([data-playing]) .play-icon { display:block; }
+#sound[aria-pressed="false"] .sound-off { display:block; }
+#sound[aria-pressed="false"] .sound-on { display:none; }
+.fullscreen .expand-icon { display:none; }
+.fullscreen .contract-icon { display:block; }
+.scrubber { display:flex; flex:1; min-width:30px; height:44px; align-items:center; margin:0 8px; }
+#seek { width:100%; height:6px; cursor:pointer; accent-color:#ee8955; }
+#time { font-size:11px; white-space:nowrap; font-variant-numeric:tabular-nums; margin:0 10px 0 4px; }
+#player-status { text-align:center; font-size:12px; min-height:0; margin:0; }
+#player-status:not(:empty) { padding:12px; }
+.film-footer { display:flex; align-items:center; justify-content:space-between; gap:20px; padding:18px 14px; font-size:12px; color:var(--muted); }
+.film-footer p { margin:0; }
+.film-footer button { min-height:44px; font-size:12px; }
+#download { position:absolute; left:0; right:0; bottom:6%; height:9.34%; min-height:44px; }
+#download:focus-visible { outline:3px solid #faf5e7; outline-offset:-4px; }
+dialog { width:min(540px,calc(100% - 32px)); max-height:calc(100% - 48px); overflow:auto; border:1px solid var(--line); border-radius:24px; padding:32px; background:var(--paper); color:var(--ink); }
+dialog::backdrop { background:#14232b90; }
+dialog .close { position:absolute; right:12px; top:10px; width:44px; height:44px; font-size:28px; }
+dialog h2 { font-size:24px; margin:0 30px 14px 0; letter-spacing:-.04em; }
+dialog h3 { font-size:15px; margin:24px 0 6px; }
+dialog p { font-size:13px; color:var(--muted); margin:0; }
+.no-script { text-align:center; }
+/* The film is colour-graded artwork; system theme changes its surrounding page. */
+.fullscreen { background:#14232b; }
+.fullscreen .masthead,.fullscreen .film-footer { display:none; }
+.fullscreen main { width:100%; height:100dvh; max-width:none; display:grid; place-items:center; }
+.fullscreen .cinema { width:min(100vw,177.7778dvh); border-radius:0; box-shadow:none; }
+.fullscreen .transport { position:fixed; inset:auto 0 max(8px,env(safe-area-inset-bottom)); margin:0 auto; }
+.fullscreen #player-status:not(:empty) { position:fixed; top:0; padding:8px 16px; background:var(--paper); }
+.fullscreen #player-status:empty { display:none; }
+.recording .transport { display:none; }
+.recording[data-playing] { cursor:none; }
+@media (max-width:740px) {
+ .masthead { width:calc(100% - 40px); height:78px; }
+ .masthead nav { gap:16px; font-size:12px; }
+ .masthead nav a:last-child { display:none; }
+ main { width:calc(100% - 24px); max-width:none; }
+ .cinema { border-radius:18px; }
+ .curtain { gap:4px 8px; padding:16px; }
+ .play-film { padding:10px 17px; min-height:48px; font-size:13px; gap:9px; }
+ .play-film svg { width:19px; height:19px; }
+ .duration { padding-left:10px; }
+ .quiet-play { font-size:11px; padding:4px 8px; }
+ #reduced-note { flex-basis:100%; max-width:none; font-size:10px; }
+ .transport { width:calc(100% - 24px); padding:4px; gap:0; margin:16px auto; }
+ #time { grid-column:3; grid-row:2; margin:0; font-size:10px; text-align:center; }
+ .scrubber { grid-column:1 / -1; grid-row:1; margin:0 12px; }
+ #play { grid-column:1; grid-row:2; }
+ #replay { grid-column:2; grid-row:2; }
+ #sound { grid-column:4; grid-row:2; }
+ #capture { grid-column:5; grid-row:2; }
+ .transport { display:grid; grid-template-columns:44px 44px minmax(0,1fr) 44px 44px; grid-template-rows:36px 44px; }
+ .film-footer { padding:13px 8px; gap:5px; font-size:11px; flex-wrap:wrap; }
+ .film-footer button { font-size:11px; }
+}
+@media (max-width:340px) { #time { display:none; } .duration { display:none; } }
+@media (prefers-reduced-motion:reduce) { *,*::before,*::after { transition:none !important; } .play-film:hover,.transport .lr-btn:hover { transform:none; } .lr-brand-mark,.lr-brand-mark * { animation:none !important; } .lr-brand-mark { transform:none !important; } }
+
+.embedded { background:transparent; }
+.embedded .masthead,.embedded .film-footer p { display:none; }
+.embedded .film-footer { justify-content:flex-end; padding:0 8px; }
+.embedded main { width:100%; max-width:none; }
+.embedded #player-status { font-size:11px; }
+
+#film-ui { position:absolute; inset:0; width:100%; height:100%; pointer-events:none; overflow:hidden; }
+#product-ui, #website-ui { display:block; width:1100px; height:740px; border:0; }
diff --git a/site/film/index.html b/site/film/index.html
new file mode 100644
index 00000000..b3f1fc2e
--- /dev/null
+++ b/site/film/index.html
@@ -0,0 +1,75 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="color-scheme" content="light dark" />
+ <meta name="theme-color" content="#e9f2ee" />
+ <meta name="description" content="Share the good stuff. See how Piik shares games, movies, drawings and photos with friends, in a 76-second film." />
+ <title>Piik — Share the good stuff.</title>
+ <link rel="icon" href="../assets/favicon.svg" type="image/svg+xml" />
+ <link rel="stylesheet" href="./playback-controls.css" />
+ <link rel="stylesheet" href="./brand-mark.css" />
+ <link rel="stylesheet" href="./film.css" />
+ <link rel="stylesheet" href="../assets/brand.css" />
+ <script type="module" src="./player.js"></script>
+ </head>
+ <body>
+ <header class="masthead">
+ <a class="identity" href="../" data-home data-brand aria-label="Piik">Piik<span class="identity-dot">.</span></a>
+ <nav aria-label="Navigation / 导航">
+ <button id="language" type="button" hidden>简体中文</button>
+ <a href="../#download" data-home><span lang="en">Download</span><span lang="zh-CN">下载</span><span aria-hidden="true"> ↗</span></a>
+ <a href="../" data-home><span lang="en">Explore Piik</span><span lang="zh-CN">回到官网</span></a>
+ </nav>
+ </header>
+ <main>
+ <h1 class="sr-only"><span lang="en">Share the good stuff. — A Piik film</span><span lang="zh-CN">来,看点好康的。—— Piik 短片</span></h1>
+ <div class="cinema">
+ <audio id="soundtrack" preload="none"></audio>
+ <div class="picture">
+ <svg id="film-art" viewBox="0 0 1600 900" xmlns="http://www.w3.org/2000/svg" font-family="ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Microsoft YaHei,sans-serif" aria-hidden="true"></svg>
+ <svg id="film-ui" viewBox="0 0 1600 900" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" hidden><g id="ui-placement"><foreignObject width="1100" height="740"><iframe xmlns="http://www.w3.org/1999/xhtml" id="website-ui" src="./ui/website.html" sandbox="allow-scripts" tabindex="-1" inert hidden title="Piik website demonstration"></iframe><iframe xmlns="http://www.w3.org/1999/xhtml" id="product-ui" src="./ui/index.html" sandbox="allow-scripts" tabindex="-1" inert title="Piik demonstration"></iframe></foreignObject></g></svg>
+ <img class="fallback" src="../assets/living-room.svg#still" width="900" height="590" alt="Friends watching a host play a game from a warm orange sofa." />
+ <a id="download" href="../#download" data-home target="_top" hidden><span class="sr-only"><span lang="en">Download Piik</span><span lang="zh-CN">下载 Piik</span></span></a>
+ </div>
+ <div class="curtain" id="curtain" hidden>
+ <button class="play-film" id="start" type="button">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m8 5 11 7-11 7Z" fill="currentColor" /></svg>
+ <span lang="en">Watch the film</span><span lang="zh-CN">看看短片</span><span class="duration">76s</span>
+ </button>
+ <button class="quiet-play" id="start-muted" type="button"><span lang="en">Play without sound</span><span lang="zh-CN">静音播放</span></button>
+ <p id="reduced-note" hidden><span lang="en">A still preview follows your motion preference. Play when you're ready.</span><span lang="zh-CN">已按系统偏好显示静态画面,也可以手动播放。</span></p>
+ </div>
+ <div class="lr-playback transport" id="transport" role="group" aria-label="Playback controls" hidden>
+ <button id="play" class="lr-btn" type="button" aria-label="Pause">
+ <span class="pause-icon"><span data-glyph="pause"></span></span><span class="play-icon"><span data-glyph="play"></span></span>
+ </button>
+ <button id="replay" class="lr-btn" type="button" aria-label="Replay"><span data-glyph="refresh"></span></button>
+ <label class="scrubber"><span class="sr-only"><span lang="en">Film position</span><span lang="zh-CN">播放进度</span></span><input id="seek" type="range" min="0" max="76.04" step="0.01" value="0" /></label>
+ <output id="time" for="seek" aria-live="off">0:00 / 1:16</output>
+ <button id="sound" class="lr-btn" type="button" aria-pressed="true" aria-label="Sound">
+ <span class="sound-on"><span data-glyph="speaker"></span></span><span class="sound-off"><span data-glyph="speakerOff"></span></span>
+ </button>
+ <button id="capture" class="lr-btn" type="button" aria-label="Fullscreen"><span class="expand-icon"><span data-glyph="expand"></span></span><span class="contract-icon"><span data-glyph="contract"></span></span></button>
+ </div>
+ </div>
+ <p id="player-status" role="status"></p>
+ <div class="film-footer">
+ <p><span lang="en">Screen sharing for friends. Free &amp; open source.</span><span lang="zh-CN">和朋友分享屏幕,免费开源。</span></p>
+ <button id="about" type="button" hidden><span lang="en">Behind the scenes</span><span lang="zh-CN">幕后花絮</span><span aria-hidden="true"> ↗</span></button>
+ </div>
+ <p class="sr-only"><span lang="en">Piik shares your screen with friends. Download and open the App, choose Public invite, select a window or screen, then copy the invitation link and send it to your friends. Viewers watch in a browser. The film uses Piik's actual interface with sample content. An original game montage shows exploration, first-person shooting, a platform jump, a tactical flank, a skill-shot counterattack and a fighting-game block and counter. Friends cheer after the final hit. One host, up to twenty viewers. Piik is free and open source under the MIT license, ready for you to use and improve. It prefers direct connections to help friends keep up with the action. Sharing is lighter on resources, with more power left for games and creative work. Friends can open the invite in a desktop or mobile browser. Share a game, a drawing, travel photos or a movie.</span><span lang="zh-CN">Piik 用来和朋友分享屏幕。下载并打开 App,选择“公网邀请”,选好要分享的窗口或屏幕,再把邀请链接发给朋友。观众用浏览器就能看。短片展示了 Piik 的实际界面,使用示例内容。原创游戏蒙太奇依次展示探索、第一人称射击、横版跳跃、战术绕后、技能反击,以及格斗中的格挡和反击;最后一击命中后,朋友才喊出“漂亮!”。一位房主,最多二十位观众。Piik 免费开源,采用 MIT 许可,可以按自己的想法改进。画面优先直达朋友,精彩及时跟上。少占些资源,给游戏和创作多留些性能。朋友用电脑或手机浏览器点开邀请链接就能看。游戏、绘画、旅行照片和电影,都能分享给朋友看。</span></p>
+ <noscript><p class="no-script">This film needs JavaScript. <a href="../">Explore Piik / 回到官网</a></p></noscript>
+ </main>
+ <dialog id="credits" aria-labelledby="credits-title">
+ <form method="dialog"><button class="close" aria-label="Close / 关闭">×</button></form>
+ <h2 id="credits-title"><span lang="en">Behind the scenes</span><span lang="zh-CN">幕后花絮</span></h2>
+ <h3><span lang="en">Drawn for Piik</span><span lang="zh-CN">为 Piik 画的小世界</span></h3>
+ <p><span lang="en">The game, photo and movie scenes are original illustrations. The App demonstration uses Piik's actual controls with sample rooms and participants.</span><span lang="zh-CN">游戏、照片和电影场景都是为 Piik 绘制的;App 演示使用真实控件,搭配示例房间和昵称。</span></p>
+ <p><a href="../LICENSE"><span lang="en">Piik license</span><span lang="zh-CN">Piik 许可证</span></a> · <a href="./ui/third-party-licenses.txt"><span lang="en">Component licenses</span><span lang="zh-CN">组件许可证</span></a></p>
+ <h3><span lang="en">Music</span><span lang="zh-CN">配乐</span></h3>
+ <p>“<a href="https://incompetech.com/music/royalty-free/index.html?Search=Search&amp;isrc=USUAN1100474">Funkorama</a>” — Kevin MacLeod (incompetech.com). <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>. <span lang="en">Excerpt, with a fade-out.</span><span lang="zh-CN">使用了剪辑与淡出的片段。</span></p>
+ </dialog>
+ </body>
+</html>
diff --git a/site/film/player.js b/site/film/player.js
new file mode 100644
index 00000000..77eb41d4
--- /dev/null
+++ b/site/film/player.js
@@ -0,0 +1,250 @@
+import { createArt, DURATION } from './art.js';
+import { BEAT, DOWNLOAD_AT } from './score.js';
+import { mountBrands } from '../assets/brand.js';
+import { initialLanguage, rememberLanguage } from '../assets/language.js';
+mountBrands();
+
+const root = document.documentElement;
+const body = document.body;
+const byId = (id) => document.getElementById(id);
+const params = new URLSearchParams(location.search);
+body.classList.toggle('embedded', params.get('embedded') === '1');
+root.lang = initialLanguage();
+if (['light', 'dark'].includes(params.get('theme'))) root.dataset.theme = params.get('theme');
+const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');
+const audio = byId('soundtrack');
+const seek = byId('seek');
+seek.max = String(Math.ceil(DURATION * 100) / 100);
+function presentUI({scene,local,time,matrix}) {
+ byId('film-ui').toggleAttribute('hidden', !scene);
+ if (!scene || !matrix) return;
+ byId('ui-placement').setAttribute('transform', `matrix(${matrix.a} ${matrix.b} ${matrix.c} ${matrix.d} ${matrix.e} ${matrix.f})`);
+ const website = scene === 'website';
+ byId('website-ui').hidden = !website;
+ byId('product-ui').hidden = website;
+ byId(website ? 'website-ui' : 'product-ui').contentWindow?.postMessage({type:'piik-film-ui',scene,local,time,lang:root.lang}, '*');
+}
+let art = createArt(byId('film-art'), root.lang, presentUI);
+let time = 0;
+let origin = 0;
+let playing = false;
+let sound = true;
+let started = false;
+let finished = false;
+let frame = 0;
+let generation = 0;
+const say = (en, zh) => root.lang === 'zh-CN' ? zh : en;
+const bounded = (value) => Math.min(DURATION, Math.max(0, value));
+const stamp = (value) => `${Math.floor(value / 60)}:${String(Math.floor(value % 60)).padStart(2, '0')}`;
+
+// Audible playback follows the media clock, including buffering/seeking. Muted
+// playback needs no audio request and uses one monotonic anchor instead.
+function position() {
+ if (!playing) return time;
+ return bounded(sound ? (audio.readyState ? audio.currentTime : time) : time + (performance.now() - origin) / 1000);
+}
+
+function showState() {
+ body.toggleAttribute('data-playing', playing);
+ body.toggleAttribute('data-started', started);
+ byId('play').setAttribute('aria-label', time >= DURATION ? say('Replay', '重播') : playing ? say('Pause', '暂停') : say('Play', '播放'));
+ byId('replay').setAttribute('aria-label', say('Replay', '从头播放'));
+ byId('sound').setAttribute('aria-label', say('Sound', '声音'));
+ byId('sound').setAttribute('aria-pressed', String(sound));
+ byId('capture').setAttribute('aria-label', body.classList.contains('fullscreen') ? say('Exit fullscreen', '退出全屏') : say('Fullscreen', '全屏'));
+ byId('transport').setAttribute('aria-label', say('Playback controls', '播放控件'));
+ byId('curtain').hidden = started;
+ byId('transport').hidden = !started;
+}
+
+function paint() {
+ const current = position();
+ art.render(current, !started, finished && !document.hidden);
+ seek.value = String(current);
+ seek.setAttribute('aria-valuetext', `${stamp(current)} / ${stamp(DURATION)}`);
+ byId('time').textContent = `${stamp(current)} / ${stamp(DURATION)}`;
+ byId('download').hidden = !started || current < DOWNLOAD_AT + BEAT;
+ if (playing && current >= DURATION) {
+ pause(true);
+ } else if (playing) {
+ frame = requestAnimationFrame(paint);
+ }
+}
+
+function pause(atEnd = false) {
+ time = position();
+ playing = false;
+ // Only natural completion releases the decorative mascot into its idle loop.
+ // An explicit pause or seek still holds every part of the requested frame.
+ finished = atEnd === true;
+ generation++;
+ audio.pause();
+ cancelAnimationFrame(frame);
+ showState();
+ paint();
+}
+
+async function play(audible = sound, fromStart = false) {
+ pause();
+ if (fromStart || time >= DURATION) time = 0;
+ sound = audible;
+ playing = true;
+ started = true;
+ origin = performance.now();
+ const owner = ++generation;
+ byId('player-status').textContent = '';
+ if (sound) {
+ // Setting src here, rather than on the poster, keeps the first visit light.
+ if (!audio.getAttribute('src')) audio.src = './assets/funkorama.mp3';
+ else if (audio.error) audio.load();
+ audio.currentTime = time;
+ }
+ showState();
+ paint();
+ if (sound) {
+ try {
+ await audio.play();
+ } catch {
+ if (owner !== generation || !sound) return;
+ continueMuted();
+ }
+ }
+}
+
+function seekTo(value) {
+ const resume = playing;
+ pause();
+ time = bounded(value);
+ started = true;
+ if (resume && time < DURATION) void play();
+ else { showState(); paint(); }
+}
+
+function continueMuted() {
+ time = bounded(audio.currentTime || time);
+ audio.pause();
+ sound = false;
+ origin = performance.now();
+ byId('player-status').textContent = say('Music could not play. The film will continue without sound.', '音乐暂时无法播放,短片将继续静音播放。');
+ showState();
+}
+
+function toggleSound() {
+ if (playing) void play(!sound);
+ else { sound = !sound; showState(); }
+}
+
+function localize() {
+ const language = byId('language');
+ language.textContent = say('简体中文', 'English');
+ language.setAttribute('aria-label', say('切换到简体中文', 'Switch to English'));
+ document.title = say('Piik — Share the good stuff.', 'Piik — 来,看点好康的。');
+ document.querySelectorAll('[data-home]').forEach((link) => {
+ const url = new URL(link.getAttribute('href'), location.href);
+ url.searchParams.set('lang', root.lang);
+ if (root.dataset.theme) url.searchParams.set('theme', root.dataset.theme);
+ else url.searchParams.delete('theme');
+ link.href = url.href;
+ });
+ byId('reduced-note').hidden = !reduceMotion.matches;
+ showState();
+}
+
+byId('start').addEventListener('click', () => { void play(true, true); byId('play').focus({ preventScroll: true }); });
+byId('start-muted').addEventListener('click', () => { void play(false, true); byId('play').focus({ preventScroll: true }); });
+byId('play').addEventListener('click', () => playing ? pause() : void play());
+byId('replay').addEventListener('click', () => void play(sound, true));
+byId('download').addEventListener('click', pause);
+byId('sound').addEventListener('click', toggleSound);
+seek.addEventListener('input', () => seekTo(Number(seek.value)));
+byId('language').addEventListener('click', () => {
+ root.lang = root.lang === 'en' ? 'zh-CN' : 'en';
+ rememberLanguage(root.lang);
+ art = createArt(byId('film-art'), root.lang, presentUI);
+ localize();
+ // The active loop will render the new artwork at the same media position.
+ if (!playing) paint();
+});
+byId('capture').addEventListener('click', async () => {
+ if (body.classList.contains('fullscreen')) {
+ body.classList.remove('fullscreen', 'recording');
+ if (document.fullscreenElement) await document.exitFullscreen();
+ } else {
+ body.classList.add('fullscreen');
+ try { await root.requestFullscreen(); } catch { /* Keep an in-page fullscreen view when the browser lacks this API. */ }
+ }
+ showState();
+});
+document.addEventListener('fullscreenchange', () => {
+ if (!document.fullscreenElement) body.classList.remove('fullscreen', 'recording');
+ showState();
+});
+byId('about').addEventListener('click', () => {
+ pause();
+ byId('credits').showModal();
+});
+document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape' && body.classList.contains('fullscreen')) {
+ body.classList.remove('fullscreen', 'recording');
+ if (document.fullscreenElement) void document.exitFullscreen();
+ showState();
+ }
+ if (byId('credits').open || event.repeat || event.ctrlKey || event.altKey || event.metaKey || event.target.closest('input,select,textarea,[contenteditable="true"]')) return;
+ if (event.code === 'Space' && !event.target.closest('button,a')) { event.preventDefault(); if (playing) pause(); else void play(); }
+ if (event.key.toLowerCase() === 'r') void play(sound, true);
+ if (event.key.toLowerCase() === 'm') toggleSound();
+ if (event.key.toLowerCase() === 'c' && body.classList.contains('fullscreen')) body.classList.toggle('recording');
+});
+document.addEventListener('visibilitychange', () => {
+ if (document.hidden && playing) pause();
+ else if (finished) paint();
+});
+window.addEventListener('pagehide', pause);
+window.addEventListener('message', event => {
+ if (parent !== window && event.source === parent && event.origin === location.origin && event.data?.type === 'piik-film-preferences') {
+ const {lang, theme} = event.data;
+ if (!['en', 'zh-CN'].includes(lang) || !['system', 'light', 'dark'].includes(theme)) return;
+ root.lang = lang;
+ if (theme === 'system') delete root.dataset.theme;
+ else root.dataset.theme = theme;
+ art = createArt(byId('film-art'), root.lang, presentUI);
+ localize();
+ if (!playing) paint();
+ return;
+ }
+ if (['product-ui','website-ui'].some(id => event.source === byId(id).contentWindow) && event.data?.type === 'piik-film-ui-ready') {
+ cancelAnimationFrame(frame);
+ paint();
+ }
+});
+reduceMotion.addEventListener('change', () => {
+ if (reduceMotion.matches && playing) pause();
+ else if (!playing) paint();
+ byId('reduced-note').hidden = !reduceMotion.matches;
+});
+audio.addEventListener('waiting', () => {
+ if (playing && sound) byId('player-status').textContent = say('Loading music…', '正在加载音乐…');
+});
+audio.addEventListener('playing', () => { byId('player-status').textContent = ''; });
+audio.addEventListener('pause', () => {
+ // Native/OS media controls share the same pause owner as the visible button.
+ if (playing && sound && audio.paused && !audio.ended && !audio.error) pause();
+});
+audio.addEventListener('error', () => { if (playing && sound) continueMuted(); });
+audio.addEventListener('ended', () => {
+ if (!playing || !sound) return;
+ // Codec duration rounding can end the soundtrack a fraction of a frame early.
+ if (audio.currentTime >= DURATION - 1 / 60) {
+ time = DURATION;
+ playing = false;
+ pause(true);
+ } else {
+ continueMuted();
+ }
+});
+
+byId('language').hidden = false;
+byId('about').hidden = false;
+body.dataset.ready = '';
+localize();
+paint();
diff --git a/site/film/score.js b/site/film/score.js
new file mode 100644
index 00000000..84ad3597
--- /dev/null
+++ b/site/film/score.js
@@ -0,0 +1,6 @@
+// Funkorama: 101 BPM, four beats per bar. Cuts and staged actions share this grid.
+export const BEAT = 60 / 101;
+export const BAR = 4 * BEAT;
+export const INVITE_CUES = { copy: 1.5 * BEAT, chat: 3 * BEAT, paste: 4 * BEAT, send: 6 * BEAT, viewer: 8 * BEAT };
+export const DOWNLOAD_AT = 29 * BAR;
+export const DURATION = 32 * BAR;
diff --git a/site/film/ui/cursor.ts b/site/film/ui/cursor.ts
new file mode 100644
index 00000000..b7a8e6fa
--- /dev/null
+++ b/site/film/ui/cursor.ts
@@ -0,0 +1,18 @@
+import { BEAT } from "../score.js";
+
+type Point = {x: number; y: number};
+const clamp = (n: number) => Math.min(1, Math.max(0, n));
+const ease = (n: number) => 1 - (1 - clamp(n)) ** 4;
+
+// Both real pages place the same pointer from time and current control bounds.
+export function point(cursor: HTMLElement, t: number, from: Point, target: Point | undefined,
+ moveAt: number, moveFor: number, clickAt: number, hideAt: number) {
+ if (target) {
+ const p = clamp((t - moveAt) / moveFor), arrive = p * p * (3 - 2 * p);
+ const x = from.x + (target.x - from.x) * arrive,
+ y = from.y + (target.y - from.y) * arrive;
+ cursor.style.transform = `translate(${x}px,${y}px) scale(${1 - 0.18 * Math.sin(clamp((t - clickAt) / (BEAT / 2)) * Math.PI)})`;
+ }
+ cursor.style.opacity = String(ease(t / (BEAT / 2)) * (1 - ease((t - hideAt + BEAT / 2) / (BEAT / 2))));
+ cursor.toggleAttribute("hidden", !target || t >= hideAt);
+}
diff --git a/site/film/ui/index.html b/site/film/ui/index.html
new file mode 100644
index 00000000..fc4ed0ed
--- /dev/null
+++ b/site/film/ui/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en" data-theme="light">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; form-action 'none'; base-uri 'none'" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Piik demonstration</title>
+ <link rel="stylesheet" href="./ui.css" />
+ <script src="./ui.js" defer></script>
+ </head>
+ <body><div id="camera"><div id="root"></div><svg id="cursor" width="42" height="49" viewBox="0 0 60 70" aria-hidden="true"><path d="M3 3v55l16-16 13 27 14-6-14-27 27-3Z" fill="#203037" stroke="#faf5e7" stroke-width="4" stroke-linejoin="round"/></svg></div></body>
+</html>
diff --git a/site/film/ui/main.tsx b/site/film/ui/main.tsx
new file mode 100644
index 00000000..97a9e5b1
--- /dev/null
+++ b/site/film/ui/main.tsx
@@ -0,0 +1,453 @@
+// Staged data, real product components. This sandbox never starts a room,
+// requests capture permission, or connects to an API/signaling service.
+import { useLayoutEffect, useRef } from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import {
+ AppHeader,
+ LedStrip,
+} from "../../../src/client/components/living/Header";
+import { LauncherForm } from "../../../src/client/components/living/LauncherForm";
+import {
+ StageTv,
+ StaticNoise,
+} from "../../../src/client/components/living/Stage";
+import { CaptureSourcePicker } from "../../../src/client/components/living/CaptureSourcePicker";
+import { Couch } from "../../../src/client/components/living/Couch";
+import { StatusIndicator } from "../../../src/client/components/living/StatusIndicator";
+import { RoomChip } from "../../../src/client/components/living/RoomChip";
+import {
+ Btn,
+ Row,
+ RowGroup,
+ NameTag,
+ FieldCap,
+ VisGlyph,
+} from "../../../src/client/components/living/primitives";
+import { setCopy, useCopy } from "../../../src/client/ui/copy";
+import { deriveParticipantStatus } from "../../../src/client/ui/media-status";
+import { gameMarkup, createGame } from "../../assets/game.js";
+import { sketchMarkup } from "../../assets/sketch.js";
+import { BEAT, INVITE_CUES } from "../score.js";
+import { point } from "./cursor";
+import "../../../src/client/styles.css";
+import "./ui.css";
+
+type Shot = "desktop" | "local" | "link" | "idle" | "picker" | "host" | "copied" | "chat" | "draft" | "sent" | "viewer";
+const noop = () => {};
+const roomId = "9527";
+const inviteUrl = `https://invite.piik.example/r/${roomId}`;
+const host = "d27a938b-61f5-4ab2-b8e4-3fc090c3ae18";
+const guests = [
+ "779594c8-a92c-48d9-918f-a7d0befa46d1",
+ "7e3c8491-04c9-44b0-a233-b2f4d894058b",
+ "c8f606ea-0e95-40d6-9018-436bedbdc742",
+];
+const status = deriveParticipantStatus(
+ { mediaReady: true, upstream: { kind: "peer", peerId: host } },
+ true,
+);
+let drawGame: ((time: number) => void) | undefined;
+function Game() {
+ const ref = useRef<SVGSVGElement>(null);
+ useLayoutEffect(() => {
+ ref.current!.innerHTML = gameMarkup("ui-game");
+ drawGame = createGame(ref.current!, "ui-game");
+ return () => {
+ drawGame = undefined;
+ };
+ }, []);
+ return (
+ <svg
+ ref={ref}
+ className="sample-game"
+ viewBox="0 0 1600 900"
+ aria-hidden="true"
+ />
+ );
+}
+const thumbnail =
+ "data:image/svg+xml," +
+ encodeURIComponent(
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900">${gameMarkup("thumb")}</svg>`,
+ );
+const sources = [
+ {
+ kind: "window" as const,
+ sourceId: "101",
+ pid: 1,
+ creationTime: "1",
+ title: "Little Wander",
+ },
+ {
+ kind: "window" as const,
+ sourceId: "102",
+ pid: 2,
+ creationTime: "2",
+ title: "Sketchbook",
+ },
+];
+const preview = async (target: { sourceId: string }) =>
+ target.sourceId === "101"
+ ? thumbnail
+ : "data:image/svg+xml," +
+ encodeURIComponent(
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 620 720">${sketchMarkup('thumb-sketch')}</svg>`,
+ );
+
+function Folder({size}: {size: number}) {
+ return <svg width={size} height={size} viewBox="0 0 32 32" aria-hidden="true"><path d="M3 10V7q0-2 2-2h8l4 4h10q2 0 2 2v14q0 2-2 2H5q-2 0-2-2Z" fill="#f3cc68" stroke="#203037" strokeWidth="1.6" /><path d="M3 12h26" stroke="#203037" strokeWidth="1.6" /></svg>;
+}
+
+function Chat({shot}: {shot: Shot}) {
+ const {lang} = useCopy();
+ const zh = lang === "zh";
+ return <section className="film-chat" aria-label={zh ? "聊天软件示意" : "Chat app example"}>
+ <header><span className="chat-avatar"><VisGlyph name="users" size={36} /></span><div><small>{zh ? "聊天软件示意" : "CHAT APP EXAMPLE"}</small><strong>{zh ? "周末小分队" : "Weekend crew"}</strong></div></header>
+ <div className="chat-messages"><p className="chat-bubble">{zh ? "人呢?" : "You joining?"}</p>
+ {shot === "sent" && <p className="chat-bubble chat-mine">{inviteUrl}<span>✓</span></p>}
+ </div>
+ <div className="chat-compose"><input id="chat-draft" value={shot === "draft" ? inviteUrl : ""} readOnly aria-label={zh ? "消息" : "Message"} /><button id="chat-send" type="button"><VisGlyph name="arrowRight" size={24} />{zh ? "发送" : "Send"}</button></div>
+ </section>;
+}
+
+function Screen({ shot }: { shot: Shot }) {
+ const { t, lang } = useCopy();
+ if (shot === "desktop") return (
+ <main className="desktop">
+ <div className="desktop-folder">
+ <div className="desktop-path"><Folder size={25} /> Piik App</div>
+ <div className="desktop-files">
+ <button id="desktop-app" type="button">
+ <img src="../../assets/favicon.svg" width="96" height="96" alt="" />
+ <span>piik-app.exe</span>
+ </button>
+ <div className="desktop-runtime"><Folder size={70} /><span>runtime</span></div>
+ </div>
+ </div>
+ <div className="desktop-taskbar"><img src="../../assets/favicon.svg" width="34" height="34" alt="" /></div>
+ </main>
+ );
+ const launcher = shot === "local" || shot === "link";
+ const chat = shot === "chat" || shot === "draft" || shot === "sent";
+ const live = shot === "host" || shot === "copied" || shot === "viewer" || chat;
+ const name = lang === "zh" ? "摸鱼办主任" : "ThisIsFine";
+ const names =
+ lang === "zh" ? ["派大星", "大聪明", "咸鱼突刺"] : ["Leeroy", "Kenobi", "NotABot"];
+ return (
+ <div className="lr-app">
+ <AppHeader
+ led={
+ launcher ? undefined : (
+ <LedStrip
+ state={live ? "live" : "off"}
+ label={t(
+ live ? "state.presence.online" : "state.presence.offline",
+ )}
+ />
+ )
+ }
+ />
+ {launcher ? (
+ <main className="lr-client-launch">
+ <LauncherForm
+ mode={shot}
+ onModeChange={noop}
+ site=""
+ onSiteChange={noop}
+ localAccessPassword=""
+ onLocalAccessPasswordChange={noop}
+ error={false}
+ onSubmit={(event) => event.preventDefault()}
+ />
+ </main>
+ ) : (
+ <main className="lr-room">
+ <div className="lr-scene">
+ <StageTv
+ live={live}
+ hasEntry={!live}
+ label={t("host.stageAria")}
+ indicator={live ? <StatusIndicator status={status} /> : undefined}
+ >
+ {live ? <Game /> : <StaticNoise />}
+ {shot === "picker" && (
+ <CaptureSourcePicker
+ nativeSources={{
+ kind: "ready",
+ processAudio: true,
+ systemAudio: true,
+ sources,
+ }}
+ onBrowser={noop}
+ onNative={noop}
+ onPreview={preview}
+ onRefresh={noop}
+ onCancel={noop}
+ />
+ )}
+ {!live && (
+ <div className="lr-tv-overlay" style={{ visibility: shot === "picker" ? "hidden" : undefined }}>
+ <div className="lr-entry-actions">
+ {(["host.start", "host.join"] as const).map((key, i) => (
+ <span className="lr-entry-action" key={key}>
+ <button
+ type="button"
+ className={`lr-tv-big${i === 0 ? " is-action is-ripple" : ""}`}
+ aria-label={t(key)}
+ >
+ <VisGlyph
+ name={i === 0 ? "cast" : "door"}
+ size={i === 0 ? 34 : 30}
+ draw={i === 0 ? "entry-cast" : "entry-door"}
+ />
+ </button>
+ <span className="lr-tv-msg">{t(key)}</span>
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+ </StageTv>
+ <div className="lr-stage-notices" />
+ <Couch
+ view={shot === "viewer" ? "viewer" : "host"}
+ host={{ key: host, name, online: true, you: shot !== "viewer" }}
+ entries={
+ shot === "viewer"
+ ? guests.map((key, i) => ({
+ key,
+ name: names[i],
+ status,
+ you: i === 0,
+ }))
+ : []
+ }
+ />
+ </div>
+ <div className="lr-deck">
+ <Row>
+ <RowGroup>
+ <FieldCap k="common.roomCode" />
+ <RoomChip roomId={roomId} onReplace={shot === "viewer" ? undefined : noop} />
+ </RowGroup>
+ <span className="lr-spacer" />
+ <NameTag name={shot === "viewer" ? names[0] : name} identity={shot === "viewer" ? guests[0] : host} />
+ <Btn icon="pencil" cap="common.edit" title="host.nameEdit" />
+ <Btn icon="gauge" cap="host.details" title="host.details" />
+ <Btn
+ icon="network"
+ cap="host.topology"
+ title="host.topology.show"
+ />
+ </Row>
+ {live && shot !== "viewer" ? (
+ <>
+ <Row>
+ <Btn icon="pause" cap="host.pause" title="host.pause" />
+ <Btn icon="square" cap="host.stop" title="host.stop" />
+ <Btn
+ icon="share"
+ cap="host.switchSource"
+ title="host.switchSource"
+ />
+ </Row>
+ <Row label={t("host.invite")}>
+ <RowGroup actions>
+ <Btn
+ icon={shot === "copied" || chat ? "check" : "link"}
+ cap="common.copy"
+ title={
+ shot === "copied" || chat ? "common.copied" : "host.invite.copy"
+ }
+ />
+ <Btn
+ icon="refresh"
+ cap="host.invite.rotateShort"
+ title="host.invite.rotate"
+ />
+ <Btn
+ icon="linkOff"
+ cap="host.invite.revokeShort"
+ title="host.invite.revoke"
+ />
+ </RowGroup>
+ <input
+ className="lr-invite-url"
+ readOnly
+ value={inviteUrl}
+ aria-label={t("host.invite")}
+ />
+ </Row>
+ </>
+ ) : null}
+ </div>
+ </main>
+ )}
+ {chat && <Chat shot={shot} />}
+ </div>
+ );
+}
+
+const root = createRoot(document.getElementById("root")!);
+const camera = document.getElementById("camera")!;
+const cursor = document.getElementById("cursor")!;
+let current = "";
+const clamp = (n: number) => Math.min(1, Math.max(0, n));
+const ease = (n: number) => 1 - (1 - clamp(n)) ** 4;
+const cues = {
+ mode: 1.5 * BEAT,
+ launch: 4 * BEAT,
+ share: 1.5 * BEAT,
+ source: 4 * BEAT,
+ live: 4.5 * BEAT,
+ ...INVITE_CUES,
+};
+type Frame = {
+ scene: "desktop" | "launch" | "share" | "invite";
+ local: number;
+ time: number;
+ lang: "en" | "zh-CN";
+};
+let settling = 0;
+// The opaque sandbox cannot persist its sample locale/theme to the real app.
+window.addEventListener("message", (event) => {
+ const data = event.data;
+ if (
+ event.source !== parent ||
+ data?.type !== "piik-film-ui" ||
+ !["desktop", "launch", "share", "invite"].includes(data.scene) ||
+ !["en", "zh-CN"].includes(data.lang) ||
+ !Number.isFinite(data.time) ||
+ !Number.isFinite(data.local)
+ )
+ return;
+ const t = data.local;
+ const shot: Shot =
+ data.scene === "desktop"
+ ? data.scene
+ : data.scene === "launch"
+ ? t >= cues.launch + BEAT / 2
+ ? "idle"
+ : t < cues.mode + BEAT / 4
+ ? "local"
+ : "link"
+ : data.scene === "share"
+ ? t < cues.share + BEAT / 4
+ ? "idle"
+ : t < cues.live
+ ? "picker"
+ : "host"
+ : t < cues.copy + BEAT / 4
+ ? "host"
+ : t < cues.chat ? "copied"
+ : t < cues.paste ? "chat"
+ : t < cues.send + BEAT / 4 ? "draft"
+ : t < cues.viewer ? "sent" : "viewer";
+ const key = `${data.lang}:${shot}`;
+ if (key !== current) {
+ current = key;
+ setCopy({ lang: data.lang === "en" ? "en" : "zh", vis: false });
+ flushSync(() => root.render(<Screen shot={shot} />));
+ // A scripted picker must not steal the film's keyboard focus or show its
+ // autofocus tooltip. The actual picker retains autofocus in the product.
+ if (document.activeElement instanceof HTMLElement)
+ document.activeElement.blur();
+ }
+ paint(data);
+ // A newly shown iframe needs a layout frame; participants also align their
+ // gestures on mount. Reapply this same position after both have settled.
+ cancelAnimationFrame(settling);
+ settling = requestAnimationFrame(() => paint(data));
+});
+function paint(data: Frame) {
+ const t = data.local;
+ drawGame?.(data.time);
+ // Product CSS gestures use the film clock, including pause, seek and replay.
+ document.getAnimations().forEach((animation) => {
+ animation.pause();
+ animation.currentTime = data.time * 1000;
+ });
+ camera.style.transform = "none";
+ let pan = 0;
+ if (data.scene === "invite") {
+ const row = document.querySelector<HTMLElement>(".lr-invite-url");
+ pan = row ? Math.max(0, row.getBoundingClientRect().top - 490) : 130;
+ pan += (130 - pan) * ease((t - 7 * BEAT) / BEAT);
+ pan *= ease(t / BEAT);
+ const chat = document.querySelector<HTMLElement>(".film-chat");
+ if (chat) chat.style.transform = `translateY(${pan}px)`;
+ }
+ const center = (element: HTMLElement | null | undefined) => {
+ const box = element?.getBoundingClientRect();
+ return box ? { x: box.x + box.width / 2, y: box.y + box.height / 2 } : undefined;
+ };
+ let from = { x: 1040, y: 710 };
+ let target: ReturnType<typeof center>;
+ let moveAt = BEAT / 2, moveFor = BEAT, clickAt = 0, hideAt = 0;
+ if (data.scene === "desktop") {
+ target = center(document.getElementById("desktop-app"));
+ clickAt = 2.5 * BEAT;
+ hideAt = 4 * BEAT;
+ moveFor = 1.5 * BEAT;
+ const press = Math.sin(clamp((t - clickAt) / (BEAT / 2)) * Math.PI);
+ document.getElementById("desktop-app")!.style.transform = `scale(${1 - .04 * press})`;
+ }
+ if (data.scene === "launch") {
+ const mode = center(document.querySelectorAll<HTMLElement>('[role="radio"]')[1]);
+ target = mode;
+ clickAt = cues.mode;
+ hideAt = cues.launch + BEAT / 2;
+ if (t >= 2 * BEAT && mode) {
+ from = mode;
+ target = center(document.querySelector<HTMLElement>('button[type="submit"]'));
+ moveAt = 2 * BEAT;
+ moveFor = 1.5 * BEAT;
+ clickAt = cues.launch;
+ }
+ }
+ if (data.scene === "share") {
+ // The entry stays laid out beneath the picker, so either seek direction
+ // uses the actual preceding control as its anchor, without cursor history.
+ const entry = center(document.querySelector<HTMLElement>(".lr-entry-action button"));
+ target = entry;
+ moveFor = BEAT;
+ clickAt = cues.share;
+ hideAt = cues.live;
+ if (t >= 2.25 * BEAT && entry) {
+ from = entry;
+ target = center(document.querySelector<HTMLElement>(".lr-source-option"));
+ moveAt = 2.25 * BEAT;
+ moveFor = 1.25 * BEAT;
+ clickAt = cues.source;
+ }
+ }
+ if (data.scene === "invite") {
+ const copy = center(
+ document
+ .querySelector<HTMLElement>(".lr-invite-url")
+ ?.closest(".lr-row")
+ ?.querySelector<HTMLElement>("button"),
+ );
+ target = copy;
+ clickAt = cues.copy;
+ hideAt = cues.send + BEAT;
+ if (t >= cues.chat && copy) {
+ from = copy;
+ target = center(document.getElementById('chat-draft'));
+ moveAt = cues.chat;
+ moveFor = BEAT;
+ clickAt = cues.paste;
+ }
+ if (t >= cues.paste + BEAT / 2) {
+ from = center(document.getElementById('chat-draft')) ?? from;
+ target = center(document.getElementById('chat-send'));
+ moveAt = cues.paste + BEAT / 2;
+ moveFor = BEAT;
+ clickAt = cues.send;
+ }
+ }
+ point(cursor, t, from, target, moveAt, moveFor, clickAt, hideAt);
+ camera.style.transform = `translateY(${-pan}px)`;
+}
+parent.postMessage({ type: "piik-film-ui-ready" }, "*");
diff --git a/site/film/ui/ui.css b/site/film/ui/ui.css
new file mode 100644
index 00000000..f90d7040
--- /dev/null
+++ b/site/film/ui/ui.css
@@ -0,0 +1,30 @@
+html,body { width:1100px; height:740px; margin:0; overflow:hidden; background:var(--wall); }
+#camera { width:1100px; transform-origin:0 0; }
+.lr-app { min-height:740px; }
+.sample-game { display:block; width:100%; height:100%; }
+.desktop { position:relative; display:grid; place-items:center; width:1100px; height:740px; background:linear-gradient(125deg,#b8e2c9 0 58%,#f3cc68 58% 76%,#e8f3ef 76%); color:#203037; }
+.desktop-folder { width:690px; height:425px; border:2px solid #203037; border-radius:16px; background:#faf5e7; box-shadow:9px 10px 0 #203037; }
+.desktop-path { display:flex; align-items:center; gap:12px; height:66px; padding:0 26px; border-bottom:2px solid #203037; font-weight:700; font-size:22px; }
+.desktop-files { display:flex; align-items:flex-start; gap:60px; padding:62px 72px; }
+.desktop-files > * { display:flex; flex-direction:column; align-items:center; gap:19px; width:190px; padding:16px; font:650 22px var(--font); }
+#desktop-app { border:2px solid #85baa8; border-radius:12px; color:inherit; background:#e8f3ef; }
+.desktop-runtime { color:#81622e; }
+.desktop-runtime > svg { margin:13px 0; }
+.desktop-taskbar { position:absolute; bottom:0; left:0; right:0; height:58px; display:grid; place-items:center; border-top:1px solid #20303744; background:#faf5e7dd; }
+.film-chat { position:absolute; z-index:40; left:0; top:0; width:1100px; height:740px; display:flex; flex-direction:column; background:#e8f3ef; color:#203037; }
+.film-chat header { display:flex; align-items:center; gap:21px; padding:28px 42px; border-bottom:2px solid #20303722; background:#faf5e7; }
+.chat-avatar { display:grid; place-items:center; width:65px; height:65px; border-radius:20px; background:#f3cc68; }
+.film-chat header div { display:grid; gap:8px; }
+.film-chat small { font-size:14px; letter-spacing:.08em; color:#53696b; }
+.film-chat strong { font-size:27px; }
+.chat-messages { display:flex; flex:1; flex-direction:column; align-items:flex-start; gap:42px; padding:48px 42px; }
+.chat-bubble { margin:0; border:1px solid #b5c7bd; border-radius:20px; padding:23px 28px; background:#faf5e7; font-size:24px; }
+.chat-mine { align-self:flex-end; background:#b8e2c9; }
+.chat-mine span { margin-left:22px; color:#37765a; }
+.chat-compose { display:flex; gap:18px; padding:28px 36px; border-top:1px solid #b5c7bd; background:#faf5e7; }
+.chat-compose input { flex:1; min-width:0; padding:19px 23px; border:2px solid #b5c7bd; border-radius:16px; font-size:24px; color:inherit; background:#fffefa; }
+.chat-compose button { display:flex; align-items:center; gap:12px; padding:16px 25px; border:0; border-radius:16px; font:700 23px var(--font); color:#faf5e7; background:#203037; }
+#cursor { position:absolute; left:0; top:0; z-index:100; pointer-events:none; transform-origin:0 0; }
+[hidden] { display:none !important; }
+/* The film supplies actions and samples; these controls retain product markup. */
+body { pointer-events:none; }
diff --git a/site/film/ui/website.ts b/site/film/ui/website.ts
new file mode 100644
index 00000000..18feb21d
--- /dev/null
+++ b/site/film/ui/website.ts
@@ -0,0 +1,47 @@
+// The actual homepage, driven by the film's existing time and inert sandbox.
+import "../../main.js";
+import { BEAT } from "../score.js";
+import { point } from "./cursor";
+
+const language = document.getElementById("language")!;
+const theme = document.getElementById("theme") as HTMLSelectElement;
+theme.value = "light";
+theme.dispatchEvent(new Event("change"));
+document.documentElement.style.scrollBehavior = "auto";
+document.documentElement.style.overflow = "hidden";
+document.body.style.pointerEvents = "none";
+const holdHero = () => { (document.querySelector(".living-room") as HTMLImageElement).src = "./assets/living-room.svg#still"; };
+holdHero();
+// The real homepage follows OS changes; this staged copy always holds its art.
+matchMedia("(prefers-reduced-motion: reduce)").addEventListener("change", holdHero);
+const cursor = document.getElementById("cursor")!;
+cursor.style.cssText = "position:fixed;left:0;top:0;z-index:100;pointer-events:none;transform-origin:0 0";
+let settling = 0;
+
+window.addEventListener("message", (event) => {
+ const data = event.data;
+ if (event.source !== parent || data?.type !== "piik-film-ui" ||
+ data.scene !== "website" || !["en", "zh-CN"].includes(data.lang) ||
+ !Number.isFinite(data.local) || !Number.isFinite(data.time)) return;
+ paint(data);
+ cancelAnimationFrame(settling);
+ settling = requestAnimationFrame(() => paint(data));
+});
+function paint(data: {lang: string; local: number; time: number}) {
+ if (document.documentElement.lang !== data.lang) language.click();
+ const download = document.getElementById("download")!;
+ const button = download.querySelector<HTMLAnchorElement>(".download-button")!;
+ const progress = Math.min(1, Math.max(0, (data.local - 1.25 * BEAT) / (2 * BEAT)));
+ const scroll = download.offsetTop - 36;
+ window.scrollTo(0, scroll * (progress * progress * (3 - 2 * progress)));
+ document.getAnimations().forEach((animation) => {
+ animation.pause();
+ animation.currentTime = data.time * 1000;
+ });
+ const box = button.getBoundingClientRect();
+ const click = Math.sin(Math.min(1, Math.max(0, (data.local - 4.5 * BEAT) / (BEAT / 2))) * Math.PI);
+ button.style.transform = `scale(${1 - .04 * click})`;
+ point(cursor, data.local, {x:995,y:615}, {x:box.x+box.width/2,y:box.y+box.height/2},
+ 3.25*BEAT, BEAT, 4.5*BEAT, 6*BEAT);
+}
+parent.postMessage({type: "piik-film-ui-ready"}, "*");
diff --git a/site/index.html b/site/index.html
new file mode 100644
index 00000000..37b5fb96
--- /dev/null
+++ b/site/index.html
@@ -0,0 +1,903 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="color-scheme" content="light dark" />
+ <meta
+ name="description"
+ content="Share the good stuff. Piik is free screen sharing for games, movie nights, drawings and photos. Invite up to 20 friends to watch in their browsers."
+ />
+ <meta name="theme-color" content="#e9f2ee" />
+ <title>Piik — Share the good stuff.</title>
+ <link rel="icon" href="./assets/favicon.svg" type="image/svg+xml" />
+ <link rel="stylesheet" href="./styles.css" />
+ <link rel="stylesheet" href="./assets/brand.css" />
+ <script type="module" src="./main.js"></script>
+ </head>
+ <body>
+ <a class="skip-link" href="#main"><span lang="en">Skip to content</span><span lang="zh-CN">跳到正文</span></a>
+ <svg class="symbols" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
+ <symbol id="tv-mark" viewBox="0 0 32 32">
+ <g fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
+ <path d="m11 4 5 4 5-4" />
+ <rect x="4" y="8" width="24" height="18" rx="4" />
+ <circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none" />
+ <path d="M19 17c1.5-1.8 3.2-1.8 4.7 0M10 29l2-3m10 3-2-3" />
+ </g>
+ </symbol>
+ <symbol id="download-mark" viewBox="0 0 24 24">
+ <path
+ d="M12 3v12m-5-5 5 5 5-5M4 16v4h16v-4"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ </symbol>
+ </svg>
+
+ <header class="site-header wrap">
+ <a class="identity" href="#" aria-label="Piik" data-brand>Piik<span class="identity-dot">.</span></a>
+ <nav aria-label="Main / 主导航">
+ <a href="#start"><span lang="en">Get started</span><span lang="zh-CN">使用教程</span></a>
+ <a href="#demo"><span lang="en">Demo</span><span lang="zh-CN">在线演示</span></a>
+ <a href="#faq">FAQ</a>
+ <a href="#download"><span lang="en">Download</span><span lang="zh-CN">下载</span></a>
+ <a href="#docs"><span lang="en">Docs</span><span lang="zh-CN">文档</span></a>
+ </nav>
+ <div class="preferences" hidden>
+ <button id="language" type="button" lang="zh-CN" aria-label="切换到简体中文">简体中文</button>
+ <label class="theme-picker"
+ ><span class="sr-only"><span lang="en">Color theme</span><span lang="zh-CN">外观</span></span
+ ><svg viewBox="0 0 24 24" aria-hidden="true">
+ <circle cx="12" cy="12" r="7.5" fill="none" stroke="currentColor" stroke-width="1.6" />
+ <path d="M12 4.5a7.5 7.5 0 0 1 0 15Z" fill="currentColor" /></svg
+ ><select id="theme">
+ <option value="system">System</option>
+ <option value="light">Light</option>
+ <option value="dark">Dark</option>
+ </select></label
+ >
+ </div>
+ </header>
+
+ <main id="main">
+ <section class="hero wrap" aria-labelledby="hero-title">
+ <div class="hero-copy">
+ <p class="eyebrow">
+ <span class="status-dot" aria-hidden="true"></span><span lang="en">Screen sharing · Free &amp; open source</span
+ ><span lang="zh-CN">屏幕共享 · 免费开源</span>
+ </p>
+ <h1 id="hero-title">
+ <span lang="en">Share the<br /><span class="highlight">good stuff.</span></span
+ ><span lang="zh-CN">来,看点<br /><span class="highlight">好康的。</span></span>
+ </h1>
+ <p class="hero-description">
+ <span lang="en">A great play. A movie night. Photos from your trip.<br />Share your screen and invite your friends.</span
+ ><span lang="zh-CN">游戏高光、周末电影、旅行照片。<br />开个房间,叫朋友来一起看。</span>
+ </p>
+ <div class="hero-actions">
+ <a class="button primary" href="#download"
+ ><span lang="en">Download Piik App</span><span lang="zh-CN">下载 Piik App</span
+ ><svg aria-hidden="true"><use href="#download-mark" /></svg></a
+ ><a class="text-link" href="#start"
+ ><span lang="en">Read the quick start</span><span lang="zh-CN">查看使用教程</span
+ ><span aria-hidden="true"> →</span></a
+ >
+ </div>
+ <p class="hero-note">
+ <span lang="en">One host · Up to 20 friends · Nothing to install to watch</span
+ ><span lang="zh-CN">一位房主 · 最多 20 位朋友 · 观看无须安装</span>
+ </p>
+ <a class="film-link" href="./film/" data-film-link>
+ <span class="film-play" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="m9 6 9 6-9 6Z" fill="currentColor" /></svg></span>
+ <span lang="en">A little film about Piik</span><span lang="zh-CN">用一支短片,认识 Piik</span>
+ <span class="film-length">76s</span>
+ </a>
+ </div>
+ <div class="hero-scene">
+ <img
+ class="living-room"
+ src="./assets/living-room.svg#still"
+ width="900"
+ height="590"
+ fetchpriority="high"
+ alt="A host with a small gold crown shares an RPG, a drawing, travel photos and an animated film. Three friends watch from the sofa."
+ />
+ <div class="scene-caption">
+ <span class="caption-line"></span>
+ <p><span lang="en">“I saved you a seat.”</span><span lang="zh-CN">“沙发给你留着呢。”</span></p>
+ </div>
+ </div>
+ </section>
+
+ <details class="film-preview wrap" id="film-preview" hidden>
+ <summary><span lang="en">A little film about Piik</span><span lang="zh-CN">用一支短片,认识 Piik</span><span class="film-collapse"><span lang="en">Close</span><span lang="zh-CN">收起</span> ×</span></summary>
+ <iframe id="website-film" title="Piik introduction / Piik 宣传片" allow="fullscreen" allowfullscreen></iframe>
+ </details>
+
+ <section class="how-section" id="how" aria-labelledby="how-title">
+ <div class="wrap">
+ <div class="section-heading">
+ <p class="eyebrow"><span lang="en">How it works</span><span lang="zh-CN">分享只需三步</span></p>
+ <h2 id="how-title">
+ <span lang="en"
+ ><span class="phrase">Pick a screen.</span> <span class="phrase">Send a link.</span>
+ <span class="phrase">Watch together.</span></span
+ ><span lang="zh-CN"><span class="phrase">选好画面,</span><span class="phrase">发个邀请。</span></span>
+ </h2>
+ </div>
+ <ol class="steps">
+ <li>
+ <button class="step-art" type="button" disabled>
+ <span class="sr-only"
+ ><span lang="en">Replay: choosing a screen</span><span lang="zh-CN">重播:选择分享画面</span></span
+ ><svg viewBox="0 0 250 136" aria-hidden="true">
+ <g fill="none" stroke="var(--drawing)" stroke-width="3" stroke-linejoin="round">
+ <rect x="47" y="17" width="141" height="90" rx="12" fill="var(--art-mint)" />
+ <path d="M105 108v14m-20 0h65" />
+ <g class="chosen-window">
+ <rect x="64" y="31" width="64" height="57" rx="7" fill="var(--art-paper)" />
+ <path d="m79 76 12-15 9 7 12-19" />
+ </g>
+ <rect x="137" y="31" width="34" height="23" rx="5" fill="var(--art-blue)" />
+ <rect x="137" y="64" width="34" height="24" rx="5" fill="var(--art-yellow)" />
+ <g class="screen-cursor">
+ <path d="m172 82 3 33 9-8 8 13 9-5-8-13 11-2Z" fill="var(--art-orange)" />
+ </g>
+ </g>
+ <path
+ d="m33 35-8-4m12-8-4-8m169 22 9-5"
+ stroke="var(--drawing)"
+ stroke-width="3"
+ stroke-linecap="round"
+ /></svg
+ ><span class="art-replay" aria-hidden="true">↻</span>
+ </button>
+ <p class="step-number">01 <span aria-hidden="true">/</span></p>
+ <h3><span lang="en">Choose what to share.</span><span lang="zh-CN">选好画面。</span></h3>
+ <p>
+ <span lang="en">Your whole screen or just one window.<br />You choose what to let people see.</span
+ ><span lang="zh-CN">整个屏幕,或只分享一个窗口。<br />分享哪些内容,由你决定。</span>
+ </p>
+ </li>
+ <li>
+ <button class="step-art" type="button" disabled>
+ <span class="sr-only"
+ ><span lang="en">Replay: sending an invitation</span
+ ><span lang="zh-CN">重播:发出邀请链接</span></span
+ ><svg viewBox="0 0 250 136" aria-hidden="true">
+ <g stroke="var(--drawing)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
+ <g class="invite-note">
+ <rect
+ x="44"
+ y="31"
+ width="143"
+ height="73"
+ rx="16"
+ fill="var(--art-paper)"
+ transform="rotate(-5 115 67)"
+ />
+ <path
+ d="m80 77-6-6a13 13 0 0 1 0-18l10-10a13 13 0 0 1 18 0l6 6m-10 8 6 6a13 13 0 0 1 0 18L94 91a13 13 0 0 1-18 0l-6-6m11-10 16-16"
+ fill="none"
+ />
+ <path d="M125 58h38m-38 15h24" />
+ </g>
+ <circle cx="191" cy="96" r="25" fill="var(--art-blue)" />
+ <g class="invite-plane">
+ <path d="m174 94 34-12-12 33-7-14Z" fill="var(--art-paper)" />
+ <path d="m189 101 8-9" />
+ </g>
+ <path class="invite-spark" d="M190 24v10m-5-5h10M33 93v8m-4-4h8" />
+ </g></svg
+ ><span class="art-replay" aria-hidden="true">↻</span>
+ </button>
+ <p class="step-number">02 <span aria-hidden="true">/</span></p>
+ <h3><span lang="en">Send a link.</span><span lang="zh-CN">发个邀请。</span></h3>
+ <p>
+ <span lang="en">Drop the room link in your group chat.<br />Your friends open it in a browser.</span
+ ><span lang="zh-CN">把邀请链接发给朋友。<br />对方用浏览器打开,就能加入。</span>
+ </p>
+ </li>
+ <li>
+ <button class="step-art" type="button" disabled>
+ <span class="sr-only"
+ ><span lang="en">Replay: friends joining the sofa</span
+ ><span lang="zh-CN">重播:朋友坐上沙发</span></span
+ ><svg viewBox="0 0 250 136" aria-hidden="true">
+ <g stroke="var(--drawing)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M55 112v9m139-9v9" />
+ <rect x="46" y="63" width="157" height="50" rx="17" fill="var(--couch)" stroke="none" />
+ <g class="sofa-friend">
+ <g fill="var(--art-blue)" stroke="none">
+ <circle cx="99" cy="39" r="12" />
+ <path d="M78 88c0-19.5 7.5-30 21-30s21 10.5 21 30q0 4.5-4.5 4.5h-33Q78 92.5 78 88Z" />
+ </g>
+ <path d="M95 39v1m8-1v1" />
+ </g>
+ <g class="sofa-friend">
+ <g fill="var(--art-pink)" stroke="none">
+ <circle cx="150" cy="37" r="12" />
+ <path d="M129 88c0-19.5 7.5-30 21-30s21 10.5 21 30q0 4.5-4.5 4.5h-33Q129 92.5 129 88Z" />
+ </g>
+ <path d="M146 37v1m8-1v1" />
+ </g>
+ <path d="M125 99v10M46 73h18a10 10 0 0 1 10 10v26m129-36h-18a10 10 0 0 0-10 10v26" fill="none" stroke="var(--couch-dark)" />
+ <g class="sofa-spark"><path d="m185 20 3 8 8 3-8 3-3 8-3-8-8-3 8-3Z" fill="var(--art-yellow)" /></g>
+ </g></svg
+ ><span class="art-replay" aria-hidden="true">↻</span>
+ </button>
+ <p class="step-number">03 <span aria-hidden="true">/</span></p>
+ <h3><span lang="en">Watch together.</span><span lang="zh-CN">沙发上见。</span></h3>
+ <p>
+ <span lang="en">Friends join from a phone or computer.<br />No installation needed to watch.</span
+ ><span lang="zh-CN">手机、电脑都能看。<br />观众不用装软件。</span>
+ </p>
+ </li>
+ </ol>
+ </div>
+ </section>
+
+ <section class="start-section wrap" id="start" aria-labelledby="start-title">
+ <div class="section-heading">
+ <p class="eyebrow"><span lang="en">Quick start</span><span lang="zh-CN">使用教程</span></p>
+ <h2 id="start-title">
+ <span lang="en">Start your first room.</span><span lang="zh-CN">开始第一次分享。</span>
+ </h2>
+ <p>
+ <span lang="en"
+ >Try the online demo first, or download the App to create your own room.<br />If Piik shows icons only,
+ select <strong>EN</strong> in its header to show English labels.</span
+ ><span lang="zh-CN"
+ >想先体验?从在线 Demo 开始;想自己开房间,可以下载客户端。<br />如果 Piik
+ 只显示图标,点击顶部的<strong>中</strong>即可显示中文按钮文字。</span
+ >
+ </p>
+ </div>
+ <nav class="guide-links" aria-label="Guides / 教程目录">
+ <a href="#demo"><span lang="en">Online demo</span><span lang="zh-CN">在线 Demo</span></a
+ ><a href="#guide-app"><span lang="en">Piik App</span><span lang="zh-CN">客户端</span></a
+ ><a href="#guide-web"><span lang="en">Existing Piik site</span><span lang="zh-CN">网页版</span></a
+ ><a href="#watch"><span lang="en">Join as a viewer</span><span lang="zh-CN">加入房间</span></a>
+ </nav>
+ <div class="guides">
+ <details class="guide" id="demo" open>
+ <summary>
+ <span class="guide-number">01</span
+ ><span class="guide-heading"
+ ><span lang="en">Try the online demo</span><span lang="zh-CN">体验在线 Demo</span
+ ><small
+ ><span lang="en">Open in your browser and start sharing</span
+ ><span lang="zh-CN">在浏览器打开,直接体验屏幕共享</span></small
+ ></span
+ >
+ </summary>
+ <div class="guide-body">
+ <ol class="guide-steps">
+ <li>
+ <strong
+ ><span lang="en">Open the demo on a computer.</span
+ ><span lang="zh-CN">在电脑上打开演示站。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Visit <a href="https://demo.piik.tv">demo.piik.tv</a> in a desktop browser that supports screen sharing.
+ </span
+ ><span lang="zh-CN"
+ >用支持屏幕共享的电脑浏览器打开 <a href="https://demo.piik.tv">demo.piik.tv</a>。
+ </span
+ >
+ </p>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Share a screen and copy its invitation.</span
+ ><span lang="zh-CN">分享画面,复制邀请。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Select <strong>Start sharing</strong>, choose a window, then select
+ <strong>Copy invite link</strong>.</span
+ ><span lang="zh-CN"
+ >点击<strong>开始分享</strong>,选择一个窗口,再点击<strong>复制邀请链接</strong>。</span
+ >
+ </p>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Open the invitation on a second device.</span
+ ><span lang="zh-CN">用另一台设备打开邀请。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Use a phone or another computer, or invite a friend. Select <strong>Play</strong> if the browser
+ does not start playback.</span
+ ><span lang="zh-CN"
+ >使用手机、另一台电脑,或邀请朋友加入。如果没有自动播放,点击<strong>播放</strong>。</span
+ >
+ </p>
+ </li>
+ <li>
+ <strong><span lang="en">Finish the demonstration.</span><span lang="zh-CN">结束体验。</span></strong>
+ <p>
+ <span lang="en"
+ >Try the volume and fullscreen controls, then select <strong>Stop sharing</strong> on the host’s
+ page.</span
+ ><span lang="zh-CN">试用音量、全屏等播放功能,完成后在房主页面点击<strong>停止分享</strong>。</span>
+ </p>
+ </li>
+ </ol>
+ <aside class="guide-note">
+ <h3><span lang="en">About this demo</span><span lang="zh-CN">演示站说明</span></h3>
+ <p id="demo-status">
+ <span lang="en"
+ >This demo uses direct device-to-device connections (P2P), with media forwarding disabled.
+ Restrictive networks may open the page but block the video.</span
+ ><span lang="zh-CN"
+ >演示站仅使用设备间直连(P2P),未启用媒体转发。
+ 在受限网络下,可能出现页面能打开、画面无法连接的情况。</span
+ >
+ </p>
+ <p>
+ <span lang="en">Self-hosted Piik sites can <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.md#optional-media-fallback">enable media forwarding (SFU)</a> as a fallback when a direct connection cannot be established.</span
+ ><span lang="zh-CN">自行部署的 Piik 站点可以<a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.zh-CN.md#可选启用媒体兜底">启用媒体转发(SFU)</a>,为直连失败提供兜底。</span>
+ </p>
+ <a class="button download-button" href="https://demo.piik.tv" aria-describedby="demo-status"
+ ><span lang="en">Open the demo</span><span lang="zh-CN">进入演示站</span
+ ><span aria-hidden="true"> ↗</span></a
+ >
+ </aside>
+ </div>
+ </details>
+ <details class="guide" id="guide-app">
+ <summary>
+ <span class="guide-number">02</span
+ ><span class="guide-heading"
+ ><span lang="en">Share with Piik App</span><span lang="zh-CN">用客户端分享</span
+ ><small
+ ><span lang="en">Download, open and create a room</span
+ ><span lang="zh-CN">下载后直接开房间</span></small
+ ></span
+ >
+ </summary>
+ <div class="guide-body">
+ <ol class="guide-steps">
+ <li>
+ <strong
+ ><span lang="en">Download and extract Piik App.</span
+ ><span lang="zh-CN">下载并解压 Piik App。</span></strong
+ >
+ <p>
+ <span lang="en"><a href="#download">Download the App package for your system</a>, extract it completely and keep the folder intact.</span
+ ><span lang="zh-CN"><a href="#download">下载对应系统的客户端程序包</a>,完整解压并保留目录结构。</span>
+ </p>
+ <dl class="launch-files">
+ <div>
+ <dt>Windows</dt>
+ <dd><span lang="en">Open </span><span lang="zh-CN">打开 </span><code>piik-app.exe</code></dd>
+ </div>
+ <div>
+ <dt>macOS</dt>
+ <dd><span lang="en">Open </span><span lang="zh-CN">打开 </span><code>Piik App.app</code></dd>
+ </div>
+ <div>
+ <dt>Linux</dt>
+ <dd><span lang="en">Run </span><span lang="zh-CN">运行 </span><code>./piik-app</code></dd>
+ </div>
+ </dl>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Choose Public invite, then Open Piik.</span
+ ><span lang="zh-CN">选择「公网邀请」,点击「进入 Piik」。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >The launcher opens in your system browser. Public invite creates a temporary Internet address
+ for friends outside your network. If you are on the same network or already have a site, see the mode descriptions.</span
+ ><span lang="zh-CN">启动页会在系统浏览器里打开。「公网邀请」会生成临时公网地址,方便不在同一网络的朋友加入。如果朋友和你在同一局域网,或你们已有站点,可查看模式说明。</span>
+ </p>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Start sharing and choose a source.</span
+ ><span lang="zh-CN">点击「开始分享」,选择来源。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Choose <strong>Browser</strong>, <strong>Apps / Windows</strong> or
+ <strong>Screens</strong> where available. Select the picture and audio you want to share.</span
+ ><span lang="zh-CN"
+ >按可用选项选择<strong>浏览器</strong>、<strong>程序 / 窗口</strong
+ >或<strong>屏幕</strong>,再选择具体画面和声音。</span
+ >
+ </p>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Copy the invitation and keep the App open.</span
+ ><span lang="zh-CN">复制邀请,并保持 App 运行。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Check the preview and select <strong>Copy invite link</strong>. Keep both the App and sharing tab
+ open until you finish.</span
+ ><span lang="zh-CN"
+ >确认预览后点击<strong>复制邀请链接</strong>。分享期间保持 App
+ 和分享标签页打开,结束时点击<strong>停止分享</strong>。</span
+ >
+ </p>
+ </li>
+ </ol>
+ <aside class="guide-note">
+ <h3><span lang="en">Which mode should I use?</span><span lang="zh-CN">模式怎么选?</span></h3>
+ <dl class="modes">
+ <div>
+ <dt><span lang="en">Local room</span><span lang="zh-CN">本地房间</span></dt>
+ <dd>
+ <span lang="en">Friends are on the same local network and can reach your computer.</span
+ ><span lang="zh-CN">朋友和你在同一局域网,且能访问你的电脑。</span>
+ </dd>
+ </div>
+ <div>
+ <dt><span lang="en">Public invite</span><span lang="zh-CN">公网邀请</span></dt>
+ <dd>
+ <span lang="en"
+ >Create a temporary Internet invitation. Closing the App ends this room and invitation.</span
+ ><span lang="zh-CN">生成临时公网邀请。退出 App 后,本次房间和邀请结束。</span>
+ </dd>
+ </div>
+ <div>
+ <dt><span lang="en">Connect to Site</span><span lang="zh-CN">连接站点</span></dt>
+ <dd>
+ <span lang="en">Enter the Piik site address your group already uses.</span
+ ><span lang="zh-CN">输入你们已有的 Piik 站点地址。</span>
+ </dd>
+ </div>
+ </dl>
+ <p>
+ <span lang="en"
+ >Public invite relies on P2P media connections, without a media-server fallback. Some networks may
+ open the page but fail to receive video.</span
+ ><span lang="zh-CN"
+ >公网邀请依赖 P2P
+ 媒体连接,不提供媒体服务器转发兜底;部分网络可能出现网页能打开、画面无法连接的情况。</span
+ >
+ </p>
+ <p>
+ <span lang="en"
+ >The macOS and Linux apps have not yet been tested on physical devices. Test reports are welcome on
+ <a href="https://github.com/TNTcraftHIM/Piik/issues">GitHub Issues</a>.
+ On macOS, native capture requires Apple silicon and macOS 13+. On Linux, it needs <a href="https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md">additional system components</a>. Browser capture is also available.</span
+ ><span lang="zh-CN"
+ >macOS 和 Linux 客户端尚未经过实机测试,欢迎有设备的朋友试用并在
+ <a href="https://github.com/TNTcraftHIM/Piik/issues">GitHub Issues</a> 反馈。
+ macOS 原生采集需要 Apple 芯片和 macOS 13 及以上;Linux 原生采集需要<a href="https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md">额外系统组件</a>。也可以用浏览器采集。</span
+ >
+ </p>
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/getting-started.md" lang="en">Full App guide →</a>
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/getting-started.zh-CN.md" lang="zh-CN">完整客户端使用指南 →</a>
+ </aside>
+ </div>
+ </details>
+ <details class="guide" id="guide-web">
+ <summary>
+ <span class="guide-number">03</span
+ ><span class="guide-heading"
+ ><span lang="en">Browser &amp; self-hosting · Advanced</span><span lang="zh-CN">网页版与自建站点 · 进阶</span
+ ><small
+ ><span lang="en">Requires an existing site running Piik Server</span
+ ><span lang="zh-CN">需要一个已部署 Piik Server 的站点</span></small
+ ></span
+ >
+ </summary>
+ <div class="guide-body">
+ <ol class="guide-steps">
+ <li>
+ <strong
+ ><span lang="en">Open the site on a computer.</span
+ ><span lang="zh-CN">在电脑上打开站点。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Use the Piik address provided by your friend or administrator. Enter the site passphrase if
+ required.</span
+ ><span lang="zh-CN">使用朋友或管理员提供的 Piik 地址。如果站点设置了口令,先输入口令。</span>
+ </p>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Choose Start sharing.</span><span lang="zh-CN">点击「开始分享」。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Select a screen, window or tab in the browser’s capture dialog. Enable audio if the selected
+ source supports it, then confirm.</span
+ ><span lang="zh-CN"
+ >在浏览器弹窗中选择屏幕、窗口或标签页;如需声音,勾选可用的音频选项,然后确认分享。</span
+ >
+ </p>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Check the preview and invite a friend.</span
+ ><span lang="zh-CN">确认预览,发送邀请。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Check the picture, then select <strong>Copy invite link</strong>. Send that link to the friends
+ you want to invite.</span
+ ><span lang="zh-CN"
+ >确认画面无误后,点击<strong>复制邀请链接</strong>,将链接发给要邀请的朋友。</span
+ >
+ </p>
+ </li>
+ <li>
+ <strong
+ ><span lang="en">Keep the sharing tab open.</span
+ ><span lang="zh-CN">分享期间保持标签页打开。</span></strong
+ >
+ <p>
+ <span lang="en"
+ >Use <strong>Switch source</strong> to change the picture, <strong>Pause sharing</strong> for a
+ break, and <strong>Stop sharing</strong> to finish.</span
+ ><span lang="zh-CN"
+ >更换画面时点击<strong>切换来源</strong>,暂时中断时点击<strong>暂停分享</strong>,结束时点击<strong>停止分享</strong>。</span
+ >
+ </p>
+ </li>
+ </ol>
+ <aside class="guide-note">
+ <h3><span lang="en">Where does the site come from?</span><span lang="zh-CN">Piik 站点从哪里来?</span></h3>
+ <p>
+ <span lang="en"
+ >Use a site provided by a friend or administrator. Hosting your own is an advanced option: run Piik Server,
+ configure HTTPS and open the required network ports. Follow the
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.md">self-hosting guide</a>.</span
+ ><span lang="zh-CN"
+ >可以直接使用朋友或管理员提供的站点。自己部署属于进阶操作,需要运行 Piik Server、配置 HTTPS 并开放相应网络端口,
+ 具体步骤见<a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.zh-CN.md">部署指南</a>。</span
+ >
+ </p>
+ <p>
+ <span lang="en">Share from a desktop browser on an HTTPS site. Sources and audio options vary by browser and operating system. No site yet? Start with the <a href="#demo">demo</a> or <a href="#guide-app">App</a>.</span
+ ><span lang="zh-CN">请用支持屏幕共享的电脑浏览器访问 HTTPS 站点。可分享的画面和声音取决于浏览器及系统。还没有站点时,可以先用<a href="#demo">在线 Demo</a> 或<a href="#guide-app">客户端</a>。</span>
+ </p>
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/getting-started.md" lang="en">Full browser guide →</a>
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/getting-started.zh-CN.md" lang="zh-CN">完整网页版使用指南 →</a>
+ <a href="#docs"><span lang="en">Documentation &amp; deployment</span><span lang="zh-CN">文档中心与部署教程</span><span aria-hidden="true"> →</span></a>
+ </aside>
+ </div>
+ </details>
+ </div>
+ <article class="watch-guide" id="watch" aria-labelledby="watch-title">
+ <svg aria-hidden="true"><use href="#tv-mark" /></svg>
+ <div>
+ <h3 id="watch-title">
+ <span lang="en">Here to watch a friend?</span><span lang="zh-CN">来围观朋友的分享?</span>
+ </h3>
+ <ol>
+ <li>
+ <span lang="en">Open your friend’s invitation in a phone or computer browser.</span
+ ><span lang="zh-CN">用手机或电脑浏览器打开朋友发来的邀请链接。</span>
+ </li>
+ <li>
+ <span lang="en">Wait for the picture. If playback does not start, select <strong>Play</strong>.</span
+ ><span lang="zh-CN">等待画面出现;如果没有自动播放,点击<strong>播放</strong>。</span>
+ </li>
+ <li>
+ <span lang="en"
+ >Move the pointer over the video or tap it to show volume, fullscreen and other playback
+ controls.</span
+ ><span lang="zh-CN">将鼠标移到画面上,或轻点画面,显示音量、全屏等播放控件。</span>
+ </li>
+ </ol>
+ <p>
+ <span lang="en"
+ >Only have a room code? Select <strong>Join a room</strong> on the same Piik site and enter the
+ four-digit code. Access depends on the host’s settings; a site passphrase or room password may be
+ required.</span
+ ><span lang="zh-CN"
+ >只有房间号时,在同一个 Piik
+ 站点选择<strong>加入房间</strong>,输入四位房间号。能否加入由房主设置决定,可能需要站点口令或房间密码。</span
+ >
+ </p>
+ </div>
+ </article>
+ </section>
+
+ <section class="faq-section wrap" id="faq" aria-labelledby="faq-title">
+ <div class="faq-intro">
+ <p class="eyebrow"><span lang="en">FAQ</span><span lang="zh-CN">常见问题</span></p>
+ <h2 id="faq-title">
+ <span lang="en">Good to know.</span><span lang="zh-CN">你可能<br />还想知道。</span>
+ </h2>
+ <svg class="faq-tv" aria-hidden="true"><use href="#tv-mark" /></svg>
+ </div>
+ <div class="questions">
+ <details>
+ <summary><span lang="en">Do I need my own server?</span><span lang="zh-CN">需要自己搭服务器吗?</span></summary>
+ <p>
+ <span lang="en">No. Try the <a href="#demo">online demo</a>, or choose <strong>Public invite</strong> in Piik App to create a temporary room. You can also use a Piik site provided by someone else. For a permanent site under your own domain, follow the <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.md">self-hosting guide</a>.</span>
+ <span lang="zh-CN">不需要。可以直接体验<a href="#demo">在线 Demo</a>,或在 Piik App 中选择<strong>公网邀请</strong>创建临时房间,也可以使用别人提供的 Piik 站点。想用自己的域名长期运行一个站点,再看<a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.zh-CN.md">部署指南</a>。</span>
+ </p>
+ </details>
+ <details>
+ <summary>
+ <span lang="en">Does everyone need Piik App?</span
+ ><span lang="zh-CN">每个人都需要安装 Piik App 吗?</span>
+ </summary>
+ <p>
+ <span lang="en"
+ >No. Friends watch in a desktop or mobile browser without installing anything. You can host from a
+ supported desktop browser on an existing Piik site, or use Piik App to create a room.</span
+ ><span lang="zh-CN"
+ >不需要。观众用电脑或手机浏览器就能看,无须安装。房主可以在已有 Piik
+ 站点上,用支持屏幕共享的电脑浏览器开始分享,也可以通过 Piik App 创建房间。</span
+ >
+ </p>
+ </details>
+ <details>
+ <summary>
+ <span lang="en">How many friends can join?</span><span lang="zh-CN">最多能叫多少朋友?</span>
+ </summary>
+ <p>
+ <span lang="en"
+ >One host and up to 20 invited viewers fit in a room. Piik is made for a private group hanging out
+ around one screen.</span
+ ><span lang="zh-CN"
+ >一个房间支持一位房主和最多 20
+ 位受邀观众。叫上熟悉的朋友,看看游戏、演示作品,或者围观彼此的新发现。</span
+ >
+ </p>
+ </details>
+ <details>
+ <summary>
+ <span lang="en">Can I share sound too?</span><span lang="zh-CN">声音也能一起分享吗?</span>
+ </summary>
+ <p>
+ <span lang="en"
+ >Yes, when the selected source and capture method support audio. Check the sound option when choosing
+ what to share. Browser and operating-system support varies; viewers may need to press Play and turn on
+ the video’s sound.</span
+ ><span lang="zh-CN"
+ >可以,前提是选择的画面来源和采集方式支持声音。选择分享内容时,检查声音选项。浏览器和系统支持有所不同;观众可能需要先点播放,再打开视频声音。</span
+ >
+ </p>
+ </details>
+ <details>
+ <summary>
+ <span lang="en">Can we watch from different places?</span
+ ><span lang="zh-CN">不在同一个地方,也能一起看吗?</span>
+ </summary>
+ <p>
+ <span lang="en"
+ >Yes. Use the demo, an Internet-accessible Piik site, or Public invite in the App. Public invite gives
+ your room a temporary address that can change or become unavailable; closing the App ends the room.
+ The demo and Public invite use direct media connections without server forwarding, so some networks
+ may load the page but block the video. You can also use a Piik site with media forwarding enabled
+ for a fallback connection.</span
+ ><span lang="zh-CN"
+ >可以使用在线 Demo、能从外网访问的 Piik 站点,或客户端的“公网邀请”。公网邀请的地址是临时的,可能中断或变化,退出 App 后房间也会结束。
+ Demo 和公网邀请的画面靠设备间直连传输,没有服务器转发兜底;部分网络可能出现页面能打开、画面连不上的情况。
+ 也可以使用已启用媒体转发兜底的 Piik 站点。</span
+ >
+ </p>
+ </details>
+ <details>
+ <summary>
+ <span lang="en">Which platforms are ready?</span><span lang="zh-CN">目前支持哪些平台?</span>
+ </summary>
+ <p>
+ <span lang="en"
+ >Windows App and browser sharing are the primary tested paths. Viewers can use a computer or phone browser.
+ The macOS and Linux apps have not yet been tested on physical devices; if you have a device,
+ we'd welcome your test results and <a href="https://github.com/TNTcraftHIM/Piik/issues">feedback</a>.</span
+ ><span lang="zh-CN"
+ >目前主要测试 Windows 客户端和浏览器分享,观众可使用电脑或手机浏览器。
+ macOS 和 Linux 客户端尚未经过实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span
+ >
+ </p>
+ </details>
+ </div>
+ </section>
+
+ <section class="download-section wrap" id="download" aria-labelledby="download-title">
+ <div class="section-heading">
+ <p class="eyebrow"><span lang="en">Download</span><span lang="zh-CN">客户端下载</span></p>
+ <h2 id="download-title"><span lang="en">Get Piik App.</span><span lang="zh-CN">下载 Piik App。</span></h2>
+ <p>
+ <span lang="en"
+ >Host from your computer, with controls in your browser.<br />Friends only need a browser to watch.</span
+ ><span lang="zh-CN">在电脑上运行客户端,在浏览器里操作。<br />观看朋友的分享,无须安装客户端。</span>
+ </p>
+ </div>
+ <p class="release-note" id="download-status">
+ <span class="release-label">GitHub · Gitee</span
+ ><span lang="en"
+ >On the release page, choose a file beginning with piik-app for your system. Read the release notes and
+ follow the App guide.</span
+ ><span lang="zh-CN">在发布页下载以 piik-app 开头、对应系统的客户端程序包,查看版本说明,再按客户端教程开始分享。</span>
+ </p>
+ <div class="download-cards">
+ <article class="download-card" aria-labelledby="download-windows">
+ <div class="platform-mark" aria-hidden="true">
+ <svg viewBox="0 0 32 32">
+ <path d="M4 5h10v10H4zm14 0h10v10H18zM4 19h10v10H4zm14 0h10v10H18z" fill="currentColor" />
+ </svg>
+ </div>
+ <h3 id="download-windows">Windows</h3>
+ <p>
+ <span lang="en">For x64 PCs. Choose the package marked</span
+ ><span lang="zh-CN">适用于 x64 电脑。请选择文件名含</span> <code>windows-amd64</code
+ ><span lang="en">.</span><span lang="zh-CN"> 的程序包。</span>
+ </p>
+ <a
+ class="button download-button"
+ href="https://github.com/TNTcraftHIM/Piik/releases"
+ aria-describedby="download-status"
+ ><svg aria-hidden="true"><use href="#download-mark" /></svg><span lang="en">GitHub download</span
+ ><span lang="zh-CN">GitHub 下载</span></a
+ ><a href="https://gitee.com/TNTcraftHIM/Piik/releases"
+ ><span lang="en">Gitee mirror</span><span lang="zh-CN">Gitee 国内镜像</span></a
+ >
+ </article>
+ <article class="download-card" aria-labelledby="download-macos">
+ <div class="platform-mark" aria-hidden="true">
+ <svg
+ viewBox="0 0 32 32"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <rect x="6" y="4" width="20" height="18" rx="2" />
+ <path d="M3 27h26M10 22l-2 5m14-5 2 5" />
+ </svg>
+ </div>
+ <h3 id="download-macos">macOS</h3>
+ <p>
+ <span lang="en">Apple silicon; native capture needs macOS 13+. Choose the package marked</span
+ ><span lang="zh-CN">适用于 Apple 芯片;原生采集需 macOS 13 及以上。请选择文件名含</span> <code>darwin-arm64</code
+ ><span lang="en">.</span><span lang="zh-CN"> 的程序包。</span>
+ </p>
+ <a
+ class="button download-button"
+ href="https://github.com/TNTcraftHIM/Piik/releases"
+ aria-describedby="download-status"
+ ><svg aria-hidden="true"><use href="#download-mark" /></svg><span lang="en">GitHub download</span
+ ><span lang="zh-CN">GitHub 下载</span></a
+ ><a href="https://gitee.com/TNTcraftHIM/Piik/releases"
+ ><span lang="en">Gitee mirror</span><span lang="zh-CN">Gitee 国内镜像</span></a
+ >
+ </article>
+ <article class="download-card" aria-labelledby="download-linux">
+ <div class="platform-mark" aria-hidden="true">
+ <svg
+ viewBox="0 0 32 32"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <rect x="3" y="5" width="26" height="22" rx="4" />
+ <path d="m9 12 5 4-5 4m9 0h5" />
+ </svg>
+ </div>
+ <h3 id="download-linux">Linux</h3>
+ <p>
+ <span lang="en">For x64 PCs. Choose the package marked</span
+ ><span lang="zh-CN">适用于 x64 电脑。请选择文件名含</span> <code>linux-amd64</code><span lang="en">.</span
+ ><span lang="zh-CN"> 的程序包。</span>
+ </p>
+ <a
+ class="button download-button"
+ href="https://github.com/TNTcraftHIM/Piik/releases"
+ aria-describedby="download-status"
+ ><svg aria-hidden="true"><use href="#download-mark" /></svg><span lang="en">GitHub download</span
+ ><span lang="zh-CN">GitHub 下载</span></a
+ ><a href="https://gitee.com/TNTcraftHIM/Piik/releases"
+ ><span lang="en">Gitee mirror</span><span lang="zh-CN">Gitee 国内镜像</span></a
+ >
+ </article>
+ </div>
+ <div class="download-help">
+ <a href="#guide-app"><span lang="en">Piik App setup guide</span><span lang="zh-CN">客户端使用教程</span><span aria-hidden="true"> →</span></a>
+ <p><span lang="en">The macOS and Linux apps have not yet been tested on physical devices. If you have a device, we'd welcome your <a href="https://github.com/TNTcraftHIM/Piik/issues">test results and feedback</a>.</span><span lang="zh-CN">macOS 和 Linux 客户端尚未经过实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span></p>
+ </div>
+ </section>
+
+ <section class="project-note wrap" id="docs" aria-labelledby="docs-title">
+ <svg class="project-tv" aria-hidden="true"><use href="#tv-mark" /></svg>
+ <div class="project-content">
+ <p class="eyebrow">
+ <span lang="en">Documentation &amp; self-hosting</span><span lang="zh-CN">文档与自托管</span>
+ </p>
+ <h2 id="docs-title">
+ <span lang="en">A site of your own.</span><span lang="zh-CN">给朋友们搭个站点。</span>
+ </h2>
+ <p>
+ <span lang="en"
+ >The documentation covers first-time setup, server configuration and maintenance. Start with the overview,
+ or go straight to the guide you need.</span
+ ><span lang="zh-CN"
+ >文档中心收录使用指南、服务器部署教程和维护说明。可以先看目录,也可以直接进入下面的专题。</span
+ >
+ </p>
+ <a class="docs-index" href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/README.md"
+ ><span lang="en">Open the documentation</span><span lang="zh-CN">查看文档中心</span
+ ><span aria-hidden="true"> ↗</span></a
+ >
+ <ul class="docs-links">
+ <li>
+ <a lang="en" href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.md"
+ >Self-hosting<span aria-hidden="true"> ↗</span></a
+ ><a
+ lang="zh-CN"
+ href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.zh-CN.md"
+ >部署自己的站点<span aria-hidden="true"> ↗</span></a
+ >
+ <p>
+ <span lang="en">One binary, with domain and network setup</span
+ ><span lang="zh-CN">从运行程序到配置域名与网络</span>
+ </p>
+ </li>
+ <li>
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/reference/configuration.md"
+ ><span lang="en">Configuration</span><span lang="zh-CN">配置参考</span
+ ><span aria-hidden="true"> ↗</span></a
+ >
+ <p>
+ <span lang="en">Access control, network ports and storage</span
+ ><span lang="zh-CN">访问控制、网络端口与存储</span>
+ </p>
+ </li>
+ <li>
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/service-management.md"
+ ><span lang="en">Service management</span><span lang="zh-CN">长期运行与容器</span
+ ><span aria-hidden="true"> ↗</span></a
+ >
+ <p>
+ <span lang="en">Automatic startup, Docker and server checks</span
+ ><span lang="zh-CN">开机启动、Docker 与运行检查</span>
+ </p>
+ </li>
+ </ul>
+ <p class="docs-note">
+ <span lang="en"
+ >Guides are maintained on GitHub. Getting started and deployment are available in English and Chinese;
+ detailed technical references are in English.</span
+ ><span lang="zh-CN">文档在 GitHub 持续维护。使用和部署教程提供中英文版本,详细技术参考为英文。</span>
+ </p>
+ </div>
+ </section>
+ </main>
+
+ <footer class="site-footer wrap">
+ <div class="footer-identity">
+ <svg aria-hidden="true"><use href="#tv-mark" /></svg
+ ><span>Piik<span class="identity-dot" aria-hidden="true">.</span></span>
+ <p><span lang="en">Share the good stuff.</span><span lang="zh-CN">来,看点好康的。</span></p>
+ </div>
+ <div class="footer-links">
+ <a href="https://github.com/TNTcraftHIM/Piik/blob/main/docs/README.md"
+ ><span lang="en">Documentation</span><span lang="zh-CN">文档中心</span></a
+ ><a href="https://github.com/TNTcraftHIM/Piik"
+ ><span lang="en">Source on GitHub</span><span lang="zh-CN">GitHub 源码</span
+ ><span aria-hidden="true"> ↗</span></a
+ ><a href="https://github.com/TNTcraftHIM/Piik/blob/main/LICENSE"
+ ><span lang="en">MIT license</span><span lang="zh-CN">MIT 许可证</span></a
+ >
+ </div>
+ <p class="footer-note">
+ <span lang="en">Piik’s own code is MIT-licensed. Contributions are welcome.</span
+ ><span lang="zh-CN">Piik 自有代码采用 MIT 许可,欢迎参与贡献。</span>
+ </p>
+ </footer>
+ </body>
+</html>
diff --git a/site/main.js b/site/main.js
new file mode 100644
index 00000000..bfae794a
--- /dev/null
+++ b/site/main.js
@@ -0,0 +1,127 @@
+import { mountBrands } from './assets/brand.js';
+import { initialLanguage, rememberLanguage } from './assets/language.js';
+mountBrands();
+// Content stays HTML; scripts only add preferences and replayable illustrations.
+const root = document.documentElement;
+const language = document.getElementById('language');
+const theme = document.getElementById('theme');
+const description = document.querySelector('meta[name="description"]');
+const roomIllustration = document.querySelector('.living-room');
+const film = document.getElementById('film-preview');
+const filmFrame = document.getElementById('website-film');
+const filmLink = document.querySelector('[data-film-link]');
+function syncFilmPreferences() {
+ const target = new URL(filmLink.href);
+ target.searchParams.set('lang', root.lang);
+ target.searchParams.set('theme', theme.value);
+ filmLink.href = target.href;
+ filmFrame.contentWindow?.postMessage({type:'piik-film-preferences',lang:root.lang,theme:theme.value}, location.origin);
+}
+const copy = {
+ en: {
+ title: document.title,
+ description: description.content,
+ themes: Object.fromEntries(Array.from(theme.options, (option) => [option.value, option.textContent])),
+ image: roomIllustration.alt,
+ },
+ 'zh-CN': {
+ title: 'Piik — 来,看点好康的。',
+ description: '游戏、绘画、电影、照片。Piik 是免费开源的屏幕共享工具,邀请最多 20 位朋友用浏览器观看。',
+ themes: { system: '跟随系统', light: '浅色', dark: '深色' },
+ image: '戴着小金冠的房主分享 RPG 游戏、绘画、旅行照片和动画电影,三位朋友坐在沙发上观看。',
+ },
+};
+function setLanguage(lang) {
+ root.lang = lang;
+ const chinese = lang === 'zh-CN';
+ language.lang = chinese ? 'en' : 'zh-CN';
+ language.textContent = chinese ? 'English' : '简体中文';
+ language.setAttribute('aria-label', chinese ? 'Switch to English' : '切换到简体中文');
+ const current = copy[root.lang];
+ document.title = current.title;
+ description.content = current.description;
+ roomIllustration.alt = current.image;
+ for (const option of theme.options) option.textContent = current.themes[option.value];
+ syncFilmPreferences();
+}
+language.addEventListener('click', () => {
+ setLanguage(root.lang === 'zh-CN' ? 'en' : 'zh-CN');
+ rememberLanguage(root.lang);
+});
+function syncThemeColor() {
+ document.querySelector('meta[name="theme-color"]').content = getComputedStyle(root).getPropertyValue('--wall').trim();
+}
+theme.addEventListener('change', () => {
+ root.dataset.theme = theme.value;
+ syncThemeColor();
+ syncFilmPreferences();
+});
+matchMedia('(prefers-color-scheme: dark)').addEventListener('change', syncThemeColor);
+syncThemeColor();
+document.querySelector('.preferences').hidden = false;
+
+// Ordinary links carry explicit choices between the page and its film.
+const preferences = new URLSearchParams(location.search);
+setLanguage(initialLanguage());
+if (['light', 'dark'].includes(preferences.get('theme'))) {
+ theme.value = preferences.get('theme');
+ root.dataset.theme = theme.value;
+ syncThemeColor();
+}
+syncFilmPreferences();
+filmLink.setAttribute('aria-controls', 'film-preview');
+filmLink.setAttribute('aria-expanded', 'false');
+filmLink.addEventListener('click', (event) => {
+ if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
+ event.preventDefault();
+ const target = new URL(event.currentTarget.href);
+ target.searchParams.set('embedded', '1');
+ if (!film.open) filmFrame.src = target.href;
+ film.hidden = false;
+ film.open = true;
+ filmLink.setAttribute('aria-expanded', 'true');
+ film.querySelector('summary').focus({preventScroll:true});
+ film.scrollIntoView({block:'start'});
+});
+film.addEventListener('toggle', () => {
+ if (film.open) return;
+ // Closing releases the frame, its music and its animation loop together.
+ filmFrame.removeAttribute('src');
+ film.hidden = true;
+ filmLink.setAttribute('aria-expanded', 'false');
+ filmLink.focus({preventScroll:true});
+});
+
+// Native disclosures remain usable without scripts; section links also reveal them.
+function revealGuide(hash) {
+ const target = document.getElementById(hash.slice(1));
+ if (target?.matches('details.guide')) target.open = true;
+}
+document.querySelectorAll('a[href^="#"]').forEach((link) => {
+ link.addEventListener('click', () => revealGuide(link.hash));
+});
+window.addEventListener('hashchange', () => revealGuide(location.hash));
+revealGuide(location.hash);
+
+const motion = matchMedia('(prefers-reduced-motion: reduce)');
+const illustrations = document.querySelectorAll('.step-art');
+document.querySelectorAll('.step-art').forEach((control) => {
+ const replayScene = () =>
+ control.getAnimations({ subtree: true }).forEach((animation) => {
+ if (animation instanceof CSSAnimation) animation.currentTime = 0;
+ });
+ (control.closest('li') ?? control).addEventListener('pointerenter', replayScene);
+ control.addEventListener('focus', replayScene);
+ control.addEventListener('click', () => {
+ control.focus({ preventScroll: true });
+ replayScene();
+ });
+});
+function syncMotionPreference() {
+ illustrations.forEach((button) => {
+ button.disabled = motion.matches;
+ });
+ roomIllustration.src = './assets/living-room.svg' + (motion.matches ? '#still' : '');
+}
+motion.addEventListener('change', syncMotionPreference);
+syncMotionPreference();
diff --git a/site/styles.css b/site/styles.css
new file mode 100644
index 00000000..e12c83c8
--- /dev/null
+++ b/site/styles.css
@@ -0,0 +1,317 @@
+:root {
+ color-scheme: light;
+ --wall: #e9f2ee;
+ --paper: #fafaf3;
+ --ink: #22303e;
+ --muted: #52635e;
+ --line: #c6d6cc;
+ --green: #256b47;
+ --orange: #e4572e;
+ --soft-orange: #f7e5cc;
+ --button-ink: #fafaf3;
+ --drawing: #22303e;
+ --art-mint: #c4e3ce;
+ --art-paper: #fffdf4;
+ --art-blue: #a2c8e8;
+ --art-yellow: #f5d37a;
+ --art-orange: #ee8955;
+ --art-pink: #e9b1bb;
+ --couch: #e9ad63;
+ --couch-dark: #cd8845;
+ --comic-beat: 3.2s;
+}
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) { color-scheme: dark; --wall: #14232b; --paper: #1b2d34; --ink: #eef4eb; --muted: #b3c4bd; --line: #3b5155; --green: #9bdbb2; --orange: #f28d66; --soft-orange: #3d342c; --button-ink: #14232b; }
+}
+:root[data-theme="dark"] { color-scheme: dark; --wall: #14232b; --paper: #1b2d34; --ink: #eef4eb; --muted: #b3c4bd; --line: #3b5155; --green: #9bdbb2; --orange: #f28d66; --soft-orange: #3d342c; --button-ink: #14232b; }
+* { box-sizing: border-box; }
+html { scroll-behavior: smooth; scroll-padding-top: 30px; }
+body { margin: 0; background: var(--wall); color: var(--ink); font: 16px/1.6 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; -webkit-font-smoothing: antialiased; }
+html[lang="en"] [lang="zh-CN"]:not(#language),
+html[lang="zh-CN"] [lang="en"]:not(#language) { display: none; }
+[hidden] { display: none !important; }
+::selection { background: var(--art-yellow); color: var(--drawing); }
+a { color: inherit; text-underline-offset: 5px; text-decoration-thickness: 1px; }
+button, select { font: inherit; color: inherit; }
+button, select, summary { cursor: pointer; }
+button { background: none; }
+button, a, select, summary { -webkit-tap-highlight-color: transparent; touch-action: manipulation; }
+:focus-visible { outline: 3px solid var(--orange); outline-offset: 5px; }
+h1, h2, h3, p { margin: 0; }
+h1, h2, h3 { text-wrap: balance; }
+.phrase { display: inline-block; }
+h1, h2 { font-weight: 750; letter-spacing: -.055em; }
+p { text-wrap: pretty; }
+svg { display: block; }
+.wrap { width: min(1200px, calc(100% - 96px)); margin-inline: auto; }
+.symbols { position: absolute; width: 0; height: 0; overflow: hidden; }
+.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
+.skip-link { position: absolute; left: 20px; top: -80px; z-index: 5; background: var(--ink); color: var(--paper); padding: 10px 20px; border-radius: 8px; }
+.skip-link:focus { top: 12px; }
+.site-header { min-height: 100px; display: flex; align-items: center; gap: 32px; border-bottom: 1px solid var(--line); }
+.site-header nav { display: flex; flex-wrap: wrap; column-gap: 25px; margin-left: auto; }
+.site-header nav a { display: inline-flex; align-items: center; min-height: 44px; font-size: 14px; font-weight: 600; text-decoration: none; }
+.site-header nav a:is(:hover, :focus-visible), .footer-links a:is(:hover, :focus-visible) { color: var(--green); }
+.preferences { display: flex; align-items: center; gap: 13px; border-left: 1px solid var(--line); padding-left: 24px; }
+.preferences button { min-height: 44px; padding: 6px 3px; font-size: 13px; border: 0; }
+.theme-picker { display: flex; align-items: center; gap: 4px; }
+.theme-picker svg { width: 17px; height: 17px; }
+.theme-picker select { min-height: 44px; max-width: 92px; border: 0; background: transparent; font-size: 12px; padding: 4px; }
+.theme-picker option { color: var(--ink); background: var(--paper); }
+.hero { display: grid; grid-template-columns: 1fr 1.08fr; align-items: center; gap: 18px; padding-block: 76px 77px; }
+.hero-copy { position: relative; z-index: 1; min-width: 0; padding-bottom: 9px; }
+.eyebrow { display: flex; align-items: center; gap: 9px; color: var(--green); font-size: 11px; font-weight: 750; letter-spacing: .12em; text-transform: uppercase; }
+.status-dot { width: 7px; height: 7px; flex: none; border-radius: 100%; background: var(--green); box-shadow: 0 0 0 4px color-mix(in srgb, var(--green) 10%, transparent); }
+h1 { font-size: clamp(49px, 5.7vw, 76px); line-height: 1.06; margin-block: 22px 23px; }
+.highlight { position: relative; white-space: nowrap; }
+.highlight::after { content: ""; position: absolute; left: 1px; right: -2px; bottom: -5px; height: 6px; background: var(--orange); border-radius: 50%; transform: rotate(-2deg); }
+.hero-description { font-size: 18px; line-height: 1.8; color: var(--muted); margin-bottom: 28px; }
+.hero-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 16px 24px; }
+.text-link { display: inline-flex; align-items: center; min-height: 44px; font-size: 13px; font-weight: 650; }
+.button { display: inline-flex; justify-content: center; align-items: center; gap: 29px; min-height: 54px; padding: 12px 25px; border: 2px solid var(--ink); border-radius: 999px; text-decoration: none; font-size: 14px; font-weight: 700; transition: transform .22s cubic-bezier(.2, .9, .3, 1.4); }
+.button svg { width: 22px; height: 22px; transition: transform .22s cubic-bezier(.2, .9, .3, 1.4); }
+.primary { background: var(--ink); color: var(--button-ink); box-shadow: 0 4px 0 color-mix(in srgb, var(--ink) 18%, transparent); }
+.button:not(:disabled):is(:hover, :focus-visible) { transform: translateY(-3px); box-shadow: 0 7px 0 color-mix(in srgb, var(--ink) 18%, transparent); }
+.button:not(:disabled):is(:hover, :focus-visible) svg { transform: translateY(3px); }
+.button:not(:disabled):active { transform: translateY(2px); box-shadow: 0 1px 0 color-mix(in srgb, var(--ink) 18%, transparent); }
+.hero-note { color: var(--muted); font-size: 12px; line-height: 1.7; margin-top: 18px; }
+.film-link { display:inline-flex; align-items:center; gap:10px; min-height:44px; margin-top:18px; text-decoration:none; font-size:12px; font-weight:650; }
+.film-play { display:grid; place-items:center; width:33px; height:33px; border-radius:50%; color:var(--orange); background:var(--paper); transition:transform .22s cubic-bezier(.2,.9,.3,1.4); }
+.film-play svg { width:23px; height:23px; }
+.film-link:is(:hover,:focus-visible) .film-play { transform:scale(1.12); }
+.film-length { color:var(--muted); font-size:10px; font-weight:400; padding-left:4px; }
+.film-preview { container-type:inline-size; margin-bottom:36px; }
+.film-preview > summary { justify-content:flex-start; padding:14px 0; }
+.film-preview > summary::after { content:none; }
+.film-collapse { margin-left:auto; font-size:12px; color:var(--muted); }
+.film-preview iframe { display:block; width:100%; height:calc(56.25cqw + 144px); border:0; }
+.download-help { margin-top:22px; text-align:center; }
+.download-help > a { display:inline-flex; align-items:center; min-height:44px; font-size:14px; font-weight:650; }
+.download-help p { max-width:760px; margin:6px auto 0; color:var(--muted); font-size:13px; }
+.hero-scene { min-width: 0; }
+.living-room { display: block; width: 108%; height: auto; max-width: none; margin-left: -5%; }
+.scene-caption { display: flex; justify-content: center; align-items: center; gap: 10px; font-size: 12px; color: var(--muted); margin-top: 2px; }
+.caption-line { width: 23px; height: 1px; background: var(--orange); transform: rotate(-6deg); }
+.how-section { padding-block: 67px 63px; background: var(--paper); border-block: 1px solid var(--line); }
+.section-heading { text-align: center; }
+.section-heading .eyebrow { justify-content: center; }
+h2 { font-size: clamp(30px, 3.25vw, 42px); line-height: 1.2; margin-top: 12px; }
+.section-heading > p:last-child:not(.eyebrow) { color: var(--muted); margin-top: 16px; font-size: 15px; }
+.steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 49px; margin: 42px 0 0; padding: 0; list-style: none; }
+.steps li { position: relative; }
+.steps li:not(:last-child)::after { position: absolute; content: "↗"; top: 49px; right: -34px; font-size: 27px; font-weight: 350; color: var(--muted); transform: rotate(28deg); }
+.step-art { position: relative; display: block; width: 100%; height: 126px; padding: 0; border: 0; border-radius: 12px; margin-bottom: 15px; }
+.step-art svg { width: 100%; height: 100%; }
+.step-art:disabled { cursor: default; }
+.art-replay { position: absolute; right: max(0px, calc(50% - 100px)); bottom: 0; color: var(--muted); font-size: 18px; }
+.step-art:disabled .art-replay { display: none; }
+.steps li:is(:hover, :focus-within) .art-replay { color: var(--green); }
+.step-number { font-size: 11px; font-weight: 700; letter-spacing: .1em; color: var(--green); margin-bottom: 8px; }
+.step-number span { color: var(--line); margin-left: 5px; }
+h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.35; }
+.steps li > p:last-child { margin-top: 12px; font-size: 14px; line-height: 1.75; color: var(--muted); }
+.download-section { padding-block: 76px 60px; }
+.release-note { display: flex; justify-content: center; align-items: baseline; flex-wrap: wrap; gap: 8px 13px; margin: 27px auto; color: var(--muted); font-size: 13px; text-align: center; }
+.release-label { display: inline-block; padding: 3px 10px; background: var(--soft-orange); border-radius: 8px; color: var(--ink); font-weight: 650; white-space: nowrap; }
+.download-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 18px; }
+.download-card { display: flex; flex-direction: column; align-items: flex-start; padding: 28px; background: var(--paper); border: 1px solid var(--line); border-radius: 24px; box-shadow: 0 4px 0 color-mix(in srgb, var(--line) 40%, transparent); }
+.platform-mark { display: grid; place-items: center; width: 52px; height: 52px; margin-bottom: 18px; border-radius: 16px; background: var(--wall); }
+.platform-mark svg { width: 30px; height: 30px; }
+.download-card h3 { font-size: 25px; }
+.download-card > p { margin: 10px 0 23px; color: var(--muted); font-size: 13px; line-height: 1.8; }
+.download-button { width: 100%; gap: 10px; padding: 12px 15px; border-width: 1.5px; min-height: 48px; font-size: 13px; }
+.download-button svg { flex: none; width: 20px; height: 20px; }
+.download-card .download-button { margin-top: auto; }
+.download-card > a:not(.button) { display: inline-flex; align-items: center; min-height: 44px; margin-top: 8px; font-size: 12px; }
+.start-section { padding-block: 45px 67px; }
+.guide-links { display: flex; flex-wrap: wrap; justify-content: center; gap: 9px; margin: 28px 0; }
+.guide-links a { display: inline-flex; align-items: center; min-height: 44px; padding: 8px 18px; background: var(--paper); border: 1px solid var(--line); border-radius: 999px; text-decoration: none; font-size: 13px; font-weight: 650; }
+.guide-links a:is(:hover, :focus-visible) { border-color: var(--green); color: var(--green); }
+.guide { margin-top: 15px; border: 1px solid var(--line); border-radius: 24px; background: var(--paper); }
+.guide > summary { padding: 24px 28px; border-radius: 24px; }
+.guide-number { display: grid; place-items: center; flex: none; width: 39px; height: 39px; border: 1px solid var(--line); border-radius: 13px; font-size: 12px; font-weight: 750; color: var(--green); }
+.guide-heading { flex: 1; font-size: 21px; }
+.guide-heading small { display: block; margin-top: 4px; color: var(--muted); font-size: 12px; font-weight: 400; }
+.guide-body { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr); gap: 38px; padding: 5px 30px 30px; }
+.guide-steps { margin: 0; padding-left: 25px; }
+.guide-steps > li { padding-left: 8px; margin-bottom: 23px; font-size: 14px; line-height: 1.8; }
+.guide-steps > li:last-child { margin-bottom: 0; }
+.guide-steps > li::marker { color: var(--green); font-size: 12px; font-weight: 750; }
+.guide-steps strong { font-weight: 700; }
+.guide-body p { max-width: none; margin: 6px 0 0; padding: 0; color: var(--muted); font-size: 13px; line-height: 1.85; }
+.guide-note { align-self: start; min-width: 0; padding: 23px; border: 1px solid var(--line); border-radius: 18px; background: var(--wall); }
+.guide-note h3 { font-size: 16px; }
+.guide-note p + p { margin-top: 15px; }
+.guide-note a:not(.button) { display: inline-block; padding-block: 12px 0; font-size: 13px; }
+.guide-note .download-button { margin-top: 22px; }
+.launch-files { margin: 12px 0 0; padding: 12px 16px; border-left: 2px solid var(--line); font-size: 13px; }
+.launch-files div { display: flex; flex-wrap: wrap; gap: 4px 12px; }
+.launch-files dt { min-width: 65px; font-weight: 650; }
+.launch-files dd { margin: 0; }
+.guide code { overflow-wrap: anywhere; font: .95em ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; }
+.watch-guide { display: flex; gap: 24px; margin-top: 28px; padding: 28px; border: 1px solid var(--line); border-radius: 24px; }
+.watch-guide > svg { flex: none; width: 42px; height: 42px; color: var(--green); }
+.watch-guide ol { padding-left: 20px; margin-block: 15px; font-size: 14px; line-height: 1.8; }
+.watch-guide p { max-width: 820px; color: var(--muted); font-size: 13px; line-height: 1.85; }
+.modes { margin: 15px 0 20px; font-size: 14px; }
+.modes div + div { margin-top: 10px; }
+.modes dt { font-weight: 700; }
+.modes dd { color: var(--muted); margin: 2px 0 0; font-size: 13px; }
+.faq-section { display: grid; grid-template-columns: 1fr 1.9fr; gap: 55px; border-top: 1px solid var(--line); padding-block: 61px 71px; }
+.faq-intro h2 { margin-top: 15px; }
+.faq-tv { width: 76px; height: 76px; margin-top: 30px; transform: rotate(-7deg); color: var(--green); }
+.questions details { border-bottom: 1px solid var(--line); }
+.questions details:first-child { border-top: 1px solid var(--line); }
+summary { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 21px 0; font-size: 15px; font-weight: 650; list-style: none; }
+summary::-webkit-details-marker { display: none; }
+summary::after { content: "+"; flex: none; width: 22px; font-size: 21px; font-weight: 400; text-align: center; color: var(--green); }
+details[open] > summary::after { content: "−"; }
+details p { max-width: 610px; padding: 0 24px 23px 0; color: var(--muted); font-size: 14px; line-height: 1.85; }
+.project-note { display: flex; align-items: flex-start; gap: 30px; padding: 32px 36px; background: var(--soft-orange); border: 1px solid color-mix(in srgb, var(--orange) 30%, var(--line)); border-radius: 18px; }
+.project-tv { width: 62px; height: 62px; flex: none; color: var(--green); }
+.project-content { flex: 1; min-width: 0; }
+.project-note h2 { margin: 0; font-size: clamp(23px, 2.2vw, 29px); letter-spacing: -.035em; }
+.project-note p { max-width: 790px; margin-block: 12px; color: var(--muted); font-size: 14px; }
+.project-note a { display: inline-flex; align-items: center; min-height: 44px; padding-block: 6px; font-size: 14px; font-weight: 650; }
+.project-note a:is(:hover, :focus-visible) { color: var(--green); }
+.project-note .eyebrow { margin: 0 0 8px; font-size: 11px; }
+.docs-links { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 22px; margin: 22px 0; padding: 18px 0 0; border-top: 1px solid color-mix(in srgb, var(--orange) 30%, var(--line)); list-style: none; }
+.docs-links p { margin: 0; font-size: 13px; }
+.project-note .docs-note { margin-bottom: 0; font-size: 12px; }
+.site-footer { display: flex; align-items: center; flex-wrap: wrap; column-gap: 20px; padding-block: 48px 29px; }
+.footer-identity { display: flex; align-items: center; gap: 8px; font-size: 21px; font-weight: 750; letter-spacing: -.035em; }
+.footer-identity svg { width: 28px; height: 28px; }
+.footer-identity p { color: var(--muted); margin-left: 12px; font-size: 11px; font-weight: 400; letter-spacing: 0; }
+.footer-links { display: flex; flex-wrap: wrap; gap: 24px; margin-left: auto; font-size: 12px; }
+.footer-links a { display: inline-flex; align-items: center; min-height: 44px; text-decoration: none; }
+.footer-note { flex-basis: 100%; text-align: right; margin-top: 9px; color: var(--muted); font-size: 11px; }
+html[lang="zh-CN"] h1 { font-size: clamp(45px, 5.4vw, 72px); line-height: 1.24; letter-spacing: -.03em; }
+html[lang="zh-CN"] :is(h2, h3) { letter-spacing: -.025em; }
+html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }
+@media (min-width: 1450px) { .hero { padding-block: 90px; } }
+@media (max-width: 1000px) {
+ .wrap { width: calc(100% - 56px); }
+ .site-header { gap: 23px; }
+ .site-header nav { gap: 20px; }
+ .preferences { padding-left: 18px; }
+ .hero { gap: 7px; padding-block: 59px 65px; }
+ h1 { font-size: 56px; }
+ .hero-description { font-size: 16px; }
+ .hero-note { max-width: 290px; }
+ .steps { gap: 30px; }
+ .steps li:not(:last-child)::after { right: -23px; }
+ h3 { font-size: 19px; }
+ .download-card { padding: 24px 20px; }
+ .guide-body { gap: 24px; }
+ .footer-identity p { display: none; }
+}
+@media (max-width: 740px) {
+ .film-preview iframe { height:calc(56.25cqw + 196px); }
+ .wrap { width: calc(100% - 40px); }
+ .site-header { min-height: 83px; gap: 0 14px; flex-wrap:wrap; padding-top:12px; }
+ .site-header nav { order:3; flex-basis:100%; justify-content:space-between; gap:0 12px; }
+ .site-header nav a { font-size:12px; }
+ .preferences { margin-left: auto; border-left: 0; padding-left: 0; gap: 10px; }
+ .preferences button { font-size: 12px; }
+ .theme-picker { gap: 0; }
+ .theme-picker select { max-width: 75px; font-size: 11px; }
+ .hero { grid-template-columns: 1fr; gap: 0; padding-block: 44px 35px; }
+ .hero-copy { text-align: center; }
+ .hero .eyebrow { justify-content: center; font-size: 10px; }
+ h1 { margin-block: 22px; font-size: clamp(47px, 10.2vw, 68px); }
+ html[lang="zh-CN"] h1 { font-size: clamp(43px, 9.5vw, 64px); }
+ .hero-description { font-size: 16px; }
+ .hero-actions { justify-content: center; gap: 10px 22px; }
+ .hero-note { max-width: none; font-size: 11px; margin-top: 15px; }
+ .hero-scene { width: min(550px, 100%); margin: 24px auto 0; }
+ .living-room { width: 100%; margin-left: 0; }
+ .scene-caption { font-size: 11px; margin-top: 8px; }
+ .how-section { padding-block: 45px; }
+ h2 { font-size: 30px; }
+ html[lang="zh-CN"] .how-section h2 { font-size: clamp(23px, 6.7vw, 30px); }
+ .section-heading .eyebrow { font-size: 10px; }
+ .steps { grid-template-columns: 1fr; gap: 30px; max-width: 500px; margin: 36px auto 0; }
+ .steps li { display: grid; grid-template-columns: 128px 1fr; grid-template-rows: auto auto 1fr; column-gap: 15px; }
+ .step-art { height: auto; grid-row: 1 / 4; margin: 0; display: flex; align-items: center; }
+ .step-art svg { height: auto; }
+ .step-number { margin-bottom: 5px; }
+ .steps h3 { font-size: 18px; }
+ .steps li > p:last-child { margin-top: 7px; font-size: 13px; }
+ .steps li:not(:last-child)::after { content: none; }
+ .download-section { padding-block: 48px; }
+ .start-section { padding-block: 12px 48px; }
+ .section-heading > p:last-child:not(.eyebrow) { font-size: 14px; }
+ .download-cards { grid-template-columns: 1fr; max-width: 500px; margin: auto; gap: 15px; }
+ .download-card { padding: 23px; }
+ .platform-mark { margin-bottom: 14px; }
+ .guide > summary { padding: 20px 18px; gap: 12px; }
+ .guide-heading { font-size: 18px; }
+ .guide-number { width: 32px; height: 32px; border-radius: 10px; }
+ .guide-body { grid-template-columns: 1fr; padding: 0 20px 22px; gap: 20px; }
+ .guide-note { padding: 18px; }
+ .guide-links { gap: 8px; }
+ .guide-links a { padding: 8px 13px; }
+ .watch-guide { padding: 22px; gap: 14px; }
+ .watch-guide > svg { width: 28px; height: 28px; }
+ .modes { display: grid; grid-template-columns: 1fr; gap: 10px; margin-bottom: 0; }
+ .modes div + div { margin-top: 0; }
+ .faq-section { grid-template-columns: 1fr; gap: 27px; padding-block: 42px; }
+ .faq-intro { position: relative; }
+ .faq-intro h2 br { display: none; }
+ .faq-tv { position: absolute; right: 7px; top: 4px; width: 48px; height: 48px; margin: 0; }
+ summary { font-size: 14px; padding-block: 20px; }
+ details p { padding-right: 9px; }
+ .project-note { padding: 24px; align-items: flex-start; gap: 18px; }
+ .project-tv { width: 35px; height: 35px; }
+ .project-note p { font-size: 14px; }
+ .docs-links { grid-template-columns: 1fr; gap: 12px; }
+ .project-note .docs-note { font-size: 12px; }
+ .site-footer { padding-top: 34px; gap: 15px; }
+ .footer-links { gap: 15px; }
+ .footer-note { margin-top: 0; }
+}
+@media (max-width: 380px) {
+ .wrap { width: calc(100% - 32px); }
+ h1, html[lang="zh-CN"] h1 { font-size: clamp(34px, 11.5vw, 43px); }
+ .hero-actions .button { gap: 18px; padding-inline: 18px; }
+ .theme-picker svg { display: none; }
+ .steps li { grid-template-columns: 99px 1fr; column-gap: 10px; }
+ .steps h3 { font-size: 16px; }
+ .project-note { padding: 21px; gap: 12px; }
+ .project-tv { width: 28px; height: 28px; }
+}
+/* Small, finite scenes; the whole step owns hover, the button also supports tap/keys. */
+@media (prefers-reduced-motion: no-preference) {
+ .step-art g { transform-box: fill-box; transform-origin: center; }
+ .steps li:is(:hover, :focus-within) .screen-cursor { animation: choose-screen var(--comic-beat) ease-in-out; }
+ .steps li:is(:hover, :focus-within) .chosen-window { animation: window-response var(--comic-beat) ease-in-out; }
+ .steps li:is(:hover, :focus-within) .invite-plane { animation: send-invite var(--comic-beat) ease-in-out; }
+ .steps li:is(:hover, :focus-within) .invite-note { animation: note-response var(--comic-beat) ease-in-out; }
+ .steps li:is(:hover, :focus-within) .sofa-friend { animation: take-a-seat var(--comic-beat) ease-out; }
+ .steps li:is(:hover, :focus-within) .sofa-friend + .sofa-friend { animation-delay: .12s; }
+ /* Keep finished timelines replayable; every scene ends at its original pose. */
+ .steps li:is(:hover, :focus-within) .step-art [class] { animation-fill-mode: both; }
+ .project-tv { transition: transform .35s cubic-bezier(.2, .9, .3, 1.4); }
+ .project-note:is(:hover, :focus-within) .project-tv { transform: rotate(8deg); }
+ details[open] p { animation: answer-appears .2s ease-out; }
+}
+@keyframes choose-screen {
+ 0%, 8%, 48%, 100% { transform: none; }
+ 22%, 34% { transform: translate(-62px, -19px); }
+ 28% { transform: translate(-62px, -19px) scale(.85); }
+}
+@keyframes window-response { 0%, 22%, 46%, 100% { transform: none; } 30% { transform: scale(1.07); } 38% { transform: scale(.99); } }
+@keyframes send-invite {
+ 0%, 6%, 48%, 100% { transform: none; opacity: 1; }
+ 12% { transform: translate(-4px, 3px) rotate(7deg); opacity: 1; }
+ 32% { transform: translate(42px, -36px) rotate(-12deg); opacity: 0; }
+ 33% { transform: translate(-8px, 8px); opacity: 0; }
+}
+@keyframes note-response { 0%, 10%, 42%, 100% { transform: none; } 20% { transform: translateY(1px) rotate(-4deg); } 32% { transform: rotate(1deg); } }
+@keyframes take-a-seat { 0% { transform: translateY(-8px); } 22% { transform: translateY(2px); } 32%, 100% { transform: none; } }
+@keyframes answer-appears { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
+@media (prefers-reduced-motion: reduce) {
+ html { scroll-behavior: auto; }
+ *, *::before, *::after { transition: none !important; }
+ .button:not(:disabled):is(:hover, :focus-visible, :active), .button:not(:disabled):is(:hover, :focus-visible) svg { transform: none; }
+}
diff --git a/src/client/App.tsx b/src/client/App.tsx
index 836b7b73..bee0ec0f 100644
--- a/src/client/App.tsx
+++ b/src/client/App.tsx
@@ -25,18 +25,33 @@ import { BrandLoader } from "./components/living/BrandMark";
import { Btn, Pill } from "./components/living/primitives";
import { Comic, type ComicKind } from "./components/living/Comic";
import { Glyph, type GlyphName } from "./ui/icons";
-import { useCopy } from "./ui/copy";
+import { setCopy, useCopy } from "./ui/copy";
+import { initTheme } from "./ui/theme";
import { installBrowserDebug } from "./lib/debug";
-import { OverlayPreviewPage } from "./pages/OverlayPreviewPage";
-import { TooltipPreviewPage } from "./pages/TooltipPreviewPage";
+
+const OverlayPreviewPage = import.meta.env.DEV
+ ? lazy(() => import("./pages/OverlayPreviewPage").then((module) => ({ default: module.OverlayPreviewPage })))
+ : null;
+const TooltipPreviewPage = import.meta.env.DEV
+ ? lazy(() => import("./pages/TooltipPreviewPage").then((module) => ({ default: module.TooltipPreviewPage })))
+ : null;
+
+const StatusPreviewPage = import.meta.env.DEV
+ ? lazy(() => import("./pages/StatusPreviewPage").then((module) => ({ default: module.StatusPreviewPage })))
+ : null;
+const PlaybackPreviewPage = import.meta.env.DEV
+ ? lazy(() => import("./pages/PlaybackPreviewPage").then((module) => ({ default: module.PlaybackPreviewPage })))
+ : null;
const appRoute = parseAppRoute(window.location.pathname);
-const overlayPreview = import.meta.env.DEV && window.location.pathname === "/__overlay-preview";
-const tooltipPreview = import.meta.env.DEV && window.location.pathname === "/__tooltip-preview";
const clientLaunchBootstrap =
appRoute.kind === "host" || appRoute.kind === "viewer"
? takeClientLaunchBootstrap()
: null;
+initTheme(clientLaunchBootstrap?.presentation?.theme);
+if (clientLaunchBootstrap?.presentation) {
+ setCopy(clientLaunchBootstrap.presentation);
+}
const clientAccessBootstrap = clientLaunchBootstrap?.accessToken ?? null;
const viewerRoute = appRoute.kind === "viewer" ? readViewerRoute() : null;
const hostPageModule =
@@ -129,10 +144,16 @@ class RouteBoundary extends Component<
}
function AppRoute() {
- if (overlayPreview) {
+ if (PlaybackPreviewPage && window.location.pathname === "/__playback-preview") {
+ return <PlaybackPreviewPage />;
+ }
+ if (StatusPreviewPage && window.location.pathname === "/__status-preview") {
+ return <StatusPreviewPage />;
+ }
+ if (OverlayPreviewPage && window.location.pathname === "/__overlay-preview") {
return <OverlayPreviewPage />;
}
- if (tooltipPreview) {
+ if (TooltipPreviewPage && window.location.pathname === "/__tooltip-preview") {
return <TooltipPreviewPage />;
}
if (appRoute.kind === "client") {
@@ -267,16 +288,16 @@ function SiteAccessGate({
const [password, setPassword] = useState("");
const [submitting, setSubmitting] = useState(false);
+ function loadAccess(password?: string) {
+ return Promise.all([
+ password ? authenticateSiteAccess(password) : getSiteAccess(),
+ surface === "host" ? getRuntimeCapabilities() : Promise.resolve(null),
+ ]);
+ }
+
useEffect(() => {
let active = true;
- void Promise.all([
- clientAccessBootstrap
- ? authenticateSiteAccess(clientAccessBootstrap)
- : getSiteAccess(),
- surface === "host"
- ? getRuntimeCapabilities()
- : Promise.resolve<RuntimeCapabilities>({ natPrediction: false }),
- ]).then(
+ void loadAccess(clientAccessBootstrap ?? undefined).then(
([status, nextCapabilities]) => {
if (!active) return;
setCapabilities(nextCapabilities);
@@ -336,12 +357,7 @@ function SiteAccessGate({
async function retry(): Promise<void> {
setAccess({ kind: "checking" });
try {
- const [status, nextCapabilities] = await Promise.all([
- getSiteAccess(),
- surface === "host"
- ? getRuntimeCapabilities()
- : Promise.resolve<RuntimeCapabilities>({ natPrediction: false }),
- ]);
+ const [status, nextCapabilities] = await loadAccess();
setCapabilities(nextCapabilities);
setAccess(stateFromStatus(status));
} catch (error) {
@@ -360,17 +376,15 @@ function SiteAccessGate({
setSubmitting(true);
try {
+ const [status, nextCapabilities] = await loadAccess(submittedPassword);
+ setCapabilities(nextCapabilities);
+ setAccess(stateFromStatus(status));
+ } catch (error) {
setAccess(
- stateFromStatus(await authenticateSiteAccess(submittedPassword)),
+ error instanceof ApiError && error.status === 401
+ ? { kind: "required", error: t("gate.wrong") }
+ : { kind: "unavailable", message: readableError(error, t) },
);
- } catch (error) {
- setAccess({
- kind: "required",
- error:
- error instanceof ApiError && error.status === 401
- ? t("gate.wrong")
- : readableError(error, t),
- });
} finally {
setSubmitting(false);
}
@@ -391,6 +405,7 @@ function SiteAccessGate({
return (
<HostPage
launchedByClient={clientLaunchBootstrap?.launchedByClient}
+ sfuAvailable={capabilities?.sfu === true}
natPredictionAvailable={capabilities?.natPrediction === true}
onAuthorizationRequired={() =>
setAccess({ kind: "required", error: t("gate.expired") })
diff --git a/src/client/components/connection-details.ts b/src/client/components/connection-details.ts
index ed6274c3..c06a9aa4 100644
--- a/src/client/components/connection-details.ts
+++ b/src/client/components/connection-details.ts
@@ -1,10 +1,3 @@
-import type { PeerSnapshot, QualityWarningKind } from "../types";
-
-export interface QualityLimitationSummary {
- message: string;
- kind: QualityWarningKind;
-}
-
export function formatPacketLossPercent(
value: number | null,
unknownLabel: string,
@@ -13,17 +6,3 @@ export function formatPacketLossPercent(
? unknownLabel
: `${value.toFixed(1)}%`;
}
-
-export function qualityLimitationSummary(
- snapshots: readonly PeerSnapshot[],
-): QualityLimitationSummary | null {
- for (const snapshot of snapshots) {
- if (snapshot.qualityWarning) {
- return {
- message: snapshot.qualityWarning,
- kind: snapshot.qualityWarningKind ?? "other",
- };
- }
- }
- return null;
-}
diff --git a/src/client/components/living/CaptureSourcePicker.tsx b/src/client/components/living/CaptureSourcePicker.tsx
index 55e9d107..db73cade 100644
--- a/src/client/components/living/CaptureSourcePicker.tsx
+++ b/src/client/components/living/CaptureSourcePicker.tsx
@@ -4,7 +4,8 @@ import type { NativeCaptureTarget } from "../../native/wire";
import { nativeCaptureTargetKey } from "../../native/capture-selection";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
-import { ComicTooltip } from "./ComicTooltip";
+import { Tooltip } from "./Tooltip";
+import { Pill } from "./primitives";
const SOURCE_TABS = ["browser", "window", "display"] as const;
type SourceTab = (typeof SOURCE_TABS)[number];
@@ -17,6 +18,7 @@ const SOURCE_ICONS = {
export type NativeSourceList =
| { kind: "loading" }
| { kind: "unavailable" }
+ | { kind: "incompatible" }
| {
kind: "ready";
sources: NativeCaptureTarget[];
@@ -76,11 +78,48 @@ export function CaptureSourcePicker({
? nativeSources.processAudio
: nativeSources.systemAudio);
const anyNativeAudio = sources.some(supportsAudio);
+ const refreshLabel = t(nativeSources.kind === "loading" ? "host.sourcePicker.loading" : "host.sourcePicker.refresh");
+ const audioAction = t(!anyNativeAudio ? "host.noAudio" : audioLocked
+ ? "host.sourcePicker.audioLocked"
+ : shareAudio ? "host.sourcePicker.audioOff" : "host.sourcePicker.audioOn");
const audioLabel = t(
activeTab === "window" && sources.some((target) => target.kind === "window")
? "host.sourcePicker.windowAudio"
: "host.sourcePicker.systemAudio",
);
+ const refreshButton = (
+ <button
+ type="button"
+ className="lr-source-picker-refresh"
+ aria-label={refreshLabel}
+ disabled={nativeSources.kind === "loading"}
+ onClick={onRefresh}
+ >
+ <Glyph name="refresh" size={18} className={nativeSources.kind === "loading" ? "lr-spin" : undefined} />
+ </button>
+ );
+ const closeButton = (
+ <button
+ type="button"
+ className="lr-source-picker-close"
+ aria-label={t("common.cancel")}
+ onClick={onCancel}
+ autoFocus
+ >
+ <Glyph name="x" size={18} />
+ </button>
+ );
+ const audioSwitch = (
+ <button
+ type="button"
+ className="lr-switch"
+ role="switch"
+ aria-checked={shareAudio && anyNativeAudio}
+ aria-label={audioLabel}
+ disabled={audioLocked || !anyNativeAudio}
+ onClick={() => setShareAudio((current) => !current)}
+ />
+ );
return (
<div
@@ -99,32 +138,16 @@ export function CaptureSourcePicker({
<strong>{t("host.sourcePicker.title")}</strong>
</span>
)}
- <button
- type="button"
- className="lr-source-picker-refresh"
- title={vis ? undefined : t("host.sourcePicker.refresh")}
- aria-label={t("host.sourcePicker.refresh")}
- disabled={nativeSources.kind === "loading"}
- onClick={onRefresh}
- >
- <Glyph
- name="refresh"
- size={18}
- className={
- nativeSources.kind === "loading" ? "lr-spin" : undefined
- }
- />
- </button>
- <button
- type="button"
- className="lr-source-picker-close"
- title={vis ? undefined : t("common.cancel")}
- aria-label={t("common.cancel")}
- onClick={onCancel}
- autoFocus
- >
- <Glyph name="x" size={18} />
- </button>
+ {vis ? refreshButton : (
+ <Tooltip text={refreshLabel} place="below" align="end">
+ {refreshButton}
+ </Tooltip>
+ )}
+ {vis ? closeButton : (
+ <Tooltip text={t("common.cancel")} place="below" align="end">
+ {closeButton}
+ </Tooltip>
+ )}
</header>
<div
@@ -181,12 +204,15 @@ export function CaptureSourcePicker({
)}
</button>
);
- return vis ? (
- <ComicTooltip key={value} kind={`hint-capture-${value}`} place="below">
+ return (
+ <Tooltip
+ key={value}
+ kind={`hint-capture-${value}`}
+ text={vis ? undefined : t(`host.sourcePicker.tab.${value}`)}
+ place="below"
+ >
{button}
- </ComicTooltip>
- ) : (
- <span key={value}>{button}</span>
+ </Tooltip>
);
})}
</div>
@@ -226,7 +252,6 @@ export function CaptureSourcePicker({
<CaptureSourceOption
key={nativeCaptureTargetKey(target)}
target={target}
- audio={shareAudio && supportsAudio(target)}
disabled={
audioLocked && shareAudio && !supportsAudio(target)
}
@@ -247,20 +272,20 @@ export function CaptureSourcePicker({
<Glyph name="speaker" size={19} />
</span>
{vis ? null : <span>{audioLabel}</span>}
- <button
- type="button"
- className="lr-switch"
- role="switch"
- aria-checked={shareAudio && anyNativeAudio}
- aria-label={audioLabel}
- title={vis ? undefined : t("host.sourcePicker.audioHint")}
- disabled={audioLocked || !anyNativeAudio}
- onClick={() => setShareAudio((current) => !current)}
- />
+ <Tooltip
+ kind={!anyNativeAudio ? "no-audio" : audioLocked
+ ? (shareAudio ? "hint-share-audio-fixed" : "hint-silent-share-fixed")
+ : shareAudio ? "hint-stop-audio" : "hint-share-audio"}
+ text={vis ? undefined : `${audioAction} · ${t("host.sourcePicker.audioHint")}`}
+ >
+ {audioSwitch}
+ </Tooltip>
</div>
) : null}
- {activeTab === "browser" ? null : nativeSources.kind === "loading" ? (
+ {nativeSources.kind === "incompatible" ? (
+ <Pill icon="alert" label={t("native.incompatible")} comic="warning" />
+ ) : activeTab === "browser" ? null : nativeSources.kind === "loading" ? (
<span
className="lr-source-picker-status"
role="status"
@@ -287,13 +312,11 @@ export function CaptureSourcePicker({
function CaptureSourceOption({
target,
- audio,
disabled,
onPreview,
onSelect,
}: {
target: NativeCaptureTarget;
- audio: boolean;
disabled: boolean;
onPreview: (
target: NativeCaptureTarget,
@@ -348,36 +371,29 @@ function CaptureSourceOption({
);
return (
- <button
- ref={buttonRef}
- type="button"
- className="lr-source-option"
- data-native-source={nativeCaptureTargetKey(target)}
- title={title}
- aria-label={action}
- disabled={disabled}
- onMouseEnter={requestPreview}
- onFocus={requestPreview}
- onClick={onSelect}
- >
- <span className="lr-source-option-copy">
- <strong>{title}</strong>
- {audio ? (
- <span>
- <Glyph name="speaker" size={16} />
- <span className="visually-hidden">
- {t("host.sourcePicker.nativeAudio")}
- </span>
- </span>
- ) : null}
- </span>
- <span className="lr-source-option-preview" aria-hidden="true">
- {preview ? (
- <img src={preview} alt="" />
- ) : (
- <Glyph name={target.kind === "window" ? "share" : "tv"} size={23} />
- )}
- </span>
- </button>
+ <Tooltip text={title} className="lr-source-option-hint">
+ <button
+ ref={buttonRef}
+ type="button"
+ className="lr-source-option"
+ data-native-source={nativeCaptureTargetKey(target)}
+ aria-label={action}
+ disabled={disabled}
+ onMouseEnter={requestPreview}
+ onFocus={requestPreview}
+ onClick={onSelect}
+ >
+ <span className="lr-source-option-copy">
+ <strong>{title}</strong>
+ </span>
+ <span className="lr-source-option-preview" aria-hidden="true">
+ {preview ? (
+ <img src={preview} alt="" />
+ ) : (
+ <Glyph name={target.kind === "window" ? "share" : "tv"} size={23} />
+ )}
+ </span>
+ </button>
+ </Tooltip>
);
}
diff --git a/src/client/components/living/Comic.tsx b/src/client/components/living/Comic.tsx
index 5939da54..2af5b92a 100644
--- a/src/client/components/living/Comic.tsx
+++ b/src/client/components/living/Comic.tsx
@@ -1,38 +1,24 @@
// Panel comics (四宫格漫画): pictorial state strips that carry meaning with no
// human language. Each
-// scene is a self-contained inline SVG: own <style>, vls- prefixed keyframes,
-// own prefers-reduced-motion block pinning informative final frames. Motion
-// constitution: state-change beats only, loops rest >=40%, max 2 movers per
-// panel, stamps play once and hold. SSR-safe: pure static markup, no hooks.
+// scene has its own vls- prefixed keyframes. Shared presentation owns tone,
+// duration and repetition; settled states and reduced motion share informative
+// poses. SSR-safe: pure static markup, no hooks.
import { memo, type CSSProperties, type ReactNode } from "react";
+import { HostMark } from "./HostMark";
+import { PersonShape } from "./Pawn";
+import { comicStyle, getComicPresentation, type ComicMotion, type ComicTone } from "./comic-presentation";
+import type { ComicKind, ComicTheme } from "../../ui/visual-kinds";
-export type ComicKind =
- | "waiting-for-host"
- | "connecting-p2p"
- | "connecting-sfu"
- | "tap-to-play"
- | "host-paused"
- | "recovering"
- | "route-failed"
- | "playback-failed"
- | "host-offline"
- | "no-audio"
- | "room-not-found"
- | "access-denied"
- | "invalid-invite"
- | "room-full"
- | "bandwidth-limited"
- | "encoder-limited"
- | "warning";
-
-/** stage = dark TV overlay (default for overlay states); paper = join rows. */
-export type ComicTheme = "stage" | "paper";
+export type { ComicKind, ComicTheme };
const DEFAULT_THEME: Record<ComicKind, ComicTheme> = {
"waiting-for-host": "stage",
"connecting-p2p": "stage",
"connecting-sfu": "stage",
+ "signal-connecting": "paper",
+ "signal-recovering": "paper",
+ "signal-offline": "paper",
"tap-to-play": "stage",
"host-paused": "stage",
recovering: "stage",
@@ -50,18 +36,15 @@ const DEFAULT_THEME: Record<ComicKind, ComicTheme> = {
};
/* ------------------------------------------------------------------ *
- * Cast + idiom helpers. Everything is absolute-coordinates: any element
- * whose class animates `transform` must not carry a transform attribute
- * (CSS motion would override it), so helpers bake positions into paths.
+ * Cast + idiom helpers. Keep animated transform classes on an outer
+ * wrapper so CSS motion cannot replace an inner positioning transform.
* ------------------------------------------------------------------ */
-/* Cast is exported for the hint-scene sets under ./hints (control tooltips);
- scene functions only dereference these at render time, so the hints ↔ Comic
- module cycle is safe (function declarations hoist; consts read post-init). */
+/* Control hints reuse these scene objects and stable identity colours. */
export const YOU = "#2fa66a";
-export const LIVE = "#2fa66a";
-export const WARN = "#d98e04";
-export const DANGER = "#d64541";
+export const LIVE = "var(--live)";
+export const WARN = "var(--warn)";
+export const DANGER = "var(--danger)";
export const INK_STAGE = "#dfe8f2";
export const MINT = "#9de8bf";
export const SKY = "#7ea4f5";
@@ -79,14 +62,15 @@ export function Frame({
x,
w,
theme,
- accent,
+ result = false,
}: {
x: number;
w: number;
theme: ComicTheme;
- accent?: string;
+ result?: boolean;
}) {
const paper = theme === "paper";
+ const border = paper ? "var(--ink)" : "#48597a";
return (
<rect
x={x}
@@ -95,7 +79,7 @@ export function Frame({
height={88}
rx={w > 100 ? 14 : 12}
fill={paper ? "var(--paper)" : "#0d1526"}
- stroke={accent ?? (paper ? "var(--ink)" : "#48597a")}
+ stroke={result ? `var(--comic-tone, ${border})` : border}
strokeWidth={2.5}
/>
);
@@ -113,37 +97,32 @@ export function Floor({ x1, x2, y = 76 }: { x1: number; x2: number; y?: number }
);
}
-/** Mini pawn, feet on (x, yb), s = half-width. Green you-pawn by default. */
+/** Mini participant, feet centered on (x, yb); s is the head diameter. */
export function Pawn({
x,
yb,
s,
color = YOU,
eyes = false,
+ host,
+ gaze,
+ eyeClassName,
className,
}: {
x: number;
yb: number;
s: number;
color?: string;
- eyes?: boolean;
+ eyes?: boolean | "closed";
+ host?: boolean;
+ gaze?: number;
+ eyeClassName?: string;
className?: string;
}) {
- const body = `M${r2(x - s)} ${yb} c0-${r2(s * 1.1)} ${r2(s * 0.45)}-${r2(s * 1.55)} ${s}-${r2(s * 1.55)} s${s} ${r2(s * 0.45)} ${s} ${r2(s * 1.55)} Z`;
- const headR = r2(s * 0.6);
- const hy = r2(yb - s * 1.55 - headR * 0.75);
- const inner = (
- <>
- <path d={body} fill={color} />
- <circle cx={x} cy={hy} r={headR} fill={color} />
- {eyes ? (
- <>
- <circle cx={x - 2.2} cy={hy} r={r2(s * 0.11)} fill="#101a2c" />
- <circle cx={x + 2.2} cy={hy} r={r2(s * 0.11)} fill="#101a2c" />
- </>
- ) : null}
- </>
- );
+ const scale = s / 16;
+ const inner = <g transform={`translate(${r2(x - 24 * scale)} ${r2(yb - 50 * scale)}) scale(${scale})`} fill={color}>
+ <PersonShape eyes={eyes} gaze={gaze} eyeClassName={eyeClassName} host={host} />
+ </g>;
return className ? <g className={className}>{inner}</g> : inner;
}
@@ -220,49 +199,6 @@ export function Moon({
);
}
-/** Host crown outline; dashed = the host is gone, not asleep. */
-const CROWN_PTS: ReadonlyArray<readonly [number, number]> = [
- [-6, 0],
- [-8.5, -10.5],
- [-3, -6],
- [0, -12.5],
- [3, -6],
- [8.5, -10.5],
- [6, 0],
-];
-export function Crown({
- x,
- y,
- k = 1,
- dashed = false,
- className,
- baseOpacity,
-}: {
- x: number;
- y: number;
- k?: number;
- dashed?: boolean;
- className?: string;
- baseOpacity?: number;
-}) {
- const d = `M${CROWN_PTS.map(([px, py]) => `${r2(x + px * k)} ${r2(y + py * k)}`).join(" L")} Z`;
- return dashed ? (
- <path
- className={className}
- opacity={baseOpacity}
- d={d}
- fill="none"
- stroke={STAR_GOLD}
- strokeWidth={2}
- strokeDasharray="4 3"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- ) : (
- <path className={className} opacity={baseOpacity} d={d} fill={STAR_GOLD} />
- );
-}
-
/** SFU relay server box; two slot lines light --live as the dot passes. */
export function ServerBox({
x,
@@ -381,7 +317,7 @@ export function RedX({
<path
className={className}
d={`M${cx - arm} ${cy - arm} L${cx + arm} ${cy + arm} M${cx + arm} ${cy - arm} L${cx - arm} ${cy + arm}`}
- stroke={DANGER}
+ stroke={`var(--comic-tone, ${DANGER})`}
strokeWidth={3}
strokeLinecap="round"
fill="none"
@@ -444,26 +380,28 @@ export function Static({
);
}
-/** SVG-local reduced-motion block: kill keyframes, pin informative poses. */
+/** Settled and reduced-motion scenes share the same informative poses. */
export function rmBlock(kills: string[], pins: Array<readonly [string, string]>): string {
- const kill = kills.map((c) => `.${c}{animation:none}`).join("");
- const pin = pins.map(([s, c]) => `${s}{${c}}`).join("");
- return `@media (prefers-reduced-motion:reduce){${kill}${pin}}`;
+ const rules = [...kills.map((c) => [`.${c}`, "animation:none"] as const), ...pins];
+ const block = (scope: string) => rules.map(([selectors, styles]) =>
+ `${selectors.split(",").map((selector) => scope + selector.trim()).join(",")}{${styles}}`,
+ ).join("");
+ return `${block('svg[data-comic-motion="still"] ')}@media (prefers-reduced-motion:reduce){${block("")}}`;
}
/* ------------------------------ scenes ------------------------------ */
-/** 1. waiting-for-host: 1 wide panel, loop 3.2s. */
+/** 1. waiting-for-host: 1 wide panel. */
function SceneWaiting({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-wf-moon{transform-box:fill-box;transform-origin:center;animation:vlsWfMoon 3.2s ease-in-out infinite}
-.vls-wf-z1{animation:vlsWfZ 3.2s ease-in-out infinite}
-.vls-wf-z2{animation:vlsWfZ 3.2s ease-in-out .45s infinite}
-.vls-wf-z3{animation:vlsWfZ 3.2s ease-in-out .9s infinite}
-.vls-wf-eyes{transform-box:fill-box;transform-origin:center;animation:vlsWfBlink 3.2s ease-in-out infinite}
-.vls-wf-led{animation:vlsWfLed 1.1s ease-in-out infinite}
+.vls-wf-moon{transform-box:fill-box;transform-origin:center;animation:vlsWfMoon var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-wf-z1{animation:vlsWfZ var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-wf-z2{animation:vlsWfZ var(--comic-duration,3.2s) ease-in-out .45s var(--comic-repeat,1) both}
+.vls-wf-z3{animation:vlsWfZ var(--comic-duration,3.2s) ease-in-out .9s var(--comic-repeat,1) both}
+.vls-wf-eyes{transform-box:fill-box;transform-origin:center;animation:vlsWfBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-wf-led{animation:vlsWfLed var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsWfMoon{0%,100%{transform:translateY(0)}50%{transform:translateY(-2px)}}
@keyframes vlsWfZ{0%{opacity:0;transform:translateY(3px)}8%{opacity:.9}20%,100%{opacity:0;transform:translateY(-3px)}}
@keyframes vlsWfBlink{0%,66%,74%,100%{transform:scaleY(1)}70%{transform:scaleY(.12)}}
@@ -473,13 +411,9 @@ ${rmBlock(
[[".vls-wf-z1,.vls-wf-z2,.vls-wf-z3", "opacity:.55"], [".vls-wf-led", "opacity:1"]],
)}
`}</style>
- <Frame x={4} w={312} theme={theme} />
+ <Frame x={4} w={312} theme={theme} result />
<Floor x1={24} x2={296} />
- <Pawn x={69} yb={76} s={11} />
- <g className="vls-wf-eyes">
- <circle cx={71} cy={53} r={1.1} fill="#101a2c" />
- <circle cx={74.6} cy={53} r={1.1} fill="#101a2c" />
- </g>
+ <Pawn x={69} yb={76} s={11} eyes gaze={2} eyeClassName="vls-wf-eyes" />
<MiniTv x={206} y={28} w={64} h={42} />
<g className="vls-wf-moon">
<Moon x={229} y={48} />
@@ -494,7 +428,7 @@ ${rmBlock(
);
}
-/** 2/3. connecting P2P / SFU: 3 panels, loop 2.8s. */
+/** 2/3. connecting P2P / SFU: 3 panels. */
function SceneConnecting({ theme, sfu }: { theme: ComicTheme; sfu: boolean }) {
const k = sfu ? "vls-cs" : "vls-cn";
const dotKf = sfu
@@ -513,11 +447,11 @@ function SceneConnecting({ theme, sfu }: { theme: ComicTheme; sfu: boolean }) {
return (
<>
<style>{`
-.${k}-line{animation:${k}March 1.1s linear infinite}
-.${k}-dot{animation:${k}Dot 2.8s ease-in-out infinite}
-${sfu ? `.${k}-slots{animation:${k}Slots 2.8s ease-in-out infinite}` : ""}
-.${k}-warm{animation:${k}Warm 2.8s ease-in-out infinite}
-.${k}-led{animation:${k}Led .8s ease-in-out infinite}
+.${k}-line{animation:${k}March var(--comic-duration,3.2s) linear var(--comic-repeat,1) both}
+.${k}-dot{animation:${k}Dot var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+${sfu ? `.${k}-slots{animation:${k}Slots var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}` : ""}
+.${k}-warm{animation:${k}Warm var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.${k}-led{animation:${k}Led var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes ${k}March{to{stroke-dashoffset:-16}}
${dotKf}
@keyframes ${k}Warm{0%,52%{opacity:0}60%{opacity:.25}66%{opacity:.1}74%{opacity:.3}100%{opacity:.18}}
@@ -526,7 +460,7 @@ ${rmBlock(kills, pins)}
`}</style>
<Frame x={8} w={96} theme={theme} />
<Frame x={112} w={96} theme={theme} />
- <Frame x={216} w={96} theme={theme} />
+ <Frame x={216} w={96} theme={theme} result />
<Floor x1={20} x2={92} />
<Pawn x={56} yb={76} s={11} eyes />
<Pawn x={128} yb={74} s={7} eyes color={SKY} />
@@ -570,18 +504,71 @@ ${rmBlock(kills, pins)}
);
}
-/** 4. tap-to-play: 2 panels, loop 2.4s. Companion to the real big button. */
+/** The page's control link, not a media path: no TV or video packets here. */
+function SceneSignal({ theme, state }: {
+ theme: ComicTheme;
+ state: "connecting" | "recovering" | "offline";
+}) {
+ const color = state === "connecting" ? SKY : state === "recovering" ? WARN : FAINT;
+ return (
+ <>
+ <style>{`
+.vls-signal-message{animation:vlsSignalMessage var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-signal-retry{transform-box:fill-box;transform-origin:center;animation:vlsSignalRetry var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+@keyframes vlsSignalMessage{0%{transform:translateX(0);opacity:0}8%{opacity:1}40%{transform:translateX(82px);opacity:1}55%,100%{transform:translateX(82px);opacity:0}}
+@keyframes vlsSignalRetry{0%{transform:rotate(0)}55%,100%{transform:rotate(360deg)}}
+${rmBlock(["vls-signal-message", "vls-signal-retry"], [
+ [".vls-signal-message", "opacity:1;transform:translateX(41px)"],
+ [".vls-signal-retry", "transform:none"],
+])}
+`}</style>
+ <Frame x={4} w={312} theme={theme} result />
+ <BrowserWindow x={24} y={23} w={96} h={50}>
+ <circle cx={37} cy={43} r={3} fill={color} />
+ <path d="M47 43h56 M34 55h36 M77 55h26 M34 64h69" stroke={LINE} strokeWidth={2} strokeLinecap="round" />
+ </BrowserWindow>
+ <ServerBox x={254} y={25} w={42} h={46} />
+ <path
+ d={state === "connecting" ? "M130 48H244" : "M130 48H164 M204 48H244"}
+ stroke={color}
+ strokeWidth={2.5}
+ strokeDasharray="4 5"
+ strokeLinecap="round"
+ fill="none"
+ />
+ {state === "connecting" ? (
+ <>
+ <path d="M140 42l-6 6 6 6 M234 42l6 6-6 6" stroke={color} strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" fill="none" />
+ <g className="vls-signal-message">
+ <rect x={136} y={40} width={16} height={13} rx={2} fill="var(--paper)" stroke={color} strokeWidth={2} />
+ <path d="M137 42l7 5 7-5" stroke={color} strokeWidth={1.5} strokeLinejoin="round" fill="none" />
+ </g>
+ </>
+ ) : state === "recovering" ? (
+ <g className="vls-signal-retry" stroke={color} strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" fill="none">
+ <path d="M175 43a11 11 0 0 1 19-2l2 3 M190 44h6v-6 M193 53a11 11 0 0 1-19 2l-2-3 M178 52h-6v6" />
+ </g>
+ ) : (
+ <g stroke={color} strokeWidth={2.5} strokeLinecap="round" fill="none">
+ <path d="M174 43h5 M174 53h5 M189 43h5 M189 53h5 M176 59l16-22" />
+ </g>
+ )}
+ </>
+ );
+}
+
+/** 4. tap-to-play: 2 panels. Companion to the real big button. */
function SceneTap({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-tp-finger{animation:vlsTpFinger 2.4s ease-in-out infinite}
-.vls-tp-btn{transform-box:fill-box;transform-origin:center;animation:vlsTpBtn 2.4s ease-in-out infinite}
-.vls-tp-ripple{transform-box:fill-box;transform-origin:center;animation:vlsTpRipple 2.4s ease-out infinite}
-.vls-tp-flash{animation:vlsTpFlash 2.4s ease-in-out infinite}
-.vls-tp-play{transform-box:fill-box;transform-origin:center;animation:vlsTpPlay 2.4s ease-in-out infinite}
-.vls-tp-led{animation:vlsTpLed 2.4s ease-in-out infinite}
-.vls-tp-arcs{animation:vlsTpArcs 2.4s ease-in-out infinite}
+.vls-tp-finger{animation:vlsTpFinger var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-tp-btn{transform-box:fill-box;transform-origin:center;animation:vlsTpBtn var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-tp-ripple{transform-box:fill-box;transform-origin:center;animation:vlsTpRipple var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-tp-flash{animation:vlsTpFlash var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-tp-play{transform-box:fill-box;transform-origin:center;animation:vlsTpPlay var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-tp-led{animation:vlsTpLed var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-tp-arcs{animation:vlsTpArcs var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsTpFinger{0%,18%{transform:translate(0,0)}42%,52%{transform:translate(30px,-18px)}78%,100%{transform:translate(0,0)}}
@keyframes vlsTpBtn{0%,40%{transform:scale(1)}46%{transform:scale(.86)}54%{transform:scale(1.05)}60%,100%{transform:scale(1)}}
@keyframes vlsTpRipple{0%,42%{transform:scale(1);opacity:0}45%{opacity:.75}72%,100%{transform:scale(1.65);opacity:0}}
@@ -599,7 +586,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<circle className="vls-tp-ripple" cx={80} cy={48} r={24} fill="none" stroke={SKY} strokeWidth={3} />
<g className="vls-tp-btn">
<circle cx={80} cy={48} r={24} fill="#2f6fed" />
@@ -621,16 +608,16 @@ ${rmBlock(
);
}
-/** 5. host-paused: 2 panels, loop 3s. Cozy, not broken — no z's, no red. */
+/** 5. host-paused: 2 panels. Cozy, not broken — no z's, no red. */
function ScenePaused({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-hp-bars{animation:vlsHpBars 3s ease-in-out infinite}
-.vls-hp-led{animation:vlsHpLed 1.1s ease-in-out infinite}
-.vls-hp-eyes{transform-box:fill-box;transform-origin:center;animation:vlsHpBlink 3s ease-in-out infinite}
-.vls-hp-steam1{animation:vlsHpSteam 3s ease-in-out infinite}
-.vls-hp-steam2{animation:vlsHpSteam 3s ease-in-out 1.5s infinite}
+.vls-hp-bars{animation:vlsHpBars var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hp-led{animation:vlsHpLed var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hp-eyes{transform-box:fill-box;transform-origin:center;animation:vlsHpBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hp-steam1{animation:vlsHpSteam var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hp-steam2{animation:vlsHpSteam var(--comic-duration,3.2s) ease-in-out 1.5s var(--comic-repeat,1) both}
@keyframes vlsHpBars{0%,100%{opacity:.55}50%{opacity:1}}
@keyframes vlsHpLed{0%,100%{opacity:1}50%{opacity:.3}}
@keyframes vlsHpBlink{0%,44%,52%,100%{transform:scaleY(1)}48%{transform:scaleY(.12)}}
@@ -645,7 +632,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<MiniTv x={36} y={16} w={88} h={54} />
<rect x={42} y={22} width={76} height={38} rx={4} fill="#0a101c" opacity={0.5} />
<g className="vls-hp-bars" fill={INK_STAGE}>
@@ -654,12 +641,7 @@ ${rmBlock(
</g>
<circle className="vls-hp-led" cx={80} cy={76} r={3.5} fill={WARN} />
<Floor x1={176} x2={304} y={78} />
- <path d="M198 78 c0-16 8-22 18-22 s18 6 18 22 Z" fill={YOU} />
- <circle cx={216} cy={50} r={9} fill={YOU} />
- <g className="vls-hp-eyes" fill="#101a2c">
- <circle cx={212.5} cy={49} r={1.5} />
- <circle cx={219.5} cy={49} r={1.5} />
- </g>
+ <Pawn x={216} yb={78} s={14} eyes eyeClassName="vls-hp-eyes" />
<rect x={240} y={66} width={12} height={12} rx={3} fill="#e4572e" />
<path d="M252 69 a5 5 0 0 1 0 6" stroke="#e4572e" strokeWidth={2.5} fill="none" />
<path className="vls-hp-steam1" d="M243 60 q3 -4 0 -8" stroke={LINE} strokeWidth={2} strokeLinecap="round" fill="none" opacity={0} />
@@ -668,18 +650,18 @@ ${rmBlock(
);
}
-/** 6. recovering: 3 panels, loop 3.2s. Plug re-seats, LEDs chase, one sweat drop. */
+/** 6. recovering: 3 panels. Plug re-seats, LEDs chase, one sweat drop. */
function SceneRecovering({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-rc-spark{animation:vlsRcSpark 3.2s ease-in-out infinite}
-.vls-rc-plug{transform-box:fill-box;transform-origin:center;animation:vlsRcPlug 3.2s ease-in-out infinite}
-.vls-rc-plug-lines{animation:vlsRcPlugLines 3.2s ease-in-out infinite}
-.vls-rc-sweat{transform-box:fill-box;transform-origin:center;animation:vlsRcSweat 3.2s ease-in-out infinite}
-.vls-rc-c1{animation:vlsRcC1 3.2s ease-in-out infinite}
-.vls-rc-c2{animation:vlsRcC2 3.2s ease-in-out infinite}
-.vls-rc-c3{animation:vlsRcC3 3.2s ease-in-out infinite}
+.vls-rc-spark{animation:vlsRcSpark var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rc-plug{transform-box:fill-box;transform-origin:center;animation:vlsRcPlug var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rc-plug-lines{animation:vlsRcPlugLines var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rc-sweat{transform-box:fill-box;transform-origin:center;animation:vlsRcSweat var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rc-c1{animation:vlsRcC1 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rc-c2{animation:vlsRcC2 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rc-c3{animation:vlsRcC3 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsRcSpark{0%{opacity:0}10%{opacity:1}30%,100%{opacity:.55}}
@keyframes vlsRcPlug{0%{transform:translate(-4px,-9px) rotate(-6deg)}12%{transform:translate(-2px,-4px) rotate(5deg)}22%{transform:translate(0,-1px) rotate(-2deg)}30%,100%{transform:translate(0,0) rotate(0)}}
@keyframes vlsRcPlugLines{0%{opacity:0}6%{opacity:.9}28%,100%{opacity:0}}
@@ -700,7 +682,7 @@ ${rmBlock(
`}</style>
<Frame x={8} w={96} theme={theme} />
<Frame x={112} w={96} theme={theme} />
- <Frame x={216} w={96} theme={theme} />
+ <Frame x={216} w={96} theme={theme} result />
<Floor x1={20} x2={92} />
<Pawn x={40} yb={76} s={8} eyes />
<MiniTv x={66} y={44} w={26} h={18} />
@@ -719,9 +701,9 @@ ${rmBlock(
fill={SKY}
opacity={0}
/>
- <circle className="vls-rc-c1" cx={272} cy={34} r={3} fill={LIVE} opacity={0.25} />
- <circle className="vls-rc-c2" cx={284} cy={34} r={3} fill={LIVE} opacity={0.25} />
- <circle className="vls-rc-c3" cx={296} cy={34} r={3} fill={LIVE} opacity={0.25} />
+ <circle className="vls-rc-c1" cx={272} cy={34} r={3} fill={`var(--comic-tone, ${WARN})`} opacity={0.25} />
+ <circle className="vls-rc-c2" cx={284} cy={34} r={3} fill={`var(--comic-tone, ${WARN})`} opacity={0.25} />
+ <circle className="vls-rc-c3" cx={296} cy={34} r={3} fill={`var(--comic-tone, ${WARN})`} opacity={0.25} />
</>
);
}
@@ -731,11 +713,11 @@ function SceneRouteFailed({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-rf-panel{transform-box:fill-box;transform-origin:center;animation:vlsRfIn .5s cubic-bezier(.3,1.5,.5,1) backwards}
+.vls-rf-panel{transform-box:fill-box;transform-origin:center;animation:vlsRfIn var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
.vls-rf-p2{animation-delay:.2s}
-.vls-rf-march{animation:vlsRfMarch .4s linear .4s 3 both}
-.vls-rf-x{transform-box:fill-box;transform-origin:center;animation:vlsRfX .4s ease-out .8s backwards}
-.vls-rf-sweat{animation:vlsRfSweat 3s ease-in-out 1.2s infinite}
+.vls-rf-march{animation:vlsRfMarch var(--comic-duration,3.2s) linear .4s var(--comic-repeat,1) both}
+.vls-rf-x{transform-box:fill-box;transform-origin:center;animation:vlsRfX var(--comic-duration,3.2s) ease-out .8s var(--comic-repeat,1) both}
+.vls-rf-sweat{animation:vlsRfSweat var(--comic-duration,3.2s) ease-in-out 1.2s var(--comic-repeat,1) both}
@keyframes vlsRfIn{from{opacity:0;transform:translateY(6px) scale(.9)}}
@keyframes vlsRfMarch{from{stroke-dashoffset:0}to{stroke-dashoffset:-16}}
@keyframes vlsRfX{from{opacity:0;transform:scale(1.5)}to{opacity:1;transform:scale(1)}}
@@ -757,7 +739,7 @@ ${rmBlock(
<path d="M66 49 l-3 6 7 0 -3 6" stroke={DANGER} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" fill="none" />
</g>
<g className="vls-rf-panel vls-rf-p2">
- <Frame x={164} w={152} theme={theme} accent={DANGER} />
+ <Frame x={164} w={152} theme={theme} result />
<Floor x1={176} x2={304} />
<Pawn x={192} yb={76} s={10} eyes />
<MiniTv x={254} y={36} w={44} h={30} />
@@ -770,16 +752,16 @@ ${rmBlock(
);
}
-/** 8. playback-failed: 2 panels, loop 3s. Link fine, picture dead. */
+/** 8. playback-failed: 2 panels. The current picture is unavailable. */
function ScenePlaybackFailed({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-pf-s1{animation:vlsPfStaticA .36s steps(3) infinite}
-.vls-pf-s2{animation:vlsPfStaticB .36s steps(3) infinite}
-.vls-pf-rip{animation:vlsPfRip 3s ease-in-out infinite}
-.vls-pf-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsPfTap 3s ease-in-out infinite}
-.vls-pf-ring{animation:vlsPfRing 3s ease-in-out infinite}
+.vls-pf-s1{animation:vlsPfStaticA var(--comic-duration,3.2s) steps(3) var(--comic-repeat,1) both}
+.vls-pf-s2{animation:vlsPfStaticB var(--comic-duration,3.2s) steps(3) var(--comic-repeat,1) both}
+.vls-pf-rip{animation:vlsPfRip var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pf-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsPfTap var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pf-ring{animation:vlsPfRing var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsPfStaticA{0%{transform:translate(0,0);opacity:.5}33%{transform:translate(1px,-1px);opacity:.8}66%{transform:translate(-1px,1px);opacity:.35}100%{transform:translate(0,0);opacity:.5}}
@keyframes vlsPfStaticB{0%{transform:translate(0,0);opacity:.35}33%{transform:translate(-1px,1px);opacity:.7}66%{transform:translate(1px,-1px);opacity:.45}100%{transform:translate(0,0);opacity:.35}}
@keyframes vlsPfRip{0%,18%{opacity:.35}22%{opacity:.7}28%{opacity:.35}33%{opacity:.7}42%,100%{opacity:.35}}
@@ -794,10 +776,10 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<Floor x1={16} x2={60} />
<Pawn x={34} yb={76} s={8} eyes />
- <path d="M44 62 H68" stroke={LIVE} strokeWidth={2.5} strokeLinecap="round" fill="none" />
+ <path d="M44 62 H68" stroke={LINE} strokeWidth={2.5} strokeLinecap="round" fill="none" />
<MiniTv x={70} y={30} w={64} h={40} />
<Static
cls="vls-pf-s1"
@@ -822,36 +804,36 @@ ${rmBlock(
);
}
-/** 9. host-offline: 2 panels, loop 3.4s. Plug pulled; dashed crown = gone. */
+/** 9. host-offline: 2 panels. Plug pulled; dashed Host crown = gone. */
function SceneHostOffline({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-ho-plug{transform-box:fill-box;transform-origin:50% 0%;animation:vlsHoSway 3.4s ease-in-out infinite}
-.vls-ho-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsHoWave 3.4s ease-in-out infinite}
-.vls-ho-crown{animation:vlsHoCrown 3.4s ease-in-out infinite}
+.vls-ho-plug{transform-box:fill-box;transform-origin:50% 0%;animation:vlsHoSway var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-ho-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsHoWave var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-ho-badge{animation:vlsHoBadge var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsHoSway{0%{transform:rotate(-6deg)}10%{transform:rotate(6deg)}20%{transform:rotate(-5deg)}30%{transform:rotate(4deg)}40%,100%{transform:rotate(0)}}
@keyframes vlsHoWave{0%,10%{transform:rotate(0)}14%{transform:rotate(-8deg)}18%{transform:rotate(8deg)}22%{transform:rotate(-8deg)}26%{transform:rotate(8deg)}30%,100%{transform:rotate(0)}}
-@keyframes vlsHoCrown{0%,30%{opacity:.2}40%{opacity:.7}50%,100%{opacity:.2}}
+@keyframes vlsHoBadge{0%,30%{opacity:.2}40%{opacity:.7}50%,100%{opacity:.2}}
${rmBlock(
- ["vls-ho-plug", "vls-ho-pawn", "vls-ho-crown"],
- [[".vls-ho-plug", "transform:none"], [".vls-ho-crown", "opacity:.5"]],
+ ["vls-ho-plug", "vls-ho-pawn", "vls-ho-badge"],
+ [[".vls-ho-plug", "transform:none"], [".vls-ho-badge", "opacity:.5"]],
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<MiniTv x={30} y={22} w={70} h={44} />
<rect x={36} y={28} width={58} height={30} rx={4} fill="#0a101c" />
<path d="M65 66 c0 6 -4 8 -8 10" stroke={TV_EDGE} strokeWidth={2.5} fill="none" strokeLinecap="round" />
<Plug x={57} y={76} className="vls-ho-plug" />
<Floor x1={176} x2={304} y={78} />
<Pawn x={210} yb={78} s={9} eyes className="vls-ho-pawn" />
- <Crown x={272} y={42} k={1.1} dashed className="vls-ho-crown" baseOpacity={0.5} />
+ <HostMark x={257} y={43} width={30} dashed className="vls-ho-badge" opacity={0.5} />
</>
);
}
-/** 10. no-audio: 2 panels, loop 3s. Before: TV alive (mint play triangle,
+/** 10. no-audio: 2 panels. Before: TV alive (mint play triangle,
* flicker ticks), three healthy LIVE-green sound arcs. After: picture still
* alive, sound dashed + red-slashed, and a big you-pawn (s=18) presses BOTH
* mitten-hands to its head — arms stamp up once and hold, head micro-shakes
@@ -860,16 +842,16 @@ function SceneNoAudio({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-na-flick{animation:vlsNaFlick 3s ease-in-out infinite}
-.vls-na-a1{animation:vlsNaArc 3s ease-in-out infinite}
-.vls-na-a2{animation:vlsNaArc 3s ease-in-out -.3s infinite}
-.vls-na-a3{animation:vlsNaArc 3s ease-in-out -.6s infinite}
-.vls-na-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsNaShake 3s ease-in-out infinite}
-.vls-na-arm{transform-box:fill-box;transform-origin:50% 100%;animation:vlsNaArm 3s cubic-bezier(.3,1.4,.5,1) infinite}
-.vls-na-slash{transform-box:fill-box;transform-origin:center;animation:vlsNaSlash 3s ease-out infinite}
+.vls-na-flick{animation:vlsNaFlick var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-na-a1{animation:vlsNaArc var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-na-a2{animation:vlsNaArc var(--comic-duration,3.2s) ease-in-out -.3s var(--comic-repeat,1) both}
+.vls-na-a3{animation:vlsNaArc var(--comic-duration,3.2s) ease-in-out -.6s var(--comic-repeat,1) both}
+.vls-na-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsNaShake var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-na-arm{transform-box:fill-box;transform-origin:50% 100%;animation:vlsNaArm var(--comic-duration,3.2s) cubic-bezier(.3,1.4,.5,1) var(--comic-repeat,1) both}
+.vls-na-slash{transform-box:fill-box;transform-origin:center;animation:vlsNaSlash var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsNaFlick{0%{opacity:.15}10%{opacity:.8}20%{opacity:.2}30%{opacity:.7}40%,100%{opacity:.15}}
@keyframes vlsNaArc{0%{opacity:.45}12%{opacity:1}26%{opacity:.45}42%,100%{opacity:.8}}
-@keyframes vlsNaArm{0%,8%{transform:scaleY(.05)}20%,100%{transform:scaleY(1)}}
+@keyframes vlsNaArm{0%,8%{opacity:0;transform:translateY(10px)}20%,100%{opacity:1;transform:translateY(0)}}
@keyframes vlsNaSlash{0%,22%{opacity:0;transform:scale(1.7)}30%,100%{opacity:1;transform:scale(1)}}
@keyframes vlsNaShake{0%,36%,56%,100%{transform:rotate(0)}40%{transform:rotate(-2.5deg)}44%{transform:rotate(2.5deg)}48%{transform:rotate(-1.8deg)}52%{transform:rotate(1.8deg)}}
${rmBlock(
@@ -883,7 +865,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* panel 1 (before): picture alive, three healthy sound arcs */}
<MiniTv x={26} y={20} w={76} h={48} />
<path d="M54 34 L74 42 L54 50 Z" fill={MINT} />
@@ -898,9 +880,8 @@ ${rmBlock(
<path className="vls-na-a3" d="M118 26a22 22 0 0 1 0 36" />
</g>
{/* panel 2 (after): picture still alive on the mini TV, but the sound
- arcs arrive dashed and carry a stamped red slash; big pawn (s=18)
- presses both mitten-hands to its head — arms are body-green with a
- dark halo outline so the pose reads on both themes. */}
+ arcs arrive dashed and carry a stamped red slash; the pawn raises
+ two floating round hands toward its ears. */}
<MiniTv x={172} y={30} w={42} h={30} />
<path d="M187 37.5 L199 43 L187 48.5 Z" fill={MINT} />
<Floor x1={176} x2={308} y={85} />
@@ -925,33 +906,28 @@ ${rmBlock(
fill="none"
/>
<g className="vls-na-pawn">
- <path d="M264 85 c0-19.8 8.1-27.9 18-27.9 s18 8.1 18 27.9 Z" fill={YOU} />
- <circle cx={282} cy={49} r={10.8} fill={YOU} />
- <circle cx={276} cy={48} r={2} fill="#101a2c" />
- <circle cx={281} cy={48} r={2} fill="#101a2c" />
+ <Pawn x={282} yb={85} s={16} eyes gaze={-2} />
<g className="vls-na-arm">
- <path d="M267 72 Q256 57 272 45" stroke="#101a2c" strokeWidth={6.5} strokeLinecap="round" fill="none" />
- <path d="M267 72 Q256 57 272 45" stroke={YOU} strokeWidth={3.5} strokeLinecap="round" fill="none" />
+ <circle cx={269} cy={52} r={3.5} fill={YOU} />
</g>
<g className="vls-na-arm">
- <path d="M297 72 Q308 57 292 45" stroke="#101a2c" strokeWidth={6.5} strokeLinecap="round" fill="none" />
- <path d="M297 72 Q308 57 292 45" stroke={YOU} strokeWidth={3.5} strokeLinecap="round" fill="none" />
+ <circle cx={295} cy={52} r={3.5} fill={YOU} />
</g>
</g>
</>
);
}
-/** 11. room-not-found: 2 paper panels, loop 3s. The door isn't there. */
+/** 11. room-not-found: 2 paper panels. The door isn't there. */
function SceneNotFound({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-rn-knock{animation:vlsRnKnock 3s ease-in-out infinite}
-.vls-rn-kn{animation:vlsRnKn 3s ease-in-out infinite}
-.vls-rn-solid{animation:vlsRnSolid 3s ease-in-out infinite}
-.vls-rn-ghost{animation:vlsRnGhost 3s ease-in-out infinite}
-.vls-rn-puff{animation:vlsRnPuff 3s ease-in-out infinite}
+.vls-rn-knock{animation:vlsRnKnock var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rn-kn{animation:vlsRnKn var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rn-solid{animation:vlsRnSolid var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rn-ghost{animation:vlsRnGhost var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rn-puff{animation:vlsRnPuff var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsRnKnock{0%{transform:translateX(0)}6%{transform:translateX(5px)}12%{transform:translateX(0)}18%{transform:translateX(5px)}25%,100%{transform:translateX(0)}}
@keyframes vlsRnKn{0%,3%{opacity:0}7%{opacity:.9}11%{opacity:0}19%{opacity:.9}24%,100%{opacity:0}}
@keyframes vlsRnSolid{0%,30%{opacity:1}45%,80%{opacity:0}92%,100%{opacity:1}}
@@ -963,12 +939,9 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<g className="vls-rn-knock">
- <path d="M52 74 c0-11 5-16 11-16 s11 5 11 16 Z" fill={YOU} />
- <circle cx={63} cy={49} r={6} fill={YOU} />
- <circle cx={66} cy={48} r={1} fill="#101a2c" />
- <circle cx={70} cy={48} r={1} fill="#101a2c" />
+ <Pawn x={63} yb={74} s={11} eyes gaze={2} />
</g>
<g className="vls-rn-kn" stroke="var(--ink)" strokeWidth={2} strokeLinecap="round" opacity={0}>
<path d="M84 36l-7-3M82 46h-8M84 56l-7 3" />
@@ -999,19 +972,19 @@ ${rmBlock(
);
}
-/** 12. access-denied: 2 paper panels, loop 3s. Door there, won't open. */
+/** 12. access-denied: 2 paper panels. Door there, won't open. */
function SceneAccessDenied({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-ad-door{transform-box:fill-box;transform-origin:center;animation:vlsAdShake 3s ease-in-out infinite}
-.vls-ad-x{transform-box:fill-box;transform-origin:center;animation:vlsAdX 3s ease-out infinite}
+.vls-ad-door{transform-box:fill-box;transform-origin:center;animation:vlsAdShake var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-ad-x{transform-box:fill-box;transform-origin:center;animation:vlsAdX var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsAdShake{0%{transform:translateX(0)}3%{transform:translateX(-3px)}6%{transform:translateX(3px)}9%{transform:translateX(-2px)}12%{transform:translateX(2px)}15%,100%{transform:translateX(0)}}
@keyframes vlsAdX{0%,18%{opacity:0;transform:scale(1.6) rotate(8deg)}24%,100%{opacity:1;transform:scale(1) rotate(8deg)}}
${rmBlock(["vls-ad-door", "vls-ad-x"], [[".vls-ad-x", "opacity:1;transform:scale(1) rotate(8deg)"]])}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<Pawn x={48} yb={76} s={9} eyes />
<rect x={60} y={38} width={16} height={11} rx={2} fill="var(--paper)" stroke="var(--ink)" strokeWidth={2} />
<circle cx={72} cy={43.5} r={1.6} fill="var(--ink)" />
@@ -1031,14 +1004,14 @@ ${rmBlock(["vls-ad-door", "vls-ad-x"], [[".vls-ad-x", "opacity:1;transform:scale
);
}
-/** 13. invalid-invite: 2 paper panels, loop 3.2s. The ticket is broken. */
+/** 13. invalid-invite: 2 paper panels. The ticket is broken. */
function SceneInvalidInvite({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-ii-l{transform-box:fill-box;transform-origin:center;animation:vlsIiL 3.2s ease-in-out infinite}
-.vls-ii-r{transform-box:fill-box;transform-origin:center;animation:vlsIiR 3.2s ease-in-out infinite}
-.vls-ii-x{transform-box:fill-box;transform-origin:center;animation:vlsIiX 3.2s ease-out infinite}
+.vls-ii-l{transform-box:fill-box;transform-origin:center;animation:vlsIiL var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-ii-r{transform-box:fill-box;transform-origin:center;animation:vlsIiR var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-ii-x{transform-box:fill-box;transform-origin:center;animation:vlsIiX var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsIiL{0%{transform:translate(0,0) rotate(0)}35%,100%{transform:translate(-3px,1px) rotate(-5deg)}}
@keyframes vlsIiR{0%{transform:translate(0,0) rotate(0)}35%,100%{transform:translate(3px,-1px) rotate(5deg)}}
@keyframes vlsIiX{0%,38%{opacity:0;transform:scale(1.6) rotate(8deg)}45%,100%{opacity:1;transform:scale(1) rotate(8deg)}}
@@ -1052,7 +1025,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<Pawn x={48} yb={76} s={9} eyes />
<rect x={62} y={40} width={20} height={13} rx={2} fill="var(--paper)" stroke="var(--ink)" strokeWidth={2} />
<path d="M62 42 L72 48 L82 42" stroke="var(--ink)" strokeWidth={1.5} fill="none" />
@@ -1080,7 +1053,7 @@ ${rmBlock(
);
}
-/** 14. room-full: 2 paper panels, loop 3.2s. Cute first, verdict clear. */
+/** 14. room-full: 2 paper panels. Cute first, verdict clear. */
function SceneRoomFull({ theme }: { theme: ComicTheme }) {
const crowd = [
"var(--pawn-1)",
@@ -1094,15 +1067,15 @@ function SceneRoomFull({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-fl-c1{animation:vlsFlSquish 3.2s ease-in-out infinite}
-.vls-fl-c2{animation:vlsFlSquish 3.2s ease-in-out .09s infinite}
-.vls-fl-c3{animation:vlsFlSquish 3.2s ease-in-out .18s infinite}
-.vls-fl-c4{animation:vlsFlSquish 3.2s ease-in-out .27s infinite}
-.vls-fl-c5{animation:vlsFlSquish 3.2s ease-in-out .36s infinite}
-.vls-fl-c6{animation:vlsFlSquish 3.2s ease-in-out .45s infinite}
-.vls-fl-c7{animation:vlsFlSquish 3.2s ease-in-out .54s infinite}
-.vls-fl-you{transform-box:fill-box;transform-origin:50% 100%;animation:vlsFlBob 3.2s ease-in-out infinite}
-.vls-fl-ghost{animation:vlsFlGhost 3.2s ease-in-out infinite}
+.vls-fl-c1{animation:vlsFlSquish var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-fl-c2{animation:vlsFlSquish var(--comic-duration,3.2s) ease-in-out .09s var(--comic-repeat,1) both}
+.vls-fl-c3{animation:vlsFlSquish var(--comic-duration,3.2s) ease-in-out .18s var(--comic-repeat,1) both}
+.vls-fl-c4{animation:vlsFlSquish var(--comic-duration,3.2s) ease-in-out .27s var(--comic-repeat,1) both}
+.vls-fl-c5{animation:vlsFlSquish var(--comic-duration,3.2s) ease-in-out .36s var(--comic-repeat,1) both}
+.vls-fl-c6{animation:vlsFlSquish var(--comic-duration,3.2s) ease-in-out .45s var(--comic-repeat,1) both}
+.vls-fl-c7{animation:vlsFlSquish var(--comic-duration,3.2s) ease-in-out .54s var(--comic-repeat,1) both}
+.vls-fl-you{transform-box:fill-box;transform-origin:50% 100%;animation:vlsFlBob var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-fl-ghost{animation:vlsFlGhost var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsFlSquish{0%{transform:translateY(0)}8%{transform:translateY(-1.5px)}16%,100%{transform:translateY(0)}}
@keyframes vlsFlBob{0%,14%{transform:translate(0,0)}20%{transform:translate(0,-3px)}26%,30%{transform:translate(0,0)}36%{transform:translate(0,-3px)}44%,100%{transform:translate(0,0)}}
@keyframes vlsFlGhost{0%,45%{opacity:.55}50%{opacity:.15}52%{opacity:.5}55%,100%{opacity:0}}
@@ -1112,16 +1085,26 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
+ <path d="M34 78v6m86-6v6M202 78v6m88-6v6" stroke="var(--ink)" strokeWidth={2} strokeLinecap="round" />
+ <rect x={26} y={58} width={102} height={19} rx={9} fill="var(--couch)" stroke="none" />
{crowd.map((color, i) => (
- <Pawn key={i} x={40 + i * 12} yb={56} s={5.5} color={color} className={`vls-fl-c${i + 1}`} />
+ <Pawn key={i} x={40 + i * 12} yb={67} s={5.5} color={color} eyes className={`vls-fl-c${i + 1}`} />
))}
- <rect x={30} y={48} width={92} height={20} rx={10} fill="var(--couch)" />
- <rect x={24} y={62} width={104} height={16} rx={8} fill="var(--couch)" />
+ <g fill="var(--couch-dark)" stroke="none">
+ <rect x={26} y={69} width={102} height={10} rx={4} />
+ <rect x={22} y={63} width={11} height={16} rx={5} />
+ <rect x={121} y={63} width={11} height={16} rx={5} />
+ <rect x={196} y={58} width={100} height={19} rx={9} fill="var(--couch)" />
+ </g>
<g className="vls-fl-you">
- <Pawn x={240} yb={64} s={7} eyes />
+ <Pawn x={240} yb={67} s={7} eyes />
+ </g>
+ <g fill="var(--couch-dark)" stroke="none">
+ <rect x={196} y={69} width={100} height={10} rx={4} />
+ <rect x={192} y={63} width={11} height={16} rx={5} />
+ <rect x={289} y={63} width={11} height={16} rx={5} />
</g>
- <rect x={196} y={58} width={100} height={22} rx={11} fill="var(--couch)" />
<rect
className="vls-fl-ghost"
x={268}
@@ -1146,10 +1129,10 @@ function SceneBandwidthLimited({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-bw-flow-a{animation:vlsBwFlowA 2.8s ease-in-out infinite}
-.vls-bw-flow-b{animation:vlsBwFlowB 2.8s ease-in-out infinite}
-.vls-bw-throat{transform-box:fill-box;transform-origin:center;animation:vlsBwThroat 2.8s ease-in-out infinite}
-.vls-bw-small{transform-box:fill-box;transform-origin:center;animation:vlsBwSmall 2.8s ease-in-out infinite}
+.vls-bw-flow-a{animation:vlsBwFlowA var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-bw-flow-b{animation:vlsBwFlowB var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-bw-throat{transform-box:fill-box;transform-origin:center;animation:vlsBwThroat var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-bw-small{transform-box:fill-box;transform-origin:center;animation:vlsBwSmall var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsBwFlowA{0%,12%{transform:translateX(-8px);opacity:0}26%,58%{transform:none;opacity:1}72%,100%{transform:translateX(8px);opacity:0}}
@keyframes vlsBwFlowB{0%,32%{transform:translateX(-7px);opacity:0}48%,72%{transform:none;opacity:1}86%,100%{transform:translateX(5px);opacity:0}}
@keyframes vlsBwThroat{0%,30%,100%{transform:scaleY(1)}48%,76%{transform:scaleY(.62)}}
@@ -1164,7 +1147,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={WARN} />
+ <Frame x={164} w={152} theme={theme} result />
<Floor x1={18} x2={142} />
<Floor x1={178} x2={302} />
<Pawn x={28} yb={76} s={7} eyes />
@@ -1203,11 +1186,11 @@ function SceneEncoderLimited({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-en-frame-a{animation:vlsEnFlow 2.9s ease-in-out infinite}
-.vls-en-frame-b{animation:vlsEnFlow 2.9s ease-in-out .3s infinite}
-.vls-en-drop{transform-box:fill-box;transform-origin:center;animation:vlsEnDrop 2.9s ease-in infinite}
-.vls-en-heat{animation:vlsEnHeat 2.9s ease-out infinite}
-.vls-en-small{transform-box:fill-box;transform-origin:center;animation:vlsEnSmall 2.9s ease-in-out infinite}
+.vls-en-frame-a{animation:vlsEnFlow var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-en-frame-b{animation:vlsEnFlow var(--comic-duration,3.2s) ease-in-out .3s var(--comic-repeat,1) both}
+.vls-en-drop{transform-box:fill-box;transform-origin:center;animation:vlsEnDrop var(--comic-duration,3.2s) ease-in var(--comic-repeat,1) both}
+.vls-en-heat{animation:vlsEnHeat var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-en-small{transform-box:fill-box;transform-origin:center;animation:vlsEnSmall var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsEnFlow{0%,12%{transform:translateX(-7px);opacity:0}28%,60%{transform:none;opacity:1}76%,100%{transform:translateX(8px);opacity:0}}
@keyframes vlsEnDrop{0%,42%{transform:none;opacity:1}64%,100%{transform:translateY(16px) rotate(12deg);opacity:0}}
@keyframes vlsEnHeat{0%,34%{transform:translateY(3px);opacity:0}48%,72%{transform:none;opacity:1}86%,100%{opacity:0}}
@@ -1222,7 +1205,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={WARN} />
+ <Frame x={164} w={152} theme={theme} result />
<Floor x1={18} x2={142} />
<Floor x1={178} x2={302} />
<Pawn x={27} yb={76} s={6.5} eyes />
@@ -1258,17 +1241,17 @@ ${rmBlock(
);
}
-/** Generic warning: 1 wide panel, loop 2.6s. Persistent condition: the you-pawn
+/** Generic warning: 1 wide panel. Persistent condition: the you-pawn
* stands beside the big Hearth coal-bowl warning glyph; heat-rays rise in a
* staggered 0-55% window, the pawn blinks at 70%, rest >=50%. */
function SceneWarning({ theme }: { theme: ComicTheme }) {
return (
<>
<style>{`
-.vls-wn-ray1{animation:vlsWnRay 2.6s ease-out infinite}
-.vls-wn-ray2{animation:vlsWnRay 2.6s ease-out .25s infinite}
-.vls-wn-ray3{animation:vlsWnRay 2.6s ease-out .5s infinite}
-.vls-wn-eyes{transform-box:fill-box;transform-origin:center;animation:vlsWnBlink 2.6s ease-in-out infinite}
+.vls-wn-ray1{animation:vlsWnRay var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-wn-ray2{animation:vlsWnRay var(--comic-duration,3.2s) ease-out .25s var(--comic-repeat,1) both}
+.vls-wn-ray3{animation:vlsWnRay var(--comic-duration,3.2s) ease-out .5s var(--comic-repeat,1) both}
+.vls-wn-eyes{transform-box:fill-box;transform-origin:center;animation:vlsWnBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsWnRay{0%{opacity:0;transform:translateY(3px)}9%{opacity:1}24%{transform:translateY(-2px)}50%,100%{transform:translateY(-2px);opacity:1}}
@keyframes vlsWnBlink{0%,66%,74%,100%{transform:scaleY(1)}70%{transform:scaleY(.12)}}
${rmBlock(
@@ -1276,24 +1259,20 @@ ${rmBlock(
[[".vls-wn-ray1,.vls-wn-ray2,.vls-wn-ray3", "opacity:1;transform:none"]],
)}
`}</style>
- <Frame x={4} w={312} theme={theme} />
+ <Frame x={4} w={312} theme={theme} result />
<Floor x1={24} x2={296} />
- <Pawn x={96} yb={76} s={11} />
- <g className="vls-wn-eyes">
- <circle cx={98} cy={53} r={1.1} fill="#101a2c" />
- <circle cx={101.6} cy={53} r={1.1} fill="#101a2c" />
- </g>
+ <Pawn x={96} yb={76} s={11} eyes gaze={2} eyeClassName="vls-wn-eyes" />
{/* Hearth warning glyph x3.5 (~54% panel height), bowl feet on the floor:
M6 13a6 6 0 0 0 12 0 + rays M12 9V5.5 / M8.5 9.5 7 7.5 / M15.5 9.5 17 7.5,
baked at origin (168, 9.5). */}
<path
d="M189 55 a21 21 0 0 0 42 0"
- stroke={WARN}
+ stroke="var(--comic-tone, var(--warn))"
strokeWidth={2.5}
strokeLinecap="round"
fill="none"
/>
- <g stroke={WARN} strokeWidth={2.5} strokeLinecap="round" fill="none">
+ <g stroke="var(--comic-tone, var(--warn))" strokeWidth={2.5} strokeLinecap="round" fill="none">
<g className="vls-wn-ray1" opacity={0}>
<path d="M197.75 42.75 L192.5 35.75" />
<path d="M188.5 41 l-4 -3.5" stroke={FAINT} strokeWidth={2} />
@@ -1315,6 +1294,9 @@ const SCENES: Record<ComicKind, (props: { theme: ComicTheme }) => ReactNode> = {
"waiting-for-host": SceneWaiting,
"connecting-p2p": (p) => <SceneConnecting {...p} sfu={false} />,
"connecting-sfu": (p) => <SceneConnecting {...p} sfu />,
+ "signal-connecting": (p) => <SceneSignal {...p} state="connecting" />,
+ "signal-recovering": (p) => <SceneSignal {...p} state="recovering" />,
+ "signal-offline": (p) => <SceneSignal {...p} state="offline" />,
"tap-to-play": SceneTap,
"host-paused": ScenePaused,
recovering: SceneRecovering,
@@ -1340,21 +1322,32 @@ export const Comic = memo(function Comic({
kind,
size,
theme,
+ tone,
+ motion,
}: {
kind: ComicKind;
size?: number;
theme?: ComicTheme;
+ tone?: ComicTone;
+ motion?: ComicMotion;
}) {
const resolvedTheme = theme ?? DEFAULT_THEME[kind];
- const style: CSSProperties = {
+ const presentation = getComicPresentation(kind);
+ const resolvedTone = tone ?? presentation.tone;
+ const resolvedMotion = motion ?? presentation.motion;
+ const style = {
+ ...comicStyle(resolvedTone, resolvedMotion),
+ "--comic-neutral": resolvedTheme === "paper" ? "var(--ink)" : "#48597a",
width: size != null ? `${size}px` : "min(320px, 86%)",
height: "auto",
display: "block",
- };
+ } as CSSProperties;
return (
<svg
viewBox="0 0 320 96"
style={style}
+ data-comic-tone={resolvedTone}
+ data-comic-motion={resolvedMotion}
aria-hidden="true"
focusable="false"
xmlns="http://www.w3.org/2000/svg"
diff --git a/src/client/components/living/Couch.tsx b/src/client/components/living/Couch.tsx
index 6d4e54d1..1288355c 100644
--- a/src/client/components/living/Couch.tsx
+++ b/src/client/components/living/Couch.tsx
@@ -1,31 +1,17 @@
-// The couch: the roster as pawns watching the TV. Joining pawns hop in,
-// self carries the green pointer, and the host wears a crown.
+// The roster sits in responsive couch rows. UUIDs own identity and gestures;
+// self carries the green pointer, and the Host wears the gold crown.
import { Glyph } from "../../ui/icons";
import { useCopy } from "../../ui/copy";
+import { useElementWidth } from "../../lib/use-element-width";
+import { PawnSvg } from "./Pawn";
import { participantColor } from "./participant-color";
-
-export function PawnSvg({ color, crown }: { color: string; crown?: boolean }) {
- return (
- <svg viewBox="0 0 40 48" width="40" height="48" aria-hidden="true">
- {crown ? (
- <path
- d="M14 12.5 L11.5 2 L17 6.5 L20 0 L23 6.5 L28.5 2 L26 12.5 Z"
- fill="var(--pawn-2)"
- />
- ) : null}
- <circle cx="20" cy="14" r="8.5" fill={color} />
- <path d="M5 46c0-13 6.5-17 15-17s15 4 15 17Z" fill={color} />
- <circle cx="17" cy="13" r="1.6" fill="var(--stage)" />
- <circle cx="23" cy="13" r="1.6" fill="var(--stage)" />
- </svg>
- );
-}
+import type { StatusDescriptor } from "../../ui/media-status";
+import { Tooltip } from "./Tooltip";
export interface CouchEntry {
key: string;
name: string;
- connected: boolean;
- statusLabel?: string;
+ status: StatusDescriptor;
you?: boolean;
selectable?: boolean;
}
@@ -33,6 +19,7 @@ export interface CouchEntry {
export interface CouchHostEntry {
key: string;
name: string;
+ online: boolean;
you?: boolean;
selected?: boolean;
controls?: string;
@@ -40,12 +27,14 @@ export interface CouchHostEntry {
}
export function Couch({
+ view,
host,
entries,
selectedKey,
onSelect,
emptyHint,
}: {
+ view: "host" | "viewer";
host?: CouchHostEntry | null;
entries: CouchEntry[];
selectedKey?: string | null;
@@ -53,100 +42,98 @@ export function Couch({
emptyHint?: string;
}) {
const { vis, t } = useCopy();
- const crowded = entries.length + (host ? 1 : 0) > 10;
+ const [couchRef, containerWidth] = useElementWidth();
+ const count = entries.length + (host ? 1 : 0);
+ const capacity = Math.max(2, Math.min(8, Math.floor((containerWidth - 64) / 72)));
+ const rows = Math.max(1, Math.ceil(count / capacity));
+ const columns = Math.max(1, Math.ceil(count / rows));
+ const width = Math.min(containerWidth, Math.max(280, columns * 72 + 64));
+ const seatStyle = (index: number) => {
+ const row = Math.floor(index / columns);
+ const inRow = Math.min(columns, count - row * columns);
+ return { gridRow: row + 1, gridColumn: `${(index % columns) * 2 + 1 + columns - inRow} / span 2` };
+ };
+ const hostLabel = host
+ ? `${host.name} · ${t("common.host")}${host.you ? ` · ${t("common.you")}` : ""} · ${t(host.online ? "state.presence.online" : "state.presence.offline")}`
+ : undefined;
return (
- <div className="lr-couch">
- <svg viewBox="0 0 640 132" aria-hidden="true">
- <rect x="70" y="110" width="18" height="16" rx="5" fill="var(--frame)" />
- <rect x="552" y="110" width="18" height="16" rx="5" fill="var(--frame)" />
- <rect x="28" y="28" width="58" height="80" rx="24" fill="var(--couch-dark)" />
- <rect x="554" y="28" width="58" height="80" rx="24" fill="var(--couch-dark)" />
- <rect x="56" y="18" width="528" height="58" rx="27" fill="var(--couch)" />
- <rect x="44" y="62" width="552" height="50" rx="23" fill="var(--couch)" />
- <path d="M212 64v46M428 64v46" stroke="var(--couch-dark)" strokeWidth="4" strokeLinecap="round" />
- </svg>
- <div className="lr-pawns-window">
+ <div ref={couchRef} className="lr-couch">
+ <div className="lr-couch-seating" style={{ width, minHeight: rows * 108 }}>
+ <div className="lr-couch-benches" aria-hidden="true">
+ {Array.from({ length: rows }, (_, row) => <svg key={row} viewBox={`0 0 ${width} 108`}>
+ <path d={`M38 98v7m${width - 76} -7v7`} stroke="var(--frame)" strokeWidth="6" strokeLinecap="round" />
+ <rect x="18" y="32" width={width - 36} height="65" rx="24" fill="var(--couch-dark)" />
+ <rect x="28" y="24" width={width - 56} height="60" rx="23" fill="var(--couch)" />
+ <rect x="28" y="76" width={width - 56} height="24" rx="10" fill="var(--couch)" />
+ <path d={`M${width / 3} 79v16m${width / 3} -16v16`} stroke="var(--couch-dark)" strokeWidth="2" strokeLinecap="round" />
+ <rect x="14" y="59" width="25" height="39" rx="12" fill="var(--couch-dark)" />
+ <rect x={width - 39} y="59" width="25" height="39" rx="12" fill="var(--couch-dark)" />
+ </svg>)}
+ </div>
<div
- className={`lr-pawns${crowded ? " is-crowded" : ""}`}
+ className="lr-pawns"
+ style={{ gridTemplateColumns: `repeat(${columns * 2}, minmax(0, 1fr))` }}
role="group"
aria-label={`${t("common.host")} · ${t("common.viewers")}`}
>
- {host
- ? host.onSelect
- ? (
+ {host ? (
+ <span className="lr-seat" style={seatStyle(0)}><Tooltip text={vis ? host.name : hostLabel}>
+ {host.onSelect ? (
<button
type="button"
className={`lr-pawn is-host${host.you ? " is-you" : ""}${host.selected ? " is-selected" : ""}`}
- title={host.name}
- aria-label={`${host.name} · ${t("common.host")}`}
+ aria-label={hostLabel}
aria-pressed={host.selected}
aria-controls={host.controls}
onClick={host.onSelect}
>
- <PawnSvg color={participantColor(host.key)} crown />
- <i className="lr-pawn-led" aria-hidden="true" />
+ <PawnSvg color={participantColor(host.key)} identity={host.key} host />
<span className="lr-pawn-name">{host.name}</span>
</button>
- )
- : (
+ ) : (
<span
className={`lr-pawn is-host is-static${host.you ? " is-you" : ""}`}
- title={host.name}
- aria-label={`${host.name} · ${t("common.host")}`}
+ role="img"
+ aria-label={hostLabel}
+ tabIndex={0}
>
- <PawnSvg color={participantColor(host.key)} crown />
- <i className="lr-pawn-led" aria-hidden="true" />
+ <PawnSvg color={participantColor(host.key)} identity={host.key} host />
<span className="lr-pawn-name">{host.name}</span>
</span>
- )
- : null}
+ )}
+ </Tooltip></span>
+ ) : null}
{entries.map((entry, index) => {
- const stateLabel = entry.connected
- ? t("state.peer.connected")
- : (entry.statusLabel ?? t("state.peer.connecting"));
- const label = entry.you
- ? `${entry.name} · ${t("common.you")}`
- : `${entry.name} · ${stateLabel}`;
+ const stateLabel = t(entry.status.labelKey);
+ const hint = entry.status.tooltip ?? entry.status.comic;
+ const label = `${entry.name}${entry.you ? ` · ${t("common.you")}` : ""} · ${stateLabel}`;
const inner = (
<>
- <PawnSvg color={participantColor(entry.key)} />
- <i
- className={`lr-pawn-led${entry.connected ? "" : " is-wait"}`}
- aria-hidden="true"
- />
+ <PawnSvg color={participantColor(entry.key)} identity={entry.key} />
+ {view === "host" ? <i className="lr-pawn-led" data-tone={entry.status.tone}
+ data-pulse={entry.status.pulse || undefined} aria-hidden="true" /> : null}
<span className="lr-pawn-name">
{entry.name}
</span>
</>
);
- // Hop stagger derives from position only, so render stays pure.
- const style = {
- animationDelay: `${Math.min(index, 12) * 70}ms`,
- };
const className = `lr-pawn${entry.you ? " is-you" : ""}${
entry.selectable === false ? " is-static" : ""
- }${selectedKey === entry.key ? " is-selected" : ""}`;
- if (entry.selectable === false) {
- return (
- <span
- key={entry.key}
- className={className}
- style={style}
- title={entry.name}
- aria-label={label}
- >
- {inner}
- </span>
- );
- }
- return (
+ }${selectedKey === entry.key ? " is-selected" : ""}${view === "viewer" && entry.status.pulse ? " is-waiting" : ""}`;
+ const pawn = entry.selectable === false ? (
+ <span
+ className={className}
+ role="img"
+ aria-label={label}
+ tabIndex={0}
+ >
+ {inner}
+ </span>
+ ) : (
<button
- key={entry.key}
type="button"
className={className}
- style={style}
- title={entry.name}
aria-label={label}
aria-pressed={selectedKey === entry.key}
onClick={() => onSelect?.(entry.key)}
@@ -154,20 +141,29 @@ export function Couch({
{inner}
</button>
);
+ return (
+ <span key={entry.key} className="lr-seat" style={seatStyle(index + (host ? 1 : 0))}><Tooltip
+ kind={hint}
+ tone={entry.status.tone}
+ motion={entry.status.pulse ? "progress" : undefined}
+ text={vis ? hint ? undefined : entry.name : label}
+ >
+ {pawn}
+ </Tooltip></span>
+ );
})}
</div>
</div>
- <span
- className="lr-couch-count"
- aria-label={`${t("common.viewers")} ${entries.length}`}
- >
- <Glyph name="users" size={14} />
- <b>{entries.length}</b>
- </span>
+ <div className="lr-couch-footer">
+ <span className="lr-couch-count" role="img" aria-label={`${t("common.viewers")} ${entries.length}`}>
+ <Glyph name="users" size={14} /><b>{entries.length}</b>
+ </span>
+ </div>
{entries.length === 0 && !host ? (
<div
className="lr-couch-empty"
- title={vis ? undefined : (emptyHint ?? t("host.viewers.empty"))}
+ role="img"
+ aria-label={emptyHint ?? t("host.viewers.empty")}
>
<Glyph name="users" size={22} />
</div>
diff --git a/src/client/components/living/Header.tsx b/src/client/components/living/Header.tsx
index 209ea614..07ae9d12 100644
--- a/src/client/components/living/Header.tsx
+++ b/src/client/components/living/Header.tsx
@@ -4,7 +4,7 @@ import { useState } from "react";
import { browserDebugEnabled, debugError, downloadBrowserDebug } from "../../lib/debug";
import { VisGlyph } from "./primitives";
import { BrandMark } from "./BrandMark";
-import { ComicTooltip } from "./ComicTooltip";
+import { Tooltip } from "./Tooltip";
import type { ComicKind } from "./Comic";
import { useCopy, type Lang } from "../../ui/copy";
import { useTheme } from "../../ui/theme";
@@ -22,13 +22,12 @@ export function LedStrip({
comic?: ComicKind;
}) {
const { vis } = useCopy();
- const wrapped = vis && comic;
+ const wrapped = !vis || comic;
const strip = (
<span
className="lr-leds"
data-state={state}
role="status"
- title={vis ? undefined : label}
aria-label={label}
tabIndex={wrapped ? 0 : undefined}
>
@@ -39,9 +38,9 @@ export function LedStrip({
</span>
);
return wrapped ? (
- <ComicTooltip kind={wrapped} place="below" align="start">
+ <Tooltip kind={comic} tone={state} text={vis ? undefined : label} place="below" align="start">
{strip}
- </ComicTooltip>
+ </Tooltip>
) : (
strip
);
@@ -57,7 +56,6 @@ export function HeaderControls() {
<button
type="button"
className={active ? "is-selected" : ""}
- title={vis ? undefined : t(tipKey)}
aria-label={t(tipKey)}
aria-pressed={active}
onClick={() => (mode === "vis" ? setVis(true) : setLang(mode))}
@@ -72,12 +70,10 @@ export function HeaderControls() {
type="button"
className="lr-btn"
style={{ minWidth: 40, height: 40, borderRadius: 999 }}
- title={vis ? undefined : themeTitle}
aria-label={themeTitle}
onClick={(event) => {
- // Hint-wrapped in vis: pointer activation must not leave the comic
- // pinned open by focus over the stage (keyboard clicks keep focus).
- if (vis && event.detail !== 0) event.currentTarget.blur();
+ // Pointer activation must not pin the hint open; keyboard keeps focus.
+ if (event.detail !== 0) event.currentTarget.blur();
toggle();
}}
>
@@ -93,10 +89,9 @@ export function HeaderControls() {
const debugButton = (
<button
type="button" className="lr-btn" disabled={debugExport === "busy"}
- title={vis ? undefined : debugTitle}
aria-label={debugTitle} aria-busy={debugExport === "busy" || undefined}
onClick={(event) => {
- if (vis && event.detail !== 0) event.currentTarget.blur();
+ if (event.detail !== 0) event.currentTarget.blur();
setDebugExport("busy");
void downloadBrowserDebug().then(() => setDebugExport("idle")).catch((error) => {
debugError("export", "collector-failed", error, { collector: "download" });
@@ -111,23 +106,19 @@ export function HeaderControls() {
);
return (
<span className="lr-top-right lr-header-controls">
- {browserDebugEnabled && (vis ? (
- <ComicTooltip kind="hint-debug-export" place="below" align="end">
+ {browserDebugEnabled && (
+ <Tooltip kind="hint-debug-export" text={vis ? undefined : debugTitle} place="below" align="end">
{debugButton}
- </ComicTooltip>
- ) : debugButton)}
+ </Tooltip>
+ )}
<span className="lr-lang" role="group" aria-label={t("mode.language")}>
{option("zh", "中", "mode.zh")}
{option("en", "EN", "mode.en")}
{option("vis", "✦", "mode.vis")}
</span>
- {vis ? (
- <ComicTooltip kind="hint-theme" place="below" align="end">
- {themeButton}
- </ComicTooltip>
- ) : (
- themeButton
- )}
+ <Tooltip kind={theme === "dark" ? "hint-theme-light" : "hint-theme-dark"} text={vis ? undefined : themeTitle} place="below" align="end">
+ {themeButton}
+ </Tooltip>
</span>
);
}
@@ -139,14 +130,13 @@ export function AppHeader({
led?: React.ReactNode;
homeHref?: string;
}) {
- const { t, vis } = useCopy();
+ const { t } = useCopy();
return (
<header className="lr-top">
<a
className="lr-brand"
href={homeHref}
aria-label={t("brand.home")}
- title={vis ? undefined : t("brand.home")}
>
<BrandMark size={34} motion="once" />
</a>
diff --git a/src/client/components/living/HostMark.tsx b/src/client/components/living/HostMark.tsx
new file mode 100644
index 00000000..77bfaed3
--- /dev/null
+++ b/src/client/components/living/HostMark.tsx
@@ -0,0 +1,36 @@
+/** The gold Host crown, shared by room pawns and explanatory comics. */
+
+export function HostMark({
+ x,
+ y,
+ width = 20,
+ dashed = false,
+ className,
+ opacity,
+}: {
+ x: number;
+ y: number;
+ width?: number;
+ dashed?: boolean;
+ className?: string;
+ opacity?: number;
+}) {
+ return (
+ <g
+ transform={`translate(${x} ${y}) scale(${width / 12})`}
+ fill="none"
+ stroke={dashed ? "var(--ink)" : "#705025"}
+ strokeWidth={1}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className={className}
+ opacity={opacity}
+ strokeDasharray={dashed ? "1.2 1" : undefined}
+ aria-hidden="true"
+ >
+ <path d="m1.2 6.3-1.2-3.7q-.2-.7.5-.4L3 3.6l2.4-2.5q.6-.7 1.2 0L9 3.6l2.5-1.4q.7-.3.5.4l-1.2 3.7q-.2.9-1.2.9H2.4q-1 0-1.2-.9Z"
+ fill={dashed ? "none" : "#f7d861"} />
+ {!dashed ? <path d="M2.1 6.5h7.8" stroke="#b58a2f" strokeWidth={1} /> : null}
+ </g>
+ );
+}
diff --git a/src/client/components/living/LauncherForm.tsx b/src/client/components/living/LauncherForm.tsx
new file mode 100644
index 00000000..200298ea
--- /dev/null
+++ b/src/client/components/living/LauncherForm.tsx
@@ -0,0 +1,176 @@
+import type { FormEvent, ReactNode } from "react";
+import { BrandMark } from "./BrandMark";
+import { Tooltip } from "./Tooltip";
+import { WelcomeLine } from "./WelcomeLine";
+import { Btn, Pill } from "./primitives";
+import type { HintKind } from "./hints";
+import { Glyph, type GlyphName } from "../../ui/icons";
+import { useCopy, type CopyKey } from "../../ui/copy";
+export type AppMode = "local" | "link" | "site";
+
+const MODES: Array<{
+ mode: AppMode;
+ icon: GlyphName;
+ label: CopyKey;
+ hint: CopyKey;
+ comic: HintKind;
+}> = [
+ {
+ mode: "local",
+ icon: "users",
+ label: "client.launch.local",
+ hint: "client.launch.localHint",
+ comic: "hint-client-local",
+ },
+ {
+ mode: "link",
+ icon: "globe",
+ label: "client.launch.link",
+ hint: "client.launch.linkHint",
+ comic: "hint-client-link",
+ },
+ {
+ mode: "site",
+ icon: "server",
+ label: "client.launch.site",
+ hint: "client.launch.siteHint",
+ comic: "hint-client-site",
+ },
+];
+
+// The product and film share this form; requests and navigation stay in the page.
+export function LauncherForm({
+ mode,
+ onModeChange,
+ site,
+ onSiteChange,
+ localAccessPassword,
+ onLocalAccessPasswordChange,
+ error,
+ onSubmit,
+ children,
+}: {
+ mode: AppMode;
+ onModeChange: (mode: AppMode) => void;
+ site: string;
+ onSiteChange: (site: string) => void;
+ localAccessPassword: string;
+ onLocalAccessPasswordChange: (password: string) => void;
+ error: boolean;
+ onSubmit: (event: FormEvent<HTMLFormElement>) => void;
+ children?: ReactNode;
+}) {
+ const { vis, t } = useCopy();
+ const accessField = (
+ <label className="lr-input lr-client-access">
+ <Glyph name="lock" size={18} />
+ <input
+ type="text"
+ value={localAccessPassword}
+ maxLength={128}
+ autoComplete="off"
+ spellCheck={false}
+ placeholder={vis ? "" : t("client.launch.localAccess")}
+ aria-label={t("client.launch.localAccess")}
+ onChange={(event) => {
+ onLocalAccessPasswordChange(event.target.value);
+ }}
+ />
+ </label>
+ );
+ return (
+ <form className="lr-client-launch-panel" onSubmit={onSubmit}>
+ <BrandMark size={68} motion="once" />
+ <WelcomeLine />
+ <h1 className={vis ? "visually-hidden" : "lr-client-launch-title"}>
+ {t("client.launch.title")}
+ </h1>
+
+ {children}
+
+ <div
+ className="lr-client-modes"
+ role="radiogroup"
+ aria-label={t("client.launch.title")}
+ >
+ {MODES.map((choice) => {
+ const button = (
+ <button
+ key={choice.mode}
+ type="button"
+ role="radio"
+ className={`lr-client-mode${mode === choice.mode ? " is-selected" : ""}`}
+ aria-checked={mode === choice.mode}
+ aria-label={t(choice.label)}
+ onClick={() => {
+ onModeChange(choice.mode);
+ }}
+ >
+ <Glyph name={choice.icon} size={27} />
+ {vis ? null : (
+ <span>
+ <strong>{t(choice.label)}</strong>
+ <small>{t(choice.hint)}</small>
+ </span>
+ )}
+ </button>
+ );
+ return (
+ <Tooltip
+ key={choice.mode}
+ kind={choice.comic}
+ text={vis ? undefined : t(choice.hint)}
+ >
+ {button}
+ </Tooltip>
+ );
+ })}
+ </div>
+
+ {mode === "site" ? (
+ <label className="lr-input lr-client-site">
+ <Glyph name="link" size={18} />
+ <input
+ type="url"
+ value={site}
+ autoFocus
+ spellCheck={false}
+ inputMode="url"
+ placeholder="https://share.example"
+ aria-label={t("client.launch.siteAddress")}
+ onChange={(event) => {
+ onSiteChange(event.target.value);
+ }}
+ />
+ </label>
+ ) : null}
+
+ {mode !== "site" ? (
+ <Tooltip
+ kind="hint-password"
+ text={vis ? undefined : t("client.launch.localAccessHint")}
+ >
+ {accessField}
+ </Tooltip>
+ ) : null}
+
+ {error ? (
+ <Pill
+ icon="alert"
+ tone="bad"
+ label={t("client.launch.error")}
+ alert
+ comic="warning"
+ />
+ ) : null}
+ <Btn
+ icon="arrowRight"
+ title="client.launch.go"
+ cap="client.launch.go"
+ tone="primary"
+ type="submit"
+ disabled={mode === "site" && !site.trim()}
+ />
+ </form>
+ );
+}
diff --git a/src/client/components/living/Metrics.tsx b/src/client/components/living/Metrics.tsx
index c2ff182f..015b2340 100644
--- a/src/client/components/living/Metrics.tsx
+++ b/src/client/components/living/Metrics.tsx
@@ -3,7 +3,7 @@
import { useId, useState, type ReactNode } from "react";
import { Glyph, type GlyphName } from "../../ui/icons";
import { useCopy, type CopyKey } from "../../ui/copy";
-import { ComicTooltip } from "./ComicTooltip";
+import { Tooltip } from "./Tooltip";
import { Pill } from "./primitives";
import type { ConnectionMetrics } from "../../types";
import { formatPacketLossPercent } from "../connection-details";
@@ -12,7 +12,6 @@ interface MetricValue {
icon: GlyphName;
label: CopyKey;
value: string;
- title?: string;
/** Visual mode shows the glyph alone; the value stays in the a11y name. */
glyphOnly?: boolean;
}
@@ -49,10 +48,9 @@ function secondaryMetrics(
value: number | null,
unit: string,
digits = 0,
- title?: string,
) => {
if (value !== null && Number.isFinite(value)) {
- values.push({ icon, label, value: `${readable(value, digits)} ${unit}`, title });
+ values.push({ icon, label, value: `${readable(value, digits)} ${unit}` });
}
};
const qualityReason = (value: string): string => {
@@ -176,10 +174,10 @@ export function MetricCells({
onToggle: (expanded: boolean) => void;
}) {
const { t, vis } = useCopy();
- const cell = ({ icon, label, value, title, glyphOnly }: MetricValue): ReactNode => {
+ const cell = ({ icon, label, value, glyphOnly }: MetricValue): ReactNode => {
const display = vis && value === t("stats.unknown") ? "—" : value;
return (
- <span className="lr-meter-cell" title={vis ? undefined : title ?? t(label)} key={label + display}>
+ <span className="lr-meter-cell" key={label + display}>
<Glyph name={icon} size={16} />
{vis ? (
<>
@@ -224,19 +222,17 @@ export function MetricCells({
<button
type="button"
className={`lr-btn lr-metrics-more${expanded ? " is-open" : ""}`}
- title={vis ? undefined : moreTitle}
aria-label={moreTitle}
aria-expanded={expanded}
aria-controls={secondaryId}
onClick={(event) => {
- // Hint-wrapped in vis: pointer activation must not leave the comic
- // pinned open by focus (keyboard clicks keep focus).
- if (vis && event.detail !== 0) event.currentTarget.blur();
+ // Pointer activation must not pin the hint open; keyboard keeps focus.
+ if (event.detail !== 0) event.currentTarget.blur();
onToggle(!expanded);
}}
>
<Glyph name="chevron" size={15} />
- {vis ? null : <span className="lr-cap">{t("stats.more")}</span>}
+ {vis ? null : <span className="lr-cap">{moreTitle}</span>}
</button>
);
@@ -247,14 +243,9 @@ export function MetricCells({
</div>
{secondary.length > 0 ? (
<>
- {vis ? (
- // This button lands at the card's left edge (the meter takes a
- // full flex basis), so prefer start; ComicTooltip re-picks from
- // live geometry if that would clip.
- <ComicTooltip kind="hint-more-metrics" align="start">{moreButton}</ComicTooltip>
- ) : (
- moreButton
- )}
+ <Tooltip kind={expanded ? "hint-collapse" : "hint-more-metrics"} text={vis ? undefined : moreTitle} align="start">
+ {moreButton}
+ </Tooltip>
{expanded ? (
<div id={secondaryId} className="lr-meter" role="group" aria-label={t("stats.more")}>
{secondary.map(cell)}
diff --git a/src/client/components/living/Pawn.tsx b/src/client/components/living/Pawn.tsx
new file mode 100644
index 00000000..75c8f7fd
--- /dev/null
+++ b/src/client/components/living/Pawn.tsx
@@ -0,0 +1,40 @@
+import { useLayoutEffect, useRef, type CSSProperties } from "react";
+import { HostMark } from "./HostMark";
+import { bindParticipantMotion, participantMotion } from "./participant-motion";
+
+/** The accepted A silhouette, shared with the explanatory cast. */
+export function PersonShape({ eyes = true, gaze = 0, eyeClassName, host }: {
+ eyes?: boolean | "closed"; gaze?: number; eyeClassName?: string; host?: boolean;
+}) {
+ return <>
+ <circle cx="24" cy="14" r="8" stroke="none" />
+ <path d="M10 47c0-13 5-20 14-20s14 7 14 20q0 3-3 3H13q-3 0-3-3Z" stroke="none" />
+ {eyes ? <g className={`lr-person-eyes${eyeClassName ? ` ${eyeClassName}` : ""}`} fill="#263b43">
+ {eyes === "closed" ? <path d={`M${20.1 + gaze} 14.5q1.1-1.4 2.2 0m3.4 0q1.1-1.4 2.2 0`}
+ fill="none" stroke="#263b43" strokeWidth="2.2" strokeLinecap="round" /> : <>
+ <ellipse cx={21.2 + gaze} cy="14.1" rx="1.1" ry="1.5" />
+ <ellipse cx={26.8 + gaze} cy="14.1" rx="1.1" ry="1.5" />
+ </>}
+ </g> : null}
+ {host ? <HostMark x={18} y={0} width={12} /> : null}
+ </>;
+}
+
+export function PawnSvg({ color, host, identity }: {
+ color: string; host?: boolean; identity?: string;
+}) {
+ const root = useRef<SVGSVGElement>(null);
+ const motion = identity ? participantMotion(identity) : null;
+ useLayoutEffect(() => {
+ if (identity && root.current) return bindParticipantMotion(root.current, identity);
+ }, [identity]);
+ return <svg ref={root} className="lr-person" viewBox="0 0 48 56" width="40" height="48"
+ aria-hidden="true" data-motion={identity ? "" : undefined} style={motion ? {
+ "--person-duration": `${motion.duration}ms`,
+ "--person-lean": `${motion.lean}deg`,
+ "--person-gaze-x": `${host ? 1.6 : motion.gaze}px`,
+ "--person-gaze-y": host ? "-1.4px" : "0px",
+ } as CSSProperties : undefined}>
+ <g className="lr-person-body" fill={color}><PersonShape host={host} /></g>
+ </svg>;
+}
diff --git a/src/client/components/living/PawnDetail.tsx b/src/client/components/living/PawnDetail.tsx
index d5f86521..6fcf9e15 100644
--- a/src/client/components/living/PawnDetail.tsx
+++ b/src/client/components/living/PawnDetail.tsx
@@ -1,11 +1,12 @@
// Per-viewer drill-down: name, route glyph, primary metrics, expandable
// detailed metrics. Host sees every Viewer; a Viewer uses this only for relay
// children because its own route already has the canonical details panel.
-import { PawnSvg } from "./Couch";
+import { PawnSvg } from "./Pawn";
import { participantColor } from "./participant-color";
import { Glyph } from "../../ui/icons";
-import { ComicTooltip } from "./ComicTooltip";
+import { Tooltip } from "./Tooltip";
import { useCopy } from "../../ui/copy";
+import { resolveMediaFailure, type MediaFailure } from "../../ui/media-failure";
import type { ConnectionMetrics } from "../../types";
import { MetricCells } from "./Metrics";
@@ -14,9 +15,8 @@ export function RouteGlyph({ route }: { route: "p2p" | "sfu" }) {
const cell = (
<span
className="lr-meter-cell"
- title={vis ? undefined : t(route === "sfu" ? "state.route.sfu" : "state.route.p2p")}
- // Hint-wrapped in vis: focusable so keyboard users reach the comic.
- tabIndex={vis ? 0 : undefined}
+ // The route hint is available to keyboard users in every language.
+ tabIndex={0}
>
{route === "sfu" ? (
<svg width="36" height="16" viewBox="0 0 36 16" fill="none" stroke="#53676a" strokeWidth="2" aria-hidden="true">
@@ -41,12 +41,13 @@ export function RouteGlyph({ route }: { route: "p2p" | "sfu" }) {
)}
</span>
);
- return vis ? (
- <ComicTooltip kind={route === "sfu" ? "hint-route-sfu" : "hint-route-p2p"}>
+ return (
+ <Tooltip
+ kind={route === "sfu" ? "hint-route-sfu" : "hint-route-p2p"}
+ text={vis ? undefined : t(route === "sfu" ? "state.route.sfu" : "state.route.p2p")}
+ >
{cell}
- </ComicTooltip>
- ) : (
- cell
+ </Tooltip>
);
}
@@ -68,16 +69,18 @@ export function PawnDetail({
metrics?: ConnectionMetrics | null;
direction: "send" | "receive";
tag?: { icon: "arrowUp" | "loader"; label: string };
- error?: string | null;
+ error?: MediaFailure | null;
expanded: boolean;
onToggleMetrics: (expanded: boolean) => void;
onClose: () => void;
}) {
- const { t, vis } = useCopy();
+ const copy = useCopy();
+ const { t, vis } = copy;
+ const errorText = resolveMediaFailure(error, copy);
return (
<div className="lr-row is-sub lr-pawn-detail" role="group" aria-label={name}>
<span className="lr-pawn-mini">
- <PawnSvg color={participantColor(pawnKey)} />
+ <PawnSvg color={participantColor(pawnKey)} identity={pawnKey} />
</span>
{vis ? (
<span className="visually-hidden">{name}</span>
@@ -85,24 +88,22 @@ export function PawnDetail({
<span className="lr-pawn-detail-name">{name}</span>
)}
{tag ? (
- <span className="lr-meter-cell" title={vis ? undefined : tag.label}>
+ <span className="lr-meter-cell">
<Glyph name={tag.icon} size={16} />
{vis ? <span className="visually-hidden">{tag.label}</span> : <b>{tag.label}</b>}
</span>
) : null}
- {error ? (
- <ComicTooltip kind="route-failed">
+ {errorText ? (
+ <Tooltip kind="route-failed" text={vis ? undefined : errorText}>
<span
className="lr-pill is-bad"
role="alert"
- title={vis ? undefined : error}
- // Comic-wrapped: focusable so keyboard users reach the comic.
- tabIndex={vis ? 0 : undefined}
+ tabIndex={0}
>
<Glyph name="alert" size={16} />
- {vis ? <span className="visually-hidden">{error}</span> : <span>{error}</span>}
+ {vis ? <span className="visually-hidden">{errorText}</span> : <span>{errorText}</span>}
</span>
- </ComicTooltip>
+ </Tooltip>
) : null}
{route ? <RouteGlyph route={route} /> : null}
{metrics ? (
@@ -113,32 +114,20 @@ export function PawnDetail({
onToggle={onToggleMetrics}
/>
) : null}
- {vis ? (
- <ComicTooltip kind="hint-close">
- <button
- type="button"
- className="lr-pawn-detail-close"
- aria-label={t("common.close")}
- onClick={(event) => {
- // Pointer activation must not leave the comic pinned by focus.
- if (event.detail !== 0) event.currentTarget.blur();
- onClose();
- }}
- >
- <Glyph name="x" size={16} />
- </button>
- </ComicTooltip>
- ) : (
+ <Tooltip kind="hint-close" text={vis ? undefined : t("common.close")}>
<button
type="button"
className="lr-pawn-detail-close"
- title={t("common.close")}
aria-label={t("common.close")}
- onClick={onClose}
+ onClick={(event) => {
+ // Pointer activation must not pin the hint open; keyboard keeps focus.
+ if (event.detail !== 0) event.currentTarget.blur();
+ onClose();
+ }}
>
<Glyph name="x" size={16} />
</button>
- )}
+ </Tooltip>
</div>
);
}
diff --git a/src/client/components/living/PlaybackControls.tsx b/src/client/components/living/PlaybackControls.tsx
new file mode 100644
index 00000000..f6c9e05d
--- /dev/null
+++ b/src/client/components/living/PlaybackControls.tsx
@@ -0,0 +1,166 @@
+import { useEffect, useRef, useState, type RefObject } from "react";
+import { ViewerAudio, type ViewerAudioSnapshot } from "../../media/viewer-audio";
+import { useCopy } from "../../ui/copy";
+import { Btn } from "./primitives";
+import { Tooltip } from "./Tooltip";
+import { usePlaybackControlsVisibility } from "./use-playback-controls-visibility";
+import { leavePictureInPicture, usePictureInPicture } from "./use-picture-in-picture";
+import "./playback-controls.css";
+
+type FullscreenVideo = HTMLVideoElement & {
+ webkitEnterFullscreen?: () => void;
+};
+
+// Reflect the existing media element; binding, autoplay recovery and room
+// presentation retain their existing owners.
+export function PlaybackControls({
+ videoRef, stream, audioTrackKey, canPlay, theaterMode, onPlay,
+ onToggleTheater, onReconnect, reconnectAvailable,
+}: {
+ videoRef: RefObject<HTMLVideoElement | null>;
+ stream: MediaStream | null;
+ audioTrackKey?: string;
+ canPlay: boolean;
+ theaterMode: boolean;
+ onPlay: () => void;
+ onToggleTheater: () => void;
+ onReconnect: () => void;
+ reconnectAvailable: boolean;
+}) {
+ const { t, vis } = useCopy();
+ const audioRef = useRef<ViewerAudio | null>(null);
+ const controlsRef = useRef<HTMLDivElement | null>(null);
+ const [audio, setAudio] = useState<ViewerAudioSnapshot>({
+ level: 1, muted: false, boostAvailable: true,
+ });
+ const [paused, setPaused] = useState(true);
+ const [hasAudio, setHasAudio] = useState(false);
+ const [fullscreen, setFullscreen] = useState(false);
+ const [canFullscreen, setCanFullscreen] = useState(false);
+ const hidden = usePlaybackControlsVisibility(videoRef, controlsRef, paused || !canPlay);
+ const picture = usePictureInPicture(videoRef);
+
+ const togglePlayback = () => {
+ if (!canPlay) return;
+ const video = videoRef.current;
+ if (!video) return;
+ if (video.paused) {
+ audioRef.current?.resume();
+ onPlay();
+ } else {
+ video.pause();
+ }
+ };
+ const togglePlaybackRef = useRef(togglePlayback);
+ togglePlaybackRef.current = togglePlayback;
+
+ useEffect(() => {
+ const video = videoRef.current as FullscreenVideo | null;
+ if (!video) return;
+ const output = new ViewerAudio(video, setAudio);
+ audioRef.current = output;
+ const syncPlayback = () => setPaused(video.paused);
+ const syncFullscreen = () => setFullscreen(document.fullscreenElement === video.parentElement);
+ const onKey = (event: KeyboardEvent) => {
+ if (event.code !== "Space" || event.target !== video) return;
+ event.preventDefault();
+ togglePlaybackRef.current();
+ };
+ syncPlayback();
+ syncFullscreen();
+ setCanFullscreen(Boolean(document.fullscreenEnabled || video.webkitEnterFullscreen));
+ for (const event of ["play", "pause", "ended", "emptied"]) video.addEventListener(event, syncPlayback);
+ video.addEventListener("keydown", onKey);
+ document.addEventListener("fullscreenchange", syncFullscreen);
+ return () => {
+ output.dispose();
+ audioRef.current = null;
+ for (const event of ["play", "pause", "ended", "emptied"]) video.removeEventListener(event, syncPlayback);
+ video.removeEventListener("keydown", onKey);
+ document.removeEventListener("fullscreenchange", syncFullscreen);
+ };
+ }, [videoRef]);
+
+ useEffect(() => {
+ audioRef.current?.bind(stream);
+ const track = stream?.getAudioTracks()[0];
+ const syncAudio = () => setHasAudio(Boolean(track && track.readyState !== "ended"));
+ syncAudio();
+ track?.addEventListener("ended", syncAudio);
+ return () => track?.removeEventListener("ended", syncAudio);
+ }, [stream, audioTrackKey]);
+
+ const toggleFullscreen = () => {
+ const video = videoRef.current as FullscreenVideo | null;
+ if (fullscreen) {
+ void document.exitFullscreen().catch(() => undefined);
+ } else if (document.fullscreenEnabled && video?.parentElement) {
+ void video.parentElement.requestFullscreen()
+ .then(() => leavePictureInPicture(video))
+ .catch(() => undefined);
+ } else {
+ audioRef.current?.useNativeControls();
+ video?.webkitEnterFullscreen?.();
+ }
+ };
+ const silent = audio.muted || audio.level === 0;
+ const percent = Math.round(audio.level * 100);
+
+ return (
+ <div ref={controlsRef} className={`lr-playback${hidden ? " is-hidden" : ""}`} role="group" aria-label={t("playback.controls")}>
+ <span className="lr-playback-audio">
+ <Btn icon={paused ? "play" : "pause"}
+ draw="playback-state"
+ title={paused ? "playback.play" : "playback.pause"}
+ hint={paused ? "hint-local-play" : "hint-local-pause"}
+ disabled={!canPlay} onClick={togglePlayback} />
+ <span className="lr-playback-separator" aria-hidden="true" />
+ <Btn icon={!hasAudio || silent ? "speakerOff" : "speaker"}
+ draw="playback-sound"
+ title={!hasAudio ? "playback.noAudio" : silent ? "playback.unmute" : "playback.mute"}
+ hint={!hasAudio ? "hint-no-audio" : silent ? "hint-unmute" : "hint-mute"} disabled={!hasAudio}
+ onClick={() => {
+ if (audio.level === 0) audioRef.current?.setLevel(1);
+ audioRef.current?.setMuted(!silent);
+ }} />
+ <Tooltip kind={!hasAudio ? "hint-no-audio" : audio.boostAvailable ? "hint-volume" : "hint-volume-basic"}
+ text={vis ? undefined : t(!hasAudio ? "playback.noAudio" : audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")}
+ className="lr-playback-volume">
+ <input type="range" min={0} max={audio.boostAvailable ? 200 : 100} step={1}
+ value={percent} disabled={!hasAudio}
+ aria-label={t(audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")} aria-valuetext={`${percent}%`}
+ onChange={(event) => {
+ audioRef.current?.setLevel(Number(event.target.value) / 100);
+ audioRef.current?.setMuted(false);
+ }} />
+ </Tooltip>
+ <span className={`lr-playback-level${percent > 100 ? " is-boosted" : ""}`} aria-hidden="true">
+ {hasAudio ? `${percent}%` : "—"}
+ </span>
+ </span>
+ <span className="lr-playback-view">
+ <Btn icon="refresh" title="viewer.reconnect" hint="hint-reconnect" draw="playback-reconnect"
+ disabled={!reconnectAvailable} onClick={onReconnect} />
+ <Btn icon={picture.active ? "pipExit" : "pip"} draw="playback-pip"
+ hintTone={picture.failed ? "bad" : undefined}
+ title={picture.failed ? "playback.pipFailed" : !picture.supported ? "playback.pipUnavailable"
+ : picture.active ? "playback.exitPip" : !canPlay ? "playback.pipWaiting" : "playback.pip"}
+ hint={!picture.supported || picture.failed ? "hint-pip-unavailable" : picture.active ? "hint-pip-exit" : "hint-pip"}
+ pressed={picture.active} disabled={!picture.supported || (!picture.active && !canPlay)}
+ onClick={() => { void picture.toggle(); }} />
+ {!fullscreen ? <Btn icon={theaterMode ? "theaterExit" : "theater"}
+ draw="playback-theater"
+ title={theaterMode ? "viewer.theater.exit" : "viewer.theater"}
+ hint={theaterMode ? "hint-theater-exit" : "hint-theater"}
+ pressed={theaterMode} onClick={onToggleTheater} /> : null}
+ {canFullscreen && !theaterMode ? (
+ <Btn icon={fullscreen ? "contract" : "expand"}
+ draw="playback-fullscreen"
+ title={fullscreen ? "playback.exitFullscreen" : "playback.fullscreen"}
+ hint={fullscreen ? "hint-fullscreen-exit" : "hint-fullscreen"}
+ onClick={toggleFullscreen} />
+ ) : null}
+ </span>
+ </div>
+ );
+}
diff --git a/src/client/components/living/RoomChip.tsx b/src/client/components/living/RoomChip.tsx
index 7c6107c6..0e81ae64 100644
--- a/src/client/components/living/RoomChip.tsx
+++ b/src/client/components/living/RoomChip.tsx
@@ -5,7 +5,7 @@ import { Glyph } from "../../ui/icons";
import { useCopy } from "../../ui/copy";
import { copyRoomCode } from "../room-code";
import { Btn, Pill } from "./primitives";
-import { ComicTooltip } from "./ComicTooltip";
+import { Tooltip } from "./Tooltip";
export function Lcd({ code }: { code: string }) {
const { t, vis } = useCopy();
@@ -41,12 +41,10 @@ export function Lcd({ code }: { code: string }) {
const copyButton = (
<button
type="button"
- title={vis ? undefined : t("common.copy")}
aria-label={copyFeedback || t("common.copy")}
onClick={(event) => {
- // Hint-wrapped in vis: pointer activation must not leave the comic
- // pinned open by focus (keyboard clicks keep focus).
- if (vis && event.detail !== 0) event.currentTarget.blur();
+ // Pointer activation must not pin the hint open; keyboard keeps focus.
+ if (event.detail !== 0) event.currentTarget.blur();
void copy();
}}
>
@@ -69,7 +67,6 @@ export function Lcd({ code }: { code: string }) {
className="lr-lcd"
role="group"
aria-label={`${t("common.roomCode")} ${code}`}
- title={vis ? undefined : t("common.roomCode")}
>
<span className="lr-lcd-roll" aria-hidden="true">
{[...code].map((digit, index) => (
@@ -78,11 +75,12 @@ export function Lcd({ code }: { code: string }) {
</span>
))}
</span>
- {vis ? (
- <ComicTooltip kind="hint-copy-code">{copyButton}</ComicTooltip>
- ) : (
- copyButton
- )}
+ <Tooltip kind={copyState === "failed" ? "warning" : "hint-copy-code"}
+ tone={copyState === "copied" ? "live" : copyState === "failed" ? "bad" : "off"}
+ motion={copyState === "idle" ? "demo" : "still"}
+ text={vis ? undefined : copyFeedback || t("common.copy")}>
+ {copyButton}
+ </Tooltip>
<span className="visually-hidden" role="status" aria-live="polite">
{copyFeedback}
</span>
diff --git a/src/client/components/living/RouteTree.tsx b/src/client/components/living/RouteTree.tsx
index a0d7a5fa..a6144e63 100644
--- a/src/client/components/living/RouteTree.tsx
+++ b/src/client/components/living/RouteTree.tsx
@@ -1,15 +1,16 @@
-// The connection topology as a real tree: host (crowned) roots direct P2P
+// The connection topology as a real tree: the host roots direct P2P
// viewers and the SFU node; relay children hang off their parent viewer.
// Data comes from deriveParticipantTopology.
-import { memo, useLayoutEffect, useRef, useState } from "react";
+import { memo, useState } from "react";
import type { LabeledViewerPresence } from "../../lib/viewer-presence";
+import { useElementWidth } from "../../lib/use-element-width";
import {
deriveParticipantTopology,
type TopologyBranch,
} from "../../lib/participant-topology";
import { useCopy } from "../../ui/copy";
-import { PawnSvg } from "./Couch";
+import { PawnSvg } from "./Pawn";
import { participantColor } from "./participant-color";
import {
topologyLayoutForWidth,
@@ -83,7 +84,7 @@ function topologyVisibleLabel(
const peerIdSuffix = peerId?.slice(-6) ?? "";
const withoutRedundantRole =
peerIdSuffix &&
- (label === `👑 (${peerIdSuffix})` || label === `👤 (${peerIdSuffix})`)
+ (label === `🎮 (${peerIdSuffix})` || label === `👤 (${peerIdSuffix})`)
? peerIdSuffix
: label;
return compactVisibleLabel(withoutRedundantRole, maximumCodePoints);
@@ -118,29 +119,8 @@ export const RouteTree = memo(function RouteTree({
onSelectPeer?: (peerId: string) => void;
}) {
const { t } = useCopy();
- const routeRef = useRef<HTMLDivElement>(null);
- const [containerWidth, setContainerWidth] = useState(
- DEFAULT_TOPOLOGY_WIDTH,
- );
+ const [routeRef, containerWidth] = useElementWidth(DEFAULT_TOPOLOGY_WIDTH);
const [hoveredPeerId, setHoveredPeerId] = useState<string | null>(null);
- useLayoutEffect(() => {
- const route = routeRef.current;
- if (!route) return;
- const updateWidth = () => {
- const width = Math.round(route.getBoundingClientRect().width);
- if (width > 0) {
- setContainerWidth((current) => (current === width ? current : width));
- }
- };
- updateWidth();
- if (typeof ResizeObserver === "undefined") {
- window.addEventListener("resize", updateWidth);
- return () => window.removeEventListener("resize", updateWidth);
- }
- const observer = new ResizeObserver(updateWidth);
- observer.observe(route);
- return () => observer.disconnect();
- }, []);
const layoutConfig = topologyLayoutForWidth(containerWidth);
const topology = deriveParticipantTopology(hostPeerId, viewers);
const selectable = new Set(
@@ -221,7 +201,7 @@ export const RouteTree = memo(function RouteTree({
return { viewer, ...point };
});
- const height = Math.max(140, row * spacing + 64);
+ let height = Math.max(140, row * spacing + 64);
const rootYs = [
...(childrenOf.get(null) ?? []).map((node) => pos.get(node.key)!.y),
...(sfuPos ? [sfuPos.y] : []),
@@ -234,7 +214,7 @@ export const RouteTree = memo(function RouteTree({
? rootYs.reduce((sum, y) => sum + y, 0) / rootYs.length
: height / 2,
};
- const width = Math.max(
+ let width = Math.max(
layoutConfig.baseWidth,
...[
...pos.values(),
@@ -265,15 +245,58 @@ export const RouteTree = memo(function RouteTree({
const labelByPeer = new Map(nodes.map((node) => [node.key, node.label]));
const topologyTitleId = "room-topology-title";
- const scrollableCanvas = width > layoutConfig.baseWidth;
+ const depths = new Map([...pos].map(([key, point]) => [key,
+ Math.round((point.x - layoutConfig.hostX) / layoutConfig.columnGap)]));
+ const maxDepth = Math.max(1, ...depths.values());
+ let fittedGap = layoutConfig.columnGap;
+ // Spend spare spacing before changing orientation; keep 96px hit targets apart.
+ if (width > layoutConfig.baseWidth && (layoutConfig.baseWidth - 120) / maxDepth >= 104) {
+ fittedGap = (layoutConfig.baseWidth - 120) / maxDepth;
+ hostPos.x = 60;
+ for (const [key, point] of pos) point.x = 60 + depths.get(key)! * fittedGap;
+ if (sfuPos) sfuPos.x = 60 + fittedGap;
+ for (const point of pendingPos) point.x = 60 + fittedGap;
+ width = layoutConfig.baseWidth;
+ }
+ // Deep routes become a vertical outline at real pawn size. Every participant
+ // and actual parent edge remains present; only horizontal indentation compresses.
+ const outline = width > layoutConfig.baseWidth;
+ if (outline) {
+ const indent = Math.min(36, (layoutConfig.baseWidth - 196) / maxDepth);
+ hostPos.x = 40;
+ hostPos.y = 36;
+ let nextRow = 1;
+ for (const node of nodes) {
+ if (sfuPos && node.key === sfuChildren[0]?.key) {
+ sfuPos.x = 40 + indent;
+ sfuPos.y = 36 + nextRow++ * spacing;
+ }
+ pos.set(node.key, { x: 40 + depths.get(node.key)! * indent, y: 36 + nextRow++ * spacing });
+ }
+ for (const point of pendingPos) {
+ point.x = 40 + indent;
+ point.y = 36 + nextRow++ * spacing;
+ }
+ width = layoutConfig.baseWidth;
+ height = nextRow * spacing + 20;
+ }
+ const labelX = (point: { x: number }) => outline ? point.x + 28 : point.x;
+ const labelY = (point: { y: number }) => outline ? point.y + 4 : pawnLabelY(point.y, PAWN_SCALE);
+ const labelAnchor = outline ? "start" : "middle";
+ const labelLimit = (point: { x: number }) => outline
+ ? Math.min(layoutConfig.maxVisibleLabelCodePoints, Math.floor((width - point.x - 40) / 11))
+ : Math.min(layoutConfig.maxVisibleLabelCodePoints, Math.floor((fittedGap - 12) / 11));
+ const linkPath = (parent: { x: number; y: number }, child: { x: number; y: number }) => outline
+ ? `M ${parent.x - 17} ${parent.y} H ${parent.x - 28} V ${child.y} H ${child.x - 18}`
+ : `M ${parent.x + 20} ${parent.y} Q ${(parent.x + child.x) / 2} ${parent.y + (child.y - parent.y) * 0.55}, ${child.x - 18} ${child.y}`;
const sfuChildPoints = sfuChildren.map((child) => ({
child,
point: pos.get(child.key)!,
}));
const sfuRail =
- sfuPos && sfuChildPoints.length > 1
+ !outline && sfuPos && sfuChildPoints.length > 1
? {
- x: sfuPos.x + layoutConfig.columnGap * 0.45,
+ x: sfuPos.x + fittedGap * 0.45,
minY: Math.min(...sfuChildPoints.map(({ point }) => point.y)),
maxY: Math.max(...sfuChildPoints.map(({ point }) => point.y)),
}
@@ -282,7 +305,7 @@ export const RouteTree = memo(function RouteTree({
return (
<div
ref={routeRef}
- className="lr-route"
+ className={`lr-route${outline ? " is-outline" : ""}`}
role="group"
aria-labelledby={topologyTitleId}
id="room-topology"
@@ -296,14 +319,7 @@ export const RouteTree = memo(function RouteTree({
aria-hidden={onSelectPeer ? undefined : true}
aria-label={onSelectPeer ? t("host.topology") : undefined}
focusable={onSelectPeer ? undefined : "false"}
- style={
- scrollableCanvas
- ? { width, maxWidth: "none" }
- : {
- width: "100%",
- maxWidth: nodes.length > 10 ? layoutConfig.baseWidth : 880,
- }
- }
+ style={{ width: "100%", maxWidth: outline || nodes.length > 10 ? layoutConfig.baseWidth : 880 }}
>
{nodes
.filter((node) => !node.sfu)
@@ -313,7 +329,7 @@ export const RouteTree = memo(function RouteTree({
return (
<path
key={`edge-${node.key}`}
- d={`M ${parent.x + 20} ${parent.y} Q ${(parent.x + point.x) / 2} ${parent.y + (point.y - parent.y) * 0.55}, ${point.x - 18} ${point.y}`}
+ d={linkPath(parent, point)}
className={edgeClass("p2p", node.ready)}
/>
);
@@ -322,10 +338,11 @@ export const RouteTree = memo(function RouteTree({
{sfuPos ? (
<>
<path
- d={`M ${hostPos.x + 20} ${hostPos.y} L ${sfuPos.x - 20} ${sfuPos.y}`}
+ d={linkPath(hostPos, sfuPos)}
className={edgeClass("sfu")}
/>
- {sfuChildren.length === 1 ? (
+ {outline ? sfuChildPoints.map(({ child, point }) => <path key={`edge-${child.key}`}
+ d={linkPath(sfuPos!, point)} className={edgeClass("sfu", child.ready)} />) : sfuChildren.length === 1 ? (
<path
d={`M ${sfuPos.x + 20} ${sfuPos.y} L ${pos.get(sfuChildren[0]!.key)!.x - 18} ${pos.get(sfuChildren[0]!.key)!.y}`}
className={edgeClass("sfu", sfuChildren[0]!.ready)}
@@ -355,7 +372,7 @@ export const RouteTree = memo(function RouteTree({
{pendingPos.map((point) => (
<path
key={`edge-pending-${point.viewer.peerId}`}
- d={`M ${hostPos.x + 20} ${hostPos.y} Q ${(hostPos.x + point.x) / 2} ${hostPos.y + (point.y - hostPos.y) * 0.55}, ${point.x - 18} ${point.y}`}
+ d={linkPath(hostPos, point)}
className="lr-route-edge is-pending"
/>
))}
@@ -366,19 +383,20 @@ export const RouteTree = memo(function RouteTree({
>
<PawnSvg
color={participantColor(hostPeerId ?? hostIdentity ?? "host-pending")}
- crown
+ identity={hostPeerId ?? hostIdentity ?? undefined}
+ host
/>
</g>
<text
className="lr-route-label is-host"
- x={hostPos.x}
- y={pawnLabelY(hostPos.y, PAWN_SCALE)}
- textAnchor="middle"
+ x={labelX(hostPos)}
+ y={labelY(hostPos)}
+ textAnchor={labelAnchor}
>
{topologyVisibleLabel(
hostLabel,
hostPeerId,
- layoutConfig.maxVisibleLabelCodePoints,
+ labelLimit(hostPos),
)}
</text>
@@ -393,9 +411,9 @@ export const RouteTree = memo(function RouteTree({
</g>
<text
className="lr-route-label is-sfu"
- x={sfuPos.x}
- y={sfuPos.y + 32}
- textAnchor="middle"
+ x={labelX(sfuPos)}
+ y={outline ? sfuPos.y + 4 : sfuPos.y + 32}
+ textAnchor={labelAnchor}
>
SFU
</text>
@@ -412,7 +430,7 @@ export const RouteTree = memo(function RouteTree({
className={`lr-route-node${node.ready ? "" : " is-recovering"}${hovered ? " is-hovered" : ""}${selected ? " is-selected" : ""}`}
transform={`translate(${centeredPawnX(point.x, PAWN_SCALE)}, ${centeredPawnY(point.y, PAWN_SCALE)}) scale(${PAWN_SCALE})`}
>
- <PawnSvg color={participantColor(node.key)} />
+ <PawnSvg color={participantColor(node.key)} identity={node.key} />
{hovered && !selected ? (
<PawnOutline className="lr-route-hover" />
) : null}
@@ -435,7 +453,7 @@ export const RouteTree = memo(function RouteTree({
className={`lr-route-node is-recovering${hovered ? " is-hovered" : ""}${selected ? " is-selected" : ""}`}
transform={`translate(${centeredPawnX(point.x, PAWN_SCALE)}, ${centeredPawnY(point.y, PAWN_SCALE)}) scale(${PAWN_SCALE})`}
>
- <PawnSvg color={participantColor(point.viewer.peerId)} />
+ <PawnSvg color={participantColor(point.viewer.peerId)} identity={point.viewer.peerId} />
{hovered && !selected ? (
<PawnOutline className="lr-route-hover" />
) : null}
@@ -455,14 +473,14 @@ export const RouteTree = memo(function RouteTree({
<text
key={`label-${node.key}`}
className={`lr-route-label${hoveredPeerId === node.key ? " is-hovered" : ""}${selectedPeerId === node.key ? " is-selected" : ""}`}
- x={point.x}
- y={pawnLabelY(point.y, PAWN_SCALE)}
- textAnchor="middle"
+ x={labelX(point)}
+ y={labelY(point)}
+ textAnchor={labelAnchor}
>
{topologyVisibleLabel(
node.label,
node.key,
- layoutConfig.maxVisibleLabelCodePoints,
+ labelLimit(point),
)}
</text>
);
@@ -471,14 +489,14 @@ export const RouteTree = memo(function RouteTree({
<text
key={`label-pending-${point.viewer.peerId}`}
className={`lr-route-label is-recovering${hoveredPeerId === point.viewer.peerId ? " is-hovered" : ""}${selectedPeerId === point.viewer.peerId ? " is-selected" : ""}`}
- x={point.x}
- y={pawnLabelY(point.y, PAWN_SCALE)}
- textAnchor="middle"
+ x={labelX(point)}
+ y={labelY(point)}
+ textAnchor={labelAnchor}
>
{topologyVisibleLabel(
point.viewer.label,
point.viewer.peerId,
- layoutConfig.maxVisibleLabelCodePoints,
+ labelLimit(point),
)}
</text>
))}
@@ -496,11 +514,11 @@ export const RouteTree = memo(function RouteTree({
<rect
key={`hit-${node.key}`}
className="lr-route-hit"
- x={point.x - 48}
+ x={outline ? point.x - 24 : point.x - 48}
// Bound the target to the row pitch: a taller rect would cover
// the next row's label and steal its clicks (later rect wins).
y={point.y - 26}
- width={96}
+ width={outline ? width - point.x + 16 : 96}
height={spacing}
rx={12}
role="button"
diff --git a/src/client/components/living/Stage.tsx b/src/client/components/living/Stage.tsx
index a766e722..b67575e8 100644
--- a/src/client/components/living/Stage.tsx
+++ b/src/client/components/living/Stage.tsx
@@ -1,26 +1,25 @@
-// The TV stage: frame, screen, chin LED. Pages render their own <video>
+// The TV stage: frame, screen, status slot. Pages render their own <video>
// (stream binding stays with the page); overlays and the connecting
// storyboard are provided here.
import type { ReactNode } from "react";
import { Glyph, type GlyphName } from "../../ui/icons";
import { useCopy, type CopyKey } from "../../ui/copy";
import { Comic, type ComicKind } from "./Comic";
+import type { ComicTone } from "./comic-presentation";
import { BrandLoader, BrandMark } from "./BrandMark";
-export type ChinState = "off" | "on" | "warn" | "bad" | "busy";
-
export function StageTv({
- chin,
hasEntry,
live,
children,
label,
+ indicator,
}: {
- chin: ChinState;
hasEntry?: boolean;
live?: boolean;
children: ReactNode;
label: string;
+ indicator?: ReactNode;
}) {
return (
<div className="lr-tv">
@@ -31,9 +30,7 @@ export function StageTv({
>
{children}
</div>
- <div className="lr-tv-chin">
- <i className={chin === "off" ? "" : `is-${chin}`} />
- </div>
+ <div className="lr-tv-chin">{indicator}</div>
</div>
);
}
@@ -88,6 +85,7 @@ export function StageOverlay({
transition,
spin,
comic,
+ tone,
progress,
onActivate,
}: {
@@ -97,6 +95,7 @@ export function StageOverlay({
transition?: boolean;
spin?: boolean;
comic?: ComicKind;
+ tone?: ComicTone;
progress?: string;
onActivate?: () => void;
}) {
@@ -107,7 +106,8 @@ export function StageOverlay({
(Boolean(spin) || comic === "waiting-for-host" || comic === "recovering"));
const content = (
<>
- {vis && comic ? <Comic kind={comic} theme="stage" /> : null}
+ {vis && comic ? <Comic kind={comic} theme="stage" tone={tone}
+ motion={transition || spin ? "progress" : undefined} /> : null}
<span className="lr-tv-status-content">
{showMascot ? (
<BrandLoader />
@@ -136,7 +136,7 @@ export function StageOverlay({
return (
<div
// Passive state layer: it must not intercept clicks meant for the
- // native <video> controls it covers (it owns no controls itself).
+ // playback controls it covers (it owns no controls itself).
className={`lr-tv-overlay is-passive${dim ? " is-dim" : ""}${vis && comic ? " has-comic" : ""}`}
role="status"
aria-label={message}
diff --git a/src/client/components/living/StatusIndicator.tsx b/src/client/components/living/StatusIndicator.tsx
new file mode 100644
index 00000000..88e8a78f
--- /dev/null
+++ b/src/client/components/living/StatusIndicator.tsx
@@ -0,0 +1,31 @@
+import type { StatusDescriptor } from "../../ui/media-status";
+import { useCopy } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
+import { Tooltip } from "./Tooltip";
+import "./status-indicator.css";
+
+/** One icon for one status; text and visual hints explain the same fact. */
+export function StatusIndicator({ status, label }: {
+ status: StatusDescriptor;
+ label?: string;
+}) {
+ const { vis, t } = useCopy();
+ const hint = status.tooltip ?? status.comic;
+ const text = label ?? t(status.labelKey);
+ const indicator = (
+ <span
+ className="lr-status-indicator"
+ data-tone={status.tone}
+ data-pulse={status.pulse || undefined}
+ role="img"
+ aria-label={text}
+ tabIndex={!vis || hint ? 0 : undefined}
+ >
+ <Glyph name={status.icon} size={17} />
+ </span>
+ );
+ return !vis || hint
+ ? <Tooltip kind={hint} tone={status.tone} motion={status.pulse ? "progress" : undefined}
+ text={vis ? undefined : text}>{indicator}</Tooltip>
+ : indicator;
+}
diff --git a/src/client/components/living/ComicTooltip.tsx b/src/client/components/living/Tooltip.tsx
similarity index 65%
rename from src/client/components/living/ComicTooltip.tsx
rename to src/client/components/living/Tooltip.tsx
index 45b76a4f..ebc8e364 100644
--- a/src/client/components/living/ComicTooltip.tsx
+++ b/src/client/components/living/Tooltip.tsx
@@ -1,4 +1,4 @@
-// Comic tooltip: a floating paper panel showing a panel comic above (or below)
+// Shared tooltip: a floating paper panel showing text or a comic above (or below)
// its trigger. Visibility is three-channel, matching platform conventions:
// hover on fine pointers, keyboard focus via :has(:focus-visible), and the
// Material long-press on touch (500ms hold → open, ~1.5s after release →
@@ -6,25 +6,30 @@
// Alignment: the align prop is a desktop-tuned preference; whenever a show
// channel opens, the trigger's live viewport position is measured and
// start/center/end is re-picked so the panel never clips off-screen (rows
-// wrap at narrow widths, so a static choice cannot hold). The caret lives on
-// the wrapper, so it stays centered on the trigger whatever the panel picks.
+// wrap at narrow widths, so a static choice cannot hold). The native top layer
+// avoids clipping by scrolling lists; the caret points back to the trigger.
// Styling in styles.css under "comic tooltip" / "glyph draw-in". SSR-safe:
// handlers only run in the browser.
import {
+ cloneElement,
isValidElement,
useEffect,
+ useId,
+ useLayoutEffect,
useRef,
useState,
+ type CSSProperties,
type ReactNode,
} from "react";
import { Comic, type ComicKind } from "./Comic";
import { HintComic, isHintKind, type HintKind } from "./hints";
import { isCopyKey, say } from "../../ui/copy";
+import { comicStyle, getComicPresentation, type ComicTone, type ComicMotion } from "./comic-presentation";
const LONG_PRESS_MS = 500;
const TOUCH_HIDE_MS = 1500;
-const COMIC_EXIT_MS = 160;
+const PANEL_EXIT_MS = 160;
// Minimum clearance the re-picked alignment keeps to each viewport edge.
const EDGE_MARGIN = 8;
// Paper panel before it is measured: 240-wide comic strip plus its padding.
@@ -32,60 +37,71 @@ const FALLBACK_PANEL_HEIGHT = 96;
type Align = "center" | "start" | "end";
-export function ComicTooltip({
+export function Tooltip({
kind,
+ text,
+ tone,
+ motion,
+ className,
place = "above",
align = "center",
children,
}: {
- kind: ComicKind | HintKind;
+ kind?: ComicKind | HintKind;
+ text?: string;
+ tone?: ComicTone;
+ motion?: ComicMotion;
+ className?: string;
/** below = for controls pinned to the viewport top (header). */
place?: "above" | "below";
/** Preferred alignment; re-picked at open time if it would clip off-screen. */
align?: Align;
children: ReactNode;
}) {
+ const defaults = getComicPresentation(kind);
+ const resolvedTone = tone ?? defaults.tone;
+ const resolvedMotion = motion ?? defaults.motion;
+ const tooltipId = useId();
const wrapRef = useRef<HTMLSpanElement | null>(null);
const tipRef = useRef<HTMLSpanElement | null>(null);
const pressTimer = useRef<number | null>(null);
const hideTimer = useRef<number | null>(null);
- const comicUnmountTimer = useRef<number | null>(null);
+ const panelUnmountTimer = useRef<number | null>(null);
const longPressed = useRef(false);
const pressPoint = useRef<{ x: number; y: number } | null>(null);
const [hoverOpen, setHoverOpen] = useState(false);
const [focusOpen, setFocusOpen] = useState(false);
const [touchOpen, setTouchOpen] = useState(false);
- const [comicMounted, setComicMounted] = useState(false);
- const [liveAlign, setLiveAlign] = useState<Align | null>(null);
- const [livePlace, setLivePlace] = useState<"above" | "below" | null>(null);
+ const [panelMounted, setPanelMounted] = useState(false);
+ const [position, setPosition] = useState({ left: 0, top: 0, caret: 0, below: place === "below" });
// True while the current gesture is a touch, so contextmenu can tell a
// long-press from a mouse right-click without reading vendor event fields.
const touchGesture = useRef(false);
const interactionOpen = hoverOpen || focusOpen || touchOpen;
- const disabledTrigger =
- isValidElement<{
+ const trigger = isValidElement<{
disabled?: boolean;
"aria-label"?: string;
+ "aria-describedby"?: string;
label?: string;
title?: string;
- }>(children) &&
- children.props.disabled === true;
- const rawDisabledTriggerLabel = disabledTrigger
- ? children.props["aria-label"] ??
- children.props.label ??
- children.props.title
+ }>(children) ? children : null;
+ const disabledTrigger = trigger?.props.disabled === true;
+ const rawDisabledTriggerLabel = disabledTrigger && trigger
+ ? trigger.props["aria-label"] ??
+ trigger.props.label ??
+ trigger.props.title
: undefined;
const disabledTriggerLabel =
rawDisabledTriggerLabel && isCopyKey(rawDisabledTriggerLabel)
? say(rawDisabledTriggerLabel)
: rawDisabledTriggerLabel;
- const mountComic = () => {
- if (comicUnmountTimer.current !== null) {
- window.clearTimeout(comicUnmountTimer.current);
- comicUnmountTimer.current = null;
+ const mountPanel = () => {
+ if (panelUnmountTimer.current !== null) {
+ window.clearTimeout(panelUnmountTimer.current);
+ panelUnmountTimer.current = null;
}
- setComicMounted(true);
+ setPanelMounted(true);
};
// Re-pick alignment from the trigger's live geometry. The configured align
@@ -98,24 +114,23 @@ export function ComicTooltip({
const vw = window.innerWidth;
if (!vw) return; // no layout (SSR/test): keep the prop alignment
const rect = wrap.getBoundingClientRect();
- const measured = comicMounted ? (tipRef.current?.offsetWidth ?? 0) : 0;
+ const measured = panelMounted ? (tipRef.current?.offsetWidth ?? 0) : 0;
const width = Math.max(0, Math.min(measured || 320, vw - EDGE_MARGIN * 2));
// Same idea vertically: a control scrolled near the top has no room above,
// and the panel would be cut off by the viewport edge.
const vh = window.innerHeight;
const panelHeight =
- (comicMounted ? tipRef.current?.offsetHeight : 0) || FALLBACK_PANEL_HEIGHT;
+ (panelMounted ? tipRef.current?.offsetHeight : 0) || FALLBACK_PANEL_HEIGHT;
const fitsAbove = rect.top - panelHeight - EDGE_MARGIN >= 0;
const fitsBelow = !vh || rect.bottom + panelHeight + EDGE_MARGIN <= vh;
- setLivePlace(
+ const livePlace =
place === "above"
? fitsAbove || !fitsBelow
? "above"
: "below"
: fitsBelow || !fitsAbove
? "below"
- : "above",
- );
+ : "above";
const center = rect.left + rect.width / 2;
const boxes: Record<Align, { left: number; right: number }> = {
center: { left: center - width / 2, right: center + width / 2 },
@@ -130,10 +145,14 @@ export function ComicTooltip({
...(["center", "start", "end"] as Align[]).filter((a) => a !== align),
];
const fits = order.find((a) => clipped(boxes[a]) === 0);
- setLiveAlign(
- fits ??
- order.reduce((a, b) => (clipped(boxes[a]) <= clipped(boxes[b]) ? a : b)),
- );
+ const selected = fits ?? order.reduce((a, b) => (clipped(boxes[a]) <= clipped(boxes[b]) ? a : b));
+ const left = Math.max(EDGE_MARGIN, Math.min(boxes[selected].left, vw - width - EDGE_MARGIN));
+ setPosition({
+ left,
+ top: livePlace === "below" ? rect.bottom + EDGE_MARGIN : rect.top - panelHeight - EDGE_MARGIN,
+ caret: Math.max(14, Math.min(center - left, width - 14)),
+ below: livePlace === "below",
+ });
};
// Single owner of panel placement: while the tooltip may be open (hover,
@@ -141,8 +160,19 @@ export function ComicTooltip({
// the panel stays inside the viewport mid-open — no page-level clamps.
const pickAlignRef = useRef(pickAlign);
pickAlignRef.current = pickAlign;
+ useLayoutEffect(() => {
+ const tip = tipRef.current;
+ if (panelMounted) {
+ // Native top layer escapes couch, table and source-list overflow without
+ // a portal or a second set of trigger/interaction owners.
+ tip?.showPopover?.();
+ pickAlignRef.current();
+ } else {
+ tip?.hidePopover?.();
+ }
+ }, [panelMounted, text, kind]);
useEffect(() => {
- if (!interactionOpen || !comicMounted) return;
+ if (!interactionOpen || !panelMounted) return;
let frame = 0;
const schedulePick = () => {
window.cancelAnimationFrame(frame);
@@ -156,28 +186,41 @@ export function ComicTooltip({
window.removeEventListener("resize", schedulePick);
window.removeEventListener("scroll", schedulePick, true);
};
- }, [comicMounted, interactionOpen]);
+ }, [panelMounted, interactionOpen, text, kind]);
useEffect(() => {
- if (interactionOpen || !comicMounted) return;
- comicUnmountTimer.current = window.setTimeout(() => {
- comicUnmountTimer.current = null;
- setComicMounted(false);
- }, COMIC_EXIT_MS);
+ if (!interactionOpen) return;
+ // Hover does not move keyboard focus into the trigger.
+ const dismiss = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ setHoverOpen(false);
+ setTouchOpen(false);
+ setFocusOpen(false);
+ };
+ document.addEventListener("keydown", dismiss);
+ return () => document.removeEventListener("keydown", dismiss);
+ }, [interactionOpen]);
+
+ useEffect(() => {
+ if (interactionOpen || !panelMounted) return;
+ panelUnmountTimer.current = window.setTimeout(() => {
+ panelUnmountTimer.current = null;
+ setPanelMounted(false);
+ }, PANEL_EXIT_MS);
return () => {
- if (comicUnmountTimer.current !== null) {
- window.clearTimeout(comicUnmountTimer.current);
- comicUnmountTimer.current = null;
+ if (panelUnmountTimer.current !== null) {
+ window.clearTimeout(panelUnmountTimer.current);
+ panelUnmountTimer.current = null;
}
};
- }, [comicMounted, interactionOpen]);
+ }, [panelMounted, interactionOpen]);
useEffect(
() => () => {
if (pressTimer.current !== null) window.clearTimeout(pressTimer.current);
if (hideTimer.current !== null) window.clearTimeout(hideTimer.current);
- if (comicUnmountTimer.current !== null) {
- window.clearTimeout(comicUnmountTimer.current);
+ if (panelUnmountTimer.current !== null) {
+ window.clearTimeout(panelUnmountTimer.current);
}
},
[],
@@ -202,20 +245,18 @@ export function ComicTooltip({
}
};
- const placeClass = (livePlace ?? place) === "below" ? " is-below" : "";
- const shownAlign = liveAlign ?? align;
- const alignClass =
- shownAlign === "start" ? " is-start" : shownAlign === "end" ? " is-end" : "";
+ const placeClass = position.below ? " is-below" : "";
return (
<span
ref={wrapRef}
- className={`lr-comic-tip-wrap${disabledTrigger ? " is-disabled-trigger" : ""}${hoverOpen ? " is-hover-open" : ""}${focusOpen ? " is-focus-open" : ""}${touchOpen ? " is-tip-open" : ""}`}
+ className={`lr-comic-tip-wrap${className ? ` ${className}` : ""}${disabledTrigger ? " is-disabled-trigger" : ""}${hoverOpen ? " is-hover-open" : ""}${focusOpen ? " is-focus-open" : ""}${touchOpen ? " is-tip-open" : ""}`}
tabIndex={disabledTrigger ? 0 : undefined}
aria-label={disabledTriggerLabel}
+ aria-describedby={disabledTrigger && text && interactionOpen ? tooltipId : undefined}
onPointerEnter={(event) => {
pickAlign();
if (event.pointerType !== "touch") {
- mountComic();
+ mountPanel();
setHoverOpen(true);
}
}}
@@ -225,7 +266,7 @@ export function ComicTooltip({
onFocus={(event) => {
pickAlign();
if ((event.target as HTMLElement).matches(":focus-visible")) {
- mountComic();
+ mountPanel();
setFocusOpen(true);
}
}}
@@ -245,7 +286,7 @@ export function ComicTooltip({
pressTimer.current = window.setTimeout(() => {
pressTimer.current = null;
longPressed.current = true;
- mountComic();
+ mountPanel();
pickAlign();
setTouchOpen(true);
}, LONG_PRESS_MS);
@@ -305,22 +346,25 @@ export function ComicTooltip({
}
}}
onKeyDown={(event) => {
- if (event.key === "Escape") {
- setHoverOpen(false);
- setTouchOpen(false);
- setFocusOpen(false);
- } else if ((event.target as HTMLElement).matches(":focus-visible")) {
- mountComic();
+ if (event.key !== "Escape" && (event.target as HTMLElement).matches(":focus-visible")) {
+ mountPanel();
setFocusOpen(true);
}
}}
>
- {children}
- <span ref={tipRef} className={`lr-comic-tip${placeClass}${alignClass}`} role="note">
- {comicMounted
- ? isHintKind(kind)
- ? <HintComic kind={kind} size={240} />
- : <Comic kind={kind} theme="paper" size={240} />
+ {trigger && text ? cloneElement(trigger, {
+ "aria-describedby": [trigger.props["aria-describedby"], interactionOpen ? tooltipId : undefined].filter(Boolean).join(" ") || undefined,
+ }) : children}
+ <span ref={tipRef} id={tooltipId} popover="manual"
+ data-tone={resolvedTone}
+ style={{ ...comicStyle(resolvedTone, resolvedMotion), left: position.left, top: position.top, "--tooltip-caret": `${position.caret}px` } as CSSProperties}
+ className={`lr-comic-tip${text !== undefined ? " is-text" : ""}${placeClass}`} role="tooltip" aria-hidden={!interactionOpen}>
+ {panelMounted
+ ? text ?? (kind
+ ? isHintKind(kind)
+ ? <HintComic kind={kind} size={240} tone={resolvedTone} motion={resolvedMotion} />
+ : <Comic kind={kind} theme="paper" size={240} tone={resolvedTone} motion={resolvedMotion} />
+ : null)
: null}
</span>
</span>
diff --git a/src/client/components/living/ViewerOverview.tsx b/src/client/components/living/ViewerOverview.tsx
index adda0821..7af9c05f 100644
--- a/src/client/components/living/ViewerOverview.tsx
+++ b/src/client/components/living/ViewerOverview.tsx
@@ -2,14 +2,15 @@ import type { ConnectionMetrics } from "../../types";
import { formatPacketLossPercent } from "../connection-details";
import { Glyph, type GlyphName } from "../../ui/icons";
import { useCopy, type CopyKey } from "../../ui/copy";
-import { PawnSvg } from "./Couch";
+import { PawnSvg } from "./Pawn";
import { participantColor } from "./participant-color";
+import type { StatusDescriptor } from "../../ui/media-status";
+import { Tooltip } from "./Tooltip";
export interface ViewerOverviewEntry {
key: string;
name: string;
- connected: boolean;
- statusLabel: string;
+ status: StatusDescriptor;
route: "p2p" | "sfu" | null;
metrics: ConnectionMetrics | null;
}
@@ -36,7 +37,7 @@ export function ViewerOverview({
): string =>
finite(value ?? null) ? `${value!.toFixed(digits)}${unit}` : unknown;
const heading = (key: CopyKey, icon: GlyphName) => (
- <span title={vis ? t(key) : undefined} aria-label={t(key)}>
+ <span aria-label={t(key)}>
{vis ? <Glyph name={icon} size={14} /> : t(key)}
</span>
);
@@ -59,6 +60,8 @@ export function ViewerOverview({
</div>
<div className="lr-viewer-overview-body">
{entries.map((entry) => {
+ const statusLabel = t(entry.status.labelKey);
+ const hint = entry.status.tooltip ?? entry.status.comic;
const metrics = entry.metrics;
const resolution = metrics?.resolution ?? unknown;
const fps = numberValue(metrics?.framesPerSecond, 1);
@@ -73,23 +76,23 @@ export function ViewerOverview({
: entry.route === "p2p"
? "P2P"
: "—";
- return (
+ const row = (
<button
- key={entry.key}
type="button"
className={`lr-viewer-overview-row${selectedKey === entry.key ? " is-selected" : ""}`}
aria-pressed={selectedKey === entry.key}
- aria-label={`${entry.name} · ${entry.statusLabel} · ${route}`}
+ aria-label={`${entry.name} · ${statusLabel} · ${route}`}
onClick={() => onSelect(entry.key)}
>
- <span className="lr-viewer-overview-person" title={entry.statusLabel}>
+ <span className="lr-viewer-overview-person">
<span className="lr-viewer-overview-pawn">
- <PawnSvg color={participantColor(entry.key)} />
- <i className={entry.connected ? "" : "is-wait"} aria-hidden="true" />
+ <PawnSvg color={participantColor(entry.key)} identity={entry.key} />
+ <i className="lr-pawn-led" data-tone={entry.status.tone}
+ data-pulse={entry.status.pulse || undefined} aria-hidden="true" />
</span>
<span className="lr-viewer-overview-person-copy">
<b>{entry.name}</b>
- {vis ? null : <small>{entry.statusLabel}</small>}
+ {vis ? null : <small>{statusLabel}</small>}
</span>
</span>
<span className={`lr-viewer-overview-route is-${entry.route ?? "pending"}`}>
@@ -124,6 +127,19 @@ export function ViewerOverview({
<span>{rtt}</span>
</button>
);
+ return (
+ <Tooltip
+ key={entry.key}
+ className="lr-overview-row-hint"
+ kind={hint}
+ tone={entry.status.tone}
+ motion={entry.status.pulse ? "progress" : undefined}
+ text={vis ? hint ? undefined : entry.name : `${entry.name} · ${statusLabel}`}
+ align="start"
+ >
+ {row}
+ </Tooltip>
+ );
})}
</div>
</div>
diff --git a/src/client/components/living/WelcomeLine.tsx b/src/client/components/living/WelcomeLine.tsx
new file mode 100644
index 00000000..7754a90a
--- /dev/null
+++ b/src/client/components/living/WelcomeLine.tsx
@@ -0,0 +1,62 @@
+import { useState } from "react";
+import { useCopy, type CopyKey } from "../../ui/copy";
+import { Glyph, type GlyphName } from "../../ui/icons";
+
+export const WELCOME_LINES = [
+ { key: "welcome.seat", symbols: ["couch", "heart"] },
+ { key: "welcome.player", symbols: ["gamepad", "users"] },
+ { key: "welcome.cut", symbols: ["clock", "clapperboard"] },
+ { key: "welcome.quest", symbols: ["branch", "heart"] },
+ { key: "welcome.snack", symbols: ["popcorn", "play"] },
+ { key: "welcome.scene", symbols: ["clapperboard", "arrowRight"] },
+ { key: "welcome.save", symbols: ["save", "moon"] },
+ { key: "welcome.achievement", symbols: ["trophy", "heart"] },
+ { key: "welcome.popcorn", symbols: ["zap", "popcorn"] },
+ { key: "welcome.credits", symbols: ["clapperboard", "gift"] },
+ { key: "welcome.replay", symbols: ["refresh", "users"] },
+ { key: "welcome.guide", symbols: ["arrowRight", "couch"] },
+ { key: "welcome.wander", symbols: ["mountain", "branch"] },
+ { key: "welcome.witness", symbols: ["tv", "eye"] },
+ { key: "welcome.discovery", symbols: ["bulb", "eye"] },
+ { key: "welcome.party", symbols: ["cast", "users"] },
+ { key: "welcome.director", symbols: ["clapperboard", "play"] },
+ { key: "welcome.next", symbols: ["flag", "users"] },
+ { key: "welcome.share", symbols: ["cast", "heart"] },
+ { key: "welcome.seats", symbols: ["couch", "users"] },
+] as const satisfies readonly { key: CopyKey; symbols: readonly [GlyphName, GlyphName] }[];
+
+// Original 5x5 pseudo-letters; recurring ideas keep the same pixel word.
+const PIXEL_LETTERS = [
+ [31, 17, 21, 17, 31], [4, 14, 21, 4, 10], [17, 31, 4, 14, 4],
+ [14, 10, 31, 4, 4], [17, 17, 31, 4, 14], [31, 4, 14, 17, 31],
+ [4, 31, 10, 14, 17], [21, 14, 4, 14, 21], [31, 16, 23, 17, 31],
+ [14, 4, 31, 17, 14], [17, 14, 4, 31, 4], [31, 1, 15, 8, 31],
+];
+
+function PixelWord({ symbol }: { symbol: GlyphName }) {
+ const seed = Array.from(symbol).reduce((sum, char) => sum + char.charCodeAt(0), 0);
+ return <svg width="40" height="14" viewBox="0 0 34 12" fill="currentColor" aria-hidden="true">
+ {[0, 1, 2].map(letter => PIXEL_LETTERS[(seed * 7 + letter * 5) % PIXEL_LETTERS.length]!.map((row, y) =>
+ [0, 1, 2, 3, 4].map(x => row & (1 << x)
+ ? <rect key={`${letter}-${x}-${y}`} x={letter * 12 + x * 2} y={y * 2 + 1} width="1.5" height="1.5" rx=".3" />
+ : null)))}
+ </svg>;
+}
+
+export function WelcomeCipher({ line }: { line: number }) {
+ const { symbols } = WELCOME_LINES[line]!;
+ return <span className="lr-welcome-cipher" aria-hidden="true">
+ <Glyph name={symbols[0]} size={18} /><PixelWord symbol={symbols[0]} />
+ <i />
+ <Glyph name={symbols[1]} size={18} /><PixelWord symbol={symbols[1]} />
+ </span>;
+}
+
+/** One original opening line per visit; never a loading or connection claim. */
+export function WelcomeLine() {
+ const { t, vis } = useCopy();
+ const [line] = useState(() => Math.floor(Math.random() * WELCOME_LINES.length));
+ return <p className={`lr-welcome${vis ? " is-cipher" : ""}`} aria-hidden={vis || undefined}>
+ {vis ? <WelcomeCipher line={line} /> : t(WELCOME_LINES[line]!.key)}
+ </p>;
+}
diff --git a/src/client/components/living/brand-mark.css b/src/client/components/living/brand-mark.css
new file mode 100644
index 00000000..9dc8b745
--- /dev/null
+++ b/src/client/components/living/brand-mark.css
@@ -0,0 +1,170 @@
+.lr-brand-mark {
+ display: block;
+ flex: 0 0 auto;
+ overflow: visible;
+}
+.lr-brand-loader {
+ display: grid;
+ width: 88px;
+ height: 88px;
+ place-items: center;
+ color: currentColor;
+}
+.lr-brand-eye-open,
+.lr-brand-sparkles { opacity: 0; }
+.lr-brand-sparkles > * { opacity: 0; }
+
+.lr-brand-mark.is-animated,
+.lr-brand-mark.is-once {
+ transform-box: fill-box;
+ transform-origin: center;
+}
+.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) {
+ animation: lr-brand-bob 1.6s cubic-bezier(.3, .8, .35, 1) 1 both;
+}
+.lr-brand-mark.is-animated.is-loop-active {
+ animation: lr-brand-bob-loop 3.6s cubic-bezier(.3, .8, .35, 1) infinite;
+}
+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell > * {
+ stroke-dasharray: 1;
+ stroke-dashoffset: 1;
+ animation: lr-brand-draw cubic-bezier(.45, .05, .35, 1) forwards;
+}
+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-frame { animation-duration: 380ms; }
+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-antenna {
+ animation-duration: 260ms;
+ animation-delay: 260ms;
+}
+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-feet {
+ animation-duration: 220ms;
+ animation-delay: 360ms;
+}
+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-face {
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: lr-brand-face-in 180ms ease-out 500ms both;
+}
+.lr-brand-mark.is-animated.is-loop-active .lr-brand-eye-open {
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: lr-brand-eye-open-loop 3.6s ease-in-out infinite;
+}
+.lr-brand-mark.is-animated.is-loop-active .lr-brand-eye-wink {
+ animation: lr-brand-eye-wink-loop 3.6s ease-in-out infinite;
+}
+.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles { opacity: 1; }
+.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles > * {
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: lr-brand-sparkle-loop 3.6s cubic-bezier(.3, 1.45, .45, 1) infinite both;
+}
+.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles > :nth-child(2) {
+ animation-name: lr-brand-sparkle-alt-loop;
+ animation-delay: 90ms;
+}
+.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-open {
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: lr-brand-eye-open 1.6s ease-in-out 1 both;
+}
+.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-wink {
+ animation: lr-brand-eye-wink 1.6s ease-in-out 1 both;
+}
+.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles { opacity: 1; }
+.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > * {
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: lr-brand-sparkle 1.6s cubic-bezier(.3, 1.45, .45, 1) 1 both;
+}
+.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > :nth-child(2) {
+ animation-name: lr-brand-sparkle-alt;
+ animation-delay: 45ms;
+}
+@keyframes lr-brand-draw { to { stroke-dashoffset: 0; } }
+@keyframes lr-brand-bob {
+ 0%, 20%, 42%, 100% { transform: translateY(0) rotate(0); }
+ 26% { transform: translateY(-.8px) rotate(-2deg); }
+ 32% { transform: translateY(.8px) rotate(1.5deg); }
+}
+@keyframes lr-brand-bob-loop {
+ 0%, 20%, 42%, 100% { transform: translateY(0) rotate(0); }
+ 26% { transform: translateY(-.8px) rotate(-2deg); }
+ 32% { transform: translateY(.8px) rotate(1.5deg); }
+}
+@keyframes lr-brand-face-in {
+ from { opacity: 0; transform: scale(.35); }
+ to { opacity: 1; transform: scale(1); }
+}
+@keyframes lr-brand-eye-open {
+ 0%, 34% { opacity: 1; transform: scale(1); }
+ 38%, 100% { opacity: 0; transform: scaleY(.15); }
+}
+@keyframes lr-brand-eye-wink {
+ 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }
+ 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }
+ 44%, 100% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }
+}
+@keyframes lr-brand-eye-open-loop {
+ 0%, 34%, 84%, 100% { opacity: 1; transform: scale(1); }
+ 38%, 76% { opacity: 0; transform: scaleY(.15); }
+}
+@keyframes lr-brand-eye-wink-loop {
+ 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }
+ 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }
+ 44%, 76% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }
+ 84%, 100% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }
+}
+@keyframes lr-brand-sparkle {
+ 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }
+ 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }
+ 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }
+ 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }
+ 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }
+}
+@keyframes lr-brand-sparkle-alt {
+ 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }
+ 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }
+ 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }
+ 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }
+ 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }
+}
+@keyframes lr-brand-sparkle-loop {
+ 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }
+ 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }
+ 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }
+ 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }
+ 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }
+}
+@keyframes lr-brand-sparkle-alt-loop {
+ 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }
+ 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }
+ 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }
+ 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }
+ 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }
+}
+.lr-brand-sparkles { stroke: #d08a22; }
+html[data-theme="dark"] .lr-brand-sparkles { stroke: #f4c14d; }
+
+@media (prefers-reduced-motion: reduce) {
+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell > * {
+ animation: none !important;
+ stroke-dashoffset: 0 !important;
+ }
+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-face {
+ animation: none !important;
+ opacity: 1 !important;
+ transform: none !important;
+ }
+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-left,
+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-wink {
+ animation: none !important;
+ opacity: 1 !important;
+ transform: none !important;
+ stroke-dashoffset: 0 !important;
+ }
+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-open,
+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-sparkles {
+ animation: none !important;
+ opacity: 0 !important;
+ }
+}
diff --git a/src/client/components/living/comic-presentation.ts b/src/client/components/living/comic-presentation.ts
new file mode 100644
index 00000000..de157590
--- /dev/null
+++ b/src/client/components/living/comic-presentation.ts
@@ -0,0 +1,70 @@
+import type { CSSProperties } from "react";
+import type { ComicKind, HintKind } from "../../ui/visual-kinds";
+
+// Visual grammar only. Current status/operation owners may supply a more
+// specific tone; a reused illustration must never override their evidence.
+export type ComicTone = "off" | "busy" | "live" | "warn" | "bad";
+export type ComicMotion = "demo" | "progress" | "still";
+export type ComicPresentation = { tone: ComicTone; motion: ComicMotion };
+
+const NEUTRAL: ComicPresentation = { tone: "off", motion: "demo" };
+const LIMITED: ComicPresentation = { tone: "warn", motion: "still" };
+const FAILED: ComicPresentation = { tone: "bad", motion: "still" };
+const CONNECTING: ComicPresentation = { tone: "busy", motion: "progress" };
+const RECOVERING: ComicPresentation = { tone: "warn", motion: "progress" };
+
+const STATES: Record<ComicKind, ComicPresentation> = {
+ "waiting-for-host": { tone: "off", motion: "still" },
+ "connecting-p2p": CONNECTING,
+ "connecting-sfu": CONNECTING,
+ "signal-connecting": CONNECTING,
+ "signal-recovering": RECOVERING,
+ "signal-offline": { tone: "off", motion: "still" },
+ "tap-to-play": { tone: "busy", motion: "demo" },
+ "host-paused": LIMITED,
+ recovering: RECOVERING,
+ "route-failed": FAILED,
+ "playback-failed": FAILED,
+ "host-offline": FAILED,
+ "no-audio": LIMITED,
+ "room-not-found": FAILED,
+ "access-denied": FAILED,
+ "invalid-invite": FAILED,
+ "room-full": FAILED,
+ "bandwidth-limited": LIMITED,
+ "encoder-limited": LIMITED,
+ warning: LIMITED,
+};
+
+export const COMIC_KINDS = Object.keys(STATES) as ComicKind[];
+
+const PRESENTATIONS: Partial<Record<ComicKind | HintKind, ComicPresentation>> = {
+ ...STATES,
+ "hint-route-p2p-required": LIMITED,
+ "hint-nat-unavailable": LIMITED,
+ "hint-volume-basic": LIMITED,
+ "hint-no-audio": LIMITED,
+ "hint-pip-unavailable": LIMITED,
+ "hint-share-audio-fixed": LIMITED,
+ "hint-silent-share-fixed": LIMITED,
+};
+
+export function getComicPresentation(kind?: ComicKind | HintKind): ComicPresentation {
+ return (kind && PRESENTATIONS[kind]) || NEUTRAL;
+}
+
+const COLOURS: Record<ComicTone, string> = {
+ off: "var(--comic-neutral, var(--ink))",
+ busy: "var(--action)",
+ live: "var(--live)",
+ warn: "var(--warn)",
+ bad: "var(--danger)",
+};
+
+export function comicStyle(tone: ComicTone, motion: ComicMotion): CSSProperties {
+ return {
+ "--comic-tone": COLOURS[tone],
+ "--comic-duration": "3.2s",
+ "--comic-repeat": motion === "progress" ? "infinite" : "1",
+ } as CSSProperties;
+}
diff --git a/src/client/components/living/hints/controls.tsx b/src/client/components/living/hints/controls.tsx
new file mode 100644
index 00000000..518e3d8a
--- /dev/null
+++ b/src/client/components/living/hints/controls.tsx
@@ -0,0 +1,92 @@
+import { FAINT, Frame, LIVE, MiniTv, Pawn, SKY, STAR_GOLD, rmBlock } from "../Comic";
+import type { ComicTheme } from "../Comic";
+import type { ControlHintKind, HintScene } from "../../../ui/visual-kinds";
+
+// One folding idiom for every disclosure: keep the header, put its contents away.
+const CollapseHint: HintScene = ({ theme }) => (
+ <>
+ <style>{`
+.vls-fold-body{transform-box:fill-box;transform-origin:50% 0%;animation:vlsFoldBody var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+@keyframes vlsFoldBody{0%,12%{transform:scaleY(1);opacity:1}40%,100%{transform:scaleY(0);opacity:0}}
+${rmBlock(["vls-fold-body"], [[".vls-fold-body", "transform:scaleY(0);opacity:0"]])}
+`}</style>
+ {[4, 164].map((x, index) => (
+ <g key={x}>
+ <Frame x={x} w={152} theme={theme} result={index === 1} />
+ <g className={index ? "vls-fold-body" : undefined}>
+ <rect x={x + 31} y={32} width={90} height={43} rx={5} fill="var(--wall-2)" stroke="var(--ink)" strokeWidth={2} />
+ <path d={`M${x + 43} 49 h66 M${x + 43} 61 h49`} stroke={FAINT} strokeWidth={3} strokeLinecap="round" />
+ </g>
+ <rect x={x + 31} y={19} width={90} height={17} rx={5} fill="var(--paper)" stroke="var(--ink)" strokeWidth={2} />
+ <path d={index ? `M${x + 68} 30 l8 -6 8 6` : `M${x + 68} 25 l8 6 8 -6`} fill="none" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" />
+ </g>
+ ))}
+ </>
+);
+
+function PasswordHint({ theme, reveal }: { theme: ComicTheme; reveal: boolean }) {
+ return <>
+ <style>{`
+.vls-password-new{animation:vlsPasswordNew var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+@keyframes vlsPasswordNew{0%,14%{opacity:0}35%,100%{opacity:1}}
+${rmBlock(["vls-password-new"], [[".vls-password-new", "opacity:1"]])}
+`}</style>
+ {[4, 164].map((x, index) => {
+ const visible = index ? reveal : !reveal;
+ return <g key={x}>
+ <Frame x={x} w={152} theme={theme} result={index === 1} />
+ <rect x={x + 22} y={35} width={108} height={31} rx={7} fill="var(--wall-2)" stroke="var(--ink)" strokeWidth={2} />
+ <g className={index ? "vls-password-new" : undefined} fill="var(--ink)">
+ {visible ? <text x={x + 76} y={57} textAnchor="middle" fontSize={21} fontFamily="monospace">1234</text>
+ : [49, 67, 85, 103].map((cx) => <circle key={cx} cx={x + cx} cy={51} r={3.5} />)}
+ </g>
+ <path d={`M${x + 63} 23 q13 -14 26 0 q-13 14 -26 0`} fill="none" stroke="var(--ink)" strokeWidth={2} />
+ {visible ? <circle cx={x + 76} cy={23} r={3} fill={LIVE} />
+ : <path d={`M${x + 66} 14 l20 18`} stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" />}
+ </g>;
+ })}
+ </>;
+}
+
+// Source audio goes to the other viewer. This is deliberately not local mute.
+function ShareAudioHint({ theme, enabled, locked = false }: { theme: ComicTheme; enabled: boolean; locked?: boolean }) {
+ return <>
+ <style>{`
+.vls-share-audio-change{animation:vlsShareAudioChange var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-share-audio-off{animation-name:vlsShareAudioOff}
+@keyframes vlsShareAudioChange{0%,12%{opacity:0}36%,100%{opacity:1}}
+@keyframes vlsShareAudioOff{0%,12%{opacity:1}36%,100%{opacity:0}}
+${rmBlock(["vls-share-audio-change"], [[".vls-share-audio-change", "opacity:1"], [".vls-share-audio-off", "opacity:0"]])}
+`}</style>
+ {[4, 164].map((x, index) => {
+ const audible = locked || index ? enabled : !enabled;
+ return <g key={x}>
+ <Frame x={x} w={152} theme={theme} result={index === 1} />
+ <MiniTv x={x + 20} y={28} w={65} h={42} />
+ <path d={`M${x + 37} 56 l12 -11 10 6 10 -8`} fill="none" stroke={SKY} strokeWidth={2.5} />
+ <Pawn x={x + 29} yb={85} s={6} eyes host />
+ <Pawn x={x + 121} yb={75} s={9} color={SKY} eyes />
+ <path d={`M${x + 85} 62 h15`} fill="none" stroke={FAINT} strokeWidth={2} strokeDasharray="3 3" />
+ <g opacity={audible ? 1 : 0} className={index && !locked ? `vls-share-audio-change${enabled ? "" : " vls-share-audio-off"}` : undefined}>
+ <path d={`M${x + 97} 38 v-14 l13 -3 v14 M${x + 97} 27 l13 -3`} fill="none" stroke={STAR_GOLD} strokeWidth={3} strokeLinecap="round" />
+ <ellipse cx={x + 94} cy={38} rx={4} ry={3} fill={STAR_GOLD} />
+ <ellipse cx={x + 107} cy={35} rx={4} ry={3} fill={STAR_GOLD} />
+ </g>
+ {locked && index ? <g stroke="var(--ink)" strokeWidth={1.5}>
+ <path d={`M${x + 87} 77 v-3 a3 3 0 0 1 6 0 v3`} fill="none" />
+ <rect x={x + 85} y={77} width={10} height={8} rx={2} fill={STAR_GOLD} />
+ </g> : null}
+ </g>;
+ })}
+ </>;
+}
+
+export const CONTROL_SCENES: Record<ControlHintKind, HintScene> = {
+ "hint-collapse": CollapseHint,
+ "hint-password-show": (props) => <PasswordHint {...props} reveal />,
+ "hint-password-hide": (props) => <PasswordHint {...props} reveal={false} />,
+ "hint-share-audio": (props) => <ShareAudioHint {...props} enabled />,
+ "hint-stop-audio": (props) => <ShareAudioHint {...props} enabled={false} />,
+ "hint-share-audio-fixed": (props) => <ShareAudioHint {...props} enabled locked />,
+ "hint-silent-share-fixed": (props) => <ShareAudioHint {...props} enabled={false} locked />,
+};
diff --git a/src/client/components/living/hints/index.tsx b/src/client/components/living/hints/index.tsx
index 14ea0a1c..2583ddc5 100644
--- a/src/client/components/living/hints/index.tsx
+++ b/src/client/components/living/hints/index.tsx
@@ -6,60 +6,17 @@
// completeness at compile time. JSX-free shell: this module is also loaded
// by the tsx preview harness, which uses the classic JSX runtime.
-import { createElement, memo, type CSSProperties, type ReactNode } from "react";
-import type { ComicTheme } from "../Comic";
+import { createElement, memo, type CSSProperties } from "react";
+import type { HintKind, HintScene } from "../../../ui/visual-kinds";
import { SET1_SCENES } from "./set1";
import { SET2_SCENES } from "./set2";
import { SET3_SCENES } from "./set3";
import { SET4_SCENES } from "./set4";
+import { PLAYBACK_SCENES } from "./playback";
+import { CONTROL_SCENES } from "./controls";
+import { comicStyle, getComicPresentation, type ComicTone, type ComicMotion } from "../comic-presentation";
-export type Set1Kind =
- | "hint-share-start"
- | "hint-share-stop"
- | "hint-pause"
- | "hint-resume"
- | "hint-switch-source"
- | "hint-reconnect"
- | "hint-capture-browser"
- | "hint-capture-window"
- | "hint-capture-display";
-
-export type Set2Kind =
- | "hint-copy-code"
- | "hint-shuffle-code"
- | "hint-copy-invite"
- | "hint-client-link"
- | "hint-rotate-invite"
- | "hint-revoke-invite"
- | "hint-policy-open"
- | "hint-policy-private"
- | "hint-password";
-
-export type Set3Kind =
- | "hint-quality"
- | "hint-audio-quality"
- | "hint-degrade-pref"
- | "hint-codec"
- | "hint-advanced"
- | "hint-details"
- | "hint-debug-export"
- | "hint-more-metrics";
-
-export type Set4Kind =
- | "hint-topology"
- | "hint-close"
- | "hint-rename"
- | "hint-theme"
- | "hint-join-go"
- | "hint-theater"
- | "hint-theater-exit"
- | "hint-route-p2p"
- | "hint-route-sfu"
- | "hint-nat-prediction"
- | "hint-client-local"
- | "hint-client-site";
-
-export type HintKind = Set1Kind | Set2Kind | Set3Kind | Set4Kind;
+export type { HintKind, HintScene };
export const HINT_KINDS: readonly HintKind[] = [
"hint-share-start",
@@ -88,27 +45,49 @@ export const HINT_KINDS: readonly HintKind[] = [
"hint-topology",
"hint-close",
"hint-rename",
- "hint-theme",
+ "hint-theme-light",
+ "hint-theme-dark",
+ "hint-collapse",
+ "hint-password-show",
+ "hint-password-hide",
+ "hint-share-audio",
+ "hint-stop-audio",
+ "hint-share-audio-fixed",
+ "hint-silent-share-fixed",
"hint-join-go",
"hint-theater",
"hint-theater-exit",
"hint-route-p2p",
+ "hint-route-p2p-required",
"hint-route-sfu",
"hint-nat-prediction",
+ "hint-nat-unavailable",
"hint-client-local",
"hint-client-site",
"hint-capture-browser",
"hint-capture-window",
"hint-capture-display",
+ "hint-local-play",
+ "hint-local-pause",
+ "hint-volume",
+ "hint-volume-basic",
+ "hint-mute",
+ "hint-unmute",
+ "hint-no-audio",
+ "hint-fullscreen",
+ "hint-fullscreen-exit",
+ "hint-pip",
+ "hint-pip-exit",
+ "hint-pip-unavailable",
];
-export type HintScene = (props: { theme: ComicTheme }) => ReactNode;
-
export const HINT_SCENES: Record<HintKind, HintScene> = {
...SET1_SCENES,
...SET2_SCENES,
...SET3_SCENES,
...SET4_SCENES,
+ ...PLAYBACK_SCENES,
+ ...CONTROL_SCENES,
};
const HINT_KIND_SET: ReadonlySet<string> = new Set(HINT_KINDS);
@@ -121,11 +100,19 @@ export function isHintKind(kind: string): kind is HintKind {
export const HintComic = memo(function HintComic({
kind,
size,
+ tone,
+ motion,
}: {
kind: HintKind;
size?: number;
+ tone?: ComicTone;
+ motion?: ComicMotion;
}) {
+ const defaults = getComicPresentation(kind);
+ const resolvedTone = tone ?? defaults.tone;
+ const resolvedMotion = motion ?? defaults.motion;
const style: CSSProperties = {
+ ...comicStyle(resolvedTone, resolvedMotion),
width: size != null ? `${size}px` : "min(320px, 86%)",
height: "auto",
display: "block",
@@ -134,6 +121,8 @@ export const HintComic = memo(function HintComic({
"svg",
{
viewBox: "0 0 320 96",
+ "data-comic-tone": resolvedTone,
+ "data-comic-motion": resolvedMotion,
style,
"aria-hidden": true,
focusable: false,
diff --git a/src/client/components/living/hints/playback.tsx b/src/client/components/living/hints/playback.tsx
new file mode 100644
index 00000000..192be304
--- /dev/null
+++ b/src/client/components/living/hints/playback.tsx
@@ -0,0 +1,192 @@
+import {
+ BrowserWindow, FAINT, Frame, INK_STAGE, LIVE, MiniTv, Pawn, SKY, TV_BODY, TV_EDGE, YOU, rmBlock,
+} from "../Comic";
+import type { HintScene, PlaybackHintKind } from "../../../ui/visual-kinds";
+
+// One action, a small response, then rest. Reduced motion keeps the result.
+function PlaybackMotion() {
+ return <style>{`
+.vls-pb-cue{transform-box:fill-box;transform-origin:center;animation:vlsPbCue var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pb-play{animation:vlsPbPlay var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-freeze{animation:vlsPbFreeze var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-waves .vls-pb-wave{stroke-dasharray:1;animation:vlsPbWave var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-waves .vls-pb-wave:nth-child(2){animation-delay:.08s}
+.vls-pb-waves .vls-pb-wave:nth-child(3){animation-delay:.16s}
+.vls-pb-waves.is-muting .vls-pb-wave{animation-name:vlsPbSilence}
+.vls-pb-cross{transform-box:fill-box;transform-origin:center;animation:vlsPbCross var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-listen{transform-box:fill-box;transform-origin:50% 100%;animation:vlsPbListen var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pb-flat{stroke-dasharray:1;animation:vlsPbWave var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-windowed,.vls-pb-expand,.vls-pb-contract{transform-box:fill-box;transform-origin:center}
+.vls-pb-windowed,.vls-pb-contract{transform:translate(12px,9px) scale(.62)}
+.vls-pb-expand{animation:vlsPbExpand var(--comic-duration,3.2s) cubic-bezier(.3,1.2,.5,1) var(--comic-repeat,1) both}
+.vls-pb-contract{animation:vlsPbContract var(--comic-duration,3.2s) cubic-bezier(.3,1.2,.5,1) var(--comic-repeat,1) both}
+.vls-pb-chrome-out{opacity:0;animation:vlsPbChromeOut var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-chrome-in{animation:vlsPbChromeIn var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-popout,.vls-pb-popin{transform-box:fill-box;transform-origin:center}
+.vls-pb-popout{animation:vlsPbPopout var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pb-popin{animation:vlsPbPopin var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+@keyframes vlsPbCue{0%,8%,34%,100%{transform:scale(1)}16%{transform:scale(.86)}25%{transform:scale(1.08)}}
+@keyframes vlsPbPlay{0%,18%{transform:translateX(-12px)}40%,100%{transform:none}}
+@keyframes vlsPbFreeze{0%{transform:translateX(-12px)}18%,100%{transform:none}}
+@keyframes vlsPbWave{0%,12%{stroke-dashoffset:1;opacity:.2}30%,100%{stroke-dashoffset:0;opacity:1}}
+@keyframes vlsPbSilence{0%,8%{stroke-dashoffset:0;opacity:1}26%,100%{stroke-dashoffset:1;opacity:0}}
+@keyframes vlsPbCross{0%,14%{opacity:0;transform:scale(.7)}30%,100%{opacity:1;transform:none}}
+@keyframes vlsPbListen{0%,26%,44%,100%{transform:rotate(0)}35%{transform:rotate(-5deg)}}
+@keyframes vlsPbExpand{0%,8%{transform:translate(12px,9px) scale(.62)}34%,100%{transform:none}}
+@keyframes vlsPbContract{0%,8%{transform:none}34%,100%{transform:translate(12px,9px) scale(.62)}}
+@keyframes vlsPbChromeOut{0%,8%{opacity:1}27%,100%{opacity:0}}
+@keyframes vlsPbChromeIn{0%,8%{opacity:0}30%,100%{opacity:1}}
+@keyframes vlsPbPopout{0%,8%{transform:translate(-28px,-14px) scale(1.4)}34%,100%{transform:none}}
+@keyframes vlsPbPopin{0%,8%{transform:translate(32px,16px) scale(.65)}34%,100%{transform:none}}
+${rmBlock(
+ ["vls-pb-cue", "vls-pb-play", "vls-pb-freeze", "vls-pb-waves .vls-pb-wave",
+ "vls-pb-waves.is-muting .vls-pb-wave", "vls-pb-cross", "vls-pb-listen",
+ "vls-pb-flat", "vls-pb-expand", "vls-pb-contract", "vls-pb-chrome-out", "vls-pb-chrome-in", "vls-pb-popout", "vls-pb-popin"],
+ [[".vls-pb-wave,.vls-pb-flat", "stroke-dashoffset:0;opacity:1"],
+ [".vls-pb-waves.is-muting .vls-pb-wave,.vls-pb-chrome-out", "opacity:0"],
+ [".vls-pb-cross,.vls-pb-chrome-in", "opacity:1"]],
+)}
+`}</style>;
+}
+
+// A green viewer, their local control, and the same picture before and after.
+function PlaybackHint({ theme, paused }: Parameters<HintScene>[0] & { paused: boolean }) {
+ return <>
+ <PlaybackMotion />
+ {[!paused, paused].map((isPaused, index) => {
+ const x = index * 160;
+ return <g key={index}>
+ <Frame x={x + 4} w={152} theme={theme} result={index === 1} />
+ <MiniTv x={x + 52} y={21} w={88} h={55} />
+ <path d={`M${x + 60} 61l15-20 13 15 12-11 29 16Z`} fill={SKY} opacity={.65} />
+ <g className={index ? (paused ? "vls-pb-freeze" : "vls-pb-play") : undefined}>
+ <circle cx={x + 115} cy={36} r={5} fill={INK_STAGE} />
+ {!isPaused ? <path d={`M${x + 100} 36h5m-8 5h5`} stroke={INK_STAGE} strokeWidth={1.5} strokeLinecap="round" /> : null}
+ </g>
+ <Pawn x={x + 28} yb={81} s={11} color={YOU} eyes />
+ <g className={index ? "vls-pb-cue" : undefined}>
+ <rect x={x + 15} y={21} width={27} height={25} rx={7}
+ fill="var(--paper)" stroke={YOU} strokeWidth={2} />
+ <path d={`M${x + 27} 46v5`} stroke={YOU} strokeWidth={2} strokeLinecap="round" />
+ {isPaused ? <path d={`M${x + 24} 28v11m8-11v11`} stroke={YOU} strokeWidth={3.5} strokeLinecap="round" />
+ : <path d={`M${x + 24} 27l12 7-12 7Z`} fill={YOU} />}
+ </g>
+ </g>;
+ })}
+ </>;
+}
+
+function LocalSpeaker({ x, silent, waves = 1, animate = false }: {
+ x: number; silent?: "muted" | "absent"; waves?: 1 | 3; animate?: boolean;
+}) {
+ return <>
+ <rect x={x + 26} y={44} width={14} height={22} rx={4} fill={TV_BODY} stroke={TV_EDGE} strokeWidth={2} />
+ <path d={`M${x + 40} 48l20-14v42l-20-14Z`} fill={TV_BODY} stroke={TV_EDGE} strokeWidth={2} strokeLinejoin="round" />
+ {silent !== "absent" ? <g className={animate ? `vls-pb-waves${silent ? " is-muting" : ""}` : undefined}
+ stroke={LIVE} strokeWidth={2.5} strokeLinecap="round" fill="none" opacity={silent && !animate ? 0 : 1}>
+ <path className="vls-pb-wave" pathLength={1} d={`M${x + 67} 49q6 6 0 12`} />
+ {waves === 3 ? <>
+ <path className="vls-pb-wave" pathLength={1} d={`M${x + 74} 43q12 12 0 24`} />
+ <path className="vls-pb-wave" pathLength={1} d={`M${x + 81} 37q18 18 0 36`} />
+ </> : null}
+ </g> : null}
+ {silent === "muted" ? <path className={animate ? "vls-pb-cross" : undefined}
+ d={`M${x + 75} 48l13 14m0-14-13 14`} stroke={FAINT} strokeWidth={3} strokeLinecap="round" /> : null}
+ </>;
+}
+
+function AudioHint({ theme, action, maxPercent = 200 }: Parameters<HintScene>[0] & {
+ action: "volume" | "mute" | "unmute"; maxPercent?: 100 | 200;
+}) {
+ const volume = action === "volume";
+ return <>
+ <PlaybackMotion />
+ {[0, 1].map((index) => {
+ const x = index * 160;
+ const silent = !volume && (action === "mute" ? index === 1 : index === 0);
+ return <g key={index}>
+ <Frame x={x + 4} w={152} theme={theme} result={index === 1} />
+ <LocalSpeaker x={x} waves={index || !volume ? 3 : 1} silent={silent ? "muted" : undefined} animate={index === 1} />
+ <Pawn x={x + 123} yb={79} s={11} color={YOU} eyes className={index && !silent ? "vls-pb-listen" : undefined} />
+ {volume ? <text x={x + 60} y={86} textAnchor="middle" fill="var(--ink)"
+ fontFamily="inherit" fontSize={13} fontWeight={700}>{index ? maxPercent : maxPercent / 2}%</text> : null}
+ </g>;
+ })}
+ </>;
+}
+
+const NoAudioHint: HintScene = ({ theme }) => <>
+ <PlaybackMotion />
+ <Frame x={4} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
+ <MiniTv x={35} y={15} w={90} h={55} />
+ <path d="M73 29l19 10-19 10Z" fill={SKY} />
+ <path d="M23 83v-10h7v4" stroke={FAINT} strokeWidth={1.5} fill="none" />
+ <ellipse cx={20} cy={83} rx={3} ry={2} fill={FAINT} />
+ <rect x={35} y={79} width={90} height={7} rx={3.5} fill="none" stroke={FAINT} strokeWidth={1.5} strokeDasharray="3 3" />
+ <path className="vls-pb-flat" pathLength={1} d="M45 82.5h70" stroke={FAINT} strokeWidth={1.5} strokeLinecap="round" />
+ <LocalSpeaker x={160} silent="absent" />
+ <Pawn x={283} yb={79} s={11} color={YOU} eyes />
+</>;
+
+function PlaybackViewport({ x, fullscreen, animate = false }: { x: number; fullscreen: boolean; animate?: boolean }) {
+ return <>
+ {!fullscreen || animate ? <g className={animate ? (fullscreen ? "vls-pb-chrome-out" : "vls-pb-chrome-in") : undefined}>
+ <BrowserWindow x={x + 16} y={13} w={128} h={69} />
+ </g> : null}
+ <g className={animate ? (fullscreen ? "vls-pb-expand" : "vls-pb-contract") : fullscreen ? undefined : "vls-pb-windowed"}>
+ <MiniTv x={x + 24} y={21} w={112} h={55} />
+ <path d={`M${x + 73} 37l19 10-19 10Z`} fill={SKY} />
+ </g>
+ <Pawn x={x + 20} yb={83} s={9} color={YOU} eyes />
+ </>;
+}
+
+function FullscreenHint({ theme, exit }: Parameters<HintScene>[0] & { exit: boolean }) {
+ return <>
+ <PlaybackMotion />
+ <Frame x={4} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
+ <PlaybackViewport x={0} fullscreen={exit} />
+ <PlaybackViewport x={160} fullscreen={!exit} animate />
+ </>;
+}
+
+function PictureHint({ theme, exit = false, unavailable = false }: Parameters<HintScene>[0] & {
+ exit?: boolean; unavailable?: boolean;
+}) {
+ return <>
+ <PlaybackMotion />
+ {[0, 1].map((index) => {
+ const x = index * 160;
+ const floating = index === (exit ? 0 : 1);
+ return <g key={index}>
+ <Frame x={x + 4} w={152} theme={theme} result={index === 1} />
+ <BrowserWindow x={x + 14} y={14} w={112} h={65} />
+ <path d={`M${x + 28} 37h65m-65 9h45m-45 9h31`} stroke={FAINT} strokeWidth={2} opacity={.35} />
+ <g className={index && !unavailable ? floating ? "vls-pb-popout" : "vls-pb-popin" : undefined}>
+ <MiniTv x={x + (floating ? 92 : 38)} y={floating ? 51 : 31}
+ w={floating ? 54 : 70} h={floating ? 31 : 41} />
+ <path d={floating ? `M${x + 113} 58l10 6-10 6Z` : `M${x + 65} 42l14 8-14 8Z`} fill={SKY} />
+ {unavailable && index ? <path d={`M${x + 97} 51l42 31`} stroke={FAINT} strokeWidth={3} strokeLinecap="round" /> : null}
+ </g>
+ <Pawn x={x + 24} yb={85} s={9} color={YOU} eyes />
+ </g>;
+ })}
+ </>;
+}
+
+export const PLAYBACK_SCENES: Record<PlaybackHintKind, HintScene> = {
+ "hint-local-play": (props) => <PlaybackHint {...props} paused={false} />,
+ "hint-local-pause": (props) => <PlaybackHint {...props} paused />,
+ "hint-volume": (props) => <AudioHint {...props} action="volume" />,
+ "hint-volume-basic": (props) => <AudioHint {...props} action="volume" maxPercent={100} />,
+ "hint-mute": (props) => <AudioHint {...props} action="mute" />,
+ "hint-unmute": (props) => <AudioHint {...props} action="unmute" />,
+ "hint-no-audio": NoAudioHint,
+ "hint-fullscreen": (props) => <FullscreenHint {...props} exit={false} />,
+ "hint-fullscreen-exit": (props) => <FullscreenHint {...props} exit />,
+ "hint-pip": (props) => <PictureHint {...props} />,
+ "hint-pip-exit": (props) => <PictureHint {...props} exit />,
+ "hint-pip-unavailable": (props) => <PictureHint {...props} unavailable />,
+};
diff --git a/src/client/components/living/hints/set1.tsx b/src/client/components/living/hints/set1.tsx
index 686b1a37..11a01990 100644
--- a/src/client/components/living/hints/set1.tsx
+++ b/src/client/components/living/hints/set1.tsx
@@ -21,10 +21,9 @@ import {
TV_EDGE,
TV_SCREEN,
WARN,
- YOU,
rmBlock,
} from "../Comic";
-import type { HintScene, Set1Kind } from "./index";
+import type { HintScene, Set1Kind } from "../../../ui/visual-kinds";
function SourceWindow({ x, y, alternate = false }: { x: number; y: number; alternate?: boolean }) {
return <>
@@ -37,17 +36,17 @@ function SourceWindow({ x, y, alternate = false }: { x: number; y: number; alter
}
/* hint-share-start: [dark TV + pawn reaching toward it] → [TV bright, mint
- glow, rays + Star]. The after panel replays one power-on beat per loop
+ glow, rays + Star]. The after panel demonstrates one power-on beat
(CRT screen-on → rays → star → pawn hop), then rests lit ~60%. */
const SceneShareStart: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-hs-reach{transform-box:fill-box;transform-origin:50% 100%;animation:vlsHsReach 3.2s ease-in-out infinite}
-.vls-hs-intent{animation:vlsHsIntent 3.2s ease-in-out infinite}
-.vls-hs-crt{transform-box:fill-box;transform-origin:center;animation:vlsHsCrt 3.2s ease-out infinite}
-.vls-hs-rays{animation:vlsHsRays 3.2s ease-out infinite}
-.vls-hs-star{transform-box:fill-box;transform-origin:center;animation:vlsHsStar 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
-.vls-hs-hop{animation:vlsHsHop 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-hs-reach{transform-box:fill-box;transform-origin:50% 100%;animation:vlsHsReach var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hs-intent{animation:vlsHsIntent var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hs-crt{transform-box:fill-box;transform-origin:center;animation:vlsHsCrt var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-hs-rays{animation:vlsHsRays var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-hs-star{transform-box:fill-box;transform-origin:center;animation:vlsHsStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
+.vls-hs-hop{animation:vlsHsHop var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsHsReach{0%{transform:rotate(0)}10%{transform:rotate(7deg)}26%{transform:rotate(7deg)}40%,100%{transform:rotate(0)}}
@keyframes vlsHsIntent{0%{opacity:0}10%{opacity:.9}26%{opacity:.9}40%,100%{opacity:0}}
@keyframes vlsHsCrt{0%{transform:scaleY(.06);opacity:.5}12%,100%{transform:scaleY(1);opacity:1}}
@@ -63,15 +62,12 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
<Floor x1={14} x2={146} y={78} />
<MiniTv x={55} y={24} w={66} h={42} />
<circle cx={88} cy={73} r={3} fill={TV_EDGE} />
<g className="vls-hs-reach">
- <path d="M20 78 c0-11 4.5-15.5 10-15.5 s10 4.5 10 15.5 Z" fill={YOU} />
- <circle cx={30} cy={58} r={6} fill={YOU} />
- <circle cx={31.5} cy={57.5} r={1.2} fill="#101a2c" />
- <circle cx={34.9} cy={57.5} r={1.2} fill="#101a2c" />
+ <Pawn x={30} yb={78} s={9} eyes host gaze={2} />
</g>
<g className="vls-hs-intent" opacity={0} stroke={FAINT} strokeWidth={2.5} strokeLinecap="round">
<path d="M43 45 l7 -5 M46 55 l8 -3" />
@@ -88,7 +84,7 @@ ${rmBlock(
<Star x={272} y={15} r={7} className="vls-hs-star" />
<circle cx={240} cy={73} r={3} fill={LIVE} />
<g className="vls-hs-hop">
- <Pawn x={184} yb={78} s={9} eyes />
+ <Pawn x={184} yb={78} s={9} eyes host />
</g>
</>
);
@@ -98,11 +94,11 @@ ${rmBlock(
const SceneShareStop: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-hx-eyes{transform-box:fill-box;transform-origin:center;animation:vlsHxBlink 3.4s ease-in-out infinite}
-.vls-hx-dim{animation:vlsHxDim 3.4s ease-out infinite}
-.vls-hx-led{animation:vlsHxLed 3.4s ease-out infinite}
-.vls-hx-moon{animation:vlsHxMoon 3.4s ease-in-out infinite}
-.vls-hx-settle{animation:vlsHxSettle 3.4s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-hx-eyes{transform-box:fill-box;transform-origin:center;animation:vlsHxBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hx-dim{animation:vlsHxDim var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-hx-led{animation:vlsHxLed var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-hx-moon{animation:vlsHxMoon var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-hx-settle{animation:vlsHxSettle var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsHxBlink{0%,44%,52%,100%{transform:scaleY(1)}48%{transform:scaleY(.12)}}
@keyframes vlsHxDim{0%{opacity:0}14%,100%{opacity:1}}
@keyframes vlsHxLed{0%{opacity:1}14%,100%{opacity:0}}
@@ -118,7 +114,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<Floor x1={14} x2={146} y={78} />
<MiniTv x={47} y={24} w={66} h={42} />
<rect x={51.62} y={28.62} width={56.76} height={27.72} rx={4} fill={MINT} />
@@ -127,12 +123,7 @@ ${rmBlock(
<path d="M62 17 l-6 -7 M80 14 V6 M98 17 l6 -7" />
</g>
<circle cx={80} cy={73} r={3} fill={LIVE} />
- <path d="M15 78 c0-9.9 4.05-13.95 9-13.95 s9 4.05 9 13.95 Z" fill={YOU} />
- <circle cx={24} cy={60} r={5.4} fill={YOU} />
- <g className="vls-hx-eyes" fill="#101a2c">
- <circle cx={24} cy={59.5} r={1.1} />
- <circle cx={27.6} cy={59.5} r={1.1} />
- </g>
+ <Pawn x={24} yb={78} s={8} eyes host gaze={2} eyeClassName="vls-hx-eyes" />
<Floor x1={174} x2={306} y={78} />
<MiniTv x={207} y={24} w={66} h={42} />
<rect className="vls-hx-dim" x={211.62} y={28.62} width={56.76} height={27.72} rx={4} fill="#0a101c" />
@@ -142,15 +133,7 @@ ${rmBlock(
<Moon x={240} y={42} k={0.8} />
</g>
<g className="vls-hx-settle">
- <path d="M187 78 c0-9.9 4.05-13.95 9-13.95 s9 4.05 9 13.95 Z" fill={YOU} />
- <circle cx={196} cy={60} r={5.4} fill={YOU} />
- <path
- d="M191.8 59.5 q1.7 -2.2 3.4 0 M198.8 59.5 q1.7 -2.2 3.4 0"
- stroke="#101a2c"
- strokeWidth={1.8}
- strokeLinecap="round"
- fill="none"
- />
+ <Pawn x={196} yb={78} s={8} eyes="closed" host />
</g>
</>
);
@@ -160,9 +143,9 @@ ${rmBlock(
const ScenePause: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-pz-flick{animation:vlsPzFlick 3s ease-in-out infinite}
-.vls-pz-hold{animation:vlsPzHold 3s ease-out infinite}
-.vls-pz-bars{transform-box:fill-box;transform-origin:center;animation:vlsPzBars 3s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-pz-flick{animation:vlsPzFlick var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pz-hold{animation:vlsPzHold var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-pz-bars{transform-box:fill-box;transform-origin:center;animation:vlsPzBars var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsPzFlick{0%{opacity:.5}10%{opacity:.9}20%{opacity:.2}32%{opacity:.85}44%,100%{opacity:.5}}
@keyframes vlsPzHold{0%{opacity:0}12%,100%{opacity:1}}
@keyframes vlsPzBars{0%,5%{opacity:0;transform:scale(1.45)}16%,100%{opacity:1;transform:scale(1)}}
@@ -172,7 +155,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={WARN} />
+ <Frame x={164} w={152} theme={theme} result />
<MiniTv x={44} y={22} w={72} h={46} />
<path d="M73 34 L89 42.2 L73 50.4 Z" fill={MINT} />
<g className="vls-pz-flick" stroke={SKY} strokeWidth={2} strokeLinecap="round" opacity={0.5}>
@@ -198,9 +181,9 @@ ${rmBlock(
const SceneResume: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-rs-play{transform-box:fill-box;transform-origin:center;animation:vlsRsPlay 3s cubic-bezier(.3,1.5,.5,1) infinite}
-.vls-rs-led{animation:vlsRsLed 3s ease-out infinite}
-.vls-rs-flick{animation:vlsRsFlick 3s ease-in-out infinite}
+.vls-rs-play{transform-box:fill-box;transform-origin:center;animation:vlsRsPlay var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
+.vls-rs-led{animation:vlsRsLed var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-rs-flick{animation:vlsRsFlick var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsRsPlay{0%{transform:scale(.55);opacity:.5}14%{transform:scale(1.18);opacity:1}22%,100%{transform:scale(1);opacity:1}}
@keyframes vlsRsLed{0%{opacity:.2}10%,100%{opacity:1}}
@keyframes vlsRsFlick{0%,12%{opacity:0}20%{opacity:.9}30%{opacity:.25}40%{opacity:.85}54%,100%{opacity:.5}}
@@ -210,7 +193,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
<MiniTv x={44} y={22} w={72} h={46} />
<path d="M73 34 L89 42.2 L73 50.4 Z" fill={MINT} />
<rect x={49.04} y={27.06} width={61.92} height={30.36} rx={4} fill="#0a101c" opacity={0.45} />
@@ -232,14 +215,14 @@ ${rmBlock(
const SceneSwitchSource: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-sw-d1{animation:vlsSwD1 3.2s ease-in-out infinite}
-.vls-sw-d2{animation:vlsSwD2 3.2s ease-in-out infinite}
+.vls-sw-d1{animation:vlsSwD1 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-sw-d2{animation:vlsSwD2 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsSwD1{0%{transform:translate(0,0);opacity:0}8%{opacity:1}22%{transform:translate(11px,-6px)}36%{transform:translate(22px,0);opacity:1}46%,100%{transform:translate(22px,0);opacity:0}}
@keyframes vlsSwD2{0%{transform:translate(0,0);opacity:0}8%{opacity:1}22%{transform:translate(-11px,6px)}36%{transform:translate(-22px,0);opacity:1}46%,100%{transform:translate(-22px,0);opacity:0}}
${rmBlock(["vls-sw-d1", "vls-sw-d2"], [[".vls-sw-d1,.vls-sw-d2", "opacity:0;transform:none"]])}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={SKY} />
+ <Frame x={164} w={152} theme={theme} result />
<SourceWindow x={27} y={28} />
<SourceWindow x={87} y={28} alternate />
<SourceWindow x={187} y={28} />
@@ -261,9 +244,9 @@ ${rmBlock(["vls-sw-d1", "vls-sw-d2"], [[".vls-sw-d1,.vls-sw-d2", "opacity:0;tran
const SceneReconnect: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-rj-spark{animation:vlsRjSpark 3.2s ease-in-out infinite}
-.vls-rj-plug{transform-box:fill-box;transform-origin:50% 100%;animation:vlsRjPlug 3.2s ease-in-out infinite}
-.vls-rj-led{transform-box:fill-box;transform-origin:center;animation:vlsRjLed 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-rj-spark{animation:vlsRjSpark var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rj-plug{transform-box:fill-box;transform-origin:50% 100%;animation:vlsRjPlug var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rj-led{transform-box:fill-box;transform-origin:center;animation:vlsRjLed var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsRjSpark{0%,100%{opacity:.55}15%{opacity:1}}
@keyframes vlsRjPlug{0%{transform:translate(-2px,-8px) rotate(-6deg)}10%{transform:translate(-1px,-3px) rotate(4deg)}20%{transform:translate(0,-1px) rotate(-2deg)}28%,100%{transform:none}}
@keyframes vlsRjLed{0%,24%{opacity:0;transform:scale(.4)}32%{opacity:1;transform:scale(1.3)}40%,100%{opacity:1;transform:scale(1)}}
@@ -277,7 +260,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
<Socket x={90} y={52} />
<Plug x={80} y={23} />
<Spark x={93} y={49} className="vls-rj-spark" />
@@ -292,12 +275,12 @@ ${rmBlock(
function CaptureHint({ theme, target }: Parameters<HintScene>[0] & { target: "browser" | "window" | "display" }) {
return <>
<style>{`
-.vls-capture-choice{animation:vlsCaptureChoice 3.2s ease-out infinite}
+.vls-capture-choice{animation:vlsCaptureChoice var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsCaptureChoice{0%,10%{opacity:.35;transform:translate(3px,3px)}28%,100%{opacity:1;transform:none}}
${rmBlock(["vls-capture-choice"], [[".vls-capture-choice", "opacity:1;transform:none"]])}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
{target === "browser" ? <>
<BrowserWindow x={29} y={20} w={100} h={58} />
<rect x={39} y={35} width={80} height={30} rx={3} fill="var(--wall-2)" stroke={SKY} strokeWidth={2} />
@@ -322,7 +305,7 @@ ${rmBlock(["vls-capture-choice"], [[".vls-capture-choice", "opacity:1;transform:
<rect x={237} y={34} width={37} height={23} rx={2} fill={TV_SCREEN} stroke={SKY} strokeWidth={1.5} />
<path d="M237 39h37 M243 53l7-10 5 6 4-4 7 8Z" stroke={SKY} strokeWidth={1} fill={SKY} />
</g> : <path className="vls-capture-choice" d="M229 54l10-14 7 8 5-5 8 11Z" fill={SKY} />}
- <Pawn x={190} yb={78} s={8} eyes />
+ <Pawn x={190} yb={78} s={8} eyes host />
</>;
}
diff --git a/src/client/components/living/hints/set2.tsx b/src/client/components/living/hints/set2.tsx
index 1d52fa97..ef09ddc7 100644
--- a/src/client/components/living/hints/set2.tsx
+++ b/src/client/components/living/hints/set2.tsx
@@ -19,7 +19,7 @@ import {
TV_SCREEN,
rmBlock,
} from "../Comic";
-import type { HintScene, Set2Kind } from "./index";
+import type { HintScene, Set2Kind } from "../../../ui/visual-kinds";
/* LCD code card: pale body, dark screen, 4 abstract digit slots at +12/+27/
+42/+57 inside the 78x46 body. */
@@ -134,10 +134,10 @@ function OpenDoorway({ x, y }: { x: number; y: number }) {
const SceneCopyCode: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-copy-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsCopyLean 2.6s ease-in-out infinite}
-.vls-copy-ring{transform-box:fill-box;transform-origin:center;animation:vlsCopyRing 2.6s ease-out infinite}
-.vls-copy-front{transform-box:fill-box;transform-origin:50% 100%;animation:vlsCopyHop 2.6s ease-in-out infinite}
-.vls-copy-star{transform-box:fill-box;transform-origin:center;animation:vlsCopyStar 2.6s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-copy-pawn{transform-box:fill-box;transform-origin:50% 100%;animation:vlsCopyLean var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-copy-ring{transform-box:fill-box;transform-origin:center;animation:vlsCopyRing var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-copy-front{transform-box:fill-box;transform-origin:50% 100%;animation:vlsCopyHop var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-copy-star{transform-box:fill-box;transform-origin:center;animation:vlsCopyStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsCopyLean{0%,8%{transform:rotate(0)}18%,30%{transform:rotate(7deg)}42%,100%{transform:rotate(0)}}
@keyframes vlsCopyRing{0%,14%{transform:scale(.6);opacity:0}20%{opacity:.8}38%,100%{transform:scale(1.7);opacity:0}}
@keyframes vlsCopyHop{0%,12%{transform:translateY(0)}20%{transform:translateY(-2.5px)}30%,100%{transform:translateY(0)}}
@@ -151,7 +151,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<LcdBase x={58} y={22} />
<LcdSlots x={58} y={22} />
<circle
@@ -181,8 +181,8 @@ const SceneShuffleCode: HintScene = ({ theme }) => (
<>
<style>{`
.vls-shuf-slots{opacity:.45}
-.vls-shuf-roll{animation:vlsShufRoll 2.4s linear infinite}
-.vls-shuf-spark{transform-box:fill-box;transform-origin:center;animation:vlsShufSpark 2.4s ease-out infinite}
+.vls-shuf-roll{animation:vlsShufRoll var(--comic-duration,3.2s) linear var(--comic-repeat,1) both}
+.vls-shuf-spark{transform-box:fill-box;transform-origin:center;animation:vlsShufSpark var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsShufRoll{0%{transform:translateY(-2px)}8%{transform:translateY(2px)}16%{transform:translateY(-2px)}24%{transform:translateY(2px)}32%{transform:translateY(-1px)}40%,100%{transform:translateY(0)}}
@keyframes vlsShufSpark{0%,8%{opacity:0;transform:scale(.5)}16%{opacity:1;transform:scale(1.1)}22%,70%{opacity:1;transform:scale(1)}82%,100%{opacity:0}}
${rmBlock(
@@ -194,7 +194,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<LcdBase x={41} y={25} />
<LcdSlots x={41} y={25} />
<LcdBase x={201} y={25} />
@@ -218,10 +218,10 @@ ${rmBlock(
const SceneCopyInvite: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-cinv-eyes{transform-box:fill-box;transform-origin:center;animation:vlsCinvBlink 2.8s ease-in-out infinite}
-.vls-cinv-fly{animation:vlsCinvFly 2.8s ease-in-out infinite}
-.vls-cinv-arc{animation:vlsCinvArc 2.8s ease-in-out infinite}
-.vls-cinv-star{transform-box:fill-box;transform-origin:center;animation:vlsCinvStar 2.8s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-cinv-eyes{transform-box:fill-box;transform-origin:center;animation:vlsCinvBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-cinv-fly{animation:vlsCinvFly var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-cinv-arc{animation:vlsCinvArc var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-cinv-star{transform-box:fill-box;transform-origin:center;animation:vlsCinvStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsCinvBlink{0%,60%,68%,100%{transform:scaleY(1)}64%{transform:scaleY(.12)}}
@keyframes vlsCinvFly{0%,6%{transform:translate(-92px,0);opacity:0}10%{opacity:1}32%{transform:translate(-46px,-20px)}50%{transform:translate(0,0)}56%{transform:translate(0,-3px)}62%,100%{transform:translate(0,0)}}
@keyframes vlsCinvArc{0%,10%{opacity:0}20%{opacity:.7}55%{opacity:.7}72%,100%{opacity:0}}
@@ -236,12 +236,8 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
- <Pawn x={62} yb={76} s={10} />
- <g className="vls-cinv-eyes" fill="#101a2c">
- <circle cx={59.8} cy={56} r={1.1} />
- <circle cx={64.2} cy={56} r={1.1} />
- </g>
+ <Frame x={164} w={152} theme={theme} result />
+ <Pawn x={62} yb={76} s={10} eyes host eyeClassName="vls-cinv-eyes" />
<LinkRing x={50} y={27.5} w={24} h={13} tilt={-12} />
<path
className="vls-cinv-arc"
@@ -252,7 +248,7 @@ ${rmBlock(
fill="none"
opacity={0}
/>
- <Pawn x={196} yb={76} s={8.5} eyes />
+ <Pawn x={196} yb={76} s={8.5} eyes host />
<Pawn x={288} yb={76} s={8.5} eyes color={SKY} />
<g className="vls-cinv-fly" opacity={0}>
<LinkRing x={278} y={31.5} w={20} h={11} tilt={-12} />
@@ -279,8 +275,8 @@ const HintClientLink: HintScene = ({ theme }) => (
const SceneRotateInvite: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-rinv-ring{transform-box:view-box;transform-origin:240px 48px;animation:vlsRinvSpin 2.6s ease-in-out infinite}
-.vls-rinv-spark{transform-box:fill-box;transform-origin:center;animation:vlsRinvSpark 2.6s ease-out infinite}
+.vls-rinv-ring{transform-box:view-box;transform-origin:240px 48px;animation:vlsRinvSpin var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rinv-spark{transform-box:fill-box;transform-origin:center;animation:vlsRinvSpark var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsRinvSpin{0%,10%{transform:rotate(0)}50%,100%{transform:rotate(360deg)}}
@keyframes vlsRinvSpark{0%,44%{opacity:0;transform:scale(.5)}54%{opacity:1;transform:scale(1.1)}62%,82%{opacity:1;transform:scale(1)}92%,100%{opacity:0}}
${rmBlock(
@@ -289,7 +285,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<LinkRing x={65} y={40} w={30} h={16} tilt={-15} />
<LinkRing x={225} y={40} w={30} h={16} tilt={-15} />
<g
@@ -312,9 +308,9 @@ ${rmBlock(
const SceneRevokeInvite: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-rev-l{transform-box:view-box;transform-origin:223px 52.5px;animation:vlsRevL 2.8s ease-in-out infinite}
-.vls-rev-r{transform-box:view-box;transform-origin:257px 52.5px;animation:vlsRevR 2.8s ease-in-out infinite}
-.vls-rev-x{transform-box:fill-box;transform-origin:center;animation:vlsRevX 2.8s ease-out infinite}
+.vls-rev-l{transform-box:view-box;transform-origin:223px 52.5px;animation:vlsRevL var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rev-r{transform-box:view-box;transform-origin:257px 52.5px;animation:vlsRevR var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rev-x{transform-box:fill-box;transform-origin:center;animation:vlsRevX var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsRevL{0%,10%{transform:translate(9px,-4.5px) rotate(-18deg)}20%{transform:translate(-2px,1px) rotate(5deg)}30%,100%{transform:translate(0,0) rotate(0)}}
@keyframes vlsRevR{0%,10%{transform:translate(-9px,-4.5px) rotate(18deg)}20%{transform:translate(2px,1px) rotate(-5deg)}30%,100%{transform:translate(0,0) rotate(0)}}
@keyframes vlsRevX{0%,30%{opacity:0;transform:scale(1.6) rotate(8deg)}38%,100%{opacity:1;transform:scale(1) rotate(8deg)}}
@@ -324,7 +320,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<LinkRing x={56} y={41} w={28} h={14} />
<LinkRing x={76} y={41} w={28} h={14} />
<g className="vls-rev-l">
@@ -365,13 +361,13 @@ ${rmBlock(
const ScenePolicyOpen: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-open-p1{transform-box:fill-box;transform-origin:50% 100%;animation:vlsOpenHop 2.8s ease-in-out infinite}
-.vls-open-p2{transform-box:fill-box;transform-origin:50% 100%;animation:vlsOpenHop 2.8s ease-in-out .2s infinite}
+.vls-open-p1{transform-box:fill-box;transform-origin:50% 100%;animation:vlsOpenHop var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-open-p2{transform-box:fill-box;transform-origin:50% 100%;animation:vlsOpenHop var(--comic-duration,3.2s) ease-in-out .2s var(--comic-repeat,1) both}
@keyframes vlsOpenHop{0%,6%{transform:translateY(0)}14%{transform:translateY(-5px)}22%{transform:translateY(0)}28%{transform:translateY(-3px)}34%,100%{transform:translateY(0)}}
${rmBlock(["vls-open-p1", "vls-open-p2"], [])}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<Door x={64} y={20} />
<OpenDoorway x={224} y={18} />
<Pawn x={238} yb={74} s={6.5} eyes className="vls-open-p1" />
@@ -386,11 +382,11 @@ ${rmBlock(["vls-open-p1", "vls-open-p2"], [])}
const ScenePolicyPrivate: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-priv-eyes{transform-box:fill-box;transform-origin:center;animation:vlsPrivBlink 3s ease-in-out infinite}
-.vls-priv-card{transform-box:fill-box;transform-origin:center;animation:vlsPrivCard 3s ease-in-out infinite}
-.vls-priv-door{transform-box:fill-box;transform-origin:0% 50%;animation:vlsPrivDoor 3s cubic-bezier(.3,.8,.35,1) infinite}
-.vls-priv-lock{transform-box:fill-box;transform-origin:center;animation:vlsPrivLock 3s cubic-bezier(.3,1.4,.45,1) infinite}
-.vls-priv-click{transform-box:fill-box;transform-origin:center;animation:vlsPrivClick 3s ease-out infinite}
+.vls-priv-eyes{transform-box:fill-box;transform-origin:center;animation:vlsPrivBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-priv-card{transform-box:fill-box;transform-origin:center;animation:vlsPrivCard var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-priv-door{transform-box:fill-box;transform-origin:0% 50%;animation:vlsPrivDoor var(--comic-duration,3.2s) cubic-bezier(.3,.8,.35,1) var(--comic-repeat,1) both}
+.vls-priv-lock{transform-box:fill-box;transform-origin:center;animation:vlsPrivLock var(--comic-duration,3.2s) cubic-bezier(.3,1.4,.45,1) var(--comic-repeat,1) both}
+.vls-priv-click{transform-box:fill-box;transform-origin:center;animation:vlsPrivClick var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsPrivBlink{0%,52%,60%,100%{transform:scaleY(1)}56%{transform:scaleY(.12)}}
@keyframes vlsPrivCard{0%,8%{transform:translateY(2px) rotate(-3deg)}18%{transform:translateY(-3px) rotate(4deg)}28%,100%{transform:none}}
@keyframes vlsPrivDoor{0%,10%{transform:scaleX(.18);opacity:.45}28%,100%{transform:scaleX(1);opacity:1}}
@@ -405,13 +401,9 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<OpenDoorway x={64} y={18} />
- <Pawn x={204} yb={76} s={8} />
- <g className="vls-priv-eyes" fill="#101a2c">
- <circle cx={201.8} cy={60} r={0.9} />
- <circle cx={206.2} cy={60} r={0.9} />
- </g>
+ <Pawn x={204} yb={76} s={8} eyes eyeClassName="vls-priv-eyes" />
<g className="vls-priv-card">
<g transform="rotate(-10 202 44)">
<rect
@@ -463,11 +455,11 @@ ${rmBlock(
const ScenePassword: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-pass-key{animation:vlsPassKey 2.8s ease-in-out infinite}
-.vls-pass-lines{animation:vlsPassLines 2.8s ease-in-out infinite}
-.vls-pass-shackle{transform-box:view-box;transform-origin:190px 44px;animation:vlsPassShackle 2.8s ease-in-out infinite}
-.vls-pass-glow{animation:vlsPassGlow 2.8s ease-in-out infinite}
-@keyframes vlsPassKey{0%{transform:translateX(0);opacity:0}6%{opacity:1}30%{transform:translateX(26px)}68%{transform:translateX(26px);opacity:1}80%{transform:translateX(26px);opacity:0}82%,100%{transform:translateX(0);opacity:0}}
+.vls-pass-key{animation:vlsPassKey var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pass-lines{animation:vlsPassLines var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pass-shackle{transform-box:view-box;transform-origin:190px 44px;animation:vlsPassShackle var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-pass-glow{animation:vlsPassGlow var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+@keyframes vlsPassKey{0%{transform:translateX(0);opacity:0}6%{opacity:1}30%,100%{transform:translateX(26px);opacity:1}}
@keyframes vlsPassLines{0%,4%{opacity:0}10%{opacity:.9}24%{opacity:.9}32%,100%{opacity:0}}
@keyframes vlsPassShackle{0%,8%{transform:rotate(34deg)}20%{transform:rotate(-6deg)}28%,100%{transform:rotate(0)}}
@keyframes vlsPassGlow{0%,30%{opacity:.3}42%{opacity:.65}55%,100%{opacity:.3}}
@@ -481,7 +473,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<g className="vls-pass-lines" opacity={0}>
<path d="M42 42 l-7 -2 M42 52 l-7 2" stroke={FAINT} strokeWidth={2} strokeLinecap="round" />
</g>
diff --git a/src/client/components/living/hints/set3.tsx b/src/client/components/living/hints/set3.tsx
index 11eed631..0a8f2293 100644
--- a/src/client/components/living/hints/set3.tsx
+++ b/src/client/components/living/hints/set3.tsx
@@ -10,6 +10,7 @@ import {
MINT,
MiniTv,
Pawn,
+ YOU,
SKY,
STAR_GOLD,
Star,
@@ -17,16 +18,16 @@ import {
TV_EDGE,
rmBlock,
} from "../Comic";
-import type { HintScene, Set3Kind } from "./index";
+import type { HintScene, Set3Kind } from "../../../ui/visual-kinds";
/** hint-quality: soft TV (few fat scanlines, squinting pawn) → sharp TV (many
- * thin crisp lines, one light sweep, star pop). Loop 3s. */
+ * thin crisp lines, one light sweep, star pop). Demonstrates once, then holds. */
const hintQuality: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-vq-soft{animation:vlsVqSoft 3s ease-in-out infinite}
-.vls-vq-sweep{animation:vlsVqSweep 3s ease-in-out infinite}
-.vls-vq-star{transform-box:fill-box;transform-origin:center;animation:vlsVqStar 3s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-vq-soft{animation:vlsVqSoft var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-vq-sweep{animation:vlsVqSweep var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-vq-star{transform-box:fill-box;transform-origin:center;animation:vlsVqStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsVqSoft{0%,48%,100%{opacity:.4}12%{opacity:.58}24%{opacity:.34}36%{opacity:.52}}
@keyframes vlsVqSweep{0%,22%{transform:translateX(0);opacity:0}30%{opacity:.3}48%,100%{transform:translateX(49px);opacity:0}}
@keyframes vlsVqStar{0%,55%{opacity:0;transform:scale(0)}66%{opacity:1;transform:scale(1.25)}74%,100%{opacity:1;transform:scale(1)}}
@@ -40,10 +41,9 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* BEFORE: pawn squints at a soft picture (3 fat faint scanlines) */}
- <Pawn x={26} yb={80} s={8} />
- <path d="M24 64h2.8 M27.6 64h2.8" stroke="#101a2c" strokeWidth={2} strokeLinecap="round" fill="none" />
+ <Pawn x={26} yb={80} s={8} eyes="closed" host gaze={2} />
<MiniTv x={52} y={22} w={76} h={46} />
<g className="vls-vq-soft" fill={LINE} opacity={0.4}>
<rect x={63} y={33} width={52} height={6} rx={3} />
@@ -51,9 +51,7 @@ ${rmBlock(
<rect x={63} y={51} width={52} height={6} rx={3} />
</g>
{/* AFTER: crisp thin scanlines + sweep + star; pawn brightens up */}
- <Pawn x={186} yb={80} s={8} />
- <circle cx={187} cy={62.8} r={1.2} fill="#101a2c" />
- <circle cx={190} cy={62.8} r={1.2} fill="#101a2c" />
+ <Pawn x={186} yb={80} s={8} eyes host gaze={2} />
<MiniTv x={212} y={22} w={76} h={46} />
<g fill={MINT} opacity={0.95}>
<rect x={221} y={30} width={58} height={2.5} rx={1.25} />
@@ -69,16 +67,16 @@ ${rmBlock(
);
/** hint-audio-quality: speaker with one thin faint arc (pawn leans in to
- * hear) → three bold rich arcs (happy-eye pawn static, star). Loop 3s. */
+ * hear) → three bold rich arcs (happy-eye pawn static, star). Demonstrates once, then holds. */
const hintAudioQuality: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-aq-weak{animation:vlsAqWeak 3s ease-in-out infinite}
-.vls-aq-listen{transform-box:fill-box;transform-origin:50% 100%;animation:vlsAqListen 3s ease-in-out infinite}
-.vls-aq-a1{animation:vlsAqPing 3s ease-out infinite}
-.vls-aq-a2{animation:vlsAqPing 3s ease-out .08s infinite}
-.vls-aq-a3{animation:vlsAqPing 3s ease-out .16s infinite}
-.vls-aq-star{transform-box:fill-box;transform-origin:center;animation:vlsAqStar 3s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-aq-weak{animation:vlsAqWeak var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-aq-listen{transform-box:fill-box;transform-origin:50% 100%;animation:vlsAqListen var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-aq-a1{animation:vlsAqPing var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-aq-a2{animation:vlsAqPing var(--comic-duration,3.2s) ease-out .08s var(--comic-repeat,1) both}
+.vls-aq-a3{animation:vlsAqPing var(--comic-duration,3.2s) ease-out .16s var(--comic-repeat,1) both}
+.vls-aq-star{transform-box:fill-box;transform-origin:center;animation:vlsAqStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsAqWeak{0%,30%,100%{opacity:.4}12%{opacity:.6}22%{opacity:.32}}
@keyframes vlsAqListen{0%,30%,58%,100%{transform:rotate(0)}40%,50%{transform:rotate(-8deg)}}
@keyframes vlsAqPing{0%,5%{opacity:.25}12%,100%{opacity:1}}
@@ -93,16 +91,14 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* BEFORE: thin faint arc, pawn cups its ear and leans in */}
<rect x={40} y={42} width={13} height={18} rx={3} fill={TV_BODY} stroke={TV_EDGE} strokeWidth={2} />
<path d="M53 47 L67 38 V64 L53 55 Z" fill={TV_BODY} stroke={TV_EDGE} strokeWidth={2} strokeLinejoin="round" />
<path className="vls-aq-weak" d="M73 45 a9 9 0 0 1 0 12" stroke={LINE} strokeWidth={2} strokeLinecap="round" fill="none" opacity={0.4} />
<g className="vls-aq-listen">
- <Pawn x={122} yb={80} s={9} />
- <circle cx={118.5} cy={61.3} r={1.3} fill="#101a2c" />
- <circle cx={122} cy={61.3} r={1.3} fill="#101a2c" />
- <path d="M116 55 a7 7 0 0 0 0 12" stroke="#23804f" strokeWidth={2.5} strokeLinecap="round" fill="none" />
+ <Pawn x={122} yb={80} s={9} eyes host gaze={-2} />
+ <circle cx={115} cy={61} r={2} fill={YOU} />
</g>
{/* AFTER: three bold arcs, happy-eye pawn static, star */}
<rect x={200} y={42} width={13} height={18} rx={3} fill={TV_BODY} stroke={TV_EDGE} strokeWidth={2} />
@@ -112,20 +108,19 @@ ${rmBlock(
<path className="vls-aq-a2" d="M237 41 a13 13 0 0 1 0 20" />
<path className="vls-aq-a3" d="M242 36 a18 18 0 0 1 0 30" />
</g>
- <Pawn x={282} yb={80} s={9} />
- <path d="M277.5 62 q1.7 -2.3 3.4 0 M282.5 62 q1.7 -2.3 3.4 0" stroke="#101a2c" strokeWidth={1.8} strokeLinecap="round" fill="none" />
+ <Pawn x={282} yb={80} s={9} eyes="closed" host />
<Star x={257} y={21} r={6.5} className="vls-aq-star" baseOpacity={0} />
</>
);
/** hint-degrade-pref: balance scale weighing a crisp frame against a
- * motion-blur frame (beam wobbles) → scale settles level, star. Loop 3.2s. */
+ * motion-blur frame (beam wobbles) → scale settles level, star. Demonstrates once, then holds. */
const hintDegradePref: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-dp-beam{transform-box:fill-box;transform-origin:50% 0%;animation:vlsDpBeam 3.2s ease-in-out infinite}
-.vls-dp-settle{transform-box:fill-box;transform-origin:50% 0%;animation:vlsDpSettle 3.2s ease-in-out infinite}
-.vls-dp-star{transform-box:fill-box;transform-origin:center;animation:vlsDpStar 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-dp-beam{transform-box:fill-box;transform-origin:50% 0%;animation:vlsDpBeam var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-dp-settle{transform-box:fill-box;transform-origin:50% 0%;animation:vlsDpSettle var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-dp-star{transform-box:fill-box;transform-origin:center;animation:vlsDpStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsDpBeam{0%,40%,100%{transform:rotate(0)}12%{transform:rotate(5deg)}26%{transform:rotate(-4deg)}}
@keyframes vlsDpSettle{0%,16%,100%{transform:rotate(0)}4%{transform:rotate(3deg)}10%{transform:rotate(-2deg)}}
@keyframes vlsDpStar{0%,30%{opacity:0;transform:scale(0)}40%{opacity:1;transform:scale(1.25)}48%,100%{opacity:1;transform:scale(1)}}
@@ -138,11 +133,9 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* BEFORE: pawn watches the scale wobble — crisp frame vs blur frame */}
- <Pawn x={26} yb={80} s={7.5} />
- <circle cx={27.3} cy={64} r={1.1} fill="#101a2c" />
- <circle cx={29.7} cy={64} r={1.1} fill="#101a2c" />
+ <Pawn x={26} yb={80} s={7.5} eyes host gaze={2} />
<path d="M84 78 V34 M70 78 H98" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" fill="none" />
<g className="vls-dp-beam" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" fill="none">
<path d="M52 34 H116" />
@@ -157,8 +150,7 @@ ${rmBlock(
</g>
<circle cx={84} cy={34} r={2.5} fill="var(--ink)" />
{/* AFTER: settle once, level, star; pawn pleased */}
- <Pawn x={298} yb={80} s={7.5} />
- <path d="M294 65 q1.6 -2.2 3.2 0 M299 65 q1.6 -2.2 3.2 0" stroke="#101a2c" strokeWidth={1.8} strokeLinecap="round" fill="none" />
+ <Pawn x={298} yb={80} s={7.5} eyes="closed" host />
<path d="M244 78 V34 M230 78 H258" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" fill="none" />
<g className="vls-dp-settle" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" fill="none">
<path d="M212 34 H276" />
@@ -177,13 +169,13 @@ ${rmBlock(
);
/** hint-codec: puzzle piece with eyes floats beside a TV with a dashed
- * socket → piece slots in, LED goes live, star. Loop 3s. */
+ * socket → piece slots in, LED goes live, star. Demonstrates once, then holds. */
const hintCodec: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-cd-bob{animation:vlsCdBob 3s ease-in-out infinite}
-.vls-cd-dock{animation:vlsCdDock 3s cubic-bezier(.3,1.5,.5,1) infinite}
-.vls-cd-star{transform-box:fill-box;transform-origin:center;animation:vlsCdStar 3s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-cd-bob{animation:vlsCdBob var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-cd-dock{animation:vlsCdDock var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
+.vls-cd-star{transform-box:fill-box;transform-origin:center;animation:vlsCdStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsCdBob{0%,40%,100%{transform:translateY(0)}20%{transform:translateY(-2.5px)}}
@keyframes vlsCdDock{0%,6%{transform:translateX(-8px)}20%{transform:translateX(1px)}26%,100%{transform:translateX(0)}}
@keyframes vlsCdStar{0%,32%{opacity:0;transform:scale(0)}42%{opacity:1;transform:scale(1.25)}50%,100%{opacity:1;transform:scale(1)}}
@@ -196,7 +188,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* BEFORE: piece bobs beside the TV, dashed socket waits on the edge */}
<g className="vls-cd-bob">
<path
@@ -230,13 +222,13 @@ ${rmBlock(
);
/** hint-advanced: closed cabinet door with a sliders glyph → door swings
- * open revealing 3 slider tracks with set knobs; pawn hops. Loop 3.2s. */
+ * open revealing 3 slider tracks with set knobs; pawn hops. Demonstrates once, then holds. */
const hintAdvanced: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-adv-blink{transform-box:fill-box;transform-origin:center;animation:vlsAdvBlink 3.2s ease-in-out infinite}
-.vls-adv-door{transform-box:fill-box;transform-origin:left center;animation:vlsAdvDoor 3.2s ease-in-out infinite}
-.vls-adv-hop{transform-box:fill-box;transform-origin:50% 100%;animation:vlsAdvHop 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-adv-blink{transform-box:fill-box;transform-origin:center;animation:vlsAdvBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-adv-door{transform-box:fill-box;transform-origin:left center;animation:vlsAdvDoor var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-adv-hop{transform-box:fill-box;transform-origin:50% 100%;animation:vlsAdvHop var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsAdvBlink{0%,52%,60%,100%{transform:scaleY(1)}56%{transform:scaleY(.12)}}
@keyframes vlsAdvDoor{0%,8%{transform:scaleX(1)}26%{transform:scaleX(.09)}33%,100%{transform:scaleX(.14)}}
@keyframes vlsAdvHop{0%,40%,62%,100%{transform:translateY(0)}46%{transform:translateY(-4.5px)}52%{transform:translateY(0)}57%{transform:translateY(-2px)}}
@@ -249,7 +241,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* BEFORE: closed door, sliders glyph embossed, pawn glances over */}
<rect x={44} y={18} width={56} height={60} rx={8} fill="var(--wall-2)" stroke="var(--ink)" strokeWidth={2.5} />
<rect x={49} y={23} width={44} height={50} rx={5} fill="var(--paper)" stroke="var(--ink)" strokeWidth={2} />
@@ -257,11 +249,7 @@ ${rmBlock(
<circle cx={64} cy={36} r={2.5} fill="var(--ink)" />
<circle cx={70} cy={46} r={2.5} fill="var(--ink)" />
<circle cx={87} cy={48} r={2.5} fill="var(--ink)" />
- <Pawn x={122} yb={80} s={7.5} />
- <g className="vls-adv-blink">
- <circle cx={118.6} cy={64.2} r={1.2} fill="#101a2c" />
- <circle cx={122} cy={64.2} r={1.2} fill="#101a2c" />
- </g>
+ <Pawn x={122} yb={80} s={7.5} eyes host gaze={-2} eyeClassName="vls-adv-blink" />
{/* AFTER: tracks + set knobs revealed as the door swings open */}
<rect x={204} y={18} width={56} height={60} rx={8} fill="var(--wall-2)" stroke="var(--ink)" strokeWidth={2.5} />
<g stroke={FAINT} strokeWidth={2.5} strokeLinecap="round" fill="none">
@@ -276,20 +264,18 @@ ${rmBlock(
<rect x={209} y={23} width={44} height={50} rx={5} fill="var(--paper)" stroke="var(--ink)" strokeWidth={2} />
</g>
<g className="vls-adv-hop">
- <Pawn x={284} yb={80} s={7.5} />
- <circle cx={281} cy={64.2} r={1.2} fill="#101a2c" />
- <circle cx={284.4} cy={64.2} r={1.2} fill="#101a2c" />
+ <Pawn x={284} yb={80} s={7.5} eyes host gaze={-2} />
</g>
</>
);
/** hint-details: a plain row of meter bars → magnifier pops over the bars,
- * enlarged inside the lens; pawn peeks. Loop 3s. */
+ * enlarged inside the lens; pawn peeks. Demonstrates once, then holds. */
const hintDetails: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-dt-lens{transform-box:fill-box;transform-origin:center;animation:vlsDtLens 3s cubic-bezier(.3,1.5,.5,1) infinite}
-.vls-dt-blink{transform-box:fill-box;transform-origin:center;animation:vlsDtBlink 3s ease-in-out infinite}
+.vls-dt-lens{transform-box:fill-box;transform-origin:center;animation:vlsDtLens var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
+.vls-dt-blink{transform-box:fill-box;transform-origin:center;animation:vlsDtBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsDtLens{0%,6%{transform:scale(0);opacity:0}14%{transform:scale(1.12);opacity:1}20%,100%{transform:scale(1);opacity:1}}
@keyframes vlsDtBlink{0%,56%,64%,100%{transform:scaleY(1)}60%{transform:scaleY(.12)}}
${rmBlock(
@@ -301,7 +287,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* BEFORE: plain bar row, pawn looks on */}
<path d="M28 74 H116" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" fill="none" />
<g fill="var(--ink)">
@@ -311,9 +297,7 @@ ${rmBlock(
<rect x={82} y={44} width={8} height={30} rx={2.5} />
<rect x={98} y={52} width={8} height={22} rx={2.5} />
</g>
- <Pawn x={132} yb={80} s={7} />
- <circle cx={129.8} cy={65.2} r={1.2} fill="#101a2c" />
- <circle cx={132.6} cy={65.2} r={1.2} fill="#101a2c" />
+ <Pawn x={132} yb={80} s={7} eyes gaze={-2} />
{/* AFTER: magnifier over the same bars, enlarged inside the lens */}
<path d="M188 74 H276" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" fill="none" />
<g fill="var(--ink)">
@@ -332,22 +316,18 @@ ${rmBlock(
<rect x={240} y={40} width={10} height={32} rx={3} />
</g>
</g>
- <Pawn x={296} yb={80} s={7} />
- <g className="vls-dt-blink">
- <circle cx={293.4} cy={65.6} r={1.2} fill="#101a2c" />
- <circle cx={296.2} cy={65.6} r={1.2} fill="#101a2c" />
- </g>
+ <Pawn x={296} yb={80} s={7} eyes gaze={-2} eyeClassName="vls-dt-blink" />
</>
);
/** hint-more-metrics: one meter row + chevron-down (beckons) → three rows
- * unfold with overshoot + chevron-up. Loop 3s. */
+ * unfold with overshoot + chevron-up. Demonstrates once, then holds. */
const hintMoreMetrics: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-mm-chev{animation:vlsMmChev 3s ease-in-out infinite}
-.vls-mm-r2{animation:vlsMmIn 3s cubic-bezier(.3,1.5,.5,1) infinite}
-.vls-mm-r3{animation:vlsMmIn 3s cubic-bezier(.3,1.5,.5,1) .12s infinite}
+.vls-mm-chev{animation:vlsMmChev var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-mm-r2{animation:vlsMmIn var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
+.vls-mm-r3{animation:vlsMmIn var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) .12s var(--comic-repeat,1) both}
@keyframes vlsMmChev{0%,30%,100%{transform:translateY(0)}15%{transform:translateY(2.5px)}}
@keyframes vlsMmIn{0%{opacity:0;transform:translateY(-7px)}8%{opacity:1;transform:translateY(1px)}14%,100%{opacity:1;transform:translateY(0)}}
${rmBlock(
@@ -359,7 +339,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
{/* BEFORE: one folded row, chevron-down bobs, pawn watches */}
<rect x={34} y={32} width={92} height={15} rx={7.5} fill="var(--wall-2)" stroke="var(--ink)" strokeWidth={2} />
<g fill="var(--ink)">
@@ -369,9 +349,7 @@ ${rmBlock(
<circle cx={80} cy={39.5} r={2} />
</g>
<path className="vls-mm-chev" d="M70 62 l10 8 l10 -8" stroke="var(--ink)" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" fill="none" />
- <Pawn x={140} yb={80} s={6} />
- <circle cx={138.2} cy={67.4} r={1} fill="#101a2c" />
- <circle cx={140.6} cy={67.4} r={1} fill="#101a2c" />
+ <Pawn x={140} yb={80} s={6} eyes gaze={-2} />
{/* AFTER: three rows unfolded, chevron-up on top */}
<path d="M230 22 l10 -7 l10 7" stroke="var(--ink)" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" fill="none" />
<rect x={194} y={28} width={92} height={15} rx={7.5} fill="var(--wall-2)" stroke="var(--ink)" strokeWidth={2} />
@@ -395,16 +373,14 @@ ${rmBlock(
<rect x={226} y={69} width={5} height={6} rx={1.5} fill={STAR_GOLD} />
<circle cx={240} cy={71.5} r={2} fill={STAR_GOLD} />
</g>
- <Pawn x={300} yb={80} s={6} />
- <circle cx={298.2} cy={67.4} r={1} fill="#101a2c" />
- <circle cx={300.6} cy={67.4} r={1} fill="#101a2c" />
+ <Pawn x={300} yb={80} s={6} eyes gaze={-2} />
</>
);
const hintDebugExport: HintScene = ({ theme }) => (
<>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<path d="M32 72H128" stroke="var(--ink)" strokeWidth={2.5} strokeLinecap="round" />
<g fill="var(--ink)">
<rect x={40} y={54} width={12} height={18} rx={2.5} />
diff --git a/src/client/components/living/hints/set4.tsx b/src/client/components/living/hints/set4.tsx
index 41b77bb9..1503156b 100644
--- a/src/client/components/living/hints/set4.tsx
+++ b/src/client/components/living/hints/set4.tsx
@@ -6,11 +6,9 @@
// carries no transform attribute — positions are baked into path data.
import {
BrowserWindow,
- Crown,
FAINT,
Frame,
LIVE,
- MINT,
MiniTv,
Pawn,
RedX,
@@ -22,21 +20,21 @@ import {
TV_SCREEN,
rmBlock,
} from "../Comic";
-import type { HintScene, Set4Kind } from "./index";
+import type { ComicTheme } from "../Comic";
+import type { HintScene, Set4Kind } from "../../../ui/visual-kinds";
const INK = "var(--ink)";
const WALL2 = "var(--wall-2)";
-const EYE = "#101a2c";
-/* hint-topology: [one crowned pawn alone] → [crowned pawn with two leaf
- pawns on live-green edges]. Loop 3.2s: leaves hop in turn (8-20%, 26-38%),
+/* hint-topology: [one pawn with a Host badge] → [host with two leaf
+ pawns on live-green edges]. Demo: leaves hop in turn (8-20%, 26-38%),
everyone blinks at 62%; rest >=55%. */
const HintTopology: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-top-eyes{transform-box:fill-box;transform-origin:center;animation:vlsTopBlink 3.2s ease-in-out infinite}
-.vls-top-leaf1{transform-box:fill-box;transform-origin:50% 100%;animation:vlsTopHop1 3.2s ease-in-out infinite}
-.vls-top-leaf2{transform-box:fill-box;transform-origin:50% 100%;animation:vlsTopHop2 3.2s ease-in-out infinite}
+.vls-top-eyes{transform-box:fill-box;transform-origin:center;animation:vlsTopBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-top-leaf1{transform-box:fill-box;transform-origin:50% 100%;animation:vlsTopHop1 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-top-leaf2{transform-box:fill-box;transform-origin:50% 100%;animation:vlsTopHop2 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsTopBlink{0%,58%,66%,100%{transform:scaleY(1)}62%{transform:scaleY(.12)}}
@keyframes vlsTopHop1{0%,8%{transform:translateY(0)}14%{transform:translateY(-4px)}20%,100%{transform:translateY(0)}}
@keyframes vlsTopHop2{0%,26%{transform:translateY(0)}32%{transform:translateY(-4px)}38%,100%{transform:translateY(0)}}
@@ -46,36 +44,26 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
- <Crown x={80} y={47} />
- <Pawn x={80} yb={78} s={12} />
- <g className="vls-top-eyes" fill={EYE}>
- <circle cx={77.4} cy={54} r={1.3} />
- <circle cx={82.6} cy={54} r={1.3} />
- </g>
+ <Frame x={164} w={152} theme={theme} result />
+ <Pawn x={80} yb={78} s={12} eyes host eyeClassName="vls-top-eyes" />
<g stroke={LIVE} strokeWidth={3} strokeLinecap="round" fill="none">
- <path d="M240 47 C231 55 222 58 213 65" />
- <path d="M240 47 C249 55 258 58 267 65" />
- </g>
- <Pawn x={240} yb={46} s={7} />
- <g className="vls-top-eyes" fill={EYE}>
- <circle cx={237.8} cy={32} r={0.9} />
- <circle cx={242.2} cy={32} r={0.9} />
+ <path d="M240 47 C231 50 218 52 210 56" />
+ <path d="M240 47 C249 50 262 52 270 56" />
</g>
- <Crown x={240} y={27} k={0.75} />
+ <Pawn x={240} yb={46} s={7} eyes host eyeClassName="vls-top-eyes" />
<Pawn x={210} yb={80} s={7} color={SKY} eyes className="vls-top-leaf1" />
- <Pawn x={270} yb={80} s={7} color={MINT} eyes className="vls-top-leaf2" />
+ <Pawn x={270} yb={80} s={7} color={STAR_GOLD} eyes className="vls-top-leaf2" />
</>
);
-/* hint-close: [open card] → [card folds away + small RedX stamp]. Loop 3.4s:
+/* hint-close: [open card] → [card folds away + small RedX stamp]. Demo:
card wobbles (10-28%), folds out (40-52%), X stamps once at 56-62% and
holds; rest 62-100%. */
const HintClose: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-cls-card{transform-box:fill-box;transform-origin:center;animation:vlsClsCard 3.4s ease-in-out infinite}
-.vls-cls-x{transform-box:fill-box;transform-origin:center;animation:vlsClsX 3.4s ease-out infinite}
+.vls-cls-card{transform-box:fill-box;transform-origin:center;animation:vlsClsCard var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-cls-x{transform-box:fill-box;transform-origin:center;animation:vlsClsX var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
@keyframes vlsClsCard{0%,10%{transform:rotate(0);opacity:1}16%{transform:rotate(2.5deg)}22%{transform:rotate(-2.5deg)}28%,40%{transform:rotate(0);opacity:1}52%,100%{transform:rotate(-14deg) translate(-12px,20px) scale(.55);opacity:0}}
@keyframes vlsClsX{0%,56%{opacity:0;transform:scale(1.6) rotate(8deg)}62%,100%{opacity:1;transform:scale(1) rotate(8deg)}}
${rmBlock(
@@ -87,7 +75,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
<rect x={52} y={22} width={56} height={50} rx={8} fill={WALL2} stroke={INK} strokeWidth={2.5} />
<g stroke={INK} strokeWidth={2} strokeLinecap="round" fill="none" opacity={0.5}>
<path d="M62 36 q4 -5 8 0 t8 0 t8 0" />
@@ -105,14 +93,14 @@ ${rmBlock(
);
/* hint-rename: [blank name tag] → [pencil writes a squiggle on the tag +
- spark]. Loop 3.2s: pencil rides the pen tip left→right wiggling (6-34%)
+ spark]. Demo: pencil rides the pen tip left→right wiggling (6-34%)
as the line draws, spark pops 38-46%, holds; rest 54%. */
const HintRename: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-rnm-line{stroke-dasharray:1;animation:vlsRnmLine 3.2s ease-in-out infinite}
-.vls-rnm-pencil{transform-box:fill-box;transform-origin:0% 100%;animation:vlsRnmPencil 3.2s ease-in-out infinite}
-.vls-rnm-spark{transform-box:fill-box;transform-origin:center;animation:vlsRnmSpark 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-rnm-line{stroke-dasharray:1;animation:vlsRnmLine var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rnm-pencil{transform-box:fill-box;transform-origin:0% 100%;animation:vlsRnmPencil var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-rnm-spark{transform-box:fill-box;transform-origin:center;animation:vlsRnmSpark var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsRnmLine{0%,6%{stroke-dashoffset:1}34%,100%{stroke-dashoffset:0}}
@keyframes vlsRnmPencil{0%,6%{transform:translate(-30px,0) rotate(0)}12%{transform:translate(-21px,0) rotate(-6deg)}18%{transform:translate(-13px,0) rotate(5deg)}24%{transform:translate(-6px,0) rotate(-5deg)}30%{transform:translate(-2px,0) rotate(4deg)}34%,100%{transform:translate(0,0) rotate(0)}}
@keyframes vlsRnmSpark{0%,38%{opacity:0;transform:scale(.4)}44%{opacity:1;transform:scale(1.2)}50%,100%{opacity:1;transform:scale(1)}}
@@ -126,7 +114,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
<rect x={44} y={30} width={72} height={30} rx={8} fill={WALL2} stroke={INK} strokeWidth={2.5} />
<circle cx={55} cy={45} r={2.5} fill="var(--paper)" stroke={INK} strokeWidth={1.5} />
<path d="M66 45 h40" stroke={INK} strokeWidth={2} strokeLinecap="round" strokeDasharray="3 4" opacity={0.3} />
@@ -149,52 +137,45 @@ ${rmBlock(
</>
);
-/* hint-theme: single wide panel — sun and moon on a two-arrow do-si-do.
- Loop 3s: sun owns 0-38%, crossfade 38-50%, moon owns 50-88%, fade back;
- arrows static. */
-const HintTheme: HintScene = ({ theme }) => (
+/* Show the next theme, with a short reveal and a readable final hold. */
+const ThemeHint = ({ theme, light }: { theme: ComicTheme; light: boolean }) => (
<>
<style>{`
-.vls-thm-sun{transform-box:fill-box;transform-origin:center;animation:vlsThmSun 3s ease-in-out infinite}
-.vls-thm-moon{transform-box:fill-box;transform-origin:center;animation:vlsThmMoon 3s ease-in-out infinite}
-@keyframes vlsThmSun{0%,38%{opacity:1;transform:scale(1)}50%,88%{opacity:.45;transform:scale(.92)}100%{opacity:1;transform:scale(1)}}
-@keyframes vlsThmMoon{0%,38%{opacity:.45;transform:scale(.92)}50%,88%{opacity:1;transform:scale(1)}100%{opacity:.45;transform:scale(.92)}}
+.vls-thm-next{transform-box:fill-box;transform-origin:center;animation:vlsThmNext var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+@keyframes vlsThmNext{0%,12%{opacity:.15;transform:scale(.75)}36%,100%{opacity:1;transform:scale(1)}}
${rmBlock(
- ["vls-thm-sun", "vls-thm-moon"],
- [[".vls-thm-sun,.vls-thm-moon", "opacity:1;transform:none"]],
+ ["vls-thm-next"],
+ [[".vls-thm-next", "opacity:1;transform:none"]],
)}
`}</style>
- <Frame x={4} w={312} theme={theme} />
- <g stroke={INK} strokeWidth={2.5} strokeLinecap="round" fill="none" opacity={0.55}>
- <path d="M100 34 A90 90 0 0 1 220 34" />
- <path d="M212 27 L220 34 L212 41" />
- <path d="M220 62 A90 90 0 0 0 100 62" />
- <path d="M108 55 L100 62 L108 69" />
- </g>
- <g className="vls-thm-sun">
- <g stroke={INK} strokeWidth={2.5} strokeLinecap="round">
- <path d="M125 48h5 M90 48h5 M117.5 61l2.5 4.3 M102.5 35l-2.5-4.3 M102.5 61l-2.5 4.3 M117.5 35l2.5-4.3" />
- </g>
- <circle cx={110} cy={48} r={11} fill={STAR_GOLD} stroke={INK} strokeWidth={2} />
- </g>
- <g className="vls-thm-moon">
- <circle cx={210} cy={48} r={11} fill={INK} />
- <circle cx={214} cy={44} r={9} fill="var(--paper)" />
- <circle cx={228} cy={32} r={1.8} fill={STAR_GOLD} />
- <circle cx={232} cy={48} r={1.4} fill={STAR_GOLD} />
- </g>
+ {[4, 164].map((x, index) => {
+ const daylight = index ? light : !light;
+ return <g key={x}>
+ <Frame x={x} w={152} theme={theme} result={index === 1} />
+ <rect x={x + 34} y={19} width={84} height={59} rx={10} fill={daylight ? "#f2e9c9" : TV_SCREEN} stroke={FAINT} strokeWidth={2} />
+ <g className={index ? "vls-thm-next" : undefined}>
+ {daylight ? <>
+ <circle cx={x + 76} cy={48} r={12} fill={STAR_GOLD} stroke="#364358" strokeWidth={2} />
+ <path d={`M${x + 76} 27 v4 M${x + 76} 65 v4 M${x + 55} 48 h4 M${x + 93} 48 h4 M${x + 61} 33 l3 3 M${x + 88} 60 l3 3 M${x + 61} 63 l3 -3 M${x + 88} 36 l3 -3`} stroke="#364358" strokeWidth={2} strokeLinecap="round" />
+ </> : <>
+ <path d={`M${x + 82} 32 a17 17 0 1 0 8 27 a18 18 0 0 1 -8 -27`} fill="#f2e9c9" />
+ <Star x={x + 101} y={34} r={4} />
+ </>}
+ </g>
+ </g>;
+ })}
</>
);
/* hint-join-go: [pawn beside 4 filled code slots] → [pawn hops through an
- open door + star]. Loop 3.2s: blink at 62%, hop-in 8-24%, star 28-42%;
+ open door + star]. Demo: blink at 62%, hop-in 8-24%, star 28-42%;
rest ~58%. */
const HintJoinGo: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-jgo-eyes{transform-box:fill-box;transform-origin:center;animation:vlsJgoBlink 3.2s ease-in-out infinite}
-.vls-jgo-hop{transform-box:fill-box;transform-origin:50% 100%;animation:vlsJgoHop 3.2s cubic-bezier(.3,1.4,.5,1) infinite}
-.vls-jgo-star{transform-box:fill-box;transform-origin:center;animation:vlsJgoStar 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-jgo-eyes{transform-box:fill-box;transform-origin:center;animation:vlsJgoBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-jgo-hop{transform-box:fill-box;transform-origin:50% 100%;animation:vlsJgoHop var(--comic-duration,3.2s) cubic-bezier(.3,1.4,.5,1) var(--comic-repeat,1) both}
+.vls-jgo-star{transform-box:fill-box;transform-origin:center;animation:vlsJgoStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsJgoBlink{0%,58%,66%,100%{transform:scaleY(1)}62%{transform:scaleY(.12)}}
@keyframes vlsJgoHop{0%,8%{transform:translate(-38px,0)}16%{transform:translate(-18px,-10px)}24%,100%{transform:translate(0,0)}}
@keyframes vlsJgoStar{0%,28%{opacity:0;transform:scale(0)}34%{opacity:1;transform:scale(1.25)}42%,100%{opacity:1;transform:scale(1)}}
@@ -207,12 +188,8 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
- <Pawn x={32} yb={76} s={9} />
- <g className="vls-jgo-eyes" fill={EYE}>
- <circle cx={34.6} cy={58} r={1} />
- <circle cx={38.2} cy={58} r={1} />
- </g>
+ <Frame x={164} w={152} theme={theme} result />
+ <Pawn x={32} yb={76} s={9} eyes gaze={2} eyeClassName="vls-jgo-eyes" />
<g fill={WALL2} stroke={INK} strokeWidth={2}>
<rect x={58} y={32} width={15} height={24} rx={4} />
<rect x={79} y={32} width={15} height={24} rx={4} />
@@ -247,8 +224,8 @@ function TheaterHint({
return (
<>
<style>{`
-.${stageClass}{transform-box:fill-box;transform-origin:center;animation:${motion} 3.2s cubic-bezier(.3,1.25,.5,1) infinite}
-.vls-th-arrows{animation:vlsThArrows 3.2s ease-in-out infinite}
+.${stageClass}{transform-box:fill-box;transform-origin:center;animation:${motion} var(--comic-duration,3.2s) cubic-bezier(.3,1.25,.5,1) var(--comic-repeat,1) both}
+.vls-th-arrows{animation:vlsThArrows var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsThEnter{0%,8%{transform:scale(.72)}28%,100%{transform:scale(1)}}
@keyframes vlsThExit{0%,8%{transform:scale(1.28)}28%,100%{transform:scale(1)}}
@keyframes vlsThArrows{0%,8%{opacity:0}20%,44%{opacity:1}58%,100%{opacity:.38}}
@@ -261,7 +238,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
<BrowserWindow x={16} y={12} w={128} h={72} />
<BrowserWindow x={176} y={12} w={128} h={72} />
{exit ? (
@@ -302,14 +279,14 @@ const HintTheaterExit: HintScene = ({ theme }) => (
);
/* hint-route-p2p: [two pawns apart] → [direct live-green arc pawn→pawn,
- live dot on the apex]. Loop 3.2s: arc draws 6-28%, both pawns hop 30-42%,
+ live dot on the apex]. Demo: arc draws 6-28%, both pawns hop 30-42%,
panel-1 pair blinks at 64%; rest ~58%. */
const HintRouteP2p: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-p2p-eyes{transform-box:fill-box;transform-origin:center;animation:vlsP2pBlink 3.2s ease-in-out infinite}
-.vls-p2p-arc{stroke-dasharray:1;animation:vlsP2pArc 3.2s ease-in-out infinite}
-.vls-p2p-hop{animation:vlsP2pHop 3.2s ease-in-out infinite}
+.vls-p2p-eyes{transform-box:fill-box;transform-origin:center;animation:vlsP2pBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-p2p-arc{stroke-dasharray:1;animation:vlsP2pArc var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-p2p-hop{animation:vlsP2pHop var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsP2pBlink{0%,60%,68%,100%{transform:scaleY(1)}64%{transform:scaleY(.12)}}
@keyframes vlsP2pArc{0%,6%{stroke-dashoffset:1}28%,100%{stroke-dashoffset:0}}
@keyframes vlsP2pHop{0%,30%{transform:translateY(0)}36%{transform:translateY(-4px)}42%,100%{transform:translateY(0)}}
@@ -322,17 +299,9 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
- <Pawn x={42} yb={74} s={9} />
- <g className="vls-p2p-eyes" fill={EYE}>
- <circle cx={45} cy={56} r={1} />
- <circle cx={48.5} cy={56} r={1} />
- </g>
- <Pawn x={118} yb={74} s={9} color={SKY} />
- <g className="vls-p2p-eyes" fill={EYE}>
- <circle cx={111.5} cy={56} r={1} />
- <circle cx={115} cy={56} r={1} />
- </g>
+ <Frame x={164} w={152} theme={theme} result />
+ <Pawn x={42} yb={74} s={9} eyes gaze={2} eyeClassName="vls-p2p-eyes" />
+ <Pawn x={118} yb={74} s={9} color={SKY} eyes gaze={-2} eyeClassName="vls-p2p-eyes" />
<g fill={FAINT}>
<circle cx={74} cy={60} r={1.5} />
<circle cx={88} cy={60} r={1.5} />
@@ -354,16 +323,25 @@ ${rmBlock(
</>
);
+// Unavailable server forwarding still leaves the ordinary direct route.
+const HintRouteP2pRequired: HintScene = ({ theme }) => (
+ <>
+ <HintRouteP2p theme={theme} />
+ <ServerBox x={64} y={16} w={32} h={24} />
+ <RedX cx={80} cy={28} arm={7} />
+ </>
+);
+
/* hint-route-sfu: [two pawns apart] → [two live-green arcs detour up
- through a lit server box]. Loop 3.2s: left arc 6-24%, right arc 14-32%,
+ through a lit server box]. Demo: left arc 6-24%, right arc 14-32%,
both pawns hop 34-46%, panel-1 pair blinks at 64%; rest ~54%. */
const HintRouteSfu: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-sfu-eyes{transform-box:fill-box;transform-origin:center;animation:vlsSfuBlink 3.2s ease-in-out infinite}
-.vls-sfu-a1{stroke-dasharray:1;animation:vlsSfuA1 3.2s ease-in-out infinite}
-.vls-sfu-a2{stroke-dasharray:1;animation:vlsSfuA2 3.2s ease-in-out infinite}
-.vls-sfu-hop{animation:vlsSfuHop 3.2s ease-in-out infinite}
+.vls-sfu-eyes{transform-box:fill-box;transform-origin:center;animation:vlsSfuBlink var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-sfu-a1{stroke-dasharray:1;animation:vlsSfuA1 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-sfu-a2{stroke-dasharray:1;animation:vlsSfuA2 var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-sfu-hop{animation:vlsSfuHop var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsSfuBlink{0%,60%,68%,100%{transform:scaleY(1)}64%{transform:scaleY(.12)}}
@keyframes vlsSfuA1{0%,6%{stroke-dashoffset:1}24%,100%{stroke-dashoffset:0}}
@keyframes vlsSfuA2{0%,14%{stroke-dashoffset:1}32%,100%{stroke-dashoffset:0}}
@@ -377,17 +355,9 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
- <Pawn x={42} yb={74} s={9} />
- <g className="vls-sfu-eyes" fill={EYE}>
- <circle cx={45} cy={56} r={1} />
- <circle cx={48.5} cy={56} r={1} />
- </g>
- <Pawn x={118} yb={74} s={9} color={SKY} />
- <g className="vls-sfu-eyes" fill={EYE}>
- <circle cx={111.5} cy={56} r={1} />
- <circle cx={115} cy={56} r={1} />
- </g>
+ <Frame x={164} w={152} theme={theme} result />
+ <Pawn x={42} yb={74} s={9} eyes gaze={2} eyeClassName="vls-sfu-eyes" />
+ <Pawn x={118} yb={74} s={9} color={SKY} eyes gaze={-2} eyeClassName="vls-sfu-eyes" />
<g fill={FAINT}>
<circle cx={74} cy={60} r={1.5} />
<circle cx={88} cy={60} r={1.5} />
@@ -432,8 +402,8 @@ const HintClientLocal: HintScene = ({ theme }) => (
const HintClientSite: HintScene = ({ theme }) => (
<>
<style>{`
-.vls-site-page{animation:vlsSitePage 3.2s ease-out infinite}
-.vls-site-star{transform-box:fill-box;transform-origin:center;animation:vlsSiteStar 3.2s cubic-bezier(.3,1.5,.5,1) infinite}
+.vls-site-page{animation:vlsSitePage var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-site-star{transform-box:fill-box;transform-origin:center;animation:vlsSiteStar var(--comic-duration,3.2s) cubic-bezier(.3,1.5,.5,1) var(--comic-repeat,1) both}
@keyframes vlsSitePage{0%,8%{transform:translateY(4px);opacity:0}28%,100%{transform:none;opacity:1}}
@keyframes vlsSiteStar{0%,28%{opacity:0;transform:scale(0)}36%{opacity:1;transform:scale(1.2)}44%,100%{opacity:1;transform:scale(1)}}
${rmBlock(
@@ -442,7 +412,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
<BrowserWindow x={24} y={18} w={120} h={64} />
<Pawn x={44} yb={75} s={8} eyes />
<ServerBox x={74} y={42} w={36} h={24} />
@@ -457,12 +427,13 @@ ${rmBlock(
/* hint-nat-prediction: [one direct path] -> [a small bounded fan of
alternate direct paths]. The scene describes extra direct chances without
- suggesting a media relay. */
-const HintNatPrediction: HintScene = ({ theme }) => (
+ suggesting a media relay. When unavailable, cross only the extra paths;
+ the ordinary path stays neutral rather than promising a connection. */
+const HintNatPrediction = ({ theme, available = true }: { theme: ComicTheme; available?: boolean }) => (
<>
<style>{`
-.vls-nat-path{stroke-dasharray:1;animation:vlsNatPath 3.2s ease-in-out infinite}
-.vls-nat-dots{animation:vlsNatDots 3.2s ease-in-out infinite}
+.vls-nat-path{stroke-dasharray:1;animation:vlsNatPath var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-nat-dots{animation:vlsNatDots var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsNatPath{0%,8%{stroke-dashoffset:1}30%,100%{stroke-dashoffset:0}}
@keyframes vlsNatDots{0%,32%,100%{opacity:.35}44%{opacity:1}}
${rmBlock(
@@ -471,7 +442,7 @@ ${rmBlock(
)}
`}</style>
<Frame x={4} w={152} theme={theme} />
- <Frame x={164} w={152} theme={theme} accent={LIVE} />
+ <Frame x={164} w={152} theme={theme} result />
<Pawn x={42} yb={76} s={9} />
<Pawn x={118} yb={76} s={9} color={SKY} />
<path
@@ -488,16 +459,17 @@ ${rmBlock(
</g>
<Pawn x={202} yb={76} s={9} eyes />
<Pawn x={278} yb={76} s={9} color={SKY} eyes />
- <g className="vls-nat-path" fill="none" stroke={LIVE} strokeWidth={2.5} strokeLinecap="round">
- <path d="M211 60 Q240 35 269 60" pathLength={1} />
- <path d="M211 64 Q240 52 269 64" pathLength={1} />
- </g>
- <g className="vls-nat-dots" fill={STAR_GOLD}>
- <circle cx={226} cy={48} r={2} />
- <circle cx={240} cy={39} r={2.5} />
- <circle cx={254} cy={48} r={2} />
+ <path d="M211 68 Q240 56 269 68" fill="none" stroke={FAINT} strokeWidth={2.5} strokeLinecap="round" />
+ <g className={available ? "vls-nat-path" : undefined} fill="none"
+ stroke={available ? LIVE : FAINT} strokeWidth={2.5} strokeLinecap="round"
+ strokeDasharray={available ? undefined : "4 4"}>
+ <path d="M211 58 Q240 10 269 58" pathLength={available ? 1 : undefined} />
+ <path d="M211 58 Q240 30 269 58" pathLength={available ? 1 : undefined} />
</g>
- <Spark x={240} y={26} />
+ {available ? <Spark x={240} y={24} /> : <>
+ <circle cx={240} cy={39} r={11} fill={theme === "paper" ? "var(--paper)" : "#0d1526"} />
+ <RedX cx={240} cy={39} arm={7} />
+ </>}
</>
);
@@ -505,13 +477,16 @@ export const SET4_SCENES: Record<Set4Kind, HintScene> = {
"hint-topology": HintTopology,
"hint-close": HintClose,
"hint-rename": HintRename,
- "hint-theme": HintTheme,
+ "hint-theme-light": (props) => <ThemeHint {...props} light />,
+ "hint-theme-dark": (props) => <ThemeHint {...props} light={false} />,
"hint-join-go": HintJoinGo,
"hint-theater": HintTheater,
"hint-theater-exit": HintTheaterExit,
"hint-route-p2p": HintRouteP2p,
+ "hint-route-p2p-required": HintRouteP2pRequired,
"hint-route-sfu": HintRouteSfu,
- "hint-nat-prediction": HintNatPrediction,
+ "hint-nat-prediction": (props) => <HintNatPrediction {...props} />,
+ "hint-nat-unavailable": (props) => <HintNatPrediction {...props} available={false} />,
"hint-client-local": HintClientLocal,
"hint-client-site": HintClientSite,
};
diff --git a/src/client/components/living/participant-color.ts b/src/client/components/living/participant-color.ts
index 311212ed..e7493e35 100644
--- a/src/client/components/living/participant-color.ts
+++ b/src/client/components/living/participant-color.ts
@@ -1,3 +1,4 @@
+// Theme tokens reserve warm upholstery and gold for the room and Host crown.
const PARTICIPANT_COLORS = [
"var(--pawn-1)", "var(--pawn-2)", "var(--pawn-3)", "var(--pawn-4)",
"var(--pawn-5)", "var(--pawn-6)", "var(--pawn-7)", "var(--pawn-8)",
diff --git a/src/client/components/living/participant-motion.ts b/src/client/components/living/participant-motion.ts
new file mode 100644
index 00000000..c3e4679a
--- /dev/null
+++ b/src/client/components/living/participant-motion.ts
@@ -0,0 +1,41 @@
+/** UUID selects a quiet cadence; wall time keeps independently mounted views in phase. */
+export function participantMotion(identity: string) {
+ let seed = 2166136261;
+ for (const char of identity) seed = Math.imul(seed ^ char.charCodeAt(0), 16777619);
+ seed >>>= 0;
+ return {
+ duration: 42_000 + (seed % 17_003),
+ offset: (seed >>> 8) % 59_003,
+ lean: seed & 1 ? 3 : -3,
+ gaze: seed & 2 ? 1.5 : -1.5,
+ };
+}
+
+export function participantMotionPhase(identity: string, now: number): number {
+ const { duration, offset } = participantMotion(identity);
+ return ((now + offset) % duration + duration) % duration;
+}
+
+/** Native animation timelines keep running without a JS tick or room messages. */
+export function bindParticipantMotion(root: SVGSVGElement, identity: string): () => void {
+ const sync = () => {
+ if (document.hidden) return;
+ const timeline = document.timeline.currentTime;
+ if (typeof timeline !== "number") return;
+ // Sample wall time at this rendered frame, not at each component's mount.
+ const phase = participantMotionPhase(identity, Date.now() - performance.now() + timeline);
+ for (const animation of root.getAnimations({ subtree: true })) {
+ if (animation instanceof CSSAnimation && animation.animationName.startsWith("lr-person-")) {
+ animation.startTime = timeline - phase;
+ }
+ }
+ };
+ // animationstart also covers returning from reduced motion.
+ root.addEventListener("animationstart", sync);
+ document.addEventListener("visibilitychange", sync);
+ sync();
+ return () => {
+ root.removeEventListener("animationstart", sync);
+ document.removeEventListener("visibilitychange", sync);
+ };
+}
diff --git a/src/client/components/living/pawn.css b/src/client/components/living/pawn.css
new file mode 100644
index 00000000..98d1bacf
--- /dev/null
+++ b/src/client/components/living/pawn.css
@@ -0,0 +1,22 @@
+.lr-person { overflow: visible; }
+.lr-person-body { transform-origin: 24px 48px; }
+.lr-person-eyes { transform-origin: 24px 14.1px; }
+@media (prefers-reduced-motion: no-preference) {
+ .lr-person[data-motion] .lr-person-body { animation: lr-person-lean var(--person-duration) ease-in-out infinite; }
+ .lr-person[data-motion] .lr-person-eyes { animation: lr-person-eyes var(--person-duration) ease-in-out infinite; }
+}
+@keyframes lr-person-lean {
+ 0%, 36%, 43%, 100% { transform: none; }
+ 38%, 41% { transform: rotate(var(--person-lean)); }
+}
+@keyframes lr-person-eyes {
+ 0%, 3%, 3.6%, 12%, 16%, 47%, 47.6%, 61%, 67%, 88%, 91%, 100% { transform: none; }
+ 3.3%, 47.3% { transform: scaleY(.14); }
+ 13%, 15% { transform: translate(var(--person-gaze-x), var(--person-gaze-y)); }
+ 62%, 63% { transform: translateX(-1.5px); }
+ 65%, 66% { transform: translateX(1.5px); }
+ 88.6% { transform: translate(0, -1.5px); }
+ 89.2% { transform: translate(1.3px, -.3px); }
+ 89.8% { transform: translate(0, 1.1px); }
+ 90.4% { transform: translate(-1.3px, -.3px); }
+}
diff --git a/src/client/components/living/playback-controls.css b/src/client/components/living/playback-controls.css
new file mode 100644
index 00000000..0774ef01
--- /dev/null
+++ b/src/client/components/living/playback-controls.css
@@ -0,0 +1,46 @@
+.lr-playback {
+ position: absolute;
+ inset: auto 0 0;
+ z-index: 4;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px max(6px, env(safe-area-inset-bottom));
+ border-top: 1.5px solid color-mix(in srgb, var(--ink) 24%, transparent);
+ color: var(--ink);
+ background: color-mix(in srgb, var(--paper) 78%, transparent);
+ box-shadow: 0 -4px 18px rgb(0 0 0 / 8%);
+ transition: opacity 180ms ease, transform 220ms var(--spring);
+}
+.lr-playback.is-hidden { opacity: 0; transform: translateY(6px); pointer-events: none; }
+.lr-tv-screen:has(> .lr-playback.is-hidden) > video { cursor: none; }
+.lr-playback .lr-btn {
+ display: grid; place-items: center; flex: none;
+ min-width: 0; width: 44px; height: 44px; padding: 0;
+ border: 0; border-radius: 10px; box-shadow: none;
+ background: transparent; color: inherit; cursor: pointer;
+ transition: transform 260ms var(--spring), background-color 140ms ease;
+}
+.lr-playback .lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: translateY(-2px); background: var(--wall-2); }
+.lr-playback .lr-btn:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.95); transition-duration: 80ms; }
+.lr-playback .lr-btn[aria-pressed="true"] { background: var(--wall-2); }
+.lr-playback-audio { display: flex; align-items: center; gap: 8px; min-width: 0; }
+.lr-playback-separator { width: 1px; height: 20px; background: currentColor; opacity: .22; }
+.lr-playback-volume { min-width: 0; }
+.lr-playback-volume input { width: clamp(64px, 14vw, 144px); min-width: 0; height: 36px; padding: 0; margin: 0; accent-color: var(--action); cursor: pointer; }
+.lr-playback-level { width: 4ch; text-align: right; font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.lr-playback-level.is-boosted { color: var(--action); }
+.lr-playback-view { display: inline-flex; align-items: center; gap: 4px; margin-left: auto; border-left: 1px solid var(--wall-2); padding-left: 8px; }
+.lr-tv-screen:fullscreen { width: 100%; height: 100%; border: 0; border-radius: 0; }
+.lr-tv-screen:has(> .lr-playback) { container-type: inline-size; }
+@container (max-width: 440px) {
+ .lr-playback { flex-wrap: wrap; gap: 2px 6px; padding: 4px 8px max(4px, env(safe-area-inset-bottom)); }
+ .lr-playback-audio { flex-basis: 100%; gap: 6px; }
+ .lr-playback-separator { display: none; }
+ .lr-playback-volume { flex: 1; }
+ .lr-playback-volume input { width: 100%; }
+ .lr-playback-view { gap: 2px; border: 0; padding: 0; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .lr-playback, .lr-playback .lr-btn { transition: none; }
+}
diff --git a/src/client/components/living/primitives.tsx b/src/client/components/living/primitives.tsx
index 95f7f797..95bf40c6 100644
--- a/src/client/components/living/primitives.tsx
+++ b/src/client/components/living/primitives.tsx
@@ -1,10 +1,11 @@
// Living-room control primitives. Every glyph control keeps its copy in
-// title/aria; text modes add a visible caption from the same catalog.
+// tooltip/aria; text modes add a visible caption from the same catalog.
import type { CSSProperties, MouseEvent, ReactNode } from "react";
-import { ComicTooltip } from "./ComicTooltip";
+import { Tooltip } from "./Tooltip";
import { participantColor } from "./participant-color";
import type { ComicKind } from "./Comic";
import type { HintKind } from "./hints";
+import type { ComicTone, ComicMotion } from "./comic-presentation";
import { Glyph, type GlyphName } from "../../ui/icons";
import { useCopy, type CopyKey } from "../../ui/copy";
@@ -62,6 +63,8 @@ export function Btn({
onClick,
type = "button",
hint,
+ hintTone,
+ hintMotion,
draw,
}: {
icon: GlyphName;
@@ -77,18 +80,19 @@ export function Btn({
type?: "button" | "submit";
/** Vis mode: 2-panel hint comic on hover/focus; native title stays off. */
hint?: HintKind;
+ hintTone?: ComicTone;
+ hintMotion?: ComicMotion;
/** Draw-in spot id for state-beat toggle icons (see Glyph). */
draw?: string;
}) {
const { t, vis } = useCopy();
const label = t(title);
- const wrapped = vis && hint;
+ const wrapped = !vis || Boolean(hint);
const softDisabled = Boolean(wrapped && disabled);
const button = (
<button
type={type}
className={`lr-btn${tone ? ` is-${tone}` : ""}`}
- title={vis ? undefined : label}
aria-label={label}
disabled={disabled && !softDisabled}
aria-disabled={softDisabled || undefined}
@@ -109,6 +113,7 @@ export function Btn({
}
>
<Glyph
+ key={draw ? (busy ? "loader" : icon) : undefined}
name={busy ? "loader" : icon}
size={19}
draw={draw}
@@ -118,7 +123,7 @@ export function Btn({
</button>
);
return wrapped ? (
- <ComicTooltip kind={wrapped}>{button}</ComicTooltip>
+ <Tooltip kind={hint} tone={hintTone} motion={hintMotion} text={vis ? undefined : label}>{button}</Tooltip>
) : (
button
);
@@ -145,7 +150,7 @@ export function Chip({
children: ReactNode;
}) {
const { vis } = useCopy();
- const wrapped = vis && hint;
+ const wrapped = !vis || Boolean(hint);
const softDisabled = Boolean(wrapped && disabled);
const chip = (
<button
@@ -157,7 +162,6 @@ export function Chip({
disabled={disabled && !softDisabled}
aria-disabled={softDisabled || undefined}
style={softDisabled ? SOFT_DISABLED_STYLE : undefined}
- title={vis ? undefined : title}
aria-label={title}
onClick={
softDisabled
@@ -174,7 +178,7 @@ export function Chip({
</button>
);
return wrapped ? (
- <ComicTooltip kind={wrapped}>{chip}</ComicTooltip>
+ <Tooltip kind={hint} text={vis ? undefined : title}>{chip}</Tooltip>
) : (
chip
);
@@ -216,20 +220,21 @@ export function Pill({
label,
alert,
comic,
+ tooltipTone,
}: {
icon: GlyphName;
tone?: "bad" | "good";
label: string;
alert?: boolean;
comic?: ComicKind | HintKind;
+ tooltipTone?: ComicTone;
}) {
const { vis } = useCopy();
- const wrapped = vis && comic;
+ const wrapped = !vis || Boolean(comic);
const body = (
<span
className={`lr-pill${tone ? ` is-${tone}` : ""}`}
role={alert ? "alert" : "status"}
- title={vis ? undefined : label}
// Hint-wrapped bodies must take keyboard focus, or the comic is
// unreachable for keyboard users (spans never match :focus-visible).
tabIndex={wrapped ? 0 : undefined}
@@ -239,7 +244,8 @@ export function Pill({
</span>
);
return wrapped ? (
- <ComicTooltip kind={wrapped}>{body}</ComicTooltip>
+ <Tooltip kind={comic} tone={tooltipTone ?? (tone === "good" ? "live" : tone === "bad" ? "bad" : "warn")}
+ motion={tone === "good" ? "still" : undefined} text={vis ? undefined : label}>{body}</Tooltip>
) : (
body
);
@@ -248,6 +254,7 @@ export function Pill({
export function SwitchItem({
checked,
disabled,
+ locked,
onChange,
label,
note,
@@ -255,16 +262,21 @@ export function SwitchItem({
}: {
checked: boolean;
disabled?: boolean;
+ /** Configuration fixes this switch's value; keep the control and explain why. */
+ locked?: boolean;
onChange: (checked: boolean) => void;
label: string;
- /** Text modes: extra sentence appended to the title tooltip. */
+ /** Text modes: extra sentence in the tooltip. */
note?: string;
/** Vis mode: 2-panel hint comic on hover/focus; native title stays off. */
hint?: HintKind;
}) {
- const { vis } = useCopy();
- const wrapped = vis && hint;
+ const { vis, t } = useCopy();
+ const wrapped = !vis || Boolean(hint);
const softDisabled = Boolean(wrapped && disabled);
+ const description = note ? `${label} · ${note}` : label;
+ const tooltipText = disabled || locked ? description
+ : `${t(checked ? "common.disable" : "common.enable", { name: label })}${note ? ` · ${note}` : ""}`;
const item = (
<span className="lr-switch-item">
<button
@@ -272,8 +284,7 @@ export function SwitchItem({
className="lr-switch"
role="switch"
aria-checked={checked}
- aria-label={label}
- title={vis ? undefined : note ? `${label} · ${note}` : label}
+ aria-label={description}
disabled={disabled && !softDisabled}
aria-disabled={softDisabled || undefined}
style={softDisabled ? SOFT_DISABLED_STYLE : undefined}
@@ -286,26 +297,28 @@ export function SwitchItem({
}
}
/>
+ {locked ? <Glyph name="lock" size={12} /> : null}
{vis ? null : <span className="lr-cap">{label}</span>}
</span>
);
return wrapped ? (
- <ComicTooltip kind={wrapped}>{item}</ComicTooltip>
+ <Tooltip kind={hint} text={vis ? undefined : tooltipText}>{item}</Tooltip>
) : (
item
);
}
export function NameTag({ name, identity }: { name: string; identity: string }) {
- const { t, vis } = useCopy();
return (
- <span className="lr-name-tag" title={vis ? undefined : t("host.name")}>
- <i
- aria-hidden="true"
- style={{ backgroundColor: participantColor(identity) }}
- />
- <span>{name}</span>
- </span>
+ <Tooltip text={name} className="lr-name-hint">
+ <span className="lr-name-tag" tabIndex={0}>
+ <i
+ aria-hidden="true"
+ style={{ backgroundColor: participantColor(identity) }}
+ />
+ <span>{name}</span>
+ </span>
+ </Tooltip>
);
}
@@ -313,12 +326,3 @@ export function FieldCap({ k }: { k: CopyKey }) {
const { vis, t } = useCopy();
return vis ? null : <span className="lr-field-cap">{t(k)}</span>;
}
-
-export function StatusText({ children }: { children: ReactNode }) {
- const { vis } = useCopy();
- return vis ? null : (
- <span className="lr-status-text" role="status" aria-live="polite">
- {children}
- </span>
- );
-}
diff --git a/src/client/components/living/status-indicator.css b/src/client/components/living/status-indicator.css
new file mode 100644
index 00000000..2f2604ed
--- /dev/null
+++ b/src/client/components/living/status-indicator.css
@@ -0,0 +1,23 @@
+.lr-status-indicator {
+ --status-colour: var(--ink-soft, #8ea3b8);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 24px;
+ min-width: 24px;
+ padding: 2px;
+ color: var(--status-colour);
+ border-radius: 8px;
+ vertical-align: middle;
+}
+.lr-status-indicator[data-tone="live"] { --status-colour: var(--live); }
+.lr-status-indicator[data-tone="busy"] { --status-colour: var(--action); }
+.lr-status-indicator[data-tone="warn"] { --status-colour: var(--warn); }
+.lr-status-indicator[data-tone="bad"] { --status-colour: var(--danger); }
+.lr-status-indicator:focus-visible { outline: 2px solid var(--action); outline-offset: 2px; }
+.lr-status-indicator[data-pulse] > svg { animation: lr-status-breathe 1.6s ease-in-out infinite; }
+.lr-status-indicator > svg { flex-shrink: 0; }
+@keyframes lr-status-breathe { 50% { opacity: .35; } }
+@media (prefers-reduced-motion: reduce) {
+ .lr-status-indicator[data-pulse] > svg { animation: none; }
+}
diff --git a/src/client/components/living/use-picture-in-picture.ts b/src/client/components/living/use-picture-in-picture.ts
new file mode 100644
index 00000000..2e4dbf60
--- /dev/null
+++ b/src/client/components/living/use-picture-in-picture.ts
@@ -0,0 +1,66 @@
+import { useEffect, useState, type RefObject } from "react";
+
+type PictureVideo = HTMLVideoElement & {
+ webkitPresentationMode?: string;
+ webkitSupportsPresentationMode?: (mode: string) => boolean;
+ webkitSetPresentationMode?: (mode: string) => void;
+};
+
+export async function leavePictureInPicture(video: PictureVideo): Promise<void> {
+ if (document.pictureInPictureElement === video) {
+ await document.exitPictureInPicture();
+ } else if (video.webkitPresentationMode === "picture-in-picture") {
+ video.webkitSetPresentationMode?.("inline");
+ }
+}
+
+// The browser owns the window and its lifecycle, including its close button.
+export function usePictureInPicture(videoRef: RefObject<HTMLVideoElement | null>) {
+ const [supported, setSupported] = useState(false);
+ const [active, setActive] = useState(false);
+ const [failed, setFailed] = useState(false);
+
+ useEffect(() => {
+ const video = videoRef.current as PictureVideo | null;
+ if (!video) return;
+ const sync = () => {
+ setSupported(Boolean(
+ (document.pictureInPictureEnabled && video.requestPictureInPicture) ||
+ (video.webkitSetPresentationMode && video.webkitSupportsPresentationMode?.("picture-in-picture")),
+ ));
+ setActive(document.pictureInPictureElement === video || video.webkitPresentationMode === "picture-in-picture");
+ setFailed(false);
+ };
+ const events = ["enterpictureinpicture", "leavepictureinpicture", "webkitpresentationmodechanged", "loadedmetadata", "emptied"];
+ events.forEach((event) => video.addEventListener(event, sync));
+ sync();
+ return () => {
+ events.forEach((event) => video.removeEventListener(event, sync));
+ void leavePictureInPicture(video).catch(() => undefined);
+ };
+ }, [videoRef]);
+
+ const toggle = async () => {
+ const video = videoRef.current as PictureVideo | null;
+ if (!video) return;
+ setFailed(false);
+ try {
+ if (document.pictureInPictureElement === video || video.webkitPresentationMode === "picture-in-picture") {
+ await leavePictureInPicture(video);
+ } else {
+ if (document.pictureInPictureEnabled && video.requestPictureInPicture) {
+ await video.requestPictureInPicture();
+ } else if (video.webkitSupportsPresentationMode?.("picture-in-picture")) {
+ video.webkitSetPresentationMode?.("picture-in-picture");
+ }
+ // Request first: entering needs the click's transient user activation.
+ if (document.fullscreenElement === video.parentElement) await document.exitFullscreen();
+ }
+ } catch {
+ // An OS/user-policy rejection affects this action, never media recovery.
+ setFailed(true);
+ }
+ };
+
+ return { supported, active, failed, toggle };
+}
diff --git a/src/client/components/living/use-playback-controls-visibility.ts b/src/client/components/living/use-playback-controls-visibility.ts
new file mode 100644
index 00000000..5c01dc2e
--- /dev/null
+++ b/src/client/components/living/use-playback-controls-visibility.ts
@@ -0,0 +1,105 @@
+import { useEffect, useRef, useState, type RefObject } from "react";
+
+// Matches Media Chrome's default: hide playing-video controls after 2s idle.
+const CONTROLS_IDLE_MS = 2000;
+
+export function usePlaybackControlsVisibility(
+ videoRef: RefObject<HTMLVideoElement | null>,
+ controlsRef: RefObject<HTMLDivElement | null>,
+ keepVisible: boolean,
+): boolean {
+ const [hidden, setHidden] = useState(false);
+ const pointerType = useRef("");
+
+ useEffect(() => {
+ const video = videoRef.current;
+ const screen = video?.parentElement;
+ const controls = controlsRef.current;
+ if (!video || !screen || !controls) return;
+ const listeners = new AbortController();
+ const options = { signal: listeners.signal };
+ let timer: number | undefined;
+ let lastMove: { x: number; y: number } | undefined;
+ let pressed = false;
+ let hoveringControls = pointerType.current !== "touch" && controls.matches(":hover");
+
+ const clearIdle = () => {
+ window.clearTimeout(timer);
+ timer = undefined;
+ };
+ const held = () => keepVisible || pressed || hoveringControls ||
+ (screen.contains(document.activeElement) && document.activeElement?.matches(":focus-visible")) ||
+ controls.querySelector(":popover-open") !== null;
+ const scheduleHide = () => {
+ clearIdle();
+ if (held()) return;
+ timer = window.setTimeout(() => {
+ timer = undefined;
+ if (!held()) setHidden(true);
+ }, CONTROLS_IDLE_MS);
+ };
+ const show = () => {
+ setHidden(false);
+ scheduleHide();
+ };
+ const release = () => {
+ if (!pressed) return;
+ pressed = false;
+ show();
+ };
+
+ screen.addEventListener("pointermove", (event) => {
+ if (event.pointerType === "touch") return;
+ // Cursor/style changes can emit stationary moves (Video.js #1068).
+ if (lastMove?.x === event.screenX && lastMove.y === event.screenY) return;
+ lastMove = { x: event.screenX, y: event.screenY };
+ show();
+ }, options);
+ screen.addEventListener("pointerdown", (event) => {
+ pointerType.current = event.pointerType;
+ if (event.pointerType === "touch") hoveringControls = false;
+ if (controls.contains(event.target as Node)) {
+ pressed = true;
+ show();
+ }
+ }, options);
+ controls.addEventListener("pointerenter", (event) => {
+ if (event.pointerType !== "touch") {
+ hoveringControls = true;
+ show();
+ }
+ }, options);
+ controls.addEventListener("pointerleave", (event) => {
+ if (event.pointerType !== "touch") {
+ hoveringControls = false;
+ scheduleHide();
+ }
+ }, options);
+ screen.addEventListener("click", (event) => {
+ // Native click excludes scrolling/cancelled gestures. A video tap only
+ // reveals/hides controls; playback remains owned by the play button.
+ if (event.target === video && pointerType.current === "touch" && !held()) {
+ setHidden((current) => !current);
+ scheduleHide();
+ }
+ }, options);
+ screen.addEventListener("focusin", show, options);
+ screen.addEventListener("focusout", scheduleHide, options);
+ screen.addEventListener("keydown", show, options);
+ // Popovers retain their DOM parent in the top layer. Their native toggle
+ // event resumes idle hiding after a tooltip/long-press has finished.
+ controls.addEventListener("toggle", show, { ...options, capture: true });
+ document.addEventListener("pointerup", release, options);
+ document.addEventListener("pointercancel", () => {
+ pointerType.current = "";
+ release();
+ }, options);
+ show();
+ return () => {
+ clearIdle();
+ listeners.abort();
+ };
+ }, [videoRef, controlsRef, keepVisible]);
+
+ return keepVisible ? false : hidden;
+}
diff --git a/src/client/lib/debug.ts b/src/client/lib/debug.ts
index 857de3a5..d7c1c4e2 100644
--- a/src/client/lib/debug.ts
+++ b/src/client/lib/debug.ts
@@ -137,6 +137,7 @@ function snapshot(): BrowserDebugEvent[] {
}
export async function exportBrowserDebug(): Promise<string> {
+ const buildEnvironment = (import.meta as ImportMeta & { env?: Record<string, string> }).env;
const collectorErrors: object[] = [];
let environment: object = {};
try {
@@ -161,6 +162,8 @@ export async function exportBrowserDebug(): Promise<string> {
}
return JSON.stringify({
capturedAt: new Date().toISOString(), startedAt, protocol: SIGNALING_PROTOCOL,
+ build: { version: buildEnvironment?.VITE_PIIK_VERSION ?? "development",
+ revision: buildEnvironment?.VITE_PIIK_REVISION ?? "development" },
asset: new URL(import.meta.url).pathname.split("/").at(-1),
environment: sanitize(environment).value,
history: { maxEvents: MAX_EVENTS, maxBytes: MAX_BYTES, retainedBytes,
diff --git a/src/client/lib/display-name.ts b/src/client/lib/display-name.ts
index b612074c..5c213e43 100644
--- a/src/client/lib/display-name.ts
+++ b/src/client/lib/display-name.ts
@@ -40,7 +40,7 @@ export function defaultViewerDisplayName(
export function defaultHostDisplayName(
visual = false,
): DisplayName {
- return (visual ? "👑" : say("common.name.hostDefault")) as DisplayName;
+ return (visual ? "📺" : say("common.name.hostDefault")) as DisplayName;
}
export function saveDisplayName(
diff --git a/src/client/lib/release-update.ts b/src/client/lib/release-update.ts
index 91c78633..a83478fd 100644
--- a/src/client/lib/release-update.ts
+++ b/src/client/lib/release-update.ts
@@ -1,110 +1,141 @@
+import { compare, valid } from "semver";
+
export const DEFAULT_RELEASE_API_URL =
"https://api.github.com/repos/TNTcraftHIM/Piik/releases/latest";
+export const MIRROR_RELEASE_API_URL = "https://gitee.com/api/v5/repos/TNTcraftHIM/Piik/releases";
+const RELEASE_PAGE = "https://github.com/TNTcraftHIM/Piik/releases/tag/";
+const MIRROR_RELEASE_PAGE = "https://gitee.com/TNTcraftHIM/Piik/releases/tag/";
-const FULL_REVISION = /^[0-9a-f]{40}$/i;
-const RELEASE_PATH_PREFIX = "/TNTcraftHIM/Piik/releases/tag/";
-
-export interface ReleaseUpdateNotice {
+export interface ReleaseIdentity {
+ version: string;
revision: string;
+}
+interface PublishedRelease {
+ version: string;
+ revision: string | null;
url: string;
}
+export interface ReleaseUpdateNotice extends PublishedRelease {
+ kind: "update-available" | "different-build" | "official-release";
+}
export function normalizeReleaseRevision(value: unknown): string | null {
const revision = typeof value === "string" ? value.trim().toLowerCase() : "";
- return FULL_REVISION.test(revision) ? revision : null;
+ return /^[0-9a-f]{40}$/.test(revision) ? revision : null;
}
-export function parseReleaseMetadata(value: unknown): ReleaseUpdateNotice | null {
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- return null;
- }
- const release = value as {
- draft?: unknown;
- prerelease?: unknown;
- tag_name?: unknown;
- html_url?: unknown;
+function normalizeVersion(value: unknown): string | null {
+ const version = typeof value === "string" ? valid(value) : null;
+ return version ? `v${version}` : null;
+}
+
+export function parseReleaseMetadata(value: unknown): PublishedRelease | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const release = value as Record<string, unknown>;
+ if ((release.draft !== undefined && release.draft !== false) ||
+ (release.prerelease !== undefined && release.prerelease !== false)) return null;
+ const version = normalizeVersion(release.tag_name);
+ if (!version || version !== release.tag_name || !/^v\d+\.\d+\.\d+$/.test(version) ||
+ release.html_url !== RELEASE_PAGE + version) return null;
+ return {
+ version,
+ // GitHub permits a branch here; only our publisher's full SHA is provenance.
+ revision: normalizeReleaseRevision(release.target_commitish),
+ url: RELEASE_PAGE + version,
};
- if (release.draft === true || release.prerelease === true) {
- return null;
- }
- const revision = normalizeReleaseRevision(release.tag_name);
- if (!revision || typeof release.html_url !== "string") {
- return null;
- }
+}
- let releaseURL: URL;
- try {
- releaseURL = new URL(release.html_url);
- } catch {
- return null;
- }
- if (
- releaseURL.protocol !== "https:" ||
- releaseURL.hostname !== "github.com" ||
- releaseURL.username ||
- releaseURL.password ||
- releaseURL.port ||
- releaseURL.search ||
- releaseURL.hash ||
- !releaseURL.pathname.startsWith(RELEASE_PATH_PREFIX)
- ) {
- return null;
- }
- let tag = "";
- try {
- tag = decodeURIComponent(releaseURL.pathname.slice(RELEASE_PATH_PREFIX.length));
- } catch {
+export function parseMirrorReleaseMetadata(value: unknown): PublishedRelease | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const release = value as Record<string, unknown>;
+ if (release.prerelease !== false || typeof release.body !== "string") return null;
+ const sources = [...release.body.matchAll(/^<!-- piik-source: ([0-9a-f]{40}) -->\r?$/gm)];
+ if (sources.length !== 1) return null;
+ // The mirror tag identifies its README commit, never the original Piik source.
+ const normalized = parseReleaseMetadata({
+ tag_name: release.tag_name, html_url: RELEASE_PAGE + String(release.tag_name),
+ target_commitish: sources[0][1],
+ });
+ return normalized ? { ...normalized, url: MIRROR_RELEASE_PAGE + normalized.version } : null;
+}
+
+export function releaseUpdateNotice(
+ current: ReleaseIdentity,
+ latest: PublishedRelease,
+): ReleaseUpdateNotice | null {
+ const version = normalizeVersion(current.version);
+ const revision = normalizeReleaseRevision(current.revision);
+ if (version) {
+ const order = compare(latest.version, version);
+ if (order > 0) return { ...latest, kind: "update-available" };
+ if (order === 0 && revision && latest.revision && revision !== latest.revision) {
+ return { ...latest, kind: "different-build" };
+ }
return null;
}
- return normalizeReleaseRevision(tag) === revision
- ? { revision, url: releaseURL.toString() }
+ return revision && latest.revision && revision !== latest.revision
+ ? { ...latest, kind: "official-release" }
: null;
}
export async function checkReleaseUpdate(
- currentRevision: unknown,
+ current: ReleaseIdentity,
options: {
apiURL?: string;
+ mirrorAPIURL?: string;
fetchImpl?: typeof fetch;
timeoutMs?: number;
} = {},
): Promise<ReleaseUpdateNotice | null> {
- const current = normalizeReleaseRevision(currentRevision);
- if (!current) return null;
- const endpoint = options.apiURL ?? DEFAULT_RELEASE_API_URL;
- let parsedEndpoint: URL;
- try {
- parsedEndpoint = new URL(endpoint);
- } catch {
- return null;
- }
- if (parsedEndpoint.protocol !== "https:" && parsedEndpoint.protocol !== "http:") {
- return null;
- }
+ if (!normalizeVersion(current.version) && !normalizeReleaseRevision(current.revision)) return null;
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
if (typeof fetchImpl !== "function") return null;
- const controller = new AbortController();
- const timer = globalThis.setTimeout(
- () => controller.abort(),
- options.timeoutMs ?? 3_000,
- );
- try {
- const response = await fetchImpl(parsedEndpoint.toString(), {
- cache: "no-store",
- credentials: "omit",
- headers: {
- Accept: "application/vnd.github+json",
- "X-GitHub-Api-Version": "2022-11-28",
- },
- redirect: "error",
- signal: controller.signal,
- });
- if (!response.ok) return null;
- const latest = parseReleaseMetadata(await response.json());
- return latest && latest.revision !== current ? latest : null;
- } catch {
- return null;
- } finally {
- globalThis.clearTimeout(timer);
+ const sources = [
+ { url: options.apiURL ?? DEFAULT_RELEASE_API_URL, mirror: false },
+ { url: options.mirrorAPIURL ?? (options.apiURL ? undefined : MIRROR_RELEASE_API_URL), mirror: true },
+ ];
+ for (const source of sources) {
+ if (!source.url) continue;
+ const controller = new AbortController();
+ const timer = globalThis.setTimeout(() => controller.abort(), options.timeoutMs ?? 3_000);
+ try {
+ const endpoint = new URL(source.url);
+ if (endpoint.protocol !== "https:" && endpoint.protocol !== "http:") continue;
+ let latest: PublishedRelease | null = null;
+ // Bound both time and pages. Never treat a truncated mirror list as latest.
+ for (let page = 1; page <= 10; page++) {
+ if (source.mirror) {
+ endpoint.searchParams.set("per_page", "100");
+ endpoint.searchParams.set("page", String(page));
+ endpoint.searchParams.set("direction", "desc");
+ }
+ const response = await fetchImpl(endpoint.toString(), {
+ cache: "no-store", credentials: "omit", redirect: "error", signal: controller.signal,
+ headers: source.mirror ? { Accept: "application/json" } :
+ { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
+ });
+ if (!response.ok) break;
+ const data: unknown = await response.json();
+ if (!source.mirror) {
+ latest = parseReleaseMetadata(data);
+ if (latest) return releaseUpdateNotice(current, latest);
+ break;
+ }
+ if (!Array.isArray(data) || data.length > 100) break;
+ for (const value of data) {
+ const candidate = parseMirrorReleaseMetadata(value);
+ if (candidate && (!latest || compare(candidate.version, latest.version) > 0)) latest = candidate;
+ }
+ if (data.length < 100) {
+ if (latest) return releaseUpdateNotice(current, latest);
+ break;
+ }
+ }
+ } catch {
+ // A blocked, timed-out or malformed provider leaves the next source usable.
+ } finally {
+ globalThis.clearTimeout(timer);
+ }
}
+ return null;
}
diff --git a/src/client/lib/session.ts b/src/client/lib/session.ts
index 56768b54..a2fc7fa2 100644
--- a/src/client/lib/session.ts
+++ b/src/client/lib/session.ts
@@ -98,6 +98,23 @@ export function parseAppRoute(pathname: string): AppRoute {
export interface ClientLaunchBootstrap {
accessToken: string | null;
launchedByClient: boolean;
+ presentation: ClientLaunchPresentation | null;
+}
+
+export interface ClientLaunchPresentation {
+ lang: "zh" | "en";
+ vis: boolean;
+ theme: "light" | "dark" | null;
+}
+
+export function clientLaunchURL(target: string, presentation: ClientLaunchPresentation): string {
+ const url = new URL(target);
+ const params = new URLSearchParams(url.hash.slice(1));
+ params.set("piik-lang", presentation.lang);
+ params.set("piik-mode", presentation.vis ? "vis" : "text");
+ params.set("piik-theme", presentation.theme ?? "system");
+ url.hash = params.toString();
+ return url.toString();
}
export function takeClientLaunchBootstrap(): ClientLaunchBootstrap {
@@ -105,10 +122,16 @@ export function takeClientLaunchBootstrap(): ClientLaunchBootstrap {
const keys = [
"client-access",
"piik-client",
+ "piik-lang",
+ "piik-mode",
+ "piik-theme",
] as const;
const present = keys.some((key) => params.has(key));
const accessValue = params.get("client-access");
const launchedFromFragment = params.get("piik-client") === "1";
+ const lang = params.get("piik-lang");
+ const mode = params.get("piik-mode");
+ const theme = params.get("piik-theme");
let launchedByClient = launchedFromFragment;
try {
if (launchedFromFragment) {
@@ -126,6 +149,11 @@ export function takeClientLaunchBootstrap(): ClientLaunchBootstrap {
? accessValue
: null,
launchedByClient,
+ presentation: launchedFromFragment && (lang === "zh" || lang === "en") &&
+ (mode === "vis" || mode === "text") &&
+ (theme === "light" || theme === "dark" || theme === "system")
+ ? { lang, vis: mode === "vis", theme: theme === "system" ? null : theme }
+ : null,
};
if (present) {
for (const key of keys) params.delete(key);
diff --git a/src/client/lib/use-element-width.ts b/src/client/lib/use-element-width.ts
new file mode 100644
index 00000000..85e454ef
--- /dev/null
+++ b/src/client/lib/use-element-width.ts
@@ -0,0 +1,20 @@
+import { useLayoutEffect, useRef, useState } from "react";
+
+/** Measure the actual panel, including when its parent changes without a viewport resize. */
+export function useElementWidth(initialWidth = 640) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(initialWidth);
+ useLayoutEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ const measure = () => {
+ const next = Math.round(element.getBoundingClientRect().width);
+ if (next > 0) setWidth(next);
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+ return [ref, width] as const;
+}
diff --git a/src/client/locales/en.ts b/src/client/locales/en.ts
index 0306f01b..092cd184 100644
--- a/src/client/locales/en.ts
+++ b/src/client/locales/en.ts
@@ -2,6 +2,21 @@ import type { CopyKey, TitleFrameCatalog } from "./zh";
// Community translations are data-only and type-checked against zh.
export const en: Record<CopyKey, string> = {
+ "playback.controls": "Local playback controls",
+ "playback.play": "Play",
+ "playback.pause": "Pause on this device",
+ "playback.mute": "Mute",
+ "playback.unmute": "Unmute",
+ "playback.noAudio": "No audio in this share",
+ "playback.volume": "Adjust volume, from 0% to 200%",
+ "playback.volumeBasic": "Adjust volume, from 0% to 100%",
+ "playback.fullscreen": "Fullscreen",
+ "playback.exitFullscreen": "Exit fullscreen",
+ "playback.pip": "Picture in picture",
+ "playback.exitPip": "Return to the page",
+ "playback.pipUnavailable": "Picture in picture is unavailable in this browser",
+ "playback.pipFailed": "Could not switch picture in picture; try again",
+ "playback.pipWaiting": "Picture in picture is available once the video is ready",
"debug.export": "Debug report",
"debug.exportHint": "Download local diagnostics; may include network addresses and device details",
"debug.exportFailed": "Could not download diagnostics; try again",
@@ -16,14 +31,42 @@ export const en: Record<CopyKey, string> = {
"common.refresh": "Refresh page",
"common.edit": "Edit",
"common.close": "Close",
+ "common.enable": "Enable {name}",
+ "common.disable": "Disable {name}",
+ "host.join.hide": "Hide room entry",
+ "host.advanced.hide": "Hide advanced settings",
+ "host.password.settingsHide": "Hide password settings",
+ "host.sourcePicker.audioOn": "Share sound",
+ "host.sourcePicker.audioOff": "Stop sharing sound",
+ "host.sourcePicker.audioLocked": "Sound sharing stays unchanged when switching sources",
"common.viewers": "Viewers",
"common.you": "you",
"common.host": "Host",
"common.name.viewerDefault": "Viewer",
"common.name.hostDefault": "Host",
+ "welcome.seat": "Your seat is right here.",
+ "welcome.player": "Single-player story. Multiplayer audience.",
+ "welcome.cut": "Three, two, one… roll it.",
+ "welcome.quest": "Side quest: share a little joy.",
+ "welcome.snack": "Snacks optional. Good company recommended.",
+ "welcome.scene": "And now, your scene.",
+ "welcome.save": "Save your game. Stay a while.",
+ "welcome.achievement": "Unlocked: someone who gets it.",
+ "welcome.popcorn": "Big moment ahead. Bring snacks.",
+ "welcome.credits": "Stay for the credits. There might be a surprise.",
+ "welcome.replay": "Some moments deserve a second audience.",
+ "welcome.guide": "You lead. I'll bring the folding chair.",
+ "welcome.wander": "No main quest today. Let's wander.",
+ "welcome.witness": "Every great moment needs a witness.",
+ "welcome.discovery": "Made a little something. Come take a look.",
+ "welcome.party": "One screen. A very enthusiastic audience.",
+ "welcome.director": "What's on the shot list, director?",
+ "welcome.next": "Next level? Bring your people.",
+ "welcome.share": "Joy travels well.",
+ "welcome.seats": "Twenty seats. Plenty of stories.",
+
"client.launch.title": "Open Piik",
- "client.launch.hint": "Choose how to connect this time",
"client.launch.local": "Local room",
"client.launch.localHint": "Use on the same local network",
"client.launch.link": "Public invite",
@@ -31,14 +74,15 @@ export const en: Record<CopyKey, string> = {
"client.launch.site": "Connect to Site",
"client.launch.siteHint": "Use an existing Piik Site",
"client.launch.siteAddress": "Piik Site address",
- "client.launch.localAccess": "Local site password (optional)",
- "client.launch.localAccessHint": "Leave blank for open access; fill it to require a password",
- "client.launch.localAccessPlaceholder": "Leave blank for open access",
+ "client.launch.localAccess": "Site passphrase (optional)",
+ "client.launch.localAccessHint": "If set, visitors enter this passphrase before accessing your site. Use 8–128 English letters, numbers or keyboard symbols, without spaces.",
"client.launch.go": "Open Piik",
"client.launch.starting": "Preparing Piik",
"client.launch.error": "Piik could not start; check the setting and retry",
"client.launch.loadFailed": "Could not read the launcher settings; retry",
"client.update.available": "A newer Piik release is available",
+ "client.update.differentBuild": "This build differs from the official release",
+ "client.update.official": "An official Piik release is available",
"gate.title": "Site access",
"gate.hint": "Enter the site passphrase",
@@ -63,8 +107,6 @@ export const en: Record<CopyKey, string> = {
"join.full": "Room is full",
"host.title": "{name}'s screen",
- "host.idle.heading": "Something worth watching?",
- "host.idle.hint": "Share your screen and friends can drop in with the room code or invite link.",
"host.start": "Start sharing",
"host.sourcePicker.title": "Choose what to share",
"host.sourcePicker.browser": "Browser picker",
@@ -75,7 +117,10 @@ export const en: Record<CopyKey, string> = {
"host.sourcePicker.windowAudio": "Application sound",
"host.sourcePicker.systemAudio": "System sound",
"host.sourcePicker.empty": "No sources available",
- "host.sourcePicker.nativeAudio": "Piik App · with sound",
+ "native.incompatible": "Piik App and this page are incompatible. Update Piik App and reload this page, or use Browser.",
+ "native.fail.edge": "Piik App media connection failed",
+ "native.fail.signaling": "Piik App signaling failed",
+ "native.fail.receiver": "Piik App media receive failed",
"host.sourcePicker.window": "Share window: {title}",
"host.sourcePicker.display": "Share screen: {title}",
"host.sourcePicker.system": "System screen or window picker",
@@ -98,7 +143,6 @@ export const en: Record<CopyKey, string> = {
"host.noAudio": "This source has no shareable audio",
"host.localPreviewPaused": "Local preview paused; sharing continues",
"host.pauseNotice": "Audio and video sharing paused",
- "host.resumeNotice": "Audio and video sharing resumed",
"host.stopNotice": "Sharing stopped",
"host.roomReplaced": "Room code replaced",
"host.roomInvalid": "Room no longer available; press again to create a new one",
@@ -188,9 +232,13 @@ export const en: Record<CopyKey, string> = {
"host.advanced.route.peerOnly": "Privacy mode",
"host.advanced.route.peerOnlyHint":
"Use P2P routes only; viewers without a P2P path cannot watch",
+ "host.advanced.route.peerOnlyRequired":
+ "This instance has no media-server fallback, so Privacy mode stays on; viewers need a P2P path",
"host.advanced.route.natPrediction": "NAT traversal",
"host.advanced.route.natPredictionHint":
"Use self-hosted STUN for a bounded set of extra direct attempts; ordinary ICE is unchanged",
+ "host.advanced.route.natPredictionUnavailable":
+ "Extra NAT traversal is not enabled on this instance; ordinary P2P still works",
"host.advanced.codec": "Video codec",
"host.advanced.codec.auto": "Auto",
"host.advanced.codec.autoHint": "Pick automatically",
@@ -207,7 +255,9 @@ export const en: Record<CopyKey, string> = {
"state.signal.connected": "Server connected",
"state.signal.connecting": "Connecting",
"state.signal.reconnecting": "Recovering",
- "state.signal.offline": "Server offline",
+ "state.signal.offline": "Not connected to server",
+ "state.presence.online": "Online",
+ "state.presence.offline": "Offline",
"state.peer.connected": "Connected",
"state.peer.connecting": "Connecting",
"state.peer.routing": "Routing",
@@ -247,6 +297,7 @@ export const en: Record<CopyKey, string> = {
"stats.inputFps": "Encoder input rate",
"stats.encodeMs": "Encode time/frame",
"stats.decodeMs": "Decode time/frame",
+ "state.peer.stuttering": "Recent playback stutter",
"stats.freezeCount": "Freezes",
"stats.freezeDuration": "Freeze duration",
"stats.audioLoss": "Audio packet loss",
@@ -261,7 +312,7 @@ export const en: Record<CopyKey, string> = {
"viewer.titleFallback": "A friend's screen",
"viewer.title.watching": "Watching",
"viewer.title.waiting": "Waiting",
- "viewer.reconnect": "Reconnect media",
+ "viewer.reconnect": "Reconnect",
"viewer.theater": "Theater mode",
"viewer.theater.exit": "Exit theater mode",
"viewer.msg.joining": "Joining the room",
@@ -314,7 +365,6 @@ export const en: Record<CopyKey, string> = {
"gate.expired": "Site access expired; verify again",
"gate.serviceUnavailable": "Site access service unavailable ({status})",
- "host.onlineCount": "{n} / {max} online",
"host.notStarted": "Not started",
"host.startCancelled": "Start cancelled",
"host.switchingSource": "Switching source",
@@ -376,7 +426,7 @@ export const en: Record<CopyKey, string> = {
"host.warn.param.scaleResolutionDownBy": "resolution scaling",
"host.warn.param.degradationPreference": "quality preference",
"host.warn.param.scalabilityMode": "scalability mode",
- "host.warn.sfuRecover": "SFU {stage} failed; automatic recovery started",
+ "host.warn.sfuRecover": "SFU {params} failed; automatic recovery started",
"host.warn.sfuStage.connect": "connect",
"host.warn.sfuStage.source": "source",
"host.warn.sfuStage.videoPublish": "video publish",
@@ -440,6 +490,9 @@ export const enTitleFrames = {
"Waiting for showtime",
"Quiet little room",
],
+ viewerReady: ["Press Play"],
+ viewerUnavailable: ["Unavailable"],
+ hostUnavailable: [en["host.fail.start"]],
viewerWaiting: [
en["viewer.title.waiting"],
"Waiting for showtime",
diff --git a/src/client/locales/visual.ts b/src/client/locales/visual.ts
index 1a29dbe4..ad74655f 100644
--- a/src/client/locales/visual.ts
+++ b/src/client/locales/visual.ts
@@ -53,6 +53,9 @@ export const visualTitleFrames = {
"📺 🫧",
"💤 ✨",
],
+ viewerReady: ["▶️"],
+ viewerUnavailable: ["❗"],
+ hostUnavailable: ["❗"],
viewerWaiting: [
"⏳",
"⏳ 👀",
diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.ts
index 3a0096c8..219c6ebc 100644
--- a/src/client/locales/zh.ts
+++ b/src/client/locales/zh.ts
@@ -1,5 +1,20 @@
// Canonical catalog: add keys here first; every other locale must match it.
export const zh = {
+ "playback.controls": "本机播放控制",
+ "playback.play": "播放",
+ "playback.pause": "暂停本机播放",
+ "playback.mute": "静音",
+ "playback.unmute": "取消静音",
+ "playback.noAudio": "分享源没有音频",
+ "playback.volume": "调节音量,支持 0%–200%",
+ "playback.volumeBasic": "调节音量,支持 0%–100%",
+ "playback.fullscreen": "全屏观看",
+ "playback.exitFullscreen": "退出全屏",
+ "playback.pip": "悬浮小窗",
+ "playback.exitPip": "返回页面观看",
+ "playback.pipUnavailable": "当前浏览器暂不支持悬浮小窗",
+ "playback.pipFailed": "小窗切换失败,请重试",
+ "playback.pipWaiting": "画面就绪后可开启悬浮小窗",
"debug.export": "调试报告",
"debug.exportHint": "下载本地诊断,可能包含网络地址和设备信息",
"debug.exportFailed": "诊断下载失败,请重试",
@@ -14,14 +29,42 @@ export const zh = {
"common.refresh": "刷新页面",
"common.edit": "编辑",
"common.close": "收起",
- "common.viewers": "观看者",
+ "common.enable": "开启{name}",
+ "common.disable": "关闭{name}",
+ "host.join.hide": "收起加入房间",
+ "host.advanced.hide": "收起高级设置",
+ "host.password.settingsHide": "收起密码设置",
+ "host.sourcePicker.audioOn": "分享声音",
+ "host.sourcePicker.audioOff": "停止分享声音",
+ "host.sourcePicker.audioLocked": "切换来源时保持原来的声音分享状态",
+ "common.viewers": "观众",
"common.you": "你",
- "common.host": "分享者",
+ "common.host": "房主",
"common.name.viewerDefault": "观众",
- "common.name.hostDefault": "分享者",
+ "common.name.hostDefault": "房主",
+
+ "welcome.seat": "沙发给你留着呢。",
+ "welcome.player": "单人剧情,也能组队围观。",
+ "welcome.cut": "三、二、一……好戏开场。",
+ "welcome.quest": "支线任务:分享一点快乐。",
+ "welcome.snack": "零食就位,随时开场。",
+ "welcome.scene": "下一幕,轮到你了。",
+ "welcome.save": "存个档,歇一会儿。",
+ "welcome.achievement": "隐藏成就:有人懂你的快乐。",
+ "welcome.popcorn": "前方高能,请自备瓜子。",
+ "welcome.credits": "别急着走,片尾还有彩蛋。",
+ "welcome.replay": "这段精彩,值得喊个人来看。",
+ "welcome.guide": "大佬带路,我搬小板凳。",
+ "welcome.wander": "今天不赶主线,随便逛逛。",
+ "welcome.witness": "有些名场面,得有人见证。",
+ "welcome.discovery": "刚研究出个好东西,快来看看。",
+ "welcome.party": "一个敢分享,一群敢围观。",
+ "welcome.director": "导演,今天拍点什么?",
+ "welcome.next": "下一关,也叫上朋友吧。",
+ "welcome.share": "分享一下,快乐就多一份。",
+ "welcome.seats": "二十个座位,凑一场热闹。",
"client.launch.title": "打开 Piik",
- "client.launch.hint": "选择这次使用的连接方式",
"client.launch.local": "本地房间",
"client.launch.localHint": "同一局域网内使用",
"client.launch.link": "公网邀请",
@@ -29,14 +72,15 @@ export const zh = {
"client.launch.site": "连接站点",
"client.launch.siteHint": "使用已有的 Piik 站点",
"client.launch.siteAddress": "Piik 站点地址",
- "client.launch.localAccess": "本地站点密码(可选)",
- "client.launch.localAccessHint": "留空即可开放访问;填写后需要密码",
- "client.launch.localAccessPlaceholder": "留空即可开放访问",
+ "client.launch.localAccess": "站点口令(可选)",
+ "client.launch.localAccessHint": "设置后,访问此站点需要先输入口令。使用 8–128 位英文字母、数字或半角符号,不含空格。",
"client.launch.go": "进入 Piik",
"client.launch.starting": "正在准备 Piik",
"client.launch.error": "暂时无法启动,请检查设置后重试",
"client.launch.loadFailed": "无法读取启动设置,请重试",
"client.update.available": "发现新的 Piik 版本",
+ "client.update.differentBuild": "当前构建与官方发行版不同",
+ "client.update.official": "可获取 Piik 正式发行版",
"gate.title": "站点访问",
"gate.hint": "请输入站点口令",
@@ -50,7 +94,7 @@ export const zh = {
"gate.unavailableRoute": "无法访问",
"join.title": "加入房间",
- "join.hint": "输入分享者提供的房间号",
+ "join.hint": "输入房主发来的房间号",
"join.field": "房间号",
"join.submit": "加入",
"join.invalid": "请输入 1000 至 9999 的四位房间号",
@@ -61,8 +105,6 @@ export const zh = {
"join.full": "房间已满",
"host.title": "{name} 的屏幕",
- "host.idle.heading": "想播点什么?",
- "host.idle.hint": "分享你的屏幕,朋友凭房间号或邀请链接就能进来看。",
"host.start": "开始分享",
"host.sourcePicker.title": "选择分享来源",
"host.sourcePicker.browser": "浏览器选择器",
@@ -73,7 +115,10 @@ export const zh = {
"host.sourcePicker.windowAudio": "应用声音",
"host.sourcePicker.systemAudio": "系统声音",
"host.sourcePicker.empty": "暂无可用来源",
- "host.sourcePicker.nativeAudio": "Piik App · 含声音",
+ "native.incompatible": "Piik App 与当前页面不兼容。请更新 Piik App 并刷新页面,或使用浏览器。",
+ "native.fail.edge": "Piik App 媒体连接失败",
+ "native.fail.signaling": "Piik App 信令失败",
+ "native.fail.receiver": "Piik App 媒体接收失败",
"host.sourcePicker.window": "分享窗口:{title}",
"host.sourcePicker.display": "分享屏幕:{title}",
"host.sourcePicker.system": "系统屏幕与窗口选择器",
@@ -96,7 +141,6 @@ export const zh = {
"host.noAudio": "当前来源没有可共享音频",
"host.localPreviewPaused": "本地预览已暂停,分享仍在继续",
"host.pauseNotice": "音视频分享已暂停",
- "host.resumeNotice": "音视频分享已恢复",
"host.stopNotice": "已停止分享",
"host.roomReplaced": "房间号已更换",
"host.roomInvalid": "房间已失效,再次点击将创建新房",
@@ -157,7 +201,7 @@ export const zh = {
"host.password.rule": "房间密码只需 1-{max} 个可见字符",
"host.accessFailed": "当前无法更新房间设置,请稍后重试",
- "host.viewers.empty": "暂无观看者",
+ "host.viewers.empty": "暂无观众",
"host.viewers.waiting": "等待朋友加入",
"host.viewerOverview": "全员连接数据",
@@ -186,9 +230,13 @@ export const zh = {
"host.advanced.route.peerOnly": "隐私模式",
"host.advanced.route.peerOnlyHint":
"仅使用 P2P 路线,不经过媒体服务器;无可用 P2P 路线时无法观看",
+ "host.advanced.route.peerOnlyRequired":
+ "当前实例未启用媒体服务器兜底,隐私模式保持开启;观众需要可用的 P2P 路线",
"host.advanced.route.natPrediction": "NAT 穿透",
"host.advanced.route.natPredictionHint":
"使用自建 STUN 增加有限的直连尝试;普通连接不受影响",
+ "host.advanced.route.natPredictionUnavailable":
+ "当前实例未启用额外 NAT 穿透;普通 P2P 连接仍可使用",
"host.advanced.codec": "视频编码",
"host.advanced.codec.auto": "自动",
"host.advanced.codec.autoHint": "自动选择",
@@ -205,7 +253,9 @@ export const zh = {
"state.signal.connected": "服务器已连接",
"state.signal.connecting": "正在连接",
"state.signal.reconnecting": "正在恢复",
- "state.signal.offline": "服务器未连接",
+ "state.signal.offline": "未连接服务器",
+ "state.presence.online": "在线",
+ "state.presence.offline": "离线",
"state.peer.connected": "已连接",
"state.peer.connecting": "正在连接",
"state.peer.routing": "线路分配中",
@@ -245,6 +295,7 @@ export const zh = {
"stats.inputFps": "编码输入帧率",
"stats.encodeMs": "编码耗时/帧",
"stats.decodeMs": "解码耗时/帧",
+ "state.peer.stuttering": "最近画面卡顿",
"stats.freezeCount": "画面冻结",
"stats.freezeDuration": "冻结时长",
"stats.audioLoss": "音频丢包率",
@@ -259,7 +310,7 @@ export const zh = {
"viewer.titleFallback": "好友屏幕",
"viewer.title.watching": "观看中",
"viewer.title.waiting": "等待中",
- "viewer.reconnect": "重新连接媒体",
+ "viewer.reconnect": "重新连接",
"viewer.theater": "剧场模式",
"viewer.theater.exit": "退出剧场模式",
"viewer.msg.joining": "正在加入房间",
@@ -271,11 +322,11 @@ export const zh = {
"viewer.msg.receiving": "正在接收画面",
"viewer.msg.playing": "正在播放",
"viewer.msg.needsPlay": "点击播放",
- "viewer.msg.hostPaused": "分享者已暂停",
+ "viewer.msg.hostPaused": "房主已暂停分享",
"viewer.msg.recovering": "正在恢复连接",
"viewer.msg.routeFailed": "没有可用的媒体线路",
"viewer.msg.playbackFailed": "浏览器无法播放当前画面",
- "viewer.msg.hostOffline": "分享者连接已中断",
+ "viewer.msg.hostOffline": "房主连接已中断",
"viewer.msg.serverError": "连接服务暂时不可用",
"viewer.msg.notFound": "房间不存在",
"viewer.msg.denied": "当前无法通过房间号加入",
@@ -287,10 +338,10 @@ export const zh = {
"viewer.msg.signalTerminated": "连接已终止,请刷新后重试",
"viewer.notice.signalRecovering": "服务器连接正在恢复,画面仍在播放",
"viewer.notice.mediaRecovering": "媒体连接正在恢复",
- "viewer.notice.hostOffline": "分享者连接已中断,画面可能冻结",
- "viewer.hint.denied": "请使用分享者提供的邀请链接,或尝试房间密码。",
- "viewer.hint.notFound": "请确认房间号,或向分享者获取新的邀请链接。",
- "viewer.hint.invite": "请向分享者获取新的邀请链接。",
+ "viewer.notice.hostOffline": "房主连接已中断,画面可能停住",
+ "viewer.hint.denied": "请使用房主发来的邀请链接,或输入房间密码。",
+ "viewer.hint.notFound": "请确认房间号,或让房主重新发送邀请链接。",
+ "viewer.hint.invite": "请让房主重新发送邀请链接。",
"viewer.hint.generic": "请检查入口后重试。",
"viewer.error.p2p": "P2P 媒体连接异常",
"viewer.error.relay": "下游媒体连接异常",
@@ -312,7 +363,6 @@ export const zh = {
"gate.expired": "站点访问已失效,请重新验证",
"gate.serviceUnavailable": "站点验证服务暂时不可用 ({status})",
- "host.onlineCount": "{n} / {max} 人在线",
"host.notStarted": "尚未开始",
"host.startCancelled": "启动已取消",
"host.switchingSource": "正在切换来源",
@@ -352,7 +402,7 @@ export const zh = {
"host.capture.noSource": "没有可用的屏幕分享来源",
"host.capture.readFailed": "浏览器暂时无法读取所选分享来源",
"host.capture.unavailable": "当前页面无法启动屏幕分享",
- "host.notice.reconnecting": "部分观看者正在重新连接",
+ "host.notice.reconnecting": "部分观众正在重新连接",
"host.notice.sfuRecovering": "SFU 分享来源未切换成功,正在恢复观看连接",
"host.password.inputPlaceholder": "输入密码",
@@ -374,7 +424,7 @@ export const zh = {
"host.warn.param.scaleResolutionDownBy": "分辨率缩放",
"host.warn.param.degradationPreference": "质量优先级",
"host.warn.param.scalabilityMode": "伸缩模式",
- "host.warn.sfuRecover": "SFU {stage}失败,已启动自动恢复",
+ "host.warn.sfuRecover": "SFU {params}失败,已启动自动恢复",
"host.warn.sfuStage.connect": "连接",
"host.warn.sfuStage.source": "分享源",
"host.warn.sfuStage.videoPublish": "视频发布",
@@ -440,6 +490,9 @@ export const zhTitleFrames = {
"等一个开场",
"小客厅静悄悄",
],
+ viewerReady: ["点击播放"],
+ viewerUnavailable: ["暂不可用"],
+ hostUnavailable: [zh["host.fail.start"]],
viewerWaiting: [
zh["viewer.title.waiting"],
"等待开场",
diff --git a/src/client/main.tsx b/src/client/main.tsx
index cce2ffe1..a4358cf0 100644
--- a/src/client/main.tsx
+++ b/src/client/main.tsx
@@ -1,11 +1,8 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
-import { initTheme } from "./ui/theme";
import "./styles.css";
-initTheme();
-
const root = document.getElementById("root");
if (!root) {
throw new Error("Application root was not found");
diff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.ts
index 134c3f37..4493d0ac 100644
--- a/src/client/media/host-sfu-route.ts
+++ b/src/client/media/host-sfu-route.ts
@@ -1,4 +1,5 @@
-import { say, type CopyKey } from "../ui/copy";
+import type { CopyKey } from "../ui/copy";
+import type { MediaFailure } from "../ui/media-failure";
import type {
ClientMessage,
MediaRoutePhase,
@@ -35,7 +36,7 @@ export interface HostPublisherTransport {
replaceStream(stream: MediaStream): Promise<boolean>;
updateProfile(profile: QualityProfile): Promise<boolean>;
setPaused(paused: boolean): void;
- getQualityWarning?(): string | null;
+ getQualityWarning?(): MediaFailure[] | null;
getFailureStage?(): SfuPublisherFailureStage | null;
disconnect(): Promise<void>;
}
@@ -342,12 +343,12 @@ export class HostSfuRoute {
).then((results) => results.every(Boolean));
}
- getQualityWarning(): string | null {
+ getQualityWarning(): MediaFailure[] | null {
if (this.active?.active) {
return this.active.publisher.getQualityWarning?.() ?? null;
}
return this.lastFailureStage
- ? sfuFailureWarning(this.lastFailureStage)
+ ? [sfuFailureWarning(this.lastFailureStage)]
: null;
}
@@ -730,7 +731,7 @@ async function disconnectPublisher(
await publisher.disconnect().catch(() => undefined);
}
-function sfuFailureWarning(stage: SfuPublisherFailureStage): string {
+function sfuFailureWarning(stage: SfuPublisherFailureStage): MediaFailure {
const stageKey: Record<SfuPublisherFailureStage, CopyKey> = {
connect: "host.warn.sfuStage.connect",
source: "host.warn.sfuStage.source",
@@ -739,5 +740,5 @@ function sfuFailureWarning(stage: SfuPublisherFailureStage): string {
"audio-publish": "host.warn.sfuStage.audioPublish",
transport: "host.warn.sfuStage.transport",
};
- return say("host.warn.sfuRecover", { stage: say(stageKey[stage]) });
+ return { key: "host.warn.sfuRecover", paramKeys: [stageKey[stage]] };
}
diff --git a/src/client/media/quality.ts b/src/client/media/quality.ts
index d8c8441a..7d92c241 100644
--- a/src/client/media/quality.ts
+++ b/src/client/media/quality.ts
@@ -6,7 +6,8 @@ import {
type QualitySettings,
type ScreenAudioQuality,
} from "../../shared/protocol";
-import { joinItems, say, type CopyKey } from "../ui/copy";
+import { say, type CopyKey } from "../ui/copy";
+import type { MediaFailure } from "../ui/media-failure";
import { displayMediaOptions } from "./audio-capture";
import { browserDebugEnabled, debugOperation } from "../lib/debug";
import { debugTrack } from "../lib/debug-webrtc";
@@ -188,7 +189,7 @@ export async function captureDisplay(
profile: QualityProfile,
): Promise<MediaStream> {
if (!navigator.mediaDevices?.getDisplayMedia) {
- throw new Error(say("host.capture.unavailable"));
+ throw new Error("getDisplayMedia unavailable");
}
const complete = debugOperation("capture", "display", { requested: profile });
@@ -204,7 +205,7 @@ export async function captureDisplay(
if (!videoTrack) {
stream.getTracks().forEach((track) => track.stop());
complete("failed", { reason: "no-video-track" });
- throw new Error(say("host.capture.noSource"));
+ throw new Error("display capture produced no video track");
}
videoTrack.contentHint = "motion";
for (const audioTrack of stream.getAudioTracks()) {
@@ -224,7 +225,7 @@ export async function applyCaptureProfile(
): Promise<void> {
const videoTrack = stream.getVideoTracks()[0];
if (!videoTrack) {
- throw new Error(say("host.capture.noSource"));
+ throw new Error("capture stream has no video track");
}
await applyVideoCaptureProfile(videoTrack, profile);
}
@@ -405,13 +406,16 @@ export async function configureScreenAudioSender(
export function audioSenderParameterWarning(
readback: AudioSenderParameterReadback,
-): string | null {
+): MediaFailure | null {
if (!readback.mismatch) {
return null;
}
return readback.appliedMaxBitrate === null
- ? say("host.warn.audioUnread")
- : say("host.warn.audioRewritten", { kbps: String(Math.round(readback.appliedMaxBitrate / 1_000)) });
+ ? { key: "host.warn.audioUnread" }
+ : {
+ key: "host.warn.audioRewritten",
+ vars: { kbps: String(Math.round(readback.appliedMaxBitrate / 1_000)) },
+ };
}
const PARAMETER_KEYS = {
@@ -424,12 +428,11 @@ const PARAMETER_KEYS = {
export function senderParameterWarning(
readback: VideoSenderParameterReadback,
-): string | null {
+): MediaFailure | null {
return readback.mismatches.length > 0
- ? say("host.warn.senderPartial", {
- params: joinItems(
- readback.mismatches.map((key) => say(PARAMETER_KEYS[key])),
- ),
- })
+ ? {
+ key: "host.warn.senderPartial",
+ paramKeys: readback.mismatches.map((key) => PARAMETER_KEYS[key]),
+ }
: null;
}
diff --git a/src/client/media/viewer-audio.ts b/src/client/media/viewer-audio.ts
new file mode 100644
index 00000000..b3140e5b
--- /dev/null
+++ b/src/client/media/viewer-audio.ts
@@ -0,0 +1,172 @@
+export interface ViewerAudioSnapshot {
+ level: number;
+ muted: boolean;
+ boostAvailable: boolean;
+}
+
+export class ViewerAudio {
+ private level = 1;
+ private muted = false;
+ private boostAvailable = typeof AudioContext !== "undefined";
+ private context: AudioContext | null = null;
+ private gain: GainNode | null = null;
+ private source: MediaStreamAudioSourceNode | null = null;
+ private track: MediaStreamTrack | null = null;
+ private disposed = false;
+
+ constructor(
+ private readonly video: HTMLVideoElement,
+ private readonly onChange: (snapshot: ViewerAudioSnapshot) => void,
+ ) {
+ this.level = video.volume;
+ this.muted = video.muted;
+ video.addEventListener("play", this.onPlay);
+ video.addEventListener("volumechange", this.onNativeVolume);
+ for (const event of ["pause", "ended"]) {
+ video.addEventListener(event, this.sync);
+ }
+ onChange(this.snapshot);
+ }
+
+ get snapshot(): ViewerAudioSnapshot {
+ return {
+ level: this.level,
+ muted: this.muted,
+ boostAvailable: this.boostAvailable,
+ };
+ }
+
+ bind(stream: MediaStream | null): void {
+ if (this.disposed) return;
+ const track = stream?.getAudioTracks()[0] ?? null;
+ if (track !== this.track) {
+ this.track = track;
+ this.bindSource();
+ }
+ this.sync();
+ }
+
+ setLevel(level: number): void {
+ if (this.disposed || !Number.isFinite(level)) return;
+ this.level = Math.max(0, Math.min(this.boostAvailable ? 2 : 1, level));
+ // iPhone video.volume is system-owned. Explicit adjustment uses the same
+ // gain node below and above 100%; untouched playback stays native.
+ if (this.level !== 1 && this.boostAvailable && !this.context) {
+ try {
+ this.context = new AudioContext();
+ this.gain = this.context.createGain();
+ this.gain.gain.value = 0;
+ this.gain.connect(this.context.destination);
+ this.context.addEventListener("statechange", this.sync);
+ this.bindSource();
+ } catch {
+ this.disableBoost();
+ }
+ }
+ this.resume();
+ this.sync();
+ this.onChange(this.snapshot);
+ }
+
+ setMuted(muted: boolean): void {
+ if (this.disposed) return;
+ this.muted = muted;
+ if (!muted) this.resume();
+ this.sync();
+ this.onChange(this.snapshot);
+ }
+
+ resume(): void {
+ const context = this.context;
+ if (this.disposed || !context || context.state === "running") return;
+ void context.resume().then(
+ () => {
+ if (this.context === context) this.sync();
+ },
+ () => {
+ if (this.context === context) this.disableBoost();
+ },
+ );
+ }
+
+ useNativeControls(): void {
+ if (this.disposed) return;
+ this.releaseGraph();
+ this.level = Math.min(this.level, 1);
+ this.sync();
+ this.onChange(this.snapshot);
+ }
+
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.video.removeEventListener("play", this.onPlay);
+ this.video.removeEventListener("volumechange", this.onNativeVolume);
+ for (const event of ["pause", "ended"]) {
+ this.video.removeEventListener(event, this.sync);
+ }
+ this.releaseGraph();
+ this.video.volume = Math.min(this.level, 1);
+ this.video.muted = this.muted;
+ }
+
+ private bindSource(): void {
+ this.source?.disconnect();
+ this.source = null;
+ if (!this.context || !this.gain || !this.track) return;
+ try {
+ // A stream source keeps its initial track even if that stream later changes.
+ this.source = this.context.createMediaStreamSource(
+ new MediaStream([this.track]),
+ );
+ this.source.connect(this.gain);
+ } catch {
+ this.disableBoost();
+ }
+ }
+
+ private readonly sync = (): void => {
+ if (this.disposed) return;
+ const boosted = this.context?.state === "running" && this.source !== null;
+ if (this.gain) {
+ this.gain.gain.value =
+ boosted && !this.muted && !this.video.paused && !this.video.ended
+ ? this.level
+ : 0;
+ }
+ this.video.volume = Math.min(this.level, 1);
+ this.video.muted = this.muted || this.level === 0 || boosted;
+ };
+
+ private readonly onPlay = (): void => {
+ this.resume();
+ this.sync();
+ };
+
+ private readonly onNativeVolume = (): void => {
+ if (this.disposed || this.context) return;
+ const { volume, muted } = this.video;
+ if (this.level === volume && this.muted === muted) return;
+ this.level = volume;
+ this.muted = muted;
+ this.onChange(this.snapshot);
+ };
+
+ private disableBoost(): void {
+ this.boostAvailable = false;
+ this.useNativeControls();
+ }
+
+ private releaseGraph(): void {
+ this.source?.disconnect();
+ this.source = null;
+ this.gain?.disconnect();
+ this.gain = null;
+ const context = this.context;
+ this.context = null;
+ if (context) {
+ context.removeEventListener("statechange", this.sync);
+ void context.close().catch(() => undefined);
+ }
+ }
+}
diff --git a/src/client/media/viewer-presentation.ts b/src/client/media/viewer-presentation.ts
index f9ae6e79..91967059 100644
--- a/src/client/media/viewer-presentation.ts
+++ b/src/client/media/viewer-presentation.ts
@@ -296,8 +296,7 @@ export function reduceViewerPresentation(
if (
!state.media ||
state.media.generation !== action.generation ||
- state.media.proofEpoch !== action.proofEpoch ||
- state.media.framePresented
+ state.media.proofEpoch !== action.proofEpoch
) {
return state;
}
@@ -646,12 +645,13 @@ function presentation(
failureCode: ViewerFailureCode | null =
state.access === "denied" ? state.accessFailure : null,
): ViewerPresentation {
+ const currentFrame = hasCurrentFrame(state);
return {
stage,
messageKey,
noticeKey: null,
overlay,
- hasCurrentFrame: hasCurrentFrame(state),
+ hasCurrentFrame: currentFrame,
hasRetainedFrame: state.retainedFrame,
failureCode,
connectionState:
diff --git a/src/client/media/viewer-quality-evidence.ts b/src/client/media/viewer-quality-evidence.ts
index 594eeee0..08bab063 100644
--- a/src/client/media/viewer-quality-evidence.ts
+++ b/src/client/media/viewer-quality-evidence.ts
@@ -378,6 +378,9 @@ export function presentViewerQualityEvidence(
for (const metric of viewerQualityEvidenceMetricKeys(evidence.metrics)) {
if (
+ // Window deltas describe this observation only. Inheriting an older
+ // freeze/loss count would turn an unavailable window into fresh evidence.
+ !metric.endsWith("Delta") &&
evidence.metrics[metric] === null &&
current !== null &&
current.evidence.metrics[metric] !== null
diff --git a/src/client/native/client.ts b/src/client/native/client.ts
index b4954bde..44bcf072 100644
--- a/src/client/native/client.ts
+++ b/src/client/native/client.ts
@@ -17,6 +17,7 @@ import {
edgeOfferResponseSchema,
nativeAckResponseSchema,
nativeEventSchema,
+ nativeDiscoveryIdentitySchema,
nativeHealthSchema,
NATIVE_CLIENT_PORT_END,
NATIVE_CLIENT_PORT_START,
@@ -61,7 +62,15 @@ export interface NativeShareInput {
codec: NativeVideoCodec | "auto";
}
+export class NativeCompatibilityError extends Error {
+ constructor(readonly actualProtocol: number) {
+ super(`Piik App control protocol ${actualProtocol} is incompatible with ${NATIVE_CLIENT_PROTOCOL}`);
+ this.name = "NativeCompatibilityError";
+ }
+}
+
export async function discoverNativeHealth(): Promise<NativeHealth | null> {
+ let incompatible: NativeCompatibilityError | null = null;
for (
let port = NATIVE_CLIENT_PORT_START;
port <= NATIVE_CLIENT_PORT_END;
@@ -79,10 +88,15 @@ export async function discoverNativeHealth(): Promise<NativeHealth | null> {
targetAddressSpace: "loopback",
} as RequestInit);
if (!response.ok) continue;
- const parsed = nativeHealthSchema.safeParse(await response.json());
- if (parsed.success && parsed.data.port === port) {
- return parsed.data;
+ const body: unknown = await response.json();
+ const identity = nativeDiscoveryIdentitySchema.safeParse(body);
+ if (!identity.success || identity.data.port !== port) continue;
+ if (identity.data.protocol !== NATIVE_CLIENT_PROTOCOL) {
+ incompatible ??= new NativeCompatibilityError(identity.data.protocol);
+ continue;
}
+ const health = nativeHealthSchema.safeParse(body);
+ if (health.success) return health.data;
} catch {
// An absent App and a denied local-network permission are both
// ordinary Browser-only operation.
@@ -90,6 +104,13 @@ export async function discoverNativeHealth(): Promise<NativeHealth | null> {
window.clearTimeout(timer);
}
}
+ if (incompatible) {
+ debugEvent("native", "incompatible", {
+ expectedProtocol: NATIVE_CLIENT_PROTOCOL,
+ actualProtocol: incompatible.actualProtocol,
+ });
+ throw incompatible;
+ }
return null;
}
diff --git a/src/client/native/media-ingress.ts b/src/client/native/media-ingress.ts
index 30d0c6de..717ebf51 100644
--- a/src/client/native/media-ingress.ts
+++ b/src/client/native/media-ingress.ts
@@ -167,7 +167,7 @@ export class NativeMediaIngress {
private onUpdate(snapshot: PeerSnapshot): void {
if (this.disposed) return;
if (snapshot.connectionState === "failed" || snapshot.connectionState === "closed" ||
- (!this.ready && snapshot.error)) {
+ (!this.ready && snapshot.error !== null)) {
this.fail();
} else if (!this.ready && snapshot.connectionState === "connected") {
this.ready = true;
diff --git a/src/client/native/native-sender-peer.ts b/src/client/native/native-sender-peer.ts
index b58f1ec1..32adc90a 100644
--- a/src/client/native/native-sender-peer.ts
+++ b/src/client/native/native-sender-peer.ts
@@ -55,8 +55,6 @@ export class NativeSenderPeer implements HostMediaPeer {
error: null,
senderParameters: null,
audioSenderParameters: null,
- qualityWarning: null,
- qualityWarningKind: null,
};
this.edge = new NativeSenderEdge(
peerId,
@@ -80,7 +78,7 @@ export class NativeSenderPeer implements HostMediaPeer {
: state === "closed"
? "closed"
: "checking",
- error: state === "failed" ? "Native media edge failed" : null,
+ error: state === "failed" ? { key: "native.fail.edge" } : null,
};
events.onUpdate(this.getSnapshot());
},
@@ -164,7 +162,7 @@ export class NativeSenderPeer implements HostMediaPeer {
...this.snapshot,
connectionState: "failed",
iceConnectionState: "failed",
- error: "Native media signaling failed",
+ error: { key: "native.fail.signaling" },
};
this.events.onUpdate(this.getSnapshot());
}
diff --git a/src/client/native/native-viewer-peer.ts b/src/client/native/native-viewer-peer.ts
index 4497a774..766ab199 100644
--- a/src/client/native/native-viewer-peer.ts
+++ b/src/client/native/native-viewer-peer.ts
@@ -694,7 +694,7 @@ class NativeViewerPeer implements ViewerMediaPeer {
: this.state === "disconnected"
? "disconnected"
: "checking",
- error: this.state === "failed" ? "Native media receiver failed" : null,
+ error: this.state === "failed" ? { key: "native.fail.receiver" } : null,
};
this.events.onUpdate({
...this.snapshot,
diff --git a/src/client/native/wire.ts b/src/client/native/wire.ts
index d6b66db8..e7dabc91 100644
--- a/src/client/native/wire.ts
+++ b/src/client/native/wire.ts
@@ -13,30 +13,33 @@ const opaqueIdentifierSchema = z
.max(256)
.regex(/^[A-Za-z0-9_-]+$/);
-export const nativeHealthSchema = z
- .object({
- protocol: z.literal(NATIVE_CLIENT_PROTOCOL),
- service: z.literal("piik-client"),
- port: z
- .number()
- .int()
- .min(NATIVE_CLIENT_PORT_START)
- .max(NATIVE_CLIENT_PORT_END),
- instanceToken: z
- .string()
- .length(43)
- .regex(/^[A-Za-z0-9_-]+$/),
- nativeMedia: z
- .object({
- video: z.boolean(),
- processAudio: z.boolean(),
- systemAudio: z.boolean(),
- hardwareH264: z.boolean(),
- softwareVP8: z.boolean(),
- })
- .strict(),
- })
- .strict();
+// Discovery descriptions may grow; control responses and events stay strict.
+export const nativeDiscoveryIdentitySchema = z.object({
+ protocol: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
+ service: z.literal("piik-client"),
+ port: z
+ .number()
+ .int()
+ .min(NATIVE_CLIENT_PORT_START)
+ .max(NATIVE_CLIENT_PORT_END),
+});
+
+export const nativeHealthSchema = nativeDiscoveryIdentitySchema.extend({
+ protocol: z.literal(NATIVE_CLIENT_PROTOCOL),
+ instanceToken: z
+ .string()
+ .length(43)
+ .regex(/^[A-Za-z0-9_-]+$/),
+ nativeMedia: z
+ .object({
+ video: z.boolean().default(false),
+ processAudio: z.boolean().default(false),
+ systemAudio: z.boolean().default(false),
+ hardwareH264: z.boolean().default(false),
+ softwareVP8: z.boolean().default(false),
+ })
+ .prefault({}),
+});
export type NativeHealth = z.infer<typeof nativeHealthSchema>;
const nativeWindowTargetSchema = z
diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsx
index d8f9d231..77eca1cd 100644
--- a/src/client/pages/AppLauncherPage.tsx
+++ b/src/client/pages/AppLauncherPage.tsx
@@ -2,59 +2,28 @@ import { useEffect, useState, type FormEvent } from "react";
import { z } from "zod";
import { BrandLoader, BrandMark } from "../components/living/BrandMark";
-import { ComicTooltip } from "../components/living/ComicTooltip";
+import { Tooltip } from "../components/living/Tooltip";
import { AppHeader } from "../components/living/Header";
+import { LauncherForm, type AppMode } from "../components/living/LauncherForm";
import { Btn, Pill } from "../components/living/primitives";
-import type { HintKind } from "../components/living/hints";
-import { Glyph, type GlyphName } from "../ui/icons";
+import { Glyph } from "../ui/icons";
import { useCopy, type CopyKey } from "../ui/copy";
+import { currentThemePreference } from "../ui/theme";
+import { clientLaunchURL } from "../lib/session";
import {
checkReleaseUpdate,
type ReleaseUpdateNotice,
} from "../lib/release-update";
-type AppMode = "local" | "link" | "site";
-
-const launcherStateSchema = z
- .object({
- site: z.string(),
- localAccessPassword: z.string().max(128),
- defaultMode: z.enum(["local", "site"]),
- revision: z.string(),
- })
- .strict();
+const launcherStateSchema = z.object({
+ site: z.string(),
+ localAccessPassword: z.string().max(128),
+ defaultMode: z.enum(["local", "site"]),
+ revision: z.string(),
+ version: z.string().default("development"),
+});
const launcherResultSchema = z.object({ target: z.string().url() }).strict();
-const MODES: Array<{
- mode: AppMode;
- icon: GlyphName;
- label: CopyKey;
- hint: CopyKey;
- comic: HintKind;
-}> = [
- {
- mode: "local",
- icon: "users",
- label: "client.launch.local",
- hint: "client.launch.localHint",
- comic: "hint-client-local",
- },
- {
- mode: "link",
- icon: "globe",
- label: "client.launch.link",
- hint: "client.launch.linkHint",
- comic: "hint-client-link",
- },
- {
- mode: "site",
- icon: "server",
- label: "client.launch.site",
- hint: "client.launch.siteHint",
- comic: "hint-client-site",
- },
-];
-
export function AppLauncherPage() {
const { lang, vis, t } = useCopy();
const [loading, setLoading] = useState(true);
@@ -78,9 +47,14 @@ export function AppLauncherPage() {
setSite(state.site);
setLocalAccessPassword(state.localAccessPassword);
setLoading(false);
- void checkReleaseUpdate(state.revision).then((notice) => {
- if (current && notice) setUpdate(notice);
- }).catch(() => undefined);
+ void checkReleaseUpdate({
+ version: state.version,
+ revision: state.revision,
+ })
+ .then((notice) => {
+ if (current && notice) setUpdate(notice);
+ })
+ .catch(() => undefined);
})
.catch(() => {
if (!current) return;
@@ -97,6 +71,7 @@ export function AppLauncherPage() {
if (starting || (mode === "site" && !site.trim())) return;
setStarting(true);
setError(null);
+ const presentation = { lang, vis, theme: currentThemePreference() };
try {
const response = await fetch("/api/client-launcher/launch", {
method: "POST",
@@ -109,32 +84,33 @@ export function AppLauncherPage() {
});
if (!response.ok) throw new Error();
const result = launcherResultSchema.parse(await response.json());
- window.location.replace(result.target);
+ window.location.replace(clientLaunchURL(result.target, presentation));
} catch {
setError("launch");
setStarting(false);
}
}
- const accessField = (
- <label className="lr-input lr-client-access">
- <Glyph name="lock" size={18} />
- <input
- type="text"
- value={localAccessPassword}
- maxLength={128}
- autoComplete="off"
- spellCheck={false}
- placeholder={vis ? "" : t("client.launch.localAccessPlaceholder")}
- aria-label={t("client.launch.localAccess")}
- title={vis ? undefined : t("client.launch.localAccessHint")}
- onChange={(event) => {
- setLocalAccessPassword(event.target.value);
- setError(null);
- }}
- />
- </label>
- );
+ const updateKey: CopyKey =
+ update?.kind === "different-build"
+ ? "client.update.differentBuild"
+ : update?.kind === "official-release"
+ ? "client.update.official"
+ : "client.update.available";
+ const updateText = update ? `${t(updateKey)} · ${update.version}` : "";
+ const updateLink = update ? (
+ <a
+ className="lr-client-update"
+ href={update.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={updateText}
+ >
+ <Glyph name="arrowUp" size={17} />
+ <span className={vis ? "visually-hidden" : undefined}>{updateText}</span>
+ {vis && <span aria-hidden="true">{update.version}</span>}
+ </a>
+ ) : null;
return (
<div className="lr-app">
@@ -173,121 +149,32 @@ export function AppLauncherPage() {
/>
</div>
) : (
- <form className="lr-client-launch-panel" onSubmit={launch}>
- <BrandMark size={68} motion="once" />
- {vis ? null : (
- <header className="lr-client-launch-copy">
- <h1>{t("client.launch.title")}</h1>
- <p>{t("client.launch.hint")}</p>
- </header>
- )}
-
- {update ? (
- <a
- className="lr-client-update"
- href={update.url}
- target="_blank"
- rel="noopener noreferrer"
- aria-label={t("client.update.available")}
- title={vis ? undefined : t("client.update.available")}
- >
- <Glyph name="arrowUp" size={17} />
- {vis ? (
- <span className="visually-hidden">
- {t("client.update.available")}
- </span>
- ) : (
- <span>{t("client.update.available")}</span>
- )}
- </a>
- ) : null}
-
- <div
- className="lr-client-modes"
- role="radiogroup"
- aria-label={t("client.launch.title")}
- >
- {MODES.map((choice) => {
- const button = (
- <button
- key={choice.mode}
- type="button"
- role="radio"
- className={`lr-client-mode${mode === choice.mode ? " is-selected" : ""}`}
- aria-checked={mode === choice.mode}
- aria-label={t(choice.label)}
- title={vis ? undefined : t(choice.hint)}
- onClick={() => {
- setMode(choice.mode);
- setError(null);
- }}
- >
- <Glyph name={choice.icon} size={27} />
- {vis ? null : (
- <span>
- <strong>{t(choice.label)}</strong>
- <small>{t(choice.hint)}</small>
- </span>
- )}
- </button>
- );
- return vis ? (
- <ComicTooltip key={choice.mode} kind={choice.comic}>
- {button}
- </ComicTooltip>
- ) : (
- button
- );
- })}
- </div>
-
- {mode === "site" ? (
- <label className="lr-input lr-client-site">
- <Glyph name="link" size={18} />
- <input
- type="url"
- value={site}
- autoFocus
- spellCheck={false}
- inputMode="url"
- placeholder="https://share.example"
- aria-label={t("client.launch.siteAddress")}
- onChange={(event) => {
- setSite(event.target.value);
- setError(null);
- }}
- />
- </label>
- ) : null}
-
- {mode !== "site" ? (
- vis ? (
- <ComicTooltip kind="hint-password">
- {accessField}
- </ComicTooltip>
+ <LauncherForm
+ mode={mode}
+ site={site}
+ localAccessPassword={localAccessPassword}
+ onModeChange={(value) => {
+ setMode(value);
+ setError(null);
+ }}
+ onSiteChange={(value) => {
+ setSite(value);
+ setError(null);
+ }}
+ onLocalAccessPasswordChange={(value) => {
+ setLocalAccessPassword(value);
+ setError(null);
+ }}
+ error={error === "launch"}
+ onSubmit={launch}
+ >
+ {updateLink &&
+ (vis ? (
+ updateLink
) : (
- accessField
- )
- ) : null}
-
- {error === "launch" ? (
- <Pill
- icon="alert"
- tone="bad"
- label={t("client.launch.error")}
- alert
- comic="warning"
- />
- ) : null}
- <Btn
- icon="arrowRight"
- title="client.launch.go"
- cap="client.launch.go"
- tone="primary"
- type="submit"
- disabled={mode === "site" && !site.trim()}
- />
- </form>
+ <Tooltip text={updateText}>{updateLink}</Tooltip>
+ ))}
+ </LauncherForm>
)}
</main>
</div>
diff --git a/src/client/pages/ControlsPreview.tsx b/src/client/pages/ControlsPreview.tsx
new file mode 100644
index 00000000..3caf5ca1
--- /dev/null
+++ b/src/client/pages/ControlsPreview.tsx
@@ -0,0 +1,150 @@
+import { useRef, useState } from "react";
+import { Btn, Chip, NameTag, Pill, SwitchItem } from "../components/living/primitives";
+import { RoomChip, RoomAdmissionBadge } from "../components/living/RoomChip";
+import { CaptureSourcePicker, type NativeSourceList } from "../components/living/CaptureSourcePicker";
+import { LedStrip } from "../components/living/Header";
+import { StageTv } from "../components/living/Stage";
+import { PlaybackControls } from "../components/living/PlaybackControls";
+import { Tooltip } from "../components/living/Tooltip";
+import { StatusIndicator } from "../components/living/StatusIndicator";
+import { deriveParticipantStatus } from "../ui/media-status";
+import { Glyph } from "../ui/icons";
+import { useCopy } from "../ui/copy";
+import { PeoplePreview } from "./PeoplePreview";
+import "./controls-preview.css";
+
+const POSTER = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 360"><rect width="640" height="360" fill="#e8eee6"/><rect x="100" y="60" width="440" height="240" rx="20" fill="#fffdf6"/><path d="M100 100h440" stroke="#c9d7cf" stroke-width="2"/><circle cx="128" cy="81" r="6" fill="#ed9e65"/><circle cx="320" cy="190" r="46" fill="#65b099"/><path d="m310 191 9 9 16-22" fill="none" stroke="#fffdf6" stroke-width="7" stroke-linecap="round" stroke-linejoin="round"/></svg>')}`;
+const SOURCES: NativeSourceList = { kind: "ready", processAudio: true, systemAudio: true, sources: [
+ { kind: "window", sourceId: "101", pid: 1, creationTime: "1", title: "Sketchbook" },
+ { kind: "window", sourceId: "102", pid: 2, creationTime: "2", title: "A short film" },
+ { kind: "display", sourceId: "103", title: "Display 1" },
+] };
+const previewSource = async () => POSTER;
+
+export function ControlsPreview() {
+ const { t, lang, vis } = useCopy();
+ const en = lang === "en";
+ const [sound, setSound] = useState(true);
+ const [preset, setPreset] = useState("1080p30");
+ const [policy, setPolicy] = useState<"open" | "private">("open");
+ const [paused, setPaused] = useState(false);
+ const [passwordVisible, setPasswordVisible] = useState(false);
+ const [name, setName] = useState("Piik friend");
+ const [invalid, setInvalid] = useState(false);
+ const [sourceOpen, setSourceOpen] = useState(false);
+ const [sourceState, setSourceState] = useState<NativeSourceList["kind"]>("ready");
+ const [roomCode, setRoomCode] = useState("6020");
+ const [feedback, setFeedback] = useState("");
+ const [dial, setDial] = useState("60");
+ const [theater, setTheater] = useState(false);
+ const video = useRef<HTMLVideoElement>(null);
+ const notify = () => setFeedback(en ? "Got it. This is a preview." : "收到,只在预览里演示。" );
+ return <>
+ <div className="cp-grid" id="control-preview">
+ <section id="button-preview" className="cp-card">
+ <header><span className="cp-number">01</span><h2>{en ? "Buttons, with a little give" : "按钮,按下去有回应。"}</h2></header>
+ <p>{en ? "Hover, press, or use Tab and Enter. The disabled one keeps its explanation." : "悬停、按下,或用 Tab 和回车试试。禁用时也能查看原因。"}</p>
+ <div className="cp-tools">
+ <Btn icon="cast" tone="primary" title="host.start" cap="host.start" hint="hint-share-start" onClick={notify} />
+ <Btn icon="stop" tone="danger" title="host.stop" cap="host.stop" hint="hint-share-stop" onClick={notify} />
+ <Btn icon={paused ? "play" : "pause"} title={paused ? "host.resume" : "host.pause"} cap={paused ? "host.resume" : "host.pause"}
+ hint={paused ? "hint-resume" : "hint-pause"} draw="preview-pause" pressed={paused} onClick={() => setPaused(!paused)} />
+ <Btn icon="gauge" tone="on" title="host.details" cap="host.details" pressed onClick={notify} />
+ <Btn icon="refresh" title="viewer.reconnect" cap="viewer.reconnect" hint="hint-reconnect" disabled />
+ <Btn icon="cast" title="host.starting" cap="host.starting" busy disabled hint="hint-share-start" />
+ </div>
+ <div className="cp-tools">
+ <Btn icon="switchSource" title="host.switchSource" hint="hint-switch-source" onClick={notify} />
+ <Btn icon="link" title="host.invite.copy" hint="hint-copy-invite" onClick={notify} />
+ <Btn icon="linkOff" title="host.invite.revoke" hint="hint-revoke-invite" onClick={notify} />
+ <Btn icon="network" title="host.topology" hint="hint-topology" onClick={notify} />
+ <Btn icon="sliders" title="host.advanced" onClick={notify} />
+ </div>
+ </section>
+ <section id="option-preview" className="cp-card">
+ <header><span className="cp-number">02</span><h2>{en ? "Pick, toggle, adjust" : "选一个,再拨一下。"}</h2></header>
+ <div className="lr-tiles" role="group" aria-label={t("host.quality")}>
+ {(["720p30", "1080p30", "1080p60"] as const).map((value, index) => <Tooltip key={value} kind="hint-quality" text={t(`host.quality.${value}`)}>
+ <button type="button" className={`lr-tile${preset === value ? " is-selected" : ""}`} aria-pressed={preset === value}
+ aria-label={t(`host.quality.${value}`)} onClick={() => setPreset(value)}>
+ <Glyph name={["mountain", "balance", "zap"][index]!} size={23} /><small>{value.replace("p", "p · ")}</small>
+ </button></Tooltip>)}
+ </div>
+ <div className="cp-tools">
+ <SwitchItem checked={sound} onChange={setSound} label={t("host.sourcePicker.audioOn")} hint="hint-share-audio" />
+ <SwitchItem checked disabled locked onChange={() => undefined} label={t("host.advanced.route.peerOnly")}
+ note={t("host.advanced.route.peerOnlyRequired")} hint="hint-route-p2p-required" />
+ </div>
+ <div className="cp-tools">
+ <span className="lr-toggle" role="group" aria-label={t("host.policy")} data-selected={policy}>
+ {(["open", "private"] as const).map(value => <Tooltip key={value} kind={value === "open" ? "hint-policy-open" : "hint-policy-private"} text={t(`host.policy.${value}`)}>
+ <button type="button" className={policy === value ? "is-selected" : undefined} aria-pressed={policy === value}
+ aria-label={t(`host.policy.${value}`)} onClick={() => setPolicy(value)}>
+ <Glyph name={value === "open" ? "globe" : "lock"} size={19} />{vis ? null : <span className="lr-cap">{t(`host.policy.${value}`)}</span>}
+ </button></Tooltip>)}
+ </span><RoomAdmissionBadge policy={policy} passwordEnabled={false} />
+ </div>
+ </section>
+ <section id="input-preview" className="cp-card">
+ <header><span className="cp-number">03</span><h2>{en ? "Names, codes and small details" : "名字、房间号,还有小细节。"}</h2></header>
+ <div className="cp-tools"><NameTag name={name || "Piik friend"} identity="preview-name" />
+ <label className="lr-input"><Glyph name="pencil" size={17} /><input value={name} aria-label={t("host.name")}
+ autoComplete="off" onChange={event => setName(event.target.value)} /></label>
+ </div>
+ <div className="cp-tools">
+ <label className="lr-input"><Glyph name="key" size={17} /><input type={passwordVisible ? "text" : "password"}
+ placeholder={t("join.password")} aria-label={t("join.password")} aria-invalid={invalid} aria-describedby={invalid ? "preview-input-error" : undefined} autoComplete="off" />
+ </label>
+ <Btn icon={passwordVisible ? "eyeOff" : "eye"} title={passwordVisible ? "host.password.hide" : "host.password.show"} onClick={() => setPasswordVisible(!passwordVisible)} />
+ <SwitchItem checked={invalid} onChange={setInvalid} label={en ? "Show error" : "看看错误态"} />
+ </div>
+ {invalid ? <p id="preview-input-error" className="cp-input-error" role="alert">{en ? "That password did not match. Try again." : "密码没对上,再试一次。"}</p> : null}
+ <div className="cp-tools"><RoomChip roomId={roomCode} onReplace={() => setRoomCode(code => code === "6020" ? "2048" : "6020")} /></div>
+ <div className="lr-dials-wrap cp-dials"><div className="lr-dials" aria-hidden="true">{[0, 1, 2, 3].map(index =>
+ <span key={index} className={`lr-dial${dial[index] ? " is-filled" : index === dial.length ? " is-active" : ""}`}>{dial[index] ?? ""}</span>)}</div>
+ <input value={dial} inputMode="numeric" maxLength={4} autoComplete="off" aria-label={t("join.field")}
+ onChange={event => setDial(event.target.value.replace(/\D/g, "").slice(0, 4))} />
+ </div>
+ </section>
+ <section id="feedback-preview" className="cp-card">
+ <header><span className="cp-number">04</span><h2>{en ? "Clear feedback" : "每种反馈,都说清楚。"}</h2></header>
+ <div className="cp-tools">
+ <LedStrip state="live" label={t("state.signal.connected")} />
+ <LedStrip state="busy" label={t("state.signal.connecting")} />
+ <LedStrip state="bad" label={t("state.signal.offline")} />
+ </div>
+ <div className="cp-tools"><Pill icon="check" tone="good" label={t("common.copied")} comic="hint-copy-code" />
+ <Pill icon="lock" label={t("host.advanced.route.peerOnlyRequired")} comic="hint-route-p2p-required" />
+ <Pill icon="alert" tone="bad" label={t("common.copyFailed")} comic="warning" /></div>
+ <div className="cp-tools"><StatusIndicator status={deriveParticipantStatus({ upstream: { kind: "peer", peerId: "preview" }, mediaReady: true }, true)} />
+ <StatusIndicator status={deriveParticipantStatus({ upstream: { kind: "none" } }, true)} />
+ </div>
+ <p className="cp-feedback" aria-live="polite">{feedback || (en ? "Button feedback appears here." : "点一下上面的按钮,回应会出现在这里。")}</p>
+ </section>
+ </div>
+ <PeoplePreview />
+ <section id="source-preview" className="cp-section">
+ <header className="cp-section-head"><span className="cp-number">06</span><div><h2>{en ? "Choose a picture" : "挑一块画面。"}</h2>
+ <p>{en ? "The actual source selector, with sample windows. Selection only updates this preview." : "正式的画面选择器,放入了几个示例窗口;选择只影响这张预览。"}</p></div></header>
+ <div className="cp-tools">{(["ready", "loading", "unavailable", "incompatible"] as const).map((value, index) => <Chip key={value}
+ title={value} selected={sourceState === value} onClick={() => { setSourceState(value); setSourceOpen(true); }}>
+ {en ? ["Available", "Loading", "App unavailable", "Update needed"][index] : ["正常", "读取中", "App 未连接", "需要更新"][index]}</Chip>)}</div>
+ <div className="cp-stage"><StageTv hasEntry label={t("host.sourcePicker.title")}>
+ <img className="cp-poster" src={POSTER} alt="" />
+ {sourceOpen ? <CaptureSourcePicker nativeSources={sourceState === "ready" ? SOURCES : { kind: sourceState }}
+ onBrowser={() => { setSourceOpen(false); notify(); }} onNative={() => { setSourceOpen(false); notify(); }}
+ onPreview={previewSource} onRefresh={() => setSourceState("ready")} onCancel={() => setSourceOpen(false)} />
+ : <div className="cp-stage-action"><Btn icon="cast" tone="primary" title="host.start" cap="host.start" onClick={() => setSourceOpen(true)} /></div>}
+ </StageTv></div>
+ </section>
+ <section id="playback-preview" className="cp-section">
+ <header className="cp-section-head"><span className="cp-number">07</span><div><h2>{en ? "The playback bar" : "播放时,顺手就能找到。"}</h2>
+ <p>{en ? "This bar shows its waiting state. The playback test page includes a moving picture, volume and picture in picture." : "这里展示等待画面时的播放栏;动态画面、音量和小窗可进入完整播放预览试用。"}</p></div></header>
+ <div className="cp-stage"><StageTv label={t("playback.controls")}><video ref={video} poster={POSTER} playsInline />
+ <PlaybackControls videoRef={video} stream={null} canPlay={false} theaterMode={theater} onPlay={notify}
+ onToggleTheater={() => setTheater(!theater)} onReconnect={notify} reconnectAvailable />
+ </StageTv></div>
+ <p><a href="/__playback-preview">{en ? "Open the full playback preview" : "进入完整播放预览"} →</a></p>
+ </section>
+ </>;
+}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index e07fac46..a4018582 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -23,8 +23,8 @@ import {
type CodeEntryPolicy,
type RoutePolicy,
} from "../../shared/protocol";
-import { qualityLimitationSummary } from "../components/connection-details";
-import { AppHeader, LedStrip, type LedState } from "../components/living/Header";
+import { AppHeader, LedStrip } from "../components/living/Header";
+import { WelcomeLine } from "../components/living/WelcomeLine";
import { Couch, type CouchEntry } from "../components/living/Couch";
import {
CaptureSourcePicker,
@@ -42,7 +42,7 @@ import {
type ViewerOverviewEntry,
} from "../components/living/ViewerOverview";
import type { ComicKind } from "../components/living/Comic";
-import { ComicTooltip } from "../components/living/ComicTooltip";
+import { Tooltip } from "../components/living/Tooltip";
import type { HintKind } from "../components/living/hints";
import {
StageOverlay,
@@ -50,6 +50,7 @@ import {
StaticNoise,
StoryBoard,
} from "../components/living/Stage";
+import { StatusIndicator } from "../components/living/StatusIndicator";
import {
Btn,
Cap,
@@ -59,13 +60,13 @@ import {
Pill,
Row,
RowGroup,
- StatusText,
SwitchItem,
VisGlyph,
} from "../components/living/primitives";
import { hasPeerRouteEvidence } from "../components/status-badge-model";
import { Glyph, type GlyphName } from "../ui/icons";
import { say, useCopy, type CopyKey } from "../ui/copy";
+import { resolveMediaFailure, type MediaFailure } from "../ui/media-failure";
import {
ApiError,
createRoom,
@@ -86,6 +87,7 @@ import {
saveDisplayName,
} from "../lib/display-name";
import { useDocumentTitle } from "../ui/document-title";
+import { deriveHostStatus, deriveParticipantStatus, type HostPhase } from "../ui/media-status";
import {
clearHostRoom,
getStableClientId,
@@ -151,7 +153,7 @@ import type {
SignalConnectionState,
} from "../types";
import { HostPeer, type HostMediaPeer } from "../webrtc/host-peer";
-import { NativeClient } from "../native/client";
+import { NativeClient, NativeCompatibilityError } from "../native/client";
import {
NativeSenderPeer,
shouldUseBrowserQualityCandidate,
@@ -186,24 +188,12 @@ import {
type HostAction,
} from "./host-page-notices";
-type HostPhase = "idle" | "starting" | "live" | "ended" | "error";
-
-type NoticeValue =
+type NoticeValue = (
| { kind: "text"; text: string }
- | { kind: "key"; key: CopyKey; vars?: Record<string, string> };
-
-const SIGNAL_LED_STATE: Record<SignalConnectionState, LedState> = {
- connected: "live",
- connecting: "busy",
- reconnecting: "warn",
- offline: "off",
-};
-
-const SIGNAL_LED_LABEL: Record<SignalConnectionState, CopyKey> = {
- connected: "state.signal.connected",
- connecting: "state.signal.connecting",
- reconnecting: "state.signal.reconnecting",
- offline: "state.signal.offline",
+ | { kind: "key"; key: CopyKey; vars?: Record<string, string> }
+) & {
+ target: "television" | "operation";
+ comic: ComicKind | null;
};
const QUALITY_PROFILE_CAPTIONS: Record<QualityProfileId, CopyKey> = {
@@ -239,24 +229,6 @@ const AUDIO_QUALITY_CAPTIONS: Record<ScreenAudioQuality, CopyKey> = {
"very-high": "host.advanced.audio.veryHigh",
};
-type PresentedPeerState =
- | RTCPeerConnectionState
- | "routing"
- | "waiting"
- | "reconnecting";
-
-const PEER_STATE_CAPTIONS: Record<PresentedPeerState, CopyKey> = {
- new: "state.peer.new",
- connecting: "state.peer.connecting",
- connected: "state.peer.connected",
- routing: "state.peer.routing",
- waiting: "state.peer.waiting",
- reconnecting: "state.peer.reconnecting",
- failed: "state.peer.failed",
- disconnected: "state.peer.disconnected",
- closed: "state.peer.closed",
-};
-
// Scanline glyph on each quality tile: denser scanlines (plus a motion wave
// at 60 fps) read as a higher preset without any text.
function QualityTileGlyph({ density }: { density: number }) {
@@ -402,6 +374,7 @@ function hostTerminationKey(reason: SignalingTerminationReason): CopyKey {
}
interface HostPageProps {
+ sfuAvailable?: boolean;
natPredictionAvailable?: boolean;
launchedByClient?: boolean;
onAuthorizationRequired?: () => void;
@@ -418,11 +391,13 @@ type ShareSourceSelection =
};
export function HostPage({
+ sfuAvailable = false,
natPredictionAvailable = false,
launchedByClient = false,
onAuthorizationRequired,
}: HostPageProps = {}) {
- const { lang, vis, t, titleFrames } = useCopy();
+ const copy = useCopy();
+ const { lang, vis, t, titleFrames } = copy;
const [qualitySettings, setQualitySettings] = useState<QualitySettings>(
DEFAULT_QUALITY_SETTINGS,
);
@@ -432,6 +407,7 @@ export function HostPage({
const [routePolicy, setRoutePolicy] = useState<RoutePolicy>(
() => ({
...DEFAULT_ROUTE_POLICY,
+ peerOnly: !sfuAvailable,
natPrediction: natPredictionAvailable,
}),
);
@@ -482,7 +458,6 @@ export function HostPage({
creationProfile.roomPassword ?? "",
);
const [viewerPasswordVisible, setViewerPasswordVisible] = useState(false);
- const [maxViewers, setMaxViewers] = useState<number | null>(null);
const [peerSnapshots, setPeerSnapshots] = useState<Map<string, PeerSnapshot>>(
() => new Map(),
);
@@ -502,29 +477,29 @@ export function HostPage({
Map<string, ViewerQualityEvidencePresentation>
>(() => new Map());
const [noticeValue, setNoticeValue] = useState<NoticeValue | null>(null);
- const [noticeComic, setNoticeComic] = useState<ComicKind | null>(null);
const [hostSfuQualityWarning, setHostSfuQualityWarning] = useState<
- string | null
+ MediaFailure[] | null
>(null);
function setNotice(value: string | null, comic: ComicKind | null = null): void {
- setNoticeValue(value ? { kind: "text", text: value } : null);
- setNoticeComic(comic);
+ setNoticeValue(value ? { kind: "text", text: value, target: "operation", comic } : null);
}
function setNoticeKey(key: CopyKey, vars?: Record<string, string>): void {
- setNoticeValue({ kind: "key", key, vars });
- setNoticeComic(null);
+ setNoticeValue({ kind: "key", key, vars, target: "operation", comic: null });
}
- function setNoticeError(error: unknown, action: HostAction): void {
- setNoticeValue({ kind: "text", text: readableError(error, action) });
- setNoticeComic(action === "connection" ? "route-failed" : "warning");
+ function setNoticeError(
+ error: unknown,
+ action: HostAction,
+ target: NoticeValue["target"] = "operation",
+ ): void {
+ setNoticeValue({ kind: "text", text: readableError(error, action), target,
+ comic: action === "connection" ? "route-failed" : "warning" });
}
function setNoticeErrorKey(
key: CopyKey,
comic: ComicKind = "warning",
vars?: Record<string, string>,
): void {
- setNoticeValue({ kind: "key", key, vars });
- setNoticeComic(comic);
+ setNoticeValue({ kind: "key", key, vars, target: "operation", comic });
}
const [copied, setCopied] = useState(false);
const copiedResetTimerRef = useRef<number | null>(null);
@@ -608,10 +583,6 @@ export function HostPage({
const nativeSourcePathRef = useRef<NativeCapturePath | null>(null);
const nativeShareCleanupRef = useRef<Promise<void>>(Promise.resolve());
- const mediaViewers = useMemo(
- () => Array.from(peerSnapshots.values()),
- [peerSnapshots],
- );
const { host: labeledHostPresence, viewers } = useMemo(
() => labelParticipantSnapshot(participantPresence),
[participantPresence],
@@ -630,10 +601,6 @@ export function HostPage({
() => matchingQualityProfileId(qualitySettings),
[qualitySettings],
);
- const qualityLimitation = useMemo(
- () => qualityLimitationSummary(mediaViewers),
- [mediaViewers],
- );
const displayedVideoCodecMode =
phase === "live" && resolvedVideoCodec
? resolvedVideoCodec
@@ -850,7 +817,7 @@ export function HostPage({
function syncHostSfuQualityWarning(
route: HostSfuRoute,
generation: number,
- ): string | null {
+ ): MediaFailure[] | null {
if (
!isCurrentGeneration(generation) ||
hostSfuRouteRef.current !== route
@@ -905,7 +872,6 @@ export function HostPage({
iceConfigRef.current = null;
setStream(null);
setDetails(null);
- setMaxViewers(null);
setPeerSnapshots(new Map());
setParticipantPresence([]);
viewerQualityEvidenceTimersRef.current.forEach((timer) =>
@@ -968,8 +934,6 @@ export function HostPage({
function endSharing(
message: string | { key: CopyKey; vars?: Record<string, string> },
notifyServer = true,
- // Involuntary endings keep the failure tone: the notice pill reads its
- // icon/tone from the comic, so a bare key would render as green success.
comic: ComicKind | null = null,
): void {
const generation = activeGenerationRef.current;
@@ -983,12 +947,13 @@ export function HostPage({
writePreferredRoom(currentRoom.roomId);
}
disposeResources(notifyServer);
- setNoticeValue(
- typeof message === "string"
+ setNoticeValue({
+ ...(typeof message === "string"
? { kind: "text", text: message }
- : { kind: "key", key: message.key, vars: message.vars },
- );
- setNoticeComic(comic);
+ : { kind: "key", key: message.key, vars: message.vars }),
+ target: "television",
+ comic,
+ });
setPhase("ended");
}
@@ -1370,6 +1335,7 @@ export function HostPage({
: null,
).catch((error) => {
debugError("native", "discovery-failed", error);
+ if (error instanceof NativeCompatibilityError) throw error;
return null;
}).then((client) => {
if (nativeClientConnectRef.current !== connecting) {
@@ -1408,7 +1374,15 @@ export function HostPage({
nativeSourcePathRef.current = null;
setNativeSources({ kind: "loading" });
- const client = await acquireNativeClient();
+ let client: NativeClient | null;
+ try {
+ client = await acquireNativeClient();
+ } catch (error) {
+ if (nativeSourceRequestRef.current === request) {
+ setNativeSources({ kind: error instanceof NativeCompatibilityError ? "incompatible" : "unavailable" });
+ }
+ return;
+ }
if (nativeSourceRequestRef.current !== request) {
return;
}
@@ -1851,7 +1825,7 @@ export function HostPage({
if (!sent) {
setNoticeErrorKey("host.pause.signalRecovering");
} else {
- setNoticeKey(nextPaused ? "host.pauseNotice" : "host.resumeNotice");
+ setNotice(null);
}
})
.catch((error: unknown) => {
@@ -1885,7 +1859,7 @@ export function HostPage({
}
sharingPausedRef.current = false;
setSharingPaused(false);
- setNoticeKey("host.resumeNotice");
+ setNotice(null);
return;
}
if (!setMediaPaused(activeStream, true)) {
@@ -1900,7 +1874,7 @@ export function HostPage({
hostSfuRouteRef.current?.setPaused(true);
discardPreparedHostChild();
if (signalRef.current?.setSharingPaused(true) === true) {
- setNoticeKey("host.pauseNotice");
+ setNotice(null);
} else {
setNoticeErrorKey("host.pause.signalRecovering");
}
@@ -2266,7 +2240,6 @@ export function HostPage({
setViewerPasswordEnabled(message.viewerPasswordEnabled);
setViewerPasswordDraft(authenticatedProfile.roomPassword ?? "");
setViewerPasswordVisible(false);
- setMaxViewers(message.maxViewers);
routePolicyRef.current = { ...message.routePolicy };
setRoutePolicy({ ...message.routePolicy });
setRoom((current) =>
@@ -2486,7 +2459,7 @@ export function HostPage({
}
activeGenerationRef.current = null;
shareGenerationRef.current = null;
- setNoticeError(error, "capture");
+ setNoticeError(error, "capture", "television");
setPhase("error");
return;
}
@@ -2698,7 +2671,7 @@ export function HostPage({
onAuthorizationRequired();
return;
}
- setNoticeError(error, "room");
+ setNoticeError(error, "room", "television");
setPhase("error");
}
};
@@ -2724,7 +2697,7 @@ export function HostPage({
onAuthorizationRequired();
return;
}
- setNoticeError(error, "room");
+ setNoticeError(error, "room", "television");
setPhase("error");
}
} finally {
@@ -2796,7 +2769,6 @@ export function HostPage({
setNotice(sourceSwitchNotice({
failedPeerCount: 0,
sfuReplaced: sfuUpdated,
- sfuWarning: null,
}));
} catch (error) {
if (
@@ -2986,7 +2958,6 @@ export function HostPage({
: sourceSwitchNotice({
failedPeerCount: failedPeerIds.length,
sfuReplaced,
- sfuWarning: null,
});
setNotice(
sourceNotice,
@@ -3236,32 +3207,10 @@ export function HostPage({
const hostIdentity = hostPeerId ?? hostClientIdRef.current ?? "host-pending";
const couchEntries: CouchEntry[] = viewers.map((viewer) => {
- const snapshot =
- viewer.upstream.kind === "peer" && viewer.upstream.peerId === hostPeerId
- ? peerSnapshots.get(viewer.peerId)
- : undefined;
- const qualityPresentation = viewerQualityEvidence.get(viewer.peerId);
- const qualityEvidence = qualityPresentation?.evidence;
- const hasCurrentQualityEvidence =
- qualityEvidence !== undefined &&
- qualityEvidenceUpstreamMatches(qualityEvidence, viewer.upstream) &&
- qualityPresentation?.fresh === true;
- const hasCommittedMedia = viewer.mediaReady === true;
- const connected =
- snapshot?.connectionState === "connected" ||
- hasCurrentQualityEvidence ||
- hasCommittedMedia;
- const viewerState = connected
- ? "connected"
- : (snapshot?.connectionState ??
- (viewer.upstream.kind === "none" ? "routing" : "connecting"));
return {
key: viewer.peerId,
name: viewer.label,
- connected,
- statusLabel: t(
- PEER_STATE_CAPTIONS[viewerState] ?? "state.peer.connecting",
- ),
+ status: deriveParticipantStatus(viewer, phase === "live", viewerQualityEvidence.get(viewer.peerId)),
};
});
@@ -3270,7 +3219,7 @@ export function HostPage({
metrics: ConnectionMetrics | null;
direction: "send" | "receive";
tag?: { icon: "loader"; label: string };
- error: string | null;
+ error: MediaFailure | null;
};
const detailForViewer = (viewer: (typeof viewers)[number]): ViewerDetail => {
const snapshot =
@@ -3289,13 +3238,6 @@ export function HostPage({
hasPeerRouteEvidence(snapshot) ||
hasCurrentQualityEvidence ||
hasCommittedMedia;
- const connected =
- snapshot?.connectionState === "connected" ||
- hasCurrentQualityEvidence ||
- hasCommittedMedia;
- const viewerState = connected
- ? "connected"
- : (snapshot?.connectionState ?? "routing");
const detailMetrics = hasCurrentQualityEvidence
? metricsFromQualityEvidence(qualityEvidence)
: snapshot && hasPeerRouteEvidence(snapshot)
@@ -3310,12 +3252,14 @@ export function HostPage({
: null,
metrics: detailMetrics,
direction: hasCurrentQualityEvidence ? "receive" : "send",
- tag: connected
+ tag: hasCommittedMedia
? undefined
: {
icon: "loader",
label: t(
- PEER_STATE_CAPTIONS[viewerState] ?? "state.peer.connecting",
+ viewer.upstream.kind === "none"
+ ? "state.peer.routing"
+ : "state.peer.connecting",
),
},
error: snapshot?.error ?? null,
@@ -3335,7 +3279,6 @@ export function HostPage({
const detail = viewerDetails.get(entry.key);
return {
...entry,
- statusLabel: entry.statusLabel ?? t("state.peer.connecting"),
route: detail?.route ?? null,
metrics: detail?.metrics ?? null,
};
@@ -3350,40 +3293,30 @@ export function HostPage({
? noticeValue.text
: t(noticeValue.key, noticeValue.vars)
: null;
+ const hostSfuWarningText = resolveMediaFailure(hostSfuQualityWarning, copy);
- const phaseLine =
- phase === "live"
- ? t("host.onlineCount", {
- n: String(viewers.length),
- max: String(maxViewers ?? "-"),
- })
- : phase === "starting"
- ? `${t("host.starting")}…`
- : phase === "ended"
- ? t("host.ended")
- : room
- ? t("host.roomReady")
- : t("host.notStarted");
- const titleFrameKey =
- phase === "live"
- ? sharingPaused
- ? "paused"
- : "hostActive"
- : phase === "starting"
- ? "hostStarting"
- : phase === "ended"
- ? "hostEnded"
- : room
- ? "hostReady"
- : "hostIdle";
- const titleContent = titleFrames(titleFrameKey);
+ const hostStatus = deriveHostStatus({
+ phase,
+ paused: sharingPaused,
+ signal: signalStatus,
+ roomReady: Boolean(room),
+ });
+ // Startup and termination reasons refine the source status. Independent
+ // operation results may coexist with it; wording is not a status identity.
+ const statusNotice = noticeValue?.target === "television" ? noticeValue : null;
+ const televisionStatus = statusNotice?.comic
+ ? { ...hostStatus.television, tone: "bad" as const, icon: "alert" as const,
+ comic: statusNotice.comic }
+ : hostStatus.television;
+ const titleContent = titleFrames(hostStatus.titleFrameKey).map((frame) =>
+ [frame, hostStatus.titleMarker].filter(Boolean).join(" "),
+ );
useDocumentTitle([room?.roomId, titleContent[0]], titleContent.slice(1));
- // Vis mode swaps native title tooltips for 2-panel hint comics; text modes
- // render the trigger unchanged, so markup structure stays identical.
+ // These Btn triggers already own their text tooltip; add only their visual comic.
// wrapStyle adds a layout span around the tooltip wrapper (vis mode only)
// for triggers whose flex context would otherwise stretch the wrapper away
- // from the trigger it must hug, or collapse a control's text-mode geometry.
+ // from the trigger it must hug.
const hintWrap = (
kind: HintKind,
node: ReactNode,
@@ -3393,14 +3326,14 @@ export function HostPage({
vis ? (
wrapStyle ? (
<span style={wrapStyle}>
- <ComicTooltip kind={kind} align={align}>
+ <Tooltip kind={kind} align={align}>
{node}
- </ComicTooltip>
+ </Tooltip>
</span>
) : (
- <ComicTooltip kind={kind} align={align}>
+ <Tooltip kind={kind} align={align}>
{node}
- </ComicTooltip>
+ </Tooltip>
)
) : (
node
@@ -3411,13 +3344,9 @@ export function HostPage({
<AppHeader
led={
<LedStrip
- state={SIGNAL_LED_STATE[signalStatus]}
- label={t(SIGNAL_LED_LABEL[signalStatus])}
- comic={
- signalStatus === "reconnecting" || signalStatus === "offline"
- ? "recovering"
- : undefined
- }
+ state={hostStatus.connection.tone}
+ label={t(hostStatus.connection.labelKey)}
+ comic={hostStatus.connection.comic}
/>
}
/>
@@ -3428,20 +3357,13 @@ export function HostPage({
</h1>
<div className="lr-scene">
<StageTv
- chin={
- phase === "live"
- ? sharingPaused
- ? "warn"
- : "on"
- : phase === "starting"
- ? "busy"
- : "off"
- }
live={phase === "live"}
hasEntry={
phase === "idle" || phase === "ended" || phase === "error"
}
label={t("host.stageAria")}
+ indicator={<StatusIndicator status={televisionStatus}
+ label={statusNotice ? noticeText ?? undefined : undefined} />}
>
{stream ? (
<video ref={videoRef} autoPlay muted playsInline />
@@ -3471,51 +3393,37 @@ export function HostPage({
) : !stream &&
(phase === "idle" || phase === "ended" || phase === "error") ? (
<div className="lr-tv-overlay">
- {vis ? null : (
- <div className="lr-entry-text">
- <h1>{t("host.idle.heading")}</h1>
- <p>{t("host.idle.hint")}</p>
- </div>
- )}
- {phase === "ended" && !vis ? (
- <span className="lr-tv-msg">{t("host.ended")}</span>
- ) : null}
+ {phase === "idle" ? <WelcomeLine /> : null}
<div className="lr-entry-actions">
<span className="lr-entry-action">
- {hintWrap(
- "hint-share-start",
+ <Tooltip kind="hint-share-start" text={vis ? undefined : t("host.start")} align="start">
<button
type="button"
className="lr-tv-big is-action is-ripple"
- title={vis ? undefined : t("host.start")}
aria-label={t("host.start")}
disabled={roomMutating}
onClick={requestSharing}
>
<VisGlyph name="cast" size={34} draw="entry-cast" />
- </button>,
- "start",
- )}
+ </button>
+ </Tooltip>
{vis ? null : (
<span className="lr-tv-msg">{t("host.start")}</span>
)}
</span>
<span className="lr-entry-action">
- {hintWrap(
- "hint-join-go",
+ <Tooltip kind={joiningRoom ? "hint-collapse" : "hint-join-go"} text={vis ? undefined : t(joiningRoom ? "host.join.hide" : "host.join")} align="end">
<button
type="button"
className="lr-tv-big"
- title={vis ? undefined : t("host.join")}
- aria-label={t("host.join")}
+ aria-label={t(joiningRoom ? "host.join.hide" : "host.join")}
aria-expanded={joiningRoom}
aria-controls="host-room-code-entry"
onClick={() => setJoiningRoom((current) => !current)}
>
<VisGlyph name="door" size={30} draw="entry-door" />
- </button>,
- "end",
- )}
+ </button>
+ </Tooltip>
{vis ? null : (
<span className="lr-tv-msg">{t("host.join")}</span>
)}
@@ -3577,18 +3485,16 @@ export function HostPage({
)}
</>
) : null}
- {hintWrap(
- "hint-join-go",
+ <Tooltip kind="hint-join-go" text={vis ? undefined : t("join.submit")}>
<button
className="lr-join-go"
type="submit"
- title={vis ? undefined : t("join.submit")}
aria-label={t("join.submit")}
disabled={joinRoomCode.length !== 4}
>
<Glyph name="arrowRight" size={24} />
- </button>,
- )}
+ </button>
+ </Tooltip>
</form>
) : null}
</div>
@@ -3603,7 +3509,7 @@ export function HostPage({
message={t("host.switchingSource")}
/>
) : sharingPaused ? (
- <StageOverlay icon="pause" dim comic="host-paused" message={t("host.pauseNotice")} />
+ <StageOverlay icon="pause" dim comic="host-paused" tone={hostStatus.activity.tone} message={t("host.pauseNotice")} />
) : phase === "starting" ? (
<>
<StaticNoise />
@@ -3623,11 +3529,25 @@ export function HostPage({
/>
) : null}
</StageTv>
- <div className="lr-shelf" aria-hidden="true" />
+ <div className="lr-stage-notices" role="status" aria-live="polite">
+ {!details?.hasAudio && stream ? (
+ <Pill icon="speaker" label={t("host.noAudio")} comic="no-audio" />
+ ) : null}
+ {hostSfuWarningText ? (
+ <Pill icon="alert" label={hostSfuWarningText} comic="warning" />
+ ) : null}
+ {noticeValue?.target === "operation" && noticeText ? (
+ <Pill icon={noticeValue.comic ? "alert" : "check"}
+ tone={noticeValue.comic ? undefined : "good"} label={noticeText}
+ comic={noticeValue.comic ?? undefined} />
+ ) : null}
+ </div>
<Couch
+ view="host"
host={{
key: hostIdentity,
name: labeledHostPresence?.label ?? displayName,
+ online: signalStatus === "connected",
you: true,
selected:
hostDiagnosticsAvailable &&
@@ -3676,41 +3596,6 @@ export function HostPage({
) : null}
</RowGroup>
) : null}
- <RowGroup>
- <StatusText>{phaseLine}</StatusText>
- {!details?.hasAudio && stream ? (
- <Pill icon="speaker" label={t("host.noAudio")} comic="no-audio" />
- ) : null}
- {qualityLimitation ? (
- <Pill
- icon="alert"
- label={qualityLimitation.message}
- comic={
- qualityLimitation.kind === "bandwidth"
- ? "bandwidth-limited"
- : qualityLimitation.kind === "cpu"
- ? "encoder-limited"
- : "warning"
- }
- />
- ) : null}
- {hostSfuQualityWarning &&
- hostSfuQualityWarning !== noticeText ? (
- <Pill
- icon="alert"
- label={hostSfuQualityWarning}
- comic="warning"
- />
- ) : null}
- {noticeText && (vis || noticeText !== phaseLine) ? (
- <Pill
- icon={noticeComic ? "alert" : "check"}
- tone={noticeComic ? undefined : "good"}
- label={noticeText}
- comic={noticeComic ?? undefined}
- />
- ) : null}
- </RowGroup>
<span className="lr-spacer" />
<div className="lr-host-personal-controls">
<div className="lr-row-group lr-group-name lr-host-identity-slot">
@@ -3793,7 +3678,7 @@ export function HostPage({
</div>
<div className="lr-row-group lr-group-actions lr-host-diagnostics-slot">
{hintWrap(
- "hint-details",
+ showConnectionDetails ? "hint-collapse" : "hint-details",
<Btn
icon="gauge"
cap={
@@ -3817,7 +3702,7 @@ export function HostPage({
"start",
)}
{hintWrap(
- "hint-topology",
+ showTopology ? "hint-collapse" : "hint-topology",
<Btn
icon="network"
cap="host.topology"
@@ -3893,7 +3778,6 @@ export function HostPage({
<div id="host-details-panel" style={{ display: "contents" }}>
<span
className="lr-meter-tag"
- title={vis ? undefined : t("host.captureAria")}
>
<Glyph name="arrowUp" size={17} />
{vis ? null : (
@@ -3907,7 +3791,6 @@ export function HostPage({
>
<span
className="lr-meter-cell"
- title={vis ? undefined : t("stats.resolution")}
>
<Glyph name="expand" size={16} />
<b>
@@ -3921,7 +3804,6 @@ export function HostPage({
</span>
<span
className="lr-meter-cell"
- title={vis ? undefined : t("stats.fps")}
>
<Glyph name="wave" size={16} />
<b>
@@ -3937,7 +3819,6 @@ export function HostPage({
</span>
<span
className="lr-meter-cell"
- title={vis ? undefined : t("stats.codec")}
>
<Glyph name="cpu" size={16} />
<b>
@@ -3950,7 +3831,6 @@ export function HostPage({
</span>
<span
className="lr-meter-cell"
- title={vis ? undefined : t("stats.audio")}
>
{vis ? (
<span
@@ -4038,18 +3918,16 @@ export function HostPage({
{room ? (
<Row label={t("host.invite")}>
<RowGroup actions>
- {hintWrap(
- "hint-copy-invite",
- <Btn
- icon={copied ? "check" : "link"}
- tone={room.inviteUrl ? "primary" : undefined}
- cap="common.copy"
- title={copied ? "common.copied" : "host.invite.copy"}
- disabled={!room.inviteUrl || roomMutating}
- onClick={() => void copyInvite()}
- />,
- "start",
- )}
+ <Btn
+ icon={copied ? "check" : "link"}
+ cap="common.copy"
+ title={copied ? "common.copied" : "host.invite.copy"}
+ hint="hint-copy-invite"
+ hintTone={copied ? "live" : undefined}
+ hintMotion={copied ? "still" : undefined}
+ disabled={!room.inviteUrl || roomMutating}
+ onClick={() => void copyInvite()}
+ />
<Btn
icon="refresh"
cap="host.invite.rotateShort"
@@ -4069,17 +3947,18 @@ export function HostPage({
/>
</RowGroup>
{room.inviteUrl ? (
- <input
- className="lr-invite-url"
- type="text"
- dir="ltr"
- value={room.inviteUrl}
- readOnly
- spellCheck={false}
- aria-label={t("host.invite")}
- title={room.inviteUrl}
- onFocus={(event) => event.currentTarget.select()}
- />
+ <Tooltip text={room.inviteUrl} className="lr-invite-hint">
+ <input
+ className="lr-invite-url"
+ type="text"
+ dir="ltr"
+ value={room.inviteUrl}
+ readOnly
+ spellCheck={false}
+ aria-label={t("host.invite")}
+ onFocus={(event) => event.currentTarget.select()}
+ />
+ </Tooltip>
) : null}
<span className="lr-divider" aria-hidden="true" />
<RowGroup>
@@ -4089,18 +3968,13 @@ export function HostPage({
aria-label={t("host.policy")}
data-selected={activeCodeEntryPolicy}
>
- {hintWrap(
- "hint-policy-open",
+ <Tooltip kind="hint-policy-open"
+ text={vis ? undefined : `${t("host.policy.open")} · ${t("host.policy.openHint")}`}>
<button
type="button"
className={
activeCodeEntryPolicy === "open" ? "is-selected" : undefined
}
- title={
- vis
- ? undefined
- : `${t("host.policy.open")} · ${t("host.policy.openHint")}`
- }
aria-label={t("host.policy.open")}
aria-pressed={activeCodeEntryPolicy === "open"}
disabled={roomMutating}
@@ -4108,16 +3982,10 @@ export function HostPage({
>
<VisGlyph name="globe" size={19} />
<Cap k="host.policy.open" />
- </button>,
- "center",
- // Vis mode interposes the tooltip wrapper between the
- // toggle and its buttons, breaking the text-mode
- // `.lr-toggle button { flex: 1 }` halves (and the sliding
- // thumb's 50% geometry). Give each wrapper its half back.
- { flex: 1, display: "grid" },
- )}
- {hintWrap(
- "hint-policy-private",
+ </button>
+ </Tooltip>
+ <Tooltip kind="hint-policy-private"
+ text={vis ? undefined : `${t("host.policy.private")} · ${t("host.policy.privateHint")}`}>
<button
type="button"
className={
@@ -4125,11 +3993,6 @@ export function HostPage({
? "is-selected"
: undefined
}
- title={
- vis
- ? undefined
- : `${t("host.policy.private")} · ${t("host.policy.privateHint")}`
- }
aria-label={t("host.policy.private")}
aria-pressed={activeCodeEntryPolicy === "private"}
disabled={roomMutating}
@@ -4137,27 +4000,16 @@ export function HostPage({
>
<VisGlyph name="lock" size={19} />
<Cap k="host.policy.private" />
- </button>,
- "center",
- { flex: 1, display: "grid" },
- )}
+ </button>
+ </Tooltip>
</span>
{activeCodeEntryPolicy === "private" ? (
- hintWrap(
- "hint-password",
+ <Tooltip kind={passwordOpen ? "hint-collapse" : "hint-password"} align="end"
+ text={vis ? undefined : `${t(passwordOpen ? "host.password.settingsHide" : "host.password.setAction")} · ${t(viewerPasswordEnabled ? "host.password.set" : "host.password.unset")}`}>
<button
type="button"
className="lr-btn"
- title={
- vis
- ? undefined
- : t(
- viewerPasswordEnabled
- ? "host.password.set"
- : "host.password.unset",
- )
- }
- aria-label={t("host.password.setAction")}
+ aria-label={t(passwordOpen ? "host.password.settingsHide" : "host.password.setAction")}
aria-expanded={passwordOpen}
aria-controls="host-password-form"
onClick={() => setPasswordOpen((current) => !current)}
@@ -4167,9 +4019,8 @@ export function HostPage({
<i className="lr-chip-dot" aria-hidden="true" />
) : null}
<Cap k="join.password" />
- </button>,
- "end",
- )
+ </button>
+ </Tooltip>
) : null}
{!room.inviteUrl ? (
<Pill
@@ -4229,6 +4080,7 @@ export function HostPage({
{viewerPasswordEnabled && viewerPasswordDraft.length > 0 ? (
<Btn
icon={viewerPasswordVisible ? "eyeOff" : "eye"}
+ hint={viewerPasswordVisible ? "hint-password-hide" : "hint-password-show"}
title={
viewerPasswordVisible
? "host.password.hide"
@@ -4279,24 +4131,17 @@ export function HostPage({
{(Object.keys(QUALITY_PROFILES) as QualityProfileId[]).map(
(id, index) => (
<Fragment key={id}>
- {hintWrap(
- "hint-quality",
+ <Tooltip kind="hint-quality" align={index === 0 ? "start" : "center"}
+ text={vis ? undefined : t("host.quality.title", {
+ label: t(QUALITY_PROFILE_CAPTIONS[id]),
+ mbps: (QUALITY_PROFILES[id].maxBitrate / 1_000_000).toFixed(0),
+ })}>
<button
type="button"
className={`lr-tile${
selectedQualityProfileId === id ? " is-selected" : ""
}`}
aria-pressed={selectedQualityProfileId === id}
- title={
- vis
- ? undefined
- : t("host.quality.title", {
- label: t(QUALITY_PROFILE_CAPTIONS[id]),
- mbps: (
- QUALITY_PROFILES[id].maxBitrate / 1_000_000
- ).toFixed(0),
- })
- }
aria-label={t(QUALITY_PROFILE_CAPTIONS[id])}
disabled={phase === "starting" || switchingSource}
onClick={() =>
@@ -4314,9 +4159,8 @@ export function HostPage({
? `${QUALITY_PROFILES[id].resolution.replace("p", "")}·${QUALITY_PROFILES[id].maxFramerate}`
: t(QUALITY_PROFILE_CAPTIONS[id])}
</small>
- </button>,
- index === 0 ? "start" : "center",
- )}
+ </button>
+ </Tooltip>
</Fragment>
),
)}
@@ -4324,12 +4168,12 @@ export function HostPage({
</RowGroup>
<span className="lr-spacer" />
{hintWrap(
- "hint-advanced",
+ showAdvanced ? "hint-collapse" : "hint-advanced",
<Btn
icon="sliders"
busy={changingQuality}
cap="host.advanced"
- title="host.advanced"
+ title={showAdvanced ? "host.advanced.hide" : "host.advanced"}
tone={showAdvanced ? "on" : undefined}
expanded={showAdvanced}
controls="host-advanced-door"
@@ -4361,7 +4205,6 @@ export function HostPage({
<div className="lr-door-group">
<span
className="lr-door-glyph"
- title={vis ? undefined : t("host.advanced.resolution")}
>
<VisGlyph name="expand" size={19} />
<Cap k="host.advanced.resolution" />
@@ -4392,7 +4235,6 @@ export function HostPage({
<div className="lr-door-group">
<span
className="lr-door-glyph"
- title={vis ? undefined : t("host.advanced.framerate")}
>
<VisGlyph name="wave" size={19} />
<Cap k="host.advanced.framerate" />
@@ -4418,7 +4260,6 @@ export function HostPage({
<div className="lr-door-group">
<span
className="lr-door-glyph"
- title={vis ? undefined : t("host.advanced.bitrate")}
>
<VisGlyph name="gauge" size={19} />
<Cap k="host.advanced.bitrate" />
@@ -4447,7 +4288,6 @@ export function HostPage({
<div className="lr-door-group">
<span
className="lr-door-glyph"
- title={vis ? undefined : t("host.advanced.preference")}
>
<VisGlyph name="mountain" size={19} />
<Cap k="host.advanced.preference" />
@@ -4490,7 +4330,6 @@ export function HostPage({
<div className="lr-door-group">
<span
className="lr-door-glyph"
- title={vis ? undefined : t("host.advanced.audio")}
>
<VisGlyph name="speaker" size={19} />
<Cap k="host.advanced.audio" />
@@ -4533,7 +4372,6 @@ export function HostPage({
<div className="lr-door-group">
<span
className="lr-door-glyph"
- title={vis ? undefined : t("host.advanced.route")}
>
<VisGlyph name="branch" size={19} />
<Cap k="host.advanced.route" />
@@ -4549,34 +4387,47 @@ export function HostPage({
note={t("host.advanced.route.topoHint")}
hint="hint-topology"
/>
- {natPredictionAvailable ? (
- <SwitchItem
- checked={routePolicy.natPrediction}
- disabled={phase === "starting" || phase === "live"}
- onChange={(checked) =>
- changeRoutePolicy({ natPrediction: checked })
- }
- label={t("host.advanced.route.natPrediction")}
- note={t("host.advanced.route.natPredictionHint")}
- hint="hint-nat-prediction"
- />
- ) : null}
+ <SwitchItem
+ checked={routePolicy.natPrediction}
+ disabled={
+ !natPredictionAvailable || phase === "starting" || phase === "live"
+ }
+ locked={!natPredictionAvailable}
+ onChange={(checked) =>
+ changeRoutePolicy({ natPrediction: checked })
+ }
+ label={t("host.advanced.route.natPrediction")}
+ note={t(
+ natPredictionAvailable
+ ? "host.advanced.route.natPredictionHint"
+ : "host.advanced.route.natPredictionUnavailable",
+ )}
+ hint={
+ natPredictionAvailable ? "hint-nat-prediction" : "hint-nat-unavailable"
+ }
+ />
<SwitchItem
checked={routePolicy.peerOnly}
- disabled={phase === "starting" || phase === "live"}
+ disabled={
+ !sfuAvailable || phase === "starting" || phase === "live"
+ }
+ locked={!sfuAvailable}
onChange={(checked) =>
changeRoutePolicy({ peerOnly: checked })
}
label={t("host.advanced.route.peerOnly")}
- note={t("host.advanced.route.peerOnlyHint")}
- hint="hint-route-p2p"
+ note={t(
+ sfuAvailable
+ ? "host.advanced.route.peerOnlyHint"
+ : "host.advanced.route.peerOnlyRequired",
+ )}
+ hint={sfuAvailable ? "hint-route-p2p" : "hint-route-p2p-required"}
/>
</div>
</div>
<div className="lr-door-group">
<span
className="lr-door-glyph"
- title={vis ? undefined : t("host.advanced.codec")}
>
<VisGlyph name="cpu" size={19} />
<Cap k="host.advanced.codec" />
diff --git a/src/client/pages/JoinPage.tsx b/src/client/pages/JoinPage.tsx
index 2db6b6a4..a94bb9f3 100644
--- a/src/client/pages/JoinPage.tsx
+++ b/src/client/pages/JoinPage.tsx
@@ -1,6 +1,6 @@
import { useState, type FormEvent } from "react";
import { AppHeader } from "../components/living/Header";
-import { ComicTooltip } from "../components/living/ComicTooltip";
+import { Tooltip } from "../components/living/Tooltip";
import { Glyph } from "../ui/icons";
import { useCopy } from "../ui/copy";
import { roomRouteForExplicitEntry } from "../lib/session";
@@ -27,7 +27,6 @@ export function JoinPage() {
<button
className="lr-join-go"
type="submit"
- title={vis ? undefined : t("join.submit")}
aria-label={t("join.submit")}
disabled={roomId.length !== 4}
>
@@ -43,7 +42,6 @@ export function JoinPage() {
<span
key={rejectedAttempt}
className={`lr-join-door${error ? " is-shake" : ""}`}
- title={vis ? undefined : t("join.title")}
role="img"
aria-label={t("join.title")}
>
@@ -99,11 +97,9 @@ export function JoinPage() {
)}
</>
) : null}
- {vis ? (
- <ComicTooltip kind="hint-join-go">{goButton}</ComicTooltip>
- ) : (
- goButton
- )}
+ <Tooltip kind="hint-join-go" text={vis ? undefined : t("join.submit")}>
+ {goButton}
+ </Tooltip>
{vis ? null : <span className="lr-cap">{t("join.submit")}</span>}
</form>
</main>
diff --git a/src/client/pages/OverlayPreviewPage.tsx b/src/client/pages/OverlayPreviewPage.tsx
index 8e1c4ca5..9baea0e6 100644
--- a/src/client/pages/OverlayPreviewPage.tsx
+++ b/src/client/pages/OverlayPreviewPage.tsx
@@ -14,13 +14,13 @@ const STATES: readonly {
{ title: "首次连接", comic: "connecting-p2p", icon: "loader", message: "正在连接" },
{ title: "第一次重试", comic: "connecting-p2p", icon: "loader", message: "正在重试", progress: "1/2" },
{ title: "SFU 连接", comic: "connecting-sfu", icon: "loader", message: "正在连接中转" },
- { title: "等待分享者", comic: "waiting-for-host", icon: "door", message: "等待分享者" },
- { title: "分享者暂停", comic: "host-paused", icon: "pause", message: "分享者已暂停" },
+ { title: "等待房主", comic: "waiting-for-host", icon: "door", message: "等待房主" },
+ { title: "房主暂停", comic: "host-paused", icon: "pause", message: "房主已暂停" },
{ title: "线路恢复", comic: "recovering", icon: "refresh", message: "正在恢复线路" },
{ title: "线路失败", comic: "route-failed", icon: "alert", message: "线路不可用" },
{ title: "播放失败", comic: "playback-failed", icon: "alert", message: "播放失败" },
{ title: "没有声音", comic: "no-audio", icon: "speaker", message: "没有可用音频" },
- { title: "分享者离线", comic: "host-offline", icon: "door", message: "分享者已离开" },
+ { title: "房主离线", comic: "host-offline", icon: "door", message: "房主已离开" },
{ title: "带宽受限", comic: "bandwidth-limited", icon: "gauge", message: "线路受到带宽限制" },
{ title: "编码受限", comic: "encoder-limited", icon: "tv", message: "编码受到限制" },
];
@@ -39,7 +39,7 @@ export function OverlayPreviewPage() {
{STATES.map((state) => (
<section className="lr-overlay-preview-card" key={state.title}>
<h2>{state.title}</h2>
- <StageTv chin={state.progress ? "busy" : "off"} label={state.message}>
+ <StageTv label={state.message}>
<StageOverlay
icon={state.icon}
comic={state.comic}
diff --git a/src/client/pages/PeoplePreview.tsx b/src/client/pages/PeoplePreview.tsx
new file mode 100644
index 00000000..a56290b8
--- /dev/null
+++ b/src/client/pages/PeoplePreview.tsx
@@ -0,0 +1,102 @@
+import { useState } from "react";
+import { Couch } from "../components/living/Couch";
+import { PawnSvg } from "../components/living/Pawn";
+import { PawnDetail } from "../components/living/PawnDetail";
+import { RouteTree } from "../components/living/RouteTree";
+import { ViewerOverview } from "../components/living/ViewerOverview";
+import { Chip, SwitchItem } from "../components/living/primitives";
+import { participantColor } from "../components/living/participant-color";
+import { labelParticipantSnapshot } from "../lib/viewer-presence";
+import { deriveParticipantStatus } from "../ui/media-status";
+import { useCopy } from "../ui/copy";
+
+const HOST_ID = "d27a938b-61f5-4ab2-b8e4-3fc090c3ae18";
+const VIEWER_IDS = [
+ "779594c8-a92c-48d9-918f-a7d0befa46d1", "7e3c8491-04c9-44b0-a233-b2f4d894058b",
+ "c8f606ea-0e95-40d6-9018-436bedbdc742", "14bf617a-60a0-47b5-b5c8-f7c883a4d41e",
+ "6d2b0957-3778-45a3-a79b-67c6aed7e0f6", "813f2dd9-ea4d-48d7-b16c-7c5526809482",
+ "f7e34a66-8bd3-4280-82f1-b175fccd2b72", "aa9f7a0f-91c9-4a67-9b0c-bf2bd8c818d3",
+ "e0400758-64a8-4134-8d78-e3c2c78f22c7", "35742451-0f6d-4860-aa36-598095fa4f3b",
+ "0052af9b-6634-44ad-97e4-f0eb14a888a0", "c03b8829-0f5a-49bf-8f62-257b2b048aaa",
+ "10608e40-c169-4da6-b5d3-a7e8668b4f30", "82a2087c-a9d4-437a-ad10-a449d2c8f032",
+ "36b3c67c-f502-4151-8e78-a16600cfd8f9", "d568a261-67c2-451c-b089-ebf090ccb563",
+ "4f787ab3-877d-445b-a2e0-e121a08b9983", "548eed4c-7572-4c69-9de3-10f1cb93ef39",
+ "9f0a89a1-f2d5-4cbd-a4ee-62a4a345d6ed", "a088c8c8-37e6-4d8a-86cf-9a48015e458b",
+];
+const NAMES = ["小桃", "阿白", "栗子", "小满", "橘子", "小岛", "可乐", "七七", "石头", "圆圆", "木木", "阿南", "小北", "豆子", "月亮", "一帆", "小鱼", "阿树", "点点", "安安"];
+
+export function PeoplePreview() {
+ const { t, lang } = useCopy();
+ const en = lang === "en";
+ const [count, setCount] = useState(20);
+ const [mode, setMode] = useState("mixed");
+ const [view, setView] = useState<"host" | "viewer">("host");
+ const [longNames, setLongNames] = useState(false);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [expanded, setExpanded] = useState(false);
+ const [overviewOpen, setOverviewOpen] = useState(false);
+ const hostName = en ? "Amu" : "阿沐";
+ const peerCount = Math.max(1, Math.floor(count * .6));
+ const { viewers } = labelParticipantSnapshot(VIEWER_IDS.slice(0, count).map((peerId, index) => ({
+ role: "viewer" as const, peerId,
+ displayName: longNames ? (en ? `Friend with a long name ${index + 1}` : `这是名字稍微长一点的朋友 ${index + 1}`) : en ? `Friend ${index + 1}` : NAMES[index]!,
+ upstream: mode === "pending" || (mode === "mixed" && index > 2 && index >= count - 2)
+ ? { kind: "none" as const }
+ : mode === "relay" ? { kind: "peer" as const, peerId: index === 0 ? HOST_ID : VIEWER_IDS[index - 1]! }
+ : index < peerCount ? { kind: "peer" as const, peerId: index === 0 ? HOST_ID : VIEWER_IDS[Math.floor((index - 1) / 2)]! }
+ : index < peerCount + 2 ? { kind: "sfu" as const }
+ : { kind: "peer" as const, peerId: VIEWER_IDS[peerCount + (index % 2)]! },
+ mediaReady: mode !== "pending" && index % 7 !== 6 && !(mode === "mixed" && index > 2 && index >= count - 2) ? true as const : undefined,
+ })));
+ const self = VIEWER_IDS[0]!;
+ const selectable = viewers.filter((viewer) => view === "host" || (viewer.upstream.kind === "peer" && viewer.upstream.peerId === self))
+ .map((viewer) => viewer.peerId);
+ const entries = viewers.map((viewer) => ({
+ key: viewer.peerId, name: viewer.label, you: view === "viewer" && viewer.peerId === self,
+ status: deriveParticipantStatus(viewer, true), selectable: selectable.includes(viewer.peerId),
+ }));
+ const selectedViewer = viewers.find((viewer) => viewer.peerId === selected && selectable.includes(viewer.peerId));
+ const select = (key: string) => setSelected((current) => current === key ? null : key);
+ return <section id="people-preview" className="cp-section">
+ <header className="cp-section-head"><span className="cp-number">05</span><div>
+ <h2>{en ? "A seat for everyone" : "人多,也坐得下。"}</h2>
+ <p>{en ? "Try the full room, long names and relay depth. Click a person to inspect the same identity in each view."
+ : "试试满员、长名字和多层转发。点击小人,沙发、连接图和详情会选中同一个人。"}</p>
+ </div></header>
+ <div className="cp-tools">
+ <div role="group" aria-label={en ? "Viewer count" : "观众人数"}>{[0, 3, 8, 20].map(value => <Chip key={value}
+ title={`${value} ${t("common.viewers")}`} selected={count === value} onClick={() => setCount(value)}>{value}</Chip>)}</div>
+ <div role="group" aria-label={en ? "Perspective" : "观察视角"}>{(["host", "viewer"] as const).map(value => <Chip key={value}
+ title={t(value === "host" ? "common.host" : "common.you")} selected={view === value} onClick={() => setView(value)}>
+ {en ? value === "host" ? "Host view" : "Viewer view" : value === "host" ? "房主视角" : "观众视角"}</Chip>)}</div>
+ <SwitchItem checked={longNames} onChange={setLongNames} label={en ? "Long names" : "换成长名字"} />
+ </div>
+ <div className="cp-people-room">
+ <div className="cp-sync" aria-label={en ? "The same Host in two places" : "同一位房主,两个位置"}>
+ <span><PawnSvg color={participantColor(HOST_ID)} identity={HOST_ID} host /><small>{en ? "Host view" : "房主这边"}</small></span>
+ <span className="cp-sync-caption">{en ? "One person, the same gesture" : "同一个人,同一个小动作"}</span>
+ <span><PawnSvg color={participantColor(HOST_ID)} identity={HOST_ID} host /><small>{en ? "Viewer view" : "朋友那边"}</small></span>
+ </div>
+ <Couch view={view} host={{ key: HOST_ID, name: hostName, online: true, you: view === "host" }}
+ entries={entries} selectedKey={selectedViewer?.peerId} onSelect={select} />
+ </div>
+ <div className="cp-tools" role="group" aria-label={en ? "Connection example" : "连接示例"}>
+ {[{ id: "mixed", label: en ? "Peers + SFU" : "P2P + SFU" }, { id: "relay", label: en ? "Deep relay chain" : "多层接力" }, { id: "pending", label: en ? "Waiting for a route" : "等待连接" }].map(item =>
+ <Chip key={item.id} title={item.label} selected={mode === item.id} onClick={() => setMode(item.id)}>{item.label}</Chip>)}
+ </div>
+ <div className="cp-connection-panel">
+ <RouteTree hostPeerId={HOST_ID} hostLabel={hostName} viewers={viewers}
+ selfPeerId={view === "viewer" ? self : HOST_ID} selectedPeerId={selectedViewer?.peerId}
+ selectablePeerIds={selectable} onSelectPeer={select} />
+ </div>
+ {selectedViewer ? <PawnDetail pawnKey={selectedViewer.peerId} name={selectedViewer.label}
+ route={selectedViewer.upstream.kind === "none" ? null : selectedViewer.upstream.kind === "sfu" ? "sfu" : "p2p"}
+ direction="send" expanded={expanded} onToggleMetrics={setExpanded} onClose={() => setSelected(null)} /> : null}
+ {view === "host" && count > 0 ? <details className="cp-disclosure" onToggle={event => setOverviewOpen(event.currentTarget.open)}>
+ <summary>{t("host.viewerOverview")}</summary>
+ {overviewOpen ? <ViewerOverview entries={entries.map((entry, index) => ({ ...entry, metrics: null,
+ route: viewers[index]!.upstream.kind === "none" ? null : viewers[index]!.upstream.kind === "sfu" ? "sfu" : "p2p",
+ }))} selectedKey={selectedViewer?.peerId ?? null} onSelect={select} /> : null}
+ </details> : null}
+ </section>;
+}
diff --git a/src/client/pages/PlaybackPreviewPage.tsx b/src/client/pages/PlaybackPreviewPage.tsx
new file mode 100644
index 00000000..44bf7b20
--- /dev/null
+++ b/src/client/pages/PlaybackPreviewPage.tsx
@@ -0,0 +1,129 @@
+import { useEffect, useRef, useState } from "react";
+import { AppHeader } from "../components/living/Header";
+import { PlaybackControls } from "../components/living/PlaybackControls";
+import { StageTv } from "../components/living/Stage";
+import { useCopy } from "../ui/copy";
+
+function testMedia(withAudio: boolean) {
+ const canvas = document.createElement("canvas");
+ canvas.width = 640;
+ canvas.height = 360;
+ const paint = canvas.getContext("2d")!;
+ const started = performance.now();
+ let animation = 0;
+ function draw(now: number) {
+ const seconds = (now - started) / 1000;
+ paint.fillStyle = "#172c3b";
+ paint.fillRect(0, 0, 640, 360);
+ paint.fillStyle = "#29475b";
+ paint.fillRect(0, 260, 640, 100);
+ paint.fillStyle = "#9de8bf";
+ paint.beginPath();
+ paint.arc(320 + Math.sin(seconds) * 190, 180, 26, 0, Math.PI * 2);
+ paint.fill();
+ paint.fillStyle = "#dfe8f2";
+ paint.font = "24px monospace";
+ paint.fillText(`${seconds.toFixed(1)} s`, 28, 44);
+ animation = requestAnimationFrame(draw);
+ }
+ draw(started);
+ const stream = canvas.captureStream(30);
+ let audio: AudioContext | undefined;
+ if (withAudio) {
+ audio = new AudioContext();
+ const tone = audio.createOscillator();
+ const gain = audio.createGain();
+ const destination = audio.createMediaStreamDestination();
+ tone.frequency.value = 220;
+ gain.gain.value = 0.02;
+ tone.connect(gain).connect(destination);
+ tone.start();
+ stream.addTrack(destination.stream.getAudioTracks()[0]);
+ }
+ return {
+ stream,
+ audio,
+ stop() {
+ cancelAnimationFrame(animation);
+ stream.getTracks().forEach((track) => track.stop());
+ if (audio) void audio.close();
+ },
+ };
+}
+
+export function PlaybackPreviewPage() {
+ const { lang } = useCopy();
+ const english = lang === "en";
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const mediaRef = useRef<ReturnType<typeof testMedia> | null>(null);
+ const [stream, setStream] = useState<MediaStream | null>(null);
+ const [theaterMode, setTheaterMode] = useState(false);
+ const [error, setError] = useState("");
+ const hasAudio = Boolean(stream?.getAudioTracks().length);
+
+ function play() {
+ const video = videoRef.current;
+ if (!video) return;
+ void video.play().catch((cause: unknown) => {
+ if (video.srcObject === stream) setError(String(cause));
+ });
+ }
+
+ function start(withAudio: boolean) {
+ mediaRef.current?.stop();
+ const media = testMedia(withAudio);
+ mediaRef.current = media;
+ setError("");
+ setStream(media.stream);
+ if (media.audio) void media.audio.resume().catch((cause: unknown) => setError(String(cause)));
+ }
+
+ useEffect(() => {
+ const video = videoRef.current!;
+ video.srcObject = stream;
+ if (stream) play();
+ }, [stream]);
+ useEffect(() => () => mediaRef.current?.stop(), []);
+ useEffect(() => {
+ if (!theaterMode) return;
+ function exit(event: KeyboardEvent) {
+ if (event.key === "Escape") setTheaterMode(false);
+ }
+ document.body.classList.add("lr-theater-open");
+ window.addEventListener("keydown", exit);
+ return () => {
+ document.body.classList.remove("lr-theater-open");
+ window.removeEventListener("keydown", exit);
+ };
+ }, [theaterMode]);
+
+ return <div className="lr-app">
+ <AppHeader homeHref="/__playback-preview" />
+ <main className={`lr-room${theaterMode ? " is-theater" : ""}`}>
+ {!theaterMode ? <header style={{ margin: "20px 0" }}>
+ <h1>{english ? "Playback controls" : "播放控件预览"}</h1>
+ <p>{english ? "Local test video only. Sound starts only when requested; no room or capture is opened."
+ : "仅本机测试画面;点击才加入轻音量测试音,不开房间、不采集屏幕。"}</p>
+ <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
+ <button className="lr-btn" type="button" onClick={() => start(false)}>
+ {english ? "Start picture only" : "开启无声测试画面"}</button>
+ <button className="lr-btn" type="button" disabled={!stream} onClick={() => start(!hasAudio)}>
+ {hasAudio ? (english ? "Remove audio track" : "移除音轨") : (english ? "Add quiet test tone" : "加入轻音量测试音")}</button>
+ <button className="lr-btn" type="button" disabled={!stream} onClick={() => start(hasAudio)}>
+ {english ? "Rebind new stream" : "重新绑定新流"}</button>
+ </div>
+ {error ? <p role="alert">{error}</p> : null}
+ </header> : null}
+ <div className="lr-scene">
+ <StageTv live={Boolean(stream)} label={english ? "Local test picture" : "本机测试画面"}>
+ <video ref={videoRef} playsInline tabIndex={0} aria-label={english ? "Local test video" : "本机测试视频"} />
+ <PlaybackControls videoRef={videoRef} stream={stream}
+ audioTrackKey={stream?.getAudioTracks().map((track) => track.id).join(",")}
+ canPlay={Boolean(stream)} theaterMode={theaterMode} onPlay={play}
+ onToggleTheater={() => setTheaterMode((value) => !value)}
+ onReconnect={() => start(hasAudio)} reconnectAvailable={Boolean(stream)} />
+ </StageTv>
+ </div>
+ </main>
+ </div>;
+}
diff --git a/src/client/pages/StatusPreviewPage.tsx b/src/client/pages/StatusPreviewPage.tsx
new file mode 100644
index 00000000..48dca243
--- /dev/null
+++ b/src/client/pages/StatusPreviewPage.tsx
@@ -0,0 +1,193 @@
+import { PawnSvg } from "../components/living/Pawn";
+import { useState } from "react";
+import { AppHeader, LedStrip } from "../components/living/Header";
+import { StageOverlay, StageTv } from "../components/living/Stage";
+import { Couch } from "../components/living/Couch";
+import { StatusIndicator } from "../components/living/StatusIndicator";
+import { Pill } from "../components/living/primitives";
+import { deriveViewerPresentation } from "../media/viewer-presentation";
+import {
+ deriveHostStatus, deriveParticipantStatus, deriveViewerStatus, peerConnectionStatus, STATUS_CATALOG,
+ type QualityObservation, type StatusDescriptor,
+} from "../ui/media-status";
+import { Glyph } from "../ui/icons";
+import { useCopy } from "../ui/copy";
+import { composeDocumentTitle, useDocumentTitle } from "../ui/document-title";
+import { HOST_STATUS_SCENARIOS, STATUS_SCENARIOS } from "./status-preview-scenarios";
+import "./status-preview.css";
+
+function StatusMark({ status }: { status: StatusDescriptor }) {
+ const { t, vis } = useCopy();
+ return (
+ <span className="sp-status">
+ <StatusIndicator status={status} />
+ {vis ? null : <span>{t(status.labelKey)}</span>}
+ </span>
+ );
+}
+
+export function StatusPreviewPage() {
+ const { t, titleFrames } = useCopy();
+ const [selected, setSelected] = useState("bandwidth");
+ const [qualityOverride, setQualityOverride] = useState<QualityObservation | null>(null);
+ const [reducedMotion, setReducedMotion] = useState(false);
+ const [couchView, setCouchView] = useState<"host" | "viewer">("viewer");
+ const scenario = STATUS_SCENARIOS.find((item) => item.id === selected)!;
+ const presentation = deriveViewerPresentation(scenario.state);
+ const quality = qualityOverride ?? scenario.quality;
+ const status = deriveViewerStatus(presentation, scenario.state.signal, quality,
+ scenario.state.route?.kind === "none" ? null : scenario.state.route?.kind);
+ const sourceActive = scenario.state.host === "online" || scenario.state.host === "paused";
+ const readyParticipant = deriveParticipantStatus({
+ mediaReady: sourceActive, upstream: { kind: "peer", peerId: "preview-host" },
+ }, sourceActive);
+ const waitingParticipant = deriveParticipantStatus({ upstream: { kind: "none" } }, sourceActive);
+ const frame = titleFrames(status.titleFrameKey)[0];
+ const titleParts = ["6020", [frame, status.titleMarker].filter(Boolean).join(" ")];
+ useDocumentTitle(titleParts);
+
+ function choose(id: string) {
+ setSelected(id);
+ setQualityOverride(null);
+ }
+
+ return (
+ <div className={`lr-app sp-page${reducedMotion ? " sp-reduced-motion" : ""}`}>
+ <AppHeader homeHref="/__status-preview" />
+ <main className="sp-main">
+ <header className="sp-heading">
+ <div><p className="sp-kicker">PIIK · 状态语义提案</p><h1>同一事实,各有分寸。</h1>
+ <p>标题说正在做什么,顶部说明信令,电视下沿图标说明画面;悬停查看文字或漫画详情。</p></div>
+ <label className="sp-motion"><input type="checkbox" checked={reducedMotion}
+ onChange={(event) => setReducedMotion(event.target.checked)} />减少动态效果</label>
+ </header>
+ <div className="sp-workbench">
+ <label className="sp-mobile-scenario">预览场景
+ <select value={selected} onChange={(event) => choose(event.target.value)}>
+ {STATUS_SCENARIOS.map((item) => <option value={item.id} key={item.id}>{item.name}</option>)}
+ </select>
+ </label>
+ <nav className="sp-scenarios" aria-label="选择状态场景">
+ {STATUS_SCENARIOS.map((item) => <button key={item.id} type="button"
+ aria-pressed={selected === item.id} onClick={() => choose(item.id)}>
+ <span>{item.name}</span><Glyph name="arrowRight" size={14} />
+ </button>)}
+ </nav>
+ <section className="sp-stage-panel" aria-label="真实组件组合预览">
+ <div className="sp-browser-title"><Glyph name="tv" size={15} />
+ <span>{composeDocumentTitle(...titleParts)}</span><span aria-hidden="true">×</span>
+ </div>
+ <div className="sp-stage-toolbar">
+ <span className="sp-room-id">6020</span>
+ <span className="sp-connection"><LedStrip state={status.connection.tone}
+ label={t(status.connection.labelKey)} comic={status.connection.comic} /></span>
+ </div>
+ <StageTv label={t(status.television.labelKey)}
+ indicator={<StatusIndicator status={status.television} />}>
+ <div className={`sp-video${presentation.hasRetainedFrame ? " is-retained" : ""}`} aria-hidden="true">
+ {presentation.hasCurrentFrame || presentation.hasRetainedFrame ? <>
+ <span className="sp-moon" /><span className="sp-hill" /><span className="sp-platform" />
+ <span className="sp-player"><PawnSvg color="var(--you)" /></span>
+ <span className="sp-score">✦ 08</span>
+ </> : null}
+ </div>
+ {status.overlay ? <StageOverlay icon={status.overlay.status.icon}
+ comic={status.overlay.status.comic} message={t(status.overlay.status.labelKey)}
+ tone={status.overlay.status.tone}
+ spin={status.overlay.status.pulse} dim={status.overlay.mode === "blocking"}
+ transition={status.overlay.status.pulse}
+ onActivate={presentation.stage === "needs-play" ? () => choose("playing") : undefined} /> : null}
+ </StageTv>
+ <div className="lr-stage-notices" role="status" aria-live="polite">
+ {status.notice ? <Pill icon={status.notice.icon} label={t(status.notice.labelKey)}
+ comic={status.notice.tooltip ?? status.notice.comic} tooltipTone={status.notice.tone} /> : null}
+ </div>
+ <div className="sp-couch-preview">
+ <div className="sp-couch-view" role="group" aria-label="沙发观察视角">
+ <span>沙发观察视角</span>
+ {(["host", "viewer"] as const).map((view) => <button type="button" className="lr-btn"
+ key={view} aria-pressed={couchView === view} onClick={() => setCouchView(view)}>
+ {view === "host" ? "Host" : "Viewer"}
+ </button>)}
+ </div>
+ <Couch view={couchView}
+ host={{ key: "preview-host", name: "Host", online: sourceActive, you: couchView === "host" }}
+ entries={[
+ { key: "preview-you", name: "You", status: readyParticipant, you: couchView === "viewer", selectable: false },
+ { key: "preview-friend", name: "Friend", selectable: false,
+ status: couchView === "host" && sourceActive ? STATUS_CATALOG.stuttering : readyParticipant },
+ { key: "preview-waiting", name: "Joining", status: waitingParticipant, selectable: false },
+ ]} />
+ </div>
+ <p className="sp-caption">沙发固定演示已接通、卡顿、等待三种事实;Host 可见卡顿证据,Viewer 只提示等待。并非现场测量。</p>
+ </section>
+ </div>
+ <section className="sp-explanation">
+ <div><h2>{scenario.name}</h2><p>{scenario.note}</p>
+ <p className="sp-caption">舞台状态:<code>{presentation.stage}</code> · 画面层:<code>{status.overlay?.mode ?? "none"}</code></p>
+ </div>
+ <div className="sp-quality-controls" role="group" aria-label="更新当前质量证据">
+ <p>手动推入一次观测,检查质量提示能否正确恢复:</p>
+ {([
+ ["带宽受限", { reason: "bandwidth", fresh: true }],
+ ["恢复正常", { reason: "none", fresh: true }],
+ ["旧样本过期", { reason: "bandwidth", fresh: false }],
+ ] as const).map(([label, observation]) => <button className="lr-btn" key={label}
+ type="button" aria-pressed={qualityOverride?.reason === observation.reason && qualityOverride.fresh === observation.fresh}
+ onClick={() => setQualityOverride(observation)}>{label}</button>)}
+ </div>
+ </section>
+ <section className="sp-surfaces" aria-label="各显示位置的含义">
+ {([
+ ["能否联系服务器", "顶部 · 信令连接", status.connection],
+ ["正在播放什么状态", "电视 · 画面与质量", status.television],
+ ] as const).map(([name, location, item]) => <article key={name}>
+ <p className="sp-kicker">{location}</p><h3>{name}</h3><StatusMark status={item} />
+ <p className="sp-caption">{t(item.labelKey)}</p>
+ </article>)}
+ <article><p className="sp-kicker">人物 · 身份与在场</p><h3>各自需要知道的状态</h3>
+ <p className="sp-caption">Host 用人物灯查看已有的逐人证据;Viewer 不显示别人的灯,只让尚未接通画面的人物呼吸。</p></article>
+ <article><p className="sp-kicker">拓扑 / Host 观众列表</p><h3>按需看线路与数据</h3>
+ <p className="sp-caption">沿用服务端已确认的媒体路径和有新鲜度的质量样本,不扩大全房广播。</p></article>
+ </section>
+ <section className="sp-catalog">
+ <header><h2>房主:源状态与控制连接</h2>
+ <p>本地预览代表正在分享的源;某个观众的弱网不改变房主的源状态。</p></header>
+ <div className="sp-host-grid">
+ {HOST_STATUS_SCENARIOS.map(({ name, facts }) => {
+ const host = deriveHostStatus(facts);
+ const hostTitle = [titleFrames(host.titleFrameKey)[0], host.titleMarker].filter(Boolean).join(" ");
+ return <article key={name}>
+ <h3>{name}</h3><p className="sp-host-title">{composeDocumentTitle("6020", hostTitle)}</p>
+ <div><span>画面</span><StatusMark status={host.television} /></div>
+ <div><span>信令</span><StatusMark status={host.connection} /></div>
+ </article>;
+ })}
+ </div>
+ </section>
+ <section className="sp-catalog">
+ <header><h2>图标状态词典</h2><p>一个图标表达一件事。悬停、键盘聚焦或长按查看对应文字或漫画。</p></header>
+ <div className="sp-catalog-grid">
+ {Object.entries(STATUS_CATALOG).map(([key, item]) => <article key={key}>
+ <StatusIndicator status={item} /><span>{t(item.labelKey)}</span><code>{key}</code>
+ </article>)}
+ </div>
+ </section>
+ <footer className="sp-footnote">
+ <details>
+ <summary>原生 WebRTC 状态怎么映射?</summary>
+ <p>这只说明传输:connected 不证明首帧已呈现;disconnected 可以恢复;closed 是连接退役,不代表新连接失败。</p>
+ <div className="sp-host-grid">
+ {(["new", "connecting", "connected", "disconnected", "failed", "closed"] as const).map((state) =>
+ <article key={state}><code>{state}</code><StatusMark status={peerConnectionStatus(state)} /></article>,
+ )}
+ </div>
+ </details>
+ <p>这是开发预览:说明固定中文,控件和漫画跟随右上角中 / EN / ✦ 与明暗主题。</p>
+ <p>Host 人物灯使用已有的新鲜证据,详情仍在观众列表。Viewer 仅使用服务端已确认的媒体就绪事实,不新增全房质量广播。</p>
+ <a href="/__tooltip-preview">全部操作漫画</a><span> · </span><a href="/__overlay-preview">旧版画面层画廊</a>
+ </footer>
+ </main>
+ </div>
+ );
+}
diff --git a/src/client/pages/TooltipPreviewPage.tsx b/src/client/pages/TooltipPreviewPage.tsx
index d57df139..3c4c8789 100644
--- a/src/client/pages/TooltipPreviewPage.tsx
+++ b/src/client/pages/TooltipPreviewPage.tsx
@@ -1,34 +1,83 @@
import { AppHeader } from "../components/living/Header";
-import { ComicTooltip } from "../components/living/ComicTooltip";
-import { HINT_KINDS, HintComic, type HintKind } from "../components/living/hints";
-import { useCopy } from "../ui/copy";
+import { Tooltip } from "../components/living/Tooltip";
+import { ControlsPreview } from "./ControlsPreview";
+import { WelcomeLine, WelcomeCipher, WELCOME_LINES } from "../components/living/WelcomeLine";
+import { HINT_KINDS, HintComic, isHintKind, type HintKind } from "../components/living/hints";
+import { Comic, type ComicKind } from "../components/living/Comic";
+import { COMIC_KINDS, getComicPresentation, type ComicTone, type ComicMotion } from "../components/living/comic-presentation";
+import { useCopy, type CopyKey } from "../ui/copy";
+
+const EXAMPLES: { label: string; kind: HintKind | ComicKind; tone: ComicTone; motion: ComicMotion; text: CopyKey }[] = [
+ { label: "说明 / Neutral", kind: "hint-volume", tone: "off", motion: "demo", text: "playback.volume" },
+ { label: "成功 / Success", kind: "hint-copy-code", tone: "live", motion: "still", text: "common.copied" },
+ { label: "受限 / Limited", kind: "hint-nat-unavailable", tone: "warn", motion: "still", text: "host.advanced.route.natPredictionUnavailable" },
+ { label: "App incompatible", kind: "warning", tone: "warn", motion: "still", text: "native.incompatible" },
+ { label: "失败 / Failed", kind: "warning", tone: "bad", motion: "still", text: "common.copyFailed" },
+ { label: "连接中 / Connecting", kind: "signal-connecting", tone: "busy", motion: "progress", text: "state.signal.connecting" },
+ { label: "恢复中 / Recovering", kind: "recovering", tone: "warn", motion: "progress", text: "state.peer.reconnecting" },
+];
+
+function PreviewCard({ kind, tone, motion, label, text }: {
+ kind: ComicKind | HintKind; tone?: ComicTone; motion?: ComicMotion; label?: string; text?: string;
+}) {
+ const defaults = getComicPresentation(kind);
+ return <section className="lr-tooltip-preview-card">
+ <header>
+ <code>{label ?? kind}</code>
+ <span className="lr-tooltip-preview-actions">
+ {text ? <Tooltip kind={kind} tone={tone} motion={motion} text={text} place="below">
+ <button type="button" aria-label={`Text ${label ?? kind}`} className="lr-tooltip-preview-trigger">Aa</button>
+ </Tooltip> : null}
+ <Tooltip kind={kind} tone={tone} motion={motion} place="below">
+ <button type="button" aria-label={`Preview ${label ?? kind}`} className="lr-tooltip-preview-trigger">✦</button>
+ </Tooltip>
+ </span>
+ </header>
+ <div className="lr-tooltip-preview-art">
+ {isHintKind(kind) ? <HintComic kind={kind} size={320} tone={tone} motion={motion} />
+ : <Comic kind={kind} size={320} theme="paper" tone={tone} motion={motion} />}
+ </div>
+ <small>{tone ?? defaults.tone} · {motion ?? defaults.motion}</small>
+ </section>;
+}
export function TooltipPreviewPage() {
- const { vis } = useCopy();
+ const { t, lang } = useCopy();
+ const en = lang === "en";
return (
<div className="lr-app">
<AppHeader />
<main className="lr-room lr-tooltip-preview">
<header className="lr-tooltip-preview-head">
- <h1>Tooltip preview</h1>
- <p>{vis ? "所有操作提示漫画" : "All control hint comics"}</p>
+ <h1>{en ? "Piik · UI catalogue" : "Piik · UI 控件大全"}</h1>
+ <p>{en ? "Actual components, sample data. Try mouse, keyboard and touch." : "正式组件,示例数据。鼠标、键盘、触屏都可以试。"}</p>
</header>
+ <nav className="cp-nav" aria-label={en ? "Preview sections" : "预览目录"}>
+ <a href="#button-preview">{en ? "Buttons" : "按钮"}</a><a href="#option-preview">{en ? "Options" : "选择与开关"}</a>
+ <a href="#input-preview">{en ? "Inputs" : "输入与房间号"}</a><a href="#feedback-preview">{en ? "Feedback" : "反馈"}</a>
+ <a href="#people-preview">{en ? "People & connections" : "人物、沙发与连接图"}</a><a href="#source-preview">{en ? "Source picker" : "画面选择"}</a>
+ <a href="#playback-preview">{en ? "Playback" : "播放栏"}</a><a href="#comic-preview">{en ? "Tooltips & comics" : "提示与漫画"}</a>
+ <a href="#welcome-preview">{en ? "20 opening lines" : "20 句开场白"}</a>
+ <a href="/__status-preview">{en ? "Status gallery" : "完整状态预览"}</a>
+ </nav>
+ <ControlsPreview />
+ <WelcomeLine />
+ <details id="welcome-preview" className="lr-welcome-catalog" open>
+ <summary>20 句开场白 / 20 opening lines</summary>
+ <p>{en ? "One line per visit to the App launcher or the browser's sharing screen. Pure visual mode uses matching pictograms and pixel lettering; switching modes keeps the same line." : "进入 App 启动页或网页版的分享准备画面时,随机选一句。纯视觉模式显示对应的图形与像素暗号;切换模式还是同一句。"}</p>
+ <ol>{WELCOME_LINES.map(({ key }, index) => <li key={key}><span>{t(key)}</span><WelcomeCipher line={index} /></li>)}</ol>
+ </details>
+ <h2 id="comic-preview">语义规则 / Semantic grammar</h2>
+ <div className="lr-tooltip-preview-grid">
+ {EXAMPLES.map((example) => <PreviewCard key={example.label} {...example} text={t(example.text)} />)}
+ </div>
+ <h2>操作说明 / Controls</h2>
+ <div className="lr-tooltip-preview-grid">
+ {HINT_KINDS.map((kind) => <PreviewCard key={kind} kind={kind} />)}
+ </div>
+ <h2>状态说明 / States</h2>
<div className="lr-tooltip-preview-grid">
- {HINT_KINDS.map((kind: HintKind) => (
- <section className="lr-tooltip-preview-card" key={kind}>
- <header>
- <code>{kind}</code>
- <ComicTooltip kind={kind} place="below">
- <button type="button" aria-label={`Preview ${kind}`} className="lr-tooltip-preview-trigger">
- ✦
- </button>
- </ComicTooltip>
- </header>
- <div className="lr-tooltip-preview-art">
- <HintComic kind={kind} size={320} />
- </div>
- </section>
- ))}
+ {COMIC_KINDS.map((kind) => <PreviewCard key={kind} kind={kind} />)}
</div>
</main>
</div>
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index 18e66d60..5e803538 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -1,3 +1,4 @@
+import { PawnSvg } from "../components/living/Pawn";
import {
useEffect,
useMemo,
@@ -18,26 +19,26 @@ import {
type ServerMessage,
type RoutePolicy,
} from "../../shared/protocol";
-import { qualityLimitationSummary } from "../components/connection-details";
import {
viewerReconnectRoute,
viewerRouteEvidence,
} from "../components/status-badge-model";
-import { AppHeader, LedStrip, type LedState } from "../components/living/Header";
-import { Couch, PawnSvg, type CouchEntry } from "../components/living/Couch";
+import { AppHeader, LedStrip } from "../components/living/Header";
+import { Couch, type CouchEntry } from "../components/living/Couch";
import { participantColor } from "../components/living/participant-color";
import { MetricCells, useMetricsExpanded } from "../components/living/Metrics";
import { PawnDetail, RouteGlyph } from "../components/living/PawnDetail";
import { Lcd } from "../components/living/RoomChip";
import { RouteTree } from "../components/living/RouteTree";
import { Comic, type ComicKind } from "../components/living/Comic";
-import { ComicTooltip } from "../components/living/ComicTooltip";
+import { Tooltip } from "../components/living/Tooltip";
import type { HintKind } from "../components/living/hints";
import {
StageOverlay,
StageTv,
- type ChinState,
} from "../components/living/Stage";
+import { StatusIndicator } from "../components/living/StatusIndicator";
+import { PlaybackControls } from "../components/living/PlaybackControls";
import { BrandLoader } from "../components/living/BrandMark";
import {
Btn,
@@ -45,7 +46,6 @@ import {
NameTag,
Pill,
Row,
- StatusText,
} from "../components/living/primitives";
import { Glyph, type GlyphName } from "../ui/icons";
import { useCopy, type CopyKey } from "../ui/copy";
@@ -56,6 +56,7 @@ import {
saveDisplayName,
} from "../lib/display-name";
import { useDocumentTitle } from "../ui/document-title";
+import { deriveViewerStatus, deriveParticipantStatus } from "../ui/media-status";
import { clearViewerGrant, getStableClientId } from "../lib/session";
import { createOpaqueId } from "../lib/opaque-id";
import { SignalingClient } from "../lib/signaling";
@@ -88,10 +89,8 @@ import {
deriveViewerPresentation,
reduceViewerPresentation,
viewerFailureFromServerCode,
- type ViewerNoticeKey,
type ViewerPresentationAction,
type ViewerRouteKind,
- type ViewerStage,
} from "../media/viewer-presentation";
import { prepareViewerPlayback } from "../media/viewer-playback";
import {
@@ -163,112 +162,10 @@ interface RemoteMediaBinding {
audioTrackKey: string;
}
-function stageOverlayGlyph(stage: ViewerStage): { icon: GlyphName; spin: boolean } {
- switch (stage) {
- case "needs-play":
- return { icon: "play", spin: false };
- case "host-paused":
- return { icon: "pause", spin: false };
- case "host-offline":
- return { icon: "wifiOff", spin: false };
- case "route-failed":
- case "playback-failed":
- case "server-error":
- case "stale-client":
- case "session-replaced":
- case "signal-terminated":
- return { icon: "alert", spin: false };
- case "recovering":
- case "waiting-sfu":
- case "preparing-p2p":
- case "preparing-sfu":
- case "receiving":
- case "allocating":
- return { icon: "loader", spin: true };
- case "waiting-host":
- return { icon: "moon", spin: false };
- default:
- return { icon: "tv", spin: false };
- }
-}
-
-// Visual mode tells the stage as a panel comic; the glyph stays as its marker.
-function stageOverlayComic(
- stage: ViewerStage,
- route: "p2p" | "sfu" | null,
-): ComicKind | undefined {
- switch (stage) {
- case "waiting-host":
- return "waiting-for-host";
- case "preparing-p2p":
- return "connecting-p2p";
- case "preparing-sfu":
- case "waiting-sfu":
- return "connecting-sfu";
- case "needs-play":
- return "tap-to-play";
- case "host-paused":
- return "host-paused";
- case "recovering":
- return "recovering";
- case "route-failed":
- return "route-failed";
- case "server-error":
- case "stale-client":
- case "session-replaced":
- case "signal-terminated":
- return "warning";
- case "playback-failed":
- return "playback-failed";
- case "host-offline":
- return "host-offline";
- case "receiving":
- case "allocating":
- return route === "sfu" ? "connecting-sfu" : "connecting-p2p";
- default:
- return undefined;
- }
-}
-
-function viewerNoticeVisual(
- noticeKey: ViewerNoticeKey,
-): { icon: GlyphName; comic: ComicKind } {
- switch (noticeKey) {
- case "viewer.notice.hostOffline":
- return { icon: "wifiOff", comic: "host-offline" };
- case "viewer.notice.signalRecovering":
- return { icon: "wifiOff", comic: "recovering" };
- case "viewer.notice.mediaRecovering":
- return { icon: "refresh", comic: "recovering" };
- }
-}
-
-function stageChin(stage: ViewerStage): ChinState {
- switch (stage) {
- case "playing":
- return "on";
- case "host-paused":
- case "recovering":
- return "warn";
- case "route-failed":
- case "playback-failed":
- case "host-offline":
- case "server-error":
- case "stale-client":
- case "session-replaced":
- case "signal-terminated":
- return "bad";
- case "waiting-host":
- return "off";
- default:
- return "busy";
- }
-}
-
function MeterTag({ icon, label }: { icon: GlyphName; label: string }) {
const { vis } = useCopy();
return (
- <span className="lr-meter-tag" title={vis ? undefined : label} role="img" aria-label={label}>
+ <span className="lr-meter-tag" role="img" aria-label={label}>
<Glyph name={icon} size={17} />
{vis ? null : <span className="lr-cap">{label}</span>}
</span>
@@ -359,35 +256,12 @@ export function ViewerPage({
};
}, [theaterMode]);
- const qualityLimitation = useMemo(
- () =>
- qualityLimitationSummary(
- [peerSnapshot, relaySnapshot].filter(
- (snapshot): snapshot is PeerSnapshot => snapshot !== null,
- ),
- ),
- [peerSnapshot, relaySnapshot],
- );
const { host: labeledHostPresence, viewers } = useMemo(
() => labelParticipantSnapshot(participantPresence ?? []),
[participantPresence],
);
const currentHostDisplayName = labeledHostPresence?.label ?? null;
const hostDisplayName = currentHostDisplayName ?? lastHostDisplayName;
- const titleFrameKey =
- presentationState.host === "paused"
- ? "paused"
- : presentation.hasCurrentFrame
- ? "viewerActive"
- : "viewerWaiting";
- const titleContent = titleFrames(titleFrameKey);
- useDocumentTitle(
- [
- accessState === "ready" ? roomId : null,
- accessState === "ready" ? titleContent[0] : null,
- ],
- accessState === "ready" ? titleContent.slice(1) : [],
- );
function clearParticipantPresence(): void {
setParticipantPresence(null);
@@ -437,6 +311,28 @@ export function ViewerPage({
peerSnapshot,
sfuUpstream,
);
+ const assignedRouteKind =
+ assignedRoute?.upstream.kind === "sfu"
+ ? "sfu"
+ : assignedRoute?.upstream.kind === "peer"
+ ? "p2p"
+ : routePresentation.route;
+ const viewerStatus = deriveViewerStatus(
+ presentation,
+ signalStatus,
+ undefined,
+ assignedRouteKind,
+ );
+ const titleContent = titleFrames(viewerStatus.titleFrameKey).map((frame) =>
+ [frame, viewerStatus.titleMarker].filter(Boolean).join(" "),
+ );
+ useDocumentTitle(
+ [
+ accessState === "ready" ? roomId : null,
+ accessState === "ready" ? titleContent[0] : null,
+ ],
+ accessState === "ready" ? titleContent.slice(1) : [],
+ );
const peerConnectionIdentity = peerRef.current?.getConnectionIdentity() ?? null;
const reconnectRoute = viewerReconnectRoute(
assignedRoute?.upstream ?? null,
@@ -679,7 +575,9 @@ export function ViewerPage({
decodedFrameStall.setPaused(currentHostPaused || pageSuspended);
};
const suspendForPageLifecycle = (): void => {
- invalidatePresentedMedia();
+ // Losing observation does not invalidate media already proved playable.
+ invalidateQualityPresentation();
+ rearmCurrentFrameProof();
const newlySuspended = !pageSuspended;
pageSuspended = true;
viewerSfuRoute?.resetQualityProbe();
@@ -694,7 +592,8 @@ export function ViewerPage({
}
};
const recoverFromPageLifecycle = (): void => {
- invalidatePresentedMedia();
+ invalidateQualityPresentation();
+ rearmCurrentFrameProof();
pageSuspended = document.visibilityState !== "visible";
syncDecodedFrameStallPause();
if (pageSuspended) return;
@@ -2319,7 +2218,7 @@ export function ViewerPage({
<div className="lr-join-panel">
{vis ? (
<>
- <Comic kind={deniedComic} theme="paper" />
+ <Comic kind={deniedComic} theme="paper" tone={viewerStatus.activity.tone} />
<span className="visually-hidden" role="alert">
{t(presentation.messageKey)} · {t(deniedHintKey)}
</span>
@@ -2332,7 +2231,6 @@ export function ViewerPage({
color: "var(--ink)",
background: "var(--paper)",
}}
- title={t(presentation.messageKey)}
role="img"
aria-label={t(presentation.messageKey)}
>
@@ -2407,19 +2305,6 @@ export function ViewerPage({
);
}
- const chin = stageChin(presentation.stage);
- const ledState: LedState = chin === "on" ? "live" : chin;
- const overlayGlyph = stageOverlayGlyph(presentation.stage);
- const assignedRouteKind =
- assignedRoute?.upstream.kind === "sfu"
- ? "sfu"
- : assignedRoute?.upstream.kind === "peer"
- ? "p2p"
- : routePresentation.route;
- const overlayComic = stageOverlayComic(
- presentation.stage,
- assignedRouteKind,
- );
const connectionAttempt = presentation.stage === "preparing-p2p" &&
assignedRoute?.phase === "prepare" &&
assignedRoute.revision === presentationState.revision
@@ -2439,13 +2324,10 @@ export function ViewerPage({
current: String(retryAttempt.current),
total: String(retryAttempt.total),
})
- : t(presentation.messageKey);
+ : t(viewerStatus.activity.labelKey);
const connectionProgress = retryAttempt
? `${retryAttempt.current}/${retryAttempt.total}`
: undefined;
- const noticeVisual = presentation.noticeKey
- ? viewerNoticeVisual(presentation.noticeKey)
- : null;
const selectedChildEvidence =
selectedPawn !== null && selectedPawn !== selfPeerId
? freshViewerQualityEvidence(relayChildEvidence.get(selectedPawn))
@@ -2473,14 +2355,7 @@ export function ViewerPage({
return {
key: viewer.peerId,
name: viewer.label,
- connected: viewer.mediaReady === true,
- statusLabel: t(
- isSelf
- ? (`state.peer.${presentation.connectionState}` as CopyKey)
- : viewer.upstream.kind === "none"
- ? "state.peer.routing"
- : "state.peer.connecting",
- ),
+ status: deriveParticipantStatus(viewer, presentationState.host === "online"),
you: isSelf,
selectable: isChild ? undefined : false,
};
@@ -2494,18 +2369,16 @@ export function ViewerPage({
)
.map((viewer) => viewer.peerId);
- // Vis mode swaps native title tooltips for 2-panel hint comics; text modes
- // render the trigger unchanged, so markup structure stays identical. Edge
- // alignment keeps the panel on-screen for triggers near a viewport edge.
+ // Btn owns its text tooltip; these wrappers supply only its visual comic.
const hintWrap = (
kind: HintKind,
node: ReactNode,
align: "start" | "center" | "end" = "center",
): ReactNode =>
vis ? (
- <ComicTooltip kind={kind} align={align}>
+ <Tooltip kind={kind} align={align}>
{node}
- </ComicTooltip>
+ </Tooltip>
) : (
node
);
@@ -2519,7 +2392,13 @@ export function ViewerPage({
.lr-tv-screen:has(:focus-visible) { outline: 3px solid var(--action); outline-offset: 2px; }
`}</style>
<AppHeader
- led={<LedStrip state={ledState} label={stageMessage} />}
+ led={
+ <LedStrip
+ state={viewerStatus.connection.tone}
+ label={t(viewerStatus.connection.labelKey)}
+ comic={viewerStatus.connection.comic}
+ />
+ }
/>
<main className={`lr-room${theaterMode ? " is-theater" : ""}`}>
<h1 className="visually-hidden">
@@ -2529,22 +2408,16 @@ export function ViewerPage({
</h1>
<div className="lr-scene" id="viewer-stage">
<StageTv
- chin={chin}
live={presentation.stage === "playing"}
label={t("viewer.stageAria")}
+ indicator={<StatusIndicator status={viewerStatus.television}
+ label={retryAttempt ? stageMessage : undefined} />}
>
<video
ref={videoRef}
autoPlay
tabIndex={0}
aria-label={t("viewer.stageAria")}
- controls={
- presentation.overlay === "none" ||
- presentation.stage === "needs-play" ||
- (presentation.stage === "receiving" &&
- presentation.hasRetainedFrame)
- }
- controlsList={theaterMode ? "nofullscreen" : undefined}
playsInline
onPlay={() => {
invalidateQualityPresentation();
@@ -2560,12 +2433,30 @@ export function ViewerPage({
onPause={invalidateQualityPresentation}
onEnded={invalidateQualityPresentation}
/>
+ <PlaybackControls
+ videoRef={videoRef}
+ stream={remoteMedia?.stream ?? null}
+ audioTrackKey={remoteMedia?.audioTrackKey}
+ theaterMode={theaterMode}
+ onToggleTheater={() => setTheaterMode((current) => !current)}
+ onReconnect={retryConnection}
+ reconnectAvailable={reconnectAvailable}
+ canPlay={presentation.overlay === "none" ||
+ presentation.stage === "needs-play" ||
+ (presentation.stage === "receiving" && presentation.hasRetainedFrame)}
+ onPlay={() => {
+ const video = videoRef.current;
+ const binding = remoteMediaRef.current;
+ if (video && binding) attemptPlayback(video, binding);
+ }}
+ />
{presentation.overlay === "blocking" && (
<StageOverlay
dim
- icon={overlayGlyph.icon}
- transition={overlayGlyph.spin}
- comic={overlayComic}
+ icon={viewerStatus.activity.icon}
+ transition={viewerStatus.activity.pulse}
+ comic={viewerStatus.activity.comic}
+ tone={viewerStatus.activity.tone}
message={stageMessage}
progress={connectionProgress}
/>
@@ -2574,8 +2465,9 @@ export function ViewerPage({
presentation.stage === "needs-play" && (
<StageOverlay
dim
- icon="play"
- comic="tap-to-play"
+ icon={viewerStatus.activity.icon}
+ comic={viewerStatus.activity.comic}
+ tone={viewerStatus.activity.tone}
message={t(presentation.messageKey)}
onActivate={() => {
const video = videoRef.current;
@@ -2588,77 +2480,33 @@ export function ViewerPage({
presentation.stage !== "needs-play" && (
<StageOverlay
dim
- icon={overlayGlyph.icon}
- comic={overlayComic}
+ icon={viewerStatus.activity.icon}
+ comic={viewerStatus.activity.comic}
+ tone={viewerStatus.activity.tone}
message={stageMessage}
progress={connectionProgress}
- spin={overlayGlyph.spin}
+ spin={viewerStatus.activity.pulse}
/>
)}
</StageTv>
- {(presentation.noticeKey ||
- (routePresentation.evidence === peerSnapshot &&
- peerSnapshot?.error) ||
- relaySnapshot?.error ||
- qualityLimitation) && (
- <div className="lr-stage-notices">
- {presentation.noticeKey && noticeVisual ? (
- <Pill
- icon={noticeVisual.icon}
- label={t(presentation.noticeKey)}
- comic={noticeVisual.comic}
- />
- ) : null}
- {routePresentation.evidence === peerSnapshot &&
- peerSnapshot?.error ? (
- <Pill
- icon="alert"
- tone="bad"
- label={t("viewer.error.p2p")}
- comic="warning"
- />
- ) : null}
- {relaySnapshot?.error ? (
- <Pill
- icon="alert"
- tone="bad"
- label={t("viewer.error.relay")}
- comic="warning"
- />
- ) : null}
- {qualityLimitation ? (
- <Pill
- icon="alert"
- label={qualityLimitation.message}
- comic={
- qualityLimitation.kind === "bandwidth"
- ? "bandwidth-limited"
- : qualityLimitation.kind === "cpu"
- ? "encoder-limited"
- : "warning"
- }
- />
- ) : null}
- </div>
- )}
- {theaterMode ? (
- <div className="lr-theater-exit">
- <Btn
- icon="contract"
- cap="viewer.theater.exit"
- title="viewer.theater.exit"
- hint="hint-theater-exit"
- onClick={() => setTheaterMode(false)}
+ <div className="lr-stage-notices" role="status" aria-live="polite">
+ {viewerStatus.notice && (
+ <Pill
+ icon={viewerStatus.notice.icon}
+ label={t(viewerStatus.notice.labelKey)}
+ comic={viewerStatus.notice.comic}
+ tooltipTone={viewerStatus.notice.tone}
/>
- </div>
- ) : null}
- <div className="lr-shelf" aria-hidden="true" />
+ )}
+ </div>
<Couch
+ view="viewer"
host={
labeledHostPresence
? {
key: labeledHostPresence.peerId,
name: labeledHostPresence.label,
+ online: true,
}
: null
}
@@ -2685,9 +2533,6 @@ export function ViewerPage({
<Glyph name="tv" size={17} />
<b>{hostDisplayName ?? t("common.host")}</b>
</div>
- <div className="lr-row-group lr-viewer-state-slot">
- <StatusText>{t(presentation.messageKey)}</StatusText>
- </div>
<div className="lr-viewer-personal-controls">
<form
className="lr-row-group lr-group-name lr-viewer-self-slot"
@@ -2763,37 +2608,6 @@ export function ViewerPage({
)}
</form>
<div className="lr-row-group lr-group-actions lr-viewer-actions-slot">
- <span
- className="lr-viewer-action-separator"
- aria-hidden="true"
- />
- <span className="lr-viewer-action-cluster">
- <Btn
- icon={theaterMode ? "contract" : "expand"}
- cap={theaterMode ? "viewer.theater.exit" : "viewer.theater"}
- title={
- theaterMode ? "viewer.theater.exit" : "viewer.theater"
- }
- hint={
- theaterMode ? "hint-theater-exit" : "hint-theater"
- }
- tone={theaterMode ? "on" : undefined}
- pressed={theaterMode}
- controls="viewer-stage"
- onClick={() => setTheaterMode((current) => !current)}
- />
- {hintWrap(
- "hint-reconnect",
- <Btn
- icon="refresh"
- cap="viewer.reconnect"
- title="viewer.reconnect"
- disabled={!reconnectAvailable}
- onClick={retryConnection}
- />,
- "end",
- )}
- </span>
<span
className="lr-viewer-action-separator"
aria-hidden="true"
@@ -2805,7 +2619,7 @@ export function ViewerPage({
title={
showConnectionDetails ? "host.details.hide" : "host.details"
}
- hint="hint-details"
+ hint={showConnectionDetails ? "hint-collapse" : "hint-details"}
tone={showConnectionDetails ? "on" : undefined}
expanded={showConnectionDetails}
controls="viewer-details-panel"
@@ -2819,7 +2633,7 @@ export function ViewerPage({
}
/>
{hintWrap(
- "hint-topology",
+ labeledHostPresence && showTopology ? "hint-collapse" : "hint-topology",
<Btn
icon="network"
cap="host.topology"
@@ -2876,7 +2690,7 @@ export function ViewerPage({
<Row sub key={viewer.peerId} label={viewer.label}>
<MeterTag icon="arrowUp" label={t("stats.downstream")} />
<span className="lr-pawn-mini">
- <PawnSvg color={participantColor(viewer.peerId)} />
+ <PawnSvg color={participantColor(viewer.peerId)} identity={viewer.peerId} />
</span>
<span className="lr-pawn-detail-name">{viewer.label}</span>
<MetricCells
diff --git a/src/client/pages/controls-preview.css b/src/client/pages/controls-preview.css
new file mode 100644
index 00000000..5b5a3a26
--- /dev/null
+++ b/src/client/pages/controls-preview.css
@@ -0,0 +1,38 @@
+.cp-nav { display: flex; flex-wrap: wrap; gap: 8px 18px; margin: 20px 0 28px; }
+.cp-nav a { color: var(--ink); font-size: 13px; text-underline-offset: 5px; }
+.cp-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
+.cp-card { min-width: 0; padding: 24px; border: 1px solid var(--control-edge); border-radius: 24px; background: var(--paper); }
+.cp-card > header, .cp-section-head { display: flex; align-items: baseline; gap: 12px; }
+.cp-card > header h2, .cp-section-head h2 { margin: 0; font-size: 19px; }
+.cp-number { font: 600 11px var(--mono); color: var(--ink); }
+.cp-card p, .cp-section-head p { margin: 12px 0 20px; color: var(--muted); font-size: 13px; line-height: 1.7; }
+.cp-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 16px 0; }
+.cp-tools > [role="group"]:not(.lr-lcd) { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+.cp-tools .lr-input { max-width: 100%; }
+.cp-tools .lr-input input { width: 160px; }
+.cp-tools .lr-pill { max-width: 100%; }
+.cp-feedback { min-height: 2em; }
+.cp-card .cp-input-error { color: var(--danger); }
+.cp-dials { width: fit-content; max-width: 100%; margin: 20px 0 0; }
+.cp-dials .lr-dial { width: 46px; height: 58px; font-size: 28px; }
+.cp-section { margin-top: 44px; scroll-margin-top: 24px; }
+.cp-people-room { padding: 24px 12px 8px; border-radius: 26px; background: var(--wall-2); }
+.cp-sync { display: flex; align-items: center; justify-content: center; gap: 24px; }
+.cp-sync > span { display: grid; justify-items: center; gap: 8px; }
+.cp-sync .lr-person { width: 56px; height: 65px; }
+.cp-sync-caption { max-width: 12ch; color: var(--muted); text-align: center; font-size: 12px; line-height: 1.7; }
+.cp-sync small { color: var(--muted); font-size: 11px; }
+.cp-connection-panel { padding: 12px; border: 1px solid var(--control-edge); border-radius: 22px; background: var(--paper); }
+.cp-disclosure { margin-top: 12px; }
+.cp-disclosure summary { padding: 12px 0; cursor: pointer; }
+.cp-stage { max-width: 780px; margin: 22px auto; }
+.cp-poster { width: 100%; height: 100%; object-fit: cover; }
+.cp-stage-action { position: absolute; inset: 0; display: grid; place-items: center; }
+@media (max-width: 850px) { .cp-grid { grid-template-columns: 1fr; } }
+@media (max-width: 480px) {
+ .cp-card { padding: 18px; }
+ .cp-section-head h2, .cp-card > header h2 { font-size: 17px; }
+ .cp-sync { gap: 16px; }
+ .cp-people-room { padding-inline: 0; }
+ .cp-connection-panel { padding: 4px; }
+}
diff --git a/src/client/pages/host-page-notices.ts b/src/client/pages/host-page-notices.ts
index 2a7ab514..37af95f2 100644
--- a/src/client/pages/host-page-notices.ts
+++ b/src/client/pages/host-page-notices.ts
@@ -1,6 +1,6 @@
import type { ServerMessage } from "../../shared/protocol";
import { NativeMediaBridgeError } from "../native/media-bridge";
-import { joinSentences, say, type CopyKey } from "../ui/copy";
+import { currentLang, joinSentences, say, type CopyKey } from "../ui/copy";
export type HostAction =
| "capture"
@@ -65,26 +65,18 @@ export function hostServerErrorNotice(code: ServerErrorCode): string {
export function sourceSwitchNotice({
failedPeerCount,
sfuReplaced,
- sfuWarning,
}: {
failedPeerCount: number;
sfuReplaced: boolean;
- sfuWarning: string | null;
}): string {
const peerWarning =
failedPeerCount > 0 ? say("host.notice.reconnecting") : null;
if (!sfuReplaced) {
const parts = [
- sfuWarning ?? say("host.notice.sfuRecovering"),
+ say("host.notice.sfuRecovering"),
peerWarning,
].filter((message): message is string => message !== null);
- return joinSentences(parts);
- }
- if (sfuWarning) {
- const parts = [sfuWarning, peerWarning].filter(
- (message): message is string => message !== null,
- );
- return joinSentences(parts);
+ return joinSentences(currentLang(), parts);
}
return peerWarning
? say("host.notice.sourceSwitch.partial", { warning: peerWarning })
diff --git a/src/client/pages/status-preview-scenarios.ts b/src/client/pages/status-preview-scenarios.ts
new file mode 100644
index 00000000..669791cd
--- /dev/null
+++ b/src/client/pages/status-preview-scenarios.ts
@@ -0,0 +1,131 @@
+import {
+ INITIAL_VIEWER_PRESENTATION_STATE,
+ reduceViewerPresentation,
+ type ViewerFailureCode,
+ type ViewerPresentationAction,
+ type ViewerPresentationState,
+} from "../media/viewer-presentation";
+import type { QualityObservation, deriveHostStatus } from "../ui/media-status";
+
+export interface StatusScenario {
+ id: string;
+ name: string;
+ note: string;
+ state: ViewerPresentationState;
+ quality?: QualityObservation;
+}
+
+const ready: ViewerPresentationAction[] = [
+ { type: "access", access: "ready" },
+ { type: "signal", signal: "connected" },
+ { type: "host", host: "online" },
+];
+const receiving: ViewerPresentationAction[] = [
+ ...ready,
+ { type: "route", revision: 1, phase: "active", kind: "p2p" },
+ { type: "media-bound", generation: 1, revision: 1 },
+ { type: "connection", revision: 1, connection: "connected" },
+];
+const playing: ViewerPresentationAction[] = [
+ ...receiving,
+ { type: "frame-presented", generation: 1, proofEpoch: 0, revision: 1 },
+];
+
+function scenario(
+ id: string,
+ name: string,
+ note: string,
+ actions: ViewerPresentationAction[],
+ quality?: QualityObservation,
+): StatusScenario {
+ return {
+ id, name, note, quality,
+ state: actions.reduce(reduceViewerPresentation, INITIAL_VIEWER_PRESENTATION_STATE),
+ };
+}
+
+const denied: [ViewerFailureCode, string][] = [
+ ["ROOM_NOT_FOUND", "房间不存在"],
+ ["ROOM_ACCESS_DENIED", "没有准入权限"],
+ ["INVALID_TOKEN", "邀请无效"],
+ ["ROOM_CLOSED", "房间已结束"],
+ ["ROOM_FULL", "房间已满"],
+ ["STALE_CLIENT", "页面版本已过期"],
+ ["SESSION_REPLACED", "被另一个页面接管"],
+ ["SIGNAL_TERMINATED", "会话已结束"],
+ ["SERVER_ERROR", "服务不可用"],
+];
+
+export const STATUS_SCENARIOS: readonly StatusScenario[] = [
+ scenario("playing", "正常观看", "已呈现当前连接的画面;没有新鲜的质量受限证据。", playing),
+ scenario("bandwidth", "带宽受限,仍在播放", "示例:该画面上游 sender 报告 bandwidth;黄色提示适配,不把画面盖住。", playing,
+ { reason: "bandwidth", fresh: true }),
+ scenario("cpu", "编码受限,仍在播放", "示例:该画面上游 sender 报告 cpu;描述编码受限,不猜测是哪块硬件。", playing,
+ { reason: "cpu", fresh: true }),
+ scenario("other", "其他质量限制", "示例:该画面上游 sender 报告 other;保留原因的不确定性。", playing,
+ { reason: "other", fresh: true }),
+ scenario("stale", "质量样本过期", "旧的 bandwidth 观测已经过期;不能继续把灯染黄。", playing,
+ { reason: "bandwidth", fresh: false }),
+ scenario("unknown", "质量未知", "没有可用的质量原因不等于质量良好,也不等于断线。", playing,
+ { reason: "unknown", fresh: true }),
+ scenario("background", "切到后台后回来", "重新武装帧观察,保留之前的播放证明;页面可见性本身不是播放故障。", [
+ ...playing, { type: "frame-proof-rearm", generation: 1 },
+ ]),
+ scenario("signal-recovering", "信令断开,画面仍在播放", "控制连接正在恢复;媒体仍有当前画面,标题保留观看状态。", [
+ ...playing, { type: "signal", signal: "reconnecting" },
+ ]),
+ scenario("host-offline-playing", "房主离线,仍有当前画面", "房主在线状态和正在接收的媒体不是同一件事;先给提示,不直接覆盖画面。", [
+ ...playing, { type: "host", host: "offline" },
+ ]),
+ scenario("joining", "正在加入房间", "尚未完成准入;不能把 WebSocket 连通当成视频已播放。", []),
+ scenario("preparing-p2p", "首次 P2P 连接", "已经准入,正在建立直连;等待首个有效画面。", [
+ ...ready, { type: "route", revision: 1, phase: "prepare", kind: "p2p" },
+ ]),
+ scenario("preparing-sfu", "首次 SFU 连接", "正在建立服务器媒体线路;与直连使用同一播放证明。", [
+ ...ready, { type: "route", revision: 1, phase: "prepare", kind: "sfu" },
+ ]),
+ scenario("waiting-sfu", "等待 SFU 线路", "服务端分配尚未完成;显示等待,不显示断线。", [
+ ...ready, { type: "route-status", revision: 1, state: "waiting" },
+ ]),
+ scenario("allocating", "正在分配线路", "房主在线,但还没有确定的媒体上游。", ready),
+ scenario("receiving", "已连接,等待首帧", "连接就绪还不够;解码并呈现首帧以后才进入观看。", receiving),
+ scenario("needs-play", "需要点击播放", "浏览器阻止了自动播放;画面上的按钮是真正可操作的。", [
+ ...receiving, { type: "autoplay-blocked", generation: 1, revision: 1 },
+ ]),
+ scenario("paused", "房主暂停", "主动暂停与连接失败分开;保留最后画面。", [
+ ...playing, { type: "host", host: "paused" },
+ ]),
+ scenario("recovering", "媒体恢复,保留最后画面", "当前帧证明失效,但有最后画面可保留;真实新帧才能清掉恢复状态。", [
+ ...playing,
+ { type: "frame-proof-reset", generation: 1, revision: 1 },
+ { type: "connection", revision: 1, connection: "reconnecting" },
+ ]),
+ scenario("route-failed", "媒体线路已失败", "权威线路失败;最后画面只是留存,不冒充正在播放。", [
+ ...playing, { type: "route-status", revision: 1, state: "failed" },
+ ]),
+ scenario("playback-failed", "浏览器播放失败", "连接存在,但播放器无法呈现画面。", [
+ ...receiving, { type: "playback-failed", generation: 1, revision: 1 },
+ ]),
+ scenario("waiting-host", "等待房主开始分享", "房间存在,当前没有共享源。", [{ type: "access", access: "ready" }]),
+ scenario("host-offline", "房主离线,没有画面", "没有当前或留存画面,说明房主离线。", [
+ ...ready, { type: "host", host: "offline" },
+ ]),
+ scenario("stopped", "分享已经停止", "正常结束,不伪装为正在恢复或播放失败。", [...playing, { type: "sharing-stopped" }]),
+ ...denied.map(([failure, name]) => scenario(failure.toLowerCase(), name,
+ "服务端准入或会话终止事实优先;旧画面和旧质量样本不能重新覆盖这个状态。",
+ [{ type: "access", access: "denied", failure }])),
+];
+
+export const HOST_STATUS_SCENARIOS: readonly {
+ name: string;
+ facts: Parameters<typeof deriveHostStatus>[0];
+}[] = [
+ { name: "待机", facts: { phase: "idle", paused: false, signal: "connected", roomReady: false } },
+ { name: "房间已就绪", facts: { phase: "idle", paused: false, signal: "connected", roomReady: true } },
+ { name: "正在启动", facts: { phase: "starting", paused: false, signal: "connected", roomReady: true } },
+ { name: "正在分享", facts: { phase: "live", paused: false, signal: "connected", roomReady: true } },
+ { name: "主动暂停", facts: { phase: "live", paused: true, signal: "connected", roomReady: true } },
+ { name: "分享结束", facts: { phase: "ended", paused: false, signal: "connected", roomReady: true } },
+ { name: "启动失败", facts: { phase: "error", paused: false, signal: "connected", roomReady: true } },
+ { name: "分享中,信令恢复", facts: { phase: "live", paused: false, signal: "reconnecting", roomReady: true } },
+];
diff --git a/src/client/pages/status-preview.css b/src/client/pages/status-preview.css
new file mode 100644
index 00000000..1e127a2d
--- /dev/null
+++ b/src/client/pages/status-preview.css
@@ -0,0 +1,84 @@
+.sp-page { --muted: color-mix(in srgb, var(--ink) 65%, var(--wall)); }
+.sp-main { max-width: 1190px; margin: 0 auto; padding: 32px 24px 64px; }
+.sp-heading { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 28px; }
+.sp-heading h1 { margin: 6px 0 12px; font-size: clamp(1.5rem, 4vw, 2.2rem); letter-spacing: -.04em; }
+.sp-heading p, .sp-catalog header p { margin: 0; color: var(--muted); line-height: 1.65; }
+.sp-kicker { font-size: .72rem; letter-spacing: .08em; font-weight: 800; color: var(--muted); }
+.sp-motion { display: flex; gap: 7px; align-items: center; flex-shrink: 0; font-size: .8rem; }
+.sp-motion input { accent-color: var(--action); }
+.sp-workbench { display: grid; grid-template-columns: 230px minmax(0, 1fr); align-items: start; gap: 24px; }
+.sp-mobile-scenario { display: none; }
+.sp-scenarios { max-height: 634px; overflow-y: auto; padding: 5px; scrollbar-width: thin; border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); border-radius: 14px; }
+.sp-scenarios button { display: flex; align-items: center; justify-content: space-between; width: 100%; min-height: 39px; text-align: left; gap: 8px; border: 0; border-radius: 8px; background: none; color: var(--muted); font: inherit; font-size: .8rem; padding: 10px; cursor: pointer; }
+.sp-scenarios button:hover { background: color-mix(in srgb, var(--action) 9%, transparent); color: var(--ink); }
+.sp-scenarios button[aria-pressed="true"] { background: color-mix(in srgb, var(--action) 15%, transparent); color: var(--action); font-weight: 800; }
+.sp-scenarios button svg { flex-shrink: 0; }
+.sp-stage-panel { min-width: 0; }
+.sp-browser-title { display: flex; align-items: center; gap: 9px; padding: 10px 16px; border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); border-radius: 12px 12px 0 0; background: var(--paper); font-size: .78rem; }
+.sp-browser-title > span:first-of-type { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.sp-stage-toolbar { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; padding: 13px 3px; }
+.sp-connection { margin-left: auto; }
+.sp-room-id { letter-spacing: .22em; font-size: .85rem; font-weight: 800; }
+.sp-video { position: absolute; inset: 0; overflow: hidden; background: #172c3b; }
+.sp-video.is-retained { filter: saturate(.35); }
+.sp-moon { position: absolute; right: 13%; top: 14%; width: 38px; height: 38px; border-radius: 50%; background: #f2e9c9; box-shadow: 0 0 0 12px #f2e9c909; }
+.sp-hill { position: absolute; width: 100%; height: 90%; top: 45%; left: -10%; border-radius: 50%; background: #29475b; transform: rotate(-15deg); }
+.sp-platform { position: absolute; bottom: 19%; left: 17%; width: 63%; height: 13%; border-radius: 10px 10px 0 0; background: #c38b62; border-top: 7px solid #8fb69b; }
+.sp-player { position: absolute; bottom: 32%; left: 38%; }
+.sp-score { position: absolute; left: 6%; top: 10%; color: #f2e9c9; font-weight: 800; letter-spacing: .15em; }
+.sp-stage-panel .lr-tv { width: 100%; }
+.sp-stage-panel .lr-tv-screen { aspect-ratio: 16 / 9; }
+.sp-couch-preview { margin-top: 18px; }
+.sp-couch-view { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 8px; margin-bottom: 18px; font-size: .74rem; }
+.sp-couch-view .lr-btn { min-height: 32px; height: auto; padding: 5px 10px; font-size: .73rem; }
+.sp-couch-view .lr-btn[aria-pressed="true"] { border-color: var(--action); color: var(--action); }
+.sp-caption { color: var(--muted); font-size: .74rem; line-height: 1.6; }
+.sp-stage-panel > .sp-caption { text-align: center; }
+.sp-status { display: inline-flex; align-items: center; gap: 7px; padding: 5px 0; font-size: .8rem; }
+.sp-explanation { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; padding: 24px 0; border-top: 1px solid color-mix(in srgb, var(--ink) 16%, transparent); margin-top: 25px; }
+.sp-explanation h2, .sp-catalog h2 { margin: 0 0 9px; font-size: 1.1rem; }
+.sp-explanation p { margin: 5px 0; line-height: 1.6; font-size: .83rem; }
+.sp-quality-controls { display: flex; flex-wrap: wrap; align-content: start; align-items: center; gap: 8px; }
+.sp-quality-controls p { flex-basis: 100%; }
+.sp-quality-controls .lr-btn { min-height: 36px; height: auto; padding: 7px 11px; font-size: .75rem; }
+.sp-quality-controls .lr-btn[aria-pressed="true"] { border-color: var(--action); color: var(--action); }
+.sp-surfaces { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
+.sp-surfaces article, .sp-catalog-grid article { border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); background: var(--paper); border-radius: 14px; padding: 17px; }
+.sp-surfaces h3 { margin: 8px 0 10px; font-size: .94rem; }
+.sp-surfaces .sp-kicker, .sp-surfaces .sp-caption { margin: 0; }
+.sp-catalog { margin-top: 36px; }
+.sp-catalog header { margin-bottom: 18px; }
+.sp-host-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(215px, 1fr)); gap: 12px; }
+.sp-host-grid article { border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); border-radius: 14px; padding: 17px; }
+.sp-host-grid h3 { margin: 0 0 10px; font-size: .9rem; }
+.sp-host-grid article > div { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: .73rem; }
+.sp-host-title { font-size: .7rem; color: var(--muted); min-height: 2em; }
+.sp-catalog-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
+.sp-catalog-grid article { display: flex; flex-direction: column; align-items: center; gap: 12px; }
+.sp-catalog-grid article > span { font-size: .8rem; text-align: center; }
+.sp-catalog-grid code { font-size: .69rem; color: var(--muted); }
+.sp-catalog-grid .sp-status { font-size: .7rem; }
+.sp-footnote { padding-top: 24px; margin-top: 28px; border-top: 1px solid color-mix(in srgb, var(--ink) 16%, transparent); font-size: .75rem; color: var(--muted); line-height: 1.7; }
+.sp-footnote a { color: var(--action); }
+.sp-reduced-motion *, .sp-reduced-motion *::before, .sp-reduced-motion *::after {
+ animation-duration: .01ms !important;
+ animation-delay: 0s !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: .01ms !important;
+}
+@media (max-width: 800px) {
+ .sp-main { padding: 22px 16px 48px; }
+ .sp-heading { align-items: start; flex-direction: column; gap: 14px; }
+ .sp-workbench { grid-template-columns: 1fr; gap: 15px; }
+ .sp-scenarios { display: none; }
+ .sp-mobile-scenario { display: flex; gap: 8px; align-items: center; font-size: .8rem; }
+ .sp-mobile-scenario select { min-width: 0; flex: 1; padding: 10px 8px; border: 1px solid color-mix(in srgb, var(--ink) 25%, transparent); border-radius: 10px; background: var(--paper); color: var(--ink); font: inherit; }
+ .sp-surfaces { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .sp-explanation { grid-template-columns: 1fr; gap: 14px; }
+}
+@media (max-width: 400px) {
+ .sp-stage-toolbar { gap: 8px; }
+ .sp-stage-toolbar .lr-leds-label { max-width: 170px; }
+ .sp-surfaces article { padding: 13px; }
+ .sp-catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+}
diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.ts
index 9051fcce..93c3fac2 100644
--- a/src/client/sfu/publisher.ts
+++ b/src/client/sfu/publisher.ts
@@ -1,5 +1,5 @@
import type { SfuMedia, SfuSignalMessage } from "../../shared/protocol";
-import { say } from "../ui/copy";
+import type { MediaFailure } from "../ui/media-failure";
import { debugRtcFailure, debugRtcStats, debugTrack } from "../lib/debug-webrtc";
import {
audioSenderParameterWarning,
@@ -69,8 +69,8 @@ export class SfuPublisher {
private failureStage: SfuPublisherFailureStage | null = null;
private senderParameters: VideoSenderParameterReadback | null = null;
private audioSenderParameters: AudioSenderParameterReadback | null = null;
- private videoWarning: string | null = null;
- private audioWarning: string | null = null;
+ private videoWarning: MediaFailure | null = null;
+ private audioWarning: MediaFailure | null = null;
private stats = createStatsAccumulator();
private nativeStats = createNativeSenderQualityAccumulator();
private statsInFlight: typeof this.stats | null = null;
@@ -256,7 +256,7 @@ export class SfuPublisher {
await videoSender.replaceTrack(previousVideo);
await audioSender.replaceTrack(previousAudio);
await this.configure(profile);
- this.videoWarning = say("host.fail.sfuSwitch");
+ this.videoWarning = { key: "host.fail.sfuSwitch" };
return false;
} catch {
this.fail("source");
@@ -298,7 +298,7 @@ export class SfuPublisher {
try {
if (videoChanged) await applyVideoCaptureProfile(video, previous);
await this.configure(previous, configureVideo);
- this.videoWarning = say("host.fail.sfuParams");
+ this.videoWarning = { key: "host.fail.sfuParams" };
return false;
} catch {
this.fail("sender-config");
@@ -308,10 +308,11 @@ export class SfuPublisher {
});
}
- getQualityWarning(): string | null {
- return (
- [this.videoWarning, this.audioWarning].filter(Boolean).join("; ") || null
+ getQualityWarning(): MediaFailure[] | null {
+ const warnings = [this.videoWarning, this.audioWarning].filter(
+ (warning): warning is MediaFailure => warning !== null,
);
+ return warnings.length > 0 ? warnings : null;
}
getFailureStage(): SfuPublisherFailureStage | null {
return this.failureStage;
@@ -483,7 +484,7 @@ export class SfuPublisher {
this.audioWarning = audioSenderParameterWarning(audio);
return true;
} catch {
- this.audioWarning = say("host.fail.sfuAudioParams");
+ this.audioWarning = { key: "host.fail.sfuAudioParams" };
return false;
}
}
diff --git a/src/client/styles.css b/src/client/styles.css
index 5e78e680..e2371795 100644
--- a/src/client/styles.css
+++ b/src/client/styles.css
@@ -1,9 +1,12 @@
+@import "./components/living/pawn.css";
+@import "./components/living/brand-mark.css";
+
/* Piik living-room UI — the production design system.
The stage is a TV on the wall, viewers are pawns on the couch, connection
- state is what the TV shows and what the LEDs say. Copy lives in tooltips
+ state is what the TV shows and what the LEDs say. Control copy lives in tooltips
and aria in visual mode; text modes add visible captions.
- Motion serves state changes and control feedback only, and collapses
- entirely under prefers-reduced-motion. */
+ Status and control motion stays distinct from quiet participant gestures;
+ all respect prefers-reduced-motion. */
:root {
color-scheme: light;
@@ -11,16 +14,18 @@
--wall-2: #dcebe4;
--ink: #22303e;
--paper: #ffffff;
- --couch: #e4572e;
- --couch-dark: #c8492b;
+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));
+ /* Fixed warm upholstery; shade changes define the cushions and arms. */
+ --couch: #e9ad63;
+ --couch-dark: #cd8845;
--you: #2fa66a;
--pawn-1: #3b7dd8;
- --pawn-2: #efb23f;
+ --pawn-2: #559bb7;
--pawn-3: #8e6fd8;
--pawn-4: #2fa8a0;
--pawn-5: #e2698f;
- --pawn-6: #7d9c3f;
- --pawn-7: #e08a3c;
+ --pawn-6: #4e9c74;
+ --pawn-7: #a978bd;
--pawn-8: #5f7dd8;
--action: #2f6fed;
--action-deep: #2058c9;
@@ -35,6 +40,9 @@
--stage: #101a2c;
--frame: #22303e;
--radius: 16px;
+ --control-radius: 18px;
+ --control-edge: color-mix(in srgb, var(--ink) 62%, var(--paper));
+ --control-shadow: 0 3px 0 color-mix(in srgb, var(--ink) 13%, transparent);
--spring: cubic-bezier(.3, 1.45, .45, 1);
--font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", "PingFang SC",
"Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
@@ -75,7 +83,7 @@ body {
}
button, input, select { font: inherit; color: inherit; }
-button { cursor: pointer; }
+button { cursor: pointer; touch-action: manipulation; }
button:disabled { cursor: not-allowed; opacity: 0.4; }
h1, h2, h3, p, dl, dd, dt { margin: 0; }
ul { margin: 0; padding: 0; list-style: none; }
@@ -118,153 +126,6 @@ ul { margin: 0; padding: 0; list-style: none; }
.lr-brand:hover { background: var(--wall-2); }
.lr-brand:active { transform: scale(.92); }
-.lr-brand-mark {
- display: block;
- flex: 0 0 auto;
- overflow: visible;
-}
-.lr-brand-loader {
- display: grid;
- width: 88px;
- height: 88px;
- place-items: center;
- color: currentColor;
-}
-.lr-brand-eye-open,
-.lr-brand-sparkles { opacity: 0; }
-.lr-brand-sparkles > * { opacity: 0; }
-
-.lr-brand-mark.is-animated,
-.lr-brand-mark.is-once {
- transform-box: fill-box;
- transform-origin: center;
-}
-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) {
- animation: lr-brand-bob 1.6s cubic-bezier(.3, .8, .35, 1) 1 both;
-}
-.lr-brand-mark.is-animated.is-loop-active {
- animation: lr-brand-bob-loop 3.6s cubic-bezier(.3, .8, .35, 1) infinite;
-}
-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell > * {
- stroke-dasharray: 1;
- stroke-dashoffset: 1;
- animation: lr-brand-draw cubic-bezier(.45, .05, .35, 1) forwards;
-}
-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-frame { animation-duration: 380ms; }
-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-antenna {
- animation-duration: 260ms;
- animation-delay: 260ms;
-}
-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-feet {
- animation-duration: 220ms;
- animation-delay: 360ms;
-}
-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-face {
- transform-box: fill-box;
- transform-origin: center;
- animation: lr-brand-face-in 180ms ease-out 500ms both;
-}
-.lr-brand-mark.is-animated.is-loop-active .lr-brand-eye-open {
- transform-box: fill-box;
- transform-origin: center;
- animation: lr-brand-eye-open-loop 3.6s ease-in-out infinite;
-}
-.lr-brand-mark.is-animated.is-loop-active .lr-brand-eye-wink {
- animation: lr-brand-eye-wink-loop 3.6s ease-in-out infinite;
-}
-.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles { opacity: 1; }
-.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles > * {
- transform-box: fill-box;
- transform-origin: center;
- animation: lr-brand-sparkle-loop 3.6s cubic-bezier(.3, 1.45, .45, 1) infinite both;
-}
-.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles > :nth-child(2) {
- animation-name: lr-brand-sparkle-alt-loop;
- animation-delay: 90ms;
-}
-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-open {
- transform-box: fill-box;
- transform-origin: center;
- animation: lr-brand-eye-open 1.6s ease-in-out 1 both;
-}
-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-wink {
- animation: lr-brand-eye-wink 1.6s ease-in-out 1 both;
-}
-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles { opacity: 1; }
-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > * {
- transform-box: fill-box;
- transform-origin: center;
- animation: lr-brand-sparkle 1.6s cubic-bezier(.3, 1.45, .45, 1) 1 both;
-}
-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > :nth-child(2) {
- animation-name: lr-brand-sparkle-alt;
- animation-delay: 45ms;
-}
-@keyframes lr-brand-draw { to { stroke-dashoffset: 0; } }
-@keyframes lr-brand-bob {
- 0%, 20%, 42%, 100% { transform: translateY(0) rotate(0); }
- 26% { transform: translateY(-.8px) rotate(-2deg); }
- 32% { transform: translateY(.8px) rotate(1.5deg); }
-}
-@keyframes lr-brand-bob-loop {
- 0%, 20%, 42%, 100% { transform: translateY(0) rotate(0); }
- 26% { transform: translateY(-.8px) rotate(-2deg); }
- 32% { transform: translateY(.8px) rotate(1.5deg); }
-}
-@keyframes lr-brand-face-in {
- from { opacity: 0; transform: scale(.35); }
- to { opacity: 1; transform: scale(1); }
-}
-@keyframes lr-brand-eye-open {
- 0%, 34% { opacity: 1; transform: scale(1); }
- 38%, 100% { opacity: 0; transform: scaleY(.15); }
-}
-@keyframes lr-brand-eye-wink {
- 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }
- 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }
- 44%, 100% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }
-}
-@keyframes lr-brand-eye-open-loop {
- 0%, 34%, 84%, 100% { opacity: 1; transform: scale(1); }
- 38%, 76% { opacity: 0; transform: scaleY(.15); }
-}
-@keyframes lr-brand-eye-wink-loop {
- 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }
- 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }
- 44%, 76% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }
- 84%, 100% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }
-}
-@keyframes lr-brand-sparkle {
- 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }
- 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }
- 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }
- 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }
- 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }
-}
-@keyframes lr-brand-sparkle-alt {
- 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }
- 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }
- 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }
- 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }
- 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }
-}
-@keyframes lr-brand-sparkle-loop {
- 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }
- 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }
- 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }
- 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }
- 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }
-}
-@keyframes lr-brand-sparkle-alt-loop {
- 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }
- 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }
- 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }
- 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }
- 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }
-}
-.lr-brand-sparkles { stroke: #d08a22; }
-html[data-theme="dark"] .lr-brand-sparkles { stroke: #f4c14d; }
-
.lr-top-right { display: inline-flex; gap: 10px; align-items: center; }
/* LED state strip */
@@ -297,14 +158,10 @@ html[data-theme="dark"] .lr-brand-sparkles { stroke: #f4c14d; }
/* language + theme controls */
.lr-lang {
- display: inline-flex;
- gap: 4px;
- padding: 4px;
border: 2.5px solid var(--ink);
- border-radius: 999px;
- background: var(--paper);
}
.lr-lang button {
+ position: relative;
display: inline-grid;
min-width: 38px;
height: 34px;
@@ -316,12 +173,13 @@ html[data-theme="dark"] .lr-brand-sparkles { stroke: #f4c14d; }
color: var(--ink);
font-size: 12px;
font-weight: 700;
- opacity: .55;
- transition: opacity 120ms ease, transform 140ms var(--spring);
+ opacity: .68;
+ transition: opacity 120ms ease, color 140ms ease, background-color 140ms ease, transform 180ms var(--spring);
}
-.lr-lang button:hover:not(.is-selected) { opacity: .85; }
+.lr-lang button:is(:hover, :focus-visible) { opacity: 1; transform: translateY(-1px); }
+.lr-lang button:is(:hover, :focus-visible):not(.is-selected) { background: var(--wall-2); }
.lr-lang button:active { transform: scale(.9); }
-.lr-lang button.is-selected { background: var(--ink); color: var(--paper); opacity: 1; }
+.lr-lang button.is-selected { color: var(--paper); opacity: 1; }
/* ---------- room layout ---------- */
@@ -369,21 +227,8 @@ body.lr-theater-open { overflow: hidden; }
border-radius: 0;
}
.lr-room.is-theater .lr-tv-chin,
-.lr-room.is-theater .lr-shelf,
.lr-room.is-theater .lr-couch,
.lr-room.is-theater .lr-deck { display: none; }
-.lr-theater-exit {
- position: absolute;
- z-index: 3;
- top: max(14px, env(safe-area-inset-top));
- right: max(14px, env(safe-area-inset-right));
-}
-.lr-theater-exit .lr-btn {
- border-color: rgba(223, 232, 242, .82);
- background: rgba(10, 16, 28, .72);
- color: #fff;
- backdrop-filter: blur(8px);
-}
/* ---------- the TV ---------- */
@@ -413,16 +258,6 @@ body.lr-theater-open { overflow: hidden; }
justify-content: center;
height: 26px;
}
-.lr-tv-chin i {
- width: 8px; height: 8px;
- border-radius: 50%;
- background: #57697f;
- transition: background 300ms ease;
-}
-.lr-tv-chin i.is-on { background: var(--live); }
-.lr-tv-chin i.is-warn { background: var(--warn); animation: lr-blink 1.1s infinite; }
-.lr-tv-chin i.is-bad { background: var(--danger); }
-.lr-tv-chin i.is-busy { background: var(--action); animation: lr-blink .8s infinite; }
@keyframes lr-crt {
0% { filter: brightness(3); transform: scaleY(.012); }
@@ -430,15 +265,6 @@ body.lr-theater-open { overflow: hidden; }
100% { filter: brightness(1); transform: scaleY(1); }
}
-.lr-shelf {
- width: min(640px, 84%);
- height: 10px;
- margin: 14px auto 0;
- border: 3px solid var(--ink);
- border-radius: 6px;
- background: var(--paper);
-}
-
/* TV overlays */
.lr-tv-overlay {
position: absolute;
@@ -467,12 +293,14 @@ body.lr-theater-open { overflow: hidden; }
.lr-tooltip-preview { max-width: 1440px; }
.lr-tooltip-preview-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin: 8px 0 20px; }
.lr-tooltip-preview-head h1 { margin: 0; font-size: 1.1rem; }
-.lr-tooltip-preview-head p { margin: 0; color: var(--muted); }
-.lr-tooltip-preview-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(330px, 1fr)); gap: 18px; }
-.lr-tooltip-preview-card { min-width: 0; padding: 10px; border: 1px solid var(--line); border-radius: 8px; background: color-mix(in srgb, var(--panel) 88%, transparent); }
+.lr-tooltip-preview-head p { margin: 0; opacity: .7; }
+.lr-tooltip-preview h2 { margin: 24px 0 12px; font-size: 1rem; }
+.lr-tooltip-preview-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 330px), 1fr)); gap: 18px; }
+.lr-tooltip-preview-card { min-width: 0; padding: 10px; border: 1px solid var(--wall-2); border-radius: 8px; background: var(--paper); }
.lr-tooltip-preview-card > header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; }
-.lr-tooltip-preview-card code { color: var(--muted); font-size: .75rem; overflow-wrap: anywhere; }
-.lr-tooltip-preview-trigger { width: 30px; height: 30px; padding: 0; border: 1px solid var(--line); border-radius: 999px; background: transparent; color: var(--accent); cursor: help; }
+.lr-tooltip-preview-card code, .lr-tooltip-preview-card small { font-size: .75rem; overflow-wrap: anywhere; opacity: .7; }
+.lr-tooltip-preview-actions { display: flex; gap: 4px; }
+.lr-tooltip-preview-trigger { width: 36px; height: 36px; padding: 0; border: 1px solid var(--wall-2); border-radius: 999px; background: transparent; color: var(--ink); cursor: help; }
.lr-tooltip-preview-art { min-height: 106px; display: grid; place-items: center; overflow: hidden; }
.lr-tooltip-preview-art svg { max-width: 100%; height: auto; }
.lr-tv-overlay.has-comic { gap: 8px; padding: 10px; }
@@ -519,9 +347,6 @@ body.lr-theater-open { overflow: hidden; }
text-shadow: 0 1px 8px rgba(0, 0, 0, .65);
}
-.lr-entry-text { display: grid; gap: 6px; margin-bottom: 4px; }
-.lr-entry-text h1 { font-size: clamp(19px, 2.6vw, 24px); font-weight: 800; color: #f2efe7; letter-spacing: -0.01em; text-wrap: balance; }
-.lr-entry-text p { max-width: 400px; margin: 0 auto; color: #9aa0b0; font-size: 13.5px; text-wrap: balance; }
.lr-entry-actions { display: flex; gap: 18px; flex-wrap: wrap; justify-content: center; }
.lr-entry-action { display: grid; justify-items: center; gap: 8px; align-content: start; }
@@ -591,6 +416,7 @@ body.lr-theater-open { overflow: hidden; }
transition: transform 140ms var(--spring), background 120ms ease;
}
.lr-source-picker-refresh { margin-left: auto; }
+.lr-source-picker-head > .lr-comic-tip-wrap:has(> .lr-source-picker-refresh) { margin-left: auto; }
.lr-source-picker-refresh:hover,
.lr-source-picker-close:hover { background: rgba(255, 255, 255, .1); }
.lr-source-picker-refresh:active,
@@ -686,7 +512,6 @@ body.lr-theater-open { overflow: hidden; }
overflow-wrap: anywhere;
line-height: 1.35;
}
-.lr-source-option-copy > span { flex: 0 0 auto; }
.lr-source-option-icon {
width: 38px;
height: 38px;
@@ -797,28 +622,23 @@ body.lr-theater-open { overflow: hidden; }
.lr-couch {
position: relative;
width: min(720px, 96%);
- margin: 34px auto 0;
+ margin: 20px auto 0;
}
-.lr-couch > svg { display: block; width: 100%; height: auto; }
-.lr-pawns-window {
+.lr-couch-seating { position: relative; max-width: 100%; margin: auto; }
+.lr-couch-benches {
position: absolute;
- inset: 0 8% auto;
- top: -35px;
- overflow-x: auto;
- overflow-y: hidden;
- padding: 20px 12px 10px;
- scrollbar-color: var(--route-sfu) transparent;
- scrollbar-width: thin;
+ inset: 0;
+ pointer-events: none;
}
+.lr-couch-benches > svg { display: block; width: 100%; height: 108px; }
.lr-pawns {
- display: flex;
- width: max-content;
- min-width: 100%;
- flex-wrap: nowrap;
- justify-content: center;
+ position: relative;
+ display: grid;
+ grid-auto-rows: 108px;
+ margin: 0 32px;
align-items: start;
- gap: 2px 10px;
}
+.lr-seat { display: grid; min-width: 0; justify-items: center; padding-top: 24px; }
.lr-pawn {
position: relative;
display: grid;
@@ -828,11 +648,10 @@ body.lr-theater-open { overflow: hidden; }
padding: 0;
border: 0;
background: transparent;
- animation: lr-hop .55s var(--spring) backwards;
transition: transform 150ms var(--spring);
}
-.lr-pawn:hover:not(.is-static) { transform: translateY(-5px) rotate(-4deg); }
-.lr-pawn svg { width: 40px; height: 48px; display: block; }
+.lr-pawn:is(:hover, :focus-visible):not(.is-static) { transform: translateY(-3px); }
+.lr-pawn svg { width: 48px; height: 56px; display: block; }
.lr-pawn-led {
position: absolute;
top: 2px;
@@ -841,9 +660,14 @@ body.lr-theater-open { overflow: hidden; }
border: 2px solid var(--wall);
border-radius: 50%;
background: var(--live);
- transition: background 200ms ease;
}
-.lr-pawn-led.is-wait { background: var(--warn); animation: lr-blink 1.2s infinite; }
+.lr-pawn-led[data-tone="busy"] { background: var(--action); }
+.lr-pawn-led[data-tone="warn"] { background: var(--warn); }
+.lr-pawn-led[data-tone="bad"] { background: var(--danger); }
+.lr-pawn-led[data-tone="off"] { background: var(--ink-soft, #8ea3b8); }
+.lr-pawn-led[data-pulse] { animation: lr-blink 1.6s ease-in-out infinite; }
+.lr-pawn.is-waiting > svg { opacity: .65; animation: lr-pawn-breathe 1.6s ease-in-out infinite; }
+@keyframes lr-pawn-breathe { 50% { opacity: .35; } }
.lr-pawn.is-you::after {
content: "";
position: absolute;
@@ -854,7 +678,6 @@ body.lr-theater-open { overflow: hidden; }
transform: translateX(-50%);
}
.lr-pawn.is-you { z-index: 1; }
-.lr-pawn.is-host { margin-right: 6px; }
.lr-pawn.is-host .lr-pawn-name { font-weight: 850; }
.lr-pawn.is-static { cursor: default; }
.lr-pawn.is-selected { transform: translateY(-5px); }
@@ -865,34 +688,27 @@ body.lr-theater-open { overflow: hidden; }
border: 2.5px solid var(--action);
border-radius: 13px;
}
-.lr-pawns.is-crowded { gap: 6px; }
-.lr-pawns.is-crowded .lr-pawn { min-width: 33px; }
-.lr-pawns.is-crowded .lr-pawn svg { width: 29px; height: 35px; }
-.lr-pawns.is-crowded .lr-pawn-led { width: 8px; height: 8px; }
.lr-pawn-name {
- max-width: 112px;
+ max-width: 70px;
margin-top: -4px;
padding: 1px 6px;
border-radius: 7px;
background: var(--paper);
color: var(--ink);
- font-size: 10px;
+ font-size: 11px;
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
box-shadow: 0 1px 0 rgba(0, 0, 0, .12);
}
-.lr-pawns.is-crowded .lr-pawn-name { max-width: 80px; }
+.lr-couch-footer { display: flex; align-items: center; justify-content: center; gap: 12px; min-height: 32px; color: var(--muted); }
.lr-couch-count {
- position: absolute;
- right: 4%;
- bottom: 8px;
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 8px;
- border: 2px solid var(--ink);
+ border: 1px solid var(--wall-2);
border-radius: 999px;
background: var(--paper);
color: var(--ink);
@@ -903,17 +719,12 @@ body.lr-theater-open { overflow: hidden; }
.lr-couch-count b { font-size: inherit; }
.lr-couch-empty {
position: absolute;
- inset: -8px 0 auto;
+ inset: 45px 0 auto;
display: grid;
place-items: center;
color: #6f8579;
opacity: .85;
}
-@keyframes lr-hop {
- 0% { transform: translateY(-16px) scale(.7); opacity: 0; }
- 60% { transform: translateY(3px) scale(1.04); opacity: 1; }
- 100% { transform: translateY(0) scale(1); opacity: 1; }
-}
/* ---------- deck: control rows ---------- */
@@ -974,8 +785,6 @@ html[data-theme="dark"] .lr-viewer-host-slot svg { color: #9bb0c5; }
text-overflow: ellipsis;
white-space: nowrap;
}
-.lr-viewer-state-slot { flex: 0 1 auto; min-width: 0; }
-.lr-viewer-state-slot:empty { display: none; }
.lr-viewer-self-slot {
display: flex;
flex: 0 1 auto;
@@ -1011,10 +820,16 @@ html[data-theme="dark"] .lr-viewer-host-slot svg { color: #9bb0c5; }
background: var(--wall-2);
}
.lr-viewer-self-slot .lr-name-tag { flex: 0 1 auto; width: auto; }
+.lr-name-hint { min-width: 0; max-width: 100%; }
+.lr-comic-tip-wrap.lr-overview-row-hint { display: flex; width: 100%; }
+.lr-source-option-hint { min-width: 0; }
+.lr-source-option-hint > .lr-source-option { width: 100%; height: 100%; }
+.lr-invite-hint { width: 100%; min-width: 0; max-width: 340px; flex: 1 1 240px; }
+.lr-invite-hint > .lr-invite-url { width: 100%; }
.lr-spacer { flex: 1; }
.lr-divider { width: 2.5px; align-self: stretch; border-radius: 2px; background: var(--wall-2); }
.lr-row.is-sub .lr-divider { background: #c3d4cb; }
-.lr-field-cap { opacity: .55; font-size: 12px; font-weight: 600; }
+.lr-field-cap { opacity: .68; font-size: 12px; font-weight: 600; }
.lr-invite-url {
width: 100%;
min-width: 0;
@@ -1037,16 +852,6 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
/* Touch only: the compact mono URL would auto-zoom iOS on focus under 16px,
and the zoom never returns. Pointer devices keep the dense line. */
@media (pointer: coarse) { .lr-invite-url { font-size: 16px; } }
-.lr-status-text {
- min-width: 0;
- overflow: hidden;
- font-size: 13.5px;
- font-weight: 600;
- opacity: .78;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
/* LCD room code */
.lr-lcd {
display: inline-flex;
@@ -1088,19 +893,21 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
gap: 8px;
min-width: 52px; height: 52px;
padding: 0 14px;
- border: 2.5px solid var(--ink);
- border-radius: 15px;
+ border: 2px solid var(--control-edge);
+ border-radius: 999px;
background: var(--paper);
color: var(--ink);
white-space: nowrap;
- transition: transform 120ms var(--spring), background 120ms ease, box-shadow 160ms ease;
-}
-.lr-btn:hover:not(:disabled) { background: var(--wall-2); transform: translateY(-1px); }
-.lr-btn:active:not(:disabled) { transform: scale(.93); }
-.lr-btn.is-primary { border-color: var(--action); background: var(--action); color: #fff; }
-.lr-btn.is-primary:hover:not(:disabled) { background: var(--action-deep); box-shadow: 0 4px 14px rgba(47, 111, 237, .35); }
-.lr-btn.is-danger { border-color: var(--danger); color: var(--danger); }
-.lr-btn.is-danger:hover:not(:disabled) { background: rgba(214, 69, 65, .1); }
+ box-shadow: var(--control-shadow);
+ transition: transform 260ms var(--spring), background-color 140ms ease, border-color 140ms ease;
+}
+.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: translateY(-2px); }
+.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-primary):not(.is-on):not(.is-danger) { background: var(--wall-2); border-color: var(--ink); }
+.lr-btn:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.95); box-shadow: none; transition-duration: 80ms; }
+.lr-btn.is-primary { border-color: var(--action-deep); background: var(--action-deep); color: #fff; }
+.lr-btn.is-primary:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--action-deep) 88%, #000); }
+.lr-btn.is-danger { border-color: var(--danger); color: color-mix(in srgb, var(--danger) 70%, var(--ink)); }
+.lr-btn.is-danger:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--danger) 10%, var(--paper)); }
.lr-btn.is-on { border-color: var(--ink); background: var(--ink); color: var(--paper); }
.lr-btn .lr-cap { margin-left: 2px; font-size: 12.5px; font-weight: 600; }
@@ -1111,18 +918,19 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
align-items: center;
gap: 6px;
padding: 9px 14px;
- border: 2.5px solid var(--ink);
- border-radius: 10px;
+ border: 2px solid var(--control-edge);
+ border-radius: 999px;
background: var(--paper);
font-family: var(--mono);
font-size: 13px;
font-weight: 700;
letter-spacing: .1em;
- transition: transform 120ms var(--spring), background 120ms ease;
+ box-shadow: var(--control-shadow);
+ transition: transform 180ms var(--spring), background-color 140ms ease;
}
-.lr-chip:hover:not(:disabled) { background: var(--wall-2); }
-.lr-chip:active:not(:disabled) { transform: scale(.94); }
-.lr-chip.is-selected { background: var(--ink); color: var(--paper); animation: lr-pop .2s var(--spring); }
+.lr-chip:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-selected) { background: var(--wall-2); transform: translateY(-2px); }
+.lr-chip:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.97); box-shadow: none; }
+.lr-chip.is-selected { background: var(--ink); color: var(--paper); border-color: var(--ink); animation: lr-pop .2s var(--spring); }
.lr-chip .lr-cap { font-family: var(--font); letter-spacing: 0; }
.lr-chip small { margin-left: 5px; font-size: 10.5px; opacity: .6; }
.lr-chip .lr-audio-rate {
@@ -1141,31 +949,32 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
}
@keyframes lr-pop { 50% { transform: scale(1.06); } }
-/* policy segmented toggle with sliding thumb. inline-grid + 1fr auto columns
- makes every option exactly half the toggle (equal to the widest caption),
- so the 50%/translateX(100%) thumb lines up in every language — flex sizing
- let EN "Open"/"Private" run unequal and the thumb underlapped the selected
- button. */
-.lr-toggle {
+/* Segmented controls share a sliding thumb. Equal grid columns keep it aligned
+ across captions; the selected button remains the only selection state. */
+.lr-toggle, .lr-lang {
position: relative;
display: inline-grid;
grid-auto-flow: column;
grid-auto-columns: 1fr;
padding: 4px;
- border: 2.5px solid var(--ink);
- border-radius: 15px;
+ border-radius: 999px;
background: var(--paper);
}
-.lr-toggle::before {
+.lr-toggle { border: 2px solid var(--control-edge); }
+.lr-toggle::before, .lr-lang::before {
content: "";
position: absolute;
top: 4px; bottom: 4px; left: 4px;
- width: calc(50% - 4px);
- border-radius: 11px;
+ border-radius: 999px;
background: var(--ink);
transition: transform 260ms var(--spring);
+ pointer-events: none;
}
+.lr-toggle::before { width: calc(50% - 4px); }
+.lr-lang::before { width: calc((100% - 8px) / 3); }
.lr-toggle[data-selected="private"]::before { transform: translateX(100%); }
+.lr-lang:has(button:nth-child(2).is-selected)::before { transform: translateX(100%); }
+.lr-lang:has(button:nth-child(3).is-selected)::before { transform: translateX(200%); }
.lr-toggle button {
position: relative;
z-index: 1;
@@ -1176,7 +985,7 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
min-width: 44px; height: 44px;
padding: 0 10px;
border: 0;
- border-radius: 11px;
+ border-radius: 999px;
background: transparent;
/* 68% ink clears AA on both themes (light 4.89:1, dark 5.89:1) while the
selected option keeps its stronger contrast. */
@@ -1185,17 +994,16 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
}
.lr-toggle button.is-selected { color: var(--paper); }
.lr-toggle button:active { transform: scale(.94); }
-/* Vis mode hint-wraps each option button, so the wrap (not the button) is the
- grid item; it stretches to its track, and without centering the icon-only
- button would pin to the left of its half. */
-.lr-toggle .lr-comic-tip-wrap { justify-content: center; }
+/* The wrapper owns each half in both language modes. */
+.lr-toggle > .lr-comic-tip-wrap { flex: 1; justify-content: center; }
+.lr-toggle > .lr-comic-tip-wrap > button { width: 100%; }
-/* iOS-style switch */
+/* Sliding switch; its thumb stays inside the track at either end. */
.lr-switch {
position: relative;
display: inline-flex;
width: 58px; height: 34px;
- border: 2.5px solid var(--ink);
+ border: 2px solid var(--control-edge);
border-radius: 999px;
background: var(--paper);
flex: 0 0 auto;
@@ -1204,7 +1012,7 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
.lr-switch::after {
content: "";
position: absolute;
- top: 2.5px; left: 3px;
+ top: 3px; left: 3px;
width: 24px; height: 24px;
border-radius: 50%;
background: var(--ink);
@@ -1228,14 +1036,15 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
gap: 6px;
min-width: 76px;
padding: 12px 10px 9px;
- border: 2.5px solid var(--ink);
- border-radius: 14px;
+ border: 2px solid var(--control-edge);
+ border-radius: var(--control-radius);
background: var(--paper);
color: var(--ink);
- transition: transform 140ms var(--spring), background 120ms ease;
+ box-shadow: var(--control-shadow);
+ transition: transform 180ms var(--spring), background-color 140ms ease;
}
-.lr-tile:hover:not(:disabled):not(.is-selected) { background: var(--wall-2); transform: translateY(-2px); }
-.lr-tile:active:not(:disabled) { transform: scale(.95); }
+.lr-tile:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-selected) { background: var(--wall-2); transform: translateY(-2px); }
+.lr-tile:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.97); box-shadow: none; }
.lr-tile.is-selected { background: var(--ink); color: var(--paper); animation: lr-pop .2s var(--spring); }
.lr-tile small { font-family: var(--mono); font-size: 11px; letter-spacing: .02em; color: #5d7086; white-space: nowrap; }
.lr-tile.is-selected small { color: var(--paper); opacity: .75; }
@@ -1248,14 +1057,25 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
min-width: 0;
height: 48px;
padding: 0 12px;
- border: 2.5px solid var(--ink);
- border-radius: 13px;
+ border: 2px solid var(--control-edge);
+ border-radius: var(--control-radius);
background: var(--paper);
transition: border-color 140ms ease;
}
.lr-input:focus-within { border-color: var(--action); outline: 3px solid var(--action); outline-offset: 2px; }
.lr-input input { min-width: 0; flex: 1; height: 100%; border: 0; outline: 0; background: transparent; font: inherit; font-size: 16px; }
.lr-input input[type="password"]:not(:placeholder-shown) { letter-spacing: .25em; }
+.lr-welcome { width: 100%; min-width: 0; max-width: 100%; margin: 0; overflow: hidden; color: inherit; font-size: 15px; font-weight: 600; line-height: 1.7; text-align: center; white-space: nowrap; text-overflow: ellipsis; }
+.lr-welcome:not(.is-cipher)::before { content: "✦"; color: #d7982b; margin-right: 8px; }
+.lr-welcome-cipher { display: inline-flex; align-items: center; gap: 8px; vertical-align: middle; opacity: .72; white-space: nowrap; }
+.lr-welcome-cipher i { width: 3px; height: 3px; background: #d7982b; transform: rotate(45deg); }
+.lr-tv-overlay > .lr-welcome { position: absolute; top: clamp(20px, 3vw, 32px); left: 18px; right: 18px; width: auto; font-size: clamp(13px, 1.5vw, 16px); }
+.lr-tv-overlay:has(> .lr-join-panel) > .lr-welcome { display: none; }
+.lr-welcome-catalog { margin-block: 0 24px; }
+.lr-welcome-catalog summary { cursor: pointer; width: fit-content; padding-block: 12px; font-weight: 650; }
+.lr-welcome-catalog ol { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(280px, 100%), 1fr)); gap: 12px 32px; padding-inline-start: 28px; }
+.lr-welcome-catalog li > span:first-child { display: block; }
+.lr-welcome-catalog .lr-welcome-cipher { margin-top: 6px; }
.lr-input.lr-name-editor {
width: clamp(140px, 18vw, 200px);
height: 40px;
@@ -1276,14 +1096,6 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
font-weight: 700;
max-width: 100%;
}
-.lr-stage-notices {
- display: flex;
- width: min(960px, 100%);
- margin: 10px auto 0;
- flex-wrap: wrap;
- justify-content: center;
- gap: 8px;
-}
.lr-name-tag i { width: 9px; height: 9px; border-radius: 50%; background: var(--you); flex: 0 0 auto; }
.lr-name-tag span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -1372,12 +1184,9 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
min-width: 0;
max-width: 100%;
flex: 1 1 100%;
- overflow-x: auto;
+ overflow-x: hidden;
padding: 6px 2px;
box-sizing: border-box;
- overscroll-behavior-inline: contain;
- scrollbar-color: var(--route-sfu) transparent;
- scrollbar-width: thin;
}
.lr-route > svg { display: block; width: 100%; max-width: 880px; height: auto; margin: 0 auto; }
.lr-route:focus-visible { border-radius: 10px; }
@@ -1506,16 +1315,13 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
.lr-viewer-overview-pawn { position: relative; flex: 0 0 auto; }
.lr-viewer-overview-pawn svg { display: block; width: 24px; height: 29px; }
.lr-viewer-overview-pawn i {
- position: absolute;
top: 0;
+ left: auto;
right: -2px;
width: 7px;
height: 7px;
border: 1.5px solid var(--paper);
- border-radius: 50%;
- background: var(--live);
}
-.lr-viewer-overview-pawn i.is-wait { background: var(--warn); }
.lr-viewer-overview-route {
display: inline-flex;
align-items: center;
@@ -1567,14 +1373,7 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }
justify-items: center;
gap: 20px;
}
-.lr-client-launch-copy {
- display: grid;
- justify-items: center;
- gap: 6px;
- text-align: center;
-}
-.lr-client-launch-copy h1 { font-size: 24px; }
-.lr-client-launch-copy p { color: #607283; font-size: 13.5px; }
+.lr-client-launch-title { font-size: 24px; text-align: center; }
.lr-client-launch-status { color: var(--ink); font-size: 14px; font-weight: 650; }
.lr-client-update {
display: inline-flex;
@@ -1584,7 +1383,7 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }
padding: 6px 11px;
border: 1.5px solid var(--action);
border-radius: 8px;
- color: var(--action-deep);
+ color: var(--ink);
font-size: 12.5px;
font-weight: 700;
text-decoration: none;
@@ -1610,15 +1409,16 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }
align-content: center;
gap: 10px;
padding: 14px;
- border: 2.5px solid var(--ink);
- border-radius: 14px;
+ border: 2px solid var(--control-edge);
+ border-radius: var(--control-radius);
background: var(--paper);
color: var(--ink);
text-align: center;
+ box-shadow: var(--control-shadow);
transition: transform 160ms var(--spring), background 120ms ease, color 120ms ease;
}
-.lr-client-mode:hover:not(.is-selected) { background: var(--wall-2); transform: translateY(-2px); }
-.lr-client-mode:active { transform: scale(.97); }
+.lr-client-mode:is(:hover, :focus-visible):not(:disabled):not(.is-selected) { background: var(--wall-2); transform: translateY(-2px); }
+.lr-client-mode:active:not(:disabled) { transform: translateY(2px) scale(.97); box-shadow: none; }
.lr-client-mode.is-selected { background: var(--ink); color: var(--paper); }
.lr-client-mode > span {
display: grid;
@@ -1626,7 +1426,7 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }
gap: 3px;
}
.lr-client-mode strong { font-size: 14px; }
-.lr-client-mode small { font-size: 11px; opacity: .66; }
+.lr-client-mode small { font-size: 11px; opacity: .7; }
.lr-client-site { width: min(460px, 100%); }
.lr-client-access {
width: min(460px, 100%);
@@ -1754,14 +1554,13 @@ html[data-theme="dark"] .lr-join-go:disabled { background: #1a2634; color: #4860
/* ---------- dark theme refinements ---------- */
-html[data-theme="dark"] .lr-btn:hover:not(:disabled) { background: #2b3d4f; }
+html[data-theme="dark"] .lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-primary):not(.is-on):not(.is-danger) { background: #2b3d4f; }
html[data-theme="dark"] .lr-btn.is-on { background: var(--ink); color: #22303e; }
-html[data-theme="dark"] .lr-btn.is-danger:hover:not(:disabled) { background: #3d2626; }
-html[data-theme="dark"] .lr-chip:hover:not(:disabled),
-html[data-theme="dark"] .lr-tile:hover:not(:disabled):not(.is-selected) { background: #2b3d4f; }
+html[data-theme="dark"] .lr-btn.is-danger:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: #3d2626; }
+html[data-theme="dark"] .lr-chip:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-selected),
+html[data-theme="dark"] .lr-tile:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-selected) { background: #2b3d4f; }
html[data-theme="dark"] .lr-chip.is-selected,
html[data-theme="dark"] .lr-tile.is-selected { background: var(--ink); color: #22303e; }
-html[data-theme="dark"] .lr-tile.is-selected small { color: #4a5f78; }
html[data-theme="dark"] .lr-row.is-sub { background: #1a2634; }
html[data-theme="dark"] .lr-meter-cell { background: #1a2634; }
html[data-theme="dark"] .lr-meter-tag { color: #7d92a8; }
@@ -1789,10 +1588,6 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
grid-template-columns: 1fr;
justify-items: center;
}
- .lr-pawns-window { inset-inline: 4%; }
- .lr-pawns { gap: 2px 6px; }
- .lr-pawn { min-width: 36px; }
- .lr-pawn svg { width: 32px; height: 39px; }
.lr-route { padding-inline: 0; }
.lr-row { flex-direction: column; align-items: stretch; gap: 12px; padding: 14px; }
.lr-row > .lr-spacer,
@@ -1805,7 +1600,6 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
min-width: 0;
max-width: 180px;
}
- .lr-viewer-state-slot { flex: 0 1 auto; min-width: 0; }
.lr-viewer-self-slot { flex: 1 1 auto; gap: 8px; margin-left: 0; }
.lr-host-personal-controls {
width: 100%;
@@ -1846,9 +1640,9 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
.lr-group-name .lr-name-tag { flex: 1; }
.lr-viewer-self-slot .lr-name-tag { flex: 0 1 auto; }
.lr-toggle { flex: 1; }
+ .lr-invite-hint, .lr-invite-url { flex: 0 1 auto; max-width: none; min-height: 44px; }
.lr-door-body { padding: 12px; }
.lr-dial { width: 54px; height: 66px; font-size: 28px; }
- .lr-status-text { width: 100%; }
.lr-tv-screen.has-entry { aspect-ratio: auto; min-height: 292px; }
.lr-tv-screen:has(.lr-source-picker) { aspect-ratio: auto; min-height: 440px; }
.lr-tv-big { width: 72px; height: 72px; }
@@ -1862,6 +1656,16 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
.lr-header-controls .lr-btn .lr-cap { display: none; }
}
+.lr-stage-notices {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ width: min(960px, 100%);
+ margin: 10px auto 0;
+}
+.lr-stage-notices:empty { display: none; }
.lr-room.is-theater .lr-stage-notices {
position: absolute;
z-index: 3;
@@ -1871,13 +1675,16 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
width: min(92vw, 720px);
margin: 0;
transform: translateX(-50%);
+ pointer-events: none;
}
+.lr-room.is-theater .lr-stage-notices > * { pointer-events: auto; }
@media (max-width: 360px) {
.lr-top { gap: 6px; padding-inline: 10px; }
.lr-top-right { gap: 6px; }
.lr-leds { gap: 4px; padding: 6px; }
.lr-leds i { width: 8px; height: 8px; }
- .lr-lang { gap: 1px; padding: 2px; border-width: 2px; }
+ .lr-lang { padding: 2px; border-width: 2px; }
+ .lr-lang::before { top: 2px; bottom: 2px; left: 2px; width: calc((100% - 4px) / 3); }
.lr-lang button { min-width: 30px; height: 32px; padding-inline: 5px; }
.lr-header-controls .lr-btn {
min-width: 36px !important;
@@ -1903,27 +1710,28 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
}
}
-/* ---------- comic tooltip ---------- */
+/* ---------- shared text / comic tooltip ---------- */
/* Stateful hover/focus panel carrying a paper Comic above its trigger. The
trigger stays focusable; when it is natively disabled, the wrapper owns the
explanation focus instead. Enter is delayed ~120ms, exit is immediate. Under
prefers-reduced-motion the global block collapses the transition to instant
and the comic's own RM block pins its final frame. */
-/* Visibility is three-channel state owned by ComicTooltip: fine-pointer hover,
+/* Visibility is three-channel state owned by Tooltip: fine-pointer hover,
keyboard focus-visible, and Material-style touch long-press. */
.lr-comic-tip-wrap { position: relative; display: inline-flex; }
.lr-comic-tip-wrap.is-disabled-trigger > :disabled { pointer-events: none; }
.lr-comic-tip {
- position: absolute;
- bottom: calc(100% + 8px);
- left: 50%;
- transform: translateX(-50%) translateY(4px);
+ position: fixed;
+ inset: auto;
+ margin: 0;
+ overflow: visible;
+ transform: translateY(4px);
width: max-content;
max-width: 320px;
z-index: 30;
background: var(--paper);
- border: 2.5px solid var(--ink);
+ border: 2.5px solid var(--comic-tone, var(--ink));
border-radius: 14px;
padding: 10px;
box-shadow: 0 6px 18px rgb(16 26 44 / .18);
@@ -1932,39 +1740,52 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
transition: opacity .16s ease, transform .16s ease;
}
.lr-comic-tip * { animation-play-state: paused !important; }
-/* Caret lives on the wrapper (not the panel) so it always centers on the
- trigger button, whatever the panel alignment is. The diamond's center sits
- on the panel's edge; the half inside the panel hides behind its paper
- background (z 29 vs 30), leaving a clean point aimed at the trigger. */
-.lr-comic-tip-wrap::before {
+.lr-comic-tip.is-text {
+ padding: 10px 14px;
+ max-width: min(320px, calc(100vw - 16px));
+ color: var(--ink);
+ font: 600 14px/1.6 var(--font);
+ text-align: start;
+ white-space: normal;
+ overflow-wrap: anywhere;
+ text-wrap: pretty;
+}
+/* Keep the panel reachable across the small gap while reading it. */
+.lr-comic-tip::after {
content: "";
position: absolute;
- bottom: calc(100% + 3px);
- left: 50%;
+ inset: 100% 0 auto;
+ height: 10px;
+}
+.lr-comic-tip.is-below::after { inset: auto 0 100%; }
+.lr-comic-tip-wrap:is(.is-hover-open, .is-focus-open, .is-tip-open) > .lr-comic-tip {
+ pointer-events: auto;
+}
+/* The caret follows the trigger, including in a scrolled/clipped list. */
+.lr-comic-tip::before {
+ content: "";
+ position: absolute;
+ bottom: -7px;
+ left: var(--tooltip-caret);
width: 10px;
height: 10px;
margin-left: -5px;
background: var(--paper);
- border: 2.5px solid var(--ink);
- transform: rotate(45deg) scale(.6);
- z-index: 29;
- opacity: 0;
+ border: solid var(--comic-tone, var(--ink));
+ border-width: 0 2.5px 2.5px 0;
+ transform: rotate(45deg);
pointer-events: none;
- transition: opacity .16s ease, transform .16s ease;
}
-.lr-comic-tip-wrap:has(.lr-comic-tip.is-below)::before {
+.lr-comic-tip.is-below::before {
bottom: auto;
- top: calc(100% + 3px);
+ top: -7px;
+ border-width: 2.5px 0 0 2.5px;
}
/* channel 1: fine-pointer hover */
@media (hover: hover) and (pointer: fine) {
- .lr-comic-tip-wrap.is-hover-open .lr-comic-tip { opacity: 1; transform: translateX(-50%) translateY(0); transition-delay: .12s; }
+ .lr-comic-tip-wrap.is-hover-open .lr-comic-tip { opacity: 1; transform: translateY(0); transition-delay: .12s; }
.lr-comic-tip-wrap.is-hover-open .lr-comic-tip * { animation-play-state: running !important; }
- .lr-comic-tip-wrap.is-hover-open .lr-comic-tip.is-below { transform: translateX(-50%) translateY(0); }
- .lr-comic-tip-wrap.is-hover-open .lr-comic-tip.is-start,
- .lr-comic-tip-wrap.is-hover-open .lr-comic-tip.is-end { transform: translateX(0) translateY(0); }
- .lr-comic-tip-wrap.is-hover-open::before { opacity: 1; transform: rotate(45deg) scale(1); transition-delay: .12s; }
/* Panel mutex: keyboard focus (channel 2) can hold one wrap's panel open
while the pointer hovers a neighboring trigger, and two 320px panels at
@@ -1978,11 +1799,7 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
:is(.lr-row-group, .lr-pawn-detail, .lr-entry-actions):has(.lr-comic-tip-wrap.is-focus-open)
.lr-comic-tip-wrap:not(.is-focus-open).is-hover-open .lr-comic-tip {
opacity: 0;
- transition-delay: 0s;
- }
- :is(.lr-row-group, .lr-pawn-detail, .lr-entry-actions):has(.lr-comic-tip-wrap.is-focus-open)
- .lr-comic-tip-wrap:not(.is-focus-open).is-hover-open::before {
- opacity: 0;
+ pointer-events: none;
transition-delay: 0s;
}
}
@@ -1991,36 +1808,16 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
.lr-comic-tip-wrap.is-focus-open .lr-comic-tip,
.lr-comic-tip-wrap.is-tip-open .lr-comic-tip {
opacity: 1;
- transform: translateX(-50%) translateY(0);
+ transform: translateY(0);
transition-delay: .12s;
}
.lr-comic-tip-wrap.is-focus-open .lr-comic-tip *,
.lr-comic-tip-wrap.is-tip-open .lr-comic-tip * {
animation-play-state: running !important;
}
-.lr-comic-tip-wrap.is-focus-open .lr-comic-tip.is-below,
-.lr-comic-tip-wrap.is-tip-open .lr-comic-tip.is-below { transform: translateX(-50%) translateY(0); }
-.lr-comic-tip-wrap.is-focus-open .lr-comic-tip.is-start,
-.lr-comic-tip-wrap.is-focus-open .lr-comic-tip.is-end,
-.lr-comic-tip-wrap.is-tip-open .lr-comic-tip.is-start,
-.lr-comic-tip-wrap.is-tip-open .lr-comic-tip.is-end { transform: translateX(0) translateY(0); }
-.lr-comic-tip-wrap.is-focus-open::before,
-.lr-comic-tip-wrap.is-tip-open::before {
- opacity: 1;
- transform: rotate(45deg) scale(1);
- transition-delay: .12s;
-}
-/* Below-placement: header controls sit at the viewport top, so their panel
- opens downward; the wrapper caret flips to the trigger's bottom edge. */
-.lr-comic-tip.is-below { bottom: auto; top: calc(100% + 8px); transform: translateX(-50%) translateY(-4px); }
-
-/* Edge alignment: triggers near a viewport edge anchor the panel's near edge
- instead of centering, so the comic never clips off-screen. */
-.lr-comic-tip.is-start { left: 0; transform: translateX(0) translateY(4px); }
-.lr-comic-tip.is-end { left: auto; right: 0; transform: translateX(0) translateY(4px); }
-.lr-comic-tip.is-below.is-start { transform: translateX(0) translateY(-4px); }
-.lr-comic-tip.is-below.is-end { transform: translateX(0) translateY(-4px); }
+/* Below-placement: header controls sit at the viewport top. */
+.lr-comic-tip.is-below { transform: translateY(-4px); }
/* On mobile the wrapper (not the button) is the flex item, so equal-width
action buttons keep their stretch when hint-wrapped. */
@@ -2049,29 +1846,9 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
transition-duration: 0.01ms !important;
}
.lr-tv-static { animation: none; opacity: .35; }
+ .lr-btn, .lr-chip, .lr-tile, .lr-client-mode, .lr-toggle button, .lr-lang button { transform: none !important; }
.lr-route-edge.is-pending,
.lr-route-edge.is-recovering { animation: none; }
- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell > * {
- animation: none !important;
- stroke-dashoffset: 0 !important;
- }
- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-face {
- animation: none !important;
- opacity: 1 !important;
- transform: none !important;
- }
- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-left,
- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-wink {
- animation: none !important;
- opacity: 1 !important;
- transform: none !important;
- stroke-dashoffset: 0 !important;
- }
- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-open,
- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-sparkles {
- animation: none !important;
- opacity: 0 !important;
- }
}
/* ---------- interaction and legibility constraints ---------- */
@@ -2086,7 +1863,7 @@ html[data-theme="dark"] .lr-pill { color: #e8a33d; }
html[data-theme="dark"] .lr-pill.is-bad { color: #e88a85; }
html[data-theme="dark"] .lr-pill.is-good { color: #63c78a; }
/* Dark-mode preset tiles: lift the unselected caption off the tile fill. */
-html[data-theme="dark"] .lr-tile small { color: #8ba0b4; }
+html[data-theme="dark"] .lr-tile:not(.is-selected) small { color: #8ba0b4; }
@media (max-width: 640px) {
/* Pawn drill-down: the shared .lr-row column stack breaks this card —
@@ -2103,55 +1880,35 @@ html[data-theme="dark"] .lr-tile small { color: #8ba0b4; }
}
-/* Entry overlay hosts hint tooltips: let them escape the screens clip. */
-.lr-tv-screen.has-entry { overflow: visible; }
@media (max-width: 640px) {
.lr-tv-screen .lr-comic-tip { max-width: 62vw; }
}
/* ---------- glyph draw-in (一笔一划) ---------- */
-/* One-shot state-entry beat, gated by Glyph: only on an icon SWAP (play↔pause,
- copy→check, moon↔sun — innerHTML remounts and replays) or on explicit
- theatrical mounts (entry cast/door, stage overlay, join door, gate key).
- Everyday interactions never retrigger it. */
-/* Every shape carries pathLength=1 (injected by Glyph), so dasharray/offset
- in [0,1] paces each stroke evenly no matter its real length. The pen
- grammar: one stroke at a time — 210ms draw per stroke, next stroke starts
- as the current one lands (190ms stagger, ~10% overlap) — with a fast-in,
- settle-out pen curve. Solid icons and filled dots pop with the spring.
- Reduced motion pins the final pose via the global collapse plus the pins. */
-.lr-glyph-draw :is(path, circle, rect, line) {
- stroke-dasharray: 1;
- stroke-dashoffset: 1;
- animation: lr-glyph-in 210ms cubic-bezier(.45, .05, .35, 1) forwards;
-}
-.lr-glyph-draw.is-solid > :is(path, circle, rect),
-.lr-glyph-draw :is([fill="currentColor"], [fill^="#"]) {
- stroke-dasharray: none;
- stroke-dashoffset: 0;
- transform-box: fill-box;
- transform-origin: center;
- /* spring curve inlined: a var() reference would make Chromium restart the
- animation whenever :root custom properties change (theme flip). */
- animation: lr-glyph-pop 220ms cubic-bezier(.3, 1.45, .45, 1) both;
-}
-.lr-glyph-draw > *:nth-child(2) { animation-delay: 190ms; }
-.lr-glyph-draw > *:nth-child(3) { animation-delay: 380ms; }
-.lr-glyph-draw > *:nth-child(4) { animation-delay: 570ms; }
-.lr-glyph-draw > *:nth-child(5) { animation-delay: 760ms; }
-.lr-glyph-draw > *:nth-child(6) { animation-delay: 950ms; }
@keyframes lr-glyph-in { to { stroke-dashoffset: 0; } }
@keyframes lr-glyph-pop {
0% { opacity: 0; transform: scale(.3); }
100% { opacity: 1; transform: scale(1); }
}
-@media (prefers-reduced-motion: reduce) {
- .lr-glyph-draw :is(path, circle, rect, line) {
- animation: none !important;
- stroke-dashoffset: 0 !important;
- opacity: 1 !important;
- transform: none !important;
+/* Drawing is reserved for primary actions and explicit state-entry feedback.
+ Both finish in one beat regardless of stroke count; pathLength=1 normalizes
+ each stroke. Reduced motion and ordinary controls use the unanimated SVG. */
+@media (prefers-reduced-motion: no-preference) {
+ .lr-glyph-draw:not(.lr-spin),
+ button:is(.lr-btn.is-primary, .lr-tv-big, .lr-join-go):not(:disabled):not([aria-disabled="true"]):is(:hover, :focus-visible) .lr-glyph:not(.lr-glyph-draw):not(.lr-spin) {
+ & > :is(path, circle, rect, line) {
+ stroke-dasharray: 1;
+ stroke-dashoffset: 1;
+ animation: lr-glyph-in 280ms cubic-bezier(.45, .05, .35, 1) both;
+ }
+ &.is-solid > :is(path, circle, rect), & > :is([fill="currentColor"], [fill^="#"]) {
+ stroke-dasharray: none;
+ stroke-dashoffset: 0;
+ transform-box: fill-box;
+ transform-origin: center;
+ animation-name: lr-glyph-pop;
+ }
}
}
diff --git a/src/client/types.ts b/src/client/types.ts
index c607ae89..27aa5084 100644
--- a/src/client/types.ts
+++ b/src/client/types.ts
@@ -1,12 +1,11 @@
import type { NatTraversalPath } from "../shared/nat-candidate";
+import type { MediaFailure } from "./ui/media-failure";
export type SignalConnectionState =
"connecting" | "connected" | "reconnecting" | "offline";
export type MediaPath = "direct" | "unknown";
export type NativeEdgeQualityState = "unknown" | "healthy" | "degraded";
-export type QualityWarningKind =
- "bandwidth" | "cpu" | "other" | "configuration";
export interface ConnectionMetrics {
sampleTimestampMs: number | null;
@@ -87,13 +86,12 @@ export interface PeerSnapshot {
connectionState: RTCPeerConnectionState;
iceConnectionState: RTCIceConnectionState;
metrics: ConnectionMetrics;
- error: string | null;
+ /** Keyed failure fact; the UI resolves the copy so it follows the language. */
+ error: MediaFailure | null;
senderParameters?:
import("./media/quality").VideoSenderParameterReadback | null;
audioSenderParameters?:
import("./media/quality").AudioSenderParameterReadback | null;
- qualityWarning?: string | null;
- qualityWarningKind?: QualityWarningKind | null;
}
export const EMPTY_METRICS: ConnectionMetrics = {
diff --git a/src/client/ui/animation.ts b/src/client/ui/animation.ts
index 683745d8..7c662720 100644
--- a/src/client/ui/animation.ts
+++ b/src/client/ui/animation.ts
@@ -30,5 +30,12 @@ export function bindSvgReplayOnPointerEnter(
replaySvgAnimations(graphic);
};
owner.addEventListener("pointerover", handlePointerOver);
- return () => owner.removeEventListener("pointerover", handlePointerOver);
+ const handleFocus = () => {
+ if (owner.matches(":focus-visible")) replaySvgAnimations(graphic);
+ };
+ owner.addEventListener("focusin", handleFocus);
+ return () => {
+ owner.removeEventListener("pointerover", handlePointerOver);
+ owner.removeEventListener("focusin", handleFocus);
+ };
}
diff --git a/src/client/ui/copy.ts b/src/client/ui/copy.ts
index d792c070..3c0893d0 100644
--- a/src/client/ui/copy.ts
+++ b/src/client/ui/copy.ts
@@ -34,16 +34,16 @@ function readStored(): Partial<CopyPrefs> {
}
function detectLang(): Lang {
- return typeof navigator !== "undefined" &&
- navigator.language?.toLowerCase().startsWith("zh")
- ? "zh"
- : "en";
+ const language = typeof navigator === "undefined"
+ ? undefined
+ : navigator.language?.split("-")[0]?.toLowerCase();
+ return language === "zh" ? "zh" : "en";
}
-const stored = readStored();
const state: CopyPrefs = {
- lang: stored.lang ?? detectLang(),
- vis: stored.vis ?? true,
+ lang: detectLang(),
+ vis: false,
+ ...readStored(),
};
function syncDocumentLanguage(): void {
@@ -118,12 +118,17 @@ export function say(key: CopyKey, vars?: Record<string, string>): string {
return t(state.lang, key, vars);
}
-// Locale-aware joins for composed notices (say() composites).
-export function joinSentences(parts: string[]): string {
- return parts.join(state.lang === "zh" ? ";" : "; ");
+// The selected language for composers that run outside React render (say()).
+export function currentLang(): Lang {
+ return state.lang;
}
-export function joinItems(parts: string[]): string {
- return parts.join(state.lang === "zh" ? "、" : ", ");
+
+// Locale-aware joins for composed notices.
+export function joinSentences(lang: Lang, parts: string[]): string {
+ return parts.join(lang === "zh" ? ";" : "; ");
+}
+export function joinItems(lang: Lang, parts: string[]): string {
+ return parts.join(lang === "zh" ? "、" : ", ");
}
export interface Copy {
diff --git a/src/client/ui/icons.tsx b/src/client/ui/icons.tsx
index 49dac682..f91deab3 100644
--- a/src/client/ui/icons.tsx
+++ b/src/client/ui/icons.tsx
@@ -8,6 +8,16 @@ import { useEffect, useRef, type ReactNode } from "react";
import { bindSvgReplayOnPointerEnter } from "./animation";
const PATHS: Record<string, { body: ReactNode; solid?: boolean }> = {
+ couch: { body: (<><path pathLength={1} d="M5 12V8a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3v4M6 19v2m12-2v2"/><path pathLength={1} d="M5 15h14v-3a2 2 0 0 1 4 0v5a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2v-5a2 2 0 0 1 4 0Z"/></>) },
+ gamepad: { body: (<><path pathLength={1} d="M8 7h8c3 0 4 2 5 6l1 5c.3 2-2 3-3.5 1.5L16 17H8l-2.5 2.5C4 21 1.7 20 2 18l1-5c1-4 2-6 5-6Z"/><path pathLength={1} d="M6 12h4m-2-2v4m8-3h.01M18 14h.01"/></>) },
+ save: { body: (<><path pathLength={1} d="M5 3h12l4 4v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z"/><path pathLength={1} d="M7 3v6h9V3M7 21v-7h10v7"/></>) },
+ popcorn: { body: (<><path pathLength={1} d="M5 9c-3-3 0-6 3-5 0-4 6-4 7-1 4-1 7 3 4 6M5 9h14l-2 12H7Z"/><path pathLength={1} d="m9 12 1 6m5-6-1 6"/></>) },
+ clapperboard: { body: (<><path pathLength={1} d="m3 9-1-5 19-3 1 5ZM3 10h19v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/><path pathLength={1} d="m7 3 3 4m4-5 3 4"/></>) },
+ trophy: { body: (<><path pathLength={1} d="M7 3h10v6a5 5 0 0 1-10 0ZM7 5H3v3a4 4 0 0 0 5 4m9-7h4v3a4 4 0 0 1-5 4M12 14v6m-5 1h10"/></>) },
+ gift: { body: (<><rect pathLength={1} x="3" y="8" width="18" height="5" rx="1"/><path pathLength={1} d="M5 13v8h14v-8M12 8v13m0-13C5 8 4 3 7 3c3 0 5 5 5 5s2-5 5-5c3 0 2 5-5 5Z"/></>) },
+ flag: { body: (<><path pathLength={1} d="M5 22V3h14l-4 5 4 5H5"/></>) },
+ heart: { body: (<><path pathLength={1} d="M12 21 3.6 12.6C-2 7 5.5.5 12 7 18.5.5 26 7 20.4 12.6Z"/></>) },
+ bulb: { body: (<><path pathLength={1} d="M8 17v-2c-6-5-3-13 4-13s10 8 4 13v2ZM9 21h6m-3-4v-7m-3 0 3 3 3-3"/></>) },
copy: { body: (<><rect pathLength={1} x="9" y="9" width="12" height="12" rx="2"/><path pathLength={1} d="M5 15V5a2 2 0 0 1 2-2h10"/></>) },
check: { body: (<><path pathLength={1} d="M4 12.5 9.5 18 20 6.5"/></>) },
refresh: { body: (<><path pathLength={1} d="M3 12a9 9 0 0 1 9-9 9.7 9.7 0 0 1 6.7 2.7L21 8"/><path pathLength={1} d="M21 3v5h-5"/><path pathLength={1} d="M21 12a9 9 0 0 1-9 9 9.7 9.7 0 0 1-6.7-2.7L3 16"/><path pathLength={1} d="M8 16H3v5"/></>) },
@@ -44,7 +54,12 @@ const PATHS: Record<string, { body: ReactNode; solid?: boolean }> = {
drop: { body: (<><path pathLength={1} d="M12 3s6 6.4 6 11a6 6 0 0 1-12 0c0-4.6 6-11 6-11Z"/></>) },
expand: { body: (<><path pathLength={1} d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></>) },
contract: { body: (<><path pathLength={1} d="M8 3v5H3m13-5v5h5M8 21v-5H3m13 5v-5h5"/></>) },
+ pip: { body: (<><rect pathLength={1} x="2" y="4" width="20" height="16" rx="2"/><rect pathLength={1} x="12" y="12" width="7" height="5" rx="1"/><path pathLength={1} d="m6 8 3 3M6 11h3V8"/></>) },
+ pipExit: { body: (<><rect pathLength={1} x="2" y="4" width="20" height="16" rx="2"/><rect pathLength={1} x="12" y="12" width="7" height="5" rx="1"/><path pathLength={1} d="m9 11-3-3m0 3V8h3"/></>) },
wave: { body: (<><path pathLength={1} d="M2 12c1.7 0 1.7-2.5 3.4-2.5S7 12 8.7 12s1.6-2.5 3.3-2.5S13.6 12 15.3 12s1.7-2.5 3.4-2.5S20.3 12 22 12"/></>) },
+ speakerOff: { body: (<><path pathLength={1} d="M4 9v6h4l5 4V5L8 9H4Z"/><path pathLength={1} d="m17 9 5 6m0-6-5 6"/></>) },
+ theater: { body: (<><rect pathLength={1} x="2" y="4" width="20" height="16" rx="2"/><path pathLength={1} d="M2 8h20M2 16h20"/></>) },
+ theaterExit: { body: (<><rect pathLength={1} x="2" y="4" width="20" height="16" rx="2"/><rect pathLength={1} x="6" y="8" width="12" height="8" rx="1"/></>) },
speaker: { body: (<><path pathLength={1} d="M4 9v6h4l5 4V5L8 9H4Z"/><path pathLength={1} d="M16 9a4.2 4.2 0 0 1 0 6M18.5 6.5a8 8 0 0 1 0 11"/></>) },
sliders: { body: (<><path pathLength={1} d="M3 6h9m4 0h5M3 12h3m4 0h11M3 18h12m4 0h2"/><circle pathLength={1} cx="14" cy="6" r="2"/><circle pathLength={1} cx="8" cy="12" r="2"/><circle pathLength={1} cx="17" cy="18" r="2"/></>) },
mountain: { body: (<><path pathLength={1} d="m3 18 5.5-8.5L13 15l3.5-5L21 18H3Z"/></>) },
@@ -69,16 +84,17 @@ export function Glyph({
size?: number;
className?: string;
/**
- * Declares an explicit draw-in spot. Marked icons replay on state swaps,
- * genuine remounts, and pointer entry; unmarked icons stay static.
+ * Declares an explicit state-entry drawing. Hover/focus replay belongs only
+ * to primary actions; ordinary controls keep their icon visible.
*/
draw?: string;
}) {
const icon = PATHS[name] ?? PATHS.alert;
const isSolid = icon?.solid === true;
- const drawClass = [
+ const glyphClass = [
+ "lr-glyph",
draw ? "lr-glyph-draw" : null,
- draw && isSolid ? "is-solid" : null,
+ isSolid ? "is-solid" : null,
className ?? null,
]
.filter(Boolean)
@@ -86,8 +102,9 @@ export function Glyph({
const graphicRef = useRef<SVGSVGElement>(null);
useEffect(() => {
- if (!draw || !graphicRef.current) return;
- return bindSvgReplayOnPointerEnter(graphicRef.current);
+ const graphic = graphicRef.current;
+ if (!draw || !graphic?.closest("button:is(.lr-btn.is-primary, .lr-tv-big, .lr-join-go)")) return;
+ return bindSvgReplayOnPointerEnter(graphic);
}, [draw]);
return (
@@ -103,7 +120,7 @@ export function Glyph({
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
- className={drawClass || undefined}
+ className={glyphClass}
>
{icon?.body}
</svg>
diff --git a/src/client/ui/media-failure.ts b/src/client/ui/media-failure.ts
new file mode 100644
index 00000000..37f7147b
--- /dev/null
+++ b/src/client/ui/media-failure.ts
@@ -0,0 +1,46 @@
+// A media failure is a fact, not copy: transport layers record what failed and
+// the UI resolves it during render, so switching language re-renders instead of
+// leaving stale text until the next media event.
+import {
+ joinItems,
+ joinSentences,
+ type Copy,
+ type CopyKey,
+} from "./copy";
+
+export interface MediaFailure {
+ key: CopyKey;
+ /** Copy keys locale-joined into the template's `{params}` slot. */
+ paramKeys?: readonly CopyKey[];
+ /** Literal template substitutions. */
+ vars?: Record<string, string>;
+}
+
+export function resolveMediaFailure(
+ failure: MediaFailure | MediaFailure[] | null | undefined,
+ copy: Pick<Copy, "lang" | "t">,
+): string | null {
+ if (!failure) {
+ return null;
+ }
+ const entries = Array.isArray(failure) ? failure : [failure];
+ if (entries.length === 0) {
+ return null;
+ }
+ const parts = entries.map((entry) =>
+ copy.t(entry.key, {
+ ...entry.vars,
+ ...(entry.paramKeys
+ ? {
+ params: joinItems(
+ copy.lang,
+ entry.paramKeys.map((key) => copy.t(key)),
+ ),
+ }
+ : {}),
+ }),
+ );
+ return parts.length === 1
+ ? parts[0]!
+ : joinSentences(copy.lang, parts);
+}
diff --git a/src/client/ui/media-status.ts b/src/client/ui/media-status.ts
new file mode 100644
index 00000000..b44e1171
--- /dev/null
+++ b/src/client/ui/media-status.ts
@@ -0,0 +1,198 @@
+// One visual vocabulary; facts stay with the media/session owners. This module
+// only projects current facts. It has no state, timers, scores or recovery work.
+import type { ComicKind, HintKind } from "./visual-kinds";
+import type { ViewerPresentation, ViewerStage } from "../media/viewer-presentation";
+import type { SignalConnectionState } from "../types";
+import type { MediaRouteUpstream } from "../../shared/protocol";
+import { qualityEvidenceUpstreamMatches, type ViewerQualityEvidencePresentation } from "../media/viewer-quality-evidence";
+import type { CopyKey, TitleFrameKey } from "./copy";
+import type { GlyphName } from "./icons";
+
+export interface StatusDescriptor {
+ tone: "off" | "busy" | "live" | "warn" | "bad";
+ labelKey: CopyKey;
+ icon: GlyphName;
+ comic?: ComicKind;
+ tooltip?: ComicKind | HintKind;
+ pulse?: boolean;
+}
+
+export interface QualityObservation {
+ // Only the current, matching media path; callers own identity and freshness.
+ // A relay's outbound limitation says nothing about its own received picture.
+ reason: RTCQualityLimitationReason | "unknown";
+ fresh: boolean;
+}
+
+export const STATUS_CATALOG = {
+ idle: { tone: "off", labelKey: "state.peer.waiting", icon: "moon", comic: "waiting-for-host" },
+ connected: { tone: "live", labelKey: "state.peer.connected", icon: "check" },
+ joining: { tone: "busy", labelKey: "state.peer.connecting", icon: "loader", comic: "connecting-p2p", pulse: true },
+ reconnecting: { tone: "warn", labelKey: "state.peer.reconnecting", icon: "refresh", comic: "recovering", pulse: true },
+ disconnected: { tone: "bad", labelKey: "state.peer.disconnected", icon: "wifiOff", comic: "route-failed" },
+ qualityUnknown: { tone: "off", labelKey: "stats.unknown", icon: "gauge" },
+ qualityNormal: { tone: "live", labelKey: "stats.quality.normal", icon: "check" },
+ stuttering: { tone: "warn", labelKey: "state.peer.stuttering", icon: "wave", comic: "warning" },
+ bandwidth: { tone: "warn", labelKey: "stats.quality.bandwidth", icon: "gauge", comic: "bandwidth-limited" },
+ cpu: { tone: "warn", labelKey: "stats.quality.cpu", icon: "cpu", comic: "encoder-limited" },
+ other: { tone: "warn", labelKey: "stats.quality.other", icon: "alert", comic: "warning" },
+} as const satisfies Record<string, StatusDescriptor>;
+
+export function deriveParticipantStatus(
+ participant: { mediaReady?: boolean; upstream: MediaRouteUpstream },
+ sourceActive: boolean,
+ presentation?: ViewerQualityEvidencePresentation,
+): StatusDescriptor {
+ // Room authority owns readiness. Receive evidence can annotate it, not
+ // convert a pending path into connected or a missing sample into failure.
+ if (!participant.mediaReady) {
+ if (!sourceActive) return STATUS_CATALOG.idle;
+ return { ...STATUS_CATALOG.joining,
+ labelKey: participant.upstream.kind === "none" ? "state.peer.routing" : "state.peer.connecting" };
+ }
+ if (sourceActive && presentation?.fresh &&
+ qualityEvidenceUpstreamMatches(presentation.evidence, participant.upstream)) {
+ const { freezeCountDelta, freezeDurationMsDelta } = presentation.evidence.metrics;
+ if ((freezeCountDelta ?? 0) > 0 || (freezeDurationMsDelta ?? 0) > 0) return STATUS_CATALOG.stuttering;
+ }
+ return STATUS_CATALOG.connected;
+}
+
+// Exhaustive stage mapping replaces the separate overlay/icon/lamp switches.
+// Stage identity and priority still come from the existing presentation reducer.
+const STAGE_VISUALS = {
+ joining: { tone: "busy", icon: "loader", comic: "signal-connecting", pulse: true },
+ "room-not-found": { tone: "bad", icon: "door", comic: "room-not-found" },
+ "access-denied": { tone: "bad", icon: "lock", comic: "access-denied" },
+ "invalid-invite": { tone: "bad", icon: "lock", comic: "invalid-invite" },
+ "room-closed": { tone: "off", icon: "door", comic: "room-not-found" },
+ "room-full": { tone: "bad", icon: "users", comic: "room-full" },
+ "stale-client": { tone: "bad", icon: "alert", comic: "warning" },
+ "server-error": { tone: "bad", icon: "alert", comic: "warning" },
+ "session-replaced": { tone: "bad", icon: "alert", comic: "warning" },
+ "signal-terminated": { tone: "bad", icon: "wifiOff", comic: "warning" },
+ "host-paused": { tone: "warn", icon: "pause", comic: "host-paused" },
+ "needs-play": { tone: "busy", icon: "play", comic: "tap-to-play" },
+ playing: { tone: "live", icon: "play" },
+ recovering: { tone: "warn", icon: "refresh", comic: "recovering", pulse: true },
+ "route-failed": { tone: "bad", icon: "wifiOff", comic: "route-failed" },
+ "playback-failed": { tone: "bad", icon: "alert", comic: "playback-failed" },
+ "waiting-host": { tone: "off", icon: "moon", comic: "waiting-for-host" },
+ "host-offline": { tone: "bad", icon: "wifiOff", comic: "host-offline" },
+ "waiting-sfu": { tone: "busy", icon: "loader", comic: "connecting-sfu", pulse: true },
+ "preparing-p2p": { tone: "busy", icon: "loader", comic: "connecting-p2p", pulse: true },
+ "preparing-sfu": { tone: "busy", icon: "loader", comic: "connecting-sfu", pulse: true },
+ receiving: { tone: "busy", icon: "loader", pulse: true },
+ allocating: { tone: "busy", icon: "loader", comic: "signal-connecting", pulse: true },
+} as const satisfies Record<ViewerStage, Omit<StatusDescriptor, "labelKey">>;
+
+function qualityWarning(observation?: QualityObservation): StatusDescriptor | null {
+ if (!observation?.fresh) return null;
+ switch (observation.reason) {
+ case "bandwidth": return STATUS_CATALOG.bandwidth;
+ case "cpu": return STATUS_CATALOG.cpu;
+ case "other": return STATUS_CATALOG.other;
+ default: return null;
+ }
+}
+
+export function peerConnectionStatus(state: RTCPeerConnectionState): StatusDescriptor {
+ // WebRTC disconnected can recover. Red is reserved for a confirmed failure,
+ // not a temporary loss of checks; closed is intentional retirement/idle.
+ switch (state) {
+ case "connected": return STATUS_CATALOG.connected;
+ case "disconnected": return STATUS_CATALOG.reconnecting;
+ case "failed": return STATUS_CATALOG.disconnected;
+ case "closed": return STATUS_CATALOG.idle;
+ default: return STATUS_CATALOG.joining;
+ }
+}
+
+export type HostPhase = "idle" | "starting" | "live" | "ended" | "error";
+
+const HOST_VISUALS = {
+ idle: { ...STATUS_CATALOG.idle, labelKey: "host.notStarted" },
+ starting: { tone: "busy", icon: "cast", tooltip: "hint-share-start", pulse: true, labelKey: "host.starting" },
+ live: { tone: "live", icon: "play", labelKey: "host.live" },
+ ended: { ...STATUS_CATALOG.idle, labelKey: "host.ended" },
+ error: { tone: "bad", icon: "alert", comic: "warning", labelKey: "host.fail.start" },
+} as const satisfies Record<HostPhase, StatusDescriptor>;
+
+const SIGNAL_VISUALS = {
+ connected: { ...STATUS_CATALOG.connected, labelKey: "state.signal.connected" },
+ connecting: { ...STATUS_CATALOG.joining, comic: "signal-connecting", labelKey: "state.signal.connecting" },
+ reconnecting: { ...STATUS_CATALOG.reconnecting, comic: "signal-recovering", labelKey: "state.signal.reconnecting" },
+ offline: { tone: "off", icon: "wifiOff", comic: "signal-offline", labelKey: "state.signal.offline" },
+} as const satisfies Record<SignalConnectionState, StatusDescriptor>;
+
+export function deriveHostStatus({ phase, paused, signal, roomReady }: {
+ phase: HostPhase; paused: boolean; signal: SignalConnectionState; roomReady: boolean;
+}) {
+ const activity: StatusDescriptor = phase === "live" && paused
+ ? { tone: "warn", icon: "pause", comic: "host-paused", labelKey: "host.paused" }
+ : phase === "idle" && roomReady
+ ? { ...HOST_VISUALS.idle, labelKey: "host.roomReady" }
+ : HOST_VISUALS[phase];
+ const titleFrameKey: TitleFrameKey = phase === "live" ? paused ? "paused" : "hostActive"
+ : phase === "starting" ? "hostStarting"
+ : phase === "error" ? "hostUnavailable"
+ : phase === "ended" ? "hostEnded"
+ : roomReady ? "hostReady" : "hostIdle";
+ return {
+ activity,
+ // The Host television is a local source preview. A weak outbound child
+ // belongs on that child's status, not on the Host's source lamp.
+ television: activity,
+ connection: SIGNAL_VISUALS[signal] as StatusDescriptor,
+ titleFrameKey,
+ titleMarker: phase === "live" && signal !== "connected" ? "⚠️" : null,
+ };
+}
+
+export function deriveViewerStatus(
+ presentation: ViewerPresentation,
+ signal: SignalConnectionState,
+ observation?: QualityObservation,
+ route: "p2p" | "sfu" | null = null,
+) {
+ // Control recovery does not interrupt a picture that remains proved.
+ const mediaRecovering = presentation.noticeKey === "viewer.notice.mediaRecovering";
+ const playable = presentation.overlay === "none" && !mediaRecovering;
+ const stage = playable ? "playing" : presentation.stage;
+ const activity: StatusDescriptor = {
+ ...STAGE_VISUALS[stage],
+ labelKey: mediaRecovering ? "viewer.notice.mediaRecovering"
+ : playable ? "viewer.msg.playing" : presentation.messageKey,
+ ...(stage === "receiving" ? { comic: route === "sfu" ? "connecting-sfu" as const : "connecting-p2p" as const } : {}),
+ };
+ const warning = qualityWarning(observation);
+ const quality: StatusDescriptor = warning ?? (observation?.fresh && observation.reason === "none"
+ ? STATUS_CATALOG.qualityNormal : STATUS_CATALOG.qualityUnknown);
+ let notice: StatusDescriptor | null = null;
+ switch (presentation.noticeKey) {
+ case "viewer.notice.hostOffline":
+ notice = { tone: "warn", icon: "wifiOff", comic: "host-offline", labelKey: presentation.noticeKey };
+ break;
+ case "viewer.notice.signalRecovering":
+ notice = { ...SIGNAL_VISUALS.reconnecting, icon: "signal", labelKey: presentation.noticeKey };
+ break;
+ }
+ const overlay = presentation.overlay === "none"
+ ? null
+ : { mode: presentation.overlay, status: activity };
+ const television: StatusDescriptor = playable
+ ? warning ?? activity
+ : activity;
+ const connection: StatusDescriptor = SIGNAL_VISUALS[signal];
+ const titleFrameKey: TitleFrameKey = presentation.stage === "host-paused"
+ ? "paused"
+ : presentation.stage === "needs-play" ? "viewerReady"
+ : activity.tone === "bad" ? "viewerUnavailable"
+ : !overlay && presentation.hasCurrentFrame ? "viewerActive"
+ : "viewerWaiting";
+ return {
+ activity, television, connection, quality, notice, overlay,
+ titleFrameKey,
+ titleMarker: !overlay && (television.tone === "warn" || notice) ? "⚠️" : null,
+ };
+}
diff --git a/src/client/ui/theme.ts b/src/client/ui/theme.ts
index 7af02228..f2235791 100644
--- a/src/client/ui/theme.ts
+++ b/src/client/ui/theme.ts
@@ -56,10 +56,22 @@ export function applyTheme(theme: Theme): void {
}
}
-export function initTheme(): void {
- const stored = storedTheme();
+export function currentThemePreference(): Theme | null {
+ return state.explicit ? state.theme : null;
+}
+
+export function initTheme(preference?: Theme | null): void {
+ if (preference !== undefined) {
+ try {
+ if (preference === null) window.localStorage.removeItem(THEME_STORAGE_KEY);
+ else window.localStorage.setItem(THEME_STORAGE_KEY, preference);
+ } catch {
+ // The launch choice still applies when persistence is unavailable.
+ }
+ }
+ const stored = preference === undefined ? storedTheme() : preference;
state.explicit = stored !== null;
- state.theme = stored ?? readInitial();
+ state.theme = stored ?? (preference === null ? detectTheme() : readInitial());
document.documentElement.dataset.theme = state.theme;
if (!state.initialized && typeof window.matchMedia === "function") {
state.initialized = true;
diff --git a/src/client/ui/visual-kinds.ts b/src/client/ui/visual-kinds.ts
new file mode 100644
index 00000000..843bd91b
--- /dev/null
+++ b/src/client/ui/visual-kinds.ts
@@ -0,0 +1,106 @@
+import type { ReactNode } from "react";
+
+export type ComicKind =
+ | "waiting-for-host"
+ | "connecting-p2p"
+ | "connecting-sfu"
+ | "signal-connecting"
+ | "signal-recovering"
+ | "signal-offline"
+ | "tap-to-play"
+ | "host-paused"
+ | "recovering"
+ | "route-failed"
+ | "playback-failed"
+ | "host-offline"
+ | "no-audio"
+ | "room-not-found"
+ | "access-denied"
+ | "invalid-invite"
+ | "room-full"
+ | "bandwidth-limited"
+ | "encoder-limited"
+ | "warning";
+
+export type Set1Kind =
+ | "hint-share-start"
+ | "hint-share-stop"
+ | "hint-pause"
+ | "hint-resume"
+ | "hint-switch-source"
+ | "hint-reconnect"
+ | "hint-capture-browser"
+ | "hint-capture-window"
+ | "hint-capture-display";
+
+export type Set2Kind =
+ | "hint-copy-code"
+ | "hint-shuffle-code"
+ | "hint-copy-invite"
+ | "hint-client-link"
+ | "hint-rotate-invite"
+ | "hint-revoke-invite"
+ | "hint-policy-open"
+ | "hint-policy-private"
+ | "hint-password";
+
+export type Set3Kind =
+ | "hint-quality"
+ | "hint-audio-quality"
+ | "hint-degrade-pref"
+ | "hint-codec"
+ | "hint-advanced"
+ | "hint-details"
+ | "hint-debug-export"
+ | "hint-more-metrics";
+
+export type Set4Kind =
+ | "hint-topology"
+ | "hint-close"
+ | "hint-rename"
+ | "hint-theme-light"
+ | "hint-theme-dark"
+ | "hint-join-go"
+ | "hint-theater"
+ | "hint-theater-exit"
+ | "hint-route-p2p"
+ | "hint-route-p2p-required"
+ | "hint-route-sfu"
+ | "hint-nat-prediction"
+ | "hint-nat-unavailable"
+ | "hint-client-local"
+ | "hint-client-site";
+
+export type PlaybackHintKind =
+ | "hint-local-play"
+ | "hint-local-pause"
+ | "hint-volume"
+ | "hint-volume-basic"
+ | "hint-mute"
+ | "hint-unmute"
+ | "hint-no-audio"
+ | "hint-fullscreen"
+ | "hint-fullscreen-exit"
+ | "hint-pip"
+ | "hint-pip-exit"
+ | "hint-pip-unavailable";
+
+export type ControlHintKind =
+ | "hint-collapse"
+ | "hint-password-show"
+ | "hint-password-hide"
+ | "hint-share-audio"
+ | "hint-stop-audio"
+ | "hint-share-audio-fixed"
+ | "hint-silent-share-fixed";
+
+export type HintKind =
+ | Set1Kind
+ | Set2Kind
+ | Set3Kind
+ | Set4Kind
+ | PlaybackHintKind
+ | ControlHintKind;
+
+export type ComicTheme = "stage" | "paper";
+export type HintScene = (props: { theme: ComicTheme }) => ReactNode;
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index 5dafe287..703ce0f1 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -1,16 +1,11 @@
-import { say } from "../ui/copy";
-import {
- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS,
- type IceConfig,
- type SignalPayload,
-} from "../../shared/protocol";
+import type { CopyKey } from "../ui/copy";
+import type { IceConfig, SignalPayload } from "../../shared/protocol";
import { createOpaqueId } from "../lib/opaque-id";
import type { BrowserEncodingPool, BrowserPooledSender } from "../media/browser-encoding-pool";
import { BrowserEncodingOutput, encodedStreams, supportsBrowserEncoding } from "../media/browser-encoding-output";
import { debugError, debugEvent } from "../lib/debug";
import { debugTrack, observeDebugConnection } from "../lib/debug-webrtc";
import {
- audioSenderParameterWarning,
applyVideoCaptureProfile,
cloneSenderVideoTrack,
configureScreenAudioSender,
@@ -18,7 +13,6 @@ import {
needsStartupVideoProfile,
resolveScreenAudioQuality,
screenAudioQualityEqual,
- senderParameterWarning,
STARTUP_VIDEO_ENCODED_FRAMES,
startupVideoProfile,
videoQualitySettingsEqual,
@@ -26,11 +20,7 @@ import {
type QualityProfile,
type ScreenAudioQuality,
} from "../media/quality";
-import {
- EMPTY_METRICS,
- type PeerSnapshot,
- type QualityWarningKind,
-} from "../types";
+import { EMPTY_METRICS, type PeerSnapshot } from "../types";
import {
captureMetrics,
collectConnectionMetrics,
@@ -96,15 +86,11 @@ export class HostPeer {
private statsTimer: number | null = null;
private statsInFlight = false;
private statsSamplingBlocked = false;
- private videoSenderWarning: string | null = null;
- private audioSenderWarning: string | null = null;
private appliedVideoProfile: QualityProfile | null = null;
private appliedAudioQuality: ScreenAudioQuality | null = null;
private appliedAudioSenderParameters:
| AudioSenderParameterReadback
| null = null;
- private limitationReason: string | null = null;
- private limitationSamples = 0;
private disposed = false;
private profileRevision = 0;
private negotiationEpoch = 0;
@@ -164,8 +150,6 @@ export class HostPeer {
error: null,
senderParameters: null,
audioSenderParameters: null,
- qualityWarning: null,
- qualityWarningKind: null,
};
this.bindConnectionEvents();
}
@@ -173,7 +157,7 @@ export class HostPeer {
async start(): Promise<boolean> {
const videoTrack = this.senderVideoTrack;
if (!videoTrack) {
- this.setError(new Error(say("host.capture.noSource")), say("host.err.createConnection"));
+ this.setError(null, "host.capture.noSource");
return false;
}
const audioTrack = this.stream.getAudioTracks()[0] ?? null;
@@ -182,7 +166,7 @@ export class HostPeer {
streams: [this.stream],
});
if (!applyVideoCodecPreference(videoTransceiver, this.videoCodec)) {
- this.setError(null, say("host.err.codecUnsupported"));
+ this.setError(null, "host.err.codecUnsupported");
return false;
}
this.videoSender = videoTransceiver.sender;
@@ -278,7 +262,7 @@ export class HostPeer {
if (videoRollback.status === "rejected") {
this.dispose();
}
- this.setError(error, say("host.fail.source"));
+ this.setError(error, "host.fail.source");
return false;
}
@@ -296,8 +280,6 @@ export class HostPeer {
this.startupVideoProfilePending = needsStartupVideoProfile(
this.desiredProfile,
);
- this.limitationReason = null;
- this.limitationSamples = 0;
this.snapshot = { ...this.snapshot, metrics: { ...EMPTY_METRICS } };
await this.configureSender(videoSender, audioSender, {
profile: startupVideoProfile(this.desiredProfile),
@@ -415,8 +397,6 @@ export class HostPeer {
}
if (updateVideo) {
this.statsAccumulator = createStatsAccumulator();
- this.limitationReason = null;
- this.limitationSamples = 0;
}
this.snapshot = { ...this.snapshot, error: null };
this.emit();
@@ -441,7 +421,7 @@ export class HostPeer {
this.pendingCandidates.push(payload.candidate);
}
} catch (error) {
- this.setError(error, say("host.err.createConnection"));
+ this.setError(error, "host.err.createConnection");
}
}
@@ -484,7 +464,7 @@ export class HostPeer {
),
);
} catch (error) {
- this.setError(error, say("host.err.createConnection"));
+ this.setError(error, "host.err.createConnection");
}
}
@@ -658,7 +638,7 @@ export class HostPeer {
},
})
) {
- throw new Error(say("host.err.serverError"));
+ throw new Error("signal send rejected");
}
this.snapshot = { ...this.snapshot, error: null };
this.emit();
@@ -670,7 +650,7 @@ export class HostPeer {
if (this.ordinaryAnswerEpoch === epoch) {
this.ordinaryAnswerEpoch = null;
}
- this.setError(error, say("host.err.createConnection"));
+ this.setError(error, "host.err.createConnection");
return false;
}
}
@@ -779,12 +759,7 @@ export class HostPeer {
void this.updateProfile(this.desiredProfile);
}
const deliveredMetrics = this.pooledVideo?.metrics(metrics) ?? metrics;
- this.updateLimitationWarning(deliveredMetrics.qualityLimitationReason);
- this.snapshot = {
- ...this.snapshot,
- metrics: deliveredMetrics,
- ...this.qualityWarningSnapshot(),
- };
+ this.snapshot = { ...this.snapshot, metrics: deliveredMetrics };
this.emit();
} catch {
// Stats are observational and must never disrupt a healthy media path.
@@ -793,9 +768,9 @@ export class HostPeer {
}
}
- private setError(error: unknown, fallback: string): void {
- debugError("webrtc", "sender-failed", error, { connectionId: this.connectionId, reason: fallback });
- this.snapshot = { ...this.snapshot, error: fallback };
+ private setError(error: unknown, key: CopyKey): void {
+ debugError("webrtc", "sender-failed", error, { connectionId: this.connectionId, reason: key });
+ this.snapshot = { ...this.snapshot, error: { key } };
this.emit();
}
@@ -817,19 +792,15 @@ export class HostPeer {
const { profile, profileRevision } = mutation;
let senderParameters = this.snapshot.senderParameters ?? null;
let audioSenderParameters = this.appliedAudioSenderParameters;
- let videoWarning = this.videoSenderWarning;
- let audioWarning = this.audioSenderWarning;
let videoSucceeded = true;
let audioSucceeded = true;
if (mutation.video) {
try {
senderParameters = await configureVideoSender(sender, profile, this.pooledVideo?.carrierScale());
- videoWarning = senderParameterWarning(senderParameters);
} catch (error) {
videoSucceeded = false;
debugError("webrtc", "sender-parameters-failed", error, { connectionId: this.connectionId, profileRevision, requested: profile });
- videoWarning = say("host.err.applySender");
}
}
@@ -843,7 +814,7 @@ export class HostPeer {
if (mutation.video && videoSucceeded && this.pooledVideo) {
try { await this.pooledVideo.updateProfile(this.desiredProfile); }
- catch { videoSucceeded = false; videoWarning = say("host.err.applySender"); }
+ catch { videoSucceeded = false; }
}
if (mutation.audio && audioSender) {
@@ -853,15 +824,12 @@ export class HostPeer {
audioSender,
profile.screenAudioQuality,
);
- audioWarning = audioSenderParameterWarning(audioSenderParameters);
} catch (error) {
audioSucceeded = false;
debugError("webrtc", "audio-parameters-failed", error, { connectionId: this.connectionId, profileRevision });
- audioWarning = say("host.err.applyAudioSender");
}
} else {
audioSenderParameters = null;
- audioWarning = null;
}
}
@@ -873,8 +841,6 @@ export class HostPeer {
) {
return false;
}
- this.videoSenderWarning = videoWarning;
- this.audioSenderWarning = audioWarning;
debugEvent("webrtc", "sender-parameters", { connectionId: this.connectionId, profileRevision,
requested: profile, videoSucceeded, audioSucceeded, senderParameters, audioSenderParameters });
if (mutation.video && videoSucceeded) {
@@ -890,78 +856,11 @@ export class HostPeer {
...this.snapshot,
senderParameters,
audioSenderParameters: this.appliedAudioSenderParameters,
- ...this.qualityWarningSnapshot(),
};
this.emit();
return videoSucceeded && audioSucceeded;
}
- private combinedSenderWarning(): string | null {
- const warnings = [
- this.videoSenderWarning,
- this.audioSenderWarning,
- ].filter((warning): warning is string => warning !== null);
- return warnings.length > 0 ? warnings.join(";") : null;
- }
-
- private updateLimitationWarning(reason: string | null): void {
- if (!reason || reason === "none") {
- this.limitationReason = null;
- this.limitationSamples = 0;
- return;
- }
- if (reason === this.limitationReason) {
- this.limitationSamples += 1;
- return;
- }
- this.limitationReason = reason;
- this.limitationSamples = 1;
- }
-
- private persistentLimitationWarning(): string | null {
- if (
- this.limitationSamples < PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS
- ) {
- return null;
- }
- switch (this.limitationReason) {
- case "bandwidth":
- return say("host.warn.bandwidth");
- case "cpu":
- return say("host.warn.encoding");
- case "other":
- return say("host.warn.other");
- default:
- return this.limitationReason
- ? say("host.warn.unclassified")
- : null;
- }
- }
-
- private qualityWarningSnapshot(): {
- qualityWarning: string | null;
- qualityWarningKind: QualityWarningKind | null;
- } {
- const configurationWarning = this.combinedSenderWarning();
- if (configurationWarning) {
- return {
- qualityWarning: configurationWarning,
- qualityWarningKind: "configuration",
- };
- }
- const qualityWarning = this.persistentLimitationWarning();
- if (!qualityWarning) {
- return { qualityWarning: null, qualityWarningKind: null };
- }
- return {
- qualityWarning,
- qualityWarningKind:
- this.limitationReason === "bandwidth" || this.limitationReason === "cpu"
- ? this.limitationReason
- : "other",
- };
- }
-
private emit(): void {
if (this.disposed) {
return;
diff --git a/src/client/webrtc/viewer-peer.ts b/src/client/webrtc/viewer-peer.ts
index f549ebde..036cef13 100644
--- a/src/client/webrtc/viewer-peer.ts
+++ b/src/client/webrtc/viewer-peer.ts
@@ -1,4 +1,4 @@
-import { say } from "../ui/copy";
+import type { CopyKey } from "../ui/copy";
import type { IceConfig, SignalPayload } from "../../shared/protocol";
import { debugError } from "../lib/debug";
import { observeDebugConnection } from "../lib/debug-webrtc";
@@ -157,7 +157,7 @@ export class ViewerPeer implements ViewerMediaPeer {
),
);
} catch (error) {
- this.setError(error, say("host.fail.connection"));
+ this.setError(error, "host.fail.connection");
}
}
@@ -385,7 +385,7 @@ export class ViewerPeer implements ViewerMediaPeer {
sdp: connection.localDescription.sdp,
},
})) {
- throw new Error(say("viewer.msg.serverError"));
+ throw new Error("signal send rejected");
}
this.clearRecoveryTimer();
this.offerRecoveryAttempts = 0;
@@ -394,7 +394,7 @@ export class ViewerPeer implements ViewerMediaPeer {
if (!this.isCurrentConnection(connection, connectionId)) {
return;
}
- this.setError(error, say("host.fail.connection"));
+ this.setError(error, "host.fail.connection");
if (
this.offerRecoveryAttempts < 1 &&
this.events.sendRestartRequest(parentPeerId, connectionId, true)
@@ -427,7 +427,7 @@ export class ViewerPeer implements ViewerMediaPeer {
await addRemoteIceCandidate(connection, payload.candidate);
} catch (error) {
if (this.isCurrentConnection(connection, connectionId)) {
- this.setError(error, say("host.fail.connection"));
+ this.setError(error, "host.fail.connection");
}
}
}
@@ -643,13 +643,12 @@ export class ViewerPeer implements ViewerMediaPeer {
);
}
- private setError(error: unknown, fallback: string): void {
- debugError("webrtc", "receiver-failed", error, { connectionId: this.connectionId, reason: fallback });
+ private setError(error: unknown, key: CopyKey): void {
+ debugError("webrtc", "receiver-failed", error, { connectionId: this.connectionId, reason: key });
if (!this.snapshot) {
return;
}
- const message = error instanceof Error ? error.message : fallback;
- this.snapshot = { ...this.snapshot, error: message || fallback };
+ this.snapshot = { ...this.snapshot, error: { key } };
this.emit();
}
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index 5640a766..3bf0afd1 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -25,7 +25,7 @@ export const VIEWER_QUALITY_EVIDENCE_EXPIRY_MS = 5_000;
export const PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS = 3;
export const MAX_DISPLAY_NAME_CODE_POINTS = 24;
export const DEFAULT_VIEWER_DISPLAY_NAME = "观众";
-export const DEFAULT_HOST_DISPLAY_NAME_PREFIX = "分享者";
+export const DEFAULT_HOST_DISPLAY_NAME_PREFIX = "房主";
export const MIN_VIEWER_PASSWORD_LENGTH = 1;
export const MAX_VIEWER_PASSWORD_LENGTH = 64;
@@ -217,11 +217,10 @@ export const DEFAULT_ROUTE_POLICY = {
natPrediction: false,
} as const satisfies RoutePolicy;
-export const runtimeCapabilitiesSchema = z
- .object({
- natPrediction: z.boolean(),
- })
- .strict();
+export const runtimeCapabilitiesSchema = z.object({
+ sfu: z.boolean().default(false),
+ natPrediction: z.boolean().default(false),
+});
export type RuntimeCapabilities = z.infer<typeof runtimeCapabilitiesSchema>;
export const relayDownstreamEdgesSchema = z
diff --git a/tsconfig.app.json b/src/tsconfig.json
similarity index 83%
rename from tsconfig.app.json
rename to src/tsconfig.json
index 1dea2265..f991834f 100644
--- a/tsconfig.app.json
+++ b/src/tsconfig.json
@@ -1,6 +1,6 @@
{
"compilerOptions": {
- "tsBuildInfoFile": "./node_modules/.cache/tsconfig.app.tsbuildinfo",
+ "tsBuildInfoFile": "../node_modules/.cache/tsconfig.app.tsbuildinfo",
"target": "ES2023",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
@@ -19,5 +19,5 @@
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
- "include": ["src/client", "src/shared"]
+ "include": ["client", "shared"]
}
diff --git a/tests/browser-debug.test.ts b/tests/browser-debug.test.ts
index 0cb91c36..ceac7a00 100644
--- a/tests/browser-debug.test.ts
+++ b/tests/browser-debug.test.ts
@@ -164,4 +164,20 @@ describe("opt-in Browser diagnostics", () => {
expect(history[0]!.details.requested).toMatchObject({ profile: DEFAULT_QUALITY_SETTINGS });
expect(await debug.exportBrowserDebug()).not.toContain(token);
});
+
+ it("reports an observed App mismatch without exposing its capability token", async () => {
+ const page = browser();
+ const token = "x".repeat(43);
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
+ protocol: 8, service: "piik-client", port: 39721, instanceToken: token,
+ }))));
+ const debug = await import("../src/client/lib/debug");
+ debug.installBrowserDebug();
+ const { NativeClient } = await import("../src/client/native/client");
+ await expect(NativeClient.connect()).rejects.toMatchObject({ name: "NativeCompatibilityError" });
+ expect(page.__PIIK_DEBUG__!.events()).toContainEqual(expect.objectContaining({
+ scope: "native", event: "incompatible", details: { actualProtocol: 8, expectedProtocol: 9 },
+ }));
+ expect(await debug.exportBrowserDebug()).not.toContain(token);
+ });
});
diff --git a/tests/client-package-targets.test.ts b/tests/client-package-targets.test.ts
new file mode 100644
index 00000000..c39ac805
--- /dev/null
+++ b/tests/client-package-targets.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ CLIENT_PACKAGE_TARGETS,
+ clientGoEnvironment,
+} from "../scripts/client-package-targets.mjs";
+
+describe("client package targets", () => {
+ it("derives build and license discovery from one explicit cgo policy", () => {
+ const previous = process.env.CGO_ENABLED;
+ try {
+ process.env.CGO_ENABLED = "unexpected-inherited-value";
+ const settings = CLIENT_PACKAGE_TARGETS.map((target) => {
+ const env = clientGoEnvironment(target);
+ const pathKey = Object.keys(process.env).find(
+ (key) => key.toLowerCase() === "path",
+ );
+ // Ambient entries survive; only OS, architecture and cgo are explicit.
+ if (pathKey) {
+ expect(Object.entries(env)).toContainEqual([
+ pathKey,
+ process.env[pathKey],
+ ]);
+ }
+ expect(process.env.CGO_ENABLED).toBe("unexpected-inherited-value");
+ return [target.id, env.GOOS, env.GOARCH, env.CGO_ENABLED];
+ });
+ expect(settings).toEqual([
+ ["windows-amd64", "windows", "amd64", "0"],
+ ["linux-amd64", "linux", "amd64", "0"],
+ ["darwin-arm64", "darwin", "arm64", "1"],
+ ]);
+ } finally {
+ if (previous === undefined) delete process.env.CGO_ENABLED;
+ else process.env.CGO_ENABLED = previous;
+ }
+ });
+});
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index 3d7a3dd6..b71e417f 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -23,6 +23,7 @@ import {
import { setCopy } from "../src/client/ui/copy.ts";
import {
clearHostRoom,
+ clientLaunchURL,
getStableClientId,
isValidRoomId,
parseAppRoute,
@@ -87,14 +88,14 @@ describe("browser-local display name", () => {
it("localizes text defaults and uses visual emoji identities", () => {
setCopy({ lang: "zh", vis: false });
expect(defaultViewerDisplayName(false)).toBe("观众");
- expect(defaultHostDisplayName(false)).toBe("分享者");
+ expect(defaultHostDisplayName(false)).toBe("房主");
setCopy({ lang: "en", vis: false });
expect(defaultViewerDisplayName(false)).toBe("Viewer");
expect(defaultHostDisplayName(false)).toBe("Host");
expect(defaultViewerDisplayName(true)).toBe("👤");
- expect(defaultHostDisplayName(true)).toBe("👑");
+ expect(defaultHostDisplayName(true)).toBe("📺");
});
it("stores only the canonical preference and falls back when cleared", () => {
@@ -954,6 +955,7 @@ describe("room codes", () => {
expect(takeClientLaunchBootstrap()).toEqual({
accessToken: "a".repeat(32),
launchedByClient: true,
+ presentation: null,
});
expect(replaceState).toHaveBeenCalledWith(
null,
@@ -965,8 +967,50 @@ describe("room codes", () => {
expect(takeClientLaunchBootstrap()).toEqual({
accessToken: null,
launchedByClient: true,
+ presentation: null,
});
});
+
+ it.each([
+ { lang: "zh", vis: false, theme: "light" },
+ { lang: "en", vis: true, theme: null },
+ ] as const)("carries launcher presentation across origins: %j", (presentation) => {
+ const target = new URL(clientLaunchURL(
+ "https://site.example/?room=9527#piik-client=1&client-access=a%2Bb%26c%3Fd%3De&retained=yes",
+ presentation,
+ ));
+ const replaceState = vi.fn();
+ vi.stubGlobal("window", {
+ location: target,
+ history: { state: null, replaceState },
+ });
+
+ expect(target.origin).toBe("https://site.example");
+ expect(takeClientLaunchBootstrap()).toEqual({
+ accessToken: "a+b&c?d=e",
+ launchedByClient: true,
+ presentation,
+ });
+ expect(replaceState).toHaveBeenCalledWith(null, "", "/?room=9527#retained=yes");
+ });
+
+ it.each([
+ "piik-lang=zh&piik-mode=text&piik-theme=light",
+ "piik-client=1&piik-lang=other&piik-mode=text&piik-theme=light",
+ "piik-client=1&piik-lang=zh&piik-mode=other&piik-theme=light",
+ "piik-client=1&piik-lang=zh&piik-mode=text&piik-theme=other",
+ ])("ignores invalid presentation without losing App access: %s", (fragment) => {
+ const replaceState = vi.fn();
+ vi.stubGlobal("window", {
+ location: { hash: `#${fragment}&client-access=${"a".repeat(32)}`, pathname: "/", search: "" },
+ history: { state: null, replaceState },
+ });
+ expect(takeClientLaunchBootstrap()).toMatchObject({
+ accessToken: "a".repeat(32),
+ presentation: null,
+ });
+ expect(replaceState).toHaveBeenCalledWith(null, "", "/");
+ });
});
describe("client signaling recovery policy", () => {
diff --git a/tests/connection-details.test.ts b/tests/connection-details.test.ts
index bfdef9d0..78d01148 100644
--- a/tests/connection-details.test.ts
+++ b/tests/connection-details.test.ts
@@ -2,45 +2,8 @@ import { describe, expect, it } from "vitest";
import {
formatPacketLossPercent,
- qualityLimitationSummary,
} from "../src/client/components/connection-details.ts";
-import {
- EMPTY_METRICS,
- type PeerSnapshot,
- type QualityWarningKind,
-} from "../src/client/types.ts";
-
-function snapshot(
- qualityWarning: string | null,
- qualityWarningKind: QualityWarningKind | null = null,
-): PeerSnapshot {
- return {
- peerId: "viewer-1",
- connectionId: "connection-1",
- connectionState: "connected",
- iceConnectionState: "connected",
- metrics: { ...EMPTY_METRICS, qualityLimitationReason: "bandwidth" },
- error: null,
- qualityWarning,
- qualityWarningKind,
- };
-}
-
describe("progressive connection details", () => {
- it("keeps one debounced quality warning outside the details panel", () => {
- expect(
- qualityLimitationSummary([
- snapshot(null),
- snapshot("当前连接带宽受限,画质已自动降低", "bandwidth"),
- snapshot("编码性能受限,画质已自动降低", "cpu"),
- ]),
- ).toEqual({
- message: "当前连接带宽受限,画质已自动降低",
- kind: "bandwidth",
- });
- expect(qualityLimitationSummary([snapshot(null)])).toBeNull();
- });
-
it("formats interval packet loss without inventing unknown values", () => {
expect(formatPacketLossPercent(1.25, "未知")).toBe("1.3%");
expect(formatPacketLossPercent(0, "未知")).toBe("0.0%");
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 04deb929..7915db0f 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+import { initialLanguage, rememberLanguage } from "../site/assets/language.js";
import {
getTitleFrames,
@@ -15,6 +16,51 @@ describe("copy catalog", () => {
setCopy({ lang: "zh", vis: false });
});
+ it.each([
+ ["zh-CN", "zh:false"],
+ ["zh-TW", "zh:false"],
+ ["en-US", "en:false"],
+ ["ja-JP", "en:false"],
+ [undefined, "en:false"],
+ ])("uses the primary system language on first use: %s", async (language, expected) => {
+ vi.resetModules();
+ vi.stubGlobal("navigator", { language });
+ const [{ useCopy }, { createElement }, { renderToStaticMarkup }] = await Promise.all([
+ import("../src/client/ui/copy.ts"),
+ import("react"),
+ import("react-dom/server"),
+ ]);
+ function Selection() {
+ const { lang, vis } = useCopy();
+ return `${lang}:${vis}`;
+ }
+ expect(renderToStaticMarkup(createElement(Selection))).toBe(expected);
+ });
+
+ it.each([
+ ["zh", "text", "zh:false"],
+ ["en", "vis", "en:true"],
+ ])("keeps an explicit %s/%s choice over the system default", async (lang, mode, expected) => {
+ vi.resetModules();
+ vi.stubGlobal("navigator", { language: "ja-JP" });
+ vi.stubGlobal("window", {
+ localStorage: {
+ getItem: (key: string) => key === "piik:ui-lang" ? lang : mode,
+ },
+ addEventListener: () => {},
+ });
+ const [{ useCopy }, { createElement }, { renderToStaticMarkup }] = await Promise.all([
+ import("../src/client/ui/copy.ts"),
+ import("react"),
+ import("react-dom/server"),
+ ]);
+ function Selection() {
+ const { lang, vis } = useCopy();
+ return `${lang}:${vis}`;
+ }
+ expect(renderToStaticMarkup(createElement(Selection))).toBe(expected);
+ });
+
it("renders zh and en for every key", () => {
const zh = t("zh", "join.title");
expect(zh).toBe("加入房间");
@@ -31,9 +77,6 @@ describe("copy catalog", () => {
it("interpolates variables", () => {
expect(t("zh", "host.title", { name: "阿舟" })).toBe("阿舟 的屏幕");
- expect(t("en", "host.onlineCount", { n: "4", max: "20" })).toBe(
- "4 / 20 online",
- );
expect(t("zh", "viewer.title", { name: "$&" })).toBe("$& 的屏幕");
});
@@ -81,3 +124,31 @@ describe("copy catalog", () => {
expect(documentElement.lang).toBe("zh-CN");
});
});
+
+describe("website language", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it.each([
+ ["zh-TW", null, "", "zh-CN"],
+ ["en-US", null, "", "en"],
+ ["ja-JP", null, "", "en"],
+ ["ja-JP", "zh-CN", "", "zh-CN"],
+ ["zh-CN", "zh-CN", "?lang=en", "en"],
+ ])("resolves system, saved and linked language: %s/%s/%s", (language, saved, search, expected) => {
+ vi.stubGlobal("navigator", { language });
+ vi.stubGlobal("location", { search });
+ vi.stubGlobal("localStorage", { getItem: () => saved });
+ expect(initialLanguage()).toBe(expected);
+ });
+
+ it("uses the system default when storage is unavailable", () => {
+ vi.stubGlobal("navigator", { language: "zh-CN" });
+ vi.stubGlobal("location", { search: "" });
+ vi.stubGlobal("localStorage", {
+ getItem: () => { throw new Error("blocked"); },
+ setItem: () => { throw new Error("blocked"); },
+ });
+ expect(initialLanguage()).toBe("zh-CN");
+ expect(() => rememberLanguage("en")).not.toThrow();
+ });
+});
diff --git a/tests/fixtures/mirror-releases.json b/tests/fixtures/mirror-releases.json
new file mode 100644
index 00000000..41abf68b
--- /dev/null
+++ b/tests/fixtures/mirror-releases.json
@@ -0,0 +1,25 @@
+[
+ {
+ "tag_name": "v1.9.0",
+ "target_commitish": "cccccccccccccccccccccccccccccccccccccccc",
+ "prerelease": false,
+ "body": "Release notes.\n\n<!-- piik-source: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->\n"
+ },
+ {
+ "tag_name": "v1.10.0",
+ "target_commitish": "cccccccccccccccccccccccccccccccccccccccc",
+ "prerelease": false,
+ "body": "Release notes.\n\n<!-- piik-source: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->\n"
+ },
+ {
+ "tag_name": "v2.0.0",
+ "prerelease": true,
+ "body": "Incomplete upload.\n\n<!-- piik-source: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->\n"
+ },
+ {
+ "tag_name": "v3.0.0",
+ "target_commitish": "cccccccccccccccccccccccccccccccccccccccc",
+ "prerelease": false,
+ "body": "Missing original source identity."
+ }
+]
diff --git a/tests/fixtures/wire-samples.json b/tests/fixtures/wire-samples.json
index 56600fd5..85352bfc 100644
--- a/tests/fixtures/wire-samples.json
+++ b/tests/fixtures/wire-samples.json
@@ -14,7 +14,7 @@
"persistentNativeEdgeDegradedWindows": 3,
"maxDisplayNameCodePoints": 24,
"defaultViewerDisplayName": "观众",
- "defaultHostDisplayNamePrefix": "分享者",
+ "defaultHostDisplayNamePrefix": "房主",
"minViewerPasswordLength": 1,
"maxViewerPasswordLength": 64,
"defaultEndpointMediaCopyCapacity": 2,
diff --git a/tests/host-page-notice.test.ts b/tests/host-page-notice.test.ts
index 42155262..41f2f3e0 100644
--- a/tests/host-page-notice.test.ts
+++ b/tests/host-page-notice.test.ts
@@ -77,27 +77,15 @@ describe("sourceSwitchNotice", () => {
sourceSwitchNotice({
failedPeerCount: 0,
sfuReplaced: false,
- sfuWarning: null,
}),
).toBe("SFU 分享来源未切换成功,正在恢复观看连接");
});
- it("surfaces an SFU sender warning after a successful replacement", () => {
- expect(
- sourceSwitchNotice({
- failedPeerCount: 1,
- sfuReplaced: true,
- sfuWarning: "浏览器改写了 SFU 发送参数",
- }),
- ).toBe("浏览器改写了 SFU 发送参数;部分观看者正在重新连接");
- });
-
it("reports success only when every active route replacement succeeded", () => {
expect(
sourceSwitchNotice({
failedPeerCount: 0,
sfuReplaced: true,
- sfuWarning: null,
}),
).toBe("分享来源已切换");
});
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index d5787964..ae41e012 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -531,8 +531,8 @@ describe("HostPeer source replacement", () => {
await expect(peer.start()).resolves.toBe(false);
- expect(updates.at(-1)?.error).toBe("创建连接失败");
- expect(updates.at(-1)?.error).not.toContain("createOffer failed");
+ // The snapshot carries a copy key, so raw WebRTC text cannot leak.
+ expect(updates.at(-1)?.error).toEqual({ key: "host.err.createConnection" });
});
it("offers only advertised VP8 and repair codecs", async () => {
@@ -658,7 +658,7 @@ describe("HostPeer source replacement", () => {
expect(FakePeerConnection.latest!.createOfferCallCount).toBe(0);
expect(FakePeerConnection.latest!.localDescription).toBeNull();
- expect(updates.at(-1)?.error).toBe("当前浏览器无法使用支持的视频编码");
+ expect(updates.at(-1)?.error).toEqual({ key: "host.err.codecUnsupported" });
});
it("fails before creating an offer when VP8 is unavailable", async () => {
@@ -681,7 +681,7 @@ describe("HostPeer source replacement", () => {
expect(FakePeerConnection.latest!.createOfferCallCount).toBe(0);
expect(FakePeerConnection.latest!.localDescription).toBeNull();
- expect(updates.at(-1)?.error).toBe("当前浏览器无法使用支持的视频编码");
+ expect(updates.at(-1)?.error).toEqual({ key: "host.err.codecUnsupported" });
});
it("fails before creating an offer when codec preference setup fails", async () => {
@@ -696,7 +696,7 @@ describe("HostPeer source replacement", () => {
expect(FakePeerConnection.latest!.createOfferCallCount).toBe(0);
expect(FakePeerConnection.latest!.localDescription).toBeNull();
- expect(updates.at(-1)?.error).toBe("当前浏览器无法使用支持的视频编码");
+ expect(updates.at(-1)?.error).toEqual({ key: "host.err.codecUnsupported" });
});
it("applies STUN-only ICE configuration at creation and update", () => {
@@ -1040,9 +1040,6 @@ describe("HostPeer source replacement", () => {
expect(peer.getSnapshot().audioSenderParameters?.appliedMaxBitrate).toBe(
128_000,
);
- expect(peer.getSnapshot().qualityWarning).toContain(
- "应用音频发送参数失败",
- );
await expect(
peer.updateProfile({
@@ -1051,7 +1048,6 @@ describe("HostPeer source replacement", () => {
}),
).resolves.toBe(true);
expect(audioSender.getParameters().encodings[0]?.maxBitrate).toBe(192_000);
- expect(peer.getSnapshot().qualityWarning).toBeNull();
});
it("keeps rapid audio ceiling changes last-wins", async () => {
@@ -1226,13 +1222,11 @@ describe("HostPeer source replacement", () => {
});
it("continues queued profile updates after initial configuration rejects", async () => {
- const updates: PeerSnapshot[] = [];
const peer = createPeer(
createStream(
createTrack("video", "video"),
createTrack("audio", "audio"),
),
- (snapshot) => updates.push(snapshot),
);
const starting = peer.start();
@@ -1241,11 +1235,6 @@ describe("HostPeer source replacement", () => {
await expect(starting).resolves.toBe(true);
await acceptPeerAnswer(peer);
- const failureWarning = updates.find((snapshot) =>
- snapshot.qualityWarning?.startsWith("应用发送参数失败"),
- )?.qualityWarning;
- expect(failureWarning).toBe("应用发送参数失败");
- expect(failureWarning).not.toContain("setParameters failed");
await expect(
peer.updateProfile(QUALITY_PROFILES["1080p60"]),
).resolves.toBe(true);
@@ -1603,95 +1592,6 @@ describe("HostPeer source replacement", () => {
});
});
- it("explains a sustained browser quality limitation without changing settings", async () => {
- const updates: PeerSnapshot[] = [];
- const peer = createPeer(
- createStream(createTrack("video", "video"), null),
- (snapshot) => updates.push(snapshot),
- );
- await expect(peer.start()).resolves.toBe(true);
- await acceptPeerAnswer(peer);
- const connection = FakePeerConnection.latest!;
- const sender = connection.senders[0]!;
- connection.statsReports.push(
- sendStatsReport({
- bytesSent: 1_000_000,
- framesEncoded: 30,
- timestamp: 1_000,
- qualityLimitationReason: "bandwidth",
- }),
- sendStatsReport({
- bytesSent: 1_500_000,
- framesEncoded: 60,
- timestamp: 2_000,
- qualityLimitationReason: "bandwidth",
- }),
- sendStatsReport({
- bytesSent: 2_000_000,
- framesEncoded: 90,
- timestamp: 3_000,
- qualityLimitationReason: "bandwidth",
- }),
- sendStatsReport({
- bytesSent: 2_500_000,
- framesEncoded: 120,
- timestamp: 4_000,
- qualityLimitationReason: "none",
- }),
- );
-
- const sample = async (): Promise<void> => {
- const updateCount = updates.length;
- statsCallbacks[0]!();
- await vi.waitFor(() => expect(updates.length).toBeGreaterThan(updateCount));
- };
- await sample();
- await sample();
- expect(updates.at(-1)?.qualityWarning).toBeNull();
- await sample();
- expect(updates.at(-1)?.qualityWarning).toBe(
- "当前连接带宽受限,画质已自动降低",
- );
- expect(updates.at(-1)?.qualityWarningKind).toBe("bandwidth");
- expect(sender.setParameters).toHaveBeenCalledTimes(2);
-
- await sample();
- expect(updates.at(-1)?.qualityWarning).toBeNull();
- expect(updates.at(-1)?.qualityWarningKind).toBeNull();
- expect(sender.setParameters).toHaveBeenCalledTimes(2);
- });
-
- it("does not expose an unknown browser quality-limitation value", async () => {
- const updates: PeerSnapshot[] = [];
- const peer = createPeer(
- createStream(createTrack("video", "video"), null),
- (snapshot) => updates.push(snapshot),
- );
- await expect(peer.start()).resolves.toBe(true);
- const connection = FakePeerConnection.latest!;
- for (const timestamp of [1_000, 2_000, 3_000]) {
- connection.statsReports.push(
- sendStatsReport({
- bytesSent: timestamp * 1_000,
- framesEncoded: timestamp / 10,
- timestamp,
- qualityLimitationReason: "browser-internal-sentinel",
- }),
- );
- }
-
- for (let index = 0; index < 3; index += 1) {
- const updateCount = updates.length;
- statsCallbacks[0]!();
- await vi.waitFor(() => expect(updates.length).toBeGreaterThan(updateCount));
- }
-
- expect(updates.at(-1)?.qualityWarning).toBe(
- "浏览器持续报告未分类的画质限制",
- );
- expect(updates.at(-1)?.qualityWarningKind).toBe("other");
- });
-
it("rolls the first sender back when the second replacement fails", async () => {
const oldVideo = createTrack("video", "old-video");
const oldAudio = createTrack("audio", "old-audio");
@@ -2125,8 +2025,13 @@ describe("ViewerRelay downstream ownership", () => {
);
relay.activateChildren(7, ["native-a", "native-b"]);
- prepared.events.onUpdate({ ...nativeSnapshot(prepared.peer), error: "late" });
- expect(relay.getSnapshot("native-b")?.error).toBe("late");
+ prepared.events.onUpdate({
+ ...nativeSnapshot(prepared.peer),
+ error: { key: "host.err.serverError" },
+ });
+ expect(relay.getSnapshot("native-b")?.error).toEqual({
+ key: "host.err.serverError",
+ });
relay.dispose();
});
diff --git a/tests/host-quality-ownership.test.ts b/tests/host-quality-ownership.test.ts
index af68a5c2..d840e1ba 100644
--- a/tests/host-quality-ownership.test.ts
+++ b/tests/host-quality-ownership.test.ts
@@ -8,8 +8,10 @@ import {
type QualitySettings,
} from "../src/client/media/quality";
import { NativeSenderPeer } from "../src/client/native/native-sender-peer";
+import { NativeCompatibilityError } from "../src/client/native/client";
import { reconcileBoundedMediaChildren } from "../src/client/webrtc/media-assignment";
import { debugError, debugEvent, debugOperation } from "../src/client/lib/debug";
+import { hostActionErrorNotice } from "../src/client/pages/host-page-notices";
// Exercise the actual page owners without mounting capture hardware or a Browser.
const source = ts.createSourceFile("HostPage.tsx", readFileSync(
@@ -20,7 +22,7 @@ const owners = new Set(["changeQuality", "commitQuality", "handleSignalMessage",
"acquireNativeClient", "requestSharing", "startNativeShare", "startBrowserNativeIngress",
"ownNativeClient", "discardNativeClient", "releaseUnusedNativeClient", "closeCaptureSourcePicker",
"openCaptureSourcePicker", "startSharing", "beginRoomMutation", "finishRoomMutation",
- "startPeer", "reconcileHostChildren"]);
+ "startPeer", "reconcileHostChildren", "setNoticeError", "endSharing"]);
const functions: string[] = [];
function collect(node: ts.Node): void {
if (ts.isFunctionDeclaration(node) && node.name && owners.has(node.name.text)) {
@@ -61,7 +63,7 @@ function fixture(launchedByClient = true) {
stopReceive: vi.fn(async () => undefined), stopShare: vi.fn(async () => undefined) };
const route = { updateProfile: vi.fn(async () => true), resyncAuthoritative: vi.fn(async (): Promise<void> => undefined) };
const state = {
- debugError, debugEvent, debugOperation,
+ debugError, debugEvent, debugOperation, NativeCompatibilityError,
launchedByClient, NativeClient: { connect: vi.fn(async (): Promise<typeof client | null> => null) },
nativeClientConnectRef: ref<Promise<typeof client | null> | null>(null),
ownNativeClient: vi.fn(), setJoiningRoom: vi.fn(), startSharing: vi.fn(), openCaptureSourcePicker: vi.fn(),
@@ -109,6 +111,8 @@ function fixture(launchedByClient = true) {
const start = context.startSharing;
const startChild = context.startPeer;
const openPicker = context.openCaptureSourcePicker;
+ const writeNoticeError = context.setNoticeError;
+ context.setNoticeError = state.setNoticeError;
context.startSharing = state.startSharing;
context.startPeer = state.startPeer;
context.openCaptureSourcePicker = state.openCaptureSourcePicker;
@@ -118,6 +122,8 @@ function fixture(launchedByClient = true) {
releaseUnused: context.releaseUnusedNativeClient as () => void,
disposeNative: context.disposeNativeShare as (expectedShare?: string) => void,
start: () => start( { kind: "native", client, target: {}, audio: false, path: {} }) as Promise<void>,
+ startBrowser: () => start({ kind: "browser" }) as Promise<void>,
+ writeNoticeError,
discover: context.acquireNativeClient as () => Promise<typeof client | null>,
requestShare: context.requestSharing as () => void,
startNative: () => context.startNativeShare(1, "share", { client, target: {}, audio: false, path: {} }) as Promise<unknown>,
@@ -130,6 +136,60 @@ function fixture(launchedByClient = true) {
}
describe("Host quality ownership", () => {
+ it.each(["browser", "app-browser", "native"])("keeps %s capture cancellation in the television status", async (entry) => {
+ const current = fixture(entry !== "browser");
+ const denied = new DOMException("private capture detail", "NotAllowedError");
+ const setNoticeValue = vi.fn();
+ Object.assign(current.context, {
+ phase: "idle", setNoticeValue, setNoticeError: current.writeNoticeError,
+ readableError: hostActionErrorNotice,
+ captureDisplay: vi.fn(async () => { throw denied; }),
+ });
+ current.activeGenerationRef.current = null;
+ current.nativeShareGenerationRef.current = null;
+ current.client.startShare.mockRejectedValue(denied);
+ await (entry === "native" ? current.start() : current.startBrowser());
+ expect(setNoticeValue).toHaveBeenCalledExactlyOnceWith({
+ kind: "text", text: hostActionErrorNotice(denied, "capture"),
+ target: "television", comic: "warning",
+ });
+ expect(current.setPhase).toHaveBeenLastCalledWith("error");
+ expect(current.createRoom).not.toHaveBeenCalled();
+ expect(current.roomMutationRef.current).toBeNull();
+ });
+
+ it("keeps a rejected source change as operation feedback while the current share stays live", async () => {
+ const current = fixture();
+ const denied = new DOMException("private capture detail", "NotAllowedError");
+ const setNoticeValue = vi.fn();
+ Object.assign(current.context, {
+ setNoticeValue, setNoticeError: current.writeNoticeError,
+ readableError: hostActionErrorNotice,
+ });
+ current.client.replaceShareSource.mockRejectedValue(denied);
+ await current.switchSource();
+ expect(setNoticeValue).toHaveBeenCalledExactlyOnceWith({
+ kind: "text", text: hostActionErrorNotice(denied, "source"),
+ target: "operation", comic: "warning",
+ });
+ expect(current.setPhase).not.toHaveBeenCalled();
+ expect(current.track.stop).not.toHaveBeenCalled();
+ });
+
+ it.each([null, "warning"])("keeps the share ending reason and tone together in the television: %s", (comic) => {
+ const current = fixture();
+ const setNoticeValue = vi.fn();
+ current.context.setNoticeValue = setNoticeValue;
+ current.generationRef.current = 1;
+ current.context.endSharing({ key: "host.shareEnded" }, false, comic);
+ expect(setNoticeValue).toHaveBeenCalledExactlyOnceWith({
+ kind: "key", key: "host.shareEnded", vars: undefined,
+ target: "television", comic,
+ });
+ expect(current.setPhase).toHaveBeenLastCalledWith("ended");
+ expect(current.activeGenerationRef.current).toBeNull();
+ });
+
it("retains connecting children during reconciliation and rebuilds them after reauthentication", async () => {
const current = fixture(false);
current.nativeClientRef.current = null;
@@ -188,6 +248,45 @@ describe("Host quality ownership", () => {
expect(current.openCaptureSourcePicker).toHaveBeenCalledTimes(2);
});
+ it("shows App incompatibility in the picker and clears it on a successful refresh", async () => {
+ const current = fixture();
+ current.nativeClientRef.current = null;
+ current.nativeShareGenerationRef.current = null;
+ current.NativeClient.connect.mockRejectedValueOnce(new NativeCompatibilityError(8));
+ await current.openPicker();
+ expect(current.setNativeSources).toHaveBeenLastCalledWith({ kind: "incompatible" });
+ expect(current.nativeClientConnectRef.current).toBeNull();
+ expect(current.nativeClientRef.current).toBeNull();
+ expect(current.client.sources).not.toHaveBeenCalled();
+ current.NativeClient.connect.mockResolvedValue(current.client);
+ await current.openPicker();
+ expect(current.NativeClient.connect).toHaveBeenCalledTimes(2);
+ expect(current.setNativeSources).toHaveBeenLastCalledWith(expect.objectContaining({ kind: "ready" }));
+ current.closePicker();
+ });
+
+ it("ignores a cancelled discovery mismatch after another picker owns a compatible App", async () => {
+ const current = fixture();
+ current.nativeClientRef.current = null;
+ current.nativeShareGenerationRef.current = null;
+ const discovery = deferred<void>();
+ current.NativeClient.connect.mockReturnValueOnce(discovery.promise.then(() => {
+ throw new NativeCompatibilityError(8);
+ }));
+ const obsolete = current.openPicker();
+ await vi.waitFor(() => expect(current.NativeClient.connect).toHaveBeenCalledOnce());
+ current.closePicker();
+ current.NativeClient.connect.mockResolvedValue(current.client);
+ await current.openPicker();
+ current.setNativeSources.mockClear();
+ discovery.resolve();
+ await obsolete;
+ expect(current.setNativeSources).not.toHaveBeenCalled();
+ expect(current.client.close).not.toHaveBeenCalled();
+ expect(current.nativeClientRef.current).toBe(current.client);
+ current.closePicker();
+ });
+
it("fails the full startup before room creation when App retires during cleanup", async () => {
const current = fixture();
current.context.phase = "idle";
diff --git a/tests/media-failure.test.ts b/tests/media-failure.test.ts
new file mode 100644
index 00000000..bf4e630b
--- /dev/null
+++ b/tests/media-failure.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import { setCopy, t, type Copy, type CopyKey } from "../src/client/ui/copy.ts";
+import {
+ resolveMediaFailure,
+ type MediaFailure,
+} from "../src/client/ui/media-failure.ts";
+
+// Only the language and the resolver are read; a switch re-renders callers.
+const copy = (lang: "zh" | "en"): Pick<Copy, "lang" | "t"> => ({
+ lang,
+ t: (key: CopyKey, vars?: Record<string, string>) => t(lang, key, vars),
+});
+
+describe("resolveMediaFailure", () => {
+ afterEach(() => {
+ setCopy({ lang: "zh", vis: false });
+ });
+
+ it("renders a fact in the copy context language, not the stored locale", () => {
+ setCopy({ lang: "zh" });
+ const failure: MediaFailure = { key: "host.fail.connection" };
+
+ expect(resolveMediaFailure(failure, copy("zh"))).toBe(
+ t("zh", "host.fail.connection"),
+ );
+ expect(resolveMediaFailure(failure, copy("en"))).toBe(
+ t("en", "host.fail.connection"),
+ );
+ });
+
+ it("fills the params slot from copy keys", () => {
+ const failure: MediaFailure = {
+ key: "host.warn.senderPartial",
+ paramKeys: ["host.warn.param.maxBitrate", "host.warn.param.maxFramerate"],
+ };
+
+ const text = resolveMediaFailure(failure, copy("en"));
+
+ expect(text).toContain(t("en", "host.warn.param.maxBitrate"));
+ expect(text).toContain(t("en", "host.warn.param.maxFramerate"));
+ expect(text).not.toContain("{params}");
+ });
+
+ it("renders every failure in a list and nothing for none", () => {
+ const text = resolveMediaFailure(
+ [{ key: "host.fail.sfuSwitch" }, { key: "host.fail.sfuParams" }],
+ copy("en"),
+ );
+
+ expect(text).toContain(t("en", "host.fail.sfuSwitch"));
+ expect(text).toContain(t("en", "host.fail.sfuParams"));
+ expect(resolveMediaFailure(null, copy("en"))).toBeNull();
+ expect(resolveMediaFailure([], copy("en"))).toBeNull();
+ });
+
+ it("interpolates literal variables", () => {
+ expect(
+ resolveMediaFailure(
+ { key: "host.warn.audioRewritten", vars: { kbps: "96" } },
+ copy("en"),
+ ),
+ ).toBe(t("en", "host.warn.audioRewritten", { kbps: "96" }));
+ });
+});
diff --git a/tests/media-status.test.ts b/tests/media-status.test.ts
new file mode 100644
index 00000000..806d0010
--- /dev/null
+++ b/tests/media-status.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vitest";
+import {
+ INITIAL_VIEWER_PRESENTATION_STATE,
+ deriveViewerPresentation,
+ reduceViewerPresentation,
+ type ViewerPresentationAction,
+} from "../src/client/media/viewer-presentation";
+import { deriveHostStatus, deriveViewerStatus, peerConnectionStatus } from "../src/client/ui/media-status";
+
+const playingActions: ViewerPresentationAction[] = [
+ { type: "access", access: "ready" },
+ { type: "host", host: "online" },
+ { type: "signal", signal: "connected" },
+ { type: "route", revision: 1, phase: "active", kind: "p2p" },
+ { type: "media-bound", generation: 1, revision: 1 },
+ { type: "frame-presented", generation: 1, revision: 1, proofEpoch: 0 },
+];
+const presentation = (...extra: ViewerPresentationAction[]) => deriveViewerPresentation(
+ [...playingActions, ...extra].reduce(reduceViewerPresentation, INITIAL_VIEWER_PRESENTATION_STATE),
+);
+
+describe("media status projection", () => {
+ it("annotates quality without masking playback, and releases stale warnings", () => {
+ const current = presentation();
+ const limited = deriveViewerStatus(current, "connected", { reason: "bandwidth", fresh: true });
+ expect(limited.television.tone).toBe("warn");
+ expect(limited.overlay).toBeNull();
+ expect(limited.titleFrameKey).toBe("viewerActive");
+ expect(limited.connection.tone).toBe("live");
+ for (const observation of [{ reason: "none", fresh: true }, { reason: "bandwidth", fresh: false }] as const) {
+ const result = deriveViewerStatus(current, "connected", observation);
+ expect(result.television.tone).toBe("live");
+ expect(result.quality.tone).toBe(observation.fresh ? "live" : "off");
+ expect(result.titleMarker).toBeNull();
+ }
+ });
+
+ it("separates signaling recovery from media loss and keeps failure above quality", () => {
+ const signaling = deriveViewerStatus(presentation({ type: "signal", signal: "reconnecting" }), "reconnecting");
+ expect(signaling.connection.tone).toBe("warn");
+ expect(signaling.television.tone).toBe("live");
+ expect(signaling.overlay).toBeNull();
+ expect(signaling.activity.labelKey).toBe("viewer.msg.playing");
+ expect(signaling.notice?.comic).toBe("signal-recovering");
+ const failed = deriveViewerStatus(presentation({ type: "route-status", revision: 1, state: "failed" }), "connected", { reason: "cpu", fresh: true });
+ expect(failed.television.tone).toBe("bad");
+ expect(failed.overlay?.mode).toBe("status");
+ expect(failed.titleFrameKey).toBe("viewerUnavailable");
+ expect(failed.connection.tone).toBe("live");
+ const tapToPlay = deriveViewerStatus(presentation({ type: "autoplay-blocked", generation: 1, revision: 1 }), "connected");
+ expect(tapToPlay.titleFrameKey).toBe("viewerReady");
+ });
+
+ it("does not turn transient ICE loss or intentional retirement into failure", () => {
+ expect(peerConnectionStatus("disconnected").tone).toBe("warn");
+ expect(peerConnectionStatus("failed").tone).toBe("bad");
+ expect(peerConnectionStatus("closed").tone).toBe("off");
+ });
+
+ it.each(["reconnecting", "failed"] as const)("shows media recovery only on the television: %s", (connection) => {
+ const result = deriveViewerStatus(presentation({ type: "connection", revision: 1, connection }), "connected");
+ expect(result.television).toMatchObject({
+ tone: "warn", icon: "refresh", labelKey: "viewer.notice.mediaRecovering",
+ });
+ expect(result.notice).toBeNull();
+ expect(result.overlay).toBeNull();
+ expect(result.connection.tone).toBe("live");
+ const recovered = deriveViewerStatus(presentation({ type: "connection", revision: 1, connection: "connected" }), "connected");
+ expect(recovered.television.labelKey).toBe("viewer.msg.playing");
+ expect(recovered.notice).toBeNull();
+ });
+
+ it("keeps the independent Host availability notice alongside a current picture", () => {
+ const result = deriveViewerStatus(presentation({ type: "host", host: "offline" }), "connected");
+ expect(result.television.labelKey).toBe("viewer.msg.playing");
+ expect(result.notice?.labelKey).toBe("viewer.notice.hostOffline");
+ expect(result.overlay).toBeNull();
+ });
+
+ it("keeps Host source activity separate from signaling and ignores a previous share's pause", () => {
+ const sharing = deriveHostStatus({ phase: "live", paused: false, signal: "reconnecting", roomReady: true });
+ expect(sharing.television.tone).toBe("live");
+ expect(sharing.connection.tone).toBe("warn");
+ expect(sharing.titleFrameKey).toBe("hostActive");
+ const failed = deriveHostStatus({ phase: "error", paused: true, signal: "connected", roomReady: true });
+ expect(failed.television.tone).toBe("bad");
+ expect(failed.connection.tone).toBe("live");
+ expect(failed.titleFrameKey).toBe("hostUnavailable");
+ });
+});
diff --git a/tests/native-capture-selection.test.ts b/tests/native-capture-selection.test.ts
index c732e182..7734feba 100644
--- a/tests/native-capture-selection.test.ts
+++ b/tests/native-capture-selection.test.ts
@@ -1,8 +1,9 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it } from "vitest";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { CaptureSourcePicker } from "../src/client/components/living/CaptureSourcePicker";
+import { setCopy, t } from "../src/client/ui/copy";
import {
defaultNativeCapturePath,
@@ -28,6 +29,24 @@ function target(
describe("native capture source selection", () => {
const game = target("My Game", "1");
+ afterEach(() => setCopy({ lang: "en", vis: true }));
+
+ it.each(["en", "zh", "vis"] as const)("keeps Browser capture reachable with an actionable App mismatch in %s", (mode) => {
+ const lang = mode === "zh" ? "zh" : "en";
+ setCopy({ lang, vis: mode === "vis" });
+ const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {
+ nativeSources: { kind: "incompatible" },
+ initialTab: "browser",
+ onBrowser: () => {}, onNative: () => {}, onPreview: async () => null,
+ onRefresh: () => {}, onCancel: () => {},
+ }));
+ expect(html).toContain(t(lang, "native.incompatible"));
+ expect(html).toContain(`aria-label="${t(lang, "host.sourcePicker.browser")}"`);
+ expect(html).not.toMatch(/data-source-tab="browser"[^>]*disabled=""/);
+ expect(html).not.toContain(t(lang, "host.sourcePicker.empty"));
+ expect(html).toContain('role="status"');
+ expect(html).toContain('tabindex="0"');
+ });
it("uses the complete window identity as the UI key", () => {
expect(nativeCaptureTargetKey(game)).toBe("window:1:10:123456");
diff --git a/tests/native-client.test.ts b/tests/native-client.test.ts
index cdc5fb95..8cdd3479 100644
--- a/tests/native-client.test.ts
+++ b/tests/native-client.test.ts
@@ -1,11 +1,14 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { NativeClient, notifyNativePresentation } from "../src/client/native/client";
+import { discoverNativeHealth, NativeClient, NativeCompatibilityError, notifyNativePresentation } from "../src/client/native/client";
import { DEFAULT_QUALITY_SETTINGS } from "../src/shared/protocol";
import {
nativeEventSchema,
nativeHealthSchema,
+ NATIVE_CLIENT_PROTOCOL,
+ NATIVE_CLIENT_PORT_START,
+ NATIVE_CLIENT_PORT_END,
nativeCaptureTargetSchema,
shareSourceReplacedResponseSchema,
shareStartedResponseSchema,
@@ -19,6 +22,80 @@ afterEach(() => {
});
describe("native App private wire", () => {
+ const health = {
+ protocol: NATIVE_CLIENT_PROTOCOL,
+ service: "piik-client",
+ port: NATIVE_CLIENT_PORT_START,
+ instanceToken: "a".repeat(43),
+ nativeMedia: { video: true, hardwareH264: true },
+ };
+
+ it.each([NATIVE_CLIENT_PROTOCOL - 1, NATIVE_CLIENT_PROTOCOL + 1])(
+ "reports observed Piik App protocol %s without opening control or presentation",
+ async (protocol) => {
+ vi.stubGlobal("window", { setTimeout, clearTimeout });
+ const socket = vi.fn();
+ vi.stubGlobal("WebSocket", socket);
+ const fetcher = vi.fn(async (url: string) => url === `http://127.0.0.1:${health.port}/health`
+ ? new Response(JSON.stringify({ ...health, protocol }))
+ : new Response(null, { status: 403 }));
+ vi.stubGlobal("fetch", fetcher);
+ await expect(NativeClient.connect()).rejects.toMatchObject({
+ name: "NativeCompatibilityError", actualProtocol: protocol,
+ });
+ await expect(notifyNativePresentation("en", new AbortController().signal))
+ .rejects.toBeInstanceOf(NativeCompatibilityError);
+ expect(socket).not.toHaveBeenCalled();
+ expect(fetcher.mock.calls.every(([url]) => url.endsWith("/health"))).toBe(true);
+ expect(fetcher).toHaveBeenCalledTimes(2 * (NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1));
+ },
+ );
+
+ it("prefers a compatible App on a later port after observing an incompatible App", async () => {
+ vi.stubGlobal("window", { setTimeout, clearTimeout });
+ const fetcher = vi.fn(async (url: string) => {
+ const port = Number(new URL(url).port);
+ return new Response(JSON.stringify({ ...health, port,
+ protocol: port === health.port ? NATIVE_CLIENT_PROTOCOL + 1 : NATIVE_CLIENT_PROTOCOL,
+ }));
+ });
+ vi.stubGlobal("fetch", fetcher);
+ await expect(discoverNativeHealth()).resolves.toMatchObject({
+ protocol: NATIVE_CLIENT_PROTOCOL, port: NATIVE_CLIENT_PORT_START + 1,
+ });
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ });
+
+ it("identifies an incompatible App even when that protocol uses different token or media metadata", async () => {
+ vi.stubGlobal("window", { setTimeout, clearTimeout });
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
+ ...health, protocol: NATIVE_CLIENT_PROTOCOL + 1,
+ instanceToken: { format: "different-protocol" }, nativeMedia: "different-protocol",
+ }))));
+ await expect(NativeClient.connect()).rejects.toMatchObject({
+ name: "NativeCompatibilityError", actualProtocol: NATIVE_CLIENT_PROTOCOL + 1,
+ });
+ });
+
+ it("treats denied, absent and malformed endpoints as ordinary Browser-only operation", async () => {
+ vi.stubGlobal("window", { setTimeout, clearTimeout });
+ const malformed = [
+ { ...health, service: "another-service" },
+ { ...health, protocol: "8" },
+ { ...health, instanceToken: "invalid" },
+ { ...health, nativeMedia: { video: "yes" } },
+ { ...health, protocol: 8, port: NATIVE_CLIENT_PORT_END },
+ ];
+ let responseIndex = 0;
+ vi.stubGlobal("fetch", vi.fn(async () => {
+ const body = malformed[responseIndex++];
+ if (body) return new Response(JSON.stringify(body));
+ if (responseIndex % 2 === 0) return new Response(null, { status: 403 });
+ throw new TypeError("Network unavailable");
+ }));
+ await expect(NativeClient.connect()).resolves.toBeNull();
+ });
+
it("notifies only the current presentation request after App discovery", async () => {
vi.stubGlobal("window", {
setTimeout: globalThis.setTimeout,
@@ -129,7 +206,7 @@ describe("native App private wire", () => {
expect(intentional).not.toHaveBeenCalled();
});
- it("keeps public discovery capability-only", () => {
+ it("accepts descriptive health extensions and treats absent media features as unavailable", () => {
expect(
nativeHealthSchema.parse({
protocol: 9,
@@ -147,7 +224,7 @@ describe("native App private wire", () => {
).toMatchObject({ nativeMedia: { processAudio: false } });
expect(
nativeHealthSchema.safeParse({
- protocol: 7,
+ protocol: NATIVE_CLIENT_PROTOCOL,
service: "piik-client",
port: 39_721,
instanceToken: "a".repeat(43),
@@ -160,7 +237,21 @@ describe("native App private wire", () => {
},
adapters: ["private"],
}).success,
- ).toBe(false);
+ ).toBe(true);
+ expect(nativeHealthSchema.parse({
+ ...health, futureDescription: "ignored", nativeMedia: { video: true, futureFeature: true },
+ })).toEqual({
+ ...health, nativeMedia: {
+ video: true, processAudio: false, systemAudio: false, hardwareH264: false, softwareVP8: false,
+ },
+ });
+ expect(nativeHealthSchema.parse({ ...health, nativeMedia: undefined }).nativeMedia)
+ .toEqual({ video: false, processAudio: false, systemAudio: false, hardwareH264: false, softwareVP8: false });
+ for (const invalid of [
+ { protocol: 0 }, { protocol: 9.5 }, { protocol: Number.MAX_SAFE_INTEGER + 1 },
+ { service: "other" }, { port: NATIVE_CLIENT_PORT_END + 1 }, { instanceToken: "short" },
+ { nativeMedia: { softwareVP8: "true" } }, { nativeMedia: null },
+ ]) expect(nativeHealthSchema.safeParse({ ...health, ...invalid }).success).toBe(false);
});
it("keeps 64-bit Windows identities as exact decimal strings", () => {
diff --git a/tests/native-media-ingress.test.ts b/tests/native-media-ingress.test.ts
index ea9ecfec..e34950e7 100644
--- a/tests/native-media-ingress.test.ts
+++ b/tests/native-media-ingress.test.ts
@@ -28,7 +28,7 @@ function snapshot(connectionState: RTCPeerConnectionState): PeerSnapshot {
return {
peerId: "ingress-peer", connectionId: "ingress-connection", connectionState,
iceConnectionState: "connected", metrics: { ...EMPTY_METRICS }, error: null,
- senderParameters: null, audioSenderParameters: null, qualityWarning: null, qualityWarningKind: null,
+ senderParameters: null, audioSenderParameters: null,
};
}
diff --git a/tests/participant-motion.test.ts b/tests/participant-motion.test.ts
new file mode 100644
index 00000000..fc057d60
--- /dev/null
+++ b/tests/participant-motion.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { participantMotion, participantMotionPhase } from "../src/client/components/living/participant-motion";
+
+describe("participant gestures", () => {
+ const identity = "779594c8-a92c-48d9-918f-a7d0befa46d1";
+ it("joins the same UUID's current gesture after a later mount or full cycle", () => {
+ const now = 1_800_000_000_000;
+ const { duration } = participantMotion(identity);
+ const firstView = participantMotionPhase(identity, now);
+ const laterView = participantMotionPhase(identity, now + 1357);
+ expect(laterView).toBe((firstView + 1357) % duration);
+ expect(participantMotionPhase(identity, now + duration * 100)).toBe(firstView);
+ });
+
+ it("spreads a full roster across independent, quiet cadences", () => {
+ const roster = Array.from({ length: 21 }, (_, index) => participantMotion(`b59ad8e2-30d1-4a67-a01c-${String(index).padStart(12, "0")}`));
+ expect(new Set(roster.map(({ duration, offset }) => `${duration}:${offset}`)).size).toBe(21);
+ expect(roster.every(({ duration, lean, gaze }) => duration >= 42_000 && duration <= 59_002
+ && Math.abs(lean) <= 3 && Math.abs(gaze) <= 1.5)).toBe(true);
+ const phases = roster.map(({ duration, offset }) => ((1_800_000_000_000 + offset) % duration) / duration);
+ expect(new Set(phases.map((phase) => Math.floor(phase * 10))).size).toBeGreaterThanOrEqual(7);
+ });
+});
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index c188f265..092d0f68 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -19,6 +19,7 @@ import {
replaceRoomRequestSchema,
roomAccessUpdateRequestSchema,
roomAccessUpdateResponseSchema,
+ runtimeCapabilitiesSchema,
serverMessageSchema,
viewerPasswordSchema,
} from "../src/shared/protocol.js";
@@ -33,6 +34,25 @@ const qualitySettings = {
degradationPreference: "maintain-resolution",
} as const;
+describe("runtime capabilities", () => {
+ it("defaults missing capabilities off and ignores unknown descriptors", () => {
+ expect(runtimeCapabilitiesSchema.parse({})).toEqual({ sfu: false, natPrediction: false });
+ expect(runtimeCapabilitiesSchema.parse({ sfu: true, extra: { enabled: true } }))
+ .toEqual({ sfu: true, natPrediction: false });
+ expect(runtimeCapabilitiesSchema.parse({ natPrediction: true, SFU: true }))
+ .toEqual({ sfu: false, natPrediction: true });
+ expect(runtimeCapabilitiesSchema.parse({ sfu: true, natPrediction: true }))
+ .toEqual({ sfu: true, natPrediction: true });
+ });
+
+ it("rejects malformed known capabilities and non-object responses", () => {
+ for (const value of [null, [], true, { sfu: null }, { sfu: "true" },
+ { natPrediction: null }, { natPrediction: 1 }]) {
+ expect(runtimeCapabilitiesSchema.safeParse(value).success).toBe(false);
+ }
+ });
+});
+
const qualitySettingsWithAudio = {
...qualitySettings,
screenAudioQuality: "music",
diff --git a/tests/publish-release.test.ts b/tests/publish-release.test.ts
new file mode 100644
index 00000000..de7700a0
--- /dev/null
+++ b/tests/publish-release.test.ts
@@ -0,0 +1,230 @@
+import { createHash } from "node:crypto";
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+const { command, notes } = vi.hoisted(() => ({
+ command: vi.fn<(program: string, args: string[]) => string>(), notes: vi.fn<() => string>(),
+}));
+vi.mock("node:child_process", () => ({ execFileSync: command }));
+vi.mock("../scripts/release-notes.mjs", () => ({ releaseNotes: notes }));
+
+const directory = mkdtempSync(join(tmpdir(), "piik-publisher-"));
+const version = "v1.0.1", revision = "a".repeat(40);
+const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex");
+for (const target of ["server", "windows-amd64", "linux-amd64", "darwin-arm64"]) {
+ const artifact = `${target}.tar.gz`;
+ writeFileSync(join(directory, artifact), target);
+ writeFileSync(join(directory, `${target}.release.json`), JSON.stringify({
+ schema: 2, version, revision, artifact, artifactSha256: hash(target),
+ ...(target === "server" ? { manifest: "server.manifest.tsv", manifestSha256: hash("manifest") } : { target }),
+ }));
+ if (target === "server") writeFileSync(join(directory, "server.manifest.tsv"), "manifest");
+ else writeFileSync(join(directory, `${artifact}.sha256`), `${hash(target)} ${artifact}\n`);
+}
+afterAll(() => rmSync(directory, { recursive: true, force: true }));
+
+const completeAssets = readdirSync(directory).map((name) => ({ name, state: "uploaded" }));
+type Release = { tag_name: string; target_commitish: string; draft: boolean;
+ prerelease: boolean; assets: typeof completeAssets };
+const release = (draft: boolean): Release => ({
+ tag_name: version, target_commitish: revision, draft, prerelease: false, assets: completeAssets,
+});
+
+describe("Gitee mirror publication", () => {
+ const marker = `<!-- piik-source: ${revision} -->`;
+ const api = "https://gitee.com/api/v5/repos/TNTcraftHIM/Piik";
+ const download = `https://gitee.com/TNTcraftHIM/Piik/releases/download/${version}/`;
+ const sourceAssets = readdirSync(directory).map((name) => {
+ const bytes = readFileSync(join(directory, name));
+ return { name, size: bytes.length, digest: `sha256:${hash(bytes)}`, state: "uploaded" };
+ });
+ async function mirror(options: { existing?: "pending" | "published" | "unknown"; corrupt?: boolean;
+ wrongSource?: boolean; wrongDigest?: boolean; missing?: boolean } = {}) {
+ const mutations: string[] = [];
+ const attachments = sourceAssets.map(({ name, size }) => ({ name, size, browser_download_url: download + name }));
+ const present = options.existing === "pending" ? attachments.slice(0, 1) : options.missing ? [] : attachments;
+ command.mockReturnValue(JSON.stringify({
+ ...release(false), html_url: `https://github.com/TNTcraftHIM/Piik/releases/tag/${version}`,
+ target_commitish: options.wrongSource ? "b".repeat(40) : revision,
+ assets: options.wrongDigest ? sourceAssets.map((asset) => ({ ...asset, digest: "sha256:wrong" })) : sourceAssets,
+ }));
+ vi.stubEnv("GITEE_TOKEN", "fixture-mirror-token");
+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (input, init) => {
+ const url = String(input);
+ if (url.startsWith(download)) {
+ expect(init?.headers).toBeUndefined();
+ const file = url.slice(download.length);
+ return new Response(options.corrupt ? "corrupt" : readFileSync(join(directory, file)));
+ }
+ expect(init?.headers).toHaveProperty("Authorization", "Bearer fixture-mirror-token");
+ expect(init?.redirect).toBe("error");
+ const path = url.slice(api.length);
+ const method = init?.method ?? "GET";
+ if (method !== "GET") mutations.push(`${method} ${path}`);
+ if (path.startsWith("/releases/tags/")) return options.existing
+ ? Response.json({ id: 42, tag_name: version, body: options.existing === "unknown" ? "unknown" : marker,
+ prerelease: options.existing !== "published" }) : new Response(null, { status: 404 });
+ if (path === "") return Response.json({ private: false, default_branch: "master" });
+ if (path === "/releases" && method === "POST") {
+ const body = JSON.parse(String(init?.body));
+ expect(body.prerelease).toBe(true);
+ expect(body.body).toContain(marker);
+ return Response.json({ ...body, id: 42 });
+ }
+ if (path.includes("/attach_files?") && method === "GET") return Response.json(options.existing ? present : []);
+ if (path.endsWith("/attach_files") && method === "POST") {
+ const file = (init?.body as FormData).get("file") as File;
+ expect(hash(Buffer.from(await file.arrayBuffer()))).toBe(hash(readFileSync(join(directory, file.name))));
+ return Response.json(attachments.find((asset) => asset.name === file.name));
+ }
+ if (path === "/releases/42" && method === "PATCH") {
+ const body = JSON.parse(String(init?.body));
+ expect(body.prerelease).toBe(false);
+ return Response.json({ ...body, id: 42 });
+ }
+ throw new Error(`Unexpected mirror request: ${method} ${path}`);
+ }));
+ const argv = process.argv;
+ const output = vi.spyOn(console, "log").mockImplementation(() => {});
+ process.argv = [process.execPath, "mirror-release.mjs", directory, version, revision];
+ vi.resetModules();
+ let failure: string | undefined;
+ try {
+ const script = "../scripts/mirror-release.mjs";
+ await import(script);
+ } catch (error) {
+ failure = error instanceof Error ? error.message : String(error);
+ } finally {
+ process.argv = argv;
+ output.mockRestore();
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ }
+ return { mutations, failure };
+ }
+
+ it("copies the published bytes, verifies anonymous downloads and marks stable last", async () => {
+ const result = await mirror();
+ expect(result.failure).toBeUndefined();
+ expect(result.mutations[0]).toBe("POST /releases");
+ expect(result.mutations.at(-1)).toBe("PATCH /releases/42");
+ expect(result.mutations.filter((value) => value.endsWith("/attach_files"))).toHaveLength(sourceAssets.length);
+ });
+
+ it("resumes pending uploads and leaves complete stable releases unchanged", async () => {
+ const pending = await mirror({ existing: "pending" });
+ expect(pending.failure).toBeUndefined();
+ expect(pending.mutations.filter((value) => value.endsWith("/attach_files"))).toHaveLength(sourceAssets.length - 1);
+ expect(await mirror({ existing: "published" })).toEqual({ mutations: [], failure: undefined });
+ });
+
+ it.each([{ wrongSource: true }, { wrongDigest: true }, { existing: "unknown" as const }])
+ ("rejects mismatched provenance before mirror writes: %j", async (options) => {
+ const result = await mirror(options);
+ expect(result.failure).toBeDefined();
+ expect(result.mutations).toEqual([]);
+ });
+
+ it("does not publish a corrupt upload or repair a published missing file", async () => {
+ const corrupt = await mirror({ corrupt: true });
+ expect(corrupt.failure).toMatch(/mismatch/);
+ expect(corrupt.mutations).not.toContain("PATCH /releases/42");
+ const incomplete = await mirror({ existing: "published", missing: true });
+ expect(incomplete.failure).toContain("corrected new version");
+ expect(incomplete.mutations).toEqual([]);
+ });
+});
+
+async function publish(releases: Release[], tag: "absent" | "annotated" | "wrong" | "api-error",
+ failureAt?: "notes" | "create") {
+ const mutations: string[][] = [];
+ const copy = "### 更新\n\n- Share `windows` and $literal text.\n";
+ let notesPath: string | undefined;
+ notes.mockImplementation(() => {
+ if (failureAt === "notes") throw new Error("Missing release notes");
+ return copy;
+ });
+ let published = releases.some((item) => item.tag_name === version && !item.draft);
+ command.mockImplementation((_program, args) => {
+ if (args[0] === "release") {
+ mutations.push(args);
+ if (args[1] === "create") {
+ notesPath = args[args.indexOf("--notes-file") + 1];
+ expect(readFileSync(notesPath, "utf8")).toBe(copy);
+ expect(args).not.toContain("--generate-notes");
+ if (failureAt === "create") throw new Error("GitHub create failed");
+ }
+ if (args[1] === "edit") published = true;
+ return "";
+ }
+ if (args[1].includes("/matching-refs/")) {
+ if (tag === "api-error") throw new Error("GitHub lookup failed");
+ return JSON.stringify(tag === "absent" && !published ? [] : [{
+ ref: `refs/tags/${version}`, object: tag === "annotated"
+ ? { type: "tag", sha: "c".repeat(40) }
+ : { type: "commit", sha: tag === "wrong" ? "b".repeat(40) : revision },
+ }]);
+ }
+ if (args[1].includes("/git/tags/")) return JSON.stringify({ object: { type: "commit", sha: revision } });
+ if (args[1].includes("/releases?")) return releases.map((item) => JSON.stringify(item)).join("\n");
+ throw new Error(`Unexpected command: ${args.join(" ")}`);
+ });
+ const argv = process.argv;
+ const exited = Symbol("successful exit");
+ const exit = vi.spyOn(process, "exit").mockImplementation(() => { throw exited; });
+ const output = vi.spyOn(process.stdout, "write").mockReturnValue(true);
+ process.argv = [process.execPath, "publish-release.mjs", directory, version, revision];
+ vi.resetModules();
+ let failure: string | undefined;
+ try {
+ const script = "../scripts/publish-release.mjs";
+ await import(script);
+ } catch (error) {
+ if (error !== exited) failure = error instanceof Error ? error.message : String(error);
+ } finally {
+ process.argv = argv;
+ exit.mockRestore();
+ output.mockRestore();
+ if (notesPath) expect(existsSync(notesPath)).toBe(false);
+ }
+ return { failure, mutations };
+}
+
+describe("publisher recovery", () => {
+ it.each(["wrong", "api-error"] as const)("stops before mutations for %s tag lookup", async (tag) => {
+ const result = await publish([release(true)], tag);
+ expect(result.failure).toMatch(/different source revision|lookup failed/);
+ expect(result.mutations).toEqual([]);
+ });
+
+ it("accepts annotated tags and preserves a newer stable release when resuming an older draft", async () => {
+ const result = await publish([release(true), { ...release(false), tag_name: "v1.1.0" }], "annotated");
+ expect(result.failure).toBeUndefined();
+ expect(result.mutations.find((args) => args[1] === "edit")).toContain("--latest=false");
+ });
+
+ it("creates a new release without a pre-existing tag and verifies the resulting tag", async () => {
+ const result = await publish([], "absent");
+ expect(result.failure).toBeUndefined();
+ expect(result.mutations.find((args) => args[1] === "create")).toContain(revision);
+ expect(result.mutations.find((args) => args[1] === "edit")).toContain("--latest=true");
+ });
+
+ it("rejects missing public copy before writes and removes temporary notes after a failed create", async () => {
+ expect(await publish([], "absent", "notes")).toEqual({ failure: "Missing release notes", mutations: [] });
+ const failed = await publish([], "absent", "create");
+ expect(failed.failure).toBe("GitHub create failed");
+ expect(failed.mutations).toHaveLength(1);
+ expect(failed.mutations[0][1]).toBe("create");
+ });
+
+ it("leaves complete published releases unchanged and rejects incomplete published releases", async () => {
+ const complete = await publish([release(false)], "annotated");
+ expect(complete).toEqual({ failure: undefined, mutations: [] });
+ const incomplete = await publish([{ ...release(false), assets: completeAssets.slice(1) }], "annotated");
+ expect(incomplete.failure).toContain("publish a new version");
+ expect(incomplete.mutations).toEqual([]);
+ });
+});
diff --git a/tests/quality.test.ts b/tests/quality.test.ts
index b56486f4..51797b4d 100644
--- a/tests/quality.test.ts
+++ b/tests/quality.test.ts
@@ -331,9 +331,10 @@ describe("realtime quality controls", () => {
appliedMaxBitrate: 96_000,
mismatch: true,
});
- expect(audioSenderParameterWarning(readback)).toBe(
- "浏览器将音频码率上限改写为 96 kbps",
- );
+ expect(audioSenderParameterWarning(readback)).toEqual({
+ key: "host.warn.audioRewritten",
+ vars: { kbps: "96" },
+ });
});
it("does not mutate prior audio parameters when setParameters fails", async () => {
@@ -379,9 +380,14 @@ describe("realtime quality controls", () => {
"scaleResolutionDownBy",
"degradationPreference",
]);
- expect(senderParameterWarning(readback)).toContain("帧率上限");
- expect(senderParameterWarning(readback)).toContain("分辨率缩放");
- expect(senderParameterWarning(readback)).toContain("质量优先级");
+ expect(senderParameterWarning(readback)).toEqual({
+ key: "host.warn.senderPartial",
+ paramKeys: [
+ "host.warn.param.maxFramerate",
+ "host.warn.param.scaleResolutionDownBy",
+ "host.warn.param.degradationPreference",
+ ],
+ });
});
it("reports an applied default scalability mode without claiming a request", async () => {
diff --git a/tests/release-automation.test.ts b/tests/release-automation.test.ts
new file mode 100644
index 00000000..9e9d11ee
--- /dev/null
+++ b/tests/release-automation.test.ts
@@ -0,0 +1,116 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { releaseNotes } from "../scripts/release-notes.mjs";
+
+const planner = fileURLToPath(new URL("../scripts/release-version.mjs", import.meta.url));
+const publisher = fileURLToPath(new URL("../scripts/publish-release.mjs", import.meta.url));
+const sha = (value: string) => createHash("sha256").update(value).digest("hex");
+
+describe("release automation", () => {
+ it("publishes reviewed notes, excludes private history and retains every unreleased phase on retries", () => {
+ const root = mkdtempSync(join(tmpdir(), "piik-release-notes-"));
+ const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
+ const commit = (message: string) => {
+ git("commit", "--allow-empty", "-m", message);
+ return git("rev-parse", "HEAD");
+ };
+ try {
+ git("init", "--quiet", "--initial-branch=main");
+ git("config", "user.name", "Piik fixture");
+ git("config", "user.email", "[email protected]");
+ git("config", "commit.gpgSign", "false");
+ commit("chore: private history without release copy");
+ const launch = commit("feat: launch\n\n## Problem\nInternal discussion\n\n## Release notes\n" +
+ "<!-- Editor guidance -->\n### 开始分享\n\n- 一起玩,一起看。\n\n## Verification\nInternal log");
+ const first = releaseNotes(root, "v1.0.0", launch, "fixture/Piik");
+ expect(first).toContain("### 开始分享\n\n- 一起玩,一起看。");
+ expect(first).toContain(`/tree/${launch}`);
+ expect(first).not.toMatch(/private history|Internal|Editor guidance/);
+ git("tag", "-a", "v1.0.0", "-m", "Launch");
+ expect(releaseNotes(root, "v1.0.0", launch, "fixture/Piik")).toBe(first);
+ commit("fix: repair playback\n\n## Release notes\n- Playback resumes after reconnecting.");
+ const next = commit("feat: add a sharing option\n\n## Release notes\n- Choose a window to share.");
+ const notes = releaseNotes(root, "v1.1.0", next, "fixture/Piik");
+ expect(notes).toContain("- Playback resumes after reconnecting.\n\n- Choose a window to share.");
+ expect(notes).toContain(`/compare/v1.0.0...${next}`);
+ expect(notes).not.toContain("开始分享");
+ git("tag", "v1.1.0");
+ expect(releaseNotes(root, "v1.1.0", next, "fixture/Piik")).toBe(notes);
+ // A checkout may have advanced; generation still uses the requested SHA.
+ expect(releaseNotes(root, "v1.0.0", launch, "fixture/Piik")).toBe(first);
+ for (const section of ["", "## Release notes", "## Release notes\n<!-- Fill in -->\n### Changes",
+ "## Release notes\n- One\n## Release notes\n- Two"]) {
+ git("checkout", "--quiet", "--detach", next);
+ const invalid = commit(`chore: maintenance\n\n${section}`);
+ expect(() => releaseNotes(root, "v1.1.1", invalid, "fixture/Piik")).toThrow("one nonempty");
+ }
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it("plans from immutable tags and all unreleased main changes without editing version files", () => {
+ const root = mkdtempSync(join(tmpdir(), "piik-release-plan-"));
+ const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
+ const plan = () => JSON.parse(execFileSync(process.execPath, [planner, "plan"], { cwd: root, encoding: "utf8" }));
+ try {
+ git("init", "--quiet", "--initial-branch=main");
+ git("config", "user.name", "Piik fixture");
+ git("config", "user.email", "[email protected]");
+ git("config", "commit.gpgSign", "false");
+ git("commit", "--allow-empty", "-m", "chore: initial");
+ expect(plan().version).toBe("v1.0.0");
+ const candidate = JSON.parse(execFileSync(process.execPath, [planner, "build"], {
+ cwd: root, encoding: "utf8", env: { ...process.env, PIIK_BUILD_VERSION: "v1.0.0" },
+ }));
+ expect(candidate).toMatchObject({ version: "v1.0.0", publish: false });
+ expect(git("tag")).toBe("");
+ git("tag", "v1.0.0");
+ // The tag might belong to an unfinished draft: publication can resume.
+ expect(plan()).toMatchObject({ version: "v1.0.0", publish: true });
+ git("commit", "--allow-empty", "-m", "fix: repair playback\n\nExample text:\nfeat: is not this commit's type");
+ expect(plan().version).toBe("v1.0.1");
+ git("commit", "--allow-empty", "-m", "feat(app): add a sharing option");
+ expect(plan().version).toBe("v1.1.0");
+ git("commit", "--allow-empty", "-m", "refactor!: replace the public contract");
+ expect(plan().version).toBe("v2.0.0");
+ expect(git("tag")).toBe("v1.0.0");
+ const reused = spawnSync(process.execPath, [planner, "build"], {
+ cwd: root, encoding: "utf8", env: { ...process.env, PIIK_BUILD_VERSION: "v1.0.0" },
+ });
+ expect(reused.status).not.toBe(0);
+ expect(reused.stderr).toContain("two source revisions");
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it("accepts only a complete same-build package set before contacting GitHub", () => {
+ const root = mkdtempSync(join(tmpdir(), "piik-release-assets-"));
+ const version = "v1.0.0";
+ const revision = "a".repeat(40);
+ const run = () => spawnSync(process.execPath, [publisher, root, version, revision, "--dry-run"], { encoding: "utf8" });
+ try {
+ for (const target of ["server", "windows-amd64", "linux-amd64", "darwin-arm64"]) {
+ const artifact = `${target}.tar.gz`;
+ writeFileSync(join(root, artifact), target);
+ const descriptor = { schema: 2, version, revision, artifact, artifactSha256: sha(target),
+ ...(target === "server" ? { manifest: "server.manifest.tsv", manifestSha256: sha("manifest") } : { target }) };
+ writeFileSync(join(root, `${target}.release.json`), JSON.stringify(descriptor));
+ if (target === "server") writeFileSync(join(root, "server.manifest.tsv"), "manifest");
+ else writeFileSync(join(root, `${artifact}.sha256`), `${sha(target)} ${artifact}\n`);
+ }
+ const complete = run();
+ expect(complete.status, complete.stderr).toBe(0);
+ expect(JSON.parse(complete.stdout).targets).toHaveLength(4);
+ const path = join(root, "windows-amd64.release.json");
+ const original = readFileSync(path, "utf8");
+ writeFileSync(path, JSON.stringify({ ...JSON.parse(original), revision: "b".repeat(40) }));
+ expect(run().stderr).toContain("Release identity mismatch");
+ writeFileSync(path, original);
+ writeFileSync(join(root, "windows-amd64.tar.gz"), "changed bytes");
+ expect(run().stderr).toContain("checksum mismatch");
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+});
diff --git a/tests/release-update.test.ts b/tests/release-update.test.ts
index de927923..3cb6b52c 100644
--- a/tests/release-update.test.ts
+++ b/tests/release-update.test.ts
@@ -1,68 +1,114 @@
import { describe, expect, it, vi } from "vitest";
-
import {
- checkReleaseUpdate,
- DEFAULT_RELEASE_API_URL,
- parseReleaseMetadata,
+ checkReleaseUpdate, DEFAULT_RELEASE_API_URL, MIRROR_RELEASE_API_URL,
+ parseMirrorReleaseMetadata, parseReleaseMetadata, releaseUpdateNotice,
} from "../src/client/lib/release-update";
-
-// The operator checker (cmd/piik-server --check-release, covered by
-// cmd/piik-server/release_test.go) shares this release contract while
-// keeping its runtime boundary independent.
+import mirrorReleases from "./fixtures/mirror-releases.json";
const currentRevision = "a".repeat(40);
const latestRevision = "b".repeat(40);
const release = {
- tag_name: latestRevision,
- html_url: `https://github.com/TNTcraftHIM/Piik/releases/tag/${latestRevision}`,
+ tag_name: "v1.2.0",
+ target_commitish: latestRevision,
+ html_url: "https://github.com/TNTcraftHIM/Piik/releases/tag/v1.2.0",
};
describe("App release update notice", () => {
- it("compares a strict release identity without sending the current revision", async () => {
+ it("checks a release without sending installed identity or credentials", async () => {
const fetchImpl = vi.fn<typeof fetch>(async (input, init) => {
expect(String(input)).toBe(DEFAULT_RELEASE_API_URL);
expect(init?.credentials).toBe("omit");
expect(JSON.stringify(init)).not.toContain(currentRevision);
expect(JSON.stringify(init)).not.toContain("Authorization");
- return new Response(JSON.stringify(release), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
+ return new Response(JSON.stringify(release), { status: 200 });
+ });
+ await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision }, { fetchImpl }))
+ .resolves.toEqual({ version: "v1.2.0", revision: latestRevision,
+ url: release.html_url, kind: "update-available" });
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ["v1.1.0", currentRevision, latestRevision, "update-available"],
+ ["v1.1.0", latestRevision, latestRevision, "update-available"],
+ ["v1.2.0-rc.1", currentRevision, latestRevision, "update-available"],
+ ["v1.2.0", currentRevision, latestRevision, "different-build"],
+ ["v1.2.0", latestRevision, latestRevision, null],
+ ["v1.2.0", currentRevision, null, null],
+ ["v1.10.0", currentRevision, latestRevision, null],
+ ["development", currentRevision, latestRevision, "official-release"],
+ ["development", latestRevision, latestRevision, null],
+ ["development", currentRevision, null, null],
+ ])("compares %s by release precedence, using SHA only to identify builds", (version, revision, remoteRevision, expected) => {
+ expect(releaseUpdateNotice({ version, revision }, {
+ version: "v1.2.0", revision: remoteRevision, url: release.html_url,
+ })?.kind ?? null).toBe(expected);
+ });
+
+ it("does not turn branch names, prereleases or malformed metadata into release identity", async () => {
+ expect(parseReleaseMetadata({ ...release, target_commitish: "main" })?.revision).toBeNull();
+ for (const changed of [
+ { tag_name: "short" },
+ { tag_name: "v1.2.0-rc.1" },
+ { tag_name: "v1.2.0+other" },
+ { html_url: "https://evil.example" },
+ { html_url: "https://[email protected]/TNTcraftHIM/Piik/releases/tag/v1.2.0" },
+ { draft: true },
+ { prerelease: true },
+ ]) expect(parseReleaseMetadata({ ...release, ...changed })).toBeNull();
+ await expect(checkReleaseUpdate({ version: "development", revision: "development" })).resolves.toBeNull();
+ await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision }, {
+ fetchImpl: vi.fn<typeof fetch>(async () => new Response("offline", { status: 503 })),
+ })).resolves.toBeNull();
+ });
+
+ it("uses source provenance and stable precedence when GitHub is unavailable", async () => {
+ const fetchImpl = vi.fn<typeof fetch>(async (input, init) => {
+ if (String(input) === DEFAULT_RELEASE_API_URL) return new Response("offline", { status: 503 });
+ expect(String(input)).toBe(`${MIRROR_RELEASE_API_URL}?per_page=100&page=1&direction=desc`);
+ expect(init?.headers).toEqual({ Accept: "application/json" });
+ expect(init?.credentials).toBe("omit");
+ return Response.json(mirrorReleases);
+ });
+ const current = { version: "v1.9.0", revision: currentRevision };
+ await expect(checkReleaseUpdate(current, { fetchImpl })).resolves.toEqual({
+ kind: "update-available", version: "v1.10.0", revision: latestRevision,
+ url: "https://gitee.com/TNTcraftHIM/Piik/releases/tag/v1.10.0",
+ });
+ await expect(checkReleaseUpdate({ ...current, version: "v2.0.0" }, { fetchImpl })).resolves.toBeNull();
+ });
+
+ it("gives the mirror its own deadline after a primary timeout", async () => {
+ const fetchImpl = vi.fn<typeof fetch>(async (input, init) => {
+ if (String(input) === DEFAULT_RELEASE_API_URL) {
+ return new Promise((_resolve, reject) => init?.signal?.addEventListener("abort", () => reject(new Error("timeout"))));
+ }
+ expect(init?.signal?.aborted).toBe(false);
+ return Response.json(mirrorReleases);
});
+ await expect(checkReleaseUpdate({ version: "v1.0.0", revision: currentRevision }, { fetchImpl, timeoutMs: 10 }))
+ .resolves.toMatchObject({ version: "v1.10.0" });
+ });
- await expect(
- checkReleaseUpdate(currentRevision, { fetchImpl }),
- ).resolves.toEqual({
- revision: latestRevision,
- url: release.html_url,
+ it("finishes mirror pagination and rejects an incomplete list", async () => {
+ const fetchImpl = vi.fn<typeof fetch>(async (input) => {
+ if (String(input) === DEFAULT_RELEASE_API_URL) throw new Error("offline");
+ return Response.json(new URL(String(input)).searchParams.get("page") === "1"
+ ? Array.from({ length: 100 }, () => mirrorReleases[0]) : [mirrorReleases[1]]);
});
- expect(fetchImpl).toHaveBeenCalledTimes(1);
+ const current = { version: "v1.9.0", revision: currentRevision };
+ await expect(checkReleaseUpdate(current, { fetchImpl })).resolves.toMatchObject({ version: "v1.10.0" });
+ fetchImpl.mockImplementation(async (input) => String(input) === DEFAULT_RELEASE_API_URL
+ ? new Response(null, { status: 503 }) : Response.json(Array.from({ length: 100 }, () => mirrorReleases[1])));
+ await expect(checkReleaseUpdate(current, { fetchImpl })).resolves.toBeNull();
});
- it("fails closed for unavailable, malformed, and current releases", async () => {
- expect(parseReleaseMetadata({ ...release, tag_name: "short" })).toBeNull();
- expect(parseReleaseMetadata({ ...release, html_url: "https://evil.example" })).toBeNull();
- expect(
- parseReleaseMetadata({
- ...release,
- html_url: `https://[email protected]/TNTcraftHIM/Piik/releases/tag/${latestRevision}`,
- }),
- ).toBeNull();
- expect(parseReleaseMetadata({ ...release, draft: true })).toBeNull();
- await expect(checkReleaseUpdate("development")).resolves.toBeNull();
- await expect(
- checkReleaseUpdate(latestRevision, {
- fetchImpl: vi.fn<typeof fetch>(async () =>
- new Response(JSON.stringify(release), { status: 200 }),
- ),
- }),
- ).resolves.toBeNull();
- await expect(
- checkReleaseUpdate(currentRevision, {
- fetchImpl: vi.fn<typeof fetch>(async () =>
- new Response("offline", { status: 503 }),
- ),
- }),
- ).resolves.toBeNull();
+ it("does not query a mirror after a usable primary result, or accept ambiguous provenance", async () => {
+ const fetchImpl = vi.fn<typeof fetch>(async () => Response.json(release));
+ await expect(checkReleaseUpdate({ version: "v1.2.0", revision: latestRevision }, { fetchImpl })).resolves.toBeNull();
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(parseMirrorReleaseMetadata({ ...mirrorReleases[0], body: mirrorReleases[0].body.repeat(2) })).toBeNull();
+ expect(parseMirrorReleaseMetadata({ ...mirrorReleases[0], prerelease: undefined })).toBeNull();
+ expect(parseMirrorReleaseMetadata({ ...mirrorReleases[0], tag_name: "v1.0.0-beta.1" })).toBeNull();
});
});
diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.ts
index 139abc4f..81e0e3fb 100644
--- a/tests/route-transition.test.ts
+++ b/tests/route-transition.test.ts
@@ -13,6 +13,8 @@ import {
reportActivePeerRouteFailure,
} from "../src/client/media/route-transition.ts";
import { ViewerSfuRoute } from "../src/client/media/viewer-sfu-route.ts";
+import { t } from "../src/client/ui/copy.ts";
+import { resolveMediaFailure } from "../src/client/ui/media-failure.ts";
import {
EMPTY_METRICS,
type ConnectionMetrics,
@@ -422,6 +424,41 @@ describe("minimal route transition contracts", () => {
expect(publishers[1]?.disconnect).not.toHaveBeenCalled();
});
+ it("renders an SFU connection failure in each language without placeholders", async () => {
+ const publisher = createFakePublisher([], "publisher");
+ publisher.connect.mockResolvedValue(false);
+ const route = new HostSfuRoute({
+ getStream: () => ({}) as MediaStream,
+ getProfile: () => QUALITY_PROFILES["720p30"],
+ getVideoCodec: () => "vp8",
+ reconcileChildren: () => undefined,
+ send: () => true,
+ createPublisher: () => ({
+ ...publisher,
+ getFailureStage: () => "connect",
+ }),
+ });
+ route.accept({
+ revision: 1,
+ phase: "prepare",
+ assignment: hostAssignment("publication"),
+ candidate: candidate(1, "viewer_12345678", "sfu"),
+ });
+ await route.acceptConfig(sfuConfig(1, "publication"));
+ const warning = route.getQualityWarning();
+
+ for (const lang of ["en", "zh"] as const) {
+ const text = resolveMediaFailure(warning, {
+ lang,
+ t: (key, vars) => t(lang, key, vars),
+ });
+ expect(text).toBe(t(lang, "host.warn.sfuRecover", {
+ params: t(lang, "host.warn.sfuStage.connect"),
+ }));
+ expect(text).not.toMatch(/\{[^}]+\}/);
+ }
+ });
+
it("changes Host children only after active authority commits", async () => {
const reconciledChildren: string[][] = [];
const route = new HostSfuRoute({
diff --git a/tests/route-tree.test.ts b/tests/route-tree.test.ts
index 1884dcf4..1b4289e7 100644
--- a/tests/route-tree.test.ts
+++ b/tests/route-tree.test.ts
@@ -3,13 +3,39 @@ import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it } from "vitest";
import { RouteTree } from "../src/client/components/living/RouteTree.tsx";
+import { Couch } from "../src/client/components/living/Couch.tsx";
import { participantColor } from "../src/client/components/living/participant-color.ts";
import { topologyLayoutForWidth } from "../src/client/components/living/route-tree-layout.ts";
import { labelParticipantSnapshot } from "../src/client/lib/viewer-presence.ts";
import { setCopy } from "../src/client/ui/copy.ts";
+import { deriveParticipantStatus } from "../src/client/ui/media-status";
afterEach(() => setCopy({ lang: "zh", vis: false }));
+it("keeps presence and readiness available in participant descriptions", () => {
+ setCopy({ lang: "en", vis: true });
+ const render = (online: boolean) => renderToStaticMarkup(createElement(Couch, {
+ view: online ? "viewer" : "host",
+ host: { key: "host", name: "Host name", online, you: !online },
+ entries: [{
+ key: "viewer", name: "Viewer name",
+ status: deriveParticipantStatus({ mediaReady: false, upstream: { kind: "none" } }, true), you: online,
+ }],
+ }));
+ const offline = render(false);
+ expect(offline).toContain('aria-label="Host name · Host · you · Offline"');
+ expect(offline).toContain('class="lr-pawn-led" data-tone="busy"');
+ const online = render(true);
+ expect(online).toContain('aria-label="Host name · Host · Online"');
+ expect(online).toContain('aria-label="Viewer name · you · Routing"');
+ expect(online).not.toContain('class="lr-pawn-led"');
+ expect(online).toContain('is-waiting');
+ setCopy({ vis: false });
+ const textMode = render(true);
+ expect(textMode).toContain('aria-label="Host name · Host · Online"');
+ expect(textMode).toContain('aria-label="Viewer name · you · Routing"');
+});
+
describe("RouteTree", () => {
it("sorts every Viewer by stable peer identity", () => {
const { viewers } = labelParticipantSnapshot([
@@ -223,7 +249,7 @@ describe("RouteTree", () => {
{
role: "host",
peerId: hostPeerId,
- displayName: "👑 (abc123)",
+ displayName: "🎮 (abc123)",
upstream: { kind: "none" },
},
{
@@ -253,7 +279,7 @@ describe("RouteTree", () => {
expect(html).toContain(">abc123</text>");
expect(html).toContain(">def456</text>");
expect(html).toContain(">👤-custom</text>");
- expect(html).not.toContain(">👑 (abc123)</text>");
+ expect(html).not.toContain(">🎮 (abc123)</text>");
expect(html).not.toContain(">👤 (def456)</text>");
expect(html).toContain("scale(0.82)");
});
@@ -399,7 +425,7 @@ describe("RouteTree", () => {
expect(html).not.toContain('aria-label="Alice · 显示连接详情"');
});
- it("gives every reachable depth its own horizontal column", () => {
+ it("keeps every person and parent edge in a full-room relay chain within the panel", () => {
const participants = [
{
role: "host" as const,
@@ -407,7 +433,7 @@ describe("RouteTree", () => {
displayName: "Host",
upstream: { kind: "none" as const },
},
- ...Array.from({ length: 5 }, (_, index) => ({
+ ...Array.from({ length: 20 }, (_, index) => ({
role: "viewer" as const,
peerId: `viewer-${index}`,
displayName: `Viewer ${index}`,
@@ -428,12 +454,17 @@ describe("RouteTree", () => {
);
const width = Number(html.match(/viewBox="0 0 (\d+) /)?.[1]);
- expect(width).toBe(1_520);
- expect(html).toContain(`style="width:${width}px;max-width:none"`);
- expect(
- new Set(
- [...html.matchAll(/translate\(([\d.]+),/g)].map((match) => match[1]),
- ).size,
- ).toBeGreaterThanOrEqual(6);
+ expect(width).toBe(640);
+ expect(html).toContain('class="lr-route is-outline"');
+ expect(html).not.toContain("max-width:none");
+ expect(html.match(/class="lr-route-edge is-p2p"/g)).toHaveLength(20);
+ expect(html.match(/class="lr-person"/g)).toHaveLength(21);
+ const points = [...html.matchAll(/class="lr-route-node[^\"]*" transform="translate\(([\d.]+), ([\d.]+)\)/g)]
+ .map((match) => ({ x: Number(match[1]), y: Number(match[2]) }));
+ expect(new Set(points.map((point) => point.y)).size).toBe(21);
+ expect(points.every((point) => point.x >= 0 && point.x + 40 < width)).toBe(true);
+ for (let index = 0; index < 20; index++) {
+ expect(html).toContain(`Viewer ${index} ← ${index === 0 ? "Host" : `Viewer ${index - 1}`}`);
+ }
});
});
diff --git a/tests/theme.test.ts b/tests/theme.test.ts
index 5b69cd8e..b887bd8d 100644
--- a/tests/theme.test.ts
+++ b/tests/theme.test.ts
@@ -1,4 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+import { readFileSync } from "node:fs";
+import { runInNewContext } from "node:vm";
import { composeDocumentTitle } from "../src/client/ui/document-title.ts";
afterEach(() => {
@@ -24,6 +26,7 @@ describe("theme preference", () => {
localStorage: {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
+ removeItem: (key: string) => values.delete(key),
},
matchMedia: () => ({
matches: dark,
@@ -39,6 +42,7 @@ describe("theme preference", () => {
const theme = await import("../src/client/ui/theme.ts");
theme.initTheme();
expect(dataset.theme).toBe("light");
+ expect(theme.currentThemePreference()).toBeNull();
dark = true;
onChange({ matches: dark });
@@ -48,5 +52,66 @@ describe("theme preference", () => {
expect(values.get("piik:ui-theme")).toBe("light");
onChange({ matches: true });
expect(dataset.theme).toBe("light");
+ expect(theme.currentThemePreference()).toBe("light");
+
+ theme.initTheme(null);
+ expect(values.has("piik:ui-theme")).toBe(false);
+ expect(dataset.theme).toBe("dark");
+ expect(theme.currentThemePreference()).toBeNull();
+ onChange({ matches: false });
+ expect(dataset.theme).toBe("light");
+ });
+
+ it.each([false, true])("applies launch theme with blocked storage=%s", async (blocked) => {
+ const values = new Map([["piik:ui-theme", "dark"]]);
+ const dataset: Record<string, string> = { theme: "dark" };
+ vi.stubGlobal("document", { documentElement: { dataset } });
+ vi.stubGlobal("window", {
+ localStorage: {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ if (blocked) throw new Error("Storage disabled");
+ values.set(key, value);
+ },
+ },
+ matchMedia: () => ({ matches: true, addEventListener: vi.fn() }),
+ });
+
+ const theme = await import("../src/client/ui/theme.ts");
+ theme.initTheme("light");
+ expect(dataset.theme).toBe("light");
+ expect(theme.currentThemePreference()).toBe("light");
+ if (!blocked) expect(values.get("piik:ui-theme")).toBe("light");
+ });
+
+ it("uses the launch theme before first paint, including system and restricted storage", () => {
+ const html = readFileSync(new URL("../index.html", import.meta.url), "utf8");
+ const script = html.match(/<script>([\s\S]*?)<\/script>/)?.[1];
+ expect(script).toBeTruthy();
+ for (const [fragment, expected] of [
+ ["piik-client=1&piik-theme=light", "light"],
+ ["piik-client=1&piik-theme=system", "light"],
+ ["piik-theme=light", "dark"],
+ ["piik-client=1&piik-theme=invalid", "dark"],
+ ]) {
+ const dataset: Record<string, string> = {};
+ runInNewContext(script!, {
+ document: { documentElement: { dataset } },
+ matchMedia: () => ({ matches: false }),
+ location: { hash: `#${fragment}` },
+ localStorage: { getItem: () => "dark" },
+ URLSearchParams,
+ });
+ expect(dataset.theme).toBe(expected);
+ }
+ const dataset: Record<string, string> = {};
+ runInNewContext(script!, {
+ document: { documentElement: { dataset } },
+ matchMedia: () => ({ matches: false }),
+ location: { hash: "#piik-client=1&piik-theme=dark" },
+ localStorage: { getItem: () => { throw new Error("Storage disabled"); } },
+ URLSearchParams,
+ });
+ expect(dataset.theme).toBe("dark");
});
});
diff --git a/tests/viewer-audio.test.ts b/tests/viewer-audio.test.ts
new file mode 100644
index 00000000..f2c5f5eb
--- /dev/null
+++ b/tests/viewer-audio.test.ts
@@ -0,0 +1,186 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ViewerAudio } from "../src/client/media/viewer-audio.ts";
+
+class PlaybackVideo extends EventTarget {
+ volume = 1;
+ muted = false;
+ paused = false;
+ ended = false;
+ srcObject = {};
+}
+
+class AudioStream {
+ constructor(public tracks: MediaStreamTrack[]) {}
+ getAudioTracks(): MediaStreamTrack[] { return this.tracks; }
+}
+
+class PlaybackContext extends EventTarget {
+ static instances: PlaybackContext[] = [];
+ state: AudioContextState = "suspended";
+ destination = {};
+ gain = { gain: { value: 1 }, connect: vi.fn(), disconnect: vi.fn() };
+ sources: Array<{ stream: AudioStream; connect: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> }> = [];
+ resolveResume!: () => void;
+ rejectResume!: () => void;
+ pendingResume = new Promise<void>((resolve, reject) => {
+ this.resolveResume = resolve;
+ this.rejectResume = reject;
+ });
+ resume = vi.fn(() => this.pendingResume);
+ close = vi.fn(() => {
+ this.state = "closed";
+ return Promise.resolve();
+ });
+
+ constructor() {
+ super();
+ PlaybackContext.instances.push(this);
+ }
+
+ createGain() { return this.gain; }
+ createMediaStreamSource(stream: AudioStream) {
+ const source = { stream, connect: vi.fn(), disconnect: vi.fn() };
+ this.sources.push(source);
+ return source;
+ }
+ start() {
+ this.state = "running";
+ this.dispatchEvent(new Event("statechange"));
+ this.resolveResume();
+ }
+}
+
+function audioTrack() {
+ return { enabled: true, stop: vi.fn() } as unknown as MediaStreamTrack;
+}
+
+describe("Viewer local audio", () => {
+ beforeEach(() => {
+ PlaybackContext.instances = [];
+ vi.stubGlobal("AudioContext", PlaybackContext);
+ vi.stubGlobal("MediaStream", AudioStream);
+ });
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("lazily adjusts current audio while pause, mute and track changes remain local", () => {
+ const video = new PlaybackVideo();
+ const srcObject = video.srcObject;
+ const onChange = vi.fn();
+ const audio = new ViewerAudio(video as unknown as HTMLVideoElement, onChange);
+ const firstTrack = audioTrack();
+ const stream = new AudioStream([firstTrack]);
+ audio.bind(stream as unknown as MediaStream);
+ expect(PlaybackContext.instances).toHaveLength(0);
+ audio.setLevel(0.5);
+ expect(video.volume).toBe(0.5);
+ const context = PlaybackContext.instances[0];
+ expect(video.muted).toBe(false);
+ expect(context.gain.gain.value).toBe(0);
+ audio.setLevel(0);
+ expect(video.muted).toBe(true);
+ audio.setLevel(0.5);
+ context.start();
+ expect(video.muted).toBe(true);
+ expect(context.gain.gain.value).toBe(0.5);
+ audio.setLevel(2);
+ expect(PlaybackContext.instances).toHaveLength(1);
+ expect(context.gain.gain.value).toBe(2);
+ expect(audio.snapshot).toEqual({ level: 2, muted: false, boostAvailable: true });
+
+ const nextTrack = audioTrack();
+ stream.tracks = [nextTrack];
+ audio.bind(stream as unknown as MediaStream);
+ expect(context.sources[0].disconnect).toHaveBeenCalledOnce();
+ expect(context.sources[1].stream.tracks).toEqual([nextTrack]);
+ audio.setMuted(true);
+ expect(context.gain.gain.value).toBe(0);
+ audio.setMuted(false);
+ expect(context.gain.gain.value).toBe(2);
+ video.paused = true;
+ video.dispatchEvent(new Event("pause"));
+ expect(context.gain.gain.value).toBe(0);
+ audio.bind(null);
+ expect(context.sources[1].disconnect).toHaveBeenCalledOnce();
+ audio.bind(stream as unknown as MediaStream);
+ expect(context.gain.gain.value).toBe(0);
+ video.paused = false;
+ video.dispatchEvent(new Event("play"));
+ expect(context.gain.gain.value).toBe(2);
+ video.ended = true;
+ video.dispatchEvent(new Event("ended"));
+ expect(context.gain.gain.value).toBe(0);
+ expect(video.srcObject).toBe(srcObject);
+ for (const track of [firstTrack, nextTrack]) {
+ expect(track.enabled).toBe(true);
+ expect(track.stop).not.toHaveBeenCalled();
+ }
+ audio.useNativeControls();
+ expect(audio.snapshot).toEqual({ level: 1, muted: false, boostAvailable: true });
+ expect(video.muted).toBe(false);
+ expect(context.sources[2].disconnect).toHaveBeenCalledOnce();
+ video.volume = 0.65;
+ video.muted = true;
+ video.dispatchEvent(new Event("volumechange"));
+ audio.resume();
+ expect(audio.snapshot).toEqual({ level: 0.65, muted: true, boostAvailable: true });
+ expect(PlaybackContext.instances).toHaveLength(1);
+ audio.dispose();
+ expect(context.close).toHaveBeenCalledOnce();
+ });
+
+ it("falls back to ordinary audio if starting the context fails", async () => {
+ const video = new PlaybackVideo();
+ const audio = new ViewerAudio(video as unknown as HTMLVideoElement, vi.fn());
+ audio.bind(new AudioStream([audioTrack()]) as unknown as MediaStream);
+ audio.setLevel(2);
+ const context = PlaybackContext.instances[0];
+ context.rejectResume();
+ await Promise.resolve();
+ expect(audio.snapshot).toEqual({ level: 1, muted: false, boostAvailable: false });
+ expect(video.muted).toBe(false);
+ expect(context.close).toHaveBeenCalledOnce();
+ audio.setLevel(2);
+ expect(PlaybackContext.instances).toHaveLength(1);
+ expect(audio.snapshot.level).toBe(1);
+ audio.setLevel(0);
+ expect(video.muted).toBe(true);
+ audio.setLevel(0.5);
+ expect(video.muted).toBe(false);
+ expect(audio.snapshot.level).toBe(0.5);
+ expect(PlaybackContext.instances).toHaveLength(1);
+ audio.dispose();
+ });
+
+ it("uses current preferences after resume and ignores completions after disposal", async () => {
+ const video = new PlaybackVideo();
+ const onChange = vi.fn();
+ const audio = new ViewerAudio(video as unknown as HTMLVideoElement, onChange);
+ audio.bind(new AudioStream([audioTrack()]) as unknown as MediaStream);
+ audio.setLevel(2);
+ const context = PlaybackContext.instances[0];
+ audio.setLevel(0.4);
+ audio.setMuted(true);
+ const currentTrack = audioTrack();
+ audio.bind(new AudioStream([currentTrack]) as unknown as MediaStream);
+ context.start();
+ await Promise.resolve();
+ expect(audio.snapshot).toEqual({ level: 0.4, muted: true, boostAvailable: true });
+ expect(context.gain.gain.value).toBe(0);
+ expect(context.sources[0].disconnect).toHaveBeenCalledOnce();
+ expect(context.sources[1].stream.tracks).toEqual([currentTrack]);
+
+ context.state = "suspended";
+ context.pendingResume = new Promise<void>((resolve) => { context.resolveResume = resolve; });
+ audio.resume();
+ audio.dispose();
+ video.volume = 0.75;
+ video.muted = false;
+ onChange.mockClear();
+ context.start();
+ await Promise.resolve();
+ expect(video.volume).toBe(0.75);
+ expect(video.muted).toBe(false);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/viewer-native-client-ownership.test.ts b/tests/viewer-native-client-ownership.test.ts
index b89834e2..9f68e69b 100644
--- a/tests/viewer-native-client-ownership.test.ts
+++ b/tests/viewer-native-client-ownership.test.ts
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
import { createContext, runInContext } from "node:vm";
import ts from "typescript";
import { expect, it, vi } from "vitest";
+import { NativeCompatibilityError } from "../src/client/native/client";
// Exercise the page's connection owner without mounting media or room signaling.
const source = ts.createSourceFile("ViewerPage.tsx", readFileSync(
@@ -65,6 +66,17 @@ it.each([false, true])("retries an absent or rejected App on the next offer: rej
expect(client.close).toHaveBeenCalledOnce();
});
+it("keeps Browser fallback available after an App mismatch and retries on the next offer", async () => {
+ const current = fixture();
+ current.connect.mockRejectedValueOnce(new NativeCompatibilityError(8));
+ await expect(current.acquire()).resolves.toBeNull();
+ const client = control();
+ current.connect.mockResolvedValue(client);
+ await expect(current.acquire()).resolves.toBe(client);
+ expect(current.connect).toHaveBeenCalledTimes(2);
+ current.dispose();
+});
+
it("shares pending discovery and rediscovers after the idle App disconnects", async () => {
const current = fixture();
const client = control();
diff --git a/tests/viewer-presentation.test.ts b/tests/viewer-presentation.test.ts
index 98d6ea8c..e608ffdb 100644
--- a/tests/viewer-presentation.test.ts
+++ b/tests/viewer-presentation.test.ts
@@ -652,6 +652,45 @@ describe("Viewer presentation reducer", () => {
).toBe(true);
});
+ it("re-arms observation without changing playback and accepts the next fresh frame", () => {
+ const playing = apply(
+ { type: "access", access: "ready" },
+ { type: "signal", signal: "connected" },
+ { type: "host", host: "online" },
+ { type: "route", revision: 3, phase: "active", kind: "p2p" },
+ { type: "media-bound", generation: 2, revision: 3 },
+ { type: "frame-presented", generation: 2, proofEpoch: 0, revision: 3 },
+ );
+ expect(deriveViewerPresentation(reduceViewerPresentation(playing, {
+ type: "autoplay-blocked", generation: 2, revision: 3,
+ }))).toMatchObject({
+ stage: "needs-play", hasCurrentFrame: true,
+ });
+ const cases = [
+ playing,
+ reduceViewerPresentation(playing, { type: "connection", revision: 3, connection: "reconnecting" }),
+ reduceViewerPresentation(playing, { type: "route-status", revision: 3, state: "failed" }),
+ reduceViewerPresentation(playing, { type: "host", host: "paused" }),
+ reduceViewerPresentation(playing, { type: "media-bound", generation: 3, revision: 3 }),
+ ];
+ for (const before of cases) {
+ const media = before.media!;
+ const rearmed = reduceViewerPresentation(before, {
+ type: "frame-proof-rearm", generation: media.generation,
+ });
+ expect(deriveViewerPresentation(rearmed)).toEqual(deriveViewerPresentation(before));
+ const frame = {
+ type: "frame-presented" as const,
+ generation: media.generation, revision: media.boundAtRevision, proofEpoch: media.proofEpoch,
+ };
+ expect(reduceViewerPresentation(rearmed, frame)).toBe(rearmed);
+ const fresh = reduceViewerPresentation(rearmed, { ...frame, proofEpoch: media.proofEpoch + 1 });
+ expect(fresh.connection).toBe("connected");
+ expect(fresh.routeStatus).toBeNull();
+ expect(deriveViewerPresentation(fresh).stage).toBe(before.host === "paused" ? "host-paused" : "playing");
+ }
+ });
+
it("demotes the current frame when an exact route terminally fails", () => {
const playing = apply(
{ type: "access", access: "ready" },
diff --git a/tests/viewer-quality-evidence.test.ts b/tests/viewer-quality-evidence.test.ts
index d88b826d..7c12a6eb 100644
--- a/tests/viewer-quality-evidence.test.ts
+++ b/tests/viewer-quality-evidence.test.ts
@@ -1,10 +1,12 @@
import { describe, expect, it } from "vitest";
+import { deriveParticipantStatus } from "../src/client/ui/media-status";
import type {
ClientMessage,
ServerMessage,
ViewerQualityEvidenceMetrics,
} from "../src/shared/protocol.ts";
+import { VIEWER_QUALITY_EVIDENCE_EXPIRY_MS } from "../src/shared/protocol.ts";
import {
classifyHostViewerQualityEvidence,
freshViewerQualityEvidence,
@@ -113,6 +115,25 @@ function serverEvidence(
}
describe("viewer quality evidence", () => {
+ it("annotates ready participants only with current receive-window freezes", () => {
+ const evidence = serverEvidence({ metrics: { freezeCountDelta: 1, freezeDurationMsDelta: 300 } });
+ const participant = { mediaReady: true, upstream: evidence.upstream };
+ const first = presentViewerQualityEvidence(null, evidence, 0);
+ expect(deriveParticipantStatus(participant, true, first).labelKey).toBe("state.peer.stuttering");
+ expect(deriveParticipantStatus({ ...participant, mediaReady: false }, true, first).tone).toBe("busy");
+ expect(deriveParticipantStatus({ ...participant, mediaReady: false }, false, first).tone).toBe("off");
+ expect(deriveParticipantStatus({ ...participant, upstream: { kind: "sfu" } }, true, first).tone).toBe("live");
+ expect(deriveParticipantStatus(participant, true,
+ refreshViewerQualityEvidencePresentation(first, VIEWER_QUALITY_EVIDENCE_EXPIRY_MS)).tone).toBe("live");
+ for (const count of [0, null]) {
+ const next = presentViewerQualityEvidence(first, serverEvidence({ sequence: 1,
+ metrics: { freezeCountDelta: count, freezeDurationMsDelta: count },
+ }), 2_000);
+ expect(next.evidence.metrics.freezeCountDelta).toBe(count);
+ expect(deriveParticipantStatus(participant, true, next).tone).toBe("live");
+ }
+ });
+
it("normalizes only bounded adjacent receive evidence", () => {
expect(qualityEvidenceWindowFromMetrics(receiveMetrics())).toEqual({
windowMs: 2_000,
diff --git a/tsconfig.json b/tsconfig.json
index 682304d8..bee5f412 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,7 +1,7 @@
{
"files": [],
"references": [
- { "path": "./tsconfig.app.json" },
- { "path": "./tsconfig.tools.json" }
+ { "path": "./src" },
+ { "path": "./scripts" }
]
}
diff --git a/tsconfig.tools.json b/tsconfig.tools.json
deleted file mode 100644
index 6b8f76d8..00000000
--- a/tsconfig.tools.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "compilerOptions": {
- "tsBuildInfoFile": "./node_modules/.cache/tsconfig.tools.tsbuildinfo",
- "target": "ES2023",
- "lib": ["ES2023", "DOM", "DOM.Iterable"],
- "module": "ESNext",
- "moduleResolution": "bundler",
- "jsx": "react-jsx",
- "types": ["node", "vitest/globals"],
- "skipLibCheck": true,
- "allowImportingTsExtensions": true,
- "verbatimModuleSyntax": true,
- "moduleDetection": "force",
- "noEmit": true,
- "strict": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true
- },
- "include": [
- "vite.config.ts",
- "vitest.config.ts",
- "scripts/access-privacy-gate.ts",
- "scripts/client-browser-fanout-gate.ts",
- "scripts/client-media-gate.ts",
- "scripts/client-native-host-gate.ts",
- "scripts/embedded-sfu-gate.ts",
- "scripts/embedded-sfu-page.ts",
- "scripts/client-loopback-gate.ts",
- "scripts/client-local-gate.ts",
- "scripts/client-link-gate.ts",
- "scripts/peer-assisted-benchmark.ts",
- "tests"
- ]
-}