mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-21 05:59:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b62c31f29 | ||
|
|
2208d4e0e0 | ||
|
|
df7f4c3c2d | ||
|
|
12323e1416 | ||
|
|
2edc5e1071 | ||
|
|
2162ed9ebe | ||
|
|
6acebb73ec | ||
|
|
7a1d6c0ab5 | ||
|
|
d16e31c0e5 | ||
|
|
d9a8b6a191 | ||
|
|
5ec4cd7fcd | ||
|
|
a7925e3c79 | ||
|
|
472b420620 | ||
|
|
8f55ba1d37 |
@@ -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://discord.gg/sUzhujK6DD">Discord</a> | <a target="_blank" href="README_CN.md">中文</a>
|
||||
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/getting-started/overview">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a> | <a target="_blank" href="https://discord.gg/sUzhujK6DD">Discord</a> | <a target="_blank" href="README_CN.md">中文</a>
|
||||
</p>
|
||||
|
||||

|
||||
@@ -45,6 +45,12 @@ Here is a short demo video showing what the Shumai agent can do:
|
||||
|
||||
https://github.com/user-attachments/assets/1186067a-72c0-41b9-836f-987438f2332a
|
||||
|
||||
Shumai also brings project management into the creative workflow. A built-in Kanban board helps teams organize tasks, track progress, and collaborate in one place.
|
||||
|
||||
The ultimate goal is an **agentic Kanban**, where agents and team members can work together on tasks. This is still a **work in progress**: you can already create tasks for AI agents, but agents cannot act on those tasks yet.
|
||||
|
||||
<img width="2880" height="2160" alt="localhost_3000_teams_01M0HQR3EEBS0B46K4FK39X2C8_kanban(1080p-2) (1)" src="https://github.com/user-attachments/assets/cd0648d0-c69a-4398-958b-8d15a33378b0" />
|
||||
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
|
||||
+8
-1
@@ -9,7 +9,7 @@
|
||||
</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>
|
||||
<a target="_blank" href="https://shumai.one/">官方网站</a> | <a target="_blank" href="https://docs.shumai.one/getting-started/overview">文档</a> | <a target="_blank" href="https://staging.shumai.one">在线演示</a> | <a target="_blank" href="README.md">English</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
@@ -44,6 +44,13 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
|
||||
|
||||
https://github.com/user-attachments/assets/1186067a-72c0-41b9-836f-987438f2332a
|
||||
|
||||
Shumai 也将项目管理融入了创意工作流程。 内置的看板可以帮助团队整理任务以及跟踪进度。
|
||||
|
||||
最终目标是打造一个 Agentic看板,让 Agent 和团队成员能够围绕同一个目标协同工作。目前这一功能仍在开发中: 你已经可以在看板中为 Agent 创建任务,但 Agent 目前还无法自动执行这些任务。
|
||||
|
||||
<img width="2880" height="2160" alt="localhost_3000_teams_01M0HQR3EEBS0B46K4FK39X2C8_kanban(1080p-2) (1)" src="https://github.com/user-attachments/assets/29ff1db1-2d65-4e3c-b467-754b777b406f" />
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> **媒体处理与存储机制:** 上传媒体文件后,Shumai 始终会保留并存储原始文件。请注意,系统中显示的文件大小为原始文件的大小,不包含转码后生成的代理文件大小。无论图片还是视频,都会额外生成一张 300p 的 WebP 封面图,作为文件列表中的预览图。此外:
|
||||
>
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please report security vulnerabilities **privately**. Do not open a public issue,
|
||||
pull request or Discord message for a suspected vulnerability, as that discloses it
|
||||
to everyone before a fix exists.
|
||||
|
||||
Use **[GitHub private vulnerability reporting](https://github.com/shumaiOne/shumai/security/advisories/new)**
|
||||
(the "Report a vulnerability" button on the Security tab). If that is unavailable,
|
||||
contact the maintainer directly rather than in a public channel.
|
||||
|
||||
Please include:
|
||||
|
||||
- What the issue is, and the impact you believe it has
|
||||
- The version or commit you tested (`git rev-parse HEAD`, or the image digest)
|
||||
- Steps to reproduce, ideally minimal
|
||||
- Your deployment shape: storage backend, whether the agent feature is enabled,
|
||||
and whether the instance is internet-reachable
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Shumai is pre-1.0 and moves quickly. Security fixes are made against the **latest
|
||||
release**. Users are encouraged to track releases rather than pin indefinitely.
|
||||
|
||||
## Scope
|
||||
|
||||
**In scope** — the application, its API, the shipped Docker images, and the
|
||||
deployment manifests under `docker-compose/`.
|
||||
|
||||
Deployment manifests are explicitly in scope. A default that is unsafe when
|
||||
followed as documented is a real finding, because the documented quickstart is what
|
||||
most operators actually run.
|
||||
|
||||
**Out of scope**
|
||||
|
||||
- Vulnerabilities in third-party dependencies, unless Shumai's use of them is what
|
||||
creates the exposure. Report those upstream.
|
||||
- Findings that require an already-compromised host or database.
|
||||
- Configurations that deviate from the documented deployment.
|
||||
|
||||
## Operator guidance
|
||||
|
||||
Shumai is self-hosted, so several controls belong to the operator rather than to the
|
||||
project:
|
||||
|
||||
- **Set `BETTER_AUTH_SECRET` per deployment.** It signs sessions and, in local
|
||||
storage mode, upload URLs. Never reuse a value from documentation or an example.
|
||||
- **Do not expose the instance to the public internet without a reverse proxy**
|
||||
terminating TLS and applying your own access policy.
|
||||
- **Do not publish the database port.** Set a real database password.
|
||||
- **Treat the agent feature as a code-execution surface.** If you enable it, run it
|
||||
where a compromise is survivable, and review the sandbox network policy.
|
||||
|
||||
## Disclosure
|
||||
|
||||
Please allow a reasonable period for a fix before public disclosure. The maintainer
|
||||
will acknowledge reports and keep reporters informed of progress.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -7,15 +7,16 @@ interface CreateShareResponse {
|
||||
}
|
||||
|
||||
/**
|
||||
* Locates a file/folder card by its name. File names are rendered as
|
||||
* `EditableText` inputs (not text nodes), so `getByText` does not match them.
|
||||
* The returned locator points at the card wrapper div (right-clickable to open
|
||||
* the card context menu).
|
||||
* Locates a file/folder card by its name. Matches both read-only text nodes
|
||||
* and active EditableText inputs. The returned locator points at the card
|
||||
* wrapper div (right-clickable to open the card context menu).
|
||||
*/
|
||||
export function fileCard(page: Page, name: string): Locator {
|
||||
return page
|
||||
.locator('div.group')
|
||||
.filter({ has: page.locator(`input[value="${name}"]`) })
|
||||
.filter({
|
||||
has: page.locator(`input[value="${name}"]`).or(page.getByText(name, { exact: true })),
|
||||
})
|
||||
.first()
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import { fileURLToPath } from 'url'
|
||||
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
async function start() {
|
||||
process.env.TESTCONTAINERS_RYUK_DISABLED = 'true'
|
||||
console.log('Starting E2E test database container...')
|
||||
await globalTestSetup()
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -245,6 +245,21 @@ describe('team api', () => {
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.videoStrategy', 'all')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates transcode.hardwareAcceleration', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ transcode: { hardwareAcceleration: 'auto' } })
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'transcode.hardwareAcceleration', value: 'auto' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.transcode.hardwareAcceleration).toBe('auto')
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.hardwareAcceleration', 'auto')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
|
||||
mockListUserMetadata.mockResolvedValue([
|
||||
{ key: 'key1', value: 'value1' },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -3575,5 +3575,133 @@ describe('AssetService — natural sort by name', () => {
|
||||
})
|
||||
expect(updatedFile.name).toBe('renamed.png')
|
||||
})
|
||||
|
||||
it('cascades soft-delete and restoration to symlinks and updates parent fileCount', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team ' + Date.now() } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
const shareRoot = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Share Root',
|
||||
type: AssetType.share_root,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
fileCount: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-file.txt',
|
||||
type: AssetType.file,
|
||||
parentId: rootFolder.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: rootFolder.id },
|
||||
data: { fileCount: 1 },
|
||||
})
|
||||
|
||||
const symlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: file.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: file.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: shareRoot.id },
|
||||
data: { fileCount: 1 },
|
||||
})
|
||||
|
||||
// Soft delete the file
|
||||
await assetService.deleteAssets([file.id])
|
||||
|
||||
const deletedSymlink = await prisma.asset.findUnique({ where: { id: symlink.id } })
|
||||
expect(deletedSymlink?.isDeleted).toBe(true)
|
||||
expect(deletedSymlink?.status).toBe(AssetStatus.trashed)
|
||||
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(0)
|
||||
|
||||
// Restore the file
|
||||
await assetService.restoreAssets([file.id])
|
||||
|
||||
const restoredSymlink = await prisma.asset.findUnique({ where: { id: symlink.id } })
|
||||
expect(restoredSymlink?.isDeleted).toBe(false)
|
||||
expect(restoredSymlink?.status).toBe(AssetStatus.processed)
|
||||
|
||||
const restoredShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(restoredShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('cascades permanent purge to symlinks when emptying trash', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team ' + Date.now() } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
const shareRoot = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Share Root',
|
||||
type: AssetType.share_root,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
fileCount: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file-to-purge.txt',
|
||||
type: AssetType.file,
|
||||
parentId: rootFolder.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const symlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: file.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: file.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
// Soft delete then empty trash
|
||||
await assetService.deleteAssets([file.id])
|
||||
await assetService.emptyTrash(project.id)
|
||||
|
||||
const purgedFile = await prisma.asset.findUnique({ where: { id: file.id } })
|
||||
expect(purgedFile).toBeNull()
|
||||
|
||||
const purgedSymlink = await prisma.asset.findUnique({ where: { id: symlink.id } })
|
||||
expect(purgedSymlink).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -632,10 +632,7 @@ export class AssetService {
|
||||
projectId: req.projectId,
|
||||
isDeleted: true,
|
||||
deletedAt: { gte: thirtyDaysAgo },
|
||||
OR: [
|
||||
{ type: { in: typesToQuery } },
|
||||
{ type: AssetType.symlink, target: { type: { in: typesToQuery } } },
|
||||
],
|
||||
type: { in: typesToQuery },
|
||||
}
|
||||
} else {
|
||||
if (!req.assetId) {
|
||||
@@ -654,7 +651,7 @@ export class AssetService {
|
||||
isDeleted: false,
|
||||
OR: [
|
||||
{ type: { in: typesToQuery } },
|
||||
{ type: AssetType.symlink, target: { type: { in: typesToQuery } } },
|
||||
{ type: AssetType.symlink, target: { isDeleted: false, type: { in: typesToQuery } } },
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -1103,6 +1100,39 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
const allDeletedIds = [a.id, ...descendantIds]
|
||||
const symlinks = await tx.asset.findMany({
|
||||
where: {
|
||||
targetId: { in: allDeletedIds },
|
||||
isDeleted: false,
|
||||
type: AssetType.symlink,
|
||||
},
|
||||
})
|
||||
|
||||
if (symlinks.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: symlinks.map((s) => s.id) } },
|
||||
data: {
|
||||
isDeleted: true,
|
||||
status: AssetStatus.trashed,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
const parentCounts = new Map<string, number>()
|
||||
for (const s of symlinks) {
|
||||
if (s.parentId) {
|
||||
parentCounts.set(s.parentId, (parentCounts.get(s.parentId) || 0) + 1)
|
||||
}
|
||||
}
|
||||
for (const [parentId, count] of parentCounts.entries()) {
|
||||
await tx.asset.update({
|
||||
where: { id: parentId },
|
||||
data: { fileCount: { decrement: count } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: a.id },
|
||||
data: {
|
||||
@@ -1126,9 +1156,16 @@ export class AssetService {
|
||||
UNION ALL
|
||||
SELECT a.id FROM assets a
|
||||
INNER JOIN descendant d ON a.parent_id = d.id
|
||||
),
|
||||
all_purging_targets AS (
|
||||
SELECT id FROM descendant
|
||||
),
|
||||
all_affected_symlinks AS (
|
||||
SELECT s.id FROM assets s
|
||||
WHERE s.type = 'symlink' AND s.target_id IN (SELECT id FROM all_purging_targets)
|
||||
)
|
||||
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
|
||||
WHERE id IN (SELECT id FROM descendant);
|
||||
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks);
|
||||
`
|
||||
}
|
||||
|
||||
@@ -1314,6 +1351,39 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
const allRestoredIds = [a.id, ...descendantIds]
|
||||
const symlinks = await tx.asset.findMany({
|
||||
where: {
|
||||
targetId: { in: allRestoredIds },
|
||||
isDeleted: true,
|
||||
type: AssetType.symlink,
|
||||
},
|
||||
})
|
||||
|
||||
if (symlinks.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: symlinks.map((s) => s.id) } },
|
||||
data: {
|
||||
isDeleted: false,
|
||||
status: AssetStatus.processed,
|
||||
deletedAt: null,
|
||||
},
|
||||
})
|
||||
|
||||
const parentCounts = new Map<string, number>()
|
||||
for (const s of symlinks) {
|
||||
if (s.parentId) {
|
||||
parentCounts.set(s.parentId, (parentCounts.get(s.parentId) || 0) + 1)
|
||||
}
|
||||
}
|
||||
for (const [parentId, count] of parentCounts.entries()) {
|
||||
await tx.asset.update({
|
||||
where: { id: parentId },
|
||||
data: { fileCount: { increment: count } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: a.id },
|
||||
data: {
|
||||
|
||||
@@ -335,4 +335,161 @@ describe('ShareService', () => {
|
||||
const item = list.data.find((l) => l.id === shareLink.id)
|
||||
expect(item?.creator?.image).toBe('http://s3/avatars/user123-presigned.png')
|
||||
})
|
||||
|
||||
it('hides soft-deleted files from share link and restores them upon file restoration', async () => {
|
||||
const project = await prisma.project.findUniqueOrThrow({ where: { id: projectId } })
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'shared-doc.pdf',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId,
|
||||
parentId: project.rootFolderId,
|
||||
},
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, {
|
||||
name: 'Doc Share',
|
||||
})
|
||||
|
||||
await shareService.addAssetToShare(shareLink.id, {
|
||||
assetIds: [file.id],
|
||||
})
|
||||
|
||||
// Verify initial state: 1 file in share link
|
||||
const initialChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(initialChildren.data).toHaveLength(1)
|
||||
expect(initialChildren.data[0].name).toBe('shared-doc.pdf')
|
||||
|
||||
const initialShareRoot = await prisma.asset.findUnique({
|
||||
where: { id: shareLink.rootFolderId },
|
||||
})
|
||||
expect(initialShareRoot?.fileCount).toBe(1)
|
||||
|
||||
const symlink = await prisma.asset.findFirst({
|
||||
where: { targetId: file.id, parentId: shareLink.rootFolderId },
|
||||
})
|
||||
expect(symlink).toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).resolves.toBeDefined()
|
||||
|
||||
// 1. Soft-delete the file (move to trash)
|
||||
await assetService.deleteAssets([file.id])
|
||||
|
||||
// Verify: file should disappear from share link children
|
||||
const afterDeleteChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(afterDeleteChildren.data).toHaveLength(0)
|
||||
|
||||
// Verify: share root fileCount should be decremented to 0
|
||||
const afterDeleteShareRoot = await prisma.asset.findUnique({
|
||||
where: { id: shareLink.rootFolderId },
|
||||
})
|
||||
expect(afterDeleteShareRoot?.fileCount).toBe(0)
|
||||
|
||||
// Verify: public access is rejected
|
||||
await expect(shareService.verifyPublicAccess(file.id)).rejects.toThrow()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).rejects.toThrow()
|
||||
|
||||
// Verify: project's recently-deleted view does NOT list symlinks
|
||||
const recentlyDeleted = await assetService.listChildren({
|
||||
projectId,
|
||||
showDeleted: true,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(recentlyDeleted.data).toHaveLength(1)
|
||||
expect(recentlyDeleted.data[0].id).toBe(file.id)
|
||||
|
||||
// 2. Restore the file from trash
|
||||
await assetService.restoreAssets([file.id])
|
||||
|
||||
// Verify: file reappears in share link children
|
||||
const afterRestoreChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(afterRestoreChildren.data).toHaveLength(1)
|
||||
expect(afterRestoreChildren.data[0].name).toBe('shared-doc.pdf')
|
||||
|
||||
// Verify: share root fileCount is restored to 1
|
||||
const afterRestoreShareRoot = await prisma.asset.findUnique({
|
||||
where: { id: shareLink.rootFolderId },
|
||||
})
|
||||
expect(afterRestoreShareRoot?.fileCount).toBe(1)
|
||||
|
||||
// Verify: public access works again
|
||||
await expect(shareService.verifyPublicAccess(file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
it('hides soft-deleted folders from share link and restores them upon folder restoration', async () => {
|
||||
const project = await prisma.project.findUniqueOrThrow({ where: { id: projectId } })
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Shared Folder',
|
||||
type: AssetType.folder,
|
||||
status: 'processed',
|
||||
projectId,
|
||||
parentId: project.rootFolderId,
|
||||
},
|
||||
})
|
||||
const childFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'inner-file.txt',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, {
|
||||
name: 'Folder Share',
|
||||
})
|
||||
|
||||
await shareService.addAssetToShare(shareLink.id, {
|
||||
assetIds: [folder.id],
|
||||
})
|
||||
|
||||
// Initial check: folder is in share link
|
||||
const initialChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'folder',
|
||||
})
|
||||
expect(initialChildren.data).toHaveLength(1)
|
||||
expect(initialChildren.data[0].name).toBe('Shared Folder')
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).resolves.toBeDefined()
|
||||
|
||||
// 1. Soft-delete the folder
|
||||
await assetService.deleteAssets([folder.id])
|
||||
|
||||
// Verify: folder disappears from share link
|
||||
const afterDeleteChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'folder',
|
||||
})
|
||||
expect(afterDeleteChildren.data).toHaveLength(0)
|
||||
|
||||
// Verify: access to child file inside folder is rejected
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).rejects.toThrow()
|
||||
|
||||
// 2. Restore the folder
|
||||
await assetService.restoreAssets([folder.id])
|
||||
|
||||
// Verify: folder reappears in share link
|
||||
const afterRestoreChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'folder',
|
||||
})
|
||||
expect(afterRestoreChildren.data).toHaveLength(1)
|
||||
expect(afterRestoreChildren.data[0].name).toBe('Shared Folder')
|
||||
|
||||
// Verify: access to child file inside folder is restored
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).resolves.toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -260,16 +260,17 @@ export class ShareService {
|
||||
WITH RECURSIVE
|
||||
-- Trace ancestors in the real asset tree
|
||||
real_ancestors AS (
|
||||
SELECT id, parent_id, type::text FROM assets WHERE id = ${assetId}
|
||||
SELECT id, parent_id, type::text FROM assets WHERE id = ${assetId} AND is_deleted = false
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text FROM assets a
|
||||
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
),
|
||||
-- Find all symlinks pointing to any of these real ancestors
|
||||
found_symlinks AS (
|
||||
SELECT s.id, s.parent_id, s.type::text FROM assets s
|
||||
INNER JOIN real_ancestors ra ON s.target_id = ra.id
|
||||
WHERE s.type = 'symlink'
|
||||
WHERE s.type = 'symlink' AND s.is_deleted = false
|
||||
),
|
||||
-- Combine: start with either real ancestors that are 'share' type, or symlinks that lead to 'share' type
|
||||
search_starts AS (
|
||||
@@ -283,6 +284,7 @@ export class ShareService {
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text FROM assets a
|
||||
INNER JOIN share_trace st ON st.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
)
|
||||
SELECT id as "shareRootId" FROM share_trace WHERE type = 'share' LIMIT 1;
|
||||
`
|
||||
|
||||
@@ -371,11 +371,12 @@ describe('TeamService', () => {
|
||||
expect(newSettings).toEqual({ theme: 'dark', semanticSearchEnabled: false })
|
||||
|
||||
await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'all')
|
||||
await teamService.updateSettings(team.id, 'transcode.hardwareAcceleration', 'auto')
|
||||
|
||||
const finalSettings = await teamService.getSettings(team.id)
|
||||
expect(finalSettings).toEqual({
|
||||
theme: 'dark',
|
||||
transcode: { videoStrategy: 'all' },
|
||||
transcode: { videoStrategy: 'all', hardwareAcceleration: 'auto' },
|
||||
semanticSearchEnabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,7 +31,7 @@ export class TeamService {
|
||||
data: {
|
||||
name: 'Default Team',
|
||||
settings: {
|
||||
transcode: { videoStrategy: 'best_match' },
|
||||
transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off' },
|
||||
},
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
@@ -318,6 +318,12 @@ export class TeamService {
|
||||
}
|
||||
settings.transcode.videoStrategy = value
|
||||
delete settings['transcode.videoStrategy']
|
||||
} else if (key === 'transcode.hardwareAcceleration') {
|
||||
if (!settings.transcode) {
|
||||
settings.transcode = {}
|
||||
}
|
||||
settings.transcode.hardwareAcceleration = value
|
||||
delete settings['transcode.hardwareAcceleration']
|
||||
} else {
|
||||
settings[key] = value
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { transcodeService, calculatePreviewDimensions } from './transcode'
|
||||
import {
|
||||
transcodeService,
|
||||
calculatePreviewDimensions,
|
||||
getPlatformEncoderCandidates,
|
||||
getDefaultBitrate,
|
||||
getDefaultBitrateBps,
|
||||
calculateMaxBitrate,
|
||||
H264_ENCODER_CONFIGS,
|
||||
} from './transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import * as path from 'path'
|
||||
import * as child_process from 'child_process'
|
||||
@@ -109,6 +117,118 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should extract videoBitRate from stream bit_rate or tags or fallback correctly', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
// 1. Direct video stream bit_rate
|
||||
const output1 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '2000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080, bit_rate: '1800000' },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output1, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info1 = await transcodeService.getVideoInfo('test1.mp4')
|
||||
expect(info1.videoBitRate).toBe(1800000)
|
||||
|
||||
// 2. Stream BPS tag
|
||||
const output2 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '2000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080, tags: { BPS: '1500000' } },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output2, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info2 = await transcodeService.getVideoInfo('test2.mp4')
|
||||
expect(info2.videoBitRate).toBe(1500000)
|
||||
|
||||
// 3. Stream NUMBER_OF_BYTES tag
|
||||
const output3 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '2000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080, tags: { NUMBER_OF_BYTES: '1000000' } },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output3, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info3 = await transcodeService.getVideoInfo('test3.mp4')
|
||||
expect(info3.videoBitRate).toBe(800000) // (1,000,000 * 8) / 10 = 800,000
|
||||
|
||||
// 4. Fallback totalBitrate - audioBitrate
|
||||
const output4 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '1000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080 },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output4, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info4 = await transcodeService.getVideoInfo('test4.mp4')
|
||||
expect(info4.videoBitRate).toBe(872000) // 1,000,000 - 128,000 = 872,000
|
||||
})
|
||||
|
||||
it('should get image info using sharp', async () => {
|
||||
const mockMetadata = {
|
||||
width: 800,
|
||||
@@ -897,4 +1017,509 @@ describe('TranscodeService', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Hardware Acceleration & Encoder Resolution', () => {
|
||||
beforeEach(() => {
|
||||
transcodeService.clearEncodersCache()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('should return platform candidates correctly', () => {
|
||||
expect(getPlatformEncoderCandidates('darwin')).toEqual([
|
||||
'h264_videotoolbox',
|
||||
'h264_nvenc',
|
||||
'h264_qsv',
|
||||
'h264_amf',
|
||||
])
|
||||
expect(getPlatformEncoderCandidates('win32')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
|
||||
expect(getPlatformEncoderCandidates('linux')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
|
||||
})
|
||||
|
||||
it('should calculate default bitrates by resolution height and width correctly', () => {
|
||||
expect(getDefaultBitrateBps(2160, 3840)).toBe(12_000_000)
|
||||
expect(getDefaultBitrate(2160, 3840)).toBe('12000k')
|
||||
expect(getDefaultBitrate(1080, 1920)).toBe('4500k')
|
||||
expect(getDefaultBitrate(720, 1280)).toBe('2500k')
|
||||
expect(getDefaultBitrate(540, 960)).toBe('1200k')
|
||||
expect(getDefaultBitrate(360, 640)).toBe('800k')
|
||||
expect(getDefaultBitrate(180, 320)).toBe('100k')
|
||||
expect(getDefaultBitrate(100, 100)).toBe('100k')
|
||||
})
|
||||
|
||||
it('calculateMaxBitrate should cap bitrate based on sourceVideoBitrate, ceiling, and targetFps', () => {
|
||||
// Default without source bitrate
|
||||
expect(calculateMaxBitrate(720, 1280)).toEqual({
|
||||
maxrate: '2500k',
|
||||
bufsize: '5000k',
|
||||
})
|
||||
|
||||
// With low source bitrate (600k * 1.2 = 720k)
|
||||
expect(calculateMaxBitrate(720, 1280, 600_000)).toEqual({
|
||||
maxrate: '720k',
|
||||
bufsize: '1440k',
|
||||
})
|
||||
|
||||
// With high source bitrate (3000k * 1.2 = 3600k, capped at 2500k)
|
||||
expect(calculateMaxBitrate(720, 1280, 3_000_000)).toEqual({
|
||||
maxrate: '2500k',
|
||||
bufsize: '5000k',
|
||||
})
|
||||
|
||||
// With downsampled targetFps (180p preview @ 0.78 fps: 100k * (0.78/24) = 3.25k -> capped at min 50k)
|
||||
expect(calculateMaxBitrate(180, 320, 600_000, 0.78)).toEqual({
|
||||
maxrate: '50k',
|
||||
bufsize: '100k',
|
||||
})
|
||||
|
||||
// With downsampled targetFps string (180p preview @ 24 fps)
|
||||
expect(calculateMaxBitrate(180, 320, 600_000, 24)).toEqual({
|
||||
maxrate: '100k',
|
||||
bufsize: '200k',
|
||||
})
|
||||
|
||||
// With extremely low source bitrate without targetFps (50k * 1.2 = 60k, minimum floor 100k)
|
||||
expect(calculateMaxBitrate(720, 1280, 50_000)).toEqual({
|
||||
maxrate: '100k',
|
||||
bufsize: '200k',
|
||||
})
|
||||
})
|
||||
|
||||
it('selectH264Encoder should return libx264 when hardwareAcceleration is off', async () => {
|
||||
const encoder = await transcodeService.selectH264Encoder('off')
|
||||
expect(encoder).toEqual(H264_ENCODER_CONFIGS.libx264)
|
||||
expect(child_process.execFile).not.toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
['-encoders'],
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_videotoolbox on darwin when available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_videotoolbox VideoToolbox H.264 Encoder
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'darwin')
|
||||
expect(encoder.name).toBe('h264_videotoolbox')
|
||||
expect(encoder.presetArgs).toEqual(['-q:v', '74'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_nvenc on linux when available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_nvenc NVIDIA NVENC H.264 encoder
|
||||
V....D h264_qsv Intel Quick Sync Video H.264
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('h264_nvenc')
|
||||
expect(encoder.presetArgs).toEqual([
|
||||
'-preset',
|
||||
'p4',
|
||||
'-rc:v',
|
||||
'vbr',
|
||||
'-cq:v',
|
||||
'26',
|
||||
'-b:v',
|
||||
'0',
|
||||
])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_qsv on linux when nvenc is not available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_qsv Intel Quick Sync Video H.264
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('h264_qsv')
|
||||
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-global_quality', '26'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_amf on win32 when available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_amf AMD AMF H.264 Encoder
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'win32')
|
||||
expect(encoder.name).toBe('h264_amf')
|
||||
expect(encoder.presetArgs).toEqual([
|
||||
'-quality',
|
||||
'balanced',
|
||||
'-rc',
|
||||
'qvbr',
|
||||
'-qvbr_quality_level',
|
||||
'26',
|
||||
])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should fallback to libx264 when no hw encoder is in ffmpeg build', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('libx264')
|
||||
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-crf', '26'])
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration off should use libx264, preset fast, crf 26, maxrate, and yuv420p', async () => {
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_off.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'off',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'fast',
|
||||
'-crf',
|
||||
'26',
|
||||
'-maxrate',
|
||||
'720k',
|
||||
'-bufsize',
|
||||
'1440k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration auto and videotoolbox should use -q:v 74 and -maxrate', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_videotoolbox,
|
||||
)
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_vt.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'h264_videotoolbox',
|
||||
'-q:v',
|
||||
'74',
|
||||
'-maxrate',
|
||||
'720k',
|
||||
'-bufsize',
|
||||
'1440k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration auto and nvenc should use -preset p4, -rc:v vbr, -cq:v 26, -b:v 0, and -maxrate', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_nvenc,
|
||||
)
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_nvenc.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 1_000_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'h264_nvenc',
|
||||
'-preset',
|
||||
'p4',
|
||||
'-rc:v',
|
||||
'vbr',
|
||||
'-cq:v',
|
||||
'26',
|
||||
'-b:v',
|
||||
'0',
|
||||
'-maxrate',
|
||||
'1200k',
|
||||
'-bufsize',
|
||||
'2400k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration auto and amf should use -quality balanced, -rc qvbr, -qvbr_quality_level 26, and -maxrate', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_amf,
|
||||
)
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_amf.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'h264_amf',
|
||||
'-quality',
|
||||
'balanced',
|
||||
'-rc',
|
||||
'qvbr',
|
||||
'-qvbr_quality_level',
|
||||
'26',
|
||||
'-maxrate',
|
||||
'720k',
|
||||
'-bufsize',
|
||||
'1440k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with explicit videoBitrate should use -b:v directly', async () => {
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_explicit.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'off',
|
||||
videoBitrate: '1500k',
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'fast',
|
||||
'-crf',
|
||||
'26',
|
||||
'-b:v',
|
||||
'1500k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
expect(child_process.execFile).not.toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining(['-maxrate']),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -91,6 +91,7 @@ export interface MediaMetadata {
|
||||
originalHeight: number
|
||||
duration: number
|
||||
bitRate: number
|
||||
videoBitRate?: number
|
||||
frameRate: number
|
||||
totalFrames: number
|
||||
startTimecode?: string
|
||||
@@ -111,6 +112,113 @@ export interface TranscodeVideoParams {
|
||||
frameRate?: number | string
|
||||
disableAudio?: boolean
|
||||
overlayFile?: string
|
||||
hardwareAcceleration?: 'off' | 'auto'
|
||||
videoBitrate?: string
|
||||
sourceVideoBitrate?: number
|
||||
}
|
||||
|
||||
export interface EncoderConfig {
|
||||
name: string
|
||||
presetArgs: string[]
|
||||
}
|
||||
|
||||
export const H264_ENCODER_CONFIGS: Record<string, EncoderConfig> = {
|
||||
h264_nvenc: {
|
||||
name: 'h264_nvenc',
|
||||
presetArgs: ['-preset', 'p4', '-rc:v', 'vbr', '-cq:v', '26', '-b:v', '0'],
|
||||
},
|
||||
h264_qsv: {
|
||||
name: 'h264_qsv',
|
||||
presetArgs: ['-preset', 'fast', '-global_quality', '26'],
|
||||
},
|
||||
h264_amf: {
|
||||
name: 'h264_amf',
|
||||
presetArgs: ['-quality', 'balanced', '-rc', 'qvbr', '-qvbr_quality_level', '26'],
|
||||
},
|
||||
h264_videotoolbox: {
|
||||
name: 'h264_videotoolbox',
|
||||
presetArgs: ['-q:v', '74'],
|
||||
},
|
||||
libx264: {
|
||||
name: 'libx264',
|
||||
presetArgs: ['-preset', 'fast', '-crf', '26'],
|
||||
},
|
||||
}
|
||||
|
||||
export function getPlatformEncoderCandidates(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string[] {
|
||||
switch (platform) {
|
||||
case 'darwin':
|
||||
return ['h264_videotoolbox', 'h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
case 'win32':
|
||||
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
case 'linux':
|
||||
default:
|
||||
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
}
|
||||
}
|
||||
|
||||
export function getDefaultBitrateBps(height: number, width?: number): number {
|
||||
const longSide = Math.max(width || 0, height)
|
||||
const shortSide = Math.min(width || height, height)
|
||||
const effectiveHeight = shortSide > 0 ? shortSide : height
|
||||
|
||||
if (effectiveHeight >= 2160 || longSide >= 3840) return 12_000_000
|
||||
if (effectiveHeight >= 1080 || longSide >= 1920) return 4_500_000
|
||||
if (effectiveHeight >= 720 || longSide >= 1280) return 2_500_000
|
||||
if (effectiveHeight >= 540 || longSide >= 960) return 1_200_000
|
||||
if (effectiveHeight >= 360 || longSide >= 640) return 800_000
|
||||
return 100_000
|
||||
}
|
||||
|
||||
export function getDefaultBitrate(height: number, width?: number): string {
|
||||
const bps = getDefaultBitrateBps(height, width)
|
||||
return `${Math.round(bps / 1000)}k`
|
||||
}
|
||||
|
||||
export function calculateMaxBitrate(
|
||||
targetHeight: number,
|
||||
targetWidth?: number,
|
||||
sourceVideoBitrate?: number,
|
||||
targetFps?: number | string,
|
||||
): { maxrate: string; bufsize: string } {
|
||||
let configuredMaxBps = getDefaultBitrateBps(targetHeight, targetWidth)
|
||||
|
||||
// If frame rate is downsampled (e.g. 180p preview with < 24 fps), scale the bitrate ceiling proportionally
|
||||
if (targetFps) {
|
||||
let parsedFps: number | undefined
|
||||
if (typeof targetFps === 'number') {
|
||||
parsedFps = targetFps
|
||||
} else {
|
||||
const parts = targetFps.split('/')
|
||||
if (parts.length === 2) {
|
||||
parsedFps = parseFloat(parts[0]) / parseFloat(parts[1])
|
||||
} else {
|
||||
parsedFps = parseFloat(targetFps)
|
||||
}
|
||||
}
|
||||
if (Number.isFinite(parsedFps) && parsedFps > 0 && parsedFps < 24) {
|
||||
const fpsRatio = Math.max(0.1, parsedFps / 24)
|
||||
configuredMaxBps = Math.max(50_000, Math.round(configuredMaxBps * fpsRatio))
|
||||
}
|
||||
}
|
||||
|
||||
let effectiveMaxBps =
|
||||
sourceVideoBitrate && sourceVideoBitrate > 0
|
||||
? Math.min(configuredMaxBps, Math.round(sourceVideoBitrate * 1.2))
|
||||
: configuredMaxBps
|
||||
|
||||
const minFloor = targetFps ? 50_000 : 100_000
|
||||
effectiveMaxBps = Math.max(minFloor, effectiveMaxBps)
|
||||
|
||||
const maxrateKbps = Math.max(50, Math.round(effectiveMaxBps / 1000))
|
||||
const bufsizeKbps = maxrateKbps * 2
|
||||
|
||||
return {
|
||||
maxrate: `${maxrateKbps}k`,
|
||||
bufsize: `${bufsizeKbps}k`,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtractVideoFramesParams {
|
||||
@@ -295,11 +403,38 @@ export class TranscodeService {
|
||||
}
|
||||
const startTimecode = videoStream.tags?.timecode || info.format?.tags?.timecode
|
||||
|
||||
let videoBitRate: number | undefined
|
||||
if (videoStream.bit_rate && parseInt(videoStream.bit_rate, 10) > 0) {
|
||||
videoBitRate = parseInt(videoStream.bit_rate, 10)
|
||||
} else {
|
||||
const bpsTag = videoStream.tags?.BPS || videoStream.tags?.['BPS-eng']
|
||||
if (bpsTag && parseInt(bpsTag, 10) > 0) {
|
||||
videoBitRate = parseInt(bpsTag, 10)
|
||||
} else {
|
||||
const bytesTag =
|
||||
videoStream.tags?.NUMBER_OF_BYTES || videoStream.tags?.['NUMBER_OF_BYTES-eng']
|
||||
if (bytesTag && duration > 0) {
|
||||
videoBitRate = Math.round((parseInt(bytesTag, 10) * 8) / duration)
|
||||
} else {
|
||||
const totalBitrate = parseFloat(info.format.bit_rate)
|
||||
if (Number.isFinite(totalBitrate) && totalBitrate > 0) {
|
||||
const audioBitrate = audioStream?.bit_rate
|
||||
? parseFloat(audioStream.bit_rate)
|
||||
: audioStream
|
||||
? 128_000
|
||||
: 0
|
||||
videoBitRate = Math.max(100_000, Math.round(totalBitrate - audioBitrate))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
originalWidth: videoStream.width,
|
||||
originalHeight: videoStream.height,
|
||||
duration,
|
||||
bitRate: parseFloat(info.format.bit_rate),
|
||||
videoBitRate,
|
||||
frameRate: fps || 30,
|
||||
totalFrames: totalFrames || 0,
|
||||
startTimecode,
|
||||
@@ -373,6 +508,53 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
private availableEncodersCache: Set<string> | null = null
|
||||
|
||||
clearEncodersCache(): void {
|
||||
this.availableEncodersCache = null
|
||||
}
|
||||
|
||||
async getAvailableEncoders(): Promise<Set<string>> {
|
||||
if (this.availableEncodersCache) {
|
||||
return this.availableEncodersCache
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('ffmpeg', ['-encoders'])
|
||||
const encoders = new Set<string>()
|
||||
const lines = stdout.split('\n')
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^\s*[A-Z.]{6}\s+([a-zA-Z0-9_-]+)/)
|
||||
if (match) {
|
||||
encoders.add(match[1])
|
||||
}
|
||||
}
|
||||
this.availableEncodersCache = encoders
|
||||
return encoders
|
||||
} catch (err) {
|
||||
console.warn('Failed to probe ffmpeg encoders:', err)
|
||||
return new Set<string>()
|
||||
}
|
||||
}
|
||||
|
||||
async selectH264Encoder(
|
||||
hardwareAcceleration?: 'off' | 'auto',
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Promise<EncoderConfig> {
|
||||
if (hardwareAcceleration !== 'auto') {
|
||||
return H264_ENCODER_CONFIGS.libx264
|
||||
}
|
||||
|
||||
const available = await this.getAvailableEncoders()
|
||||
const candidates = getPlatformEncoderCandidates(platform)
|
||||
for (const enc of candidates) {
|
||||
if (available.has(enc) && H264_ENCODER_CONFIGS[enc]) {
|
||||
return H264_ENCODER_CONFIGS[enc]
|
||||
}
|
||||
}
|
||||
|
||||
return H264_ENCODER_CONFIGS.libx264
|
||||
}
|
||||
|
||||
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
|
||||
let filterComplex: string
|
||||
const args: string[] = ['-i', params.inputFile]
|
||||
@@ -420,7 +602,25 @@ export class TranscodeService {
|
||||
args.push('-map', '0:a?')
|
||||
}
|
||||
|
||||
args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '26')
|
||||
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
|
||||
args.push('-c:v', encoder.name)
|
||||
if (encoder.presetArgs.length > 0) {
|
||||
args.push(...encoder.presetArgs)
|
||||
}
|
||||
|
||||
if (params.videoBitrate) {
|
||||
args.push('-b:v', params.videoBitrate)
|
||||
} else {
|
||||
const { maxrate, bufsize } = calculateMaxBitrate(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
params.frameRate,
|
||||
)
|
||||
args.push('-maxrate', maxrate, '-bufsize', bufsize)
|
||||
}
|
||||
|
||||
args.push('-pix_fmt', 'yuv420p')
|
||||
|
||||
if (!params.disableAudio) {
|
||||
args.push('-c:a', 'aac', '-b:a', '128k')
|
||||
|
||||
@@ -190,6 +190,7 @@ describe('UploadService', () => {
|
||||
projectId: projectId,
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
|
||||
@@ -303,9 +303,11 @@ export class UploadService {
|
||||
const settings = team.settings as PrismaJson.Settings | null
|
||||
if (isVideo) {
|
||||
const strategy = settings?.transcode?.videoStrategy || 'best_match'
|
||||
const hardwareAcceleration = settings?.transcode?.hardwareAcceleration || 'off'
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
|
||||
.setStrategy(strategy)
|
||||
.setHardwareAcceleration(hardwareAcceleration)
|
||||
.withSprite()
|
||||
.withPoster()
|
||||
.submit()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -46,6 +46,7 @@ declare global {
|
||||
// Team Settings
|
||||
// ----------------------------------------------------------------------
|
||||
export type VideoTranscodeStrategy = 'best_match' | 'all'
|
||||
export type HardwareAcceleration = 'off' | 'auto'
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Collection Filter
|
||||
@@ -54,6 +55,7 @@ declare global {
|
||||
|
||||
export interface TranscodeSettings {
|
||||
videoStrategy: VideoTranscodeStrategy
|
||||
hardwareAcceleration?: HardwareAcceleration
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
@@ -103,6 +105,7 @@ declare global {
|
||||
hasAudio: boolean
|
||||
duration: number
|
||||
bitRate: number
|
||||
videoBitRate?: number
|
||||
frameRate: number
|
||||
totalFrames: number
|
||||
startTimecode: string
|
||||
@@ -290,6 +293,7 @@ declare global {
|
||||
|
||||
export interface TaskSpec {
|
||||
videoStrategy?: VideoTranscodeStrategy
|
||||
hardwareAcceleration?: HardwareAcceleration
|
||||
thumbnail?: boolean
|
||||
sprite?: boolean
|
||||
poster?: boolean
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -74,11 +74,21 @@ export const VideoTranscodeStrategy = {
|
||||
export type VideoTranscodeStrategy =
|
||||
(typeof VideoTranscodeStrategy)[keyof typeof VideoTranscodeStrategy]
|
||||
|
||||
export const HardwareAcceleration = {
|
||||
off: 'off',
|
||||
auto: 'auto',
|
||||
} as const
|
||||
export type HardwareAcceleration = (typeof HardwareAcceleration)[keyof typeof HardwareAcceleration]
|
||||
|
||||
export const updateTeamSettingsRequestSchema = z.union([
|
||||
z.object({
|
||||
key: z.literal('transcode.videoStrategy'),
|
||||
value: z.nativeEnum(VideoTranscodeStrategy),
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('transcode.hardwareAcceleration'),
|
||||
value: z.nativeEnum(HardwareAcceleration),
|
||||
}),
|
||||
])
|
||||
export type UpdateTeamSettingsRequest = z.infer<typeof updateTeamSettingsRequestSchema>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -172,6 +172,7 @@ describe('Transcode Activities', () => {
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
bitRate: 1000,
|
||||
videoBitRate: 850000,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
hasAudio: true,
|
||||
@@ -193,6 +194,7 @@ describe('Transcode Activities', () => {
|
||||
expect(transcodeService.getVideoInfo).toHaveBeenCalledWith('/tmp/v.mp4')
|
||||
expect(result.duration).toBe(10)
|
||||
expect(result.metadata?.originalWidth).toBe(1920)
|
||||
expect(result.metadata?.videoBitRate).toBe(850000)
|
||||
expect(result.metadata?.videoCodec).toBe('Advanced Video Coding')
|
||||
expect(result.metadata?.audioCodec).toBe('MPEG-4 Audio')
|
||||
expect(result.metadata?.audioChannels).toBe(2)
|
||||
@@ -590,9 +592,17 @@ describe('Transcode Activities', () => {
|
||||
videoSpec: { resolution: '720p', width: 1280, height: 720 },
|
||||
duration: 10,
|
||||
originalFps: 30,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalled()
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
inputFile: '/tmp/v.mp4',
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should call transcodeService.takeScreenshots', async () => {
|
||||
|
||||
@@ -104,6 +104,7 @@ export async function getMediaInfoActivity(params: {
|
||||
originalHeight: info.originalHeight,
|
||||
duration: info.duration,
|
||||
bitRate: info.bitRate,
|
||||
videoBitRate: info.videoBitRate,
|
||||
frameRate: info.frameRate,
|
||||
totalFrames: info.totalFrames,
|
||||
startTimecode: info.startTimecode || '00:00:00:00',
|
||||
@@ -220,6 +221,8 @@ export interface VideoActivityParams {
|
||||
videoSpec: PrismaJson.VideoTranscode
|
||||
duration: number
|
||||
originalFps: number
|
||||
hardwareAcceleration?: PrismaJson.HardwareAcceleration
|
||||
sourceVideoBitrate?: number
|
||||
}
|
||||
|
||||
export async function transcodeVideoActivity(
|
||||
@@ -262,6 +265,8 @@ export async function transcodeVideoActivity(
|
||||
height: params.videoSpec.height,
|
||||
frameRate: targetFps || undefined,
|
||||
disableAudio,
|
||||
hardwareAcceleration: params.hardwareAcceleration,
|
||||
sourceVideoBitrate: params.sourceVideoBitrate,
|
||||
})
|
||||
|
||||
const stat = fs.statSync(outputFile)
|
||||
|
||||
@@ -182,7 +182,13 @@ describe('Watermark Activities', () => {
|
||||
describe('transcodeWatermarkMediaActivity', () => {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
async function seedAsset(name: string, mediaType: string, key: string, proxyType: string) {
|
||||
async function seedAsset(
|
||||
name: string,
|
||||
mediaType: string,
|
||||
key: string,
|
||||
proxyType: string,
|
||||
projectId?: string,
|
||||
) {
|
||||
const storageKey = await prisma.storageKey.create({ data: { key } })
|
||||
return prisma.asset.create({
|
||||
data: {
|
||||
@@ -190,6 +196,7 @@ describe('Watermark Activities', () => {
|
||||
type: 'file',
|
||||
mediaType,
|
||||
status: 'processed',
|
||||
projectId,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
duration: 0,
|
||||
@@ -327,12 +334,71 @@ describe('Watermark Activities', () => {
|
||||
expect(media.proxyType).toBe('video')
|
||||
expect(media.videoTranscodes?.length).toBeGreaterThan(0)
|
||||
expect(media.videoTranscodes?.[0].key).toContain('watermark-')
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
bucket,
|
||||
expect.stringContaining('watermark-'),
|
||||
expect.anything(),
|
||||
expect.any(Number),
|
||||
'video/mp4',
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
hardwareAcceleration: 'off',
|
||||
sourceVideoBitrate: 1000,
|
||||
}),
|
||||
)
|
||||
|
||||
fs.rmSync(outFilePath, { force: true })
|
||||
})
|
||||
|
||||
it('passes team hardwareAcceleration and videoBitRate to transcodeVideo', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'HW Accel Team',
|
||||
settings: {
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'auto',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'HW Accel Project',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
const assetKey = 'files/e2e-wm/video-hw.mp4'
|
||||
const asset = await seedAsset('video-hw.mp4', 'video/mp4', assetKey, 'video', project.id)
|
||||
const config = await seedConfig()
|
||||
|
||||
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
|
||||
originalWidth: 1280,
|
||||
originalHeight: 720,
|
||||
duration: 15,
|
||||
bitRate: 2000000,
|
||||
videoBitRate: 1800000,
|
||||
frameRate: 24,
|
||||
totalFrames: 360,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: false,
|
||||
mimeType: 'video/mp4',
|
||||
})
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
|
||||
|
||||
const stem = 'video-hw'
|
||||
const configId = config.id
|
||||
const outFilePath = path.join('/tmp', `${stem}-watermark-${configId}-100p.mp4`)
|
||||
fs.writeFileSync(outFilePath, Buffer.from('fake mp4'))
|
||||
|
||||
const media = await transcodeWatermarkMediaActivity({
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: config.id,
|
||||
})
|
||||
|
||||
expect(media.proxyType).toBe('video')
|
||||
expect(media.metadata?.bitRate).toBe(2000000)
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 1800000,
|
||||
disableAudio: true,
|
||||
}),
|
||||
)
|
||||
|
||||
fs.rmSync(outFilePath, { force: true })
|
||||
|
||||
@@ -133,7 +133,12 @@ export async function transcodeWatermarkMediaActivity(
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { storageKey: true },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: { team: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!asset || !asset.storageKey?.key) {
|
||||
@@ -143,6 +148,9 @@ export async function transcodeWatermarkMediaActivity(
|
||||
})
|
||||
}
|
||||
|
||||
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
|
||||
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
|
||||
|
||||
// The config column is declared as PrismaJson.WatermarkConfigSpec, which is
|
||||
// structurally identical to the DTO type, so no cast is required.
|
||||
const config: WatermarkConfigSpec = watermarkConfigRecord.config
|
||||
@@ -165,20 +173,26 @@ export async function transcodeWatermarkMediaActivity(
|
||||
let originalWidth = 1920
|
||||
let originalHeight = 1080
|
||||
let duration = 0
|
||||
let bitRate = 0
|
||||
let videoBitRate: number | undefined
|
||||
let frameRate = 30
|
||||
let totalFrames = 0
|
||||
let startTimecode = '00:00:00:00'
|
||||
let hasAudio = false
|
||||
let sourceVideoBitrate: number | undefined
|
||||
|
||||
if (isVideo) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
duration = info.duration
|
||||
bitRate = info.bitRate
|
||||
videoBitRate = info.videoBitRate
|
||||
frameRate = info.frameRate
|
||||
totalFrames = info.totalFrames
|
||||
startTimecode = info.startTimecode || '00:00:00:00'
|
||||
hasAudio = info.hasAudio
|
||||
sourceVideoBitrate = info.videoBitRate || info.bitRate
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
@@ -237,7 +251,8 @@ export async function transcodeWatermarkMediaActivity(
|
||||
originalWidth,
|
||||
originalHeight,
|
||||
duration,
|
||||
bitRate: 0,
|
||||
bitRate,
|
||||
videoBitRate,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
startTimecode,
|
||||
@@ -321,6 +336,8 @@ export async function transcodeWatermarkMediaActivity(
|
||||
height: targetHeight,
|
||||
disableAudio: !hasAudio,
|
||||
overlayFile: overlayPngPath,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
})
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
|
||||
@@ -22,6 +22,13 @@ export class VideoTranscoder {
|
||||
return this
|
||||
}
|
||||
|
||||
setHardwareAcceleration(hardwareAcceleration?: PrismaJson.HardwareAcceleration): this {
|
||||
if (hardwareAcceleration) {
|
||||
this.spec.hardwareAcceleration = hardwareAcceleration
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
withSprite(): this {
|
||||
this.spec.sprite = true
|
||||
return this
|
||||
|
||||
@@ -154,11 +154,13 @@ describe('transcodeVideoWorkflow', () => {
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
|
||||
expect(mockActivities.createAutofillTaskIfEnabledActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetKey: 'video.mp4',
|
||||
filePath: '/tmp/video.mp4',
|
||||
hardwareAcceleration: undefined,
|
||||
}),
|
||||
)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
@@ -166,6 +168,74 @@ describe('transcodeVideoWorkflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('should forward hardwareAcceleration to transcodeVideoActivity when specified', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-hw',
|
||||
assetId: 'asset-hw',
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'auto',
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-hw',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-hw',
|
||||
storageKey: { key: 'video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'video',
|
||||
metadata: {
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
startTimecode: '00:00:00:00',
|
||||
bitRate: 1000,
|
||||
videoBitRate: 850000,
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockResolvedValue({
|
||||
key: 'v.mp4',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
})
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetKey: 'video.mp4',
|
||||
filePath: '/tmp/video.mp4',
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 850000,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should run audio transcoding workflow successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-audio',
|
||||
|
||||
@@ -85,6 +85,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
videoSpec,
|
||||
duration: metadata.duration,
|
||||
originalFps: metadata.frameRate,
|
||||
hardwareAcceleration: spec.hardwareAcceleration,
|
||||
sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate,
|
||||
})
|
||||
|
||||
if (res === '180p') {
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('BreadcrumbNav component', () => {
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByTitle(/Linked Tasks|关联任务/i)).toBeDefined()
|
||||
expect(screen.getAllByTitle(/Linked Tasks|关联任务/i).length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('hides SquareKanban task link button on project root folder', () => {
|
||||
@@ -83,4 +83,44 @@ describe('BreadcrumbNav component', () => {
|
||||
|
||||
expect(screen.queryByTitle(/Linked Tasks|关联任务/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('renders mobile navigation menu button when not in public share mode', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav {...baseProps} isPublic={false} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Open navigation menu/i })).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders mobile breadcrumbs without All Projects and with project name', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav {...baseProps} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
// Project name is in mobile and desktop
|
||||
expect(screen.getAllByText('Demo Project').length).toBeGreaterThan(0)
|
||||
// Folder A is rendered
|
||||
expect(screen.getAllByText('Folder A').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('renders omitted middle folders button (...) for deep hierarchy on mobile', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav
|
||||
{...baseProps}
|
||||
ancestorFolders={[
|
||||
{ id: 'parent-1', name: 'Middle Folder 1' },
|
||||
{ id: 'parent-2', name: 'Middle Folder 2' },
|
||||
]}
|
||||
currentAsset={{ id: 'asset-deep', name: 'Deep Folder', type: 'folder' }}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Show omitted folders/i })).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -41,9 +41,11 @@ import {
|
||||
History,
|
||||
LayoutGrid,
|
||||
List,
|
||||
Menu,
|
||||
SquareKanban,
|
||||
} from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useDualSidebarStore } from '@/ui/stores/dual-sidebar'
|
||||
import { ManageVersionsDialog } from './manage-versions-dialog'
|
||||
import { AssetLinkedTasksDialog } from './kanban/asset-linked-tasks-dialog'
|
||||
|
||||
@@ -127,6 +129,7 @@ export function BreadcrumbNav({
|
||||
}: BreadcrumbNavProps) {
|
||||
const navigate = useNavigate()
|
||||
const { canEdit } = usePermissions(projectId)
|
||||
const { openMobileMenu } = useDualSidebarStore()
|
||||
const [isManageVersionsOpen, setIsManageVersionsOpen] = useState(false)
|
||||
const [isLinkedTasksOpen, setIsLinkedTasksOpen] = useState(false)
|
||||
|
||||
@@ -203,239 +206,360 @@ export function BreadcrumbNav({
|
||||
const isAudio = currentAsset.proxyType === 'audio'
|
||||
const hasVideoTranscodes = !isAudio && (downloadInfo?.videoTranscodes?.length ?? 0) > 0
|
||||
|
||||
const breadcrumbs: { name: string; path?: string; id?: string; isMuted?: boolean }[] = isPublic
|
||||
? [
|
||||
{
|
||||
name: projectName,
|
||||
id: 'root', // Special ID for share root
|
||||
},
|
||||
...ancestorFolders
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((folder) => ({
|
||||
name: folder.name || '',
|
||||
id: folder.id,
|
||||
})),
|
||||
]
|
||||
: [
|
||||
{ name: m.all_projects(), path: `/teams/${teamId}`, isMuted: true },
|
||||
{ name: projectName, path: `/projects/${projectId}` },
|
||||
...ancestorFolders
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((folder) => ({
|
||||
name: folder.name || '',
|
||||
path: `/projects/${projectId}/folders/${folder.id}`,
|
||||
})),
|
||||
]
|
||||
const hasTerminal = Boolean(customTerminalBreadcrumb || (!isRootFolder && !compareMode))
|
||||
|
||||
const mobileProjectItem = {
|
||||
name: projectName,
|
||||
path: isPublic ? undefined : `/projects/${projectId}`,
|
||||
id: 'root',
|
||||
}
|
||||
|
||||
const mobileAncestorItems = ancestorFolders
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((folder) => ({
|
||||
name: folder.name || '',
|
||||
path: isPublic ? undefined : `/projects/${projectId}/folders/${folder.id}`,
|
||||
id: folder.id,
|
||||
}))
|
||||
|
||||
const mobileMiddleItems = hasTerminal ? mobileAncestorItems : mobileAncestorItems.slice(0, -1)
|
||||
const mobileTerminalDirect =
|
||||
!hasTerminal && mobileAncestorItems.length > 0
|
||||
? mobileAncestorItems[mobileAncestorItems.length - 1]
|
||||
: null
|
||||
|
||||
const renderTerminal = () => {
|
||||
if (customTerminalBreadcrumb) {
|
||||
return (
|
||||
<span className="truncate rounded px-2 py-1 text-sm font-medium text-foreground">
|
||||
{customTerminalBreadcrumb}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (!isRootFolder && !compareMode) {
|
||||
if (currentAsset.type === 'folder') {
|
||||
return (
|
||||
<span className="truncate rounded px-2 py-1 text-sm font-medium text-foreground">
|
||||
{currentAsset.name}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger className="flex items-center gap-1 truncate rounded px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground">
|
||||
<span className="truncate">{currentAsset.name}</span>
|
||||
{currentAsset.version !== undefined && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-xs shrink-0">
|
||||
v{currentAsset.version}
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronDown className="h-4 w-4 shrink-0" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56" align="start">
|
||||
{allowDownload &&
|
||||
(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?.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 && onRename && (
|
||||
<DropdownMenuItem onClick={onRename}>{m.rename()}</DropdownMenuItem>
|
||||
)}
|
||||
{canEdit && onDelete && (
|
||||
<DropdownMenuItem
|
||||
onClick={onDelete}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{canCompareVersions && onCompareVersions && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => onCompareVersions()}>
|
||||
<Columns2 className="h-4 w-4" />
|
||||
<span>{m.compare_versions()}</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
{versions && versions.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="flex items-center gap-2">
|
||||
<History className="h-4 w-4" />
|
||||
<span>Versions</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent className="w-80 p-1">
|
||||
<div className="flex flex-col gap-1 max-h-96 overflow-y-auto">
|
||||
{versions.map((v) => {
|
||||
const isActive = currentAsset.version === v.version
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={v.id}
|
||||
onClick={() => handleVersionClick(v.id)}
|
||||
className="flex items-center gap-3 py-2 px-3 rounded-md cursor-pointer focus:bg-accent focus:text-accent-foreground"
|
||||
>
|
||||
<div className="flex-shrink-0 flex items-center justify-center bg-muted dark:bg-muted-foreground/20 text-muted-foreground dark:text-muted-foreground rounded-full px-2 py-0.5 text-xs font-semibold select-none min-w-[2rem]">
|
||||
v{v.version}
|
||||
</div>
|
||||
|
||||
<div className="h-10 w-16 flex-shrink-0 overflow-hidden rounded-md border border-border bg-muted flex items-center justify-center">
|
||||
{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 flex-col flex-1 min-w-0 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>
|
||||
|
||||
{isActive && (
|
||||
<Check className="h-4 w-4 text-primary ml-auto flex-shrink-0" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<DropdownMenuSeparator />
|
||||
<div className="p-1">
|
||||
<button
|
||||
className="w-full text-center text-xs font-medium py-2 px-3 rounded-md bg-muted/80 hover:bg-muted text-foreground transition-colors cursor-pointer"
|
||||
onClick={() => setIsManageVersionsOpen(true)}
|
||||
>
|
||||
{m.manage_versions()}
|
||||
</button>
|
||||
</div>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-14 flex-wrap items-center justify-between gap-2 border-b border-border bg-card px-4 py-2">
|
||||
<div className="flex min-w-0 flex-shrink items-center gap-1">
|
||||
{breadcrumbs.map((breadcrumb, index) => (
|
||||
<div key={index} className="flex items-center gap-1">
|
||||
{index > 0 && <span className="text-muted-foreground">/</span>}
|
||||
{breadcrumb.path ? (
|
||||
<Link
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
to={breadcrumb.path as any}
|
||||
className={cn(
|
||||
'truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground',
|
||||
breadcrumb.isMuted ? 'text-muted-foreground' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{breadcrumb.name}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => breadcrumb.id && onFolderClick?.(breadcrumb.id)}
|
||||
className="truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground text-foreground"
|
||||
>
|
||||
{breadcrumb.name}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{customTerminalBreadcrumb ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex h-14 flex-nowrap items-center justify-between gap-2 border-b border-border bg-card px-4 py-2 overflow-hidden">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden">
|
||||
{/* Mobile menu button */}
|
||||
{!isPublic && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => openMobileMenu()}
|
||||
className="md:hidden h-8 w-8 text-foreground hover:bg-accent shrink-0 -ml-2 mr-1"
|
||||
aria-label="Open navigation menu"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Desktop-only: All Projects */}
|
||||
{!isPublic && (
|
||||
<div className="hidden md:flex items-center gap-1 shrink-0">
|
||||
<Link
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
to={`/teams/${teamId}` as any}
|
||||
className="truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground text-muted-foreground"
|
||||
>
|
||||
{m.all_projects()}
|
||||
</Link>
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<span className="truncate rounded px-2 py-1 text-sm font-medium text-foreground">
|
||||
{customTerminalBreadcrumb}
|
||||
</span>
|
||||
</div>
|
||||
) : !isRootFolder && !compareMode ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-muted-foreground">/</span>
|
||||
{currentAsset.type === 'folder' ? (
|
||||
<span className="truncate rounded px-2 py-1 text-sm font-medium text-foreground">
|
||||
{currentAsset.name}
|
||||
</span>
|
||||
) : (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger className="flex items-center gap-1 truncate rounded px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground">
|
||||
<span>{currentAsset.name}</span>
|
||||
{currentAsset.version !== undefined && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-xs">
|
||||
v{currentAsset.version}
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
{allowDownload &&
|
||||
(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?.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}
|
||||
)}
|
||||
|
||||
{/* Project Name (Desktop & Mobile) */}
|
||||
{hasTerminal || ancestorFolders.length > 0 ? (
|
||||
mobileProjectItem.path ? (
|
||||
<Link
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
to={mobileProjectItem.path as any}
|
||||
className="min-w-0 max-w-[45%] md:max-w-none truncate rounded px-1.5 md:px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground shrink"
|
||||
>
|
||||
{mobileProjectItem.name}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => mobileProjectItem.id && onFolderClick?.(mobileProjectItem.id)}
|
||||
className="min-w-0 max-w-[45%] md:max-w-none truncate rounded px-1.5 md:px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground text-left shrink cursor-pointer"
|
||||
>
|
||||
{mobileProjectItem.name}
|
||||
</button>
|
||||
)
|
||||
) : (
|
||||
<span className="min-w-0 flex-1 truncate rounded px-1.5 md:px-2 py-1 text-sm font-medium text-foreground">
|
||||
{mobileProjectItem.name}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Mobile-only: Omitted Middle Ancestors (...) dropdown */}
|
||||
{mobileMiddleItems.length > 0 && (
|
||||
<div className="flex md:hidden items-center gap-1 shrink-0">
|
||||
<span className="text-muted-foreground shrink-0">/</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground text-sm font-medium px-1.5 py-0.5 rounded hover:bg-accent shrink-0 cursor-pointer"
|
||||
aria-label="Show omitted folders"
|
||||
>
|
||||
...
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
{mobileMiddleItems.map((item, idx) => (
|
||||
<DropdownMenuItem key={idx} asChild>
|
||||
{item.path ? (
|
||||
<Link
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
to={item.path as any}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{m.download()}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
{canEdit && onRename && (
|
||||
<DropdownMenuItem onClick={onRename}>{m.rename()}</DropdownMenuItem>
|
||||
)}
|
||||
{canEdit && onDelete && (
|
||||
<DropdownMenuItem
|
||||
onClick={onDelete}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{canCompareVersions && onCompareVersions && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => onCompareVersions()}>
|
||||
<Columns2 className="h-4 w-4" />
|
||||
<span>{m.compare_versions()}</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
{versions && versions.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="flex items-center gap-2">
|
||||
<History className="h-4 w-4" />
|
||||
<span>Versions</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent className="w-80 p-1">
|
||||
<div className="flex flex-col gap-1 max-h-96 overflow-y-auto">
|
||||
{versions.map((v) => {
|
||||
const isActive = currentAsset.version === v.version
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={v.id}
|
||||
onClick={() => handleVersionClick(v.id)}
|
||||
className="flex items-center gap-3 py-2 px-3 rounded-md cursor-pointer focus:bg-accent focus:text-accent-foreground"
|
||||
>
|
||||
<div className="flex-shrink-0 flex items-center justify-center bg-muted dark:bg-muted-foreground/20 text-muted-foreground dark:text-muted-foreground rounded-full px-2 py-0.5 text-xs font-semibold select-none min-w-[2rem]">
|
||||
v{v.version}
|
||||
</div>
|
||||
|
||||
<div className="h-10 w-16 flex-shrink-0 overflow-hidden rounded-md border border-border bg-muted flex items-center justify-center">
|
||||
{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 flex-col flex-1 min-w-0 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>
|
||||
|
||||
{isActive && (
|
||||
<Check className="h-4 w-4 text-primary ml-auto flex-shrink-0" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<DropdownMenuSeparator />
|
||||
<div className="p-1">
|
||||
<button
|
||||
className="w-full text-center text-xs font-medium py-2 px-3 rounded-md bg-muted/80 hover:bg-muted text-foreground transition-colors cursor-pointer"
|
||||
onClick={() => setIsManageVersionsOpen(true)}
|
||||
>
|
||||
{m.manage_versions()}
|
||||
</button>
|
||||
</div>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
{item.name}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => item.id && onFolderClick?.(item.id)}
|
||||
className="cursor-pointer w-full text-left"
|
||||
>
|
||||
{item.name}
|
||||
</button>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<span className="text-muted-foreground shrink-0">/</span>
|
||||
</div>
|
||||
) : null}
|
||||
)}
|
||||
|
||||
{/* Desktop-only: All Ancestor Folders */}
|
||||
{ancestorFolders
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((folder) => {
|
||||
const path = isPublic ? undefined : `/projects/${projectId}/folders/${folder.id}`
|
||||
return (
|
||||
<div key={folder.id} className="hidden md:flex items-center gap-1">
|
||||
<span className="text-muted-foreground">/</span>
|
||||
{path ? (
|
||||
<Link
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
to={path as any}
|
||||
className="truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground text-foreground"
|
||||
>
|
||||
{folder.name}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => folder.id && onFolderClick?.(folder.id)}
|
||||
className="truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground text-foreground"
|
||||
>
|
||||
{folder.name}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Terminal Item (Desktop & Mobile) */}
|
||||
{(hasTerminal || (!hasTerminal && ancestorFolders.length > 0)) && (
|
||||
<div className="flex items-center gap-1 min-w-0 shrink overflow-hidden">
|
||||
<span
|
||||
className={cn(
|
||||
'text-muted-foreground shrink-0',
|
||||
mobileMiddleItems.length > 0 ? 'hidden md:inline' : 'inline',
|
||||
)}
|
||||
>
|
||||
/
|
||||
</span>
|
||||
{hasTerminal
|
||||
? renderTerminal()
|
||||
: mobileTerminalDirect && (
|
||||
<span className="min-w-0 truncate rounded px-2 py-1 text-sm font-medium text-foreground">
|
||||
{mobileTerminalDirect.name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Linked Tasks */}
|
||||
{showKanbanLink && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs gap-1.5 text-muted-foreground hover:text-foreground hover:bg-muted ml-1 cursor-pointer"
|
||||
className="h-7 px-2 text-xs gap-1.5 text-muted-foreground hover:text-foreground hover:bg-muted ml-1 cursor-pointer shrink-0"
|
||||
onClick={() => setIsLinkedTasksOpen(true)}
|
||||
title={m.linked_tasks()}
|
||||
>
|
||||
@@ -447,53 +571,53 @@ export function BreadcrumbNav({
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{showKanbanLink && isLinkedTasksOpen && targetAssetId && (
|
||||
<AssetLinkedTasksDialog
|
||||
teamId={teamId}
|
||||
assetId={targetAssetId}
|
||||
assetName={currentAsset.name}
|
||||
isOpen={isLinkedTasksOpen}
|
||||
onClose={() => setIsLinkedTasksOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fileId && versions && versions.length > 0 && (
|
||||
<ManageVersionsDialog
|
||||
open={isManageVersionsOpen}
|
||||
onOpenChange={setIsManageVersionsOpen}
|
||||
stackId={fileId}
|
||||
canEdit={canEdit}
|
||||
onStackDissolved={(remainingFileId) => {
|
||||
setIsManageVersionsOpen(false)
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId: remainingFileId },
|
||||
})
|
||||
}}
|
||||
onVersionRemoved={(removedVersionId, remainingVersions) => {
|
||||
const currentVersionId = currentAsset.version
|
||||
? versions.find((v) => v.version === currentAsset.version)?.id
|
||||
: undefined
|
||||
if (currentVersionId === removedVersionId) {
|
||||
const topVersion = remainingVersions[0]
|
||||
if (topVersion) {
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (prev: Record<string, unknown>) => ({
|
||||
...prev,
|
||||
version: topVersion.id,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{showKanbanLink && isLinkedTasksOpen && targetAssetId && (
|
||||
<AssetLinkedTasksDialog
|
||||
teamId={teamId}
|
||||
assetId={targetAssetId}
|
||||
assetName={currentAsset.name}
|
||||
isOpen={isLinkedTasksOpen}
|
||||
onClose={() => setIsLinkedTasksOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fileId && versions && versions.length > 0 && (
|
||||
<ManageVersionsDialog
|
||||
open={isManageVersionsOpen}
|
||||
onOpenChange={setIsManageVersionsOpen}
|
||||
stackId={fileId}
|
||||
canEdit={canEdit}
|
||||
onStackDissolved={(remainingFileId) => {
|
||||
setIsManageVersionsOpen(false)
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId: remainingFileId },
|
||||
})
|
||||
}}
|
||||
onVersionRemoved={(removedVersionId, remainingVersions) => {
|
||||
const currentVersionId = currentAsset.version
|
||||
? versions.find((v) => v.version === currentAsset.version)?.id
|
||||
: undefined
|
||||
if (currentVersionId === removedVersionId) {
|
||||
const topVersion = remainingVersions[0]
|
||||
if (topVersion) {
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (prev: Record<string, unknown>) => ({
|
||||
...prev,
|
||||
version: topVersion.id,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="hidden md:flex items-center gap-2">
|
||||
<div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1">
|
||||
{/* Left Sidebar Toggle */}
|
||||
{!fileId && !isPublic && onLeftSidebarToggle && (
|
||||
|
||||
@@ -228,11 +228,12 @@ export function CompareViewer({
|
||||
)
|
||||
|
||||
const handleToggleFullScreen = useCallback(() => {
|
||||
if (!rootRef.current) return
|
||||
const el = rootRef.current
|
||||
if (!el || typeof el.requestFullscreen !== 'function') return
|
||||
if (!document.fullscreenElement) {
|
||||
rootRef.current.requestFullscreen()
|
||||
} else {
|
||||
document.exitFullscreen()
|
||||
el.requestFullscreen().catch(() => {})
|
||||
} else if (document.exitFullscreen) {
|
||||
document.exitFullscreen().catch(() => {})
|
||||
}
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { DualSidebar, DualSidebarItem } from './dual-sidebar'
|
||||
import { useDualSidebarStore } from '@/ui/stores/dual-sidebar'
|
||||
|
||||
vi.mock('@tanstack/react-router', () => ({
|
||||
useRouterState: () => '/projects/proj-1',
|
||||
}))
|
||||
|
||||
vi.mock('./user-menu', () => ({
|
||||
UserMenu: () => <div data-testid="user-menu">User</div>,
|
||||
}))
|
||||
|
||||
describe('DualSidebar component', () => {
|
||||
beforeEach(() => {
|
||||
useDualSidebarStore.setState({
|
||||
isMobileMenuOpen: false,
|
||||
activeItem: null,
|
||||
activeItemId: null,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders Level 1 icons and UserMenu', () => {
|
||||
render(
|
||||
<DualSidebar>
|
||||
<DualSidebarItem icon={<span>HomeIcon</span>} label="Home" />
|
||||
<DualSidebarItem icon={<span>NotifIcon</span>} label="Notifications">
|
||||
<div>Notification List</div>
|
||||
</DualSidebarItem>
|
||||
</DualSidebar>,
|
||||
)
|
||||
|
||||
expect(screen.getByLabelText('Home')).toBeDefined()
|
||||
expect(screen.getByLabelText('Notifications')).toBeDefined()
|
||||
expect(screen.getByTestId('user-menu')).toBeDefined()
|
||||
})
|
||||
|
||||
it('displays defaultMobileContent when mobile menu is open and no active item is selected', () => {
|
||||
useDualSidebarStore.setState({ isMobileMenuOpen: true })
|
||||
|
||||
render(
|
||||
<DualSidebar
|
||||
defaultMobileContent={{
|
||||
label: 'Project Folders',
|
||||
children: <div>Folder Tree Content</div>,
|
||||
}}
|
||||
>
|
||||
<DualSidebarItem icon={<span>HomeIcon</span>} label="Home" />
|
||||
<DualSidebarItem icon={<span>NotifIcon</span>} label="Notifications">
|
||||
<div>Notification List</div>
|
||||
</DualSidebarItem>
|
||||
</DualSidebar>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Project Folders')).toBeDefined()
|
||||
expect(screen.getByText('Folder Tree Content')).toBeDefined()
|
||||
})
|
||||
|
||||
it('switches to child item content when a Level 1 icon is clicked', () => {
|
||||
useDualSidebarStore.setState({ isMobileMenuOpen: true })
|
||||
|
||||
render(
|
||||
<DualSidebar
|
||||
defaultMobileContent={{
|
||||
label: 'Project Folders',
|
||||
children: <div>Folder Tree Content</div>,
|
||||
}}
|
||||
>
|
||||
<DualSidebarItem icon={<span>HomeIcon</span>} label="Home" />
|
||||
<DualSidebarItem icon={<span>NotifIcon</span>} label="Notifications">
|
||||
<div>Notification List</div>
|
||||
</DualSidebarItem>
|
||||
</DualSidebar>,
|
||||
)
|
||||
|
||||
const notifBtn = screen.getByLabelText('Notifications')
|
||||
act(() => {
|
||||
fireEvent.click(notifBtn)
|
||||
})
|
||||
|
||||
expect(screen.getByText('Notification List')).toBeDefined()
|
||||
})
|
||||
|
||||
it('closes mobile menu when close (X) button is clicked', () => {
|
||||
useDualSidebarStore.setState({ isMobileMenuOpen: true })
|
||||
|
||||
render(
|
||||
<DualSidebar
|
||||
defaultMobileContent={{
|
||||
label: 'Project Folders',
|
||||
children: <div>Folder Tree Content</div>,
|
||||
}}
|
||||
>
|
||||
<DualSidebarItem icon={<span>HomeIcon</span>} label="Home" />
|
||||
</DualSidebar>,
|
||||
)
|
||||
|
||||
const closeButton = screen.getByRole('button', { name: /Close navigation menu/i })
|
||||
act(() => {
|
||||
fireEvent.click(closeButton)
|
||||
})
|
||||
|
||||
expect(useDualSidebarStore.getState().isMobileMenuOpen).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,14 @@
|
||||
import { Menu } from 'lucide-react'
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import { Menu, X } from 'lucide-react'
|
||||
import React, { useEffect, useMemo } from 'react'
|
||||
import { useRouterState } from '@tanstack/react-router'
|
||||
import { useDualSidebarStore } from '@/ui/stores/dual-sidebar'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { Button } from './ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip'
|
||||
import { UserMenu } from './user-menu'
|
||||
|
||||
interface DualSidebarItemProps {
|
||||
export interface DualSidebarItemProps {
|
||||
id?: string
|
||||
icon: React.ReactNode
|
||||
label: string
|
||||
badge?: React.ReactNode
|
||||
@@ -20,11 +24,22 @@ export const DualSidebarItem: React.FC<DualSidebarItemProps> = () => {
|
||||
|
||||
interface DualSidebarProps {
|
||||
children: React.ReactNode
|
||||
hideMobileButton?: boolean
|
||||
defaultMobileContent?: {
|
||||
label: string
|
||||
children: React.ReactNode
|
||||
}
|
||||
}
|
||||
|
||||
export const DualSidebar: React.FC<DualSidebarProps> = ({ children }) => {
|
||||
const [activeItem, setActiveItem] = useState<number | null>(null)
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
|
||||
export const DualSidebar: React.FC<DualSidebarProps> = ({
|
||||
children,
|
||||
hideMobileButton = false,
|
||||
defaultMobileContent,
|
||||
}) => {
|
||||
const { isMobileMenuOpen, activeItem, setActiveItem, toggleMobileMenu, closeMobileMenu } =
|
||||
useDualSidebarStore()
|
||||
|
||||
const pathname = useRouterState({ select: (s) => s.location.pathname })
|
||||
|
||||
const sidebarItems = useMemo(
|
||||
() =>
|
||||
@@ -35,7 +50,19 @@ export const DualSidebar: React.FC<DualSidebarProps> = ({ children }) => {
|
||||
[children],
|
||||
)
|
||||
|
||||
const prevPathnameRef = React.useRef(pathname)
|
||||
|
||||
// Automatically close mobile menu when navigating to another route
|
||||
useEffect(() => {
|
||||
if (prevPathnameRef.current !== pathname) {
|
||||
prevPathnameRef.current = pathname
|
||||
closeMobileMenu()
|
||||
}
|
||||
}, [pathname, closeMobileMenu])
|
||||
|
||||
const activeItemContent = activeItem !== null ? sidebarItems[activeItem]?.props : null
|
||||
const displayContent = activeItemContent ?? (isMobileMenuOpen ? defaultMobileContent : null)
|
||||
const isLevel2Open = Boolean(activeItemContent || (isMobileMenuOpen && defaultMobileContent))
|
||||
|
||||
const handleItemClick = (index: number) => {
|
||||
const item = sidebarItems[index]
|
||||
@@ -46,39 +73,31 @@ export const DualSidebar: React.FC<DualSidebarProps> = ({ children }) => {
|
||||
return
|
||||
}
|
||||
|
||||
setActiveItem((prev) => {
|
||||
if (prev === index) {
|
||||
return null
|
||||
}
|
||||
if (activeItem === index) {
|
||||
setActiveItem(null)
|
||||
} else {
|
||||
if (item && item.props.onItemClick) {
|
||||
item.props.onItemClick()
|
||||
}
|
||||
return index
|
||||
})
|
||||
}
|
||||
|
||||
const toggleMobileMenu = () => {
|
||||
setIsMobileMenuOpen((prev) => !prev)
|
||||
}
|
||||
|
||||
const closeMobileMenu = () => {
|
||||
setIsMobileMenuOpen(false)
|
||||
setActiveItem(null)
|
||||
setActiveItem(index)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile Hamburger Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleMobileMenu}
|
||||
className="md:hidden fixed top-4 left-4 z-50 rounded-md bg-sidebar/50 backdrop-blur-sm text-sidebar-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring"
|
||||
aria-label="Open navigation menu"
|
||||
aria-expanded={isMobileMenuOpen}
|
||||
>
|
||||
<Menu />
|
||||
</Button>
|
||||
{/* Mobile Hamburger Button (Optional if header provides its own menu button) */}
|
||||
{!hideMobileButton && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleMobileMenu}
|
||||
className="md:hidden fixed top-4 left-4 z-50 rounded-md bg-sidebar/50 backdrop-blur-sm text-sidebar-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring"
|
||||
aria-label="Open navigation menu"
|
||||
aria-expanded={isMobileMenuOpen}
|
||||
>
|
||||
<Menu />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Mobile Overlay */}
|
||||
{isMobileMenuOpen && (
|
||||
@@ -142,19 +161,30 @@ export const DualSidebar: React.FC<DualSidebarProps> = ({ children }) => {
|
||||
|
||||
{/* Level 2: Content Panel */}
|
||||
<div
|
||||
className={`transition-all duration-300 ease-in-out bg-sidebar/95 backdrop-blur-sm shadow-lg overflow-hidden ${
|
||||
activeItem !== null
|
||||
? 'w-[calc(100vw-4rem)] md:w-100 border-r border-sidebar-border'
|
||||
: 'w-0'
|
||||
}`}
|
||||
className={cn(
|
||||
'transition-all duration-300 ease-in-out bg-sidebar/95 backdrop-blur-sm shadow-lg overflow-hidden',
|
||||
isLevel2Open ? 'w-[calc(100vw-4rem)] border-r border-sidebar-border' : 'w-0',
|
||||
activeItemContent
|
||||
? 'md:w-100 md:border-r md:border-sidebar-border'
|
||||
: 'md:w-0 md:border-r-0',
|
||||
)}
|
||||
>
|
||||
<div className="w-[calc(100vw-4rem)] md:w-100 h-full flex flex-col">
|
||||
{activeItemContent && (
|
||||
{displayContent && (
|
||||
<>
|
||||
<header className="h-16 flex items-center px-4 font-bold text-lg border-b border-sidebar-border flex-shrink-0">
|
||||
<h2>{activeItemContent.label}</h2>
|
||||
<header className="h-16 flex items-center justify-between px-4 font-bold text-lg border-b border-sidebar-border flex-shrink-0">
|
||||
<h2 className="truncate">{displayContent.label}</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={closeMobileMenu}
|
||||
className="h-8 w-8 text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
aria-label="Close navigation menu"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</Button>
|
||||
</header>
|
||||
<div className="flex-1 overflow-y-auto p-2">{activeItemContent.children}</div>
|
||||
<div className="flex-1 overflow-y-auto p-2">{displayContent.children}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
AssetInfo,
|
||||
CollectionInfo,
|
||||
CreateUploadTaskRequest,
|
||||
PresignedUrl,
|
||||
SearchCondition,
|
||||
SearchSort,
|
||||
ShareLinkInfo,
|
||||
@@ -558,9 +559,7 @@ export function FileBrowser({
|
||||
queryKey: ['teams', teamId, 'upload', 'tasks'],
|
||||
})
|
||||
|
||||
// The RPC client returns an object that we cast to the expected type
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await uploadFiles(currentFiles, data.presignedUrls as any, data.taskId!)
|
||||
await uploadFiles(currentFiles, data.presignedUrls, data.taskId!)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
@@ -731,14 +730,11 @@ export function FileBrowser({
|
||||
|
||||
const uploadFiles = async (
|
||||
files: FileWithId[],
|
||||
presignedUrls: { id?: string; url?: string; fileId?: string }[],
|
||||
presignedUrls: PresignedUrl[] | undefined,
|
||||
taskId: string,
|
||||
) => {
|
||||
const uploadUrlMap = presignedUrls?.reduce(
|
||||
(
|
||||
acc: Record<string, { url: string; fileId: string }>,
|
||||
item: { id?: string; url?: string; fileId?: string },
|
||||
) => {
|
||||
(acc: Record<string, { url: string; fileId: string }>, item: PresignedUrl) => {
|
||||
if (item.id) {
|
||||
acc[item.id] = {
|
||||
url: item.url || '',
|
||||
|
||||
@@ -305,7 +305,7 @@ export function FileCard({
|
||||
onBlur={handleRename}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={!isEditing}
|
||||
className="h-auto p-0 text-sm text-foreground !bg-transparent"
|
||||
className="h-auto p-0 text-sm font-medium text-foreground truncate !bg-transparent"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{displayItem.createdAt &&
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { FileListItem } from './file-list-item'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
|
||||
vi.mock('@dnd-kit/react', () => ({
|
||||
useDraggable: () => ({
|
||||
ref: vi.fn(),
|
||||
isDragging: false,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
files: {
|
||||
':fileId': {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('FileListItem', () => {
|
||||
let queryClient: QueryClient
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
vi.useRealTimers()
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const mockItem: AssetInfo = {
|
||||
id: 'file-123',
|
||||
name: 'very_long_file_name_for_testing_purposes.mov',
|
||||
type: 'file',
|
||||
sizeByte: 1024 * 1024 * 5,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
status: 'processed',
|
||||
} as AssetInfo
|
||||
|
||||
const renderComponent = (props: Partial<React.ComponentProps<typeof FileListItem>> = {}) => {
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<FileListItem
|
||||
item={mockItem}
|
||||
isSelected={false}
|
||||
isChecked={false}
|
||||
isEditing={false}
|
||||
onSelect={vi.fn()}
|
||||
onDoubleClick={vi.fn()}
|
||||
onContextMenu={vi.fn()}
|
||||
onDragStart={vi.fn()}
|
||||
onDrop={vi.fn()}
|
||||
onRename={vi.fn()}
|
||||
onFinishEditing={vi.fn()}
|
||||
onSaveField={vi.fn()}
|
||||
fields={[]}
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
it('renders truncated text span when not editing', () => {
|
||||
renderComponent()
|
||||
|
||||
expect(screen.queryByRole('textbox')).toBeNull()
|
||||
const nameSpan = screen.getByText('very_long_file_name_for_testing_purposes.mov')
|
||||
expect(nameSpan).toBeTruthy()
|
||||
expect(nameSpan.tagName.toLowerCase()).toBe('span')
|
||||
expect(nameSpan.className).toContain('truncate')
|
||||
})
|
||||
|
||||
it('shows tooltip on hover when item name overflows', () => {
|
||||
renderComponent()
|
||||
|
||||
const span = screen.getByText('very_long_file_name_for_testing_purposes.mov')
|
||||
Object.defineProperty(span, 'scrollWidth', { value: 350, configurable: true })
|
||||
Object.defineProperty(span, 'clientWidth', { value: 150, configurable: true })
|
||||
|
||||
fireEvent.pointerMove(span, { pointerType: 'mouse' })
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
const tooltip = screen.getByRole('tooltip')
|
||||
expect(tooltip).toBeTruthy()
|
||||
expect(tooltip.textContent).toContain('very_long_file_name_for_testing_purposes.mov')
|
||||
})
|
||||
|
||||
it('switches to input in editing mode', () => {
|
||||
renderComponent({ isEditing: true })
|
||||
|
||||
const input = screen.getByRole('textbox') as HTMLInputElement
|
||||
expect(input).toBeTruthy()
|
||||
expect(input.value).toBe('very_long_file_name_for_testing_purposes.mov')
|
||||
})
|
||||
|
||||
it('calls onSelect when row is clicked', () => {
|
||||
const onSelect = vi.fn()
|
||||
renderComponent({ onSelect })
|
||||
|
||||
const span = screen.getByText('very_long_file_name_for_testing_purposes.mov')
|
||||
fireEvent.click(span)
|
||||
|
||||
expect(onSelect).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onDoubleClick when row is double clicked', () => {
|
||||
const onDoubleClick = vi.fn()
|
||||
renderComponent({ onDoubleClick })
|
||||
|
||||
const span = screen.getByText('very_long_file_name_for_testing_purposes.mov')
|
||||
fireEvent.doubleClick(span)
|
||||
|
||||
expect(onDoubleClick).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -235,7 +235,7 @@ export function FileListItem({
|
||||
onBlur={handleRename}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={!isEditing}
|
||||
className="h-auto p-0 text-sm font-medium text-foreground truncate"
|
||||
className="h-auto p-0 text-sm font-medium text-foreground truncate min-w-0 flex-1"
|
||||
/>
|
||||
{displayItem.status === 'error' && (
|
||||
<span className="text-xs text-destructive font-semibold shrink-0">
|
||||
|
||||
@@ -277,7 +277,7 @@ export function FolderCard({
|
||||
: undefined
|
||||
}
|
||||
className={cn(
|
||||
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full outline-none focus:outline-none focus-visible:outline-none',
|
||||
'group relative w-full md:max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full outline-none focus:outline-none focus-visible:outline-none',
|
||||
)}
|
||||
>
|
||||
<div className="absolute inset-0 z-10 pointer-events-none">
|
||||
@@ -344,8 +344,7 @@ export function FolderCard({
|
||||
onBlur={handleRename}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={!isEditing}
|
||||
className="font-semibold text-foreground text-lg leading-tight truncate h-auto p-0 !bg-transparent"
|
||||
title={name}
|
||||
className="h-auto p-0 text-sm font-medium text-foreground truncate !bg-transparent"
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between text-muted-foreground">
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MobileFileBrowser } from './mobile-file-browser'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
|
||||
vi.mock('@dnd-kit/react', () => ({
|
||||
useDraggable: () => ({
|
||||
ref: vi.fn(),
|
||||
isDragging: false,
|
||||
}),
|
||||
useDroppable: () => ({
|
||||
ref: vi.fn(),
|
||||
isOver: false,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/hooks/use-permissions', () => ({
|
||||
usePermissions: () => ({
|
||||
canEdit: true,
|
||||
canAdmin: true,
|
||||
canView: true,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
files: {
|
||||
$delete: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
'download-links': {
|
||||
$post: vi.fn().mockResolvedValue({ ok: true, json: async () => ({ files: [] }) }),
|
||||
},
|
||||
restore: {
|
||||
$post: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
},
|
||||
':fileId': {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
}),
|
||||
$put: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
folders: {
|
||||
$post: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'new-folder-id' }),
|
||||
}),
|
||||
$delete: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
restore: {
|
||||
$post: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
},
|
||||
':folderId': {
|
||||
$put: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
':teamId': {
|
||||
upload: {
|
||||
tasks: {
|
||||
$post: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
':taskId': {
|
||||
$patch: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
projects: {
|
||||
':projectId': {
|
||||
'empty-trash': {
|
||||
$post: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('MobileFileBrowser', () => {
|
||||
let queryClient: QueryClient
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const mockFolder: AssetInfo = {
|
||||
id: 'folder-1',
|
||||
name: 'Test Folder',
|
||||
type: 'folder',
|
||||
fileCount: 3,
|
||||
sizeByte: 0,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
status: 'processed',
|
||||
} as AssetInfo
|
||||
|
||||
const mockFile: AssetInfo = {
|
||||
id: 'file-1',
|
||||
name: 'test_document.pdf',
|
||||
type: 'file',
|
||||
sizeByte: 1024 * 100,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
status: 'processed',
|
||||
} as AssetInfo
|
||||
|
||||
const defaultProps = {
|
||||
teamId: 'team-1',
|
||||
projectId: 'project-1',
|
||||
assetId: 'root-folder',
|
||||
folders: [mockFolder],
|
||||
files: [mockFile],
|
||||
selectedItem: null,
|
||||
selectedIds: new Set<string>(),
|
||||
onItemSelect: vi.fn(),
|
||||
onItemDoubleClick: vi.fn(),
|
||||
onClearSelection: vi.fn(),
|
||||
fetchNextFoldersPage: vi.fn(),
|
||||
hasNextFoldersPage: false,
|
||||
isFetchingNextFoldersPage: false,
|
||||
fetchNextFilesPage: vi.fn(),
|
||||
hasNextFilesPage: false,
|
||||
isFetchingNextFilesPage: false,
|
||||
}
|
||||
|
||||
const renderComponent = (props: Partial<React.ComponentProps<typeof MobileFileBrowser>> = {}) => {
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MobileFileBrowser {...defaultProps} {...props} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
it('renders folders and files in mobile grid', () => {
|
||||
renderComponent()
|
||||
|
||||
expect(screen.getByText('Test Folder')).toBeDefined()
|
||||
expect(screen.getByText('test_document.pdf')).toBeDefined()
|
||||
})
|
||||
|
||||
it('triggers onItemSelect when an item is clicked', () => {
|
||||
const onItemSelect = vi.fn()
|
||||
renderComponent({ onItemSelect })
|
||||
|
||||
const folderElement = screen.getByText('Test Folder')
|
||||
fireEvent.click(folderElement)
|
||||
|
||||
expect(onItemSelect).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('triggers onItemDoubleClick when an item is double-clicked', () => {
|
||||
const onItemDoubleClick = vi.fn()
|
||||
renderComponent({ onItemDoubleClick })
|
||||
|
||||
const folderElement = screen.getByText('Test Folder')
|
||||
fireEvent.doubleClick(folderElement)
|
||||
|
||||
expect(onItemDoubleClick).toHaveBeenCalledWith(mockFolder)
|
||||
})
|
||||
|
||||
it('renders empty state when there are no folders and files', () => {
|
||||
renderComponent({ folders: [], files: [] })
|
||||
|
||||
expect(screen.getByText(/This folder is empty|此文件夹为空/i)).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders collapsible section headers for folders and files with count and size', () => {
|
||||
renderComponent({
|
||||
totalFoldersSize: 50000,
|
||||
totalFilesSize: 100000,
|
||||
})
|
||||
|
||||
expect(screen.getByText(/1 Folder • 50 KB/i)).toBeDefined()
|
||||
expect(screen.getByText(/1 Asset • 100 KB/i)).toBeDefined()
|
||||
})
|
||||
|
||||
it('collapses and expands folders and files when clicking section headers', () => {
|
||||
renderComponent()
|
||||
|
||||
expect(screen.getByText('Test Folder')).toBeDefined()
|
||||
expect(screen.getByText('test_document.pdf')).toBeDefined()
|
||||
|
||||
// Collapse folders
|
||||
const folderHeaderBtn = screen.getByRole('button', { name: /Folder/i })
|
||||
fireEvent.click(folderHeaderBtn)
|
||||
|
||||
expect(screen.queryByText('Test Folder')).toBeNull()
|
||||
|
||||
// Expand folders back
|
||||
fireEvent.click(folderHeaderBtn)
|
||||
expect(screen.getByText('Test Folder')).toBeDefined()
|
||||
|
||||
// Collapse files
|
||||
const fileHeaderBtn = screen.getByRole('button', { name: /Asset/i })
|
||||
fireEvent.click(fileHeaderBtn)
|
||||
|
||||
expect(screen.queryByText('test_document.pdf')).toBeNull()
|
||||
|
||||
// Expand files back
|
||||
fireEvent.click(fileHeaderBtn)
|
||||
expect(screen.getByText('test_document.pdf')).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders Floating Action Button when canEdit is true', () => {
|
||||
renderComponent()
|
||||
|
||||
expect(screen.getByRole('button', { name: /actions/i })).toBeDefined()
|
||||
})
|
||||
|
||||
it('completes upload and confirms upload on 2xx response', async () => {
|
||||
const originalXhr = window.XMLHttpRequest
|
||||
const patchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) })
|
||||
|
||||
const { client } = await import('@/ui/api/client')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].upload.tasks as any)['$post'] = vi
|
||||
.fn()
|
||||
.mockImplementation(async (req) => {
|
||||
const json = req.json
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
taskId: 'task-1',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
presignedUrls: json.files.map((f: any) => ({
|
||||
id: f.id,
|
||||
url: 'https://upload.example.com',
|
||||
fileId: 'server-file-1',
|
||||
})),
|
||||
}),
|
||||
}
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].upload.tasks[':taskId'] as any)['$patch'] = patchMock
|
||||
|
||||
class MockXhr {
|
||||
open = vi.fn()
|
||||
setRequestHeader = vi.fn()
|
||||
send = vi.fn(() => {
|
||||
this.status = 200
|
||||
this.onload?.()
|
||||
})
|
||||
status = 200
|
||||
upload = { onprogress: null as unknown }
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
onabort: (() => void) | null = null
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
window.XMLHttpRequest = MockXhr as any
|
||||
|
||||
const { container } = renderComponent()
|
||||
const fileInput = container.querySelector(
|
||||
'input[type="file"]:not([webkitdirectory])',
|
||||
) as HTMLInputElement
|
||||
expect(fileInput).toBeDefined()
|
||||
|
||||
const testFile = new File(['content'], 'hello.txt', { type: 'text/plain' })
|
||||
fireEvent.change(fileInput, { target: { files: [testFile] } })
|
||||
|
||||
// Wait for mutation to finish
|
||||
await vi.waitFor(() => {
|
||||
expect(patchMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { teamId: 'team-1', taskId: 'task-1' },
|
||||
json: { fileId: 'server-file-1' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
window.XMLHttpRequest = originalXhr
|
||||
})
|
||||
|
||||
it('fails upload and confirms with error on non-2xx status', async () => {
|
||||
const originalXhr = window.XMLHttpRequest
|
||||
const patchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) })
|
||||
|
||||
const { client } = await import('@/ui/api/client')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].upload.tasks as any)['$post'] = vi
|
||||
.fn()
|
||||
.mockImplementation(async (req) => {
|
||||
const json = req.json
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
taskId: 'task-2',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
presignedUrls: json.files.map((f: any) => ({
|
||||
id: f.id,
|
||||
url: 'https://upload.example.com',
|
||||
fileId: 'server-file-2',
|
||||
})),
|
||||
}),
|
||||
}
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].upload.tasks[':taskId'] as any)['$patch'] = patchMock
|
||||
|
||||
class MockXhr500 {
|
||||
open = vi.fn()
|
||||
setRequestHeader = vi.fn()
|
||||
send = vi.fn(() => {
|
||||
this.status = 500
|
||||
this.onload?.()
|
||||
})
|
||||
status = 500
|
||||
upload = { onprogress: null as unknown }
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
onabort: (() => void) | null = null
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
window.XMLHttpRequest = MockXhr500 as any
|
||||
|
||||
const { container } = renderComponent()
|
||||
const fileInput = container.querySelector(
|
||||
'input[type="file"]:not([webkitdirectory])',
|
||||
) as HTMLInputElement
|
||||
|
||||
const testFile = new File(['content'], 'error.txt', { type: 'text/plain' })
|
||||
fireEvent.change(fileInput, { target: { files: [testFile] } })
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(patchMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { teamId: 'team-1', taskId: 'task-2' },
|
||||
json: {
|
||||
fileId: 'server-file-2',
|
||||
errorMessage: 'upload failed with status: 500',
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
window.XMLHttpRequest = originalXhr
|
||||
})
|
||||
|
||||
it('fails upload and confirms with error on network failure', async () => {
|
||||
const originalXhr = window.XMLHttpRequest
|
||||
const patchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) })
|
||||
|
||||
const { client } = await import('@/ui/api/client')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].upload.tasks as any)['$post'] = vi
|
||||
.fn()
|
||||
.mockImplementation(async (req) => {
|
||||
const json = req.json
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
taskId: 'task-3',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
presignedUrls: json.files.map((f: any) => ({
|
||||
id: f.id,
|
||||
url: 'https://upload.example.com',
|
||||
fileId: 'server-file-3',
|
||||
})),
|
||||
}),
|
||||
}
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].upload.tasks[':taskId'] as any)['$patch'] = patchMock
|
||||
|
||||
class MockXhrError {
|
||||
open = vi.fn()
|
||||
setRequestHeader = vi.fn()
|
||||
send = vi.fn(() => {
|
||||
this.onerror?.()
|
||||
})
|
||||
status = 0
|
||||
upload = { onprogress: null as unknown }
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
onabort: (() => void) | null = null
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
window.XMLHttpRequest = MockXhrError as any
|
||||
|
||||
const { container } = renderComponent()
|
||||
const fileInput = container.querySelector(
|
||||
'input[type="file"]:not([webkitdirectory])',
|
||||
) as HTMLInputElement
|
||||
|
||||
const testFile = new File(['content'], 'network-error.txt', { type: 'text/plain' })
|
||||
fireEvent.change(fileInput, { target: { files: [testFile] } })
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(patchMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { teamId: 'team-1', taskId: 'task-3' },
|
||||
json: {
|
||||
fileId: 'server-file-3',
|
||||
errorMessage: 'upload failed with error: Network error',
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
window.XMLHttpRequest = originalXhr
|
||||
})
|
||||
|
||||
it('hides Floating Action Button in public share mode', () => {
|
||||
renderComponent({ isPublic: true })
|
||||
|
||||
expect(screen.queryByRole('button', { name: /actions/i })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,831 @@
|
||||
'use client'
|
||||
|
||||
import { client } from '@/ui/api/client'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import type { AssetInfo, CreateUploadTaskRequest, PresignedUrl } from '@shumai/dtos'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import {
|
||||
AlertTriangle,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Download,
|
||||
FolderClock,
|
||||
FolderPlus,
|
||||
Loader2,
|
||||
Plus,
|
||||
Upload,
|
||||
} from 'lucide-react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
import { ulid } from 'ulid'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '../ui/alert-dialog'
|
||||
import { Button } from '../ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '../ui/dialog'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '../ui/dropdown-menu'
|
||||
import { Input } from '../ui/input'
|
||||
import { FileCard } from './file-card'
|
||||
import { FolderCard } from './folder-card'
|
||||
import { useFileActions } from './use-file-actions'
|
||||
|
||||
export interface MobileFileBrowserProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
assetId: string
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
totalFolders?: number
|
||||
totalFiles?: number
|
||||
totalFoldersSize?: number
|
||||
totalFilesSize?: number
|
||||
selectedItem: AssetInfo | null
|
||||
selectedIds: Set<string>
|
||||
onItemSelect: (item: AssetInfo, event: React.MouseEvent) => void
|
||||
onItemDoubleClick: (item: AssetInfo) => void
|
||||
onSaveField?: (fileId: string, fieldId: string, value: unknown) => void
|
||||
onClearSelection: () => void
|
||||
fetchNextFoldersPage: () => void
|
||||
hasNextFoldersPage: boolean
|
||||
isFetchingNextFoldersPage: boolean
|
||||
fetchNextFilesPage: () => void
|
||||
hasNextFilesPage: boolean
|
||||
isFetchingNextFilesPage: boolean
|
||||
isRecentlyDeleted?: boolean
|
||||
isRecents?: boolean
|
||||
isShareView?: boolean
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
allowDownload?: boolean
|
||||
rootFolderId?: string
|
||||
}
|
||||
|
||||
type FileWithId = {
|
||||
file: File
|
||||
id: string
|
||||
}
|
||||
|
||||
let pendingFilesToUpload: FileWithId[] = []
|
||||
|
||||
export function MobileFileBrowser({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
folders,
|
||||
files,
|
||||
totalFolders,
|
||||
totalFiles,
|
||||
totalFoldersSize,
|
||||
totalFilesSize,
|
||||
selectedItem,
|
||||
selectedIds,
|
||||
onItemSelect,
|
||||
onItemDoubleClick,
|
||||
onSaveField,
|
||||
onClearSelection,
|
||||
fetchNextFoldersPage,
|
||||
hasNextFoldersPage,
|
||||
isFetchingNextFoldersPage,
|
||||
fetchNextFilesPage,
|
||||
hasNextFilesPage,
|
||||
isFetchingNextFilesPage,
|
||||
isRecentlyDeleted = false,
|
||||
isRecents = false,
|
||||
isShareView = false,
|
||||
isPublic = false,
|
||||
shareId,
|
||||
allowDownload = true,
|
||||
}: MobileFileBrowserProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { canEdit, canAdmin } = usePermissions(projectId)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const [foldersExpanded, setFoldersExpanded] = useState(true)
|
||||
const [filesExpanded, setFilesExpanded] = useState(true)
|
||||
const [isNewFolderDialogOpen, setIsNewFolderDialogOpen] = useState(false)
|
||||
const [newFolderName, setNewFolderName] = useState('')
|
||||
const [isEmptyTrashDialogOpen, setIsEmptyTrashDialogOpen] = useState(false)
|
||||
|
||||
const foldersCount = totalFolders ?? folders.length
|
||||
const filesCount = totalFiles ?? files.length
|
||||
const foldersSizeVal =
|
||||
totalFoldersSize ??
|
||||
(folders.length > 0 ? folders.reduce((acc, f) => acc + (f.sizeByte || 0), 0) : -1)
|
||||
const filesSizeVal =
|
||||
totalFilesSize ?? (files.length > 0 ? files.reduce((acc, f) => acc + (f.sizeByte || 0), 0) : -1)
|
||||
const showFoldersSize = foldersSizeVal > -1
|
||||
const showFilesSize = filesSizeVal > -1
|
||||
|
||||
const formatCount = (count: number, isFile: boolean) => {
|
||||
if (isFile) {
|
||||
return count === 1 ? m.n_assets_singular({ count }) : m.n_assets_plural({ count })
|
||||
} else {
|
||||
return count === 1 ? m.n_folders_singular({ count }) : m.n_folders_plural({ count })
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
editingItemId,
|
||||
setEditingItemId,
|
||||
handleAction,
|
||||
onRenameSubmit,
|
||||
isDeleteDialogOpen,
|
||||
setIsDeleteDialogOpen,
|
||||
confirmDelete,
|
||||
isDownloadDialogOpen,
|
||||
setIsDownloadDialogOpen,
|
||||
isLoadingLinks,
|
||||
resolvedFiles,
|
||||
startDownload,
|
||||
} = useFileActions({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
folders,
|
||||
files,
|
||||
selectedIds,
|
||||
isPublic,
|
||||
shareId,
|
||||
})
|
||||
|
||||
// Infinite scroll trigger
|
||||
const { ref: loadMoreRef, inView } = useInView()
|
||||
React.useEffect(() => {
|
||||
if (inView) {
|
||||
if (hasNextFoldersPage && !isFetchingNextFoldersPage) {
|
||||
fetchNextFoldersPage()
|
||||
} else if (hasNextFilesPage && !isFetchingNextFilesPage) {
|
||||
fetchNextFilesPage()
|
||||
}
|
||||
}
|
||||
}, [
|
||||
inView,
|
||||
hasNextFoldersPage,
|
||||
isFetchingNextFoldersPage,
|
||||
hasNextFilesPage,
|
||||
isFetchingNextFilesPage,
|
||||
fetchNextFoldersPage,
|
||||
fetchNextFilesPage,
|
||||
])
|
||||
|
||||
// Upload actions
|
||||
const incrementUploading = useUploadStore((state) => state.increment)
|
||||
const decrementUploading = useUploadStore((state) => state.decrement)
|
||||
const startTask = useUploadStore((state) => state.startTask)
|
||||
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
|
||||
const completeFile = useUploadStore((state) => state.completeFile)
|
||||
const failFile = useUploadStore((state) => state.failFile)
|
||||
|
||||
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
|
||||
const { mutateAsync: confirmUpload } = useMutation<
|
||||
InferResponseType<typeof $confirmUpload>,
|
||||
Error,
|
||||
InferRequestType<typeof $confirmUpload>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $confirmUpload(request)
|
||||
if (!res.ok) throw new Error('Failed to confirm upload')
|
||||
return (await res.json()) as InferResponseType<typeof $confirmUpload>
|
||||
},
|
||||
})
|
||||
|
||||
const uploadFiles = async (
|
||||
filesList: FileWithId[],
|
||||
presignedUrls: PresignedUrl[] | undefined,
|
||||
taskId: string,
|
||||
) => {
|
||||
const uploadUrlMap = presignedUrls?.reduce(
|
||||
(acc: Record<string, { url: string; fileId: string }>, item: PresignedUrl) => {
|
||||
if (item.id) {
|
||||
acc[item.id] = {
|
||||
url: item.url || '',
|
||||
fileId: item.fileId || '',
|
||||
}
|
||||
}
|
||||
return acc
|
||||
},
|
||||
{},
|
||||
)
|
||||
if (!uploadUrlMap) return
|
||||
|
||||
const concurrencyLimit = 5
|
||||
const queue = [...filesList]
|
||||
|
||||
const uploadNext = async () => {
|
||||
while (queue.length > 0) {
|
||||
const item = queue.shift()
|
||||
if (item) {
|
||||
const uploadInfo = uploadUrlMap[item.id]
|
||||
if (uploadInfo && uploadInfo.url) {
|
||||
incrementUploading()
|
||||
try {
|
||||
const xhr = new XMLHttpRequest()
|
||||
const uploadPromise = new Promise<{ ok: boolean; status: number }>(
|
||||
(resolve, reject) => {
|
||||
xhr.open('PUT', uploadInfo.url)
|
||||
xhr.setRequestHeader('Content-Type', item.file.type)
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) {
|
||||
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve({ ok: true, status: xhr.status })
|
||||
} else {
|
||||
resolve({ ok: false, status: xhr.status })
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onerror = () => reject(new Error('Network error'))
|
||||
xhr.onabort = () => reject(new Error('Upload aborted'))
|
||||
xhr.send(item.file)
|
||||
},
|
||||
)
|
||||
|
||||
const resp = await uploadPromise
|
||||
if (resp.ok) {
|
||||
completeFile(taskId, uploadInfo.fileId)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${item.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with status: ${resp.status}`,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${item.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
})
|
||||
return
|
||||
} finally {
|
||||
decrementUploading()
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const activeUploaders = Array(concurrencyLimit)
|
||||
.fill(null)
|
||||
.map(() => uploadNext())
|
||||
await Promise.all(activeUploaders)
|
||||
}
|
||||
|
||||
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
|
||||
const { mutate: createUploadTaskMutation } = useMutation<
|
||||
InferResponseType<typeof $createUploadTask>,
|
||||
Error,
|
||||
InferRequestType<typeof $createUploadTask>,
|
||||
{ files: FileWithId[] }
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $createUploadTask(request)
|
||||
if (!res.ok) throw new Error('Failed to create upload task')
|
||||
return (await res.json()) as InferResponseType<typeof $createUploadTask>
|
||||
},
|
||||
onMutate: () => {
|
||||
return { files: [...pendingFilesToUpload] }
|
||||
},
|
||||
onSuccess: async (data, _variables, context) => {
|
||||
const currentFiles = context?.files || []
|
||||
const filesProgressInfo = currentFiles
|
||||
.map((f) => {
|
||||
const urlInfo = data.presignedUrls?.find((p) => p.id === f.id)
|
||||
return {
|
||||
fileId: urlInfo?.fileId || f.id,
|
||||
name: f.file.name,
|
||||
size: f.file.size,
|
||||
}
|
||||
})
|
||||
.filter((info) => !!info.fileId)
|
||||
|
||||
const visibleFiles = currentFiles.filter((f) => !f.file.name.startsWith('.'))
|
||||
const taskName =
|
||||
visibleFiles.length === 1 ? visibleFiles[0].file.name : `${visibleFiles.length} Items`
|
||||
|
||||
if (data.taskId) {
|
||||
startTask(data.taskId, taskName, filesProgressInfo)
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
|
||||
await uploadFiles(currentFiles, data.presignedUrls, data.taskId!)
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
},
|
||||
})
|
||||
|
||||
const processAndUploadFiles = (selectedFiles: FileList | File[]) => {
|
||||
if (!selectedFiles || selectedFiles.length === 0) return
|
||||
|
||||
const fileWithIds: FileWithId[] = []
|
||||
const root: CreateUploadTaskRequest['files'] = []
|
||||
const directories = new Map<string, CreateUploadTaskRequest['files']>()
|
||||
|
||||
for (const file of selectedFiles) {
|
||||
const path = (file.webkitRelativePath || file.name).split('/')
|
||||
if (path.some((part) => part.startsWith('.'))) {
|
||||
continue
|
||||
}
|
||||
const fileName = path.pop()!
|
||||
let currentLevel = root
|
||||
let currentPath = ''
|
||||
for (const dir of path) {
|
||||
currentPath = `${currentPath}/${dir}`
|
||||
if (!directories.has(currentPath)) {
|
||||
const newDir: CreateUploadTaskRequest['files'] = []
|
||||
const parentDir = {
|
||||
name: dir,
|
||||
type: 'folder' as const,
|
||||
id: ulid(),
|
||||
children: newDir,
|
||||
size: 0,
|
||||
}
|
||||
currentLevel.push(parentDir)
|
||||
directories.set(currentPath, newDir)
|
||||
currentLevel = newDir
|
||||
} else {
|
||||
currentLevel = directories.get(currentPath)!
|
||||
}
|
||||
}
|
||||
const fileWithId = { file, id: ulid() }
|
||||
fileWithIds.push(fileWithId)
|
||||
let mediaType = file.type
|
||||
if (fileName.toLowerCase().endsWith('.wma') && mediaType?.startsWith('video/')) {
|
||||
mediaType = mediaType.replace(/^video\//, 'audio/')
|
||||
}
|
||||
currentLevel.push({
|
||||
name: fileName,
|
||||
size: file.size,
|
||||
type: 'file',
|
||||
id: fileWithId.id,
|
||||
children: [],
|
||||
mediaType,
|
||||
})
|
||||
}
|
||||
pendingFilesToUpload = fileWithIds
|
||||
createUploadTaskMutation({
|
||||
param: { teamId: teamId },
|
||||
json: {
|
||||
parentId: assetId,
|
||||
files: root,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const $createFolder = client.api.folders.$post
|
||||
const { mutate: createFolderMutation, isPending: isCreatingFolder } = useMutation({
|
||||
mutationFn: async (name: string) => {
|
||||
const res = await $createFolder({
|
||||
json: { name, parentId: assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create folder')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(m.new_folder())
|
||||
setIsNewFolderDialogOpen(false)
|
||||
setNewFolderName('')
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: emptyTrash, isPending: isEmptyingTrash } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.projects[':projectId']['empty-trash'].$post({
|
||||
param: { projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to empty trash')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(m.trash_emptied_successfully())
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['projects', projectId, 'recently-deleted'],
|
||||
})
|
||||
onClearSelection()
|
||||
setIsEmptyTrashDialogOpen(false)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const handleCreateFolderSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!newFolderName.trim()) return
|
||||
createFolderMutation(newFolderName.trim())
|
||||
}
|
||||
|
||||
const isFolderEmpty =
|
||||
folders.length === 0 &&
|
||||
files.length === 0 &&
|
||||
!isFetchingNextFoldersPage &&
|
||||
!isFetchingNextFilesPage
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col min-h-0 bg-background overflow-hidden relative">
|
||||
{/* Hidden file inputs for upload actions */}
|
||||
{canEdit && (
|
||||
<>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
if (e.target.files) processAndUploadFiles(e.target.files)
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
type="file"
|
||||
ref={folderInputRef}
|
||||
multiple
|
||||
/* @ts-expect-error - webkitdirectory is not in standard input type */
|
||||
webkitdirectory="true"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
if (e.target.files) processAndUploadFiles(e.target.files)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Recently Deleted banner */}
|
||||
{isRecentlyDeleted && (
|
||||
<div className="flex items-center justify-between px-4 py-2.5 bg-muted/20 border-b border-border text-sm shrink-0">
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />
|
||||
<span className="text-xs">{m.recently_deleted_notice()}</span>
|
||||
</div>
|
||||
{canAdmin && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={isEmptyingTrash || (folders.length === 0 && files.length === 0)}
|
||||
onClick={() => setIsEmptyTrashDialogOpen(true)}
|
||||
className="h-7 px-2.5 text-xs font-medium bg-destructive/10 text-destructive border border-destructive/20 hover:bg-destructive hover:text-destructive-foreground"
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main scroll area */}
|
||||
<div className="flex-1 overflow-y-auto min-h-0 p-3 pb-24">
|
||||
<div className="max-w-lg mx-auto w-full">
|
||||
{/* Folders Section */}
|
||||
{foldersCount > 0 && (
|
||||
<div className="mb-4">
|
||||
<button
|
||||
onClick={() => setFoldersExpanded(!foldersExpanded)}
|
||||
className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground mb-3 font-medium select-none cursor-pointer"
|
||||
>
|
||||
{foldersExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
<span>
|
||||
{formatCount(foldersCount, false)}
|
||||
{showFoldersSize ? ` • ${formatSize(foldersSizeVal)}` : ''}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{foldersExpanded && (
|
||||
<div className="grid grid-cols-1 gap-4 w-full">
|
||||
{folders.map((folder) => (
|
||||
<FolderCard
|
||||
key={folder.id}
|
||||
item={folder}
|
||||
isSelected={selectedItem?.id === folder.id}
|
||||
isChecked={selectedIds.has(folder.id!)}
|
||||
isEditing={editingItemId === folder.id}
|
||||
onSelect={onItemSelect}
|
||||
onDoubleClick={onItemDoubleClick}
|
||||
onContextMenu={() => {}}
|
||||
onDragStart={() => {}}
|
||||
onDrop={() => {}}
|
||||
onRename={(newName) => onRenameSubmit(folder, newName)}
|
||||
onFinishEditing={() => setEditingItemId(null)}
|
||||
onAction={(action, item) =>
|
||||
handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item)
|
||||
}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
isRecents={isRecents}
|
||||
selectedCount={selectedIds.size}
|
||||
canEdit={canEdit}
|
||||
isShareView={isShareView}
|
||||
allowDownload={allowDownload}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Files Section */}
|
||||
{filesCount > 0 && (
|
||||
<div className="mb-4">
|
||||
<button
|
||||
onClick={() => setFilesExpanded(!filesExpanded)}
|
||||
className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground mb-3 font-medium select-none cursor-pointer"
|
||||
>
|
||||
{filesExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
<span>
|
||||
{formatCount(filesCount, true)}
|
||||
{showFilesSize ? ` • ${formatSize(filesSizeVal)}` : ''}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{filesExpanded && (
|
||||
<div className="grid grid-cols-1 gap-4 w-full">
|
||||
{files.map((file) => (
|
||||
<FileCard
|
||||
key={file.id}
|
||||
teamId={teamId}
|
||||
item={file}
|
||||
isSelected={selectedItem?.id === file.id}
|
||||
isChecked={selectedIds.has(file.id!)}
|
||||
isEditing={editingItemId === file.id}
|
||||
onSelect={onItemSelect}
|
||||
onDoubleClick={onItemDoubleClick}
|
||||
onContextMenu={() => {}}
|
||||
onDragStart={() => {}}
|
||||
onDrop={() => {}}
|
||||
onRename={(newName) => onRenameSubmit(file, newName)}
|
||||
onFinishEditing={() => setEditingItemId(null)}
|
||||
onSaveField={(fieldId, value) => onSaveField?.(file.id!, fieldId, value)}
|
||||
fields={[]}
|
||||
onAction={(action, item) =>
|
||||
handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item)
|
||||
}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
isRecents={isRecents}
|
||||
selectedCount={selectedIds.size}
|
||||
canEdit={canEdit}
|
||||
isShareView={isShareView}
|
||||
allowDownload={allowDownload}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Empty state */}
|
||||
{isFolderEmpty && (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-sm text-muted-foreground p-6 text-center">
|
||||
{isRecents ? (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<FolderClock className="h-10 w-10 text-muted-foreground/40 mb-1" />
|
||||
<p className="font-medium text-foreground">{m.no_recent_files()}</p>
|
||||
<p className="text-xs text-muted-foreground">{m.no_recent_files_description()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<span>{m.this_folder_is_empty()}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Infinite scroll loader / trigger */}
|
||||
<div ref={loadMoreRef} className="py-4 flex justify-center items-center min-h-6">
|
||||
{(isFetchingNextFoldersPage || isFetchingNextFilesPage) && (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Floating Action Button (+) for users with edit permissions */}
|
||||
{canEdit && !isRecentlyDeleted && !isRecents && !isShareView && !isPublic && (
|
||||
<div className="fixed bottom-6 right-6 z-30">
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
size="icon"
|
||||
className="h-14 w-14 rounded-full bg-primary text-primary-foreground shadow-lg shadow-primary/25 hover:bg-primary/90 flex items-center justify-center"
|
||||
aria-label="Actions"
|
||||
>
|
||||
<Plus className="h-6 w-6" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" side="top" className="w-48 mb-2">
|
||||
<DropdownMenuItem
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="flex items-center gap-2.5 py-2 cursor-pointer"
|
||||
>
|
||||
<Upload className="h-4 w-4" />
|
||||
<span>{m.upload_file()}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => folderInputRef.current?.click()}
|
||||
className="flex items-center gap-2.5 py-2 cursor-pointer"
|
||||
>
|
||||
<Upload className="h-4 w-4" />
|
||||
<span>{m.upload_folder()}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setIsNewFolderDialogOpen(true)}
|
||||
className="flex items-center gap-2.5 py-2 cursor-pointer"
|
||||
>
|
||||
<FolderPlus className="h-4 w-4" />
|
||||
<span>{m.new_folder()}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New Folder Dialog */}
|
||||
<Dialog open={isNewFolderDialogOpen} onOpenChange={setIsNewFolderDialogOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<form onSubmit={handleCreateFolderSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.new_folder()}</DialogTitle>
|
||||
<DialogDescription>{m.folder_name()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<Input
|
||||
autoFocus
|
||||
placeholder={m.folder_name()}
|
||||
value={newFolderName}
|
||||
onChange={(e) => setNewFolderName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setIsNewFolderDialogOpen(false)}
|
||||
>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!newFolderName.trim() || isCreatingFolder}>
|
||||
{isCreatingFolder ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
|
||||
{m.confirm()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Confirmation Alert Dialog */}
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.delete_asset_title()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{m.delete_asset_description()}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => confirmDelete()}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Empty Trash Confirmation Alert Dialog */}
|
||||
<AlertDialog open={isEmptyTrashDialogOpen} onOpenChange={setIsEmptyTrashDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.empty_trash_title()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{m.empty_trash_description()}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => emptyTrash()}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
disabled={isEmptyingTrash}
|
||||
>
|
||||
{isEmptyingTrash ? 'Deleting...' : m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Download Dialog */}
|
||||
<Dialog open={isDownloadDialogOpen} onOpenChange={setIsDownloadDialogOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{isLoadingLinks ? m.preparing_download() : m.confirm_download()}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isLoadingLinks ? m.resolving_files_wait() : m.folder_files_download_description()}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoadingLinks ? (
|
||||
<div className="space-y-4 py-6 flex flex-col items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<span className="text-sm font-medium text-muted-foreground mt-2">
|
||||
{m.preparing_download_links()}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{m.download_includes_files({ count: resolvedFiles.length })}
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 text-sm rounded-lg bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-900/30">
|
||||
<AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-semibold">{m.no_folder_structure()}</p>
|
||||
<p className="mt-0.5 text-xs text-amber-700/90 dark:text-amber-400/90">
|
||||
{m.folder_structure_warning()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{!isLoadingLinks ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setIsDownloadDialogOpen(false)}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={startDownload}
|
||||
className="gap-2"
|
||||
disabled={resolvedFiles.length === 0}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
{m.start_download()}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button variant="outline" onClick={() => setIsDownloadDialogOpen(false)}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -25,9 +25,11 @@ import { useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { cn } from '../lib/utils'
|
||||
import { getSelectedRangeIds } from '../lib/selection-utils'
|
||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
import { ChatbotSidebar } from './chatbot-sidebar'
|
||||
import { SnapToPointer } from './dnd-modifiers'
|
||||
import { FileBrowser } from './file-browser/file-browser'
|
||||
import { MobileFileBrowser } from './file-browser/mobile-file-browser'
|
||||
import { FileViewerRightSidebar } from './file-viewer-right-sidebar'
|
||||
import { FolderTree } from './folder-tree'
|
||||
import { ResizeHandle } from './resize-handle'
|
||||
@@ -162,6 +164,7 @@ export default function FileSystemManager({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
rootFolderId,
|
||||
ancestorFolders: folderInfo?.ancestorFolders ?? [],
|
||||
currentAsset: isRecentlyDeleted
|
||||
? { name: m.recently_deleted(), type: 'folder' }
|
||||
@@ -418,6 +421,39 @@ export default function FileSystemManager({
|
||||
)
|
||||
}
|
||||
|
||||
const isMobile = useIsMobile()
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<MobileFileBrowser
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
assetId={assetId}
|
||||
folders={folders}
|
||||
files={files}
|
||||
totalFolders={totalFolders}
|
||||
totalFiles={totalFiles}
|
||||
totalFoldersSize={totalFoldersSize}
|
||||
totalFilesSize={totalFilesSize}
|
||||
selectedItem={selectedItem}
|
||||
selectedIds={selectedIds}
|
||||
onItemSelect={handleItemSelect}
|
||||
onItemDoubleClick={handleItemDoubleClick}
|
||||
onSaveField={handleSaveField}
|
||||
onClearSelection={handleClearSelection}
|
||||
fetchNextFoldersPage={fetchNextFoldersPage}
|
||||
hasNextFoldersPage={hasNextPageFolders || false}
|
||||
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
|
||||
fetchNextFilesPage={fetchNextFilesPage}
|
||||
hasNextFilesPage={hasNextPageFiles || false}
|
||||
isFetchingNextFilesPage={isFetchingNextFilesPage}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
isRecents={isRecents}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DragDropProvider
|
||||
modifiers={[SnapToPointer.configure({ anchor: { x: 0, y: 0 } })]}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MobileFileBottomSheet } from './mobile-file-bottom-sheet'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
vi.mock('react-intersection-observer', () => ({
|
||||
useInView: () => ({
|
||||
ref: vi.fn(),
|
||||
inView: false,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/hooks/use-permissions', () => ({
|
||||
usePermissions: () => ({
|
||||
canEdit: true,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
projects: {
|
||||
':projectId': {
|
||||
fields: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [],
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
files: {
|
||||
':fileId': {
|
||||
comments: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [
|
||||
{
|
||||
id: 'comment-1',
|
||||
message: 'First mobile comment',
|
||||
userId: 'user-1',
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: {},
|
||||
}),
|
||||
}),
|
||||
$post: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'new-comment-id' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
shares: {
|
||||
':shareId': {
|
||||
files: {
|
||||
':fileId': {
|
||||
comments: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [], pageInfo: {} }),
|
||||
}),
|
||||
$post: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'new-comment-id' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
me: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'user-1', name: 'Test User' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('MobileFileBottomSheet', () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const mockFile: AssetInfo = {
|
||||
id: 'file-1',
|
||||
name: 'test.mp4',
|
||||
proxyType: 'video',
|
||||
media: {
|
||||
metadata: {
|
||||
duration: 60,
|
||||
frameRate: 30,
|
||||
},
|
||||
},
|
||||
} as AssetInfo
|
||||
|
||||
it('renders comments and fields tabs', async () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MobileFileBottomSheet
|
||||
teamId="team-1"
|
||||
projectId="proj-1"
|
||||
file={mockFile}
|
||||
onSaveField={vi.fn()}
|
||||
members={[{ id: 'user-1', name: 'User One', role: 'owner' }]}
|
||||
heightPercent={50}
|
||||
onHeightPercentChange={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('tab', { name: /comments/i })).toBeDefined()
|
||||
expect(screen.getByRole('tab', { name: /fields/i })).toBeDefined()
|
||||
})
|
||||
|
||||
it('handles drag interactions on the handle bar', () => {
|
||||
const onHeightChange = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MobileFileBottomSheet
|
||||
teamId="team-1"
|
||||
projectId="proj-1"
|
||||
file={mockFile}
|
||||
onSaveField={vi.fn()}
|
||||
members={[]}
|
||||
heightPercent={50}
|
||||
onHeightPercentChange={onHeightChange}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const handle = screen.getByLabelText(/Drag to resize bottom sheet/i)
|
||||
expect(handle).toBeDefined()
|
||||
|
||||
fireEvent.pointerDown(handle, { clientY: 400, pointerId: 1 })
|
||||
fireEvent.pointerMove(handle, { clientY: 300, pointerId: 1 })
|
||||
fireEvent.pointerUp(handle, { clientY: 300, pointerId: 1 })
|
||||
|
||||
expect(onHeightChange).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,534 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { MessageCard } from '@/ui/components/chat/message-card'
|
||||
import { ChatInput } from '@/ui/components/chat/message-input'
|
||||
import FieldRenderer from '@/ui/components/field-renderer'
|
||||
import { GuestIdentityPopup } from '@/ui/components/guest-identity-popup'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { getViewerForFile } from '@/ui/components/viewers/registry'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import type { MemberInfo } from '@/ui/stores/members'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import type { AssetInfo, AttachmentInfo, CommentInfo, FieldValueInfo } from '@shumai/dtos'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { XIcon } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export interface MobileFileBottomSheetProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
file: AssetInfo | null
|
||||
onSaveField: (fieldId: string, value: unknown) => void
|
||||
members: MemberInfo[]
|
||||
onCommentSelect?: (comment: CommentInfo) => void
|
||||
hideAnnotationControl?: boolean
|
||||
readOnly?: boolean
|
||||
publicFields?: MetadataFieldInfo[]
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
currentTime?: number
|
||||
onTyping?: () => void
|
||||
selectedCommentId?: string | null
|
||||
heightPercent: number
|
||||
onHeightPercentChange: (height: number) => void
|
||||
}
|
||||
|
||||
export function MobileFileBottomSheet({
|
||||
teamId,
|
||||
projectId,
|
||||
file,
|
||||
onSaveField,
|
||||
members,
|
||||
onCommentSelect,
|
||||
hideAnnotationControl = false,
|
||||
readOnly = false,
|
||||
publicFields,
|
||||
isPublic = false,
|
||||
shareId,
|
||||
currentTime,
|
||||
onTyping,
|
||||
selectedCommentId,
|
||||
heightPercent,
|
||||
onHeightPercentChange,
|
||||
}: MobileFileBottomSheetProps) {
|
||||
const { canEdit } = usePermissions(projectId)
|
||||
const { fields, setFields } = useFieldStore()
|
||||
const queryClient = useQueryClient()
|
||||
const { ref, inView } = useInView()
|
||||
const [replyingTo, setReplyingTo] = useState<CommentInfo | null>(null)
|
||||
const [viewingAttachment, setViewingAttachment] = useState<AttachmentInfo | null>(null)
|
||||
const [isGuestPopupOpen, setIsGuestPopupOpen] = useState(false)
|
||||
const [pendingComment, setPendingComment] = useState<{
|
||||
text: string
|
||||
attachmentIds: string[]
|
||||
annotations?: Annotation[]
|
||||
replyToId?: string | null
|
||||
second?: number | null
|
||||
} | null>(null)
|
||||
|
||||
// Dragging state
|
||||
const isDragging = useRef(false)
|
||||
const dragStartY = useRef(0)
|
||||
const dragStartHeightPercent = useRef(heightPercent)
|
||||
|
||||
const handlePointerDown = (e: React.PointerEvent) => {
|
||||
isDragging.current = true
|
||||
dragStartY.current = e.clientY
|
||||
dragStartHeightPercent.current = heightPercent
|
||||
;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)
|
||||
}
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
if (!isDragging.current) return
|
||||
const deltaY = dragStartY.current - e.clientY
|
||||
const deltaPercent = (deltaY / window.innerHeight) * 100
|
||||
const newHeight = Math.min(85, Math.max(10, dragStartHeightPercent.current + deltaPercent))
|
||||
onHeightPercentChange(newHeight)
|
||||
},
|
||||
[onHeightPercentChange],
|
||||
)
|
||||
|
||||
const handlePointerUp = (e: React.PointerEvent) => {
|
||||
isDragging.current = false
|
||||
try {
|
||||
;(e.target as HTMLElement).releasePointerCapture?.(e.pointerId)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
const { data: apiFields } = useQuery({
|
||||
queryKey: ['fields', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].fields.$get({
|
||||
param: { projectId: projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch fields')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!projectId && !publicFields,
|
||||
})
|
||||
|
||||
const viewerDef = getViewerForFile(file)
|
||||
|
||||
useEffect(() => {
|
||||
if (publicFields) {
|
||||
setFields(publicFields, projectId)
|
||||
} else if (apiFields) {
|
||||
setFields(apiFields as unknown as MetadataFieldInfo[], projectId)
|
||||
}
|
||||
}, [apiFields, publicFields, projectId, setFields])
|
||||
|
||||
const {
|
||||
data: commentsData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: isPublic
|
||||
? ['shares', shareId, 'files', file?.id, 'comments']
|
||||
: ['files', file?.id, 'comments'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (isPublic) {
|
||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$get(
|
||||
{
|
||||
param: { shareId: shareId!, fileId: file!.id! },
|
||||
query: { after: pageParam as string },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
},
|
||||
},
|
||||
)
|
||||
if (!res.ok) throw new Error('Failed to fetch comments')
|
||||
return await res.json()
|
||||
} else {
|
||||
const res = await client.api.files[':fileId'].comments.$get({
|
||||
param: { fileId: file!.id! },
|
||||
query: { after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch comments')
|
||||
return await res.json()
|
||||
}
|
||||
},
|
||||
enabled: !!file?.id && (!isPublic || !!shareId),
|
||||
initialPageParam: '',
|
||||
refetchInterval: 2000,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
getNextPageParam: (lastPage: any) => lastPage.pageInfo?.cursor || undefined,
|
||||
})
|
||||
|
||||
const { mutate: createComment } = useMutation({
|
||||
mutationFn: async ({
|
||||
text,
|
||||
attachmentIds,
|
||||
annotations,
|
||||
replyToId,
|
||||
guestUserId,
|
||||
second,
|
||||
}: {
|
||||
text: string
|
||||
attachmentIds: string[]
|
||||
annotations?: Annotation[]
|
||||
replyToId?: string | null
|
||||
guestUserId?: string
|
||||
second?: number | null
|
||||
}) => {
|
||||
if (isPublic) {
|
||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$post(
|
||||
{
|
||||
param: { shareId: shareId!, fileId: file!.id! },
|
||||
json: {
|
||||
message: text,
|
||||
attachmentIds: attachmentIds,
|
||||
replyToId: replyToId ?? undefined,
|
||||
annotations: annotations,
|
||||
second: second ?? undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
...(guestUserId ? { 'x-guest-user-id': guestUserId } : {}),
|
||||
},
|
||||
},
|
||||
)
|
||||
if (!res.ok) throw new Error('Failed to create comment')
|
||||
return await res.json()
|
||||
} else {
|
||||
const res = await client.api.files[':fileId'].comments.$post({
|
||||
param: { fileId: file!.id! },
|
||||
json: {
|
||||
message: text,
|
||||
attachmentIds: attachmentIds,
|
||||
replyToId: replyToId ?? undefined,
|
||||
annotations: annotations,
|
||||
second: second ?? undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create comment')
|
||||
return await res.json()
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: isPublic
|
||||
? ['shares', shareId, 'files', file?.id, 'comments']
|
||||
: ['files', file?.id, 'comments'],
|
||||
})
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(m.failed_to_post_comment?.() || 'Failed to post comment')
|
||||
},
|
||||
})
|
||||
|
||||
const totalComments =
|
||||
commentsData?.pages?.[0]?.pageInfo?.total ??
|
||||
commentsData?.pages.reduce((acc, page) => acc + (page.data?.length || 0), 0) ??
|
||||
0
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, fetchNextPage, hasNextPage])
|
||||
|
||||
const itemFieldValueMap = useMemo(() => {
|
||||
return (file?.fieldValues || []).reduce(
|
||||
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
|
||||
acc[val.fieldId!] = val
|
||||
return acc
|
||||
},
|
||||
{},
|
||||
)
|
||||
}, [file?.fieldValues])
|
||||
|
||||
const sortedFields = useMemo(() => {
|
||||
return [...fields].sort((a, b) => {
|
||||
const nameA = a.config?.name?.toLowerCase() || ''
|
||||
const nameB = b.config?.name?.toLowerCase() || ''
|
||||
if (nameA < nameB) return -1
|
||||
if (nameA > nameB) return 1
|
||||
return 0
|
||||
})
|
||||
}, [fields])
|
||||
|
||||
const comments =
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(commentsData?.pages.flatMap((page: any) => page.data ?? []) as CommentInfo[]) ?? []
|
||||
|
||||
const handleSendMessage = (
|
||||
text: string,
|
||||
attachmentIds: string[],
|
||||
annotations: Annotation[] = [],
|
||||
replyToId?: string | null,
|
||||
second?: number | null,
|
||||
) => {
|
||||
if (!text.trim() && attachmentIds.length === 0 && annotations.length === 0) return
|
||||
|
||||
const actualReplyToId = replyToId || replyingTo?.id || null
|
||||
if (isPublic) {
|
||||
const guestUserId = localStorage.getItem(`guest_user_id_${shareId}`)
|
||||
if (!guestUserId) {
|
||||
setPendingComment({ text, attachmentIds, annotations, replyToId: actualReplyToId, second })
|
||||
setIsGuestPopupOpen(true)
|
||||
} else {
|
||||
createComment({
|
||||
text,
|
||||
attachmentIds,
|
||||
annotations,
|
||||
replyToId: actualReplyToId,
|
||||
guestUserId,
|
||||
second,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
createComment({ text, attachmentIds, annotations, replyToId: actualReplyToId, second })
|
||||
}
|
||||
setReplyingTo(null)
|
||||
}
|
||||
|
||||
const handleGuestSuccess = (guestUserId: string) => {
|
||||
if (pendingComment) {
|
||||
createComment({ ...pendingComment, guestUserId })
|
||||
setPendingComment(null)
|
||||
setReplyingTo(null)
|
||||
}
|
||||
}
|
||||
|
||||
const getUser = (id: string): MemberInfo => {
|
||||
const member = members.find((m) => m.id === id)
|
||||
if (member) {
|
||||
return member
|
||||
}
|
||||
|
||||
return {
|
||||
id: 'unknown',
|
||||
name: 'Unknown',
|
||||
role: 'unknown',
|
||||
}
|
||||
}
|
||||
|
||||
const isCollapsed = heightPercent <= 15
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{ height: `${heightPercent}dvh` }}
|
||||
className="shrink-0 flex flex-col bg-background border-t border-border shadow-2xl rounded-t-2xl overflow-hidden select-none z-20"
|
||||
data-testid="mobile-bottom-sheet"
|
||||
>
|
||||
{/* Lightbox for attachment viewing */}
|
||||
{viewingAttachment && viewingAttachment.proxyType === 'image' && (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-4 animate-in fade-in duration-200"
|
||||
onClick={() => setViewingAttachment(null)}
|
||||
>
|
||||
<button
|
||||
className="absolute top-4 right-4 text-white/70 hover:text-white bg-white/10 hover:bg-white/20 rounded-full p-2 transition-colors z-50"
|
||||
aria-label={m.close()}
|
||||
>
|
||||
<XIcon className="w-8 h-8" />
|
||||
</button>
|
||||
|
||||
<div className="w-full h-full flex items-center justify-center p-2">
|
||||
<img
|
||||
src={viewingAttachment.url}
|
||||
alt={m.preview()}
|
||||
className="max-w-full max-h-[85vh] object-contain rounded shadow-2xl cursor-zoom-out"
|
||||
onClick={() => setViewingAttachment(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Drag Handle Bar */}
|
||||
<div
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerUp}
|
||||
className="w-full pt-2 pb-1.5 flex flex-col items-center justify-center cursor-grab active:cursor-grabbing touch-none shrink-0"
|
||||
aria-label="Drag to resize bottom sheet"
|
||||
>
|
||||
<div className="w-10 h-1 rounded-full bg-muted-foreground/30 hover:bg-muted-foreground/50 transition-colors" />
|
||||
</div>
|
||||
|
||||
{/* Tabs Header */}
|
||||
<Tabs
|
||||
defaultValue="comments"
|
||||
className="flex-1 flex flex-col min-h-0 px-2 pb-1 overflow-hidden"
|
||||
>
|
||||
<TabsList className="w-full shrink-0 h-9 bg-muted/60 p-1">
|
||||
<TabsTrigger value="comments" className="flex-1 text-xs font-semibold py-1">
|
||||
{m.comments()} {totalComments > 0 && `(${totalComments})`}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="fields" className="flex-1 text-xs font-semibold py-1">
|
||||
{m.fields()}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Comments Tab Content */}
|
||||
<TabsContent
|
||||
value="comments"
|
||||
className={cn(
|
||||
'flex-1 flex flex-col overflow-hidden min-h-0 mt-2',
|
||||
isCollapsed && 'hidden',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between px-2 pb-1.5 shrink-0 border-b border-border/50">
|
||||
<span className="text-xs font-bold text-foreground">
|
||||
{m.all_comments?.() || 'All comments'}
|
||||
{totalComments > 0 ? ` (${totalComments})` : ''}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="flex-1 min-h-0 px-2 py-2 [&>div>div]:block!">
|
||||
{comments.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-muted-foreground">
|
||||
{m.no_comments_yet()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id}>
|
||||
<MessageCard
|
||||
teamId={teamId}
|
||||
message={comment}
|
||||
getUser={getUser}
|
||||
onReply={setReplyingTo}
|
||||
onViewAttachment={setViewingAttachment}
|
||||
hasReplies={!!comment.replies?.length}
|
||||
formatTimestamp={viewerDef?.commentsConfig?.formatTimestamp}
|
||||
frameRate={
|
||||
viewerDef?.commentsConfig?.hasTimestamp
|
||||
? file?.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
}
|
||||
startTimecode={
|
||||
viewerDef?.commentsConfig?.hasTimestamp
|
||||
? file?.media?.metadata?.startTimecode
|
||||
: undefined
|
||||
}
|
||||
isSelected={selectedCommentId === comment.id}
|
||||
onSelect={() => {
|
||||
onCommentSelect?.(comment)
|
||||
}}
|
||||
/>
|
||||
{comment.replies?.map((reply, index) => (
|
||||
<div key={reply.id}>
|
||||
<MessageCard
|
||||
teamId={teamId}
|
||||
isReply={true}
|
||||
message={reply}
|
||||
getUser={getUser}
|
||||
onReply={setReplyingTo}
|
||||
onViewAttachment={setViewingAttachment}
|
||||
hasReplies={false}
|
||||
isLastReply={index === (comment.replies?.length ?? 0) - 1}
|
||||
formatTimestamp={viewerDef?.commentsConfig?.formatTimestamp}
|
||||
frameRate={
|
||||
viewerDef?.commentsConfig?.hasTimestamp
|
||||
? file?.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
}
|
||||
startTimecode={
|
||||
viewerDef?.commentsConfig?.hasTimestamp
|
||||
? file?.media?.metadata?.startTimecode
|
||||
: undefined
|
||||
}
|
||||
isSelected={selectedCommentId === reply.id}
|
||||
onSelect={() => {
|
||||
onCommentSelect?.(reply)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<div ref={ref} />
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
{/* Sticky Bottom Comment Input Bar */}
|
||||
{(!readOnly || isPublic) && (
|
||||
<div className="mt-auto shrink-0 bg-background border-t border-border pt-1">
|
||||
<GuestIdentityPopup
|
||||
isOpen={isGuestPopupOpen}
|
||||
onClose={() => setIsGuestPopupOpen(false)}
|
||||
onSuccess={handleGuestSuccess}
|
||||
>
|
||||
<ChatInput
|
||||
projectId={projectId}
|
||||
onSendMessage={handleSendMessage}
|
||||
replyingTo={replyingTo}
|
||||
onCancelReply={() => setReplyingTo(null)}
|
||||
hideAnnotationControl={hideAnnotationControl}
|
||||
disableMentions={isPublic}
|
||||
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
|
||||
formatTimestamp={viewerDef?.commentsConfig?.formatTimestamp}
|
||||
frameRate={
|
||||
viewerDef?.commentsConfig?.hasTimestamp
|
||||
? file?.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
}
|
||||
startTimecode={
|
||||
viewerDef?.commentsConfig?.hasTimestamp
|
||||
? file?.media?.metadata?.startTimecode
|
||||
: undefined
|
||||
}
|
||||
onTyping={onTyping}
|
||||
/>
|
||||
</GuestIdentityPopup>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{/* Fields Tab Content */}
|
||||
<TabsContent
|
||||
value="fields"
|
||||
className={cn(
|
||||
'flex-1 flex flex-col overflow-hidden min-h-0 mt-2',
|
||||
isCollapsed && 'hidden',
|
||||
)}
|
||||
>
|
||||
<ScrollArea className="flex-1 px-3 py-2 min-h-0 [&>div>div]:block!">
|
||||
{sortedFields && sortedFields.length > 0 ? (
|
||||
<div className="space-y-4 pb-6">
|
||||
{sortedFields.map((field) => (
|
||||
<div key={field.id} className="space-y-1.5">
|
||||
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
{field.config?.name}
|
||||
</label>
|
||||
<div className="min-h-[32px]">
|
||||
<FieldRenderer
|
||||
fieldId={field.id}
|
||||
config={field.config}
|
||||
value={itemFieldValueMap[field.id!]?.value}
|
||||
onSave={canEdit ? (val) => onSaveField(field.id!, val) : undefined}
|
||||
readOnly={readOnly || field.readOnly || !canEdit}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-8 text-center text-xs text-muted-foreground">
|
||||
No custom fields defined
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MobileFileDetail } from './mobile-file-detail'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
vi.mock('react-intersection-observer', () => ({
|
||||
useInView: () => ({
|
||||
ref: vi.fn(),
|
||||
inView: false,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/hooks/use-permissions', () => ({
|
||||
usePermissions: () => ({
|
||||
canEdit: true,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/components/file-viewer', () => ({
|
||||
FileViewer: ({ file }: { file: AssetInfo }) => (
|
||||
<div data-testid="mock-file-viewer">{file.name}</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
projects: {
|
||||
':projectId': {
|
||||
fields: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [],
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
':teamId': {
|
||||
kanban: {
|
||||
assets: {
|
||||
':assetId': {
|
||||
tasks: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [], total: 0 }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
files: {
|
||||
':fileId': {
|
||||
comments: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [], pageInfo: {} }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
me: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'user-1', name: 'User 1' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('MobileFileDetail', () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const mockFile: AssetInfo = {
|
||||
id: 'file-100',
|
||||
name: 'sample_video.mp4',
|
||||
proxyType: 'video',
|
||||
media: {
|
||||
metadata: {
|
||||
duration: 120,
|
||||
frameRate: 30,
|
||||
},
|
||||
},
|
||||
} as AssetInfo
|
||||
|
||||
it('renders header, media viewer, and bottom sheet', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MobileFileDetail
|
||||
projectId="proj-1"
|
||||
teamId="team-1"
|
||||
fileId="file-100"
|
||||
file={mockFile}
|
||||
activeFileId="file-100"
|
||||
onNavigateToFile={vi.fn()}
|
||||
onNavigateBack={vi.fn()}
|
||||
onSaveField={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getAllByText('sample_video.mp4').length).toBeGreaterThanOrEqual(1)
|
||||
expect(screen.getByTestId('mock-file-viewer')).toBeDefined()
|
||||
expect(screen.getByTestId('mobile-bottom-sheet')).toBeDefined()
|
||||
})
|
||||
|
||||
it('displays the immediate parent folder name in nested folder hierarchies', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MobileFileDetail
|
||||
projectId="proj-1"
|
||||
teamId="team-1"
|
||||
fileId="file-100"
|
||||
file={mockFile}
|
||||
activeFileId="file-100"
|
||||
ancestorFolders={[
|
||||
{ id: 'f-sub', name: 'Immediate Subfolder' },
|
||||
{ id: 'f-root', name: 'Top Level Root' },
|
||||
]}
|
||||
onNavigateToFile={vi.fn()}
|
||||
onNavigateBack={vi.fn()}
|
||||
onSaveField={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Immediate Subfolder')).toBeDefined()
|
||||
expect(screen.queryByText('Top Level Root')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders version list from stack when viewing selected version', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MobileFileDetail
|
||||
projectId="proj-1"
|
||||
teamId="team-1"
|
||||
fileId="file-100"
|
||||
file={mockFile}
|
||||
activeFileId="ver-2"
|
||||
versions={[
|
||||
{ id: 'ver-1', version: 1, name: 'video_v1.mp4' },
|
||||
{ id: 'ver-2', version: 2, name: 'video_v2.mp4' },
|
||||
]}
|
||||
onNavigateToFile={vi.fn()}
|
||||
onNavigateBack={vi.fn()}
|
||||
onSaveField={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('v2')).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,344 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FileViewer } from '@/ui/components/file-viewer'
|
||||
import { AssetLinkedTasksDialog } from '@/ui/components/kanban/asset-linked-tasks-dialog'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useMemberStore } from '@/ui/stores/members'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import type { AncestorFolder, AssetInfo, CommentInfo, FieldInfo } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { MediaController } from '../viewers/types'
|
||||
import { MobileFileBottomSheet } from './mobile-file-bottom-sheet'
|
||||
import { MobileFileHeader } from './mobile-file-header'
|
||||
|
||||
export interface MobileFileDetailProps {
|
||||
projectId: string
|
||||
teamId?: string
|
||||
fileId: string
|
||||
file: AssetInfo
|
||||
projectInfo?: { name?: string; rootFolder?: string }
|
||||
ancestorFolders?: AncestorFolder[]
|
||||
parentFolderId?: string
|
||||
versions?: Array<{
|
||||
id: string
|
||||
version: number
|
||||
name?: string | null
|
||||
previewUrl?: string | null
|
||||
}>
|
||||
activeFileId: string
|
||||
startTime?: number
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
allowDownload?: boolean
|
||||
publicFields?: FieldInfo[]
|
||||
siblingFiles?: AssetInfo[]
|
||||
onNavigateToFile: (fileId: string) => void
|
||||
onNavigateBack: () => void
|
||||
onRenameFile?: (newName: string) => Promise<void>
|
||||
onDeleteFile?: () => Promise<void>
|
||||
onSaveField: (fieldId: string, value: unknown) => void
|
||||
onSelectVersion?: (versionId: string) => void
|
||||
}
|
||||
|
||||
export function MobileFileDetail({
|
||||
projectId,
|
||||
teamId = '',
|
||||
fileId,
|
||||
file,
|
||||
projectInfo,
|
||||
ancestorFolders = [],
|
||||
versions,
|
||||
activeFileId,
|
||||
startTime,
|
||||
isPublic = false,
|
||||
shareId,
|
||||
allowDownload = true,
|
||||
publicFields,
|
||||
siblingFiles = [],
|
||||
onNavigateToFile,
|
||||
onNavigateBack,
|
||||
onRenameFile,
|
||||
onDeleteFile,
|
||||
onSaveField,
|
||||
onSelectVersion,
|
||||
}: MobileFileDetailProps) {
|
||||
const { canEdit } = usePermissions(projectId)
|
||||
const { members } = useMemberStore()
|
||||
const mediaControllerRef = useRef<MediaController | null>(null)
|
||||
|
||||
const [sheetHeightPercent, setSheetHeightPercent] = useState(50)
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
|
||||
|
||||
// Dialogs
|
||||
const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false)
|
||||
const [renameInput, setRenameInput] = useState('')
|
||||
const renameInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [isRenaming, setIsRenaming] = useState(false)
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [isLinkedTasksOpen, setIsLinkedTasksOpen] = useState(false)
|
||||
|
||||
// Linked tasks query for count
|
||||
const { data: linkedTasksData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'assets', activeFileId, 'tasks'],
|
||||
queryFn: async () => {
|
||||
if (!teamId || !activeFileId || isPublic) return { data: [], total: 0 }
|
||||
const res = await client.api.teams[':teamId'].kanban.assets[':assetId'].tasks.$get({
|
||||
param: { teamId, assetId: activeFileId },
|
||||
})
|
||||
if (!res.ok) return { data: [], total: 0 }
|
||||
return (await res.json()) as { data: Array<{ id: string }>; total: number }
|
||||
},
|
||||
enabled: !!teamId && !!activeFileId && !isPublic,
|
||||
})
|
||||
const linkedTaskCount = linkedTasksData?.total ?? linkedTasksData?.data?.length ?? 0
|
||||
|
||||
// Prev / Next file calculation
|
||||
const { prevFile, nextFile } = useMemo(() => {
|
||||
if (!siblingFiles || siblingFiles.length === 0) {
|
||||
return { prevFile: null, nextFile: null }
|
||||
}
|
||||
const currentIndex = siblingFiles.findIndex((f) => f.id === fileId || f.id === activeFileId)
|
||||
if (currentIndex === -1) {
|
||||
return { prevFile: null, nextFile: null }
|
||||
}
|
||||
return {
|
||||
prevFile: currentIndex > 0 ? siblingFiles[currentIndex - 1] : null,
|
||||
nextFile: currentIndex < siblingFiles.length - 1 ? siblingFiles[currentIndex + 1] : null,
|
||||
}
|
||||
}, [siblingFiles, fileId, activeFileId])
|
||||
|
||||
const folderName = ancestorFolders.length > 0 ? ancestorFolders[0]?.name : projectInfo?.name
|
||||
|
||||
const currentVersionObj = versions?.find((v) => v.id === activeFileId)
|
||||
const versionNumber =
|
||||
currentVersionObj?.version ?? (versions && versions.length > 0 ? versions.length : undefined)
|
||||
|
||||
const downloadInfo = useMemo(() => {
|
||||
return {
|
||||
originalKey: file.media?.original?.key,
|
||||
videoTranscodes: file.media?.videoTranscodes?.map((t) => ({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
})),
|
||||
}
|
||||
}, [file.media])
|
||||
|
||||
const handlePlay = () => {
|
||||
setAnnotations([])
|
||||
setSelectedCommentId(null)
|
||||
}
|
||||
|
||||
const handleCommentSelect = (comment: CommentInfo) => {
|
||||
setSelectedCommentId(comment.id || null)
|
||||
const newAnnotations = comment.annotations as Annotation[]
|
||||
if (newAnnotations && newAnnotations.length > 0) {
|
||||
setAnnotations(newAnnotations)
|
||||
} else {
|
||||
setAnnotations([])
|
||||
}
|
||||
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
mediaControllerRef.current?.seekTo(comment.second)
|
||||
mediaControllerRef.current?.pause()
|
||||
} else if (newAnnotations && newAnnotations.length > 0) {
|
||||
mediaControllerRef.current?.pause()
|
||||
}
|
||||
}
|
||||
|
||||
const handleRenameSubmit = async (e?: React.FormEvent) => {
|
||||
e?.preventDefault()
|
||||
if (!renameInput.trim() || !onRenameFile) return
|
||||
try {
|
||||
setIsRenaming(true)
|
||||
await onRenameFile(renameInput.trim())
|
||||
setIsRenameDialogOpen(false)
|
||||
} finally {
|
||||
setIsRenaming(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteSubmit = async () => {
|
||||
if (!onDeleteFile) return
|
||||
try {
|
||||
setIsDeleting(true)
|
||||
await onDeleteFile()
|
||||
setIsDeleteDialogOpen(false)
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentTime(0)
|
||||
setSelectedCommentId(null)
|
||||
setAnnotations([])
|
||||
}, [file?.id])
|
||||
|
||||
return (
|
||||
<div className="flex h-[100dvh] w-full flex-col bg-background overflow-hidden relative">
|
||||
{/* Part 1: Mobile Header */}
|
||||
<MobileFileHeader
|
||||
fileName={file.name}
|
||||
folderName={folderName}
|
||||
version={versionNumber}
|
||||
versions={versions}
|
||||
activeFileId={activeFileId}
|
||||
isPublic={isPublic}
|
||||
shareId={shareId}
|
||||
allowDownload={allowDownload}
|
||||
downloadInfo={downloadInfo}
|
||||
canEdit={canEdit}
|
||||
onBack={onNavigateBack}
|
||||
hasPrevFile={!!prevFile}
|
||||
hasNextFile={!!nextFile}
|
||||
onPrevFile={() => prevFile && onNavigateToFile(prevFile.id!)}
|
||||
onNextFile={() => nextFile && onNavigateToFile(nextFile.id!)}
|
||||
onSelectVersion={onSelectVersion}
|
||||
onRename={() => {
|
||||
setRenameInput(file.name)
|
||||
setIsRenameDialogOpen(true)
|
||||
}}
|
||||
onDelete={() => setIsDeleteDialogOpen(true)}
|
||||
onLinkedTasks={!isPublic ? () => setIsLinkedTasksOpen(true) : undefined}
|
||||
linkedTaskCount={linkedTaskCount}
|
||||
/>
|
||||
|
||||
{/* Part 2: Media Viewer Content Area */}
|
||||
<div className="relative flex-1 min-h-0 bg-background overflow-hidden flex flex-col">
|
||||
<FileViewer
|
||||
file={file}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
shareId={shareId}
|
||||
allowDownload={allowDownload}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Part 3: Freely Draggable Bottom Sheet */}
|
||||
<MobileFileBottomSheet
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
file={file}
|
||||
onSaveField={onSaveField}
|
||||
members={members}
|
||||
onCommentSelect={handleCommentSelect}
|
||||
hideAnnotationControl={file.proxyType === 'audio'}
|
||||
readOnly={isPublic || !canEdit}
|
||||
publicFields={publicFields}
|
||||
isPublic={isPublic}
|
||||
shareId={shareId}
|
||||
currentTime={currentTime}
|
||||
onTyping={() => mediaControllerRef.current?.pause()}
|
||||
selectedCommentId={selectedCommentId}
|
||||
heightPercent={sheetHeightPercent}
|
||||
onHeightPercentChange={setSheetHeightPercent}
|
||||
/>
|
||||
|
||||
{/* Dialogs */}
|
||||
{!isPublic && isLinkedTasksOpen && (
|
||||
<AssetLinkedTasksDialog
|
||||
teamId={teamId}
|
||||
assetId={activeFileId}
|
||||
assetName={file.name}
|
||||
isOpen={isLinkedTasksOpen}
|
||||
onClose={() => setIsLinkedTasksOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isPublic && (
|
||||
<Dialog open={isRenameDialogOpen} onOpenChange={setIsRenameDialogOpen}>
|
||||
<DialogContent>
|
||||
<form onSubmit={handleRenameSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.rename()}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<Input
|
||||
ref={renameInputRef}
|
||||
value={renameInput}
|
||||
onChange={(e) => setRenameInput(e.target.value)}
|
||||
placeholder={m.enter_new_name?.() || 'Enter new name'}
|
||||
onFocus={() => {
|
||||
setTimeout(() => {
|
||||
if (renameInputRef.current) {
|
||||
selectFileNameWithoutExtension(renameInputRef.current)
|
||||
}
|
||||
}, 0)
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setIsRenameDialogOpen(false)}
|
||||
>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isRenaming || !renameInput.trim()}>
|
||||
{isRenaming && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{m.save()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
|
||||
{!isPublic && (
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.delete_asset_title?.() || 'Delete Asset?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.delete_asset_description?.() ||
|
||||
'Deleted items can be recovered for 30 days before being permanently deleted.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteSubmit}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MobileFileHeader } from './mobile-file-header'
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
files: {
|
||||
'download-url': {
|
||||
$post: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://example.com/download' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
shares: {
|
||||
':shareId': {
|
||||
files: {
|
||||
':fileId': {
|
||||
'download-url': {
|
||||
$post: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://example.com/share-download' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('MobileFileHeader', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders file name, folder name, and back button', () => {
|
||||
const onBack = vi.fn()
|
||||
render(
|
||||
<MobileFileHeader
|
||||
fileName="trailer.mp4"
|
||||
folderName="Rushes"
|
||||
activeFileId="file-1"
|
||||
onBack={onBack}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('trailer.mp4')).toBeDefined()
|
||||
expect(screen.getByText('Rushes')).toBeDefined()
|
||||
|
||||
const backBtn = screen.getByLabelText(/Back|Previous Page/i)
|
||||
fireEvent.click(backBtn)
|
||||
expect(onBack).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('renders and calls prev/next file buttons when available', () => {
|
||||
const onPrevFile = vi.fn()
|
||||
const onNextFile = vi.fn()
|
||||
render(
|
||||
<MobileFileHeader
|
||||
fileName="clip2.mp4"
|
||||
activeFileId="file-2"
|
||||
onBack={vi.fn()}
|
||||
hasPrevFile={true}
|
||||
hasNextFile={true}
|
||||
onPrevFile={onPrevFile}
|
||||
onNextFile={onNextFile}
|
||||
/>,
|
||||
)
|
||||
|
||||
const prevBtn = screen.getByLabelText(/Previous file/i)
|
||||
const nextBtn = screen.getByLabelText(/Next file/i)
|
||||
|
||||
fireEvent.click(prevBtn)
|
||||
expect(onPrevFile).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.click(nextBtn)
|
||||
expect(onNextFile).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('renders version badge and version switch items if multiple versions exist', () => {
|
||||
const onSelectVersion = vi.fn()
|
||||
render(
|
||||
<MobileFileHeader
|
||||
fileName="v2.mp4"
|
||||
version={2}
|
||||
versions={[
|
||||
{ id: 'v-1', version: 1, name: 'v1.mp4' },
|
||||
{ id: 'v-2', version: 2, name: 'v2.mp4' },
|
||||
]}
|
||||
activeFileId="v-2"
|
||||
onBack={vi.fn()}
|
||||
onSelectVersion={onSelectVersion}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('v2')).toBeDefined()
|
||||
})
|
||||
|
||||
it('shows action buttons in three-dot menu', () => {
|
||||
const onRename = vi.fn()
|
||||
const onDelete = vi.fn()
|
||||
render(
|
||||
<MobileFileHeader
|
||||
fileName="scene1.mp4"
|
||||
activeFileId="file-1"
|
||||
canEdit={true}
|
||||
onBack={vi.fn()}
|
||||
onRename={onRename}
|
||||
onDelete={onDelete}
|
||||
/>,
|
||||
)
|
||||
|
||||
const menuBtn = screen.getByLabelText(/More options/i)
|
||||
expect(menuBtn).toBeDefined()
|
||||
fireEvent.click(menuBtn)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,369 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Download,
|
||||
MoreVertical,
|
||||
Pencil,
|
||||
SquareKanban,
|
||||
Trash2,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export interface MobileFileHeaderProps {
|
||||
fileName: string
|
||||
folderName?: string
|
||||
version?: number
|
||||
versions?: Array<{
|
||||
id: string
|
||||
version: number
|
||||
name?: string | null
|
||||
}>
|
||||
activeFileId: string
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
allowDownload?: boolean
|
||||
downloadInfo?: {
|
||||
originalKey?: string
|
||||
videoTranscodes?: Array<{
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
}>
|
||||
}
|
||||
canEdit?: boolean
|
||||
onBack: () => void
|
||||
onPrevFile?: () => void
|
||||
onNextFile?: () => void
|
||||
hasPrevFile?: boolean
|
||||
hasNextFile?: boolean
|
||||
onSelectVersion?: (versionId: string) => void
|
||||
onRename?: () => void
|
||||
onDelete?: () => void
|
||||
onLinkedTasks?: () => void
|
||||
linkedTaskCount?: number
|
||||
}
|
||||
|
||||
export function MobileFileHeader({
|
||||
fileName,
|
||||
folderName,
|
||||
version,
|
||||
versions,
|
||||
activeFileId,
|
||||
isPublic = false,
|
||||
shareId,
|
||||
allowDownload = true,
|
||||
downloadInfo,
|
||||
canEdit = false,
|
||||
onBack,
|
||||
onPrevFile,
|
||||
onNextFile,
|
||||
hasPrevFile = false,
|
||||
hasNextFile = false,
|
||||
onSelectVersion,
|
||||
onRename,
|
||||
onDelete,
|
||||
onLinkedTasks,
|
||||
linkedTaskCount = 0,
|
||||
}: MobileFileHeaderProps) {
|
||||
const handleDownload = async (key: string) => {
|
||||
try {
|
||||
const res =
|
||||
isPublic && shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: activeFileId },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: activeFileId },
|
||||
})
|
||||
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?.length ?? 0) > 0
|
||||
|
||||
return (
|
||||
<header className="flex h-12 w-full items-center justify-between border-b border-border bg-card px-2 py-1.5 shrink-0 select-none z-30">
|
||||
{/* Left: Back Button */}
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onBack}
|
||||
className="h-8 w-8 text-foreground hover:bg-accent cursor-pointer"
|
||||
aria-label={m.previous_page()}
|
||||
>
|
||||
<ChevronLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Center: Folder / File Title & Prev / Next Arrows */}
|
||||
<div className="flex flex-1 items-center justify-center gap-1 min-w-0 px-1">
|
||||
<div className="flex items-center min-w-0 max-w-[65vw]">
|
||||
{folderName && (
|
||||
<>
|
||||
<span className="truncate text-xs font-medium text-muted-foreground max-w-[80px]">
|
||||
{folderName}
|
||||
</span>
|
||||
<span className="text-muted-foreground mx-1 text-xs">/</span>
|
||||
</>
|
||||
)}
|
||||
|
||||
{versions && versions.length > 1 ? (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex items-center gap-1 min-w-0 truncate text-xs font-medium text-foreground hover:bg-accent rounded px-1 py-0.5 transition-colors cursor-pointer">
|
||||
<span className="truncate max-w-[120px] font-semibold">{fileName}</span>
|
||||
{version !== undefined && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-[10px] shrink-0 font-normal">
|
||||
v{version}
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center" className="w-48 z-40">
|
||||
<DropdownMenuLabel className="text-xs">{m.switch_version()}</DropdownMenuLabel>
|
||||
{versions.map((v) => (
|
||||
<DropdownMenuItem
|
||||
key={v.id}
|
||||
onClick={() => onSelectVersion?.(v.id)}
|
||||
className={cn(
|
||||
'flex items-center justify-between text-xs cursor-pointer',
|
||||
v.id === activeFileId ? 'bg-accent font-semibold text-accent-foreground' : '',
|
||||
)}
|
||||
>
|
||||
<span>v{v.version}</span>
|
||||
<span className="text-[11px] text-muted-foreground truncate max-w-[120px]">
|
||||
{v.name || fileName}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<div className="flex items-center gap-1 min-w-0 truncate">
|
||||
<span className="truncate text-xs font-semibold text-foreground max-w-[140px]">
|
||||
{fileName}
|
||||
</span>
|
||||
{version !== undefined && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-[10px] shrink-0 font-normal">
|
||||
v{version}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Prev / Next file navigation buttons */}
|
||||
{(hasPrevFile || hasNextFile) && (
|
||||
<div className="flex items-center gap-0.5 shrink-0 bg-muted/60 rounded p-0.5 ml-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!hasPrevFile}
|
||||
onClick={onPrevFile}
|
||||
className="h-5 w-5 p-0 text-muted-foreground hover:text-foreground disabled:opacity-30 cursor-pointer"
|
||||
title={m.previous_file()}
|
||||
aria-label={m.previous_file()}
|
||||
>
|
||||
<ChevronLeft className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!hasNextFile}
|
||||
onClick={onNextFile}
|
||||
className="h-5 w-5 p-0 text-muted-foreground hover:text-foreground disabled:opacity-30 cursor-pointer"
|
||||
title={m.next_file()}
|
||||
aria-label={m.next_file()}
|
||||
>
|
||||
<ChevronRight className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right: Three-Dot Menu */}
|
||||
<div className="flex items-center gap-1">
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-foreground hover:bg-accent cursor-pointer"
|
||||
aria-label={m.more_options()}
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-52 z-40">
|
||||
{/* Download */}
|
||||
{allowDownload &&
|
||||
(hasVideoTranscodes ? (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="flex items-center gap-2 text-xs cursor-pointer">
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
<span>{m.download()}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent className="w-48 z-50">
|
||||
<DropdownMenuLabel className="text-xs">{m.download()}</DropdownMenuLabel>
|
||||
{downloadInfo?.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 (
|
||||
<DropdownMenuItem
|
||||
key={resolution}
|
||||
onClick={() => handleDownload(t.key)}
|
||||
className="flex items-center justify-between text-xs cursor-pointer"
|
||||
>
|
||||
<span>{resolution}</span>
|
||||
<span className="text-[10px] text-muted-foreground">MP4</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
{downloadInfo?.originalKey && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDownload(downloadInfo.originalKey!)}
|
||||
className="flex items-center justify-between text-xs cursor-pointer"
|
||||
>
|
||||
<span>{m.original?.() || 'Original'}</span>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{fileName.split('.').pop()?.toUpperCase() || 'RAW'}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
downloadInfo?.originalKey && handleDownload(downloadInfo.originalKey)
|
||||
}
|
||||
disabled={!downloadInfo?.originalKey}
|
||||
className="flex items-center gap-2 text-xs cursor-pointer"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
<span>{m.download()}</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
|
||||
{/* Switch Version (if multi-version) */}
|
||||
{versions && versions.length > 1 && onSelectVersion && (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="flex items-center gap-2 text-xs cursor-pointer">
|
||||
<span>{m.switch_version?.() || 'Switch version'}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent className="w-48 z-50">
|
||||
<DropdownMenuLabel className="text-xs">
|
||||
{m.switch_version?.() || 'Switch version'}
|
||||
</DropdownMenuLabel>
|
||||
{versions.map((v) => (
|
||||
<DropdownMenuItem
|
||||
key={v.id}
|
||||
onClick={() => onSelectVersion(v.id)}
|
||||
className={cn(
|
||||
'flex items-center justify-between text-xs cursor-pointer',
|
||||
v.id === activeFileId
|
||||
? 'bg-accent font-semibold text-accent-foreground'
|
||||
: '',
|
||||
)}
|
||||
>
|
||||
<span>v{v.version}</span>
|
||||
<span className="text-[10px] text-muted-foreground truncate max-w-[120px]">
|
||||
{v.name || fileName}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
)}
|
||||
|
||||
{/* Linked Tasks */}
|
||||
{onLinkedTasks && (
|
||||
<DropdownMenuItem
|
||||
onClick={onLinkedTasks}
|
||||
className="flex items-center justify-between text-xs cursor-pointer"
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<SquareKanban className="h-3.5 w-3.5" />
|
||||
<span>{m.linked_tasks?.() || 'Linked Tasks'}</span>
|
||||
</span>
|
||||
{linkedTaskCount > 0 && (
|
||||
<span className="inline-flex items-center justify-center px-1.5 py-0.2 text-[10px] font-semibold rounded-full bg-muted-foreground/15 text-foreground">
|
||||
{linkedTaskCount}
|
||||
</span>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{/* Rename */}
|
||||
{canEdit && onRename && (
|
||||
<DropdownMenuItem
|
||||
onClick={onRename}
|
||||
className="flex items-center gap-2 text-xs cursor-pointer"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
<span>{m.rename()}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{/* Delete */}
|
||||
{canEdit && onDelete && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={onDelete}
|
||||
className="flex items-center gap-2 text-xs text-destructive focus:text-destructive cursor-pointer"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
<span>{m.delete()}</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
@@ -5,8 +5,11 @@ import { useTopNavStore } from '@/ui/stores/top-nav'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useState, useMemo, useRef } from 'react'
|
||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
import { TopNav } from './top-nav'
|
||||
import { FileBrowser } from './file-browser/file-browser'
|
||||
import { MobileFileBrowser } from './file-browser/mobile-file-browser'
|
||||
import { MobileFileDetail } from './file-viewer/mobile-file-detail'
|
||||
import { FileViewerRightSidebar } from './file-viewer-right-sidebar'
|
||||
import { ResizeHandle } from './resize-handle'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from './ui/card'
|
||||
@@ -61,6 +64,7 @@ export function PublicShareManager({
|
||||
compareActiveSide = 'left',
|
||||
}: PublicShareManagerProps) {
|
||||
const navigate = useNavigate()
|
||||
const isMobile = useIsMobile()
|
||||
const isCompareMode = !!compare && !!compareLeftId && !!compareRightId
|
||||
const [password, setPassword] = useState(() => {
|
||||
return localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
@@ -294,6 +298,11 @@ export function PublicShareManager({
|
||||
[filesData],
|
||||
)
|
||||
|
||||
const totalFolders = foldersData?.pages[0]?.pageInfo?.total
|
||||
const totalFiles = filesData?.pages[0]?.pageInfo?.total
|
||||
const totalFoldersSize = foldersData?.pages[0]?.pageInfo?.totalSize
|
||||
const totalFilesSize = filesData?.pages[0]?.pageInfo?.totalSize
|
||||
|
||||
const currentSelectedItem = useMemo(() => {
|
||||
if (viewingFileData) return viewingFileData
|
||||
if (selectedIds.size !== 1) return null
|
||||
@@ -544,128 +553,226 @@ export function PublicShareManager({
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
content = (
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{viewingFileId ? (
|
||||
<div className="flex-1 relative bg-muted/30">
|
||||
{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>
|
||||
)}
|
||||
{isCompareMode && compareLeftId && compareRightId ? (
|
||||
<CompareViewer
|
||||
isPublic
|
||||
shareId={shareId}
|
||||
versions={viewingFileData?.versionStack?.versions ?? []}
|
||||
leftId={compareLeftId}
|
||||
rightId={compareRightId}
|
||||
activeSide={compareActiveSide}
|
||||
annotations={annotations}
|
||||
seekRequest={seekRequest}
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
onActiveSideChange={(side) => updateCompareSearch({ cmpActive: side })}
|
||||
onSwitchVersion={(side, versionId) =>
|
||||
updateCompareSearch(
|
||||
side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
|
||||
)
|
||||
}
|
||||
onExit={handleCompareExit}
|
||||
onActiveAssetChange={setCompareActiveAsset}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
/>
|
||||
) : (
|
||||
viewingFileData && (
|
||||
<FileViewer
|
||||
file={viewingFileData}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
if (isMobile && viewingFileId && !isCompareMode && viewingFileData) {
|
||||
const containingFolderId =
|
||||
viewingFileData?.ancestorFolders?.[0]?.id ||
|
||||
(currentFolderId !== shareInfo.rootFolderId ? currentFolderId : undefined)
|
||||
const publicAncestorFolders =
|
||||
viewingFileData?.ancestorFolders && viewingFileData.ancestorFolders.length > 0
|
||||
? viewingFileData.ancestorFolders
|
||||
: ancestorFolders
|
||||
|
||||
content = (
|
||||
<MobileFileDetail
|
||||
projectId={shareInfo.projectId}
|
||||
fileId={viewingFileId}
|
||||
file={viewingFileData}
|
||||
projectInfo={{ name: shareInfo.name, rootFolder: shareInfo.rootFolderId }}
|
||||
ancestorFolders={publicAncestorFolders}
|
||||
versions={
|
||||
stackFileData?.versionStack?.versions ?? viewingFileData?.versionStack?.versions
|
||||
}
|
||||
activeFileId={activeFileId || viewingFileId}
|
||||
startTime={startTime}
|
||||
isPublic={true}
|
||||
shareId={shareId}
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
publicFields={publicFields}
|
||||
siblingFiles={files}
|
||||
onNavigateToFile={(targetId) => {
|
||||
navigate({
|
||||
to: '/share/$shareId/files/$fileId',
|
||||
params: { shareId, fileId: targetId },
|
||||
})
|
||||
}}
|
||||
onNavigateBack={() => {
|
||||
if (containingFolderId && containingFolderId !== shareInfo.rootFolderId) {
|
||||
navigate({
|
||||
to: '/share/$shareId/folders/$folderId',
|
||||
params: { shareId, folderId: containingFolderId },
|
||||
})
|
||||
} else {
|
||||
navigate({
|
||||
to: '/share/$shareId',
|
||||
params: { shareId },
|
||||
})
|
||||
}
|
||||
}}
|
||||
onSelectVersion={(newVerId) => {
|
||||
navigate({
|
||||
to: '/share/$shareId/files/$fileId',
|
||||
params: { shareId, fileId: viewingFileId },
|
||||
search: (prev: Record<string, unknown>) => ({
|
||||
...prev,
|
||||
version: newVerId,
|
||||
}),
|
||||
})
|
||||
}}
|
||||
onSaveField={() => {}}
|
||||
/>
|
||||
)
|
||||
} else {
|
||||
content = (
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{viewingFileId ? (
|
||||
<div className="flex-1 relative bg-muted/30">
|
||||
{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>
|
||||
)}
|
||||
{isCompareMode && compareLeftId && compareRightId ? (
|
||||
<CompareViewer
|
||||
isPublic
|
||||
shareId={shareId}
|
||||
versions={viewingFileData?.versionStack?.versions ?? []}
|
||||
leftId={compareLeftId}
|
||||
rightId={compareRightId}
|
||||
activeSide={compareActiveSide}
|
||||
annotations={annotations}
|
||||
seekRequest={seekRequest}
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
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}
|
||||
shareId={shareId}
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
currentFolderId && (
|
||||
<FileBrowser
|
||||
teamId=""
|
||||
projectId={shareInfo.projectId}
|
||||
assetId={currentFolderId}
|
||||
folders={folders}
|
||||
files={files}
|
||||
selectedItem={null}
|
||||
selectedIds={selectedIds}
|
||||
onItemSelect={(item, e) => {
|
||||
if (e.metaKey || e.ctrlKey) {
|
||||
const next = new Set(selectedIds)
|
||||
if (next.has(item.id!)) next.delete(item.id!)
|
||||
else next.add(item.id!)
|
||||
setSelectedIds(next)
|
||||
} else {
|
||||
setSelectedIds(new Set([item.id!]))
|
||||
}
|
||||
}}
|
||||
onItemDoubleClick={handleItemDoubleClick}
|
||||
onSaveField={() => {}}
|
||||
displayStyle={(shareInfo.viewMode as 'card' | 'list') ?? 'card'}
|
||||
onClearSelection={() => setSelectedIds(new Set())}
|
||||
fetchNextFoldersPage={fetchNextFoldersPage}
|
||||
hasNextFoldersPage={hasNextPageFolders}
|
||||
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
|
||||
fetchNextFilesPage={fetchNextFilesPage}
|
||||
hasNextFilesPage={hasNextPageFiles}
|
||||
isFetchingNextFilesPage={isFetchingNextFilesPage}
|
||||
isShareView={true}
|
||||
isPublic={true}
|
||||
shareId={shareId}
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
|
||||
{!isRightSidebarCollapsed && (
|
||||
<>
|
||||
<ResizeHandle
|
||||
onResize={(delta) =>
|
||||
setRightSidebarWidth((p) => Math.max(240, Math.min(600, p - delta)))
|
||||
}
|
||||
/>
|
||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0 border-l">
|
||||
<FileViewerRightSidebar
|
||||
) : (
|
||||
viewingFileData && (
|
||||
<FileViewer
|
||||
file={viewingFileData}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
shareId={shareId}
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
currentFolderId &&
|
||||
(isMobile ? (
|
||||
<MobileFileBrowser
|
||||
teamId=""
|
||||
projectId={shareInfo.projectId}
|
||||
file={isCompareMode ? compareActiveAsset : currentSelectedItem}
|
||||
onSaveField={() => {}}
|
||||
members={[]}
|
||||
readOnly={true}
|
||||
publicFields={publicFields}
|
||||
onCommentSelect={handleCommentSelect}
|
||||
assetId={currentFolderId}
|
||||
folders={folders}
|
||||
files={files}
|
||||
totalFolders={totalFolders}
|
||||
totalFiles={totalFiles}
|
||||
totalFoldersSize={totalFoldersSize}
|
||||
totalFilesSize={totalFilesSize}
|
||||
selectedItem={null}
|
||||
selectedIds={selectedIds}
|
||||
onItemSelect={(item, e) => {
|
||||
if (e.metaKey || e.ctrlKey) {
|
||||
const next = new Set(selectedIds)
|
||||
if (next.has(item.id!)) next.delete(item.id!)
|
||||
else next.add(item.id!)
|
||||
setSelectedIds(next)
|
||||
} else {
|
||||
setSelectedIds(new Set([item.id!]))
|
||||
}
|
||||
}}
|
||||
onItemDoubleClick={handleItemDoubleClick}
|
||||
onClearSelection={() => setSelectedIds(new Set())}
|
||||
fetchNextFoldersPage={fetchNextFoldersPage}
|
||||
hasNextFoldersPage={hasNextPageFolders}
|
||||
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
|
||||
fetchNextFilesPage={fetchNextFilesPage}
|
||||
hasNextFilesPage={hasNextPageFiles}
|
||||
isFetchingNextFilesPage={isFetchingNextFilesPage}
|
||||
isShareView={true}
|
||||
isPublic={true}
|
||||
shareId={shareId}
|
||||
currentTime={currentTime}
|
||||
onTyping={() => {
|
||||
mediaControllerRef.current?.pause()
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
/>
|
||||
) : (
|
||||
<FileBrowser
|
||||
teamId=""
|
||||
projectId={shareInfo.projectId}
|
||||
assetId={currentFolderId}
|
||||
folders={folders}
|
||||
files={files}
|
||||
selectedItem={null}
|
||||
selectedIds={selectedIds}
|
||||
onItemSelect={(item, e) => {
|
||||
if (e.metaKey || e.ctrlKey) {
|
||||
const next = new Set(selectedIds)
|
||||
if (next.has(item.id!)) next.delete(item.id!)
|
||||
else next.add(item.id!)
|
||||
setSelectedIds(next)
|
||||
} else {
|
||||
setSelectedIds(new Set([item.id!]))
|
||||
}
|
||||
}}
|
||||
selectedCommentId={selectedCommentId}
|
||||
hideAnnotationControl={
|
||||
(isCompareMode ? compareActiveAsset : currentSelectedItem)?.proxyType === 'audio'
|
||||
onItemDoubleClick={handleItemDoubleClick}
|
||||
onSaveField={() => {}}
|
||||
displayStyle={(shareInfo.viewMode as 'card' | 'list') ?? 'card'}
|
||||
onClearSelection={() => setSelectedIds(new Set())}
|
||||
fetchNextFoldersPage={fetchNextFoldersPage}
|
||||
hasNextFoldersPage={hasNextPageFolders}
|
||||
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
|
||||
fetchNextFilesPage={fetchNextFilesPage}
|
||||
hasNextFilesPage={hasNextPageFiles}
|
||||
isFetchingNextFilesPage={isFetchingNextFilesPage}
|
||||
isShareView={true}
|
||||
isPublic={true}
|
||||
shareId={shareId}
|
||||
allowDownload={shareInfo.allowDownload}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
|
||||
{!isRightSidebarCollapsed && !isMobile && (
|
||||
<>
|
||||
<ResizeHandle
|
||||
onResize={(delta) =>
|
||||
setRightSidebarWidth((p) => Math.max(240, Math.min(600, p - delta)))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0 border-l">
|
||||
<FileViewerRightSidebar
|
||||
teamId=""
|
||||
projectId={shareInfo.projectId}
|
||||
file={isCompareMode ? compareActiveAsset : currentSelectedItem}
|
||||
onSaveField={() => {}}
|
||||
members={[]}
|
||||
readOnly={true}
|
||||
publicFields={publicFields}
|
||||
onCommentSelect={handleCommentSelect}
|
||||
isPublic={true}
|
||||
shareId={shareId}
|
||||
currentTime={currentTime}
|
||||
onTyping={() => {
|
||||
mediaControllerRef.current?.pause()
|
||||
}}
|
||||
selectedCommentId={selectedCommentId}
|
||||
hideAnnotationControl={
|
||||
(isCompareMode ? compareActiveAsset : currentSelectedItem)?.proxyType ===
|
||||
'audio'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background">
|
||||
<TopNav />
|
||||
<div className="flex h-[100dvh] flex-col bg-background">
|
||||
{(!isMobile || !viewingFileId) && <TopNav />}
|
||||
{content}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -3,11 +3,17 @@ import { BreadcrumbNav } from './breadcrumb-nav'
|
||||
import { ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useChatbotStore } from '@/ui/stores/chatbot'
|
||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
|
||||
export function TopNav() {
|
||||
const { projectState } = useTopNavStore()
|
||||
const uiStore = useUiStore()
|
||||
const { isChatbotOpen, setIsChatbotOpen } = useChatbotStore()
|
||||
const isMobile = useIsMobile()
|
||||
|
||||
if (isMobile && projectState?.fileId) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!projectState) {
|
||||
return <TeamHeader />
|
||||
@@ -134,10 +140,27 @@ export function TopNav() {
|
||||
)
|
||||
}
|
||||
|
||||
import { Menu } from 'lucide-react'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { useDualSidebarStore } from '@/ui/stores/dual-sidebar'
|
||||
|
||||
function TeamHeader() {
|
||||
const { toggleMobileMenu } = useDualSidebarStore()
|
||||
return (
|
||||
<div className="flex h-14 flex-wrap items-center justify-center gap-2 border-b border-border bg-card px-4 py-2 flex-shrink-0">
|
||||
<ShumaiLogo className="w-10 h-10 text-orange-600" />
|
||||
<div className="flex h-14 items-center justify-between border-b border-border bg-card px-4 py-2 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleMobileMenu}
|
||||
className="md:hidden text-foreground hover:bg-accent -ml-2"
|
||||
aria-label="Open navigation menu"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</Button>
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<ShumaiLogo className="w-10 h-10 text-orange-600" />
|
||||
</div>
|
||||
<div className="w-9 md:hidden" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { EditableText } from './editable-text'
|
||||
|
||||
describe('EditableText', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
vi.useRealTimers()
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders a span in read-only (disabled) mode with the value', () => {
|
||||
render(<EditableText value="MyLongFileName.mp4" disabled={true} />)
|
||||
|
||||
expect(screen.queryByRole('textbox')).toBeNull()
|
||||
const span = screen.getByText('MyLongFileName.mp4')
|
||||
expect(span).toBeTruthy()
|
||||
expect(span.tagName.toLowerCase()).toBe('span')
|
||||
expect(span.className).toContain('truncate')
|
||||
})
|
||||
|
||||
it('renders an input in editable (!disabled) mode', () => {
|
||||
const handleChange = vi.fn()
|
||||
render(<EditableText value="MyFile.txt" disabled={false} onChange={handleChange} />)
|
||||
|
||||
const input = screen.getByRole('textbox') as HTMLInputElement
|
||||
expect(input).toBeTruthy()
|
||||
expect(input.value).toBe('MyFile.txt')
|
||||
})
|
||||
|
||||
it('does not show tooltip on hover when text is not truncated', () => {
|
||||
render(<EditableText value="Short.png" disabled={true} />)
|
||||
|
||||
const span = screen.getByText('Short.png')
|
||||
Object.defineProperty(span, 'scrollWidth', { value: 80, configurable: true })
|
||||
Object.defineProperty(span, 'clientWidth', { value: 100, configurable: true })
|
||||
|
||||
fireEvent.pointerMove(span, { pointerType: 'mouse' })
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
// Tooltip should not be displayed
|
||||
expect(screen.queryByRole('tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows full name in tooltip after 100ms when text is truncated', () => {
|
||||
render(
|
||||
<EditableText
|
||||
value="A_very_long_file_name_that_will_overflow_the_column_width.mov"
|
||||
disabled={true}
|
||||
/>,
|
||||
)
|
||||
|
||||
const span = screen.getByText('A_very_long_file_name_that_will_overflow_the_column_width.mov')
|
||||
Object.defineProperty(span, 'scrollWidth', { value: 300, configurable: true })
|
||||
Object.defineProperty(span, 'clientWidth', { value: 120, configurable: true })
|
||||
|
||||
fireEvent.pointerMove(span, { pointerType: 'mouse' })
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
const tooltip = screen.getByRole('tooltip')
|
||||
expect(tooltip).toBeTruthy()
|
||||
expect(tooltip.textContent).toContain(
|
||||
'A_very_long_file_name_that_will_overflow_the_column_width.mov',
|
||||
)
|
||||
})
|
||||
|
||||
it('handles input events and keydown when editing', () => {
|
||||
const handleKeyDown = vi.fn()
|
||||
const handleBlur = vi.fn()
|
||||
render(
|
||||
<EditableText
|
||||
value="Editable.txt"
|
||||
disabled={false}
|
||||
onKeyDown={handleKeyDown}
|
||||
onBlur={handleBlur}
|
||||
/>,
|
||||
)
|
||||
|
||||
const input = screen.getByRole('textbox')
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
expect(handleKeyDown).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.blur(input)
|
||||
expect(handleBlur).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -1,33 +1,96 @@
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/ui/components/ui/tooltip'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import React from 'react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
|
||||
export type EditableTextProps = React.ComponentPropsWithoutRef<'input'>
|
||||
export type EditableTextProps = React.ComponentPropsWithoutRef<'input'> & {
|
||||
tooltipSide?: 'top' | 'right' | 'bottom' | 'left'
|
||||
tooltipDelayDuration?: number
|
||||
}
|
||||
|
||||
const EditableText = React.forwardRef<HTMLInputElement, EditableTextProps>(
|
||||
({ className, onClick, onMouseDown, disabled, ...props }, ref) => {
|
||||
(
|
||||
{
|
||||
className,
|
||||
onClick,
|
||||
onMouseDown,
|
||||
disabled,
|
||||
value,
|
||||
title: _title,
|
||||
tooltipSide = 'top',
|
||||
tooltipDelayDuration = 100,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const spanRef = useRef<HTMLSpanElement>(null)
|
||||
|
||||
const textContent = typeof value === 'string' ? value : (value?.toString() ?? '')
|
||||
|
||||
if (disabled) {
|
||||
return (
|
||||
<TooltipProvider delayDuration={tooltipDelayDuration}>
|
||||
<Tooltip
|
||||
open={isOpen}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nextOpen) {
|
||||
if (spanRef.current && spanRef.current.scrollWidth > spanRef.current.clientWidth) {
|
||||
setIsOpen(true)
|
||||
} else {
|
||||
setIsOpen(false)
|
||||
}
|
||||
} else {
|
||||
setIsOpen(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
ref={spanRef}
|
||||
className={cn(
|
||||
'box-border block min-w-0 w-full rounded-sm border border-transparent px-1 py-0.5 text-base shadow-none transition-all outline-none cursor-default opacity-100 select-none truncate',
|
||||
className,
|
||||
)}
|
||||
onClick={onClick}
|
||||
onMouseDown={onMouseDown}
|
||||
>
|
||||
{textContent}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
{isOpen && (
|
||||
<TooltipContent
|
||||
side={tooltipSide}
|
||||
className="max-w-md break-all text-wrap [text-wrap:normal] text-left"
|
||||
>
|
||||
{textContent}
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Input
|
||||
ref={ref}
|
||||
readOnly={disabled}
|
||||
tabIndex={disabled ? -1 : undefined}
|
||||
value={value}
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
'h-auto min-h-0 w-full rounded-sm border px-1 py-0.5 text-base shadow-none transition-all outline-none focus-visible:ring-0',
|
||||
!disabled
|
||||
? 'border-blue-500 !bg-muted/10 ring-1 ring-blue-500'
|
||||
: 'border-transparent !bg-transparent cursor-default opacity-100 focus-visible:border-transparent focus-visible:ring-0 caret-transparent select-none',
|
||||
'box-border block min-w-0 h-auto w-full rounded-sm border border-blue-500 !bg-muted/10 ring-1 ring-blue-500 px-1 py-0.5 text-base shadow-none transition-all outline-none focus-visible:ring-0',
|
||||
className,
|
||||
)}
|
||||
onClick={(e) => {
|
||||
if (!disabled) {
|
||||
e.stopPropagation()
|
||||
}
|
||||
e.stopPropagation()
|
||||
onClick?.(e)
|
||||
}}
|
||||
onMouseDown={(e) => {
|
||||
if (!disabled) {
|
||||
e.stopPropagation()
|
||||
}
|
||||
e.stopPropagation()
|
||||
onMouseDown?.(e)
|
||||
}}
|
||||
{...props}
|
||||
|
||||
@@ -28,24 +28,29 @@ export function PdfControlBar({
|
||||
allowDownload = true,
|
||||
}: PdfControlBarProps) {
|
||||
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-between gap-2 transition-colors duration-200">
|
||||
<div className="relative px-2 py-2 sm:px-4 sm:py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-between gap-1.5 sm:gap-2 transition-colors duration-200 shrink-0">
|
||||
{/* Page Navigation */}
|
||||
<div className="flex items-center gap-1.5 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5">
|
||||
<div className="flex items-center gap-1 sm:gap-1.5 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 shrink-0">
|
||||
<button
|
||||
onClick={() => onPageChange(Math.max(1, currentPage - 1))}
|
||||
disabled={currentPage <= 1}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40"
|
||||
className="p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40"
|
||||
title={m.previous_page()}
|
||||
>
|
||||
<ChevronLeft size={16} />
|
||||
</button>
|
||||
<span className="px-2 text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
|
||||
{m.page_of_pages({ current: currentPage, total: totalPages || 1 })}
|
||||
<span className="px-1 sm:px-2 text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none whitespace-nowrap">
|
||||
<span className="hidden sm:inline">
|
||||
{m.page_of_pages({ current: currentPage, total: totalPages || 1 })}
|
||||
</span>
|
||||
<span className="inline sm:hidden">
|
||||
{currentPage}/{totalPages || 1}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
onClick={() => onPageChange(Math.min(totalPages, currentPage + 1))}
|
||||
disabled={currentPage >= totalPages}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40"
|
||||
className="p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40"
|
||||
title={m.next_page()}
|
||||
>
|
||||
<ChevronRight size={16} />
|
||||
@@ -53,21 +58,21 @@ export function PdfControlBar({
|
||||
</div>
|
||||
|
||||
{/* Zoom & Action Controls */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5">
|
||||
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
|
||||
<div className="flex items-center gap-0.5 sm:gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5">
|
||||
<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"
|
||||
className="p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title={m.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">
|
||||
<span className="w-10 sm: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"
|
||||
className="p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title={m.zoom_in()}
|
||||
>
|
||||
<Plus size={16} />
|
||||
@@ -75,7 +80,7 @@ export function PdfControlBar({
|
||||
</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"
|
||||
className="text-xs font-medium px-2 py-1 sm:px-3 sm: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"
|
||||
>
|
||||
{m.fit()}
|
||||
</button>
|
||||
@@ -83,11 +88,11 @@ export function PdfControlBar({
|
||||
<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"
|
||||
className="flex items-center gap-1 text-xs font-medium px-2 py-1 sm:px-3 sm: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"
|
||||
title={m.download_original_file()}
|
||||
>
|
||||
<Download size={14} />
|
||||
{m.download()}
|
||||
<span className="hidden sm:inline">{m.download()}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -20,13 +20,19 @@ const MAX_RENDER_PIXELS = 32_000_000
|
||||
const MAX_RENDER_SCALE = 16
|
||||
|
||||
if (typeof window !== 'undefined' && pdfjsLib.GlobalWorkerOptions) {
|
||||
const workerPath =
|
||||
typeof pdfworker === 'string'
|
||||
? pdfworker.startsWith('/')
|
||||
? pdfworker
|
||||
: '/' + pdfworker.replace(/^\.\//, '')
|
||||
: pdfworker
|
||||
pdfjsLib.GlobalWorkerOptions.workerSrc = workerPath
|
||||
try {
|
||||
const workerPath =
|
||||
typeof pdfworker === 'string'
|
||||
? pdfworker.startsWith('/')
|
||||
? pdfworker
|
||||
: '/' + pdfworker.replace(/^\.\//, '')
|
||||
: (pdfworker as unknown as string)
|
||||
if (typeof workerPath === 'string') {
|
||||
pdfjsLib.GlobalWorkerOptions.workerSrc = workerPath
|
||||
}
|
||||
} catch {
|
||||
// Ignore in test/non-standard environments
|
||||
}
|
||||
}
|
||||
|
||||
export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MobileVideoControlBar } from './mobile-video-control-bar'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
import type { DisplayTranscode } from './video-control-bar'
|
||||
|
||||
describe('MobileVideoControlBar', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const mockData: AssetInfo = {
|
||||
id: 'video-1',
|
||||
name: 'sample.mp4',
|
||||
proxyType: 'video',
|
||||
media: {
|
||||
metadata: {
|
||||
duration: 100,
|
||||
frameRate: 25,
|
||||
},
|
||||
},
|
||||
} as AssetInfo
|
||||
|
||||
const defaultState = {
|
||||
isPlaying: false,
|
||||
progress: 10,
|
||||
currentTime: 10,
|
||||
duration: 100,
|
||||
volume: 1,
|
||||
isMuted: false,
|
||||
isLooping: false,
|
||||
playbackRate: 1,
|
||||
isFullScreen: false,
|
||||
showFrames: false,
|
||||
currentResolution: '720p',
|
||||
}
|
||||
|
||||
it('renders play, mute, timecode readout, settings, and fullscreen buttons', () => {
|
||||
const togglePlay = vi.fn()
|
||||
const toggleMute = vi.fn()
|
||||
const toggleFullScreen = vi.fn()
|
||||
|
||||
render(
|
||||
<MobileVideoControlBar
|
||||
state={defaultState}
|
||||
zoom={1}
|
||||
isControlsVisible={true}
|
||||
buffered={50}
|
||||
data={mockData}
|
||||
resolutions={[
|
||||
{
|
||||
key: '720.mp4',
|
||||
width: 1280,
|
||||
height: 720,
|
||||
resolution: '720p',
|
||||
} as unknown as DisplayTranscode,
|
||||
]}
|
||||
togglePlay={togglePlay}
|
||||
toggleLoop={vi.fn()}
|
||||
toggleMute={toggleMute}
|
||||
handleVolumeChange={vi.fn()}
|
||||
changePlaybackRate={vi.fn()}
|
||||
changeResolution={vi.fn()}
|
||||
handleDownload={vi.fn()}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
onZoomChange={vi.fn()}
|
||||
onZoomReset={vi.fn()}
|
||||
frameRate={25}
|
||||
totalFrames={2500}
|
||||
currentFrame={250}
|
||||
seekToFrame={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
const playBtn = screen.getByTestId('play-toggle')
|
||||
expect(playBtn).toBeDefined()
|
||||
fireEvent.click(playBtn)
|
||||
expect(togglePlay).toHaveBeenCalledTimes(1)
|
||||
|
||||
const muteBtn = screen.getByLabelText(/Mute|Unmute/i)
|
||||
expect(muteBtn).toBeDefined()
|
||||
fireEvent.click(muteBtn)
|
||||
expect(toggleMute).toHaveBeenCalledTimes(1)
|
||||
|
||||
const timeReadout = screen.getByTestId('time-readout')
|
||||
expect(timeReadout).toBeDefined()
|
||||
|
||||
const fsBtn = screen.getByTitle(/Fullscreen/i)
|
||||
expect(fsBtn).toBeDefined()
|
||||
fireEvent.click(fsBtn)
|
||||
expect(toggleFullScreen).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,271 @@
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
Maximize,
|
||||
Minimize,
|
||||
Pause,
|
||||
Play,
|
||||
Repeat,
|
||||
Settings,
|
||||
Volume2,
|
||||
VolumeX,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '../../ui/dropdown-menu'
|
||||
import ProgressBar from './progress-bar'
|
||||
import { formatTime, formatTimecode } from './utils'
|
||||
import type { ControlBarProps } from './video-control-bar'
|
||||
|
||||
export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
|
||||
state,
|
||||
isControlsVisible,
|
||||
buffered,
|
||||
data,
|
||||
resolutions,
|
||||
togglePlay,
|
||||
toggleLoop,
|
||||
toggleMute,
|
||||
changePlaybackRate,
|
||||
changeResolution,
|
||||
toggleFullScreen,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
currentFrame,
|
||||
seekToFrame,
|
||||
floatOverlayInFullScreen = true,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
}) => {
|
||||
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
|
||||
|
||||
if (!data.media?.metadata) {
|
||||
return null
|
||||
}
|
||||
|
||||
const overlay = state.isFullScreen && floatOverlayInFullScreen
|
||||
const isAudio = data.proxyType === 'audio'
|
||||
|
||||
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-3 py-3 bg-card/90 backdrop-blur-md border-t border-border'
|
||||
: 'relative w-full bg-card border-t border-border px-3 py-2.5 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-2 px-0.5">
|
||||
<ProgressBar
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
fps={frameRate}
|
||||
buffered={buffered}
|
||||
previewUrl={data.media.videoPreview?.url}
|
||||
onSeek={seekToFrame}
|
||||
metadata={{
|
||||
...data.media.metadata,
|
||||
frameRate: frameRate,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Control Row */}
|
||||
<div className="flex items-center justify-between text-foreground gap-1 select-none">
|
||||
{/* Left Side: Play, Mute, Time */}
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<button
|
||||
onClick={togglePlay}
|
||||
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
|
||||
data-testid="play-toggle"
|
||||
data-playing={state.isPlaying}
|
||||
aria-label={state.isPlaying ? 'Pause' : 'Play'}
|
||||
>
|
||||
{state.isPlaying ? (
|
||||
<Pause className="w-5 h-5 fill-current" />
|
||||
) : (
|
||||
<Play className="w-5 h-5 fill-current" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={toggleMute}
|
||||
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
|
||||
aria-label={state.isMuted ? 'Unmute' : 'Mute'}
|
||||
>
|
||||
{state.isMuted || state.volume === 0 ? (
|
||||
<VolumeX className="w-5 h-5" />
|
||||
) : (
|
||||
<Volume2 className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-0.5 text-xs font-medium tabular-nums min-w-0">
|
||||
<span
|
||||
className="text-muted-foreground font-mono truncate text-[11px] sm:text-xs"
|
||||
data-testid="time-readout"
|
||||
>
|
||||
{displayString}
|
||||
</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
className="h-5 w-5 inline-flex items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none shrink-0"
|
||||
aria-label={m.change_time_format()}
|
||||
>
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-40 z-30">
|
||||
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
|
||||
{m.format()}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setVideoTimeDisplayMode('standard')}
|
||||
className="flex items-center justify-between cursor-pointer text-xs"
|
||||
>
|
||||
<span>{m.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>{m.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>{m.timecode()}</span>
|
||||
{videoTimeDisplayMode === 'timecode' && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side: Settings (Quality + Speed) & Fullscreen */}
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
className="flex items-center gap-1 rounded border border-border px-1.5 py-1 text-xs font-semibold hover:bg-muted transition-colors cursor-pointer"
|
||||
title={m.settings()}
|
||||
aria-label={m.settings()}
|
||||
>
|
||||
<Settings className="h-3.5 w-3.5" />
|
||||
<span className="text-[11px]">
|
||||
{!isAudio && state.currentResolution
|
||||
? state.currentResolution
|
||||
: `${state.playbackRate}x`}
|
||||
</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48 z-30">
|
||||
{!isAudio && resolutions.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
|
||||
{m.quality()}
|
||||
</DropdownMenuLabel>
|
||||
{resolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => changeResolution(res)}
|
||||
className={cn(
|
||||
'flex w-full items-center justify-between text-xs cursor-pointer',
|
||||
state.currentResolution === res.resolution
|
||||
? 'text-primary font-medium'
|
||||
: 'text-foreground',
|
||||
)}
|
||||
>
|
||||
<span>{res.resolution === 'Original' ? m.original() : res.resolution}</span>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{res.width}x{res.height}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
|
||||
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
|
||||
{m.playback_speed()}
|
||||
</DropdownMenuLabel>
|
||||
{[0.5, 1, 1.5, 2].map((rate) => (
|
||||
<DropdownMenuItem
|
||||
key={rate}
|
||||
onClick={() => changePlaybackRate(rate)}
|
||||
className={cn(
|
||||
'flex items-center justify-between text-xs cursor-pointer',
|
||||
state.playbackRate === rate ? 'text-primary font-medium' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
<span>{rate}x</span>
|
||||
{state.playbackRate === rate && <Check className="h-3.5 w-3.5 text-primary" />}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={toggleLoop}
|
||||
className="flex items-center justify-between text-xs cursor-pointer"
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Repeat className="h-3.5 w-3.5" />
|
||||
<span>{m.loop()}</span>
|
||||
</span>
|
||||
{state.isLooping && <Check className="h-3.5 w-3.5 text-primary" />}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Fullscreen */}
|
||||
<button
|
||||
onClick={toggleFullScreen}
|
||||
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
|
||||
title={m.fullscreen()}
|
||||
aria-label={m.fullscreen()}
|
||||
>
|
||||
{state.isFullScreen ? (
|
||||
<Minimize className="h-5 w-5" />
|
||||
) : (
|
||||
<Maximize className="h-5 w-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import type Player from 'video.js/dist/types/player'
|
||||
import { useFramePlayer } from './use-frame-player'
|
||||
import { resolveTotalFrames } from './utils'
|
||||
import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
|
||||
import { MobileVideoControlBar } from './mobile-video-control-bar'
|
||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
import DrawingCanvas from '@/ui/components/drawing-canvas'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import { FileViewerProps, MediaController } from '../types'
|
||||
@@ -593,14 +595,49 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
}
|
||||
|
||||
const toggleFullScreen = () => {
|
||||
if (!rootRef.current) return
|
||||
if (!document.fullscreenElement) {
|
||||
rootRef.current.requestFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: true }))
|
||||
} else {
|
||||
document.exitFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: false }))
|
||||
const rootEl = rootRef.current
|
||||
const videoEl = videoHtmlEl || videoRef.current
|
||||
|
||||
// 1. Standard W3C Fullscreen API (Desktop Chrome/Firefox/Safari, Android, iPadOS)
|
||||
if (rootEl && typeof rootEl.requestFullscreen === 'function') {
|
||||
if (!document.fullscreenElement) {
|
||||
rootEl.requestFullscreen().catch(() => {})
|
||||
setState((prev) => ({ ...prev, isFullScreen: true }))
|
||||
} else if (document.exitFullscreen) {
|
||||
document.exitFullscreen().catch(() => {})
|
||||
setState((prev) => ({ ...prev, isFullScreen: false }))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 2. iOS WebKit native video fullscreen (iPhone Safari & Chrome)
|
||||
const webkitVideo = videoEl as
|
||||
| (HTMLVideoElement & {
|
||||
webkitEnterFullscreen?: () => void
|
||||
webkitExitFullscreen?: () => void
|
||||
webkitDisplayingFullscreen?: boolean
|
||||
})
|
||||
| null
|
||||
|
||||
if (webkitVideo && typeof webkitVideo.webkitEnterFullscreen === 'function') {
|
||||
if (!webkitVideo.webkitDisplayingFullscreen) {
|
||||
try {
|
||||
webkitVideo.webkitEnterFullscreen()
|
||||
} catch (err) {
|
||||
console.error('Failed to enter iOS fullscreen:', err)
|
||||
}
|
||||
} else if (typeof webkitVideo.webkitExitFullscreen === 'function') {
|
||||
try {
|
||||
webkitVideo.webkitExitFullscreen()
|
||||
} catch (err) {
|
||||
console.error('Failed to exit iOS fullscreen:', err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Fallback: pseudo-fullscreen
|
||||
setState((prev) => ({ ...prev, isFullScreen: !prev.isFullScreen }))
|
||||
}
|
||||
|
||||
const handleDownload = async (key: string) => {
|
||||
@@ -626,7 +663,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for fullscreen change events (ESC key)
|
||||
// Listen for fullscreen change events (ESC key, iOS Done button)
|
||||
useEffect(() => {
|
||||
const onFsChange = () => {
|
||||
setState((prev) => ({
|
||||
@@ -635,12 +672,34 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
}))
|
||||
}
|
||||
document.addEventListener('fullscreenchange', onFsChange)
|
||||
return () => document.removeEventListener('fullscreenchange', onFsChange)
|
||||
}, [])
|
||||
|
||||
// iOS WebKit fullscreen events on <video>
|
||||
const videoEl = videoHtmlEl || videoRef.current
|
||||
const onWebkitBeginFs = () => {
|
||||
setState((prev) => ({ ...prev, isFullScreen: true }))
|
||||
}
|
||||
const onWebkitEndFs = () => {
|
||||
setState((prev) => ({ ...prev, isFullScreen: false }))
|
||||
}
|
||||
if (videoEl) {
|
||||
videoEl.addEventListener('webkitbeginfullscreen', onWebkitBeginFs)
|
||||
videoEl.addEventListener('webkitendfullscreen', onWebkitEndFs)
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('fullscreenchange', onFsChange)
|
||||
if (videoEl) {
|
||||
videoEl.removeEventListener('webkitbeginfullscreen', onWebkitBeginFs)
|
||||
videoEl.removeEventListener('webkitendfullscreen', onWebkitEndFs)
|
||||
}
|
||||
}
|
||||
}, [videoHtmlEl])
|
||||
|
||||
// Center pan is owned by `pan` state (set by auto-fit / gestures).
|
||||
const scale = zoom
|
||||
|
||||
const isMobile = useIsMobile()
|
||||
|
||||
if (!hasMedia) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
@@ -653,7 +712,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={cn(
|
||||
'group shadow-2xl font-sans select-none flex flex-col mx-auto transition-all duration-300 relative',
|
||||
'group shadow-2xl font-sans select-none flex flex-col mx-auto relative',
|
||||
state.isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
|
||||
!isControlsVisible && state.isFullScreen ? 'cursor-none' : '',
|
||||
)}
|
||||
@@ -725,31 +784,59 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<VideoControlBar
|
||||
state={controlBarState}
|
||||
zoom={zoom}
|
||||
isControlsVisible={isControlsVisible}
|
||||
buffered={buffered}
|
||||
data={data}
|
||||
resolutions={resolutions}
|
||||
togglePlay={togglePlay}
|
||||
toggleLoop={toggleLoop}
|
||||
toggleMute={toggleMute}
|
||||
handleVolumeChange={handleVolumeChange}
|
||||
changePlaybackRate={changePlaybackRate}
|
||||
changeResolution={changeResolution}
|
||||
handleDownload={handleDownload}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
frameRate={frameRate}
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
seekToFrame={seekToFrame}
|
||||
onMouseEnter={handleControlsMouseEnter}
|
||||
onMouseLeave={handleControlsMouseLeave}
|
||||
allowDownload={allowDownload}
|
||||
/>
|
||||
{isMobile ? (
|
||||
<MobileVideoControlBar
|
||||
state={controlBarState}
|
||||
zoom={zoom}
|
||||
isControlsVisible={isControlsVisible}
|
||||
buffered={buffered}
|
||||
data={data}
|
||||
resolutions={resolutions}
|
||||
togglePlay={togglePlay}
|
||||
toggleLoop={toggleLoop}
|
||||
toggleMute={toggleMute}
|
||||
handleVolumeChange={handleVolumeChange}
|
||||
changePlaybackRate={changePlaybackRate}
|
||||
changeResolution={changeResolution}
|
||||
handleDownload={handleDownload}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
frameRate={frameRate}
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
seekToFrame={seekToFrame}
|
||||
onMouseEnter={handleControlsMouseEnter}
|
||||
onMouseLeave={handleControlsMouseLeave}
|
||||
allowDownload={allowDownload}
|
||||
/>
|
||||
) : (
|
||||
<VideoControlBar
|
||||
state={controlBarState}
|
||||
zoom={zoom}
|
||||
isControlsVisible={isControlsVisible}
|
||||
buffered={buffered}
|
||||
data={data}
|
||||
resolutions={resolutions}
|
||||
togglePlay={togglePlay}
|
||||
toggleLoop={toggleLoop}
|
||||
toggleMute={toggleMute}
|
||||
handleVolumeChange={handleVolumeChange}
|
||||
changePlaybackRate={changePlaybackRate}
|
||||
changeResolution={changeResolution}
|
||||
handleDownload={handleDownload}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
frameRate={frameRate}
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
seekToFrame={seekToFrame}
|
||||
onMouseEnter={handleControlsMouseEnter}
|
||||
onMouseLeave={handleControlsMouseLeave}
|
||||
allowDownload={allowDownload}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -254,6 +254,11 @@
|
||||
"best_match_description": "Generates a single optimal resolution matching the source quality.",
|
||||
"all_resolutions": "All resolutions",
|
||||
"all_resolutions_description": "Generates all supported resolutions up to the source quality.",
|
||||
"hardware_acceleration": "Hardware Acceleration",
|
||||
"hardware_acceleration_off": "Disabled (Software)",
|
||||
"hardware_acceleration_off_description": "Uses software libx264 encoder with constant rate factor (CRF).",
|
||||
"hardware_acceleration_auto": "Auto Detect",
|
||||
"hardware_acceleration_auto_description": "Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcoding may fail.",
|
||||
|
||||
"notification_settings": "Notification Settings",
|
||||
"notifications_description": "Configure your personal notification preferences for this team.",
|
||||
@@ -1294,5 +1299,18 @@
|
||||
"no_assets_in_folder": "No assets in this folder",
|
||||
"linked_assets_count": "{count} assets",
|
||||
"linked_tasks_count": "{count} tasks",
|
||||
"current_project_label": "Current Project"
|
||||
"current_project_label": "Current Project",
|
||||
"all_comments": "All comments",
|
||||
"previous_file": "Previous file",
|
||||
"next_file": "Next file",
|
||||
"switch_version": "Switch version",
|
||||
"more_options": "More options",
|
||||
"change_time_format": "Change time format",
|
||||
"format": "Format",
|
||||
"standard_time": "Standard Time",
|
||||
"frames": "Frames",
|
||||
"timecode": "Timecode",
|
||||
"playback_speed": "Playback Speed",
|
||||
"settings": "Settings",
|
||||
"failed_to_post_comment": "Failed to post comment"
|
||||
}
|
||||
|
||||
@@ -254,6 +254,11 @@
|
||||
"best_match_description": "生成与源质量匹配的单一最优分辨率。",
|
||||
"all_resolutions": "所有分辨率",
|
||||
"all_resolutions_description": "生成不超过源质量的所有支持分辨率。",
|
||||
"hardware_acceleration": "硬件加速",
|
||||
"hardware_acceleration_off": "已禁用 (软件编码)",
|
||||
"hardware_acceleration_off_description": "使用 CPU 的 libx264 软件编码器及 CRF 恒定画质模式。",
|
||||
"hardware_acceleration_auto": "自动检测",
|
||||
"hardware_acceleration_auto_description": "自动检测并使用 GPU/硬件加速(NVENC、QSV、AMF、VideoToolbox)。若宿主硬件不支持加速,视频转码可能会失败。",
|
||||
|
||||
"notification_settings": "通知设置",
|
||||
"notifications_description": "配置您在此团队的个人通知偏好。",
|
||||
@@ -1294,5 +1299,18 @@
|
||||
"no_assets_in_folder": "此文件夹中没有资产",
|
||||
"linked_assets_count": "{count} 个资产",
|
||||
"linked_tasks_count": "{count} 个任务",
|
||||
"current_project_label": "当前项目"
|
||||
"current_project_label": "当前项目",
|
||||
"all_comments": "所有评论",
|
||||
"previous_file": "上一个文件",
|
||||
"next_file": "下一个文件",
|
||||
"switch_version": "切换版本",
|
||||
"more_options": "更多选项",
|
||||
"change_time_format": "更改时间格式",
|
||||
"format": "格式",
|
||||
"standard_time": "标准时间",
|
||||
"frames": "帧数",
|
||||
"timecode": "时间码",
|
||||
"playback_speed": "播放速度",
|
||||
"settings": "设置",
|
||||
"failed_to_post_comment": "发送评论失败"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.3.11",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./index.html",
|
||||
|
||||
+16
@@ -241,6 +241,11 @@ export * from "./best_match.js";
|
||||
export * from "./best_match_description.js";
|
||||
export * from "./all_resolutions.js";
|
||||
export * from "./all_resolutions_description.js";
|
||||
export * from "./hardware_acceleration.js";
|
||||
export * from "./hardware_acceleration_off.js";
|
||||
export * from "./hardware_acceleration_off_description.js";
|
||||
export * from "./hardware_acceleration_auto.js";
|
||||
export * from "./hardware_acceleration_auto_description.js";
|
||||
export * from "./notification_settings.js";
|
||||
export * from "./notifications_description.js";
|
||||
export * from "./notification_settings_updated.js";
|
||||
@@ -1234,4 +1239,15 @@ export * from "./no_assets_in_folder.js";
|
||||
export * from "./linked_assets_count.js";
|
||||
export * from "./linked_tasks_count.js";
|
||||
export * from "./current_project_label.js";
|
||||
export * from "./all_comments.js";
|
||||
export * from "./previous_file.js";
|
||||
export * from "./next_file.js";
|
||||
export * from "./more_options.js";
|
||||
export * from "./change_time_format.js";
|
||||
export * from "./format.js";
|
||||
export * from "./standard_time.js";
|
||||
export * from "./frames.js";
|
||||
export * from "./timecode.js";
|
||||
export * from "./playback_speed.js";
|
||||
export * from "./failed_to_post_comment.js";
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
|
||||
+17
-1
@@ -243,6 +243,11 @@ export * from './best_match.js'
|
||||
export * from './best_match_description.js'
|
||||
export * from './all_resolutions.js'
|
||||
export * from './all_resolutions_description.js'
|
||||
export * from './hardware_acceleration.js'
|
||||
export * from './hardware_acceleration_off.js'
|
||||
export * from './hardware_acceleration_off_description.js'
|
||||
export * from './hardware_acceleration_auto.js'
|
||||
export * from './hardware_acceleration_auto_description.js'
|
||||
export * from './notification_settings.js'
|
||||
export * from './notifications_description.js'
|
||||
export * from './notification_settings_updated.js'
|
||||
@@ -1235,4 +1240,15 @@ export * from './n_assets_selected.js'
|
||||
export * from './no_assets_in_folder.js'
|
||||
export * from './linked_assets_count.js'
|
||||
export * from './linked_tasks_count.js'
|
||||
export * from './current_project_label.js'
|
||||
export * from './current_project_label.js'
|
||||
export * from './all_comments.js'
|
||||
export * from './previous_file.js'
|
||||
export * from './next_file.js'
|
||||
export * from './more_options.js'
|
||||
export * from './change_time_format.js'
|
||||
export * from './format.js'
|
||||
export * from './standard_time.js'
|
||||
export * from './frames.js'
|
||||
export * from './timecode.js'
|
||||
export * from './playback_speed.js'
|
||||
export * from './failed_to_post_comment.js'
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "All comments" |
|
||||
*
|
||||
* @param {All_CommentsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const all_comments: ((inputs?: All_CommentsInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<All_CommentsInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type All_CommentsInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} All_CommentsInputs */
|
||||
|
||||
const en_all_comments = /** @type {(inputs: All_CommentsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`All comments`)
|
||||
};
|
||||
|
||||
const zh_all_comments = /** @type {(inputs: All_CommentsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`所有评论`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "All comments" |
|
||||
*
|
||||
* @param {All_CommentsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const all_comments = /** @type {((inputs?: All_CommentsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<All_CommentsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_all_comments(inputs)
|
||||
return zh_all_comments(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Change time format" |
|
||||
*
|
||||
* @param {Change_Time_FormatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const change_time_format: ((inputs?: Change_Time_FormatInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Change_Time_FormatInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Change_Time_FormatInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Change_Time_FormatInputs */
|
||||
|
||||
const en_change_time_format = /** @type {(inputs: Change_Time_FormatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Change time format`)
|
||||
};
|
||||
|
||||
const zh_change_time_format = /** @type {(inputs: Change_Time_FormatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`更改时间格式`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Change time format" |
|
||||
*
|
||||
* @param {Change_Time_FormatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const change_time_format = /** @type {((inputs?: Change_Time_FormatInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Change_Time_FormatInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_change_time_format(inputs)
|
||||
return zh_change_time_format(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Failed to post comment" |
|
||||
*
|
||||
* @param {Failed_To_Post_CommentInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const failed_to_post_comment: ((inputs?: Failed_To_Post_CommentInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Failed_To_Post_CommentInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Failed_To_Post_CommentInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Failed_To_Post_CommentInputs */
|
||||
|
||||
const en_failed_to_post_comment = /** @type {(inputs: Failed_To_Post_CommentInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Failed to post comment`)
|
||||
};
|
||||
|
||||
const zh_failed_to_post_comment = /** @type {(inputs: Failed_To_Post_CommentInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`发送评论失败`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Failed to post comment" |
|
||||
*
|
||||
* @param {Failed_To_Post_CommentInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const failed_to_post_comment = /** @type {((inputs?: Failed_To_Post_CommentInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Failed_To_Post_CommentInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_failed_to_post_comment(inputs)
|
||||
return zh_failed_to_post_comment(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Format" |
|
||||
*
|
||||
* @param {FormatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const format: ((inputs?: FormatInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<FormatInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type FormatInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} FormatInputs */
|
||||
|
||||
const en_format = /** @type {(inputs: FormatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Format`)
|
||||
};
|
||||
|
||||
const zh_format = /** @type {(inputs: FormatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`格式`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Format" |
|
||||
*
|
||||
* @param {FormatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const format = /** @type {((inputs?: FormatInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<FormatInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_format(inputs)
|
||||
return zh_format(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Frames" |
|
||||
*
|
||||
* @param {FramesInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const frames: ((inputs?: FramesInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<FramesInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type FramesInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} FramesInputs */
|
||||
|
||||
const en_frames = /** @type {(inputs: FramesInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Frames`)
|
||||
};
|
||||
|
||||
const zh_frames = /** @type {(inputs: FramesInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`帧数`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Frames" |
|
||||
*
|
||||
* @param {FramesInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const frames = /** @type {((inputs?: FramesInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<FramesInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_frames(inputs)
|
||||
return zh_frames(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Hardware Acceleration" |
|
||||
*
|
||||
* @param {Hardware_AccelerationInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration: ((inputs?: Hardware_AccelerationInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Hardware_AccelerationInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_AccelerationInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Hardware_AccelerationInputs */
|
||||
|
||||
const en_hardware_acceleration = /** @type {(inputs: Hardware_AccelerationInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Hardware Acceleration`)
|
||||
};
|
||||
|
||||
const zh_hardware_acceleration = /** @type {(inputs: Hardware_AccelerationInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`硬件加速`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Hardware Acceleration" |
|
||||
*
|
||||
* @param {Hardware_AccelerationInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration = /** @type {((inputs?: Hardware_AccelerationInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Hardware_AccelerationInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration(inputs)
|
||||
return zh_hardware_acceleration(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Auto Detect" |
|
||||
*
|
||||
* @param {Hardware_Acceleration_AutoInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_auto: ((inputs?: Hardware_Acceleration_AutoInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Hardware_Acceleration_AutoInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_AutoInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Hardware_Acceleration_AutoInputs */
|
||||
|
||||
const en_hardware_acceleration_auto = /** @type {(inputs: Hardware_Acceleration_AutoInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Auto Detect`)
|
||||
};
|
||||
|
||||
const zh_hardware_acceleration_auto = /** @type {(inputs: Hardware_Acceleration_AutoInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`自动检测`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Auto Detect" |
|
||||
*
|
||||
* @param {Hardware_Acceleration_AutoInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_auto = /** @type {((inputs?: Hardware_Acceleration_AutoInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Hardware_Acceleration_AutoInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration_auto(inputs)
|
||||
return zh_hardware_acceleration_auto(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcodi..." |
|
||||
*
|
||||
* @param {Hardware_Acceleration_Auto_DescriptionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_auto_description: ((inputs?: Hardware_Acceleration_Auto_DescriptionInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Hardware_Acceleration_Auto_DescriptionInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_Auto_DescriptionInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Hardware_Acceleration_Auto_DescriptionInputs */
|
||||
|
||||
const en_hardware_acceleration_auto_description = /** @type {(inputs: Hardware_Acceleration_Auto_DescriptionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcoding may fail.`)
|
||||
};
|
||||
|
||||
const zh_hardware_acceleration_auto_description = /** @type {(inputs: Hardware_Acceleration_Auto_DescriptionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`自动检测并使用 GPU/硬件加速(NVENC、QSV、AMF、VideoToolbox)。若宿主硬件不支持加速,视频转码可能会失败。`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcodi..." |
|
||||
*
|
||||
* @param {Hardware_Acceleration_Auto_DescriptionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_auto_description = /** @type {((inputs?: Hardware_Acceleration_Auto_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Hardware_Acceleration_Auto_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration_auto_description(inputs)
|
||||
return zh_hardware_acceleration_auto_description(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Disabled (Software)" |
|
||||
*
|
||||
* @param {Hardware_Acceleration_OffInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_off: ((inputs?: Hardware_Acceleration_OffInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Hardware_Acceleration_OffInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_OffInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Hardware_Acceleration_OffInputs */
|
||||
|
||||
const en_hardware_acceleration_off = /** @type {(inputs: Hardware_Acceleration_OffInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Disabled (Software)`)
|
||||
};
|
||||
|
||||
const zh_hardware_acceleration_off = /** @type {(inputs: Hardware_Acceleration_OffInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`已禁用 (软件编码)`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Disabled (Software)" |
|
||||
*
|
||||
* @param {Hardware_Acceleration_OffInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_off = /** @type {((inputs?: Hardware_Acceleration_OffInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Hardware_Acceleration_OffInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration_off(inputs)
|
||||
return zh_hardware_acceleration_off(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Uses software libx264 encoder with constant rate factor (CRF)." |
|
||||
*
|
||||
* @param {Hardware_Acceleration_Off_DescriptionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_off_description: ((inputs?: Hardware_Acceleration_Off_DescriptionInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Hardware_Acceleration_Off_DescriptionInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_Off_DescriptionInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Hardware_Acceleration_Off_DescriptionInputs */
|
||||
|
||||
const en_hardware_acceleration_off_description = /** @type {(inputs: Hardware_Acceleration_Off_DescriptionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Uses software libx264 encoder with constant rate factor (CRF).`)
|
||||
};
|
||||
|
||||
const zh_hardware_acceleration_off_description = /** @type {(inputs: Hardware_Acceleration_Off_DescriptionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`使用 CPU 的 libx264 软件编码器及 CRF 恒定画质模式。`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Uses software libx264 encoder with constant rate factor (CRF)." |
|
||||
*
|
||||
* @param {Hardware_Acceleration_Off_DescriptionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const hardware_acceleration_off_description = /** @type {((inputs?: Hardware_Acceleration_Off_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Hardware_Acceleration_Off_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration_off_description(inputs)
|
||||
return zh_hardware_acceleration_off_description(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "More options" |
|
||||
*
|
||||
* @param {More_OptionsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const more_options: ((inputs?: More_OptionsInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<More_OptionsInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type More_OptionsInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} More_OptionsInputs */
|
||||
|
||||
const en_more_options = /** @type {(inputs: More_OptionsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`More options`)
|
||||
};
|
||||
|
||||
const zh_more_options = /** @type {(inputs: More_OptionsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`更多选项`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "More options" |
|
||||
*
|
||||
* @param {More_OptionsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const more_options = /** @type {((inputs?: More_OptionsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<More_OptionsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_more_options(inputs)
|
||||
return zh_more_options(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Next file" |
|
||||
*
|
||||
* @param {Next_FileInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const next_file: ((inputs?: Next_FileInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Next_FileInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Next_FileInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Next_FileInputs */
|
||||
|
||||
const en_next_file = /** @type {(inputs: Next_FileInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Next file`)
|
||||
};
|
||||
|
||||
const zh_next_file = /** @type {(inputs: Next_FileInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`下一个文件`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Next file" |
|
||||
*
|
||||
* @param {Next_FileInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const next_file = /** @type {((inputs?: Next_FileInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Next_FileInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_next_file(inputs)
|
||||
return zh_next_file(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Playback Speed" |
|
||||
*
|
||||
* @param {Playback_SpeedInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const playback_speed: ((inputs?: Playback_SpeedInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Playback_SpeedInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Playback_SpeedInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Playback_SpeedInputs */
|
||||
|
||||
const en_playback_speed = /** @type {(inputs: Playback_SpeedInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Playback Speed`)
|
||||
};
|
||||
|
||||
const zh_playback_speed = /** @type {(inputs: Playback_SpeedInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`播放速度`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Playback Speed" |
|
||||
*
|
||||
* @param {Playback_SpeedInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const playback_speed = /** @type {((inputs?: Playback_SpeedInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Playback_SpeedInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_playback_speed(inputs)
|
||||
return zh_playback_speed(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Previous file" |
|
||||
*
|
||||
* @param {Previous_FileInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const previous_file: ((inputs?: Previous_FileInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Previous_FileInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Previous_FileInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Previous_FileInputs */
|
||||
|
||||
const en_previous_file = /** @type {(inputs: Previous_FileInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Previous file`)
|
||||
};
|
||||
|
||||
const zh_previous_file = /** @type {(inputs: Previous_FileInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`上一个文件`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Previous file" |
|
||||
*
|
||||
* @param {Previous_FileInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const previous_file = /** @type {((inputs?: Previous_FileInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Previous_FileInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_previous_file(inputs)
|
||||
return zh_previous_file(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Standard Time" |
|
||||
*
|
||||
* @param {Standard_TimeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const standard_time: ((inputs?: Standard_TimeInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Standard_TimeInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Standard_TimeInputs = {};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user