feat(webui): add mobile friendly file detail and public share view (#359)

* feat(webui): add mobile friendly file detail and public share view

* fix(webui): address review feedback for mobile file detail and public share view

* fix(webui): use dynamic viewport and flex column layout for mobile file viewer

* fix(webui): support iOS WebKit video fullscreen and guard requestFullscreen

* fix(webui): compact page indicator and layout in mobile PDF control bar
This commit is contained in:
Yiling-J
2026-08-28 15:11:33 +08:00
committed by GitHub
parent 7a1d6c0ab5
commit 6acebb73ec
42 changed files with 3071 additions and 216 deletions
@@ -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} className="space-y-2">
<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} className="pl-4 border-l border-border/60">
<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>
)
}