feat(webui): always show right sidebar and implement left vertical carousel

This commit is contained in:
yiling
2026-06-15 15:37:10 +08:00
parent d8aaed5212
commit 68a1714e7f
5 changed files with 401 additions and 299 deletions
+3 -1
View File
@@ -203,7 +203,9 @@ 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
.spyOn(SandboxManager, 'initialize')
.mockImplementation(async (config, cb) => {
if (!registeredCallback) { if (!registeredCallback) {
registeredCallback = cb || null registeredCallback = cb || null
} }
@@ -240,6 +240,7 @@ export function BreadcrumbNav({
)} )}
</div> </div>
{!fileId && (
<div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1"> <div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1">
{/* Left Sidebar Toggle */} {/* Left Sidebar Toggle */}
{!isPublic && onLeftSidebarToggle && ( {!isPublic && onLeftSidebarToggle && (
@@ -299,6 +300,7 @@ export function BreadcrumbNav({
)} )}
</button> </button>
</div> </div>
)}
</div> </div>
) )
} }
@@ -457,7 +457,8 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
cursor: text; cursor: text;
} }
`}</style> `}</style>
{showMentionList && (membersLoading || filteredAgents.length > 0 || filteredHumans.length > 0) && ( {showMentionList &&
(membersLoading || filteredAgents.length > 0 || filteredHumans.length > 0) && (
<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"> <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">
<div className="h-64 overflow-y-auto"> <div className="h-64 overflow-y-auto">
{membersLoading ? ( {membersLoading ? (
@@ -1,26 +1,40 @@
import { client } from '@/ui/api/client' import { client } from '@/ui/api/client'
import { useInfiniteQuery } from '@tanstack/react-query' import { File, Loader2 } from 'lucide-react'
import { Loader2, PanelLeftClose } from 'lucide-react'
import type { FC } from 'react' import type { FC } from 'react'
import type { AssetInfoPaginatedList } from '@shumai/dtos' import type { AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos'
import { useEffect, useRef } from 'react' import { useEffect, useRef, useState } from 'react'
import { useInView } from 'react-intersection-observer' import { useInView } from 'react-intersection-observer'
import { SidebarFileCard } from './sidebar-file-card' import { Link } from '@tanstack/react-router'
import { Button } from './ui/button' import { cn } from '@/ui/lib/utils'
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,48 @@ 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',
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-full w-24 bg-card border-r border-border flex flex-col flex-shrink-0 select-none">
<div className="p-2 border-b flex items-center justify-between"> <div className="flex-1 overflow-y-auto py-4 flex 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">
<div className="p-2 space-y-2">
{isLoading && (
<div className="flex justify-center items-center p-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)}
{files.map(
(file) =>
file && (
<SidebarFileCard
ref={file.id === currentAssetId ? activeItemRef : null}
key={file.id} key={file.id}
projectId={projectId} ref={file.id === currentAssetId ? activeItemRef : null}
item={file} className="flex-shrink-0"
isActive={file.id === currentAssetId} >
/> <Link
), to="/projects/$projectId/files/$fileId"
params={{ projectId, fileId: file.id }}
search={{ version: undefined }}
className={cn(
'w-[54px] h-[54px] rounded-lg border overflow-hidden flex items-center justify-center transition-all bg-muted/30 block',
isActive
? 'border-primary ring-2 ring-primary opacity-100 scale-105'
: 'border-border hover:border-primary/50 opacity-65 hover:opacity-100',
)} )}
<div ref={ref}> >
{isFetchingNextPage && ( <CarouselFilePreview item={file} />
<div className="flex justify-center items-center p-4"> </Link>
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /> </div>
)
})}
{/* Infinite Scroll Trigger */}
{hasMore && (
<div ref={ref} className="py-2 flex justify-center items-center w-full">
{isFetchingNext && <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />}
</div> </div>
)} )}
</div> </div>
</div> </div>
</ScrollArea>
</div>
) )
} }
@@ -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,13 +25,7 @@ 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)
@@ -222,30 +215,110 @@ function FileViewPage() {
setSelectedCommentId(null) setSelectedCommentId(null)
} }
return ( const parentFolderId =
<div className="h-full flex flex-1 flex-col bg-background">
<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 ?? fileData.ancestorFolders?.[fileData.ancestorFolders.length - 1]?.id ??
projectInfo.rootFolder ?? projectInfo.rootFolder ??
'' ''
const [carouselState, setCarouselState] = useState<{
show: boolean
files: AssetInfo[]
nextCursor?: string
folderId?: string
}>({ show: false, files: [], nextCursor: undefined, folderId: undefined })
useEffect(() => {
if (!parentFolderId || !activeFileId) return
if (carouselState.folderId === parentFolderId) {
return
} }
onCollapse={() => setIsLeftSidebarCollapsed(true)}
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])
return (
<div className="h-full flex flex-1 flex-col bg-background">
<div className="h-full flex flex-1 overflow-hidden">
{carouselState.show && (
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
/> />
</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 && (
@@ -261,8 +334,6 @@ function FileViewPage() {
annotations={annotations} annotations={annotations}
/> />
</div> </div>
{!isRightSidebarCollapsed && (
<>
<ResizeHandle <ResizeHandle
onResize={(delta) => { onResize={(delta) => {
setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta))) setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
@@ -286,8 +357,6 @@ function FileViewPage() {
selectedCommentId={selectedCommentId} selectedCommentId={selectedCommentId}
/> />
</div> </div>
</>
)}
</div> </div>
</div> </div>
) )