diff --git a/AGENTS.md b/AGENTS.md
index 09532d01..0ac7406e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -197,10 +197,15 @@ The frontend is built with:
- **Prefer System Colors**: Always prefer using semantic system color design tokens (e.g., `bg-background`, `text-foreground`, `text-sidebar-primary`, `text-muted-foreground`, etc.) over hardcoded color utilities (e.g., `bg-blue-50`, `text-emerald-600`, `bg-emerald-500`). This ensures seamless compatibility with light and dark themes.
+### Route Code-Splitting
+
+To optimize initial bundle size, all routes must be code-split into `[route].tsx` (lightweight route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
+
### Development
- **Run Dev**: `bun run dev` (Runs on port 3000)
+
## Testing
We use **Vitest** for testing (via `bun run test`). **Do not use `bun test`** as it uses Bun's native test runner which is not compatible with this project's test suite.
diff --git a/apps/web/src/index.ts b/apps/web/src/index.ts
index b2c23257..12049077 100644
--- a/apps/web/src/index.ts
+++ b/apps/web/src/index.ts
@@ -89,7 +89,13 @@ async function run() {
const mainHtmlHeaders = bundle.files.find((f) => f.path === bundle.index)?.headers || {
'content-type': 'text/html;charset=utf-8',
}
- const serveMainHtml = () => new Response(mainHtmlFile, { headers: mainHtmlHeaders })
+ const raw = await mainHtmlFile.text()
+ const mainHtmlText = raw
+ .replaceAll('href="./', 'href="/')
+ .replaceAll('src="./', 'src="/')
+ .replaceAll('content="./', 'content="/')
+ const serveMainHtml = () => new Response(mainHtmlText, { headers: mainHtmlHeaders })
+
routes['/'] = serveMainHtml
routes['/*'] = serveMainHtml
diff --git a/build.ts b/build.ts
index f5aac79b..b9a7e346 100644
--- a/build.ts
+++ b/build.ts
@@ -19,7 +19,8 @@ await Bun.build({
root: '.',
target: 'bun',
outdir: outdir,
- minify: false,
+ minify: true,
+ splitting: true,
naming: '[name].[ext]',
plugins: [
temporalWorkflow({
@@ -44,5 +45,4 @@ await Bun.build({
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
- publicPath: '/',
})
diff --git a/packages/webui/routeTree.gen.ts b/packages/webui/routeTree.gen.ts
index 74355f8a..c92aded6 100644
--- a/packages/webui/routeTree.gen.ts
+++ b/packages/webui/routeTree.gen.ts
@@ -51,68 +51,78 @@ 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: '/',
getParentRoute: () => ShareShareIdRoute,
-} as any)
+} as any).lazy(() => import('./routes/share/$shareId/index.lazy').then((d) => d.Route))
const ProjectsProjectIdIndexRoute = ProjectsProjectIdIndexRouteImport.update({
id: '/projects/$projectId/',
path: '/projects/$projectId/',
getParentRoute: () => rootRouteImport,
-} as any)
+} as any).lazy(() => import('./routes/projects/$projectId/index.lazy').then((d) => d.Route))
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',
getParentRoute: () => rootRouteImport,
-} as any)
+} as any).lazy(() =>
+ import('./routes/projects/$projectId/recently-deleted.lazy').then((d) => d.Route),
+)
const ProjectsProjectIdSharesIndexRoute = ProjectsProjectIdSharesIndexRouteImport.update({
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',
getParentRoute: () => ShareShareIdRoute,
-} as any)
+} as any).lazy(() => import('./routes/share/$shareId/folders/$folderId.lazy').then((d) => d.Route))
const ShareShareIdFilesFileIdRoute = ShareShareIdFilesFileIdRouteImport.update({
id: '/files/$fileId',
path: '/files/$fileId',
getParentRoute: () => ShareShareIdRoute,
-} as any)
+} as any).lazy(() => import('./routes/share/$shareId/files/$fileId.lazy').then((d) => d.Route))
const ProjectsProjectIdSharesShareIdRoute = ProjectsProjectIdSharesShareIdRouteImport.update({
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',
getParentRoute: () => rootRouteImport,
-} as any)
+} as any).lazy(() =>
+ import('./routes/projects/$projectId/folders/$folderId.lazy').then((d) => d.Route),
+)
const ProjectsProjectIdFilesFileIdRoute = ProjectsProjectIdFilesFileIdRouteImport.update({
id: '/projects/$projectId/files/$fileId',
path: '/projects/$projectId/files/$fileId',
getParentRoute: () => rootRouteImport,
-} as any)
+} as any).lazy(() => import('./routes/projects/$projectId/files/$fileId.lazy').then((d) => d.Route))
const ProjectsProjectIdCollectionsCollectionIdRoute =
ProjectsProjectIdCollectionsCollectionIdRouteImport.update({
id: '/projects/$projectId/collections/$collectionId',
path: '/projects/$projectId/collections/$collectionId',
getParentRoute: () => rootRouteImport,
- } as any)
+ } as any).lazy(() =>
+ import('./routes/projects/$projectId/collections/$collectionId.lazy').then((d) => d.Route),
+ )
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
diff --git a/packages/webui/routes/projects/$projectId/collections/$collectionId.lazy.tsx b/packages/webui/routes/projects/$projectId/collections/$collectionId.lazy.tsx
new file mode 100644
index 00000000..b217604c
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/collections/$collectionId.lazy.tsx
@@ -0,0 +1,75 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+import { useTeamContextStore } from '@/ui/stores/team-context'
+import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { useEffect } from 'react'
+import { client } from '@/ui/api/client'
+import FileSystemManager from '@/ui/components/file-system-manager'
+import { m } from '@/ui/paraglide/messages.js'
+import { projectInfoQueryOptions, collectionInfoQueryOptions } from './$collectionId'
+
+function CollectionPage() {
+ const { projectId, collectionId } = Route.useParams()
+ const { teamId, ensureTeamIdForProject } = useTeamContextStore()
+
+ useEffect(() => {
+ ensureTeamIdForProject(projectId)
+ }, [projectId, ensureTeamIdForProject])
+
+ const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
+
+ const { data: collection, refetch: refetchCollection } = useQuery({
+ ...collectionInfoQueryOptions(collectionId),
+ })
+
+ const { mutate: updateCollection } = useMutation({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ mutationFn: async (updates: { name?: string; filter?: any }) => {
+ const res = await client.api.collections[':collectionId'].$patch({
+ param: { collectionId },
+ json: updates,
+ })
+ if (!res.ok) throw new Error('Failed to update collection')
+ return await res.json()
+ },
+ onSuccess: () => {
+ refetchCollection()
+ },
+ })
+
+ 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 || !collection) {
+ return
{m.loading_collection()}
+ }
+
+ const sourceFolderId = collection.filter.sourceFolderId || rootFolderId
+
+ return (
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/collections/$collectionId')({
+ component: CollectionPage,
+})
diff --git a/packages/webui/routes/projects/$projectId/collections/$collectionId.tsx b/packages/webui/routes/projects/$projectId/collections/$collectionId.tsx
index bbcd0c85..cc7967bb 100644
--- a/packages/webui/routes/projects/$projectId/collections/$collectionId.tsx
+++ b/packages/webui/routes/projects/$projectId/collections/$collectionId.tsx
@@ -1,12 +1,8 @@
import { client } from '@/ui/api/client'
-import FileSystemManager from '@/ui/components/file-system-manager'
-import { useTeamContextStore } from '@/ui/stores/team-context'
-import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
-import { createFileRoute } from '@tanstack/react-router'
-import { useEffect } from 'react'
import { m } from '@/ui/paraglide/messages.js'
+import { createFileRoute } from '@tanstack/react-router'
-const projectInfoQueryOptions = (projectId: string) => ({
+export const projectInfoQueryOptions = (projectId: string) => ({
queryKey: ['projects', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].$get({
@@ -17,7 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
},
})
-const collectionInfoQueryOptions = (collectionId: string) => ({
+export const collectionInfoQueryOptions = (collectionId: string) => ({
queryKey: ['collections', collectionId],
queryFn: async () => {
const res = await client.api.collections[':collectionId'].$get({
@@ -28,71 +24,7 @@ const collectionInfoQueryOptions = (collectionId: string) => ({
},
})
-function CollectionPage() {
- const { projectId, collectionId } = Route.useParams()
- const { teamId, ensureTeamIdForProject } = useTeamContextStore()
-
- useEffect(() => {
- ensureTeamIdForProject(projectId)
- }, [projectId, ensureTeamIdForProject])
-
- const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
-
- const { data: collection, refetch: refetchCollection } = useQuery({
- ...collectionInfoQueryOptions(collectionId),
- })
-
- const { mutate: updateCollection } = useMutation({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- mutationFn: async (updates: { name?: string; filter?: any }) => {
- const res = await client.api.collections[':collectionId'].$patch({
- param: { collectionId },
- json: updates,
- })
- if (!res.ok) throw new Error('Failed to update collection')
- return await res.json()
- },
- onSuccess: () => {
- refetchCollection()
- },
- })
-
- 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 || !collection) {
- return {m.loading_collection()}
- }
-
- const sourceFolderId = collection.filter.sourceFolderId || rootFolderId
-
- return (
-
- )
-}
-
export const Route = createFileRoute('/projects/$projectId/collections/$collectionId')({
- component: CollectionPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => {m.loading_collection()}
,
diff --git a/packages/webui/routes/projects/$projectId/collections/index.lazy.tsx b/packages/webui/routes/projects/$projectId/collections/index.lazy.tsx
new file mode 100644
index 00000000..183e21bf
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/collections/index.lazy.tsx
@@ -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
+ }
+
+ return (
+
+
+ {!isLeftSidebarCollapsed && (
+
setIsLeftSidebarCollapsed(true)}
+ />
+ )}
+
+ {!isLeftSidebarCollapsed && (
+ <>
+
+
+
+
{
+ setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
+ }}
+ className="hidden md:block"
+ />
+ >
+ )}
+
+ {/* Main Content Area */}
+
+
+
+
+ {isCollectionsLoading ? (
+
+ ) : collections.length === 0 ? (
+
+
+
{m.no_collections_yet()}
+
+ ) : (
+
+
+
+
+
+ {m.collection_name()}
+
+ {m.creator()}
+
+ {m.created_date()}
+
+
+
+
+ {collections.map((collection) => (
+
+ navigate({
+ to: '/projects/$projectId/collections/$collectionId',
+ params: { projectId, collectionId: collection.id },
+ })
+ }
+ >
+
+
+
+
+ {collection.name}
+
+
+
+
+
+
+ {collection.creator?.image && (
+
+ )}
+
+ {getInitials(collection.creator?.name)}
+
+
+
+ {collection.creator?.name || m.unknown()}
+
+
+
+
+
+
+ {new Date(collection.createdAt).toLocaleDateString()}
+
+
+
+ ))}
+
+
+
+ {isFetchingNextPage && }
+
+
+ )}
+
+
+
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/collections/')({
+ component: CollectionsPage,
+})
diff --git a/packages/webui/routes/projects/$projectId/collections/index.tsx b/packages/webui/routes/projects/$projectId/collections/index.tsx
index 764282dc..d7ad14d3 100644
--- a/packages/webui/routes/projects/$projectId/collections/index.tsx
+++ b/packages/webui/routes/projects/$projectId/collections/index.tsx
@@ -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
- }
-
- return (
-
-
- {!isLeftSidebarCollapsed && (
-
setIsLeftSidebarCollapsed(true)}
- />
- )}
-
- {!isLeftSidebarCollapsed && (
- <>
-
-
-
-
{
- setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
- }}
- className="hidden md:block"
- />
- >
- )}
-
- {/* Main Content Area */}
-
-
-
-
- {isCollectionsLoading ? (
-
- ) : collections.length === 0 ? (
-
-
-
{m.no_collections_yet()}
-
- ) : (
-
-
-
-
-
- {m.collection_name()}
-
- {m.creator()}
-
- {m.created_date()}
-
-
-
-
- {collections.map((collection) => (
-
- navigate({
- to: '/projects/$projectId/collections/$collectionId',
- params: { projectId, collectionId: collection.id },
- })
- }
- >
-
-
-
-
- {collection.name}
-
-
-
-
-
-
- {collection.creator?.image && (
-
- )}
-
- {getInitials(collection.creator?.name)}
-
-
-
- {collection.creator?.name || m.unknown()}
-
-
-
-
-
-
- {new Date(collection.createdAt).toLocaleDateString()}
-
-
-
- ))}
-
-
-
- {isFetchingNextPage && }
-
-
- )}
-
-
-
-
- )
-}
-
export const Route = createFileRoute('/projects/$projectId/collections/')({
- component: CollectionsPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () =>
,
diff --git a/packages/webui/routes/projects/$projectId/files/$fileId.lazy.tsx b/packages/webui/routes/projects/$projectId/files/$fileId.lazy.tsx
new file mode 100644
index 00000000..192528e2
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/files/$fileId.lazy.tsx
@@ -0,0 +1,464 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+import { client } from '@/ui/api/client'
+import { FileViewer } from '@/ui/components/file-viewer'
+import { CompareViewer } from '@/ui/components/compare/compare-viewer'
+import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
+import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
+import { m } from '@/ui/paraglide/messages.js'
+import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
+import { ResizeHandle } from '@/ui/components/resize-handle'
+import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
+import { useMemberStore } from '@/ui/stores/members'
+import { useTeamContextStore } from '@/ui/stores/team-context'
+import { useTopNavStore } from '@/ui/stores/top-nav'
+import { type Annotation } from '@/ui/types'
+import { useMutation } from '@tanstack/react-query'
+import { InferRequestType, InferResponseType } from 'hono/client'
+
+import type { AssetInfo, AssetInfoPaginatedList, CommentInfo } from '@shumai/dtos'
+import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useNavigate } from '@tanstack/react-router'
+import { Loader2 } from 'lucide-react'
+import { useEffect, useRef, useState } from 'react'
+import type { MediaController } from '@/ui/components/viewers/types'
+
+function FileViewPage() {
+ const { projectId, fileId } = Route.useParams()
+ const search = Route.useSearch()
+ const versionAssetId = search.version
+ const startTime = search.start
+ const activeFileId = versionAssetId || fileId
+ const compareLeftId = search.cmpLeft
+ const compareRightId = search.cmpRight
+ const compareActiveSide = search.cmpActive ?? 'left'
+ const isCompareMode = !!search.compare && !!compareLeftId && !!compareRightId
+
+ const mediaControllerRef = useRef
(null)
+ const { teamId, ensureTeamIdForProject } = useTeamContextStore()
+ const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
+ const [annotations, setAnnotations] = useState([])
+ const [currentTime, setCurrentTime] = useState(0)
+ const [selectedCommentId, setSelectedCommentId] = useState(null)
+ const [compareActiveAsset, setCompareActiveAsset] = useState(null)
+ const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
+ undefined,
+ )
+ const [carouselState, setCarouselState] = useState<{
+ show: boolean
+ files: AssetInfo[]
+ nextCursor?: string
+ folderId?: string
+ }>({ show: false, files: [], nextCursor: undefined, folderId: undefined })
+ const $patchMetadata = client.api.files[':fileId'].metadata.$patch
+ const { mutate: patchMetadata } = useMutation<
+ InferResponseType,
+ Error,
+ InferRequestType
+ >({
+ mutationFn: async (request) => {
+ const res = await $patchMetadata(request)
+ if (!res.ok) throw new Error('Failed to patch metadata')
+ return (await res.json()) as unknown as InferResponseType
+ },
+ })
+ const queryClient = useQueryClient()
+ const { members, fetchMembers } = useMemberStore()
+
+ useEffect(() => {
+ ensureTeamIdForProject(projectId)
+ }, [projectId, ensureTeamIdForProject])
+
+ useEffect(() => {
+ if (teamId) {
+ fetchMembers(teamId, true)
+ }
+ }, [teamId, fetchMembers])
+
+ const {
+ data: stackData,
+ isLoading: isStackLoading,
+ isError: isStackError,
+ isFetching: isStackFetching,
+ } = useQuery({
+ queryKey: ['files', fileId],
+ queryFn: async () => {
+ const res = await client.api.files[':fileId'].$get({
+ param: { fileId: fileId },
+ })
+ if (!res.ok) throw new Error('Failed to fetch stack')
+ return await res.json()
+ },
+ enabled: !!teamId,
+ placeholderData: keepPreviousData,
+ })
+
+ const {
+ data: versionData,
+ isLoading: isVersionLoading,
+ isError: isVersionError,
+ isFetching: isVersionFetching,
+ } = useQuery({
+ queryKey: ['files', versionAssetId],
+ queryFn: async () => {
+ const res = await client.api.files[':fileId'].$get({
+ param: { fileId: versionAssetId! },
+ })
+ if (!res.ok) throw new Error('Failed to fetch version')
+ return await res.json()
+ },
+ enabled: !!teamId && !!versionAssetId,
+ placeholderData: keepPreviousData,
+ })
+
+ const { data: versionsList } = useQuery({
+ queryKey: ['version_stacks', fileId, 'versions'],
+ queryFn: async () => {
+ const res = await client.api.version_stacks[':stackId'].versions.$get({
+ param: { stackId: fileId },
+ })
+ if (!res.ok) throw new Error('Failed to fetch versions')
+ return await res.json()
+ },
+ enabled: !!projectId && !!fileId && (!!versionAssetId || isCompareMode),
+ })
+
+ const { data: projectInfo } = useQuery({
+ queryKey: ['projects', projectId],
+ queryFn: async () => {
+ const res = await client.api.projects[':projectId'].$get({
+ param: { projectId: projectId },
+ })
+ if (!res.ok) throw new Error('Failed to fetch project')
+ return await res.json()
+ },
+ })
+
+ const navigate = useNavigate()
+ const { setProjectState, clearProjectState } = useTopNavStore()
+
+ const isLoading = isStackLoading || (!!versionAssetId && isVersionLoading)
+ const isError = isStackError || (!!versionAssetId && isVersionError)
+ const isFetching = isStackFetching || (!!versionAssetId && isVersionFetching)
+ const fileData = versionData || stackData
+ const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions
+
+ useEffect(() => {
+ if (fileData && projectInfo && teamId) {
+ setProjectState({
+ teamId,
+ projectId,
+ projectName: projectInfo.name ?? '',
+ ancestorFolders: fileData.ancestorFolders ?? [],
+ currentAsset: {
+ name: fileData.name,
+ type: 'file',
+ version: versionsDataList
+ ? (versionsDataList.find((v: { id: string }) => v.id === activeFileId)?.version ??
+ versionsDataList.length)
+ : undefined,
+ mediaType: fileData.mediaType,
+ },
+ isRootFolder: false,
+ fileId,
+ downloadInfo: {
+ originalKey: fileData.media?.original?.key,
+ videoTranscodes: fileData.media?.videoTranscodes?.map((t) => ({
+ key: t.key,
+ width: t.width,
+ height: t.height,
+ isRaw: t.isRaw,
+ })),
+ },
+ versions: versionsDataList,
+ compareMode: isCompareMode,
+ canCompareVersions: (versionsDataList?.length ?? 0) >= 2,
+ onCompareVersions: () => {
+ const pair = pickDefaultCompareVersions(versionsDataList)
+ if (!pair) return
+ navigate({
+ to: '/projects/$projectId/files/$fileId',
+ params: { projectId, fileId },
+ search: (p: Record) => ({
+ ...p,
+ version: undefined,
+ compare: true,
+ cmpLeft: pair.left.id,
+ cmpRight: pair.right.id,
+ cmpActive: 'left' as const,
+ }),
+ })
+ },
+ onFolderClick: (id: string) => {
+ navigate({
+ to: '/projects/$projectId/folders/$folderId',
+ params: { projectId, folderId: id },
+ })
+ },
+ })
+ }
+
+ return () => clearProjectState()
+ }, [
+ teamId,
+ projectId,
+ projectInfo,
+ fileData,
+ versionsDataList,
+ activeFileId,
+ fileId,
+ isCompareMode,
+ setProjectState,
+ clearProjectState,
+ navigate,
+ ])
+
+ const parentFolderId = fileData?.ancestorFolders?.[0]?.id ?? projectInfo?.rootFolder ?? ''
+
+ useEffect(() => {
+ if (!parentFolderId || !activeFileId) return
+ if (carouselState.folderId === parentFolderId) {
+ return
+ }
+
+ let isMounted = true
+
+ const fetchCarouselData = async () => {
+ try {
+ let cursor = ''
+ let found = false
+ const allFiles: AssetInfo[] = []
+ let lastCursor: string | undefined = undefined
+
+ for (let batch = 0; batch < 5; batch++) {
+ const res = await client.api.folders[':folderId'].search.$post({
+ param: { folderId: parentFolderId },
+ json: {
+ assetType: 'file',
+ after: cursor,
+ first: 200,
+ recursively: false,
+ conditions: [],
+ },
+ })
+ if (!res.ok) {
+ throw new Error('Failed to search parent folder for carousel')
+ }
+ const result = (await res.json()) as unknown as AssetInfoPaginatedList
+ const batchFiles = (result.data || []) as AssetInfo[]
+ allFiles.push(...batchFiles)
+
+ if (batchFiles.some((f) => f.id === activeFileId)) {
+ found = true
+ lastCursor = result.pageInfo?.cursor || undefined
+ break
+ }
+ if (!result.pageInfo?.cursor || batchFiles.length < 200) {
+ break
+ }
+ cursor = result.pageInfo.cursor
+ }
+
+ if (isMounted) {
+ if (found) {
+ setCarouselState({
+ show: true,
+ files: allFiles,
+ nextCursor: lastCursor,
+ folderId: parentFolderId,
+ })
+ } else {
+ setCarouselState({
+ show: false,
+ files: [],
+ nextCursor: undefined,
+ folderId: parentFolderId,
+ })
+ }
+ }
+ } catch (err) {
+ console.error(err)
+ if (isMounted) {
+ setCarouselState({
+ show: false,
+ files: [],
+ nextCursor: undefined,
+ folderId: parentFolderId,
+ })
+ }
+ }
+ }
+
+ fetchCarouselData()
+
+ return () => {
+ isMounted = false
+ }
+ }, [parentFolderId, activeFileId, carouselState.folderId])
+
+ useEffect(() => {
+ setCurrentTime(0)
+ setSelectedCommentId(null)
+ setAnnotations([])
+ }, [fileData?.id])
+
+ useEffect(() => {
+ setSelectedCommentId(null)
+ setAnnotations([])
+ }, [compareActiveAsset?.id])
+
+ if (isLoading && !fileData) {
+ return
+ }
+
+ if (isError || !fileData || !projectInfo || !teamId) {
+ return {m.file_not_found()}
+ }
+
+ const sidebarFile = isCompareMode ? compareActiveAsset : (fileData as unknown as AssetInfo)
+ const sidebarFileId = sidebarFile?.id ?? activeFileId
+
+ const handleSaveField = (fieldId: string, value: unknown) => {
+ if (!teamId) return
+ patchMetadata(
+ {
+ param: { fileId: sidebarFileId },
+ json: [{ key: fieldId, value }] as InferRequestType['json'],
+ },
+ {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: ['files', sidebarFileId],
+ })
+ },
+ },
+ )
+ }
+
+ const updateCompareSearch = (patch: Record) => {
+ navigate({
+ to: '/projects/$projectId/files/$fileId',
+ params: { projectId, fileId },
+ search: (p: Record) => ({ ...p, ...patch }),
+ })
+ }
+
+ const handleCompareExit = () => {
+ const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
+ updateCompareSearch({
+ compare: undefined,
+ cmpLeft: undefined,
+ cmpRight: undefined,
+ cmpActive: undefined,
+ version: activeId,
+ })
+ }
+
+ const handleCommentSelect = (comment: CommentInfo) => {
+ setSelectedCommentId(comment.id || null)
+ const newAnnotations = comment.annotations as Annotation[]
+ if (newAnnotations && newAnnotations.length > 0) {
+ setAnnotations(newAnnotations)
+ } else {
+ setAnnotations([])
+ }
+
+ if (isCompareMode) {
+ if (comment.second !== null && comment.second !== undefined) {
+ setSeekRequest({ second: comment.second, nonce: Date.now() })
+ }
+ return
+ }
+
+ if (comment.second !== null && comment.second !== undefined) {
+ mediaControllerRef.current?.seekTo(comment.second)
+ mediaControllerRef.current?.pause()
+ } else if (newAnnotations && newAnnotations.length > 0) {
+ mediaControllerRef.current?.pause()
+ }
+ }
+
+ const handlePlay = () => {
+ setAnnotations([])
+ setSelectedCommentId(null)
+ }
+
+ return (
+
+
+
+ {isFetching && !isCompareMode && (
+
+
+
+ )}
+ {isCompareMode && compareLeftId && compareRightId ? (
+
updateCompareSearch({ cmpActive: side })}
+ onSwitchVersion={(side, versionId) =>
+ updateCompareSearch(
+ side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
+ )
+ }
+ onExit={handleCompareExit}
+ onActiveAssetChange={setCompareActiveAsset}
+ onPlay={handlePlay}
+ onTimeUpdate={setCurrentTime}
+ />
+ ) : (
+
+ {carouselState.show && (
+
+ )}
+
+ )}
+
+
{
+ setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
+ }}
+ className="hidden md:block"
+ />
+
+ {
+ if (isCompareMode) return
+ mediaControllerRef.current?.pause()
+ }}
+ selectedCommentId={selectedCommentId}
+ hideAnnotationControl={sidebarFile?.mediaType?.startsWith('audio/')}
+ />
+
+
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/files/$fileId')({
+ component: FileViewPage,
+})
diff --git a/packages/webui/routes/projects/$projectId/files/$fileId.tsx b/packages/webui/routes/projects/$projectId/files/$fileId.tsx
index 74515efa..c7cdb4ba 100644
--- a/packages/webui/routes/projects/$projectId/files/$fileId.tsx
+++ b/packages/webui/routes/projects/$projectId/files/$fileId.tsx
@@ -1,465 +1,6 @@
-import { client } from '@/ui/api/client'
-import { FileViewer } from '@/ui/components/file-viewer'
-import { CompareViewer } from '@/ui/components/compare/compare-viewer'
-import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
-import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
-import { m } from '@/ui/paraglide/messages.js'
-import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
-import { ResizeHandle } from '@/ui/components/resize-handle'
-import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
-import { useMemberStore } from '@/ui/stores/members'
-import { useTeamContextStore } from '@/ui/stores/team-context'
-import { useTopNavStore } from '@/ui/stores/top-nav'
-import { type Annotation } from '@/ui/types'
-import { useMutation } from '@tanstack/react-query'
-import { InferRequestType, InferResponseType } from 'hono/client'
-
-import type { AssetInfo, AssetInfoPaginatedList, CommentInfo } from '@shumai/dtos'
-import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
-import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import { Loader2 } from 'lucide-react'
-import { useEffect, useRef, useState } from 'react'
-import type { MediaController } from '@/ui/components/viewers/types'
-
-function FileViewPage() {
- const { projectId, fileId } = Route.useParams()
- const search = Route.useSearch()
- const versionAssetId = search.version
- const startTime = search.start
- const activeFileId = versionAssetId || fileId
- const compareLeftId = search.cmpLeft
- const compareRightId = search.cmpRight
- const compareActiveSide = search.cmpActive ?? 'left'
- const isCompareMode = !!search.compare && !!compareLeftId && !!compareRightId
-
- const mediaControllerRef = useRef(null)
- const { teamId, ensureTeamIdForProject } = useTeamContextStore()
- const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
- const [annotations, setAnnotations] = useState([])
- const [currentTime, setCurrentTime] = useState(0)
- const [selectedCommentId, setSelectedCommentId] = useState(null)
- const [compareActiveAsset, setCompareActiveAsset] = useState(null)
- const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
- undefined,
- )
- const [carouselState, setCarouselState] = useState<{
- show: boolean
- files: AssetInfo[]
- nextCursor?: string
- folderId?: string
- }>({ show: false, files: [], nextCursor: undefined, folderId: undefined })
- const $patchMetadata = client.api.files[':fileId'].metadata.$patch
- const { mutate: patchMetadata } = useMutation<
- InferResponseType,
- Error,
- InferRequestType
- >({
- mutationFn: async (request) => {
- const res = await $patchMetadata(request)
- if (!res.ok) throw new Error('Failed to patch metadata')
- return (await res.json()) as unknown as InferResponseType
- },
- })
- const queryClient = useQueryClient()
- const { members, fetchMembers } = useMemberStore()
-
- useEffect(() => {
- ensureTeamIdForProject(projectId)
- }, [projectId, ensureTeamIdForProject])
-
- useEffect(() => {
- if (teamId) {
- fetchMembers(teamId, true)
- }
- }, [teamId, fetchMembers])
-
- const {
- data: stackData,
- isLoading: isStackLoading,
- isError: isStackError,
- isFetching: isStackFetching,
- } = useQuery({
- queryKey: ['files', fileId],
- queryFn: async () => {
- const res = await client.api.files[':fileId'].$get({
- param: { fileId: fileId },
- })
- if (!res.ok) throw new Error('Failed to fetch stack')
- return await res.json()
- },
- enabled: !!teamId,
- placeholderData: keepPreviousData,
- })
-
- const {
- data: versionData,
- isLoading: isVersionLoading,
- isError: isVersionError,
- isFetching: isVersionFetching,
- } = useQuery({
- queryKey: ['files', versionAssetId],
- queryFn: async () => {
- const res = await client.api.files[':fileId'].$get({
- param: { fileId: versionAssetId! },
- })
- if (!res.ok) throw new Error('Failed to fetch version')
- return await res.json()
- },
- enabled: !!teamId && !!versionAssetId,
- placeholderData: keepPreviousData,
- })
-
- const { data: versionsList } = useQuery({
- queryKey: ['version_stacks', fileId, 'versions'],
- queryFn: async () => {
- const res = await client.api.version_stacks[':stackId'].versions.$get({
- param: { stackId: fileId },
- })
- if (!res.ok) throw new Error('Failed to fetch versions')
- return await res.json()
- },
- enabled: !!projectId && !!fileId && (!!versionAssetId || isCompareMode),
- })
-
- const { data: projectInfo } = useQuery({
- queryKey: ['projects', projectId],
- queryFn: async () => {
- const res = await client.api.projects[':projectId'].$get({
- param: { projectId: projectId },
- })
- if (!res.ok) throw new Error('Failed to fetch project')
- return await res.json()
- },
- })
-
- const navigate = useNavigate()
- const { setProjectState, clearProjectState } = useTopNavStore()
-
- const isLoading = isStackLoading || (!!versionAssetId && isVersionLoading)
- const isError = isStackError || (!!versionAssetId && isVersionError)
- const isFetching = isStackFetching || (!!versionAssetId && isVersionFetching)
- const fileData = versionData || stackData
- const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions
-
- useEffect(() => {
- if (fileData && projectInfo && teamId) {
- setProjectState({
- teamId,
- projectId,
- projectName: projectInfo.name ?? '',
- ancestorFolders: fileData.ancestorFolders ?? [],
- currentAsset: {
- name: fileData.name,
- type: 'file',
- version: versionsDataList
- ? (versionsDataList.find((v: { id: string }) => v.id === activeFileId)?.version ??
- versionsDataList.length)
- : undefined,
- mediaType: fileData.mediaType,
- },
- isRootFolder: false,
- fileId,
- downloadInfo: {
- originalKey: fileData.media?.original?.key,
- videoTranscodes: fileData.media?.videoTranscodes?.map((t) => ({
- key: t.key,
- width: t.width,
- height: t.height,
- isRaw: t.isRaw,
- })),
- },
- versions: versionsDataList,
- compareMode: isCompareMode,
- canCompareVersions: (versionsDataList?.length ?? 0) >= 2,
- onCompareVersions: () => {
- const pair = pickDefaultCompareVersions(versionsDataList)
- if (!pair) return
- navigate({
- to: '/projects/$projectId/files/$fileId',
- params: { projectId, fileId },
- search: (p: Record) => ({
- ...p,
- version: undefined,
- compare: true,
- cmpLeft: pair.left.id,
- cmpRight: pair.right.id,
- cmpActive: 'left' as const,
- }),
- })
- },
- onFolderClick: (id: string) => {
- navigate({
- to: '/projects/$projectId/folders/$folderId',
- params: { projectId, folderId: id },
- })
- },
- })
- }
-
- return () => clearProjectState()
- }, [
- teamId,
- projectId,
- projectInfo,
- fileData,
- versionsDataList,
- activeFileId,
- fileId,
- isCompareMode,
- setProjectState,
- clearProjectState,
- navigate,
- ])
-
- const parentFolderId = fileData?.ancestorFolders?.[0]?.id ?? projectInfo?.rootFolder ?? ''
-
- useEffect(() => {
- if (!parentFolderId || !activeFileId) return
- if (carouselState.folderId === parentFolderId) {
- return
- }
-
- let isMounted = true
-
- const fetchCarouselData = async () => {
- try {
- let cursor = ''
- let found = false
- const allFiles: AssetInfo[] = []
- let lastCursor: string | undefined = undefined
-
- for (let batch = 0; batch < 5; batch++) {
- const res = await client.api.folders[':folderId'].search.$post({
- param: { folderId: parentFolderId },
- json: {
- assetType: 'file',
- after: cursor,
- first: 200,
- recursively: false,
- conditions: [],
- },
- })
- if (!res.ok) {
- throw new Error('Failed to search parent folder for carousel')
- }
- const result = (await res.json()) as unknown as AssetInfoPaginatedList
- const batchFiles = (result.data || []) as AssetInfo[]
- allFiles.push(...batchFiles)
-
- if (batchFiles.some((f) => f.id === activeFileId)) {
- found = true
- lastCursor = result.pageInfo?.cursor || undefined
- break
- }
- if (!result.pageInfo?.cursor || batchFiles.length < 200) {
- break
- }
- cursor = result.pageInfo.cursor
- }
-
- if (isMounted) {
- if (found) {
- setCarouselState({
- show: true,
- files: allFiles,
- nextCursor: lastCursor,
- folderId: parentFolderId,
- })
- } else {
- setCarouselState({
- show: false,
- files: [],
- nextCursor: undefined,
- folderId: parentFolderId,
- })
- }
- }
- } catch (err) {
- console.error(err)
- if (isMounted) {
- setCarouselState({
- show: false,
- files: [],
- nextCursor: undefined,
- folderId: parentFolderId,
- })
- }
- }
- }
-
- fetchCarouselData()
-
- return () => {
- isMounted = false
- }
- }, [parentFolderId, activeFileId, carouselState.folderId])
-
- useEffect(() => {
- setCurrentTime(0)
- setSelectedCommentId(null)
- setAnnotations([])
- }, [fileData?.id])
-
- useEffect(() => {
- setSelectedCommentId(null)
- setAnnotations([])
- }, [compareActiveAsset?.id])
-
- if (isLoading && !fileData) {
- return
- }
-
- if (isError || !fileData || !projectInfo || !teamId) {
- return {m.file_not_found()}
- }
-
- const sidebarFile = isCompareMode ? compareActiveAsset : (fileData as unknown as AssetInfo)
- const sidebarFileId = sidebarFile?.id ?? activeFileId
-
- const handleSaveField = (fieldId: string, value: unknown) => {
- if (!teamId) return
- patchMetadata(
- {
- param: { fileId: sidebarFileId },
- json: [{ key: fieldId, value }] as InferRequestType['json'],
- },
- {
- onSuccess: () => {
- queryClient.invalidateQueries({
- queryKey: ['files', sidebarFileId],
- })
- },
- },
- )
- }
-
- const updateCompareSearch = (patch: Record) => {
- navigate({
- to: '/projects/$projectId/files/$fileId',
- params: { projectId, fileId },
- search: (p: Record) => ({ ...p, ...patch }),
- })
- }
-
- const handleCompareExit = () => {
- const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
- updateCompareSearch({
- compare: undefined,
- cmpLeft: undefined,
- cmpRight: undefined,
- cmpActive: undefined,
- version: activeId,
- })
- }
-
- const handleCommentSelect = (comment: CommentInfo) => {
- setSelectedCommentId(comment.id || null)
- const newAnnotations = comment.annotations as Annotation[]
- if (newAnnotations && newAnnotations.length > 0) {
- setAnnotations(newAnnotations)
- } else {
- setAnnotations([])
- }
-
- if (isCompareMode) {
- if (comment.second !== null && comment.second !== undefined) {
- setSeekRequest({ second: comment.second, nonce: Date.now() })
- }
- return
- }
-
- if (comment.second !== null && comment.second !== undefined) {
- mediaControllerRef.current?.seekTo(comment.second)
- mediaControllerRef.current?.pause()
- } else if (newAnnotations && newAnnotations.length > 0) {
- mediaControllerRef.current?.pause()
- }
- }
-
- const handlePlay = () => {
- setAnnotations([])
- setSelectedCommentId(null)
- }
-
- return (
-
-
-
- {isFetching && !isCompareMode && (
-
-
-
- )}
- {isCompareMode && compareLeftId && compareRightId ? (
-
updateCompareSearch({ cmpActive: side })}
- onSwitchVersion={(side, versionId) =>
- updateCompareSearch(
- side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
- )
- }
- onExit={handleCompareExit}
- onActiveAssetChange={setCompareActiveAsset}
- onPlay={handlePlay}
- onTimeUpdate={setCurrentTime}
- />
- ) : (
-
- {carouselState.show && (
-
- )}
-
- )}
-
-
{
- setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
- }}
- className="hidden md:block"
- />
-
- {
- if (isCompareMode) return
- mediaControllerRef.current?.pause()
- }}
- selectedCommentId={selectedCommentId}
- hideAnnotationControl={sidebarFile?.mediaType?.startsWith('audio/')}
- />
-
-
-
- )
-}
+import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/projects/$projectId/files/$fileId')({
- component: FileViewPage,
validateSearch: (search: Record) => {
return {
version: (search.version as string) || undefined,
diff --git a/packages/webui/routes/projects/$projectId/folders/$folderId.lazy.tsx b/packages/webui/routes/projects/$projectId/folders/$folderId.lazy.tsx
new file mode 100644
index 00000000..bddbba4e
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/folders/$folderId.lazy.tsx
@@ -0,0 +1,51 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+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 FileSystemManager from '@/ui/components/file-system-manager'
+import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
+import { projectInfoQueryOptions } from './$folderId'
+
+function FolderPage() {
+ const { projectId, folderId } = 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! },
+ })
+ return await res.json()
+ })(),
+ enabled: !!rootFolderId,
+ })
+
+ if (!teamId || !rootFolderId || !rootFolder) {
+ return
+ }
+
+ return (
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/folders/$folderId')({
+ component: FolderPage,
+})
diff --git a/packages/webui/routes/projects/$projectId/folders/$folderId.tsx b/packages/webui/routes/projects/$projectId/folders/$folderId.tsx
index f3ed6d16..da2debee 100644
--- a/packages/webui/routes/projects/$projectId/folders/$folderId.tsx
+++ b/packages/webui/routes/projects/$projectId/folders/$folderId.tsx
@@ -1,12 +1,8 @@
import { client } from '@/ui/api/client'
-import FileSystemManager from '@/ui/components/file-system-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 FolderPage() {
- const { projectId, folderId } = 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! },
- })
- return await res.json()
- })(),
- enabled: !!rootFolderId,
- })
-
- if (!teamId || !rootFolderId || !rootFolder) {
- return
- }
-
- return (
-
- )
-}
-
export const Route = createFileRoute('/projects/$projectId/folders/$folderId')({
- component: FolderPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => ,
diff --git a/packages/webui/routes/projects/$projectId/index.lazy.tsx b/packages/webui/routes/projects/$projectId/index.lazy.tsx
new file mode 100644
index 00000000..077dea1d
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/index.lazy.tsx
@@ -0,0 +1,51 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+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 FileSystemManager from '@/ui/components/file-system-manager'
+import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
+import { projectInfoQueryOptions } from './index'
+
+function ProjectPage() {
+ const { projectId } = 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
+ }
+
+ return (
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/')({
+ component: ProjectPage,
+})
diff --git a/packages/webui/routes/projects/$projectId/index.tsx b/packages/webui/routes/projects/$projectId/index.tsx
index 85753960..46d553a5 100644
--- a/packages/webui/routes/projects/$projectId/index.tsx
+++ b/packages/webui/routes/projects/$projectId/index.tsx
@@ -1,12 +1,8 @@
import { client } from '@/ui/api/client'
-import FileSystemManager from '@/ui/components/file-system-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 ProjectPage() {
- const { projectId } = 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
- }
-
- return (
-
- )
-}
-
export const Route = createFileRoute('/projects/$projectId/')({
- component: ProjectPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => ,
diff --git a/packages/webui/routes/projects/$projectId/recently-deleted.lazy.tsx b/packages/webui/routes/projects/$projectId/recently-deleted.lazy.tsx
new file mode 100644
index 00000000..612c5a2d
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/recently-deleted.lazy.tsx
@@ -0,0 +1,51 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+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 FileSystemManager from '@/ui/components/file-system-manager'
+import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
+import { projectInfoQueryOptions } from './recently-deleted'
+
+function RecentlyDeletedPage() {
+ const { projectId } = 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! },
+ })
+ return await res.json()
+ })(),
+ enabled: !!rootFolderId,
+ })
+
+ if (!teamId || !rootFolderId || !rootFolder) {
+ return
+ }
+
+ return (
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/recently-deleted')({
+ component: RecentlyDeletedPage,
+})
diff --git a/packages/webui/routes/projects/$projectId/recently-deleted.tsx b/packages/webui/routes/projects/$projectId/recently-deleted.tsx
index fc00fd08..a0c7999d 100644
--- a/packages/webui/routes/projects/$projectId/recently-deleted.tsx
+++ b/packages/webui/routes/projects/$projectId/recently-deleted.tsx
@@ -1,12 +1,8 @@
import { client } from '@/ui/api/client'
-import FileSystemManager from '@/ui/components/file-system-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 RecentlyDeletedPage() {
- const { projectId } = 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! },
- })
- return await res.json()
- })(),
- enabled: !!rootFolderId,
- })
-
- if (!teamId || !rootFolderId || !rootFolder) {
- return
- }
-
- return (
-
- )
-}
-
export const Route = createFileRoute('/projects/$projectId/recently-deleted')({
- component: RecentlyDeletedPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => ,
diff --git a/packages/webui/routes/projects/$projectId/shares/$shareId.lazy.tsx b/packages/webui/routes/projects/$projectId/shares/$shareId.lazy.tsx
new file mode 100644
index 00000000..4f715153
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/shares/$shareId.lazy.tsx
@@ -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
+ }
+
+ return (
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/shares/$shareId')({
+ component: SharePage,
+})
diff --git a/packages/webui/routes/projects/$projectId/shares/$shareId.tsx b/packages/webui/routes/projects/$projectId/shares/$shareId.tsx
index 2f255dbd..88138222 100644
--- a/packages/webui/routes/projects/$projectId/shares/$shareId.tsx
+++ b/packages/webui/routes/projects/$projectId/shares/$shareId.tsx
@@ -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
- }
-
- return (
-
- )
-}
-
export const Route = createFileRoute('/projects/$projectId/shares/$shareId')({
- component: SharePage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => ,
diff --git a/packages/webui/routes/projects/$projectId/shares/index.lazy.tsx b/packages/webui/routes/projects/$projectId/shares/index.lazy.tsx
new file mode 100644
index 00000000..6f79c7da
--- /dev/null
+++ b/packages/webui/routes/projects/$projectId/shares/index.lazy.tsx
@@ -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
+ }
+
+ const handleCopyLink = (shareId: string) => {
+ const url = `${window.location.origin}/share/${shareId}`
+ navigator.clipboard.writeText(url)
+ toast.success(m.link_copied())
+ }
+
+ return (
+
+
+ {!isLeftSidebarCollapsed && (
+
setIsLeftSidebarCollapsed(true)}
+ />
+ )}
+
+ {!isLeftSidebarCollapsed && (
+ <>
+
+
+
+
{
+ setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
+ }}
+ className="hidden md:block"
+ />
+ >
+ )}
+
+ {/* Main Content Area */}
+
+
+
+
+ {isSharesLoading ? (
+
+ ) : shares.length === 0 ? (
+
+
+
{m.no_share_links_yet()}
+
+ ) : (
+
+
+
+
+ {m.name()}
+ {m.public_link()}
+ {m.creator()}
+
+ {m.created_date()}
+
+
+ {m.active()}
+
+
+
+
+ {shares.map((share) => {
+ const shareUrl = `${window.location.origin}/share/${share.id}`
+ return (
+
+
+
+ navigate({
+ to: '/projects/$projectId/shares/$shareId',
+ params: { projectId, shareId: share.id },
+ })
+ }
+ >
+ {share.name}
+
+
+
+
+
handleCopyLink(share.id)}
+ title={m.click_to_copy_link()}
+ >
+ {shareUrl}
+
+
+
+
+
+
+
+
+
+
+ {share.creator?.image && (
+
+ )}
+
+ {getInitials(share.creator?.name)}
+
+
+
+ {share.creator?.name || m.unknown()}
+
+
+
+
+
+
+ {new Date(share.createdAt).toLocaleDateString()}
+
+
+
+
+
+ toggleVisibility({ id: share.id, isDisabled: !checked })
+ }
+ />
+
+
+
+ )
+ })}
+
+
+
+ {isFetchingNextPage && }
+
+
+ )}
+
+
+
+
+ )
+}
+
+export const Route = createLazyFileRoute('/projects/$projectId/shares/')({
+ component: SharesPage,
+})
diff --git a/packages/webui/routes/projects/$projectId/shares/index.tsx b/packages/webui/routes/projects/$projectId/shares/index.tsx
index dea1d8bc..095950ad 100644
--- a/packages/webui/routes/projects/$projectId/shares/index.tsx
+++ b/packages/webui/routes/projects/$projectId/shares/index.tsx
@@ -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
- }
-
- const handleCopyLink = (shareId: string) => {
- const url = `${window.location.origin}/share/${shareId}`
- navigator.clipboard.writeText(url)
- toast.success(m.link_copied())
- }
-
- return (
-
-
- {!isLeftSidebarCollapsed && (
-
setIsLeftSidebarCollapsed(true)}
- />
- )}
-
- {!isLeftSidebarCollapsed && (
- <>
-
-
-
-
{
- setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
- }}
- className="hidden md:block"
- />
- >
- )}
-
- {/* Main Content Area */}
-
-
-
-
- {isSharesLoading ? (
-
- ) : shares.length === 0 ? (
-
-
-
{m.no_share_links_yet()}
-
- ) : (
-
-
-
-
- {m.name()}
- {m.public_link()}
- {m.creator()}
-
- {m.created_date()}
-
-
- {m.active()}
-
-
-
-
- {shares.map((share) => {
- const shareUrl = `${window.location.origin}/share/${share.id}`
- return (
-
-
-
- navigate({
- to: '/projects/$projectId/shares/$shareId',
- params: { projectId, shareId: share.id },
- })
- }
- >
- {share.name}
-
-
-
-
-
handleCopyLink(share.id)}
- title={m.click_to_copy_link()}
- >
- {shareUrl}
-
-
-
-
-
-
-
-
-
-
- {share.creator?.image && (
-
- )}
-
- {getInitials(share.creator?.name)}
-
-
-
- {share.creator?.name || m.unknown()}
-
-
-
-
-
-
- {new Date(share.createdAt).toLocaleDateString()}
-
-
-
-
-
- toggleVisibility({ id: share.id, isDisabled: !checked })
- }
- />
-
-
-
- )
- })}
-
-
-
- {isFetchingNextPage && }
-
-
- )}
-
-
-
-
- )
-}
-
export const Route = createFileRoute('/projects/$projectId/shares/')({
- component: SharesPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () =>
,
diff --git a/packages/webui/routes/share/$shareId/files/$fileId.lazy.tsx b/packages/webui/routes/share/$shareId/files/$fileId.lazy.tsx
new file mode 100644
index 00000000..601196be
--- /dev/null
+++ b/packages/webui/routes/share/$shareId/files/$fileId.lazy.tsx
@@ -0,0 +1,24 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+import { PublicShareManager } from '@/ui/components/public-share-manager'
+
+function PublicShareFilePage() {
+ const { shareId, fileId } = Route.useParams()
+ const { start, version, compare, cmpLeft, cmpRight, cmpActive } = Route.useSearch()
+
+ return (
+
+ )
+}
+
+export const Route = createLazyFileRoute('/share/$shareId/files/$fileId')({
+ component: PublicShareFilePage,
+})
diff --git a/packages/webui/routes/share/$shareId/files/$fileId.tsx b/packages/webui/routes/share/$shareId/files/$fileId.tsx
index c21c81e6..d439108a 100644
--- a/packages/webui/routes/share/$shareId/files/$fileId.tsx
+++ b/packages/webui/routes/share/$shareId/files/$fileId.tsx
@@ -1,26 +1,6 @@
-import { PublicShareManager } from '@/ui/components/public-share-manager'
import { createFileRoute } from '@tanstack/react-router'
-function PublicShareFilePage() {
- const { shareId, fileId } = Route.useParams()
- const { start, version, compare, cmpLeft, cmpRight, cmpActive } = Route.useSearch()
-
- return (
-
- )
-}
-
export const Route = createFileRoute('/share/$shareId/files/$fileId')({
- component: PublicShareFilePage,
validateSearch: (search: Record
) => {
return {
start: search.start ? Number(search.start) : undefined,
diff --git a/packages/webui/routes/share/$shareId/folders/$folderId.lazy.tsx b/packages/webui/routes/share/$shareId/folders/$folderId.lazy.tsx
new file mode 100644
index 00000000..91bb2c17
--- /dev/null
+++ b/packages/webui/routes/share/$shareId/folders/$folderId.lazy.tsx
@@ -0,0 +1,12 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+import { PublicShareManager } from '@/ui/components/public-share-manager'
+
+function PublicShareFolderPage() {
+ const { shareId, folderId } = Route.useParams()
+
+ return
+}
+
+export const Route = createLazyFileRoute('/share/$shareId/folders/$folderId')({
+ component: PublicShareFolderPage,
+})
diff --git a/packages/webui/routes/share/$shareId/folders/$folderId.tsx b/packages/webui/routes/share/$shareId/folders/$folderId.tsx
index ed2de98f..16109c96 100644
--- a/packages/webui/routes/share/$shareId/folders/$folderId.tsx
+++ b/packages/webui/routes/share/$shareId/folders/$folderId.tsx
@@ -1,12 +1,3 @@
-import { PublicShareManager } from '@/ui/components/public-share-manager'
import { createFileRoute } from '@tanstack/react-router'
-function PublicShareFolderPage() {
- const { shareId, folderId } = Route.useParams()
-
- return
-}
-
-export const Route = createFileRoute('/share/$shareId/folders/$folderId')({
- component: PublicShareFolderPage,
-})
+export const Route = createFileRoute('/share/$shareId/folders/$folderId')({})
diff --git a/packages/webui/routes/share/$shareId/index.lazy.tsx b/packages/webui/routes/share/$shareId/index.lazy.tsx
new file mode 100644
index 00000000..d600b303
--- /dev/null
+++ b/packages/webui/routes/share/$shareId/index.lazy.tsx
@@ -0,0 +1,12 @@
+import { createLazyFileRoute } from '@tanstack/react-router'
+import { PublicShareManager } from '@/ui/components/public-share-manager'
+
+function PublicShareIndexPage() {
+ const { shareId } = Route.useParams()
+
+ return
+}
+
+export const Route = createLazyFileRoute('/share/$shareId/')({
+ component: PublicShareIndexPage,
+})
diff --git a/packages/webui/routes/share/$shareId/index.tsx b/packages/webui/routes/share/$shareId/index.tsx
index 4fa0017b..30509ceb 100644
--- a/packages/webui/routes/share/$shareId/index.tsx
+++ b/packages/webui/routes/share/$shareId/index.tsx
@@ -1,12 +1,3 @@
-import { PublicShareManager } from '@/ui/components/public-share-manager'
import { createFileRoute } from '@tanstack/react-router'
-function PublicShareIndexPage() {
- const { shareId } = Route.useParams()
-
- return
-}
-
-export const Route = createFileRoute('/share/$shareId/')({
- component: PublicShareIndexPage,
-})
+export const Route = createFileRoute('/share/$shareId/')({})
diff --git a/packages/webui/routes/teams/$teamId/index.lazy.tsx b/packages/webui/routes/teams/$teamId/index.lazy.tsx
new file mode 100644
index 00000000..ec4b8ca6
--- /dev/null
+++ b/packages/webui/routes/teams/$teamId/index.lazy.tsx
@@ -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(null)
+
+ // State for Project Dialog
+ const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false)
+ const [projectDialogMode, setProjectDialogMode] = useState<'create' | 'edit'>('create')
+ const [selectedProject, setSelectedProject] = useState(undefined)
+
+ // State for Delete Alert
+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
+ const [projectToDelete, setProjectToDelete] = useState(undefined)
+ const [deleteConfirmText, setDeleteConfirmText] = useState('')
+
+ // State for Members Dialog
+ const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
+
+ // Sort State
+ const [sortBy, setSortBy] = useState('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,
+ Error,
+ InferRequestType
+ >({
+ 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 (
+
+
+
{m.projects()}
+
+
setIsMembersDialogOpen(true)}
+ >
+ {safeMembers.slice(0, 3).map((member) => (
+
+ {member.image && (
+
+ )}
+ {getInitials(member.name)}
+
+ ))}
+ {safeMembers.length > 3 && (
+
+ +{safeMembers.length - 3}
+
+ )}
+
+
+ {canEdit && (
+
+ )}
+
+
+
+ {projects.data?.map((project: ProjectInfo) => (
+
handleCardClick(project.id!, e)}
+ >
+
+
+ {project.coverImage ? (
+

+ ) : (
+
+ )}
+
+
{project.name}
+
+
+
+ {m.updated_ago()} {formatDateAgo((project.updatedAt as string) ?? '')}
+
+
e.stopPropagation()}>
+
+
+
+
+
+ {canEdit && (
+ {
+ e.stopPropagation()
+ handleEditProjectClick(project)
+ }}
+ >
+ {m.project_settings()}
+
+ )}
+ {
+ e.preventDefault()
+ toggleProjectNotificationsMutation.mutate(project)
+ }}
+ >
+ {m.notification()}
+
+
+ {canAdmin && (
+ handleDeleteProjectClick(project)}
+ >
+ {m.delete()}
+
+ )}
+
+
+
+
+
+
+ ))}
+ {canEdit && (
+
+
+
+
+
+ {m.create_project()}
+
+
+
+
+ )}
+
+
+
+
+
+
+
+ {m.are_you_sure()}
+
+ {m.delete_project_warning({ name: projectToDelete?.name ?? '' })}
+
+ {m.type_delete_to_confirm()}
+ setDeleteConfirmText(e.target.value)}
+ placeholder={m.delete_placeholder()}
+ className="h-9"
+ autoFocus
+ />
+
+
+
+
+
+ {m.cancel()}
+
+ {
+ e.preventDefault()
+ handleConfirmDelete()
+ }}
+ disabled={deleteConfirmText !== 'delete' || deleteProjectMutation.isPending}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {deleteProjectMutation.isPending ? m.deleting() : m.delete()}
+
+
+
+
+
+
{
+ await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
+ }}
+ onRemoveMember={async (memberId) => {
+ await removeMemberMutation.mutateAsync(memberId)
+ }}
+ currentUserId={me?.id}
+ />
+
+ )
+}
+
+export const Route = createLazyFileRoute('/teams/$teamId/')({
+ component: TeamPage,
+})
diff --git a/packages/webui/routes/teams/$teamId/index.tsx b/packages/webui/routes/teams/$teamId/index.tsx
index 50570d59..cebdbb1f 100644
--- a/packages/webui/routes/teams/$teamId/index.tsx
+++ b/packages/webui/routes/teams/$teamId/index.tsx
@@ -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(null)
-
- // State for Project Dialog
- const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false)
- const [projectDialogMode, setProjectDialogMode] = useState<'create' | 'edit'>('create')
- const [selectedProject, setSelectedProject] = useState(undefined)
-
- // State for Delete Alert
- const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
- const [projectToDelete, setProjectToDelete] = useState(undefined)
- const [deleteConfirmText, setDeleteConfirmText] = useState('')
-
- // State for Members Dialog
- const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
-
- // Sort State
- const [sortBy, setSortBy] = useState('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,
- Error,
- InferRequestType
- >({
- 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 (
-
-
-
{m.projects()}
-
-
setIsMembersDialogOpen(true)}
- >
- {safeMembers.slice(0, 3).map((member) => (
-
- {member.image && (
-
- )}
- {getInitials(member.name)}
-
- ))}
- {safeMembers.length > 3 && (
-
- +{safeMembers.length - 3}
-
- )}
-
-
- {canEdit && (
-
- )}
-
-
-
- {projects.data?.map((project: ProjectInfo) => (
-
handleCardClick(project.id!, e)}
- >
-
-
- {project.coverImage ? (
-

- ) : (
-
- )}
-
-
{project.name}
-
-
-
- {m.updated_ago()} {formatDateAgo((project.updatedAt as string) ?? '')}
-
-
e.stopPropagation()}>
-
-
-
-
-
- {canEdit && (
- {
- e.stopPropagation()
- handleEditProjectClick(project)
- }}
- >
- {m.project_settings()}
-
- )}
- {
- e.preventDefault()
- toggleProjectNotificationsMutation.mutate(project)
- }}
- >
- {m.notification()}
-
-
- {canAdmin && (
- handleDeleteProjectClick(project)}
- >
- {m.delete()}
-
- )}
-
-
-
-
-
-
- ))}
- {canEdit && (
-
-
-
-
-
- {m.create_project()}
-
-
-
-
- )}
-
-
-
-
-
-
-
- {m.are_you_sure()}
-
- {m.delete_project_warning({ name: projectToDelete?.name ?? '' })}
-
- {m.type_delete_to_confirm()}
- setDeleteConfirmText(e.target.value)}
- placeholder={m.delete_placeholder()}
- className="h-9"
- autoFocus
- />
-
-
-
-
-
- {m.cancel()}
-
- {
- e.preventDefault()
- handleConfirmDelete()
- }}
- disabled={deleteConfirmText !== 'delete' || deleteProjectMutation.isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {deleteProjectMutation.isPending ? m.deleting() : m.delete()}
-
-
-
-
-
-
{
- await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
- }}
- onRemoveMember={async (memberId) => {
- await removeMemberMutation.mutateAsync(memberId)
- }}
- currentUserId={me?.id}
- />
-
- )
-}
-
-export const Route = createFileRoute('/teams/$teamId/')({
- component: TeamPage,
-})
+export const Route = createFileRoute('/teams/$teamId/')({})
diff --git a/packages/webui/routes/teams/$teamId/settings.lazy.tsx b/packages/webui/routes/teams/$teamId/settings.lazy.tsx
new file mode 100644
index 00000000..f66fd4db
--- /dev/null
+++ b/packages/webui/routes/teams/$teamId/settings.lazy.tsx
@@ -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('general')
+ const [profileName, setProfileName] = useState('')
+ const [isCropOpen, setIsCropOpen] = useState(false)
+ const [cropImageSrc, setCropImageSrc] = useState(null)
+ const fileInputRef = useRef(null)
+ const [isUpdatingProfile, setIsUpdatingProfile] = useState(false)
+
+ const { setMetadata, getMetadata } = useUserMetadataStore()
+ const currentLocale = getMetadata('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) => {
+ 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 (
+
+
+
+ )
+ }
+
+ if (settingsError) {
+ return {m.failed_load_settings()}
+ }
+
+ 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 (
+
+
+ {/* Sidebar */}
+
+
+
+
+ {/* Main Content Area */}
+
+
+
+
+
+ {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()}
+
+
+ {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()}
+
+
+
+
+
+ {activeTab === 'general' && (
+
+
+
+ {m.personal_info()}
+ {m.personal_info_description()}
+
+
+
+ {/* Avatar Column */}
+
+
+ {m.avatar()}
+
+
fileInputRef.current?.click()}
+ >
+
+ {me?.image && (
+
+ )}
+
+ {getInitials(me?.name)}
+
+
+
+ {m.change()}
+
+
+
+
+ {me?.image && (
+
+ )}
+
+
+
+
+ {/* Details Column */}
+
+
+
+ setProfileName(e.target.value)}
+ placeholder={m.enter_your_name()}
+ className="max-w-md"
+ />
+
+
+
+
+
+ {m.email_managed_by_auth()}
+
+
+
+
+
+
+
+
+
+
+ {m.language_settings()}
+ {m.select_preferred_language()}
+
+
+
+
+
+
+
+
+
setIsCropOpen(false)}
+ imageSrc={cropImageSrc}
+ onConfirm={handleConfirmCrop}
+ />
+
+ )}
+
+ {activeTab === 'transcode' && (
+
+
+
+ {m.transcode_settings()}
+
+ {m.transcode_description()}
+ {m.transcode_strategy_note()}
+
+
+
+ {/* Video Strategy */}
+
+
{m.video_strategy()}
+
+
+ handleVideoStrategyChange(VideoTranscodeStrategy.best_match)
+ }
+ >
+
{m.best_match()}
+
+ {m.best_match_description()}
+
+
+
+
handleVideoStrategyChange(VideoTranscodeStrategy.all)}
+ >
+
{m.all_resolutions()}
+
+ {m.all_resolutions_description()}
+
+
+
+
+
+
+
+ )}
+
+ {activeTab === 'skills' && (
+
+
+
+ )}
+
+ {activeTab === 'providers' &&
}
+
+ {activeTab === 'agents' && (
+
+ )}
+
+ {activeTab === 'sandbox' && (
+
+
+
+ )}
+
+ {activeTab === 'notifications' &&
}
+
+ {activeTab === 'developer' &&
}
+
+
+
+
+
+ )
+}
+
+export const Route = createLazyFileRoute('/teams/$teamId/settings')({
+ component: TeamSettingsPage,
+})
diff --git a/packages/webui/routes/teams/$teamId/settings.tsx b/packages/webui/routes/teams/$teamId/settings.tsx
index 789362d1..10f35248 100644
--- a/packages/webui/routes/teams/$teamId/settings.tsx
+++ b/packages/webui/routes/teams/$teamId/settings.tsx
@@ -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('general')
- const [profileName, setProfileName] = useState('')
- const [isCropOpen, setIsCropOpen] = useState(false)
- const [cropImageSrc, setCropImageSrc] = useState(null)
- const fileInputRef = useRef(null)
- const [isUpdatingProfile, setIsUpdatingProfile] = useState(false)
-
- const { setMetadata, getMetadata } = useUserMetadataStore()
- const currentLocale = getMetadata('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) => {
- 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 (
-
-
-
- )
- }
-
- if (settingsError) {
- return {m.failed_load_settings()}
- }
-
- 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 (
-
-
- {/* Sidebar */}
-
-
-
-
- {/* Main Content Area */}
-
-
-
-
-
- {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()}
-
-
- {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()}
-
-
-
-
-
- {activeTab === 'general' && (
-
-
-
- {m.personal_info()}
- {m.personal_info_description()}
-
-
-
- {/* Avatar Column */}
-
-
- {m.avatar()}
-
-
fileInputRef.current?.click()}
- >
-
- {me?.image && (
-
- )}
-
- {getInitials(me?.name)}
-
-
-
- {m.change()}
-
-
-
-
- {me?.image && (
-
- )}
-
-
-
-
- {/* Details Column */}
-
-
-
- setProfileName(e.target.value)}
- placeholder={m.enter_your_name()}
- className="max-w-md"
- />
-
-
-
-
-
- {m.email_managed_by_auth()}
-
-
-
-
-
-
-
-
-
-
- {m.language_settings()}
- {m.select_preferred_language()}
-
-
-
-
-
-
-
-
-
setIsCropOpen(false)}
- imageSrc={cropImageSrc}
- onConfirm={handleConfirmCrop}
- />
-
- )}
-
- {activeTab === 'transcode' && (
-
-
-
- {m.transcode_settings()}
-
- {m.transcode_description()}
- {m.transcode_strategy_note()}
-
-
-
- {/* Video Strategy */}
-
-
{m.video_strategy()}
-
-
- handleVideoStrategyChange(VideoTranscodeStrategy.best_match)
- }
- >
-
{m.best_match()}
-
- {m.best_match_description()}
-
-
-
-
handleVideoStrategyChange(VideoTranscodeStrategy.all)}
- >
-
{m.all_resolutions()}
-
- {m.all_resolutions_description()}
-
-
-
-
-
-
-
- )}
-
- {activeTab === 'skills' && (
-
-
-
- )}
-
- {activeTab === 'providers' &&
}
-
- {activeTab === 'agents' && (
-
- )}
-
- {activeTab === 'sandbox' && (
-
-
-
- )}
-
- {activeTab === 'notifications' &&
}
-
- {activeTab === 'developer' &&
}
-
-
-
-
-
- )
-}
-
-export const Route = createFileRoute('/teams/$teamId/settings')({
- component: TeamSettingsPage,
-})
+export const Route = createFileRoute('/teams/$teamId/settings')({})
diff --git a/packages/webui/tsr.config.json b/packages/webui/tsr.config.json
index 187eb365..0c1968d1 100644
--- a/packages/webui/tsr.config.json
+++ b/packages/webui/tsr.config.json
@@ -1,4 +1,5 @@
{
"routesDirectory": "routes",
- "generatedRouteTree": "routeTree.gen.ts"
+ "generatedRouteTree": "routeTree.gen.ts",
+ "autoCodeSplitting": true
}
diff --git a/scripts/build-npm.ts b/scripts/build-npm.ts
index adb021d4..99da29f8 100644
--- a/scripts/build-npm.ts
+++ b/scripts/build-npm.ts
@@ -237,13 +237,13 @@ async function buildMainPackage({
target: 'bun',
outdir: binOutDir,
minify: true,
+ splitting: true,
naming: `${appName}-app.[ext]`,
plugins,
external,
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
- publicPath: '/',
})
if (!buildResult.success) {