Merge pull request #111 from shumaiOne/feat/file-detail-sidebar-carousel

feat(webui): always show right sidebar and implement left vertical carousel
This commit is contained in:
Yiling-J
2026-06-15 16:45:58 +08:00
committed by GitHub
8 changed files with 535 additions and 383 deletions
+7 -5
View File
@@ -203,11 +203,13 @@ describe('Sandbox Network isolation integration', () => {
// Mock SandboxManager.initialize to behave like a process-global singleton // Mock SandboxManager.initialize to behave like a process-global singleton
let registeredCallback: SandboxAskCallback | null = null let registeredCallback: SandboxAskCallback | null = null
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockImplementation(async (config, cb) => { const initializeSpy = vi
if (!registeredCallback) { .spyOn(SandboxManager, 'initialize')
registeredCallback = cb || null .mockImplementation(async (config, cb) => {
} if (!registeredCallback) {
}) registeredCallback = cb || null
}
})
const resetSpy = vi.spyOn(SandboxManager, 'reset').mockImplementation(async () => { const resetSpy = vi.spyOn(SandboxManager, 'reset').mockImplementation(async () => {
// In the real SandboxManager, reset clears the global initialization promise and servers, // In the real SandboxManager, reset clears the global initialization promise and servers,
// which allows subsequent initialize calls to register a new callback. // which allows subsequent initialize calls to register a new callback.
+55 -53
View File
@@ -240,65 +240,67 @@ export function BreadcrumbNav({
)} )}
</div> </div>
<div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1"> {!fileId && (
{/* Left Sidebar Toggle */} <div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1">
{!isPublic && onLeftSidebarToggle && ( {/* Left Sidebar Toggle */}
{!isPublic && onLeftSidebarToggle && (
<button
onClick={onLeftSidebarToggle}
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
title={isLeftSidebarCollapsed ? 'Show Left Sidebar' : 'Hide Left Sidebar'}
>
{isLeftSidebarCollapsed ? (
<DockToLeft className="h-4 w-4" />
) : (
<DockToLeftFilled className="h-4 w-4 fill-primary stroke-0" />
)}
</button>
)}
{/* Card View */}
{!isPublic && displayStyle && onDisplayStyleChange && (
<>
<button
onClick={() => onDisplayStyleChange('card')}
className={`rounded p-1.5 transition-colors ${
displayStyle === 'card'
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
}`}
title="Card View"
>
<LayoutGrid className="h-4 w-4" />
</button>
{/* List View */}
<button
onClick={() => onDisplayStyleChange('list')}
className={`rounded p-1.5 transition-colors ${
displayStyle === 'list'
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
}`}
title="List View"
>
<List className="h-4 w-4" />
</button>
</>
)}
{/* Right Sidebar Toggle */}
<button <button
onClick={onLeftSidebarToggle} onClick={onRightSidebarToggle}
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground" className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
title={isLeftSidebarCollapsed ? 'Show Left Sidebar' : 'Hide Left Sidebar'} title={isRightSidebarCollapsed ? 'Show Right Sidebar' : 'Hide Right Sidebar'}
> >
{isLeftSidebarCollapsed ? ( {isRightSidebarCollapsed ? (
<DockToLeft className="h-4 w-4" /> <DockToRight className="h-4 w-4" />
) : ( ) : (
<DockToLeftFilled className="h-4 w-4 fill-primary stroke-0" /> <DockToRightFilled className="h-4 w-4 fill-primary stroke-0" />
)} )}
</button> </button>
)} </div>
)}
{/* Card View */}
{!isPublic && displayStyle && onDisplayStyleChange && (
<>
<button
onClick={() => onDisplayStyleChange('card')}
className={`rounded p-1.5 transition-colors ${
displayStyle === 'card'
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
}`}
title="Card View"
>
<LayoutGrid className="h-4 w-4" />
</button>
{/* List View */}
<button
onClick={() => onDisplayStyleChange('list')}
className={`rounded p-1.5 transition-colors ${
displayStyle === 'list'
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
}`}
title="List View"
>
<List className="h-4 w-4" />
</button>
</>
)}
{/* Right Sidebar Toggle */}
<button
onClick={onRightSidebarToggle}
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
title={isRightSidebarCollapsed ? 'Show Right Sidebar' : 'Hide Right Sidebar'}
>
{isRightSidebarCollapsed ? (
<DockToRight className="h-4 w-4" />
) : (
<DockToRightFilled className="h-4 w-4 fill-primary stroke-0" />
)}
</button>
</div>
</div> </div>
) )
} }
+115 -114
View File
@@ -457,125 +457,126 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
cursor: text; cursor: text;
} }
`}</style> `}</style>
{showMentionList && (membersLoading || filteredAgents.length > 0 || filteredHumans.length > 0) && ( {showMentionList &&
<div className="absolute bottom-full left-4 mb-2 w-64 rounded-xl shadow-lg border border-border overflow-hidden z-20 bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 duration-200"> (membersLoading || filteredAgents.length > 0 || filteredHumans.length > 0) && (
<div className="h-64 overflow-y-auto"> <div className="absolute bottom-full left-4 mb-2 w-64 rounded-xl shadow-lg border border-border overflow-hidden z-20 bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 duration-200">
{membersLoading ? ( <div className="h-64 overflow-y-auto">
<div className="p-2 space-y-4 animate-pulse"> {membersLoading ? (
{/* Agents Skeleton */} <div className="p-2 space-y-4 animate-pulse">
<div className="space-y-2"> {/* Agents Skeleton */}
<div className="px-3 py-1.5 bg-muted/50 border-b border-border"> <div className="space-y-2">
<Skeleton className="h-3 w-16" /> <div className="px-3 py-1.5 bg-muted/50 border-b border-border">
<Skeleton className="h-3 w-16" />
</div>
<div className="flex items-center gap-2 px-3 py-2">
<Skeleton className="w-6 h-6 rounded-full" />
<Skeleton className="h-4 w-28" />
</div>
<div className="flex items-center gap-2 px-3 py-2">
<Skeleton className="w-6 h-6 rounded-full" />
<Skeleton className="h-4 w-20" />
</div>
</div> </div>
<div className="flex items-center gap-2 px-3 py-2"> {/* Members Skeleton */}
<Skeleton className="w-6 h-6 rounded-full" /> <div className="space-y-2">
<Skeleton className="h-4 w-28" /> <div className="px-3 py-1.5 bg-muted/50 border-b border-border">
</div> <Skeleton className="h-3 w-16" />
<div className="flex items-center gap-2 px-3 py-2"> </div>
<Skeleton className="w-6 h-6 rounded-full" /> <div className="flex items-center gap-2 px-3 py-2">
<Skeleton className="h-4 w-20" /> <Skeleton className="w-6 h-6 rounded-full" />
<Skeleton className="h-4 w-32" />
</div>
<div className="flex items-center gap-2 px-3 py-2">
<Skeleton className="w-6 h-6 rounded-full" />
<Skeleton className="h-4 w-24" />
</div>
</div> </div>
</div> </div>
{/* Members Skeleton */} ) : (
<div className="space-y-2"> <>
<div className="px-3 py-1.5 bg-muted/50 border-b border-border"> {filteredAgents.length > 0 && (
<Skeleton className="h-3 w-16" /> <>
</div> <button
<div className="flex items-center gap-2 px-3 py-2"> onClick={(e) => {
<Skeleton className="w-6 h-6 rounded-full" /> e.preventDefault()
<Skeleton className="h-4 w-32" /> e.stopPropagation()
</div> setCollapsedSections((prev) => ({ ...prev, bots: !prev.bots }))
<div className="flex items-center gap-2 px-3 py-2"> }}
<Skeleton className="w-6 h-6 rounded-full" /> className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors"
<Skeleton className="h-4 w-24" /> >
</div> <span>Agents</span>
</div> <ChevronDown
</div> className={`w-3 h-3 transition-transform ${collapsedSections.bots ? '-rotate-90' : ''}`}
) : ( />
<> </button>
{filteredAgents.length > 0 && ( {!collapsedSections.bots &&
<> filteredAgents.map((item, index) => {
<button const actualIndex = index
onClick={(e) => { return (
e.preventDefault() <button
e.stopPropagation() key={item.data.id}
setCollapsedSections((prev) => ({ ...prev, bots: !prev.bots })) onClick={() => handleSelectEntity(item)}
}} onMouseEnter={() => setHighlightedIndex(actualIndex)}
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors" className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
> actualIndex === highlightedIndex
<span>Agents</span> ? 'bg-accent text-accent-foreground'
<ChevronDown : 'hover:bg-accent/50'
className={`w-3 h-3 transition-transform ${collapsedSections.bots ? '-rotate-90' : ''}`} }`}
/> >
</button> <div className="w-6 h-6 rounded-full bg-purple-100 dark:bg-purple-900/40 flex items-center justify-center text-xs font-bold text-purple-600 dark:text-purple-300">
{!collapsedSections.bots && {item.data.name?.[0]}
filteredAgents.map((item, index) => { </div>
const actualIndex = index <span className="text-sm">{item.data.name}</span>
return ( </button>
<button )
key={item.data.id} })}
onClick={() => handleSelectEntity(item)} </>
onMouseEnter={() => setHighlightedIndex(actualIndex)} )}
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
actualIndex === highlightedIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
}`}
>
<div className="w-6 h-6 rounded-full bg-purple-100 dark:bg-purple-900/40 flex items-center justify-center text-xs font-bold text-purple-600 dark:text-purple-300">
{item.data.name?.[0]}
</div>
<span className="text-sm">{item.data.name}</span>
</button>
)
})}
</>
)}
{filteredHumans.length > 0 && ( {filteredHumans.length > 0 && (
<> <>
<button <button
onClick={(e) => { onClick={(e) => {
e.preventDefault() e.preventDefault()
e.stopPropagation() e.stopPropagation()
setCollapsedSections((prev) => ({ ...prev, users: !prev.users })) setCollapsedSections((prev) => ({ ...prev, users: !prev.users }))
}} }}
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors" className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors"
> >
<span>Members</span> <span>Members</span>
<ChevronDown <ChevronDown
className={`w-3 h-3 transition-transform ${collapsedSections.users ? '-rotate-90' : ''}`} className={`w-3 h-3 transition-transform ${collapsedSections.users ? '-rotate-90' : ''}`}
/> />
</button> </button>
{!collapsedSections.users && {!collapsedSections.users &&
filteredHumans.map((item, index) => { filteredHumans.map((item, index) => {
const actualIndex = const actualIndex =
(collapsedSections.bots ? 0 : filteredAgents.length) + index (collapsedSections.bots ? 0 : filteredAgents.length) + index
return ( return (
<button <button
key={item.data.id} key={item.data.id}
onClick={() => handleSelectEntity(item)} onClick={() => handleSelectEntity(item)}
onMouseEnter={() => setHighlightedIndex(actualIndex)} onMouseEnter={() => setHighlightedIndex(actualIndex)}
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${ className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
actualIndex === highlightedIndex actualIndex === highlightedIndex
? 'bg-accent text-accent-foreground' ? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50' : 'hover:bg-accent/50'
}`} }`}
> >
<div className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center text-xs font-bold text-blue-600 dark:text-blue-300"> <div className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center text-xs font-bold text-blue-600 dark:text-blue-300">
{item.data.name?.[0]} {item.data.name?.[0]}
</div> </div>
<span className="text-sm">{item.data.name}</span> <span className="text-sm">{item.data.name}</span>
</button> </button>
) )
})} })}
</> </>
)} )}
</> </>
)} )}
</div>
</div> </div>
</div> )}
)}
{showUpperPart && ( {showUpperPart && (
<div className="flex flex-col gap-2 p-3 pb-0 animate-in fade-in slide-in-from-bottom-2 duration-200"> <div className="flex flex-col gap-2 p-3 pb-0 animate-in fade-in slide-in-from-bottom-2 duration-200">
@@ -1,26 +1,40 @@
import { client } from '@/ui/api/client' import { client } from '@/ui/api/client'
import { useInfiniteQuery } from '@tanstack/react-query' import { cn } from '@/ui/lib/utils'
import { Loader2, PanelLeftClose } from 'lucide-react' import type { AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos'
import { Link } from '@tanstack/react-router'
import { File, Loader2 } from 'lucide-react'
import type { FC } from 'react' import type { FC } from 'react'
import type { AssetInfoPaginatedList } from '@shumai/dtos' import { useEffect, useRef, useState } from 'react'
import { useEffect, useRef } from 'react'
import { useInView } from 'react-intersection-observer' import { useInView } from 'react-intersection-observer'
import { SidebarFileCard } from './sidebar-file-card'
import { Button } from './ui/button'
import { ScrollArea } from './ui/scroll-area'
interface FileViewerLeftSidebarProps { interface FileViewerLeftSidebarProps {
projectId: string projectId: string
currentAssetId: string currentAssetId: string
parentFolderId: string parentFolderId: string
onCollapse: () => void initialFiles: AssetInfo[]
initialNextCursor: string | undefined
}
export const CarouselFilePreview = ({ item }: { item: AssetInfo }) => {
if (item.preview?.thumbnailUrl) {
return (
<img src={item.preview.thumbnailUrl} alt="Preview" className="w-full h-full object-cover" />
)
}
return (
<div className="w-full h-full flex items-center justify-center bg-muted">
<File className="w-5 h-5 text-muted-foreground" />
</div>
)
} }
export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
projectId, projectId,
currentAssetId, currentAssetId,
parentFolderId, parentFolderId,
onCollapse, initialFiles,
initialNextCursor,
}) => { }) => {
const { ref, inView } = useInView({ const { ref, inView } = useInView({
threshold: 0, threshold: 0,
@@ -29,38 +43,51 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
const activeItemRef = useRef<HTMLDivElement>(null) const activeItemRef = useRef<HTMLDivElement>(null)
const hasScrolledRef = useRef(false) const hasScrolledRef = useRef(false)
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({ const [files, setFiles] = useState<AssetInfo[]>(initialFiles)
queryKey: [ const [nextCursor, setNextCursor] = useState<string | undefined>(initialNextCursor)
'folders', const [hasMore, setHasMore] = useState<boolean>(!!initialNextCursor)
parentFolderId, const [isFetchingNext, setIsFetchingNext] = useState<boolean>(false)
'children',
{
assetType: 'file',
},
],
queryFn: async ({ pageParam }) => {
const res = await client.api.folders[':folderId'].children.$get({
param: { folderId: parentFolderId },
query: {
assetType: 'file',
after: pageParam,
first: '20',
},
})
if (!res.ok) throw new Error('failed to fetch folder children')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
})
const files = data?.pages.flatMap((page) => page.data) ?? []
// Sync state if initial files / cursor changes (due to parent folder change)
useEffect(() => { useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) { setFiles(initialFiles)
fetchNextPage() setNextCursor(initialNextCursor)
setHasMore(!!initialNextCursor)
hasScrolledRef.current = false
}, [initialFiles, initialNextCursor])
// Fetch next page when scrolling near bottom
useEffect(() => {
const fetchNextPage = async () => {
if (!nextCursor || isFetchingNext || !inView || !hasMore) return
setIsFetchingNext(true)
try {
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: parentFolderId },
json: {
assetType: 'file',
after: nextCursor,
first: 200,
recursively: false,
conditions: [],
},
})
if (!res.ok) throw new Error('Failed to fetch next page')
const result = (await res.json()) as unknown as AssetInfoPaginatedList
const batchFiles = (result.data || []) as AssetInfo[]
setFiles((prev) => [...prev, ...batchFiles])
setNextCursor(result.pageInfo?.cursor || undefined)
setHasMore(!!result.pageInfo?.cursor && batchFiles.length > 0)
} catch (err) {
console.error('Error fetching next page:', err)
} finally {
setIsFetchingNext(false)
}
} }
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
fetchNextPage()
}, [inView, nextCursor, hasMore, isFetchingNext, parentFolderId])
// Reset scroll lock when current asset changes // Reset scroll lock when current asset changes
useEffect(() => { useEffect(() => {
@@ -73,47 +100,52 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
if (activeFileInView && activeItemRef.current && !hasScrolledRef.current) { if (activeFileInView && activeItemRef.current && !hasScrolledRef.current) {
activeItemRef.current.scrollIntoView({ activeItemRef.current.scrollIntoView({
block: 'center', block: 'center',
inline: 'center',
behavior: 'smooth',
}) })
hasScrolledRef.current = true hasScrolledRef.current = true
} }
}, [files, currentAssetId]) }, [files, currentAssetId])
return ( return (
<div className="h-full w-full bg-card border-r border-border flex flex-col"> <div className="h-24 md:h-full w-full md:w-24 bg-gray-100 dark:bg-gray-950 flex flex-row md:flex-col flex-shrink-0 select-none">
<div className="p-2 border-b flex items-center justify-between"> <div className="flex-1 overflow-x-auto overflow-y-hidden md:overflow-y-auto md:overflow-x-hidden px-4 md:px-0 py-2 md:py-4 flex flex-row md:flex-col items-center gap-3 no-scrollbar">
<h3 className="text-sm font-semibold px-2">Current Folder</h3> {files.map((file) => {
<Button variant="ghost" size="icon-sm" onClick={onCollapse}> if (!file) return null
<PanelLeftClose className="h-4 w-4" /> const isActive = file.id === currentAssetId
</Button> return (
</div> <div
<ScrollArea className="flex-1 [&>div>div]:block! px-2"> key={file.id}
<div className="p-2 space-y-2"> ref={file.id === currentAssetId ? activeItemRef : null}
{isLoading && ( className="flex-shrink-0"
<div className="flex justify-center items-center p-4"> >
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /> <Link
to="/projects/$projectId/files/$fileId"
params={{ projectId, fileId: file.id }}
search={{ version: undefined }}
className={cn(
'rounded-lg border overflow-hidden flex items-center justify-center transition-all bg-muted/30 block',
isActive
? 'w-[62px] h-[62px] opacity-100'
: 'w-[52px] h-[52px] opacity-60 hover:opacity-100',
)}
>
<CarouselFilePreview item={file} />
</Link>
</div> </div>
)} )
{files.map( })}
(file) =>
file && ( {/* Infinite Scroll Trigger */}
<SidebarFileCard {hasMore && (
ref={file.id === currentAssetId ? activeItemRef : null} <div
key={file.id} ref={ref}
projectId={projectId} className="px-2 md:px-0 py-2 md:py-4 flex justify-center items-center h-full md:w-full flex-shrink-0"
item={file} >
isActive={file.id === currentAssetId} {isFetchingNext && <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />}
/>
),
)}
<div ref={ref}>
{isFetchingNextPage && (
<div className="flex justify-center items-center p-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)}
</div> </div>
</div> )}
</ScrollArea> </div>
</div> </div>
) )
} }
+74 -43
View File
@@ -2,8 +2,8 @@ import { useScreenSize } from '@/ui/hooks/useScreenSize'
import { getBestTranscode } from '@/ui/lib/media' import { getBestTranscode } from '@/ui/lib/media'
import type { AssetInfo } from '@shumai/dtos' import type { AssetInfo } from '@shumai/dtos'
import { Check, Copy, Download, Minus, Plus } from 'lucide-react' import { Check, Copy, Download, Minus, Plus } from 'lucide-react'
import type { RefObject } from 'react' import type { ReactNode, RefObject } from 'react'
import { useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import type Player from 'video.js/dist/types/player' import type Player from 'video.js/dist/types/player'
import DrawingCanvas from './drawing-canvas' import DrawingCanvas from './drawing-canvas'
import VideoPlayer from './viewers/video-player' import VideoPlayer from './viewers/video-player'
@@ -18,6 +18,7 @@ type FileViewerProps = {
onPause?: () => void onPause?: () => void
onTimeUpdate?: (time: number) => void onTimeUpdate?: (time: number) => void
annotations?: Annotation[] annotations?: Annotation[]
children?: ReactNode
} }
export function FileViewer({ export function FileViewer({
@@ -27,6 +28,7 @@ export function FileViewer({
onPause, onPause,
onTimeUpdate, onTimeUpdate,
annotations, annotations,
children,
}: FileViewerProps) { }: FileViewerProps) {
const { width: screenWidth } = useScreenSize() const { width: screenWidth } = useScreenSize()
const isImage = file.mediaType?.startsWith('image/') const isImage = file.mediaType?.startsWith('image/')
@@ -49,11 +51,33 @@ export function FileViewer({
// State for Image Viewer // State for Image Viewer
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 }) const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
const containerRef = useRef<HTMLDivElement>(null)
const [zoom, setZoom] = useState(1) const [zoom, setZoom] = useState(1)
const [pan, setPan] = useState({ x: 0, y: 0 }) const [pan, setPan] = useState({ x: 0, y: 0 })
const [copied, setCopied] = useState(false) const [copied, setCopied] = useState(false)
const observerRef = useRef<ResizeObserver | null>(null)
const containerRef = useCallback((node: HTMLDivElement | null) => {
if (observerRef.current) {
observerRef.current.disconnect()
observerRef.current = null
}
if (node !== null) {
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(node)
observerRef.current = observer
}
}, [])
const imgW = file.media?.metadata?.originalWidth ?? 1920 const imgW = file.media?.metadata?.originalWidth ?? 1920
const imgH = file.media?.metadata?.originalHeight ?? 1080 const imgH = file.media?.metadata?.originalHeight ?? 1080
const conW = containerSize.width const conW = containerSize.width
@@ -76,22 +100,6 @@ export function FileViewer({
} }
}, [file.id, conW, conH, isImage, baseScale, imgW, imgH]) }, [file.id, conW, conH, isImage, baseScale, imgW, imgH])
// Resize Observer
useEffect(() => {
if (!containerRef.current) return
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(containerRef.current)
return () => observer.disconnect()
}, [])
const handleZoom = (factor: number) => { const handleZoom = (factor: number) => {
const cx = conW / 2 const cx = conW / 2
const cy = conH / 2 const cy = conH / 2
@@ -186,10 +194,28 @@ export function FileViewer({
} }
} }
if (!bestUrl) { const isUnsupported = !bestUrl || (!isImage && !isVideo)
if (isUnsupported) {
return ( return (
<div className="flex flex-1 items-center justify-center"> <div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
<p className="text-muted-foreground">Preview unavailable</p> <div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{children}
<div className="flex-1 flex items-center justify-center">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
</div>
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
<button
onClick={handleDownload}
disabled={!file.media?.original?.downloadUrl}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Download original file"
>
<Download size={14} />
Download
</button>
</div>
</div> </div>
) )
} }
@@ -201,26 +227,29 @@ export function FileViewer({
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative"> <div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
{isImage && ( {isImage && (
<> <>
<div ref={containerRef} className="flex-1 relative overflow-hidden"> <div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
<DrawingCanvas {children}
width={conW} <div ref={containerRef} className="flex-1 relative overflow-hidden">
height={conH} <DrawingCanvas
mediaDimensions={{ width={conW}
width: imgW, height={conH}
height: imgH, mediaDimensions={{
}} width: imgW,
imageUrl={bestUrl} height: imgH,
annotations={displayAnnotations} }}
scale={zoom} imageUrl={bestUrl}
offset={pan} annotations={displayAnnotations}
onPan={setPan} scale={zoom}
className="absolute inset-0 z-0" offset={pan}
// Drawing Props onPan={setPan}
isDrawing={isDrawing} className="absolute inset-0 z-0"
currentTool={currentTool} // Drawing Props
currentColor={currentColor} isDrawing={isDrawing}
onAddAnnotation={addAnnotation} currentTool={currentTool}
/> currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
</div>
</div> </div>
{/* Zoom Toolbar */} {/* Zoom Toolbar */}
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200"> <div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
@@ -278,7 +307,9 @@ export function FileViewer({
onPause={onPause} onPause={onPause}
onTimeUpdate={onTimeUpdate} onTimeUpdate={onTimeUpdate}
annotations={displayAnnotations} annotations={displayAnnotations}
/> >
{children}
</VideoPlayer>
)} )}
</div> </div>
) )
@@ -53,6 +53,7 @@ interface VideoPlayerProps {
onPause?: () => void onPause?: () => void
onTimeUpdate?: (time: number) => void onTimeUpdate?: (time: number) => void
annotations?: Annotation[] annotations?: Annotation[]
children?: React.ReactNode
} }
type DisplayTranscode = VideoTranscode & { resolution: string } type DisplayTranscode = VideoTranscode & { resolution: string }
@@ -310,6 +311,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
onPause, onPause,
onTimeUpdate, onTimeUpdate,
annotations, annotations,
children,
}) => { }) => {
const localPlayerRef = useRef<Player | null>(null) const localPlayerRef = useRef<Player | null>(null)
const playerRef = passedPlayerRef || localPlayerRef const playerRef = passedPlayerRef || localPlayerRef
@@ -797,49 +799,54 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
onMouseMove={handleMouseMove} onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave} onMouseLeave={handleMouseLeave}
> >
{/* Video Area */} <div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
<div {/* Render Carousel/Sidebar here if not fullscreen */}
ref={containerRef} {!state.isFullScreen && children}
className={cn(
'w-full bg-black cursor-pointer relative flex items-center justify-center overflow-hidden flex-1 min-h-0',
)}
onClick={togglePlay}
data-vjs-player
>
{/* Hidden VideoJS container */}
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{/* Drawing Canvas (Visible) */} {/* Video Area */}
{videoHtmlEl && containerSize.width > 0 && ( <div
<DrawingCanvas ref={containerRef}
width={containerSize.width} className={cn(
height={containerSize.height} 'flex-1 bg-black cursor-pointer relative flex items-center justify-center overflow-hidden min-h-0',
mediaDimensions={{ )}
width: vidW, onClick={togglePlay}
height: vidH, data-vjs-player
}} >
videoElement={videoHtmlEl} {/* Hidden VideoJS container */}
annotations={displayAnnotations} <div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
scale={scale}
offset={{ x: panX, y: panY }}
className="absolute inset-0"
onClick={togglePlay}
// Drawing Props
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)}
{/* Big Play Button Overlay (when paused) */} {/* Drawing Canvas (Visible) */}
{!state.isPlaying && !isDrawing && ( {videoHtmlEl && containerSize.width > 0 && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10"> <DrawingCanvas
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse"> width={containerSize.width}
<Play className="w-10 h-10 text-white ml-1 fill-white" /> height={containerSize.height}
mediaDimensions={{
width: vidW,
height: vidH,
}}
videoElement={videoHtmlEl}
annotations={displayAnnotations}
scale={scale}
offset={{ x: panX, y: panY }}
className="absolute inset-0"
onClick={togglePlay}
// Drawing Props
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)}
{/* Big Play Button Overlay (when paused) */}
{!state.isPlaying && !isDrawing && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse">
<Play className="w-10 h-10 text-white ml-1 fill-white" />
</div>
</div> </div>
</div> )}
)} </div>
</div> </div>
<ControlBar <ControlBar
+8
View File
@@ -159,3 +159,11 @@
@apply bg-background text-foreground; @apply bg-background text-foreground;
} }
} }
.no-scrollbar {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
.no-scrollbar::-webkit-scrollbar {
display: none; /* Chrome, Safari and Opera */
}
@@ -7,12 +7,11 @@ import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
import { useMemberStore } from '@/ui/stores/members' import { useMemberStore } from '@/ui/stores/members'
import { useTeamContextStore } from '@/ui/stores/team-context' import { useTeamContextStore } from '@/ui/stores/team-context'
import { useTopNavStore } from '@/ui/stores/top-nav' import { useTopNavStore } from '@/ui/stores/top-nav'
import { useUiStore } from '@/ui/stores/ui'
import { type Annotation } from '@/ui/types' import { type Annotation } from '@/ui/types'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import { InferRequestType, InferResponseType } from 'hono/client' import { InferRequestType, InferResponseType } from 'hono/client'
import type { AssetInfo, CommentInfo } from '@shumai/dtos' import type { AssetInfo, AssetInfoPaginatedList, CommentInfo } from '@shumai/dtos'
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query' import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router' import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react' import { Loader2 } from 'lucide-react'
@@ -26,17 +25,17 @@ function FileViewPage() {
const activeFileId = versionAssetId || fileId const activeFileId = versionAssetId || fileId
const videoRef = useRef<Player | null>(null) const videoRef = useRef<Player | null>(null)
const {
fileViewRightSidebarCollapsed: isRightSidebarCollapsed,
fileViewLeftSidebarCollapsed: isLeftSidebarCollapsed,
setFileViewLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
} = useUiStore()
const { teamId, ensureTeamIdForProject } = useTeamContextStore() const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const [leftSidebarWidth, setLeftSidebarWidth] = useState(280)
const [rightSidebarWidth, setRightSidebarWidth] = useState(360) const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [annotations, setAnnotations] = useState<Annotation[]>([]) const [annotations, setAnnotations] = useState<Annotation[]>([])
const [currentTime, setCurrentTime] = useState(0) const [currentTime, setCurrentTime] = useState(0)
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null) const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
const [carouselState, setCarouselState] = useState<{
show: boolean
files: AssetInfo[]
nextCursor?: string
folderId?: string
}>({ show: false, files: [], nextCursor: undefined, folderId: undefined })
const $patchMetadata = client.api.files[':fileId'].metadata.$patch const $patchMetadata = client.api.files[':fileId'].metadata.$patch
const { mutate: patchMetadata } = useMutation< const { mutate: patchMetadata } = useMutation<
InferResponseType<typeof $patchMetadata>, InferResponseType<typeof $patchMetadata>,
@@ -171,6 +170,92 @@ function FileViewPage() {
navigate, navigate,
]) ])
const parentFolderId =
fileData?.ancestorFolders?.[fileData.ancestorFolders.length - 1]?.id ??
projectInfo?.rootFolder ??
''
useEffect(() => {
if (!parentFolderId || !activeFileId) return
if (carouselState.folderId === parentFolderId) {
return
}
let isMounted = true
const fetchCarouselData = async () => {
try {
let cursor = ''
let found = false
const allFiles: AssetInfo[] = []
let lastCursor: string | undefined = undefined
for (let batch = 0; batch < 5; batch++) {
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: parentFolderId },
json: {
assetType: 'file',
after: cursor,
first: 200,
recursively: false,
conditions: [],
},
})
if (!res.ok) {
throw new Error('Failed to search parent folder for carousel')
}
const result = (await res.json()) as unknown as AssetInfoPaginatedList
const batchFiles = (result.data || []) as AssetInfo[]
allFiles.push(...batchFiles)
if (batchFiles.some((f) => f.id === activeFileId)) {
found = true
lastCursor = result.pageInfo?.cursor || undefined
break
}
if (!result.pageInfo?.cursor || batchFiles.length < 200) {
break
}
cursor = result.pageInfo.cursor
}
if (isMounted) {
if (found) {
setCarouselState({
show: true,
files: allFiles,
nextCursor: lastCursor,
folderId: parentFolderId,
})
} else {
setCarouselState({
show: false,
files: [],
nextCursor: undefined,
folderId: parentFolderId,
})
}
}
} catch (err) {
console.error(err)
if (isMounted) {
setCarouselState({
show: false,
files: [],
nextCursor: undefined,
folderId: parentFolderId,
})
}
}
}
fetchCarouselData()
return () => {
isMounted = false
}
}, [parentFolderId, activeFileId, carouselState.folderId])
if (isLoading && !fileData) { if (isLoading && !fileData) {
return <FileDetailSkeleton /> return <FileDetailSkeleton />
} }
@@ -225,28 +310,6 @@ function FileViewPage() {
return ( return (
<div className="h-full flex flex-1 flex-col bg-background"> <div className="h-full flex flex-1 flex-col bg-background">
<div className="h-full flex flex-1 overflow-hidden"> <div className="h-full flex flex-1 overflow-hidden">
{!isLeftSidebarCollapsed && (
<>
<div style={{ width: leftSidebarWidth }} className="flex-shrink-0">
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={
fileData.ancestorFolders?.[fileData.ancestorFolders.length - 1]?.id ??
projectInfo.rootFolder ??
''
}
onCollapse={() => setIsLeftSidebarCollapsed(true)}
/>
</div>
<ResizeHandle
onResize={(delta) => {
setLeftSidebarWidth((prev) => Math.max(200, Math.min(500, prev + delta)))
}}
className="hidden md:block"
/>
</>
)}
<div className="flex-1 relative"> <div className="flex-1 relative">
{isFetching && ( {isFetching && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50"> <div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
@@ -259,35 +322,41 @@ function FileViewPage() {
onPlay={handlePlay} onPlay={handlePlay}
onTimeUpdate={setCurrentTime} onTimeUpdate={setCurrentTime}
annotations={annotations} annotations={annotations}
>
{carouselState.show && (
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
/>
)}
</FileViewer>
</div>
<ResizeHandle
onResize={(delta) => {
setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
}}
className="hidden md:block"
/>
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
<FileViewerRightSidebar
teamId={teamId}
projectId={projectId}
file={fileData as unknown as AssetInfo}
onSaveField={handleSaveField}
members={members}
onCommentSelect={handleCommentSelect}
currentTime={currentTime}
onTyping={() => {
if (videoRef.current) {
videoRef.current.pause()
}
}}
selectedCommentId={selectedCommentId}
/> />
</div> </div>
{!isRightSidebarCollapsed && (
<>
<ResizeHandle
onResize={(delta) => {
setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
}}
className="hidden md:block"
/>
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
<FileViewerRightSidebar
teamId={teamId}
projectId={projectId}
file={fileData as unknown as AssetInfo}
onSaveField={handleSaveField}
members={members}
onCommentSelect={handleCommentSelect}
currentTime={currentTime}
onTyping={() => {
if (videoRef.current) {
videoRef.current.pause()
}
}}
selectedCommentId={selectedCommentId}
/>
</div>
</>
)}
</div> </div>
</div> </div>
) )