mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-21 09:10:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
229070fe19 | ||
|
|
3bfbd2c217 | ||
|
|
481c1ff8ba | ||
|
|
5f6847a373 | ||
|
|
175b5ac171 | ||
|
|
f32f2d43aa | ||
|
|
ba88cdad78 | ||
|
|
0bbb846beb | ||
|
|
c793e0dd78 | ||
|
|
13833e8144 | ||
|
|
d3c1c641b4 | ||
|
|
aeaff3bc88 | ||
|
|
cf005797be | ||
|
|
4b3b31c83d | ||
|
|
a4e25db0f7 | ||
|
|
78c8a56183 | ||
|
|
e2d4944060 | ||
|
|
6c3d3ea2b3 | ||
|
|
e7273f1a02 | ||
|
|
d3efc00902 | ||
|
|
06df7537e0 | ||
|
|
1de8c4ad32 | ||
|
|
278bbdd4fe | ||
|
|
ed40b41e1a | ||
|
|
3dcab584ae | ||
|
|
cfbb799ddc | ||
|
|
9623da7504 | ||
|
|
370b0d3050 | ||
|
|
c847649242 | ||
|
|
38694eb77b | ||
|
|
8c53685590 | ||
|
|
469f68b25d | ||
|
|
7c3412686c | ||
|
|
297c4903fe | ||
|
|
b7367bb129 | ||
|
|
114cdca4ee | ||
|
|
9d7b142129 | ||
|
|
91fafafeff | ||
|
|
d5b9439371 | ||
|
|
3725193e72 | ||
|
|
62c9fb46ae | ||
|
|
9b1890f57c | ||
|
|
68a8b67931 | ||
|
|
d0bda60b9f | ||
|
|
d71b0de056 | ||
|
|
8c7d4f5b72 | ||
|
|
d8793a89a2 | ||
|
|
178670fdab | ||
|
|
715b657153 | ||
|
|
c0353bb050 | ||
|
|
0c1907d868 | ||
|
|
edbf2c6001 | ||
|
|
fa319d0898 | ||
|
|
b0a595fe9c | ||
|
|
b7d250dbac |
@@ -55,3 +55,44 @@ jobs:
|
||||
|
||||
echo "Smoke testing shumai-transcode..."
|
||||
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai-transcode/bin/shumai-transcode-app.js --check
|
||||
|
||||
e2e_video_player:
|
||||
name: E2E (${{ matrix.project }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
project: chromium
|
||||
- os: ubuntu-latest
|
||||
project: firefox
|
||||
# WebKit is the Safari engine; run it on a macOS runner to validate
|
||||
# Safari compatibility.
|
||||
- os: macos-latest
|
||||
project: webkit
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
- name: Install Playwright browser (${{ matrix.project }})
|
||||
run: bunx playwright install --with-deps ${{ matrix.project }}
|
||||
|
||||
- name: Run video player e2e tests
|
||||
run: bun run test:e2e --project=${{ matrix.project }}
|
||||
|
||||
- name: Upload Playwright report
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: playwright-report-${{ matrix.project }}
|
||||
path: playwright-report/
|
||||
retention-days: 7
|
||||
|
||||
@@ -27,12 +27,22 @@ jobs:
|
||||
username: shumaione
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# Log in to Aliyun ACR
|
||||
- name: Log in to Aliyun ACR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com
|
||||
username: njjyl723
|
||||
password: ${{ secrets.ALI_ACR_TOKEN }}
|
||||
|
||||
# Extract metadata (tags, labels) for Docker
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: shumaione/shumai
|
||||
images: |
|
||||
shumaione/shumai
|
||||
crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=ref,event=branch
|
||||
|
||||
@@ -11,3 +11,9 @@ data/
|
||||
*.db
|
||||
*.diff
|
||||
*.orig
|
||||
|
||||
# Playwright
|
||||
/playwright-report/
|
||||
/test-results/
|
||||
/blob-report/
|
||||
/playwright/.cache/
|
||||
|
||||
@@ -90,6 +90,7 @@ Add any additional context, caveats, or follow-up work.
|
||||
- `bun run format`
|
||||
- `bun run typecheck`
|
||||
- `bun run test`
|
||||
- `bun run test:e2e`
|
||||
|
||||
- **Backend Testing Mandate**: Every backend feature, service method, workflow, and activity MUST be accompanied by comprehensive tests. Logic-heavy code without corresponding test coverage is considered incomplete.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#syntax=docker/dockerfile:1.7-labs
|
||||
# Stage 1: Builder
|
||||
FROM oven/bun:1 AS builder
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/introduction">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a>
|
||||
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/introduction">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a> | <a target="_blank" href="README_CN.md">中文</a>
|
||||
</p>
|
||||
|
||||

|
||||
@@ -25,11 +25,16 @@
|
||||
|
||||
#### Shumai Agent
|
||||
|
||||
- **Collaborative AI Chat**: Converse with a context-aware AI agent directly within your project workspace.
|
||||
- **Collaborative AI Chat**: Converse with a context-aware AI agent by using `@mentions` directly within the file's comments area.
|
||||
- **Custom Skills & Tools**: Extend the agent's capabilities by registering custom scripts, tools, and automation skills.
|
||||
- **Isolated Sandbox Execution**: Run agent-submitted scripts securely within a sandboxed environment.
|
||||
- **AI-Powered Metadata Autofill**: Automatically generate tags, descriptions, and custom metadata for new assets using Google Gemini.
|
||||
- **Semantic Search**: Locate assets instantly based on visual or conceptual search queries using vector embeddings.
|
||||
- **AI Metadata Autofill**: Automatically autofill custom metadata for new assets.
|
||||
- **Semantic Search**: Find assets based on visual or conceptual search queries using vector embeddings(Gemini Embedding 2).
|
||||
|
||||
> [!NOTE]
|
||||
> **Media Processing & Storage:** When uploading media, Shumai always preserves and stores your original raw file. For all media types (both images and videos), Shumai creates a 480p WebP poster image to serve as the preview in the file list view. Additionally:
|
||||
> * **For Images:** Shumai generates a high-quality WebP proxy at the exact same resolution as your original file for optimized viewing.
|
||||
> * **For Videos:** It generates at least one proxy video (depending on your transcoding settings), alongside a sprite image and a small preview video (capped at 1600 frames) to enable fast timeline scrubbing and lightning-quick previews.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
<p align="center">
|
||||
<img src="docs/logo-rounded.png" alt="Shumai Logo" width="65" />
|
||||
</p>
|
||||
|
||||
<h1 align="center">Shumai</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>为创意工作打造的开源协作平台。</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://shumai.one/">官方网站</a> | <a target="_blank" href="https://docs.shumai.one/introduction">文档</a> | <a target="_blank" href="https://staging.shumai.one">在线演示</a> | <a target="_blank" href="README.md">English</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
## 功能特性
|
||||
|
||||
- **兼容 S3 与本地存储**:使用本地文件系统或任何兼容 S3 的云存储(AWS S3、Cloudflare R2、阿里云 OSS 等)安全地存储和提供您的创意资产。
|
||||
- **逐帧批注与评论**:直接在视频和图像资产上使用特定帧的绘图工具和带时间戳的评论,提供精确的反馈。
|
||||
- **安全分享与合集**:创建安全的公开分享链接和媒体合集,以便与客户和团队进行协作。
|
||||
- **细粒度访问控制**:使用团队级别和项目级别的基于角色的访问控制来管理访问权限。
|
||||
- **基于 Temporal 的分布式转码**:将占用大量资源的视频转码任务部署到 Temporal Worker上。
|
||||
- **自定义资产元数据**:为媒体文件添加可搜索/编辑的自定义元数据字段。
|
||||
|
||||
#### Shumai 智能体 (Agent)
|
||||
|
||||
- **AI Agent 协作**:通过评论区和 AI 智能体进行交流。
|
||||
- **自定义技能**:通过添加自定义技能来扩展智能体的能力。
|
||||
- **隔离的沙箱执行**:在沙箱环境中安全地运行智能体提交的脚本。
|
||||
- **AI 元数据自动填充**:使用AI为资产自动生填充元数据字段。
|
||||
- **语义搜索**:基于 Gemini Embedding 2 的图片/视频内容搜索。
|
||||
|
||||
> [!NOTE]
|
||||
> **媒体处理与存储说明:** 在上传媒体文件时,Shumai 会始终完整保留并存储您的原始文件。对于所有媒体类型(图片与视频),Shumai 都会统一生成一张 480p 的 WebP 预览图,用作文件列表页预览。此外:
|
||||
> * **图片文件:** Shumai 会额外生成一个与原图分辨率完全一致的 WebP 优化版本。
|
||||
> * **视频文件:** 系统会根据您的转码设置生成至少一个预览版本mp4,同时还会生成一张雪碧图(Sprite)和一个轻量级预览视频(上限 1600 帧),以实现流畅的文件列表页面预览和文件查看页面时间轴快速预览。
|
||||
|
||||
---
|
||||
|
||||
## 安装指南
|
||||
|
||||
以下是使用本地存储运行 Shumai 的快速上手指南。如需了解高级配置(包括 S3 兼容存储配置、Temporal 工作流编排等),请参阅我们的[官方文档](https://docs.shumai.one/getting-started/overview)。
|
||||
|
||||
### 方案一:使用 Docker Compose(推荐)
|
||||
|
||||
使用 Docker Compose 是运行 Shumai 最快的方式。您无需克隆仓库,也不需要手动安装依赖包。请确保电脑上已安装 [Docker](https://docs.docker.com/get-docker/) 和 [Docker Compose](https://docs.docker.com/compose/install/),然后按照以下步骤操作:
|
||||
|
||||
1. 创建并进入一个新目录,用于存放配置文件和数据卷:
|
||||
```bash
|
||||
mkdir shumai && cd shumai
|
||||
|
||||
```
|
||||
|
||||
2. 下载 `docker-compose.yaml` 配置文件:
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.yaml
|
||||
|
||||
```
|
||||
|
||||
|
||||
3. 配置环境变量(可选):
|
||||
* `SHUMAI_SERVER_PORT` 用于控制 Shumai 服务监听的端口,默认值为 `3000`。
|
||||
* 默认情况下,该 Docker Compose 部署会自动启用集成的本地存储。若想切换至外部 S3 兼容存储,请将 `AWS_ENDPOINT_URL_S3` 设置为对应云厂商的 Endpoint URL,并根据需要配置相应的 AWS 凭证和存储桶(Bucket)参数:
|
||||
```
|
||||
AWS_ENDPOINT_URL_S3: S3_ENDPOINT_URL
|
||||
S3_REGION: S3_REGION
|
||||
S3_BUCKET: BUCKET_NAME
|
||||
S3_ACCESS_KEY_ID: ID
|
||||
S3_SECRET_ACCESS_KEY: KEY
|
||||
|
||||
```
|
||||
|
||||
|
||||
* 默认情况下 `AWS_ENDPOINT_URL_S3` 指向 `http://localhost:{SHUMAI_SERVER_PORT}`。如果您使用本地存储,但希望在自定义的主机名或端口上公开访问 Shumai,请务必将 `AWS_ENDPOINT_URL_S3` 修改为浏览器访问该服务时所使用的外部 URL。
|
||||
例如,如果您将 `docker-compose.yaml` 中的端口映射从 `3000:3000` 修改为了 `12345:3000`,且服务部署在 IP 为 `12.34.56.78` 的服务器上,请进行如下设置:
|
||||
```
|
||||
AWS_ENDPOINT_URL_S3: http://12.34.56.78:12345
|
||||
|
||||
```
|
||||
|
||||
|
||||
此地址必须能够从客户端浏览器正常访问,且必须包含对外暴露的实际端口号。
|
||||
|
||||
|
||||
4. 在后台启动所有服务:
|
||||
```bash
|
||||
docker compose up -d
|
||||
|
||||
```
|
||||
|
||||
|
||||
5. 打开浏览器,访问 `http://localhost:3000` 即可开始使用(若是远程部署,请访问 `http://<您的服务器IP>:3000`)。
|
||||
|
||||
### 方案二:通过 NPM / 包管理器安装
|
||||
|
||||
通过 NPM 上的 `@shumai-one/shumai` 进行安装。
|
||||
|
||||
#### 第一步:启动带 pgvector 支持的 PostgreSQL
|
||||
|
||||
Shumai 依赖支持 `pgvector` 扩展的 PostgreSQL 数据库。您可以使用 Docker 快速启动一个预配置好的数据库容器:
|
||||
|
||||
```bash
|
||||
docker run --name shumai_postgres \
|
||||
-e POSTGRES_USER=shumai \
|
||||
-e POSTGRES_PASSWORD=shumai_password \
|
||||
-e POSTGRES_DB=shumai_db \
|
||||
-p 5432:5432 \
|
||||
-d docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
|
||||
```
|
||||
|
||||
#### 第二步:创建工作区目录
|
||||
|
||||
创建一个专属目录用来存放环境配置和媒体文件(媒体文件默认会保存在 `./data` 目录下):
|
||||
|
||||
```bash
|
||||
mkdir shumai && cd shumai
|
||||
|
||||
```
|
||||
|
||||
#### 第三步:安装平台特定系统依赖
|
||||
|
||||
在安装 Shumai 之前,请确保您的宿主机上已经安装了以下系统依赖项:
|
||||
|
||||
| 依赖包 | 功能描述 | Ubuntu/Debian | Fedora | Arch | macOS |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| **ffmpeg** | 媒体转码及元数据提取 | `sudo apt install -y ffmpeg` | `sudo dnf install -y ffmpeg` | `sudo pacman -S --noconfirm ffmpeg` | `brew install ffmpeg` |
|
||||
| **bubblewrap** | 用于安全执行 AI 助手脚本的隔离沙箱环境 | `sudo apt install -y bubblewrap` | `sudo dnf install -y bubblewrap` | `sudo pacman -S --noconfirm bubblewrap` | *无需安装* |
|
||||
| **socat** | 用于沙箱网络桥接的双向套接字中继 | `sudo apt install -y socat` | `sudo dnf install -y socat` | `sudo pacman -S --noconfirm socat` | `brew install socat` |
|
||||
| **ripgrep** | 用于工作区安全策略的高效文本搜索工具 | `sudo apt install -y ripgrep` | `sudo dnf install -y ripgrep` | `sudo pacman -S --noconfirm ripgrep` | `brew install ripgrep` |
|
||||
|
||||
> [!NOTE]
|
||||
> **Ubuntu 24.04+ 用户请注意:** 这些系统版本默认限制了非特权用户命名空间(unprivileged user namespaces)。为了让 `bubblewrap` 和沙箱隔离层正常工作,需要关闭此限制:
|
||||
> ```bash
|
||||
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
>
|
||||
> ```
|
||||
>
|
||||
>
|
||||
> 或者,您也可以专门配置一个 AppArmor 配置文件,为相关二进制文件授予用户命名空间创建(`userns`)权限。
|
||||
|
||||
#### 第四步:全局安装 Shumai
|
||||
|
||||
使用您常用的包管理器进行全局安装:
|
||||
|
||||
```bash
|
||||
# 使用 NPM
|
||||
npm install -g @shumai-one/shumai
|
||||
|
||||
# 使用 PNPM
|
||||
pnpm add -g @shumai-one/shumai
|
||||
|
||||
# 使用 Bun
|
||||
bun add -g @shumai-one/shumai
|
||||
|
||||
```
|
||||
|
||||
#### 第五步:配置环境配置
|
||||
|
||||
在刚才创建的工作区目录(`shumai/`)下新建一个 `.env` 文件,并填入以下配置:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `SHUMAI_SERVER_PORT` 用于设置 Web 服务的启动端口,而 `AWS_ENDPOINT_URL_S3` 供浏览器端构建文件上传链接。
|
||||
> 如果您部署在远程服务器(如 `http://123.456.7.8`)并且做了端口映射(如 Docker 中的 `12345:3000`),请将 `AWS_ENDPOINT_URL_S3` 设置为 `http://123.456.7.8:12345`。
|
||||
|
||||
#### 第六步:启动 Shumai
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Bun 用户特别提示:** 由于发布的包二进制文件包含 `#!/usr/bin/env node` 头部声明(Shebang),直接在终端执行全局命令(例如 `shumai`)默认会通过 Node.js 运行。如果您是用 Bun 安装的并且希望调用 Bun 运行时,请在所有命令前加上 `bun run --bun` 前缀(例如:`bun run --bun shumai`、`bun run --bun shumai -d`、`bun run --bun shumai stop`)。
|
||||
|
||||
在您的工作区目录下执行以下命令启动应用:
|
||||
|
||||
```bash
|
||||
shumai
|
||||
|
||||
```
|
||||
|
||||
您也可以让 Shumai 在后台以守护进程(Daemon)模式运行和管理:
|
||||
|
||||
* **后台模式启动**:
|
||||
```bash
|
||||
shumai -d
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **停止服务**:
|
||||
```bash
|
||||
shumai stop
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **重启服务**:
|
||||
```bash
|
||||
shumai restart
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **查看并跟踪实时日志**:
|
||||
```bash
|
||||
shumai logs
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
启动时,Shumai 会自动执行数据库迁移(Migration)并在 `http://localhost:3000` 拉起 Web 服务。
|
||||
|
||||
---
|
||||
|
||||
### 方案三:源码编译运行(开发环境)
|
||||
|
||||
如果您希望在本地参与 Shumai 的开发,请按以下步骤配置开发环境:
|
||||
|
||||
1. 克隆代码仓库并安装依赖项:
|
||||
```bash
|
||||
git clone [https://github.com/shumaiOne/shumai.git](https://github.com/shumaiOne/shumai.git)
|
||||
cd shumai
|
||||
bun install
|
||||
|
||||
```
|
||||
|
||||
|
||||
2. 启动 `pgvector` 数据库容器(参考**方案二中的第一步**)。
|
||||
3. 参照**方案二中的第五步**,在项目根目录下创建一个 `.env` 文件。
|
||||
4. 执行数据库结构迁移:
|
||||
```bash
|
||||
bun run db:migrate
|
||||
|
||||
```
|
||||
|
||||
|
||||
5. 启动本地开发服务器:
|
||||
```bash
|
||||
bun run dev
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 命令行工具 (CLI)
|
||||
|
||||
Shumai 自带一个功能完备的命令行工具(CLI),支持您直接在终端里高效管理项目、文件夹、资产,批量上传文件/目录,以及快速创建新版本。
|
||||
|
||||
关于 CLI 的安装与详细使用指南,请参阅 [CLI Readme](https://www.google.com/search?q=apps/cli/README.md)。
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -11,7 +11,10 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
"@inlang/paraglide-js": "2.20.0",
|
||||
"@playwright/test": "1.61.1",
|
||||
"@testcontainers/postgresql": "12.0.1",
|
||||
"@testing-library/dom": "10.4.1",
|
||||
"@testing-library/react": "16.3.2",
|
||||
"@types/bun": "1.3.14",
|
||||
"@types/node": "25.9.1",
|
||||
"bun-plugin-pino": "1.5.0",
|
||||
@@ -22,6 +25,7 @@
|
||||
"eslint-plugin-prettier": "5.5.6",
|
||||
"eslint-plugin-react": "7.37.5",
|
||||
"globals": "17.6.0",
|
||||
"happy-dom": "20.10.6",
|
||||
"pino-pretty": "13.1.3",
|
||||
"prisma": "7.8.0",
|
||||
"testcontainers": "12.0.1",
|
||||
@@ -33,7 +37,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -45,7 +49,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -60,7 +64,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -72,7 +76,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -87,7 +91,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.52",
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
@@ -111,7 +115,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@shumai/core": "workspace:*",
|
||||
@@ -125,7 +129,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
@@ -152,7 +156,7 @@
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
"@prisma/adapter-pg": "7.8.0",
|
||||
@@ -168,18 +172,18 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"zod": "4.4.3",
|
||||
},
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -193,7 +197,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.5.0",
|
||||
"@dnd-kit/abstract": "0.4.0",
|
||||
@@ -277,24 +281,20 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "4.3.0",
|
||||
"@tailwindcss/vite": "4.3.0",
|
||||
"@tanstack/router-cli": "1.167.13",
|
||||
"@tanstack/router-plugin": "1.168.14",
|
||||
"@types/react": "19.2.16",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@vitejs/plugin-react": "5.2.0",
|
||||
"autoprefixer": "10.5.0",
|
||||
"postcss": "8.5.15",
|
||||
"tailwindcss": "4.3.0",
|
||||
"tw-animate-css": "1.3.3",
|
||||
"typescript": "6.0.3",
|
||||
"vite": "7.3.5",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
},
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -395,10 +395,6 @@
|
||||
|
||||
"@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA=="],
|
||||
|
||||
"@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw=="],
|
||||
|
||||
"@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q=="],
|
||||
|
||||
"@babel/runtime": ["@babel/runtime@7.29.7", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],
|
||||
|
||||
"@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
|
||||
@@ -761,6 +757,8 @@
|
||||
|
||||
"@pkgr/core": ["@pkgr/core@0.3.6", "", {}, "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA=="],
|
||||
|
||||
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
|
||||
|
||||
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
|
||||
|
||||
"@preact/signals-core": ["@preact/signals-core@1.14.2", "", {}, "sha512-RZHdBj9ZF4n40Rp4jS052EHHjBWf96P9oNdXPfhQTovCuWY9iQn3Gq+gOTJSgBO9A/JBuPfMOWsSX/lIU9Pc/A=="],
|
||||
@@ -941,8 +939,6 @@
|
||||
|
||||
"@reduxjs/toolkit": ["@reduxjs/toolkit@2.12.0", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw=="],
|
||||
|
||||
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.3", "", {}, "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q=="],
|
||||
|
||||
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.61.0", "", { "os": "android", "cpu": "arm" }, "sha512-dnxczajOqt0gesZlN5pGQ1s1imQVrsmCw5G2Ci4oM+0WvNz3pyRnlWrT7McoZIb8VlFwCawdmbWRmxRn7HI+VQ=="],
|
||||
|
||||
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.61.0", "", { "os": "android", "cpu": "arm64" }, "sha512-Bp3JpGP00Vu3f238ivRrjf7z3xSzVPXqCmaJYA9t2c+c8vKYvOzmXF7LkkeUalTEGd6cZcSWe+PFIP3Vy48fRg=="],
|
||||
@@ -1105,8 +1101,6 @@
|
||||
|
||||
"@tailwindcss/postcss": ["@tailwindcss/postcss@4.3.0", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.0", "@tailwindcss/oxide": "4.3.0", "postcss": "^8.5.10", "tailwindcss": "4.3.0" } }, "sha512-Jm05Tjx+9yCLGv5qw1c+84Psds8MnyrEQYCB+FFk2lgGiUjlRqdxke4mVTuYrj2xnVZqKim2Apr5ySuQRYAw/w=="],
|
||||
|
||||
"@tailwindcss/vite": ["@tailwindcss/vite@4.3.0", "", { "dependencies": { "@tailwindcss/node": "4.3.0", "@tailwindcss/oxide": "4.3.0", "tailwindcss": "4.3.0" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-t6J3OrB5Fc0ExuhohouH0fWUGMYL6PTLhW+E7zIk/pdbnJARZDCwjBznFnkh5ynRnIRSI4YjtTH0t6USjJISrw=="],
|
||||
|
||||
"@tanstack/devtools-event-client": ["@tanstack/devtools-event-client@0.4.3", "", { "bin": { "intent": "bin/intent.js" } }, "sha512-OZI6QyULw0FI0wjgmeYzCIfbgPsOEzwJtCpa69XrfLMtNXLGnz3d/dIabk7frg0TmHo+Ah49w5I4KC7Tufwsvw=="],
|
||||
|
||||
"@tanstack/form-core": ["@tanstack/form-core@1.33.0", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.1", "@tanstack/pacer-lite": "^0.1.1", "@tanstack/store": "^0.11.0" } }, "sha512-AV4Pw9Dk4orFsuPBcDssfWMJFs+yMYBae7zZ4oTqrCf4ftNGQKxvrQRZeqKHG6A4TkiLeSvf2kzIjcVkrW7E6w=="],
|
||||
@@ -1165,15 +1159,13 @@
|
||||
|
||||
"@testcontainers/postgresql": ["@testcontainers/postgresql@12.0.1", "", { "dependencies": { "testcontainers": "^12.0.1" } }, "sha512-6SyyduUM6lTAo4UwKG1aCochP6wTe0k7/W/m5uODZQMUrV3STk6/28Km3474JLGZdw/P793BUEF2IeU7rDyoEg=="],
|
||||
|
||||
"@testing-library/dom": ["@testing-library/dom@10.4.1", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.3.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "picocolors": "1.1.1", "pretty-format": "^27.0.2" } }, "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg=="],
|
||||
|
||||
"@testing-library/react": ["@testing-library/react@16.3.2", "", { "dependencies": { "@babel/runtime": "^7.12.5" }, "peerDependencies": { "@testing-library/dom": "^10.0.0", "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g=="],
|
||||
|
||||
"@types/adm-zip": ["@types/adm-zip@0.5.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q=="],
|
||||
|
||||
"@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
|
||||
|
||||
"@types/babel__generator": ["@types/babel__generator@7.27.0", "", { "dependencies": { "@babel/types": "^7.0.0" } }, "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg=="],
|
||||
|
||||
"@types/babel__template": ["@types/babel__template@7.4.4", "", { "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A=="],
|
||||
|
||||
"@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
|
||||
"@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="],
|
||||
|
||||
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
|
||||
|
||||
@@ -1241,6 +1233,10 @@
|
||||
|
||||
"@types/use-sync-external-store": ["@types/use-sync-external-store@0.0.6", "", {}, "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],
|
||||
|
||||
"@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
|
||||
|
||||
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
|
||||
|
||||
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.60.1", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.60.1", "@typescript-eslint/type-utils": "8.60.1", "@typescript-eslint/utils": "8.60.1", "@typescript-eslint/visitor-keys": "8.60.1", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.60.1", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-JQ4S5GB0tfjO8BuJ4fcX+HodkzJjYBV+7OJ+wLygaX7OGQ7FudyHL4NSCA6ob+w3Yn+5MkKIozOwQhXeM7opVg=="],
|
||||
@@ -1271,8 +1267,6 @@
|
||||
|
||||
"@videojs/xhr": ["@videojs/xhr@2.7.0", "", { "dependencies": { "@babel/runtime": "^7.5.5", "global": "~4.4.0", "is-function": "^1.0.1" } }, "sha512-giab+EVRanChIupZK7gXjHy90y3nncA2phIOyG3Ne5fvpiMJzvqYwiTOnEVW2S4CoYcuKJkomat7bMXA/UoUZQ=="],
|
||||
|
||||
"@vitejs/plugin-react": ["@vitejs/plugin-react@5.2.0", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw=="],
|
||||
|
||||
"@vitest/expect": ["@vitest/expect@4.1.8", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.8", "@vitest/utils": "4.1.8", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ=="],
|
||||
|
||||
"@vitest/mocker": ["@vitest/mocker@4.1.8", "", { "dependencies": { "@vitest/spy": "4.1.8", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw=="],
|
||||
@@ -1345,7 +1339,7 @@
|
||||
|
||||
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
|
||||
|
||||
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
"ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
|
||||
|
||||
"ansis": ["ansis@4.3.1", "", {}, "sha512-BJ8/l4R5LRE7hW9WdSuGYrLSHi2ynxeFpDFbH0K/CgNeY/tyhk+vO6TYxXC5r5CpUhNVX310xzPsN/H9lCdfOA=="],
|
||||
|
||||
@@ -1355,6 +1349,8 @@
|
||||
|
||||
"aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
|
||||
|
||||
"aria-query": ["aria-query@5.3.0", "", { "dependencies": { "dequal": "^2.0.3" } }, "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A=="],
|
||||
|
||||
"array-buffer-byte-length": ["array-buffer-byte-length@1.0.2", "", { "dependencies": { "call-bound": "^1.0.3", "is-array-buffer": "^3.0.5" } }, "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw=="],
|
||||
|
||||
"array-includes": ["array-includes@3.1.9", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.4", "define-properties": "^1.2.1", "es-abstract": "^1.24.0", "es-object-atoms": "^1.1.1", "get-intrinsic": "^1.3.0", "is-string": "^1.1.1", "math-intrinsics": "^1.1.0" } }, "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ=="],
|
||||
@@ -1439,6 +1435,8 @@
|
||||
|
||||
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
|
||||
|
||||
"buffer-image-size": ["buffer-image-size@0.6.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ=="],
|
||||
|
||||
"buildcheck": ["buildcheck@0.0.7", "", {}, "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA=="],
|
||||
|
||||
"bun": ["bun@1.3.14", "", { "optionalDependencies": { "@oven/bun-darwin-aarch64": "1.3.14", "@oven/bun-darwin-x64": "1.3.14", "@oven/bun-darwin-x64-baseline": "1.3.14", "@oven/bun-freebsd-aarch64": "1.3.14", "@oven/bun-freebsd-x64": "1.3.14", "@oven/bun-linux-aarch64": "1.3.14", "@oven/bun-linux-aarch64-android": "1.3.14", "@oven/bun-linux-aarch64-musl": "1.3.14", "@oven/bun-linux-x64": "1.3.14", "@oven/bun-linux-x64-android": "1.3.14", "@oven/bun-linux-x64-baseline": "1.3.14", "@oven/bun-linux-x64-musl": "1.3.14", "@oven/bun-linux-x64-musl-baseline": "1.3.14", "@oven/bun-windows-aarch64": "1.3.14", "@oven/bun-windows-x64": "1.3.14", "@oven/bun-windows-x64-baseline": "1.3.14" }, "os": [ "!aix", "!sunos", "!openbsd", ], "cpu": [ "x64", "arm64", ], "bin": { "bun": "bin/bun.exe", "bunx": "bin/bunx.exe" } }, "sha512-aB6GVd42x1Y5ie1K16SF+oLGtgSkwX9hgoDdIW88pjvfTccU8F1vfpoOt34QLv0dZ1v3XimtaxPlZUG81Gx9Zg=="],
|
||||
@@ -1599,6 +1597,8 @@
|
||||
|
||||
"doctrine": ["doctrine@2.1.0", "", { "dependencies": { "esutils": "^2.0.2" } }, "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw=="],
|
||||
|
||||
"dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="],
|
||||
|
||||
"dom-walk": ["dom-walk@0.1.2", "", {}, "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w=="],
|
||||
|
||||
"dotenv": ["dotenv@16.6.1", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],
|
||||
@@ -1629,6 +1629,8 @@
|
||||
|
||||
"enhanced-resolve": ["enhanced-resolve@5.22.1", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-6QEuw3zoX1SJQc7b87aBXke/no+mG2bTBgw29gWMQonLmpEkWoCAVkl+M49e48AZlWzxiDzDZzYdp6kobcyLww=="],
|
||||
|
||||
"entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"env-paths": ["env-paths@3.0.0", "", {}, "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A=="],
|
||||
|
||||
"es-abstract": ["es-abstract@1.24.2", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg=="],
|
||||
@@ -1751,7 +1753,7 @@
|
||||
|
||||
"fs-monkey": ["fs-monkey@1.1.0", "", {}, "sha512-QMUezzXWII9EV5aTFXW1UBVUO77wYPpjqIF8/AviUCThNeSYZykpoTixUeaNNBwmCev0AMDWMAni+f8Hxb1IFw=="],
|
||||
|
||||
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
"fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
|
||||
|
||||
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
|
||||
|
||||
@@ -1815,6 +1817,8 @@
|
||||
|
||||
"graphmatch": ["graphmatch@1.1.1", "", {}, "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg=="],
|
||||
|
||||
"happy-dom": ["happy-dom@20.10.6", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-6QD0ilzDDt93tX44y8tbmZdAcdTRYDhUP+Asgi6pC8Pp5IA3cvaZGyoVN/EGtlq9ziT65iPuBBn3ASLr6hCgVw=="],
|
||||
|
||||
"has-bigints": ["has-bigints@1.1.0", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
|
||||
|
||||
"has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
|
||||
@@ -2043,6 +2047,8 @@
|
||||
|
||||
"lucide-react": ["lucide-react@1.17.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-9FA9evdox/JQL5PT57fdA1x/yg8T7knJ98+zjTL3UfKza6pflQUUh3XtaQIHKvnsJw1lmsEyHVlt5jchYxOQ5w=="],
|
||||
|
||||
"lz-string": ["lz-string@1.5.0", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="],
|
||||
|
||||
"m3u8-parser": ["m3u8-parser@7.2.0", "", { "dependencies": { "@babel/runtime": "^7.12.5", "@videojs/vhs-utils": "^4.1.1", "global": "^4.4.0" } }, "sha512-CRatFqpjVtMiMaKXxNvuI3I++vUumIXVVT/JpCpdU/FynV/ceVw1qpPyyBNindL+JlPMSesx+WX1QJaZEJSaMQ=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
@@ -2249,6 +2255,10 @@
|
||||
|
||||
"pkg-types": ["pkg-types@2.3.1", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],
|
||||
|
||||
"playwright": ["playwright@1.61.1", "", { "dependencies": { "playwright-core": "1.61.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ=="],
|
||||
|
||||
"playwright-core": ["playwright-core@1.61.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg=="],
|
||||
|
||||
"possible-typed-array-names": ["possible-typed-array-names@1.1.0", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],
|
||||
|
||||
"postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="],
|
||||
@@ -2271,6 +2281,8 @@
|
||||
|
||||
"prettier-linter-helpers": ["prettier-linter-helpers@1.0.1", "", { "dependencies": { "fast-diff": "^1.1.2" } }, "sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg=="],
|
||||
|
||||
"pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="],
|
||||
|
||||
"prisma": ["prisma@7.8.0", "", { "dependencies": { "@prisma/config": "7.8.0", "@prisma/dev": "0.24.3", "@prisma/engines": "7.8.0", "@prisma/studio-core": "0.27.3", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-yfN4yrw7HV9kEJhoy1+jgah0jafEIQsf7uWouSsM8MvJtlubsk+kM7AIBWZ8+GJl74Yj3c+nbYqBkMOxtsZ3Lw=="],
|
||||
|
||||
"prisma-json-types-generator": ["prisma-json-types-generator@4.1.1", "", { "dependencies": { "@prisma/generator-helper": "^7.2.0", "semver": "^7.7.3", "try": "^1.0.3", "tslib": "^2.8.1" }, "peerDependencies": { "@prisma/client": "^7.2.0", "prisma": "^7.2.0", "typescript": "^5.9.3" }, "bin": { "prisma-json-types-generator": "index.js" } }, "sha512-oz0MYu1r2Jqu3qOGCEGulz6RjPsECVjyS3ZAz3HEmz0jkKbVkZEwQyksNJm0X5utV1TZCmaG/98EPExN7S22xw=="],
|
||||
@@ -2329,8 +2341,6 @@
|
||||
|
||||
"react-redux": ["react-redux@9.3.0", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "@types/react": "^18.2.25 || ^19", "react": "^18.0 || ^19", "redux": "^5.0.0" }, "optionalPeers": ["@types/react", "redux"] }, "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g=="],
|
||||
|
||||
"react-refresh": ["react-refresh@0.18.0", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
|
||||
"react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
|
||||
|
||||
"react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="],
|
||||
@@ -2657,6 +2667,8 @@
|
||||
|
||||
"webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
|
||||
|
||||
"whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="],
|
||||
|
||||
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"which-boxed-primitive": ["which-boxed-primitive@1.1.1", "", { "dependencies": { "is-bigint": "^1.1.0", "is-boolean-object": "^1.2.1", "is-number-object": "^1.1.1", "is-string": "^1.1.1", "is-symbol": "^1.1.1" } }, "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA=="],
|
||||
@@ -3027,6 +3039,8 @@
|
||||
|
||||
"pg-types/postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
|
||||
|
||||
"pretty-format/react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="],
|
||||
|
||||
"prisma-json-types-generator/semver": ["semver@7.8.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg=="],
|
||||
|
||||
"protobufjs/@types/node": ["@types/node@22.19.19", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew=="],
|
||||
@@ -3113,6 +3127,8 @@
|
||||
|
||||
"readdir-glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
|
||||
|
||||
"rollup/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"schema-utils/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
|
||||
|
||||
"sharp/semver": ["semver@7.8.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg=="],
|
||||
@@ -3127,8 +3143,14 @@
|
||||
|
||||
"thread-stream/real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="],
|
||||
|
||||
"vite/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"webpack/eslint-scope": ["eslint-scope@5.1.1", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw=="],
|
||||
|
||||
"wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
services:
|
||||
postgres:
|
||||
image: docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
container_name: shumai_postgres
|
||||
environment:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
ports:
|
||||
- '5432:5432'
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
shumai:
|
||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
# Server Configuration
|
||||
SHUMAI_SERVER_PORT: 3000
|
||||
|
||||
# S3 Configuration
|
||||
STORAGE_BACKEND: local
|
||||
AWS_ENDPOINT_URL_S3: http://localhost:3000
|
||||
|
||||
# Better Auth
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
+10
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
@@ -18,6 +18,11 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"test": "bun --bun vitest run",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
"test:e2e:report": "playwright show-report",
|
||||
"test:e2e:install": "playwright install --with-deps",
|
||||
"harness:dev": "bun run packages/webui/e2e/harness/serve.ts",
|
||||
"format": "prettier --write .",
|
||||
"db:migrate": "bun run prisma migrate dev",
|
||||
"db:deploy": "bun run prisma migrate deploy",
|
||||
@@ -38,7 +43,10 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
"@inlang/paraglide-js": "2.20.0",
|
||||
"@playwright/test": "1.61.1",
|
||||
"@testcontainers/postgresql": "12.0.1",
|
||||
"@testing-library/dom": "10.4.1",
|
||||
"@testing-library/react": "16.3.2",
|
||||
"@types/bun": "1.3.14",
|
||||
"@types/node": "25.9.1",
|
||||
"bun-plugin-pino": "1.5.0",
|
||||
@@ -49,6 +57,7 @@
|
||||
"eslint-plugin-prettier": "5.5.6",
|
||||
"eslint-plugin-react": "7.37.5",
|
||||
"globals": "17.6.0",
|
||||
"happy-dom": "20.10.6",
|
||||
"pino-pretty": "13.1.3",
|
||||
"prisma": "7.8.0",
|
||||
"testcontainers": "12.0.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as path from 'path'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
try {
|
||||
@@ -64,7 +65,7 @@ export function createCreateFileTool(userId: string): AgentTool<typeof createFil
|
||||
const mimeType = getMimeType(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
const s3Key = `files/${ulid()}/raw`
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as path from 'path'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
try {
|
||||
@@ -65,7 +66,7 @@ export function createCreateVersionTool(userId: string): AgentTool<typeof create
|
||||
const mimeType = getMimeType(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
const s3Key = `files/${ulid()}/raw`
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -299,5 +299,32 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const files = await assetService.getDownloadLinks(req.ids)
|
||||
return c.json({ files })
|
||||
})
|
||||
.post(
|
||||
'/files/download-url',
|
||||
zValidator('json', z.object({ key: z.string().min(1), assetId: z.string().min(1) })),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
const { key, assetId } = req
|
||||
|
||||
// Validate key format
|
||||
if (!key.startsWith('files/')) {
|
||||
return c.json({ error: 'Invalid key' }, 400)
|
||||
}
|
||||
|
||||
// Verify user has read access to the asset
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
|
||||
// Verify key belongs to the asset and generate download URL
|
||||
const url = await assetService.getDownloadUrl(assetId, key)
|
||||
|
||||
return c.json({ url })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
|
||||
@@ -147,6 +147,28 @@ const route = app
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
})
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/download-url',
|
||||
zValidator('json', z.object({ key: z.string().min(1) })),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const { key } = c.req.valid('json')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
if (!key.startsWith('files/')) {
|
||||
return c.json({ error: 'Invalid key' }, 400)
|
||||
}
|
||||
|
||||
const url = await assetService.getDownloadUrl(fileId, key)
|
||||
return c.json({ url })
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
|
||||
+19
-11
@@ -39,7 +39,7 @@ describe('S3 API', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('GET /files/* with filename query parameter sets Content-Disposition header', async () => {
|
||||
it('GET /files/* sets Content-Disposition: attachment only when download=1 query param is present', async () => {
|
||||
// We need to capture the onFound callback from serveStatic options
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let onFoundCallback: ((path: string, c: any) => void) | undefined
|
||||
@@ -54,26 +54,34 @@ describe('S3 API', () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
// First, verify onFound is called through the mock
|
||||
await app.request('/files/b1/test.webp?filename=my-file.txt')
|
||||
await app.request('/files/b1/test.webp?download=1')
|
||||
|
||||
expect(onFoundCallback).toBeDefined()
|
||||
|
||||
// Test the callback directly
|
||||
const mockContext = {
|
||||
req: {
|
||||
query: (key: string) => (key === 'filename' ? 'my-file.txt' : undefined),
|
||||
},
|
||||
// Test with download=1
|
||||
const mockContextWithDownload = {
|
||||
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
|
||||
header: vi.fn(),
|
||||
}
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContext)
|
||||
expect(mockContext.header).toHaveBeenCalledWith(
|
||||
onFoundCallback('/files/b1/test.webp', mockContextWithDownload)
|
||||
expect(mockContextWithDownload.header).toHaveBeenCalledWith(
|
||||
'Content-Disposition',
|
||||
'attachment; filename="my-file.txt"',
|
||||
'attachment',
|
||||
)
|
||||
}
|
||||
|
||||
// Test without download param
|
||||
const mockContextWithout = {
|
||||
req: { query: () => undefined },
|
||||
header: vi.fn(),
|
||||
}
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContextWithout)
|
||||
expect(mockContextWithout.header).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('PUT /files/:bucket/:key calls s3Service.putObject', async () => {
|
||||
|
||||
@@ -9,10 +9,8 @@ const route = new Hono()
|
||||
root: './data',
|
||||
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
||||
onFound: (_path, c) => {
|
||||
const filename = c.req.query('filename')
|
||||
if (filename) {
|
||||
const safeFilename = filename.replace(/["\r\n]/g, '_')
|
||||
c.header('Content-Disposition', `attachment; filename="${safeFilename}"`)
|
||||
if (c.req.query('download') === '1') {
|
||||
c.header('Content-Disposition', 'attachment')
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1280,6 +1280,61 @@ describe('AssetService', () => {
|
||||
expect(updatedA.sortIndex! < assetC.sortIndex!).toBe(true)
|
||||
})
|
||||
|
||||
describe('Preview', () => {
|
||||
it('toPreviewInfo includes video duration from media metadata', async () => {
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
const video = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
sizeByte: 123456,
|
||||
mediaType: 'video/mp4',
|
||||
status: 'processed',
|
||||
media: {
|
||||
poster: { key: 'poster-key' },
|
||||
metadata: { duration: 262 },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const info = await assetService.getAsset({ assetId: video.id })
|
||||
|
||||
expect(info.preview).toBeDefined()
|
||||
expect(info.preview?.mediaType).toBe('video/mp4')
|
||||
expect(info.preview?.duration).toBe(262)
|
||||
})
|
||||
|
||||
it('toPreviewInfo omits duration for images', async () => {
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
const image = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'pic.png',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
sizeByte: 5000,
|
||||
mediaType: 'image/png',
|
||||
status: 'processed',
|
||||
media: {
|
||||
thumbnail: { key: 'thumb-key' },
|
||||
metadata: { originalWidth: 100, originalHeight: 80 },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const info = await assetService.getAsset({ assetId: image.id })
|
||||
|
||||
expect(info.preview).toBeDefined()
|
||||
expect(info.preview?.duration).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Symlinks', () => {
|
||||
it('toAssetInfo resolves symlink target metadata', async () => {
|
||||
const { project, user } = await setupBasicAssets()
|
||||
@@ -2222,4 +2277,158 @@ describe('AssetService — natural sort by name', () => {
|
||||
expect(childActiveDb?.status).toBe('uploaded')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDownloadUrl', () => {
|
||||
it('should return a presigned download URL for a key in the same directory', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const url = await assetService.getDownloadUrl(
|
||||
asset.id,
|
||||
'files/01TESTULID000000000000000/test-720p.mp4',
|
||||
)
|
||||
|
||||
expect(url).toBe('http://mock-s3-url')
|
||||
})
|
||||
|
||||
it('should return a presigned download URL for the original key', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const url = await assetService.getDownloadUrl(
|
||||
asset.id,
|
||||
'files/01TESTULID000000000000000/test.mp4',
|
||||
)
|
||||
|
||||
expect(url).toBe('http://mock-s3-url')
|
||||
})
|
||||
|
||||
it('should throw if the key does not share the same parent directory', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.getDownloadUrl(asset.id, 'files/01OTHERULIDXXXXXXXXXX/hack.mp4'),
|
||||
).rejects.toThrow('Key does not belong to this asset')
|
||||
})
|
||||
|
||||
it('should throw if the key contains path traversal segments', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.getDownloadUrl(
|
||||
asset.id,
|
||||
'files/01TESTULID000000000000000/../01OTHERULIDXXXXXXXXXX/secret.mp4',
|
||||
),
|
||||
).rejects.toThrow('Key does not belong to this asset')
|
||||
})
|
||||
|
||||
it('should throw if the asset does not exist', async () => {
|
||||
await expect(
|
||||
assetService.getDownloadUrl('nonexistent-id', 'files/01TESTULID000000000000000/test.mp4'),
|
||||
).rejects.toThrow('Asset not found or has no storage key')
|
||||
})
|
||||
|
||||
it('should throw if the asset has no storage key', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'folder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.getDownloadUrl(asset.id, 'files/01TESTULID000000000000000/test.mp4'),
|
||||
).rejects.toThrow('Asset not found or has no storage key')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveLatestVersionId', () => {
|
||||
it('resolves the latest version ID of a version stack correctly (the one with the smallest sort index)', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project', teamId: team.id },
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'stack',
|
||||
type: AssetType.version_stack,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
// Oldest version (A): larger sort index
|
||||
const fileA = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'fileA.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
parent: { connect: { id: stack.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.uploaded,
|
||||
sortIndex: 'y',
|
||||
},
|
||||
})
|
||||
|
||||
// Latest version (B): smaller sort index
|
||||
const fileB = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'fileB.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
parent: { connect: { id: stack.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.uploaded,
|
||||
sortIndex: 'x',
|
||||
},
|
||||
})
|
||||
|
||||
// Act: resolve latest version of the stack
|
||||
const resolvedId = await assetService.resolveLatestVersionId(stack.id)
|
||||
|
||||
// Assert: should resolve to the latest version (fileB)
|
||||
expect(resolvedId).toBe(fileB.id)
|
||||
expect(resolvedId).not.toBe(fileA.id)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -842,7 +842,6 @@ export class AssetService {
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
info.media.original.key,
|
||||
'GET',
|
||||
a.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -910,7 +909,7 @@ export class AssetService {
|
||||
if (currentType === AssetType.version_stack) {
|
||||
const latestChild = await this.prismaClient.asset.findFirst({
|
||||
where: { parentId: currentId, isDeleted: false },
|
||||
orderBy: { sortIndex: 'desc' },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
select: { id: true },
|
||||
})
|
||||
if (latestChild) {
|
||||
@@ -1583,7 +1582,7 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
const media = latestVersion.media as PrismaJson.MediaInfo | null
|
||||
let media = latestVersion.media as PrismaJson.MediaInfo | null
|
||||
if (media && media.videoPreview?.key) {
|
||||
media.videoPreview.url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
@@ -1593,21 +1592,19 @@ export class AssetService {
|
||||
}
|
||||
|
||||
const key = latestVersion.storageKey?.key
|
||||
if (media && key) {
|
||||
const fileName =
|
||||
a.type === AssetType.version_stack && (a.name === '' || !a.name)
|
||||
? latestVersion.name
|
||||
: a.name
|
||||
if (key) {
|
||||
if (!media) {
|
||||
media = {
|
||||
original: null,
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
} as unknown as PrismaJson.MediaInfo
|
||||
}
|
||||
media.original = {
|
||||
key,
|
||||
downloadUrl: await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
fileName,
|
||||
),
|
||||
downloadUrl: await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET'),
|
||||
filesizeInBytes: latestVersion.sizeByte,
|
||||
codec: '', // TODO: extract from metadata if needed
|
||||
codec: '',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1845,12 +1842,7 @@ export class AssetService {
|
||||
const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null
|
||||
if (!key) return null
|
||||
|
||||
const url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
file.name,
|
||||
)
|
||||
const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
|
||||
|
||||
return {
|
||||
id: file.id,
|
||||
@@ -1863,6 +1855,31 @@ export class AssetService {
|
||||
return downloadLinks.filter((link): link is { id: string; name: string; url: string } => !!link)
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a presigned download URL for a given key, verifying it belongs to the asset's
|
||||
* storage directory. This ensures users can only download files (original, transcodes, etc.)
|
||||
* that belong to an asset they have access to.
|
||||
*/
|
||||
async getDownloadUrl(assetId: string, key: string): Promise<string> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { storageKey: { select: { key: true } } },
|
||||
})
|
||||
|
||||
if (!asset?.storageKey?.key) {
|
||||
throw new Error('Asset not found or has no storage key')
|
||||
}
|
||||
|
||||
// Verify the requested key shares the same parent directory as the asset's storage key
|
||||
const storageKey = asset.storageKey.key
|
||||
const assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
if (key.includes('..') || !key.startsWith(assetDir)) {
|
||||
throw new Error('Key does not belong to this asset')
|
||||
}
|
||||
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
|
||||
}
|
||||
|
||||
private async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise<PreviewInfo | null> {
|
||||
if (!asset.media) return null
|
||||
|
||||
@@ -1896,6 +1913,7 @@ export class AssetService {
|
||||
originalHeight: asset.media.metadata?.originalHeight,
|
||||
originalWidth: asset.media.metadata?.originalWidth,
|
||||
spriteUrl,
|
||||
duration: asset.media.metadata?.duration,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { auth } from './auth'
|
||||
import { userMetadataService } from '../user-metadata/user-metadata'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
describe('Auth Signup Locale Hook', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(teamService, 'getSignupInfo').mockResolvedValue({
|
||||
initialized: false,
|
||||
demoMode: false,
|
||||
userCount: 1,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('should save locale metadata for the user upon signup', async () => {
|
||||
const email = `signup-locale-${Date.now()}@example.com`
|
||||
|
||||
// We must use any here because 'locale' is a custom property we extract in
|
||||
// our auth hooks, but better-auth's signUpEmail typescript interface does
|
||||
// not recognize it.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const res = await (auth.api.signUpEmail as any)({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
email,
|
||||
password: 'testpassword',
|
||||
name: 'Locale Tester',
|
||||
locale: 'zh',
|
||||
},
|
||||
})
|
||||
|
||||
if (res.error) {
|
||||
console.error('SIGNUP ERROR:', res.error)
|
||||
}
|
||||
|
||||
expect(res).toBeDefined()
|
||||
expect(res.user).toBeDefined()
|
||||
expect(res.user.email).toBe(email)
|
||||
|
||||
// Check that the userMetadata record was created with key 'locale' and value 'zh'
|
||||
const teamMembers = await prisma.teamMember.findMany({
|
||||
where: { userId: res.user.id },
|
||||
})
|
||||
expect(teamMembers.length).toBeGreaterThan(0)
|
||||
|
||||
for (const member of teamMembers) {
|
||||
const meta = await userMetadataService.getMetadata(res.user.id, member.teamId, 'locale')
|
||||
expect(meta).toBeDefined()
|
||||
expect(meta?.value).toBe('zh')
|
||||
}
|
||||
})
|
||||
|
||||
it('should not save locale metadata if locale is invalid or missing', async () => {
|
||||
const email = `signup-no-locale-${Date.now()}@example.com`
|
||||
|
||||
// We must use any here because 'locale' is a custom property we extract in
|
||||
// our auth hooks, but better-auth's signUpEmail typescript interface does
|
||||
// not recognize it.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const res = await (auth.api.signUpEmail as any)({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
email,
|
||||
password: 'testpassword',
|
||||
name: 'No Locale Tester',
|
||||
locale: 'fr', // invalid locale
|
||||
},
|
||||
})
|
||||
|
||||
if (res.error) {
|
||||
console.error('SIGNUP ERROR 2:', res.error)
|
||||
}
|
||||
|
||||
expect(res).toBeDefined()
|
||||
expect(res.user).toBeDefined()
|
||||
|
||||
const teamMembers = await prisma.teamMember.findMany({
|
||||
where: { userId: res.user.id },
|
||||
})
|
||||
expect(teamMembers.length).toBeGreaterThan(0)
|
||||
|
||||
for (const member of teamMembers) {
|
||||
const meta = await userMetadataService.getMetadata(res.user.id, member.teamId, 'locale')
|
||||
expect(meta).toBeNull()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { prisma } from '@shumai/db'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { createAuthMiddleware } from 'better-auth/api'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
@@ -102,6 +103,17 @@ export const auth = betterAuth({
|
||||
if (inviteCode) {
|
||||
await inviteService.consumeInvite(inviteCode, user.id)
|
||||
}
|
||||
|
||||
const locale = body?.locale
|
||||
if (locale === 'en' || locale === 'zh') {
|
||||
const joinedTeams = await prisma.teamMember.findMany({
|
||||
where: { userId: user.id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
for (const member of joinedTeams) {
|
||||
await userMetadataService.upsertMetadata(user.id, member.teamId, 'locale', locale)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Better Auth Hook] Error in after hook: ${err}`)
|
||||
}
|
||||
|
||||
@@ -117,17 +117,44 @@ describe('S3Service implementations', () => {
|
||||
delete process.env.PRESIGNED_URL_EXPIRES_IN
|
||||
})
|
||||
|
||||
it('should pass filename to presign', async () => {
|
||||
it('should not set contentDisposition for normal GET presign', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
await s3.presign('bucket', 'key', 'GET', 'test.txt')
|
||||
await s3.presign('bucket', 'key', 'GET')
|
||||
|
||||
expect(s3PresignSpy).toHaveBeenCalledWith(
|
||||
'key',
|
||||
expect.not.objectContaining({
|
||||
contentDisposition: expect.anything(),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should set contentDisposition attachment when download is true', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
await s3.presign('bucket', 'key', 'GET', true)
|
||||
|
||||
expect(s3PresignSpy).toHaveBeenCalledWith(
|
||||
'key',
|
||||
expect.objectContaining({
|
||||
contentDisposition: 'attachment; filename="test.txt"',
|
||||
contentDisposition: 'attachment',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not cache download presign URLs', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
|
||||
s3PresignSpy.mockClear()
|
||||
s3PresignSpy.mockReturnValueOnce('http://download-url-1')
|
||||
s3PresignSpy.mockReturnValueOnce('http://download-url-2')
|
||||
|
||||
const url1 = await s3.presign('bucket', 'key', 'GET', true)
|
||||
const url2 = await s3.presign('bucket', 'key', 'GET', true)
|
||||
|
||||
expect(url1).toBe('http://download-url-1')
|
||||
expect(url2).toBe('http://download-url-2')
|
||||
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('LocalStorageService', () => {
|
||||
@@ -182,9 +209,9 @@ describe('S3Service implementations', () => {
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt')
|
||||
})
|
||||
|
||||
it('should generate a local presign URL with filename', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', 'original.txt')
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?filename=original.txt')
|
||||
it('should generate a local presign URL with download param', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?download=1')
|
||||
})
|
||||
|
||||
it('should throw an error for unsupported presign methods', async () => {
|
||||
|
||||
+10
-10
@@ -54,7 +54,7 @@ export interface S3Service {
|
||||
listObjects(bucket: string, prefix: string): Promise<string[]>
|
||||
uploadFile(filePath: string, contentType: string): Promise<string>
|
||||
uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void>
|
||||
presign(bucket: string, key: string, method: string, filename?: string): Promise<string>
|
||||
presign(bucket: string, key: string, method: string, download?: boolean): Promise<string>
|
||||
}
|
||||
|
||||
export class S3StorageService implements S3Service {
|
||||
@@ -203,16 +203,16 @@ export class S3StorageService implements S3Service {
|
||||
})
|
||||
}
|
||||
|
||||
async presign(bucket: string, key: string, method: string, filename?: string): Promise<string> {
|
||||
async presign(bucket: string, key: string, method: string, download?: boolean): Promise<string> {
|
||||
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
|
||||
const expiresInSeconds = expireHours * 3600
|
||||
// Cache time is 2/3 of expire time, rounded to minute
|
||||
const cacheMinutes = Math.round((expireHours * 60 * 2) / 3)
|
||||
const cacheTtlMs = cacheMinutes * 60 * 1000
|
||||
|
||||
const cacheKey = `${bucket}:${key}:${filename || ''}`
|
||||
const cacheKey = `${bucket}:${key}`
|
||||
|
||||
if (method === 'GET') {
|
||||
if (method === 'GET' && !download) {
|
||||
const cached = this.presignCache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
}
|
||||
@@ -225,13 +225,13 @@ export class S3StorageService implements S3Service {
|
||||
method: method as any,
|
||||
}
|
||||
|
||||
if (filename) {
|
||||
options.contentDisposition = `attachment; filename="${filename}"`
|
||||
if (download) {
|
||||
options.contentDisposition = 'attachment'
|
||||
}
|
||||
|
||||
const url = this.client.presign(key, options)
|
||||
|
||||
if (method === 'GET') {
|
||||
if (method === 'GET' && !download) {
|
||||
this.presignCache.set(cacheKey, url, cacheTtlMs)
|
||||
}
|
||||
|
||||
@@ -435,7 +435,7 @@ export class LocalStorageService implements S3Service {
|
||||
await fs.promises.copyFile(filePath, destPath)
|
||||
}
|
||||
|
||||
async presign(bucket: string, key: string, method: string, filename?: string): Promise<string> {
|
||||
async presign(bucket: string, key: string, method: string, download?: boolean): Promise<string> {
|
||||
if (method !== 'GET' && method !== 'PUT') {
|
||||
throw new Error(`Invalid method: ${method}`)
|
||||
}
|
||||
@@ -443,8 +443,8 @@ export class LocalStorageService implements S3Service {
|
||||
return `${this.endpoint}${signLocalUrl(bucket, key)}`
|
||||
}
|
||||
let url = `${this.endpoint}/files/${bucket}/${key}`
|
||||
if (filename) {
|
||||
url += `?filename=${encodeURIComponent(filename)}`
|
||||
if (download) {
|
||||
url += '?download=1'
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ export class TranscodeService {
|
||||
duration: number,
|
||||
): Promise<void> {
|
||||
const spriteFps = 100 / duration
|
||||
const filterComplex = `[0:v]fps=${spriteFps},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:720:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
const filterComplex = `[0:v]fps=${spriteFps},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:480:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
|
||||
const args = [
|
||||
'-i',
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { ImageTranscoder, VideoTranscoder } from '@shumai/transcode'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
export class UploadService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
@@ -130,7 +131,7 @@ export class UploadService {
|
||||
const assetType = file.type === 'folder' ? AssetType.folder : AssetType.file
|
||||
let key: string | null = null
|
||||
if (assetType === AssetType.file) {
|
||||
key = `files/${ulid()}/raw`
|
||||
key = `files/${ulid()}/${sanitizeFilename(file.name)}`
|
||||
}
|
||||
|
||||
const newAsset = await tx.asset.create({
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { sanitizeFilename, stemFromKey } from './filename'
|
||||
|
||||
describe('sanitizeFilename', () => {
|
||||
it('returns the filename unchanged when it is already safe', () => {
|
||||
expect(sanitizeFilename('foo.mp4')).toBe('foo.mp4')
|
||||
expect(sanitizeFilename('my-video_final.mov')).toBe('my-video_final.mov')
|
||||
})
|
||||
|
||||
it('replaces slashes and backslashes with underscores', () => {
|
||||
expect(sanitizeFilename('path/to/file.mp4')).toBe('path_to_file.mp4')
|
||||
expect(sanitizeFilename('path\\to\\file.mp4')).toBe('path_to_file.mp4')
|
||||
})
|
||||
|
||||
it('replaces NUL bytes and control characters', () => {
|
||||
expect(sanitizeFilename('foo\x00bar.mp4')).toBe('foo_bar.mp4')
|
||||
expect(sanitizeFilename('foo\x01bar.mp4')).toBe('foo_bar.mp4')
|
||||
})
|
||||
|
||||
it('trims leading and trailing dots and whitespace', () => {
|
||||
expect(sanitizeFilename('.hidden')).toBe('hidden')
|
||||
expect(sanitizeFilename('...dotted...')).toBe('dotted')
|
||||
expect(sanitizeFilename(' spaced ')).toBe('spaced')
|
||||
expect(sanitizeFilename(' .mixed. ')).toBe('mixed')
|
||||
})
|
||||
|
||||
it('collapses multiple consecutive underscores', () => {
|
||||
expect(sanitizeFilename('a//b')).toBe('a_b')
|
||||
expect(sanitizeFilename('a///b')).toBe('a_b')
|
||||
})
|
||||
|
||||
it('returns "file" for empty or whitespace-only input', () => {
|
||||
expect(sanitizeFilename('')).toBe('file')
|
||||
expect(sanitizeFilename(' ')).toBe('file')
|
||||
expect(sanitizeFilename('...')).toBe('file')
|
||||
})
|
||||
|
||||
it('preserves unicode characters', () => {
|
||||
expect(sanitizeFilename('视频文件.mp4')).toBe('视频文件.mp4')
|
||||
expect(sanitizeFilename('café.png')).toBe('café.png')
|
||||
})
|
||||
|
||||
it('preserves spaces within the filename', () => {
|
||||
expect(sanitizeFilename('my video file.mp4')).toBe('my video file.mp4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('stemFromKey', () => {
|
||||
it('extracts the stem from a key with extension', () => {
|
||||
expect(stemFromKey('files/01ABC/foo.mp4')).toBe('foo')
|
||||
expect(stemFromKey('files/01ABC/my-video.mov')).toBe('my-video')
|
||||
})
|
||||
|
||||
it('extracts the stem from a key without extension', () => {
|
||||
expect(stemFromKey('files/01ABC/raw')).toBe('raw')
|
||||
})
|
||||
|
||||
it('handles keys with multiple dots in filename', () => {
|
||||
expect(stemFromKey('files/01ABC/my.video.file.mp4')).toBe('my.video.file')
|
||||
})
|
||||
|
||||
it('handles keys with no directory', () => {
|
||||
expect(stemFromKey('foo.mp4')).toBe('foo')
|
||||
expect(stemFromKey('raw')).toBe('raw')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import path from 'path'
|
||||
|
||||
/**
|
||||
* Sanitize a filename for safe use as an S3 key segment.
|
||||
* - Replaces characters unsafe for S3/filesystems with '_'
|
||||
* - Trims leading/trailing whitespace and dots
|
||||
* - Falls back to 'file' if the result is empty
|
||||
*/
|
||||
export function sanitizeFilename(filename: string): string {
|
||||
// Replace NUL bytes, slashes, backslashes, and control characters
|
||||
// eslint-disable-next-line no-control-regex
|
||||
let safe = filename.replace(/[\x00-\x1f\x7f/\\]/g, '_')
|
||||
|
||||
// Trim leading/trailing whitespace and dots
|
||||
safe = safe.replace(/^[\s.]+|[\s.]+$/g, '')
|
||||
|
||||
// Collapse multiple underscores
|
||||
safe = safe.replace(/_+/g, '_')
|
||||
|
||||
if (!safe) {
|
||||
return 'file'
|
||||
}
|
||||
|
||||
return safe
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the filename stem (without extension) from a storage key.
|
||||
* e.g. 'files/01ABC.../foo.mp4' → 'foo'
|
||||
* 'files/01ABC.../raw' → 'raw'
|
||||
*/
|
||||
export function stemFromKey(key: string): string {
|
||||
const basename = path.basename(key)
|
||||
const ext = path.extname(basename)
|
||||
return ext ? basename.slice(0, -ext.length) : basename
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -13,6 +13,7 @@ export const previewInfoSchema = z.object({
|
||||
originalHeight: z.number().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
spriteUrl: z.string().optional(),
|
||||
duration: z.number().optional(),
|
||||
})
|
||||
export type PreviewInfo = z.infer<typeof previewInfoSchema>
|
||||
|
||||
@@ -279,6 +280,7 @@ export interface ImageTranscode {
|
||||
export interface VideoTranscode {
|
||||
id: string
|
||||
url: string
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
size: number
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
@@ -162,7 +163,9 @@ export async function transcodeVideoActivity(
|
||||
params: VideoActivityParams,
|
||||
): Promise<PrismaJson.VideoTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = path.join(path.dirname(params.assetKey), `video-${params.videoSpec.height}p.mp4`)
|
||||
const stem = stemFromKey(params.assetKey)
|
||||
const res = params.videoSpec.resolution || `${params.videoSpec.height}p`
|
||||
const key = path.posix.join(path.posix.dirname(params.assetKey), `${stem}-${res}.mp4`)
|
||||
|
||||
try {
|
||||
await s3Service.headObject(bucket, key)
|
||||
@@ -172,7 +175,7 @@ export async function transcodeVideoActivity(
|
||||
}
|
||||
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`)
|
||||
const outputFile = path.join(tmpDir, `${stem}-${res}.mp4`)
|
||||
|
||||
try {
|
||||
let targetFps: number | string = params.originalFps || 30
|
||||
@@ -237,7 +240,11 @@ export async function transcodeImageActivity(
|
||||
params: ImageActivityParams,
|
||||
): Promise<PrismaJson.ImageTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = path.join(path.dirname(params.assetKey), `image-${params.imageSpec.width}p.webp`)
|
||||
const stem = stemFromKey(params.assetKey)
|
||||
const key = path.posix.join(
|
||||
path.posix.dirname(params.assetKey),
|
||||
`${stem}-${params.imageSpec.width}p.webp`,
|
||||
)
|
||||
|
||||
try {
|
||||
await s3Service.headObject(bucket, key)
|
||||
@@ -247,7 +254,7 @@ export async function transcodeImageActivity(
|
||||
}
|
||||
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const outputFile = path.join(tmpDir, `image-${params.imageSpec.width}p.webp`)
|
||||
const outputFile = path.join(tmpDir, `${stem}-${params.imageSpec.width}p.webp`)
|
||||
|
||||
try {
|
||||
await transcodeService.transcodeImage(
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { client } from '@/ui/api/client'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
@@ -21,7 +23,7 @@ import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { AncestorFolder } from '@shumai/dtos'
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { Check, ChevronDown, FileIcon, History, LayoutGrid, List } from 'lucide-react'
|
||||
import { Check, ChevronDown, Columns2, FileIcon, History, LayoutGrid, List } from 'lucide-react'
|
||||
|
||||
interface BreadcrumbNavProps {
|
||||
teamId: string
|
||||
@@ -44,6 +46,15 @@ interface BreadcrumbNavProps {
|
||||
shareId?: string
|
||||
onFolderClick?: (folderId: string) => void
|
||||
fileId?: string
|
||||
downloadInfo?: {
|
||||
originalKey?: string
|
||||
videoTranscodes?: Array<{
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
isRaw?: boolean
|
||||
}>
|
||||
}
|
||||
versions?: Array<{
|
||||
id: string
|
||||
version: number
|
||||
@@ -51,6 +62,9 @@ interface BreadcrumbNavProps {
|
||||
previewUrl?: string | null
|
||||
creator?: { id: string; name: string | null } | null
|
||||
}>
|
||||
compareMode?: boolean
|
||||
canCompareVersions?: boolean
|
||||
onCompareVersions?: () => void
|
||||
}
|
||||
|
||||
export function BreadcrumbNav({
|
||||
@@ -69,13 +83,27 @@ export function BreadcrumbNav({
|
||||
isPublic = false,
|
||||
onFolderClick,
|
||||
fileId,
|
||||
shareId,
|
||||
downloadInfo,
|
||||
versions,
|
||||
compareMode = false,
|
||||
canCompareVersions = false,
|
||||
onCompareVersions,
|
||||
}: BreadcrumbNavProps) {
|
||||
const navigate = useNavigate()
|
||||
const { canEdit } = usePermissions(projectId)
|
||||
|
||||
const handleVersionClick = (versionId: string) => {
|
||||
if (!projectId || !fileId) return
|
||||
if (!fileId) return
|
||||
if (isPublic && shareId) {
|
||||
navigate({
|
||||
to: '/share/$shareId/files/$fileId',
|
||||
params: { shareId, fileId },
|
||||
search: (prev: Record<string, unknown>) => ({ ...prev, version: versionId }),
|
||||
})
|
||||
return
|
||||
}
|
||||
if (!projectId) return
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
@@ -83,6 +111,33 @@ export function BreadcrumbNav({
|
||||
})
|
||||
}
|
||||
|
||||
const handleDownload = async (key: string) => {
|
||||
if (!fileId) return
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: fileId },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
const hasVideoTranscodes =
|
||||
downloadInfo?.videoTranscodes && downloadInfo.videoTranscodes.filter((t) => !t.isRaw).length > 0
|
||||
|
||||
const breadcrumbs: { name: string; path?: string; id?: string; isMuted?: boolean }[] = isPublic
|
||||
? [
|
||||
{
|
||||
@@ -136,7 +191,7 @@ export function BreadcrumbNav({
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{!isRootFolder && (
|
||||
{!isRootFolder && !compareMode && (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-muted-foreground">/</span>
|
||||
{currentAsset.type === 'folder' ? (
|
||||
@@ -155,9 +210,63 @@ export function BreadcrumbNav({
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
<DropdownMenuItem onClick={() => console.log('Download')}>
|
||||
Download
|
||||
</DropdownMenuItem>
|
||||
{hasVideoTranscodes ? (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="flex items-center gap-2">
|
||||
<span>{m.download()}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent className="w-48">
|
||||
<DropdownMenuLabel>{m.download()}</DropdownMenuLabel>
|
||||
{downloadInfo?.videoTranscodes
|
||||
?.filter((t) => !t.isRaw)
|
||||
.map((t) => {
|
||||
const longSide = Math.max(t.width, t.height)
|
||||
let resolution = `${t.height}p`
|
||||
if (longSide >= 3840) resolution = '2160p'
|
||||
else if (longSide >= 1920) resolution = '1080p'
|
||||
else if (longSide >= 1280) resolution = '720p'
|
||||
else if (longSide >= 960) resolution = '540p'
|
||||
else if (longSide >= 640) resolution = '360p'
|
||||
else if (longSide >= 320) resolution = '180p'
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={resolution}
|
||||
onClick={() => handleDownload(t.key)}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>{resolution}</span>
|
||||
<span className="text-xs text-muted-foreground">MP4</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
{downloadInfo?.originalKey && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDownload(downloadInfo.originalKey!)}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>Original</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{currentAsset.name?.split('.').pop()?.toUpperCase() || 'RAW'}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
downloadInfo?.originalKey && handleDownload(downloadInfo.originalKey)
|
||||
}
|
||||
disabled={!downloadInfo?.originalKey}
|
||||
>
|
||||
{m.download()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canEdit && (
|
||||
<DropdownMenuItem onClick={() => console.log('Rename')}>
|
||||
Rename
|
||||
@@ -169,6 +278,16 @@ export function BreadcrumbNav({
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{canCompareVersions && onCompareVersions && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => onCompareVersions()}>
|
||||
<Columns2 className="h-4 w-4" />
|
||||
<span>{m.compare_versions()}</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
{versions && versions.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { ImageControlBar } from '@/ui/components/viewers/image-control-bar'
|
||||
import {
|
||||
VideoControlBar,
|
||||
type DisplayTranscode,
|
||||
type PlayerState,
|
||||
} from '@/ui/components/viewers/video-control-bar'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { Maximize, Minimize } from 'lucide-react'
|
||||
import type { PaneReportedState } from './types'
|
||||
|
||||
interface CompareControlBarProps {
|
||||
activeState: PaneReportedState | null
|
||||
activeAsset: AssetInfo | null
|
||||
previewUrl?: string
|
||||
isFullScreen: boolean
|
||||
onTogglePlay: () => void
|
||||
onToggleLoop: () => void
|
||||
onSeek: (frame: number) => void
|
||||
onVolumeChange: (volume: number) => void
|
||||
onToggleMute: () => void
|
||||
onChangePlaybackRate: (rate: number) => void
|
||||
onChangeResolution: (resolution: string) => void
|
||||
onZoomIn: () => void
|
||||
onZoomOut: () => void
|
||||
onFit: () => void
|
||||
onDownload: (key?: string) => void
|
||||
onToggleFullScreen: () => void
|
||||
}
|
||||
|
||||
export function CompareControlBar({
|
||||
activeState,
|
||||
activeAsset,
|
||||
previewUrl,
|
||||
isFullScreen,
|
||||
onTogglePlay,
|
||||
onToggleLoop,
|
||||
onSeek,
|
||||
onVolumeChange,
|
||||
onToggleMute,
|
||||
onChangePlaybackRate,
|
||||
onChangeResolution,
|
||||
onZoomIn,
|
||||
onZoomOut,
|
||||
onFit,
|
||||
onDownload,
|
||||
onToggleFullScreen,
|
||||
}: CompareControlBarProps) {
|
||||
// Active side is a video: reuse the shared VideoControlBar.
|
||||
if (activeState?.kind === 'video' && activeState.video && activeAsset) {
|
||||
const v = activeState.video
|
||||
const duration = v.totalFrames / v.frameRate
|
||||
const currentTime = v.currentFrame / v.frameRate
|
||||
const state: PlayerState = {
|
||||
isPlaying: v.isPlaying,
|
||||
progress: duration > 0 ? (currentTime / duration) * 100 : 0,
|
||||
currentTime,
|
||||
duration,
|
||||
volume: v.volume,
|
||||
isMuted: v.isMuted,
|
||||
isLooping: v.isLooping,
|
||||
playbackRate: v.playbackRate,
|
||||
isFullScreen,
|
||||
showFrames: false,
|
||||
currentResolution: v.currentResolution,
|
||||
}
|
||||
|
||||
// The active-side asset carries the metadata used for timecode display and
|
||||
// preview scrubbing; ensure the preview url is present for the shared bar.
|
||||
const data =
|
||||
previewUrl && !activeAsset.media?.videoPreview
|
||||
? { ...activeAsset, media: { ...activeAsset.media, videoPreview: { url: previewUrl } } }
|
||||
: activeAsset
|
||||
|
||||
return (
|
||||
<VideoControlBar
|
||||
state={state}
|
||||
zoom={activeState.zoom}
|
||||
isControlsVisible
|
||||
floatOverlayInFullScreen={false}
|
||||
buffered={v.buffered}
|
||||
data={data}
|
||||
resolutions={v.resolutions as DisplayTranscode[]}
|
||||
togglePlay={onTogglePlay}
|
||||
toggleLoop={onToggleLoop}
|
||||
toggleMute={onToggleMute}
|
||||
handleVolumeChange={onVolumeChange}
|
||||
changePlaybackRate={onChangePlaybackRate}
|
||||
changeResolution={(res) => onChangeResolution(res.resolution)}
|
||||
handleDownload={(key) => onDownload(key)}
|
||||
toggleFullScreen={onToggleFullScreen}
|
||||
onZoomChange={(nz) => (nz >= activeState.zoom ? onZoomIn() : onZoomOut())}
|
||||
onZoomReset={onFit}
|
||||
frameRate={v.frameRate}
|
||||
totalFrames={v.totalFrames}
|
||||
currentFrame={v.currentFrame}
|
||||
seekToFrame={onSeek}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Active side is an image: reuse the shared ImageControlBar.
|
||||
if (activeState?.kind === 'image') {
|
||||
return (
|
||||
<ImageControlBar
|
||||
zoom={activeState.zoom}
|
||||
onZoomIn={onZoomIn}
|
||||
onZoomOut={onZoomOut}
|
||||
onFit={onFit}
|
||||
onDownload={() => onDownload()}
|
||||
canDownload={!!activeAsset?.media?.original?.key}
|
||||
fullscreen={{ isFullScreen, onToggle: onToggleFullScreen }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Unsupported / not yet loaded: only expose fullscreen.
|
||||
return (
|
||||
<div className="relative z-10 flex items-center justify-end gap-2 border-t border-border bg-card px-4 py-3">
|
||||
<button
|
||||
onClick={onToggleFullScreen}
|
||||
className="text-foreground transition-colors hover:text-primary"
|
||||
title="Fullscreen"
|
||||
>
|
||||
{isFullScreen ? <Minimize className="h-5 w-5" /> : <Maximize className="h-5 w-5" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import DrawingCanvas from '@/ui/components/drawing-canvas'
|
||||
import { useScreenSize } from '@/ui/hooks/useScreenSize'
|
||||
import { getBestTranscode } from '@/ui/lib/media'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
|
||||
import type { ComparePaneHandle, PaneReportedState } from './types'
|
||||
|
||||
interface CompareImagePaneProps {
|
||||
file: AssetInfo
|
||||
shareId?: string
|
||||
isActive: boolean
|
||||
annotations: Annotation[]
|
||||
onStateChange: (state: PaneReportedState) => void
|
||||
onUserPan?: (dx: number, dy: number) => void
|
||||
onActivate?: () => void
|
||||
}
|
||||
|
||||
const MIN_ZOOM = 0.01
|
||||
const MAX_ZOOM = 50
|
||||
|
||||
export const CompareImagePane = forwardRef<ComparePaneHandle, CompareImagePaneProps>(
|
||||
function CompareImagePane(
|
||||
{ file, shareId, isActive, annotations, onStateChange, onUserPan, onActivate },
|
||||
ref,
|
||||
) {
|
||||
const { width: screenWidth } = useScreenSize()
|
||||
const {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
addAnnotation,
|
||||
annotations: draftAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [pan, setPan] = useState({ x: 0, y: 0 })
|
||||
|
||||
const observerRef = useRef<ResizeObserver | null>(null)
|
||||
const zoomRef = useRef(zoom)
|
||||
zoomRef.current = zoom
|
||||
const panRef = useRef(pan)
|
||||
panRef.current = pan
|
||||
|
||||
const containerRef = useCallback((node: HTMLDivElement | null) => {
|
||||
if (observerRef.current) {
|
||||
observerRef.current.disconnect()
|
||||
observerRef.current = null
|
||||
}
|
||||
if (node !== null) {
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const entry = entries[0]
|
||||
if (entry) {
|
||||
setContainerSize({
|
||||
width: entry.contentRect.width,
|
||||
height: entry.contentRect.height,
|
||||
})
|
||||
}
|
||||
})
|
||||
observer.observe(node)
|
||||
observerRef.current = observer
|
||||
}
|
||||
}, [])
|
||||
|
||||
const imgW = file.media?.metadata?.originalWidth ?? 1920
|
||||
const imgH = file.media?.metadata?.originalHeight ?? 1080
|
||||
const conW = containerSize.width
|
||||
const conH = containerSize.height
|
||||
|
||||
let baseScale = 1
|
||||
if (conW > 0 && conH > 0) {
|
||||
baseScale = Math.min(conW / imgW, conH / imgH)
|
||||
}
|
||||
|
||||
// Fit on mount / container resize / file change
|
||||
useEffect(() => {
|
||||
if (conW > 0 && conH > 0) {
|
||||
setZoom(baseScale)
|
||||
setPan({
|
||||
x: (conW - imgW * baseScale) / 2,
|
||||
y: (conH - imgH * baseScale) / 2,
|
||||
})
|
||||
}
|
||||
}, [file.id, conW, conH, baseScale, imgW, imgH])
|
||||
|
||||
const applyZoom = useCallback(
|
||||
(factor: number) => {
|
||||
const cx = conW / 2
|
||||
const cy = conH / 2
|
||||
const cur = zoomRef.current
|
||||
const newZoom = cur * factor
|
||||
if (newZoom < MIN_ZOOM || newZoom > MAX_ZOOM) return
|
||||
const curPan = panRef.current
|
||||
setPan({
|
||||
x: cx - (cx - curPan.x) * (newZoom / cur),
|
||||
y: cy - (cy - curPan.y) * (newZoom / cur),
|
||||
})
|
||||
setZoom(newZoom)
|
||||
},
|
||||
[conW, conH],
|
||||
)
|
||||
|
||||
const fit = useCallback(() => {
|
||||
setZoom(baseScale)
|
||||
setPan({
|
||||
x: (conW - imgW * baseScale) / 2,
|
||||
y: (conH - imgH * baseScale) / 2,
|
||||
})
|
||||
}, [baseScale, conW, conH, imgW, imgH])
|
||||
|
||||
let bestUrl = file.media?.original?.downloadUrl
|
||||
const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth)
|
||||
if (bestTranscode?.url) {
|
||||
bestUrl = bestTranscode.url
|
||||
}
|
||||
|
||||
const handleDownload = useCallback(async () => {
|
||||
const key = file.media?.original?.key
|
||||
if (!key || !file.id) return
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: file.id },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: file.id },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}, [file.id, file.media?.original?.key, shareId])
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
(): ComparePaneHandle => ({
|
||||
getKind: () => 'image',
|
||||
play: () => {},
|
||||
pause: () => {},
|
||||
togglePlay: () => {},
|
||||
seekToFrame: () => {},
|
||||
seekToSecond: () => {},
|
||||
stepFrame: () => {},
|
||||
setMuted: () => {},
|
||||
setVolume: () => {},
|
||||
setPlaybackRate: () => {},
|
||||
toggleLoop: () => {},
|
||||
changeResolution: () => {},
|
||||
zoomBy: (factor) => applyZoom(factor),
|
||||
fit,
|
||||
panBy: (dx, dy) => setPan((p) => ({ x: p.x + dx, y: p.y + dy })),
|
||||
download: handleDownload,
|
||||
}),
|
||||
[applyZoom, fit, handleDownload],
|
||||
)
|
||||
|
||||
// Report state upward
|
||||
useEffect(() => {
|
||||
onStateChange({ kind: 'image', zoom })
|
||||
}, [zoom, onStateChange])
|
||||
|
||||
const displayAnnotations = [...annotations, ...(isActive ? draftAnnotations : [])]
|
||||
|
||||
const handlePan = useCallback(
|
||||
(newOffset: { x: number; y: number }) => {
|
||||
const prev = panRef.current
|
||||
const dx = newOffset.x - prev.x
|
||||
const dy = newOffset.y - prev.y
|
||||
setPan(newOffset)
|
||||
if (dx !== 0 || dy !== 0) onUserPan?.(dx, dy)
|
||||
},
|
||||
[onUserPan],
|
||||
)
|
||||
|
||||
if (!bestUrl) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center bg-gray-100 dark:bg-gray-950">
|
||||
<p className="text-muted-foreground">Preview unavailable</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="relative flex-1 overflow-hidden bg-gray-100 dark:bg-gray-950"
|
||||
onMouseDown={onActivate}
|
||||
>
|
||||
<DrawingCanvas
|
||||
width={conW}
|
||||
height={conH}
|
||||
mediaDimensions={{ width: imgW, height: imgH }}
|
||||
imageUrl={bestUrl}
|
||||
annotations={displayAnnotations}
|
||||
scale={zoom}
|
||||
offset={pan}
|
||||
onPan={handlePan}
|
||||
className="absolute inset-0 z-0"
|
||||
isDrawing={isActive && isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={isActive ? addAnnotation : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Check, ChevronDown, FileIcon, X } from 'lucide-react'
|
||||
import type { CompareSide } from './types'
|
||||
|
||||
interface VersionItem {
|
||||
id: string
|
||||
version: number
|
||||
name?: string | null
|
||||
previewUrl?: string | null
|
||||
creator?: { id: string; name: string | null } | null
|
||||
}
|
||||
|
||||
interface ComparePaneTopbarProps {
|
||||
side: CompareSide
|
||||
fileName: string
|
||||
version?: number
|
||||
activeVersionId: string
|
||||
versions: VersionItem[]
|
||||
isActive: boolean
|
||||
onActivate: () => void
|
||||
onSwitchVersion: (versionId: string) => void
|
||||
onExit: () => void
|
||||
}
|
||||
|
||||
export function ComparePaneTopbar({
|
||||
side,
|
||||
fileName,
|
||||
version,
|
||||
activeVersionId,
|
||||
versions,
|
||||
isActive,
|
||||
onActivate,
|
||||
onSwitchVersion,
|
||||
onExit,
|
||||
}: ComparePaneTopbarProps) {
|
||||
const iconButtonClass = cn(
|
||||
'flex-shrink-0 rounded p-1 transition-colors hover:bg-muted',
|
||||
isActive ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)
|
||||
|
||||
const exitButton = (
|
||||
<button onClick={onExit} title={m.exit_compare()} className={iconButtonClass}>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)
|
||||
|
||||
const label = (
|
||||
<button
|
||||
onClick={onActivate}
|
||||
className={cn(
|
||||
'flex min-w-0 items-center gap-1 rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-muted',
|
||||
isActive ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{fileName}</span>
|
||||
{version !== undefined && (
|
||||
<span
|
||||
className={cn(
|
||||
'flex-shrink-0 rounded border px-1 py-0 text-xs',
|
||||
isActive ? 'border-foreground/40' : 'border-border',
|
||||
)}
|
||||
>
|
||||
v{version}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
|
||||
const versionDropdown = (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
onClick={onActivate}
|
||||
title={m.switch_version()}
|
||||
className={iconButtonClass}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align={side === 'left' ? 'start' : 'end'} className="w-80 p-1">
|
||||
<div className="flex max-h-96 flex-col gap-1 overflow-y-auto">
|
||||
{versions.map((v) => {
|
||||
const isCurrent = v.id === activeVersionId
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={v.id}
|
||||
onClick={() => onSwitchVersion(v.id)}
|
||||
className="flex cursor-pointer items-center gap-3 rounded-md px-3 py-2"
|
||||
>
|
||||
<div className="flex min-w-[2rem] flex-shrink-0 items-center justify-center rounded-full bg-muted px-2 py-0.5 text-xs font-semibold text-muted-foreground select-none">
|
||||
v{v.version}
|
||||
</div>
|
||||
<div className="flex h-10 w-16 flex-shrink-0 items-center justify-center overflow-hidden rounded-md border border-border bg-muted">
|
||||
{v.previewUrl ? (
|
||||
<img
|
||||
src={v.previewUrl}
|
||||
alt={v.name || undefined}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<FileIcon className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 flex-col text-left">
|
||||
<span className="truncate text-sm font-semibold text-foreground">{v.name}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{v.creator?.name || 'Unknown'}
|
||||
</span>
|
||||
</div>
|
||||
{isCurrent && <Check className="ml-auto h-4 w-4 flex-shrink-0 text-primary" />}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
onMouseDown={onActivate}
|
||||
className={cn(
|
||||
// Force the dark palette so the bar is always dark with light text in
|
||||
// both light and dark app themes, using system tokens (no hardcoded hex).
|
||||
'dark flex h-10 flex-shrink-0 items-center gap-1 border-b bg-background px-2 transition-colors',
|
||||
isActive ? 'border-b-2 border-primary' : 'border-border',
|
||||
)}
|
||||
>
|
||||
{side === 'left' ? (
|
||||
<>
|
||||
{exitButton}
|
||||
{label}
|
||||
{versionDropdown}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{label}
|
||||
{versionDropdown}
|
||||
<div className="ml-auto" />
|
||||
{exitButton}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { kindOf, pickDefaultCompareVersions, clampFrame, isSameType } from './compare-utils'
|
||||
|
||||
describe('compare-utils', () => {
|
||||
describe('kindOf', () => {
|
||||
it('classifies image media types', () => {
|
||||
expect(kindOf('image/png')).toBe('image')
|
||||
expect(kindOf('image/webp')).toBe('image')
|
||||
})
|
||||
|
||||
it('classifies video media types', () => {
|
||||
expect(kindOf('video/mp4')).toBe('video')
|
||||
expect(kindOf('video/quicktime')).toBe('video')
|
||||
})
|
||||
|
||||
it('returns unsupported for missing or unknown types', () => {
|
||||
expect(kindOf(null)).toBe('unsupported')
|
||||
expect(kindOf(undefined)).toBe('unsupported')
|
||||
expect(kindOf('application/pdf')).toBe('unsupported')
|
||||
})
|
||||
})
|
||||
|
||||
describe('pickDefaultCompareVersions', () => {
|
||||
it('picks latest and latest-1 regardless of input order', () => {
|
||||
const versions = [
|
||||
{ id: 'a', version: 1 },
|
||||
{ id: 'c', version: 3 },
|
||||
{ id: 'b', version: 2 },
|
||||
]
|
||||
const pair = pickDefaultCompareVersions(versions)
|
||||
expect(pair).not.toBeNull()
|
||||
expect(pair!.left.id).toBe('c') // v3 (latest)
|
||||
expect(pair!.right.id).toBe('b') // v2 (latest - 1)
|
||||
})
|
||||
|
||||
it('returns null when fewer than two versions', () => {
|
||||
expect(pickDefaultCompareVersions([{ id: 'a', version: 1 }])).toBeNull()
|
||||
expect(pickDefaultCompareVersions([])).toBeNull()
|
||||
expect(pickDefaultCompareVersions(undefined)).toBeNull()
|
||||
expect(pickDefaultCompareVersions(null)).toBeNull()
|
||||
})
|
||||
|
||||
it('does not mutate the input array', () => {
|
||||
const versions = [
|
||||
{ id: 'a', version: 1 },
|
||||
{ id: 'b', version: 2 },
|
||||
]
|
||||
pickDefaultCompareVersions(versions)
|
||||
expect(versions.map((v) => v.id)).toEqual(['a', 'b'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('clampFrame', () => {
|
||||
it('clamps to the last frame when beyond total (shorter side holds last frame)', () => {
|
||||
expect(clampFrame(500, 100)).toBe(99)
|
||||
})
|
||||
|
||||
it('clamps negative frames to zero', () => {
|
||||
expect(clampFrame(-5, 100)).toBe(0)
|
||||
})
|
||||
|
||||
it('passes through in-range frames', () => {
|
||||
expect(clampFrame(42, 100)).toBe(42)
|
||||
})
|
||||
|
||||
it('handles zero-length safely', () => {
|
||||
expect(clampFrame(10, 0)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isSameType', () => {
|
||||
it('true only for matching, supported kinds', () => {
|
||||
expect(isSameType('video', 'video')).toBe(true)
|
||||
expect(isSameType('image', 'image')).toBe(true)
|
||||
})
|
||||
|
||||
it('false for mismatched or unsupported kinds', () => {
|
||||
expect(isSameType('video', 'image')).toBe(false)
|
||||
expect(isSameType('unsupported', 'unsupported')).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { PaneKind } from './types'
|
||||
|
||||
/** Classify an asset's media type into a compare pane kind. */
|
||||
export function kindOf(mediaType: string | null | undefined): PaneKind {
|
||||
if (!mediaType) return 'unsupported'
|
||||
if (mediaType.startsWith('image/')) return 'image'
|
||||
if (mediaType.startsWith('video/')) return 'video'
|
||||
return 'unsupported'
|
||||
}
|
||||
|
||||
interface VersionLike {
|
||||
id: string
|
||||
version: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a version stack's versions, pick the default compare pair:
|
||||
* left = latest (highest version number), right = latest - 1.
|
||||
* Returns null if fewer than two versions exist.
|
||||
*/
|
||||
export function pickDefaultCompareVersions(
|
||||
versions: ReadonlyArray<VersionLike> | undefined | null,
|
||||
): { left: VersionLike; right: VersionLike } | null {
|
||||
if (!versions || versions.length < 2) return null
|
||||
const sorted = [...versions].sort((a, b) => b.version - a.version)
|
||||
return { left: sorted[0], right: sorted[1] }
|
||||
}
|
||||
|
||||
/** Clamp a frame index into the valid range [0, totalFrames - 1]. */
|
||||
export function clampFrame(frame: number, totalFrames: number): number {
|
||||
return Math.max(0, Math.min(frame, Math.max(0, totalFrames - 1)))
|
||||
}
|
||||
|
||||
/** True when both panes hold the same (non-unsupported) media kind. */
|
||||
export function isSameType(left: PaneKind, right: PaneKind): boolean {
|
||||
return left === right && left !== 'unsupported'
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import DrawingCanvas from '@/ui/components/drawing-canvas'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { Play } from 'lucide-react'
|
||||
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
|
||||
import videojs from 'video.js'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import { useFramePlayer } from '@/ui/components/viewers/use-frame-player'
|
||||
import { resolveTotalFrames } from '@/ui/components/viewers/utils'
|
||||
import { clampFrame as clampFrameUtil } from './compare-utils'
|
||||
import type { ComparePaneHandle, DisplayTranscode, PaneReportedState } from './types'
|
||||
|
||||
interface CompareVideoPaneProps {
|
||||
file: AssetInfo
|
||||
shareId?: string
|
||||
isActive: boolean
|
||||
/** Whether this pane's audio should be muted (only the active side plays audio). */
|
||||
muted: boolean
|
||||
volume: number
|
||||
annotations: Annotation[]
|
||||
onStateChange: (state: PaneReportedState) => void
|
||||
onActivate?: () => void
|
||||
onRequestTogglePlay?: () => void
|
||||
/** Called with the current playhead time in seconds (used only for the active pane). */
|
||||
onTimeUpdate?: (second: number) => void
|
||||
onPlay?: () => void
|
||||
}
|
||||
|
||||
function computeResolutions(file: AssetInfo): DisplayTranscode[] {
|
||||
const original: DisplayTranscode | null = file.media?.original?.downloadUrl
|
||||
? {
|
||||
id: 'original',
|
||||
url: file.media.original.downloadUrl,
|
||||
key: file.media.original.key ?? '',
|
||||
width: file.media?.metadata?.originalWidth ?? 0,
|
||||
height: file.media?.metadata?.originalHeight ?? 0,
|
||||
size: 0,
|
||||
isRaw: true,
|
||||
resolution: 'Original',
|
||||
}
|
||||
: null
|
||||
|
||||
const transcodes: DisplayTranscode[] = (file.media?.videoTranscodes ?? []).map((t) => {
|
||||
const longSide = Math.max(t.width, t.height)
|
||||
let resolution = `${t.height}p`
|
||||
if (longSide >= 3840) resolution = '2160p'
|
||||
else if (longSide >= 1920) resolution = '1080p'
|
||||
else if (longSide >= 1280) resolution = '720p'
|
||||
else if (longSide >= 960) resolution = '540p'
|
||||
else if (longSide >= 640) resolution = '360p'
|
||||
else if (longSide >= 320) resolution = '180p'
|
||||
return { ...t, resolution: t.isRaw ? 'Original' : resolution }
|
||||
})
|
||||
|
||||
const hasOriginalTranscode = transcodes.some((t) => t.isRaw)
|
||||
if (!hasOriginalTranscode && original) {
|
||||
return [...transcodes, original]
|
||||
}
|
||||
return transcodes
|
||||
}
|
||||
|
||||
export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPaneProps>(
|
||||
function CompareVideoPane(
|
||||
{
|
||||
file,
|
||||
shareId,
|
||||
isActive,
|
||||
muted,
|
||||
volume,
|
||||
annotations,
|
||||
onStateChange,
|
||||
onActivate,
|
||||
onRequestTogglePlay,
|
||||
onTimeUpdate,
|
||||
onPlay,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const playerRef = useRef<Player | null>(null)
|
||||
const videoContainerRef = useRef<HTMLDivElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null)
|
||||
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
|
||||
|
||||
const {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
addAnnotation,
|
||||
annotations: draftAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
|
||||
const [pan, setPan] = useState<{ x: number; y: number } | null>(null)
|
||||
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [isLooping, setIsLooping] = useState(false)
|
||||
const [playbackRate, setPlaybackRate] = useState(1)
|
||||
const [buffered, setBuffered] = useState(0)
|
||||
const [playerVolume, setPlayerVolume] = useState(volume)
|
||||
const [playerMuted, setPlayerMuted] = useState(muted)
|
||||
const [isPlayerReady, setIsPlayerReady] = useState(false)
|
||||
|
||||
const metadata = file.media?.metadata
|
||||
const frameRate = metadata?.frameRate || 30
|
||||
const dbTotalFrames = metadata?.totalFrames || 0
|
||||
const containerDuration = metadata?.duration || 0
|
||||
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
|
||||
|
||||
const resolutions = computeResolutions(file)
|
||||
const previewResolutions = resolutions.filter((r) => !r.isRaw)
|
||||
const initialRes = previewResolutions[0] ?? resolutions[0]
|
||||
const [currentResolution, setCurrentResolution] = useState(initialRes?.resolution ?? 'Original')
|
||||
const currentSrcRef = useRef(initialRes?.url)
|
||||
|
||||
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
|
||||
|
||||
const zoomRef = useRef(zoom)
|
||||
zoomRef.current = zoom
|
||||
const currentFrameRef = useRef(currentFrame)
|
||||
currentFrameRef.current = currentFrame
|
||||
|
||||
// Resize observer
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const entry = entries[0]
|
||||
if (entry) {
|
||||
setContainerSize({ width: entry.contentRect.width, height: entry.contentRect.height })
|
||||
}
|
||||
})
|
||||
observer.observe(containerRef.current)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const vidW = metadata?.originalWidth ?? 1920
|
||||
const vidH = metadata?.originalHeight ?? 1080
|
||||
|
||||
// Auto-fit zoom
|
||||
useEffect(() => {
|
||||
if (containerSize.width > 0 && containerSize.height > 0 && !hasManuallyZoomed) {
|
||||
const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH)
|
||||
setZoom(scale)
|
||||
}
|
||||
}, [containerSize.width, containerSize.height, vidW, vidH, hasManuallyZoomed])
|
||||
|
||||
// Keep the resolution selection and source url in sync when the displayed
|
||||
// asset changes, so the player (re)initializes with the correct source even
|
||||
// if the parent renders this pane without a per-asset `key`. Runs before the
|
||||
// video.js init effect below (declaration order) so the ref is fresh.
|
||||
useEffect(() => {
|
||||
setCurrentResolution(initialRes?.resolution ?? 'Original')
|
||||
currentSrcRef.current = initialRes?.url
|
||||
}, [file.id])
|
||||
|
||||
// Initialize video.js
|
||||
useEffect(() => {
|
||||
if (!videoContainerRef.current) return
|
||||
const videoElement = document.createElement('video-js')
|
||||
videoElement.classList.add('vjs-big-play-centered', '!h-full', '!w-full')
|
||||
videoElement.style.opacity = '0'
|
||||
videoElement.style.pointerEvents = 'none'
|
||||
videoContainerRef.current.appendChild(videoElement)
|
||||
|
||||
const player = (playerRef.current = videojs(videoElement, {
|
||||
controls: false,
|
||||
autoplay: false,
|
||||
preload: 'auto',
|
||||
playsinline: true,
|
||||
sources: [{ src: currentSrcRef.current ?? '', type: 'video/mp4' }],
|
||||
}))
|
||||
|
||||
const htmlVid = videoElement.querySelector('video')
|
||||
if (htmlVid) {
|
||||
setVideoHtmlEl(htmlVid)
|
||||
videoRef.current = htmlVid
|
||||
} else {
|
||||
player.ready(() => {
|
||||
const techEl = player.tech({ iWillNotUseThisInPlugins: true })?.el() as HTMLVideoElement
|
||||
if (techEl) {
|
||||
setVideoHtmlEl(techEl)
|
||||
videoRef.current = techEl
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
player.on('play', () => {
|
||||
setIsPlaying(true)
|
||||
onPlay?.()
|
||||
})
|
||||
player.on('pause', () => setIsPlaying(false))
|
||||
player.on('ended', () => setIsPlaying(false))
|
||||
player.on('loadedmetadata', () => setIsPlayerReady(true))
|
||||
player.on('loadstart', () => setIsPlayerReady(false))
|
||||
player.on('timeupdate', () => {
|
||||
const playerDuration = player.duration() || containerDuration || 0
|
||||
const bufferedEnd = player.bufferedEnd()
|
||||
if (playerDuration > 0) setBuffered((bufferedEnd / playerDuration) * 100)
|
||||
})
|
||||
player.on('volumechange', () => {
|
||||
setPlayerVolume(player.volume() || 0)
|
||||
setPlayerMuted(player.muted() || false)
|
||||
})
|
||||
player.on('ratechange', () => setPlaybackRate(player.playbackRate() || 1))
|
||||
|
||||
return () => {
|
||||
if (player && !player.isDisposed()) {
|
||||
player.dispose()
|
||||
playerRef.current = null
|
||||
videoRef.current = null
|
||||
}
|
||||
}
|
||||
}, [file.id])
|
||||
|
||||
// Apply muted / volume (audio routing: only active side unmuted)
|
||||
useEffect(() => {
|
||||
const player = playerRef.current
|
||||
if (!player || !isPlayerReady) return
|
||||
player.muted(muted)
|
||||
player.volume(volume)
|
||||
}, [muted, volume, isPlayerReady])
|
||||
|
||||
// Report state upward
|
||||
useEffect(() => {
|
||||
const state: PaneReportedState = {
|
||||
kind: 'video',
|
||||
zoom,
|
||||
video: {
|
||||
frameRate,
|
||||
totalFrames,
|
||||
currentFrame,
|
||||
isPlaying,
|
||||
volume: playerVolume,
|
||||
isMuted: playerMuted,
|
||||
playbackRate,
|
||||
isLooping,
|
||||
currentResolution,
|
||||
resolutions,
|
||||
buffered,
|
||||
},
|
||||
}
|
||||
onStateChange(state)
|
||||
}, [
|
||||
zoom,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
currentFrame,
|
||||
isPlaying,
|
||||
playerVolume,
|
||||
playerMuted,
|
||||
playbackRate,
|
||||
isLooping,
|
||||
currentResolution,
|
||||
buffered,
|
||||
])
|
||||
|
||||
// Propagate active playhead time
|
||||
useEffect(() => {
|
||||
if (isActive) onTimeUpdate?.(currentFrame / frameRate)
|
||||
}, [currentFrame, frameRate, isActive, onTimeUpdate])
|
||||
|
||||
const applyZoom = useCallback((factor: number) => {
|
||||
const cur = zoomRef.current
|
||||
const newZoom = cur * factor
|
||||
if (newZoom < 0.01 || newZoom > 50) return
|
||||
setZoom(newZoom)
|
||||
setHasManuallyZoomed(true)
|
||||
}, [])
|
||||
|
||||
const fit = useCallback(() => {
|
||||
setHasManuallyZoomed(false)
|
||||
setPan(null)
|
||||
}, [])
|
||||
|
||||
const clampFrame = useCallback(
|
||||
(frame: number) => clampFrameUtil(frame, totalFrames),
|
||||
[totalFrames],
|
||||
)
|
||||
|
||||
const handleDownload = useCallback(
|
||||
async (key?: string) => {
|
||||
const dlKey = key ?? file.media?.original?.key
|
||||
if (!dlKey || !file.id) return
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: file.id },
|
||||
json: { key: dlKey },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key: dlKey, assetId: file.id },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
},
|
||||
[file.id, file.media?.original?.key, shareId],
|
||||
)
|
||||
|
||||
const changeResolution = useCallback(
|
||||
(resolution: string) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
const target = resolutions.find((r) => r.resolution === resolution)
|
||||
if (!target) return
|
||||
const wasPlaying = !player.paused()
|
||||
const currentT = player.currentTime()
|
||||
setCurrentResolution(resolution)
|
||||
currentSrcRef.current = target.url
|
||||
player.src({ type: 'video/mp4', src: target.url })
|
||||
player.one('loadedmetadata', () => {
|
||||
player.currentTime(currentT)
|
||||
if (wasPlaying) {
|
||||
const p = player.play()
|
||||
if (p !== undefined) p.catch(() => {})
|
||||
}
|
||||
})
|
||||
},
|
||||
[resolutions],
|
||||
)
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
(): ComparePaneHandle => ({
|
||||
getKind: () => 'video',
|
||||
play: () => {
|
||||
const p = playerRef.current?.play()
|
||||
if (p !== undefined) p.catch(() => {})
|
||||
},
|
||||
pause: () => playerRef.current?.pause(),
|
||||
togglePlay: () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
if (player.paused() || player.ended()) {
|
||||
const p = player.play()
|
||||
if (p !== undefined) p.catch(() => {})
|
||||
} else {
|
||||
player.pause()
|
||||
}
|
||||
},
|
||||
seekToFrame: (frame) => seekToFrame(clampFrame(frame)),
|
||||
seekToSecond: (second) => {
|
||||
const frame = Math.floor(second * frameRate + 0.45)
|
||||
seekToFrame(clampFrame(frame))
|
||||
},
|
||||
stepFrame: (delta) => seekToFrame(clampFrame(currentFrameRef.current + delta)),
|
||||
setMuted: (m) => playerRef.current?.muted(m),
|
||||
setVolume: (v) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
player.volume(v)
|
||||
if (v > 0 && player.muted()) player.muted(false)
|
||||
else if (v === 0 && !player.muted()) player.muted(true)
|
||||
},
|
||||
setPlaybackRate: (rate) => playerRef.current?.playbackRate(rate),
|
||||
toggleLoop: () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
const next = !player.loop()
|
||||
player.loop(next)
|
||||
setIsLooping(next)
|
||||
},
|
||||
changeResolution,
|
||||
zoomBy: applyZoom,
|
||||
fit,
|
||||
panBy: (dx, dy) =>
|
||||
setPan((p) => {
|
||||
const scale = zoomRef.current
|
||||
const base = p ?? {
|
||||
x: (containerSize.width - vidW * scale) / 2,
|
||||
y: (containerSize.height - vidH * scale) / 2,
|
||||
}
|
||||
return { x: base.x + dx, y: base.y + dy }
|
||||
}),
|
||||
download: (key?: string) => handleDownload(key),
|
||||
}),
|
||||
[
|
||||
seekToFrame,
|
||||
clampFrame,
|
||||
frameRate,
|
||||
applyZoom,
|
||||
fit,
|
||||
changeResolution,
|
||||
handleDownload,
|
||||
containerSize.width,
|
||||
containerSize.height,
|
||||
vidW,
|
||||
vidH,
|
||||
],
|
||||
)
|
||||
|
||||
const displayAnnotations = [...annotations, ...(isActive ? draftAnnotations : [])]
|
||||
|
||||
const scale = zoom
|
||||
const defaultPanX = (containerSize.width - vidW * scale) / 2
|
||||
const defaultPanY = (containerSize.height - vidH * scale) / 2
|
||||
const panX = pan?.x ?? defaultPanX
|
||||
const panY = pan?.y ?? defaultPanY
|
||||
|
||||
const handleAreaClick = useCallback(() => {
|
||||
if (useAnnotationStore.getState().isDrawing) return
|
||||
// Clicking an inactive pane only activates it; playback is untouched.
|
||||
if (!isActive) {
|
||||
onActivate?.()
|
||||
return
|
||||
}
|
||||
onRequestTogglePlay?.()
|
||||
}, [isActive, onActivate, onRequestTogglePlay])
|
||||
|
||||
if (!file.media?.original?.downloadUrl || !metadata) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-black">
|
||||
<p className="text-muted-foreground">Media is not available.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
'relative flex flex-1 cursor-pointer items-center justify-center overflow-hidden bg-black',
|
||||
)}
|
||||
onClick={handleAreaClick}
|
||||
data-testid="compare-video-area"
|
||||
>
|
||||
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
|
||||
|
||||
{videoHtmlEl && containerSize.width > 0 && (
|
||||
<DrawingCanvas
|
||||
width={containerSize.width}
|
||||
height={containerSize.height}
|
||||
mediaDimensions={{ width: vidW, height: vidH }}
|
||||
videoElement={videoHtmlEl}
|
||||
annotations={displayAnnotations}
|
||||
scale={scale}
|
||||
offset={{ x: panX, y: panY }}
|
||||
className="absolute inset-0"
|
||||
onClick={handleAreaClick}
|
||||
isDrawing={isActive && isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={isActive ? addAnnotation : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isPlaying && !isDrawing && (
|
||||
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full border-2 border-white/30 bg-white/10 backdrop-blur-sm">
|
||||
<Play className="ml-1 h-8 w-8 fill-white text-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,355 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { CompareControlBar } from './compare-control-bar'
|
||||
import { CompareImagePane } from './compare-image-pane'
|
||||
import { ComparePaneTopbar } from './compare-pane-topbar'
|
||||
import { isSameType, kindOf } from './compare-utils'
|
||||
import { CompareVideoPane } from './compare-video-pane'
|
||||
import type { ComparePaneHandle, CompareSide, PaneKind, PaneReportedState } from './types'
|
||||
|
||||
interface VersionItem {
|
||||
id: string
|
||||
version: number
|
||||
name?: string | null
|
||||
previewUrl?: string | null
|
||||
creator?: { id: string; name: string | null } | null
|
||||
}
|
||||
|
||||
interface CompareViewerProps {
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
versions: VersionItem[]
|
||||
leftId: string
|
||||
rightId: string
|
||||
activeSide: CompareSide
|
||||
annotations: Annotation[]
|
||||
/** Bumped nonce requests the active pane seek to `second` (comment navigation). */
|
||||
seekRequest?: { second: number; nonce: number }
|
||||
onActiveSideChange: (side: CompareSide) => void
|
||||
onSwitchVersion: (side: CompareSide, versionId: string) => void
|
||||
onExit: () => void
|
||||
onActiveAssetChange: (asset: AssetInfo | null) => void
|
||||
onPlay?: () => void
|
||||
onTimeUpdate?: (second: number) => void
|
||||
}
|
||||
|
||||
function useCompareAsset(id: string, isPublic: boolean, shareId?: string) {
|
||||
return useQuery({
|
||||
queryKey: isPublic
|
||||
? ['public-share-file', shareId, id, localStorage.getItem(`share_pwd_${shareId}`) || '']
|
||||
: ['files', id],
|
||||
queryFn: async () => {
|
||||
if (isPublic) {
|
||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
|
||||
{ param: { shareId: shareId!, fileId: id } },
|
||||
{ headers: { 'x-share-password': password } },
|
||||
)
|
||||
if (!res.ok) throw new Error('Failed to fetch version asset')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
}
|
||||
const res = await client.api.files[':fileId'].$get({ param: { fileId: id } })
|
||||
if (!res.ok) throw new Error('Failed to fetch version asset')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: !!id && (!isPublic || !!shareId),
|
||||
})
|
||||
}
|
||||
|
||||
export function CompareViewer({
|
||||
isPublic = false,
|
||||
shareId,
|
||||
versions,
|
||||
leftId,
|
||||
rightId,
|
||||
activeSide,
|
||||
annotations,
|
||||
seekRequest,
|
||||
onActiveSideChange,
|
||||
onSwitchVersion,
|
||||
onExit,
|
||||
onActiveAssetChange,
|
||||
onPlay,
|
||||
onTimeUpdate,
|
||||
}: CompareViewerProps) {
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const leftRef = useRef<ComparePaneHandle | null>(null)
|
||||
const rightRef = useRef<ComparePaneHandle | null>(null)
|
||||
|
||||
const [leftState, setLeftState] = useState<PaneReportedState | null>(null)
|
||||
const [rightState, setRightState] = useState<PaneReportedState | null>(null)
|
||||
const [userVolume, setUserVolume] = useState(1)
|
||||
const [userMuted, setUserMuted] = useState(false)
|
||||
const [isFullScreen, setIsFullScreen] = useState(false)
|
||||
|
||||
const { data: leftAsset, isLoading: leftLoading } = useCompareAsset(leftId, isPublic, shareId)
|
||||
const { data: rightAsset, isLoading: rightLoading } = useCompareAsset(rightId, isPublic, shareId)
|
||||
|
||||
const leftKind = kindOf(leftAsset?.mediaType)
|
||||
const rightKind = kindOf(rightAsset?.mediaType)
|
||||
const sameType = isSameType(leftKind, rightKind)
|
||||
|
||||
const activeAsset = activeSide === 'left' ? leftAsset : rightAsset
|
||||
const activeState = activeSide === 'left' ? leftState : rightState
|
||||
|
||||
const getActive = useCallback(
|
||||
() => (activeSide === 'left' ? leftRef.current : rightRef.current),
|
||||
[activeSide],
|
||||
)
|
||||
const getOther = useCallback(
|
||||
() => (activeSide === 'left' ? rightRef.current : leftRef.current),
|
||||
[activeSide],
|
||||
)
|
||||
|
||||
// Bind right sidebar to active asset
|
||||
useEffect(() => {
|
||||
onActiveAssetChange(activeAsset ?? null)
|
||||
}, [activeAsset, onActiveAssetChange])
|
||||
|
||||
// Comment-driven seek on the active pane
|
||||
useEffect(() => {
|
||||
if (!seekRequest) return
|
||||
const active = getActive()
|
||||
active?.seekToSecond(seekRequest.second)
|
||||
active?.pause()
|
||||
if (sameType) {
|
||||
const other = getOther()
|
||||
other?.seekToSecond(seekRequest.second)
|
||||
other?.pause()
|
||||
}
|
||||
}, [seekRequest?.nonce])
|
||||
|
||||
// Fullscreen tracking
|
||||
useEffect(() => {
|
||||
const onFs = () => setIsFullScreen(!!document.fullscreenElement)
|
||||
document.addEventListener('fullscreenchange', onFs)
|
||||
return () => document.removeEventListener('fullscreenchange', onFs)
|
||||
}, [])
|
||||
|
||||
const handleStateChangeLeft = useCallback((s: PaneReportedState) => setLeftState(s), [])
|
||||
const handleStateChangeRight = useCallback((s: PaneReportedState) => setRightState(s), [])
|
||||
|
||||
const applyBoth = useCallback(
|
||||
(fn: (h: ComparePaneHandle) => void) => {
|
||||
const active = getActive()
|
||||
if (active) fn(active)
|
||||
if (sameType) {
|
||||
const other = getOther()
|
||||
if (other) fn(other)
|
||||
}
|
||||
},
|
||||
[getActive, getOther, sameType],
|
||||
)
|
||||
|
||||
// --- Control handlers ---
|
||||
const handleTogglePlay = useCallback(() => {
|
||||
const shouldPlay = !activeState?.video?.isPlaying
|
||||
applyBoth((h) => (shouldPlay ? h.play() : h.pause()))
|
||||
}, [activeState?.video?.isPlaying, applyBoth])
|
||||
|
||||
const handleSeek = useCallback(
|
||||
(frame: number) => applyBoth((h) => h.seekToFrame(frame)),
|
||||
[applyBoth],
|
||||
)
|
||||
|
||||
const handleToggleLoop = useCallback(() => getActive()?.toggleLoop(), [getActive])
|
||||
|
||||
const handleVolumeChange = useCallback((v: number) => {
|
||||
setUserVolume(v)
|
||||
setUserMuted(v === 0)
|
||||
}, [])
|
||||
|
||||
const handleToggleMute = useCallback(() => setUserMuted((m) => !m), [])
|
||||
|
||||
const handlePlaybackRate = useCallback(
|
||||
(rate: number) => applyBoth((h) => h.setPlaybackRate(rate)),
|
||||
[applyBoth],
|
||||
)
|
||||
|
||||
const handleChangeResolution = useCallback(
|
||||
(resolution: string) => getActive()?.changeResolution(resolution),
|
||||
[getActive],
|
||||
)
|
||||
|
||||
const handleZoomIn = useCallback(() => applyBoth((h) => h.zoomBy(1.2)), [applyBoth])
|
||||
const handleZoomOut = useCallback(() => applyBoth((h) => h.zoomBy(0.8)), [applyBoth])
|
||||
const handleFit = useCallback(() => applyBoth((h) => h.fit()), [applyBoth])
|
||||
const handleDownload = useCallback(
|
||||
(key?: string) => {
|
||||
getActive()?.download(key)
|
||||
},
|
||||
[getActive],
|
||||
)
|
||||
|
||||
const handleToggleFullScreen = useCallback(() => {
|
||||
if (!rootRef.current) return
|
||||
if (!document.fullscreenElement) {
|
||||
rootRef.current.requestFullscreen()
|
||||
} else {
|
||||
document.exitFullscreen()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleUserPanLeft = useCallback(
|
||||
(dx: number, dy: number) => {
|
||||
if (sameType) rightRef.current?.panBy(dx, dy)
|
||||
},
|
||||
[sameType],
|
||||
)
|
||||
const handleUserPanRight = useCallback(
|
||||
(dx: number, dy: number) => {
|
||||
if (sameType) leftRef.current?.panBy(dx, dy)
|
||||
},
|
||||
[sameType],
|
||||
)
|
||||
|
||||
const handleRequestTogglePlay = useCallback(() => handleTogglePlay(), [handleTogglePlay])
|
||||
|
||||
const versionOf = useCallback(
|
||||
(id: string) => versions.find((v) => v.id === id)?.version,
|
||||
[versions],
|
||||
)
|
||||
|
||||
const activePreviewUrl = useMemo(
|
||||
() => activeAsset?.media?.videoPreview?.url,
|
||||
[activeAsset?.media?.videoPreview?.url],
|
||||
)
|
||||
|
||||
const renderPane = (side: CompareSide, asset: AssetInfo, kind: PaneKind) => {
|
||||
const isActive = activeSide === side
|
||||
const paneRef = side === 'left' ? leftRef : rightRef
|
||||
const onStateChange = side === 'left' ? handleStateChangeLeft : handleStateChangeRight
|
||||
const onUserPan = side === 'left' ? handleUserPanLeft : handleUserPanRight
|
||||
const paneAnnotations = isActive ? annotations : []
|
||||
|
||||
if (kind === 'video') {
|
||||
return (
|
||||
<CompareVideoPane
|
||||
key={asset.id}
|
||||
ref={paneRef}
|
||||
file={asset}
|
||||
shareId={shareId}
|
||||
isActive={isActive}
|
||||
muted={isActive ? userMuted : true}
|
||||
volume={userVolume}
|
||||
annotations={paneAnnotations}
|
||||
onStateChange={onStateChange}
|
||||
onActivate={() => onActiveSideChange(side)}
|
||||
onRequestTogglePlay={handleRequestTogglePlay}
|
||||
onTimeUpdate={onTimeUpdate}
|
||||
onPlay={onPlay}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (kind === 'image') {
|
||||
return (
|
||||
<CompareImagePane
|
||||
key={asset.id}
|
||||
ref={paneRef}
|
||||
file={asset}
|
||||
shareId={shareId}
|
||||
isActive={isActive}
|
||||
annotations={paneAnnotations}
|
||||
onStateChange={onStateChange}
|
||||
onUserPan={onUserPan}
|
||||
onActivate={() => onActiveSideChange(side)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center bg-gray-100 dark:bg-gray-950">
|
||||
<p className="text-muted-foreground">Preview unavailable</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const bothLoaded = !!leftAsset && !!rightAsset
|
||||
const isLoading = leftLoading || rightLoading
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className="flex h-full flex-1 flex-col bg-background">
|
||||
<div className="flex min-h-0 flex-1">
|
||||
{/* Left pane */}
|
||||
<div className="flex min-w-0 flex-1 flex-col border-r border-zinc-800">
|
||||
{leftAsset && (
|
||||
<ComparePaneTopbar
|
||||
side="left"
|
||||
fileName={leftAsset.name}
|
||||
version={versionOf(leftId)}
|
||||
activeVersionId={leftId}
|
||||
versions={versions}
|
||||
isActive={activeSide === 'left'}
|
||||
onActivate={() => onActiveSideChange('left')}
|
||||
onSwitchVersion={(vid) => onSwitchVersion('left', vid)}
|
||||
onExit={onExit}
|
||||
/>
|
||||
)}
|
||||
<div className="relative flex min-h-0 flex-1">
|
||||
{leftAsset ? (
|
||||
renderPane('left', leftAsset, leftKind)
|
||||
) : (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right pane */}
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
{rightAsset && (
|
||||
<ComparePaneTopbar
|
||||
side="right"
|
||||
fileName={rightAsset.name}
|
||||
version={versionOf(rightId)}
|
||||
activeVersionId={rightId}
|
||||
versions={versions}
|
||||
isActive={activeSide === 'right'}
|
||||
onActivate={() => onActiveSideChange('right')}
|
||||
onSwitchVersion={(vid) => onSwitchVersion('right', vid)}
|
||||
onExit={onExit}
|
||||
/>
|
||||
)}
|
||||
<div className="relative flex min-h-0 flex-1">
|
||||
{rightAsset ? (
|
||||
renderPane('right', rightAsset, rightKind)
|
||||
) : (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading && !bothLoaded && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/30">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CompareControlBar
|
||||
activeState={activeState}
|
||||
activeAsset={activeAsset ?? null}
|
||||
previewUrl={activePreviewUrl}
|
||||
isFullScreen={isFullScreen}
|
||||
onTogglePlay={handleTogglePlay}
|
||||
onToggleLoop={handleToggleLoop}
|
||||
onSeek={handleSeek}
|
||||
onVolumeChange={handleVolumeChange}
|
||||
onToggleMute={handleToggleMute}
|
||||
onChangePlaybackRate={handlePlaybackRate}
|
||||
onChangeResolution={handleChangeResolution}
|
||||
onZoomIn={handleZoomIn}
|
||||
onZoomOut={handleZoomOut}
|
||||
onFit={handleFit}
|
||||
onDownload={handleDownload}
|
||||
onToggleFullScreen={handleToggleFullScreen}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { VideoTranscode } from '@shumai/dtos'
|
||||
|
||||
export type PaneKind = 'image' | 'video' | 'unsupported'
|
||||
|
||||
export type CompareSide = 'left' | 'right'
|
||||
|
||||
export type DisplayTranscode = VideoTranscode & { resolution: string }
|
||||
|
||||
/**
|
||||
* Reactive state a pane reports upward so the shared control bar can render.
|
||||
* `video` is populated only for video panes.
|
||||
*/
|
||||
export interface PaneReportedState {
|
||||
kind: PaneKind
|
||||
zoom: number
|
||||
video?: {
|
||||
frameRate: number
|
||||
totalFrames: number
|
||||
currentFrame: number
|
||||
isPlaying: boolean
|
||||
volume: number
|
||||
isMuted: boolean
|
||||
playbackRate: number
|
||||
isLooping: boolean
|
||||
currentResolution: string
|
||||
resolutions: DisplayTranscode[]
|
||||
buffered: number
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Imperative command surface exposed by each pane via ref. The shared control
|
||||
* bar dispatches to the active pane (and, when media types match, to both).
|
||||
*/
|
||||
export interface ComparePaneHandle {
|
||||
getKind: () => PaneKind
|
||||
// Playback (video only; no-ops for images)
|
||||
play: () => void
|
||||
pause: () => void
|
||||
togglePlay: () => void
|
||||
seekToFrame: (frame: number) => void
|
||||
seekToSecond: (second: number) => void
|
||||
stepFrame: (delta: number) => void
|
||||
setMuted: (muted: boolean) => void
|
||||
setVolume: (volume: number) => void
|
||||
setPlaybackRate: (rate: number) => void
|
||||
toggleLoop: () => void
|
||||
changeResolution: (resolution: string) => void
|
||||
// Zoom / pan (image + video)
|
||||
zoomBy: (factor: number) => void
|
||||
fit: () => void
|
||||
panBy: (dx: number, dy: number) => void
|
||||
// Download active side's original/selected media
|
||||
download: (key?: string) => void
|
||||
}
|
||||
@@ -276,7 +276,7 @@ export function FileCard({
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<FilePreview item={displayItem} />
|
||||
<FilePreview item={displayItem} showDuration />
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { File, Folder } from 'lucide-react'
|
||||
import { SpriteScrubber } from '../sprite-scrubber'
|
||||
import { formatTime } from '../viewers/utils'
|
||||
|
||||
type FilePreviewItem = {
|
||||
type?: string | null
|
||||
@@ -9,39 +10,56 @@ type FilePreviewItem = {
|
||||
thumbnailUrl?: string
|
||||
originalWidth?: number
|
||||
originalHeight?: number
|
||||
duration?: number
|
||||
} | null
|
||||
}
|
||||
|
||||
interface FilePreviewProps {
|
||||
item: FilePreviewItem
|
||||
showDuration?: boolean
|
||||
}
|
||||
|
||||
export const FilePreview = ({ item }: FilePreviewProps) => {
|
||||
export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) => {
|
||||
const isVideo = item.preview?.mediaType?.startsWith('video/')
|
||||
const duration = item.preview?.duration
|
||||
const durationOverlay =
|
||||
showDuration && isVideo && typeof duration === 'number' && duration > 0 ? (
|
||||
<span className="pointer-events-none absolute bottom-1 right-1 text-xs font-medium tabular-nums text-white">
|
||||
{formatTime(duration)}
|
||||
</span>
|
||||
) : null
|
||||
|
||||
const isVideoWithSprite =
|
||||
item.preview?.mediaType?.startsWith('video/') &&
|
||||
item.preview.spriteUrl &&
|
||||
isVideo &&
|
||||
item.preview?.spriteUrl &&
|
||||
item.preview.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
item.preview.originalHeight
|
||||
|
||||
if (isVideoWithSprite && item.preview) {
|
||||
return (
|
||||
<SpriteScrubber
|
||||
spriteUrl={item.preview.spriteUrl!}
|
||||
thumbnailUrl={item.preview.thumbnailUrl!}
|
||||
videoWidth={item.preview.originalWidth!}
|
||||
videoHeight={item.preview.originalHeight!}
|
||||
/>
|
||||
<>
|
||||
<SpriteScrubber
|
||||
spriteUrl={item.preview.spriteUrl!}
|
||||
thumbnailUrl={item.preview.thumbnailUrl!}
|
||||
videoWidth={item.preview.originalWidth!}
|
||||
videoHeight={item.preview.originalHeight!}
|
||||
/>
|
||||
{durationOverlay}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
if (item.preview?.thumbnailUrl) {
|
||||
return (
|
||||
<img
|
||||
src={item.preview.thumbnailUrl}
|
||||
alt="Preview"
|
||||
className="w-full h-full object-contain bg-black"
|
||||
/>
|
||||
<>
|
||||
<img
|
||||
src={item.preview.thumbnailUrl}
|
||||
alt="Preview"
|
||||
className="w-full h-full object-contain bg-black"
|
||||
/>
|
||||
{durationOverlay}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useScreenSize } from '@/ui/hooks/useScreenSize'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { getBestTranscode } from '@/ui/lib/media'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { Check, Copy, Download, Minus, Plus } from 'lucide-react'
|
||||
import { Download } from 'lucide-react'
|
||||
import type { ReactNode, RefObject } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import DrawingCanvas from './drawing-canvas'
|
||||
import VideoPlayer from './viewers/video-player'
|
||||
import { ImageControlBar } from './viewers/image-control-bar'
|
||||
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
@@ -19,6 +21,7 @@ type FileViewerProps = {
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
startTime?: number
|
||||
shareId?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
@@ -30,6 +33,7 @@ export function FileViewer({
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
shareId,
|
||||
children,
|
||||
}: FileViewerProps) {
|
||||
const { width: screenWidth } = useScreenSize()
|
||||
@@ -133,15 +137,29 @@ export function FileViewer({
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = () => {
|
||||
const url = file.media?.original?.downloadUrl
|
||||
if (!url) return
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = file.name || 'image'
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
const handleDownload = async () => {
|
||||
const key = file.media?.original?.key
|
||||
if (!key || !file.id) return
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: file.id },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: file.id },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopy = async () => {
|
||||
@@ -210,7 +228,7 @@ export function FileViewer({
|
||||
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
|
||||
<button
|
||||
onClick={handleDownload}
|
||||
disabled={!file.media?.original?.downloadUrl}
|
||||
disabled={!file.media?.original?.key}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Download original file"
|
||||
>
|
||||
@@ -254,51 +272,17 @@ export function FileViewer({
|
||||
</div>
|
||||
</div>
|
||||
{/* Zoom Toolbar */}
|
||||
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
|
||||
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 mr-auto">
|
||||
<button
|
||||
onClick={() => handleZoom(0.8)}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title="Zoom Out"
|
||||
>
|
||||
<Minus size={16} />
|
||||
</button>
|
||||
<span className="w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
|
||||
{Math.round(zoom * 100)}%
|
||||
</span>
|
||||
<button
|
||||
onClick={() => handleZoom(1.2)}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title="Zoom In"
|
||||
>
|
||||
<Plus size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleFit}
|
||||
className="text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent animate-in fade-in zoom-in-95 duration-200"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
disabled={!bestUrl}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Copy optimized image to clipboard"
|
||||
>
|
||||
{copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownload}
|
||||
disabled={!file.media?.original?.downloadUrl}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Download original image"
|
||||
>
|
||||
<Download size={14} />
|
||||
Download
|
||||
</button>
|
||||
</div>
|
||||
<ImageControlBar
|
||||
zoom={zoom}
|
||||
onZoomIn={() => handleZoom(1.2)}
|
||||
onZoomOut={() => handleZoom(0.8)}
|
||||
onFit={handleFit}
|
||||
onDownload={handleDownload}
|
||||
canDownload={!!file.media?.original?.key}
|
||||
onCopy={handleCopy}
|
||||
copied={copied}
|
||||
canCopy={!!bestUrl}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{isVideo && (
|
||||
@@ -311,6 +295,7 @@ export function FileViewer({
|
||||
onTimeUpdate={onTimeUpdate}
|
||||
annotations={displayAnnotations}
|
||||
startTime={startTime}
|
||||
shareId={shareId}
|
||||
>
|
||||
{children}
|
||||
</VideoPlayer>
|
||||
|
||||
@@ -16,6 +16,8 @@ import { Lock, AlertCircle, Loader2 } from 'lucide-react'
|
||||
import type { AncestorFolder, AssetInfoPaginatedList, AssetInfo, CommentInfo } from '@shumai/dtos'
|
||||
import { FieldInfo } from '@shumai/dtos'
|
||||
import { FileViewer } from './file-viewer'
|
||||
import { CompareViewer } from './compare/compare-viewer'
|
||||
import { pickDefaultCompareVersions } from './compare/compare-utils'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
|
||||
@@ -26,6 +28,11 @@ interface PublicShareManagerProps {
|
||||
initialFolderId?: string
|
||||
initialFileId?: string
|
||||
startTime?: number
|
||||
versionId?: string
|
||||
compare?: boolean
|
||||
compareLeftId?: string
|
||||
compareRightId?: string
|
||||
compareActiveSide?: 'left' | 'right'
|
||||
}
|
||||
|
||||
interface PublicShareInfo {
|
||||
@@ -46,8 +53,14 @@ export function PublicShareManager({
|
||||
initialFolderId,
|
||||
initialFileId,
|
||||
startTime,
|
||||
versionId,
|
||||
compare,
|
||||
compareLeftId,
|
||||
compareRightId,
|
||||
compareActiveSide = 'left',
|
||||
}: PublicShareManagerProps) {
|
||||
const navigate = useNavigate()
|
||||
const isCompareMode = !!compare && !!compareLeftId && !!compareRightId
|
||||
const [password, setPassword] = useState(() => {
|
||||
return localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
})
|
||||
@@ -87,6 +100,9 @@ export function PublicShareManager({
|
||||
|
||||
const currentFolderId = initialFolderId || shareInfo?.rootFolderId
|
||||
const viewingFileId = initialFileId || null
|
||||
// The stack asset is always fetched by the route file id; when a version is
|
||||
// selected we additionally display that version child asset.
|
||||
const activeFileId = versionId || viewingFileId
|
||||
|
||||
const [ancestorFolders, setAncestorFolders] = useState<AncestorFolder[]>([])
|
||||
|
||||
@@ -129,6 +145,10 @@ export function PublicShareManager({
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
|
||||
const [compareActiveAsset, setCompareActiveAsset] = useState<AssetInfo | null>(null)
|
||||
const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
|
||||
undefined,
|
||||
)
|
||||
|
||||
const {
|
||||
data: foldersData,
|
||||
@@ -214,7 +234,7 @@ export function PublicShareManager({
|
||||
enabled: !!shareInfo,
|
||||
})
|
||||
|
||||
const { data: viewingFileData, isLoading: isViewingFileLoading } = useQuery({
|
||||
const { data: stackFileData, isLoading: isStackFileLoading } = useQuery({
|
||||
queryKey: ['public-share-file', shareId, viewingFileId, password],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
|
||||
@@ -233,6 +253,30 @@ export function PublicShareManager({
|
||||
enabled: !!viewingFileId && !!shareInfo,
|
||||
})
|
||||
|
||||
const { data: versionFileData, isLoading: isVersionFileLoading } = useQuery({
|
||||
queryKey: ['public-share-file', shareId, versionId, password],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
|
||||
{
|
||||
param: { shareId, fileId: versionId! },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
},
|
||||
},
|
||||
)
|
||||
if (res.status === 401) throw new Error('Unauthorized')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: !!versionId && !!shareInfo,
|
||||
})
|
||||
|
||||
// The stack asset provides the version list; the active asset (version child
|
||||
// or the stack itself) is what we actually display.
|
||||
const viewingFileData = versionId ? versionFileData : stackFileData
|
||||
const isViewingFileLoading = isStackFileLoading || (!!versionId && isVersionFileLoading)
|
||||
|
||||
useEffect(() => {
|
||||
if (foldersError?.message === 'Unauthorized') {
|
||||
setPassword('')
|
||||
@@ -307,6 +351,13 @@ export function PublicShareManager({
|
||||
setAnnotations([])
|
||||
}
|
||||
|
||||
if (isCompareMode) {
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
setSeekRequest({ second: comment.second, nonce: Date.now() })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
if (videoRef.current) {
|
||||
videoRef.current.currentTime(comment.second)
|
||||
@@ -324,6 +375,26 @@ export function PublicShareManager({
|
||||
setSelectedCommentId(null)
|
||||
}
|
||||
|
||||
const updateCompareSearch = (patch: Record<string, unknown>) => {
|
||||
if (!viewingFileId) return
|
||||
navigate({
|
||||
to: '/share/$shareId/files/$fileId',
|
||||
params: { shareId, fileId: viewingFileId },
|
||||
search: (p: Record<string, unknown>) => ({ ...p, ...patch }),
|
||||
})
|
||||
}
|
||||
|
||||
const handleCompareExit = () => {
|
||||
const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
|
||||
updateCompareSearch({
|
||||
compare: undefined,
|
||||
cmpLeft: undefined,
|
||||
cmpRight: undefined,
|
||||
cmpActive: undefined,
|
||||
version: activeId,
|
||||
})
|
||||
}
|
||||
|
||||
const { setProjectState, clearProjectState } = useTopNavStore()
|
||||
|
||||
useEffect(() => {
|
||||
@@ -341,18 +412,47 @@ export function PublicShareManager({
|
||||
currentAsset: {
|
||||
name: viewingFileData?.name || currentFolderName,
|
||||
type: viewingFileId ? 'file' : 'folder',
|
||||
version: viewingFileData?.versionStack
|
||||
? (viewingFileData.versionStack.versions.find((v) => v.id === viewingFileData.id)
|
||||
?.version ?? viewingFileData.versionStack.versions.length)
|
||||
version: stackFileData?.versionStack
|
||||
? (stackFileData.versionStack.versions.find((v) => v.id === activeFileId)?.version ??
|
||||
stackFileData.versionStack.versions.length)
|
||||
: undefined,
|
||||
},
|
||||
isRootFolder: currentFolderId === shareInfo.rootFolderId && !viewingFileId,
|
||||
isPublic: true,
|
||||
shareId,
|
||||
fileId: viewingFileId || undefined,
|
||||
downloadInfo: viewingFileData
|
||||
? {
|
||||
originalKey: viewingFileData.media?.original?.key,
|
||||
videoTranscodes: viewingFileData.media?.videoTranscodes?.map((t) => ({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
isRaw: t.isRaw,
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
onFolderClick: handleBreadcrumbClick,
|
||||
isRightSidebarCollapsed,
|
||||
onRightSidebarToggle: () => setIsRightSidebarCollapsed((prev) => !prev),
|
||||
versions: stackFileData?.versionStack?.versions,
|
||||
compareMode: isCompareMode,
|
||||
canCompareVersions: (stackFileData?.versionStack?.versions?.length ?? 0) >= 2,
|
||||
onCompareVersions: () => {
|
||||
const pair = pickDefaultCompareVersions(stackFileData?.versionStack?.versions)
|
||||
if (!pair || !viewingFileId) return
|
||||
navigate({
|
||||
to: '/share/$shareId/files/$fileId',
|
||||
params: { shareId, fileId: viewingFileId },
|
||||
search: (p: Record<string, unknown>) => ({
|
||||
...p,
|
||||
compare: true,
|
||||
cmpLeft: pair.left.id,
|
||||
cmpRight: pair.right.id,
|
||||
cmpActive: 'left' as const,
|
||||
}),
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -362,11 +462,16 @@ export function PublicShareManager({
|
||||
currentFolderId,
|
||||
folders,
|
||||
viewingFileData,
|
||||
stackFileData,
|
||||
activeFileId,
|
||||
viewingFileId,
|
||||
ancestorFolders,
|
||||
setProjectState,
|
||||
clearProjectState,
|
||||
isRightSidebarCollapsed,
|
||||
isCompareMode,
|
||||
navigate,
|
||||
shareId,
|
||||
])
|
||||
|
||||
let content
|
||||
@@ -445,20 +550,44 @@ export function PublicShareManager({
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{viewingFileId ? (
|
||||
<div className="flex-1 relative bg-muted/30">
|
||||
{isViewingFileLoading && (
|
||||
{isViewingFileLoading && !isCompareMode && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{viewingFileData && (
|
||||
<FileViewer
|
||||
file={viewingFileData}
|
||||
videoRef={videoRef}
|
||||
{isCompareMode && compareLeftId && compareRightId ? (
|
||||
<CompareViewer
|
||||
isPublic
|
||||
shareId={shareId}
|
||||
versions={viewingFileData?.versionStack?.versions ?? []}
|
||||
leftId={compareLeftId}
|
||||
rightId={compareRightId}
|
||||
activeSide={compareActiveSide}
|
||||
annotations={annotations}
|
||||
seekRequest={seekRequest}
|
||||
onActiveSideChange={(side) => updateCompareSearch({ cmpActive: side })}
|
||||
onSwitchVersion={(side, versionId) =>
|
||||
updateCompareSearch(
|
||||
side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
|
||||
)
|
||||
}
|
||||
onExit={handleCompareExit}
|
||||
onActiveAssetChange={setCompareActiveAsset}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
/>
|
||||
) : (
|
||||
viewingFileData && (
|
||||
<FileViewer
|
||||
file={viewingFileData}
|
||||
videoRef={videoRef}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
shareId={shareId}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
@@ -508,7 +637,7 @@ export function PublicShareManager({
|
||||
<FileViewerRightSidebar
|
||||
teamId=""
|
||||
projectId={shareInfo.projectId}
|
||||
file={currentSelectedItem}
|
||||
file={isCompareMode ? compareActiveAsset : currentSelectedItem}
|
||||
onSaveField={() => {}}
|
||||
members={[]}
|
||||
readOnly={true}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect } from 'react'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
export function TeamSelector() {
|
||||
@@ -23,14 +24,20 @@ export function TeamSelector() {
|
||||
},
|
||||
})
|
||||
|
||||
const teams = teamsData?.data
|
||||
const onlyTeamId = teams?.length === 1 ? teams[0].id : null
|
||||
|
||||
useEffect(() => {
|
||||
if (onlyTeamId) {
|
||||
navigate({ to: `/teams/${onlyTeamId}` })
|
||||
}
|
||||
}, [onlyTeamId, navigate])
|
||||
|
||||
if (isLoading) {
|
||||
return <div>{m.loading()}</div>
|
||||
}
|
||||
|
||||
const teams = teamsData?.data
|
||||
|
||||
if (teams?.length === 1) {
|
||||
navigate({ to: `/teams/${teams[0].id}` })
|
||||
if (onlyTeamId) {
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
@@ -19,10 +19,14 @@ export function TopNav() {
|
||||
currentAsset,
|
||||
isRootFolder,
|
||||
fileId,
|
||||
downloadInfo,
|
||||
versions,
|
||||
isPublic,
|
||||
shareId,
|
||||
onFolderClick,
|
||||
compareMode,
|
||||
canCompareVersions,
|
||||
onCompareVersions,
|
||||
} = projectState
|
||||
|
||||
const isFileView = !!fileId
|
||||
@@ -87,8 +91,12 @@ export function TopNav() {
|
||||
isPublic={isPublic}
|
||||
shareId={shareId}
|
||||
fileId={fileId}
|
||||
downloadInfo={downloadInfo}
|
||||
versions={versions}
|
||||
onFolderClick={onFolderClick}
|
||||
compareMode={compareMode}
|
||||
canCompareVersions={canCompareVersions}
|
||||
onCompareVersions={onCompareVersions}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { Check, Copy, Download, Maximize, Minimize, Minus, Plus } from 'lucide-react'
|
||||
|
||||
export interface ImageControlBarProps {
|
||||
zoom: number
|
||||
onZoomIn: () => void
|
||||
onZoomOut: () => void
|
||||
onFit: () => void
|
||||
onDownload: () => void
|
||||
canDownload: boolean
|
||||
onCopy?: () => void
|
||||
copied?: boolean
|
||||
canCopy?: boolean
|
||||
/** When provided, renders a fullscreen toggle (used by compare mode). */
|
||||
fullscreen?: { isFullScreen: boolean; onToggle: () => void }
|
||||
}
|
||||
|
||||
export function ImageControlBar({
|
||||
zoom,
|
||||
onZoomIn,
|
||||
onZoomOut,
|
||||
onFit,
|
||||
onDownload,
|
||||
canDownload,
|
||||
onCopy,
|
||||
copied = false,
|
||||
canCopy = true,
|
||||
fullscreen,
|
||||
}: ImageControlBarProps) {
|
||||
return (
|
||||
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
|
||||
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 mr-auto">
|
||||
<button
|
||||
onClick={onZoomOut}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title="Zoom Out"
|
||||
>
|
||||
<Minus size={16} />
|
||||
</button>
|
||||
<span className="w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
|
||||
{Math.round(zoom * 100)}%
|
||||
</span>
|
||||
<button
|
||||
onClick={onZoomIn}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title="Zoom In"
|
||||
>
|
||||
<Plus size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={onFit}
|
||||
className="text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent animate-in fade-in zoom-in-95 duration-200"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
{onCopy && (
|
||||
<button
|
||||
onClick={onCopy}
|
||||
disabled={!canCopy}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Copy optimized image to clipboard"
|
||||
>
|
||||
{copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={onDownload}
|
||||
disabled={!canDownload}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Download original image"
|
||||
>
|
||||
<Download size={14} />
|
||||
Download
|
||||
</button>
|
||||
{fullscreen && (
|
||||
<button
|
||||
onClick={fullscreen.onToggle}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title="Fullscreen"
|
||||
>
|
||||
{fullscreen.isFullScreen ? <Minimize size={16} /> : <Maximize size={16} />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -262,6 +262,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onMouseDown={handleMouseDown}
|
||||
onTouchStart={handleTouchStart}
|
||||
data-testid="seekbar"
|
||||
>
|
||||
{/* Hidden Preview Video Element */}
|
||||
<video
|
||||
@@ -316,6 +317,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
|
||||
<div
|
||||
className="relative absolute top-0 left-0 h-full rounded-full bg-primary"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
data-testid="seekbar-fill"
|
||||
>
|
||||
{/* Thumb (Playhead) - visible on group hover or active */}
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { useFramePlayer } from './use-frame-player'
|
||||
|
||||
/**
|
||||
* Deterministic reproduction of the Safari playhead-rewind bug.
|
||||
*
|
||||
* On Safari/WebKit, `video.currentTime` (the playback/audio clock) runs AHEAD of
|
||||
* the frame actually presented on screen right after playback starts, and the
|
||||
* first `requestVideoFrameCallback` (mediaTime) arrives only after a delay. The
|
||||
* old logic drove the playhead from `currentTime` immediately on play, racing it
|
||||
* forward, then snapped it backward when the first rVFC reported the true (lower)
|
||||
* presented frame.
|
||||
*
|
||||
* The headless WebKit engine does not exhibit that clock skew, so this can only
|
||||
* be reproduced deterministically at the logic layer: we mock a video element
|
||||
* whose `currentTime` leads while a fake `requestVideoFrameCallback` delivers a
|
||||
* lagging `mediaTime`, drive RAF/clock manually, and assert the playhead never
|
||||
* moves backward.
|
||||
*/
|
||||
|
||||
const FPS = 30
|
||||
const TOTAL = 150
|
||||
|
||||
// --- Controllable environment -------------------------------------------------
|
||||
|
||||
interface RafEntry {
|
||||
id: number
|
||||
cb: FrameRequestCallback
|
||||
}
|
||||
|
||||
let clock = 0
|
||||
let rafQueue: RafEntry[] = []
|
||||
let rafSeq = 0
|
||||
|
||||
/** Run exactly the RAF callbacks queued at flush time (one simulated frame). */
|
||||
const flushRaf = () => {
|
||||
const queued = rafQueue
|
||||
rafQueue = []
|
||||
for (const { cb } of queued) cb(clock)
|
||||
}
|
||||
|
||||
/** Minimal HTMLVideoElement stand-in with a manually-fired rVFC. */
|
||||
class FakeVideo extends EventTarget {
|
||||
currentTime = 0
|
||||
paused = true
|
||||
ended = false
|
||||
private vfcCallbacks: Array<(now: number, meta: { mediaTime: number }) => void> = []
|
||||
|
||||
requestVideoFrameCallback(cb: (now: number, meta: { mediaTime: number }) => void): number {
|
||||
this.vfcCallbacks.push(cb)
|
||||
return this.vfcCallbacks.length
|
||||
}
|
||||
|
||||
cancelVideoFrameCallback(): void {
|
||||
this.vfcCallbacks = []
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.paused = true
|
||||
this.dispatchEvent(new Event('pause'))
|
||||
}
|
||||
|
||||
play(): void {
|
||||
this.paused = false
|
||||
this.dispatchEvent(new Event('play'))
|
||||
}
|
||||
|
||||
/** Simulate the compositor presenting a frame at the given mediaTime. */
|
||||
fireVfc(mediaTime: number): void {
|
||||
const callbacks = this.vfcCallbacks
|
||||
this.vfcCallbacks = []
|
||||
for (const cb of callbacks) cb(0, { mediaTime })
|
||||
}
|
||||
}
|
||||
|
||||
function makeRef(video: FakeVideo): { current: HTMLVideoElement | null } {
|
||||
return { current: video as unknown as HTMLVideoElement }
|
||||
}
|
||||
|
||||
let originalRaf: typeof globalThis.requestAnimationFrame
|
||||
let originalCaf: typeof globalThis.cancelAnimationFrame
|
||||
|
||||
beforeEach(() => {
|
||||
clock = 0
|
||||
rafQueue = []
|
||||
rafSeq = 0
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => clock)
|
||||
|
||||
originalRaf = globalThis.requestAnimationFrame
|
||||
originalCaf = globalThis.cancelAnimationFrame
|
||||
globalThis.requestAnimationFrame = ((cb: FrameRequestCallback): number => {
|
||||
rafSeq += 1
|
||||
rafQueue.push({ id: rafSeq, cb })
|
||||
return rafSeq
|
||||
}) as typeof globalThis.requestAnimationFrame
|
||||
globalThis.cancelAnimationFrame = ((id: number): void => {
|
||||
rafQueue = rafQueue.filter((entry) => entry.id !== id)
|
||||
}) as typeof globalThis.cancelAnimationFrame
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
globalThis.requestAnimationFrame = originalRaf
|
||||
globalThis.cancelAnimationFrame = originalCaf
|
||||
})
|
||||
|
||||
// --- Tests --------------------------------------------------------------------
|
||||
|
||||
describe('useFramePlayer Safari playhead synchronization', () => {
|
||||
it('does not rewind the playhead on play when currentTime leads the presented frame', () => {
|
||||
const video = new FakeVideo()
|
||||
const { result } = renderHook(() => useFramePlayer(makeRef(video), FPS, TOTAL))
|
||||
|
||||
const frames: number[] = []
|
||||
const record = () => frames.push(result.current.currentFrame)
|
||||
|
||||
// Start playback via the play event (as a real click would).
|
||||
act(() => {
|
||||
video.paused = false
|
||||
video.dispatchEvent(new Event('play'))
|
||||
})
|
||||
record()
|
||||
|
||||
// Safari: the playback clock races ahead (~frame 10) while NO rVFC frame has
|
||||
// been presented yet. The playhead must NOT follow currentTime here.
|
||||
const leadingCurrentTimes = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35]
|
||||
for (const ct of leadingCurrentTimes) {
|
||||
clock += 50
|
||||
video.currentTime = ct
|
||||
act(() => {
|
||||
flushRaf()
|
||||
})
|
||||
record()
|
||||
}
|
||||
expect(Math.max(...frames)).toBe(0) // Fix 1: no forward race from currentTime
|
||||
|
||||
// First presented frame arrives, lagging currentTime (frame 1).
|
||||
act(() => {
|
||||
video.fireVfc(1 / FPS)
|
||||
})
|
||||
record()
|
||||
|
||||
// Subsequent presented frames advance normally.
|
||||
for (let f = 2; f <= 8; f++) {
|
||||
clock += 33
|
||||
act(() => {
|
||||
flushRaf()
|
||||
})
|
||||
act(() => {
|
||||
video.fireVfc(f / FPS)
|
||||
})
|
||||
record()
|
||||
}
|
||||
|
||||
// The playhead must be monotonic non-decreasing throughout (never rewinds).
|
||||
for (let i = 1; i < frames.length; i++) {
|
||||
expect(frames[i]).toBeGreaterThanOrEqual(frames[i - 1])
|
||||
}
|
||||
expect(result.current.currentFrame).toBe(8)
|
||||
})
|
||||
|
||||
it('still falls back to currentTime once rVFC has delivered and then stalls', () => {
|
||||
const video = new FakeVideo()
|
||||
const { result } = renderHook(() => useFramePlayer(makeRef(video), FPS, TOTAL))
|
||||
|
||||
act(() => {
|
||||
video.paused = false
|
||||
video.dispatchEvent(new Event('play'))
|
||||
})
|
||||
|
||||
// rVFC delivers a few frames -> the session has "seen" the compositor.
|
||||
for (let f = 1; f <= 3; f++) {
|
||||
clock += 33
|
||||
video.currentTime = f / FPS
|
||||
act(() => {
|
||||
flushRaf()
|
||||
})
|
||||
act(() => {
|
||||
video.fireVfc(f / FPS)
|
||||
})
|
||||
}
|
||||
expect(result.current.currentFrame).toBe(3)
|
||||
|
||||
// Video track ends: rVFC stops, but audio (currentTime) keeps advancing past
|
||||
// the stall threshold. The RAF fallback should take over from currentTime.
|
||||
clock += 200
|
||||
video.currentTime = 10 / FPS
|
||||
act(() => {
|
||||
flushRaf()
|
||||
})
|
||||
expect(result.current.currentFrame).toBe(10)
|
||||
})
|
||||
|
||||
it('locks the paused frame to the presented mediaTime, not the leading currentTime', () => {
|
||||
const video = new FakeVideo()
|
||||
const { result } = renderHook(() => useFramePlayer(makeRef(video), FPS, TOTAL))
|
||||
|
||||
act(() => {
|
||||
video.paused = false
|
||||
video.dispatchEvent(new Event('play'))
|
||||
})
|
||||
|
||||
// Presented up to frame 16 via rVFC.
|
||||
for (let f = 1; f <= 16; f++) {
|
||||
clock += 33
|
||||
act(() => {
|
||||
flushRaf()
|
||||
})
|
||||
act(() => {
|
||||
video.fireVfc(f / FPS)
|
||||
})
|
||||
}
|
||||
expect(result.current.currentFrame).toBe(16)
|
||||
|
||||
// Safari's currentTime has raced ahead to frame 20's center.
|
||||
video.currentTime = 20 / FPS + 1 / (2 * FPS)
|
||||
|
||||
// Pause while rVFC is still fresh.
|
||||
act(() => {
|
||||
video.pause()
|
||||
})
|
||||
|
||||
// Fix 2: the paused frame follows the presented frame (16), not currentTime (20).
|
||||
expect(result.current.currentFrame).toBe(16)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { calculateFrameCenterTime } from './utils'
|
||||
import { calculateFrameCenterTime, stallThresholdMs } from './utils'
|
||||
|
||||
export interface UseFramePlayerResult {
|
||||
currentFrame: number
|
||||
@@ -15,6 +15,11 @@ interface HtmlVideoElementWithCallback {
|
||||
cancelVideoFrameCallback?: (id: number) => void
|
||||
}
|
||||
|
||||
// If requestVideoFrameCallback is supported but has not delivered a frame within
|
||||
// this window after playback starts, fall back to the currentTime/RAF driver so
|
||||
// the playhead can never freeze permanently on an engine that stops emitting rVFC.
|
||||
const INITIAL_VFC_GRACE_MS = 1000
|
||||
|
||||
export function useFramePlayer(
|
||||
videoRef: React.RefObject<HTMLVideoElement | null>,
|
||||
frameRate: number,
|
||||
@@ -59,7 +64,23 @@ export function useFramePlayer(
|
||||
let rVfcId: number | null = null
|
||||
let rafId: number | null = null
|
||||
let active = true
|
||||
|
||||
// Per-playback-session synchronization state.
|
||||
// `lastVfcTime` / `hasDeliveredVfc` gate when it is safe to trust
|
||||
// `video.currentTime` (see the fallback condition below). `lastMediaTime` is
|
||||
// the most recent compositor-presented time, used to lock the playhead on
|
||||
// pause to the frame the user is actually looking at.
|
||||
let lastVfcTime = Date.now()
|
||||
let hasDeliveredVfc = false
|
||||
let lastMediaTime = -1
|
||||
|
||||
// Reset session state whenever playback (re)starts, so each play waits for a
|
||||
// fresh compositor frame before trusting the playback clock.
|
||||
const beginSession = () => {
|
||||
lastVfcTime = Date.now()
|
||||
hasDeliveredVfc = false
|
||||
lastMediaTime = -1
|
||||
}
|
||||
|
||||
const updateFrameLoop = () => {
|
||||
if (!active) return
|
||||
@@ -69,20 +90,32 @@ export function useFramePlayer(
|
||||
}
|
||||
|
||||
const videoWithCallback = video as unknown as HtmlVideoElementWithCallback
|
||||
const rVfcSupported = !!videoWithCallback.requestVideoFrameCallback
|
||||
|
||||
// Calculate dynamic stall threshold (minimum 100ms, or 3 frames of duration)
|
||||
const stallThreshold = Math.max(100, 3000 / frameRate)
|
||||
const isVfcStalled = Date.now() - lastVfcTime > stallThreshold
|
||||
const stallThreshold = stallThresholdMs(frameRate)
|
||||
const sinceLastVfc = Date.now() - lastVfcTime
|
||||
|
||||
// Print debug log roughly once per second during playback
|
||||
if (Math.floor(video.currentTime * frameRate + 0.45) % 30 === 0) {
|
||||
console.log(
|
||||
`[useFramePlayer] currentTime: ${video.currentTime}, isVfcStalled: ${isVfcStalled}, stallThreshold: ${stallThreshold}, totalFrames: ${totalFrames}`,
|
||||
)
|
||||
}
|
||||
// Decide whether the RAF path may drive the playhead from `video.currentTime`.
|
||||
//
|
||||
// `video.currentTime` is the playback (audio) clock. On some engines
|
||||
// (notably Safari/WebKit) it runs AHEAD of the frame actually presented on
|
||||
// screen right after playback starts, so trusting it before the compositor
|
||||
// catches up makes the playhead race forward and then snap backward when the
|
||||
// first requestVideoFrameCallback (mediaTime) arrives.
|
||||
//
|
||||
// We therefore only use the currentTime fallback when:
|
||||
// - rVFC is unsupported (it is the only driver available), or
|
||||
// - rVFC has delivered at least one frame this session AND has since
|
||||
// stalled (e.g. the video track ended while audio keeps playing), or
|
||||
// - rVFC never delivered within the initial grace window (safety net so
|
||||
// the playhead cannot freeze forever).
|
||||
const rVfcStalledAfterDelivery = hasDeliveredVfc && sinceLastVfc > stallThreshold
|
||||
const rVfcNeverDelivered = !hasDeliveredVfc && sinceLastVfc > INITIAL_VFC_GRACE_MS
|
||||
const useCurrentTimeFallback =
|
||||
!rVfcSupported || rVfcStalledAfterDelivery || rVfcNeverDelivered
|
||||
|
||||
// Only update playhead via currentTime (RAF) if rVFC has stalled or isn't supported
|
||||
if (!videoWithCallback.requestVideoFrameCallback || isVfcStalled) {
|
||||
if (useCurrentTimeFallback) {
|
||||
const frame = Math.floor(video.currentTime * frameRate + 0.45)
|
||||
const clamped = Math.max(0, Math.min(frame, totalFrames - 1))
|
||||
setCurrentFrame(clamped)
|
||||
@@ -97,6 +130,8 @@ export function useFramePlayer(
|
||||
(_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => {
|
||||
rVfcId = null
|
||||
lastVfcTime = Date.now() // Reset stall timer
|
||||
hasDeliveredVfc = true
|
||||
lastMediaTime = metadata.mediaTime
|
||||
|
||||
const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.45)
|
||||
const compositorClamped = Math.max(0, Math.min(compositorFrame, totalFrames - 1))
|
||||
@@ -107,6 +142,7 @@ export function useFramePlayer(
|
||||
}
|
||||
|
||||
const handlePlay = () => {
|
||||
beginSession()
|
||||
updateFrameLoop()
|
||||
}
|
||||
|
||||
@@ -127,14 +163,26 @@ export function useFramePlayer(
|
||||
rafId = null
|
||||
}
|
||||
|
||||
// Synchronize frame on pause
|
||||
const frame = Math.floor(video.currentTime * frameRate + 0.45)
|
||||
// Synchronize the frame on pause. Prefer the last compositor-presented time
|
||||
// (mediaTime) when it is still fresh, because on Safari `video.currentTime`
|
||||
// can lead the on-screen frame — using it would snap the playhead forward
|
||||
// past the frame the user actually paused on. Fall back to currentTime when
|
||||
// rVFC is stale/unsupported (e.g. the video track ended while audio plays).
|
||||
const stallThreshold = stallThresholdMs(frameRate)
|
||||
const vfcFresh =
|
||||
hasDeliveredVfc && lastMediaTime >= 0 && Date.now() - lastVfcTime <= stallThreshold
|
||||
const syncTime = vfcFresh ? lastMediaTime : video.currentTime
|
||||
|
||||
const frame = Math.floor(syncTime * frameRate + 0.45)
|
||||
const clamped = Math.max(0, Math.min(frame, totalFrames - 1))
|
||||
setCurrentFrame(clamped)
|
||||
|
||||
// Snap the playhead to the center of the paused frame to align browser compositor
|
||||
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
|
||||
video.currentTime = safeCenterTime
|
||||
// Skip snapping if the video has ended to preserve the native ended state and allow native replay
|
||||
if (!video.ended) {
|
||||
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
|
||||
video.currentTime = safeCenterTime
|
||||
}
|
||||
}
|
||||
|
||||
video.addEventListener('play', handlePlay)
|
||||
@@ -142,6 +190,7 @@ export function useFramePlayer(
|
||||
|
||||
// If it's already playing when this effect runs
|
||||
if (!video.paused) {
|
||||
beginSession()
|
||||
updateFrameLoop()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { formatTimecode, calculateFrameCenterTime } from './utils'
|
||||
import {
|
||||
formatTimecode,
|
||||
calculateFrameCenterTime,
|
||||
resolveTotalFrames,
|
||||
stallThresholdMs,
|
||||
} from './utils'
|
||||
|
||||
describe('formatTimecode tests', () => {
|
||||
describe('non-drop-frame calculations', () => {
|
||||
@@ -67,3 +72,96 @@ describe('formatTimecode tests', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('stallThresholdMs', () => {
|
||||
it('is 100ms at 30fps and 60fps (floor of 100ms dominates)', () => {
|
||||
expect(stallThresholdMs(30)).toBe(100)
|
||||
expect(stallThresholdMs(60)).toBe(100)
|
||||
})
|
||||
|
||||
it('is frame-rate dependent below 30fps', () => {
|
||||
// 3000 / 24 = 125ms
|
||||
expect(stallThresholdMs(24)).toBe(125)
|
||||
// 3000 / 25 = 120ms
|
||||
expect(stallThresholdMs(25)).toBe(120)
|
||||
})
|
||||
|
||||
it('guards against a falsy frame rate by treating it as 30fps', () => {
|
||||
expect(stallThresholdMs(0)).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveTotalFrames', () => {
|
||||
describe('at 30fps (100ms stall threshold)', () => {
|
||||
it('uses the video-stream count when there is no container tail', () => {
|
||||
expect(resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 5, frameRate: 30 })).toBe(
|
||||
150,
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the video-stream count for a sub-threshold tail (videoA / ~2 frames)', () => {
|
||||
// video 268 frames = 8.9333s, container 9.008s -> 0.0747s tail (< 100ms).
|
||||
// Must NOT inflate to round(9.008 * 30) = 270.
|
||||
expect(
|
||||
resolveTotalFrames({ dbTotalFrames: 268, containerDuration: 9.008, frameRate: 30 }),
|
||||
).toBe(268)
|
||||
})
|
||||
|
||||
it('uses the video-stream count for the container-longer e2e fixture tail', () => {
|
||||
// 150 frames = 5.0s, container 5.075s -> 0.075s tail (< 100ms).
|
||||
expect(
|
||||
resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 5.075, frameRate: 30 }),
|
||||
).toBe(150)
|
||||
})
|
||||
|
||||
it('still uses the video-stream count just below the threshold', () => {
|
||||
// 300 frames = 10s, container 10.09s -> 0.09s tail (< 100ms).
|
||||
expect(
|
||||
resolveTotalFrames({ dbTotalFrames: 300, containerDuration: 10.09, frameRate: 30 }),
|
||||
).toBe(300)
|
||||
})
|
||||
|
||||
it('switches to the container count just above the threshold', () => {
|
||||
// 300 frames = 10s, container 10.11s -> 0.11s tail (> 100ms).
|
||||
// round(10.11 * 30) = 303.
|
||||
expect(
|
||||
resolveTotalFrames({ dbTotalFrames: 300, containerDuration: 10.11, frameRate: 30 }),
|
||||
).toBe(303)
|
||||
})
|
||||
|
||||
it('uses the container count for a large tail (videoB / long audio)', () => {
|
||||
// 150 frames = 5.0s, container 6.5s -> 1.5s tail. round(6.5 * 30) = 195.
|
||||
expect(
|
||||
resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 6.5, frameRate: 30 }),
|
||||
).toBe(195)
|
||||
})
|
||||
})
|
||||
|
||||
describe('frame-rate dependence of the threshold', () => {
|
||||
it('treats a 100ms tail as below threshold at 24fps (threshold 125ms)', () => {
|
||||
// 240 frames = 10s, container 10.1s -> 0.1s tail (< 125ms at 24fps).
|
||||
expect(
|
||||
resolveTotalFrames({ dbTotalFrames: 240, containerDuration: 10.1, frameRate: 24 }),
|
||||
).toBe(240)
|
||||
})
|
||||
|
||||
it('treats a 130ms tail as above threshold at 24fps', () => {
|
||||
// 240 frames = 10s, container 10.13s -> 0.13s tail (> 125ms).
|
||||
// round(10.13 * 24) = 243.
|
||||
expect(
|
||||
resolveTotalFrames({ dbTotalFrames: 240, containerDuration: 10.13, frameRate: 24 }),
|
||||
).toBe(243)
|
||||
})
|
||||
})
|
||||
|
||||
describe('missing video-stream frame count', () => {
|
||||
it('falls back to the container-derived count when nb_frames is 0', () => {
|
||||
expect(resolveTotalFrames({ dbTotalFrames: 0, containerDuration: 5, frameRate: 30 })).toBe(
|
||||
150,
|
||||
)
|
||||
expect(resolveTotalFrames({ dbTotalFrames: 0, containerDuration: 6.5, frameRate: 30 })).toBe(
|
||||
195,
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -94,3 +94,63 @@ export const calculateFrameCenterTime = (frameIndex: number, frameRate: number):
|
||||
const frameDuration = 1 / frameRate
|
||||
return frameIndex * frameDuration + frameDuration / 2
|
||||
}
|
||||
|
||||
/**
|
||||
* The dynamic playback stall threshold, in milliseconds: the window of
|
||||
* `requestVideoFrameCallback` silence after which the playback loop's
|
||||
* `requestAnimationFrame` fallback begins driving the playhead from
|
||||
* `video.currentTime`.
|
||||
*
|
||||
* Shared by `useFramePlayer` (runtime stall detection) and `resolveTotalFrames`
|
||||
* (frame-count derivation) so the two stay in lockstep: the boundary at which a
|
||||
* container's audio-only tail becomes *reachable* by the playhead is exactly the
|
||||
* boundary at which we start counting those tail frames.
|
||||
*/
|
||||
export const stallThresholdMs = (frameRate: number): number =>
|
||||
Math.max(100, 3000 / (frameRate || 30))
|
||||
|
||||
interface ResolveTotalFramesArgs {
|
||||
/**
|
||||
* Physical video-stream frame count (ffprobe `nb_frames`), as stored in
|
||||
* `metadata.totalFrames`.
|
||||
*/
|
||||
dbTotalFrames: number
|
||||
/**
|
||||
* Container/format duration in seconds (`metadata.duration`). May exceed the
|
||||
* video-stream duration when e.g. the audio track is longer.
|
||||
*/
|
||||
containerDuration: number
|
||||
frameRate: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the player's effective total frame count.
|
||||
*
|
||||
* A container's duration can exceed its video stream (commonly because the audio
|
||||
* track is slightly longer, or from container overhead). Deriving the frame count
|
||||
* from the container duration in that case invents phantom trailing frames the
|
||||
* video stream does not contain.
|
||||
*
|
||||
* We only trust the container-derived count when the extra tail is long enough
|
||||
* for the playhead to actually reach it during playback — i.e. longer than the
|
||||
* playback stall threshold (see `stallThresholdMs`). Below that threshold the
|
||||
* RAF fallback never activates, so those tail frames are unreachable and would
|
||||
* strand the readout short of its own maximum; we use the accurate video-stream
|
||||
* frame count instead.
|
||||
*
|
||||
* When `nb_frames` is unavailable (`dbTotalFrames <= 0`), fall back to the
|
||||
* container-derived count.
|
||||
*/
|
||||
export const resolveTotalFrames = ({
|
||||
dbTotalFrames,
|
||||
containerDuration,
|
||||
frameRate,
|
||||
}: ResolveTotalFramesArgs): number => {
|
||||
const fps = frameRate || 30
|
||||
const containerFrames = Math.round(containerDuration * fps)
|
||||
if (dbTotalFrames <= 0) return containerFrames
|
||||
const videoDuration = dbTotalFrames / fps
|
||||
const tailSeconds = containerDuration - videoDuration
|
||||
const thresholdSeconds = stallThresholdMs(fps) / 1000
|
||||
return tailSeconds > thresholdSeconds ? containerFrames : dbTotalFrames
|
||||
}
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import type { AssetInfo, VideoTranscode } from '@shumai/dtos'
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
Download,
|
||||
Maximize,
|
||||
Minimize,
|
||||
Minus,
|
||||
Pause,
|
||||
Play,
|
||||
Plus,
|
||||
Repeat,
|
||||
Settings,
|
||||
Volume2,
|
||||
VolumeX,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from '../ui/dropdown-menu'
|
||||
import { Slider } from '../ui/slider'
|
||||
import ProgressBar from './progress-bar'
|
||||
import { formatTime, formatTimecode } from './utils'
|
||||
|
||||
export interface PlayerState {
|
||||
isPlaying: boolean
|
||||
progress: number // 0 to 100
|
||||
currentTime: number
|
||||
duration: number
|
||||
volume: number
|
||||
isMuted: boolean
|
||||
isLooping: boolean
|
||||
playbackRate: number
|
||||
isFullScreen: boolean
|
||||
showFrames: boolean // Toggle between time (02:30) and frames (1234)
|
||||
currentResolution: string // 'Original' or '720p', '480p' etc.
|
||||
currentSrc?: string
|
||||
}
|
||||
|
||||
export type DisplayTranscode = VideoTranscode & { resolution: string }
|
||||
|
||||
export interface ControlBarProps {
|
||||
state: PlayerState
|
||||
zoom: number
|
||||
isControlsVisible: boolean
|
||||
buffered: number
|
||||
data: AssetInfo
|
||||
resolutions: DisplayTranscode[]
|
||||
togglePlay: () => void
|
||||
toggleLoop: () => void
|
||||
toggleMute: () => void
|
||||
handleVolumeChange: (newVolume: number) => void
|
||||
changePlaybackRate: (rate: number) => void
|
||||
changeResolution: (res: DisplayTranscode) => void
|
||||
handleDownload: (key: string) => void
|
||||
toggleFullScreen: () => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
onZoomReset: () => void
|
||||
// Frame-accurate props
|
||||
frameRate: number
|
||||
totalFrames: number
|
||||
currentFrame: number
|
||||
seekToFrame: (frame: number) => Promise<void> | void
|
||||
/**
|
||||
* Whether the bar floats as an absolute overlay over the media while
|
||||
* fullscreen (single-file player). Compare mode sets this false so the bar
|
||||
* stays in-flow. Colors are always theme-aware regardless of this flag.
|
||||
*/
|
||||
floatOverlayInFullScreen?: boolean
|
||||
/** Fired when the cursor enters/leaves the bar (used to pin it visible). */
|
||||
onMouseEnter?: () => void
|
||||
onMouseLeave?: () => void
|
||||
}
|
||||
|
||||
export const VideoControlBar: React.FC<ControlBarProps> = ({
|
||||
state,
|
||||
zoom,
|
||||
isControlsVisible,
|
||||
buffered,
|
||||
data,
|
||||
resolutions,
|
||||
togglePlay,
|
||||
toggleLoop,
|
||||
toggleMute,
|
||||
handleVolumeChange,
|
||||
changePlaybackRate,
|
||||
changeResolution,
|
||||
handleDownload,
|
||||
toggleFullScreen,
|
||||
onZoomChange,
|
||||
onZoomReset,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
currentFrame,
|
||||
seekToFrame,
|
||||
floatOverlayInFullScreen = true,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
}) => {
|
||||
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
|
||||
|
||||
if (!data.media?.metadata) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Whether to render the bar as a floating overlay over the media (single-file
|
||||
// fullscreen). Compare keeps it in-flow. Colors stay theme-aware either way.
|
||||
const overlay = state.isFullScreen && floatOverlayInFullScreen
|
||||
|
||||
const previewResolutions = resolutions.filter((r) => !r.isRaw)
|
||||
|
||||
const startTimecode = data.media?.metadata?.startTimecode
|
||||
const displayTotalFrames = Math.max(0, totalFrames - 1)
|
||||
const displayString =
|
||||
videoTimeDisplayMode === 'frames'
|
||||
? `${currentFrame} / ${displayTotalFrames} fr`
|
||||
: videoTimeDisplayMode === 'standard'
|
||||
? `${formatTimecode(currentFrame, frameRate, 'standard')} / ${formatTime(totalFrames / frameRate)}`
|
||||
: `${formatTimecode(currentFrame, frameRate, videoTimeDisplayMode, startTimecode)} / ${formatTimecode(displayTotalFrames, frameRate, videoTimeDisplayMode, startTimecode)}`
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'transition-all duration-300 ease-in-out z-20 text-foreground',
|
||||
overlay
|
||||
? 'absolute bottom-0 left-0 right-0 px-4 py-4 bg-card/90 backdrop-blur-md border-t border-border'
|
||||
: 'relative w-full bg-card border-t border-border px-4 py-3 z-10 transition-colors duration-200',
|
||||
isControlsVisible
|
||||
? 'opacity-100 translate-y-0'
|
||||
: 'opacity-0 translate-y-4 pointer-events-none',
|
||||
)}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
>
|
||||
{/* Progress Bar */}
|
||||
<div className="mb-4 px-1">
|
||||
<ProgressBar
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
fps={frameRate}
|
||||
buffered={buffered}
|
||||
previewUrl={data.media.videoPreview?.url}
|
||||
onSeek={seekToFrame}
|
||||
metadata={{
|
||||
...data.media.metadata,
|
||||
frameRate: frameRate,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Lower Controls Row */}
|
||||
<div className="flex items-center justify-between text-foreground">
|
||||
{/* Left Side: Play, Vol, Time */}
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={togglePlay}
|
||||
className="hover:text-primary transition-colors"
|
||||
data-testid="play-toggle"
|
||||
data-playing={state.isPlaying}
|
||||
aria-label={state.isPlaying ? 'Pause' : 'Play'}
|
||||
>
|
||||
{state.isPlaying ? (
|
||||
<Pause className="w-6 h-6 fill-current" />
|
||||
) : (
|
||||
<Play className="w-6 h-6 fill-current" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={toggleLoop}
|
||||
className={cn(
|
||||
'transition-colors',
|
||||
state.isLooping ? 'text-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
title="Loop"
|
||||
>
|
||||
<Repeat className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-3 group/vol">
|
||||
<button onClick={toggleMute} className="hover:text-primary">
|
||||
{state.isMuted || state.volume === 0 ? (
|
||||
<VolumeX className="w-6 h-6" />
|
||||
) : (
|
||||
<Volume2 className="w-6 h-6" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="w-0 overflow-hidden group-hover/vol:w-24 transition-all duration-300 ease-in-out">
|
||||
<div className="w-24 px-1">
|
||||
<Slider
|
||||
value={state.isMuted ? [0] : [state.volume]}
|
||||
onValueChange={(v) => handleVolumeChange(v[0])}
|
||||
max={1}
|
||||
step={0.05}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]">
|
||||
<span className="text-muted-foreground font-mono" data-testid="time-readout">
|
||||
{displayString}
|
||||
</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none">
|
||||
<ChevronDown className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-40 z-30">
|
||||
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
|
||||
Format
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setVideoTimeDisplayMode('standard')}
|
||||
className="flex items-center justify-between cursor-pointer text-xs"
|
||||
>
|
||||
<span>Standard Time</span>
|
||||
{videoTimeDisplayMode === 'standard' && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setVideoTimeDisplayMode('frames')}
|
||||
className="flex items-center justify-between cursor-pointer text-xs"
|
||||
>
|
||||
<span>Frames</span>
|
||||
{videoTimeDisplayMode === 'frames' && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setVideoTimeDisplayMode('timecode')}
|
||||
className="flex items-center justify-between cursor-pointer text-xs"
|
||||
>
|
||||
<span>Timecode</span>
|
||||
{videoTimeDisplayMode === 'timecode' && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
|
||||
<div className="relative flex items-center gap-3">
|
||||
{/* Zoom Controls */}
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex items-center gap-1 rounded-md bg-muted p-0.5">
|
||||
<button
|
||||
onClick={() => onZoomChange(zoom * 0.8)}
|
||||
className="p-1 hover:text-primary rounded"
|
||||
>
|
||||
<Minus size={14} />
|
||||
</button>
|
||||
<span className="text-xs w-8 text-center tabular-nums">
|
||||
{Math.round(zoom * 100)}%
|
||||
</span>
|
||||
<button
|
||||
onClick={() => onZoomChange(zoom * 1.2)}
|
||||
className="p-1 hover:text-primary rounded"
|
||||
>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={onZoomReset}
|
||||
className="text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Playback Rate */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="w-8 text-sm font-bold hover:text-primary">
|
||||
{state.playbackRate}x
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
{[0.5, 1, 1.5, 2].map((rate) => (
|
||||
<DropdownMenuItem
|
||||
key={rate}
|
||||
onClick={() => changePlaybackRate(rate)}
|
||||
className={cn(
|
||||
'rounded py-1 px-2 text-left text-xs',
|
||||
state.playbackRate === rate
|
||||
? 'bg-primary text-primary-foreground focus:bg-primary focus:text-primary-foreground'
|
||||
: 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{rate}x
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Resolution Selector */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex items-center gap-1 rounded border border-border px-2 py-0.5 text-sm font-semibold hover:bg-muted transition-colors">
|
||||
<Settings className="h-3.5 w-3.5" />
|
||||
<span>{state.currentResolution}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuLabel>Quality</DropdownMenuLabel>
|
||||
{previewResolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => changeResolution(res)}
|
||||
className={cn(
|
||||
'flex w-full items-center justify-between',
|
||||
state.currentResolution === res.resolution
|
||||
? 'text-primary font-medium'
|
||||
: 'text-foreground',
|
||||
)}
|
||||
>
|
||||
<span>{res.resolution}</span>
|
||||
<span className="pl-5 text-xs text-muted-foreground">
|
||||
{res.width}x{res.height}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Download */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="transition-colors hover:text-primary" title="Download">
|
||||
<Download className="h-5 w-5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuLabel>Download</DropdownMenuLabel>
|
||||
{resolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => handleDownload(res.key ?? '')}
|
||||
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
|
||||
>
|
||||
<span>{res.resolution}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Fullscreen */}
|
||||
<button onClick={toggleFullScreen} className="transition-colors hover:text-primary">
|
||||
{state.isFullScreen ? (
|
||||
<Minimize className="h-6 w-6" />
|
||||
) : (
|
||||
<Maximize className="h-6 w-6" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,55 +1,18 @@
|
||||
import type { AssetInfo, VideoTranscode } from '@shumai/dtos'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
Download,
|
||||
Maximize,
|
||||
Minimize,
|
||||
Minus,
|
||||
Pause,
|
||||
Play,
|
||||
Plus,
|
||||
Repeat,
|
||||
Settings,
|
||||
Volume2,
|
||||
VolumeX,
|
||||
} from 'lucide-react'
|
||||
import { Play } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import videojs from 'video.js'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from '../ui/dropdown-menu'
|
||||
import { Slider } from '../ui/slider'
|
||||
import ProgressBar from './progress-bar'
|
||||
import { formatTimecode, formatTime } from './utils'
|
||||
import { useFramePlayer } from './use-frame-player'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { resolveTotalFrames } from './utils'
|
||||
import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
|
||||
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import DrawingCanvas from '../drawing-canvas'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
|
||||
export interface PlayerState {
|
||||
isPlaying: boolean
|
||||
progress: number // 0 to 100
|
||||
currentTime: number
|
||||
duration: number
|
||||
volume: number
|
||||
isMuted: boolean
|
||||
isLooping: boolean
|
||||
playbackRate: number
|
||||
isFullScreen: boolean
|
||||
showFrames: boolean // Toggle between time (02:30) and frames (1234)
|
||||
currentResolution: string // 'Original' or '720p', '480p' etc.
|
||||
currentSrc?: string
|
||||
}
|
||||
|
||||
interface VideoPlayerProps {
|
||||
data: AssetInfo
|
||||
playerRef?: React.RefObject<Player | null>
|
||||
@@ -58,316 +21,10 @@ interface VideoPlayerProps {
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
startTime?: number
|
||||
shareId?: string
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
type DisplayTranscode = VideoTranscode & { resolution: string }
|
||||
|
||||
interface ControlBarProps {
|
||||
state: PlayerState
|
||||
zoom: number
|
||||
isControlsVisible: boolean
|
||||
buffered: number
|
||||
data: AssetInfo
|
||||
resolutions: DisplayTranscode[]
|
||||
togglePlay: () => void
|
||||
toggleLoop: () => void
|
||||
toggleMute: () => void
|
||||
handleVolumeChange: (newVolume: number) => void
|
||||
changePlaybackRate: (rate: number) => void
|
||||
changeResolution: (res: DisplayTranscode) => void
|
||||
handleDownload: (url: string, resolution: string) => void
|
||||
toggleFullScreen: () => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
onZoomReset: () => void
|
||||
// Frame-accurate props
|
||||
frameRate: number
|
||||
totalFrames: number
|
||||
currentFrame: number
|
||||
seekToFrame: (frame: number) => Promise<void>
|
||||
}
|
||||
|
||||
const ControlBar: React.FC<ControlBarProps> = ({
|
||||
state,
|
||||
zoom,
|
||||
isControlsVisible,
|
||||
buffered,
|
||||
data,
|
||||
resolutions,
|
||||
togglePlay,
|
||||
toggleLoop,
|
||||
toggleMute,
|
||||
handleVolumeChange,
|
||||
changePlaybackRate,
|
||||
changeResolution,
|
||||
handleDownload,
|
||||
toggleFullScreen,
|
||||
onZoomChange,
|
||||
onZoomReset,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
currentFrame,
|
||||
seekToFrame,
|
||||
}) => {
|
||||
if (!data.media?.metadata) {
|
||||
return null
|
||||
}
|
||||
|
||||
const previewResolutions = resolutions.filter((r) => !r.isRaw)
|
||||
|
||||
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
|
||||
|
||||
const startTimecode = data.media?.metadata?.startTimecode
|
||||
const displayTotalFrames = Math.max(0, totalFrames - 1)
|
||||
const displayString =
|
||||
videoTimeDisplayMode === 'frames'
|
||||
? `${currentFrame} / ${displayTotalFrames} fr`
|
||||
: videoTimeDisplayMode === 'standard'
|
||||
? `${formatTimecode(currentFrame, frameRate, 'standard')} / ${formatTime(totalFrames / frameRate)}`
|
||||
: `${formatTimecode(currentFrame, frameRate, videoTimeDisplayMode, startTimecode)} / ${formatTimecode(displayTotalFrames, frameRate, videoTimeDisplayMode, startTimecode)}`
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'transition-all duration-300 ease-in-out z-20',
|
||||
state.isFullScreen
|
||||
? 'absolute bottom-0 left-0 right-0 px-4 py-4 bg-black/60 backdrop-blur-md text-white'
|
||||
: 'relative w-full bg-card border-t border-border px-4 py-3 z-10 transition-colors duration-200',
|
||||
isControlsVisible
|
||||
? 'opacity-100 translate-y-0'
|
||||
: 'opacity-0 translate-y-4 pointer-events-none',
|
||||
)}
|
||||
>
|
||||
{/* Progress Bar */}
|
||||
<div className="mb-4 px-1">
|
||||
<ProgressBar
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
fps={frameRate}
|
||||
buffered={buffered}
|
||||
previewUrl={data.media.videoPreview?.url}
|
||||
onSeek={seekToFrame}
|
||||
metadata={{
|
||||
...data.media.metadata,
|
||||
frameRate: frameRate,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Lower Controls Row */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-between',
|
||||
state.isFullScreen ? 'text-white/90' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{/* Left Side: Play, Vol, Time */}
|
||||
<div className="flex items-center gap-4">
|
||||
<button onClick={togglePlay} className="hover:text-primary transition-colors">
|
||||
{state.isPlaying ? (
|
||||
<Pause className="w-6 h-6 fill-current" />
|
||||
) : (
|
||||
<Play className="w-6 h-6 fill-current" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={toggleLoop}
|
||||
className={cn(
|
||||
'transition-colors',
|
||||
state.isLooping ? 'text-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
title="Loop"
|
||||
>
|
||||
<Repeat className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-3 group/vol">
|
||||
<button onClick={toggleMute} className="hover:text-primary">
|
||||
{state.isMuted || state.volume === 0 ? (
|
||||
<VolumeX className="w-6 h-6" />
|
||||
) : (
|
||||
<Volume2 className="w-6 h-6" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="w-0 overflow-hidden group-hover/vol:w-24 transition-all duration-300 ease-in-out">
|
||||
<div className="w-24 px-1">
|
||||
<Slider
|
||||
value={state.isMuted ? [0] : [state.volume]}
|
||||
onValueChange={(v) => handleVolumeChange(v[0])}
|
||||
max={1}
|
||||
step={0.05}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]">
|
||||
<span className="text-muted-foreground font-mono">{displayString}</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none">
|
||||
<ChevronDown className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-40 z-30">
|
||||
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
|
||||
Format
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setVideoTimeDisplayMode('standard')}
|
||||
className="flex items-center justify-between cursor-pointer text-xs"
|
||||
>
|
||||
<span>Standard Time</span>
|
||||
{videoTimeDisplayMode === 'standard' && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setVideoTimeDisplayMode('frames')}
|
||||
className="flex items-center justify-between cursor-pointer text-xs"
|
||||
>
|
||||
<span>Frames</span>
|
||||
{videoTimeDisplayMode === 'frames' && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setVideoTimeDisplayMode('timecode')}
|
||||
className="flex items-center justify-between cursor-pointer text-xs"
|
||||
>
|
||||
<span>Timecode</span>
|
||||
{videoTimeDisplayMode === 'timecode' && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
|
||||
<div className="relative flex items-center gap-3">
|
||||
{/* Zoom Controls */}
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex items-center gap-1 bg-muted rounded-md p-0.5">
|
||||
<button
|
||||
onClick={() => onZoomChange(zoom * 0.8)}
|
||||
className="p-1 hover:text-primary rounded"
|
||||
>
|
||||
<Minus size={14} />
|
||||
</button>
|
||||
<span className="text-xs w-8 text-center tabular-nums">
|
||||
{Math.round(zoom * 100)}%
|
||||
</span>
|
||||
<button
|
||||
onClick={() => onZoomChange(zoom * 1.2)}
|
||||
className="p-1 hover:text-primary rounded"
|
||||
>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={onZoomReset}
|
||||
className="text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Playback Rate */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="w-8 text-sm font-bold hover:text-primary">
|
||||
{state.playbackRate}x
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
{[0.5, 1, 1.5, 2].map((rate) => (
|
||||
<DropdownMenuItem
|
||||
key={rate}
|
||||
onClick={() => changePlaybackRate(rate)}
|
||||
className={cn(
|
||||
'rounded py-1 px-2 text-left text-xs',
|
||||
state.playbackRate === rate
|
||||
? 'bg-primary text-primary-foreground focus:bg-primary focus:text-primary-foreground'
|
||||
: 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{rate}x
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Resolution Selector */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex items-center gap-1 rounded border border-border px-2 py-0.5 text-sm font-semibold hover:bg-muted transition-colors">
|
||||
<Settings className="h-3.5 w-3.5" />
|
||||
<span>{state.currentResolution}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuLabel>Quality</DropdownMenuLabel>
|
||||
{previewResolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => changeResolution(res)}
|
||||
className={cn(
|
||||
'flex w-full items-center justify-between',
|
||||
state.currentResolution === res.resolution
|
||||
? 'text-primary font-medium'
|
||||
: 'text-foreground',
|
||||
)}
|
||||
>
|
||||
<span>{res.resolution}</span>
|
||||
<span className="pl-5 text-xs text-muted-foreground">
|
||||
{res.width}x{res.height}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Download */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="transition-colors hover:text-primary" title="Download">
|
||||
<Download className="h-5 w-5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuLabel>Download</DropdownMenuLabel>
|
||||
{resolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => handleDownload(res.url ?? '', res.resolution)}
|
||||
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
|
||||
>
|
||||
<span>{res.resolution}</span>
|
||||
<span className="text-xs text-muted-foreground">MP4</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Fullscreen */}
|
||||
<button onClick={toggleFullScreen} className="transition-colors hover:text-primary">
|
||||
{state.isFullScreen ? (
|
||||
<Minimize className="h-6 w-6" />
|
||||
) : (
|
||||
<Maximize className="h-6 w-6" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
data,
|
||||
playerRef: passedPlayerRef,
|
||||
@@ -376,6 +33,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
shareId,
|
||||
children,
|
||||
}) => {
|
||||
const localPlayerRef = useRef<Player | null>(null)
|
||||
@@ -383,7 +41,9 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
// We use a container ref to manually append the video element
|
||||
const videoContainerRef = useRef<HTMLDivElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const controlsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const isOverControlsRef = useRef(false)
|
||||
|
||||
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null)
|
||||
@@ -456,12 +116,16 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
|
||||
// Initial resolution setup
|
||||
const originalRes = {
|
||||
const originalRes: DisplayTranscode = {
|
||||
id: 'original',
|
||||
url: data.media.original.downloadUrl,
|
||||
key: data.media.original.key ?? '',
|
||||
width: data.media.metadata.originalWidth ?? 0,
|
||||
height: data.media.metadata.originalHeight ?? 0,
|
||||
size: 0,
|
||||
isRaw: true,
|
||||
resolution: 'Original',
|
||||
} as DisplayTranscode
|
||||
}
|
||||
|
||||
const resolutions: DisplayTranscode[] = (data.media.videoTranscodes ?? []).map((t) => {
|
||||
const longSide = Math.max(t.width, t.height)
|
||||
@@ -532,13 +196,8 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
const frameRate = metadata.frameRate || 30
|
||||
const dbTotalFrames = metadata.totalFrames || 0
|
||||
const containerDuration = metadata.duration || 0
|
||||
const videoDuration = dbTotalFrames / frameRate
|
||||
const frameDuration = 1 / frameRate
|
||||
|
||||
const totalFrames =
|
||||
containerDuration - videoDuration > 0.5 * frameDuration
|
||||
? Math.round(containerDuration * frameRate)
|
||||
: dbTotalFrames
|
||||
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
|
||||
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
|
||||
|
||||
const currentTime = currentFrame / frameRate
|
||||
@@ -678,30 +337,42 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
}, [startTime, frameRate, seekToFrame, isPlayerReady])
|
||||
|
||||
const handleMouseMove = useCallback(() => {
|
||||
// Always show controls on movement
|
||||
setIsControlsVisible(true)
|
||||
|
||||
const scheduleHide = useCallback(() => {
|
||||
if (controlsTimeoutRef.current) {
|
||||
clearTimeout(controlsTimeoutRef.current)
|
||||
}
|
||||
|
||||
// Only set auto-hide timer if we are in fullscreen and playing
|
||||
// If paused, controls should remain visible so user can see what to do
|
||||
if (state.isFullScreen && state.isPlaying) {
|
||||
// Never hide while the cursor rests over the control bar itself.
|
||||
if (state.isFullScreen && !isOverControlsRef.current) {
|
||||
controlsTimeoutRef.current = setTimeout(() => {
|
||||
setIsControlsVisible(false)
|
||||
}, 2000)
|
||||
}, 1200)
|
||||
}
|
||||
}, [state.isFullScreen, state.isPlaying])
|
||||
}, [state.isFullScreen])
|
||||
|
||||
const handleMouseMove = useCallback(() => {
|
||||
// Always show controls on movement, then (re)start the idle hide timer.
|
||||
setIsControlsVisible(true)
|
||||
scheduleHide()
|
||||
}, [scheduleHide])
|
||||
|
||||
const handleControlsMouseEnter = useCallback(() => {
|
||||
isOverControlsRef.current = true
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
setIsControlsVisible(true)
|
||||
}, [])
|
||||
|
||||
const handleControlsMouseLeave = useCallback(() => {
|
||||
isOverControlsRef.current = false
|
||||
scheduleHide()
|
||||
}, [scheduleHide])
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
// If we leave the player area in fullscreen, hide controls (optional preference, usually good)
|
||||
if (state.isFullScreen && state.isPlaying) {
|
||||
// If the cursor leaves the player while fullscreen, hide the controls.
|
||||
if (state.isFullScreen) {
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
setIsControlsVisible(false)
|
||||
}
|
||||
}, [state.isFullScreen, state.isPlaying])
|
||||
}, [state.isFullScreen])
|
||||
|
||||
// Clean up timeout on unmount or state change
|
||||
useEffect(() => {
|
||||
@@ -710,13 +381,13 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Ensure controls are visible when pausing or entering fullscreen initially
|
||||
// Windowed mode: controls are always visible. Fullscreen: show now and let
|
||||
// the idle timer hide them (re-runs on play/pause so pausing re-reveals them).
|
||||
useEffect(() => {
|
||||
if (!state.isPlaying) {
|
||||
if (!state.isFullScreen) {
|
||||
setIsControlsVisible(true)
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
} else {
|
||||
// If we just started playing (or re-entered playing state), trigger the timer logic
|
||||
handleMouseMove()
|
||||
}
|
||||
}, [state.isPlaying, state.isFullScreen, handleMouseMove])
|
||||
@@ -827,9 +498,9 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
|
||||
const toggleFullScreen = () => {
|
||||
if (!containerRef.current) return
|
||||
if (!rootRef.current) return
|
||||
if (!document.fullscreenElement) {
|
||||
containerRef.current.requestFullscreen()
|
||||
rootRef.current.requestFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: true }))
|
||||
} else {
|
||||
document.exitFullscreen()
|
||||
@@ -837,13 +508,27 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = (url: string, resolution: string) => {
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = `${data.name}-${resolution}.mp4`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
const handleDownload = async (key: string) => {
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: data.id! },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: data.id! },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for fullscreen change events (ESC key)
|
||||
@@ -868,6 +553,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={cn(
|
||||
'group shadow-2xl font-sans select-none flex flex-col mx-auto transition-all duration-300 relative',
|
||||
state.isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
|
||||
@@ -888,6 +574,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
)}
|
||||
onClick={togglePlay}
|
||||
data-vjs-player
|
||||
data-testid="video-area"
|
||||
>
|
||||
{/* Hidden VideoJS container */}
|
||||
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
|
||||
@@ -926,7 +613,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ControlBar
|
||||
<VideoControlBar
|
||||
state={controlBarState}
|
||||
zoom={zoom}
|
||||
isControlsVisible={isControlsVisible}
|
||||
@@ -947,6 +634,8 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
seekToFrame={seekToFrame}
|
||||
onMouseEnter={handleControlsMouseEnter}
|
||||
onMouseLeave={handleControlsMouseLeave}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -68,6 +68,30 @@ $$\text{Time}_{\text{center}} = \left(N \cdot T_d\right) + \frac{T_d}{2} = \frac
|
||||
|
||||
*Where $T_d = \frac{1}{\text{frameRate}}$ is the duration of a single frame.*
|
||||
|
||||
---
|
||||
|
||||
### D. Effective Frame Count Derivation (Container vs. Video Stream)
|
||||
|
||||
The player's `totalFrames` governs the frame readout (`N / M fr`), the seekbar extent, frame-stepping bounds, and the playback clamp. It is **not** always the same as the container's frame count, because a container's duration can exceed its video stream — most commonly when the **audio track is slightly longer than the video track** (AAC padding and the fixed 1024-samples-per-frame granularity mean audio rarely ends on the exact video timestamp), or from container overhead.
|
||||
|
||||
Deriving the count naively from the container duration ($\lfloor \text{containerDuration} \cdot \text{frameRate} \rceil$) invents **phantom trailing frames** the video stream does not contain. Whether those extra frames should be counted depends on whether the playhead can actually *reach* them during playback, which is governed by the same **stall threshold** used by the playback loop (§3):
|
||||
|
||||
$$\text{Threshold}_{s} = \frac{\max\left(100, \frac{3000}{\text{frameRate}}\right)}{1000}\text{ seconds}$$
|
||||
|
||||
Let $\text{tail} = \text{containerDuration} - \frac{\text{dbTotalFrames}}{\text{frameRate}}$ (where `dbTotalFrames` is the video stream's `nb_frames`). Then:
|
||||
|
||||
$$\text{totalFrames} = \begin{cases}
|
||||
\lfloor \text{containerDuration} \cdot \text{frameRate} \rceil & \text{if tail} > \text{Threshold}_{s}\ \text{(reachable — keep the tail)} \\
|
||||
\text{dbTotalFrames} & \text{otherwise (unreachable — drop phantom frames)} \\
|
||||
\lfloor \text{containerDuration} \cdot \text{frameRate} \rceil & \text{if dbTotalFrames} \le 0\ \text{(nb\_frames missing)}
|
||||
\end{cases}$$
|
||||
|
||||
* **Small tail (tail ≤ threshold):** The RAF fallback never activates (§3), so the playhead physically cannot enter the tail. Counting those frames would strand the readout short of its own maximum (e.g. a 268-frame video in a 270-frame container would show `267 / 269` and stop at 267). We therefore use the accurate video-stream count → `267 / 267`. The trailing audio still plays out to the container end on the native element; it is simply not represented as extra scrubbable frames.
|
||||
* **Large tail (tail > threshold):** The playhead *does* traverse the audio-only region (the RAF fallback drives it from `video.currentTime`, §3), so the container-derived count is correct and the readout reaches its maximum at the natural end (e.g. a 150-frame video with a 6.5s audio tail shows `194 / 194`).
|
||||
|
||||
This rule is implemented by `resolveTotalFrames` in `viewers/utils.ts`, which shares `stallThresholdMs` with `useFramePlayer` so the frame-count boundary and the runtime playhead-reachability boundary can never drift apart.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 3. Active Playback Loops & Dual-Drive Coordination
|
||||
@@ -97,9 +121,9 @@ When playing, the playhead loop coordinates two mechanisms in parallel to preven
|
||||
|
||||
1. **`requestVideoFrameCallback` (rVFC):** The primary driver when the video is actively decoding. It fires only when a new video frame is sent to the compositor, updating the UI frame-accurately based on `metadata.mediaTime`.
|
||||
2. **`requestAnimationFrame` (RAF):** Runs continuously at 60Hz. It acts as the fallback driver.
|
||||
3. **Stall Detection:** The playhead tracks when the last rVFC callback was fired. If it has been stalled for longer than the **dynamic stall threshold**:
|
||||
3. **Compositor-First Gating & Stall Detection:** `video.currentTime` is the playback (audio) clock, and on some engines (notably Safari/WebKit) it runs *ahead* of the frame actually presented on screen right after playback starts. Trusting it before the compositor catches up would race the playhead forward and then snap it backward when the first rVFC (`mediaTime`) arrives. To prevent this, each `play` resets the per-session sync state, and the playhead is driven from `video.currentTime` **only** when `requestVideoFrameCallback` is unsupported, **or** rVFC has delivered a frame this session and has since stalled beyond the **dynamic stall threshold**:
|
||||
$$\text{Threshold} = \max\left(100, \frac{3000}{\text{frameRate}}\right)\text{ ms}$$
|
||||
the RAF loop takes over playhead updates using `video.currentTime`.
|
||||
the `requestAnimationFrame` loop may drive playhead updates from `video.currentTime`. As a safety net, this fallback also engages if rVFC never fires within an initial grace window (~1000 ms) after play, so the playhead can never freeze permanently. Until the first compositor frame is presented, the playhead follows `mediaTime` (rVFC) exclusively, so it never leads the on-screen image.
|
||||
|
||||
This prevents the timeline from freezing when the video track ends but audio keeps playing (e.g. video track ends at 10s, audio at 15.4s).
|
||||
|
||||
@@ -109,9 +133,10 @@ When playing, the playhead loop coordinates two mechanisms in parallel to preven
|
||||
|
||||
### A. Play Video
|
||||
1. User clicks Play.
|
||||
2. The `play` event listener triggers `updateFrameLoop()`.
|
||||
2. The `play` event listener resets the per-session sync state and triggers `updateFrameLoop()`.
|
||||
3. If supported, `requestVideoFrameCallback` is registered. In parallel, `requestAnimationFrame` is scheduled recursively.
|
||||
4. UI displays continuous updates aligned with compositor frames.
|
||||
4. Until the first rVFC frame is presented, the playhead is driven **only** by `mediaTime`; the `requestAnimationFrame` path does not advance it from `video.currentTime` (see §3), avoiding a forward race on engines whose playback clock leads presentation at startup.
|
||||
5. Thereafter the UI displays continuous updates aligned with compositor frames.
|
||||
|
||||
---
|
||||
|
||||
@@ -119,12 +144,16 @@ When playing, the playhead loop coordinates two mechanisms in parallel to preven
|
||||
1. User clicks Pause.
|
||||
2. The `pause` event listener triggers `handlePause()`:
|
||||
* Cancels active VFC (`cancelVideoFrameCallback`) and RAF (`cancelAnimationFrame`) loops.
|
||||
* Chooses the synchronization time. When rVFC is **fresh** (it delivered a frame within the stall threshold), the last presented compositor time `lastMediaTime` is used — this is the frame actually on screen. Otherwise (rVFC stale or unsupported, e.g. an audio-only tail after the video track ends) it falls back to `video.currentTime`:
|
||||
$$\text{syncTime} = \begin{cases} \text{lastMediaTime} & \text{if rVFC is fresh} \\ video.currentTime & \text{otherwise} \end{cases}$$
|
||||
* Performs a final playhead synchronization:
|
||||
$$\text{clampedFrame} = \max\left(0, \min\left(\lfloor(video.currentTime \cdot frameRate) + 0.45\rfloor, \text{totalFrames} - 1\right)\right)$$
|
||||
* Calls `setCurrentFrame(clampedFrame)` to lock the UI to the correct frame.
|
||||
$$\text{clampedFrame} = \max\left(0, \min\left(\lfloor(\text{syncTime} \cdot frameRate) + 0.45\rfloor, \text{totalFrames} - 1\right)\right)$$
|
||||
* Calls `setCurrentFrame(clampedFrame)` to lock the UI to the frame the user is actually looking at.
|
||||
* **Snaps the browser playhead** to the calculated frame's center time to force the browser compositor to align:
|
||||
$$\text{currentTime} = \text{calculateFrameCenterTime}(\text{clampedFrame}, \text{frameRate})$$
|
||||
|
||||
> **Frame-accurate tradeoff:** because pause locks to the *presented* frame (which on Safari lags the audio clock), snapping `currentTime` back to that frame's center means the small audio segment between the presented frame and the audio position is replayed on resume. This is intentional and matches other frame-accurate tools (e.g. frame.io): landing on the exact displayed frame takes priority over seamless audio. The effect is proportional to the engine's audio/video presentation offset — negligible on Chrome, ~100–300 ms on Safari.
|
||||
|
||||
---
|
||||
|
||||
### C. Drag Seekbar Head to a Timestamp
|
||||
@@ -209,6 +238,8 @@ The extracted metadata details are saved to the `AssetMetadata` table:
|
||||
* `duration` (the absolute container duration, e.g. `15.42`)
|
||||
* `totalFrames` (the physical number of frames in the video stream, e.g. `240`)
|
||||
|
||||
> **Note:** `totalFrames` is always the physical **video-stream** frame count (`nb_frames`), while `duration` is the **container** duration (which can be longer, e.g. when the audio track outlasts the video). The frontend reconciles the two into an effective frame count via the rule in §2.D — it does not blindly trust either value alone.
|
||||
|
||||
---
|
||||
|
||||
### B. Database Schema
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,138 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
/**
|
||||
* Deterministic metadata for the committed fixture video
|
||||
* (packages/webui/e2e/fixtures/sample.mp4).
|
||||
*
|
||||
* Generated with:
|
||||
* ffmpeg -f lavfi -i testsrc=size=16x16:rate=30 -t 5 -pix_fmt yuv420p sample.mp4
|
||||
*
|
||||
* Verified via ffprobe: 16x16, 30/1 fps, duration 5.0s, 150 frames.
|
||||
* These constants are shared by the harness and the Playwright specs so the
|
||||
* frame-accurate assertions have known-good expected values.
|
||||
*/
|
||||
export const SAMPLE_FRAME_RATE = 30
|
||||
export const SAMPLE_TOTAL_FRAMES = 150
|
||||
export const SAMPLE_DURATION = 5
|
||||
export const SAMPLE_WIDTH = 16
|
||||
export const SAMPLE_HEIGHT = 16
|
||||
|
||||
/**
|
||||
* The fixture video is served statically by the harness Vite server
|
||||
* (publicDir points at packages/webui/e2e/fixtures), so it is reachable at
|
||||
* the site root. No backend is involved.
|
||||
*/
|
||||
export const SAMPLE_VIDEO_URL = '/sample.mp4'
|
||||
|
||||
export const sampleVideoAsset: AssetInfo = {
|
||||
id: 'e2e-sample-asset',
|
||||
name: 'sample.mp4',
|
||||
sizeByte: 6170,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'ready',
|
||||
mediaType: 'video',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
media: {
|
||||
original: {
|
||||
downloadUrl: SAMPLE_VIDEO_URL,
|
||||
key: 'sample.mp4',
|
||||
},
|
||||
metadata: {
|
||||
duration: SAMPLE_DURATION,
|
||||
originalWidth: SAMPLE_WIDTH,
|
||||
originalHeight: SAMPLE_HEIGHT,
|
||||
frameRate: SAMPLE_FRAME_RATE,
|
||||
totalFrames: SAMPLE_TOTAL_FRAMES,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata variant reproducing the real-world case where the container/format
|
||||
* duration is LONGER than the actual video stream (audio padding / container
|
||||
* overhead). This mirrors an observed asset whose ffprobe reported:
|
||||
* - video stream: nb_frames=268, duration=8.9333s
|
||||
* - format: duration=9.008s (~2 frames longer than the stream)
|
||||
*
|
||||
* Here the backing file is still the real 150-frame sample.mp4 (video stream =
|
||||
* 5.0s, 150 real decodable frames), but the stored metadata reports a container
|
||||
* duration of 5.075s — i.e. ~2.25 frames longer than the 150-frame stream.
|
||||
*
|
||||
* `metadata.totalFrames` stays at the accurate stream frame count (150, from
|
||||
* ffprobe `nb_frames`), exactly as the backend stores it.
|
||||
*/
|
||||
export const CONTAINER_LONGER_DURATION = 5.075
|
||||
|
||||
/**
|
||||
* The frame count the player's current heuristic derives from the inflated
|
||||
* container duration: round(5.075 * 30) = 152, i.e. 2 frames MORE than the 150
|
||||
* frames that actually exist in the stream. Frames 150 and 151 are phantom.
|
||||
*/
|
||||
export const CONTAINER_LONGER_COMPUTED_TOTAL_FRAMES = Math.round(
|
||||
CONTAINER_LONGER_DURATION * SAMPLE_FRAME_RATE,
|
||||
)
|
||||
|
||||
/** The last frame index that actually exists in the stream (0-based): 149. */
|
||||
export const REAL_LAST_FRAME = SAMPLE_TOTAL_FRAMES - 1
|
||||
|
||||
export const containerLongerVideoAsset: AssetInfo = {
|
||||
...sampleVideoAsset,
|
||||
id: 'e2e-container-longer-asset',
|
||||
media: {
|
||||
original: {
|
||||
downloadUrl: SAMPLE_VIDEO_URL,
|
||||
key: 'sample.mp4',
|
||||
},
|
||||
metadata: {
|
||||
duration: CONTAINER_LONGER_DURATION,
|
||||
originalWidth: SAMPLE_WIDTH,
|
||||
originalHeight: SAMPLE_HEIGHT,
|
||||
frameRate: SAMPLE_FRAME_RATE,
|
||||
totalFrames: SAMPLE_TOTAL_FRAMES,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata variant for the LARGE-gap ("videoB") case: the audio track is much
|
||||
* longer than the video track, so the container tail is long enough for the
|
||||
* playhead to actually traverse it during playback.
|
||||
*
|
||||
* Backed by the real committed fixture `sample-long-audio.mp4` (verified via
|
||||
* ffprobe):
|
||||
* - video stream: nb_frames=150, duration=5.000s, 30fps
|
||||
* - audio stream: duration=6.500s
|
||||
* - format: duration=6.500s (1.5s / 45-frame tail — well above the
|
||||
* ~100ms playback stall threshold)
|
||||
*
|
||||
* Because the tail exceeds the stall threshold, both the current code and the
|
||||
* fix derive the frame count from the container duration
|
||||
* (round(6.5 * 30) = 195). The playhead advances through the audio tail to the
|
||||
* container end, so at natural end the readout reaches its maximum (194).
|
||||
*/
|
||||
export const LONG_AUDIO_VIDEO_URL = '/sample-long-audio.mp4'
|
||||
export const LONG_AUDIO_DURATION = 6.5
|
||||
|
||||
/** Container-derived frame count for the long-audio fixture: round(6.5 * 30). */
|
||||
export const LONG_AUDIO_COMPUTED_TOTAL_FRAMES = Math.round(LONG_AUDIO_DURATION * SAMPLE_FRAME_RATE)
|
||||
|
||||
export const longAudioVideoAsset: AssetInfo = {
|
||||
...sampleVideoAsset,
|
||||
id: 'e2e-long-audio-asset',
|
||||
name: 'sample-long-audio.mp4',
|
||||
media: {
|
||||
original: {
|
||||
downloadUrl: LONG_AUDIO_VIDEO_URL,
|
||||
key: 'sample-long-audio.mp4',
|
||||
},
|
||||
metadata: {
|
||||
duration: LONG_AUDIO_DURATION,
|
||||
originalWidth: SAMPLE_WIDTH,
|
||||
originalHeight: SAMPLE_HEIGHT,
|
||||
frameRate: SAMPLE_FRAME_RATE,
|
||||
totalFrames: SAMPLE_TOTAL_FRAMES,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" href="../../globals.css" />
|
||||
<title>Video Player E2E Harness</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,179 @@
|
||||
import { type ReactElement, useCallback, useRef, useState } from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import VideoPlayer from '@/ui/components/viewers/video-player'
|
||||
import { calculateFrameCenterTime } from '@/ui/components/viewers/utils'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import {
|
||||
SAMPLE_FRAME_RATE,
|
||||
sampleVideoAsset,
|
||||
containerLongerVideoAsset,
|
||||
longAudioVideoAsset,
|
||||
} from './fixture'
|
||||
|
||||
/**
|
||||
* Backend-free harness page that mounts the *real* VideoPlayer component with a
|
||||
* fixture AssetInfo pointing at a locally served sample video. No API/router/
|
||||
* query providers are required for playback, so this isolates the frame-accurate
|
||||
* player logic (useFramePlayer + ProgressBar + video.js) for UI integration tests.
|
||||
*
|
||||
* We force the time readout into "frames" mode so specs can parse the exact
|
||||
* integer frame index the UI is displaying and assert it against the native
|
||||
* <video> clock and the seekbar fill.
|
||||
*
|
||||
* On top of the bare player, this harness reproduces — with the app's *real*
|
||||
* code paths — the comment↔player wiring that production uses
|
||||
* (`routes/projects/$projectId/files/$fileId.tsx` + `file-viewer.tsx`):
|
||||
*
|
||||
* - `onTimeUpdate` captures the player's current time in seconds. This is the
|
||||
* exact value the app stores as a comment's `second` (see message-input's
|
||||
* `onSendMessage(..., currentTime)`).
|
||||
* - "Create comment" snapshots that `second` and appends a comment. Each
|
||||
* comment renders its derived frame `Math.round(second * fps)`, matching
|
||||
* message-card's timestamp derivation.
|
||||
* - Clicking a comment runs the app's real seek: `player.currentTime(second)`
|
||||
* followed by `player.pause()`, exactly like the route's
|
||||
* `handleCommentSelect`. That raw seek drives useFramePlayer's external
|
||||
* `seeked` handler, which recomputes the frame from the media clock.
|
||||
* - "Reload as user B" remounts the player with a fresh key (starting at
|
||||
* frame 0) to simulate a second user opening the page, while the comment
|
||||
* list persists.
|
||||
*
|
||||
* All comment controls live OUTSIDE the player's constrained 800x600 box so the
|
||||
* player's layout is byte-for-byte identical to what play-pause.spec.ts expects
|
||||
* (the box constraint prevents the drawing-canvas ResizeObserver from feeding
|
||||
* its width back and growing unbounded).
|
||||
*/
|
||||
useUiStore.setState({ videoTimeDisplayMode: 'frames' })
|
||||
|
||||
/**
|
||||
* Select which fixture asset to mount based on the `?variant=` query param, so
|
||||
* specs can exercise different metadata shapes against the same real backing
|
||||
* video. Defaults to the canonical sample asset used by the other specs.
|
||||
*/
|
||||
function resolveAsset() {
|
||||
const variant =
|
||||
typeof window !== 'undefined'
|
||||
? new URLSearchParams(window.location.search).get('variant')
|
||||
: null
|
||||
if (variant === 'container-longer') return containerLongerVideoAsset
|
||||
if (variant === 'long-audio') return longAudioVideoAsset
|
||||
return sampleVideoAsset
|
||||
}
|
||||
|
||||
const harnessAsset = resolveAsset()
|
||||
|
||||
interface HarnessComment {
|
||||
id: string
|
||||
second: number
|
||||
frame: number
|
||||
}
|
||||
|
||||
function Harness(): ReactElement {
|
||||
const playerRef = useRef<Player | null>(null)
|
||||
// Latest player time (seconds) as reported by the real onTimeUpdate prop.
|
||||
const currentTimeRef = useRef<number>(0)
|
||||
const seekInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const [comments, setComments] = useState<HarnessComment[]>([])
|
||||
// Bumping this key remounts VideoPlayer, simulating a fresh page load (user B).
|
||||
const [playerKey, setPlayerKey] = useState<number>(0)
|
||||
|
||||
const handleTimeUpdate = useCallback((time: number) => {
|
||||
currentTimeRef.current = time
|
||||
}, [])
|
||||
|
||||
// Deterministic setup seek for "user A": land exactly on a target frame using
|
||||
// a real external seek to the frame-center time (the same class of seek the
|
||||
// timeline/comment paths use). This positions the player without depending on
|
||||
// the thing under test (the comment roundtrip).
|
||||
const handleSeekToFrame = useCallback(() => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
const frame = Number.parseInt(seekInputRef.current?.value ?? '', 10)
|
||||
if (Number.isNaN(frame)) return
|
||||
player.currentTime(calculateFrameCenterTime(frame, SAMPLE_FRAME_RATE))
|
||||
player.pause()
|
||||
}, [])
|
||||
|
||||
// "User A" creates a comment: captures the current time in seconds exactly as
|
||||
// the app does, then derives the displayed frame the same way message-card does.
|
||||
const handleCreateComment = useCallback(() => {
|
||||
const second = currentTimeRef.current
|
||||
setComments((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: `comment-${prev.length}`,
|
||||
second,
|
||||
frame: Math.round(second * SAMPLE_FRAME_RATE),
|
||||
},
|
||||
])
|
||||
}, [])
|
||||
|
||||
// "User B" clicks a comment: the app's real seek path.
|
||||
const handleCommentClick = useCallback((second: number) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
player.currentTime(second)
|
||||
player.pause()
|
||||
}, [])
|
||||
|
||||
const handleReloadAsUserB = useCallback(() => {
|
||||
setPlayerKey((k) => k + 1)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Player box: identical constrained container to the real file-viewer. */}
|
||||
<div
|
||||
data-testid="harness-stage"
|
||||
style={{ width: '800px', height: '600px', display: 'flex', overflow: 'hidden' }}
|
||||
>
|
||||
<div className="flex flex-col flex-1 h-full overflow-hidden relative">
|
||||
<VideoPlayer
|
||||
key={playerKey}
|
||||
data={harnessAsset}
|
||||
playerRef={playerRef}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Comment controls: kept outside the player box so they cannot affect its
|
||||
layout / ResizeObserver behaviour. */}
|
||||
<div data-testid="comment-panel">
|
||||
<input ref={seekInputRef} data-testid="seek-frame-input" type="number" />
|
||||
<button data-testid="seek-frame-go" onClick={handleSeekToFrame}>
|
||||
Seek to frame
|
||||
</button>
|
||||
<button data-testid="create-comment" onClick={handleCreateComment}>
|
||||
Create comment
|
||||
</button>
|
||||
<button data-testid="reload-user-b" onClick={handleReloadAsUserB}>
|
||||
Reload as user B
|
||||
</button>
|
||||
<ul data-testid="comment-list">
|
||||
{comments.map((comment, index) => (
|
||||
<li
|
||||
key={comment.id}
|
||||
data-testid="comment-item"
|
||||
data-comment-index={index}
|
||||
data-comment-frame={comment.frame}
|
||||
data-comment-second={comment.second}
|
||||
onClick={() => handleCommentClick(comment.second)}
|
||||
>
|
||||
Frame {comment.frame}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const rootElement = document.getElementById('root')
|
||||
if (!rootElement) {
|
||||
throw new Error('Harness root element not found')
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(rootElement).render(<Harness />)
|
||||
@@ -0,0 +1,38 @@
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import index from './index.html'
|
||||
|
||||
/**
|
||||
* Backend-free harness server for the Playwright e2e suite.
|
||||
*
|
||||
* Uses Bun's native HTML bundler (the same path the real app uses via
|
||||
* `Bun.serve({ routes })` in apps/web) so the test toolchain matches the
|
||||
* project's Bun-based dev/prod serving. Tailwind is applied through the
|
||||
* `bun-plugin-tailwind` entry configured in the repo's bunfig.toml
|
||||
* ([serve.static]). It serves:
|
||||
* - the harness page (index.html -> main.tsx, bundled on the fly), and
|
||||
* - the committed fixture video from ../fixtures at the site root.
|
||||
*/
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fixturesDir = join(here, '..', 'fixtures')
|
||||
|
||||
const port = process.env.HARNESS_PORT ? Number(process.env.HARNESS_PORT) : 5199
|
||||
|
||||
const server = Bun.serve({
|
||||
port,
|
||||
development: true,
|
||||
routes: {
|
||||
'/sample.mp4': () =>
|
||||
new Response(Bun.file(join(fixturesDir, 'sample.mp4')), {
|
||||
headers: { 'Content-Type': 'video/mp4' },
|
||||
}),
|
||||
'/sample-long-audio.mp4': () =>
|
||||
new Response(Bun.file(join(fixturesDir, 'sample-long-audio.mp4')), {
|
||||
headers: { 'Content-Type': 'video/mp4' },
|
||||
}),
|
||||
'/': index,
|
||||
'/*': index,
|
||||
},
|
||||
})
|
||||
|
||||
console.log(`🎬 Video player harness running at ${server.url}`)
|
||||
@@ -0,0 +1,216 @@
|
||||
import type { Locator, Page } from '@playwright/test'
|
||||
import { SAMPLE_FRAME_RATE, SAMPLE_TOTAL_FRAMES } from '../harness/fixture'
|
||||
|
||||
const VIDEO_SELECTOR = '[data-testid="video-area"] video'
|
||||
|
||||
/**
|
||||
* Snapshot of the player's synchronized state, read from the two independent
|
||||
* surfaces that must stay frame-locked after a seek:
|
||||
* - the native <video> element (video.js engine / media clock),
|
||||
* - the numeric frame readout (derived from useFramePlayer's currentFrame).
|
||||
*/
|
||||
export interface CommentSeekSnapshot {
|
||||
paused: boolean
|
||||
currentTime: number
|
||||
/** Frame index implied by the native media clock: floor(t * fps + 0.45). */
|
||||
nativeFrame: number
|
||||
/** Frame index shown in the "N / M fr" readout. */
|
||||
readoutFrame: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Page object for the comment-seek scenario. It drives the extended video-player
|
||||
* harness that reproduces the app's real comment↔player wiring: capturing a
|
||||
* comment's `second` from `onTimeUpdate`, seeking on comment click via
|
||||
* `player.currentTime(second)`, and remounting the player to simulate a second
|
||||
* user opening the page.
|
||||
*/
|
||||
export class CommentSeekPage {
|
||||
readonly page: Page
|
||||
readonly video: Locator
|
||||
readonly timeReadout: Locator
|
||||
readonly seekFrameInput: Locator
|
||||
readonly seekFrameGo: Locator
|
||||
readonly createComment: Locator
|
||||
readonly reloadUserB: Locator
|
||||
readonly commentItems: Locator
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page
|
||||
this.video = page.locator(VIDEO_SELECTOR).first()
|
||||
this.timeReadout = page.getByTestId('time-readout')
|
||||
this.seekFrameInput = page.getByTestId('seek-frame-input')
|
||||
this.seekFrameGo = page.getByTestId('seek-frame-go')
|
||||
this.createComment = page.getByTestId('create-comment')
|
||||
this.reloadUserB = page.getByTestId('reload-user-b')
|
||||
this.commentItems = page.getByTestId('comment-item')
|
||||
}
|
||||
|
||||
async goto(): Promise<void> {
|
||||
await this.page.goto('/')
|
||||
await this.waitUntilReady()
|
||||
}
|
||||
|
||||
/** Wait until the video.js engine has metadata and a usable frame readout. */
|
||||
async waitUntilReady(): Promise<void> {
|
||||
await this.video.waitFor({ state: 'attached' })
|
||||
await this.page.waitForFunction(
|
||||
(selector) => {
|
||||
const el = document.querySelector(selector) as HTMLVideoElement | null
|
||||
return !!el && el.readyState >= 1 /* HAVE_METADATA */ && Number.isFinite(el.duration)
|
||||
},
|
||||
VIDEO_SELECTOR,
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
await this.page.waitForFunction(
|
||||
(selector) => /\d+\s*\/\s*\d+\s*fr/.test(document.querySelector(selector)?.textContent ?? ''),
|
||||
'[data-testid="time-readout"]',
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The fixture has no audio track, but WebKit headless can refuse to start
|
||||
* playback for a potentially-audible clip without an explicit muted flag. We
|
||||
* never play here, but mute defensively to keep engine behaviour consistent.
|
||||
*/
|
||||
async muteNativeVideo(): Promise<void> {
|
||||
await this.video.evaluate((el: HTMLVideoElement) => {
|
||||
el.muted = true
|
||||
})
|
||||
}
|
||||
|
||||
async isPaused(): Promise<boolean> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => el.paused)
|
||||
}
|
||||
|
||||
async currentTime(): Promise<number> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => el.currentTime)
|
||||
}
|
||||
|
||||
private async readoutFrame(): Promise<number> {
|
||||
const text = (await this.timeReadout.textContent()) ?? ''
|
||||
const match = text.match(/(\d+)\s*\/\s*\d+\s*fr/)
|
||||
return match ? Number.parseInt(match[1], 10) : Number.NaN
|
||||
}
|
||||
|
||||
/** Read a coherent snapshot of the native clock and the frame readout. */
|
||||
async snapshot(): Promise<CommentSeekSnapshot> {
|
||||
const [native, readoutFrame] = await Promise.all([
|
||||
this.video.evaluate((el: HTMLVideoElement, fps: number) => {
|
||||
return {
|
||||
paused: el.paused,
|
||||
currentTime: el.currentTime,
|
||||
nativeFrame: Math.floor(el.currentTime * fps + 0.45),
|
||||
}
|
||||
}, SAMPLE_FRAME_RATE),
|
||||
this.readoutFrame(),
|
||||
])
|
||||
|
||||
return {
|
||||
paused: native.paused,
|
||||
currentTime: native.currentTime,
|
||||
nativeFrame: native.nativeFrame,
|
||||
readoutFrame,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministically position the player on an exact frame (simulating user A
|
||||
* scrubbing there) and wait until it has fully settled: paused, with the
|
||||
* native clock and the readout both agreeing on the target frame.
|
||||
*/
|
||||
async seekToFrame(frame: number): Promise<void> {
|
||||
await this.seekFrameInput.fill(String(frame))
|
||||
await this.seekFrameGo.click()
|
||||
await this.waitUntilSettledOn(frame)
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait until the player has settled to a stable, paused frame whose native
|
||||
* clock and readout both equal `frame`.
|
||||
*
|
||||
* Ordering matters:
|
||||
* 1. First wait for the player to actually *reach* the target frame. This
|
||||
* uses a synchronous predicate polled at rAF rate — no async work inside
|
||||
* the browser evaluation, so executions never overlap.
|
||||
* 2. Only then wait for `currentTime` to stop changing (any post-seek nudge
|
||||
* to the frame center has fully applied). This runs as a sequential loop
|
||||
* in the Node context, so there is likewise no overlapping polling.
|
||||
*
|
||||
* Doing arrival first avoids the race where `currentTime` looks momentarily
|
||||
* stable before the seek has registered in the media engine.
|
||||
*/
|
||||
async waitUntilSettledOn(frame: number): Promise<void> {
|
||||
await this.waitForFrame(frame)
|
||||
await this.waitForStableCurrentTime()
|
||||
}
|
||||
|
||||
/** Wait until the native clock and readout both report `frame` while paused. */
|
||||
private async waitForFrame(frame: number): Promise<void> {
|
||||
await this.page.waitForFunction(
|
||||
({ selector, fps, target }) => {
|
||||
const el = document.querySelector(selector) as HTMLVideoElement | null
|
||||
if (!el || !el.paused) return false
|
||||
const nativeFrame = Math.floor(el.currentTime * fps + 0.45)
|
||||
const readoutEl = document.querySelector('[data-testid="time-readout"]')
|
||||
const match = (readoutEl?.textContent ?? '').match(/(\d+)\s*\/\s*\d+\s*fr/)
|
||||
const readoutFrame = match ? Number.parseInt(match[1], 10) : Number.NaN
|
||||
return nativeFrame === target && readoutFrame === target
|
||||
},
|
||||
{ selector: VIDEO_SELECTOR, fps: SAMPLE_FRAME_RATE, target: frame },
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait until `currentTime` stops changing between consecutive reads, driven
|
||||
* from Node so browser evaluations are strictly sequential (never overlapping).
|
||||
*/
|
||||
private async waitForStableCurrentTime(): Promise<void> {
|
||||
const deadline = Date.now() + 5_000
|
||||
let previous = await this.currentTime()
|
||||
while (Date.now() < deadline) {
|
||||
await this.page.waitForTimeout(80)
|
||||
const current = await this.currentTime()
|
||||
if (Math.abs(current - previous) < 1e-3) return
|
||||
previous = current
|
||||
}
|
||||
throw new Error('Timed out waiting for currentTime to stabilize')
|
||||
}
|
||||
|
||||
async clickCreateComment(): Promise<void> {
|
||||
const before = await this.commentItems.count()
|
||||
await this.createComment.click()
|
||||
await this.page.waitForFunction(
|
||||
(expected) => document.querySelectorAll('[data-testid="comment-item"]').length === expected,
|
||||
before + 1,
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
}
|
||||
|
||||
async commentCount(): Promise<number> {
|
||||
return this.commentItems.count()
|
||||
}
|
||||
|
||||
/** The derived frame indices shown on each comment, in list order. */
|
||||
async commentFrames(): Promise<number[]> {
|
||||
const values = await this.commentItems.evaluateAll((nodes) =>
|
||||
nodes.map((n) => Number.parseInt(n.getAttribute('data-comment-frame') ?? '', 10)),
|
||||
)
|
||||
return values
|
||||
}
|
||||
|
||||
clickCommentByIndex(index: number): Promise<void> {
|
||||
return this.commentItems.nth(index).click()
|
||||
}
|
||||
|
||||
/** Simulate a second user opening the page: remount the player at frame 0. */
|
||||
async reloadAsUserB(): Promise<void> {
|
||||
await this.reloadUserB.click()
|
||||
await this.waitUntilReady()
|
||||
}
|
||||
}
|
||||
|
||||
export const FRAME_RATE = SAMPLE_FRAME_RATE
|
||||
export const TOTAL_FRAMES = SAMPLE_TOTAL_FRAMES
|
||||
@@ -0,0 +1,186 @@
|
||||
import type { Locator, Page } from '@playwright/test'
|
||||
import { SAMPLE_FRAME_RATE, SAMPLE_TOTAL_FRAMES } from '../harness/fixture'
|
||||
|
||||
const VIDEO_SELECTOR = '[data-testid="video-area"] video'
|
||||
|
||||
/**
|
||||
* Snapshot of the player's synchronized state, read from the three independent
|
||||
* surfaces that must stay frame-locked:
|
||||
* - the native <video> element (video.js engine / media clock),
|
||||
* - the seekbar fill (derived from useFramePlayer's currentFrame),
|
||||
* - the numeric frame readout (also derived from currentFrame).
|
||||
*/
|
||||
export interface PlayerSnapshot {
|
||||
paused: boolean
|
||||
ended: boolean
|
||||
currentTime: number
|
||||
/** Frame index implied by the native media clock: floor(t * fps + 0.45). */
|
||||
nativeFrame: number
|
||||
/** Frame index shown in the "N / M fr" readout. */
|
||||
readoutFrame: number
|
||||
/** Seekbar fill width as a fraction (0..1) of the track width. */
|
||||
seekbarFraction: number
|
||||
}
|
||||
|
||||
export class VideoPlayerPage {
|
||||
readonly page: Page
|
||||
readonly stage: Locator
|
||||
readonly videoArea: Locator
|
||||
readonly playToggle: Locator
|
||||
readonly video: Locator
|
||||
readonly seekbar: Locator
|
||||
readonly seekbarFill: Locator
|
||||
readonly timeReadout: Locator
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page
|
||||
this.stage = page.getByTestId('harness-stage')
|
||||
this.videoArea = page.getByTestId('video-area')
|
||||
this.playToggle = page.getByTestId('play-toggle')
|
||||
this.video = page.locator(VIDEO_SELECTOR).first()
|
||||
this.seekbar = page.getByTestId('seekbar')
|
||||
this.seekbarFill = page.getByTestId('seekbar-fill')
|
||||
this.timeReadout = page.getByTestId('time-readout')
|
||||
}
|
||||
|
||||
async goto(): Promise<void> {
|
||||
await this.page.goto('/')
|
||||
await this.waitUntilReady()
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to the harness with a specific fixture variant (see the harness
|
||||
* `resolveAsset`), e.g. `'container-longer'` for the asset whose container
|
||||
* duration exceeds its real video stream.
|
||||
*/
|
||||
async gotoVariant(variant: string): Promise<void> {
|
||||
await this.page.goto(`/?variant=${encodeURIComponent(variant)}`)
|
||||
await this.waitUntilReady()
|
||||
}
|
||||
|
||||
/** Wait until the video.js engine has metadata and a usable frame readout. */
|
||||
async waitUntilReady(): Promise<void> {
|
||||
await this.video.waitFor({ state: 'attached' })
|
||||
await this.page.waitForFunction(
|
||||
(selector) => {
|
||||
const el = document.querySelector(selector) as HTMLVideoElement | null
|
||||
return !!el && el.readyState >= 1 /* HAVE_METADATA */ && Number.isFinite(el.duration)
|
||||
},
|
||||
VIDEO_SELECTOR,
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
// The readout renders "N / M fr" once currentFrame state is wired up.
|
||||
await this.page.waitForFunction(
|
||||
(selector) => /\d+\s*\/\s*\d+\s*fr/.test(document.querySelector(selector)?.textContent ?? ''),
|
||||
'[data-testid="time-readout"]',
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Some engines (notably WebKit headless) refuse to start playback for a clip
|
||||
* that could produce sound without an explicit muted flag. The fixture has no
|
||||
* audio track, but we mute defensively so play() resolves consistently.
|
||||
*/
|
||||
async muteNativeVideo(): Promise<void> {
|
||||
await this.video.evaluate((el: HTMLVideoElement) => {
|
||||
el.muted = true
|
||||
})
|
||||
}
|
||||
|
||||
async isPaused(): Promise<boolean> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => el.paused)
|
||||
}
|
||||
|
||||
async currentTime(): Promise<number> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => el.currentTime)
|
||||
}
|
||||
|
||||
private async readoutFrame(): Promise<number> {
|
||||
const text = (await this.timeReadout.textContent()) ?? ''
|
||||
const match = text.match(/(\d+)\s*\/\s*\d+\s*fr/)
|
||||
return match ? Number.parseInt(match[1], 10) : Number.NaN
|
||||
}
|
||||
|
||||
/** The total frame index shown as "M" in the "N / M fr" readout. */
|
||||
async readoutTotalFrame(): Promise<number> {
|
||||
const text = (await this.timeReadout.textContent()) ?? ''
|
||||
const match = text.match(/\d+\s*\/\s*(\d+)\s*fr/)
|
||||
return match ? Number.parseInt(match[1], 10) : Number.NaN
|
||||
}
|
||||
|
||||
private async seekbarFraction(): Promise<number> {
|
||||
const track = await this.seekbar.boundingBox()
|
||||
const fill = await this.seekbarFill.boundingBox()
|
||||
if (!track || !fill || track.width === 0) return 0
|
||||
return fill.width / track.width
|
||||
}
|
||||
|
||||
/** Read a coherent snapshot of all three synchronized surfaces. */
|
||||
async snapshot(): Promise<PlayerSnapshot> {
|
||||
const [native, readoutFrame, seekbarFraction] = await Promise.all([
|
||||
this.video.evaluate((el: HTMLVideoElement, fps: number) => {
|
||||
return {
|
||||
paused: el.paused,
|
||||
ended: el.ended,
|
||||
currentTime: el.currentTime,
|
||||
nativeFrame: Math.floor(el.currentTime * fps + 0.45),
|
||||
}
|
||||
}, SAMPLE_FRAME_RATE),
|
||||
this.readoutFrame(),
|
||||
this.seekbarFraction(),
|
||||
])
|
||||
|
||||
return {
|
||||
paused: native.paused,
|
||||
ended: native.ended,
|
||||
currentTime: native.currentTime,
|
||||
nativeFrame: native.nativeFrame,
|
||||
readoutFrame,
|
||||
seekbarFraction,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Jump the native media clock to a given frame's center time via a real
|
||||
* external seek (sets `video.currentTime`, which fires `seeked` and drives
|
||||
* useFramePlayer). Used to land near the end of the clip so the "play to end"
|
||||
* wait is short and deterministic instead of streaming the whole fixture.
|
||||
*/
|
||||
async seekToFrame(frame: number): Promise<void> {
|
||||
await this.video.evaluate(
|
||||
(el: HTMLVideoElement, args: { frame: number; fps: number }) => {
|
||||
const frameDuration = 1 / args.fps
|
||||
el.currentTime = args.frame * frameDuration + frameDuration / 2
|
||||
},
|
||||
{ frame, fps: SAMPLE_FRAME_RATE },
|
||||
)
|
||||
}
|
||||
|
||||
/** Wait until the native <video> element reports that playback has ended. */
|
||||
async waitForEnded(timeout = 10_000): Promise<void> {
|
||||
await this.video.evaluate(
|
||||
(el: HTMLVideoElement) =>
|
||||
el.ended
|
||||
? Promise.resolve()
|
||||
: new Promise<void>((resolve) => {
|
||||
el.addEventListener('ended', () => resolve(), { once: true })
|
||||
}),
|
||||
undefined,
|
||||
{ timeout },
|
||||
)
|
||||
}
|
||||
|
||||
clickPlayToggle(): Promise<void> {
|
||||
return this.playToggle.click()
|
||||
}
|
||||
|
||||
clickVideoArea(): Promise<void> {
|
||||
// The drawing-canvas overlay is pointer-events:none when not drawing, so the
|
||||
// click lands on the video-area div and triggers togglePlay.
|
||||
return this.videoArea.click({ position: { x: 20, y: 20 } })
|
||||
}
|
||||
}
|
||||
|
||||
export const FRAME_RATE = SAMPLE_FRAME_RATE
|
||||
export const TOTAL_FRAMES = SAMPLE_TOTAL_FRAMES
|
||||
@@ -0,0 +1,110 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { CommentSeekPage, TOTAL_FRAMES } from '../pages/comment-seek.page'
|
||||
|
||||
/**
|
||||
* Frame-accurate comment seek roundtrip.
|
||||
*
|
||||
* Simulates two users against the *real* comment↔player wiring:
|
||||
* 1. User A scrubs to a frame, pauses, and creates a comment. The app stores
|
||||
* the comment's timestamp as `second = currentFrame / fps` (a float in
|
||||
* seconds — never a frame integer), captured via the player's real
|
||||
* `onTimeUpdate` prop.
|
||||
* 2. User B opens the page fresh (the player remounts at frame 0) and clicks
|
||||
* the comment, which runs the app's real seek `player.currentTime(second)`.
|
||||
* useFramePlayer then recomputes the frame from the media clock as
|
||||
* `floor(second * fps + 0.45)`.
|
||||
*
|
||||
* The invariant under test is that this seconds-based roundtrip is loss-free:
|
||||
* frameA -> second = frameA/fps -> (stored) -> seek(second)
|
||||
* -> floor(second*fps + 0.45) == frameA
|
||||
*
|
||||
* We exercise it on 5 distinct frames chosen randomly on every run, so any
|
||||
* off-by-one in the conversion surfaces across runs and is caught deterministically
|
||||
* for the sampled frames within a run.
|
||||
*/
|
||||
|
||||
const COMMENT_COUNT = 5
|
||||
|
||||
/**
|
||||
* Pick `count` distinct random frame indices in a safe range. We avoid frame 0
|
||||
* (the player's post-reload starting state, so "seeked back" is a real change)
|
||||
* and the final frame (to dodge the native `ended` edge case).
|
||||
*/
|
||||
function pickRandomFrames(count: number): number[] {
|
||||
const min = 1
|
||||
const max = TOTAL_FRAMES - 2
|
||||
const chosen = new Set<number>()
|
||||
while (chosen.size < count) {
|
||||
chosen.add(min + Math.floor(Math.random() * (max - min + 1)))
|
||||
}
|
||||
return [...chosen].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Mock every backend call so this stays a pure frontend test. The harness never
|
||||
// hits the API, but this guarantees isolation regardless. Patterns are anchored
|
||||
// to the origin root so they don't match Vite-served source modules.
|
||||
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
|
||||
)
|
||||
})
|
||||
|
||||
test.describe('video player comment seek roundtrip', () => {
|
||||
test('user A comments on 5 random frames, user B seeks back to each', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const frames = pickRandomFrames(COMMENT_COUNT)
|
||||
// Record the sampled frames so a failing run is reproducible.
|
||||
testInfo.annotations.push({ type: 'random-frames', description: frames.join(', ') })
|
||||
|
||||
const cs = new CommentSeekPage(page)
|
||||
await cs.goto()
|
||||
await cs.muteNativeVideo()
|
||||
|
||||
// Starts paused at frame 0.
|
||||
const initial = await cs.snapshot()
|
||||
expect(initial.paused).toBe(true)
|
||||
expect(initial.readoutFrame).toBe(0)
|
||||
|
||||
// -- Phase A: user A authors a comment on each random frame. --
|
||||
for (const frame of frames) {
|
||||
await cs.seekToFrame(frame)
|
||||
|
||||
// The frame user A is actually looking at (readout and native clock agree).
|
||||
const authored = await cs.snapshot()
|
||||
expect(authored.paused).toBe(true)
|
||||
expect(authored.readoutFrame).toBe(frame)
|
||||
expect(authored.nativeFrame).toBe(frame)
|
||||
|
||||
await cs.clickCreateComment()
|
||||
|
||||
// Goal 1: the comment is stored at exactly the frame user A saw.
|
||||
const commentFrames = await cs.commentFrames()
|
||||
expect(commentFrames[commentFrames.length - 1]).toBe(frame)
|
||||
}
|
||||
|
||||
// All five comments exist and correspond, in order, to the authored frames.
|
||||
expect(await cs.commentCount()).toBe(COMMENT_COUNT)
|
||||
expect(await cs.commentFrames()).toEqual(frames)
|
||||
|
||||
// -- Phase B: a second user opens the page fresh (player remounts at 0). --
|
||||
await cs.reloadAsUserB()
|
||||
await cs.muteNativeVideo()
|
||||
const afterReload = await cs.snapshot()
|
||||
expect(afterReload.readoutFrame).toBe(0)
|
||||
|
||||
// Clicking each comment lands the player back on exactly user A's frame.
|
||||
const commentFrames = await cs.commentFrames()
|
||||
for (let index = 0; index < commentFrames.length; index++) {
|
||||
const frame = commentFrames[index]
|
||||
await cs.clickCommentByIndex(index)
|
||||
await cs.waitUntilSettledOn(frame)
|
||||
|
||||
// Goal 2: user B sees exactly the frame user A commented on.
|
||||
const seen = await cs.snapshot()
|
||||
expect(seen.paused).toBe(true)
|
||||
expect(seen.readoutFrame).toBe(frame)
|
||||
expect(seen.nativeFrame).toBe(frame)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { VideoPlayerPage } from '../pages/video-player.page'
|
||||
import { REAL_LAST_FRAME, SAMPLE_TOTAL_FRAMES } from '../harness/fixture'
|
||||
|
||||
/**
|
||||
* Regression reproduction for the frame-count inflation bug.
|
||||
*
|
||||
* When an asset's container/format duration is slightly LONGER than its actual
|
||||
* video stream (common: audio padding / container overhead), the player derived
|
||||
* `totalFrames` from the container duration (`round(duration * fps)`) instead of
|
||||
* the accurate stream frame count (`metadata.totalFrames` == ffprobe nb_frames).
|
||||
* This invents phantom trailing frames that do not exist in the stream, so:
|
||||
*
|
||||
* - normal playback stops N frames SHORT of the displayed maximum (it can only
|
||||
* reach the last real frame), and
|
||||
* - frame-stepping can walk PAST the last real frame onto phantom frames.
|
||||
*
|
||||
* The `container-longer` fixture reports duration 5.075s while the real backing
|
||||
* video is exactly 150 frames @ 30fps (5.0s stream). The buggy heuristic derives
|
||||
* round(5.075*30) = 152 frames, so the readout shows "/ 151 fr" even though the
|
||||
* last real (and last reachable) frame is 149.
|
||||
*
|
||||
* Correct behaviour (asserted below): playing to the natural end must land on
|
||||
* the last displayed frame — i.e. the readout's current frame equals the
|
||||
* readout's total frame, and that total equals the real last frame of the
|
||||
* stream. This spec FAILS against the buggy build and PASSES once totalFrames is
|
||||
* derived from the accurate stream frame count.
|
||||
*/
|
||||
|
||||
// Land a few frames from the real end so playing out the tail (and firing the
|
||||
// native `ended` event) is fast and deterministic.
|
||||
const NEAR_END_FRAME = SAMPLE_TOTAL_FRAMES - 3
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Mock every backend call so this stays a pure frontend test (mirrors the
|
||||
// other player specs). Patterns are anchored to the origin root so they only
|
||||
// match real backend requests, not Vite-served source modules.
|
||||
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
|
||||
)
|
||||
})
|
||||
|
||||
test.describe('video player container-duration mismatch', () => {
|
||||
test('plays to the last real frame instead of stopping short on phantom frames', async ({
|
||||
page,
|
||||
}) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.gotoVariant('container-longer')
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
// Drive the real player to its natural end.
|
||||
await vp.seekToFrame(NEAR_END_FRAME)
|
||||
await vp.clickPlayToggle()
|
||||
await vp.waitForEnded()
|
||||
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true)
|
||||
|
||||
// Let the end-of-playback frame settle (currentTime stops moving).
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const a = await vp.currentTime()
|
||||
await vp.page.waitForTimeout(80)
|
||||
const b = await vp.currentTime()
|
||||
return Math.abs(b - a) < 1e-3
|
||||
},
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
const totalFrame = await vp.readoutTotalFrame()
|
||||
|
||||
// The displayed total must reflect the real stream (last real frame = 149),
|
||||
// not the inflated container-derived count (151). This fails under the bug.
|
||||
expect(totalFrame).toBe(REAL_LAST_FRAME)
|
||||
|
||||
// Core user-facing invariant: reaching the natural end lands on the last
|
||||
// displayed frame — the playhead is not stranded short of the maximum.
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBe(totalFrame)
|
||||
|
||||
// The seekbar is visually full at the end (within tolerance).
|
||||
const snap = await vp.snapshot()
|
||||
expect(snap.seekbarFraction).toBeGreaterThan(0.98)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { VideoPlayerPage } from '../pages/video-player.page'
|
||||
import { REAL_LAST_FRAME, SAMPLE_TOTAL_FRAMES } from '../harness/fixture'
|
||||
|
||||
/**
|
||||
* Companion to container-duration-mismatch.spec.ts, covering the LARGE-gap
|
||||
* ("videoB") case: the audio track is much longer than the video track (here a
|
||||
* 150-frame / 5.0s video with a 6.5s audio tail — a 1.5s tail, far above the
|
||||
* ~100ms playback stall threshold).
|
||||
*
|
||||
* Because the tail is long enough for the RAF fallback to activate and drive the
|
||||
* playhead through the audio-only region, the timeline is (correctly) derived
|
||||
* from the container duration: round(6.5 * 30) = 195 frames, readout max 194.
|
||||
* Playing to the natural end must advance the playhead all the way to that
|
||||
* container-based maximum, and the readout must show "194 / 194".
|
||||
*
|
||||
* This behaviour is expected to hold BOTH before and after the frame-count fix
|
||||
* (the fix only changes the small-gap case), so this spec passes on the current
|
||||
* code and guards against regressing the large-gap case.
|
||||
*/
|
||||
|
||||
// Land a couple frames before the VIDEO track ends, so playback streams through
|
||||
// the video tail and then the long audio-only tail to the natural end.
|
||||
const NEAR_VIDEO_END_FRAME = SAMPLE_TOTAL_FRAMES - 3
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
|
||||
)
|
||||
})
|
||||
|
||||
test.describe('video player long audio tail (large gap)', () => {
|
||||
test('playhead traverses the audio tail to the container-based maximum', async ({ page }) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.gotoVariant('long-audio')
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
// The displayed total reflects the container (audio-extended) duration, not
|
||||
// the shorter video track: it is well beyond the last real video frame.
|
||||
const totalFrame = await vp.readoutTotalFrame()
|
||||
expect(totalFrame).toBeGreaterThan(REAL_LAST_FRAME)
|
||||
|
||||
// Drive the player from just before the video track ends, out through the
|
||||
// audio-only tail, to the natural end of the media.
|
||||
await vp.seekToFrame(NEAR_VIDEO_END_FRAME)
|
||||
await vp.clickPlayToggle()
|
||||
await vp.waitForEnded()
|
||||
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true)
|
||||
|
||||
// Let the end-of-playback frame settle.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const a = await vp.currentTime()
|
||||
await vp.page.waitForTimeout(80)
|
||||
const b = await vp.currentTime()
|
||||
return Math.abs(b - a) < 1e-3
|
||||
},
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
// The playhead advanced past the last real video frame into the audio tail...
|
||||
const snap = await vp.snapshot()
|
||||
expect(snap.readoutFrame).toBeGreaterThan(REAL_LAST_FRAME)
|
||||
|
||||
// ...and reached the container-based maximum at the natural end.
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBe(totalFrame)
|
||||
|
||||
// The seekbar is visually full at the end.
|
||||
const finalSnap = await vp.snapshot()
|
||||
expect(finalSnap.seekbarFraction).toBeGreaterThan(0.98)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,141 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { FRAME_RATE, TOTAL_FRAMES, VideoPlayerPage } from '../pages/video-player.page'
|
||||
|
||||
/**
|
||||
* Pure UI integration test for the frame-accurate video player.
|
||||
*
|
||||
* The player keeps three surfaces in lockstep off a single `currentFrame` state:
|
||||
* 1. the native <video> element (video.js media clock),
|
||||
* 2. the seekbar fill, and
|
||||
* 3. the numeric frame readout.
|
||||
*
|
||||
* On pause, useFramePlayer snaps the native clock to the paused frame's center
|
||||
* time, so after a short settle the native frame, the readout frame and the
|
||||
* seekbar fill must all agree. We assert that invariant here rather than trusting
|
||||
* any single surface.
|
||||
*/
|
||||
|
||||
const SEEKBAR_TOLERANCE = 0.01 // fraction of the track (~1%), covers sub-pixel + thumb rounding
|
||||
const HALF_FRAME_SECONDS = 1 / (2 * FRAME_RATE)
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Mock every backend call so this stays a pure frontend test. The player never
|
||||
// hits the API during play/pause, but this guarantees isolation regardless.
|
||||
//
|
||||
// NOTE: the patterns are anchored to the origin root (/api/, /files/) so they
|
||||
// only match real backend requests and NOT Vite-served source modules whose
|
||||
// paths happen to contain those segments (e.g. /packages/webui/api/client.ts).
|
||||
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* Wait until the player has settled to a stable, paused, fully-synchronized
|
||||
* frame, then assert the native clock, the readout and the seekbar all agree.
|
||||
*/
|
||||
async function expectPausedAndSynchronized(vp: VideoPlayerPage): Promise<void> {
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true)
|
||||
|
||||
// Wait for the pause snap + external-seek nudge to fully settle: currentTime
|
||||
// stops changing between consecutive reads.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const a = await vp.currentTime()
|
||||
await vp.page.waitForTimeout(80)
|
||||
const b = await vp.currentTime()
|
||||
return Math.abs(b - a) < 1e-3
|
||||
},
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
// The UI frame and the native-clock frame converge on the same integer.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const snap = await vp.snapshot()
|
||||
return snap.readoutFrame === snap.nativeFrame
|
||||
},
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
const snap = await vp.snapshot()
|
||||
|
||||
expect(snap.paused).toBe(true)
|
||||
|
||||
// Readout <-> native media clock.
|
||||
expect(snap.readoutFrame).toBe(snap.nativeFrame)
|
||||
|
||||
// Seekbar fill <-> frame index.
|
||||
expect(Math.abs(snap.seekbarFraction - snap.nativeFrame / TOTAL_FRAMES)).toBeLessThan(
|
||||
SEEKBAR_TOLERANCE,
|
||||
)
|
||||
|
||||
// Native clock is snapped to the paused frame's center time.
|
||||
const frameCenter = snap.nativeFrame / FRAME_RATE + HALF_FRAME_SECONDS
|
||||
expect(Math.abs(snap.currentTime - frameCenter)).toBeLessThan(HALF_FRAME_SECONDS + 1e-6)
|
||||
}
|
||||
|
||||
/** Assert the player is genuinely stopped: the frame does not advance over time. */
|
||||
async function expectPlayheadStopped(vp: VideoPlayerPage): Promise<void> {
|
||||
const first = await vp.snapshot()
|
||||
await vp.page.waitForTimeout(300)
|
||||
const second = await vp.snapshot()
|
||||
// The integer frame is the robust "not advancing" signal.
|
||||
expect(second.readoutFrame).toBe(first.readoutFrame)
|
||||
// currentTime must not advance meaningfully. A playing video would move ~0.3s
|
||||
// in 300ms; a stopped one moves less than a frame (browser seeks land *near*,
|
||||
// not exactly on, the requested frame-center, and the pause snap may still be
|
||||
// settling), so half a frame cleanly separates stopped from playing.
|
||||
expect(Math.abs(second.currentTime - first.currentTime)).toBeLessThan(HALF_FRAME_SECONDS)
|
||||
}
|
||||
|
||||
test.describe('video player play/pause', () => {
|
||||
test('toggles via the play/pause control', async ({ page }) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.goto()
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
// Starts paused at frame 0.
|
||||
const initial = await vp.snapshot()
|
||||
expect(initial.paused).toBe(true)
|
||||
expect(initial.readoutFrame).toBe(0)
|
||||
|
||||
// Play via the control -> playback starts and the readout advances.
|
||||
await vp.clickPlayToggle()
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(false)
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBeGreaterThan(initial.readoutFrame)
|
||||
|
||||
// Pause via the control -> everything re-synchronizes and stays put.
|
||||
await vp.clickPlayToggle()
|
||||
await expectPausedAndSynchronized(vp)
|
||||
await expectPlayheadStopped(vp)
|
||||
})
|
||||
|
||||
test('toggles via clicking the video area', async ({ page }) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.goto()
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
const initial = await vp.snapshot()
|
||||
expect(initial.paused).toBe(true)
|
||||
expect(initial.readoutFrame).toBe(0)
|
||||
|
||||
// Click the video surface to play.
|
||||
await vp.clickVideoArea()
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(false)
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBeGreaterThan(initial.readoutFrame)
|
||||
|
||||
// Click again to pause -> native clock, readout and seekbar agree.
|
||||
await vp.clickVideoArea()
|
||||
await expectPausedAndSynchronized(vp)
|
||||
await expectPlayheadStopped(vp)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { TOTAL_FRAMES, VideoPlayerPage } from '../pages/video-player.page'
|
||||
|
||||
/**
|
||||
* Pure UI integration test for restarting a finished video.
|
||||
*
|
||||
* When a clip plays to its end, `togglePlay` treats an ended player the same as
|
||||
* a paused one: `if (player.paused() || player.ended()) player.play()`. Calling
|
||||
* play() on an ended media element restarts it from the beginning. This spec
|
||||
* drives the *real* player to its end (by seeking near the tail, then playing
|
||||
* out the last few frames) and asserts that the two user-facing restart
|
||||
* triggers — the play/pause control and a click on the video area — both resume
|
||||
* playback from the start.
|
||||
*
|
||||
* To keep the test fast and deterministic we seek close to the end rather than
|
||||
* streaming the whole fixture; the restart behaviour under test is independent
|
||||
* of how the player reached the `ended` state.
|
||||
*/
|
||||
|
||||
// Land a few frames from the end so playing out the tail (and firing `ended`)
|
||||
// takes a fraction of a second instead of the full clip duration.
|
||||
const NEAR_END_FRAME = TOTAL_FRAMES - 3
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Mock every backend call so this stays a pure frontend test (mirrors
|
||||
// play-pause.spec.ts). Patterns are anchored to the origin root so they only
|
||||
// match real backend requests, not Vite-served source modules.
|
||||
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
|
||||
)
|
||||
})
|
||||
|
||||
/** Drive the player to its natural end and assert it is stopped at the tail. */
|
||||
async function playToEnd(vp: VideoPlayerPage): Promise<void> {
|
||||
await vp.seekToFrame(NEAR_END_FRAME)
|
||||
await vp.clickPlayToggle()
|
||||
await vp.waitForEnded()
|
||||
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true)
|
||||
const ended = await vp.snapshot()
|
||||
expect(ended.ended).toBe(true)
|
||||
expect(ended.paused).toBe(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* After a restart trigger, assert the player leaves the ended state, resumes
|
||||
* playing, and the playhead jumps back to the start before advancing again.
|
||||
*/
|
||||
async function expectRestartedFromStart(vp: VideoPlayerPage): Promise<void> {
|
||||
// Leaves the ended state and resumes playback.
|
||||
await expect.poll(async () => (await vp.snapshot()).ended, { timeout: 5_000 }).toBe(false)
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(false)
|
||||
|
||||
// The playhead rewound to the start: it is now well before where the clip
|
||||
// ended (comfortably below the near-end frame it was stopped at).
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBeLessThan(NEAR_END_FRAME)
|
||||
|
||||
// ...and playback is genuinely progressing again from near the start.
|
||||
const first = await vp.snapshot()
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBeGreaterThan(first.readoutFrame)
|
||||
}
|
||||
|
||||
test.describe('video player restart on end', () => {
|
||||
test('restarts playback via the play/pause control after the video ends', async ({ page }) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.goto()
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
await playToEnd(vp)
|
||||
|
||||
// Restart trigger: the play/pause control.
|
||||
await vp.clickPlayToggle()
|
||||
await expectRestartedFromStart(vp)
|
||||
})
|
||||
|
||||
test('restarts playback by clicking the video area after the video ends', async ({ page }) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.goto()
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
await playToEnd(vp)
|
||||
|
||||
// Restart trigger: clicking the video surface.
|
||||
await vp.clickVideoArea()
|
||||
await expectRestartedFromStart(vp)
|
||||
})
|
||||
})
|
||||
@@ -433,6 +433,9 @@
|
||||
|
||||
"versions": "Versions",
|
||||
"manage_versions": "Manage versions...",
|
||||
"compare_versions": "Compare Versions",
|
||||
"exit_compare": "Exit compare",
|
||||
"switch_version": "Switch version",
|
||||
"show_left_sidebar": "Show Left Sidebar",
|
||||
"hide_left_sidebar": "Hide Left Sidebar",
|
||||
"show_right_sidebar": "Show Right Sidebar",
|
||||
|
||||
@@ -424,8 +424,8 @@
|
||||
"avatar_source": "头像来源",
|
||||
"saving": "保存中",
|
||||
|
||||
"auth_tagline": "一个工作区,管理所有创意资产。",
|
||||
"auth_description": "上传并索引您的文件,使用自定义元数据模式丰富它们,直接在媒体上绘制标注,并收集即时反馈——这一切都在一个为创作者打造的现代工作区中完成。",
|
||||
"auth_tagline": "一站式创意资产管理协作平台。",
|
||||
"auth_description": "上传您的创意资产,添加各种类型的自定义元数据,直接在图片或视频上绘制标注和添加评论,——这一切都在Shumai,一个为创作者打造的一站式平台上完成。",
|
||||
"auth_feature_uploads": "即时资产上传 & 高保真媒体播放器",
|
||||
"auth_feature_metadata": "自定义元数据模式 & 画布标注审阅",
|
||||
"auth_feature_teams": "无缝团队工作区 & 安全分享",
|
||||
@@ -433,6 +433,9 @@
|
||||
|
||||
"versions": "版本",
|
||||
"manage_versions": "管理版本...",
|
||||
"compare_versions": "对比版本",
|
||||
"exit_compare": "退出对比",
|
||||
"switch_version": "切换版本",
|
||||
"show_left_sidebar": "显示左侧边栏",
|
||||
"hide_left_sidebar": "隐藏左侧边栏",
|
||||
"show_right_sidebar": "显示右侧边栏",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./index.html",
|
||||
@@ -88,17 +88,13 @@
|
||||
"devDependencies": {
|
||||
"typescript": "6.0.3",
|
||||
"@tailwindcss/postcss": "4.3.0",
|
||||
"@tailwindcss/vite": "4.3.0",
|
||||
"@tanstack/router-cli": "1.167.13",
|
||||
"@tanstack/router-plugin": "1.168.14",
|
||||
"@types/react": "19.2.16",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@vitejs/plugin-react": "5.2.0",
|
||||
"autoprefixer": "10.5.0",
|
||||
"postcss": "8.5.15",
|
||||
"tailwindcss": "4.3.0",
|
||||
"tw-animate-css": "1.3.3",
|
||||
"vite": "7.3.5",
|
||||
"vite-tsconfig-paths": "6.1.1"
|
||||
"tw-animate-css": "1.3.3"
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -411,6 +411,9 @@ export * from "./auth_feature_teams.js";
|
||||
export * from "./auth_community_cta.js";
|
||||
export * from "./versions.js";
|
||||
export * from "./manage_versions.js";
|
||||
export * from "./compare_versions.js";
|
||||
export * from "./exit_compare.js";
|
||||
export * from "./switch_version.js";
|
||||
export * from "./show_left_sidebar.js";
|
||||
export * from "./hide_left_sidebar.js";
|
||||
export * from "./show_right_sidebar.js";
|
||||
|
||||
+3
@@ -413,6 +413,9 @@ export * from './auth_feature_teams.js'
|
||||
export * from './auth_community_cta.js'
|
||||
export * from './versions.js'
|
||||
export * from './manage_versions.js'
|
||||
export * from './compare_versions.js'
|
||||
export * from './exit_compare.js'
|
||||
export * from './switch_version.js'
|
||||
export * from './show_left_sidebar.js'
|
||||
export * from './hide_left_sidebar.js'
|
||||
export * from './show_right_sidebar.js'
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ const en_auth_description = /** @type {(inputs: Auth_DescriptionInputs) => Local
|
||||
};
|
||||
|
||||
const zh_auth_description = /** @type {(inputs: Auth_DescriptionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`上传并索引您的文件,使用自定义元数据模式丰富它们,直接在媒体上绘制标注,并收集即时反馈——这一切都在一个为创作者打造的现代工作区中完成。`)
|
||||
return /** @type {LocalizedString} */ (`上传您的创意资产,添加各种类型的自定义元数据,直接在图片或视频上绘制标注和添加评论,——这一切都在Shumai,一个为创作者打造的一站式平台上完成。`)
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ const en_auth_tagline = /** @type {(inputs: Auth_TaglineInputs) => LocalizedStri
|
||||
};
|
||||
|
||||
const zh_auth_tagline = /** @type {(inputs: Auth_TaglineInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`一个工作区,管理所有创意资产。`)
|
||||
return /** @type {LocalizedString} */ (`一站式创意资产管理协作平台。`)
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Compare Versions" |
|
||||
*
|
||||
* @param {Compare_VersionsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const compare_versions: ((inputs?: Compare_VersionsInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Compare_VersionsInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Compare_VersionsInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Compare_VersionsInputs */
|
||||
|
||||
const en_compare_versions = /** @type {(inputs: Compare_VersionsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Compare Versions`)
|
||||
};
|
||||
|
||||
const zh_compare_versions = /** @type {(inputs: Compare_VersionsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`对比版本`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Compare Versions" |
|
||||
*
|
||||
* @param {Compare_VersionsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const compare_versions = /** @type {((inputs?: Compare_VersionsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Compare_VersionsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_compare_versions(inputs)
|
||||
return zh_compare_versions(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Exit compare" |
|
||||
*
|
||||
* @param {Exit_CompareInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const exit_compare: ((inputs?: Exit_CompareInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Exit_CompareInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Exit_CompareInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Exit_CompareInputs */
|
||||
|
||||
const en_exit_compare = /** @type {(inputs: Exit_CompareInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Exit compare`)
|
||||
};
|
||||
|
||||
const zh_exit_compare = /** @type {(inputs: Exit_CompareInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`退出对比`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Exit compare" |
|
||||
*
|
||||
* @param {Exit_CompareInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const exit_compare = /** @type {((inputs?: Exit_CompareInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Exit_CompareInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_exit_compare(inputs)
|
||||
return zh_exit_compare(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Switch version" |
|
||||
*
|
||||
* @param {Switch_VersionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const switch_version: ((inputs?: Switch_VersionInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Switch_VersionInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Switch_VersionInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Switch_VersionInputs */
|
||||
|
||||
const en_switch_version = /** @type {(inputs: Switch_VersionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Switch version`)
|
||||
};
|
||||
|
||||
const zh_switch_version = /** @type {(inputs: Switch_VersionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`切换版本`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Switch version" |
|
||||
*
|
||||
* @param {Switch_VersionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const switch_version = /** @type {((inputs?: Switch_VersionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Switch_VersionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_switch_version(inputs)
|
||||
return zh_switch_version(inputs)
|
||||
});
|
||||
@@ -40,15 +40,10 @@ function RootComponent() {
|
||||
const { uploading } = useUploadStore()
|
||||
const pathname = useRouterState({ select: (s) => s.location.pathname })
|
||||
const navigate = useNavigate()
|
||||
const { teamId: storedTeamId, setTeamId } = useTeamContextStore()
|
||||
|
||||
const showSidebar = user && (pathname.startsWith('/teams/') || pathname.startsWith('/projects/'))
|
||||
|
||||
if (!showSidebar) {
|
||||
return <Outlet />
|
||||
}
|
||||
|
||||
const { teamId: storedTeamId, setTeamId } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
resolveTeamIdFromPath(pathname).then((resolvedTeamId) => {
|
||||
if (resolvedTeamId && resolvedTeamId !== storedTeamId) {
|
||||
@@ -70,6 +65,10 @@ function RootComponent() {
|
||||
enabled: !!storedTeamId,
|
||||
})
|
||||
|
||||
if (!showSidebar) {
|
||||
return <Outlet />
|
||||
}
|
||||
|
||||
const unreadCount = me?.unreadNotificationCount ?? 0
|
||||
const displayCount = unreadCount > 99 ? '99+' : unreadCount
|
||||
const badge =
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FileViewer } from '@/ui/components/file-viewer'
|
||||
import { CompareViewer } from '@/ui/components/compare/compare-viewer'
|
||||
import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
|
||||
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
|
||||
@@ -25,6 +27,10 @@ function FileViewPage() {
|
||||
const versionAssetId = search.version
|
||||
const startTime = search.start
|
||||
const activeFileId = versionAssetId || fileId
|
||||
const compareLeftId = search.cmpLeft
|
||||
const compareRightId = search.cmpRight
|
||||
const compareActiveSide = search.cmpActive ?? 'left'
|
||||
const isCompareMode = !!search.compare && !!compareLeftId && !!compareRightId
|
||||
|
||||
const videoRef = useRef<Player | null>(null)
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
@@ -32,6 +38,10 @@ function FileViewPage() {
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
|
||||
const [compareActiveAsset, setCompareActiveAsset] = useState<AssetInfo | null>(null)
|
||||
const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
|
||||
undefined,
|
||||
)
|
||||
const [carouselState, setCarouselState] = useState<{
|
||||
show: boolean
|
||||
files: AssetInfo[]
|
||||
@@ -108,7 +118,7 @@ function FileViewPage() {
|
||||
if (!res.ok) throw new Error('Failed to fetch versions')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!projectId && !!fileId && !!versionAssetId,
|
||||
enabled: !!projectId && !!fileId && (!!versionAssetId || isCompareMode),
|
||||
})
|
||||
|
||||
const { data: projectInfo } = useQuery({
|
||||
@@ -148,7 +158,34 @@ function FileViewPage() {
|
||||
},
|
||||
isRootFolder: false,
|
||||
fileId,
|
||||
downloadInfo: {
|
||||
originalKey: fileData.media?.original?.key,
|
||||
videoTranscodes: fileData.media?.videoTranscodes?.map((t) => ({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
isRaw: t.isRaw,
|
||||
})),
|
||||
},
|
||||
versions: versionsDataList,
|
||||
compareMode: isCompareMode,
|
||||
canCompareVersions: (versionsDataList?.length ?? 0) >= 2,
|
||||
onCompareVersions: () => {
|
||||
const pair = pickDefaultCompareVersions(versionsDataList)
|
||||
if (!pair) return
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (p: Record<string, unknown>) => ({
|
||||
...p,
|
||||
version: undefined,
|
||||
compare: true,
|
||||
cmpLeft: pair.left.id,
|
||||
cmpRight: pair.right.id,
|
||||
cmpActive: 'left' as const,
|
||||
}),
|
||||
})
|
||||
},
|
||||
onFolderClick: (id: string) => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
@@ -167,6 +204,7 @@ function FileViewPage() {
|
||||
versionsDataList,
|
||||
activeFileId,
|
||||
fileId,
|
||||
isCompareMode,
|
||||
setProjectState,
|
||||
clearProjectState,
|
||||
navigate,
|
||||
@@ -261,6 +299,11 @@ function FileViewPage() {
|
||||
setAnnotations([])
|
||||
}, [fileData?.id])
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedCommentId(null)
|
||||
setAnnotations([])
|
||||
}, [compareActiveAsset?.id])
|
||||
|
||||
if (isLoading && !fileData) {
|
||||
return <FileDetailSkeleton />
|
||||
}
|
||||
@@ -269,23 +312,45 @@ function FileViewPage() {
|
||||
return <div>{m.file_not_found()}</div>
|
||||
}
|
||||
|
||||
const sidebarFile = isCompareMode ? compareActiveAsset : (fileData as unknown as AssetInfo)
|
||||
const sidebarFileId = sidebarFile?.id ?? activeFileId
|
||||
|
||||
const handleSaveField = (fieldId: string, value: unknown) => {
|
||||
if (!teamId) return
|
||||
patchMetadata(
|
||||
{
|
||||
param: { fileId: activeFileId },
|
||||
param: { fileId: sidebarFileId },
|
||||
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['files', activeFileId],
|
||||
queryKey: ['files', sidebarFileId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const updateCompareSearch = (patch: Record<string, unknown>) => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (p: Record<string, unknown>) => ({ ...p, ...patch }),
|
||||
})
|
||||
}
|
||||
|
||||
const handleCompareExit = () => {
|
||||
const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
|
||||
updateCompareSearch({
|
||||
compare: undefined,
|
||||
cmpLeft: undefined,
|
||||
cmpRight: undefined,
|
||||
cmpActive: undefined,
|
||||
version: activeId,
|
||||
})
|
||||
}
|
||||
|
||||
const handleCommentSelect = (comment: CommentInfo) => {
|
||||
setSelectedCommentId(comment.id || null)
|
||||
const newAnnotations = comment.annotations as Annotation[]
|
||||
@@ -295,6 +360,13 @@ function FileViewPage() {
|
||||
setAnnotations([])
|
||||
}
|
||||
|
||||
if (isCompareMode) {
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
setSeekRequest({ second: comment.second, nonce: Date.now() })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
if (videoRef.current) {
|
||||
videoRef.current.currentTime(comment.second)
|
||||
@@ -316,29 +388,50 @@ function FileViewPage() {
|
||||
<div className="h-full flex flex-1 flex-col bg-background">
|
||||
<div className="h-full flex flex-1 overflow-hidden">
|
||||
<div className="flex-1 relative">
|
||||
{isFetching && (
|
||||
{isFetching && !isCompareMode && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<FileViewer
|
||||
file={fileData as unknown as AssetInfo}
|
||||
videoRef={videoRef}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
>
|
||||
{carouselState.show && (
|
||||
<FileViewerLeftSidebar
|
||||
projectId={projectId}
|
||||
currentAssetId={activeFileId}
|
||||
parentFolderId={parentFolderId}
|
||||
initialFiles={carouselState.files}
|
||||
initialNextCursor={carouselState.nextCursor}
|
||||
/>
|
||||
)}
|
||||
</FileViewer>
|
||||
{isCompareMode && compareLeftId && compareRightId ? (
|
||||
<CompareViewer
|
||||
versions={versionsDataList ?? []}
|
||||
leftId={compareLeftId}
|
||||
rightId={compareRightId}
|
||||
activeSide={compareActiveSide}
|
||||
annotations={annotations}
|
||||
seekRequest={seekRequest}
|
||||
onActiveSideChange={(side) => updateCompareSearch({ cmpActive: side })}
|
||||
onSwitchVersion={(side, versionId) =>
|
||||
updateCompareSearch(
|
||||
side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
|
||||
)
|
||||
}
|
||||
onExit={handleCompareExit}
|
||||
onActiveAssetChange={setCompareActiveAsset}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
/>
|
||||
) : (
|
||||
<FileViewer
|
||||
file={fileData as unknown as AssetInfo}
|
||||
videoRef={videoRef}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
>
|
||||
{carouselState.show && (
|
||||
<FileViewerLeftSidebar
|
||||
projectId={projectId}
|
||||
currentAssetId={activeFileId}
|
||||
parentFolderId={parentFolderId}
|
||||
initialFiles={carouselState.files}
|
||||
initialNextCursor={carouselState.nextCursor}
|
||||
/>
|
||||
)}
|
||||
</FileViewer>
|
||||
)}
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
@@ -350,12 +443,13 @@ function FileViewPage() {
|
||||
<FileViewerRightSidebar
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
file={fileData as unknown as AssetInfo}
|
||||
file={sidebarFile}
|
||||
onSaveField={handleSaveField}
|
||||
members={members}
|
||||
onCommentSelect={handleCommentSelect}
|
||||
currentTime={currentTime}
|
||||
onTyping={() => {
|
||||
if (isCompareMode) return
|
||||
if (videoRef.current) {
|
||||
videoRef.current.pause()
|
||||
}
|
||||
@@ -374,6 +468,17 @@ export const Route = createFileRoute('/projects/$projectId/files/$fileId')({
|
||||
return {
|
||||
version: (search.version as string) || undefined,
|
||||
start: search.start ? Number(search.start) : undefined,
|
||||
} as { version?: string; start?: number }
|
||||
compare: search.compare === true || search.compare === 'true' || undefined,
|
||||
cmpLeft: (search.cmpLeft as string) || undefined,
|
||||
cmpRight: (search.cmpRight as string) || undefined,
|
||||
cmpActive: search.cmpActive === 'right' ? 'right' : undefined,
|
||||
} as {
|
||||
version?: string
|
||||
start?: number
|
||||
compare?: boolean
|
||||
cmpLeft?: string
|
||||
cmpRight?: string
|
||||
cmpActive?: 'left' | 'right'
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -3,9 +3,20 @@ import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
function PublicShareFilePage() {
|
||||
const { shareId, fileId } = Route.useParams()
|
||||
const { start } = Route.useSearch()
|
||||
const { start, version, compare, cmpLeft, cmpRight, cmpActive } = Route.useSearch()
|
||||
|
||||
return <PublicShareManager shareId={shareId} initialFileId={fileId} startTime={start} />
|
||||
return (
|
||||
<PublicShareManager
|
||||
shareId={shareId}
|
||||
initialFileId={fileId}
|
||||
startTime={start}
|
||||
versionId={version}
|
||||
compare={compare}
|
||||
compareLeftId={cmpLeft}
|
||||
compareRightId={cmpRight}
|
||||
compareActiveSide={cmpActive}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/share/$shareId/files/$fileId')({
|
||||
@@ -13,6 +24,18 @@ export const Route = createFileRoute('/share/$shareId/files/$fileId')({
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
start: search.start ? Number(search.start) : undefined,
|
||||
} as { start?: number }
|
||||
version: (search.version as string) || undefined,
|
||||
compare: search.compare === true || search.compare === 'true' || undefined,
|
||||
cmpLeft: (search.cmpLeft as string) || undefined,
|
||||
cmpRight: (search.cmpRight as string) || undefined,
|
||||
cmpActive: search.cmpActive === 'right' ? 'right' : undefined,
|
||||
} as {
|
||||
start?: number
|
||||
version?: string
|
||||
compare?: boolean
|
||||
cmpLeft?: string
|
||||
cmpRight?: string
|
||||
cmpActive?: 'left' | 'right'
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { AuthLayout } from '@/ui/components/auth-layout'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Loader2, Mail, Lock, ArrowRight, UserPlus } from 'lucide-react'
|
||||
import { signUp } from '@/ui/lib/auth-client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { getLocale, setLocale } from '@/ui/paraglide/runtime.js'
|
||||
import { useAuthStore } from '@/ui/stores/auth'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowRight, Loader2, Lock, Mail, UserPlus } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
import { signUp } from '@/ui/lib/auth-client'
|
||||
import { useState } from 'react'
|
||||
import { ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { AuthLayout } from '@/ui/components/auth-layout'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
const signupSchema = z.object({
|
||||
email: z.string().email(m.invalid_email_address()),
|
||||
@@ -30,6 +31,15 @@ function SignupPage() {
|
||||
const inviteCode = (search as { inviteCode?: string }).inviteCode
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [locale, setLocaleState] = useState<'en' | 'zh'>(() => {
|
||||
const activeLocale = getLocale()
|
||||
return activeLocale === 'zh' ? 'zh' : 'en'
|
||||
})
|
||||
|
||||
const handleLocaleChange = (newLocale: 'en' | 'zh') => {
|
||||
setLocaleState(newLocale)
|
||||
setLocale(newLocale)
|
||||
}
|
||||
|
||||
const { data: inviteInfo } = useQuery({
|
||||
queryKey: ['invite', inviteCode],
|
||||
@@ -71,6 +81,7 @@ function SignupPage() {
|
||||
password: data.password,
|
||||
name: data.email, // Use email as the username
|
||||
inviteCode: data.inviteCode,
|
||||
locale,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
@@ -238,14 +249,38 @@ function SignupPage() {
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-8 pt-6 border-t border-zinc-200/30 dark:border-zinc-800/30 text-center text-sm">
|
||||
<span className="text-zinc-500 dark:text-zinc-400">{m.already_have_account()}</span>
|
||||
<a
|
||||
href="/login"
|
||||
className="font-semibold text-rose-500 hover:text-rose-600 dark:text-rose-400 dark:hover:text-rose-300 transition-colors hover:underline inline-flex items-center gap-0.5"
|
||||
>
|
||||
{m.login()} <ArrowRight className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
<div className="mt-12 pt-10 border-t border-zinc-200/30 dark:border-zinc-800/30 text-center text-sm flex flex justify-between gap-4">
|
||||
<div>
|
||||
<span className="text-zinc-500 dark:text-zinc-400">{m.already_have_account()} </span>
|
||||
<a
|
||||
href="/login"
|
||||
className="font-semibold text-rose-500 hover:text-rose-600 dark:text-rose-400 dark:hover:text-rose-300 transition-colors hover:underline inline-flex items-center gap-0.5"
|
||||
>
|
||||
{m.login()} <ArrowRight className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-xs text-zinc-400 dark:text-zinc-500">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleLocaleChange('en')}
|
||||
className={`cursor-pointer hover:text-zinc-800 dark:hover:text-zinc-200 transition-colors ${
|
||||
locale === 'en' ? 'font-bold text-rose-500 dark:text-rose-400' : ''
|
||||
}`}
|
||||
>
|
||||
English
|
||||
</button>
|
||||
<span className="text-zinc-300 dark:text-zinc-850">/</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleLocaleChange('zh')}
|
||||
className={`cursor-pointer hover:text-zinc-800 dark:hover:text-zinc-200 transition-colors ${
|
||||
locale === 'zh' ? 'font-bold text-rose-500 dark:text-rose-400' : ''
|
||||
}`}
|
||||
>
|
||||
中文
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</AuthLayout>
|
||||
)
|
||||
|
||||
@@ -13,6 +13,15 @@ export interface TopNavProjectState {
|
||||
}
|
||||
isRootFolder: boolean
|
||||
fileId?: string
|
||||
downloadInfo?: {
|
||||
originalKey?: string
|
||||
videoTranscodes?: Array<{
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
isRaw?: boolean
|
||||
}>
|
||||
}
|
||||
versions?: Array<{
|
||||
id: string
|
||||
version: number
|
||||
@@ -25,6 +34,10 @@ export interface TopNavProjectState {
|
||||
onFolderClick?: (folderId: string) => void
|
||||
isRightSidebarCollapsed?: boolean
|
||||
onRightSidebarToggle?: () => void
|
||||
// Compare Versions
|
||||
compareMode?: boolean
|
||||
canCompareVersions?: boolean
|
||||
onCompareVersions?: () => void
|
||||
}
|
||||
|
||||
interface TopNavStore {
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const APP_VERSION = '0.1.3'
|
||||
export const APP_VERSION = '0.1.6'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* Playwright configuration for the webui UI integration tests.
|
||||
*
|
||||
* The suite runs against a backend-free harness (packages/webui/e2e) served by
|
||||
* Bun's native HTML bundler, so no database, auth or transcode pipeline is
|
||||
* required.
|
||||
*
|
||||
* Browser selection: pass `--project=<name>` to pick an engine, e.g.
|
||||
* bun run test:e2e --project=webkit # WebKit (Safari engine), used on macOS CI
|
||||
* bun run test:e2e --project=chromium
|
||||
* bun run test:e2e --project=firefox
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './packages/webui/e2e/tests',
|
||||
testMatch: '**/*.spec.ts',
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: process.env.CI ? [['list'], ['html', { open: 'never' }]] : 'list',
|
||||
timeout: 60_000,
|
||||
expect: { timeout: 10_000 },
|
||||
|
||||
use: {
|
||||
// `baseURL` is Playwright's required option key and cannot be renamed.
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
baseURL: 'http://localhost:5199',
|
||||
trace: 'on-first-retry',
|
||||
video: 'retain-on-failure',
|
||||
},
|
||||
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
{
|
||||
name: 'firefox',
|
||||
use: { ...devices['Desktop Firefox'] },
|
||||
},
|
||||
{
|
||||
name: 'webkit',
|
||||
use: { ...devices['Desktop Safari'] },
|
||||
},
|
||||
],
|
||||
|
||||
// Launch the isolated harness dev server (Bun's native HTML bundler) before
|
||||
// the tests.
|
||||
webServer: {
|
||||
command: 'bun run packages/webui/e2e/harness/serve.ts',
|
||||
url: 'http://localhost:5199',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120_000,
|
||||
},
|
||||
})
|
||||
+4
-1
@@ -1,5 +1,5 @@
|
||||
import tsconfigPaths from 'vite-tsconfig-paths'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import { configDefaults, defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [tsconfigPaths()],
|
||||
@@ -7,6 +7,9 @@ export default defineConfig({
|
||||
globalSetup: './packages/db/src/test-global-setup.ts',
|
||||
globals: false,
|
||||
pool: 'forks',
|
||||
// Playwright e2e specs live under packages/webui/e2e and are run by the
|
||||
// Playwright runner (bun run test:e2e), not Vitest.
|
||||
exclude: [...configDefaults.exclude, 'packages/webui/e2e/**'],
|
||||
server: {
|
||||
deps: {
|
||||
inline: ['zod'],
|
||||
|
||||
Reference in New Issue
Block a user