feat(webui): code-split remaining team and share sub-routes to optimize vendor chunk size

This commit is contained in:
yiling
2026-07-09 15:16:33 +08:00
parent 6b5c2d8b23
commit a80e9de6cc
11 changed files with 1708 additions and 1674 deletions
+9 -5
View File
@@ -51,7 +51,7 @@ const TeamsTeamIdIndexRoute = TeamsTeamIdIndexRouteImport.update({
id: '/teams/$teamId/',
path: '/teams/$teamId/',
getParentRoute: () => rootRouteImport,
} as any)
} as any).lazy(() => import('./routes/teams/$teamId/index.lazy').then((d) => d.Route))
const ShareShareIdIndexRoute = ShareShareIdIndexRouteImport.update({
id: '/',
path: '/',
@@ -66,7 +66,7 @@ const TeamsTeamIdSettingsRoute = TeamsTeamIdSettingsRouteImport.update({
id: '/teams/$teamId/settings',
path: '/teams/$teamId/settings',
getParentRoute: () => rootRouteImport,
} as any)
} as any).lazy(() => import('./routes/teams/$teamId/settings.lazy').then((d) => d.Route))
const ProjectsProjectIdRecentlyDeletedRoute = ProjectsProjectIdRecentlyDeletedRouteImport.update({
id: '/projects/$projectId/recently-deleted',
path: '/projects/$projectId/recently-deleted',
@@ -78,12 +78,14 @@ const ProjectsProjectIdSharesIndexRoute = ProjectsProjectIdSharesIndexRouteImpor
id: '/projects/$projectId/shares/',
path: '/projects/$projectId/shares/',
getParentRoute: () => rootRouteImport,
} as any)
} as any).lazy(() => import('./routes/projects/$projectId/shares/index.lazy').then((d) => d.Route))
const ProjectsProjectIdCollectionsIndexRoute = ProjectsProjectIdCollectionsIndexRouteImport.update({
id: '/projects/$projectId/collections/',
path: '/projects/$projectId/collections/',
getParentRoute: () => rootRouteImport,
} as any)
} as any).lazy(() =>
import('./routes/projects/$projectId/collections/index.lazy').then((d) => d.Route),
)
const ShareShareIdFoldersFolderIdRoute = ShareShareIdFoldersFolderIdRouteImport.update({
id: '/folders/$folderId',
path: '/folders/$folderId',
@@ -98,7 +100,9 @@ const ProjectsProjectIdSharesShareIdRoute = ProjectsProjectIdSharesShareIdRouteI
id: '/projects/$projectId/shares/$shareId',
path: '/projects/$projectId/shares/$shareId',
getParentRoute: () => rootRouteImport,
} as any)
} as any).lazy(() =>
import('./routes/projects/$projectId/shares/$shareId.lazy').then((d) => d.Route),
)
const ProjectsProjectIdFoldersFolderIdRoute = ProjectsProjectIdFoldersFolderIdRouteImport.update({
id: '/projects/$projectId/folders/$folderId',
path: '/projects/$projectId/folders/$folderId',
@@ -0,0 +1,221 @@
import { createLazyFileRoute } from '@tanstack/react-router'
import { client } from '@/ui/api/client'
import { FolderTree } from '@/ui/components/folder-tree'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { m } from '@/ui/paraglide/messages.js'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/ui/components/ui/table'
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
import { useUiStore } from '@/ui/stores/ui'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useInfiniteQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useEffect, useMemo, useState } from 'react'
import { Bookmark, Calendar, LayoutGrid, Loader2 } from 'lucide-react'
import { useInView } from 'react-intersection-observer'
import type { CollectionInfo } from '@shumai/dtos'
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
import { projectInfoQueryOptions } from './index'
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
function CollectionsPage() {
const { projectId } = Route.useParams()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const navigate = useNavigate()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const rootFolderId = projectInfo?.rootFolder
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
} = useUiStore()
const {
data: collectionsData,
isLoading: isCollectionsLoading,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['collections', projectId],
queryFn: async ({ pageParam }) => {
const res = await client.api.projects[':projectId'].collections.$get({
param: { projectId },
query: { first: '20', after: pageParam as string },
})
if (!res.ok) throw new Error('Failed to fetch collections')
return (await res.json()) as unknown as {
data: CollectionInfo[]
pageInfo: { cursor?: string; total?: number }
}
},
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
enabled: !!projectId,
})
const { ref: inViewRef, inView } = useInView()
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
const collections = useMemo(
() => collectionsData?.pages.flatMap((p) => p.data) || [],
[collectionsData],
)
if (!teamId || !rootFolderId || !projectInfo) {
return <ProjectFolderSkeleton />
}
return (
<div className="flex flex-1 flex-col bg-background min-h-0">
<div className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && (
<div
className="md:hidden fixed inset-0 bg-black/50 z-40"
onClick={() => setIsLeftSidebarCollapsed(true)}
/>
)}
{!isLeftSidebarCollapsed && (
<>
<div className="bg-background" style={{ width: leftSidebarWidth }}>
<FolderTree
teamId={teamId}
projectId={projectId}
projectName={projectInfo.name ?? ''}
rootFolderId={rootFolderId}
/>
</div>
<ResizeHandle
onResize={(delta) => {
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
}}
className="hidden md:block"
/>
</>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
<div className="flex items-center gap-2">
<Bookmark className="h-5 w-5 text-primary" />
<h1 className="font-bold text-lg text-foreground">{m.all_collections()}</h1>
</div>
</header>
<div className="flex-1 overflow-y-auto p-6">
{isCollectionsLoading ? (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
</div>
) : collections.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
<LayoutGrid className="h-10 w-10 text-muted-foreground/50" />
<p>{m.no_collections_yet()}</p>
</div>
) : (
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent bg-muted/20">
<TableHead className="font-semibold px-4 py-3">
{m.collection_name()}
</TableHead>
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
<TableHead className="font-semibold px-4 py-3 w-[200px]">
{m.created_date()}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{collections.map((collection) => (
<TableRow
key={collection.id}
className="hover:bg-muted/10 transition-colors cursor-pointer"
onClick={() =>
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: collection.id },
})
}
>
<TableCell className="font-medium px-4 py-3.5">
<div className="flex items-center gap-2">
<Bookmark className="h-4 w-4 text-primary shrink-0" />
<span className="text-foreground font-semibold hover:underline">
{collection.name}
</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5">
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
{collection.creator?.image && (
<AvatarImage
src={collection.creator.image}
alt={collection.creator.name}
className="object-cover"
/>
)}
<AvatarFallback className="text-[10px]">
{getInitials(collection.creator?.name)}
</AvatarFallback>
</Avatar>
<span className="text-sm font-medium text-foreground truncate max-w-[200px]">
{collection.creator?.name || m.unknown()}
</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
<div className="flex items-center gap-2">
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
<span>{new Date(collection.createdAt).toLocaleDateString()}</span>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
}
export const Route = createLazyFileRoute('/projects/$projectId/collections/')({
component: CollectionsPage,
})
@@ -1,37 +1,8 @@
import { client } from '@/ui/api/client'
import { FolderTree } from '@/ui/components/folder-tree'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { m } from '@/ui/paraglide/messages.js'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/ui/components/ui/table'
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
import { useUiStore } from '@/ui/stores/ui'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useInfiniteQuery, useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useEffect, useMemo, useState } from 'react'
import { Bookmark, Calendar, LayoutGrid, Loader2 } from 'lucide-react'
import { useInView } from 'react-intersection-observer'
import type { CollectionInfo } from '@shumai/dtos'
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
import { createFileRoute } from '@tanstack/react-router'
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
const projectInfoQueryOptions = (projectId: string) => ({
export const projectInfoQueryOptions = (projectId: string) => ({
queryKey: ['projects', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].$get({
@@ -42,191 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
},
})
function CollectionsPage() {
const { projectId } = Route.useParams()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const navigate = useNavigate()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const rootFolderId = projectInfo?.rootFolder
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
} = useUiStore()
const {
data: collectionsData,
isLoading: isCollectionsLoading,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['collections', projectId],
queryFn: async ({ pageParam }) => {
const res = await client.api.projects[':projectId'].collections.$get({
param: { projectId },
query: { first: '20', after: pageParam as string },
})
if (!res.ok) throw new Error('Failed to fetch collections')
return (await res.json()) as unknown as {
data: CollectionInfo[]
pageInfo: { cursor?: string; total?: number }
}
},
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
enabled: !!projectId,
})
const { ref: inViewRef, inView } = useInView()
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
const collections = useMemo(
() => collectionsData?.pages.flatMap((p) => p.data) || [],
[collectionsData],
)
if (!teamId || !rootFolderId || !projectInfo) {
return <ProjectFolderSkeleton />
}
return (
<div className="flex flex-1 flex-col bg-background min-h-0">
<div className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && (
<div
className="md:hidden fixed inset-0 bg-black/50 z-40"
onClick={() => setIsLeftSidebarCollapsed(true)}
/>
)}
{!isLeftSidebarCollapsed && (
<>
<div className="bg-background" style={{ width: leftSidebarWidth }}>
<FolderTree
teamId={teamId}
projectId={projectId}
projectName={projectInfo.name ?? ''}
rootFolderId={rootFolderId}
/>
</div>
<ResizeHandle
onResize={(delta) => {
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
}}
className="hidden md:block"
/>
</>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
<div className="flex items-center gap-2">
<Bookmark className="h-5 w-5 text-primary" />
<h1 className="font-bold text-lg text-foreground">{m.all_collections()}</h1>
</div>
</header>
<div className="flex-1 overflow-y-auto p-6">
{isCollectionsLoading ? (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
</div>
) : collections.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
<LayoutGrid className="h-10 w-10 text-muted-foreground/50" />
<p>{m.no_collections_yet()}</p>
</div>
) : (
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent bg-muted/20">
<TableHead className="font-semibold px-4 py-3">
{m.collection_name()}
</TableHead>
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
<TableHead className="font-semibold px-4 py-3 w-[200px]">
{m.created_date()}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{collections.map((collection) => (
<TableRow
key={collection.id}
className="hover:bg-muted/10 transition-colors cursor-pointer"
onClick={() =>
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: collection.id },
})
}
>
<TableCell className="font-medium px-4 py-3.5">
<div className="flex items-center gap-2">
<Bookmark className="h-4 w-4 text-primary shrink-0" />
<span className="text-foreground font-semibold hover:underline">
{collection.name}
</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5">
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
{collection.creator?.image && (
<AvatarImage
src={collection.creator.image}
alt={collection.creator.name}
className="object-cover"
/>
)}
<AvatarFallback className="text-[10px]">
{getInitials(collection.creator?.name)}
</AvatarFallback>
</Avatar>
<span className="text-sm font-medium text-foreground truncate max-w-[200px]">
{collection.creator?.name || m.unknown()}
</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
<div className="flex items-center gap-2">
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
<span>{new Date(collection.createdAt).toLocaleDateString()}</span>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
}
export const Route = createFileRoute('/projects/$projectId/collections/')({
component: CollectionsPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => <ProjectFolderSkeleton />,
@@ -0,0 +1,51 @@
import { createLazyFileRoute } from '@tanstack/react-router'
import ShareManager from '@/ui/components/share-manager'
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useEffect } from 'react'
import { client } from '@/ui/api/client'
import { projectInfoQueryOptions } from './$shareId'
function SharePage() {
const { projectId, shareId } = Route.useParams()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({
queryKey: ['folders', rootFolderId!],
queryFn: async () => {
const res = await client.api.folders[':folderId'].$get({
param: { folderId: rootFolderId! },
})
if (!res.ok) throw new Error('Failed to fetch folder')
return await res.json()
},
enabled: !!rootFolderId,
})
if (!teamId || !rootFolderId || !rootFolder) {
return <ProjectFolderSkeleton />
}
return (
<ShareManager
teamId={teamId}
projectId={projectId}
projectName={projectInfo.name ?? ''}
shareId={shareId}
rootFolderId={rootFolderId}
/>
)
}
export const Route = createLazyFileRoute('/projects/$projectId/shares/$shareId')({
component: SharePage,
})
@@ -1,12 +1,8 @@
import { client } from '@/ui/api/client'
import ShareManager from '@/ui/components/share-manager'
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import { useEffect } from 'react'
const projectInfoQueryOptions = (projectId: string) => ({
export const projectInfoQueryOptions = (projectId: string) => ({
queryKey: ['projects', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].$get({
@@ -17,47 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
},
})
function SharePage() {
const { projectId, shareId } = Route.useParams()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({
queryKey: ['folders', rootFolderId!],
queryFn: async () => {
const res = await client.api.folders[':folderId'].$get({
param: { folderId: rootFolderId! },
})
if (!res.ok) throw new Error('Failed to fetch folder')
return await res.json()
},
enabled: !!rootFolderId,
})
if (!teamId || !rootFolderId || !rootFolder) {
return <ProjectFolderSkeleton />
}
return (
<ShareManager
teamId={teamId}
projectId={projectId}
projectName={projectInfo.name ?? ''}
shareId={shareId}
rootFolderId={rootFolderId}
/>
)
}
export const Route = createFileRoute('/projects/$projectId/shares/$shareId')({
component: SharePage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => <ProjectFolderSkeleton />,
@@ -0,0 +1,289 @@
import { createLazyFileRoute } from '@tanstack/react-router'
import { client } from '@/ui/api/client'
import { FolderTree } from '@/ui/components/folder-tree'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { m } from '@/ui/paraglide/messages.js'
import { Switch } from '@/ui/components/ui/switch'
import { Button } from '@/ui/components/ui/button'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/ui/components/ui/table'
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
import { useUiStore } from '@/ui/stores/ui'
import { useTeamContextStore } from '@/ui/stores/team-context'
import {
useMutation,
useInfiniteQuery,
useQueryClient,
useSuspenseQuery,
} from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useEffect, useMemo, useState } from 'react'
import { Copy, ExternalLink, Calendar, Link2, Share2, Loader2 } from 'lucide-react'
import { useInView } from 'react-intersection-observer'
import { toast } from 'sonner'
import type { ShareLinkInfo } from '@shumai/dtos'
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
import { projectInfoQueryOptions } from './index'
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
function SharesPage() {
const { projectId } = Route.useParams()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const queryClient = useQueryClient()
const navigate = useNavigate()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const rootFolderId = projectInfo?.rootFolder
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const {
shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
setShareConfigLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
} = useUiStore()
const {
data: sharesData,
isLoading: isSharesLoading,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['shares', projectId],
queryFn: async ({ pageParam }) => {
const res = await client.api.projects[':projectId'].shares.$get({
param: { projectId },
query: { first: '20', after: pageParam as string },
})
if (!res.ok) throw new Error('Failed to fetch share links')
return (await res.json()) as unknown as {
data: ShareLinkInfo[]
pageInfo: { cursor?: string; total?: number }
}
},
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
enabled: !!projectId,
})
const { ref: inViewRef, inView } = useInView()
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
const shares = useMemo(() => sharesData?.pages.flatMap((p) => p.data) || [], [sharesData])
const { mutate: toggleVisibility } = useMutation({
mutationFn: async ({ id, isDisabled }: { id: string; isDisabled: boolean }) => {
const res = await client.api.shares[':shareId'].$put({
param: { shareId: id },
json: { isDisabled },
})
if (!res.ok) throw new Error('Failed to update share link')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
toast.success(m.share_link_status_updated())
},
onError: (err) => {
toast.error(m.error_message({ message: err.message }))
},
})
if (!teamId || !rootFolderId || !projectInfo) {
return <ProjectFolderSkeleton />
}
const handleCopyLink = (shareId: string) => {
const url = `${window.location.origin}/share/${shareId}`
navigator.clipboard.writeText(url)
toast.success(m.link_copied())
}
return (
<div className="flex flex-1 flex-col bg-background min-h-0">
<div className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && (
<div
className="md:hidden fixed inset-0 bg-black/50 z-40"
onClick={() => setIsLeftSidebarCollapsed(true)}
/>
)}
{!isLeftSidebarCollapsed && (
<>
<div className="bg-background" style={{ width: leftSidebarWidth }}>
<FolderTree
teamId={teamId}
projectId={projectId}
projectName={projectInfo.name ?? ''}
rootFolderId={rootFolderId}
/>
</div>
<ResizeHandle
onResize={(delta) => {
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
}}
className="hidden md:block"
/>
</>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
<div className="flex items-center gap-2">
<Share2 className="h-5 w-5 text-primary" />
<h1 className="font-bold text-lg text-foreground">{m.all_share_links()}</h1>
</div>
</header>
<div className="flex-1 overflow-y-auto p-6">
{isSharesLoading ? (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
</div>
) : shares.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
<Link2 className="h-10 w-10 text-muted-foreground/50" />
<p>{m.no_share_links_yet()}</p>
</div>
) : (
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent bg-muted/20">
<TableHead className="font-semibold px-4 py-3">{m.name()}</TableHead>
<TableHead className="font-semibold px-4 py-3">{m.public_link()}</TableHead>
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
<TableHead className="font-semibold px-4 py-3 w-[150px]">
{m.created_date()}
</TableHead>
<TableHead className="font-semibold px-4 py-3 text-right w-[120px]">
{m.active()}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{shares.map((share) => {
const shareUrl = `${window.location.origin}/share/${share.id}`
return (
<TableRow key={share.id} className="hover:bg-muted/10 transition-colors">
<TableCell className="font-medium px-4 py-3.5">
<span
className="cursor-pointer hover:underline text-foreground"
onClick={() =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: share.id },
})
}
>
{share.name}
</span>
</TableCell>
<TableCell className="px-4 py-3.5 max-w-[300px]">
<div className="flex items-center gap-2 group">
<span
className="truncate text-xs font-mono bg-muted/50 text-muted-foreground px-2 py-1 rounded-md border border-border cursor-pointer hover:bg-muted transition-colors flex-1"
onClick={() => handleCopyLink(share.id)}
title={m.click_to_copy_link()}
>
{shareUrl}
</span>
<Button
variant="ghost"
size="icon-sm"
className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => handleCopyLink(share.id)}
>
<Copy className="h-3.5 w-3.5" />
</Button>
<a
href={shareUrl}
target="_blank"
rel="noreferrer"
className="text-muted-foreground hover:text-foreground inline-flex items-center"
>
<ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
</TableCell>
<TableCell className="px-4 py-3.5">
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
{share.creator?.image && (
<AvatarImage
src={share.creator.image}
alt={share.creator.name}
className="object-cover"
/>
)}
<AvatarFallback className="text-[10px]">
{getInitials(share.creator?.name)}
</AvatarFallback>
</Avatar>
<span className="text-sm font-medium text-foreground truncate max-w-[150px]">
{share.creator?.name || m.unknown()}
</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
<div className="flex items-center gap-2">
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
<span>{new Date(share.createdAt).toLocaleDateString()}</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5 text-right">
<div className="flex justify-end">
<Switch
checked={!share.isDisabled}
onCheckedChange={(checked) =>
toggleVisibility({ id: share.id, isDisabled: !checked })
}
/>
</div>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
}
export const Route = createLazyFileRoute('/projects/$projectId/shares/')({
component: SharesPage,
})
@@ -1,45 +1,8 @@
import { client } from '@/ui/api/client'
import { FolderTree } from '@/ui/components/folder-tree'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { m } from '@/ui/paraglide/messages.js'
import { Switch } from '@/ui/components/ui/switch'
import { Button } from '@/ui/components/ui/button'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/ui/components/ui/table'
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
import { useUiStore } from '@/ui/stores/ui'
import { useTeamContextStore } from '@/ui/stores/team-context'
import {
useMutation,
useInfiniteQuery,
useQueryClient,
useSuspenseQuery,
} from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useEffect, useMemo, useState } from 'react'
import { Copy, ExternalLink, Calendar, Link2, Share2, Loader2 } from 'lucide-react'
import { useInView } from 'react-intersection-observer'
import { toast } from 'sonner'
import type { ShareLinkInfo } from '@shumai/dtos'
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
import { createFileRoute } from '@tanstack/react-router'
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
const projectInfoQueryOptions = (projectId: string) => ({
export const projectInfoQueryOptions = (projectId: string) => ({
queryKey: ['projects', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].$get({
@@ -50,251 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
},
})
function SharesPage() {
const { projectId } = Route.useParams()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const queryClient = useQueryClient()
const navigate = useNavigate()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const rootFolderId = projectInfo?.rootFolder
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const {
shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
setShareConfigLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
} = useUiStore()
const {
data: sharesData,
isLoading: isSharesLoading,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['shares', projectId],
queryFn: async ({ pageParam }) => {
const res = await client.api.projects[':projectId'].shares.$get({
param: { projectId },
query: { first: '20', after: pageParam as string },
})
if (!res.ok) throw new Error('Failed to fetch share links')
return (await res.json()) as unknown as {
data: ShareLinkInfo[]
pageInfo: { cursor?: string; total?: number }
}
},
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
enabled: !!projectId,
})
const { ref: inViewRef, inView } = useInView()
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
const shares = useMemo(() => sharesData?.pages.flatMap((p) => p.data) || [], [sharesData])
const { mutate: toggleVisibility } = useMutation({
mutationFn: async ({ id, isDisabled }: { id: string; isDisabled: boolean }) => {
const res = await client.api.shares[':shareId'].$put({
param: { shareId: id },
json: { isDisabled },
})
if (!res.ok) throw new Error('Failed to update share link')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
toast.success(m.share_link_status_updated())
},
onError: (err) => {
toast.error(m.error_message({ message: err.message }))
},
})
if (!teamId || !rootFolderId || !projectInfo) {
return <ProjectFolderSkeleton />
}
const handleCopyLink = (shareId: string) => {
const url = `${window.location.origin}/share/${shareId}`
navigator.clipboard.writeText(url)
toast.success(m.link_copied())
}
return (
<div className="flex flex-1 flex-col bg-background min-h-0">
<div className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && (
<div
className="md:hidden fixed inset-0 bg-black/50 z-40"
onClick={() => setIsLeftSidebarCollapsed(true)}
/>
)}
{!isLeftSidebarCollapsed && (
<>
<div className="bg-background" style={{ width: leftSidebarWidth }}>
<FolderTree
teamId={teamId}
projectId={projectId}
projectName={projectInfo.name ?? ''}
rootFolderId={rootFolderId}
/>
</div>
<ResizeHandle
onResize={(delta) => {
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
}}
className="hidden md:block"
/>
</>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
<div className="flex items-center gap-2">
<Share2 className="h-5 w-5 text-primary" />
<h1 className="font-bold text-lg text-foreground">{m.all_share_links()}</h1>
</div>
</header>
<div className="flex-1 overflow-y-auto p-6">
{isSharesLoading ? (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
</div>
) : shares.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
<Link2 className="h-10 w-10 text-muted-foreground/50" />
<p>{m.no_share_links_yet()}</p>
</div>
) : (
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent bg-muted/20">
<TableHead className="font-semibold px-4 py-3">{m.name()}</TableHead>
<TableHead className="font-semibold px-4 py-3">{m.public_link()}</TableHead>
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
<TableHead className="font-semibold px-4 py-3 w-[150px]">
{m.created_date()}
</TableHead>
<TableHead className="font-semibold px-4 py-3 text-right w-[120px]">
{m.active()}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{shares.map((share) => {
const shareUrl = `${window.location.origin}/share/${share.id}`
return (
<TableRow key={share.id} className="hover:bg-muted/10 transition-colors">
<TableCell className="font-medium px-4 py-3.5">
<span
className="cursor-pointer hover:underline text-foreground"
onClick={() =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: share.id },
})
}
>
{share.name}
</span>
</TableCell>
<TableCell className="px-4 py-3.5 max-w-[300px]">
<div className="flex items-center gap-2 group">
<span
className="truncate text-xs font-mono bg-muted/50 text-muted-foreground px-2 py-1 rounded-md border border-border cursor-pointer hover:bg-muted transition-colors flex-1"
onClick={() => handleCopyLink(share.id)}
title={m.click_to_copy_link()}
>
{shareUrl}
</span>
<Button
variant="ghost"
size="icon-sm"
className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => handleCopyLink(share.id)}
>
<Copy className="h-3.5 w-3.5" />
</Button>
<a
href={shareUrl}
target="_blank"
rel="noreferrer"
className="text-muted-foreground hover:text-foreground inline-flex items-center"
>
<ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
</TableCell>
<TableCell className="px-4 py-3.5">
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
{share.creator?.image && (
<AvatarImage
src={share.creator.image}
alt={share.creator.name}
className="object-cover"
/>
)}
<AvatarFallback className="text-[10px]">
{getInitials(share.creator?.name)}
</AvatarFallback>
</Avatar>
<span className="text-sm font-medium text-foreground truncate max-w-[150px]">
{share.creator?.name || m.unknown()}
</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
<div className="flex items-center gap-2">
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
<span>{new Date(share.createdAt).toLocaleDateString()}</span>
</div>
</TableCell>
<TableCell className="px-4 py-3.5 text-right">
<div className="flex justify-end">
<Switch
checked={!share.isDisabled}
onCheckedChange={(checked) =>
toggleVisibility({ id: share.id, isDisabled: !checked })
}
/>
</div>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
}
export const Route = createFileRoute('/projects/$projectId/shares/')({
component: SharesPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => <ProjectFolderSkeleton />,
@@ -0,0 +1,498 @@
import { createLazyFileRoute } from '@tanstack/react-router'
import type { ProjectInfo } from '@shumai/dtos'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { client } from '@/ui/api/client'
import { MembersDialog } from '@/ui/components/members-dialog'
import { ProjectDialog } from '@/ui/components/project-dialog'
import { SortDropdown } from '@/ui/components/sort-dropdown'
import { m } from '@/ui/paraglide/messages.js'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Button } from '@/ui/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { Input } from '@/ui/components/ui/input'
import { Switch } from '@/ui/components/ui/switch'
import { formatDateAgo } from '@/ui/lib/time'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { MoreHorizontal, PlusIcon } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
function TeamPage() {
const { teamId } = Route.useParams()
const { canEdit, canAdmin } = usePermissions()
const navigate = useNavigate()
const queryClient = useQueryClient()
// State for clicked project for animation
const [clickedProjectId, setClickedProjectId] = useState<string | null>(null)
// State for Project Dialog
const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false)
const [projectDialogMode, setProjectDialogMode] = useState<'create' | 'edit'>('create')
const [selectedProject, setSelectedProject] = useState<ProjectInfo | undefined>(undefined)
// State for Delete Alert
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [projectToDelete, setProjectToDelete] = useState<ProjectInfo | undefined>(undefined)
const [deleteConfirmText, setDeleteConfirmText] = useState('')
// State for Members Dialog
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
// Sort State
const [sortBy, setSortBy] = useState<string>('name')
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
const $getProjects = client.api.teams[':teamId'].projects.$get
const { data: projects } = useSuspenseQuery({
queryKey: ['teams', teamId, 'projects', sortBy, sortDirection],
queryFn: async () => {
const res = await $getProjects({
param: { teamId: teamId },
query: { sortBy, sortDirection },
})
if (!res.ok) throw new Error('Failed to fetch projects')
return await res.json()
},
})
const { data: members } = useQuery({
queryKey: ['teams', teamId, 'members'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].members.$get({
param: { teamId: teamId },
query: {},
})
if (!res.ok) throw new Error('Failed to fetch members')
return await res.json()
},
})
const { data: me } = useQuery({
queryKey: ['teams', teamId, 'me'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].me.$get({
param: { teamId: teamId },
})
if (!res.ok) throw new Error('Failed to fetch me')
return await res.json()
},
})
const $inviteTeam = client.api.teams[':teamId'].invite.$post
const inviteMutation = useMutation<
InferResponseType<typeof $inviteTeam>,
Error,
InferRequestType<typeof $inviteTeam>
>({
mutationFn: async (args) => {
const res = await $inviteTeam(args)
if (!res.ok) {
throw new Error('Failed to invite')
}
return await res.json()
},
})
const deleteProjectMutation = useMutation({
mutationFn: async (projectId: string) => {
const res = await client.api.projects[':projectId'].$delete({
param: { projectId },
})
if (!res.ok) throw new Error('Failed to delete project')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
},
})
const toggleProjectNotificationsMutation = useMutation({
mutationFn: async (project: ProjectInfo) => {
const res = await client.api.projects[':projectId'].$put({
param: { projectId: project.id! },
json: {
enableNotification: !project.enableNotification,
},
})
if (!res.ok) throw new Error('Failed to update project notification settings')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
toast.success(m.project_notification_updated())
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : m.failed_update_project_notification())
},
})
const handleCreateProjectClick = () => {
setProjectDialogMode('create')
setSelectedProject(undefined)
setIsProjectDialogOpen(true)
}
const handleCreateCardClick = () => {
setClickedProjectId('create')
setTimeout(() => {
setClickedProjectId(null)
}, 100)
setTimeout(() => {
handleCreateProjectClick()
}, 200)
}
const handleEditProjectClick = (project: ProjectInfo) => {
setProjectDialogMode('edit')
setSelectedProject(project)
setIsProjectDialogOpen(true)
}
const handleDeleteProjectClick = (project: ProjectInfo) => {
setProjectToDelete(project)
setDeleteConfirmText('')
setIsDeleteDialogOpen(true)
}
const handleConfirmDelete = async () => {
if (projectToDelete && deleteConfirmText === 'delete') {
try {
await deleteProjectMutation.mutateAsync(projectToDelete.id!)
setIsDeleteDialogOpen(false)
} catch (error) {
console.error(error)
}
}
}
const handleCardClick = (projectId: string, e: React.MouseEvent) => {
if (e.detail > 1) return
setClickedProjectId(projectId)
// Restore scale after 100ms for "shrink and restore" effect
setTimeout(() => {
setClickedProjectId(null)
}, 100)
// Navigate after 200ms
setTimeout(() => {
navigate({
to: '/projects/$projectId',
params: { projectId },
})
}, 200)
}
const handleInvite = async (role: 'editor' | 'reviewer') => {
const res = await inviteMutation.mutateAsync({
param: { teamId: teamId },
json: { role },
})
return res.code
}
const updateMemberRoleMutation = useMutation({
mutationFn: async ({ userId, role }: { userId: string; role: 'editor' | 'reviewer' }) => {
const res = await client.api.teams[':teamId'].members[':userId'].$patch({
param: { teamId, userId },
json: { role },
})
if (!res.ok) throw new Error('Failed to update member role')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
},
})
const removeMemberMutation = useMutation({
mutationFn: async (userId: string) => {
const res = await client.api.teams[':teamId'].members[':userId'].$delete({
param: { teamId, userId },
})
if (!res.ok) throw new Error('Failed to remove member')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
},
})
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
const handleSortChange = (newSortBy: string, newSortDirection: 'asc' | 'desc') => {
setSortBy(newSortBy)
setSortDirection(newSortDirection)
}
const safeMembers = Array.isArray(members) ? members : []
return (
<div className="flex-1 overflow-y-auto p-4">
<div className="flex flex-wrap items-center justify-between mb-4 gap-4">
<h1 className="text-2xl font-bold">{m.projects()}</h1>
<div className="flex flex-wrap items-center gap-4">
<div
className="flex items-center -space-x-2 cursor-pointer hover:opacity-90"
onClick={() => setIsMembersDialogOpen(true)}
>
{safeMembers.slice(0, 3).map((member) => (
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
{member.image && (
<AvatarImage src={member.image} alt={member.name} className="object-cover" />
)}
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
</Avatar>
))}
{safeMembers.length > 3 && (
<div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-background bg-muted text-[10px] font-medium">
+{safeMembers.length - 3}
</div>
)}
</div>
<SortDropdown
sortBy={sortBy}
sortDirection={sortDirection}
onSortChange={handleSortChange}
/>
{canEdit && (
<Button
className="bg-orange-600 hover:bg-orange-700 text-white gap-2"
onClick={handleCreateProjectClick}
>
<PlusIcon className="w-4 h-4" />
{m.create_project()}
</Button>
)}
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
{projects.data?.map((project: ProjectInfo) => (
<div
key={project.id}
className={cn(
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out',
clickedProjectId === project.id ? 'scale-95' : 'scale-100',
)}
onClick={(e) => handleCardClick(project.id!, e)}
>
<div className="flex flex-col">
<div className="relative w-full h-full aspect-square flex items-center justify-center bg-zinc-400/20">
{project.coverImage ? (
<img
src={project.coverImage}
alt={project.name}
className="w-full h-full object-cover rounded"
/>
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 180.95 164.7"
preserveAspectRatio="xMidYMid slice"
className="w-full h-full object-cover rounded"
>
<polygon
fill="#FC9F8E"
points="0 18.5 0 76.0 151.69 164.7 180.95 164.7 180.95 113.6"
/>
<polygon
fill="#FEBAB8"
points="0 0 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0"
/>
<polyline
fill="#FAA5A5"
points="0 18.5 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0 0 0"
/>
<polygon fill="#EC5B6C" points="0 76.0 0 164.7 151.69 164.7" />
<polygon
fill="#E85C71"
points="180.95 18.9 110.33 63.9 117.37 68.0 117.26 73.4 180.95 113.6"
/>
<polygon
fill="#C8405B"
points="117.26 73.4 117.37 99.0 90.53 114.9 174.35 164.7 180.95 164.7 180.95 113.6"
/>
<polygon fill="#FFCCBE" points="90.53 51.6 63.69 68.1 90.53 83.4" />
<path
fill="#FB9991"
d="M 90.53 51.6 L 90.53 61.3 L 100.87 67.4 L 90.53 73.5 L 90.53 83.4 L 117.37 68.0 C 117.15 67.6 90.53 51.6 90.53 51.6 Z"
/>
<path
fill="#FFEACD"
d="M 63.69 68.1 C 63.47 68.5 64.02 99.3 64.02 99.3 C 64.02 99.3 64.46 99.6 64.9 99.9 L 90.53 83.4 L 63.69 68.1 Z"
/>
<polygon fill="#FFCFB5" points="64.02 99.3 90.53 114.9 90.53 83.4" />
<path fill="#F67D73" d="M 90.53 83.4 L 90.53 114.9 L 117.37 99.0 Z" />
<path fill="#F26560" d="M 90.53 83.4 L 117.37 99.0 L 117.37 68.0 Z" />
<polygon fill="#EB5F5B" points="80.08 67.5 90.53 73.5 90.53 61.3" />
<polygon fill="#DB4D50" points="90.53 61.3 90.53 73.5 100.87 67.4" />
</svg>
)}
<div className="absolute bottom-0 left-0 w-full h-[65%] bg-linear-to-t from-black/35 to-black/0" />
<p className="absolute left-1 bottom-2 text-white">{project.name}</p>
</div>
<div className="px-2 h-10 flex justify-between items-center">
<p className="truncate pr-1 text-xs text-muted-foreground">
{m.updated_ago()} {formatDateAgo((project.updatedAt as string) ?? '')}
</p>
<div onClick={(e) => e.stopPropagation()}>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className="hover:bg-muted outline-none flex px-1">
<MoreHorizontal className="w-5 h-5 text-muted-foreground" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{canEdit && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
handleEditProjectClick(project)
}}
>
{m.project_settings()}
</DropdownMenuItem>
)}
<DropdownMenuItem
className="flex items-center justify-between gap-4 cursor-pointer"
onSelect={(e) => {
e.preventDefault()
toggleProjectNotificationsMutation.mutate(project)
}}
>
<span>{m.notification()}</span>
<Switch
checked={project.enableNotification ?? true}
className="pointer-events-none"
/>
</DropdownMenuItem>
{canAdmin && (
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onClick={() => handleDeleteProjectClick(project)}
>
{m.delete()}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</div>
))}
{canEdit && (
<div
className={cn(
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out border-dashed hover:border-orange-600/50 group',
clickedProjectId === 'create' ? 'scale-95' : 'scale-100',
)}
onClick={handleCreateCardClick}
>
<div className="flex flex-col">
<div className="relative w-full aspect-square flex items-center justify-center bg-zinc-400/5 group-hover:bg-orange-600/5 transition-colors">
<PlusIcon className="w-8 h-8 text-zinc-400 group-hover:text-orange-600 transition-colors" />
</div>
<div className="px-2 h-10 flex items-center justify-center bg-zinc-400/10 border-t group-hover:bg-orange-600/10 transition-colors">
<p className="text-sm text-muted-foreground group-hover:text-orange-600 transition-colors">
{m.create_project()}
</p>
</div>
</div>
</div>
)}
</div>
<ProjectDialog
open={isProjectDialogOpen}
onOpenChange={setIsProjectDialogOpen}
mode={projectDialogMode}
teamId={teamId}
project={selectedProject}
/>
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.are_you_sure()}</AlertDialogTitle>
<AlertDialogDescription>
{m.delete_project_warning({ name: projectToDelete?.name ?? '' })}
<div className="mt-4 flex flex-col gap-2 text-foreground">
<span className="text-sm font-medium">{m.type_delete_to_confirm()}</span>
<Input
value={deleteConfirmText}
onChange={(e) => setDeleteConfirmText(e.target.value)}
placeholder={m.delete_placeholder()}
className="h-9"
autoFocus
/>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteProjectMutation.isPending}>
{m.cancel()}
</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault()
handleConfirmDelete()
}}
disabled={deleteConfirmText !== 'delete' || deleteProjectMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteProjectMutation.isPending ? m.deleting() : m.delete()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<MembersDialog
open={isMembersDialogOpen}
onOpenChange={setIsMembersDialogOpen}
title={m.team_members()}
type="team"
members={safeMembers}
isOwner={me?.role === 'owner'}
onInvite={handleInvite}
onUpdateRole={async (memberId, role) => {
await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
}}
onRemoveMember={async (memberId) => {
await removeMemberMutation.mutateAsync(memberId)
}}
currentUserId={me?.id}
/>
</div>
)
}
export const Route = createLazyFileRoute('/teams/$teamId/')({
component: TeamPage,
})
+2 -496
View File
@@ -1,497 +1,3 @@
import type { ProjectInfo } from '@shumai/dtos'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { client } from '@/ui/api/client'
import { MembersDialog } from '@/ui/components/members-dialog'
import { ProjectDialog } from '@/ui/components/project-dialog'
import { SortDropdown } from '@/ui/components/sort-dropdown'
import { m } from '@/ui/paraglide/messages.js'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Button } from '@/ui/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { Input } from '@/ui/components/ui/input'
import { Switch } from '@/ui/components/ui/switch'
import { formatDateAgo } from '@/ui/lib/time'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { MoreHorizontal, PlusIcon } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { createFileRoute } from '@tanstack/react-router'
function TeamPage() {
const { teamId } = Route.useParams()
const { canEdit, canAdmin } = usePermissions()
const navigate = useNavigate()
const queryClient = useQueryClient()
// State for clicked project for animation
const [clickedProjectId, setClickedProjectId] = useState<string | null>(null)
// State for Project Dialog
const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false)
const [projectDialogMode, setProjectDialogMode] = useState<'create' | 'edit'>('create')
const [selectedProject, setSelectedProject] = useState<ProjectInfo | undefined>(undefined)
// State for Delete Alert
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [projectToDelete, setProjectToDelete] = useState<ProjectInfo | undefined>(undefined)
const [deleteConfirmText, setDeleteConfirmText] = useState('')
// State for Members Dialog
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
// Sort State
const [sortBy, setSortBy] = useState<string>('name')
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
const $getProjects = client.api.teams[':teamId'].projects.$get
const { data: projects } = useSuspenseQuery({
queryKey: ['teams', teamId, 'projects', sortBy, sortDirection],
queryFn: async () => {
const res = await $getProjects({
param: { teamId: teamId },
query: { sortBy, sortDirection },
})
if (!res.ok) throw new Error('Failed to fetch projects')
return await res.json()
},
})
const { data: members } = useQuery({
queryKey: ['teams', teamId, 'members'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].members.$get({
param: { teamId: teamId },
query: {},
})
if (!res.ok) throw new Error('Failed to fetch members')
return await res.json()
},
})
const { data: me } = useQuery({
queryKey: ['teams', teamId, 'me'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].me.$get({
param: { teamId: teamId },
})
if (!res.ok) throw new Error('Failed to fetch me')
return await res.json()
},
})
const $inviteTeam = client.api.teams[':teamId'].invite.$post
const inviteMutation = useMutation<
InferResponseType<typeof $inviteTeam>,
Error,
InferRequestType<typeof $inviteTeam>
>({
mutationFn: async (args) => {
const res = await $inviteTeam(args)
if (!res.ok) {
throw new Error('Failed to invite')
}
return await res.json()
},
})
const deleteProjectMutation = useMutation({
mutationFn: async (projectId: string) => {
const res = await client.api.projects[':projectId'].$delete({
param: { projectId },
})
if (!res.ok) throw new Error('Failed to delete project')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
},
})
const toggleProjectNotificationsMutation = useMutation({
mutationFn: async (project: ProjectInfo) => {
const res = await client.api.projects[':projectId'].$put({
param: { projectId: project.id! },
json: {
enableNotification: !project.enableNotification,
},
})
if (!res.ok) throw new Error('Failed to update project notification settings')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
toast.success(m.project_notification_updated())
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : m.failed_update_project_notification())
},
})
const handleCreateProjectClick = () => {
setProjectDialogMode('create')
setSelectedProject(undefined)
setIsProjectDialogOpen(true)
}
const handleCreateCardClick = () => {
setClickedProjectId('create')
setTimeout(() => {
setClickedProjectId(null)
}, 100)
setTimeout(() => {
handleCreateProjectClick()
}, 200)
}
const handleEditProjectClick = (project: ProjectInfo) => {
setProjectDialogMode('edit')
setSelectedProject(project)
setIsProjectDialogOpen(true)
}
const handleDeleteProjectClick = (project: ProjectInfo) => {
setProjectToDelete(project)
setDeleteConfirmText('')
setIsDeleteDialogOpen(true)
}
const handleConfirmDelete = async () => {
if (projectToDelete && deleteConfirmText === 'delete') {
try {
await deleteProjectMutation.mutateAsync(projectToDelete.id!)
setIsDeleteDialogOpen(false)
} catch (error) {
console.error(error)
}
}
}
const handleCardClick = (projectId: string, e: React.MouseEvent) => {
if (e.detail > 1) return
setClickedProjectId(projectId)
// Restore scale after 100ms for "shrink and restore" effect
setTimeout(() => {
setClickedProjectId(null)
}, 100)
// Navigate after 200ms
setTimeout(() => {
navigate({
to: '/projects/$projectId',
params: { projectId },
})
}, 200)
}
const handleInvite = async (role: 'editor' | 'reviewer') => {
const res = await inviteMutation.mutateAsync({
param: { teamId: teamId },
json: { role },
})
return res.code
}
const updateMemberRoleMutation = useMutation({
mutationFn: async ({ userId, role }: { userId: string; role: 'editor' | 'reviewer' }) => {
const res = await client.api.teams[':teamId'].members[':userId'].$patch({
param: { teamId, userId },
json: { role },
})
if (!res.ok) throw new Error('Failed to update member role')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
},
})
const removeMemberMutation = useMutation({
mutationFn: async (userId: string) => {
const res = await client.api.teams[':teamId'].members[':userId'].$delete({
param: { teamId, userId },
})
if (!res.ok) throw new Error('Failed to remove member')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
},
})
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
const handleSortChange = (newSortBy: string, newSortDirection: 'asc' | 'desc') => {
setSortBy(newSortBy)
setSortDirection(newSortDirection)
}
const safeMembers = Array.isArray(members) ? members : []
return (
<div className="flex-1 overflow-y-auto p-4">
<div className="flex flex-wrap items-center justify-between mb-4 gap-4">
<h1 className="text-2xl font-bold">{m.projects()}</h1>
<div className="flex flex-wrap items-center gap-4">
<div
className="flex items-center -space-x-2 cursor-pointer hover:opacity-90"
onClick={() => setIsMembersDialogOpen(true)}
>
{safeMembers.slice(0, 3).map((member) => (
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
{member.image && (
<AvatarImage src={member.image} alt={member.name} className="object-cover" />
)}
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
</Avatar>
))}
{safeMembers.length > 3 && (
<div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-background bg-muted text-[10px] font-medium">
+{safeMembers.length - 3}
</div>
)}
</div>
<SortDropdown
sortBy={sortBy}
sortDirection={sortDirection}
onSortChange={handleSortChange}
/>
{canEdit && (
<Button
className="bg-orange-600 hover:bg-orange-700 text-white gap-2"
onClick={handleCreateProjectClick}
>
<PlusIcon className="w-4 h-4" />
{m.create_project()}
</Button>
)}
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
{projects.data?.map((project: ProjectInfo) => (
<div
key={project.id}
className={cn(
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out',
clickedProjectId === project.id ? 'scale-95' : 'scale-100',
)}
onClick={(e) => handleCardClick(project.id!, e)}
>
<div className="flex flex-col">
<div className="relative w-full h-full aspect-square flex items-center justify-center bg-zinc-400/20">
{project.coverImage ? (
<img
src={project.coverImage}
alt={project.name}
className="w-full h-full object-cover rounded"
/>
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 180.95 164.7"
preserveAspectRatio="xMidYMid slice"
className="w-full h-full object-cover rounded"
>
<polygon
fill="#FC9F8E"
points="0 18.5 0 76.0 151.69 164.7 180.95 164.7 180.95 113.6"
/>
<polygon
fill="#FEBAB8"
points="0 0 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0"
/>
<polyline
fill="#FAA5A5"
points="0 18.5 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0 0 0"
/>
<polygon fill="#EC5B6C" points="0 76.0 0 164.7 151.69 164.7" />
<polygon
fill="#E85C71"
points="180.95 18.9 110.33 63.9 117.37 68.0 117.26 73.4 180.95 113.6"
/>
<polygon
fill="#C8405B"
points="117.26 73.4 117.37 99.0 90.53 114.9 174.35 164.7 180.95 164.7 180.95 113.6"
/>
<polygon fill="#FFCCBE" points="90.53 51.6 63.69 68.1 90.53 83.4" />
<path
fill="#FB9991"
d="M 90.53 51.6 L 90.53 61.3 L 100.87 67.4 L 90.53 73.5 L 90.53 83.4 L 117.37 68.0 C 117.15 67.6 90.53 51.6 90.53 51.6 Z"
/>
<path
fill="#FFEACD"
d="M 63.69 68.1 C 63.47 68.5 64.02 99.3 64.02 99.3 C 64.02 99.3 64.46 99.6 64.9 99.9 L 90.53 83.4 L 63.69 68.1 Z"
/>
<polygon fill="#FFCFB5" points="64.02 99.3 90.53 114.9 90.53 83.4" />
<path fill="#F67D73" d="M 90.53 83.4 L 90.53 114.9 L 117.37 99.0 Z" />
<path fill="#F26560" d="M 90.53 83.4 L 117.37 99.0 L 117.37 68.0 Z" />
<polygon fill="#EB5F5B" points="80.08 67.5 90.53 73.5 90.53 61.3" />
<polygon fill="#DB4D50" points="90.53 61.3 90.53 73.5 100.87 67.4" />
</svg>
)}
<div className="absolute bottom-0 left-0 w-full h-[65%] bg-linear-to-t from-black/35 to-black/0" />
<p className="absolute left-1 bottom-2 text-white">{project.name}</p>
</div>
<div className="px-2 h-10 flex justify-between items-center">
<p className="truncate pr-1 text-xs text-muted-foreground">
{m.updated_ago()} {formatDateAgo((project.updatedAt as string) ?? '')}
</p>
<div onClick={(e) => e.stopPropagation()}>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className="hover:bg-muted outline-none flex px-1">
<MoreHorizontal className="w-5 h-5 text-muted-foreground" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{canEdit && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
handleEditProjectClick(project)
}}
>
{m.project_settings()}
</DropdownMenuItem>
)}
<DropdownMenuItem
className="flex items-center justify-between gap-4 cursor-pointer"
onSelect={(e) => {
e.preventDefault()
toggleProjectNotificationsMutation.mutate(project)
}}
>
<span>{m.notification()}</span>
<Switch
checked={project.enableNotification ?? true}
className="pointer-events-none"
/>
</DropdownMenuItem>
{canAdmin && (
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onClick={() => handleDeleteProjectClick(project)}
>
{m.delete()}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</div>
))}
{canEdit && (
<div
className={cn(
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out border-dashed hover:border-orange-600/50 group',
clickedProjectId === 'create' ? 'scale-95' : 'scale-100',
)}
onClick={handleCreateCardClick}
>
<div className="flex flex-col">
<div className="relative w-full aspect-square flex items-center justify-center bg-zinc-400/5 group-hover:bg-orange-600/5 transition-colors">
<PlusIcon className="w-8 h-8 text-zinc-400 group-hover:text-orange-600 transition-colors" />
</div>
<div className="px-2 h-10 flex items-center justify-center bg-zinc-400/10 border-t group-hover:bg-orange-600/10 transition-colors">
<p className="text-sm text-muted-foreground group-hover:text-orange-600 transition-colors">
{m.create_project()}
</p>
</div>
</div>
</div>
)}
</div>
<ProjectDialog
open={isProjectDialogOpen}
onOpenChange={setIsProjectDialogOpen}
mode={projectDialogMode}
teamId={teamId}
project={selectedProject}
/>
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.are_you_sure()}</AlertDialogTitle>
<AlertDialogDescription>
{m.delete_project_warning({ name: projectToDelete?.name ?? '' })}
<div className="mt-4 flex flex-col gap-2 text-foreground">
<span className="text-sm font-medium">{m.type_delete_to_confirm()}</span>
<Input
value={deleteConfirmText}
onChange={(e) => setDeleteConfirmText(e.target.value)}
placeholder={m.delete_placeholder()}
className="h-9"
autoFocus
/>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteProjectMutation.isPending}>
{m.cancel()}
</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault()
handleConfirmDelete()
}}
disabled={deleteConfirmText !== 'delete' || deleteProjectMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteProjectMutation.isPending ? m.deleting() : m.delete()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<MembersDialog
open={isMembersDialogOpen}
onOpenChange={setIsMembersDialogOpen}
title={m.team_members()}
type="team"
members={safeMembers}
isOwner={me?.role === 'owner'}
onInvite={handleInvite}
onUpdateRole={async (memberId, role) => {
await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
}}
onRemoveMember={async (memberId) => {
await removeMemberMutation.mutateAsync(memberId)
}}
currentUserId={me?.id}
/>
</div>
)
}
export const Route = createFileRoute('/teams/$teamId/')({
component: TeamPage,
})
export const Route = createFileRoute('/teams/$teamId/')({})
@@ -0,0 +1,632 @@
import { createLazyFileRoute } from '@tanstack/react-router'
import { VideoTranscodeStrategy, UpdateTeamSettingsRequest } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { AgentsSettings } from '@/ui/components/settings/AgentsSettings'
import { ProvidersSettings } from '@/ui/components/settings/ProvidersSettings'
import { SandboxSettings } from '@/ui/components/settings/SandboxSettings'
import { SkillsConfigCard } from '@/ui/components/settings/SkillsConfigCard'
import { NotificationSettings } from '@/ui/components/settings/NotificationSettings'
import { DeveloperSettings } from '@/ui/components/settings/DeveloperSettings'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Bot, Cpu, Film, Loader2, Puzzle, Shield, User, Bell, Key } from 'lucide-react'
import { useState, useRef, useEffect } from 'react'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { AvatarCropDialog } from '@/ui/components/settings/AvatarCropDialog'
import { toast } from 'sonner'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
import { getLocale, setLocale } from '@/ui/paraglide/runtime.js'
import { m } from '@/ui/paraglide/messages.js'
type SettingsTab =
| 'general'
| 'transcode'
| 'skills'
| 'providers'
| 'agents'
| 'sandbox'
| 'notifications'
| 'developer'
function TeamSettingsPage() {
const { teamId } = Route.useParams()
const queryClient = useQueryClient()
const [activeTab, setActiveTab] = useState<SettingsTab>('general')
const [profileName, setProfileName] = useState('')
const [isCropOpen, setIsCropOpen] = useState(false)
const [cropImageSrc, setCropImageSrc] = useState<string | null>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const [isUpdatingProfile, setIsUpdatingProfile] = useState(false)
const { setMetadata, getMetadata } = useUserMetadataStore()
const currentLocale = getMetadata<string>('locale') || getLocale()
const handleLanguageChange = async (newLocale: string) => {
if (newLocale === 'en' || newLocale === 'zh') {
try {
await setMetadata(teamId, 'locale', newLocale)
setLocale(newLocale)
toast.success(m.language_updated())
} catch (e) {
console.error(e)
toast.error(m.failed_update_language())
}
}
}
const {
data: settings,
isLoading: isSettingsLoading,
error: settingsError,
} = useQuery({
queryKey: ['teams', teamId, 'settings'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].settings.$get({
param: { teamId: teamId },
})
if (!res.ok) throw new Error('Failed to fetch settings')
return await res.json()
},
})
const { data: me, isLoading: isMeLoading } = useQuery({
queryKey: ['teams', teamId, 'me'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].me.$get({
param: { teamId: teamId },
})
if (!res.ok) throw new Error('Failed to fetch me')
return await res.json()
},
enabled: !!teamId,
})
useEffect(() => {
if (me?.name) {
setProfileName(me.name)
}
}, [me])
const getInitials = (name?: string) => {
if (!name) return 'U'
const names = name.split(' ')
if (names.length > 1) {
return `${names[0][0]}${names[names.length - 1][0]}`.toUpperCase()
}
return name.substring(0, 2).toUpperCase()
}
const handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
const reader = new FileReader()
reader.onload = () => {
setCropImageSrc(reader.result as string)
setIsCropOpen(true)
}
reader.readAsDataURL(file)
e.target.value = ''
}
}
const handleConfirmCrop = async (blob: Blob) => {
setIsUpdatingProfile(true)
try {
const fileToUpload = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
const uploadRes = await client.api.teams[':teamId'].files.$post({
param: { teamId },
form: { file: fileToUpload },
})
if (!uploadRes.ok) throw new Error('Failed to upload avatar')
const uploadData = await uploadRes.json()
const key = (uploadData as { key: string }).key
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { imageKey: key },
})
if (!patchRes.ok) throw new Error('Failed to save profile')
toast.success(m.avatar_updated())
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
setIsCropOpen(false)
} catch (err) {
console.error(err)
toast.error(m.failed_update_avatar())
} finally {
setIsUpdatingProfile(false)
}
}
const handleRemoveAvatar = async () => {
setIsUpdatingProfile(true)
try {
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { imageKey: null },
})
if (!patchRes.ok) throw new Error('Failed to remove avatar')
toast.success(m.avatar_removed())
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
} catch (err) {
console.error(err)
toast.error(m.failed_remove_avatar())
} finally {
setIsUpdatingProfile(false)
}
}
const handleUpdateProfile = async () => {
if (!profileName.trim()) return
setIsUpdatingProfile(true)
try {
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { name: profileName.trim() },
})
if (!patchRes.ok) throw new Error('Failed to update name')
toast.success(m.profile_updated())
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
} catch (err) {
console.error(err)
toast.error(m.failed_update_profile())
} finally {
setIsUpdatingProfile(false)
}
}
const { mutate: updateSettings } = useMutation({
mutationFn: async (data: { teamId: string; data: UpdateTeamSettingsRequest }) => {
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId: data.teamId },
json: data.data,
})
if (!res.ok) throw new Error('Failed to update settings')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
},
})
const handleVideoStrategyChange = (value: VideoTranscodeStrategy) => {
updateSettings({
teamId,
data: {
key: 'transcode.videoStrategy',
value: value,
},
})
}
if (isSettingsLoading || isMeLoading) {
return (
<div className="flex h-screen items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
if (settingsError) {
return <div className="p-8 text-center text-red-500">{m.failed_load_settings()}</div>
}
let currentVideoStrategy =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(settings as any)?.transcode?.videoStrategy || VideoTranscodeStrategy.best_match
if (currentVideoStrategy === 'single' || currentVideoStrategy === 'disable') {
currentVideoStrategy = VideoTranscodeStrategy.best_match
} else if (currentVideoStrategy === 'full') {
currentVideoStrategy = VideoTranscodeStrategy.all
}
return (
<div className="h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300">
<div className="flex flex-col md:flex-row h-full">
{/* Sidebar */}
<div className="w-full h-full md:w-72 bg-sidebar border-b md:border-b-0 md:border-r border-sidebar-border z-10 md:left-16 overflow-y-auto transition-colors duration-300">
<nav className="p-4 space-y-1 mt-4">
<div className="mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider">
{m.settings()}
</div>
<button
onClick={() => setActiveTab('general')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'general'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<User className="w-5 h-5" />
{m.general()}
{activeTab === 'general' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
{me?.role === 'owner' && (
<button
onClick={() => setActiveTab('transcode')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'transcode'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Film className="w-5 h-5" />
{m.media_processing()}
{activeTab === 'transcode' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
)}
<button
onClick={() => setActiveTab('notifications')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'notifications'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Bell className="w-5 h-5" />
{m.notifications()}
{activeTab === 'notifications' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('developer')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'developer'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Key className="w-5 h-5" />
{m.api_tokens()}
{activeTab === 'developer' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
{me?.role === 'owner' && (
<>
<div className="mt-6 mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider pt-4 border-t border-sidebar-border">
{m.ai()}
</div>
<button
onClick={() => setActiveTab('providers')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'providers'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Cpu className="w-5 h-5" />
{m.providers()}
{activeTab === 'providers' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('skills')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'skills'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Puzzle className="w-5 h-5" />
{m.skills()}
{activeTab === 'skills' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('agents')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'agents'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Bot className="w-5 h-5" />
{m.agents()}
{activeTab === 'agents' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('sandbox')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'sandbox'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Shield className="w-5 h-5" />
{m.agent_sandbox()}
{activeTab === 'sandbox' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
</>
)}
</nav>
</div>
{/* Main Content Area */}
<main className="flex-1 bg-background/50 h-full flex flex-col transition-colors duration-300 overflow-y-hidden">
<div className="flex-1 flex flex-col max-w-4xl w-full mx-auto p-6 md:p-10 overflow-hidden">
<div className="flex-none flex items-center justify-between mb-6">
<div>
<h2 className="text-2xl font-bold text-foreground">
{activeTab === 'general' && m.general_settings()}
{activeTab === 'transcode' && m.media_processing()}
{activeTab === 'skills' && m.skills_management()}
{activeTab === 'providers' && m.ai_providers()}
{activeTab === 'agents' && m.ai_agents()}
{activeTab === 'sandbox' && m.agent_sandbox_settings()}
{activeTab === 'notifications' && m.notification_settings()}
{activeTab === 'developer' && m.developer_settings()}
</h2>
<p className="text-sm text-muted-foreground mt-1">
{activeTab === 'general' && m.general_settings_description()}
{activeTab === 'transcode' && m.transcode_description()}
{activeTab === 'skills' && m.skills_description()}
{activeTab === 'providers' && m.providers_description()}
{activeTab === 'agents' && m.agents_description()}
{activeTab === 'sandbox' && m.sandbox_description()}
{activeTab === 'notifications' && m.notifications_description()}
{activeTab === 'developer' && m.developer_description()}
</p>
</div>
</div>
<div className="flex-1 overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-500">
{activeTab === 'general' && (
<div className="h-full overflow-y-auto space-y-6 pr-1">
<Card>
<CardHeader>
<CardTitle>{m.personal_info()}</CardTitle>
<CardDescription>{m.personal_info_description()}</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex flex-col md:flex-row gap-8 items-start">
{/* Avatar Column */}
<div className="flex flex-col items-center gap-3">
<span className="text-sm font-medium text-muted-foreground">
{m.avatar()}
</span>
<div
className="group relative cursor-pointer overflow-hidden rounded-full w-24 h-24 border border-border/60 shadow-md transition-all hover:opacity-90"
onClick={() => fileInputRef.current?.click()}
>
<Avatar className="w-24 h-24">
{me?.image && (
<AvatarImage
src={me.image}
alt={me.name}
className="object-cover w-24 h-24"
/>
)}
<AvatarFallback className="text-2xl bg-primary/40 text-foreground">
{getInitials(me?.name)}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<span className="text-white text-xs font-semibold">{m.change()}</span>
</div>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
{m.upload()}
</Button>
{me?.image && (
<Button
variant="ghost"
size="sm"
className="text-red-500 hover:text-red-600"
onClick={handleRemoveAvatar}
>
{m.remove()}
</Button>
)}
</div>
<input
type="file"
ref={fileInputRef}
className="hidden"
accept="image/*"
onChange={handleAvatarFileChange}
/>
</div>
{/* Details Column */}
<div className="flex-1 space-y-4 w-full">
<div className="space-y-2">
<label className="text-sm font-medium text-muted-foreground">
{m.name()}
</label>
<Input
value={profileName}
onChange={(e) => setProfileName(e.target.value)}
placeholder={m.enter_your_name()}
className="max-w-md"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-muted-foreground">
{m.email()}
</label>
<Input
value={me?.email || ''}
disabled
className="max-w-md bg-muted/50 cursor-not-allowed"
/>
<p className="text-xs text-muted-foreground">
{m.email_managed_by_auth()}
</p>
</div>
<Button
onClick={handleUpdateProfile}
disabled={isUpdatingProfile || !profileName.trim()}
className="mt-2"
>
{isUpdatingProfile && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
{m.save_changes()}
</Button>
</div>
</div>
</CardContent>
</Card>
<Card className="border border-slate-200 dark:border-slate-800 mt-6">
<CardHeader>
<CardTitle>{m.language_settings()}</CardTitle>
<CardDescription>{m.select_preferred_language()}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="max-w-xs">
<Select value={currentLocale} onValueChange={handleLanguageChange}>
<SelectTrigger>
<SelectValue placeholder={m.select_language()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="en">{m.english()}</SelectItem>
<SelectItem value="zh">{m.chinese()}</SelectItem>
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
<AvatarCropDialog
isOpen={isCropOpen}
onClose={() => setIsCropOpen(false)}
imageSrc={cropImageSrc}
onConfirm={handleConfirmCrop}
/>
</div>
)}
{activeTab === 'transcode' && (
<div className="h-full overflow-y-auto pr-1">
<Card>
<CardHeader>
<CardTitle>{m.transcode_settings()}</CardTitle>
<CardDescription>
<span className="block mb-2">{m.transcode_description()}</span>
<span className="block">{m.transcode_strategy_note()}</span>
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Video Strategy */}
<div className="space-y-3">
<h3 className="text-lg font-medium">{m.video_strategy()}</h3>
<div className="space-y-3">
<div
className={cn(
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
currentVideoStrategy === VideoTranscodeStrategy.best_match
? 'border-primary bg-primary/5'
: 'border-border',
)}
onClick={() =>
handleVideoStrategyChange(VideoTranscodeStrategy.best_match)
}
>
<div className="font-semibold">{m.best_match()}</div>
<div className="text-sm text-muted-foreground">
{m.best_match_description()}
</div>
</div>
<div
className={cn(
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
currentVideoStrategy === VideoTranscodeStrategy.all
? 'border-primary bg-primary/5'
: 'border-border',
)}
onClick={() => handleVideoStrategyChange(VideoTranscodeStrategy.all)}
>
<div className="font-semibold">{m.all_resolutions()}</div>
<div className="text-sm text-muted-foreground">
{m.all_resolutions_description()}
</div>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
)}
{activeTab === 'skills' && (
<div className="h-full overflow-y-auto pr-1">
<SkillsConfigCard teamId={teamId} />
</div>
)}
{activeTab === 'providers' && <ProvidersSettings teamId={teamId} />}
{activeTab === 'agents' && (
<div className="h-full overflow-y-auto pr-1">
<AgentsSettings teamId={teamId} />
</div>
)}
{activeTab === 'sandbox' && (
<div className="h-full overflow-y-auto pr-1">
<SandboxSettings teamId={teamId} />
</div>
)}
{activeTab === 'notifications' && <NotificationSettings teamId={teamId} />}
{activeTab === 'developer' && <DeveloperSettings teamId={teamId} />}
</div>
</div>
</main>
</div>
</div>
)
}
export const Route = createLazyFileRoute('/teams/$teamId/settings')({
component: TeamSettingsPage,
})
@@ -1,632 +1,3 @@
import { VideoTranscodeStrategy, UpdateTeamSettingsRequest } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { AgentsSettings } from '@/ui/components/settings/AgentsSettings'
import { ProvidersSettings } from '@/ui/components/settings/ProvidersSettings'
import { SandboxSettings } from '@/ui/components/settings/SandboxSettings'
import { SkillsConfigCard } from '@/ui/components/settings/SkillsConfigCard'
import { NotificationSettings } from '@/ui/components/settings/NotificationSettings'
import { DeveloperSettings } from '@/ui/components/settings/DeveloperSettings'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import { Bot, Cpu, Film, Loader2, Puzzle, Shield, User, Bell, Key } from 'lucide-react'
import { useState, useRef, useEffect } from 'react'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { AvatarCropDialog } from '@/ui/components/settings/AvatarCropDialog'
import { toast } from 'sonner'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
import { getLocale, setLocale } from '@/ui/paraglide/runtime.js'
import { m } from '@/ui/paraglide/messages.js'
type SettingsTab =
| 'general'
| 'transcode'
| 'skills'
| 'providers'
| 'agents'
| 'sandbox'
| 'notifications'
| 'developer'
function TeamSettingsPage() {
const { teamId } = Route.useParams()
const queryClient = useQueryClient()
const [activeTab, setActiveTab] = useState<SettingsTab>('general')
const [profileName, setProfileName] = useState('')
const [isCropOpen, setIsCropOpen] = useState(false)
const [cropImageSrc, setCropImageSrc] = useState<string | null>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const [isUpdatingProfile, setIsUpdatingProfile] = useState(false)
const { setMetadata, getMetadata } = useUserMetadataStore()
const currentLocale = getMetadata<string>('locale') || getLocale()
const handleLanguageChange = async (newLocale: string) => {
if (newLocale === 'en' || newLocale === 'zh') {
try {
await setMetadata(teamId, 'locale', newLocale)
setLocale(newLocale)
toast.success(m.language_updated())
} catch (e) {
console.error(e)
toast.error(m.failed_update_language())
}
}
}
const {
data: settings,
isLoading: isSettingsLoading,
error: settingsError,
} = useQuery({
queryKey: ['teams', teamId, 'settings'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].settings.$get({
param: { teamId: teamId },
})
if (!res.ok) throw new Error('Failed to fetch settings')
return await res.json()
},
})
const { data: me, isLoading: isMeLoading } = useQuery({
queryKey: ['teams', teamId, 'me'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].me.$get({
param: { teamId: teamId },
})
if (!res.ok) throw new Error('Failed to fetch me')
return await res.json()
},
enabled: !!teamId,
})
useEffect(() => {
if (me?.name) {
setProfileName(me.name)
}
}, [me])
const getInitials = (name?: string) => {
if (!name) return 'U'
const names = name.split(' ')
if (names.length > 1) {
return `${names[0][0]}${names[names.length - 1][0]}`.toUpperCase()
}
return name.substring(0, 2).toUpperCase()
}
const handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
const reader = new FileReader()
reader.onload = () => {
setCropImageSrc(reader.result as string)
setIsCropOpen(true)
}
reader.readAsDataURL(file)
e.target.value = ''
}
}
const handleConfirmCrop = async (blob: Blob) => {
setIsUpdatingProfile(true)
try {
const fileToUpload = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
const uploadRes = await client.api.teams[':teamId'].files.$post({
param: { teamId },
form: { file: fileToUpload },
})
if (!uploadRes.ok) throw new Error('Failed to upload avatar')
const uploadData = await uploadRes.json()
const key = (uploadData as { key: string }).key
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { imageKey: key },
})
if (!patchRes.ok) throw new Error('Failed to save profile')
toast.success(m.avatar_updated())
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
setIsCropOpen(false)
} catch (err) {
console.error(err)
toast.error(m.failed_update_avatar())
} finally {
setIsUpdatingProfile(false)
}
}
const handleRemoveAvatar = async () => {
setIsUpdatingProfile(true)
try {
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { imageKey: null },
})
if (!patchRes.ok) throw new Error('Failed to remove avatar')
toast.success(m.avatar_removed())
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
} catch (err) {
console.error(err)
toast.error(m.failed_remove_avatar())
} finally {
setIsUpdatingProfile(false)
}
}
const handleUpdateProfile = async () => {
if (!profileName.trim()) return
setIsUpdatingProfile(true)
try {
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { name: profileName.trim() },
})
if (!patchRes.ok) throw new Error('Failed to update name')
toast.success(m.profile_updated())
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
} catch (err) {
console.error(err)
toast.error(m.failed_update_profile())
} finally {
setIsUpdatingProfile(false)
}
}
const { mutate: updateSettings } = useMutation({
mutationFn: async (data: { teamId: string; data: UpdateTeamSettingsRequest }) => {
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId: data.teamId },
json: data.data,
})
if (!res.ok) throw new Error('Failed to update settings')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
},
})
const handleVideoStrategyChange = (value: VideoTranscodeStrategy) => {
updateSettings({
teamId,
data: {
key: 'transcode.videoStrategy',
value: value,
},
})
}
if (isSettingsLoading || isMeLoading) {
return (
<div className="flex h-screen items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
if (settingsError) {
return <div className="p-8 text-center text-red-500">{m.failed_load_settings()}</div>
}
let currentVideoStrategy =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(settings as any)?.transcode?.videoStrategy || VideoTranscodeStrategy.best_match
if (currentVideoStrategy === 'single' || currentVideoStrategy === 'disable') {
currentVideoStrategy = VideoTranscodeStrategy.best_match
} else if (currentVideoStrategy === 'full') {
currentVideoStrategy = VideoTranscodeStrategy.all
}
return (
<div className="h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300">
<div className="flex flex-col md:flex-row h-full">
{/* Sidebar */}
<div className="w-full h-full md:w-72 bg-sidebar border-b md:border-b-0 md:border-r border-sidebar-border z-10 md:left-16 overflow-y-auto transition-colors duration-300">
<nav className="p-4 space-y-1 mt-4">
<div className="mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider">
{m.settings()}
</div>
<button
onClick={() => setActiveTab('general')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'general'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<User className="w-5 h-5" />
{m.general()}
{activeTab === 'general' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
{me?.role === 'owner' && (
<button
onClick={() => setActiveTab('transcode')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'transcode'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Film className="w-5 h-5" />
{m.media_processing()}
{activeTab === 'transcode' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
)}
<button
onClick={() => setActiveTab('notifications')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'notifications'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Bell className="w-5 h-5" />
{m.notifications()}
{activeTab === 'notifications' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('developer')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'developer'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Key className="w-5 h-5" />
{m.api_tokens()}
{activeTab === 'developer' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
{me?.role === 'owner' && (
<>
<div className="mt-6 mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider pt-4 border-t border-sidebar-border">
{m.ai()}
</div>
<button
onClick={() => setActiveTab('providers')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'providers'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Cpu className="w-5 h-5" />
{m.providers()}
{activeTab === 'providers' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('skills')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'skills'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Puzzle className="w-5 h-5" />
{m.skills()}
{activeTab === 'skills' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('agents')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'agents'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Bot className="w-5 h-5" />
{m.agents()}
{activeTab === 'agents' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('sandbox')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'sandbox'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Shield className="w-5 h-5" />
{m.agent_sandbox()}
{activeTab === 'sandbox' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
</>
)}
</nav>
</div>
{/* Main Content Area */}
<main className="flex-1 bg-background/50 h-full flex flex-col transition-colors duration-300 overflow-y-hidden">
<div className="flex-1 flex flex-col max-w-4xl w-full mx-auto p-6 md:p-10 overflow-hidden">
<div className="flex-none flex items-center justify-between mb-6">
<div>
<h2 className="text-2xl font-bold text-foreground">
{activeTab === 'general' && m.general_settings()}
{activeTab === 'transcode' && m.media_processing()}
{activeTab === 'skills' && m.skills_management()}
{activeTab === 'providers' && m.ai_providers()}
{activeTab === 'agents' && m.ai_agents()}
{activeTab === 'sandbox' && m.agent_sandbox_settings()}
{activeTab === 'notifications' && m.notification_settings()}
{activeTab === 'developer' && m.developer_settings()}
</h2>
<p className="text-sm text-muted-foreground mt-1">
{activeTab === 'general' && m.general_settings_description()}
{activeTab === 'transcode' && m.transcode_description()}
{activeTab === 'skills' && m.skills_description()}
{activeTab === 'providers' && m.providers_description()}
{activeTab === 'agents' && m.agents_description()}
{activeTab === 'sandbox' && m.sandbox_description()}
{activeTab === 'notifications' && m.notifications_description()}
{activeTab === 'developer' && m.developer_description()}
</p>
</div>
</div>
<div className="flex-1 overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-500">
{activeTab === 'general' && (
<div className="h-full overflow-y-auto space-y-6 pr-1">
<Card>
<CardHeader>
<CardTitle>{m.personal_info()}</CardTitle>
<CardDescription>{m.personal_info_description()}</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex flex-col md:flex-row gap-8 items-start">
{/* Avatar Column */}
<div className="flex flex-col items-center gap-3">
<span className="text-sm font-medium text-muted-foreground">
{m.avatar()}
</span>
<div
className="group relative cursor-pointer overflow-hidden rounded-full w-24 h-24 border border-border/60 shadow-md transition-all hover:opacity-90"
onClick={() => fileInputRef.current?.click()}
>
<Avatar className="w-24 h-24">
{me?.image && (
<AvatarImage
src={me.image}
alt={me.name}
className="object-cover w-24 h-24"
/>
)}
<AvatarFallback className="text-2xl bg-primary/40 text-foreground">
{getInitials(me?.name)}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<span className="text-white text-xs font-semibold">{m.change()}</span>
</div>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
{m.upload()}
</Button>
{me?.image && (
<Button
variant="ghost"
size="sm"
className="text-red-500 hover:text-red-600"
onClick={handleRemoveAvatar}
>
{m.remove()}
</Button>
)}
</div>
<input
type="file"
ref={fileInputRef}
className="hidden"
accept="image/*"
onChange={handleAvatarFileChange}
/>
</div>
{/* Details Column */}
<div className="flex-1 space-y-4 w-full">
<div className="space-y-2">
<label className="text-sm font-medium text-muted-foreground">
{m.name()}
</label>
<Input
value={profileName}
onChange={(e) => setProfileName(e.target.value)}
placeholder={m.enter_your_name()}
className="max-w-md"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-muted-foreground">
{m.email()}
</label>
<Input
value={me?.email || ''}
disabled
className="max-w-md bg-muted/50 cursor-not-allowed"
/>
<p className="text-xs text-muted-foreground">
{m.email_managed_by_auth()}
</p>
</div>
<Button
onClick={handleUpdateProfile}
disabled={isUpdatingProfile || !profileName.trim()}
className="mt-2"
>
{isUpdatingProfile && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
{m.save_changes()}
</Button>
</div>
</div>
</CardContent>
</Card>
<Card className="border border-slate-200 dark:border-slate-800 mt-6">
<CardHeader>
<CardTitle>{m.language_settings()}</CardTitle>
<CardDescription>{m.select_preferred_language()}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="max-w-xs">
<Select value={currentLocale} onValueChange={handleLanguageChange}>
<SelectTrigger>
<SelectValue placeholder={m.select_language()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="en">{m.english()}</SelectItem>
<SelectItem value="zh">{m.chinese()}</SelectItem>
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
<AvatarCropDialog
isOpen={isCropOpen}
onClose={() => setIsCropOpen(false)}
imageSrc={cropImageSrc}
onConfirm={handleConfirmCrop}
/>
</div>
)}
{activeTab === 'transcode' && (
<div className="h-full overflow-y-auto pr-1">
<Card>
<CardHeader>
<CardTitle>{m.transcode_settings()}</CardTitle>
<CardDescription>
<span className="block mb-2">{m.transcode_description()}</span>
<span className="block">{m.transcode_strategy_note()}</span>
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Video Strategy */}
<div className="space-y-3">
<h3 className="text-lg font-medium">{m.video_strategy()}</h3>
<div className="space-y-3">
<div
className={cn(
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
currentVideoStrategy === VideoTranscodeStrategy.best_match
? 'border-primary bg-primary/5'
: 'border-border',
)}
onClick={() =>
handleVideoStrategyChange(VideoTranscodeStrategy.best_match)
}
>
<div className="font-semibold">{m.best_match()}</div>
<div className="text-sm text-muted-foreground">
{m.best_match_description()}
</div>
</div>
<div
className={cn(
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
currentVideoStrategy === VideoTranscodeStrategy.all
? 'border-primary bg-primary/5'
: 'border-border',
)}
onClick={() => handleVideoStrategyChange(VideoTranscodeStrategy.all)}
>
<div className="font-semibold">{m.all_resolutions()}</div>
<div className="text-sm text-muted-foreground">
{m.all_resolutions_description()}
</div>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
)}
{activeTab === 'skills' && (
<div className="h-full overflow-y-auto pr-1">
<SkillsConfigCard teamId={teamId} />
</div>
)}
{activeTab === 'providers' && <ProvidersSettings teamId={teamId} />}
{activeTab === 'agents' && (
<div className="h-full overflow-y-auto pr-1">
<AgentsSettings teamId={teamId} />
</div>
)}
{activeTab === 'sandbox' && (
<div className="h-full overflow-y-auto pr-1">
<SandboxSettings teamId={teamId} />
</div>
)}
{activeTab === 'notifications' && <NotificationSettings teamId={teamId} />}
{activeTab === 'developer' && <DeveloperSettings teamId={teamId} />}
</div>
</div>
</main>
</div>
</div>
)
}
export const Route = createFileRoute('/teams/$teamId/settings')({
component: TeamSettingsPage,
})
export const Route = createFileRoute('/teams/$teamId/settings')({})