refactor(monorepo): decouple api and webui into workspaces packages

This commit is contained in:
yiling
2026-06-01 23:35:00 +08:00
parent e3f4fa219e
commit 1f341c15d0
288 changed files with 18024 additions and 21178 deletions
@@ -0,0 +1,294 @@
import type { AncestorFolder } from '@shumai/dtos'
import { Badge } from '@/ui/components/ui/badge'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
DropdownMenuPortal,
DropdownMenuSeparator,
} from '@/ui/components/ui/dropdown-menu'
import {
DockToLeft,
DockToLeftFilled,
DockToRight,
DockToRightFilled,
} from '@/ui/components/ui/icons'
import { Link, useNavigate } from '@tanstack/react-router'
import { ChevronDown, LayoutGrid, List, History, Check, FileIcon } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
interface BreadcrumbNavProps {
teamId: string
projectId: string
projectName: string
ancestorFolders: AncestorFolder[]
currentAsset: {
name?: string
type: 'file' | 'folder'
version?: number
}
isRootFolder: boolean
displayStyle?: 'card' | 'list'
onDisplayStyleChange?: (style: 'card' | 'list') => void
isLeftSidebarCollapsed?: boolean
onLeftSidebarToggle?: () => void
isRightSidebarCollapsed: boolean
onRightSidebarToggle: () => void
isPublic?: boolean
shareId?: string
onFolderClick?: (folderId: string) => void
fileId?: string
versions?: Array<{
id: string
version: number
name?: string | null
previewUrl?: string | null
creator?: { id: string; name: string | null } | null
}>
}
export function BreadcrumbNav({
teamId,
projectId,
projectName,
ancestorFolders,
currentAsset,
isRootFolder,
displayStyle,
onDisplayStyleChange,
isLeftSidebarCollapsed,
onLeftSidebarToggle,
isRightSidebarCollapsed,
onRightSidebarToggle,
isPublic = false,
onFolderClick,
fileId,
versions,
}: BreadcrumbNavProps) {
const navigate = useNavigate()
const handleVersionClick = (versionId: string) => {
if (!projectId || !fileId) return
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId },
search: (prev: Record<string, unknown>) => ({ ...prev, version: versionId }),
})
}
const breadcrumbs: { name: string; path?: string; id?: string; isMuted?: boolean }[] = isPublic
? [
{
name: projectName,
id: 'root', // Special ID for share root
},
...ancestorFolders
.slice()
.reverse()
.map((folder) => ({
name: folder.name || '',
id: folder.id,
})),
]
: [
{ name: 'All Projects', path: `/teams/${teamId}`, isMuted: true },
{ name: projectName, path: `/projects/${projectId}` },
...ancestorFolders
.slice()
.reverse()
.map((folder) => ({
name: folder.name || '',
path: `/projects/${projectId}/folders/${folder.id}`,
})),
]
return (
<div className="flex h-14 flex-wrap items-center justify-between gap-2 border-b border-border bg-card px-4 py-2">
<div className="flex min-w-0 flex-shrink items-center gap-1">
{breadcrumbs.map((breadcrumb, index) => (
<div key={index} className="flex items-center gap-1">
{index > 0 && <span className="text-muted-foreground">/</span>}
{breadcrumb.path ? (
<Link
// eslint-disable-next-line @typescript-eslint/no-explicit-any
to={breadcrumb.path as any}
className={cn(
'truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground',
breadcrumb.isMuted ? 'text-muted-foreground' : 'text-foreground',
)}
>
{breadcrumb.name}
</Link>
) : (
<button
onClick={() => breadcrumb.id && onFolderClick?.(breadcrumb.id)}
className="truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground text-foreground"
>
{breadcrumb.name}
</button>
)}
</div>
))}
{!isRootFolder && (
<div className="flex items-center gap-1">
<span className="text-muted-foreground">/</span>
{currentAsset.type === 'folder' ? (
<span className="truncate rounded px-2 py-1 text-sm font-medium text-foreground">
{currentAsset.name}
</span>
) : (
<DropdownMenu>
<DropdownMenuTrigger className="flex items-center gap-1 truncate rounded px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground">
<span>{currentAsset.name}</span>
{currentAsset.version !== undefined && (
<Badge variant="outline" className="px-1 py-0 text-xs">
v{currentAsset.version}
</Badge>
)}
<ChevronDown className="h-4 w-4" />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56">
<DropdownMenuItem onClick={() => console.log('Download')}>
Download
</DropdownMenuItem>
<DropdownMenuItem onClick={() => console.log('Rename')}>Rename</DropdownMenuItem>
<DropdownMenuItem onClick={() => console.log('Delete')}>Delete</DropdownMenuItem>
{versions && versions.length > 0 && (
<>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger className="flex items-center gap-2">
<History className="h-4 w-4" />
<span>Versions</span>
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent className="w-80 p-1">
<div className="flex flex-col gap-1 max-h-96 overflow-y-auto">
{versions.map((v) => {
const isActive = currentAsset.version === v.version
return (
<DropdownMenuItem
key={v.id}
onClick={() => handleVersionClick(v.id)}
className="flex items-center gap-3 py-2 px-3 rounded-md cursor-pointer focus:bg-accent focus:text-accent-foreground"
>
<div className="flex-shrink-0 flex items-center justify-center bg-muted dark:bg-muted-foreground/20 text-muted-foreground dark:text-muted-foreground rounded-full px-2 py-0.5 text-xs font-semibold select-none min-w-[2rem]">
v{v.version}
</div>
<div className="h-10 w-16 flex-shrink-0 overflow-hidden rounded-md border border-border bg-muted flex items-center justify-center">
{v.previewUrl ? (
<img
src={v.previewUrl}
alt={v.name || undefined}
className="h-full w-full object-cover"
/>
) : (
<FileIcon className="h-4 w-4 text-muted-foreground" />
)}
</div>
<div className="flex flex-col flex-1 min-w-0 text-left">
<span className="truncate text-sm font-semibold text-foreground">
{v.name}
</span>
<span className="truncate text-xs text-muted-foreground">
{v.creator?.name || 'Unknown'}
</span>
</div>
{isActive && (
<Check className="h-4 w-4 text-primary ml-auto flex-shrink-0" />
)}
</DropdownMenuItem>
)
})}
</div>
<DropdownMenuSeparator />
<div className="p-1">
<button
className="w-full text-center text-xs font-medium py-2 px-3 rounded-md bg-muted/80 hover:bg-muted text-foreground transition-colors"
onClick={() => console.log('Manage versions')}
>
Manage versions...
</button>
</div>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
)}
</div>
<div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1">
{/* Left Sidebar Toggle */}
{!isPublic && onLeftSidebarToggle && (
<button
onClick={onLeftSidebarToggle}
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
title={isLeftSidebarCollapsed ? 'Show Left Sidebar' : 'Hide Left Sidebar'}
>
{isLeftSidebarCollapsed ? (
<DockToLeft className="h-4 w-4" />
) : (
<DockToLeftFilled className="h-4 w-4 fill-primary stroke-0" />
)}
</button>
)}
{/* Card View */}
{!isPublic && displayStyle && onDisplayStyleChange && (
<>
<button
onClick={() => onDisplayStyleChange('card')}
className={`rounded p-1.5 transition-colors ${
displayStyle === 'card'
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
}`}
title="Card View"
>
<LayoutGrid className="h-4 w-4" />
</button>
{/* List View */}
<button
onClick={() => onDisplayStyleChange('list')}
className={`rounded p-1.5 transition-colors ${
displayStyle === 'list'
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
}`}
title="List View"
>
<List className="h-4 w-4" />
</button>
</>
)}
{/* Right Sidebar Toggle */}
<button
onClick={onRightSidebarToggle}
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
title={isRightSidebarCollapsed ? 'Show Right Sidebar' : 'Hide Right Sidebar'}
>
{isRightSidebarCollapsed ? (
<DockToRight className="h-4 w-4" />
) : (
<DockToRightFilled className="h-4 w-4 fill-primary stroke-0" />
)}
</button>
</div>
</div>
)
}
@@ -0,0 +1,577 @@
import type { AttachmentInfo, CommentInfo } from '@shumai/dtos'
import type { UserInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Separator } from '@/ui/components/ui/separator'
import { formatTimeAgo } from '@/ui/lib/time'
import { useQuery } from '@tanstack/react-query'
import { Download, File, Terminal } from 'lucide-react'
import React from 'react'
import Markdown from 'react-markdown'
import { Avatar, AvatarFallback } from '../ui/avatar'
import { DrawAnnotation } from '../ui/icons'
import { Skeleton } from '../ui/skeleton'
import { formatTimestamp } from '../viewers/utils'
interface MessageCardProps {
teamId?: string
message: CommentInfo
isReply?: boolean
hasReplies?: boolean
isLastReply?: boolean
getUser: (id: string) => UserInfo
onReply: (message: CommentInfo) => void
onViewAttachment: (attachment: AttachmentInfo) => void
isSelected?: boolean
onSelect?: () => void
frameRate?: number
rootParentId?: string
}
/* eslint-disable @typescript-eslint/naming-convention */
const AI_PLACEHOLDERS: Record<string, string> = {
__CHAT__: 'Generating...',
__AUTOFILL__: 'Autofilling metadata...',
__EMBEDDING__: 'Generating embeddings...',
__RUNNING__: 'Generating...',
}
export const MessageCard: React.FC<MessageCardProps> = ({
teamId,
message: initialMessage,
isReply,
hasReplies,
isLastReply,
getUser,
onReply,
onViewAttachment,
isSelected,
onSelect,
frameRate,
}) => {
const message = initialMessage
const hasDrawInfo =
!!message.annotations && Array.isArray(message.annotations) && message.annotations.length > 0
const creator = message.creator
const showSkeleton =
!!message.sessionId && !!message.message && message.message in AI_PLACEHOLDERS
const loadingText = (message.message && AI_PLACEHOLDERS[message.message]) || 'Generating...'
const [isLogsOpen, setIsLogsOpen] = React.useState(false)
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 current member info')
return await res.json()
},
enabled: !!teamId,
staleTime: 300000,
})
const isAdmin = me?.role === 'owner'
const { data: logs, isLoading: isLogsLoading } = useQuery({
queryKey: ['agent-sessions', message.sessionId, 'entries'],
queryFn: async () => {
const res = await client.api['agent-sessions'][':sessionId'].entries.$get({
param: { sessionId: message.sessionId! },
})
if (!res.ok) throw new Error('Failed to fetch session logs')
return await res.json()
},
enabled: isLogsOpen && !!message.sessionId,
})
const renderFormattedMessage = (text: string) => {
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
return parts.map((part, index) => {
if (part.match(/^<@[a-zA-Z0-9_-]+>$/)) {
const userId = part.slice(2, -1)
const mentionedUser = message.mentions?.find((m) => m.id === userId) || getUser(userId)
return (
<span key={index} className="text-primary font-medium hover:underline cursor-pointer">
@{mentionedUser?.name || 'Unknown'}
</span>
)
}
return <span key={index}>{part}</span>
})
}
const preprocessMarkdown = (text: string): string => {
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
}
const handleReply = () => {
onReply(message)
}
return (
<div
onClick={onSelect}
className={`relative flex gap-4 ${isReply ? 'mt-[-1px]' : 'mt-3'} mr-3 group p-3 py-4 border transition-all duration-200 cursor-pointer ${
isReply
? isLastReply
? 'rounded-b-xl rounded-t-none'
: 'rounded-none'
: hasReplies
? 'rounded-t-xl rounded-b-none'
: 'rounded-xl'
} ${
isSelected
? 'z-20 border-blue-500/40 dark:border-blue-400/40 bg-blue-500/10 dark:bg-blue-400/10 shadow-sm'
: 'z-10 border-transparent bg-foreground/2 dark:bg-foreground/10 hover:bg-foreground/4 dark:hover:bg-foreground/15'
}`}
>
{/* Left Column: Avatar & Thread Lines */}
<div className="flex flex-col items-center shrink-0 w-8 relative">
{/* Thread line above avatar (for replies) */}
{isReply && (
<div className="absolute top-[-1rem] h-8 w-0.5 bg-foreground/10 left-1/2 -translate-x-1/2 z-0" />
)}
{/* Thread line under avatar (for parent comments with replies, or intermediate replies) */}
{((hasReplies && !isReply) || (isReply && !isLastReply)) && (
<div className="absolute top-4 bottom-[-1rem] w-0.5 bg-foreground/10 left-1/2 -translate-x-1/2 z-0" />
)}
<Avatar className="z-10 relative">
<AvatarFallback className="bg-rose-400 text-black">
{creator?.name?.[0]?.toUpperCase() || 'U'}
</AvatarFallback>
</Avatar>
</div>
{/* Content */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-semibold text-sm">{creator?.name || 'Unknown'}</span>
<span className="text-xs text-gray-400">
{new Date(message.createdAt!).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})}
</span>
</div>
<div className="flow-root mt-1">
{message.second !== null && message.second !== undefined && frameRate && (
<div className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-mono font-bold flex items-center gap-1">
{formatTimestamp(message.second, frameRate)}
</div>
)}
{hasDrawInfo && (
<div
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-bold flex items-center gap-1"
title="Contains drawing annotations"
>
<DrawAnnotation className="w-3.5 h-3.5" />
</div>
)}
{showSkeleton ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<span className="text-xs text-muted-foreground animate-pulse">{loadingText}</span>
</div>
) : message.sessionId ? (
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
<Markdown>{preprocessMarkdown(message.message!)}</Markdown>
</div>
) : (
<div className="text-sm leading-relaxed whitespace-pre-wrap break-words text-wrap break-all">
{renderFormattedMessage(message.message!)}
</div>
)}
</div>
{/* Attachments */}
{message.attachments && message.attachments.length > 0 && (
<div className="flex flex-wrap gap-2 mt-3">
{message.attachments.map((att) => {
const isImage = att.mediaType?.startsWith('image/')
const name = att.url?.split('/').pop()?.split('?')[0] || 'file'
return (
<div
key={att.id}
className="relative group rounded-lg overflow-hidden border bg-white shadow-sm hover:shadow-md transition-shadow w-48 h-32"
onClick={() => isImage && onViewAttachment(att)}
>
{isImage ? (
<img
src={att.url}
alt={name}
className="w-full h-full object-cover cursor-pointer"
/>
) : (
<div className="w-full h-full bg-gray-100 flex flex-col items-center justify-center p-2 text-center">
<File className="w-8 h-8 text-gray-500 mb-2" />
<span className="text-xs font-medium text-gray-700 break-all line-clamp-2">
{name}
</span>
</div>
)}
<a
href={att.url}
target="_blank"
rel="noreferrer"
download={name}
className="absolute right-2 bottom-2 bg-black/60 text-white hover:bg-black/80 p-1.5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
onClick={(e) => e.stopPropagation()}
>
<Download className="w-4 h-4" />
</a>
</div>
)
})}
</div>
)}
{/* Agent Footer */}
{message.sessionId && (
<div className="mt-3 pt-2 border-t border-foreground/5 flex items-center justify-between text-xs text-muted-foreground/60">
<span className="flex items-center gap-1.5 font-medium text-muted-foreground/80">
Created by Agent
</span>
{isAdmin && (
<Button
variant="outline"
size="xs"
onClick={() => setIsLogsOpen(true)}
className="cursor-pointer border-violet-500/20 text-violet-600 dark:text-violet-400 hover:bg-violet-500/10 hover:text-violet-700 hover:border-violet-500/30 font-semibold"
>
Logs
</Button>
)}
</div>
)}
{/* Actions */}
<div className="mt-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center gap-4">
<button
onClick={handleReply}
className="text-xs font-medium text-gray-500 hover:text-blue-600 flex items-center gap-1 cursor-pointer"
>
Reply
</button>
</div>
</div>
{/* Logs Dialog */}
<Dialog open={isLogsOpen} onOpenChange={setIsLogsOpen}>
<DialogContent className="sm:max-w-2xl max-h-[80vh] flex flex-col p-6 overflow-hidden bg-background/95 backdrop-blur-md border border-foreground/15 shadow-2xl">
<DialogHeader className="pb-4 border-b border-foreground/15">
<DialogTitle className="flex items-center gap-2 text-xl font-bold">
<Terminal className="w-5 h-5 text-violet-500" />
Agent Session Logs
</DialogTitle>
<DialogDescription>
Step-by-step execution trace of the agent's background tasks and tool calls.
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto pr-1 py-4 space-y-4 min-h-0 select-text">
{isLogsLoading ? (
<div className="space-y-4">
<div className="flex gap-4">
<Skeleton className="h-5 w-5 rounded-full shrink-0" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-1/4" />
<Skeleton className="h-20 w-full" />
</div>
</div>
<div className="flex gap-4">
<Skeleton className="h-5 w-5 rounded-full shrink-0" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-1/4" />
<Skeleton className="h-12 w-full" />
</div>
</div>
</div>
) : logs && logs.length > 0 ? (
<div className="flex flex-col">
{logs.map((entry) => {
const piEntry = entry.entry as Record<string, unknown> | null
const timestampStr =
piEntry?.timestamp || (entry as Record<string, unknown>).timestamp
let timestamp = ''
if (typeof timestampStr === 'string' || typeof timestampStr === 'number') {
const dateObj = new Date(timestampStr)
if (!isNaN(dateObj.getTime())) {
timestamp = formatTimeAgo(dateObj.toISOString())
}
}
if (piEntry && typeof piEntry === 'object') {
if (piEntry.type === 'message' && piEntry.message) {
const msg = piEntry.message as Record<string, unknown>
let badgeColor =
'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200'
let roleName: string = String(msg.role || '')
if (msg.role === 'user') {
badgeColor =
'bg-slate-100 text-slate-800 dark:bg-slate-900/30 dark:text-slate-300'
roleName = 'User'
} else if (msg.role === 'assistant') {
badgeColor =
'bg-violet-100 text-violet-800 dark:bg-violet-900/30 dark:text-violet-300'
roleName = 'Agent'
} else if (msg.role === 'toolResult') {
badgeColor = msg.isError
? 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300'
roleName = `Tool Result: ${String(msg.toolName || 'Unknown')}`
} else if (msg.role === 'thought') {
badgeColor =
'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300'
roleName = 'Thinking'
}
const renderToolCallArguments = (args: unknown) => {
let parsedArgs: unknown = args
if (typeof args === 'string') {
try {
parsedArgs = JSON.parse(args)
} catch {
// ignore
}
}
if (
parsedArgs &&
typeof parsedArgs === 'object' &&
!Array.isArray(parsedArgs)
) {
const obj = parsedArgs as Record<string, unknown>
return (
<div className="mt-1 space-y-1.5 pt-3">
{Object.entries(obj).map(([key, value]) => {
let valueStr = ''
if (value && typeof value === 'object') {
valueStr = JSON.stringify(value, null, 2)
} else {
valueStr = String(value)
}
return (
<div key={key} className="text-xs leading-relaxed break-words">
<span className="font-semibold text-violet-600 dark:text-violet-400">
{key}:
</span>{' '}
<span className="text-foreground/90 font-mono whitespace-pre-wrap">
{valueStr}
</span>
</div>
)
})}
</div>
)
}
return (
<div className="text-xs font-mono whitespace-pre-wrap">
{String(args)}
</div>
)
}
const renderMessageContent = () => {
const content = msg.content
if (!content) return null
if (typeof content === 'string') {
if (!content.trim()) return null
return (
<div className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
<Markdown>{preprocessMarkdown(content)}</Markdown>
</div>
)
}
if (Array.isArray(content)) {
const renderedBlocks: React.ReactNode[] = []
content.forEach((item, idx) => {
if (!item) return
if (typeof item === 'string') {
if (!item.trim()) return
renderedBlocks.push(
<div
key={`str-${idx}`}
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
>
<Markdown>{preprocessMarkdown(item)}</Markdown>
</div>,
)
return
}
if (typeof item === 'object') {
const itemObj = item as Record<string, unknown>
const type = itemObj.type
if (type === 'text') {
const text = itemObj.text
if (typeof text !== 'string' || !text.trim()) return
renderedBlocks.push(
<div
key={`txt-${idx}`}
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
>
<Markdown>{preprocessMarkdown(text)}</Markdown>
</div>,
)
return
}
if (type === 'toolCall') {
const toolName = String(
itemObj.name || itemObj.toolName || 'Unknown',
)
const toolArgs = itemObj.arguments || itemObj.args
renderedBlocks.push(
<div key={`tool-${idx}`} className="text-xs space-y-2 py-1">
<div className="font-semibold text-violet-600 dark:text-violet-400 flex items-center gap-1.5">
Calling Tool:{' '}
<span className="font-mono bg-violet-500/10 px-1 py-0.5 rounded text-[11px]">
{toolName}
</span>
</div>
{!!toolArgs && (
<div className="space-y-1 pt-3">
<div className="text-[10px] text-muted-foreground/60 uppercase font-bold tracking-wider">
Arguments
</div>
{renderToolCallArguments(toolArgs)}
</div>
)}
</div>,
)
return
}
if (type === 'image') {
renderedBlocks.push(
<div
key={`img-${idx}`}
className="text-xs text-muted-foreground italic flex items-center gap-1.5 py-1"
>
[Image Object]
</div>,
)
return
}
// Fallback for other object types
const stringified = JSON.stringify(item, null, 2)
if (stringified === '{}') return
renderedBlocks.push(
<pre
key={`other-${idx}`}
className="text-xs text-foreground/80 font-mono whitespace-pre-wrap break-words bg-muted/20 p-2 rounded"
>
{stringified}
</pre>,
)
}
})
if (renderedBlocks.length === 0) return null
return (
<div className="space-y-3 w-full">
{renderedBlocks.map((block, index) => (
<React.Fragment key={index}>
{index > 0 && <Separator className="my-3 opacity-50" />}
{block}
</React.Fragment>
))}
</div>
)
}
return null
}
return (
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
{/* Timeline Line */}
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
{/* Timeline Node */}
<div
className={`absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background flex items-center justify-center ${
msg.role === 'user'
? 'bg-slate-500'
: msg.role === 'assistant'
? 'bg-violet-500'
: msg.role === 'toolResult'
? msg.isError
? 'bg-red-500'
: 'bg-emerald-500'
: 'bg-amber-500'
}`}
/>
<div className="flex flex-col gap-1.5 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-foreground/5 backdrop-blur-xs w-full">
<div className="flex items-center justify-between gap-2">
<span
className={`text-[10px] px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${badgeColor}`}
>
{roleName}
</span>
<span className="text-[10px] text-muted-foreground/60">
{timestamp}
</span>
</div>
{renderMessageContent()}
</div>
</div>
)
}
}
// Fallback for non-message entries or arbitrary entries
return (
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
<div className="absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background bg-gray-400" />
<div className="bg-muted/30 p-3 rounded-lg border border-foreground/5">
<div className="text-[10px] text-muted-foreground/60">{timestamp}</div>
<pre className="text-xs text-foreground/80 font-mono whitespace-pre-wrap break-words">
{JSON.stringify(entry.entry, null, 2)}
</pre>
</div>
</div>
)
})}
</div>
) : (
<div className="flex flex-col items-center justify-center py-12 text-center text-muted-foreground">
<Terminal className="w-8 h-8 text-muted-foreground/40 mb-2 animate-pulse" />
<p className="text-sm font-medium">No logs found for this session.</p>
<p className="text-xs text-muted-foreground/60 mt-1">
The session might have been initialized but has not produced any entries yet.
</p>
</div>
)}
</div>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,784 @@
import type { CommentInfo, PostAttachmentRequest, PostAttachmentResponse } from '@shumai/dtos'
import type { BotInfo } from '@shumai/dtos'
import type { UserInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { Annotation } from '@/ui/types'
import { useMutation } from '@tanstack/react-query'
import {
ArrowLeft,
ArrowUp,
Brush,
ChevronDown,
Clock,
FileIcon,
Minus,
Paperclip,
Redo,
Square,
Undo,
XIcon,
} from 'lucide-react'
import React, { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react'
import { Button } from '../ui/button'
import { DrawAnnotation } from '../ui/icons'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { ProgressCircle } from '../ui/progress-circle'
import { formatTimestamp } from '../viewers/utils'
type UploadingFile = {
id: string // A unique ID for the file, e.g., timestamp + name
file: File
progress: number
attachmentId?: string
error?: string
}
interface ChatInputProps {
projectId: string
onSendMessage: (
text: string,
attachmentIds: string[],
annotations?: Annotation[],
replyToId?: string | null,
second?: number | null,
) => void
replyingTo?: CommentInfo | null
onCancelReply?: () => void
users?: UserInfo[]
bots?: BotInfo[]
initialText?: string
hideAnnotationControl?: boolean
disableMentions?: boolean
currentTime?: number
frameRate?: number
onTyping?: () => void
}
const PREDEFINED_COLORS = [
'#ef4444', // Red
'#f97316', // Orange
'#eab308', // Yellow
'#22c55e', // Green
'#3b82f6', // Blue
'#a855f7', // Purple
'#ec4899', // Pink
'#000000', // Black
'#ffffff', // White
]
type MentionEntity = { type: 'user'; data: UserInfo } | { type: 'bot'; data: BotInfo }
export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
(
{
projectId,
onSendMessage,
replyingTo,
onCancelReply,
users = [],
bots = [],
initialText = '',
hideAnnotationControl = false,
disableMentions = false,
currentTime,
frameRate,
onTyping,
},
ref,
) => {
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
const [viewingFile, setViewingFile] = useState<File | null>(null)
const [isTimestampEnabled, setIsTimestampEnabled] = useState(true)
// Annotation Store
const {
isDrawing,
setIsDrawing,
currentTool,
setTool,
currentColor,
setColor,
undo,
redo,
history,
historyIndex,
annotations,
reset: resetAnnotations,
} = useAnnotationStore()
const [showMentionList, setShowMentionList] = useState(false)
const [mentionQuery, setMentionQuery] = useState('')
const [highlightedIndex, setHighlightedIndex] = useState(0)
const [collapsedSections, setCollapsedSections] = useState({ bots: false, users: false })
const [hasContent, setHasContent] = useState(false)
const editorRef = useRef<HTMLDivElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const mentionRangeRef = useRef<Range | null>(null)
const { mutateAsync: uploadAttachment } = useMutation({
mutationFn: async ({
projectId,
data,
}: {
projectId: string
data: PostAttachmentRequest
}) => {
const res = await client.api.projects[':projectId'].attachments.$post({
param: { projectId: projectId },
json: data,
})
if (!res.ok) throw new Error('Failed to create attachment')
return (await res.json()) as PostAttachmentResponse
},
})
useEffect(() => {
if (initialText && editorRef.current) {
editorRef.current.innerText = initialText
setHasContent(!!initialText.trim())
// Focus and move cursor to end
editorRef.current.focus()
const range = document.createRange()
const sel = window.getSelection()
range.selectNodeContents(editorRef.current)
range.collapse(false)
sel?.removeAllRanges()
sel?.addRange(range)
}
}, [initialText])
// Focus editor when replyingTo becomes truthy
useEffect(() => {
if (replyingTo && editorRef.current) {
editorRef.current.focus()
// Focus and move cursor to end
const range = document.createRange()
const sel = window.getSelection()
range.selectNodeContents(editorRef.current)
range.collapse(false)
sel?.removeAllRanges()
sel?.addRange(range)
}
}, [replyingTo])
// Clean up drawing mode on unmount
useEffect(() => {
return () => {
setIsDrawing(false)
}
}, [setIsDrawing])
const filteredAgents = [
...users
.filter(
(u) => u.type === 'agent' && u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()),
)
.map((u) => ({ type: 'user' as const, data: u })),
...bots
.filter((b) => b.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()))
.map((b) => ({ type: 'bot' as const, data: b })),
]
const filteredHumans = users
.filter(
(u) => u.type !== 'agent' && u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()),
)
.map((u) => ({ type: 'user' as const, data: u }))
const filteredEntities: MentionEntity[] = [
...(collapsedSections.bots ? [] : filteredAgents),
...(collapsedSections.users ? [] : filteredHumans),
]
useEffect(() => {
setHighlightedIndex(0)
}, [mentionQuery, showMentionList, collapsedSections])
const handleInput = () => {
if (!editorRef.current) return
setHasContent(!!editorRef.current.innerText.trim())
onTyping?.()
if (disableMentions) {
setShowMentionList(false)
mentionRangeRef.current = null
return
}
const sel = window.getSelection()
if (!sel || sel.rangeCount === 0) return
const range = sel.getRangeAt(0)
const node = range.startContainer
const offset = range.startOffset
if (node.nodeType === Node.TEXT_NODE) {
const textContent = node.textContent || ''
const textBeforeCursor = textContent.slice(0, offset)
const lastAtPos = textBeforeCursor.lastIndexOf('@')
if (lastAtPos !== -1) {
const isStartOfLine = lastAtPos === 0
const charBeforeAt = textBeforeCursor[lastAtPos - 1]
const hasSpaceBefore = isStartOfLine || /\s/.test(charBeforeAt)
if (hasSpaceBefore) {
const query = textBeforeCursor.slice(lastAtPos + 1)
if (!/\s/.test(query)) {
setMentionQuery(query)
setShowMentionList(true)
// Save the range for later insertion
const mentionRange = document.createRange()
mentionRange.setStart(node, lastAtPos)
mentionRange.setEnd(node, offset)
mentionRangeRef.current = mentionRange
return
}
}
}
}
setShowMentionList(false)
mentionRangeRef.current = null
}
const handleSelectEntity = (entity: MentionEntity) => {
if (!mentionRangeRef.current || !editorRef.current) return
const range = mentionRangeRef.current
range.deleteContents()
const mentionNode = document.createElement('span')
mentionNode.contentEditable = 'false'
mentionNode.dataset.type = 'mention'
mentionNode.dataset.id = entity.data.id
mentionNode.className =
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
mentionNode.innerText = `@${entity.data.name}`
range.insertNode(mentionNode)
// Insert a space after the mention
const spaceNode = document.createTextNode('\u00A0')
mentionNode.after(spaceNode)
// Move cursor after the space
const newRange = document.createRange()
const sel = window.getSelection()
newRange.setStartAfter(spaceNode)
newRange.collapse(true)
sel?.removeAllRanges()
sel?.addRange(newRange)
setShowMentionList(false)
mentionRangeRef.current = null
setHasContent(true)
editorRef.current.focus()
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (showMentionList && filteredEntities.length > 0) {
if (e.key === 'ArrowUp') {
e.preventDefault()
setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : filteredEntities.length - 1))
return
}
if (e.key === 'ArrowDown') {
e.preventDefault()
setHighlightedIndex((prev) => (prev < filteredEntities.length - 1 ? prev + 1 : 0))
return
}
if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault()
handleSelectEntity(filteredEntities[highlightedIndex])
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowMentionList(false)
return
}
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSend()
}
}
const handleFileSelect = useCallback(
async (e: ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return
const newFiles = Array.from(e.target.files)
for (const file of newFiles) {
const tempId = `${Date.now()}-${file.name}`
const newUploadingFile: UploadingFile = {
id: tempId,
file,
progress: 0,
}
setUploadingFiles((prev) => [...prev, newUploadingFile])
try {
const data: PostAttachmentResponse = await uploadAttachment({
projectId,
data: {
fileName: file.name,
contentType: file.type,
size: file.size,
},
})
if (data.uploadUrl && data.id) {
await fetch(data.uploadUrl, {
method: 'PUT',
body: file,
headers: {
'Content-Type': file.type,
},
})
setUploadingFiles((prev) =>
prev.map((uf) =>
uf.id === tempId ? { ...uf, progress: 100, attachmentId: data.id } : uf,
),
)
}
} catch (error) {
setUploadingFiles((prev) =>
prev.map((uf) =>
uf.id === tempId
? {
...uf,
error: error instanceof Error ? error.message : 'Upload failed',
}
: uf,
),
)
}
}
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
},
[projectId, uploadAttachment],
)
const removeFile = (id: string) => {
setUploadingFiles((prev) => prev.filter((f) => f.id !== id))
}
const handleSend = () => {
if (!editorRef.current) return
const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error)
if (isUploading) return
const successfulAttachmentIds = uploadingFiles
.map((f) => f.attachmentId)
.filter((id): id is string => !!id)
// Serialize content
let processedText = ''
editorRef.current.childNodes.forEach((node) => {
if (node.nodeType === Node.TEXT_NODE) {
processedText += node.textContent
} else if (node.nodeType === Node.ELEMENT_NODE) {
const el = node as HTMLElement
if (el.dataset.type === 'mention') {
processedText += `<@${el.dataset.id}>`
} else if (el.tagName === 'BR') {
processedText += '\n'
} else if (el.tagName === 'DIV' || el.tagName === 'P') {
// contentEditable often uses div/p for new lines
processedText += '\n' + el.innerText
} else {
processedText += el.innerText
}
}
})
processedText = processedText.trim()
// Allow sending if annotations exist, even if text is empty
if (!processedText && successfulAttachmentIds.length === 0 && annotations.length === 0) return
onSendMessage(
processedText,
successfulAttachmentIds,
annotations,
replyingTo?.id,
isTimestampEnabled ? currentTime : undefined,
)
// Reset editor
editorRef.current.innerHTML = ''
setHasContent(false)
setUploadingFiles([])
setViewingFile(null)
setIsDrawing(false)
resetAnnotations()
setShowMentionList(false)
if (onCancelReply) onCancelReply()
}
const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error)
const hasSuccessfulUploads = uploadingFiles.some((f) => !!f.attachmentId)
const canSend = hasContent || hasSuccessfulUploads || annotations.length > 0
const showUpperPart = uploadingFiles.length > 0 || !!replyingTo
return (
<div
ref={ref}
className="relative flex flex-col w-full border border-foreground/35 rounded-3xl shadow-sm transition-all duration-200"
>
<style>{`
[contenteditable]:empty:before {
content: attr(data-placeholder);
color: #9ca3af;
cursor: text;
}
`}</style>
{showMentionList && (filteredAgents.length > 0 || filteredHumans.length > 0) && (
<div className="absolute bottom-full left-4 mb-2 w-64 rounded-xl shadow-lg border border-border overflow-hidden z-20 bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 duration-200">
<div className="h-64 overflow-y-auto">
{filteredAgents.length > 0 && (
<>
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setCollapsedSections((prev) => ({ ...prev, bots: !prev.bots }))
}}
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors"
>
<span>Agents</span>
<ChevronDown
className={`w-3 h-3 transition-transform ${collapsedSections.bots ? '-rotate-90' : ''}`}
/>
</button>
{!collapsedSections.bots &&
filteredAgents.map((item, index) => {
const actualIndex = index
return (
<button
key={item.data.id}
onClick={() => handleSelectEntity(item)}
onMouseEnter={() => setHighlightedIndex(actualIndex)}
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
actualIndex === highlightedIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
}`}
>
<div className="w-6 h-6 rounded-full bg-purple-100 dark:bg-purple-900/40 flex items-center justify-center text-xs font-bold text-purple-600 dark:text-purple-300">
{item.data.name?.[0]}
</div>
<span className="text-sm">{item.data.name}</span>
</button>
)
})}
</>
)}
{filteredHumans.length > 0 && (
<>
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setCollapsedSections((prev) => ({ ...prev, users: !prev.users }))
}}
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors"
>
<span>Members</span>
<ChevronDown
className={`w-3 h-3 transition-transform ${collapsedSections.users ? '-rotate-90' : ''}`}
/>
</button>
{!collapsedSections.users &&
filteredHumans.map((item, index) => {
const actualIndex =
(collapsedSections.bots ? 0 : filteredAgents.length) + index
return (
<button
key={item.data.id}
onClick={() => handleSelectEntity(item)}
onMouseEnter={() => setHighlightedIndex(actualIndex)}
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
actualIndex === highlightedIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
}`}
>
<div className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center text-xs font-bold text-blue-600 dark:text-blue-300">
{item.data.name?.[0]}
</div>
<span className="text-sm">{item.data.name}</span>
</button>
)
})}
</>
)}
</div>
</div>
)}
{showUpperPart && (
<div className="flex flex-col gap-2 p-3 pb-0 animate-in fade-in slide-in-from-bottom-2 duration-200">
{replyingTo && (
<div className="flex items-center justify-between bg-muted p-2 px-3 rounded-lg border border-border">
<div className="text-xs text-muted-foreground truncate mr-2">
reply to: {replyingTo.message}
</div>
<button
onClick={onCancelReply}
className="text-muted-foreground hover:text-foreground p-1 rounded-full hover:bg-muted-foreground/10 shrink-0"
>
<XIcon className="w-3.5 h-3.5" />
</button>
</div>
)}
{uploadingFiles.length > 0 && (
<div className="flex gap-3 overflow-x-auto py-2 px-1 scrollbar-hide">
{uploadingFiles.map((upload) => (
<div key={upload.id} className="relative group flex-shrink-0">
<div className="w-16 h-16 rounded-lg border border-gray-200 overflow-hidden bg-gray-50 flex items-center justify-center">
{upload.file.type.startsWith('image/') ? (
<img
src={URL.createObjectURL(upload.file)}
alt="preview"
onClick={() => setViewingFile(upload.file)}
className={`w-full h-full object-cover ${
!upload.attachmentId ? 'opacity-50' : ''
}`}
/>
) : (
<FileIcon className="w-8 h-8 text-gray-400" />
)}
{isUploading && !upload.attachmentId && !upload.error && (
<div className="absolute inset-0 flex items-center justify-center bg-black/50">
<ProgressCircle progress={upload.progress} className="w-10 h-10" />
</div>
)}
</div>
<button
onClick={() => removeFile(upload.id)}
className="absolute -top-1.5 -right-1.5 bg-gray-500 text-white rounded-full p-0.5 shadow-md opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-500 z-10"
>
<XIcon className="w-3 h-3" />
</button>
<span className="text-[10px] text-gray-500 mt-1 block max-w-[4rem] truncate text-center">
{upload.file.name}
</span>
</div>
))}
</div>
)}
</div>
)}
<div
onClick={() => editorRef.current?.focus()}
className="w-full px-4 pt-1 pb-1 cursor-text flow-root max-h-60 overflow-y-auto"
>
{isTimestampEnabled && currentTime !== undefined && frameRate !== undefined && (
<div
onClick={(e) => {
e.stopPropagation()
editorRef.current?.focus()
}}
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-0.5 mt-3 mr-2 rounded-sm text-xs font-mono font-bold flex items-center gap-1 cursor-text"
>
{formatTimestamp(currentTime, frameRate)}
</div>
)}
<div
ref={editorRef}
contentEditable
suppressContentEditableWarning
onInput={handleInput}
onKeyDown={handleKeyDown}
data-placeholder={replyingTo ? 'Reply...' : 'Message...'}
className={`bg-transparent border-none focus:ring-0 resize-none min-h-[40px] leading-relaxed py-2 focus:outline-none block ${isTimestampEnabled && currentTime !== undefined && frameRate !== undefined && !hasContent ? 'pl-[120px]' : ''}`}
/>
</div>
<div className="flex justify-between items-center px-2 pb-2">
{isDrawing ? (
<div className="flex items-center gap-2 overflow-x-auto scrollbar-hide w-full mr-2">
<Button
onClick={() => {
setIsDrawing(false)
resetAnnotations() // Cancel drawing
}}
variant="ghost"
size="icon"
className="p-2 rounded-full cursor-pointer text-gray-500 hover:text-gray-700 hover:bg-gray-100 mr-2"
title="Back"
>
<ArrowLeft className="w-4 h-4" />
</Button>
<div className="h-4 w-px bg-gray-300 mx-1"></div>
<button
onClick={() => setTool('arrow')}
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'arrow' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
title="Arrow"
>
<ArrowUp size={16} className="rotate-45" />
</button>
<button
onClick={() => setTool('line')}
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'line' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
title="Line"
>
<Minus size={16} className="-rotate-45" />
</button>
<button
onClick={() => setTool('box')}
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'box' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
title="Box"
>
<Square size={16} />
</button>
<button
onClick={() => setTool('freehand')}
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'freehand' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
title="Freehand"
>
<Brush size={16} />
</button>
<div className="h-4 w-px bg-gray-300 mx-1"></div>
<Popover>
<PopoverTrigger asChild>
<button className="flex items-center gap-1 p-1 rounded hover:bg-gray-100">
<div
className="w-4 h-4 rounded-full border border-gray-200"
style={{ backgroundColor: currentColor }}
/>
<ChevronDown size={12} className="text-gray-500" />
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-2" align="center" side="top">
<div className="flex items-center gap-1">
{PREDEFINED_COLORS.map((c) => (
<button
key={c}
onClick={() => setColor(c)}
className={`w-6 h-6 rounded-full border border-gray-200 transition-transform hover:scale-110 ${currentColor === c ? 'ring-2 ring-blue-500 ring-offset-1' : ''}`}
style={{ backgroundColor: c }}
/>
))}
</div>
</PopoverContent>
</Popover>
<div className="h-4 w-px bg-gray-300 mx-1"></div>
<button
onClick={undo}
disabled={historyIndex <= 0}
className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-500"
>
<Undo size={16} />
</button>
<button
onClick={redo}
disabled={historyIndex >= history.length - 1}
className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-500"
>
<Redo size={16} />
</button>
</div>
) : (
<div className="flex items-center gap-1">
<input
type="file"
ref={fileInputRef}
className="hidden"
multiple
onChange={handleFileSelect}
/>
{currentTime !== undefined && frameRate !== undefined && (
<Button
onClick={() => setIsTimestampEnabled(!isTimestampEnabled)}
variant={isTimestampEnabled ? 'secondary' : 'ghost'}
size="icon"
className={`p-2 rounded-full cursor-pointer ${isTimestampEnabled ? 'text-blue-600 bg-blue-50 dark:bg-blue-900/20' : ''}`}
title={isTimestampEnabled ? 'Disable Timestamp' : 'Enable Timestamp'}
>
<Clock className="w-4 h-4" />
</Button>
)}
<Button
onClick={() => fileInputRef.current?.click()}
className="p-2 rounded-full cursor-pointer"
variant="ghost"
size="icon"
title="Attach files"
>
<Paperclip className="w-4 h-4" />
</Button>
{!hideAnnotationControl && (
<Button
onClick={() => setIsDrawing(true)}
variant="ghost"
size="icon"
className="p-2 rounded-full cursor-pointer"
title="Toggle Annotation"
>
<DrawAnnotation className="w-4 h-4" />
</Button>
)}
</div>
)}
<button
onClick={handleSend}
disabled={!canSend || isUploading}
className={`p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 ${
canSend && !isUploading
? 'bg-blue-600 text-white shadow-md hover:bg-blue-700 hover:shadow-lg transform hover:-translate-y-0.5'
: 'bg-gray-400 cursor-not-allowed'
}`}
>
<ArrowUp className="w-4 h-4" />
</button>
</div>
{viewingFile && (
<div
className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-4 animate-in fade-in duration-200"
onClick={() => setViewingFile(null)}
>
<button className="absolute top-4 right-4 text-white/70 hover:text-white hover:bg-white/20 rounded-full p-2 transition-colors z-50">
<XIcon className="w-8 h-8" />
</button>
<div className="w-full h-full flex items-center justify-center p-2">
<img
src={URL.createObjectURL(viewingFile)}
alt="Enlarged view"
className="max-w-full max-h-[85vh] object-contain rounded shadow-2xl cursor-zoom-out"
onClick={(e) => {
e.stopPropagation()
setViewingFile(null)
}}
/>
</div>
<div className="absolute bottom-6 text-white text-sm font-medium bg-black/50 px-4 py-2 rounded-full backdrop-blur-sm">
{viewingFile.name}
</div>
</div>
)}
</div>
)
},
)
ChatInput.displayName = 'ChatInput'
@@ -0,0 +1,179 @@
'use client'
import { Button } from '@/ui/components/ui/button'
import { Calendar } from '@/ui/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import { ScrollArea, ScrollBar } from '@/ui/components/ui/scroll-area'
import { Separator } from '@/ui/components/ui/separator'
import { cn } from '@/ui/lib/utils'
import { addHours, addWeeks, format } from 'date-fns'
import { CalendarIcon } from 'lucide-react'
import * as React from 'react'
interface DateTimePickerProps {
value?: Date
onChange?: (date: Date | undefined) => void
placeholder?: string
disabled?: boolean
className?: string
}
export function DateTimePicker({
value,
onChange,
placeholder = 'Pick a date',
disabled,
className,
}: DateTimePickerProps) {
const [isOpen, setIsOpen] = React.useState(false)
const [tempValue, setTempValue] = React.useState<Date | undefined>(value)
// Sync tempValue with value when popover opens
React.useEffect(() => {
if (isOpen) {
setTempValue(value)
}
}, [isOpen, value])
const hours = Array.from({ length: 24 }, (_, i) => i)
const minutes = Array.from({ length: 12 }, (_, i) => i * 5) // 5-minute increments
const handleDateSelect = (selectedDate: Date | undefined) => {
if (selectedDate) {
const newDate = tempValue ? new Date(tempValue) : new Date()
newDate.setFullYear(selectedDate.getFullYear())
newDate.setMonth(selectedDate.getMonth())
newDate.setDate(selectedDate.getDate())
setTempValue(newDate)
} else {
setTempValue(undefined)
}
}
const handleTimeChange = (type: 'hour' | 'minute', timeValue: number) => {
const newDate = tempValue ? new Date(tempValue) : new Date()
if (type === 'hour') {
newDate.setHours(timeValue)
} else {
newDate.setMinutes(timeValue)
}
setTempValue(newDate)
}
const handleQuickSelect = (type: '24h' | '1w' | '2w') => {
let newDate = new Date()
if (type === '24h') {
newDate = addHours(newDate, 24)
} else if (type === '1w') {
newDate = addWeeks(newDate, 1)
} else if (type === '2w') {
newDate = addWeeks(newDate, 2)
}
setTempValue(newDate)
}
const handleSave = () => {
onChange?.(tempValue)
setIsOpen(false)
}
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
disabled={disabled}
className={cn(
'w-full justify-start text-left font-normal h-9',
!value && 'text-muted-foreground',
className,
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{value ? format(value, 'yyyy/MM/dd HH:mm') : <span>{placeholder}</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[22rem] p-0" align="start">
<div className="flex flex-col w-full">
<div className="flex w-full">
<Calendar
mode="single"
selected={tempValue}
onSelect={handleDateSelect}
className="grow"
/>
<div className="flex flex-col sm:flex-row sm:h-[300px] divide-y sm:divide-y-0 sm:divide-x border-t sm:border-t-0 border-l">
{/* Hours Column */}
<ScrollArea className="w-64 sm:w-auto [&_[data-orientation=vertical]]:hidden">
<div className="flex sm:flex-col p-2">
{hours.map((hour) => (
<Button
key={hour}
size="icon"
variant={tempValue && tempValue.getHours() === hour ? 'default' : 'ghost'}
className="sm:w-full shrink-0 aspect-square text-xs h-8 w-8"
onClick={() => handleTimeChange('hour', hour)}
>
{hour.toString().padStart(2, '0')}
</Button>
))}
</div>
<ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea>
{/* Minutes Column */}
<ScrollArea className="w-64 sm:w-auto [&_[data-orientation=vertical]]:hidden">
<div className="flex sm:flex-col p-2">
{minutes.map((minute) => (
<Button
key={minute}
size="icon"
variant={tempValue && tempValue.getMinutes() === minute ? 'default' : 'ghost'}
className="sm:w-full shrink-0 aspect-square text-xs h-8 w-8"
onClick={() => handleTimeChange('minute', minute)}
>
{minute.toString().padStart(2, '0')}
</Button>
))}
</div>
<ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea>
</div>
</div>
<Separator />
<div className="p-2 flex items-center justify-between bg-muted/50">
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
className="text-[10px] h-7 px-2"
onClick={() => handleQuickSelect('24h')}
>
24 Hours
</Button>
<Button
variant="outline"
size="sm"
className="text-[10px] h-7 px-2"
onClick={() => handleQuickSelect('1w')}
>
1 Week
</Button>
<Button
variant="outline"
size="sm"
className="text-[10px] h-7 px-2"
onClick={() => handleQuickSelect('2w')}
>
2 Weeks
</Button>
</div>
<Button size="sm" className="h-7 px-4" onClick={handleSave}>
Save
</Button>
</div>
</div>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,35 @@
import { Modifier, configurator } from '@dnd-kit/abstract'
import type { DragOperation } from '@dnd-kit/abstract'
import type { DragDropManager } from '@dnd-kit/dom'
interface Anchor {
x: number
y: number
}
interface Options {
anchor?: Anchor
}
const DEFAULT_ANCHOR: Anchor = { x: 0.5, y: 0.5 }
export class SnapToPointer extends Modifier<DragDropManager, Options> {
apply({ activatorEvent, shape, transform }: DragOperation) {
if (!shape || !(activatorEvent instanceof PointerEvent)) {
return transform
}
const anchor = this.options?.anchor ?? DEFAULT_ANCHOR
const { boundingRectangle } = shape.initial
const anchorX = boundingRectangle.left + boundingRectangle.width * anchor.x
const anchorY = boundingRectangle.top + boundingRectangle.height * anchor.y
return {
x: transform.x + activatorEvent.clientX - anchorX,
y: transform.y + activatorEvent.clientY - anchorY,
}
}
static configure = configurator(SnapToPointer)
}
+6
View File
@@ -0,0 +1,6 @@
export interface DragState {
isActive: boolean
draggedIds: Set<string>
hasFolders: boolean
itemCount: number
}
@@ -0,0 +1,487 @@
import Konva from 'konva'
import type { KonvaEventObject } from 'konva/lib/Node'
import type {
Annotation,
BoxAnnotation,
LineAnnotation,
ArrowAnnotation,
FreehandAnnotation,
} from '@/ui/types'
import { useEffect, useRef } from 'react'
import { Stage, Layer, Image as KonvaImage, Rect, Arrow, Line, Group } from 'react-konva'
import useImage from 'use-image'
import type { DrawingTool } from '@/ui/stores/annotation-store'
interface DrawingCanvasProps {
width: number
height: number
mediaDimensions: { width: number; height: number }
imageUrl?: string
videoElement?: HTMLVideoElement
annotations: Annotation[]
scale: number
offset: { x: number; y: number }
onPan?: (newOffset: { x: number; y: number }) => void
onClick?: () => void
className?: string
// Drawing Props
isDrawing?: boolean
currentTool?: DrawingTool
currentColor?: string
onAddAnnotation?: (annotation: Annotation) => void
}
const DrawingCanvas = ({
width,
height,
mediaDimensions,
imageUrl,
videoElement,
annotations,
scale,
offset,
onPan,
onClick,
className,
isDrawing = false,
currentTool = 'arrow',
currentColor = '#ef4444',
onAddAnnotation,
}: DrawingCanvasProps) => {
const [loadedImage] = useImage(imageUrl || '', 'anonymous')
const imageRef = useRef<Konva.Image>(null)
const isDragging = useRef(false)
const lastPos = useRef({ x: 0, y: 0 })
const startPointRef = useRef<{ x: number; y: number } | null>(null)
// Draft shapes for drawing
const currentLineRef = useRef<Konva.Line>(null)
const currentRectRef = useRef<Konva.Rect>(null)
const currentArrowRef = useRef<Konva.Arrow>(null)
// Handle Video Redraw
useEffect(() => {
if (videoElement && imageRef.current) {
const layer = imageRef.current.getLayer()
if (!layer) return
const anim = new Konva.Animation(() => {
// Force redraw to update video frame
}, layer)
anim.start()
return () => {
anim.stop()
}
}
}, [videoElement])
// -- Helpers --
const getRelativePointerPosition = (
node: Konva.Node,
clamp = false,
customPos?: { x: number; y: number },
) => {
// the function will return pointer position relative to the passed node
const transform = node.getAbsoluteTransform().copy()
// to detect relative position we need to invert transform
transform.invert()
// get pointer (say mouse or touch) position
const pos = customPos || node.getStage()?.getPointerPosition()
if (pos) {
const point = transform.point(pos)
if (clamp) {
return {
x: Math.max(0, Math.min(mediaDimensions.width, point.x)),
y: Math.max(0, Math.min(mediaDimensions.height, point.y)),
}
}
return point
}
return null
}
// Ref to hold current props for global listeners to avoid stale closures
const stateRef = useRef({
isDrawing,
currentTool,
currentColor,
onPan,
offset,
scale,
mediaDimensions,
onAddAnnotation,
})
stateRef.current = {
isDrawing,
currentTool,
currentColor,
onPan,
offset,
scale,
mediaDimensions,
onAddAnnotation,
}
const finalizeDrawing = () => {
if (!isDragging.current) return
isDragging.current = false
const {
isDrawing: activeDrawing,
onAddAnnotation: addAnn,
mediaDimensions: dims,
currentTool: tool,
currentColor: color,
} = stateRef.current
if (activeDrawing && addAnn) {
const w = dims.width
const h = dims.height
// Helper to normalize
const norm = (val: number, dim: number) => val / dim
// Capture shape
if (tool === 'freehand' && currentLineRef.current) {
currentLineRef.current.visible(false)
const rawPoints = currentLineRef.current.points()
const points: [number, number][] = []
for (let i = 0; i < rawPoints.length; i += 2) {
points.push([norm(rawPoints[i], w), norm(rawPoints[i + 1], h)])
}
if (points.length > 1) {
const ann: FreehandAnnotation = {
type: 'freehand',
color,
points,
}
addAnn(ann)
}
} else if (tool === 'line' && currentLineRef.current) {
currentLineRef.current.visible(false)
const pts = currentLineRef.current.points()
const ann: LineAnnotation = {
type: 'line',
color,
points: [
[norm(pts[0], w), norm(pts[1], h)],
[norm(pts[2], w), norm(pts[3], h)],
],
}
addAnn(ann)
} else if (tool === 'box' && currentRectRef.current) {
currentRectRef.current.visible(false)
const x = currentRectRef.current.x()
const y = currentRectRef.current.y()
const boxW = currentRectRef.current.width()
const boxH = currentRectRef.current.height()
// Convert to start/end points
const start: [number, number] = [norm(x, w), norm(y, h)]
const end: [number, number] = [norm(x + boxW, w), norm(y + boxH, h)]
const ann: BoxAnnotation = {
type: 'box',
color,
points: [start, end],
}
addAnn(ann)
} else if (tool === 'arrow' && currentArrowRef.current) {
currentArrowRef.current.visible(false)
const pts = currentArrowRef.current.points()
const ann: ArrowAnnotation = {
type: 'arrow',
color,
points: [
[norm(pts[0], w), norm(pts[1], h)],
[norm(pts[2], w), norm(pts[3], h)],
],
}
addAnn(ann)
}
}
}
useEffect(() => {
const handleGlobalMove = (e: MouseEvent | TouchEvent) => {
if (!isDragging.current) return
const stage = imageRef.current?.getStage()
if (!stage) return
const container = stage.container()
const rect = container.getBoundingClientRect()
let clientX, clientY
if ('clientX' in e) {
clientX = e.clientX
clientY = e.clientY
} else {
clientX = e.touches[0].clientX
clientY = e.touches[0].clientY
}
const stagePos = {
x: clientX - rect.left,
y: clientY - rect.top,
}
const {
isDrawing: activeDrawing,
currentTool: tool,
onPan: panFn,
offset: currentOffset,
} = stateRef.current
if (activeDrawing) {
if (tool === 'select') return
const pos = getRelativePointerPosition(imageRef.current!, true, stagePos)
if (!pos || !startPointRef.current) return
const start = startPointRef.current
const layer = imageRef.current?.getLayer()
if (tool === 'freehand' && currentLineRef.current) {
const newPoints = currentLineRef.current.points().concat([pos.x, pos.y])
currentLineRef.current.points(newPoints)
} else if (tool === 'line' && currentLineRef.current) {
currentLineRef.current.points([start.x, start.y, pos.x, pos.y])
} else if (tool === 'box' && currentRectRef.current) {
currentRectRef.current.width(pos.x - start.x)
currentRectRef.current.height(pos.y - start.y)
} else if (tool === 'arrow' && currentArrowRef.current) {
currentArrowRef.current.points([start.x, start.y, pos.x, pos.y])
}
layer?.batchDraw()
} else {
// Panning
if (!panFn) return
const dx = stagePos.x - lastPos.current.x
const dy = stagePos.y - lastPos.current.y
lastPos.current = stagePos
panFn({
x: currentOffset.x + dx,
y: currentOffset.y + dy,
})
}
}
const handleGlobalUp = () => {
finalizeDrawing()
}
window.addEventListener('mousemove', handleGlobalMove)
window.addEventListener('mouseup', handleGlobalUp)
window.addEventListener('touchmove', handleGlobalMove)
window.addEventListener('touchend', handleGlobalUp)
return () => {
window.removeEventListener('mousemove', handleGlobalMove)
window.removeEventListener('mouseup', handleGlobalUp)
window.removeEventListener('touchmove', handleGlobalMove)
window.removeEventListener('touchend', handleGlobalUp)
}
}, [])
const handleMouseDown = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
if (isDrawing) {
// Drawing Logic
if (currentTool === 'select') return
const stage = e.target.getStage()
if (!stage) return
// Use imageRef to get coordinates relative to the image (handling zoom/pan)
const pos = getRelativePointerPosition(imageRef.current!)
if (!pos) return
// Only start drawing if within media bounds
if (
pos.x < 0 ||
pos.x > mediaDimensions.width ||
pos.y < 0 ||
pos.y > mediaDimensions.height
) {
return
}
isDragging.current = true
startPointRef.current = pos
const layer = imageRef.current?.getLayer()
if (!layer) return
if (currentTool === 'freehand' && currentLineRef.current) {
currentLineRef.current.points([pos.x, pos.y])
currentLineRef.current.stroke(currentColor)
currentLineRef.current.visible(true)
} else if (currentTool === 'line' && currentLineRef.current) {
currentLineRef.current.points([pos.x, pos.y, pos.x, pos.y])
currentLineRef.current.stroke(currentColor)
currentLineRef.current.visible(true)
} else if (currentTool === 'box' && currentRectRef.current) {
currentRectRef.current.position(pos)
currentRectRef.current.width(0)
currentRectRef.current.height(0)
currentRectRef.current.stroke(currentColor)
currentRectRef.current.visible(true)
} else if (currentTool === 'arrow' && currentArrowRef.current) {
currentArrowRef.current.points([pos.x, pos.y, pos.x, pos.y])
currentArrowRef.current.stroke(currentColor)
currentArrowRef.current.fill(currentColor)
currentArrowRef.current.visible(true)
}
layer.batchDraw()
} else {
// Panning Logic
if (!onPan) return
isDragging.current = true
const stage = e.target.getStage()
if (stage) {
const pointer = stage.getPointerPosition()
if (pointer) {
lastPos.current = pointer
}
}
}
}
const renderAnnotation = (annotation: Annotation, i: number) => {
const w = mediaDimensions.width
const h = mediaDimensions.height
// We add a key suffix to force re-render if updated? No, index is fine for this list.
// Actually, we might want stable IDs if we were editing existing ones.
// Stroke Width Logic:
// We want the stroke to be visible regardless of zoom.
// If we use `strokeScaleEnabled={false}`, Konva handles it!
// Wait, `strokeScaleEnabled` defaults to true.
// If false, stroke width is in screen pixels.
// Let's try `strokeScaleEnabled={false}` and `strokeWidth={2}`.
switch (annotation.type) {
case 'box': {
const [start, end] = annotation.points
const x = Math.min(start[0], end[0]) * w
const y = Math.min(start[1], end[1]) * h
const boxWidth = Math.abs(end[0] - start[0]) * w
const boxHeight = Math.abs(end[1] - start[1]) * h
return (
<Rect
key={i}
x={x}
y={y}
width={boxWidth}
height={boxHeight}
stroke={annotation.color}
strokeWidth={2.6 / scale}
listening={false}
/>
)
}
case 'arrow': {
const points = annotation.points.flat().map((p, idx) => (idx % 2 === 0 ? p * w : p * h))
return (
<Arrow
key={i}
points={points}
stroke={annotation.color}
strokeWidth={2.6 / scale}
fill={annotation.color}
pointerLength={10 / scale}
pointerWidth={10 / scale}
listening={false}
/>
)
}
case 'line':
case 'freehand': {
const points = annotation.points.flat().map((p, idx) => (idx % 2 === 0 ? p * w : p * h))
return (
<Line
key={i}
points={points}
stroke={annotation.color}
strokeWidth={2.6 / scale}
tension={0.5}
lineCap="round"
lineJoin="round"
listening={false}
/>
)
}
default:
return null
}
}
return (
<div
className={className}
style={{
width,
height,
overflow: 'hidden',
pointerEvents: !isDrawing && !onPan ? 'none' : 'auto',
cursor:
isDrawing && currentTool !== 'select'
? 'crosshair'
: onPan
? isDragging.current
? 'grabbing'
: 'grab'
: 'default',
}}
>
<Stage
width={width}
height={height}
scaleX={scale}
scaleY={scale}
x={offset.x}
y={offset.y}
onMouseDown={handleMouseDown}
onClick={!isDrawing ? onClick : undefined}
onTap={!isDrawing ? onClick : undefined}
onTouchStart={handleMouseDown}
>
<Layer>
<KonvaImage
ref={imageRef}
image={videoElement || loadedImage}
width={mediaDimensions.width}
height={mediaDimensions.height}
/>
{annotations.map(renderAnnotation)}
{/* Draft Shapes */}
<Group listening={false}>
<Line
ref={currentLineRef}
strokeWidth={2.6 / scale}
lineCap="round"
lineJoin="round"
visible={false}
/>
<Rect ref={currentRectRef} strokeWidth={2.6 / scale} visible={false} />
<Arrow
ref={currentArrowRef}
points={[]}
strokeWidth={2.6 / scale}
pointerLength={10 / scale}
pointerWidth={10 / scale}
visible={false}
/>
</Group>
</Layer>
</Stage>
</div>
)
}
export default DrawingCanvas
+161
View File
@@ -0,0 +1,161 @@
import { Menu } from 'lucide-react'
import React, { useMemo, useState } from 'react'
import { Button } from './ui/button'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip'
import { UserMenu } from './user-menu'
interface DualSidebarItemProps {
icon: React.ReactNode
label: string
badge?: React.ReactNode
children?: React.ReactNode
onItemClick?: () => void
}
// A declarative component that holds props for a sidebar item. It doesn't render anything itself.
export const DualSidebarItem: React.FC<DualSidebarItemProps> = () => {
return null
}
interface DualSidebarProps {
children: React.ReactNode
}
export const DualSidebar: React.FC<DualSidebarProps> = ({ children }) => {
const [activeItem, setActiveItem] = useState<number | null>(null)
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
const sidebarItems = useMemo(
() =>
React.Children.toArray(children).filter(
(child): child is React.ReactElement<DualSidebarItemProps> =>
React.isValidElement(child) && child.type === DualSidebarItem,
),
[children],
)
const activeItemContent = activeItem !== null ? sidebarItems[activeItem]?.props : null
const handleItemClick = (index: number) => {
const item = sidebarItems[index]
if (!item.props.children) {
setActiveItem(null)
item.props.onItemClick?.()
return
}
setActiveItem((prev) => {
if (prev === index) {
return null
}
if (item && item.props.onItemClick) {
item.props.onItemClick()
}
return index
})
}
const toggleMobileMenu = () => {
setIsMobileMenuOpen((prev) => !prev)
}
const closeMobileMenu = () => {
setIsMobileMenuOpen(false)
setActiveItem(null)
}
return (
<>
{/* Mobile Hamburger Button */}
<Button
variant="ghost"
size="icon"
onClick={toggleMobileMenu}
className="md:hidden fixed top-4 left-4 z-50 rounded-md bg-sidebar/50 backdrop-blur-sm text-sidebar-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring"
aria-label="Open navigation menu"
aria-expanded={isMobileMenuOpen}
>
<Menu />
</Button>
{/* Mobile Overlay */}
{isMobileMenuOpen && (
<div
onClick={closeMobileMenu}
className="fixed inset-0 bg-black/60 z-30 md:hidden"
aria-hidden="true"
/>
)}
{/* Desktop Overlay for Child Sidebar */}
{activeItem !== null && (
<div
onClick={() => setActiveItem(null)}
className="hidden md:block fixed inset-0 bg-black/20 z-30"
aria-hidden="true"
/>
)}
<aside
className={`fixed inset-y-0 left-0 z-40 flex transition-transform duration-300 ease-in-out ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'} md:translate-x-0`}
>
<div className="absolute bottom-0 w-full h-[70dvh] bg-linear-to-t from-sidebar-primary/10 to-transparent"></div>
{/* Level 1: Icon Bar */}
<nav className="w-16 bg-sidebar border-r border-sidebar-border flex flex-col items-center pb-4 pt-0 space-y-2 flex-shrink-0">
<div className="flex-1 w-full flex flex-col items-center space-y-5 pt-1">
<TooltipProvider>
{sidebarItems.map((item, index) => (
<Tooltip key={item.props.label}>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-lg"
onClick={() => handleItemClick(index)}
aria-label={item.props.label}
aria-expanded={activeItem === index}
className={`relative w-12 h-12 [&_svg:not([class*='size-'])]:size-6 transition-all duration-200 ${
activeItem === index
? 'bg-sidebar-primary text-sidebar-primary-foreground shadow-lg hover:bg-sidebar-primary hover:text-sidebar-primary-foreground'
: 'text-sidebar-foreground/60 hover:text-sidebar-foreground hover:bg-sidebar-accent'
}`}
>
{item.props.icon}
{item.props.badge}
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>{item.props.label}</p>
</TooltipContent>
</Tooltip>
))}
</TooltipProvider>
</div>
<div className="mt-auto w-full flex flex-col items-center pb-2">
<UserMenu />
</div>
</nav>
{/* Level 2: Content Panel */}
<div
className={`transition-all duration-300 ease-in-out bg-sidebar/95 backdrop-blur-sm shadow-lg overflow-hidden ${
activeItem !== null
? 'w-[calc(100vw-4rem)] md:w-100 border-r border-sidebar-border'
: 'w-0'
}`}
>
<div className="w-[calc(100vw-4rem)] md:w-100 h-full flex flex-col">
{activeItemContent && (
<>
<header className="h-16 flex items-center px-4 font-bold text-lg border-b border-sidebar-border flex-shrink-0">
<h2>{activeItemContent.label}</h2>
</header>
<div className="flex-1 overflow-y-auto p-2">{activeItemContent.children}</div>
</>
)}
</div>
</div>
</aside>
</>
)
}
@@ -0,0 +1,93 @@
import type { FieldInfo as FieldInfo } from '@shumai/dtos'
import React from 'react'
import DateField from './fields/date-field'
import LongTextField from './fields/long-text-field'
import NumberField from './fields/number-field'
import RatingField from './fields/rating-field'
import SelectField from './fields/select-field'
import SelectMultiField from './fields/select-multi-field'
import TextField from './fields/text-field'
import ToggleField from './fields/toggle-field'
interface FieldRendererProps {
config: FieldInfo['config']
value: unknown
onSave: (value: unknown) => void
readOnly?: boolean
}
const FieldRenderer: React.FC<FieldRendererProps> = (props) => {
if (!props.config) {
return <div>Unknown Field Type</div>
}
switch (props.config.type) {
case 'text':
return (
<TextField
{...props}
value={props.value as string}
onSave={props.onSave as (value: string) => void}
/>
)
case 'longText':
return (
<LongTextField
{...props}
value={props.value as string}
onSave={props.onSave as (value: string) => void}
/>
)
case 'select':
return (
<SelectField
{...props}
value={props.value as string}
onSave={props.onSave as (value: string) => void}
/>
)
case 'selectMulti':
return (
<SelectMultiField
{...props}
value={props.value as string[]}
onSave={props.onSave as (value: string[]) => void}
/>
)
case 'rating':
return (
<RatingField
{...props}
value={props.value as number}
onSave={props.onSave as (value: number) => void}
/>
)
case 'number':
return (
<NumberField
{...props}
value={props.value as number}
onSave={props.onSave as (value: number | undefined) => void}
/>
)
case 'toggle':
return (
<ToggleField
{...props}
value={props.value as boolean}
onSave={props.onSave as (value: boolean) => void}
/>
)
case 'date':
return (
<DateField
{...props}
value={props.value as string}
onSave={props.onSave as (value: string) => void}
/>
)
default:
return <div>Unknown Field Type</div>
}
}
export default FieldRenderer
@@ -0,0 +1,303 @@
import { FieldType, type FieldInfo, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useFieldStore } from '@/ui/stores/fields'
import { DragDropProvider, KeyboardSensor, PointerSensor, type DragEndEvent } from '@dnd-kit/react'
import { useSortable } from '@dnd-kit/react/sortable'
import { useMutation } from '@tanstack/react-query'
import { InferRequestType, InferResponseType } from 'hono/client'
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 { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { arrayMove } from '@/ui/lib/dnd-utils'
import { PointerActivationConstraints } from '@dnd-kit/dom'
import { ChevronDown, GripVertical, Plus, Search, Settings, Sparkles } from 'lucide-react'
import { useMemo, useState } from 'react'
type SortableFieldItemProps = {
field: FieldInfo
index: number
onVisibilityChange: (fieldId: string, visible: boolean) => void
}
function SortableFieldItem({ field, index, onVisibilityChange }: SortableFieldItemProps) {
const { ref, handleRef } = useSortable({
id: field.id!,
index,
})
return (
<div ref={ref} className="flex items-center justify-between p-2 rounded-md hover:bg-muted">
<div className="flex items-center gap-2">
<div ref={handleRef} className="cursor-grab">
<GripVertical className="h-4 w-4 text-muted-foreground" />
</div>
{field.aiAutofill && <Sparkles className="h-4 w-4 text-muted-foreground" />}
<span className="text-sm">{field.config?.name}</span>
</div>
<Switch
checked={field.visible}
onCheckedChange={(checked: boolean) => onVisibilityChange(field.id!, checked)}
/>
</div>
)
}
type FieldsManagerProps = {
projectId: string
onManageFields: () => void
onSave?: () => void
}
export function FieldsManager({ projectId, onManageFields, onSave }: FieldsManagerProps) {
const { fields, updateFields } = useFieldStore()
const [searchQuery, setSearchQuery] = useState('')
const [view, setView] = useState<'list' | 'create'>('list')
const [newFieldName, setNewFieldName] = useState('')
const [newFieldType, setNewFieldType] = useState<FieldType | ''>('')
const [newAiAutofill, setNewAiAutofill] = useState(false)
const [newDescription, setNewDescription] = useState('')
const $patchOrder = client.api.projects[':projectId'].fields.order.$patch
const { mutate: updateFieldsOrder } = useMutation<
InferResponseType<typeof $patchOrder>,
Error,
InferRequestType<typeof $patchOrder>
>({
mutationFn: async (request) => {
const res = await $patchOrder(request)
if (!res.ok) throw new Error('Failed to update fields order')
return null as unknown as InferResponseType<typeof $patchOrder>
},
})
const $post = client.api.projects[':projectId'].fields.$post
const { mutate: createField } = useMutation<
InferResponseType<typeof $post>,
Error,
InferRequestType<typeof $post>
>({
mutationFn: async (request) => {
const res = await $post(request)
if (!res.ok) throw new Error('Failed to create field')
return (await res.json()) as MetadataFieldInfo
},
onSuccess: (data) => {
const newField: MetadataFieldInfo = {
...(data as MetadataFieldInfo),
visible: true,
}
const newFieldsList = [...fields, newField]
updateFields(newFieldsList)
setNewFieldName('')
updateFieldsOrder({
param: { projectId: projectId },
json: newFieldsList.map((f) => ({
fieldId: f.id!,
visible: f.visible || false,
})),
})
onSave?.()
},
})
const filteredFields = useMemo(
() =>
fields.filter((field) =>
field.config?.name?.toLowerCase().includes(searchQuery.toLowerCase()),
),
[fields, searchQuery],
)
const handleDragEnd = (event: DragEndEvent) => {
const { source, target } = event.operation
if (source && target && source.id !== target.id) {
const oldIndex = fields.findIndex((f) => f.id === source.id)
const newIndex = fields.findIndex((f) => f.id === target.id)
const newFields = arrayMove(fields, oldIndex, newIndex)
updateFields(newFields)
updateFieldsOrder({
param: { projectId: projectId },
json: newFields.map((f: MetadataFieldInfo) => ({
fieldId: f.id!,
visible: f.visible || false,
})),
})
}
}
const handleVisibilityChange = (fieldId: string, visible: boolean) => {
const newFields = fields.map((f) => (f.id === fieldId ? { ...f, visible } : f))
updateFields(newFields)
updateFieldsOrder({
param: { projectId: projectId },
json: newFields.map((f) => ({
fieldId: f.id!,
visible: f.visible || false,
})),
})
}
const handleCreateField = () => {
if (!newFieldName || !newFieldType) return
createField({
param: { projectId: projectId },
json: {
config: {
name: newFieldName,
type: newFieldType,
},
label: newFieldName,
aiAutofill: newAiAutofill,
description: newDescription,
},
})
}
const visibleCount = fields.filter((f) => f.visible).length
if (view === 'create') {
return (
<div className="w-80 p-4">
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="field-name">Name</Label>
<Input
id="field-name"
placeholder="New Field"
value={newFieldName}
onChange={(e) => setNewFieldName(e.target.value)}
autoFocus
/>
</div>
<div className="space-y-2">
<Label>Type</Label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full justify-between font-normal">
{newFieldType ? (
<span className="capitalize">{newFieldType.replace(/_/g, ' ')}</span>
) : (
<span className="text-muted-foreground border-dashed">Select field type</span>
)}
<ChevronDown className="ml-2 h-4 w-4 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[--radix-dropdown-menu-trigger-width]">
{Object.values(FieldType).map((type) => (
<DropdownMenuItem
key={type}
onClick={() => setNewFieldType(type)}
className="capitalize"
>
{type.replace(/_/g, ' ')}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="space-y-2">
<Label htmlFor="field-desc">Description</Label>
<Input
id="field-desc"
placeholder="Description (Optional)"
value={newDescription}
onChange={(e) => setNewDescription(e.target.value)}
/>
</div>
<div className="flex items-center space-x-2">
<Switch id="ai-autofill" checked={newAiAutofill} onCheckedChange={setNewAiAutofill} />
<Label htmlFor="ai-autofill">AI Autofill</Label>
</div>
<div className="flex gap-2 pt-2">
<Button
variant="secondary"
className="flex-1"
onClick={() => {
setView('list')
setNewFieldName('')
setNewFieldType('')
setNewAiAutofill(false)
setNewDescription('')
}}
>
Cancel
</Button>
<Button
className="flex-1"
onClick={handleCreateField}
disabled={!newFieldName || !newFieldType}
>
Save
</Button>
</div>
</div>
</div>
)
}
return (
<div className="w-80 p-4">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold">
Fields{' '}
<span className="text-muted-foreground text-sm font-normal">
({visibleCount} visible)
</span>
</h3>
</div>
<div className="relative mb-4">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search fields"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-8"
/>
</div>
<div className="max-h-60 overflow-y-auto pr-2">
<DragDropProvider
sensors={[
PointerSensor.configure({
activationConstraints: [new PointerActivationConstraints.Distance({ value: 8 })],
}),
KeyboardSensor,
]}
onDragEnd={handleDragEnd}
>
{filteredFields.map((field, index) => (
<SortableFieldItem
key={field.id}
field={field}
index={index}
onVisibilityChange={handleVisibilityChange}
/>
))}
</DragDropProvider>
</div>
<div className="mt-4 space-y-2">
<Button variant="secondary" className="w-full" onClick={onManageFields}>
<Settings className="h-4 w-4 mr-2" />
Manage Fields
</Button>
<Button className="w-full" onClick={() => setView('create')}>
<Plus className="h-4 w-4 mr-2" />
New Field
</Button>
</div>
</div>
)
}
@@ -0,0 +1,229 @@
import {
addMonths,
eachDayOfInterval,
endOfMonth,
format,
getDate,
getDay,
getHours,
getMinutes,
getMonth,
getYear,
isValid,
} from 'date-fns'
import { ChevronLeft, ChevronRight, Clock } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOnly }) => {
const dateConfig = config?.date
const [isEditing, setIsEditing] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
// Parse value or default to today
// Replaced parseISO with new Date() to avoid import errors
const parsedDate = value ? new Date(value) : new Date()
const safeDate = isValid(parsedDate) ? parsedDate : new Date()
// Calendar State
const [viewDate, setViewDate] = useState(safeDate)
useEffect(() => {
if (isEditing && value) {
const d = new Date(value)
if (isValid(d)) setViewDate(d)
}
}, [isEditing, value])
// Click outside to close
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
if (isEditing) {
setIsEditing(false)
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const getDisplayValue = (isoString: string) => {
if (!isoString) return ''
const date = new Date(isoString)
if (!isValid(date)) return 'Invalid Date'
let formatStr = 'PPP' // Default Friendly
if (dateConfig?.displayFormat === 'usa') formatStr = 'MM/dd/yyyy'
else if (dateConfig?.displayFormat === 'euro') formatStr = 'dd/MM/yyyy'
else if (dateConfig?.displayFormat === 'iso') formatStr = 'yyyy-MM-dd'
if (dateConfig?.includeTime) {
if (dateConfig?.timeFormat === 'twenty_four_hour') {
formatStr += ' HH:mm'
} else {
formatStr += ' p'
}
}
let display = format(date, formatStr)
if (dateConfig?.displayTimezone) {
display += ` (${Intl.DateTimeFormat().resolvedOptions().timeZone})`
}
return display
}
// Calendar Logic
// Replaced startOfMonth with native Date manipulation
const monthStart = new Date(viewDate.getFullYear(), viewDate.getMonth(), 1)
const monthEnd = endOfMonth(viewDate)
const daysInMonth = eachDayOfInterval({ start: monthStart, end: monthEnd })
const startDayOfWeek = getDay(monthStart) // 0 = Sunday
const handleDateClick = (day: Date) => {
// Preserve time from current value if exists
const newDate = new Date(day)
if (dateConfig?.includeTime) {
// Replaced setHours/setMinutes with native methods
newDate.setHours(getHours(safeDate))
newDate.setMinutes(getMinutes(safeDate))
}
const isoString = newDate.toISOString()
onSave(isoString)
if (!dateConfig?.includeTime) {
setIsEditing(false)
}
}
const handleTimeChange = (type: 'hour' | 'minute', val: number) => {
const newDate = value ? new Date(value) : new Date()
if (!isValid(newDate)) newDate.setTime(new Date().getTime())
if (type === 'hour') newDate.setHours(val)
if (type === 'minute') newDate.setMinutes(val)
const isoString = newDate.toISOString()
onSave(isoString)
}
const hours = Array.from({ length: 24 }, (_, i) => i)
const minutes = Array.from({ length: 12 }, (_, i) => i * 5) // 0, 5, 10...
if (isEditing) {
return (
<div className="relative w-full" ref={containerRef}>
<div className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm shadow-sm min-h-[28px] flex items-center">
{value ? getDisplayValue(value) : <span className="text-gray-400">Select date...</span>}
</div>
<div className="absolute z-50 top-full left-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden min-w-[280px]">
{/* Date Picker */}
<div className="p-4 w-64">
<div className="flex justify-between items-center mb-4">
{/* Replaced subMonths with addMonths(-1) */}
<button
onClick={() => setViewDate(addMonths(viewDate, -1))}
className="p-1 hover:bg-gray-100 rounded"
>
<ChevronLeft className="w-4 h-4" />
</button>
<span className="font-semibold text-sm">{format(viewDate, 'MMMM yyyy')}</span>
<button
onClick={() => setViewDate(addMonths(viewDate, 1))}
className="p-1 hover:bg-gray-100 rounded"
>
<ChevronRight className="w-4 h-4" />
</button>
</div>
<div className="grid grid-cols-7 gap-1 text-center text-xs mb-2 text-gray-500">
{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
<div key={d}>{d}</div>
))}
</div>
<div className="grid grid-cols-7 gap-1 text-center text-sm">
{Array.from({ length: startDayOfWeek }).map((_, i) => (
<div key={`empty-${i}`} />
))}
{daysInMonth.map((date) => {
const valDate = value ? new Date(value) : null
const isSelected =
valDate &&
isValid(valDate) &&
getDate(valDate) === getDate(date) &&
getMonth(valDate) === getMonth(date) &&
getYear(valDate) === getYear(date)
return (
<button
key={date.toString()}
onClick={() => handleDateClick(date)}
className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-blue-50 transition-colors ${
isSelected ? 'bg-blue-50 text-white hover:bg-blue-600' : 'text-gray-700'
}`}
>
{getDate(date)}
</button>
)
})}
</div>
</div>
{/* Time Picker */}
{dateConfig?.includeTime && (
<div className="border-l border-gray-200 bg-gray-50 w-32 flex flex-col">
<div className="p-2 border-b border-gray-200 text-xs font-semibold text-gray-500 flex items-center justify-center gap-1">
<Clock className="w-3 h-3" /> Time
</div>
<div className="flex flex-1 h-64">
<div className="flex-1 overflow-y-auto scrollbar-hide border-r border-gray-200">
{hours.map((h) => (
<div
key={h}
onClick={() => handleTimeChange('hour', h)}
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getHours(safeDate) === h ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
>
{h.toString().padStart(2, '0')}
</div>
))}
</div>
<div className="flex-1 overflow-y-auto scrollbar-hide">
{minutes.map((m) => (
<div
key={m}
onClick={() => handleTimeChange('minute', m)}
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getMinutes(safeDate) === m ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
>
{m.toString().padStart(2, '0')}
</div>
))}
</div>
</div>
</div>
)}
</div>
</div>
)
}
return (
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
}`}
>
{value ? getDisplayValue(value) : <span className="text-gray-400 italic">Empty</span>}
</div>
)
}
export default DateField
@@ -0,0 +1,10 @@
import type { FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
export type FieldConfig = MetadataFieldInfo['config']
export interface FieldProps<T = unknown> {
value: T
config: FieldConfig
onSave: (value: T) => void
readOnly?: boolean
}
@@ -0,0 +1,99 @@
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) => {
const [isEditing, setIsEditing] = useState(false)
const [localValue, setLocalValue] = useState(value || '')
const textareaRef = useRef<HTMLTextAreaElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const [expanded, setExpanded] = useState(false)
useEffect(() => {
setLocalValue(value || '')
}, [value])
useEffect(() => {
if (isEditing && textareaRef.current) {
textareaRef.current.focus()
setExpanded(false)
}
}, [isEditing])
// Handle click outside to close expanded state
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
expanded &&
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
setExpanded(false)
}
}
if (expanded) {
document.addEventListener('mousedown', handleClickOutside)
}
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [expanded])
const handleBlur = () => {
setIsEditing(false)
onSave(localValue)
}
const handlePlaceholderClick = (e: React.MouseEvent) => {
e.stopPropagation()
setExpanded(true)
}
const handleOverlayClick = (e: React.MouseEvent) => {
e.stopPropagation()
if (!readOnly) {
setIsEditing(true)
}
}
if (isEditing) {
return (
<textarea
ref={textareaRef}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
className="w-full min-h-[80px] p-2 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm resize-none"
/>
)
}
return (
<div ref={containerRef} className="relative w-full text-sm">
{/* Placeholder */}
<div
onClick={handlePlaceholderClick}
className={`w-full text-gray-800 rounded border border-transparent transition-all px-2 py-1 line-clamp-2 max-h-[3rem] overflow-hidden ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : 'cursor-pointer'
}`}
title="Click to expand"
>
{value ? value : <span className="text-gray-400 italic">Empty</span>}
</div>
{/* Expanded Overlay */}
{expanded && (
<div
onClick={handleOverlayClick}
className={`absolute top-0 left-0 w-full min-h-full h-auto z-50 bg-white border border-blue-500 rounded shadow-lg px-2 py-1 whitespace-pre-wrap ${
!readOnly ? 'cursor-text' : ''
}`}
>
{value ? value : <span className="text-gray-400 italic">Empty</span>}
</div>
)}
</div>
)
}
export default LongTextField
@@ -0,0 +1,87 @@
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const NumberField: React.FC<FieldProps<number | undefined>> = ({
value,
config,
onSave,
readOnly,
}) => {
const numberConfig = config?.number
const [isEditing, setIsEditing] = useState(false)
// Store as string to allow intermediate states like "1." or empty
const [localValue, setLocalValue] = useState('')
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
setLocalValue(value !== undefined && value !== null ? value.toString() : '')
}, [value])
useEffect(() => {
if (isEditing && inputRef.current) {
inputRef.current.focus()
}
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const handleBlur = () => {
setIsEditing(false)
if (localValue === '') {
onSave(undefined) // Handle empty
} else {
const num = parseFloat(localValue)
onSave(isNaN(num) ? undefined : num)
}
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.stopPropagation()
inputRef.current?.blur()
}
}
const formatNumber = (val: number | undefined) => {
if (val === undefined || val === null || isNaN(val)) return ''
return val.toFixed(numberConfig?.scale)
}
if (isEditing) {
return (
<input
ref={inputRef}
type="number"
step={1 / Math.pow(10, numberConfig?.scale || 0)}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onDoubleClick={(e) => e.stopPropagation()}
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm text-left font-mono"
/>
)
}
return (
<div
onClick={handleStartEdit}
onDoubleClick={(e) => e.stopPropagation()}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors text-left font-mono ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
}`}
>
{value !== undefined && value !== null ? (
formatNumber(value)
) : (
<span className="text-gray-400 italic font-sans text-left block">Empty</span>
)}
</div>
)
}
export default NumberField
@@ -0,0 +1,56 @@
import { Star } from 'lucide-react'
import React, { useState } from 'react'
import type { FieldProps } from './field-types'
const RatingField: React.FC<FieldProps<number>> = ({ value, config, onSave, readOnly }) => {
const ratingConfig = config?.rating
const max = Math.max(2, Math.min(6, ratingConfig?.maxValue || 5)) // Clamp 2-6
const [hoverValue, setHoverValue] = useState<number | null>(null)
const handleClick = (e: React.MouseEvent, rating: number) => {
e.stopPropagation()
if (readOnly) return
let newValue
if (value === rating) {
newValue = 0 // Toggle off
} else {
newValue = rating
}
onSave(newValue)
}
const stars = Array.from({ length: max }, (_, i) => i + 1)
return (
<div
className="flex items-center gap-1 h-[28px]"
onMouseLeave={() => !readOnly && setHoverValue(null)}
onDoubleClick={(e) => e.stopPropagation()}
>
{stars.map((star) => {
const isFilled = hoverValue !== null ? star <= hoverValue : star <= (value || 0)
return (
<button
key={star}
onClick={(e) => handleClick(e, star)}
onMouseEnter={() => !readOnly && setHoverValue(star)}
className={`focus:outline-none transition-transform ${
!readOnly ? 'cursor-pointer hover:scale-110' : 'cursor-default'
}`}
type="button"
disabled={readOnly}
>
<Star
className={`w-5 h-5 transition-colors ${
isFilled ? 'fill-yellow-400 text-yellow-400' : 'fill-gray-100 text-gray-300'
}`}
/>
</button>
)
})}
</div>
)
}
export default RatingField
@@ -0,0 +1,97 @@
import type { SelectOption } from '@shumai/dtos'
import { ChevronDown, X } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOnly }) => {
const selectConfig = config?.select
const [isEditing, setIsEditing] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const selectedOption = selectConfig?.options?.find((opt: SelectOption) => opt.id === value)
// Click outside handler
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
if (isEditing) {
setIsEditing(false)
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const handleSelect = (optionId: string) => {
onSave(optionId)
setIsEditing(false)
}
const renderOptionBadge = (option: SelectOption | undefined) => {
if (!option) return <span className="text-gray-400 italic">Select an option</span>
return (
<span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}} // 33 is approx 20% opacity hex
>
{option.displayName}
</span>
)
}
return (
<div className="relative w-full" ref={containerRef}>
<div
onClick={handleStartEdit}
className={`flex items-center justify-between w-full min-h-[28px] px-2 py-1 rounded border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200 group' : ''
}`}
>
{renderOptionBadge(selectedOption)}
{!readOnly && (
<ChevronDown className="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" />
)}
</div>
{isEditing && (
<div className="absolute z-50 top-full left-0 mt-1 w-full min-w-[150px] bg-white border border-gray-200 rounded-lg shadow-lg py-1 max-h-60 overflow-auto">
<div
onClick={() => handleSelect('')}
className="px-3 py-2 text-sm text-gray-500 hover:bg-gray-50 cursor-pointer flex items-center gap-2"
>
<X className="w-3 h-3" /> Clear
</div>
{selectConfig?.options?.map((option: SelectOption) => (
<div
key={option.id}
onClick={() => handleSelect(option.id)}
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center"
>
<span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
</div>
))}
</div>
)}
</div>
)
}
export default SelectField
@@ -0,0 +1,221 @@
import { Check } from 'lucide-react'
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
import type { SelectOption } from '@shumai/dtos'
const SelectMultiField: React.FC<FieldProps<string[]>> = ({
value = [],
config,
onSave,
readOnly,
}) => {
const selectConfig = config?.selectMulti
const containerRef = useRef<HTMLDivElement>(null)
const dropdownRef = useRef<HTMLDivElement>(null)
const [isEditing, setIsEditing] = useState(false)
const [expanded, setExpanded] = useState(false)
const [visibleCount, setVisibleCount] = useState(value.length)
const selectedOptions =
selectConfig?.options?.filter((opt: SelectOption) => (value || []).includes(opt.id)) || []
// Dynamic calculation for how many items fit in one line
useLayoutEffect(() => {
if (isEditing || expanded) {
// When editing or expanded, we technically don't use visibleCount for rendering
// (we render all), but keeping state clean is good.
setVisibleCount(selectedOptions.length)
return
}
if (containerRef.current) {
const containerWidth = containerRef.current.offsetWidth
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
if (context) {
context.font = '12px ui-sans-serif, system-ui, sans-serif'
let currentWidth = 0
let count = 0
const moreBadgeWidth = 28
// We use a small buffer to be safe
const maxAvailableWidth = containerWidth - moreBadgeWidth
for (let i = 0; i < selectedOptions.length; i++) {
const textWidth = context.measureText(selectedOptions[i].displayName).width
const badgeWidth = textWidth + 16 + 4 // 16px padding, 4px gap
if (currentWidth + badgeWidth > maxAvailableWidth && i < selectedOptions.length - 1) {
break
}
if (i === selectedOptions.length - 1) {
if (currentWidth + badgeWidth <= containerWidth) {
count++
}
break
}
currentWidth += badgeWidth
count++
}
setVisibleCount(count)
}
}
}, [selectedOptions, isEditing, expanded, value])
// Click outside to close dropdown or expanded view
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
// Check if click is outside both the main container and the dropdown
const isOutsideDropdown =
!dropdownRef.current || !dropdownRef.current.contains(event.target as Node)
const isOutsideContainer =
!containerRef.current || !containerRef.current.contains(event.target as Node)
if (isOutsideDropdown && isOutsideContainer) {
if (isEditing) {
setIsEditing(false)
}
if (expanded) {
setExpanded(false)
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isEditing, expanded])
const toggleOption = (optionId: string) => {
const currentVal = value || []
let newVal
if (currentVal.includes(optionId)) {
newVal = currentVal.filter((id) => id !== optionId)
} else {
newVal = [...currentVal, optionId]
}
onSave(newVal)
}
const handlePlaceholderClick = (e: React.MouseEvent) => {
e.stopPropagation()
if (isEditing) return
// "if there is hidden items, first click will expand"
const hiddenCount = selectedOptions.length - visibleCount
if (!expanded && hiddenCount > 0) {
setExpanded(true)
} else {
// "if there is no hidden items, will change to edit mode"
if (!readOnly) {
setIsEditing(true)
}
}
}
const handleOverlayClick = (e: React.MouseEvent) => {
e.stopPropagation()
// "second click (on expanded) will change to edit mode"
if (!readOnly) {
setIsEditing(true)
}
}
const hiddenCount = selectedOptions.length - visibleCount
return (
<div className="relative w-full">
{/* Placeholder Display Mode */}
<div
ref={containerRef}
onClick={handlePlaceholderClick}
className={`w-full px-1 py-1 flex flex-wrap gap-1 rounded border border-transparent transition-all box-border h-[32px] overflow-hidden ${
!readOnly || hiddenCount > 0
? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200'
: ''
}`}
>
{selectedOptions.length === 0 && (
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
)}
{/* Render visible items */}
{selectedOptions.slice(0, visibleCount).map((option: SelectOption) => (
<span
key={option.id}
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[22px]"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
))}
{hiddenCount > 0 && (
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-600 h-[22px]">
+{hiddenCount}
</span>
)}
</div>
{/* Expanded Overlay Mode */}
{expanded && !isEditing && (
<div
onClick={handleOverlayClick}
className={`absolute top-0 left-0 w-full px-1 py-1 flex flex-wrap gap-1 bg-white rounded border border-blue-500 shadow-lg z-50 min-h-[32px] h-auto ${
!readOnly ? 'cursor-pointer' : ''
}`}
>
{selectedOptions.length === 0 && (
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
)}
{selectedOptions.map((option: SelectOption) => (
<span
key={option.id}
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[22px]"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
))}
</div>
)}
{/* Edit Mode Dropdown */}
{isEditing && (
<div
ref={dropdownRef}
className="absolute z-50 top-full left-0 mt-1 w-64 bg-white border border-gray-200 rounded-lg shadow-xl max-h-60 overflow-auto"
>
{selectConfig?.options?.map((option: SelectOption) => {
const isSelected = (value || []).includes(option.id)
return (
<div
key={option.id}
onClick={() => toggleOption(option.id)}
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between"
>
<span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
{isSelected && <Check className="w-4 h-4 text-blue-500" />}
</div>
)
})}
</div>
)}
</div>
)
}
export default SelectMultiField
@@ -0,0 +1,63 @@
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) => {
const [isEditing, setIsEditing] = useState(false)
const [localValue, setLocalValue] = useState(value || '')
const inputRef = useRef<HTMLInputElement>(null)
// Sync with prop updates
useEffect(() => {
setLocalValue(value || '')
}, [value])
useEffect(() => {
if (isEditing && inputRef.current) {
inputRef.current.focus()
}
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const handleBlur = () => {
setIsEditing(false)
onSave(localValue)
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
inputRef.current?.blur()
}
}
if (isEditing) {
return (
<input
ref={inputRef}
type="text"
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm"
/>
)
}
return (
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded truncate border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
}`}
>
{value || <span className="text-gray-400 italic">Empty</span>}
</div>
)
}
export default TextField
@@ -0,0 +1,42 @@
import type { FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import React from 'react'
interface FieldProps {
value: boolean
config: MetadataFieldInfo['config']
onSave: (value: boolean) => void
readOnly?: boolean
}
const ToggleField: React.FC<FieldProps> = ({ value, onSave, readOnly }) => {
// Toggle is instant edit, doesn't really have a separate "Edit mode" UI structure other than interaction.
const handleToggle = (e: React.MouseEvent) => {
e.stopPropagation()
if (!readOnly) {
const newValue = !value
onSave(newValue)
}
}
return (
<div
onClick={handleToggle}
className={`flex items-center h-[28px] w-full ${!readOnly ? 'cursor-pointer' : ''}`}
>
<div
className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${
value ? 'bg-green-500' : 'bg-gray-300'
} ${readOnly ? 'opacity-70' : ''}`}
>
<span
className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white transition duration-200 ease-in-out ${
value ? 'translate-x-4.5' : 'translate-x-1'
}`}
style={{ transform: value ? 'translateX(18px)' : 'translateX(4px)' }}
/>
</div>
</div>
)
}
export default ToggleField
@@ -0,0 +1,288 @@
import type { AssetInfo } from '@shumai/dtos'
import type { ShareLinkInfo } from '@shumai/dtos'
import {
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuPortal,
} from '@/ui/components/ui/context-menu'
import {
Download,
Edit,
FolderPlus,
Trash2,
UploadCloud,
History,
FileText,
Link,
Plus,
ArrowRight,
Copy,
} from 'lucide-react'
interface FileBrowserContextMenuProps {
item: AssetInfo | null
selectedIds: Set<string>
onRename: (item: AssetInfo) => void
onDelete: (items: AssetInfo[]) => void
onDownload: (items: AssetInfo[]) => void
onRestore: (items: AssetInfo[]) => void
onNewFolder: (name: string) => void
onUploadFile: () => void
onUploadFolder: () => void
onNewVersion: (item: AssetInfo) => void
onMoveTo: (items: AssetInfo[]) => void
onCopyTo: (items: AssetInfo[]) => void
folders: AssetInfo[]
files: AssetInfo[]
isRecentlyDeleted?: boolean
onOpenAgentsMd?: (item: AssetInfo | null) => void
isShareView?: boolean
onRemoveFromShare?: (items: AssetInfo[]) => void
shareLinks?: ShareLinkInfo[]
onCreateShareLink?: (items: AssetInfo[]) => void
onAddToShareLink?: (shareId: string, items: AssetInfo[]) => void
}
export function FileBrowserContextMenu({
item,
selectedIds,
onRename,
onDelete,
onDownload,
onRestore,
onNewFolder,
onUploadFile,
onUploadFolder,
onNewVersion,
onMoveTo,
onCopyTo,
folders,
files,
isRecentlyDeleted,
onOpenAgentsMd,
isShareView,
onRemoveFromShare,
shareLinks = [],
onCreateShareLink,
onAddToShareLink,
}: FileBrowserContextMenuProps) {
const allItems = [...folders, ...files]
const selectedItems = allItems.filter((i) => selectedIds.has(i.id!))
const isItemSelected = item && selectedIds.has(item.id!)
const itemsToModify = isItemSelected ? selectedItems : item ? [item] : []
const itemsToDelete = itemsToModify
const itemsToRestore = itemsToModify
const handleRename = () => {
if (item) {
onRename(item)
}
}
const handleDelete = () => {
onDelete(itemsToDelete)
}
const handleDownload = () => {
if (isItemSelected) {
onDownload(selectedItems)
} else if (item) {
onDownload([item])
}
}
const handleRestore = () => {
onRestore(itemsToRestore)
}
if (isShareView) {
if (!item) return null
return (
<ContextMenuContent>
<ContextMenuItem
onSelect={() => onRemoveFromShare?.(itemsToModify)}
className="text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
<span>Remove from Share</span>
</ContextMenuItem>
</ContextMenuContent>
)
}
if (isRecentlyDeleted) {
if (!item) {
return null
}
return (
<ContextMenuContent>
<ContextMenuItem onSelect={handleRestore}>
<History className="mr-2 h-4 w-4" />
<span>Restore</span>
</ContextMenuItem>
</ContextMenuContent>
)
}
if (!item) {
// Right-click on empty area
return (
<ContextMenuContent
onCloseAutoFocus={(e) => {
e.preventDefault()
}}
>
<ContextMenuItem onSelect={onUploadFile}>
<UploadCloud className="mr-2 h-4 w-4" />
<span>Upload File</span>
</ContextMenuItem>
<ContextMenuItem onSelect={onUploadFolder}>
<UploadCloud className="mr-2 h-4 w-4" />
<span>Upload Folder</span>
</ContextMenuItem>
<ContextMenuItem
onSelect={() => {
onNewFolder('New Folder')
}}
>
<FolderPlus className="mr-2 h-4 w-4" />
<span>New Folder</span>
</ContextMenuItem>
</ContextMenuContent>
)
}
const contextMenuContent =
isItemSelected && selectedIds.size > 1 ? (
<ContextMenuContent
onCloseAutoFocus={(e) => {
e.preventDefault()
}}
>
<ContextMenuItem onSelect={handleDownload}>
<Download className="mr-2 h-4 w-4" />
<span>Download</span>
</ContextMenuItem>
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
<ArrowRight className="mr-2 h-4 w-4" />
<span>Move to</span>
</ContextMenuItem>
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
<Copy className="mr-2 h-4 w-4" />
<span>Copy to</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleDelete} className="text-destructive">
<Trash2 className="mr-2 h-4 w-4" />
<span>Delete</span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={() => onCreateShareLink?.(itemsToModify)}>
<Plus className="mr-2 h-4 w-4" />
<span>Create Share Link</span>
</ContextMenuItem>
{shareLinks.length > 0 && (
<ContextMenuSub>
<ContextMenuSubTrigger>
<Link className="mr-2 h-4 w-4" />
<span>Add to Share Links</span>
</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent className="w-48">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
>
<span className="truncate">{share.name}</span>
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
)}
</ContextMenuContent>
) : (
<ContextMenuContent
onCloseAutoFocus={(e) => {
e.preventDefault()
}}
>
<ContextMenuItem
onSelect={() => {
handleRename()
}}
>
<Edit className="mr-2 h-4 w-4" />
<span>Rename</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleDownload}>
<Download className="mr-2 h-4 w-4" />
<span>Download</span>
</ContextMenuItem>
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
<ArrowRight className="mr-2 h-4 w-4" />
<span>Move to</span>
</ContextMenuItem>
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
<Copy className="mr-2 h-4 w-4" />
<span>Copy to</span>
</ContextMenuItem>
{(item.type === 'file' || item.type === 'version_stack') && (
<ContextMenuItem onSelect={() => onNewVersion(item)}>
<UploadCloud className="mr-2 h-4 w-4" />
<span>Create new version</span>
</ContextMenuItem>
)}
{item.type === 'folder' && onOpenAgentsMd && (
<ContextMenuItem onSelect={() => onOpenAgentsMd(item)}>
<FileText className="mr-2 h-4 w-4" />
<span>AGENTS.md</span>
</ContextMenuItem>
)}
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleDelete} className="text-destructive">
<Trash2 className="mr-2 h-4 w-4" />
<span>Delete</span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={() => onCreateShareLink?.(itemsToModify)}>
<Plus className="mr-2 h-4 w-4" />
<span>Create Share Link</span>
</ContextMenuItem>
{shareLinks.length > 0 && (
<ContextMenuSub>
<ContextMenuSubTrigger>
<Link className="mr-2 h-4 w-4" />
<span>Add to Share Links</span>
</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent className="w-48">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
>
<span className="truncate">{share.name}</span>
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
)}
</ContextMenuContent>
)
return <>{contextMenuContent}</>
}
@@ -0,0 +1,960 @@
'use client'
import { client } from '@/ui/api/client'
import type { InferRequestType, InferResponseType } from 'hono/client'
import type { AssetInfo } from '@shumai/dtos'
import type { CollectionInfo } from '@shumai/dtos'
import type { SearchCondition, SearchSort } from '@shumai/dtos'
import type { ShareLinkInfo } from '@shumai/dtos'
import type { CreateUploadTaskRequest } from '@shumai/dtos'
import { formatSize } from '@/ui/lib/format'
import { useFieldStore } from '@/ui/stores/fields'
import { useUploadStore } from '@/ui/stores/upload'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Download } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { toast } from 'sonner'
import type { DragState } from '../dnd-types'
import { MoveCopyDialog } from '../move-copy-dialog'
import { FileBrowserContextMenu } from './context-menu'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '../ui/alert-dialog'
import { Button } from '../ui/button'
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
import { FileCard } from './file-card'
import { FileListItem } from './file-list-item'
import { FolderCard } from './folder-card'
import { FileBrowserGridView } from './grid-view'
import { FileBrowserListView } from './list-view'
import { FileBrowserToolbar } from './toolbar'
import { useFileActions } from './use-file-actions'
interface FileBrowserProps {
teamId: string
projectId: string
assetId: string
folders: AssetInfo[]
files: AssetInfo[]
totalFolders?: number
totalFiles?: number
selectedItem: AssetInfo | null
selectedIds: Set<string>
onItemSelect: (item: AssetInfo, event: React.MouseEvent) => void
onItemDoubleClick: (item: AssetInfo) => void
onSaveField: (fileId: string, fieldId: string, value: unknown) => void
displayStyle: 'card' | 'list'
onClearSelection: () => void
fetchNextFoldersPage: () => void
hasNextFoldersPage: boolean
isFetchingNextFoldersPage: boolean
fetchNextFilesPage: () => void
hasNextFilesPage: boolean
isFetchingNextFilesPage: boolean
isRecentlyDeleted?: boolean
filterConditions?: SearchCondition[]
onFilterChange?: (conditions: SearchCondition[]) => void
sort?: SearchSort
onSortChange?: (sort?: SearchSort) => void
dragState?: DragState
isShareView?: boolean
isPublic?: boolean
onRemoveFromShare?: (items: AssetInfo[]) => void
fieldVisibility?: Record<string, boolean>
collection?: CollectionInfo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
rootFolderId?: string
}
type FileWithId = {
file: File
id: string
}
let filesToUpload: FileWithId[] = []
export function FileBrowser({
teamId,
projectId,
assetId,
folders,
files,
totalFolders,
totalFiles,
selectedItem,
selectedIds,
onItemSelect,
onItemDoubleClick,
onSaveField,
displayStyle,
onClearSelection,
fetchNextFoldersPage,
hasNextFoldersPage,
isFetchingNextFoldersPage,
fetchNextFilesPage,
hasNextFilesPage,
isFetchingNextFilesPage,
isRecentlyDeleted,
filterConditions,
onFilterChange,
sort,
onSortChange,
dragState,
isShareView,
isPublic,
onRemoveFromShare,
fieldVisibility,
collection,
onUpdateCollection,
rootFolderId,
}: FileBrowserProps) {
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
const [itemsToMoveCopy, setItemsToMoveCopy] = useState<AssetInfo[]>([])
const queryClient = useQueryClient()
const navigate = useNavigate()
const { data: shareLinksData } = useQuery({
queryKey: ['shares', teamId, projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].shares.$get({
param: { projectId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch share links')
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
},
enabled: !!teamId && !!projectId && !isPublic,
})
const $reparent = client.api.projects[':projectId'].reparent.$post
const { mutate: reparentAssets } = useMutation<
InferResponseType<typeof $reparent, 204>,
Error,
InferRequestType<typeof $reparent>
>({
mutationFn: async (request) => {
const res = await $reparent(request)
if (!res.ok) throw new Error('Failed to move assets')
return null as unknown as InferResponseType<typeof $reparent, 204>
},
})
const $copy = client.api.projects[':projectId'].copy.$post
const { mutate: copyAssets } = useMutation<
InferResponseType<typeof $copy, 204>,
Error,
InferRequestType<typeof $copy>
>({
mutationFn: async (request) => {
const res = await $copy(request)
if (!res.ok) throw new Error('Failed to copy assets')
return null as unknown as InferResponseType<typeof $copy, 204>
},
})
const handleMoveCopyConfirm = async (targetFolderId: string, withComments: boolean) => {
const assetIds = itemsToMoveCopy.map((i) => i.id!)
if (moveCopyMode === 'move') {
reparentAssets(
{
param: { projectId },
json: { newParentId: targetFolderId, assetIds },
},
{
onSuccess: () => {
toast.success(`Successfully moved ${assetIds.length} item(s)`, {
action: {
label: 'Go to folder',
onClick: () => {
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: targetFolderId },
})
},
},
})
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
setMoveCopyMode(null)
setItemsToMoveCopy([])
onClearSelection()
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
},
)
} else {
copyAssets(
{
param: { projectId },
json: { newParentId: targetFolderId, assetIds, withComments },
},
{
onSuccess: () => {
toast.success(`Successfully copied ${assetIds.length} item(s)`, {
action: {
label: 'Go to folder',
onClick: () => {
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: targetFolderId },
})
},
},
})
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
setMoveCopyMode(null)
setItemsToMoveCopy([])
onClearSelection()
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
},
)
}
}
const { mutate: createShareLink } = useMutation({
mutationFn: async (items: AssetInfo[]) => {
const name =
items.length === 1
? items[0].name
: new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
})
const res = await client.api.projects[':projectId'].shares.$post({
param: { projectId },
json: { name },
})
if (!res.ok) throw new Error('Failed to create share link')
const share = await res.json()
// Add assets to the new share link
const assetsRes = await client.api.shares[':shareId'].assets.$post({
param: { shareId: share.id },
json: { assetIds: items.map((i) => i.id!) },
})
if (!assetsRes.ok) throw new Error('Failed to add assets to share link')
return share
},
onSuccess: (share) => {
queryClient.invalidateQueries({ queryKey: ['shares', teamId, projectId] })
toast.success('Share link created', {
action: {
label: 'View',
onClick: () =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: share.id },
}),
},
})
},
})
const { mutate: addToShareLink } = useMutation({
mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => {
const res = await client.api.shares[':shareId'].assets.$post({
param: { shareId },
json: { assetIds: items.map((i) => i.id!) },
})
if (!res.ok) throw new Error('Failed to add assets')
return { shareId }
},
onSuccess: ({ shareId }) => {
toast.success('Added to share link', {
action: {
label: 'View',
onClick: () =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId },
}),
},
})
},
})
const handleCreateShareLink = (items: AssetInfo[]) => {
createShareLink(items)
}
const handleAddToShareLink = (shareId: string, items: AssetInfo[]) => {
addToShareLink({ shareId, items })
}
const {
editingItemId,
setEditingItemId,
handleNewFolder,
handleDelete,
handleRename,
handleRestore,
handleDownload,
handleAction,
onRenameSubmit,
isDeleteDialogOpen,
setIsDeleteDialogOpen,
confirmDelete,
} = useFileActions({
teamId,
projectId,
assetId,
folders,
files,
selectedIds,
})
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
const { mutateAsync: confirmUpload } = useMutation<
InferResponseType<typeof $confirmUpload>,
Error,
InferRequestType<typeof $confirmUpload>
>({
mutationFn: async (request) => {
const res = await $confirmUpload(request)
if (!res.ok) throw new Error('Failed to confirm upload')
return (await res.json()) as InferResponseType<typeof $confirmUpload>
},
})
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
const { mutate: createUploadTaskMutation } = useMutation<
InferResponseType<typeof $createUploadTask>,
Error,
InferRequestType<typeof $createUploadTask>
>({
mutationFn: async (request) => {
const res = await $createUploadTask(request)
if (!res.ok) throw new Error('Failed to create upload task')
return (await res.json()) as InferResponseType<typeof $createUploadTask>
},
onSuccess: async (data) => {
// The RPC client returns an object that we cast to the expected type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await uploadFiles(filesToUpload, data.presignedUrls as any, data.taskId!)
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
},
})
const incrementUploading = useUploadStore((state) => state.increment)
const decrementUploading = useUploadStore((state) => state.decrement)
const { fields } = useFieldStore()
const displayedFields = useMemo(() => {
if (!isShareView) return fields.filter((f) => f.visible)
return fields.filter((f) => fieldVisibility?.[f.id!])
}, [fields, isShareView, fieldVisibility])
const [foldersExpanded, setFoldersExpanded] = React.useState(true)
const [filesExpanded, setFilesExpanded] = React.useState(true)
const fileInputRef = useRef<HTMLInputElement>(null)
const folderInputRef = useRef<HTMLInputElement>(null)
const newVersionInputRef = useRef<HTMLInputElement>(null)
const [targetVersionFileId, setTargetVersionFileId] = useState<string | null>(null)
const fileContextMenu = useRef(false)
const scrollContainerRef = useRef<HTMLDivElement>(null)
const { ref: foldersRef, inView: foldersInView } = useInView()
const { ref: filesRef, inView: filesInView } = useInView()
useEffect(() => {
if (foldersInView && hasNextFoldersPage && !isFetchingNextFoldersPage) {
fetchNextFoldersPage()
}
}, [foldersInView, hasNextFoldersPage, isFetchingNextFoldersPage, fetchNextFoldersPage])
useEffect(() => {
if (filesInView && hasNextFilesPage && !isFetchingNextFilesPage) {
fetchNextFilesPage()
}
}, [filesInView, hasNextFilesPage, isFetchingNextFilesPage, fetchNextFilesPage])
const foldersSize = folders.reduce((acc, f) => acc + (f.sizeByte || 0), 0)
const filesSize = files.reduce((acc, f) => acc + (f.sizeByte || 0), 0)
const formatCount = (count: number, isFile: boolean) => {
const isNameFilter = filterConditions?.some(
(c) => c.field === 'name' && c.operator === 'contains',
)
if (isNameFilter && count === 10001) {
return `10000+ ${isFile ? 'Asset' : 'Folder'}s`
}
return `${count} ${isFile ? 'Asset' : 'Folder'}${count !== 1 ? 's' : ''}`
}
const handleEmptyAreaClick = (e: React.MouseEvent) => {
const target = e.target as HTMLElement
// Clear selection if we didn't click on a card/row, button, or other interactive element
// Also ignore clicks on context menu items (which might bubble via React portals)
if (target.closest('[role="menuitem"]') || target.closest('[data-radix-menu-content]')) {
return
}
if (
target === e.currentTarget ||
target.closest('.empty-area') ||
(!target.closest('.group') &&
!target.closest('button') &&
!target.closest('a') &&
!target.closest('input'))
) {
onClearSelection()
setEditingItemId(null)
}
}
const onContextMenu = (_e: React.MouseEvent, item?: AssetInfo) => {
if (item === undefined) {
// Two possibilities when item is undefined:
// 1. User right-clicked on empty space → fileContextMenu should be false.
// 2. A right-click on a file/folder was already handled above → fileContextMenu is true.
// In that case, toggle it off; otherwise clear the selected item.
if (fileContextMenu.current) {
fileContextMenu.current = false
} else {
setContextMenuItem(null)
}
} else {
// User right-clicked a file or folder.
// Mark that this click is for a file context menu, store the item,
// and let the event bubble so the empty-area handler manages positioning.
fileContextMenu.current = true
setContextMenuItem(item ?? null)
return
}
}
const renderItem = (item: AssetInfo, columnSizing?: Record<string, number>) => {
const effectiveType = item.type === 'symlink' ? item.targetType || 'file' : item.type
const props = {
teamId,
item: item,
isSelected: selectedItem?.id === item.id,
isChecked: selectedIds.has(item.id!),
isEditing: editingItemId === item.id,
onSelect: onItemSelect,
onDoubleClick: onItemDoubleClick,
onContextMenu: onContextMenu,
onDragStart: () => {}, // Handled by dnd-kit
onDrop: () => {}, // Handled by dnd-kit
onRename: (newName: string) => onRenameSubmit(item, newName),
onFinishEditing: () => setEditingItemId(null),
onSaveField: (fieldId: string, value: unknown) => {
onSaveField(item.id!, fieldId, value)
},
dragState,
onAction: (action: string, item: AssetInfo) => {
if (isShareView) {
if (action === 'remove-from-share') {
const isSelected = selectedIds.has(item.id!)
const targetItems = isSelected
? [...folders, ...files].filter((i) => selectedIds.has(i.id!))
: [item]
onRemoveFromShare?.(targetItems)
}
return
}
handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item)
},
isRecentlyDeleted,
selectedCount: selectedIds.size,
isShareView,
fields: displayedFields,
}
if (displayStyle === 'card') {
if (effectiveType === 'folder') return <FolderCard key={item.id} {...props} />
if (effectiveType === 'file' || effectiveType === 'version_stack')
return <FileCard key={item.id} {...props} />
}
return <FileListItem key={item.id} {...props} columnSizing={columnSizing} />
}
const selectedCount = selectedIds.size
const selectedFolders = Array.from(selectedIds).filter((id) =>
folders.find((item) => item.id === id),
).length
const selectedFiles = Array.from(selectedIds).filter((id) =>
files.find((item) => item.id === id),
).length
const handleUploadFilesClick = () => {
fileInputRef.current?.click()
}
const handleUploadFolderClick = () => {
folderInputRef.current?.click()
}
const uploadFiles = async (
files: FileWithId[],
presignedUrls: { id?: string; url?: string; fileId?: string }[],
taskId: string,
) => {
const uploadUrlMap = presignedUrls?.reduce(
(
acc: Record<string, { url: string; fileId: string }>,
item: { id?: string; url?: string; fileId?: string },
) => {
if (item.id) {
acc[item.id] = {
url: item.url || '',
fileId: item.fileId || '',
}
}
return acc
},
{},
)
if (!uploadUrlMap) return
const concurrencyLimit = 5
const filesToUpload = [...files]
const uploadNext = async () => {
while (filesToUpload.length > 0) {
const file = filesToUpload.shift()
if (file) {
const uploadInfo = uploadUrlMap[file.id]
if (uploadInfo && uploadInfo.url) {
incrementUploading()
try {
try {
const resp = await fetch(uploadInfo.url, {
method: 'PUT',
body: file.file,
headers: {
'Content-Type': file.file.type,
},
})
if (resp.ok) {
await confirmUpload({
param: { teamId: teamId, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
},
})
} else {
toast.error(`Failed to upload file: ${file.file.name}`)
await confirmUpload({
param: { teamId: teamId, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
errorMessage: `upload failed with status: ${resp.status}`,
},
})
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
return
}
} catch (error) {
toast.error(`Failed to upload file: ${file.file.name}`)
await confirmUpload({
param: { teamId: teamId, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
},
})
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
return
}
} finally {
decrementUploading()
}
}
}
}
}
const activeUploaders = Array(concurrencyLimit)
.fill(null)
.map(() => uploadNext())
await Promise.all(activeUploaders)
}
const processAndUploadFiles = useCallback(
(files: FileList | File[], overrideParentId?: string) => {
if (!files || files.length === 0) return
const fileWithIds: FileWithId[] = []
const root: CreateUploadTaskRequest['files'] = []
const directories = new Map<string, CreateUploadTaskRequest['files']>()
for (const file of files) {
const path = (file.webkitRelativePath || file.name).split('/')
if (path.some((part) => part.startsWith('.'))) {
continue
}
const fileName = path.pop()!
let currentLevel = root
let currentPath = ''
for (const dir of path) {
currentPath = `${currentPath}/${dir}`
if (!directories.has(currentPath)) {
const newDir: CreateUploadTaskRequest['files'] = []
const parentDir = {
name: dir,
type: 'folder' as const,
id: crypto.randomUUID(),
children: newDir,
size: 0,
}
currentLevel.push(parentDir)
directories.set(currentPath, newDir)
currentLevel = newDir
} else {
currentLevel = directories.get(currentPath)!
}
}
const fileWithId = { file, id: crypto.randomUUID() }
fileWithIds.push(fileWithId)
currentLevel.push({
name: fileName,
size: file.size,
type: 'file',
id: fileWithId.id,
children: [],
mediaType: file.type,
})
}
filesToUpload = fileWithIds
createUploadTaskMutation({
param: { teamId: teamId },
json: {
parentId: overrideParentId || assetId,
files: root,
},
})
},
[assetId, createUploadTaskMutation, teamId],
)
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
processAndUploadFiles(event.target.files!)
}
const handleNewVersionClick = (item: AssetInfo) => {
setTargetVersionFileId(item.id!)
newVersionInputRef.current?.click()
}
const handleNewVersionFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && targetVersionFileId) {
processAndUploadFiles(event.target.files, targetVersionFileId)
setTargetVersionFileId(null)
// Reset input
event.target.value = ''
}
}
const handlePaste = useCallback(
(e: React.ClipboardEvent | ClipboardEvent) => {
if (isShareView) return
if (!e.clipboardData) return
const items = e.clipboardData.items
const files: File[] = []
for (let i = 0; i < items.length; i++) {
const item = items[i]
if (item.kind === 'file') {
const file = item.getAsFile()
if (file) {
// If it's a raw image without a real name (e.g. "image.png" from clipboard image)
if (file.name === 'image.png' && file.type.startsWith('image/')) {
const timestamp = new Date()
.toISOString()
.replace(/[:.]/g, '')
.replace('T', '_')
.substring(0, 15)
const ext = file.type.split('/')[1] || 'png'
const newFile = new File([file], `pasted_image_${timestamp}.${ext}`, {
type: file.type,
})
files.push(newFile)
} else {
files.push(file)
}
}
}
}
if (files.length > 0) {
processAndUploadFiles(files)
}
},
[processAndUploadFiles],
)
// Add global paste listener if browser is active
useEffect(() => {
const onGlobalPaste = (e: ClipboardEvent) => {
if (isShareView) return
// Don't intercept if user is typing in an input
if (
document.activeElement &&
(document.activeElement.tagName === 'INPUT' ||
document.activeElement.tagName === 'TEXTAREA' ||
(document.activeElement as HTMLElement).isContentEditable)
) {
return
}
handlePaste(e)
}
window.addEventListener('paste', onGlobalPaste)
return () => {
window.removeEventListener('paste', onGlobalPaste)
}
}, [handlePaste, isShareView])
const renderContent = () => {
return (
<ContextMenu modal={false}>
<ContextMenuTrigger asChild disabled={isShareView || isPublic}>
<div
className="flex-1 bg-background relative flex flex-col min-h-0 overflow-hidden"
onContextMenu={(e) => onContextMenu(e)}
>
{!isShareView && !isPublic && onFilterChange && onSortChange && (
<FileBrowserToolbar
teamId={teamId}
projectId={projectId}
assetId={assetId}
fields={fields || []}
filterConditions={filterConditions || []}
onFilterChange={onFilterChange}
sort={sort}
onSortChange={onSortChange}
isRecentlyDeleted={isRecentlyDeleted}
collection={collection}
onUpdateCollection={onUpdateCollection}
rootFolderId={rootFolderId}
/>
)}
<div
ref={scrollContainerRef}
className="flex-1 overflow-y-auto min-h-0 relative flex flex-col"
>
{displayStyle === 'list' ? (
<FileBrowserListView
folders={folders}
files={files}
totalFolders={totalFolders}
totalFiles={totalFiles}
selectedItem={selectedItem}
selectedIds={selectedIds}
displayedFields={displayedFields}
onItemSelect={onItemSelect}
onItemDoubleClick={onItemDoubleClick}
renderItem={renderItem}
foldersExpanded={foldersExpanded}
setFoldersExpanded={setFoldersExpanded}
filesExpanded={filesExpanded}
setFilesExpanded={setFilesExpanded}
foldersRef={foldersRef}
filesRef={filesRef}
hasNextFoldersPage={hasNextFoldersPage}
hasNextFilesPage={hasNextFilesPage}
formatCount={formatCount}
formatSize={formatSize}
foldersSize={foldersSize}
filesSize={filesSize}
handleEmptyAreaClick={handleEmptyAreaClick}
dragState={dragState}
sort={sort}
/>
) : (
<FileBrowserGridView
folders={folders}
files={files}
totalFolders={totalFolders}
totalFiles={totalFiles}
renderItem={renderItem}
foldersExpanded={foldersExpanded}
setFoldersExpanded={setFoldersExpanded}
filesExpanded={filesExpanded}
setFilesExpanded={setFilesExpanded}
foldersRef={foldersRef}
filesRef={filesRef}
hasNextFoldersPage={hasNextFoldersPage}
hasNextFilesPage={hasNextFilesPage}
formatCount={formatCount}
formatSize={formatSize}
foldersSize={foldersSize}
filesSize={filesSize}
handleEmptyAreaClick={handleEmptyAreaClick}
dragState={dragState}
sort={sort}
/>
)}
{(isFetchingNextFoldersPage || isFetchingNextFilesPage) && (
<div className="flex justify-center items-center p-4">
<p>Loading more...</p>
</div>
)}
{folders.length === 0 &&
files.length === 0 &&
!isFetchingNextFoldersPage &&
!isFetchingNextFilesPage && (
<div className="empty-area flex h-full items-center justify-center text-sm text-muted-foreground">
This folder is empty
</div>
)}
</div>
{selectedCount > 0 && (
<div className="border-t border-border bg-card px-4 py-3 flex items-center justify-between shrink-0">
<div className="text-sm text-muted-foreground">
{selectedFolders > 0 && selectedFiles > 0 && (
<span>
{selectedFolders} folder
{selectedFolders !== 1 ? 's' : ''}, {selectedFiles} file
{selectedFiles !== 1 ? 's' : ''} selected
</span>
)}
{selectedFolders > 0 && selectedFiles === 0 && (
<span>
{selectedFolders} folder
{selectedFolders !== 1 ? 's' : ''} selected
</span>
)}
{selectedFolders === 0 && selectedFiles > 0 && (
<span>
{selectedFiles} file{selectedFiles !== 1 ? 's' : ''} selected
</span>
)}
</div>
<Button
variant="ghost"
size="sm"
onClick={() =>
handleDownload([...folders, ...files].filter((i) => selectedIds.has(i.id!)))
}
className="gap-2"
>
<Download className="h-4 w-4" />
Download
</Button>
</div>
)}
</div>
</ContextMenuTrigger>
<FileBrowserContextMenu
item={contextMenuItem}
selectedIds={selectedIds}
folders={folders}
files={files}
onRename={handleRename}
onDelete={handleDelete}
onDownload={handleDownload}
onNewFolder={handleNewFolder}
onUploadFile={handleUploadFilesClick}
onUploadFolder={handleUploadFolderClick}
onNewVersion={handleNewVersionClick}
onMoveTo={(items) => {
setItemsToMoveCopy(items)
setMoveCopyMode('move')
}}
onCopyTo={(items) => {
setItemsToMoveCopy(items)
setMoveCopyMode('copy')
}}
onRestore={handleRestore}
isRecentlyDeleted={isRecentlyDeleted}
shareLinks={shareLinksData?.data ?? []}
onCreateShareLink={handleCreateShareLink}
onAddToShareLink={handleAddToShareLink}
/>
</ContextMenu>
)
}
return (
<>
<input
type="file"
ref={fileInputRef}
multiple
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<input
type="file"
ref={folderInputRef}
multiple
/* @ts-expect-error - webkitdirectory is not in the type definition */
webkitdirectory="true"
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<input
type="file"
ref={newVersionInputRef}
style={{ display: 'none' }}
onChange={handleNewVersionFileChange}
/>
{renderContent()}
{moveCopyMode && (
<MoveCopyDialog
isOpen={!!moveCopyMode}
onClose={() => setMoveCopyMode(null)}
onConfirm={handleMoveCopyConfirm}
mode={moveCopyMode}
teamId={teamId}
currentProjectId={projectId}
/>
)}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Asset?</AlertDialogTitle>
<AlertDialogDescription>
Deleted items can be recovered for 30 days before being permanently deleted.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
confirmDelete()
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
@@ -0,0 +1,361 @@
import type { AssetInfo, FieldValueInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useQuery } from '@tanstack/react-query'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { formatTimeAgo } from '@/ui/lib/time'
import { useDraggable, useDroppable } from '@dnd-kit/react'
import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { cn } from '@/ui/lib/utils'
import type { DragState } from '../dnd-types'
import FieldRenderer from '../field-renderer'
import { FilePreview } from './file-preview'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import { Checkbox } from '@/ui/components/ui/checkbox'
import { EditableText } from '@/ui/components/ui/editable-text'
import { Skeleton } from '@/ui/components/ui/skeleton'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
interface FileCardProps {
teamId?: string
item: AssetInfo
isSelected: boolean
isChecked: boolean
isEditing: boolean
onSelect: (item: AssetInfo, event: React.MouseEvent) => void
onDoubleClick: (item: AssetInfo) => void
onContextMenu: (e: React.MouseEvent, item: AssetInfo) => void
// Deprecated manual drag handlers replaced by dnd-kit
onDragStart: (item: AssetInfo) => void
onDrop: (target: AssetInfo) => void
onRename: (newName: string) => void
onFinishEditing: () => void
onSaveField: (fieldId: string, value: unknown) => void
dragState?: DragState
disabled?: boolean
onAction?: (
action: 'rename' | 'delete' | 'download' | 'restore' | 'remove-from-share',
item: AssetInfo,
) => void
isRecentlyDeleted?: boolean
selectedCount?: number
fields: MetadataFieldInfo[]
isShareView?: boolean
}
export function FileCard({
teamId,
item,
isSelected,
isChecked,
isEditing,
onSelect,
onDoubleClick,
onContextMenu,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onDragStart: _onDragStart,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onDrop: _onDrop,
onRename,
onFinishEditing,
onSaveField,
dragState,
disabled,
onAction,
isRecentlyDeleted,
selectedCount,
fields,
isShareView,
}: FileCardProps) {
const [name, setName] = useState(item.name)
const inputRef = useRef<HTMLInputElement>(null)
const shouldPoll =
(item.type === 'file' || item.type === 'version_stack') &&
!!teamId &&
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
const { data: polledItem } = useQuery({
queryKey: ['file', teamId, item.id],
queryFn: async () => {
const res = await client.api.files[':fileId'].$get({
param: { fileId: item.id || '' },
})
if (!res.ok) throw new Error('failed to fetch file')
return (await res.json()) as unknown as AssetInfo
},
enabled: shouldPoll,
refetchInterval: (query: unknown) => {
const data = (query as { state: { data: { status?: string } } }).state.data
return data?.status === 'processed' ? false : 1000
},
})
const displayItem = polledItem || item
// dnd-kit hooks
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
id: `browser:${displayItem.id!}`,
data: {
type: 'file',
id: displayItem.id,
item: displayItem,
},
disabled: disabled,
})
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
id: `browser:${displayItem.id!}`,
data: {
type: 'file',
id: displayItem.id,
item: displayItem,
},
})
// Combine refs
const setNodeRef = (node: HTMLElement | null) => {
setDraggableRef(node)
setDroppableRef(node)
}
// Determine if this item is being dragged (either directly or as part of selection)
const isBeingDragged =
isDraggableDragging || (dragState?.draggedIds.has(displayItem.id!) ?? false)
// Determine if this is a valid drop target
// File target is valid ONLY if dragging 1 item AND it is a file (version stack)
// And strictly, we shouldn't drop on ourselves
const isValidDropTarget = useMemo(() => {
if (!dragState?.isActive) return false
if (dragState.draggedIds.has(displayItem.id!)) return false // Can't drop on self
if (dragState.hasFolders) return false // Can't drag folders onto file
if (dragState.itemCount !== 1) return false // Can't drag multiple files onto file
return true
}, [dragState, displayItem.id])
const showDropFeedback = isOver && isValidDropTarget
// We only gray out the original item, drag overlay will show the "ghost"
const opacity = isBeingDragged ? 0.5 : 1
const itemFieldValueMap = useMemo(() => {
return (displayItem.fieldValues || []).reduce(
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
acc[val.fieldId!] = val
return acc
},
{} as Record<string, FieldValueInfo>,
)
}, [displayItem.fieldValues])
useEffect(() => {
if (isEditing) {
// Use a longer timeout to ensure the context menu has closed and
// the DOM has stabilized before focusing. Radix focus restoration
// can sometimes conflict with immediate focus calls.
const timeoutId = setTimeout(() => {
inputRef.current?.focus()
inputRef.current?.select()
}, 150)
return () => clearTimeout(timeoutId)
}
}, [isEditing])
// Reset name if item changes
useEffect(() => {
setName(displayItem.name)
}, [displayItem.name])
const handleClick = (e: React.MouseEvent) => {
onSelect(displayItem, e)
}
const handleRename = () => {
if (name !== displayItem.name) {
onRename(name || '')
}
onFinishEditing()
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleRename()
}
if (e.key === 'Escape') {
setName(displayItem.name || '')
onFinishEditing()
}
}
return (
<div
ref={setNodeRef}
style={{ opacity }}
onClick={handleClick}
onDoubleClick={() => onDoubleClick(displayItem)}
onContextMenu={(e) => onContextMenu(e, displayItem)}
onMouseDown={(e) => {
if (e.shiftKey) {
e.preventDefault()
}
}}
className={cn(
'group relative flex cursor-pointer select-none flex-col overflow-hidden rounded-xl border border-border bg-card transition-all hover:border-primary/50 h-full',
isSelected && 'ring-2 ring-primary',
showDropFeedback && 'border-primary ring-2 ring-primary',
)}
>
<div className="absolute left-2 top-2 z-10">
<Checkbox
checked={isChecked}
onCheckedChange={() => {}}
onClick={(e) => {
e.stopPropagation()
onSelect(displayItem, e)
}}
className="h-4 w-4 bg-white/20 dark:bg-white/20 border-2 data-[state=checked]:bg-primary data-[state=checked]:border-primary border-foreground/15"
/>
</div>
{displayItem.versionStack && (
<Badge className="absolute right-2 top-2 z-10">
v
{displayItem.versionStack.versions.find((v) => v.id === displayItem.id)?.version ??
displayItem.versionStack.versions.length}
</Badge>
)}
<div className="relative aspect-square overflow-hidden bg-muted/30">
{displayItem.status === 'uploading' ||
displayItem.status === 'processing' ||
displayItem.status === 'uploaded' ? (
<div className="flex h-full w-full items-center justify-center bg-background/50">
<Skeleton className="absolute inset-0 h-full w-full" />
<span className="z-10 font-medium capitalize text-muted-foreground">
{displayItem.status === 'uploaded' ? 'Processing' : displayItem.status}
</span>
</div>
) : (
<FilePreview item={displayItem} />
)}
</div>
<div className="flex items-center justify-between gap-2 p-3">
<div className="min-w-0 flex-1">
<EditableText
ref={inputRef}
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={handleRename}
onKeyDown={handleKeyDown}
disabled={!isEditing}
className="h-auto p-0 text-sm text-foreground"
/>
<p className="text-sm text-muted-foreground">
{displayItem.createdAt && formatTimeAgo(displayItem.createdAt)} by{' '}
{displayItem.creator?.name}
</p>
</div>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button
size="icon-sm"
variant="ghost"
className="cursor-pointer"
onClick={(e) => e.stopPropagation()}
>
<MoreHorizontal className="h-4 w-4 text-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isShareView ? (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('remove-from-share', item)
}}
className="text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
<span>Remove from Share</span>
</DropdownMenuItem>
) : isRecentlyDeleted ? (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('restore', item)
}}
>
<History className="mr-2 h-4 w-4" />
<span>Restore</span>
</DropdownMenuItem>
) : (
<>
{(!isChecked || (selectedCount || 0) <= 1) && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('rename', item)
}}
>
<Edit className="mr-2 h-4 w-4" />
<span>Rename</span>
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('download', item)
}}
>
<Download className="mr-2 h-4 w-4" />
<span>Download</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('delete', item)
}}
className="text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
<span>Delete</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
{fields && fields.length > 0 && (
<div className="space-y-2 border-t p-3 mx-2">
{fields.map((field) => (
<div key={field.id} className="space-y-1">
<label className="text-xs text-muted-foreground tracking-wide">
{field.config?.name}
</label>
<div className="min-h-[28px]">
<FieldRenderer
config={field.config}
value={itemFieldValueMap[field.id!]?.value}
onSave={(val) => onSaveField(field.id!, val)}
readOnly={field.readOnly}
/>
</div>
</div>
))}
</div>
)}
</div>
)
}
@@ -0,0 +1,286 @@
import type { AssetInfo, FieldValueInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useQuery } from '@tanstack/react-query'
import { useDraggable } from '@dnd-kit/react'
import { File, Folder, MoreVertical } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { cn } from '@/ui/lib/utils'
import type { DragState } from '../dnd-types'
import FieldRenderer from '../field-renderer'
import { Badge } from '@/ui/components/ui/badge'
import { Checkbox } from '@/ui/components/ui/checkbox'
import { EditableText } from '@/ui/components/ui/editable-text'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
interface FileListItemProps {
teamId?: string
item: AssetInfo
isSelected: boolean
isChecked: boolean
isEditing: boolean
onSelect: (item: AssetInfo, event: React.MouseEvent) => void
onDoubleClick: (item: AssetInfo) => void
onContextMenu: (e: React.MouseEvent, item: AssetInfo) => void
onDragStart: (item: AssetInfo) => void
onDrop: (target: AssetInfo) => void
onRename: (newName: string) => void
onFinishEditing: () => void
onSaveField: (fieldId: string, value: unknown) => void
dragState?: DragState
disabled?: boolean
fields: MetadataFieldInfo[]
columnSizing?: Record<string, number>
}
export function FileListItem({
teamId,
item,
isSelected,
isChecked,
isEditing,
onSelect,
onDoubleClick,
onContextMenu,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onDragStart: _onDragStart,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onDrop: _onDrop,
onRename,
onFinishEditing,
onSaveField,
dragState,
disabled,
fields,
columnSizing,
}: FileListItemProps) {
const [name, setName] = useState(item.name)
const inputRef = useRef<HTMLInputElement>(null)
const shouldPoll =
(item.type === 'file' || item.type === 'version_stack') &&
!!teamId &&
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
const { data: polledItem } = useQuery({
queryKey: ['file', teamId, item.id],
queryFn: async () => {
const res = await client.api.files[':fileId'].$get({
param: { fileId: item.id || '' },
})
if (!res.ok) throw new Error('failed to fetch file')
return (await res.json()) as unknown as AssetInfo
},
enabled: shouldPoll,
refetchInterval: (query: unknown) => {
const data = (query as { state: { data: { status?: string } } }).state.data
return data?.status === 'processed' ? false : 1000
},
})
const displayItem = polledItem || item
// dnd-kit hooks
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
id: `browser:${displayItem.id!}`,
data: {
type: displayItem.type === 'folder' ? 'folder' : 'file',
id: displayItem.id,
item: displayItem,
},
disabled: disabled,
})
const isBeingDragged =
isDraggableDragging || (dragState?.draggedIds.has(displayItem.id!) ?? false)
const opacity = isBeingDragged ? 0.5 : 1
const itemFieldValueMap = useMemo(() => {
return (displayItem.fieldValues || []).reduce(
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
acc[val.fieldId!] = val
return acc
},
{} as Record<string, FieldValueInfo>,
)
}, [displayItem.fieldValues])
useEffect(() => {
if (isEditing) {
// Use a longer timeout to ensure the context menu has closed and
// the DOM has stabilized before focusing. Radix focus restoration
// can sometimes conflict with immediate focus calls.
const timeoutId = setTimeout(() => {
inputRef.current?.focus()
inputRef.current?.select()
}, 150)
return () => clearTimeout(timeoutId)
}
}, [isEditing])
useEffect(() => {
setName(displayItem.name)
}, [displayItem.name])
const formatSize = (size?: number) => {
if (!size) return '-'
if (size < 1024) return `${size} B`
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
return `${(size / (1024 * 1024)).toFixed(1)} MB`
}
const formatDate = (date?: string) => {
if (!date) return '-'
return new Date(date).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
})
}
const handleClick = (e: React.MouseEvent) => {
onSelect(displayItem, e)
}
const handleRename = () => {
if (name !== displayItem.name) {
onRename(name || '')
}
onFinishEditing()
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleRename()
}
if (e.key === 'Escape') {
setName(displayItem.name || '')
onFinishEditing()
}
}
return (
<tr
ref={setDraggableRef}
style={{ opacity }}
onClick={handleClick}
onDoubleClick={() => onDoubleClick(displayItem)}
onContextMenu={(e) => onContextMenu(e, displayItem)}
onMouseDown={(e) => {
if (e.shiftKey) {
e.preventDefault()
}
}}
className="group cursor-pointer select-none transition-colors whitespace-nowrap"
>
<td
className={cn(
'px-4 py-2 sticky left-0 z-10 transition-colors border-r',
isSelected ? 'bg-muted' : 'bg-card group-hover:bg-muted',
)}
style={{
width: columnSizing?.['name'] || 300,
minWidth: columnSizing?.['name'] || 300,
}}
>
<div className="flex items-center gap-2 overflow-hidden">
<Checkbox
checked={isChecked}
onCheckedChange={() => {}}
onClick={(e) => {
e.stopPropagation()
onSelect(displayItem, e)
}}
className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
/>
<div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
{displayItem.preview?.thumbnailUrl ? (
<img
src={displayItem.preview.thumbnailUrl}
alt=""
className="w-full h-full object-cover"
/>
) : displayItem.type === 'folder' ? (
<Folder className="h-4 w-4 text-primary" />
) : (
<File className="h-4 w-4 text-muted-foreground" />
)}
</div>
<EditableText
ref={inputRef}
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={handleRename}
onKeyDown={handleKeyDown}
disabled={!isEditing}
className="h-auto p-0 text-sm font-medium text-foreground truncate"
/>
{displayItem.versionStack && (
<Badge variant="outline" className="px-1 py-0 text-xs shrink-0">
v
{displayItem.versionStack.versions.find((v) => v.id === displayItem.id)?.version ??
displayItem.versionStack.versions.length}
</Badge>
)}
</div>
</td>
<td
className="px-4 py-2 text-sm text-muted-foreground truncate"
style={{
width: columnSizing?.['size'] || 100,
minWidth: columnSizing?.['size'] || 100,
}}
>
{displayItem.type === 'folder' ? '-' : formatSize(displayItem.sizeByte)}
</td>
<td
className="px-4 py-2"
style={{
width: columnSizing?.['modified'] || 200,
minWidth: columnSizing?.['modified'] || 200,
}}
>
<div className="flex items-center justify-between overflow-hidden">
<span className="text-sm text-muted-foreground truncate">
{formatDate(displayItem.updatedAt)}
</span>
<button
onClick={(e) => {
e.stopPropagation()
const rect = (e.target as HTMLElement).getBoundingClientRect()
const contextEvent = new MouseEvent(e.nativeEvent.type, {
bubbles: true,
cancelable: true,
clientX: rect.left,
clientY: rect.bottom,
}) as unknown as React.MouseEvent<Element, MouseEvent>
onContextMenu(contextEvent, displayItem)
}}
className="opacity-0 shrink-0 transition-opacity group-hover:opacity-100 ml-2"
>
<MoreVertical className="h-4 w-4 text-muted-foreground hover:text-foreground" />
</button>
</div>
</td>
{displayItem.type === 'file' &&
fields.map((field) => (
<td
key={field.id}
className="px-4 py-2 truncate"
style={{
width: columnSizing?.[field.id!] || 150,
minWidth: columnSizing?.[field.id!] || 150,
}}
>
<FieldRenderer
config={field.config}
value={itemFieldValueMap[field.id!]?.value}
onSave={(val) => onSaveField(field.id!, val)}
readOnly={field.readOnly}
/>
</td>
))}
</tr>
)
}
@@ -0,0 +1,62 @@
import { File, Folder } from 'lucide-react'
import { SpriteScrubber } from '../sprite-scrubber'
type FilePreviewItem = {
type?: string | null
preview?: {
mediaType?: string | null
spriteUrl?: string
thumbnailUrl?: string
originalWidth?: number
originalHeight?: number
} | null
}
interface FilePreviewProps {
item: FilePreviewItem
}
export const FilePreview = ({ item }: FilePreviewProps) => {
const isVideoWithSprite =
item.preview?.mediaType?.startsWith('video/') &&
item.preview.spriteUrl &&
item.preview.thumbnailUrl &&
item.preview.originalWidth &&
item.preview.originalHeight
if (isVideoWithSprite && item.preview) {
return (
<SpriteScrubber
spriteUrl={item.preview.spriteUrl!}
thumbnailUrl={item.preview.thumbnailUrl!}
videoWidth={item.preview.originalWidth!}
videoHeight={item.preview.originalHeight!}
/>
)
}
if (item.preview?.thumbnailUrl) {
return (
<img
src={item.preview.thumbnailUrl}
alt="Preview"
className="w-full h-full object-contain bg-black"
/>
)
}
// Assumption: folders in latestChildren have no media type.
if (!item.type) {
return (
<div className="w-full h-full flex items-center justify-center bg-linear-to-t from-black/5 to-black/0">
<Folder className="w-8 h-8 fill-primary/60 stroke-0" />
</div>
)
}
return (
<div className="w-full h-full flex items-center justify-center">
<File className="w-8 h-8 fill-primary/60 stroke-0" />
</div>
)
}
@@ -0,0 +1,354 @@
import type { AssetInfo, ChildPreview } from '@shumai/dtos'
import { Checkbox } from '@/ui/components/ui/checkbox'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { EditableText } from '@/ui/components/ui/editable-text'
import { cn } from '@/ui/lib/utils'
import { useDraggable, useDroppable } from '@dnd-kit/react'
import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { DragState } from '../dnd-types'
import { FilePreview } from './file-preview'
interface FolderCardProps {
item: AssetInfo
isSelected: boolean
isChecked: boolean
isEditing: boolean
onSelect: (item: AssetInfo, event: React.MouseEvent) => void
onDoubleClick: (item: AssetInfo) => void
onContextMenu: (e: React.MouseEvent, item: AssetInfo) => void
// Deprecated manual drag props replaced by dnd-kit
onDragStart: (item: AssetInfo) => void
onDrop: (target: AssetInfo) => void
onRename: (newName: string) => void
onFinishEditing: () => void
dragState?: DragState
disabled?: boolean
onAction?: (action: 'rename' | 'delete' | 'download' | 'restore', item: AssetInfo) => void
isRecentlyDeleted?: boolean
selectedCount?: number
}
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
const latestChildren = items as NonNullable<AssetInfo['latestChildren']>
const safeChildren = latestChildren ? latestChildren.slice(0, 3) : []
const count = safeChildren.length
const renderItem = (child: ChildPreview) => {
if (!child) return null
return <FilePreview item={child} />
}
if (count === 0) {
return <div></div>
}
// 1 Item
if (count === 1) {
return <div className="w-full h-full bg-muted/50 rounded-sm">{renderItem(safeChildren[0])}</div>
}
// 2 Items
if (count === 2) {
return (
<div className="grid grid-cols-2 gap-0.5 h-full w-full">
<div className="overflow-hidden h-full bg-muted/50 rounded-sm">
{renderItem(safeChildren[0])}
</div>
<div className="overflow-hidden h-full bg-muted/50 rounded-sm">
{renderItem(safeChildren[1])}
</div>
</div>
)
}
// 3 Items
return (
<div className="grid grid-cols-3 gap-0.5 h-full w-full">
<div className="col-span-1 overflow-hidden h-full relative bg-muted/50 rounded-sm col-span-2">
<div className="absolute inset-0 w-full h-full">{renderItem(safeChildren[0])}</div>
</div>
<div className="col-span-1 grid grid-rows-2 gap-0.5 h-full col-span-1">
<div className="overflow-hidden h-full relative bg-muted/50 rounded-sm">
<div className="absolute inset-0 w-full h-full">{renderItem(safeChildren[1])}</div>
</div>
<div className="overflow-hidden h-full relative bg-muted/50 rounded-sm">
<div className="absolute inset-0 w-full h-full">{renderItem(safeChildren[2])}</div>
</div>
</div>
</div>
)
}
export function FolderCard({
item,
isSelected,
isChecked,
isEditing,
onSelect,
onDoubleClick,
onContextMenu,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onDragStart: _onDragStart,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onDrop: _onDrop,
onRename,
onFinishEditing,
dragState,
disabled,
onAction,
isRecentlyDeleted,
selectedCount,
}: FolderCardProps) {
const [name, setName] = useState(item.name || '')
const inputRef = useRef<HTMLInputElement>(null)
// dnd-kit hooks
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
id: `browser:${item.id!}`,
data: {
type: 'folder',
id: item.id,
item: item,
},
disabled: disabled,
})
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
id: `browser:${item.id!}`,
data: {
type: 'folder',
id: item.id,
item: item,
},
})
const setNodeRef = (node: HTMLElement | null) => {
setDraggableRef(node)
setDroppableRef(node)
}
const isBeingDragged = isDraggableDragging || (dragState?.draggedIds.has(item.id!) ?? false)
const isValidDropTarget = useMemo(() => {
if (!dragState?.isActive) return false
if (dragState.draggedIds.has(item.id!)) return false // Can't drop on self
// Folder is always valid drop target unless self/descendant
return true
}, [dragState, item.id])
const showDropFeedback = isOver && isValidDropTarget
const opacity = isBeingDragged ? 0.5 : 1
useEffect(() => {
if (isEditing) {
// Use a longer timeout to ensure the context menu has closed and
// the DOM has stabilized before focusing. Radix focus restoration
// can sometimes conflict with immediate focus calls.
const timeoutId = setTimeout(() => {
inputRef.current?.focus()
inputRef.current?.select()
}, 150)
return () => clearTimeout(timeoutId)
}
}, [isEditing])
useEffect(() => {
setName(item.name || '')
}, [item.name])
const handleClick = (e: React.MouseEvent) => {
onSelect(item, e)
}
const handleRename = () => {
if (name !== item.name) {
onRename(name || '')
}
onFinishEditing()
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleRename()
}
if (e.key === 'Escape') {
setName(item.name || '')
onFinishEditing()
}
}
// SVG background logic from fancy card
const width = 300
const height = 220
const tabHeight = 8
const config = {
cornerRadius: 4,
tabRadius: 0,
tabSlope: 15,
tabBaseWidth: 150,
}
const folderPath = useMemo(() => {
const { cornerRadius: cr, tabRadius: tr, tabSlope: ts, tabBaseWidth: tbw } = config
const s = 1
return `M ${s}, ${tabHeight + s} L ${s}, ${s + tr} A ${tr} ${tr} 0 0 1 ${s + tr} ${s} L ${tbw - ts + s - tr} ${s} Q ${tbw - ts + s} ${s} ${tbw - ts + s + tr} ${s + tr} L ${tbw + s} ${tabHeight + s} L ${width - cr - s} ${tabHeight + s} A ${cr} ${cr} 0 0 1 ${width - s} ${tabHeight + cr + s} L ${width - s} ${height - cr - s} A ${cr} ${cr} 0 0 1 ${width - cr - s} ${height - s} L ${cr + s} ${height - s} A ${cr} ${cr} 0 0 1 ${s} ${height - cr - s} Z`
.replace(/\s+/g, ' ')
.trim()
}, [])
return (
<div
ref={setNodeRef}
style={{ opacity }}
onClick={handleClick}
onDoubleClick={() => onDoubleClick(item)}
onContextMenu={(e) => onContextMenu(e, item)}
onMouseDown={(e) => {
if (e.shiftKey) {
e.preventDefault()
}
}}
className={cn(
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full',
)}
>
<div className="absolute inset-0 z-10 pointer-events-none">
<svg
width="100%"
height="100%"
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="none"
className="overflow-visible"
>
<path
d={folderPath}
vectorEffect="non-scaling-stroke"
strokeLinejoin="round"
strokeWidth={showDropFeedback ? 3 : 1}
className={cn(
'transition-colors duration-200 fill-none group-hover:stroke-primary',
(isSelected || isChecked || showDropFeedback) && 'stroke-primary',
)}
/>
</svg>
</div>
<div className="absolute inset-0 -z-10 drop-shadow-sm pointer-events-none">
<svg
width="100%"
height="100%"
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="none"
className="overflow-visible"
>
<path
d={folderPath}
vectorEffect="non-scaling-stroke"
strokeLinejoin="round"
strokeWidth={showDropFeedback ? 3 : 1}
className={cn('transition-colors duration-200 fill-foreground/15')}
/>
</svg>
</div>
<div className="relative w-full flex flex-1 flex-col p-2 mt-5 bg-muted dark:bg-card rounded-sm">
<div className="relative w-full aspect-video shrink-0 overflow-hidden">
<div className="absolute top-1 left-1 z-30 transition-all duration-200">
<Checkbox
checked={isChecked}
onClick={(e) => e.stopPropagation()} // Let parent handler deal with it
className="w-5 h-5 border-1 border-foreground/20 bg-background/50 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
/>
</div>
{item.latestChildren && item.latestChildren.length > 0 && (
<FolderPreviewGrid items={item.latestChildren} />
)}
</div>
<div className="flex flex-col gap-1 mt-2 px-1">
<EditableText
ref={inputRef}
value={name || ''}
onChange={(e) => setName(e.target.value)}
onBlur={handleRename}
onKeyDown={handleKeyDown}
disabled={!isEditing}
className="font-semibold text-foreground text-lg leading-tight truncate h-auto p-0 !bg-transparent"
title={name}
/>
<div className="flex items-center justify-between text-muted-foreground">
<span className="text-xs tracking-wide opacity-80">
{item.fileCount || 0} {(item.fileCount || 0) === 1 ? 'Item' : 'Items'}
</span>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
onClick={(e) => e.stopPropagation()}
className="p-1.5 -mr-2 rounded-full hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
>
<MoreHorizontal size={18} />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isRecentlyDeleted ? (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('restore', item)
}}
>
<History className="mr-2 h-4 w-4" />
<span>Restore</span>
</DropdownMenuItem>
) : (
<>
{(!isChecked || (selectedCount || 0) <= 1) && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('rename', item)
}}
>
<Edit className="mr-2 h-4 w-4" />
<span>Rename</span>
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('download', item)
}}
>
<Download className="mr-2 h-4 w-4" />
<span>Download</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onAction?.('delete', item)
}}
className="text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
<span>Delete</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,212 @@
'use client'
import type { AssetInfo } from '@shumai/dtos'
import type { SearchSort } from '@shumai/dtos'
import { useDroppable } from '@dnd-kit/react'
import { ChevronDown, ChevronRight } from 'lucide-react'
import React from 'react'
import { cn } from '../../lib/utils'
import type { DragState } from '../dnd-types'
interface ReorderIndicatorProps {
id: string
item: AssetInfo
position: 'before' | 'after'
active: boolean
className?: string
dragState?: DragState
isNextItemDragging?: boolean
}
function ReorderIndicator({
id,
item,
position,
active,
className,
dragState,
isNextItemDragging,
}: ReorderIndicatorProps) {
const isDraggingItem = dragState?.draggedIds.has(item.id!)
const isDraggingAny = dragState?.isActive
const { ref: setNodeRef, isDropTarget: isOver } = useDroppable({
id,
data: {
type: 'reorder',
item,
position,
},
disabled: !active || isDraggingItem || !isDraggingAny,
})
if (isDraggingItem || isNextItemDragging) return null
return (
<div
ref={setNodeRef}
className={cn(
'absolute top-0 bottom-0 w-4 flex-shrink-0 flex items-center justify-center pointer-events-auto z-50',
position === 'before' ? '-left-2 -translate-x-1/2' : '-right-2 translate-x-1/2',
position === 'before' && [
'hidden',
'max-md:[.group-reorder:nth-child(2n+1)_&]:flex',
'md:max-lg:[.group-reorder:nth-child(3n+1)_&]:flex',
'lg:max-xl:[.group-reorder:nth-child(4n+1)_&]:flex',
'xl:[.group-reorder:nth-child(5n+1)_&]:flex',
],
className,
)}
>
<div
className={cn(
'h-full w-[3px] rounded-full transition-colors',
isOver && active && !isDraggingItem && isDraggingAny ? 'bg-primary' : 'bg-transparent',
)}
/>
</div>
)
}
interface FileBrowserGridViewProps {
folders: AssetInfo[]
files: AssetInfo[]
totalFolders?: number
totalFiles?: number
renderItem: (item: AssetInfo) => React.ReactNode
foldersExpanded: boolean
setFoldersExpanded: (expanded: boolean) => void
filesExpanded: boolean
setFilesExpanded: (expanded: boolean) => void
foldersRef: (node?: Element | null) => void
filesRef: (node?: Element | null) => void
hasNextFoldersPage: boolean
hasNextFilesPage: boolean
formatCount: (count: number, isFile: boolean) => string
formatSize: (bytes: number) => string
foldersSize: number
filesSize: number
handleEmptyAreaClick: (e: React.MouseEvent) => void
dragState?: DragState
sort?: SearchSort
}
export function FileBrowserGridView({
folders,
files,
totalFolders,
totalFiles,
renderItem,
foldersExpanded,
setFoldersExpanded,
filesExpanded,
setFilesExpanded,
foldersRef,
filesRef,
hasNextFoldersPage,
hasNextFilesPage,
formatCount,
formatSize,
foldersSize,
filesSize,
handleEmptyAreaClick,
dragState,
sort,
}: FileBrowserGridViewProps) {
return (
<div className="flex-1 p-4" onClick={handleEmptyAreaClick}>
{folders.length > 0 && (
<div className="mb-8">
<button
onClick={() => setFoldersExpanded(!foldersExpanded)}
className="mb-3 flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
>
{foldersExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
<span>
{formatCount(totalFolders ?? folders.length, false)} • {formatSize(foldersSize)}
</span>
</button>
{foldersExpanded && (
<>
<div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{folders.map((item, index) => (
<div key={item.id} className="group-reorder relative flex">
<ReorderIndicator
id={`reorder-before-folder-${item.id}`}
item={item}
position="before"
active={sort?.field === 'custom'}
dragState={dragState}
/>
<div className="flex-1 min-w-0">{renderItem(item)}</div>
<ReorderIndicator
id={`reorder-after-folder-${item.id}`}
item={item}
position="after"
active={sort?.field === 'custom'}
dragState={dragState}
isNextItemDragging={
folders[index + 1] && dragState?.draggedIds.has(folders[index + 1].id!)
}
/>
</div>
))}
</div>
{hasNextFoldersPage && <div ref={foldersRef} className="h-1" />}
</>
)}
</div>
)}
{files.length > 0 && (
<div>
<button
onClick={() => setFilesExpanded(!filesExpanded)}
className="mb-3 flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
>
{filesExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
<span>
{formatCount(totalFiles ?? files.length, true)} • {formatSize(filesSize)}
</span>
</button>
{filesExpanded && (
<>
<div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{files.map((item, index) => (
<div key={item.id} className="group-reorder relative flex">
<ReorderIndicator
id={`reorder-before-file-${item.id}`}
item={item}
position="before"
active={sort?.field === 'custom'}
dragState={dragState}
/>
<div className="flex-1 min-w-0">{renderItem(item)}</div>
<ReorderIndicator
id={`reorder-after-file-${item.id}`}
item={item}
position="after"
active={sort?.field === 'custom'}
dragState={dragState}
isNextItemDragging={
files[index + 1] && dragState?.draggedIds.has(files[index + 1].id!)
}
/>
</div>
))}
</div>
{hasNextFilesPage && <div ref={filesRef} className="h-1" />}
</>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,376 @@
'use client'
import type { AssetInfo } from '@shumai/dtos'
import type { FieldInfo } from '@shumai/dtos'
import type { SearchSort } from '@shumai/dtos'
import { useDroppable } from '@dnd-kit/react'
import { flexRender, getCoreRowModel, useReactTable, type ColumnDef } from '@tanstack/react-table'
import { ChevronDown, ChevronRight } from 'lucide-react'
import React, { useMemo, useState } from 'react'
import { cn } from '../../lib/utils'
import type { DragState } from '../dnd-types'
import { Checkbox } from '../ui/checkbox'
interface ListRowProps {
item: AssetInfo
renderItem: (item: AssetInfo, columnSizing?: Record<string, number>) => React.ReactNode
active: boolean
dragState?: DragState
isSelected?: boolean
columnSizing?: Record<string, number>
}
function ListRow({ item, renderItem, active, dragState, isSelected, columnSizing }: ListRowProps) {
const isDraggingItem = dragState?.draggedIds.has(item.id!)
const isDraggingAny = dragState?.isActive
const { ref: setTopRef, isDropTarget: isTopOver } = useDroppable({
id: `reorder-before-${item.id}`,
data: {
type: 'reorder',
item,
position: 'before',
},
disabled: !active || isDraggingItem || !isDraggingAny,
})
const { ref: setBottomRef, isDropTarget: isBottomOver } = useDroppable({
id: `reorder-after-${item.id}`,
data: {
type: 'reorder',
item,
position: 'after',
},
disabled: !active || isDraggingItem || !isDraggingAny,
})
const { ref: setRowRef, isDropTarget: isRowOver } = useDroppable({
id: `browser:${item.id!}`,
data: {
type: item.type === 'folder' ? 'folder' : 'file',
id: item.id,
item: item,
},
disabled: !isDraggingAny,
})
const isValidDropTarget = useMemo(() => {
if (!dragState?.isActive) return false
if (dragState.draggedIds.has(item.id!)) return false
if (item.type === 'folder') return true
if (item.type === 'file') {
if (dragState.hasFolders) return false
if (dragState.itemCount !== 1) return false
return true
}
return false
}, [dragState, item.id, item.type])
const showDropFeedback = isRowOver && isValidDropTarget
return (
<tbody
ref={setRowRef}
className={cn(
'group border-b border-border transition-colors hover:bg-primary/20 relative',
isSelected && 'bg-primary/10',
showDropFeedback && 'bg-primary/10',
isTopOver && 'border-t-2 border-t-primary',
isBottomOver && 'border-b-2 border-b-primary',
)}
>
<tr
ref={setTopRef}
className="p-0 m-0 leading-none bg-transparent pointer-events-auto h-[2px]"
>
<td colSpan={100} className="p-0 m-0 border-0" />
</tr>
{renderItem(item, columnSizing)}
<tr
ref={setBottomRef}
className="p-0 m-0 leading-none bg-transparent pointer-events-auto h-[2px]"
>
<td colSpan={100} className="p-0 m-0 border-0" />
</tr>
</tbody>
)
}
interface FileBrowserListViewProps {
folders: AssetInfo[]
files: AssetInfo[]
totalFolders?: number
totalFiles?: number
selectedItem: AssetInfo | null
selectedIds: Set<string>
displayedFields: FieldInfo[]
onItemSelect: (item: AssetInfo, event: React.MouseEvent) => void
onItemDoubleClick: (item: AssetInfo) => void
renderItem: (item: AssetInfo, columnSizing?: Record<string, number>) => React.ReactNode
foldersExpanded: boolean
setFoldersExpanded: (expanded: boolean) => void
filesExpanded: boolean
setFilesExpanded: (expanded: boolean) => void
foldersRef: (node?: Element | null) => void
filesRef: (node?: Element | null) => void
hasNextFoldersPage: boolean
hasNextFilesPage: boolean
formatCount: (count: number, isFile: boolean) => string
formatSize: (bytes: number) => string
foldersSize: number
filesSize: number
handleEmptyAreaClick: (e: React.MouseEvent) => void
dragState?: DragState
sort?: SearchSort
}
export function FileBrowserListView({
folders,
files,
totalFolders,
totalFiles,
selectedItem,
selectedIds,
displayedFields,
renderItem,
foldersExpanded,
setFoldersExpanded,
filesExpanded,
setFilesExpanded,
foldersRef,
filesRef,
hasNextFoldersPage,
hasNextFilesPage,
formatCount,
formatSize,
foldersSize,
filesSize,
handleEmptyAreaClick,
dragState,
sort,
}: FileBrowserListViewProps) {
const [columnSizing, setColumnSizing] = useState<Record<string, number>>({})
const columns = useMemo<ColumnDef<AssetInfo>[]>(() => {
const cols: ColumnDef<AssetInfo>[] = [
{
id: 'name',
header: 'Name',
size: 300,
minSize: 150,
},
{
id: 'size',
header: 'Size',
size: 100,
minSize: 80,
},
{
id: 'modified',
header: 'Modified',
size: 200,
minSize: 150,
},
]
displayedFields.forEach((field) => {
cols.push({
id: field.id,
header: field.config?.name || field.id,
size: 150,
minSize: 100,
})
})
return cols
}, [displayedFields])
const table = useReactTable({
data: [], // We don't use the table's data model for rows yet to keep our custom grouping logic
columns,
columnResizeMode: 'onChange',
getCoreRowModel: getCoreRowModel(),
state: {
columnSizing,
},
onColumnSizingChange: setColumnSizing,
})
return (
<div className="flex-1 overflow-x-auto" onClick={handleEmptyAreaClick}>
<table
className="w-full border-collapse"
style={{
tableLayout: 'fixed',
width: table.getTotalSize(),
minWidth: '100%',
}}
>
<thead className="sticky top-0 z-30 bg-background border-b border-border">
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id} className="bg-muted/50 whitespace-nowrap">
{headerGroup.headers.map((header) => (
<th
key={header.id}
className={cn(
'px-4 py-2 text-left text-xs font-medium text-muted-foreground relative border-r',
header.id === 'name' && 'sticky left-0 z-40 bg-muted',
)}
style={{
width: header.getSize(),
}}
>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
<div
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
className={cn(
'absolute right-0 top-0 bottom-0 w-1 cursor-col-resize user-select-none touch-none z-50 hover:bg-primary/50 transition-colors',
header.column.getIsResizing() && 'bg-primary w-1',
)}
/>
</th>
))}
</tr>
))}
</thead>
{folders.length > 0 && (
<>
<tbody className="bg-card">
<tr
className="border-b border-border hover:bg-muted/50 transition-colors cursor-pointer group"
onClick={(e) => {
e.stopPropagation()
setFoldersExpanded(!foldersExpanded)
}}
>
<td
className="px-4 py-2 sticky left-0 z-10 bg-card border-r"
style={{
width: columnSizing?.['name'] || 300,
minWidth: columnSizing?.['name'] || 300,
}}
>
<div className="flex items-center gap-2">
<Checkbox
checked={folders.length > 0 && folders.every((f) => selectedIds.has(f.id!))}
onCheckedChange={() => {
// Batch selection logic
}}
onClick={(e: React.MouseEvent) => e.stopPropagation()}
className="h-4 w-4"
/>
<div className="p-1 rounded hover:bg-muted">
{foldersExpanded ? (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
</div>
<span className="text-sm font-medium text-muted-foreground whitespace-nowrap">
{formatCount(totalFolders ?? folders.length, false)} •{' '}
{formatSize(foldersSize)}
</span>
</div>
</td>
<td colSpan={columns.length - 1} className="bg-card" />
</tr>
</tbody>
{foldersExpanded &&
folders.map((item) => (
<ListRow
key={item.id}
item={item}
renderItem={renderItem}
active={sort?.field === 'custom'}
dragState={dragState}
isSelected={selectedItem?.id === item.id}
columnSizing={columnSizing}
/>
))}
{hasNextFoldersPage && (
<tbody className="bg-transparent">
<tr>
<td colSpan={columns.length}>
<div ref={foldersRef} className="h-1" />
</td>
</tr>
</tbody>
)}
</>
)}
{files.length > 0 && (
<>
<tbody className="bg-card">
<tr
className="border-b border-border hover:bg-muted/50 transition-colors cursor-pointer group"
onClick={(e) => {
e.stopPropagation()
setFilesExpanded(!filesExpanded)
}}
>
<td
className="px-4 py-2 sticky left-0 z-10 bg-card border-r"
style={{
width: columnSizing?.['name'] || 300,
minWidth: columnSizing?.['name'] || 300,
}}
>
<div className="flex items-center gap-2">
<Checkbox
checked={files.length > 0 && files.every((f) => selectedIds.has(f.id!))}
onCheckedChange={() => {
// Batch selection logic
}}
onClick={(e: React.MouseEvent) => e.stopPropagation()}
className="h-4 w-4"
/>
<div className="p-1 rounded hover:bg-muted">
{filesExpanded ? (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
</div>
<span className="text-sm font-medium text-muted-foreground whitespace-nowrap">
{formatCount(totalFiles ?? files.length, true)} • {formatSize(filesSize)}
</span>
</div>
</td>
<td colSpan={columns.length - 1} className="bg-card" />
</tr>
</tbody>
{filesExpanded &&
files.map((item) => (
<ListRow
key={item.id}
item={item}
renderItem={renderItem}
active={sort?.field === 'custom'}
dragState={dragState}
isSelected={selectedItem?.id === item.id}
columnSizing={columnSizing}
/>
))}
{hasNextFilesPage && (
<tbody className="bg-transparent">
<tr>
<td colSpan={columns.length}>
<div ref={filesRef} className="h-1" />
</td>
</tr>
</tbody>
)}
</>
)}
</table>
</div>
)
}
@@ -0,0 +1,322 @@
import type { AssetInfo } from '@shumai/dtos'
import type { CollectionInfo } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { SearchCondition, SearchSort } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useMutation, useQuery } from '@tanstack/react-query'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { useState } from 'react'
import { FieldsManager } from '../fields-manager'
import { FolderTree } from '../folder-tree'
import { ManageFieldsDialog } from '../manage-fields-dialog'
import { MembersDialog } from '../members-dialog'
import { FilterPanel } from '../search/filter-panel'
import { SearchFilterDialog } from '../search/search-filter-dialog'
import { SortControl } from '../search/sort-control'
import { Avatar, AvatarFallback } from '../ui/avatar'
import { Button } from '../ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { Separator } from '../ui/separator'
type FileBrowserToolbarProps = {
teamId: string
projectId: string
assetId: string
fields: MetadataFieldInfo[]
filterConditions: SearchCondition[]
onFilterChange: (conditions: SearchCondition[]) => void
sort?: SearchSort
onSortChange: (sort?: SearchSort) => void
isRecentlyDeleted?: boolean
collection?: CollectionInfo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
rootFolderId?: string
}
export function FileBrowserToolbar({
teamId,
projectId,
assetId,
fields,
filterConditions,
onFilterChange,
sort,
onSortChange,
isRecentlyDeleted,
collection,
onUpdateCollection,
rootFolderId,
}: FileBrowserToolbarProps) {
const [popoverOpen, setPopoverOpen] = useState(false)
const [searchDialogOpen, setSearchDialogOpen] = useState(false)
const [manageDialogOpen, setManageDialogOpen] = useState(false)
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
const [isFolderSelectorOpen, setIsFolderSelectorOpen] = useState(false)
const activeFiltersCount = filterConditions.length
const isCollection = !!collection
const { data: folderInfo } = useQuery({
queryKey: ['folders', assetId],
queryFn: async () => {
const res = await client.api.folders[':folderId'].$get({
param: { folderId: assetId },
})
if (!res.ok) throw new Error('failed to fetch folder')
return (await res.json()) as unknown as AssetInfo
},
enabled: isCollection && !!assetId,
})
const { data: members } = useQuery({
queryKey: ['projects', projectId, 'members'],
queryFn: async () => {
const res = await client.api.projects[':projectId'].members.$get({
param: { projectId: projectId },
query: {},
})
if (!res.ok) throw new Error('Failed to fetch members')
return await res.json()
},
})
const { data: teamInfo } = useQuery({
queryKey: ['projects', projectId, 'team'],
queryFn: async () => {
const res = await client.api.projects[':projectId'].team.$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('Failed to fetch team info')
return await res.json()
},
})
const { data: me } = useQuery({
queryKey: ['teams', teamInfo?.teamId, 'me'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].me.$get({
param: { teamId: teamInfo?.teamId || '' },
})
if (!res.ok) throw new Error('Failed to fetch me')
return await res.json()
},
enabled: !!teamInfo?.teamId,
})
const $inviteProject = client.api.projects[':projectId'].invite.$post
const inviteMutation = useMutation<
InferResponseType<typeof $inviteProject>,
Error,
InferRequestType<typeof $inviteProject>
>({
mutationFn: async (args) => {
const res = await $inviteProject(args)
if (!res.ok) {
throw new Error('Failed to invite')
}
return await res.json()
},
})
const handleManageFields = () => {
setPopoverOpen(false)
setManageDialogOpen(true)
}
const handleInvite = async (role: 'editor' | 'reviewer') => {
const res = await inviteMutation.mutateAsync({
param: { projectId: projectId },
json: { role },
})
return res.code
}
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
return (
<div className="flex items-center justify-between p-2 border-b sticky top-0 bg-background z-10">
<div className="flex items-center gap-2 h-full">
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
<PopoverTrigger asChild>
<div>
<Button variant="ghost" size="sm">
Fields
</Button>
</div>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<FieldsManager
projectId={projectId}
onManageFields={handleManageFields}
onSave={() => setPopoverOpen(false)}
/>
</PopoverContent>
</Popover>
<Separator orientation="vertical" />
<SortControl
fields={fields}
sort={sort}
onSortChange={onSortChange}
disabled={isRecentlyDeleted}
/>
<Separator orientation="vertical" />
{isCollection ? (
<>
<Popover open={isFolderSelectorOpen} onOpenChange={setIsFolderSelectorOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="inline-flex items-center gap-2 px-3 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8 text-muted-foreground"
>
<span className="truncate max-w-[150px]">{folderInfo?.name || 'Loading...'}</span>
</Button>
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0" align="start">
<div className="h-[400px] flex flex-col">
<div className="p-2 border-b text-xs font-semibold text-muted-foreground uppercase tracking-wider">
Select Source Folder
</div>
<div className="flex-1 overflow-y-auto">
<FolderTree
teamId={teamId}
projectId={projectId}
projectName="Assets"
rootFolderId={rootFolderId!}
onSelect={(folder: AssetInfo) => {
onUpdateCollection?.({
filter: {
...collection.filter,
sourceFolderId: folder.id,
},
})
setIsFolderSelectorOpen(false)
}}
selectedFolderId={collection.filter.sourceFolderId}
hideCollections
hideShares
/>
</div>
</div>
</PopoverContent>
</Popover>
<Separator orientation="vertical" />
<Popover>
<PopoverTrigger asChild>
<Button
variant={activeFiltersCount > 0 ? 'secondary' : 'ghost'}
size="sm"
className="inline-flex items-center gap-2 px-4 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8"
>
<span>Filter</span>
{activeFiltersCount > 0 && (
<span className="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/50 border border-primary-foreground/20">
{activeFiltersCount}
</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[500px] p-0 overflow-hidden" align="start">
<div className="max-h-[80vh] overflow-y-auto">
<FilterPanel
fields={fields}
conditions={filterConditions}
onChange={(newConditions) => {
onFilterChange(newConditions)
onUpdateCollection?.({
filter: {
...collection.filter,
searchFilter: {
...collection.filter.searchFilter,
conditions: newConditions,
},
},
})
}}
excludeFields={[]}
hidePrefix
/>
</div>
</PopoverContent>
</Popover>
</>
) : (
<Button
onClick={() => setSearchDialogOpen(true)}
disabled={isRecentlyDeleted}
variant={activeFiltersCount > 0 ? 'secondary' : 'ghost'}
size="sm"
className="inline-flex items-center gap-2 px-4 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8"
>
<span>Search</span>
{activeFiltersCount > 0 && (
<span className="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/50 border border-primary-foreground/20">
{activeFiltersCount}
</span>
)}
</Button>
)}
</div>
<div className="flex items-center gap-2">
{!isRecentlyDeleted && (
<div
className="flex items-center -space-x-2 cursor-pointer hover:opacity-90"
onClick={() => setIsMembersDialogOpen(true)}
>
{members?.slice(0, 3).map((member) => (
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
</Avatar>
))}
{members && members.length > 3 && (
<div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-background bg-muted text-[10px] font-medium">
+{members.length - 3}
</div>
)}
</div>
)}
</div>
<ManageFieldsDialog
projectId={projectId}
open={manageDialogOpen}
onOpenChange={setManageDialogOpen}
/>
<MembersDialog
open={isMembersDialogOpen}
onOpenChange={setIsMembersDialogOpen}
title="Project Members"
members={members || []}
isOwner={me?.role === 'owner'}
onInvite={handleInvite}
/>
<SearchFilterDialog
open={searchDialogOpen}
onOpenChange={setSearchDialogOpen}
teamId={teamId}
projectId={projectId}
assetId={assetId}
fields={fields}
initialConditions={filterConditions}
onApply={onFilterChange}
/>
</div>
)
}
@@ -0,0 +1,287 @@
'use client'
import { client } from '@/ui/api/client'
import type { AssetInfo } from '@shumai/dtos'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { useState } from 'react'
interface UseFileActionsProps {
teamId: string
projectId: string
assetId: string
folders: AssetInfo[]
files: AssetInfo[]
selectedIds: Set<string>
}
export function useFileActions({
teamId,
projectId,
assetId,
folders,
files,
selectedIds,
}: UseFileActionsProps) {
const [editingItemId, setEditingItemId] = useState<string | null>(null)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
const queryClient = useQueryClient()
const $createFolder = client.api.folders.$post
const { mutate: createFolder } = useMutation<
InferResponseType<typeof $createFolder, 200>,
Error,
InferRequestType<typeof $createFolder>
>({
mutationFn: async (request) => {
const res = await $createFolder(request)
if (!res.ok) throw new Error('Failed to create')
return (await res.json()) as unknown as InferResponseType<typeof $createFolder, 200>
},
})
const $renameFolder = client.api.folders[':folderId'].$put
const { mutate: renameFolder } = useMutation<
InferResponseType<typeof $renameFolder, 200>,
Error,
InferRequestType<typeof $renameFolder>
>({
mutationFn: async (request) => {
const res = await $renameFolder(request)
if (!res.ok) throw new Error('Failed to rename')
return (await res.json()) as unknown as InferResponseType<typeof $renameFolder, 200>
},
})
const $renameFile = client.api.files[':fileId'].$put
const { mutate: renameFile } = useMutation<
InferResponseType<typeof $renameFile, 200>,
Error,
InferRequestType<typeof $renameFile>
>({
mutationFn: async (request) => {
const res = await $renameFile(request)
if (!res.ok) throw new Error('Failed to rename')
return (await res.json()) as unknown as InferResponseType<typeof $renameFile, 200>
},
})
const $deleteFiles = client.api.files.$delete
const { mutate: deleteFiles } = useMutation<void, Error, InferRequestType<typeof $deleteFiles>>({
mutationFn: async (request) => {
const res = await $deleteFiles(request)
if (!res.ok) throw new Error('Failed to delete')
},
})
const $deleteFolders = client.api.folders.$delete
const { mutate: deleteFolders } = useMutation<
InferResponseType<typeof $deleteFolders>,
Error,
InferRequestType<typeof $deleteFolders>
>({
mutationFn: async (request) => {
const res = await $deleteFolders(request)
if (!res.ok) throw new Error('Failed to delete')
return null as unknown as InferResponseType<typeof $deleteFolders>
},
})
const $restoreFiles = client.api.files.restore.$post
const { mutate: restoreFiles } = useMutation<void, Error, InferRequestType<typeof $restoreFiles>>(
{
mutationFn: async (request) => {
const res = await $restoreFiles(request)
if (!res.ok) throw new Error('Failed to restore')
},
},
)
const $restoreFolders = client.api.folders.restore.$post
const { mutate: restoreFolders } = useMutation<
InferResponseType<typeof $restoreFolders>,
Error,
InferRequestType<typeof $restoreFolders>
>({
mutationFn: async (request) => {
const res = await $restoreFolders(request)
if (!res.ok) throw new Error('Failed to restore')
return null as unknown as InferResponseType<typeof $restoreFolders>
},
})
const handleRename = (item: AssetInfo) => {
setEditingItemId(item.id!)
}
const confirmDelete = () => {
const fileIds = itemsToDelete.filter((i) => i.type === 'file').map((i) => i.id!)
const folderIds = itemsToDelete.filter((i) => i.type === 'folder').map((i) => i.id!)
if (fileIds.length > 0) {
deleteFiles(
{ json: { ids: fileIds } },
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
},
},
)
}
if (folderIds.length > 0) {
deleteFolders(
{ json: { ids: folderIds } },
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
},
},
)
}
setIsDeleteDialogOpen(false)
setItemsToDelete([])
}
const handleDelete = (items: AssetInfo[]) => {
setItemsToDelete(items)
setIsDeleteDialogOpen(true)
}
const handleRestore = (items: AssetInfo[]) => {
const fileIds = items.filter((i) => i.type === 'file').map((i) => i.id!)
const folderIds = items.filter((i) => i.type === 'folder').map((i) => i.id!)
if (fileIds.length > 0) {
restoreFiles(
{ json: { ids: fileIds } },
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['projects', projectId, 'recently-deleted', 'file'],
})
},
},
)
}
if (folderIds.length > 0) {
restoreFolders(
{ json: { ids: folderIds } },
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['projects', projectId, 'recently-deleted', 'folder'],
})
},
},
)
}
}
const handleDownload = (items: AssetInfo[]) => {
alert(
`Download functionality - Would download ${
items.length
} item(s): ${items.map((i) => i.name).join(', ')}`,
)
}
const handleNewFolder = (name: string) => {
createFolder(
{ json: { name, parentId: assetId } },
{
onSuccess: (data) => {
queryClient.invalidateQueries({
queryKey: ['search', teamId],
})
queryClient.invalidateQueries({
queryKey: ['folders', teamId],
})
if (data?.id) {
setEditingItemId(data.id)
}
},
},
)
}
const onRenameSubmit = (item: AssetInfo, newName: string) => {
if (item.type === 'folder') {
renameFolder(
{ param: { folderId: item.id! }, json: { name: newName } },
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['search', teamId],
})
queryClient.invalidateQueries({
queryKey: ['folders', teamId],
})
},
},
)
} else {
renameFile(
{
param: { fileId: item.id! },
json: { name: newName },
},
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['search', teamId],
})
queryClient.invalidateQueries({
queryKey: ['folders', teamId],
})
},
},
)
}
}
const handleAction = (action: 'rename' | 'delete' | 'download' | 'restore', item: AssetInfo) => {
const isSelected = selectedIds.has(item.id!)
const targetItems = isSelected
? [...folders, ...files].filter((i) => selectedIds.has(i.id!))
: [item]
switch (action) {
case 'rename':
handleRename(item)
break
case 'delete':
handleDelete(targetItems)
break
case 'download':
handleDownload(targetItems)
break
case 'restore':
handleRestore(targetItems)
break
}
}
return {
editingItemId,
setEditingItemId,
handleRename,
handleDelete,
handleRestore,
handleDownload,
handleNewFolder,
handleAction,
onRenameSubmit,
isDeleteDialogOpen,
setIsDeleteDialogOpen,
itemsToDelete,
confirmDelete,
}
}
@@ -0,0 +1,530 @@
import type { AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos'
import type { CollectionInfo } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { SearchCondition, SearchSort } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useMutation } from '@tanstack/react-query'
import { InferRequestType, InferResponseType } from 'hono/client'
import { useFieldStore } from '@/ui/stores/fields'
import { useMemberStore } from '@/ui/stores/members'
import { useTopNavStore } from '@/ui/stores/top-nav'
import { useUiStore } from '@/ui/stores/ui'
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
import { PointerActivationConstraints } from '@dnd-kit/dom'
import { DragDropProvider, DragOverlay, KeyboardSensor, PointerSensor } from '@dnd-kit/react'
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useEffect, useMemo, useRef, useState } from 'react'
import { cn } from '../lib/utils'
import { SnapToPointer } from './dnd-modifiers'
import { FileBrowser } from './file-browser/file-browser'
import { FileViewerRightSidebar } from './file-viewer-right-sidebar'
import { FolderTree } from './folder-tree'
import { ResizeHandle } from './resize-handle'
import { useFileSystemDnd } from './use-file-system-dnd'
type FileSystemManagerProps = {
teamId: string
projectId: string
projectName: string
assetId: string
rootFolderId: string
collection?: CollectionInfo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
}
export default function FileSystemManager({
teamId,
projectId,
projectName,
assetId,
rootFolderId,
collection,
onUpdateCollection,
}: FileSystemManagerProps) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const { loadedProjectId, setFields } = useFieldStore()
const $patchMetadata = client.api.files[':fileId'].metadata.$patch
const { mutate: patchMetadata } = useMutation<
InferResponseType<typeof $patchMetadata>,
Error,
InferRequestType<typeof $patchMetadata>
>({
mutationFn: async (request) => {
const res = await $patchMetadata(request)
if (!res.ok) throw new Error('Failed to patch metadata')
return null as unknown as InferResponseType<typeof $patchMetadata>
},
})
const { data: fields } = useQuery({
queryKey: ['fields', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].fields.$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('Failed to fetch fields')
return await res.json()
},
enabled: !!projectId,
})
useEffect(() => {
if (fields && projectId !== loadedProjectId) {
setFields(fields as unknown as MetadataFieldInfo[], projectId)
}
}, [fields, projectId, loadedProjectId, setFields])
const isRecentlyDeleted = assetId === 'recently-deleted'
const [selectedItem, setSelectedItem] = useState<AssetInfo | null>(null)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [lastSelectedId, setLastSelectedId] = useState<string | null>(null)
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const { members, fetchMembers } = useMemberStore()
const { metadata, fetchMetadata, setMetadata: setUserMetadata } = useUserMetadataStore()
useEffect(() => {
if (teamId) {
fetchMembers(teamId)
fetchMetadata(teamId)
}
}, [teamId, fetchMembers, fetchMetadata])
const initialFilterConditions = useMemo(() => {
return collection?.filter?.searchFilter?.conditions || []
}, [collection])
const [filterConditions, setFilterConditions] =
useState<SearchCondition[]>(initialFilterConditions)
useEffect(() => {
setFilterConditions(initialFilterConditions)
}, [initialFilterConditions])
const sortKey = `project:${projectId}:sort`
const sort = (metadata[sortKey] as SearchSort | undefined) || { field: 'custom', order: 'asc' }
const setSort = (newSort: SearchSort | undefined) => {
if (newSort) {
setUserMetadata(teamId, sortKey, newSort)
}
}
const isCollection = !!collection
const isFiltering = filterConditions.length > 0 || isCollection
const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
fileListRightSidebarCollapsed: isRightSidebarCollapsed,
setFileListRightSidebarCollapsed: setIsRightSidebarCollapsed,
viewModes,
} = useUiStore()
const displayStyle = viewModes[projectId] ?? 'card'
const containerRef = useRef<HTMLDivElement>(null)
const { data: folderInfo } = isRecentlyDeleted
? { data: undefined }
: useQuery({
queryKey: ['folders', assetId],
queryFn: async () => {
const res = await client.api.folders[':folderId'].$get({
param: { folderId: assetId },
})
if (!res.ok) throw new Error('failed to fetch folder')
return (await res.json()) as unknown as AssetInfo
},
})
const { setProjectState, clearProjectState } = useTopNavStore()
useEffect(() => {
setProjectState({
teamId,
projectId,
projectName,
ancestorFolders: folderInfo?.ancestorFolders ?? [],
currentAsset: isRecentlyDeleted
? { name: 'Recently Deleted', type: 'folder' }
: isCollection
? { name: collection.name, type: 'folder' }
: { name: folderInfo?.name, type: 'folder' },
isRootFolder: !isRecentlyDeleted && !isCollection && assetId === rootFolderId,
onFolderClick: (id: string) => {
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: id },
})
},
})
return () => clearProjectState()
}, [
teamId,
projectId,
projectName,
folderInfo,
isRecentlyDeleted,
assetId,
rootFolderId,
setProjectState,
clearProjectState,
navigate,
])
const {
data: foldersData,
fetchNextPage: fetchNextFoldersPage,
hasNextPage: hasNextPageFolders,
isFetchingNextPage: isFetchingNextFoldersPage,
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: isRecentlyDeleted
? ['projects', projectId, 'recently-deleted', 'folder']
: ['search', teamId, assetId, 'folder', filterConditions, sort, isCollection],
queryFn: async ({ pageParam }) => {
if (isRecentlyDeleted || isCollection) {
if (isRecentlyDeleted) {
const res = await client.api.projects[':projectId']['recently-deleted'].$get({
param: { projectId: projectId },
query: {
assetType: 'folder',
after: pageParam as string,
},
})
if (!res.ok) throw new Error('failed to fetch recently deleted folders')
return (await res.json()) as unknown as AssetInfoPaginatedList
}
return { data: [], pageInfo: { total: 0 } }
}
if (isFiltering) {
return { data: [], pageInfo: { total: 0 } }
}
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: assetId },
json: {
assetType: 'folder',
after: pageParam as string,
recursively: false,
sort,
conditions: [],
},
})
if (!res.ok) throw new Error('failed to search folders')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
enabled: !isFiltering, // Disable folders when filtering
initialPageParam: '',
getNextPageParam: (lastPage) => {
return lastPage.pageInfo?.cursor || undefined
},
})
const {
data: filesData,
fetchNextPage: fetchNextFilesPage,
hasNextPage: hasNextPageFiles,
isFetchingNextPage: isFetchingNextFilesPage,
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: isRecentlyDeleted
? ['projects', projectId, 'recently-deleted', 'file']
: ['search', teamId, assetId, 'file', filterConditions, sort, isCollection],
queryFn: async ({ pageParam }) => {
if (isRecentlyDeleted) {
const res = await client.api.projects[':projectId']['recently-deleted'].$get({
param: { projectId: projectId },
query: {
assetType: 'file',
after: pageParam as string,
},
})
if (!res.ok) throw new Error('failed to fetch recently deleted files')
return (await res.json()) as unknown as AssetInfoPaginatedList
}
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: assetId },
json: {
assetType: 'file',
after: pageParam as string,
recursively: isFiltering || isCollection,
conditions: filterConditions,
sort,
},
})
if (!res.ok) throw new Error('failed to search files')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
initialPageParam: '',
getNextPageParam: (lastPage) => {
return lastPage.pageInfo?.cursor || undefined
},
})
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
const totalFolders = foldersData?.pages[0]?.pageInfo?.total
const totalFiles = filesData?.pages[0]?.pageInfo?.total
const handleClearSelection = () => {
setSelectedIds(new Set())
setSelectedItem(null)
setLastSelectedId(null)
}
const { dragState, handleDragStart, handleDragEnd } = useFileSystemDnd({
teamId,
projectId,
assetId,
folders,
files,
selectedIds,
onClearSelection: handleClearSelection,
})
const singleSelectedFile = useMemo(() => {
if (selectedIds.size !== 1) return null
const id = Array.from(selectedIds)[0]
const file = files.find((f) => f.id === id)
return file || null
}, [selectedIds, files])
const handleItemDoubleClick = (item: AssetInfo) => {
if (item.type === 'folder') {
if (isRecentlyDeleted) {
return
}
setFilterConditions([])
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: item.id },
})
} else {
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId: item.versionStack ? item.versionStack.id : item.id },
search: { version: undefined },
})
}
}
const handleItemSelect = (item: AssetInfo, event: React.MouseEvent) => {
const isCtrlOrCmd = event.metaKey || event.ctrlKey
const isShift = event.shiftKey
if (isShift && lastSelectedId) {
// Find the last selected item
const allItems = [...folders, ...files]
const lastSelectedItem = allItems.find((i) => i.id === lastSelectedId)
if (lastSelectedItem) {
if (lastSelectedItem.type === item.type) {
// Only select range if they are the same type
const typeItems = item.type === 'folder' ? folders : files
const lastIndex = typeItems.findIndex((i) => i.id === lastSelectedId)
const currentIndex = typeItems.findIndex((i) => i.id === item.id)
if (lastIndex !== -1 && currentIndex !== -1) {
const start = Math.min(lastIndex, currentIndex)
const end = Math.max(lastIndex, currentIndex)
const rangeItems = typeItems.slice(start, end + 1)
const newSelectedIds = new Set(selectedIds)
rangeItems.forEach((rangeItem) => {
newSelectedIds.add(rangeItem.id)
})
setSelectedIds(newSelectedIds)
setSelectedItem(item)
return
}
} else {
// If types are different, do nothing (as requested by user)
return
}
}
}
if (isCtrlOrCmd) {
const newSelectedIds = new Set(selectedIds)
if (newSelectedIds.has(item.id)) {
newSelectedIds.delete(item.id)
} else {
newSelectedIds.add(item.id)
}
setSelectedIds(newSelectedIds)
} else {
setSelectedIds(new Set([item.id]))
}
setLastSelectedId(item.id)
setSelectedItem(item)
}
const handleSaveField = (fileId: string, fieldId: string, value: unknown) => {
patchMetadata(
{
param: { fileId: fileId },
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
},
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [
'folders',
assetId,
'children',
{
assetType: 'file',
},
],
})
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
},
},
)
}
return (
<DragDropProvider
modifiers={[SnapToPointer.configure({ anchor: { x: 0, y: 0 } })]}
sensors={
isRecentlyDeleted
? []
: [
PointerSensor.configure({
activationConstraints: [new PointerActivationConstraints.Distance({ value: 10 })],
}),
KeyboardSensor,
]
}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<div className="flex flex-1 flex-col bg-background min-h-0">
<div ref={containerRef} className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && (
<div
className="md:hidden fixed inset-0 bg-black/50 z-40"
onClick={() => setIsLeftSidebarCollapsed(true)}
/>
)}
{!isRightSidebarCollapsed && (
<div
className="md:hidden fixed inset-0 bg-black/50 z-40"
onClick={() => setIsRightSidebarCollapsed(true)}
/>
)}
{!isLeftSidebarCollapsed && (
<>
<div className="bg-background" style={{ width: leftSidebarWidth }}>
<FolderTree
teamId={teamId}
projectId={projectId}
projectName={projectName}
rootFolderId={rootFolderId}
dragState={dragState}
/>
</div>
<ResizeHandle
onResize={(delta) => {
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
}}
className="hidden md:block"
/>
</>
)}
<FileBrowser
teamId={teamId}
projectId={projectId}
assetId={assetId}
folders={folders}
files={files}
totalFolders={totalFolders}
totalFiles={totalFiles}
selectedItem={selectedItem}
selectedIds={selectedIds}
onItemSelect={handleItemSelect}
onItemDoubleClick={handleItemDoubleClick}
onSaveField={handleSaveField}
displayStyle={displayStyle}
onClearSelection={handleClearSelection}
fetchNextFoldersPage={fetchNextFoldersPage}
hasNextFoldersPage={hasNextPageFolders || false}
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
fetchNextFilesPage={fetchNextFilesPage}
hasNextFilesPage={hasNextPageFiles || false}
isFetchingNextFilesPage={isFetchingNextFilesPage}
isRecentlyDeleted={isRecentlyDeleted}
filterConditions={filterConditions}
onFilterChange={setFilterConditions}
sort={sort}
onSortChange={setSort}
dragState={dragState}
collection={collection}
onUpdateCollection={onUpdateCollection}
rootFolderId={rootFolderId}
/>
{!isRightSidebarCollapsed && (
<>
<ResizeHandle
onResize={(delta) => {
setRightSidebarWidth((prev) => Math.max(240, Math.min(600, prev - delta)))
}}
className="hidden md:block"
/>
<div
style={{ width: rightSidebarWidth }}
className="bg-background border-l border-border flex flex-col flex-shrink-0"
>
{singleSelectedFile ? (
<FileViewerRightSidebar
teamId={teamId}
projectId={projectId}
file={singleSelectedFile}
onSaveField={(fieldId, value) =>
handleSaveField(singleSelectedFile.id, fieldId, value)
}
members={members}
hideAnnotationControl={true}
/>
) : (
<div className="flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground">
Select an asset to view details
</div>
)}
</div>
</>
)}
</div>
</div>
<DragOverlay>
{dragState?.isActive ? (
<div
className={cn(
'flex items-center gap-2 rounded-md bg-popover px-3 py-2 text-sm font-medium text-popover-foreground shadow-md ring-1 ring-border cursor-grabbing',
displayStyle === 'list' &&
'w-30 h-[40px] px-0 flex-none overflow-hidden justify-center',
)}
style={{ transform: 'translate(0px, 0px)' }}
>
<span>
Moving {dragState.itemCount} item{dragState.itemCount !== 1 ? 's' : ''}
</span>
</div>
) : null}
</DragOverlay>
</DragDropProvider>
)
}
@@ -0,0 +1,119 @@
import { client } from '@/ui/api/client'
import { useInfiniteQuery } from '@tanstack/react-query'
import { Loader2, PanelLeftClose } from 'lucide-react'
import type { FC } from 'react'
import type { AssetInfoPaginatedList } from '@shumai/dtos'
import { useEffect, useRef } from 'react'
import { useInView } from 'react-intersection-observer'
import { SidebarFileCard } from './sidebar-file-card'
import { Button } from './ui/button'
import { ScrollArea } from './ui/scroll-area'
interface FileViewerLeftSidebarProps {
projectId: string
currentAssetId: string
parentFolderId: string
onCollapse: () => void
}
export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
projectId,
currentAssetId,
parentFolderId,
onCollapse,
}) => {
const { ref, inView } = useInView({
threshold: 0,
rootMargin: '200px',
})
const activeItemRef = useRef<HTMLDivElement>(null)
const hasScrolledRef = useRef(false)
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({
queryKey: [
'folders',
parentFolderId,
'children',
{
assetType: 'file',
},
],
queryFn: async ({ pageParam }) => {
const res = await client.api.folders[':folderId'].children.$get({
param: { folderId: parentFolderId },
query: {
assetType: 'file',
after: pageParam,
first: '20',
},
})
if (!res.ok) throw new Error('failed to fetch folder children')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
})
const files = data?.pages.flatMap((page) => page.data) ?? []
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
// Reset scroll lock when current asset changes
useEffect(() => {
hasScrolledRef.current = false
}, [currentAssetId])
// Scroll the active item into view
useEffect(() => {
const activeFileInView = files.some((f) => f?.id === currentAssetId)
if (activeFileInView && activeItemRef.current && !hasScrolledRef.current) {
activeItemRef.current.scrollIntoView({
block: 'center',
})
hasScrolledRef.current = true
}
}, [files, currentAssetId])
return (
<div className="h-full w-full bg-card border-r border-border flex flex-col">
<div className="p-2 border-b flex items-center justify-between">
<h3 className="text-sm font-semibold px-2">Current Folder</h3>
<Button variant="ghost" size="icon-sm" onClick={onCollapse}>
<PanelLeftClose className="h-4 w-4" />
</Button>
</div>
<ScrollArea className="flex-1 [&>div>div]:block! px-2">
<div className="p-2 space-y-2">
{isLoading && (
<div className="flex justify-center items-center p-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)}
{files.map(
(file) =>
file && (
<SidebarFileCard
ref={file.id === currentAssetId ? activeItemRef : null}
key={file.id}
projectId={projectId}
item={file}
isActive={file.id === currentAssetId}
/>
),
)}
<div ref={ref}>
{isFetchingNextPage && (
<div className="flex justify-center items-center p-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)}
</div>
</div>
</ScrollArea>
</div>
)
}
@@ -0,0 +1,447 @@
import type { AssetInfo, AttachmentInfo, CommentInfo, FieldValueInfo } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { UserInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
import { useFieldStore } from '@/ui/stores/fields'
import type { Annotation } from '@/ui/types'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { XIcon } from 'lucide-react'
import React, { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { MessageCard } from './chat/message-card'
import { ChatInput } from './chat/message-input'
import FieldRenderer from './field-renderer'
import { GuestIdentityPopup } from './guest-identity-popup'
import { ScrollArea } from './ui/scroll-area'
interface FileViewerRightSidebarProps {
teamId: string
projectId: string
file: AssetInfo | null
onSaveField: (fieldId: string, value: unknown) => void
members: UserInfo[]
onCommentSelect?: (comment: CommentInfo) => void
hideAnnotationControl?: boolean
readOnly?: boolean
publicFields?: MetadataFieldInfo[]
isPublic?: boolean
shareId?: string
currentTime?: number
onTyping?: () => void
selectedCommentId?: string | null
}
export function FileViewerRightSidebar({
teamId,
projectId,
file,
onSaveField,
members,
onCommentSelect,
hideAnnotationControl = false,
readOnly = false,
publicFields,
isPublic = false,
shareId,
currentTime,
onTyping,
selectedCommentId,
}: FileViewerRightSidebarProps) {
const { fields, setFields } = useFieldStore()
const queryClient = useQueryClient()
const { ref, inView } = useInView()
const [replyingTo, setReplyingTo] = useState<CommentInfo | null>(null)
const [viewingAttachment, setViewingAttachment] = useState<AttachmentInfo | null>(null)
const [isGuestPopupOpen, setIsGuestPopupOpen] = useState(false)
const [pendingComment, setPendingComment] = useState<{
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
second?: number | null
} | null>(null)
const { data: apiFields } = useQuery({
queryKey: ['fields', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].fields.$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('Failed to fetch fields')
return await res.json()
},
enabled: !!projectId && !publicFields,
})
const { data: bots } = useQuery({
queryKey: ['projects', projectId, 'bots'],
queryFn: async () => {
const res = await client.api.projects[':projectId'].bots.$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('Failed to fetch bots')
return await res.json()
},
enabled: !!projectId && !readOnly,
})
const isAiEnabled = file?.mediaType?.startsWith('image/') || file?.mediaType?.startsWith('video/')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const enabledBots = isAiEnabled ? (bots as any[]) || [] : []
useEffect(() => {
if (publicFields) {
setFields(publicFields, projectId)
} else if (apiFields) {
setFields(apiFields as unknown as MetadataFieldInfo[], projectId)
}
}, [apiFields, publicFields, projectId, setFields])
const {
data: commentsData,
fetchNextPage,
hasNextPage,
} = useInfiniteQuery({
queryKey: isPublic
? ['shares', shareId, 'files', file?.id, 'comments']
: ['files', file?.id, 'comments'],
queryFn: async ({ pageParam }) => {
if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$get(
{
param: { shareId: shareId!, fileId: file!.id! },
query: { after: pageParam as string },
},
{
headers: {
'x-share-password': password,
},
},
)
if (!res.ok) throw new Error('Failed to fetch comments')
return await res.json()
} else {
const res = await client.api.files[':fileId'].comments.$get({
param: { fileId: file!.id! },
query: { after: pageParam as string },
})
if (!res.ok) throw new Error('Failed to fetch comments')
return await res.json()
}
},
enabled: !!file?.id && (!isPublic || !!shareId),
initialPageParam: '',
refetchInterval: 2000,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getNextPageParam: (lastPage: any) => lastPage.pageInfo?.cursor || undefined,
})
const { mutate: createComment } = useMutation({
mutationFn: async ({
text,
attachmentIds,
annotations,
replyToId,
guestUserId,
second,
}: {
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
guestUserId?: string
second?: number | null
}) => {
if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$post(
{
param: { shareId: shareId!, fileId: file!.id! },
json: {
message: text,
attachmentIds: attachmentIds,
replyToId: replyToId ?? undefined,
annotations: annotations,
second: second ?? undefined,
},
},
{
headers: {
'x-share-password': password,
...(guestUserId ? { 'x-guest-user-id': guestUserId } : {}),
},
},
)
if (!res.ok) throw new Error('Failed to create comment')
return await res.json()
} else {
const res = await client.api.files[':fileId'].comments.$post({
param: { fileId: file!.id! },
json: {
message: text,
attachmentIds: attachmentIds,
replyToId: replyToId ?? undefined,
annotations: annotations,
second: second ?? undefined,
},
})
if (!res.ok) throw new Error('Failed to create comment')
return await res.json()
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: isPublic
? ['shares', shareId, 'files', file?.id, 'comments']
: ['files', file?.id, 'comments'],
})
},
})
React.useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage()
}
}, [inView, fetchNextPage, hasNextPage])
const itemFieldValueMap = useMemo(() => {
return (file?.fieldValues || []).reduce(
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
acc[val.fieldId!] = val
return acc
},
{},
)
}, [file?.fieldValues])
const sortedFields = useMemo(() => {
return [...fields].sort((a, b) => {
const nameA = a.config?.name?.toLowerCase() || ''
const nameB = b.config?.name?.toLowerCase() || ''
if (nameA < nameB) return -1
if (nameA > nameB) return 1
return 0
})
}, [fields])
const comments =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(commentsData?.pages.flatMap((page: any) => page.data ?? []) as CommentInfo[]) ?? []
const handleSendMessage = async (
text: string,
attachmentIds: string[],
annotations?: Annotation[],
replyToId?: string | null,
second?: number | null,
) => {
if (!file?.id) return
if (isPublic) {
// Check if logged in
console.log('[handleSendMessage] checking auth status')
const meRes = await client.api.me.$get()
const { id: loggedInUserId } = await meRes.json()
console.log('[handleSendMessage] loggedInUserId:', loggedInUserId)
if (!loggedInUserId) {
const guestUserId = localStorage.getItem('guest_user_id')
console.log('[handleSendMessage] guestUserId from storage:', guestUserId)
if (!guestUserId) {
console.log('[handleSendMessage] no guest ID, opening popup')
setPendingComment({ text, attachmentIds, annotations, replyToId, second })
setIsGuestPopupOpen(true)
return
}
createComment({ text, attachmentIds, annotations, replyToId, guestUserId, second })
} else {
createComment({ text, attachmentIds, annotations, replyToId, second })
}
} else {
createComment({ text, attachmentIds, annotations, replyToId, second })
}
setReplyingTo(null)
}
const handleGuestSuccess = (guestUserId: string) => {
console.log('[handleGuestSuccess] guestUserId:', guestUserId)
if (pendingComment) {
createComment({ ...pendingComment, guestUserId })
setPendingComment(null)
setReplyingTo(null)
}
}
const getUser = (id: string): UserInfo => {
const member = members.find((m) => m.id === id)
if (member) {
return member
}
if (bots) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const bot = (bots as any[]).find((b) => b.id === id)
if (bot) {
return { id: bot.id, name: bot.name, role: 'bot' }
}
}
return {
id: 'unknown',
name: 'Unknown',
role: 'unknown',
}
}
if (!file) {
return (
<div className="flex h-full items-center justify-center p-8 text-center bg-background">
<div className="space-y-2">
<p className="text-sm font-medium text-foreground">No item selected</p>
<p className="text-xs text-muted-foreground">
Select a file to view its details and comments.
</p>
</div>
</div>
)
}
return (
<div className="bg-background h-full flex flex-col overflow-hidden">
{/* Lightbox */}
{viewingAttachment && viewingAttachment.mediaType?.startsWith('image/') && (
<div
className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-4 animate-in fade-in duration-200"
onClick={() => setViewingAttachment(null)}
>
<button className="absolute top-4 right-4 text-white/70 hover:text-white bg-white/10 hover:bg-white/20 rounded-full p-2 transition-colors z-50">
<XIcon className="w-8 h-8" />
</button>
<div className="w-full h-full flex items-center justify-center p-2">
<img
src={viewingAttachment.url}
alt="Enlarged view"
className="max-w-full max-h-[85vh] object-contain rounded shadow-2xl cursor-zoom-out"
onClick={() => setViewingAttachment(null)}
/>
</div>
</div>
)}
<Tabs defaultValue="comments" className="p-1 flex-1 flex flex-col px-2 min-h-0">
<TabsList className="w-full shrink-0">
<TabsTrigger value="comments" className="flex-1">
Comments
</TabsTrigger>
<TabsTrigger value="fields" className="flex-1">
Fields
</TabsTrigger>
</TabsList>
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
<div className="space-y-4">
{comments.map((comment) => (
<div key={comment.id}>
<MessageCard
teamId={teamId}
message={comment}
getUser={getUser}
onReply={setReplyingTo}
onViewAttachment={setViewingAttachment}
hasReplies={!!comment.replies?.length}
frameRate={
file?.mediaType?.startsWith('video/')
? file?.media?.metadata?.frameRate || 30
: undefined
}
isSelected={selectedCommentId === comment.id}
onSelect={() => {
onCommentSelect?.(comment)
}}
/>
{comment.replies?.map((reply, index) => (
<div key={reply.id}>
<MessageCard
teamId={teamId}
isReply={true}
message={reply}
getUser={getUser}
onReply={setReplyingTo}
onViewAttachment={setViewingAttachment}
hasReplies={false}
isLastReply={index === (comment.replies?.length ?? 0) - 1}
frameRate={
file?.mediaType?.startsWith('video/')
? file?.media?.metadata?.frameRate || 30
: undefined
}
isSelected={selectedCommentId === reply.id}
onSelect={() => {
onCommentSelect?.(reply)
}}
/>
</div>
))}
</div>
))}
<div ref={ref} />
</div>
</ScrollArea>
{(!readOnly || isPublic) && (
<div className="mt-4 shrink-0">
<GuestIdentityPopup
isOpen={isGuestPopupOpen}
onClose={() => setIsGuestPopupOpen(false)}
onSuccess={handleGuestSuccess}
>
<ChatInput
projectId={projectId}
onSendMessage={handleSendMessage}
replyingTo={replyingTo}
onCancelReply={() => setReplyingTo(null)}
users={members}
bots={enabledBots}
hideAnnotationControl={hideAnnotationControl}
disableMentions={isPublic}
currentTime={file?.mediaType?.startsWith('video/') ? currentTime : undefined}
frameRate={
file?.mediaType?.startsWith('video/')
? file?.media?.metadata?.frameRate || 30
: undefined
}
onTyping={onTyping}
/>
</GuestIdentityPopup>
</div>
)}
</TabsContent>
<TabsContent value="fields" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-4">
<ScrollArea className="flex-1 px-4 min-h-0 [&>div>div]:block!">
{sortedFields && sortedFields.length > 0 && (
<div className="space-y-4 pb-4">
{sortedFields.map((field) => (
<div key={field.id} className="space-y-1">
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{field.config?.name}
</label>
<div className="min-h-[28px]">
<FieldRenderer
config={field.config}
value={itemFieldValueMap[field.id!]?.value}
onSave={(val) => onSaveField(field.id!, val)}
readOnly={readOnly || field.readOnly}
/>
</div>
</div>
))}
</div>
)}
</ScrollArea>
</TabsContent>
</Tabs>
</div>
)
}
+285
View File
@@ -0,0 +1,285 @@
import type { AssetInfo } from '@shumai/dtos'
import { useScreenSize } from '@/ui/hooks/useScreenSize'
import { getBestTranscode } from '@/ui/lib/media'
import { Minus, Plus, Copy, Download, Check } from 'lucide-react'
import type { RefObject } from 'react'
import { useEffect, useRef, useState } from 'react'
import type Player from 'video.js/dist/types/player'
import DrawingCanvas from './drawing-canvas'
import VideoPlayer from './viewers/video-player'
import type { Annotation } from '@/ui/types'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
type FileViewerProps = {
file: AssetInfo
videoRef?: RefObject<Player | null>
onPlay?: () => void
onPause?: () => void
onTimeUpdate?: (time: number) => void
annotations?: Annotation[]
}
export function FileViewer({
file,
videoRef,
onPlay,
onPause,
onTimeUpdate,
annotations,
}: FileViewerProps) {
const { width: screenWidth } = useScreenSize()
const isImage = file.mediaType?.startsWith('image/')
const isVideo = file.mediaType?.startsWith('video/')
// Annotation Store
const {
isDrawing,
currentTool,
currentColor,
addAnnotation,
annotations: draftAnnotations,
reset: resetAnnotations,
} = useAnnotationStore()
// Reset annotations when file changes
useEffect(() => {
resetAnnotations()
}, [file.id, resetAnnotations])
// State for Image Viewer
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
const containerRef = useRef<HTMLDivElement>(null)
const [zoom, setZoom] = useState(1)
const [pan, setPan] = useState({ x: 0, y: 0 })
const [copied, setCopied] = useState(false)
const imgW = file.media?.metadata?.originalWidth ?? 1920
const imgH = file.media?.metadata?.originalHeight ?? 1080
const conW = containerSize.width
const conH = containerSize.height
let baseScale = 1
if (conW > 0 && conH > 0) {
baseScale = Math.min(conW / imgW, conH / imgH)
}
// Reset/Fit logic
useEffect(() => {
if (conW > 0 && conH > 0 && isImage) {
setZoom(baseScale)
// Center
const x = (conW - imgW * baseScale) / 2
const y = (conH - imgH * baseScale) / 2
setPan({ x, y })
}
}, [file.id, conW, conH, isImage, baseScale, imgW, imgH])
// Resize Observer
useEffect(() => {
if (!containerRef.current) return
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(containerRef.current)
return () => observer.disconnect()
}, [])
const handleZoom = (factor: number) => {
const cx = conW / 2
const cy = conH / 2
// Limit min/max zoom if needed?
const newZoom = zoom * factor
if (newZoom < 0.01 || newZoom > 50) return
const newPanX = cx - (cx - pan.x) * (newZoom / zoom)
const newPanY = cy - (cy - pan.y) * (newZoom / zoom)
setZoom(newZoom)
setPan({ x: newPanX, y: newPanY })
}
const handleFit = () => {
setZoom(baseScale)
const x = (conW - imgW * baseScale) / 2
const y = (conH - imgH * baseScale) / 2
setPan({ x, y })
}
let bestUrl = file.media?.original?.downloadUrl
if (isImage) {
const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth)
if (bestTranscode?.url) {
bestUrl = bestTranscode.url
}
}
const handleDownload = () => {
const url = file.media?.original?.downloadUrl
if (!url) return
const link = document.createElement('a')
link.href = url
link.download = file.name || 'image'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
const handleCopy = async () => {
const webpUrl = bestUrl
if (!webpUrl) return
try {
// To support Safari and iOS, we must invoke navigator.clipboard.write
// synchronously inside the click handler. We can pass a promise to ClipboardItem
// which resolves to the Blob asynchronously.
const copyPromise = (async () => {
const response = await fetch(webpUrl)
const blob = await response.blob()
const img = new Image()
img.crossOrigin = 'anonymous'
const objectUrl = URL.createObjectURL(blob)
img.src = objectUrl
try {
await new Promise((resolve, reject) => {
img.onload = resolve
img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e)))
})
const canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Could not get canvas context')
ctx.drawImage(img, 0, 0)
const pngBlob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob(resolve, 'image/png')
})
if (!pngBlob) throw new Error('Failed to convert image to PNG')
return pngBlob
} finally {
URL.revokeObjectURL(objectUrl)
}
})()
await navigator.clipboard.write([
new ClipboardItem({
'image/png': copyPromise,
}),
])
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (err) {
console.error('Failed to copy image to clipboard:', err)
}
}
if (!bestUrl) {
return (
<div className="flex flex-1 items-center justify-center">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
)
}
// Combine saved annotations and draft annotations
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
return (
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
{isImage && (
<>
<div ref={containerRef} className="flex-1 relative overflow-hidden">
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={{
width: imgW,
height: imgH,
}}
imageUrl={bestUrl}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
onPan={setPan}
className="absolute inset-0 z-0"
// Drawing Props
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
</div>
{/* Zoom Toolbar */}
<div className="relative px-4 py-3 bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 mr-auto">
<button
onClick={() => handleZoom(0.8)}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title="Zoom Out"
>
<Minus size={16} />
</button>
<span className="w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
{Math.round(zoom * 100)}%
</span>
<button
onClick={() => handleZoom(1.2)}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title="Zoom In"
>
<Plus size={16} />
</button>
</div>
<button
onClick={handleFit}
className="text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent animate-in fade-in zoom-in-95 duration-200"
>
Fit
</button>
<button
onClick={handleCopy}
disabled={!bestUrl}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Copy optimized image to clipboard"
>
{copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
{copied ? 'Copied' : 'Copy'}
</button>
<button
onClick={handleDownload}
disabled={!file.media?.original?.downloadUrl}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Download original image"
>
<Download size={14} />
Download
</button>
</div>
</>
)}
{isVideo && (
<VideoPlayer
data={file}
playerRef={videoRef}
onPlay={onPlay}
onPause={onPause}
onTimeUpdate={onTimeUpdate}
annotations={displayAnnotations}
/>
)}
</div>
)
}
+593
View File
@@ -0,0 +1,593 @@
import type { AssetInfoPaginatedList, AssetInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { cn } from '@/ui/lib/utils'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useMatch, useNavigate, useParams } from '@tanstack/react-router'
import {
ChevronDown,
ChevronsDownUp,
ChevronsUpDown,
ChevronRight,
Clapperboard,
Folder,
Loader2,
Trash2,
Plus,
Share2,
LayoutGrid,
Bookmark,
} from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { useDraggable, useDroppable } from '@dnd-kit/react'
import type { DragState } from './dnd-types'
import { toast } from 'sonner'
import type { ShareLinkInfo } from '@shumai/dtos'
import type { CollectionInfo } from '@shumai/dtos'
interface FolderTreeProps {
teamId: string
projectId: string
projectName: string
rootFolderId: string
dragState?: DragState
onSelect?: (folder: AssetInfo) => void
selectedFolderId?: string
hideCollections?: boolean
hideShares?: boolean
}
export function FolderTree({
teamId,
projectId,
projectName,
rootFolderId,
dragState,
onSelect,
selectedFolderId,
hideCollections,
hideShares,
}: FolderTreeProps) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const isRecentlyDeleted = useMatch({
from: '/projects/$projectId/recently-deleted',
shouldThrow: false,
})
const [isAssetsExpanded, setIsAssetsExpanded] = useState(true)
const [isCollectionsExpanded, setIsCollectionsExpanded] = useState(true)
const [isSharesExpanded, setIsSharesExpanded] = useState(true)
const { data: shareLinksData } = useQuery({
queryKey: ['shares', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].shares.$get({
param: { projectId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch share links')
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
},
enabled: !!projectId,
})
const { data: collectionsData } = useQuery({
queryKey: ['collections', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].collections.$get({
param: { projectId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch collections')
return (await res.json()) as unknown as { data: CollectionInfo[] }
},
enabled: !!projectId,
})
const { mutate: createCollection } = useMutation({
mutationFn: async () => {
const res = await client.api.projects[':projectId'].collections.$post({
param: { projectId },
json: {
name: 'Untitled Collection',
filter: {
sourceFolderId: rootFolderId,
searchFilter: {
conditions: [],
recursively: true,
},
},
},
})
if (!res.ok) throw new Error('Failed to create collection')
return await res.json()
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['collections', projectId] })
toast.success('Collection created')
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: data.id },
})
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
})
const { mutate: createShareLink } = useMutation({
mutationFn: async () => {
const res = await client.api.projects[':projectId'].shares.$post({
param: { projectId },
json: {
name: new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}),
},
})
if (!res.ok) throw new Error('Failed to create share link')
return await res.json()
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
toast.success('Share link created')
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: data.id },
})
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
})
const shareLinks = shareLinksData?.data ?? []
return (
<div className="flex flex-col h-full overflow-hidden p-3 gap-4 bg-background">
<div
className={cn(
'flex flex-col overflow-hidden transition-all duration-300 ease-in-out border-b border-border pb-4',
isAssetsExpanded ? 'flex-1 min-h-[50%] h-full' : 'flex-none h-[44px] max-h-[44px]',
)}
>
<header className="group flex items-center justify-between px-2 mb-1 flex-none">
<div
className="flex-1 flex items-center gap-1.5 cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors"
onClick={() => setIsAssetsExpanded(!isAssetsExpanded)}
>
<h3 className="text-xs font-semibold uppercase tracking-wider">Assets</h3>
{isAssetsExpanded ? (
<ChevronsDownUp className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
) : (
<ChevronsUpDown className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
)}
</div>
<button className="text-muted-foreground hover:text-foreground flex-none">
<Plus className="h-3.5 w-3.5" />
</button>
</header>
<div
className={cn(
'flex-1 overflow-y-auto min-h-0 space-y-0.5 pr-1 transition-all duration-300 ease-in-out',
isAssetsExpanded
? 'opacity-100 visible pointer-events-auto'
: 'opacity-0 invisible pointer-events-none h-0',
)}
>
<FolderTreeItem
key={rootFolderId}
teamId={teamId}
projectId={projectId}
folder={{
id: rootFolderId,
name: projectName,
type: 'folder',
sizeByte: 0,
fileCount: 0,
status: 'processed',
mediaType: null,
createdAt: '',
updatedAt: '',
}}
level={0}
isRoot={true}
dragState={dragState}
onSelect={onSelect}
selectedFolderId={selectedFolderId}
/>
<div
className={cn(
'group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
isRecentlyDeleted && 'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
)}
onClick={() =>
navigate({
to: '/projects/$projectId/recently-deleted',
params: { projectId },
})
}
>
<div className="flex h-4 w-4 items-center justify-center">
<Trash2 className="h-4 w-4 text-sidebar-primary" />
</div>
<span className="flex-1 truncate text-sidebar-foreground">Recently Deleted</span>
</div>
</div>
</div>
{!hideCollections && (
<div
className={cn(
'flex flex-col overflow-hidden transition-all duration-300 ease-in-out border-b border-border pb-4',
isCollectionsExpanded ? 'flex-1 min-h-0 h-full' : 'flex-none h-[44px] max-h-[44px]',
)}
>
<header className="group flex items-center justify-between px-2 mb-1 flex-none">
<div
className="flex-1 flex items-center gap-1.5 cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors"
onClick={() => setIsCollectionsExpanded(!isCollectionsExpanded)}
>
<h3 className="text-xs font-semibold uppercase tracking-wider">Collections</h3>
{isCollectionsExpanded ? (
<ChevronsDownUp className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
) : (
<ChevronsUpDown className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
)}
</div>
<button
onClick={() => createCollection()}
className="text-muted-foreground hover:text-foreground flex-none"
>
<Plus className="h-3.5 w-3.5" />
</button>
</header>
<div
className={cn(
'flex-1 overflow-y-auto min-h-0 space-y-0.5 pr-1 transition-all duration-300 ease-in-out',
isCollectionsExpanded
? 'opacity-100 visible pointer-events-auto'
: 'opacity-0 invisible pointer-events-none h-0',
)}
>
{collectionsData?.data.map((collection) => (
<div
key={collection.id}
className="group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
onClick={() =>
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: collection.id },
})
}
>
<div className="flex h-4 w-4 items-center justify-center">
<Bookmark className="h-4 w-4 text-sidebar-primary" />
</div>
<span className="flex-1 truncate text-sidebar-foreground">{collection.name}</span>
</div>
))}
</div>
</div>
)}
{!hideShares && (
<div
className={cn(
'flex flex-col overflow-hidden transition-all duration-300 ease-in-out border-b border-border pb-4',
isSharesExpanded ? 'flex-1 min-h-0 h-full' : 'flex-none h-[44px] max-h-[44px]',
)}
>
<header className="group flex items-center justify-between px-2 mb-1 flex-none">
<div
className="flex-1 flex items-center gap-1.5 cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors"
onClick={() => setIsSharesExpanded(!isSharesExpanded)}
>
<h3 className="text-xs font-semibold uppercase tracking-wider">Share Links</h3>
{isSharesExpanded ? (
<ChevronsDownUp className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
) : (
<ChevronsUpDown className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
)}
</div>
<div className="flex items-center gap-1 flex-none">
<button
onClick={() => createShareLink()}
className="text-muted-foreground hover:text-foreground"
>
<Plus className="h-3.5 w-3.5" />
</button>
</div>
</header>
<div
className={cn(
'flex-1 overflow-y-auto min-h-0 space-y-0.5 pr-1 transition-all duration-300 ease-in-out',
isSharesExpanded
? 'opacity-100 visible pointer-events-auto'
: 'opacity-0 invisible pointer-events-none h-0',
)}
>
<div className="group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground">
<div className="flex h-4 w-4 items-center justify-center">
<LayoutGrid className="h-4 w-4 text-sidebar-primary" />
</div>
<span className="flex-1 truncate text-sidebar-foreground">
All Share Links ({shareLinks.length})
</span>
</div>
{shareLinks.map((link) => (
<ShareLinkItem
key={link.id}
link={link}
projectId={projectId}
dragState={dragState}
/>
))}
</div>
</div>
)}
</div>
)
}
function ShareLinkItem({
link,
projectId,
dragState,
}: {
link: ShareLinkInfo
projectId: string
dragState?: DragState
}) {
const navigate = useNavigate()
const params = useParams({
from: '/projects/$projectId/shares/$shareId',
shouldThrow: false,
})
const isActive = params?.shareId === link.id
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
id: `share:${link.id}`,
data: {
type: 'share-link',
id: link.id,
},
})
const isValidDropTarget = !!dragState?.isActive
return (
<div
ref={setDroppableRef}
className={cn(
'group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
isActive && 'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
isOver && isValidDropTarget && 'bg-sidebar-accent ring-2 ring-primary ring-inset',
)}
onClick={() =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: link.id },
})
}
>
<div className="flex h-4 w-4 items-center justify-center">
<Share2 className="h-4 w-4 text-sidebar-primary" />
</div>
<span className="flex-1 truncate text-sidebar-foreground">{link.name}</span>
</div>
)
}
interface FolderTreeItemProps {
teamId: string
projectId: string
folder: AssetInfo
level: number
isRoot?: boolean
dragState?: DragState
onSelect?: (folder: AssetInfo) => void
selectedFolderId?: string
}
function FolderTreeItem({
teamId,
projectId,
folder,
level,
isRoot,
dragState,
onSelect,
selectedFolderId,
}: FolderTreeItemProps) {
const [isExpanded, setIsExpanded] = useState(isRoot || false)
const navigate = useNavigate()
const params = useParams({
from: '/projects/$projectId/folders/$folderId',
select: (p) => ({ folderId: p.folderId }),
shouldThrow: false,
})
const rootParams = useParams({
from: '/projects/$projectId/',
shouldThrow: false,
})
const isActive = isRoot ? !!rootParams : params?.folderId === folder.id
const {
data: childrenData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: [
'folders',
folder.id,
'children',
{
assetType: 'folder',
},
],
queryFn: async ({ pageParam }) => {
const res = await client.api.folders[':folderId'].children.$get({
param: { folderId: folder.id },
query: {
assetType: 'folder',
after: pageParam as string,
first: '20',
},
})
if (!res.ok) throw new Error('failed to fetch folder children')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
initialPageParam: '',
getNextPageParam: (lastPage) => {
return lastPage.pageInfo?.cursor || undefined
},
enabled: isExpanded || !!isRoot,
})
const { ref, inView } = useInView()
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
const childrenFolders = childrenData?.pages.flatMap((page) => page.data ?? []) ?? []
const handleToggleExpand = (e: React.MouseEvent) => {
e.stopPropagation()
setIsExpanded(!isExpanded)
}
const handleFolderClick = () => {
if (onSelect) {
onSelect(folder)
return
}
if (isRoot) {
navigate({
to: '/projects/$projectId',
params: { projectId },
})
} else {
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: folder.id! },
})
}
}
const { ref: setDraggableRef, isDragging } = useDraggable({
id: `tree:${folder.id!}`,
data: {
type: 'folder',
item: folder,
},
disabled: !!isRoot || !!onSelect,
})
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
id: `tree:${folder.id!}`,
data: {
type: 'folder',
item: folder,
},
disabled: dragState?.draggedIds.has(folder.id!) || !!onSelect,
})
const setNodeRef = (node: HTMLDivElement | null) => {
setDraggableRef(node)
setDroppableRef(node)
}
const isValidDropTarget = useMemo(() => {
if (onSelect) return false
if (!dragState?.isActive) return false
if (dragState.draggedIds.has(folder.id!)) return false
return true
}, [dragState, folder.id, onSelect])
const showDropFeedback = isOver && isValidDropTarget
const isSelected = selectedFolderId === folder.id
return (
<div>
<div
ref={setNodeRef}
className={cn(
'group flex cursor-pointer items-center gap-1 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
(isActive || isSelected) &&
'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
isDragging && 'opacity-50',
showDropFeedback && 'bg-sidebar-accent ring-2 ring-primary ring-inset',
)}
style={{
...(isRoot ? {} : { paddingLeft: `${level * 12 + 8}px` }),
}}
onClick={handleFolderClick}
>
{!isRoot && (
<button onClick={handleToggleExpand} className="flex h-4 w-4 items-center justify-center">
{isExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
</button>
)}
{isRoot ? (
<Clapperboard className="h-4 w-4 text-sidebar-primary" />
) : (
<Folder className="h-4 w-4 text-sidebar-primary" />
)}
<span className="flex-1 truncate text-sidebar-foreground">{folder.name}</span>
</div>
{isExpanded && (
<div>
{isLoading && (
<div
className="flex items-center justify-center p-2"
style={{ paddingLeft: `${(level + 1) * 12 + 8}px` }}
>
<Loader2 className="h-4 w-4 animate-spin" />
</div>
)}
{childrenFolders.map((child) => (
<FolderTreeItem
key={child.id}
teamId={teamId}
projectId={projectId}
folder={child}
level={level + 1}
dragState={dragState}
onSelect={onSelect}
selectedFolderId={selectedFolderId}
/>
))}
{hasNextPage && (
<div
ref={ref}
className="flex items-center justify-center p-2"
style={{ paddingLeft: `${(level + 1) * 12 + 8}px` }}
>
{isFetchingNextPage && <Loader2 className="h-4 w-4 animate-spin" />}
</div>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,105 @@
'use client'
import { useState } from 'react'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { client } from '@/ui/api/client'
import { Loader2 } from 'lucide-react'
interface GuestIdentityPopupProps {
isOpen: boolean
onClose: () => void
onSuccess: (guestUserId: string) => void
children?: React.ReactNode
}
export function GuestIdentityPopup({
isOpen,
onClose,
onSuccess,
children,
}: GuestIdentityPopupProps) {
console.log('[GuestIdentityPopup] isOpen:', isOpen)
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
setError(null)
try {
const res = await client.api.identify.$post({
json: { username: name, email: email },
})
if (!res.ok) {
const data = (await res.json()) as { error?: string }
throw new Error(data.error || 'Failed to identify')
}
const { id } = await res.json()
localStorage.setItem('guest_user_id', id)
onSuccess(id)
onClose()
} catch (err) {
setError((err as Error).message)
} finally {
setIsLoading(false)
}
}
return (
<Popover open={isOpen} onOpenChange={(open) => !open && onClose()}>
<PopoverTrigger asChild>{children}</PopoverTrigger>
<PopoverContent className="w-80" align="end" side="top">
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<h4 className="font-medium leading-none">Enter your details</h4>
<p className="text-sm text-muted-foreground">
Please provide your name and email to add a comment.
</p>
</div>
<div className="grid gap-2">
<div className="grid gap-1">
<Label htmlFor="name">Name</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="John Doe"
size={32}
required
/>
</div>
<div className="grid gap-1">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="john@example.com"
required
/>
</div>
{error && <p className="text-xs text-destructive">{error}</p>}
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" size="sm" onClick={onClose}>
Cancel
</Button>
<Button type="submit" size="sm" disabled={isLoading}>
{isLoading && <Loader2 className="mr-2 h-3 w-3 animate-spin" />}
Confirm
</Button>
</div>
</form>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,324 @@
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { useCallback, useEffect, useState } from 'react'
import {
SELECTION_CHANGE_COMMAND,
FORMAT_TEXT_COMMAND,
$getSelection,
$isRangeSelection,
COMMAND_PRIORITY_CRITICAL,
$createParagraphNode,
} from 'lexical'
import {
$isListNode,
ListNode,
INSERT_ORDERED_LIST_COMMAND,
INSERT_UNORDERED_LIST_COMMAND,
REMOVE_LIST_COMMAND,
} from '@lexical/list'
import {
$createHeadingNode,
$createQuoteNode,
$isHeadingNode,
type HeadingTagType,
} from '@lexical/rich-text'
import { $createCodeNode } from '@lexical/code'
import { $setBlocksType } from '@lexical/selection'
import { $getNearestNodeOfType } from '@lexical/utils'
import {
Bold,
Italic,
Underline,
Strikethrough,
Code,
Quote,
List,
ListOrdered,
Type,
Heading1,
Heading2,
Heading3,
} from 'lucide-react'
import { Toggle } from '@/ui/components/ui/toggle'
import { Separator } from '@/ui/components/ui/separator'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
const blockTypeToBlockName = {
paragraph: 'Normal',
h1: 'Heading 1',
h2: 'Heading 2',
h3: 'Heading 3',
bullet: 'Bullet List',
number: 'Numbered List',
quote: 'Quote',
code: 'Code Block',
}
export function ToolbarPlugin() {
const [editor] = useLexicalComposerContext()
const [activeEditor, setActiveEditor] = useState(editor)
const [isBold, setIsBold] = useState(false)
const [isItalic, setIsItalic] = useState(false)
const [isUnderline, setIsUnderline] = useState(false)
const [isStrikethrough, setIsStrikethrough] = useState(false)
const [isCode, setIsCode] = useState(false)
const [blockType, setBlockType] = useState<keyof typeof blockTypeToBlockName>('paragraph')
const $updateToolbar = useCallback(() => {
const selection = $getSelection()
if ($isRangeSelection(selection)) {
setIsBold(selection.hasFormat('bold'))
setIsItalic(selection.hasFormat('italic'))
setIsUnderline(selection.hasFormat('underline'))
setIsStrikethrough(selection.hasFormat('strikethrough'))
setIsCode(selection.hasFormat('code'))
const anchorNode = selection.anchor.getNode()
const element =
anchorNode.getKey() === 'root' ? anchorNode : anchorNode.getTopLevelElementOrThrow()
const elementKey = element.getKey()
const elementDom = activeEditor.getElementByKey(elementKey)
if (elementDom !== null) {
if ($isListNode(element)) {
const parentList = $getNearestNodeOfType(anchorNode, ListNode)
const type = parentList ? parentList.getListType() : element.getListType()
setBlockType(type as keyof typeof blockTypeToBlockName)
} else {
const type = $isHeadingNode(element) ? element.getTag() : element.getType()
if (type in blockTypeToBlockName) {
setBlockType(type as keyof typeof blockTypeToBlockName)
}
}
}
}
}, [activeEditor])
useEffect(() => {
return editor.registerCommand(
SELECTION_CHANGE_COMMAND,
(_payload, newEditor) => {
$updateToolbar()
setActiveEditor(newEditor)
return false
},
COMMAND_PRIORITY_CRITICAL,
)
}, [editor, $updateToolbar])
useEffect(() => {
return editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
$updateToolbar()
})
})
}, [editor, $updateToolbar])
const formatParagraph = () => {
if (blockType !== 'paragraph') {
activeEditor.update(() => {
const selection = $getSelection()
if ($isRangeSelection(selection)) {
$setBlocksType(selection, () => $createParagraphNode())
}
})
}
}
const formatHeading = (headingSize: HeadingTagType) => {
if (blockType !== headingSize) {
activeEditor.update(() => {
const selection = $getSelection()
if ($isRangeSelection(selection)) {
$setBlocksType(selection, () => $createHeadingNode(headingSize))
}
})
}
}
const formatBulletList = () => {
if (blockType !== 'bullet') {
activeEditor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined)
} else {
activeEditor.dispatchCommand(REMOVE_LIST_COMMAND, undefined)
}
}
const formatNumberedList = () => {
if (blockType !== 'number') {
activeEditor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined)
} else {
activeEditor.dispatchCommand(REMOVE_LIST_COMMAND, undefined)
}
}
const formatQuote = () => {
if (blockType !== 'quote') {
activeEditor.update(() => {
const selection = $getSelection()
if ($isRangeSelection(selection)) {
$setBlocksType(selection, () => $createQuoteNode())
}
})
} else {
formatParagraph()
}
}
const formatCode = () => {
if (blockType !== 'code') {
activeEditor.update(() => {
const selection = $getSelection()
if ($isRangeSelection(selection)) {
$setBlocksType(selection, () => $createCodeNode())
}
})
} else {
formatParagraph()
}
}
const handleBlockTypeChange = (value: string) => {
switch (value) {
case 'paragraph':
formatParagraph()
break
case 'h1':
formatHeading('h1')
break
case 'h2':
formatHeading('h2')
break
case 'h3':
formatHeading('h3')
break
case 'bullet':
formatBulletList()
break
case 'number':
formatNumberedList()
break
case 'quote':
formatQuote()
break
case 'code':
formatCode()
break
}
}
return (
<div className="toolbar bg-background border-b border-border flex items-center p-1 gap-1 sticky top-0 z-10 flex-wrap">
<Select value={blockType} onValueChange={handleBlockTypeChange}>
<SelectTrigger className="h-8 w-[140px] border-none shadow-none focus:ring-0">
<SelectValue placeholder="Normal" />
</SelectTrigger>
<SelectContent
onCloseAutoFocus={(e) => {
e.preventDefault()
activeEditor.focus()
}}
>
<SelectItem value="paragraph">
<div className="flex items-center gap-2">
<Type className="h-4 w-4" /> Normal
</div>
</SelectItem>
<SelectItem value="h1">
<div className="flex items-center gap-2">
<Heading1 className="h-4 w-4" /> Heading 1
</div>
</SelectItem>
<SelectItem value="h2">
<div className="flex items-center gap-2">
<Heading2 className="h-4 w-4" /> Heading 2
</div>
</SelectItem>
<SelectItem value="h3">
<div className="flex items-center gap-2">
<Heading3 className="h-4 w-4" /> Heading 3
</div>
</SelectItem>
<SelectItem value="number">
<div className="flex items-center gap-2">
<ListOrdered className="h-4 w-4" /> Numbered List
</div>
</SelectItem>
<SelectItem value="bullet">
<div className="flex items-center gap-2">
<List className="h-4 w-4" /> Bullet List
</div>
</SelectItem>
<SelectItem value="quote">
<div className="flex items-center gap-2">
<Quote className="h-4 w-4" /> Quote
</div>
</SelectItem>
<SelectItem value="code">
<div className="flex items-center gap-2">
<Code className="h-4 w-4" /> Code Block
</div>
</SelectItem>
</SelectContent>
</Select>
<Separator orientation="vertical" className="h-6 mx-1" />
<Toggle
size="sm"
pressed={isBold}
onPressedChange={() => {
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'bold')
}}
aria-label="Format Bold"
>
<Bold className="h-4 w-4" />
</Toggle>
<Toggle
size="sm"
pressed={isItalic}
onPressedChange={() => {
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'italic')
}}
aria-label="Format Italic"
>
<Italic className="h-4 w-4" />
</Toggle>
<Toggle
size="sm"
pressed={isUnderline}
onPressedChange={() => {
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'underline')
}}
aria-label="Format Underline"
>
<Underline className="h-4 w-4" />
</Toggle>
<Toggle
size="sm"
pressed={isStrikethrough}
onPressedChange={() => {
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'strikethrough')
}}
aria-label="Format Strikethrough"
>
<Strikethrough className="h-4 w-4" />
</Toggle>
<Toggle
size="sm"
pressed={isCode}
onPressedChange={() => {
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'code')
}}
aria-label="Insert Code"
>
<Code className="h-4 w-4" />
</Toggle>
</div>
)
}
@@ -0,0 +1,609 @@
import {
type FieldInfo as MetadataFieldInfo,
type FieldInfo,
FieldType,
type SelectOption,
} from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useMutation } from '@tanstack/react-query'
import { InferRequestType, InferResponseType } from 'hono/client'
import { useFieldStore } from '@/ui/stores/fields'
import { DragDropProvider, KeyboardSensor, PointerSensor, type DragEndEvent } from '@dnd-kit/react'
import { useSortable } from '@dnd-kit/react/sortable'
import { arrayMove } from '@/ui/lib/dnd-utils'
import { PointerActivationConstraints } from '@dnd-kit/dom'
import {
ChevronDown,
FileText,
GripVertical,
Lock,
Plus,
Settings,
Sparkles,
X,
} from 'lucide-react'
import { useMemo, useState } from 'react'
import { Button } from '@/ui/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/ui/components/ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { cn } from '@/ui/lib/utils'
type ManageFieldsDialogProps = {
projectId: string
open: boolean
onOpenChange: (open: boolean) => void
}
// Map scopes to UI groups
// Note: "Essentials" and "File Attributes" are typically system fields.
// "Custom Fields" are project fields.
// Since we don't have explicit "Essentials" vs "File Attributes" flag,
// we'll put all system/team fields in "Essentials" for now or split if possible.
// User said: "groups are `scope` field... can be system/team/project".
const SCOPE_GROUPS = {
SYSTEM: 'system',
TEAM: 'team',
PROJECT: 'project',
}
const GROUP_LABELS: Record<string, string> = {
[SCOPE_GROUPS.SYSTEM]: 'Essentials',
[SCOPE_GROUPS.TEAM]: 'Team Attributes', // Assuming this, user screenshot said "File Attributes" but maybe that's system?
[SCOPE_GROUPS.PROJECT]: 'Custom Fields',
}
// Icons for groups
const GROUP_ICONS: Record<string, React.ElementType> = {
[SCOPE_GROUPS.SYSTEM]: FileText, // Placeholder
[SCOPE_GROUPS.TEAM]: FileText, // Placeholder
[SCOPE_GROUPS.PROJECT]: Settings,
}
type SortableFieldRowProps = {
field: FieldInfo
index: number
isSelected: boolean
onSelect: (field: FieldInfo) => void
isSortable: boolean
}
function SortableFieldRow({
field,
index,
isSelected,
onSelect,
isSortable,
}: SortableFieldRowProps) {
const { ref, handleRef } = useSortable({
id: field.id!,
index,
disabled: !isSortable,
})
return (
<div
ref={ref}
className={cn(
'flex items-center gap-2 p-2 rounded-md cursor-pointer hover:bg-muted/50',
isSelected && 'bg-muted',
)}
onClick={() => onSelect(field)}
>
{isSortable && (
<div ref={handleRef} className="cursor-grab">
<GripVertical className="h-4 w-4 text-muted-foreground" />
</div>
)}
{!isSortable && <div className="w-4" />} {/* Spacer */}
{field.aiAutofill && <Sparkles className="h-4 w-4 text-muted-foreground" />}
<div className="flex-1 text-sm font-medium truncate">{field.config?.name}</div>
{/* Visual indicator for type or something? */}
</div>
)
}
export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFieldsDialogProps) {
const { fields, updateFields } = useFieldStore()
const [selectedGroup, setSelectedGroup] = useState<string>(SCOPE_GROUPS.PROJECT)
const [selectedFieldId, setSelectedFieldId] = useState<string | null>(null)
const [isCreating, setIsCreating] = useState(false)
// Editor State
const [editLabel, setEditLabel] = useState('')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [editConfig, setEditConfig] = useState<any>({})
const [editAiAutofill, setEditAiAutofill] = useState(false)
const [editDescription, setEditDescription] = useState('')
// Creator State
const [newName, setNewName] = useState('')
const [newType, setNewType] = useState<FieldType | ''>('')
const [newAiAutofill, setNewAiAutofill] = useState(false)
const [newDescription, setNewDescription] = useState('')
const $patchOrder = client.api.projects[':projectId'].fields.order.$patch
const { mutate: updateFieldsOrder } = useMutation<
InferResponseType<typeof $patchOrder>,
Error,
InferRequestType<typeof $patchOrder>
>({
mutationFn: async (request) => {
const res = await $patchOrder(request)
if (!res.ok) throw new Error('Failed to update fields order')
return null as unknown as InferResponseType<typeof $patchOrder>
},
})
const $post = client.api.projects[':projectId'].fields.$post
const { mutate: createField } = useMutation<
InferResponseType<typeof $post>,
Error,
InferRequestType<typeof $post>
>({
mutationFn: async (request) => {
const res = await $post(request)
if (!res.ok) throw new Error('Failed to create field')
return (await res.json()) as MetadataFieldInfo
},
onSuccess: (data) => {
const newField: MetadataFieldInfo = { ...(data as MetadataFieldInfo), visible: true }
updateFields([...fields, newField])
setIsCreating(false)
setSelectedFieldId(data.id!)
resetEditor(data)
},
})
const $put = client.api.fields[':fieldId'].$put
const { mutate: updateField } = useMutation<
InferResponseType<typeof $put>,
Error,
InferRequestType<typeof $put>
>({
mutationFn: async (request) => {
const res = await $put(request)
if (!res.ok) throw new Error('Failed to update field')
return (await res.json()) as MetadataFieldInfo
},
onSuccess: (data) => {
const newFields = fields.map((f) =>
f.id === data.id ? { ...f, ...(data as MetadataFieldInfo) } : f,
)
updateFields(newFields)
},
})
const $delete = client.api.fields[':fieldId'].$delete
const { mutate: deleteField } = useMutation<
InferResponseType<typeof $delete>,
Error,
InferRequestType<typeof $delete>
>({
mutationFn: async (request) => {
const res = await $delete(request)
if (!res.ok) throw new Error('Failed to delete field')
return null as unknown as InferResponseType<typeof $delete>
},
onSuccess: (_, variables) => {
const newFields = fields.filter((f) => f.id !== variables.param.fieldId)
updateFields(newFields)
setSelectedFieldId(null)
},
})
const groups = useMemo(() => {
// Determine available groups from fields or static list
// User said groups are scope field.
const presentScopes = Array.from(new Set(fields.map((f) => f.scope || 'project')))
// Ensure Project is always there for custom fields
if (!presentScopes.includes('project')) presentScopes.push('project')
return presentScopes.map((scope) => ({
id: scope,
label: GROUP_LABELS[scope] || scope.charAt(0).toUpperCase() + scope.slice(1),
icon: GROUP_ICONS[scope] || FileText,
}))
}, [fields])
const selectedField = useMemo(
() => fields.find((f) => f.id === selectedFieldId),
[fields, selectedFieldId],
)
const resetEditor = (field?: FieldInfo) => {
if (field) {
setEditLabel(field.config?.name || '') // Using name as label for now if label missing
setEditConfig(field.config || {})
setEditAiAutofill(field.aiAutofill || false)
setEditDescription(field.description || '')
} else {
setEditLabel('')
setEditConfig({})
setEditAiAutofill(false)
setEditDescription('')
}
}
const handleSelectField = (field: FieldInfo) => {
setIsCreating(false)
setSelectedFieldId(field.id!)
resetEditor(field)
}
const handleCreateClick = () => {
setIsCreating(true)
setSelectedFieldId(null)
setNewName('')
setNewType('')
setNewAiAutofill(false)
setNewDescription('')
}
const handleDragEnd = (event: DragEndEvent) => {
const { source, target } = event.operation
if (source && target && source.id !== target.id) {
const oldIndex = fields.findIndex((f) => f.id === source.id)
const newIndex = fields.findIndex((f) => f.id === target.id)
const newFields = arrayMove(fields, oldIndex, newIndex)
updateFields(newFields)
// Only persist order if we are in project scope (custom fields)
// or if the API supports ordering for other scopes.
if (selectedGroup === SCOPE_GROUPS.PROJECT) {
updateFieldsOrder({
param: { projectId: projectId },
json: newFields.map((f: MetadataFieldInfo) => ({
fieldId: f.id!,
visible: f.visible || false,
})),
})
}
}
}
const handleSaveCreation = () => {
if (!newName || !newType) return
createField({
param: { projectId: projectId },
json: {
config: {
name: newName,
type: newType,
},
label: newName,
scope: selectedGroup === SCOPE_GROUPS.PROJECT ? undefined : selectedGroup,
aiAutofill: newAiAutofill,
description: newDescription,
},
})
}
const handleSaveEdit = () => {
if (!selectedField) return
updateField({
param: { fieldId: selectedField.id! },
json: {
config: {
...selectedField.config,
...editConfig,
name: editLabel,
},
aiAutofill: editAiAutofill,
description: editDescription,
},
})
}
const handleDelete = () => {
if (!selectedField) return
if (confirm('Are you sure you want to delete this field?')) {
deleteField({ param: { fieldId: selectedField.id! } })
}
}
// --- Render Helpers for Config ---
const renderConfigEditor = () => {
if (isCreating) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Field Name</Label>
<Input
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="e.g. Status"
/>
</div>
<div className="space-y-2">
<Label>Field Type</Label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full justify-between">
{newType ? (
<span className="capitalize">{newType.replace(/_/g, ' ')}</span>
) : (
<span className="text-muted-foreground">Select type</span>
)}
<ChevronDown className="h-4 w-4 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="max-h-60 overflow-y-auto">
{Object.values(FieldType).map((type) => (
<DropdownMenuItem
key={type}
onClick={() => setNewType(type)}
className="capitalize"
>
{type.replace(/_/g, ' ')}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="space-y-2">
<Label>Description</Label>
<Input
value={newDescription}
onChange={(e) => setNewDescription(e.target.value)}
placeholder="Description (Optional)"
/>
</div>
<div className="flex items-center space-x-2">
<Switch checked={newAiAutofill} onCheckedChange={setNewAiAutofill} />
<Label>AI Autofill</Label>
</div>
</div>
)
}
if (!selectedField) {
return <div className="text-muted-foreground text-sm">Select a field to edit options</div>
}
const isReadOnly = selectedField.readOnly
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<Input
value={editLabel}
onChange={(e) => setEditLabel(e.target.value)}
disabled={isReadOnly}
className="font-medium"
/>
{isReadOnly && <Lock className="h-4 w-4 text-muted-foreground ml-2" />}
</div>
{/* Type Specific Configs */}
{/* For Select / Select Multi, we might want option editing */}
{/* For now, just a placeholder or basic json editor if complex? */}
{/* User requirement: "implement editing for all field types" */}
{/* Generic placeholder for options */}
<div className="text-sm text-muted-foreground">
Type: <span className="capitalize">{selectedField.config?.type?.replace(/_/g, ' ')}</span>
</div>
<div className="space-y-2">
<Label>Description</Label>
<Input
value={editDescription}
onChange={(e) => setEditDescription(e.target.value)}
placeholder="Description (Optional)"
disabled={isReadOnly}
/>
</div>
<div className="flex items-center space-x-2">
<Switch
checked={editAiAutofill}
onCheckedChange={setEditAiAutofill}
disabled={isReadOnly}
/>
<Label>AI Autofill</Label>
</div>
{/* TODO: Add specific option editors here */}
{/* Example: Add option button for select types */}
{(selectedField.config?.type === 'select' ||
selectedField.config?.type === 'selectMulti') && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium">Options</label>
<Button
variant="ghost"
size="sm"
onClick={() => {
// Logic to add option
const newOption = {
id: crypto.randomUUID(),
displayName: 'New Option',
color: '#808080',
}
const currentOptions =
(selectedField.config?.type === 'select'
? editConfig.select?.options
: editConfig.selectMulti?.options) || []
const newOptions = [...currentOptions, newOption]
setEditConfig({
...editConfig,
[selectedField.config?.type === 'select' ? 'select' : 'selectMulti']: {
options: newOptions,
},
})
}}
>
<Plus className="h-4 w-4 mr-2" /> Add option
</Button>
</div>
<div className="space-y-2">
{(
(selectedField.config?.type === 'select'
? editConfig.select?.options
: editConfig.selectMulti?.options) || []
).map((opt: SelectOption, idx: number) => (
<div key={idx} className="flex items-center gap-2">
<Input
value={opt.displayName}
onChange={(e) => {
const newOpts = [
...((selectedField.config?.type === 'select'
? editConfig.select?.options
: editConfig.selectMulti?.options) || []),
]
newOpts[idx] = { ...opt, displayName: e.target.value }
setEditConfig({
...editConfig,
[selectedField.config?.type === 'select' ? 'select' : 'selectMulti']: {
options: newOpts,
},
})
}}
/>
<div
className="w-6 h-6 rounded-full border"
style={{ backgroundColor: opt.color }}
></div>
<Button
variant="ghost"
size="icon"
onClick={() => {
const newOpts = (
(selectedField.config?.type === 'select'
? editConfig.select?.options
: editConfig.selectMulti?.options) || []
).filter((_: SelectOption, i: number) => i !== idx)
setEditConfig({
...editConfig,
[selectedField.config?.type === 'select' ? 'select' : 'selectMulti']: {
options: newOpts,
},
})
}}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
</div>
)}
{!isReadOnly && (
<div className="pt-4 flex justify-between">
<Button
variant="outline"
onClick={handleDelete}
className="text-destructive hover:bg-destructive/10"
>
Delete field
</Button>
</div>
)}
</div>
)
}
// --- Main Render ---
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="!max-w-[50rem] h-[70vh] flex flex-col p-0 gap-0">
<div className="p-4 border-b flex items-center justify-between">
<DialogTitle>Manage Fields</DialogTitle>
</div>
<div className="flex overflow-hidden h-full">
{/* Left Column: Groups */}
<div className="w-60 border-r bg-muted/30 p-4 space-y-1">
<div className="font-semibold mb-4 px-2">Groups</div>
{groups.map((group) => (
<button
key={group.id}
onClick={() => {
setSelectedGroup(group.id)
setIsCreating(false)
setSelectedFieldId(null)
}}
className={cn(
'w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-colors hover:bg-muted text-left',
selectedGroup === group.id && 'bg-muted text-foreground',
)}
>
<group.icon className="h-4 w-4" />
{group.label}
</button>
))}
</div>
{/* Middle Column: Field List */}
<div className="w-100 border-r flex flex-col">
<div className="p-4 border-b flex items-center justify-between bg-background h-[57px]">
<span className="font-medium text-sm">
{groups.find((g) => g.id === selectedGroup)?.label}
</span>
<Button size="sm" variant="outline" className="h-8" onClick={handleCreateClick}>
New <Plus className="ml-1 h-3 w-3" />
</Button>
</div>
<div className="flex-1 overflow-y-auto p-2 space-y-1">
<DragDropProvider
sensors={[
PointerSensor.configure({
activationConstraints: [
new PointerActivationConstraints.Distance({ value: 8 }),
],
}),
KeyboardSensor,
]}
onDragEnd={handleDragEnd}
>
{fields.map((field, index) => (
<SortableFieldRow
key={field.id}
field={field}
index={index}
isSelected={selectedFieldId === field.id}
onSelect={handleSelectField}
isSortable={selectedGroup === SCOPE_GROUPS.PROJECT}
/>
))}
</DragDropProvider>
{fields.length === 0 && (
<div className="text-center text-muted-foreground text-sm py-8">
No fields found
</div>
)}
</div>
</div>
{/* Right Column: Config */}
<div className="w-100 bg-background flex flex-col">
<div className="flex-1 overflow-y-auto p-6">{renderConfigEditor()}</div>
{(isCreating || (selectedField && !selectedField.readOnly)) && (
<div className="p-4 border-t flex justify-end gap-2 bg-muted/10">
<Button
variant="ghost"
onClick={() => {
setIsCreating(false)
if (selectedFieldId && selectedField) resetEditor(selectedField)
}}
>
Cancel
</Button>
<Button onClick={isCreating ? handleSaveCreation : handleSaveEdit}>Save</Button>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,176 @@
.editor-container {
border-radius: 8px;
background: transparent;
color: inherit;
position: relative;
line-height: 1.5;
font-weight: 400;
text-align: left;
height: 100%;
}
.editor-inner {
background: transparent;
position: relative;
height: 100%;
}
.editor-input {
height: 100%;
min-height: 150px;
resize: none;
font-size: 15px;
caret-color: inherit;
position: relative;
tab-size: 1;
outline: 0;
padding: 15px 10px;
overflow-y: auto;
}
.editor-placeholder {
color: #999;
overflow: hidden;
position: absolute;
text-overflow: ellipsis;
top: 15px;
left: 10px;
font-size: 15px;
user-select: none;
display: inline-block;
pointer-events: none;
}
.editor-paragraph {
margin: 0 0 15px 0;
position: relative;
}
.editor-paragraph:last-child {
margin-bottom: 0;
}
.editor-heading-h1 {
font-size: 24px;
color: inherit;
font-weight: 400;
margin: 0;
padding: 0;
}
.editor-heading-h2 {
font-size: 15px;
color: inherit;
font-weight: 700;
margin: 0;
padding: 0;
text-transform: uppercase;
}
.editor-quote {
margin: 0;
margin-left: 20px;
font-size: 15px;
color: inherit;
border-left-color: #cecece;
border-left-width: 4px;
border-left-style: solid;
padding-left: 16px;
}
.editor-list-ol {
padding: 0;
margin: 0;
margin-left: 16px;
}
.editor-list-ul {
padding: 0;
margin: 0;
margin-left: 16px;
}
.editor-listitem {
margin: 8px 32px 8px 32px;
}
.editor-nested-listitem {
list-style-type: none;
}
pre {
line-height: 1.5;
}
.editor-code {
background-color: rgba(0, 0, 0, 0.05);
font-family: Menlo, Consolas, Monaco, monospace;
display: block;
padding: 8px 8px 8px 52px;
line-height: 1.53;
font-size: 13px;
margin: 0;
margin-top: 8px;
margin-bottom: 8px;
tab-size: 2;
overflow-x: auto;
position: relative;
}
.dark .editor-code {
background-color: rgba(255, 255, 255, 0.05);
}
.editor-code:before {
content: attr(data-gutter);
position: absolute;
background-color: transparent;
left: 0;
top: 0;
border-right: 1px solid transparent;
padding: 8px;
color: #777;
white-space: pre-wrap;
text-align: right;
min-width: 25px;
}
.editor-text-bold {
font-weight: bold;
}
.editor-text-italic {
font-style: italic;
}
.editor-text-underline {
text-decoration: underline;
}
.editor-text-strikethrough {
text-decoration: line-through;
}
.editor-text-underlineStrikethrough {
text-decoration: underline line-through;
}
.editor-text-code {
background-color: rgba(0, 0, 0, 0.05);
padding: 1px 0.25rem;
font-family: Menlo, Consolas, Monaco, monospace;
font-size: 94%;
}
.dark .editor-text-code {
background-color: rgba(255, 255, 255, 0.05);
}
.editor-link {
color: rgb(33, 111, 219);
text-decoration: none;
}
.editor-link:hover {
text-decoration: underline;
cursor: pointer;
}
@@ -0,0 +1,180 @@
import { CodeHighlightNode, CodeNode } from '@lexical/code'
import { AutoLinkNode, LinkNode } from '@lexical/link'
import { ListItemNode, ListNode } from '@lexical/list'
import {
$convertFromMarkdownString,
$convertToMarkdownString,
TRANSFORMERS,
} from '@lexical/markdown'
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin'
import { LexicalComposer } from '@lexical/react/LexicalComposer'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { ContentEditable } from '@lexical/react/LexicalContentEditable'
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin'
import { MarkdownShortcutPlugin } from '@lexical/react/LexicalMarkdownShortcutPlugin'
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin'
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'
import { HeadingNode, QuoteNode } from '@lexical/rich-text'
import { TableCellNode, TableNode, TableRowNode } from '@lexical/table'
import { useEffect, useRef } from 'react'
import { ToolbarPlugin } from './lexical/plugins/ToolbarPlugin'
import './markdown-editor.css'
const theme = {
ltr: 'ltr',
rtl: 'rtl',
placeholder: 'editor-placeholder',
paragraph: 'editor-paragraph',
quote: 'editor-quote',
heading: {
h1: 'editor-heading-h1',
h2: 'editor-heading-h2',
h3: 'editor-heading-h3',
h4: 'editor-heading-h4',
h5: 'editor-heading-h5',
h6: 'editor-heading-h6',
},
list: {
nested: {
listitem: 'editor-nested-listitem',
},
ol: 'editor-list-ol',
ul: 'editor-list-ul',
listitem: 'editor-listitem',
},
image: 'editor-image',
link: 'editor-link',
text: {
bold: 'editor-text-bold',
italic: 'editor-text-italic',
overflowed: 'editor-text-overflowed',
hashtag: 'editor-text-hashtag',
underline: 'editor-text-underline',
strikethrough: 'editor-text-strikethrough',
underlineStrikethrough: 'editor-text-underlineStrikethrough',
code: 'editor-text-code',
},
code: 'editor-code',
codeHighlight: {
atrule: 'editor-tokenAttr',
attr: 'editor-tokenAttr',
boolean: 'editor-tokenProperty',
builtin: 'editor-tokenSelector',
cdata: 'editor-tokenComment',
char: 'editor-tokenSelector',
class: 'editor-tokenFunction',
'class-name': 'editor-tokenFunction',
comment: 'editor-tokenComment',
constant: 'editor-tokenProperty',
deleted: 'editor-tokenProperty',
doctype: 'editor-tokenComment',
entity: 'editor-tokenOperator',
function: 'editor-tokenFunction',
important: 'editor-tokenVariable',
inserted: 'editor-tokenSelector',
keyword: 'editor-tokenAttr',
namespace: 'editor-tokenVariable',
number: 'editor-tokenProperty',
operator: 'editor-tokenOperator',
prolog: 'editor-tokenComment',
property: 'editor-tokenProperty',
punctuation: 'editor-tokenPunctuation',
regex: 'editor-tokenVariable',
selector: 'editor-tokenSelector',
string: 'editor-tokenSelector',
symbol: 'editor-tokenProperty',
tag: 'editor-tokenProperty',
url: 'editor-tokenOperator',
variable: 'editor-tokenVariable',
},
}
function OnChangeMarkdownPlugin({ onChange }: { onChange: (markdown: string) => void }) {
const [editor] = useLexicalComposerContext()
return (
<OnChangePlugin
ignoreSelectionChange
onChange={() => {
editor.getEditorState().read(() => {
const markdown = $convertToMarkdownString(TRANSFORMERS)
onChange(markdown)
})
}}
/>
)
}
function InitialContentPlugin({ content }: { content: string }) {
const [editor] = useLexicalComposerContext()
const isFirstRender = useRef(true)
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false
editor.update(() => {
$convertFromMarkdownString(content, TRANSFORMERS)
})
}
}, [editor, content])
return null
}
export interface MarkdownEditorProps {
initialContent?: string
onChange?: (content: string) => void
readOnly?: boolean
}
export function MarkdownEditor({
initialContent = '',
onChange,
readOnly = false,
}: MarkdownEditorProps) {
const initialConfig = {
namespace: 'MarkdownEditor',
theme,
editable: !readOnly,
onError: (error: Error) => {
console.error(error)
},
nodes: [
HeadingNode,
ListNode,
ListItemNode,
QuoteNode,
CodeNode,
CodeHighlightNode,
TableNode,
TableCellNode,
TableRowNode,
AutoLinkNode,
LinkNode,
],
}
return (
<LexicalComposer initialConfig={initialConfig}>
<div className={`editor-container ${readOnly ? 'read-only' : ''}`}>
{!readOnly && <ToolbarPlugin />}
<div className="editor-inner">
<RichTextPlugin
contentEditable={<ContentEditable className="editor-input" />}
placeholder={
<div className="editor-placeholder">
{readOnly ? 'No content.' : 'Enter some text...'}
</div>
}
ErrorBoundary={LexicalErrorBoundary}
/>
<HistoryPlugin />
<AutoFocusPlugin />
<MarkdownShortcutPlugin transformers={TRANSFORMERS} />
{onChange && <OnChangeMarkdownPlugin onChange={onChange} />}
<InitialContentPlugin content={initialContent} />
</div>
</div>
</LexicalComposer>
)
}
@@ -0,0 +1,156 @@
import { Avatar, AvatarFallback } from '@/ui/components/ui/avatar'
import { Button } from '@/ui/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { Input } from '@/ui/components/ui/input'
import { ChevronDown, Copy, Loader2 } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
export interface Member {
id?: string
name?: string
role?: string
}
interface MembersDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
title: string
members: Member[]
isOwner: boolean
onInvite?: (role: 'editor' | 'reviewer') => Promise<string>
}
export function MembersDialog({
open,
onOpenChange,
title,
members,
isOwner,
onInvite,
}: MembersDialogProps) {
const [inviteRole, setInviteRole] = useState<'editor' | 'reviewer'>('editor')
const [inviteLink, setInviteLink] = useState<string | null>(null)
const [isGenerating, setIsGenerating] = useState(false)
const handleGenerate = async () => {
if (!onInvite) return
setIsGenerating(true)
try {
const code = await onInvite(inviteRole)
const url = `${window.location.origin}/signup?inviteCode=${code}`
setInviteLink(url)
} catch (error) {
console.error(error)
toast.error('Failed to generate invite link')
} finally {
setIsGenerating(false)
}
}
const copyToClipboard = () => {
if (inviteLink) {
navigator.clipboard.writeText(inviteLink)
toast.success('Invite link copied to clipboard')
}
}
// Get initials for avatar
const getInitials = (name?: string) => {
if (!name) return '??'
return name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
// Reset state when closed
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
setInviteLink(null)
setInviteRole('editor')
}
onOpenChange(newOpen)
}
const safeMembers = Array.isArray(members) ? members : []
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="max-h-[300px] overflow-y-auto space-y-2">
{safeMembers.map((member) => (
<div
key={member.id}
className="flex items-center justify-between p-2 rounded-lg hover:bg-muted/50"
>
<div className="flex items-center gap-3">
<Avatar>
<AvatarFallback>{getInitials(member.name)}</AvatarFallback>
</Avatar>
<div className="flex flex-col">
<span className="text-sm font-medium">{member.name}</span>
<span className="text-xs text-muted-foreground capitalize">{member.role}</span>
</div>
</div>
</div>
))}
</div>
{isOwner && onInvite && (
<div className="border-t pt-4">
<h4 className="text-sm font-medium mb-3">Invite New Member</h4>
<div className="space-y-3">
<div className="flex gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-[120px] justify-between">
{inviteRole === 'editor' ? 'Editor' : 'Reviewer'}
<ChevronDown className="h-4 w-4 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuRadioGroup
value={inviteRole}
onValueChange={(v) => setInviteRole(v as 'editor' | 'reviewer')}
>
<DropdownMenuRadioItem value="editor">Editor</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="reviewer">Reviewer</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
<Button onClick={handleGenerate} disabled={isGenerating} className="flex-1">
{isGenerating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Generate Link
</Button>
</div>
{inviteLink && (
<div className="flex gap-2">
<Input value={inviteLink} readOnly />
<Button variant="outline" size="icon" onClick={copyToClipboard}>
<Copy className="h-4 w-4" />
</Button>
</div>
)}
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,157 @@
import { useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/ui/components/ui/dialog'
import { Button } from '@/ui/components/ui/button'
import { Checkbox } from '@/ui/components/ui/checkbox'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { FolderTree } from './folder-tree'
import { AssetInfo } from '@shumai/dtos'
import { ProjectInfo } from '@shumai/dtos'
import { ScrollArea } from './ui/scroll-area'
import { Loader2 } from 'lucide-react'
interface MoveCopyDialogProps {
isOpen: boolean
onClose: () => void
onConfirm: (targetFolderId: string, withComments: boolean) => void
mode: 'move' | 'copy'
teamId: string
currentProjectId: string
}
export function MoveCopyDialog({
isOpen,
onClose,
onConfirm,
mode,
teamId,
currentProjectId,
}: MoveCopyDialogProps) {
const [selectedProjectId, setSelectedProjectId] = useState(currentProjectId)
const [selectedFolder, setSelectedFolder] = useState<AssetInfo | null>(null)
const [withComments, setWithComments] = useState(false)
const { data: projectsData, isLoading: isLoadingProjects } = useQuery({
queryKey: ['projects', teamId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].projects.$get({
param: { teamId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch projects')
return (await res.json()) as unknown as { data: ProjectInfo[] }
},
enabled: !!teamId && isOpen,
})
const projects = projectsData?.data ?? []
const selectedProject = projects.find((p) => p.id === selectedProjectId)
const handleConfirm = () => {
if (selectedFolder) {
onConfirm(selectedFolder.id, withComments)
} else if (selectedProject?.rootFolder) {
onConfirm(selectedProject.rootFolder, withComments)
}
}
const title = mode === 'move' ? 'Move to' : 'Copy to'
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[425px] flex flex-col h-[600px]">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4 flex-1 overflow-hidden">
<div className="flex flex-col gap-2">
<label className="text-sm font-medium">Select Project</label>
<Select
value={selectedProjectId}
onValueChange={(val) => {
setSelectedProjectId(val)
setSelectedFolder(null)
}}
>
<SelectTrigger>
<SelectValue placeholder="Select a project" />
</SelectTrigger>
<SelectContent>
{projects.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2 flex-1 overflow-hidden">
<label className="text-sm font-medium">Select Folder</label>
<div className="border rounded-md flex-1 overflow-hidden">
<ScrollArea className="h-full">
{selectedProject && selectedProject.rootFolder ? (
<FolderTree
teamId={teamId}
projectId={selectedProject.id}
projectName={selectedProject.name}
rootFolderId={selectedProject.rootFolder}
onSelect={setSelectedFolder}
selectedFolderId={selectedFolder?.id || selectedProject.rootFolder}
/>
) : (
<div className="flex items-center justify-center h-full p-4">
{isLoadingProjects ? (
<Loader2 className="animate-spin h-6 w-6" />
) : (
'Select a project first'
)}
</div>
)}
</ScrollArea>
</div>
</div>
{mode === 'copy' && (
<div className="flex items-center space-x-2">
<Checkbox
id="copy-comments"
checked={withComments}
onCheckedChange={(checked) => setWithComments(!!checked)}
/>
<label
htmlFor="copy-comments"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Copy comments
</label>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button onClick={handleConfirm} disabled={!selectedProject}>
Confirm
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,106 @@
import type { NotificationInfo } from '@shumai/dtos'
import { formatTimeAgo } from '@/ui/lib/time'
import { cn } from '@/ui/lib/utils'
interface NotificationCardProps {
notification: NotificationInfo
}
export const NotificationCard = ({ notification }: NotificationCardProps) => {
const { creator, createdAt, isRead, type, asset, project, team, user } = notification
const message = (() => {
const creatorName = creator?.name || 'Unknown User'
const assetName = asset?.name || 'unknown asset'
const projectName = project?.name || 'unknown project'
const teamName = team?.name || 'unknown team'
const targetUserName = user?.name || 'unknown user'
switch (type) {
case 'comment_created':
return (
<span>
<span className="font-semibold">{creatorName}</span> commented on{' '}
<span className="font-semibold">{assetName}</span>
</span>
)
case 'reply_created':
return (
<span>
<span className="font-semibold">{creatorName}</span> replied to a comment on{' '}
<span className="font-semibold">{assetName}</span>
</span>
)
case 'mention':
return (
<span>
<span className="font-semibold">{creatorName}</span> mentioned you in{' '}
<span className="font-semibold">{assetName}</span>
</span>
)
case 'successful_file_uploaded':
return (
<span>
<span className="font-semibold">{creatorName}</span> uploaded{' '}
<span className="font-semibold">{assetName}</span> to{' '}
<span className="font-semibold">{projectName}</span>
</span>
)
case 'metadata_field_updated_status':
return (
<span>
<span className="font-semibold">{creatorName}</span> updated status of{' '}
<span className="font-semibold">{assetName}</span>
</span>
)
case 'new_user_join_team':
return (
<span>
<span className="font-semibold">{targetUserName}</span> joined{' '}
<span className="font-semibold">{teamName}</span>
</span>
)
case 'new_user_join_project':
return (
<span>
<span className="font-semibold">{targetUserName}</span> joined{' '}
<span className="font-semibold">{projectName}</span>
</span>
)
default:
return (
<span>
New notification from <span className="font-semibold">{creatorName}</span>
</span>
)
}
})()
const hasPreview =
asset?.preview && (asset.mediaType?.startsWith('image') || asset.mediaType?.startsWith('video'))
return (
<div className="flex py-2 cursor-pointer group border border-transparent items-center justify-center">
{/* Unread Indicator */}
<div
className={cn(
'w-1.5 h-1.5 rounded-full shadow-xs',
isRead ? 'bg-transparent' : 'bg-destructive',
)}
/>
<div className="flex-1 min-w-0 flex flex-col justify-center pl-2">
<div className="text-sm text-foreground break-all leading-snug">{message}</div>
<div className="text-[11px] text-muted-foreground mt-1">
{formatTimeAgo(createdAt || '')}
</div>
</div>
{hasPreview && (
<div className="w-18 h-18 ml-2 rounded-md overflow-hidden flex-shrink-0 bg-muted border border-border flex items-center justify-center mt-0.5">
<img src={asset!.preview} alt={asset!.name} className="w-full h-full object-cover" />
</div>
)}
</div>
)
}
@@ -0,0 +1,176 @@
import { client } from '@/ui/api/client'
import { NotificationCard } from '@/ui/components/notification-card'
import { Button } from '@/ui/components/ui/button'
import { Tabs, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { CheckCheckIcon, Loader2 } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import type { InferResponseType } from 'hono/client'
import type { GetMeResponse } from '@shumai/dtos'
export const NotificationList = () => {
const { teamId } = useTeamContextStore()
const [activeTab, setActiveTab] = useState<'all' | 'unread'>('all')
const queryClient = useQueryClient()
const { ref, inView } = useInView()
const getQueryKey = (teamId: string | null, unread: boolean) => [
'notifications',
teamId,
{ unreadOnly: unread },
]
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, refetch } =
useInfiniteQuery({
queryKey: getQueryKey(teamId ?? null, activeTab === 'unread'),
queryFn: async ({ pageParam }) => {
const res = await client.api.teams[':teamId'].notifications.$get({
param: { teamId: teamId! },
query: {
unreadOnly: activeTab === 'unread' ? 'true' : 'false',
...(pageParam ? { after: pageParam } : {}),
pageSize: '20',
},
})
if (!res.ok) throw new Error('failed to fetch notifications')
return res.json()
},
initialPageParam: undefined as string | undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getNextPageParam: (lastPage: any) => lastPage.pageInfo?.cursor || undefined,
enabled: !!teamId,
})
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, fetchNextPage])
// Flatten data
const notifications = useMemo(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
() => data?.pages.flatMap((page: any) => page.data || []) || [],
[data],
)
useEffect(() => {
if (teamId) {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'me'],
})
}
}, [teamId, notifications.length, queryClient])
const $post = client.api.teams[':teamId'].notifications.read.$post
const markReadMutation = useMutation<
InferResponseType<typeof $post>,
Error,
{ teamId: string; notificationId: string }
>({
mutationFn: async ({ teamId, notificationId }) => {
const res = await $post({
param: { teamId: teamId },
json: { notificationId: notificationId },
})
if (!res.ok) throw new Error('failed to mark read')
return null as unknown as InferResponseType<typeof $post>
},
})
const handleMarkAllRead = async () => {
if (notifications.length > 0 && teamId) {
const topId = notifications[0].id
if (topId) {
// Optimistically clear the unread count in React Query cache instantly
queryClient.setQueryData(['teams', teamId, 'me'], (oldData: GetMeResponse | undefined) => {
if (!oldData) return oldData
return {
...oldData,
unreadNotificationCount: 0,
}
})
try {
await markReadMutation.mutateAsync({
teamId,
notificationId: topId,
})
} catch (err) {
console.error('Failed to mark all as read:', err)
}
// Invalidate queries to trigger sync refetches
queryClient.invalidateQueries({
queryKey: ['notifications', teamId],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'me'],
})
// Refetch to update UI state immediately
refetch()
}
}
}
return (
<div className="flex flex-col h-full w-full bg-transparent">
<div className="flex-none pb-1">
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as 'all' | 'unread')}
className="w-full"
>
<div className="flex items-center justify-between mb-2">
<TabsList className="h-8">
<TabsTrigger value="all" className="text-xs px-3 h-6">
All
</TabsTrigger>
<TabsTrigger value="unread" className="text-xs px-3 h-6">
Unread
</TabsTrigger>
</TabsList>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-muted-foreground hover:text-foreground"
onClick={handleMarkAllRead}
disabled={notifications.length === 0 || markReadMutation.isPending}
title="Mark all as read"
>
<CheckCheckIcon className="w-4 h-4" />
</Button>
</div>
</Tabs>
</div>
<div className="flex-1 overflow-y-auto p-2 min-h-0">
{isLoading && (
<div className="flex justify-center p-4">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
)}
{!isLoading && notifications.length === 0 && (
<div className="flex flex-col items-center justify-center h-40 text-muted-foreground">
<p className="text-sm">No notifications</p>
</div>
)}
<div className="space-y-1">
{notifications.map((notification) => (
<NotificationCard key={notification.id} notification={notification} />
))}
</div>
{/* Infinite Scroll Trigger */}
<div ref={ref} className="h-4 w-full flex justify-center p-1">
{isFetchingNextPage && <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />}
</div>
</div>
</div>
)
}
@@ -0,0 +1,355 @@
import type { ProjectInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { Bell, Check, Loader2, Sliders, Sparkles, Upload, X } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
interface ProjectDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
mode: 'create' | 'edit'
teamId: string
project?: ProjectInfo
}
export function ProjectDialog({ open, onOpenChange, mode, teamId, project }: ProjectDialogProps) {
const queryClient = useQueryClient()
const navigate = useNavigate()
const [name, setName] = useState('')
const [enableNotification, setEnableNotification] = useState(true)
// Cover Image State
const [coverImageKey, setCoverImageKey] = useState<string | undefined>(undefined)
const [coverImagePreview, setCoverImagePreview] = useState<string | undefined>(undefined)
const [isUploading, setIsUploading] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (open) {
if (mode === 'edit' && project) {
setName(project.name || '')
setCoverImageKey(project.coverImageKey)
setCoverImagePreview(project.coverImage)
setEnableNotification(project.enableNotification !== false)
} else {
setName('')
setCoverImageKey(undefined)
setCoverImagePreview(undefined)
setEnableNotification(true)
}
}
}, [open, mode, project])
const $post = client.api.teams[':teamId'].projects.$post
const { mutate: createProject } = useMutation<
InferResponseType<typeof $post>,
Error,
InferRequestType<typeof $post>['json']
>({
mutationFn: async (payload) => {
const res = await $post({ param: { teamId: teamId }, json: payload })
if (!res.ok) throw new Error('Failed to create project')
return await res.json()
},
onSuccess: (data) => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'projects'],
})
onOpenChange(false)
const dataObj = data as Record<string, unknown>
if (dataObj && typeof dataObj.id === 'string') {
navigate({
to: '/projects/$projectId',
params: { projectId: dataObj.id },
})
}
},
})
const $put = client.api.projects[':projectId'].$put
const { mutate: updateProject } = useMutation<
InferResponseType<typeof $put>,
Error,
InferRequestType<typeof $put>['json']
>({
mutationFn: async (payload) => {
const res = await $put({
param: { projectId: project!.id! },
json: payload,
})
if (!res.ok) throw new Error('Failed to update project')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'projects'],
})
onOpenChange(false)
},
})
const $upload = client.api.teams[':teamId'].files.$post
const { mutate: uploadFile } = useMutation<
InferResponseType<typeof $upload>,
Error,
{ file: File }
>({
mutationFn: async ({ file }) => {
const res = await $upload({
param: { teamId: teamId },
form: {
file: file,
},
})
if (!res.ok) throw new Error('Failed to upload file')
return await res.json()
},
onSuccess: (data) => {
const obj = data as Record<string, unknown>
if (obj && typeof obj.key === 'string') {
setCoverImageKey(obj.key)
}
setIsUploading(false)
},
onError: () => {
setIsUploading(false)
},
})
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
setIsUploading(true)
// Create local preview
const objectUrl = URL.createObjectURL(file)
setCoverImagePreview(objectUrl)
// Upload
uploadFile({
file: file,
})
}
}
const handleImageAreaClick = () => {
fileInputRef.current?.click()
}
const handleRemoveCover = (e: React.MouseEvent) => {
e.stopPropagation()
setCoverImageKey(undefined)
setCoverImagePreview(undefined)
}
const handleSubmit = () => {
if (!name.trim()) return
if (mode === 'create') {
createProject({
name: name.trim(),
coverImageKey: coverImageKey,
enableNotification: enableNotification,
})
} else if (mode === 'edit' && project?.id) {
updateProject({
name: name.trim(),
coverImageKey: coverImageKey,
enableNotification: enableNotification,
})
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[550px] overflow-hidden rounded-2xl border border-border/60 bg-background/95 backdrop-blur-md shadow-2xl p-0 gap-0">
{/* Beautiful Glowing Header */}
<DialogHeader className="relative overflow-hidden bg-gradient-to-br from-primary/5 to-transparent p-6 border-b border-border/40">
<div className="absolute top-0 right-0 w-24 h-24 bg-primary/10 rounded-full blur-2xl pointer-events-none" />
<div className="absolute bottom-0 left-10 w-32 h-12 bg-primary/5 rounded-full blur-xl pointer-events-none" />
<div className="flex items-center gap-3">
<div>
<DialogTitle className="text-xl font-semibold tracking-tight text-foreground">
{mode === 'create' ? 'Create New Project' : 'Project Settings'}
</DialogTitle>
<DialogDescription className="text-xs text-muted-foreground/80 mt-1">
{mode === 'create'
? 'Configure your new project workspace and appearance.'
: 'Manage and update your project workspace configurations.'}
</DialogDescription>
</div>
</div>
</DialogHeader>
{/* Scrollable Form Content */}
<div className="space-y-6 p-6 max-h-[75vh] overflow-y-auto">
{/* Project Name Field */}
<div className="space-y-2">
<Label htmlFor="name" className="text-sm font-semibold tracking-tight text-foreground">
Project Name
</Label>
<div className="relative">
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Acme Marketing, Q3 Product Launch..."
className="h-11 px-4 rounded-xl border-border/80 focus-visible:ring-ring/25 focus-visible:border-primary transition-all shadow-xs pr-10"
/>
{name.trim() && (
<div className="absolute inset-y-0 right-3 flex items-center">
<Check className="w-4 h-4 text-primary" />
</div>
)}
</div>
<p className="text-[11px] text-muted-foreground">
A clear, concise name to identify your project space.
</p>
</div>
{/* Cover Image & Branding Section */}
<div className="space-y-3 border-t border-border/40 pt-5">
<div className="flex items-center justify-between">
<Label className="text-sm font-semibold tracking-tight text-foreground flex items-center gap-1.5">
<Sparkles className="w-4 h-4 text-primary" />
Project Cover
</Label>
{coverImagePreview && (
<button
type="button"
onClick={handleRemoveCover}
className="text-xs text-muted-foreground hover:text-destructive hover:bg-destructive/5 px-2.5 py-1 rounded-lg transition-all flex items-center gap-1 font-medium"
>
<X className="w-3.5 h-3.5" />
Remove Cover
</button>
)}
</div>
{/* Centered Square 1:1 Preview Area */}
<div
className="relative aspect-square w-48 mx-auto rounded-2xl border border-dashed border-border flex items-center justify-center cursor-pointer overflow-hidden group shadow-inner bg-muted/20 transition-all duration-300 hover:border-primary/50 hover:bg-muted/40"
onClick={handleImageAreaClick}
>
<input
type="file"
ref={fileInputRef}
className="hidden"
accept="image/*"
onChange={handleFileChange}
/>
{/* Uploading Spinner */}
{isUploading && (
<div className="absolute inset-0 bg-background/70 backdrop-blur-xs flex flex-col items-center justify-center gap-2 z-20">
<div className="flex items-center gap-2 px-3 py-1.5 bg-background border rounded-full shadow-lg">
<Loader2 className="w-4 h-4 animate-spin text-primary" />
<span className="text-xs font-semibold text-foreground">Uploading...</span>
</div>
</div>
)}
{coverImagePreview ? (
<>
<img
src={coverImagePreview}
alt="Cover Preview"
className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
/>
{/* Hover Overlay */}
<div className="absolute inset-0 bg-black/45 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center gap-1.5 text-white z-10">
<Upload className="w-5 h-5 transform translate-y-1 group-hover:translate-y-0 transition-transform duration-300" />
<span className="text-xs font-semibold">Upload Image</span>
</div>
</>
) : (
<div className="flex flex-col items-center gap-2 text-center p-4">
<div className="p-2.5 rounded-full bg-background border shadow-xs group-hover:scale-110 transition-transform duration-300">
<Upload className="w-4 h-4 text-muted-foreground" />
</div>
<div>
<p className="text-xs font-medium text-foreground">Upload cover</p>
<p className="text-[11px] text-muted-foreground mt-0.5 max-w-[140px] mx-auto leading-normal">
Drag and drop, or browse. Recommended 1:1 (400×400px).
</p>
</div>
</div>
)}
</div>
</div>
{/* Preferences Section */}
<div className="space-y-3 border-t border-border/40 pt-5">
<Label className="text-sm font-semibold tracking-tight text-foreground flex items-center gap-1.5">
<Sliders className="w-4 h-4 text-primary" />
Project Preferences
</Label>
<div className="flex items-start justify-between rounded-xl border border-border/50 bg-muted/10 p-4 transition-all duration-300 hover:bg-muted/20">
<div className="space-y-1 pr-4">
<div className="text-sm font-semibold flex items-center gap-2 text-foreground">
<Bell className="w-4 h-4 text-primary" />
Activity Notifications
</div>
<p className="text-xs text-muted-foreground leading-normal">
Receive in-app updates for comments, uploads, and automated background analysis
tasks inside this project.
</p>
</div>
<Switch
checked={enableNotification}
onCheckedChange={setEnableNotification}
disabled={isUploading}
className="mt-0.5"
/>
</div>
</div>
</div>
{/* Beautiful Footer with Premium Buttons */}
<DialogFooter className="flex items-center justify-end gap-3 px-6 py-4 bg-muted/20 border-t border-border/40">
<Button
type="button"
variant="ghost"
onClick={() => onOpenChange(false)}
disabled={isUploading}
className="rounded-xl h-10 px-4 hover:bg-muted font-medium text-sm text-muted-foreground hover:text-foreground transition-colors"
>
Cancel
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={!name.trim() || isUploading}
className="rounded-xl h-10 px-5 bg-primary text-primary-foreground hover:bg-primary/90 font-semibold text-sm shadow-lg shadow-primary/10 hover:shadow-primary/20 active:scale-98 transition-all flex items-center gap-2"
>
{isUploading ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Processing...
</>
) : mode === 'create' ? (
'Create Project'
) : (
'Save Changes'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,467 @@
'use client'
import { client } from '@/ui/api/client'
import { useTopNavStore } from '@/ui/stores/top-nav'
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { useEffect, useState, useMemo, useRef } from 'react'
import { TopNav } from './top-nav'
import { FileBrowser } from './file-browser/file-browser'
import { FileViewerRightSidebar } from './file-viewer-right-sidebar'
import { ResizeHandle } from './resize-handle'
import { Card, CardContent, CardHeader, CardTitle } from './ui/card'
import { Input } from './ui/input'
import { Button } from './ui/button'
import { Lock, AlertCircle, Loader2 } from 'lucide-react'
import type { AncestorFolder, AssetInfoPaginatedList, AssetInfo, CommentInfo } from '@shumai/dtos'
import { FieldInfo } from '@shumai/dtos'
import { FileViewer } from './file-viewer'
import type Player from 'video.js/dist/types/player'
import type { Annotation } from '@/ui/types'
import { useNavigate } from '@tanstack/react-router'
interface PublicShareManagerProps {
shareInfo: {
id: string
name: string
expireAt: string | null
isDisabled: boolean
isExpired: boolean
hasPassword: boolean
rootFolderId: string
projectId: string
}
initialFolderId?: string
initialFileId?: string
}
export function PublicShareManager({
shareInfo,
initialFolderId,
initialFileId,
}: PublicShareManagerProps) {
const navigate = useNavigate()
const [password, setPassword] = useState(() => {
return localStorage.getItem(`share_pwd_${shareInfo.id}`) || ''
})
const [passwordInput, setPasswordInput] = useState('')
const [isPasswordValid, setIsPasswordValid] = useState(!shareInfo.hasPassword || !!password)
const currentFolderId = initialFolderId || shareInfo.rootFolderId
const viewingFileId = initialFileId || null
const [ancestorFolders, setAncestorFolders] = useState<AncestorFolder[]>([])
// Fetch ancestors for breadcrumb
const { data: folderInfo } = useQuery({
queryKey: ['public-share-folder', shareInfo.id, currentFolderId, password],
queryFn: async () => {
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
{
param: { shareId: shareInfo.id, fileId: currentFolderId },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.status === 401) throw new Error('Unauthorized')
return (await res.json()) as unknown as AssetInfo
},
enabled: isPasswordValid && !shareInfo.isExpired && !shareInfo.isDisabled,
})
useEffect(() => {
if (folderInfo?.ancestorFolders) {
// Filter ancestors to only those within the share root
const rootIndex = folderInfo.ancestorFolders.findIndex((f) => f.id === shareInfo.rootFolderId)
if (rootIndex !== -1) {
setAncestorFolders(folderInfo.ancestorFolders.slice(0, rootIndex))
} else if (currentFolderId === shareInfo.rootFolderId) {
setAncestorFolders([])
}
}
}, [folderInfo, shareInfo.rootFolderId, currentFolderId])
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [isRightSidebarCollapsed] = useState(false)
const videoRef = useRef<Player | null>(null)
const [annotations, setAnnotations] = useState<Annotation[]>([])
const [currentTime, setCurrentTime] = useState(0)
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
const {
data: foldersData,
fetchNextPage: fetchNextFoldersPage,
hasNextPage: hasNextPageFolders,
isFetchingNextPage: isFetchingNextFoldersPage,
error: foldersError,
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['public-share-children', shareInfo.id, currentFolderId, 'folder', password],
queryFn: async ({ pageParam }) => {
const res = await client.api.shares[':shareId'].folders[':folderId'].children.$get(
{
param: { shareId: shareInfo.id, folderId: currentFolderId },
query: {
assetType: 'folder',
after: pageParam as string,
},
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.status === 401) throw new Error('Unauthorized')
if (res.status === 403) throw new Error('Expired')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
enabled: isPasswordValid && !shareInfo.isExpired && !shareInfo.isDisabled,
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
retry: false,
})
const {
data: filesData,
fetchNextPage: fetchNextFilesPage,
hasNextPage: hasNextPageFiles,
isFetchingNextPage: isFetchingNextFilesPage,
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['public-share-children', shareInfo.id, currentFolderId, 'file', password],
queryFn: async ({ pageParam }) => {
const res = await client.api.shares[':shareId'].folders[':folderId'].children.$get(
{
param: { shareId: shareInfo.id, folderId: currentFolderId },
query: {
assetType: 'file',
after: pageParam as string,
},
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.status === 401) throw new Error('Unauthorized')
if (res.status === 403) throw new Error('Expired')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
enabled: isPasswordValid && !shareInfo.isExpired && !shareInfo.isDisabled,
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
retry: false,
})
const { data: publicFields } = useQuery({
queryKey: ['public-share-fields', shareInfo.id, password],
queryFn: async () => {
const res = await client.api.shares[':shareId'].fields.$get(
{
param: { shareId: shareInfo.id },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.status === 401) throw new Error('Unauthorized')
return (await res.json()) as unknown as FieldInfo[]
},
enabled: isPasswordValid && !shareInfo.isExpired && !shareInfo.isDisabled,
})
const { data: viewingFileData, isLoading: isViewingFileLoading } = useQuery({
queryKey: ['public-share-file', shareInfo.id, viewingFileId, password],
queryFn: async () => {
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
{
param: { shareId: shareInfo.id, fileId: viewingFileId! },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.status === 401) throw new Error('Unauthorized')
return (await res.json()) as unknown as AssetInfo
},
enabled: !!viewingFileId && isPasswordValid && !shareInfo.isExpired && !shareInfo.isDisabled,
})
useEffect(() => {
if (foldersError?.message === 'Unauthorized') {
setIsPasswordValid(false)
setPassword('')
localStorage.removeItem(`share_pwd_${shareInfo.id}`)
}
}, [foldersError, shareInfo.id])
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
const currentSelectedItem = useMemo(() => {
if (viewingFileData) return viewingFileData
if (selectedIds.size !== 1) return null
const id = Array.from(selectedIds)[0]
return [...folders, ...files].find((item) => item.id === id) || null
}, [selectedIds, folders, files, viewingFileData])
const handlePasswordSubmit = (e: React.FormEvent) => {
e.preventDefault()
setPassword(passwordInput)
setIsPasswordValid(true)
localStorage.setItem(`share_pwd_${shareInfo.id}`, passwordInput)
}
const handleItemDoubleClick = (item: AssetInfo) => {
if (item.type === 'folder' || item.targetType === 'folder') {
navigate({
to: '/share/$shareId/folders/$folderId',
params: { shareId: shareInfo.id, folderId: item.id! },
})
} else {
navigate({
to: '/share/$shareId/files/$fileId',
params: {
shareId: shareInfo.id,
fileId: item.versionStack ? item.versionStack.id : item.id!,
},
})
}
setSelectedIds(new Set())
}
const handleBreadcrumbClick = (folderId: string) => {
const targetId = folderId === 'root' ? shareInfo.rootFolderId : folderId
if (targetId === shareInfo.rootFolderId) {
navigate({
to: '/share/$shareId',
params: { shareId: shareInfo.id },
})
} else {
navigate({
to: '/share/$shareId/folders/$folderId',
params: { shareId: shareInfo.id, folderId: targetId },
})
}
setSelectedIds(new Set())
}
const handleCommentSelect = (comment: CommentInfo) => {
setSelectedCommentId(comment.id || null)
const newAnnotations = comment.annotations as Annotation[]
if (newAnnotations && newAnnotations.length > 0) {
setAnnotations(newAnnotations)
} else {
setAnnotations([])
}
if (comment.second !== null && comment.second !== undefined) {
if (videoRef.current) {
videoRef.current.currentTime(comment.second)
videoRef.current.pause()
}
} else if (newAnnotations && newAnnotations.length > 0) {
if (videoRef.current) {
videoRef.current.pause()
}
}
}
const handlePlay = () => {
setAnnotations([])
setSelectedCommentId(null)
}
const { setProjectState, clearProjectState } = useTopNavStore()
useEffect(() => {
if (isPasswordValid && !shareInfo.isExpired && !shareInfo.isDisabled) {
const currentFolderName =
currentFolderId === shareInfo.rootFolderId
? shareInfo.name
: folders.find((f) => f.id === currentFolderId)?.name || shareInfo.name
setProjectState({
teamId: '', // Public view doesn't have team context
projectId: shareInfo.projectId,
projectName: shareInfo.name,
ancestorFolders: ancestorFolders,
currentAsset: {
name: viewingFileData?.name || currentFolderName,
type: viewingFileId ? 'file' : 'folder',
version: viewingFileData?.versionStack
? (viewingFileData.versionStack.versions.find((v) => v.id === viewingFileData.id)
?.version ?? viewingFileData.versionStack.versions.length)
: undefined,
},
isRootFolder: currentFolderId === shareInfo.rootFolderId && !viewingFileId,
isPublic: true,
shareId: shareInfo.id,
onFolderClick: handleBreadcrumbClick,
})
}
return () => clearProjectState()
}, [
isPasswordValid,
shareInfo,
currentFolderId,
folders,
viewingFileData,
viewingFileId,
ancestorFolders,
setProjectState,
clearProjectState,
])
let content
if (shareInfo.isExpired || shareInfo.isDisabled) {
content = (
<div className="flex flex-1 items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10">
<AlertCircle className="h-6 w-6 text-destructive" />
</div>
<CardTitle>Share {shareInfo.isDisabled ? 'Disabled' : 'Expired'}</CardTitle>
</CardHeader>
<CardContent className="text-center text-muted-foreground">
{shareInfo.isDisabled
? 'This share link has been disabled by the owner.'
: 'This share link has expired and is no longer accessible.'}
</CardContent>
</Card>
</div>
)
} else if (!isPasswordValid) {
content = (
<div className="flex flex-1 items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
<Lock className="h-6 w-6 text-primary" />
</div>
<CardTitle>Password Protected</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handlePasswordSubmit} className="space-y-4">
<Input
type="password"
placeholder="Enter password"
value={passwordInput}
onChange={(e) => setPasswordInput(e.target.value)}
autoFocus
/>
<Button type="submit" className="w-full">
Access Share
</Button>
</form>
</CardContent>
</Card>
</div>
)
} else {
content = (
<div className="flex flex-1 overflow-hidden relative">
{viewingFileId ? (
<div className="flex-1 relative bg-muted/30">
{isViewingFileLoading && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
</div>
)}
{viewingFileData && (
<FileViewer
file={viewingFileData}
videoRef={videoRef}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
annotations={annotations}
/>
)}
</div>
) : (
<FileBrowser
teamId=""
projectId={shareInfo.projectId}
assetId={currentFolderId}
folders={folders}
files={files}
selectedItem={null}
selectedIds={selectedIds}
onItemSelect={(item, e) => {
if (e.metaKey || e.ctrlKey) {
const next = new Set(selectedIds)
if (next.has(item.id!)) next.delete(item.id!)
else next.add(item.id!)
setSelectedIds(next)
} else {
setSelectedIds(new Set([item.id!]))
}
}}
onItemDoubleClick={handleItemDoubleClick}
onSaveField={() => {}}
displayStyle="card"
onClearSelection={() => setSelectedIds(new Set())}
fetchNextFoldersPage={fetchNextFoldersPage}
hasNextFoldersPage={hasNextPageFolders}
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
fetchNextFilesPage={fetchNextFilesPage}
hasNextFilesPage={hasNextPageFiles}
isFetchingNextFilesPage={isFetchingNextFilesPage}
isShareView={true}
isPublic={true}
/>
)}
{!isRightSidebarCollapsed && (
<>
<ResizeHandle
onResize={(delta) =>
setRightSidebarWidth((p) => Math.max(240, Math.min(600, p - delta)))
}
/>
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0 border-l">
<FileViewerRightSidebar
teamId=""
projectId={shareInfo.projectId}
file={currentSelectedItem}
onSaveField={() => {}}
members={[]}
readOnly={true}
publicFields={publicFields}
onCommentSelect={handleCommentSelect}
isPublic={true}
shareId={shareInfo.id}
currentTime={currentTime}
onTyping={() => {
if (videoRef.current) {
videoRef.current.pause()
}
}}
selectedCommentId={selectedCommentId}
/>
</div>
</>
)}
</div>
)
}
return (
<div className="flex h-screen flex-col bg-background">
<TopNav />
{content}
</div>
)
}
@@ -0,0 +1,87 @@
import { useEffect, useRef, useState } from 'react'
interface ResizeHandleProps {
onResize: (delta: number) => void
className?: string
}
export const ResizeHandle: React.FC<ResizeHandleProps> = ({
onResize,
className = '',
}) => {
const [isDragging, setIsDragging] = useState(false)
const startXref = useRef(0)
useEffect(() => {
if (!isDragging) return
const handleMouseMove = (e: MouseEvent) => {
// Calculate how much the mouse has moved
const delta = e.clientX - startXref.current
// Update the reference point for the next frame
startXref.current = e.clientX
onResize(delta)
}
const handleMouseUp = () => {
setIsDragging(false)
document.body.style.cursor = '' // Reset cursor
}
// Attach global listeners
document.addEventListener('mousemove', handleMouseMove)
document.addEventListener('mouseup', handleMouseUp)
// Force cursor style on body to prevent flickering during fast drags
document.body.style.cursor = 'col-resize'
return () => {
document.removeEventListener('mousemove', handleMouseMove)
document.removeEventListener('mouseup', handleMouseUp)
document.body.style.cursor = ''
}
}, [isDragging, onResize])
const handleMouseDown = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(true)
startXref.current = e.clientX
}
// Common hit area that is always larger than the visible element for usability
const HitArea = () => (
<div className="absolute inset-y-0 -left-4 -right-4 z-20 cursor-col-resize touch-none" />
)
return (
<div
className={`group relative z-20 flex h-full w-[2px] cursor-col-resize items-center justify-center bg-border transition-all hover:bg-transparent ${className}`}
onMouseDown={handleMouseDown}
>
<HitArea />
{/* The glowing vertical line */}
<div
className={`absolute inset-y-0 w-[2px] transition-all duration-300 ease-out
${
isDragging
? 'bg-blue-600 shadow-[0_0_15px_rgba(37,99,235,0.6)] opacity-100'
: 'bg-blue-400 opacity-0 group-hover:opacity-100 group-hover:shadow-[0_0_8px_rgba(96,165,250,0.5)]'
}
`}
/>
{/* The central drag handle (Pill) */}
<div
className={`absolute top-1/2 left-1/2 h-10 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-blue-600 transition-all duration-300 ease-out
${
isDragging
? 'opacity-100 scale-100 shadow-[0_0_10px_rgba(37,99,235,0.5)]'
: 'opacity-0 scale-75 group-hover:opacity-100 group-hover:scale-100'
}`}
/>
</div>
)
}
@@ -0,0 +1,406 @@
import type { SearchCondition, SearchConditionOperator } from '@shumai/dtos'
import { type FieldInfo } from '@shumai/dtos'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { DebouncedInput } from '@/ui/components/ui/debounced-input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { cn } from '@/ui/lib/utils'
import { Trash2 } from 'lucide-react'
interface FilterPanelProps {
fields: FieldInfo[]
conditions: SearchCondition[]
onChange: (conditions: SearchCondition[]) => void
className?: string
excludeFields?: string[]
hidePrefix?: boolean
}
const SYSTEM_FIELDS = [
{ id: 'name', label: 'Name', type: 'text' },
{ id: 'createdAt', label: 'Created At', type: 'date' },
{ id: 'updatedAt', label: 'Updated At', type: 'date' },
{ id: 'sizeByte', label: 'Size', type: 'number' },
]
export function FilterPanel({
fields,
conditions,
onChange,
className,
excludeFields,
hidePrefix,
}: FilterPanelProps) {
const allFields = [
...SYSTEM_FIELDS,
...fields.map((f) => ({
id: f.id!,
label: f.config?.name || f.description || 'Unknown',
type: getFieldType(f),
options: f.config?.select?.options,
})),
].filter((f) => !excludeFields?.includes(f.id))
const handleAddCondition = () => {
onChange([
...conditions,
{
field: allFields[0]?.id || 'name',
operator: 'eq',
value: '',
},
])
}
const handleRemoveCondition = (index: number) => {
const newConditions = [...conditions]
newConditions.splice(index, 1)
onChange(newConditions)
}
const handleConditionChange = (index: number, key: keyof SearchCondition, value: unknown) => {
const newConditions = [...conditions]
newConditions[index] = { ...newConditions[index], [key]: value } as SearchCondition
// Reset operator/value if field changes
if (key === 'field') {
const field = allFields.find((f) => f.id === value)
if (field) {
newConditions[index].operator = getDefaultOperator(field.type)
newConditions[index].value = ''
}
}
onChange(newConditions)
}
return (
<div className={cn('p-2 space-y-4 min-w-[100px]', className)}>
{conditions.map((condition, index) => (
<div key={index} className="flex items-center gap-2">
{!hidePrefix && (
<div className="w-16 text-sm text-muted-foreground font-medium text-right">
{index === 0 ? 'Where' : 'and'}
</div>
)}
<div className="flex-1 flex items-center gap-2">
<Select
value={condition.field}
onValueChange={(val) => handleConditionChange(index, 'field', val)}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select field" />
</SelectTrigger>
<SelectContent>
{allFields.map((field) => (
<SelectItem key={field.id} value={field.id}>
{field.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={condition.operator}
onValueChange={(val) => handleConditionChange(index, 'operator', val)}
>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="Operator" />
</SelectTrigger>
<SelectContent>
{getOperators(
allFields.find((f) => f.id === condition.field) || {
id: '',
label: '',
type: 'text',
},
).map((op) => (
<SelectItem key={op.value} value={op.value}>
{op.label}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="flex-1">
{condition.operator !== 'isEmpty' && condition.operator !== 'isNotEmpty' && (
<ConditionValueInput
field={allFields.find((f) => f.id === condition.field)}
value={condition.value}
onChange={(val) => handleConditionChange(index, 'value', val)}
/>
)}
</div>
<Button variant="ghost" size="icon" onClick={() => handleRemoveCondition(index)}>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
<div className="flex items-center gap-2">
<Button
variant="ghost"
className="text-muted-foreground hover:text-foreground"
onClick={handleAddCondition}
>
+ Add condition
</Button>
</div>
</div>
)
}
function getFieldType(field: FieldInfo): string {
if (field.config?.type === 'select') return 'select'
if (field.config?.type === 'selectMulti') return 'selectMulti'
if (field.config?.type === 'number') return 'number'
if (field.config?.type === 'date') return 'date'
if (field.config?.type === 'rating') return 'number'
if (field.config?.type === 'toggle') return 'toggle'
return 'text'
}
function getDefaultOperator(type: string): SearchConditionOperator {
switch (type) {
case 'selectMulti':
return 'hasAny' as SearchConditionOperator
case 'number':
case 'date':
return 'eq'
default:
return 'eq' as SearchConditionOperator
}
}
function getOperators(field: { id: string; label: string; type: string }): {
value: SearchConditionOperator
label: string
}[] {
const type = field.type
const id = field.id
if (id === 'name') {
return [
{ value: 'eq' as SearchConditionOperator, label: 'is' },
{ value: 'neq' as SearchConditionOperator, label: 'is not' },
{ value: 'contains' as SearchConditionOperator, label: 'contains' },
{ value: 'notContains' as SearchConditionOperator, label: 'does not contain' },
{ value: 'isEmpty' as SearchConditionOperator, label: 'is empty' },
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
]
}
switch (type) {
case 'text':
return [
{ value: 'eq' as SearchConditionOperator, label: 'is' },
{ value: 'neq' as SearchConditionOperator, label: 'is not' },
{ value: 'isEmpty' as SearchConditionOperator, label: 'is empty' },
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
]
case 'number':
return [
{ value: 'eq' as SearchConditionOperator, label: '=' },
{ value: 'neq' as SearchConditionOperator, label: '≠' },
{ value: 'gt' as SearchConditionOperator, label: '>' },
{ value: 'lt' as SearchConditionOperator, label: '<' },
{ value: 'lte' as SearchConditionOperator, label: '≤' },
{ value: 'gte' as SearchConditionOperator, label: '≥' },
{ value: 'isEmpty' as SearchConditionOperator, label: 'is empty' },
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
]
case 'select':
return [
{ value: 'eq' as SearchConditionOperator, label: 'is' },
{ value: 'neq' as SearchConditionOperator, label: 'is not' },
{ value: 'in' as SearchConditionOperator, label: 'is any of' },
{ value: 'notIn' as SearchConditionOperator, label: 'is none of' },
{ value: 'isEmpty' as SearchConditionOperator, label: 'is empty' },
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
]
case 'selectMulti':
return [
{ value: 'hasAny' as SearchConditionOperator, label: 'has any of' },
{ value: 'hasAll' as SearchConditionOperator, label: 'has all of' },
{ value: 'eq' as SearchConditionOperator, label: 'is exactly' },
{ value: 'hasNone' as SearchConditionOperator, label: 'has none of' },
{ value: 'isEmpty' as SearchConditionOperator, label: 'is empty' },
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
]
case 'date':
return [
{ value: 'eq' as SearchConditionOperator, label: 'is' },
{ value: 'isWithin' as SearchConditionOperator, label: 'is within' },
{ value: 'lt' as SearchConditionOperator, label: 'is before' },
{ value: 'gt' as SearchConditionOperator, label: 'is after' },
{ value: 'lte' as SearchConditionOperator, label: 'is on or before' },
{ value: 'gte' as SearchConditionOperator, label: 'is on or after' },
{ value: 'neq' as SearchConditionOperator, label: 'is not' },
{ value: 'isEmpty' as SearchConditionOperator, label: 'is empty' },
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
]
case 'toggle':
return [{ value: 'eq' as SearchConditionOperator, label: 'is' }]
default:
return [{ value: 'eq' as SearchConditionOperator, label: 'is' }]
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type FieldType = any
function ConditionValueInput({
field,
value,
onChange,
}: {
field: FieldType
value: unknown
onChange: (val: unknown) => void
}) {
if (!field) return <Input disabled />
if (field.type === 'select' && field.options) {
return (
<Select value={value as string} onValueChange={onChange}>
<SelectTrigger>
<SelectValue placeholder="Select option" />
</SelectTrigger>
<SelectContent>
{field.options.map((opt: FieldType) => (
<SelectItem key={opt.id} value={opt.id}>
{opt.displayName}
</SelectItem>
))}
</SelectContent>
</Select>
)
}
if (field.type === 'selectMulti' && field.options) {
const selected = Array.isArray(value) ? value : []
return (
<Select
value={selected[0] || ''}
onValueChange={(val) => {
if (selected.includes(val)) {
onChange(selected.filter((v) => v !== val))
} else {
onChange([...selected, val])
}
}}
>
<SelectTrigger>
<SelectValue
placeholder={selected.length > 0 ? `${selected.length} selected` : 'Select options'}
/>
</SelectTrigger>
<SelectContent>
{field.options.map((opt: FieldType) => (
<SelectItem key={opt.id} value={opt.id}>
<div className="flex items-center gap-2">
<input
type="checkbox"
checked={selected.includes(opt.id)}
readOnly
className="pointer-events-none"
/>
{opt.displayName}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)
}
if (field.type === 'date') {
const relativeDates = [
{ value: 'today', label: 'Today' },
{ value: 'yesterday', label: 'Yesterday' },
{ value: 'tomorrow', label: 'Tomorrow' },
{ value: 'one week ago', label: 'One week ago' },
{ value: 'one week from now', label: 'One week from now' },
{ value: 'one month ago', label: 'One month ago' },
{ value: 'one month from now', label: 'One month from now' },
]
const isRelative = relativeDates.some((rd) => rd.value === value)
return (
<div className="flex gap-2">
<Select
value={isRelative ? (value as string) : 'exact'}
onValueChange={(val) => {
if (val === 'exact') onChange('')
else onChange(val)
}}
>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="Date type" />
</SelectTrigger>
<SelectContent>
{relativeDates.map((rd) => (
<SelectItem key={rd.value} value={rd.value}>
{rd.label}
</SelectItem>
))}
<SelectItem value="exact">Exact date...</SelectItem>
</SelectContent>
</Select>
{!isRelative && (
<Input
type="date"
className="flex-1"
value={value as string}
onChange={(e) => onChange(e.target.value)}
/>
)}
</div>
)
}
if (field.type === 'number') {
return (
<DebouncedInput
type="number"
value={value as string}
onChange={(val) => onChange(Number(val))}
/>
)
}
if (field.type === 'toggle') {
return (
<Select
value={value === true ? 'true' : 'false'}
onValueChange={(val) => onChange(val === 'true')}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="true">Checked</SelectItem>
<SelectItem value="false">Unchecked</SelectItem>
</SelectContent>
</Select>
)
}
return (
<DebouncedInput
type="text"
placeholder="Enter a value"
value={value as string}
onChange={onChange}
/>
)
}
@@ -0,0 +1,511 @@
import { type AssetInfo } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { SearchCondition } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { formatSize } from '@/ui/lib/format'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import {
AlertCircle,
ChevronDown,
ChevronUp,
FileIcon,
FolderIcon,
Loader2,
Search,
X,
} from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { FilterPanel } from './filter-panel'
interface SearchFilterDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
teamId: string
projectId: string
assetId: string
fields: MetadataFieldInfo[]
initialConditions: SearchCondition[]
onApply: (conditions: SearchCondition[]) => void
}
export function SearchFilterDialog({
open,
onOpenChange,
teamId,
projectId,
assetId,
fields,
initialConditions,
onApply,
}: SearchFilterDialogProps) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const initialKeyword = useMemo(() => {
const cond = initialConditions.find((c) => c.field === 'name' && c.operator === 'contains')
return cond ? String(cond.value) : ''
}, [initialConditions])
const initialOtherConditions = useMemo(() => {
return initialConditions.filter((c) => !(c.field === 'name' && c.operator === 'contains'))
}, [initialConditions])
const [conditions, setConditions] = useState<SearchCondition[]>(initialOtherConditions)
const [isFiltersExpanded, setIsFiltersExpanded] = useState(true)
const [searchInput, setSearchInput] = useState(initialKeyword)
const [triggerQuery, setTriggerQuery] = useState(initialKeyword)
const [isSemantic, setIsSemantic] = useState<boolean>(false)
const { data: teamSettings } = useQuery({
queryKey: ['team-settings', teamId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].settings.$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to fetch team settings')
return (await res.json()) as { semanticSearchEnabled: boolean }
},
enabled: open,
})
const semanticSearchEnabled = teamSettings?.semanticSearchEnabled ?? false
// Sync back if changed from outside, clear on close
useEffect(() => {
if (open) {
setSearchInput(initialKeyword)
setTriggerQuery(initialKeyword)
setConditions(initialOtherConditions)
setIsSemantic(false)
} else {
setSearchInput('')
setTriggerQuery('')
setConditions([])
setIsSemantic(false)
}
}, [open, initialKeyword, initialOtherConditions])
const combinedConditions = useMemo(() => {
const result: SearchCondition[] = [...conditions]
const activeText = triggerQuery
if (activeText.trim() && !isSemantic) {
result.push({
field: 'name',
operator: 'contains',
value: activeText.trim(),
})
}
return result
}, [isSemantic, triggerQuery, conditions])
const hasActiveCriteria = useMemo(() => {
const activeText = triggerQuery
return activeText.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
}, [triggerQuery, conditions])
const { mutate: saveAsCollection, isPending: isSaving } = useMutation({
mutationFn: async () => {
const activeText = triggerQuery
let name = activeText.trim()
if (!name && conditions.length > 0) {
const first = conditions[0]
const field = fields.find((f) => f.id === first.field)
const fieldName = field?.config?.name || first.field
name = `${fieldName} ${first.operator} ${first.value}`
}
if (!name) name = 'Untitled Collection'
const res = await client.api.projects[':projectId'].collections.$post({
param: { projectId },
json: {
name,
filter: {
sourceFolderId: assetId,
searchFilter: {
conditions: combinedConditions,
recursively: true,
query: activeText.trim(),
isSemantic: isSemantic,
},
},
},
})
if (!res.ok) throw new Error('Failed to save collection')
return await res.json()
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['collections', projectId] })
toast.success('Collection saved')
onOpenChange(false)
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: data.id },
})
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
})
const {
data: searchResults,
isLoading,
error: searchError,
} = useQuery({
queryKey: ['search-preview', teamId, assetId, combinedConditions, isSemantic, triggerQuery],
queryFn: async () => {
const activeText = triggerQuery
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: assetId },
json: {
assetType: undefined,
conditions: combinedConditions,
recursively: true,
query: activeText.trim(),
isSemantic: isSemantic,
first: 20,
},
})
if (!res.ok) {
const errorData = (await res.json().catch(() => ({}))) as Record<string, unknown>
throw new Error((errorData.message as string) || 'Search failed')
}
return (await res.json()) as { data: AssetInfo[] }
},
enabled: open && hasActiveCriteria,
staleTime: 500,
retry: false,
})
const handleApply = () => {
onApply(combinedConditions)
onOpenChange(false)
}
const handleClearFilters = () => {
setConditions([])
setSearchInput('')
setTriggerQuery('')
setIsSemantic(false)
}
const formatTimestamp = (seconds: number) => {
const m = Math.floor(seconds / 60)
const s = Math.floor(seconds % 60)
return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}
const handleResultClick = (item: AssetInfo) => {
if (item.type === 'folder') {
navigate({
to: '/projects/$projectId/folders/$folderId',
params: { projectId, folderId: item.id! },
})
} else {
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId: item.versionStack ? item.versionStack.id : item.id! },
search: { version: undefined },
})
}
onOpenChange(false)
}
const activeFiltersCount = conditions.filter((c) => c.value !== '').length
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[900px] p-0 gap-0 overflow-hidden bg-background border-border rounded-2xl shadow-2xl flex flex-col max-h-[90vh]">
<DialogHeader className="px-6 pt-3 pb-0 text-left">
<DialogTitle className="text-lg font-bold">Search</DialogTitle>
</DialogHeader>
<div className="px-6 pb-6 pt-4 border-b border-border bg-muted/30 flex flex-col gap-3">
<form
onSubmit={(e) => {
e.preventDefault()
setTriggerQuery(searchInput.trim())
}}
className="flex flex-col gap-3 mt-2"
>
<div className="relative">
<Input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder={
isSemantic ? 'Search records by content...' : 'Search records by name...'
}
className="w-full pl-4 pr-24 py-3 bg-background border-border rounded-xl text-sm h-12 focus-visible:ring-2 focus-visible:ring-primary/20 shadow-sm"
/>
{searchInput && (
<button
type="button"
onClick={() => {
setSearchInput('')
setTriggerQuery('')
}}
className="absolute right-20 top-1/2 -translate-y-1/2 p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors"
>
<X className="w-4 h-4" />
</button>
)}
<button
type="submit"
className="absolute right-1.5 top-1.5 bottom-1.5 px-4 bg-primary hover:bg-primary/90 text-primary-foreground text-xs font-semibold rounded-lg flex items-center justify-center transition-colors shadow-sm"
>
Search
</button>
</div>
<div className="flex items-center gap-3 py-1">
<div className="flex items-center gap-2 bg-background border border-border px-3 py-1.5 rounded-lg shadow-sm">
<Switch
id="semantic-search-switch"
checked={isSemantic}
onCheckedChange={(checked) => {
setIsSemantic(checked)
setSearchInput('')
setTriggerQuery('')
setConditions([])
}}
disabled={!semanticSearchEnabled}
/>
<Label
htmlFor="semantic-search-switch"
className={cn(
'text-xs font-semibold select-none cursor-pointer',
!semanticSearchEnabled && 'opacity-50 cursor-not-allowed',
)}
>
Semantic Search
</Label>
</div>
{!semanticSearchEnabled && (
<span className="text-[10px] text-muted-foreground italic">
* Semantic search requires an enabled embedding agent.
</span>
)}
</div>
</form>
<div
onClick={() => setIsFiltersExpanded(!isFiltersExpanded)}
className="flex items-center justify-between py-1.5 px-1 mt-1 rounded-lg hover:bg-accent/50 cursor-pointer select-none transition-colors group"
>
<div className="flex items-center gap-2">
{isFiltersExpanded ? (
<ChevronUp className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
) : (
<ChevronDown className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
)}
<span className="text-xs font-semibold text-foreground/80">Filters</span>
{activeFiltersCount > 0 && (
<span className="px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/10 text-primary border border-primary/20">
{activeFiltersCount} active
</span>
)}
</div>
{(activeFiltersCount > 0 || searchInput) && (
<button
type="button"
onClick={(e) => {
e.stopPropagation()
handleClearFilters()
}}
className="text-[11px] font-medium text-destructive hover:text-destructive/80 underline underline-offset-2 transition-colors"
>
Reset
</button>
)}
</div>
{isFiltersExpanded && (
<div className="mt-1 p-4 bg-muted/40 border border-border rounded-xl flex flex-col gap-3 animate-in slide-in-from-top-1 duration-200">
<FilterPanel
fields={fields}
conditions={conditions}
onChange={setConditions}
excludeFields={['name']}
hidePrefix={true}
className="p-0 bg-transparent space-y-2"
/>
</div>
)}
</div>
{/* Results Body ported from Demo */}
<div className="flex-1 overflow-y-auto p-4 md:p-5 bg-background">
<div className="flex items-center justify-between mb-3 px-1">
<span className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground/60 font-mono">
Search Results
</span>
{isLoading && (
<span className="inline-flex items-center gap-1.5 text-xs text-primary">
<Loader2 className="h-3 w-3 animate-spin" />
{isSemantic
? 'Semantic search using media intelligence might be slow...'
: 'Querying database...'}
</span>
)}
</div>
<div className="flex flex-col border border-border rounded-xl divide-y divide-border overflow-hidden">
{!hasActiveCriteria ? (
<div className="py-20 text-center flex flex-col items-center justify-center bg-muted/20 px-4">
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
<h3 className="text-sm font-semibold text-foreground/80">Ready to Search</h3>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
Type your query above and click the Search button to display results.
</p>
{isSemantic && (
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
Semantic search results will be ordered by their relevance to the search query
text, but won't be strictly filtered. If you need accurate filtering, please add
filter conditions to control that.
</p>
)}
</div>
) : searchError ? (
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
<AlertCircle className="w-10 h-10 text-destructive/50 mb-2" />
<h3 className="text-sm font-semibold text-foreground/80">Search failed</h3>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
{searchError.message.includes('Embedding agent not configured')
? 'Please create and enable an embedding agent in the team settings to use semantic search.'
: searchError.message}
</p>
</div>
) : isLoading ? (
Array.from({ length: 3 }).map((_, idx) => (
<div key={idx} className="p-3.5 flex items-center gap-3 animate-pulse bg-muted/10">
<div className="w-11 h-11 rounded-xl bg-muted shrink-0" />
<div className="flex-1 space-y-2">
<div className="h-4 bg-muted rounded w-1/3" />
<div className="h-3 bg-muted/50 rounded w-1/4" />
</div>
</div>
))
) : searchResults?.data?.length === 0 ? (
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
<AlertCircle className="w-10 h-10 text-muted-foreground/30 mb-2" />
<h3 className="text-sm font-semibold text-foreground/80">
No records matched your criteria
</h3>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
Try adjusting spelling or removing filter rows.
</p>
</div>
) : (
searchResults?.data?.map((record) => (
<div
key={record.id}
onClick={() => handleResultClick(record)}
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer"
>
<div
className={cn(
'shrink-0 w-11 h-11 rounded-xl shadow-xs flex items-center justify-center text-white font-bold relative group-hover/record:scale-105 transition-transform bg-muted overflow-hidden',
record.type === 'folder' ? 'bg-primary/5' : '',
)}
>
{record.preview?.thumbnailUrl ? (
<img
src={record.preview.thumbnailUrl}
alt=""
className="w-full h-full object-cover rounded-xl"
/>
) : record.type === 'folder' ? (
<FolderIcon className="h-6 w-6 text-primary/70" />
) : (
<FileIcon className="h-6 w-6 text-muted-foreground" />
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3">
<div className="truncate">
<span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate">
{record.name}
</span>
<span className="text-xs text-muted-foreground block mt-0.5 truncate">
{record.type === 'folder'
? 'Folder'
: `Size: ${formatSize(record.sizeByte || 0)}`}
</span>
{record.startTime !== undefined &&
record.startTime !== null &&
record.endTime !== undefined &&
record.endTime !== null && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
Match found at {formatTimestamp(record.startTime)} -{' '}
{formatTimestamp(record.endTime)}
</span>
)}
</div>
<span className="text-xs text-muted-foreground font-mono shrink-0">
{new Date(record.createdAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
})}
</span>
</div>
</div>
</div>
))
)}
</div>
</div>
{/* Footer ported from Demo */}
<div className="p-4 border-t border-border bg-muted/30 flex items-center justify-between shrink-0">
<div className="text-xs text-muted-foreground flex items-center gap-2">
<span>
Matched{' '}
<strong className="font-mono font-bold text-foreground">
{searchResults?.data?.length || 0}
</strong>{' '}
items
</span>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="xs"
className="h-8 text-[10px] font-semibold uppercase tracking-wider mr-1"
disabled={!hasActiveCriteria || isSaving || isSemantic}
onClick={() => saveAsCollection()}
>
{isSaving ? (
<>
<Loader2 className="mr-2 h-3 w-3 animate-spin" />
Saving...
</>
) : (
'Save as collection'
)}
</Button>
<Button
size="xs"
className="h-8 text-[10px] font-semibold uppercase tracking-wider"
onClick={isSemantic ? () => onOpenChange(false) : handleApply}
>
{isSemantic ? 'Close' : 'Apply and Close'}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,120 @@
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { SearchSort } from '@shumai/dtos'
import { ArrowDownUp } from 'lucide-react'
import { Button } from '@/ui/components/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
interface SortControlProps {
fields: MetadataFieldInfo[]
sort?: SearchSort
onSortChange: (sort?: SearchSort) => void
disabled?: boolean
}
const SYSTEM_FIELDS = [
{ id: 'custom', label: 'Custom' },
{ id: 'name', label: 'Name' },
{ id: 'createdAt', label: 'Date Created' },
{ id: 'updatedAt', label: 'Date Modified' },
{ id: 'sizeByte', label: 'Size' },
]
export function SortControl({ fields, sort, onSortChange, disabled }: SortControlProps) {
const allFields = [
...SYSTEM_FIELDS,
...fields.map((f) => ({
id: f.id!,
label: f.config?.name || f.description || 'Unknown',
})),
]
// Default to Custom if no sort selected
const currentFieldId = sort?.field || 'custom'
const currentField = allFields.find((f) => f.id === currentFieldId) || allFields[0]
const isAsc = sort?.order === 'asc'
const getDirectionOptions = (fieldId: string) => {
if (fieldId === 'name') {
return { asc: 'A → Z', desc: 'Z → A' }
}
if (['createdAt', 'updatedAt'].includes(fieldId)) {
return { asc: 'Oldest → Newest', desc: 'Newest → Oldest' }
}
if (fieldId === 'sizeByte') {
return { asc: 'Smallest → Largest', desc: 'Largest → Smallest' }
}
return { asc: 'Ascending', desc: 'Descending' }
}
const dirOptions = getDirectionOptions(currentFieldId)
const handleFieldChange = (fieldId: string) => {
onSortChange({
field: fieldId,
order: sort?.order || 'desc',
})
}
const handleOrderChange = (val: string) => {
onSortChange({
field: currentFieldId,
order: val === 'asc' ? 'asc' : 'desc',
})
}
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant={sort ? 'secondary' : 'ghost'}
size="sm"
className="h-8"
disabled={disabled}
>
{sort ? `Sorted by ${currentField.label}` : 'Sort by'}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[280px] p-3" align="end">
<div className="grid gap-4">
<div className="grid gap-2">
<span className="text-sm text-muted-foreground">Sort by</span>
<Select value={currentFieldId} onValueChange={handleFieldChange}>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
{allFields.map((f) => (
<SelectItem key={f.id} value={f.id}>
{f.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{currentFieldId !== 'custom' && (
<div className="grid gap-2">
<span className="text-sm text-muted-foreground">Order</span>
<Button
variant="outline"
className="w-full justify-between font-normal"
onClick={() => handleOrderChange(isAsc ? 'desc' : 'asc')}
>
<span>{isAsc ? dirOptions.asc : dirOptions.desc}</span>
<ArrowDownUp className="size-4 opacity-50" />
</Button>
</div>
)}
</div>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,486 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Field, FieldLabel, FieldError } from '@/ui/components/ui/field'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { Switch } from '@/ui/components/ui/switch'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm, useStore } from '@tanstack/react-form'
import { Loader2, Puzzle } from 'lucide-react'
import { useEffect, useMemo } from 'react'
import { toast } from 'sonner'
import { AgentInfo, AgentType } from '@shumai/dtos'
import { Textarea } from '@/ui/components/ui/textarea'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { z } from 'zod'
interface AgentFormDialogProps {
isOpen: boolean
onClose: () => void
teamId: string
type?: AgentType
initialValues?: AgentInfo
title: string
}
const agentFormSchema = z.object({
name: z.string().min(1, 'Name is required'),
type: z.enum(['chat', 'autofill', 'embedding']),
avatar: z.string().optional(),
providerId: z.string().optional(),
modelId: z.string().optional(),
soul: z.string().optional(),
thinkingLevel: z.string().optional(),
systemPrompt: z.string().optional(),
skills: z.array(z.string()).optional(),
})
type AgentFormValues = z.infer<typeof agentFormSchema>
export function AgentFormDialog({
isOpen,
onClose,
teamId,
type,
initialValues,
title,
}: AgentFormDialogProps) {
const queryClient = useQueryClient()
// Fetch Providers
const { data: providers } = useQuery({
queryKey: ['teams', teamId, 'providers'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].providers.$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to fetch providers')
return await res.json()
},
enabled: isOpen,
})
// Fetch Skills
const { data: skillsData } = useQuery({
queryKey: ['teams', teamId, 'skills'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].skills.$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to fetch skills')
return await res.json()
},
enabled: isOpen,
})
const allSkills = skillsData?.skills || []
const schema = useMemo(() => {
return agentFormSchema.superRefine((data, ctx) => {
if (data.type === 'chat' || data.type === 'autofill') {
if (!data.providerId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Provider is required',
path: ['providerId'],
})
}
if (!data.modelId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Model is required',
path: ['modelId'],
})
}
}
})
}, [])
const form = useForm({
defaultValues: {
name: initialValues?.name || '',
type: type || initialValues?.type || 'chat',
avatar: initialValues?.avatar || '',
providerId: initialValues?.providerId || '',
modelId: initialValues?.modelId || '',
soul: initialValues?.soul || '',
thinkingLevel: initialValues?.thinkingLevel || 'medium',
systemPrompt: initialValues?.systemPrompt || '',
skills: initialValues?.skills?.map((s) => s.skillId) || ([] as string[]),
} as AgentFormValues,
validators: {
onChange: schema,
},
onSubmit: async ({ value }) => {
try {
if (initialValues?.id) {
await updateMutation.mutateAsync({ id: initialValues.id, values: value })
} else {
await createMutation.mutateAsync(value)
}
} catch {
// Error handled by mutation
}
},
})
// Fetch models for selected provider
const selectedProviderId = useStore(form.store, (s) => s.values.providerId)
const { data: models, isLoading: isModelsLoading } = useQuery({
queryKey: ['teams', teamId, 'providers', selectedProviderId, 'models'],
queryFn: async () => {
const res = await client.api.providers[':id'].models.$get({
param: { id: selectedProviderId! },
})
if (!res.ok) throw new Error('Failed to fetch models')
return await res.json()
},
enabled: !!selectedProviderId && isOpen,
})
const createMutation = useMutation({
mutationFn: async (values: AgentFormValues) => {
const res = await client.api.teams[':teamId'].agents.$post({
param: { teamId },
json: values,
})
if (!res.ok) throw new Error('Failed to create agent')
return await res.json()
},
onSuccess: () => {
onClose()
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
toast.success('Agent created successfully')
},
onError: (error) => {
toast.error(`Error: ${error.message}`)
},
})
const updateMutation = useMutation({
mutationFn: async ({ id, values }: { id: string; values: AgentFormValues }) => {
const res = await client.api.agents[':agentId'].$put({
param: { agentId: id },
json: values,
})
if (!res.ok) throw new Error('Failed to update agent')
return await res.json()
},
onSuccess: () => {
onClose()
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
toast.success('Agent updated successfully')
},
onError: (error) => {
toast.error(`Error: ${error.message}`)
},
})
useEffect(() => {
if (isOpen) {
form.reset()
}
}, [isOpen, initialValues, type])
const agentType = useStore(form.store, (s) => s.values.type)
const isAiType = agentType === 'chat' || agentType === 'autofill'
const mapErrors = (errors: unknown[]) => {
return errors.map((e) => {
if (typeof e === 'string') return { message: e }
if (e && typeof e === 'object' && 'message' in e) {
return { message: String(e.message) }
}
return { message: String(e || '') }
})
}
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-3xl h-[90vh] flex flex-col p-0 overflow-hidden">
<DialogHeader className="p-6 pb-2 flex-shrink-0">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>
Configure your AI agent's personality and capabilities.
</DialogDescription>
</DialogHeader>
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
className="flex-1 flex flex-col min-h-0 overflow-hidden"
>
<ScrollArea className="flex-1 h-full">
<div className="p-6 pt-2 space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<form.Field
name="name"
children={(field) => {
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel>Agent Name</FieldLabel>
<Input
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="e.g., Support Assistant"
aria-invalid={isInvalid}
/>
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
</Field>
)
}}
/>
<form.Field
name="type"
children={(field) => (
<Field>
<FieldLabel>Agent Type</FieldLabel>
<Select
value={field.state.value}
onValueChange={(val) => field.handleChange(val as AgentType)}
disabled={true}
>
<SelectTrigger className="bg-slate-50 dark:bg-slate-900/50">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="chat">Chat</SelectItem>
<SelectItem value="autofill">Autofill</SelectItem>
<SelectItem value="embedding">Embedding</SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>
</div>
{isAiType && (
<>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800">
<form.Field
name="providerId"
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel>Provider</FieldLabel>
<Select
value={field.state.value}
onValueChange={(val) => {
field.handleChange(val)
form.setFieldValue('modelId', '')
}}
>
<SelectTrigger aria-invalid={isInvalid}>
<SelectValue placeholder="Select Provider" />
</SelectTrigger>
<SelectContent>
{providers?.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name}
</SelectItem>
))}
</SelectContent>
</Select>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
<form.Field
name="modelId"
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel className="flex items-center gap-2">
Model
{isModelsLoading && <Loader2 className="w-3 h-3 animate-spin" />}
</FieldLabel>
<Select
value={field.state.value}
onValueChange={field.handleChange}
disabled={!selectedProviderId || isModelsLoading}
>
<SelectTrigger aria-invalid={isInvalid}>
<SelectValue placeholder="Select Model" />
</SelectTrigger>
<SelectContent>
{models?.map((m) => (
<SelectItem key={m.id} value={m.id}>
{m.name || m.modelId}
</SelectItem>
))}
</SelectContent>
</Select>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
<div className="md:col-span-2">
<form.Field
name="thinkingLevel"
children={(field) => (
<Field>
<FieldLabel>Thinking Level</FieldLabel>
<Select value={field.state.value} onValueChange={field.handleChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="low">Low (Fast)</SelectItem>
<SelectItem value="medium">Medium (Balanced)</SelectItem>
<SelectItem value="high">High (Reasoning)</SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>
</div>
</div>
<form.Field
name="soul"
children={(field) => (
<Field>
<FieldLabel>Agent Soul (Personality)</FieldLabel>
<Textarea
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="Describe the agent's personality, tone, and behavior..."
className="min-h-[120px]"
/>
</Field>
)}
/>
<div className="space-y-4">
<Label className="text-base font-bold flex items-center gap-2">
<Puzzle className="w-5 h-5 text-blue-600" />
Skills
</Label>
<div className="space-y-2">
<form.Field
name="skills"
children={(skillsField) => (
<>
{allSkills.map((skill) => {
const isEnabled = skillsField.state.value?.includes(skill.id) || false
return (
<div
key={skill.id}
className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg"
>
<div className="flex items-center gap-3">
<Puzzle className="w-4 h-4 text-slate-400" />
<div className="flex flex-col">
<span className="text-sm font-medium">{skill.name}</span>
{skill.description && (
<span className="text-[10px] text-slate-500 line-clamp-1">
{skill.description}
</span>
)}
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-slate-500">
{isEnabled ? 'Enabled' : 'Disabled'}
</span>
<Switch
checked={isEnabled}
onCheckedChange={(checked) => {
if (checked) {
skillsField.handleChange([
...(skillsField.state.value || []),
skill.id,
])
} else {
skillsField.handleChange(
(skillsField.state.value || []).filter(
(id) => id !== skill.id,
),
)
}
}}
/>
</div>
</div>
)
})}
{allSkills.length === 0 && (
<div className="text-center py-8 border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-xl">
<p className="text-sm text-slate-400">No skills available.</p>
</div>
)}
</>
)}
/>
</div>
</div>
</>
)}
</div>
</ScrollArea>
<DialogFooter className="p-6 pt-4 border-t dark:border-slate-800 flex-shrink-0">
<Button variant="outline" onClick={onClose} type="button">
Cancel
</Button>
<form.Subscribe
selector={(state) => [state.canSubmit, state.isSubmitting]}
children={([canSubmit, isSubmitting]) => (
<Button
type="submit"
className="bg-blue-600 hover:bg-blue-700 text-white min-w-[120px]"
disabled={
!canSubmit ||
isSubmitting ||
createMutation.isPending ||
updateMutation.isPending
}
>
{(isSubmitting || createMutation.isPending || updateMutation.isPending) && (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
)}
{initialValues ? 'Save Changes' : 'Create Agent'}
</Button>
)}
/>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,366 @@
import { client } from '@/ui/api/client'
import { Card, CardContent } from '@/ui/components/ui/card'
import { Button } from '@/ui/components/ui/button'
import { Badge } from '@/ui/components/ui/badge'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
Loader2,
Plus,
Trash2,
Bot,
MoreVertical,
MessageSquare,
Zap,
Cpu,
Puzzle,
} from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { AgentInfo, AgentType } from '@shumai/dtos'
import { AgentFormDialog } from './AgentFormDialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { cn } from '@/ui/lib/utils'
import { ChevronDown } from 'lucide-react'
import { Switch } from '@/ui/components/ui/switch'
interface AgentsSettingsProps {
teamId: string
}
const AGENT_TYPES: {
type: AgentType
label: string
icon: React.FC<React.SVGProps<SVGSVGElement>>
}[] = [
{ type: 'chat', label: 'Chat', icon: MessageSquare },
{ type: 'autofill', label: 'Autofill', icon: Zap },
{ type: 'embedding', label: 'Embedding', icon: Cpu },
]
export function AgentsSettings({ teamId }: AgentsSettingsProps) {
const queryClient = useQueryClient()
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [createType, setCreateType] = useState<AgentType>('chat')
const [editingAgent, setAgentToEdit] = useState<AgentInfo | null>(null)
const [agentToDelete, setAgentToDelete] = useState<AgentInfo | null>(null)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
chat: true,
autofill: true,
embedding: true,
})
const { data: agents = [], isLoading } = useQuery({
queryKey: ['agents', teamId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].agents.$get({
param: { teamId },
})
if (!res.ok) throw new Error('failed to fetch agents')
const data = await res.json()
return [...data].sort((a, b) => b.id.localeCompare(a.id))
},
})
const deleteAgentMutation = useMutation({
mutationFn: async (agentId: string) => {
const res = await client.api.agents[':agentId'].$delete({
param: { agentId },
})
if (!res.ok) throw new Error('failed to delete agent')
},
onSuccess: () => {
setIsDeleteDialogOpen(false)
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
toast.success('Agent deleted successfully')
},
onError: (error) => {
toast.error(error.message)
},
})
const updateAgentMutation = useMutation({
mutationFn: async (params: {
teamId: string
agentId: string
name: string
type: AgentType
enabled: boolean
avatar?: string
providerId?: string
modelId?: string
thinkingLevel?: string
systemPrompt?: string
soul?: string
skills?: string[]
}) => {
const res = await client.api.agents[':agentId'].$put({
param: { agentId: params.agentId },
json: {
name: params.name,
type: params.type,
enabled: params.enabled,
avatar: params.avatar,
providerId: params.providerId,
modelId: params.modelId,
thinkingLevel: params.thinkingLevel,
systemPrompt: params.systemPrompt,
soul: params.soul,
skills: params.skills,
},
})
if (!res.ok) throw new Error('failed to update agent')
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
toast.success('Agent updated successfully')
},
onError: (error) => {
toast.error(error.message)
},
})
const toggleSection = (type: string) => {
setExpandedSections((prev) => ({
...prev,
[type]: !prev[type],
}))
}
return (
<>
{(isCreateDialogOpen || editingAgent) && (
<AgentFormDialog
isOpen={true}
title={editingAgent ? `Edit ${editingAgent.name}` : `Create ${createType} Agent`}
onClose={() => {
setIsCreateDialogOpen(false)
setAgentToEdit(null)
}}
teamId={teamId}
type={createType}
initialValues={editingAgent || undefined}
/>
)}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete the agent "
{agentToDelete?.name}" and remove all its data from our servers.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-white"
onClick={(e) => {
if (deleteAgentMutation.isPending) {
e.preventDefault()
return
}
if (agentToDelete) {
deleteAgentMutation.mutate(agentToDelete.id)
}
}}
>
{deleteAgentMutation.isPending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
'Delete Agent'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{isLoading && agents.length === 0 ? (
<div className="flex items-center justify-center p-12">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-6 max-w-5xl mx-auto relative">
{isLoading && (
<div className="absolute top-0 right-0 p-2">
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
</div>
)}
{AGENT_TYPES.map((section) => {
const typeAgents = agents.filter((a) => a.type === section.type)
const Icon = section.icon
return (
<div
key={section.type}
className="bg-card rounded-xl border border-border overflow-hidden"
>
<div
className="px-6 py-4 flex items-center justify-between cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => toggleSection(section.type)}
>
<div className="flex items-center gap-2">
<h3 className="font-semibold text-foreground">{section.label} Agents</h3>
<Badge variant="secondary" className="h-5 px-1.5 min-w-[1.25rem] text-[10px]">
{typeAgents.length}
</Badge>
</div>
<div className="flex items-center gap-2">
{!(
(section.type === 'autofill' || section.type === 'embedding') &&
typeAgents.length > 0
) && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 rounded-full bg-primary/10 text-primary hover:bg-primary/20"
onClick={(e) => {
e.stopPropagation()
setCreateType(section.type)
setIsCreateDialogOpen(true)
}}
>
<Plus className="w-4 h-4" />
</Button>
)}
<ChevronDown
className={cn(
'w-5 h-5 text-muted-foreground transition-transform duration-200',
expandedSections[section.type] ? 'rotate-180' : '',
)}
/>
</div>
</div>
{expandedSections[section.type] && (
<div className="px-6 pb-6 pt-2 space-y-3">
<div className="grid grid-cols-1 gap-4">
{typeAgents.map((agent) => (
<Card
key={agent.id}
className="group relative overflow-hidden border-border hover:border-primary/50 transition-all duration-200 cursor-pointer"
onClick={() => setAgentToEdit(agent)}
>
<CardContent className="p-4 flex items-center justify-between">
<div className="flex items-center gap-3 min-w-0 flex-1">
<div className="w-10 h-10 rounded-full bg-muted flex items-center justify-center overflow-hidden">
{agent.avatar ? (
<img
src={agent.avatar}
className="w-full h-full object-cover"
alt=""
/>
) : (
<Bot className="w-6 h-6 text-muted-foreground" />
)}
</div>
<div className="min-w-0 flex-1">
<span className="font-bold text-foreground block truncate">
{agent.name}
</span>
<div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
<span className="flex items-center gap-1">
<Puzzle className="w-3 h-3" />
{agent.skills?.length || 0} Skills
</span>
</div>
</div>
</div>
<div className="flex items-center gap-1">
<div className="mr-2" onClick={(e) => e.stopPropagation()}>
<Switch
checked={agent.enabled}
onCheckedChange={(enabled) => {
updateAgentMutation.mutate({
teamId,
agentId: agent.id,
name: agent.name,
type: agent.type,
enabled,
avatar: agent.avatar,
providerId: agent.providerId,
modelId: agent.modelId,
thinkingLevel: agent.thinkingLevel,
systemPrompt: agent.systemPrompt,
soul: agent.soul,
skills: agent.skills?.map((s) => s.skillId),
})
}}
/>
</div>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
>
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-32">
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
setAgentToDelete(agent)
setIsDeleteDialogOpen(true)
}}
className="text-red-500 focus:text-red-500 gap-2 cursor-pointer"
>
<Trash2 className="w-4 h-4" /> Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>{' '}
</div>
</CardContent>
</Card>
))}
{typeAgents.length === 0 && (
<div className="col-span-full py-8 flex flex-col items-center justify-center border-2 border-dashed border-border rounded-xl bg-muted/30">
<div className="w-10 h-10 rounded-full bg-card flex items-center justify-center shadow-sm mb-3">
<Icon className="w-5 h-5 text-muted-foreground" />
</div>
<p className="text-sm text-muted-foreground">
No {section.label} agents found
</p>
<Button
variant="link"
size="sm"
className="text-primary font-medium h-auto p-0 mt-1"
onClick={() => {
setCreateType(section.type)
setIsCreateDialogOpen(true)
}}
>
Create one now
</Button>
</div>
)}
</div>
</div>
)}
</div>
)
})}
</div>
)}
</>
)
}
@@ -0,0 +1,228 @@
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { Switch as ShadcnSwitch } from '@/ui/components/ui/switch'
import { Textarea } from '@/ui/components/ui/textarea'
import React from 'react'
import { PROVIDERS } from './constants'
import { ThinkingLevel } from './types'
// --- Section Header ---
export const SectionLabel: React.FC<{
label: string
subLabel?: string
htmlFor?: string
}> = ({ label, subLabel, htmlFor }) => (
<div className="mb-2">
<Label htmlFor={htmlFor} className="block text-sm font-medium">
{label}
</Label>
{subLabel && <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{subLabel}</p>}
</div>
)
// --- Text Input ---
interface TextInputProps extends React.ComponentProps<typeof Input> {
label: string
}
export const TextInput: React.FC<TextInputProps> = ({ label, className = '', id, ...props }) => (
<div className="space-y-2">
<Label htmlFor={id}>{label}</Label>
<Input className={className} id={id} {...props} />
</div>
)
// --- Agent Type Selector ---
export const AgentTypeSelector: React.FC<{
value: 'chat' | 'autofill'
onChange: (val: 'chat' | 'autofill') => void
}> = ({ value, onChange }) => {
return (
<div className="space-y-2">
<SectionLabel label="Agent Type" />
<Select value={value} onValueChange={(val: 'chat' | 'autofill') => onChange(val)}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="chat">Chat Agent</SelectItem>
<SelectItem value="autofill">Autofill Agent</SelectItem>
</SelectContent>
</Select>
</div>
)
}
// --- Text Area ---
interface TextAreaProps extends React.ComponentProps<typeof Textarea> {
label: string
subLabel?: string
}
export const TextArea: React.FC<TextAreaProps> = ({
label,
subLabel,
className = '',
id,
...props
}) => (
<div className="space-y-2">
<SectionLabel label={label} subLabel={subLabel} htmlFor={id} />
<Textarea className={`resize-y min-h-[100px] ${className}`} id={id} {...props} />
</div>
)
// --- Provider & Model Selector ---
interface ModelSelectorProps {
provider: string | undefined
model: string | undefined
models: string[]
onProviderChange: (p: string) => void
onModelChange: (m: string) => void
label?: string // Optional custom label
subLabel?: string
}
export const ModelSelector: React.FC<ModelSelectorProps> = ({
provider,
model,
models,
onProviderChange,
onModelChange,
label = 'AI Provider',
subLabel,
}) => {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<SectionLabel label={label} subLabel={subLabel} />
<Select value={provider || ''} onValueChange={(val) => onProviderChange(val)}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select provider" />
</SelectTrigger>
<SelectContent>
{PROVIDERS.map((p) => (
<SelectItem key={p.value} value={p.value}>
{p.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<SectionLabel label="Model" />
<Select value={model || ''} onValueChange={(val) => onModelChange(val)}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select model" />
</SelectTrigger>
<SelectContent>
{models.length > 0 ? (
models.map((m) => (
<SelectItem key={m} value={m}>
{m}
</SelectItem>
))
) : (
<SelectItem value="none" disabled>
No models configured
</SelectItem>
)}
</SelectContent>
</Select>
</div>
</div>
)
}
// --- Thinking Level Selector ---
interface ThinkingLevelSelectorProps {
value: ThinkingLevel | string | undefined
onChange: (val: ThinkingLevel) => void
disabled?: boolean
label?: string
}
export const ThinkingLevelSelector: React.FC<ThinkingLevelSelectorProps> = ({
value,
onChange,
disabled,
label = 'Thinking Strength',
}) => {
const levels = [
{
id: ThinkingLevel.DISABLED,
label: 'Disable',
desc: 'Standard generation',
},
{ id: ThinkingLevel.LOW, label: 'Low', desc: 'Quick reasoning' },
{ id: ThinkingLevel.MEDIUM, label: 'Medium', desc: 'Balanced thought' },
{ id: ThinkingLevel.HIGH, label: 'High', desc: 'Deep reasoning' },
]
return (
<div className={disabled ? 'opacity-50 pointer-events-none grayscale' : ''}>
<SectionLabel label={label} subLabel="Control the depth of reasoning for complex tasks." />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
{levels.map((level) => {
const isSelected = value === level.id
return (
<button
key={level.id}
onClick={(e) => {
e.preventDefault()
onChange(level.id)
}}
className={`flex flex-col items-center justify-center p-3 rounded-lg border transition-all duration-200 ${
isSelected
? 'bg-blue-50 dark:bg-blue-900/30 border-blue-500 dark:border-blue-400 text-blue-700 dark:text-blue-300 ring-1 ring-blue-500 dark:ring-blue-400'
: 'bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:border-slate-300 dark:hover:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-900'
}`}
>
<span
className={`text-sm font-semibold ${isSelected ? 'text-blue-700 dark:text-blue-300' : 'text-slate-900 dark:text-white'}`}
>
{level.label}
</span>
<span
className={`text-[10px] mt-1 ${isSelected ? 'text-blue-600 dark:text-blue-400' : 'text-slate-500 dark:text-slate-500'}`}
>
{level.desc}
</span>
</button>
)
})}
</div>
</div>
)
}
// --- Toggle Switch ---
interface SwitchProps {
label: string
description?: string
checked: boolean | undefined // Handle optional/undefined from API
onChange: (checked: boolean) => void
}
export const Switch: React.FC<SwitchProps> = ({ label, description, checked, onChange }) => {
const isChecked = !!checked
return (
<div className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm">
<div className="space-y-0.5">
<Label className="text-base cursor-pointer" onClick={() => onChange(!isChecked)}>
{label}
</Label>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
</div>
<ShadcnSwitch checked={isChecked} onCheckedChange={onChange} />
</div>
)
}
@@ -0,0 +1,227 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Switch } from '@/ui/components/ui/switch'
import {
Loader2,
MessageSquare,
MessageCircle,
AtSign,
UploadCloud,
Activity,
Bell,
} from 'lucide-react'
import { toast } from 'sonner'
import type { NotificationSettings as Settings } from '@shumai/dtos'
export function NotificationSettings({ teamId }: { teamId: string }) {
const queryClient = useQueryClient()
const { data: settings, isLoading } = useQuery({
queryKey: ['teams', teamId, 'notification-settings'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].notifications.settings.$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to fetch notification settings')
return (await res.json()) as Settings
},
})
const { mutate: updateSettings, isPending: isUpdating } = useMutation({
mutationFn: async (updated: Settings) => {
const res = await client.api.teams[':teamId'].notifications.settings.$post({
param: { teamId },
json: updated,
})
if (!res.ok) throw new Error('Failed to update notification settings')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'notification-settings'] })
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'notifications'] })
toast.success('Notification settings updated')
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : 'Failed to update notification settings')
},
})
const handleToggle = (key: keyof Settings) => {
if (!settings) return
const updated = {
...settings,
[key]: !settings[key],
}
updateSettings(updated)
}
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="h-full overflow-y-auto space-y-6 pr-1">
{/* Comments Settings */}
<Card className="border border-slate-200 dark:border-slate-800">
<CardHeader className="border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50">
<div className="flex items-center gap-2">
<MessageSquare className="w-5 h-5 text-blue-500" />
<CardTitle className="text-lg">Comments & Replies</CardTitle>
</div>
<CardDescription>
Control notification preferences when other users comment on assets you collaborate on
or mention you.
</CardDescription>
</CardHeader>
<CardContent className="divide-y divide-slate-100 dark:divide-slate-800 p-0">
{/* General Comments */}
<div className="flex items-center justify-between p-6">
<div className="flex gap-4">
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400">
<MessageSquare className="w-4 h-4" />
</div>
<div className="space-y-0.5">
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">
General Comments
</h4>
<p className="text-sm text-slate-500 dark:text-slate-400">
When someone comments on an asset
</p>
</div>
</div>
<Switch
checked={settings?.comments ?? true}
onCheckedChange={() => handleToggle('comments')}
disabled={isUpdating}
/>
</div>
{/* Comment Replies */}
<div className="flex items-center justify-between p-6">
<div className="flex gap-4">
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400">
<MessageCircle className="w-4 h-4" />
</div>
<div className="space-y-0.5">
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">
Comment Replies
</h4>
<p className="text-sm text-slate-500 dark:text-slate-400">
When someone replies to your comment
</p>
</div>
</div>
<Switch
checked={settings?.replies ?? true}
onCheckedChange={() => handleToggle('replies')}
disabled={isUpdating}
/>
</div>
{/* Mentions */}
<div className="flex items-center justify-between p-6">
<div className="flex gap-4">
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-pink-50 dark:bg-pink-900/20 text-pink-600 dark:text-pink-400">
<AtSign className="w-4 h-4" />
</div>
<div className="space-y-0.5">
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">@Mentions</h4>
<p className="text-sm text-slate-500 dark:text-slate-400">
When someone @mentions you in a comment
</p>
</div>
</div>
<Switch
checked={settings?.mentions ?? true}
onCheckedChange={() => handleToggle('mentions')}
disabled={isUpdating}
/>
</div>
</CardContent>
</Card>
{/* Assets Settings */}
<Card className="border border-slate-200 dark:border-slate-800">
<CardHeader className="border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50">
<div className="flex items-center gap-2">
<UploadCloud className="w-5 h-5 text-emerald-500" />
<CardTitle className="text-lg">Assets & Statuses</CardTitle>
</div>
<CardDescription>
Manage notifications related to file uploads and metadata field status updates.
</CardDescription>
</CardHeader>
<CardContent className="divide-y divide-slate-100 dark:divide-slate-800 p-0">
{/* Your Uploads */}
<div className="flex items-center justify-between p-6">
<div className="flex gap-4">
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">
<Bell className="w-4 h-4" />
</div>
<div className="space-y-0.5">
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">
Your Uploads
</h4>
<p className="text-sm text-slate-500 dark:text-slate-400">When you upload assets</p>
</div>
</div>
<Switch
checked={settings?.yourUploads ?? false}
onCheckedChange={() => handleToggle('yourUploads')}
disabled={isUpdating}
/>
</div>
{/* Other Uploads */}
<div className="flex items-center justify-between p-6">
<div className="flex gap-4">
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400">
<UploadCloud className="w-4 h-4" />
</div>
<div className="space-y-0.5">
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">
Other Uploads
</h4>
<p className="text-sm text-slate-500 dark:text-slate-400">
When other users upload assets
</p>
</div>
</div>
<Switch
checked={settings?.otherUploads ?? true}
onCheckedChange={() => handleToggle('otherUploads')}
disabled={isUpdating}
/>
</div>
{/* Status Updates */}
<div className="flex items-center justify-between p-6">
<div className="flex gap-4">
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400">
<Activity className="w-4 h-4" />
</div>
<div className="space-y-0.5">
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">
Status Updates
</h4>
<p className="text-sm text-slate-500 dark:text-slate-400">
When someone changes an asset’s status
</p>
</div>
</div>
<Switch
checked={settings?.statusUpdates ?? true}
onCheckedChange={() => handleToggle('statusUpdates')}
disabled={isUpdating}
/>
</div>
</CardContent>
</Card>
</div>
)
}
@@ -0,0 +1,942 @@
import { client } from '@/ui/api/client'
import { Card, CardContent } from '@/ui/components/ui/card'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Field, FieldLabel, FieldDescription, FieldError } from '@/ui/components/ui/field'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { Switch } from '@/ui/components/ui/switch'
import { Badge } from '@/ui/components/ui/badge'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm } from '@tanstack/react-form'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import {
Loader2,
Plus,
Trash2,
Cpu,
Globe,
ChevronRight,
Info,
DollarSign,
Maximize2,
Zap,
Search,
MoreVertical,
} from 'lucide-react'
import { useState, useMemo, useEffect } from 'react'
import { toast } from 'sonner'
import { InferResponseType } from 'hono/client'
import { providerConfigSchema, providerModelSchema } from '@shumai/dtos'
import { z } from 'zod'
const providerFormSchemaBase = z.object({
name: z.string().min(1, 'Provider name is required'),
config: providerConfigSchema,
models: z.array(providerModelSchema).min(1, 'At least one model is required'),
})
type ProviderFormValues = z.infer<typeof providerFormSchemaBase>
type ProvidersResponse = InferResponseType<
(typeof client.api.teams)[':teamId']['providers']['$get']
>
type Provider = ProvidersResponse[number]
interface ProvidersSettingsProps {
teamId: string
}
export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
const queryClient = useQueryClient()
const [editingProviderId, setEditingProviderId] = useState<string | null>(null)
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [providerToDelete, setProviderToDelete] = useState<Provider | null>(null)
// Fetch Providers
const { data: providers, isLoading } = useQuery({
queryKey: ['teams', teamId, 'providers'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].providers.$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to fetch providers')
return await res.json()
},
})
const editingProvider = useMemo(
() => providers?.find((p) => p.id === editingProviderId) || null,
[providers, editingProviderId],
)
// Fetch models for editing
const { data: editingModels, isLoading: isModelsLoading } = useQuery({
queryKey: ['teams', teamId, 'providers', editingProviderId, 'models'],
queryFn: async () => {
const res = await client.api.providers[':id'].models.$get({
param: { id: editingProviderId! },
})
if (!res.ok) throw new Error('Failed to fetch models')
return await res.json()
},
enabled: !!editingProviderId,
})
const existingProviderNames = useMemo(() => providers?.map((p) => p.name) || [], [providers])
const filteredProviders = useMemo(() => {
if (!providers) return []
if (!searchQuery.trim()) return providers
const query = searchQuery.toLowerCase()
return providers.filter((p) => p.name.toLowerCase().includes(query))
}, [providers, searchQuery])
// Create Mutation
const createMutation = useMutation({
mutationFn: async (values: ProviderFormValues) => {
const res = await client.api.teams[':teamId'].providers.$post({
param: { teamId },
json: {
name: values.name,
config: values.config,
models: values.models,
},
})
if (!res.ok) throw new Error('Failed to create provider')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
setIsCreateDialogOpen(false)
toast.success('Provider created successfully')
},
onError: (error) => {
toast.error(`Error: ${error.message}`)
},
})
// Update Mutation
const updateMutation = useMutation({
mutationFn: async ({ id, values }: { id: string; values: ProviderFormValues }) => {
const res = await client.api.providers[':id'].$put({
param: { id },
json: {
config: values.config,
models: values.models,
},
})
if (!res.ok) throw new Error('Failed to update provider')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
setEditingProviderId(null)
toast.success('Provider updated successfully')
},
onError: (error) => {
toast.error(`Error: ${error.message}`)
},
})
// Delete Mutation
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
const res = await client.api.providers[':id'].$delete({
param: { id },
})
if (!res.ok) throw new Error('Failed to delete provider')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
setEditingProviderId(null)
setIsDeleteDialogOpen(false)
setProviderToDelete(null)
toast.success('Provider deleted successfully')
},
onError: (error) => {
toast.error(`Error: ${error.message}`)
},
})
if (isLoading) {
return (
<div className="flex h-64 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
)
}
return (
<div className="h-full flex flex-col space-y-0">
<div className="flex-none space-y-4 pb-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold text-foreground flex items-center gap-2">
<Cpu className="w-5 h-5 text-primary" />
Configured AI Providers
</h3>
<Button
onClick={() => setIsCreateDialogOpen(true)}
className="bg-primary hover:bg-primary/90 text-primary-foreground gap-2"
>
<Plus className="w-4 h-4" />
Add Provider
</Button>
</div>
<div className="relative px-0.5">
<Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search providers..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 bg-card border-border focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-0"
/>
</div>
</div>
<div className="flex-1 overflow-y-auto pr-2 min-h-0 overflow-x-hidden">
<div className="grid grid-cols-1 gap-4 py-2">
{filteredProviders.map((provider) => (
<Card
key={provider.id}
className="group cursor-pointer hover:border-primary/50 transition-all hover:shadow-md overflow-hidden"
onClick={() => setEditingProviderId(provider.id)}
>
<CardContent className="p-5 flex items-center justify-between gap-4">
<div className="flex items-center gap-4 min-w-0 flex-1">
<div className="flex-none p-3 bg-muted rounded-xl group-hover:bg-primary/10 transition-colors">
<Globe className="w-6 h-6 text-muted-foreground group-hover:text-primary" />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="font-bold text-foreground truncate">{provider.name}</span>
{provider.isBuiltin && (
<Badge
variant="secondary"
className="flex-none text-[10px] uppercase tracking-wider font-bold h-5"
>
Built-in
</Badge>
)}
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs text-muted-foreground mt-1">
<span className="flex items-center gap-1 flex-none">
<Zap className="w-3 h-3" />
{provider.config.api}
</span>
{provider.config.baseUrl && (
<span className="flex items-center gap-1 min-w-0">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 flex-none" />
<Info className="w-3 h-3 flex-none" />
<span className="truncate max-w-[200px] md:max-w-[300px]">
{provider.config.baseUrl}
</span>
</span>
)}
<span className="flex items-center gap-1 flex-none">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 flex-none" />
<Maximize2 className="w-3 h-3" />
{provider.modelsCount} Models
{editingProviderId === provider.id && isModelsLoading && (
<Loader2 className="w-3 h-3 animate-spin ml-1" />
)}
</span>
</div>
</div>
</div>
<div className="flex items-center gap-1">
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
>
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-32">
<DropdownMenuItem
disabled={provider.isBuiltin}
onClick={(e) => {
e.stopPropagation()
setProviderToDelete(provider)
setIsDeleteDialogOpen(true)
}}
className="text-destructive focus:text-destructive gap-2 cursor-pointer"
>
<Trash2 className="w-4 h-4" /> Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ChevronRight className="flex-none w-5 h-5 text-muted-foreground/50 group-hover:text-primary transition-colors" />
</div>
</CardContent>
</Card>
))}
{providers?.length === 0 && (
<div className="text-center py-12 bg-muted/30 rounded-2xl border-2 border-dashed border-border">
<Cpu className="w-12 h-12 text-muted-foreground/50 mx-auto mb-4" />
<h4 className="text-foreground font-medium">No Providers Configured</h4>
<p className="text-sm text-muted-foreground mt-1">
Add your first AI provider to get started.
</p>
</div>
)}
{providers && providers.length > 0 && filteredProviders.length === 0 && (
<div className="text-center py-12">
<Search className="w-12 h-12 text-muted-foreground/50 mx-auto mb-4" />
<h4 className="text-foreground font-medium">No matches found</h4>
<p className="text-sm text-muted-foreground mt-1">
Try adjusting your search for "{searchQuery}"
</p>
<Button
variant="ghost"
size="sm"
onClick={() => setSearchQuery('')}
className="mt-4 text-primary hover:text-primary/90 hover:bg-primary/10"
>
Clear search
</Button>
</div>
)}
</div>
</div>
<ProviderFormDialog
isOpen={isCreateDialogOpen}
onClose={() => setIsCreateDialogOpen(false)}
onSubmit={(values) => createMutation.mutate(values)}
isLoading={createMutation.isPending}
title="Add New Provider"
existingProviderNames={existingProviderNames}
/>
<ProviderFormDialog
isOpen={!!editingProvider && !isModelsLoading && !!editingModels}
onClose={() => setEditingProviderId(null)}
onSubmit={(values) => updateMutation.mutate({ id: editingProvider!.id, values })}
onDelete={() => deleteMutation.mutate(editingProvider!.id)}
isLoading={updateMutation.isPending || deleteMutation.isPending}
initialValues={
editingProvider && editingModels
? {
name: editingProvider.name,
config: editingProvider.config,
models: editingModels,
}
: undefined
}
isBuiltin={editingProvider?.isBuiltin}
title={`Edit ${editingProvider?.name}`}
existingProviderNames={existingProviderNames}
/>
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete the provider "
{providerToDelete?.name}" and all associated model configurations.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setProviderToDelete(null)}>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-white"
onClick={() => {
if (providerToDelete) {
deleteMutation.mutate(providerToDelete.id)
}
}}
>
{deleteMutation.isPending ? (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
) : (
<Trash2 className="w-4 h-4 mr-2" />
)}
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
interface ProviderFormDialogProps {
isOpen: boolean
onClose: () => void
onSubmit: (values: ProviderFormValues) => void
onDelete?: () => void
isLoading: boolean
initialValues?: ProviderFormValues
isBuiltin?: boolean
title: string
existingProviderNames: string[]
}
function ProviderFormDialog({
isOpen,
onClose,
onSubmit,
onDelete,
isLoading,
initialValues,
isBuiltin,
title,
existingProviderNames,
}: ProviderFormDialogProps) {
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const schema = useMemo(() => {
return providerFormSchemaBase.extend({
name: z
.string()
.min(1, 'Provider name is required')
.refine(
(name) => {
if (initialValues?.name === name) return true
return !existingProviderNames.includes(name)
},
{ message: 'Provider name must be unique' },
),
})
}, [existingProviderNames, initialValues])
const form = useForm({
defaultValues: (initialValues || {
name: '',
config: {
api: 'openai-completions',
baseUrl: '',
apiKey: '',
},
models: [
{
modelId: '',
name: '',
config: {
api: 'openai-completions',
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
],
}) as z.input<typeof schema>,
validators: {
onChange: schema,
},
onSubmit: async ({ value }) => {
onSubmit(value as ProviderFormValues)
},
})
// Reset form when dialog opens
useEffect(() => {
if (isOpen) {
form.reset()
}
}, [isOpen, form])
const mapErrors = (errors: unknown[]) => {
return errors.map((e) => {
if (typeof e === 'string') return { message: e }
if (e && typeof e === 'object' && 'message' in e) {
return { message: String(e.message) }
}
return { message: String(e || '') }
})
}
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-4xl max-h-[90vh] flex flex-col p-0 overflow-hidden">
<DialogHeader className="p-6 pb-2">
<DialogTitle className="text-xl">{title}</DialogTitle>
<DialogDescription>
Configure authentication and model details for your AI provider.
</DialogDescription>
</DialogHeader>
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
className="flex flex-col flex-1 overflow-hidden"
>
<div className="flex-1 overflow-y-auto p-6 pt-2 space-y-8">
{/* Row 1: Basic Config */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-6 bg-slate-50 dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800">
<form.Field
name="name"
children={(field) => {
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name}>Provider Name</FieldLabel>
<Input
id={field.name}
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="e.g., My OpenAI"
disabled={isBuiltin}
aria-invalid={isInvalid}
/>
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
</Field>
)
}}
/>
<form.Field
name="config.api"
children={(field) => {
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name}>Global API Protocol</FieldLabel>
<Select
onValueChange={field.handleChange}
value={field.state.value}
disabled={isBuiltin}
>
<SelectTrigger id={field.name} aria-invalid={isInvalid}>
<SelectValue placeholder="Select API Protocol" />
</SelectTrigger>
<SelectContent>
<SelectItem value="openai-completions">OpenAI Completions</SelectItem>
<SelectItem value="anthropic-messages">Anthropic Messages</SelectItem>
<SelectItem value="google-genai">Google GenAI</SelectItem>
<SelectItem value="bedrock-converse-stream">AWS Bedrock</SelectItem>
</SelectContent>
</Select>
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
</Field>
)
}}
/>
<div className="md:col-span-2">
<form.Field
name="config.baseUrl"
children={(field) => {
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name}>Base URL (Optional)</FieldLabel>
<Input
id={field.name}
name={field.name}
value={field.state.value || ''}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="https://api.openai.com/v1"
aria-invalid={isInvalid}
/>
<FieldDescription>Override the default endpoint.</FieldDescription>
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
</Field>
)
}}
/>
</div>
</div>
{/* Row 2: API Key Card */}
<Card className="bg-slate-50 dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800">
<CardContent className="p-6">
<form.Field
name="config.apiKey"
children={(field) => {
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name} className="text-base font-semibold">
API Key
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="text"
value={field.state.value || ''}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="Enter API Key or Environment Variable"
aria-invalid={isInvalid}
/>
<FieldDescription className="text-xs mt-2">
You can provide a literal value (e.g.{' '}
<code className="bg-slate-200 dark:bg-slate-800 px-1 rounded text-blue-600 dark:text-blue-400">
sk-...
</code>
) or an Environment variable name (e.g.{' '}
<code className="bg-slate-200 dark:bg-slate-800 px-1 rounded text-blue-600 dark:text-blue-400">
MY_API_KEY
</code>
).
</FieldDescription>
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
</Field>
)
}}
/>
</CardContent>
</Card>
{/* Models Section */}
<div className="space-y-4">
<form.Field
name="models"
mode="array"
children={(modelsField) => (
<div className="space-y-4">
<div className="flex items-center justify-between">
<Label className="text-lg font-bold">Models Configuration</Label>
<Button
type="button"
variant="outline"
size="sm"
onClick={() =>
modelsField.pushValue({
modelId: '',
name: '',
config: {
api: form.getFieldValue('config.api'),
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
})
}
className="gap-2"
>
<Plus className="w-4 h-4" />
Add Model
</Button>
</div>
<div className="space-y-6">
{modelsField.state.value.map((_, index) => (
<div
key={index}
className="group relative p-6 bg-white dark:bg-slate-950 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm animate-in fade-in zoom-in-95 duration-300"
>
{/* Row 1: ID and Name */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<form.Field
name={`models[${index}].modelId`}
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name}>Model ID</FieldLabel>
<Input
id={field.name}
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="gpt-4o"
aria-invalid={isInvalid}
/>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
<form.Field
name={`models[${index}].name`}
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name}>
Display Name (Optional)
</FieldLabel>
<Input
id={field.name}
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="e.g., GPT-4o"
aria-invalid={isInvalid}
disabled={isBuiltin}
/>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
</div>
{/* Row 2: Reasoning and Context Window */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
<form.Field
name={`models[${index}].config.reasoning`}
children={(field) => (
<Field
orientation="horizontal"
className="rounded-lg border p-3 shadow-sm bg-slate-50 dark:bg-slate-900 justify-between"
>
<FieldLabel htmlFor={field.name}>Reasoning Support</FieldLabel>
<Switch
id={field.name}
checked={field.state.value}
onCheckedChange={field.handleChange}
disabled={isBuiltin}
/>
</Field>
)}
/>
<form.Field
name={`models[${index}].config.contextWindow`}
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name} className="text-xs">
Context Window (tokens)
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="number"
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) =>
field.handleChange(parseInt(e.target.value) || 0)
}
aria-invalid={isInvalid}
disabled={isBuiltin}
/>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
</div>
{/* Row 3: Constraints and Cost */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
<form.Field
name={`models[${index}].config.maxTokens`}
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name} className="text-xs">
Max Output Tokens
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="number"
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) =>
field.handleChange(parseInt(e.target.value) || 0)
}
aria-invalid={isInvalid}
disabled={isBuiltin}
/>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
<form.Field
name={`models[${index}].config.cost.input`}
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel
htmlFor={field.name}
className="text-xs flex items-center gap-1"
>
<DollarSign className="w-3 h-3" /> Input Cost (1M)
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="number"
step="0.01"
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) =>
field.handleChange(parseFloat(e.target.value) || 0)
}
aria-invalid={isInvalid}
disabled={isBuiltin}
/>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
<form.Field
name={`models[${index}].config.cost.output`}
children={(field) => {
const isInvalid =
!!field.state.meta.errors.length && field.state.meta.isTouched
return (
<Field data-invalid={isInvalid}>
<FieldLabel
htmlFor={field.name}
className="text-xs flex items-center gap-1"
>
<DollarSign className="w-3 h-3" /> Output Cost (1M)
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="number"
step="0.01"
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) =>
field.handleChange(parseFloat(e.target.value) || 0)
}
aria-invalid={isInvalid}
disabled={isBuiltin}
/>
{isInvalid && (
<FieldError errors={mapErrors(field.state.meta.errors)} />
)}
</Field>
)
}}
/>
</div>
{!isBuiltin && (
<Button
type="button"
variant="ghost"
size="icon"
className="absolute -top-2 -right-2 h-8 w-8 rounded-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-400 hover:text-red-600 transition-colors shadow-sm"
onClick={() => modelsField.removeValue(index)}
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
))}
</div>
</div>
)}
/>
</div>
</div>
<DialogFooter className="p-6 pt-4 border-t dark:border-slate-800 gap-2">
<Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<form.Subscribe
selector={(state) => [state.canSubmit, state.isSubmitting]}
children={([canSubmit, isSubmitting]) => (
<Button
type="submit"
className="bg-blue-600 hover:bg-blue-700 text-white min-w-[120px]"
disabled={!canSubmit || isSubmitting || isLoading}
>
{isSubmitting || isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
'Save Configuration'
)}
</Button>
)}
/>
</DialogFooter>
</form>
</DialogContent>
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete the provider and all
associated model configurations.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-red-600 hover:bg-red-700 text-white"
onClick={() => {
onDelete?.()
setIsDeleteDialogOpen(false)
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Dialog>
)
}
@@ -0,0 +1,136 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { Loader2, Plus, X, Globe } from 'lucide-react'
import { toast } from 'sonner'
export function SandboxSettings({ teamId }: { teamId: string }) {
const queryClient = useQueryClient()
const [newDomain, setNewDomain] = useState('')
const { data: sandbox, isLoading } = useQuery({
queryKey: ['teams', teamId, 'sandbox'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].sandbox.$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to fetch sandbox settings')
return await res.json()
},
})
const { mutate: updateSandbox, isPending: isUpdating } = useMutation({
mutationFn: async (allowedDomains: string[]) => {
const res = await client.api.teams[':teamId'].sandbox.$put({
param: { teamId },
json: { allowedDomains },
})
if (!res.ok) throw new Error('Failed to update sandbox settings')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'sandbox'] })
toast.success('Sandbox settings updated')
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : 'Failed to update sandbox settings')
},
})
const handleAddDomain = (e: React.FormEvent) => {
e.preventDefault()
if (!newDomain.trim()) return
if (sandbox?.allowedDomains.includes(newDomain.trim())) {
toast.error('Domain already exists')
return
}
const updated = [...(sandbox?.allowedDomains || []), newDomain.trim()]
updateSandbox(updated)
setNewDomain('')
}
const handleRemoveDomain = (domain: string) => {
const updated = (sandbox?.allowedDomains || []).filter((d) => d !== domain)
updateSandbox(updated)
}
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="h-full overflow-y-auto space-y-6 pr-1">
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Globe className="w-5 h-5 text-blue-500" />
<CardTitle>Network Sandbox</CardTitle>
</div>
<CardDescription>
Configure allowed domains for the sandboxed agent. By default, only essential domains
are allowed.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleAddDomain} className="flex gap-2 mb-6">
<Input
placeholder="e.g. api.openai.com"
value={newDomain}
onChange={(e) => setNewDomain(e.target.value)}
disabled={isUpdating}
/>
<Button type="submit" disabled={isUpdating}>
{isUpdating ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Plus className="w-4 h-4 mr-2" />
)}
Add Domain
</Button>
</form>
<div className="space-y-2">
<h4 className="text-sm font-medium text-slate-500 mb-3">Allowed Domains</h4>
<div className="flex flex-wrap gap-2">
{sandbox?.allowedDomains.map((domain) => (
<div
key={domain}
className="flex items-center gap-1 px-3 py-1.5 bg-slate-100 dark:bg-slate-800 rounded-full text-sm border border-slate-200 dark:border-slate-700 transition-all hover:border-slate-300 dark:hover:border-slate-600"
>
<span className="font-medium text-slate-700 dark:text-slate-300">{domain}</span>
<button
onClick={() => handleRemoveDomain(domain)}
className="ml-1 text-slate-400 hover:text-red-500 transition-colors"
disabled={isUpdating}
>
<X className="w-3.5 h-3.5" />
</button>
</div>
))}
{sandbox?.allowedDomains.length === 0 && (
<div className="text-sm text-slate-400 italic">No custom domains allowed</div>
)}
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Filesystem Restriction</CardTitle>
<CardDescription>
The agent is restricted to reading and writing only within the <code>.pi</code> and{' '}
<code>/tmp</code> folders. These settings are currently hardcoded for security.
</CardDescription>
</CardHeader>
</Card>
</div>
)
}
@@ -0,0 +1,629 @@
import { client } from '@/ui/api/client'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Code, Loader2, MoreVertical, Plus, Puzzle, Trash2, Upload, X } from 'lucide-react'
import React, { useState, useRef } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Button } from '@/ui/components/ui/button'
import { cn } from '@/ui/lib/utils'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { SkillInfo } from '@shumai/dtos'
const Github = (props: React.SVGProps<SVGSVGElement>) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" />
<path d="M9 18c-4.51 2-5-2-7-2" />
</svg>
)
interface SkillsConfigCardProps {
teamId: string
}
export const SkillsConfigCard: React.FC<SkillsConfigCardProps> = ({ teamId }) => {
const queryClient = useQueryClient()
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
const [isConfigDialogOpen, setIsConfigDialogOpen] = useState(false)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [selectedSkill, setSelectedSkill] = useState<SkillInfo | null>(null)
// Fetch Skills
const { data, isLoading } = useQuery({
queryKey: ['teams', teamId, 'skills'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].skills.$get({ param: { teamId } })
if (!res.ok) throw new Error('Failed to fetch skills')
return await res.json()
},
})
// Delete Skill
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
const res = await client.api.skills[':id'].$delete({
param: { id },
})
if (!res.ok) throw new Error('Failed to delete skill')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] })
setIsDeleteDialogOpen(false)
},
})
const skills = data?.skills || []
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-7">
<div className="flex items-center gap-3">
<div className="p-2 bg-primary/10 text-primary rounded-lg">
<Puzzle className="w-6 h-6" />
</div>
<div>
<CardTitle className="text-xl font-bold">Skills Management</CardTitle>
<CardDescription>
Extend your chatbot's capabilities with custom skills.
</CardDescription>
</div>
</div>
<Button onClick={() => setIsAddDialogOpen(true)} className="gap-2">
<Plus className="w-4 h-4" /> Add Skill
</Button>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex justify-center py-10">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
</div>
) : skills.length === 0 ? (
<div className="text-center py-12 border-2 border-dashed border-border rounded-xl">
<div className="mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center mb-4 text-muted-foreground">
<Puzzle className="w-6 h-6" />
</div>
<h3 className="text-lg font-medium text-foreground">No skills installed</h3>
<p className="text-muted-foreground mt-1 max-w-xs mx-auto">
Add a skill via GitHub URL or upload a ZIP file to get started.
</p>
</div>
) : (
<div className="space-y-4">
{skills.map((skill) => (
<SkillItem
key={skill.id}
skill={skill}
onDelete={() => {
setSelectedSkill(skill)
setIsDeleteDialogOpen(true)
}}
onConfigure={() => {
setSelectedSkill(skill)
setIsConfigDialogOpen(true)
}}
/>
))}
</div>
)}
</CardContent>
<AddSkillDialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen} teamId={teamId} />
{selectedSkill && (
<ConfigSkillDialog
open={isConfigDialogOpen}
onOpenChange={(open) => {
setIsConfigDialogOpen(open)
if (!open) {
// Ensure body pointer-events is restored if something stuck it
setTimeout(() => {
document.body.style.pointerEvents = 'auto'
}, 100)
}
}}
teamId={teamId}
skill={selectedSkill}
/>
)}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete the skill "
{selectedSkill?.name}" and all its configurations.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-white"
onClick={() => {
if (selectedSkill) {
deleteMutation.mutate(selectedSkill.id)
}
}}
>
{deleteMutation.isPending ? (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
) : (
<Trash2 className="w-4 h-4 mr-2" />
)}
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Card>
)
}
const SkillItem = ({
skill,
onDelete,
onConfigure,
}: {
skill: SkillInfo
onDelete: () => void
onConfigure: () => void
}) => {
return (
<div
className="p-4 bg-card rounded-xl border border-border flex flex-col justify-between hover:shadow-md transition-all group cursor-pointer"
onClick={onConfigure}
>
<div>
<div className="flex items-start justify-between mb-2">
<h4 className="font-bold text-foreground flex items-center gap-2">{skill.name}</h4>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="icon" className="h-8 w-8">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-32">
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onDelete()
}}
className="text-red-500 focus:text-red-500 gap-2 cursor-pointer"
>
<Trash2 className="w-4 h-4" /> Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<p className="text-sm text-muted-foreground line-clamp-2">
{skill.description || 'No description provided.'}
</p>
</div>
<div className="mt-4 flex items-center justify-between text-[10px] text-muted-foreground uppercase tracking-wider font-semibold">
<span>Updated {new Date(skill.updatedAt).toLocaleDateString()}</span>
<div className="px-2 py-0.5 rounded-full bg-primary/10 text-primary">Installed</div>
</div>
</div>
)
}
const AddSkillDialog = ({
open,
onOpenChange,
teamId,
}: {
open: boolean
onOpenChange: (open: boolean) => void
teamId: string
}) => {
const queryClient = useQueryClient()
const [githubUrl, setGithubUrl] = useState('')
const [isProcessing, setIsProcessing] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
// Need a project ID for the attachment upload
const { data: projectsData } = useQuery({
queryKey: ['teams', teamId, 'projects'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].projects.$get({
param: { teamId },
query: { first: '1' },
})
if (!res.ok) throw new Error('Failed to fetch projects')
return await res.json()
},
enabled: open,
})
const installSkill = async (payload: {
assetId?: string
githubUrl?: string
override?: boolean
}) => {
setIsProcessing(true)
try {
const res = await client.api.teams[':teamId'].skills.$post({
param: { teamId },
json: payload,
})
if (res.status === 409) {
const data = (await res.json()) as { error: string }
if (window.confirm(`${data.error}\n\nDo you want to override the existing skill?`)) {
await installSkill({ ...payload, override: true })
return
}
} else if (!res.ok) {
const errorData = (await res.json().catch(() => ({}))) as { error?: string }
throw new Error(errorData.error || 'Failed to install skill')
} else {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] })
onOpenChange(false)
setGithubUrl('')
}
} catch (err: unknown) {
if (err instanceof Error) {
alert(err.message)
} else {
alert('An unknown error occurred')
}
} finally {
setIsProcessing(false)
}
}
const handleFileUpload = async (files: FileList | null) => {
if (!files || files.length === 0) return
const projectId = projectsData?.data?.[0]?.id
if (!projectId) {
alert('You need at least one project in your team to upload skills.')
return
}
const fileToUpload = files[0]
if (!fileToUpload.name.toLowerCase().endsWith('.zip')) {
alert('Only .zip files are supported.')
return
}
setIsProcessing(true)
try {
const fileName = fileToUpload.name
const contentType = fileToUpload.type || 'application/zip'
// 1. Get Presigned URL and Asset ID
const attachRes = await client.api.projects[':projectId'].attachments.$post({
param: { projectId },
json: {
fileName: fileName,
size: fileToUpload.size,
contentType: contentType,
},
})
if (!attachRes.ok) throw new Error('Failed to get upload URL')
const { id: assetId, uploadUrl } = (await attachRes.json()) as {
id: string
uploadUrl: string
}
// 2. Upload to S3
const uploadRes = await fetch(uploadUrl, {
method: 'PUT',
body: fileToUpload,
headers: { 'Content-Type': contentType },
})
if (!uploadRes.ok) throw new Error('Failed to upload file to storage')
// 3. Install Skill
await installSkill({ assetId })
} catch (err: unknown) {
if (err instanceof Error) {
alert(err.message)
} else {
alert('An unknown error occurred')
}
} finally {
setIsProcessing(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[450px]">
<DialogHeader>
<DialogTitle>Add New Skill</DialogTitle>
<DialogDescription>
Import a skill from a local ZIP archive or a GitHub repository.
</DialogDescription>
</DialogHeader>
<div className="space-y-6 pt-4">
{/* File Upload Section */}
<div className="space-y-3">
<Label>Package Upload</Label>
<div
onClick={() => !isProcessing && fileInputRef.current?.click()}
className={cn(
'group relative h-32 border-2 border-dashed rounded-xl flex flex-col items-center justify-center transition-all cursor-pointer',
isProcessing
? 'opacity-50 cursor-not-allowed bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-800'
: 'hover:bg-blue-50/50 dark:hover:bg-blue-900/10 hover:border-blue-500/50 border-slate-200 dark:border-slate-800',
)}
>
<input
type="file"
ref={fileInputRef}
className="hidden"
accept=".zip"
onChange={(e) => handleFileUpload(e.target.files)}
/>
<div className="p-3 bg-slate-100 dark:bg-slate-800 rounded-full group-hover:bg-blue-100 dark:group-hover:bg-blue-900/30 transition-colors">
<Upload className="w-6 h-6 text-slate-400 group-hover:text-blue-500" />
</div>
<div className="mt-3 text-center">
<p className="text-sm font-medium text-slate-700 dark:text-slate-300">
Select ZIP file
</p>
<p className="text-[10px] text-slate-500 dark:text-slate-400 mt-1 uppercase tracking-wider font-semibold">
Packages must contain a SKILL.md
</p>
</div>
</div>
{isProcessing && !githubUrl && (
<div className="flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400 justify-center bg-blue-50 dark:bg-blue-900/10 py-2 rounded-lg animate-pulse">
<Loader2 className="w-4 h-4 animate-spin" />
Processing package...
</div>
)}
</div>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t border-slate-200 dark:border-slate-800" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-white dark:bg-slate-950 px-2 text-slate-500 font-bold">OR</span>
</div>
</div>
{/* GitHub URL Section */}
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="githubUrl">GitHub Repository URL</Label>
<div className="flex gap-2">
<div className="relative flex-1">
<Github className="absolute left-3 top-2.5 w-4 h-4 text-slate-400" />
<Input
id="githubUrl"
placeholder="https://github.com/owner/repo"
value={githubUrl}
onChange={(e) => setGithubUrl(e.target.value)}
disabled={isProcessing}
className="pl-9"
/>
</div>
<Button
onClick={() => installSkill({ githubUrl })}
disabled={!githubUrl || isProcessing}
className="px-6"
>
{isProcessing && githubUrl ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
'Install'
)}
</Button>
</div>
<p className="text-[10px] text-slate-500 dark:text-slate-400 italic">
Example: https://github.com/google/gemini-cli
</p>
</div>
</div>
</div>
</DialogContent>
</Dialog>
)
}
const ConfigSkillDialog = ({
open,
onOpenChange,
teamId,
skill,
}: {
open: boolean
onOpenChange: (open: boolean) => void
teamId: string
skill: SkillInfo
}) => {
const queryClient = useQueryClient()
const [config, setConfig] = useState({
...(skill.config || {}),
environmentVariables: skill.config?.environmentVariables || [],
})
const [isSaving, setIsSaving] = useState(false)
const handleEnvVarValueChange = (index: number, value: string) => {
const newVars = [...config.environmentVariables]
newVars[index] = { ...newVars[index], default: value }
setConfig({ ...config, environmentVariables: newVars })
}
const handleEnvVarNameChange = (index: number, name: string) => {
const newVars = [...config.environmentVariables]
newVars[index] = { ...newVars[index], name }
setConfig({ ...config, environmentVariables: newVars })
}
const addEnvVar = () => {
setConfig({
...config,
environmentVariables: [...config.environmentVariables, { name: '', default: '' }],
})
}
const removeEnvVar = (index: number) => {
const newVars = [...config.environmentVariables]
newVars.splice(index, 1)
setConfig({ ...config, environmentVariables: newVars })
}
const handleSave = async () => {
// Basic validation: filter out empty names
const filteredVars = config.environmentVariables.filter((v) => v.name.trim() !== '')
const finalConfig = { ...config, environmentVariables: filteredVars }
setIsSaving(true)
try {
const res = await client.api.skills[':id'].config.$patch({
param: { id: skill.id },
json: { config: finalConfig },
})
if (!res.ok) {
const errorData = (await res.json().catch(() => ({}))) as { error?: string }
throw new Error(errorData.error || 'Failed to update config')
}
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] })
onOpenChange(false)
} catch (err: unknown) {
if (err instanceof Error) {
alert(err.message)
} else {
alert('An unknown error occurred')
}
} finally {
setIsSaving(false)
}
}
const envVars = config?.environmentVariables || []
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<div className="flex items-center justify-between">
<DialogTitle className="flex items-center gap-2">
<Code className="w-5 h-5 text-blue-500" />
Configure Skill: {skill.name}
</DialogTitle>
</div>
<DialogDescription>
Manage environment variables for this skill instance.
</DialogDescription>
</DialogHeader>
<div className="py-4 space-y-4 max-h-[60vh] overflow-y-auto pr-2 custom-scrollbar">
{envVars.length === 0 ? (
<div className="text-center py-10 bg-slate-50 dark:bg-slate-900 rounded-xl border border-dashed border-slate-200 dark:border-slate-800">
<p className="text-slate-500 dark:text-slate-400 text-sm italic">
No environment variables found. Click "Add Variable" to create one.
</p>
</div>
) : (
envVars.map((env: { name: string; default?: string | undefined }, index: number) => (
<div
key={index}
className="p-4 bg-slate-100/50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-700 space-y-3 relative group"
>
<button
onClick={() => removeEnvVar(index)}
className="absolute top-2 right-2 p-1 text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md transition-colors opacity-0 group-hover:opacity-100"
>
<X className="w-4 h-4" />
</button>
<div className="space-y-1.5">
<Label className="text-[10px] uppercase tracking-wider font-bold text-slate-400">
Variable Name
</Label>
<Input
value={env.name}
onChange={(e) => handleEnvVarNameChange(index, e.target.value)}
placeholder="e.app. API_KEY"
className="h-8 bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 text-sm font-mono"
/>
</div>
<div className="space-y-1.5">
<Label className="text-[10px] uppercase tracking-wider font-bold text-slate-400">
Default Value
</Label>
<Input
value={env.default || ''}
onChange={(e) => handleEnvVarValueChange(index, e.target.value)}
placeholder="Optional default value..."
className="h-8 bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 text-sm"
/>
<p className="text-[10px] text-slate-500 italic">
If left empty, the value will be read from the host machine's environment.
</p>
</div>
</div>
))
)}
</div>
<DialogFooter className="flex items-center justify-between sm:justify-between w-full pt-2 border-t border-slate-100 dark:border-slate-800">
<Button
variant="ghost"
size="sm"
onClick={addEnvVar}
className="h-8 gap-1.5 text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20"
>
<Plus className="w-3.5 h-3.5" /> Add Variable
</Button>
<div className="flex gap-2">
<Button variant="ghost" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
onClick={handleSave}
disabled={isSaving}
className="px-8 bg-blue-600 hover:bg-blue-700 text-white"
>
{isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
Save Changes
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,7 @@
import { AiProvider } from './types'
export const PROVIDERS = [
{ value: AiProvider.GEMINI, label: 'Google Gemini' },
{ value: AiProvider.openAi, label: 'OpenAi' },
{ value: AiProvider.ANTHROPIC, label: 'Anthropic' },
]
@@ -0,0 +1,37 @@
import type { AiProviderSettings } from '@shumai/dtos'
export const AiProvider = {
GEMINI: 'google',
openAi: 'openai',
ANTHROPIC: 'anthropic',
ELEVEN: 'elevenlabs',
} as const
export type AiProvider = (typeof AiProvider)[keyof typeof AiProvider]
export const GeminiModel = {
FLASH: 'gemini-3-flash-preview',
PRO: 'gemini-3-pro-preview',
FLASH_LITE: 'gemini-flash-lite-latest',
} as const
export type GeminiModel = (typeof GeminiModel)[keyof typeof GeminiModel]
export const FileType = {
IMAGE: 'image',
VIDEO: 'video',
AUDIO: 'audio',
TEXT: 'text',
} as const
export type FileType = (typeof FileType)[keyof typeof FileType]
export const ThinkingLevel = {
DISABLED: 'disabled',
LOW: 'low',
MEDIUM: 'medium',
HIGH: 'high',
} as const
export type ThinkingLevel = (typeof ThinkingLevel)[keyof typeof ThinkingLevel]
import type { AgentInfo } from '@shumai/dtos'
export type ProviderSettings = AiProviderSettings
export type Agent = AgentInfo
+324
View File
@@ -0,0 +1,324 @@
import type { AncestorFolder, AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState, useMemo } from 'react'
import { FileBrowser } from './file-browser/file-browser'
import { ShareSettingsSidebar } from './share-settings-sidebar'
import { FolderTree } from './folder-tree'
import { ResizeHandle } from './resize-handle'
import { useFileSystemDnd } from './use-file-system-dnd'
import { DragDropProvider, DragOverlay, KeyboardSensor, PointerSensor } from '@dnd-kit/react'
import { PointerActivationConstraints } from '@dnd-kit/dom'
import { SnapToPointer } from './dnd-modifiers'
import { useUiStore } from '@/ui/stores/ui'
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
import { useTopNavStore } from '@/ui/stores/top-nav'
import type { ShareLinkInfo } from '@shumai/dtos'
import { toast } from 'sonner'
type ShareManagerProps = {
teamId: string
projectId: string
projectName: string
shareId: string
rootFolderId: string // Project root folder id for the left sidebar tree
}
export default function ShareManager({
teamId,
projectId,
projectName,
shareId,
rootFolderId,
}: ShareManagerProps) {
const queryClient = useQueryClient()
const { fetchMetadata } = useUserMetadataStore()
useEffect(() => {
if (teamId) {
fetchMetadata(teamId)
}
}, [teamId, fetchMetadata])
const { data: shareLink } = useQuery({
queryKey: ['share', shareId],
queryFn: async () => {
const res = await client.api.shares[':shareId'].$get({
param: { shareId },
})
if (!res.ok) throw new Error('Failed to fetch share link')
return (await res.json()) as unknown as ShareLinkInfo
},
})
const shareRootId = shareLink?.rootFolderId
const [currentFolderId, setCurrentFolderId] = useState<string | null>(null)
const [ancestorFolders, setAncestorFolders] = useState<AncestorFolder[]>([])
useEffect(() => {
if (shareRootId) {
setCurrentFolderId(shareRootId)
setAncestorFolders([])
setSelectedIds(new Set())
}
}, [shareRootId, shareId])
const setProjectState = useTopNavStore((s) => s.setProjectState)
const clearProjectState = useTopNavStore((s) => s.clearProjectState)
const handleBreadcrumbClick = (folderId: string) => {
if (folderId === currentFolderId) return
if (folderId === shareRootId) {
setCurrentFolderId(shareRootId)
setAncestorFolders([])
} else {
const index = ancestorFolders.findIndex((f) => f.id === folderId)
if (index !== -1) {
setCurrentFolderId(folderId)
setAncestorFolders(ancestorFolders.slice(index + 1))
}
}
setSelectedIds(new Set())
}
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
fileListRightSidebarCollapsed: isRightSidebarCollapsed,
viewModes,
} = useUiStore()
const displayStyle = viewModes[projectId] ?? 'card'
const {
data: foldersData,
fetchNextPage: fetchNextFoldersPage,
hasNextPage: hasNextPageFolders,
isFetchingNextPage: isFetchingNextFoldersPage,
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['folder-children', teamId, currentFolderId, 'folder'],
queryFn: async ({ pageParam }) => {
const res = await client.api.folders[':folderId'].children.$get({
param: { folderId: currentFolderId! },
query: {
assetType: 'folder',
after: pageParam as string,
},
})
if (!res.ok) throw new Error('Failed to fetch folders')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
enabled: !!currentFolderId,
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
})
const {
data: filesData,
fetchNextPage: fetchNextFilesPage,
hasNextPage: hasNextPageFiles,
isFetchingNextPage: isFetchingNextFilesPage,
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['folder-children', teamId, currentFolderId, 'file'],
queryFn: async ({ pageParam }) => {
const res = await client.api.folders[':folderId'].children.$get({
param: { folderId: currentFolderId! },
query: {
assetType: 'file',
after: pageParam as string,
},
})
if (!res.ok) throw new Error('Failed to fetch files')
return (await res.json()) as unknown as AssetInfoPaginatedList
},
enabled: !!currentFolderId,
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
})
const folders = useMemo(
() => foldersData?.pages.flatMap((page) => page.data ?? []) ?? [],
[foldersData],
)
const files = useMemo(
() => filesData?.pages.flatMap((page) => page.data ?? []) ?? [],
[filesData],
)
useEffect(() => {
if (shareLink) {
setProjectState({
teamId,
projectId,
projectName,
ancestorFolders,
currentAsset: {
name:
currentFolderId === shareRootId
? shareLink.name
: folders.find((f) => f.id === currentFolderId)?.name || shareLink.name,
type: 'folder',
},
isRootFolder: false, // Ensure share link name or subfolder is always shown in TopNav
shareId,
onFolderClick: handleBreadcrumbClick,
})
}
return () => clearProjectState()
}, [
teamId,
projectId,
projectName,
ancestorFolders,
currentFolderId,
shareRootId,
shareLink,
shareId,
folders,
setProjectState,
clearProjectState,
])
const handleClearSelection = () => {
setSelectedIds(new Set())
}
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const { dragState, handleDragStart, handleDragEnd } = useFileSystemDnd({
teamId,
projectId,
assetId: currentFolderId || '',
folders,
files,
selectedIds,
onClearSelection: handleClearSelection,
})
const $removeFromShare = client.api.shares[':shareId'].assets[':assetId'].$delete
const { mutate: removeFromShare } = useMutation({
mutationFn: async (assetId: string) => {
const res = await $removeFromShare({
param: { shareId, assetId },
})
if (!res.ok) throw new Error('Failed to remove')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['folder-children', teamId, currentFolderId] })
toast.success('Removed from share')
},
})
const handleItemDoubleClick = (item: AssetInfo) => {
if (item.type === 'folder' || item.targetType === 'folder') {
const currentFolderName =
currentFolderId === shareRootId
? shareLink?.name || ''
: folders.find((f) => f.id === currentFolderId)?.name || 'Unknown'
setAncestorFolders((prev) => [{ id: currentFolderId!, name: currentFolderName }, ...prev])
setCurrentFolderId(item.id)
setSelectedIds(new Set())
}
}
if (!shareLink) return <div>Loading...</div>
return (
<DragDropProvider
modifiers={[SnapToPointer.configure({ anchor: { x: 0, y: 0 } })]}
sensors={[
PointerSensor.configure({
activationConstraints: [new PointerActivationConstraints.Distance({ value: 10 })],
}),
KeyboardSensor,
]}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<div className="flex h-screen flex-col bg-background">
<div className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && (
<>
<div className="bg-background" style={{ width: leftSidebarWidth }}>
<FolderTree
teamId={teamId}
projectId={projectId}
projectName={projectName}
rootFolderId={rootFolderId}
dragState={dragState}
/>
</div>
<ResizeHandle
onResize={(delta) =>
setLeftSidebarWidth((p) => Math.max(180, Math.min(400, p + delta)))
}
/>
</>
)}
<FileBrowser
teamId={teamId}
projectId={projectId}
assetId={currentFolderId || ''}
folders={folders}
files={files}
selectedItem={null}
selectedIds={selectedIds}
onItemSelect={(item, e) => {
if (e.metaKey || e.ctrlKey) {
const next = new Set(selectedIds)
if (next.has(item.id)) next.delete(item.id)
else next.add(item.id)
setSelectedIds(next)
} else {
setSelectedIds(new Set([item.id]))
}
}}
onItemDoubleClick={handleItemDoubleClick}
onSaveField={() => {}}
displayStyle={displayStyle}
onClearSelection={handleClearSelection}
fetchNextFoldersPage={fetchNextFoldersPage}
hasNextFoldersPage={hasNextPageFolders}
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
fetchNextFilesPage={fetchNextFilesPage}
hasNextFilesPage={hasNextPageFiles}
isFetchingNextFilesPage={isFetchingNextFilesPage}
filterConditions={[]}
onFilterChange={() => {}}
dragState={dragState}
isShareView={true}
onRemoveFromShare={(items) => {
items.forEach((i) => removeFromShare(i.id))
}}
fieldVisibility={shareLink.fieldVisibility}
/>
{!isRightSidebarCollapsed && (
<>
<ResizeHandle
onResize={(delta) =>
setRightSidebarWidth((p) => Math.max(240, Math.min(600, p - delta)))
}
/>
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
<ShareSettingsSidebar shareLink={shareLink} />
</div>
</>
)}
</div>
</div>
<DragOverlay>
{dragState?.isActive ? (
<div className="flex items-center gap-2 rounded-md bg-popover px-3 py-2 text-sm font-medium shadow-md">
Moving {dragState.itemCount} item{dragState.itemCount !== 1 ? 's' : ''}
</div>
) : null}
</DragOverlay>
</DragDropProvider>
)
}
@@ -0,0 +1,242 @@
import { ShareLinkInfo, UpdateShareLinkRequest } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
ChevronRight,
Copy,
ExternalLink,
Shield,
Settings2,
Palette,
ListFilter,
SortAsc,
} from 'lucide-react'
import React, { useState } from 'react'
import { toast } from 'sonner'
import { DateTimePicker } from '@/ui/components/datetime-picker'
interface ShareSettingsSidebarProps {
shareLink: ShareLinkInfo
}
export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
const queryClient = useQueryClient()
const [password, setPassword] = useState('')
const [expireAt, setExpireAt] = useState<Date | undefined>(
shareLink.expireAt ? new Date(shareLink.expireAt) : undefined,
)
const [isPasswordEnabled, setIsPasswordEnabled] = useState(shareLink.hasPassword)
const [isExpireEnabled, setIsExpireEnabled] = useState(!!shareLink.expireAt)
const { data: fields } = useQuery({
queryKey: ['fields', shareLink.projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].fields.$get({
param: { projectId: shareLink.projectId },
})
if (!res.ok) throw new Error('Failed to fetch fields')
return await res.json()
},
enabled: !!shareLink.projectId,
})
const $updateShare = client.api.shares[':shareId'].$put
const { mutate: updateShare } = useMutation({
mutationFn: async (json: UpdateShareLinkRequest) => {
const res = await $updateShare({
param: { shareId: shareLink.id },
json,
})
if (!res.ok) throw new Error('Failed to update')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
toast.success('Settings updated')
},
})
const shareUrl = `${window.location.origin}/share/${shareLink.id}`
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text)
toast.success('Copied to clipboard')
}
const toggleFieldVisibility = (fieldId: string) => {
const current = shareLink.fieldVisibility || {}
const next = { ...current, [fieldId]: !current[fieldId] }
updateShare({ fieldVisibility: next })
}
return (
<div className="flex flex-col h-full bg-background border-l border-border">
<div className="flex-1 overflow-y-auto">
<div className="p-4 space-y-6">
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium">Link Visibility</h3>
<Switch
checked={!shareLink.isDisabled}
onCheckedChange={(checked) => updateShare({ isDisabled: !checked })}
/>
</div>
<div className="flex gap-2">
<div className="relative flex-1">
<Input value={shareUrl} readOnly className="pr-10 bg-muted/50 text-xs" />
<Button
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full"
onClick={() => copyToClipboard(shareUrl)}
>
<Copy className="h-4 w-4" />
</Button>
</div>
<Button variant="outline" className="px-3">
<Settings2 className="h-4 w-4 mr-2" />
Public
</Button>
</div>
<Input placeholder="Send to name or email" className="text-sm" />
</div>
<div className="space-y-1">
<SidebarAccordionItem title="Permissions" icon={<Settings2 className="h-4 w-4" />} />
<SidebarAccordionItem title="Security" icon={<Shield className="h-4 w-4" />}>
<div className="p-3 space-y-4 pt-0">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">Password</Label>
<Switch
checked={isPasswordEnabled}
onCheckedChange={(checked) => {
setIsPasswordEnabled(checked)
if (!checked) updateShare({ password: null })
}}
/>
</div>
{isPasswordEnabled && (
<div className="flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
<Input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={shareLink.hasPassword ? '••••••••' : 'Set password'}
className="text-xs"
/>
<Button size="sm" onClick={() => updateShare({ password })}>
Save
</Button>
</div>
)}
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">Expiration Date</Label>
<Switch
checked={isExpireEnabled}
onCheckedChange={(checked) => {
setIsExpireEnabled(checked)
if (!checked) {
setExpireAt(undefined)
updateShare({ expireAt: null })
}
}}
/>
</div>
{isExpireEnabled && (
<div className="animate-in fade-in slide-in-from-top-1 duration-200">
<DateTimePicker
value={expireAt}
onChange={(date) => {
setExpireAt(date)
updateShare({ expireAt: date ? date.toISOString() : null })
}}
className="text-xs"
/>
</div>
)}
</div>
</div>
</SidebarAccordionItem>
<SidebarAccordionItem title="Appearance" icon={<Palette className="h-4 w-4" />} />
<SidebarAccordionItem title="Fields" icon={<ListFilter className="h-4 w-4" />}>
<div className="p-3 space-y-3 pt-0">
{(fields as MetadataFieldInfo[])?.map((field) => (
<div key={field.id} className="flex items-center justify-between">
<Label className="text-xs">{field.config?.name}</Label>
<Switch
checked={shareLink.fieldVisibility?.[field.id] ?? false}
onCheckedChange={() => toggleFieldVisibility(field.id)}
/>
</div>
))}
</div>
</SidebarAccordionItem>
<SidebarAccordionItem title="Sort by" icon={<SortAsc className="h-4 w-4" />} />
</div>
</div>
</div>
<div className="p-4 border-t border-border space-y-2">
<Button
variant="outline"
className="w-full justify-center"
onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="h-4 w-4 mr-2" />
Open Share Link
</Button>
<Button
className="w-full justify-center bg-blue-600 hover:bg-blue-700 text-white"
onClick={() => copyToClipboard(shareUrl)}
>
<Copy className="h-4 w-4 mr-2" />
Copy Link
</Button>
</div>
</div>
)
}
function SidebarAccordionItem({
title,
icon,
children,
}: {
title: string
icon: React.ReactNode
children?: React.ReactNode
}) {
const [isOpen, setIsOpen] = useState(false)
return (
<div className="border-b border-border last:border-0">
<button
onClick={() => setIsOpen(!isOpen)}
className="w-full flex items-center justify-between py-3 px-2 hover:bg-muted/50 transition-colors"
>
<div className="flex items-center gap-3">
{icon}
<span className="text-sm font-medium">{title}</span>
</div>
<ChevronRight className={cn('h-4 w-4 transition-transform', isOpen && 'rotate-90')} />
</button>
{isOpen && children && (
<div className="animate-in fade-in slide-in-from-top-1 duration-200">{children}</div>
)}
</div>
)
}
function cn(...classes: (string | boolean | undefined | null)[]) {
return classes.filter(Boolean).join(' ')
}
@@ -0,0 +1,38 @@
import type { AssetInfo } from '@shumai/dtos'
import { cn } from '@/ui/lib/utils'
import { Link } from '@tanstack/react-router'
import React from 'react'
import { FilePreview } from './file-browser/file-preview'
interface SidebarFileCardProps {
projectId: string
item: AssetInfo
isActive: boolean
}
export const SidebarFileCard = React.forwardRef<HTMLDivElement, SidebarFileCardProps>(
({ projectId, item, isActive }, ref) => {
const filePath = `/projects/${projectId}/files/${item.id}`
return (
<div ref={ref}>
<Link
to={filePath}
className={cn(
'flex flex-col overflow-hidden rounded-lg border',
isActive ? 'border-primary ring-2 ring-primary' : 'hover:border-primary/50',
)}
>
<div className="relative aspect-[4/3] w-full overflow-hidden bg-muted/30">
<FilePreview item={item} />
</div>
<div className="p-2">
<p className="truncate text-sm font-medium">{item.name}</p>
<p className="truncate text-xs text-muted-foreground">{item.creator?.name}</p>
</div>
</Link>
</div>
)
},
)
SidebarFileCard.displayName = 'SidebarFileCard'
+105
View File
@@ -0,0 +1,105 @@
import { Button } from '@/ui/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { ArrowDownWideNarrow, ArrowUpNarrowWide, Check } from 'lucide-react'
interface SortDropdownProps {
sortBy: string
sortDirection: 'asc' | 'desc'
onSortChange: (sortBy: string, sortDirection: 'asc' | 'desc') => void
}
export function SortDropdown({ sortBy, sortDirection, onSortChange }: SortDropdownProps) {
const handleSortByChange = (field: string) => {
onSortChange(field, sortDirection)
}
const handleDirectionChange = () => {
const newDirection = sortDirection === 'asc' ? 'desc' : 'asc'
onSortChange(sortBy, newDirection)
}
const formatSortBy = (field: string) => {
switch (field) {
case 'name':
return 'Name'
case 'created_at':
return 'Created'
case 'updated_at':
return 'Updated'
default:
return field
}
}
const isAsc = sortDirection === 'asc'
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="gap-2 bg-muted/50">
<span className="text-muted-foreground">Sorted by</span>
<span className="font-medium text-foreground">{formatSortBy(sortBy)}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56 p-2">
<div className="text-xs font-semibold text-muted-foreground mb-2 px-2">Sort by</div>
{/* Field Selection */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="w-full justify-between font-normal px-2 h-10 bg-muted/50 hover:bg-muted mb-2 border"
>
<span>{formatSortBy(sortBy)}</span>
<ArrowDownWideNarrow className="h-4 w-4 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-52">
{['name', 'created_at', 'updated_at'].map((field) => (
<DropdownMenuItem
key={field}
onClick={() => handleSortByChange(field)}
className="justify-between"
>
{formatSortBy(field)}
{sortBy === field && <Check className="h-4 w-4" />}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Direction Toggle */}
<Button
variant="ghost"
className="w-full justify-between font-normal px-2 h-10 bg-muted/50 hover:bg-muted border"
onClick={handleDirectionChange}
>
<span className="text-muted-foreground">
{sortBy === 'name' ? (
isAsc ? (
<>from A &rarr; Z</>
) : (
<>from Z &rarr; A</>
)
) : isAsc ? (
<>Oldest &rarr; Newest</>
) : (
<>Newest &rarr; Oldest</>
)}
</span>
{isAsc ? (
<ArrowUpNarrowWide className="h-4 w-4 opacity-50" />
) : (
<ArrowDownWideNarrow className="h-4 w-4 opacity-50" />
)}
</Button>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,200 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
interface SpriteScrubberProps {
/** The URL of the 10x10 sprite sheet */
spriteUrl: string
/** The URL of the static thumbnail */
thumbnailUrl: string
/** The width of the original video source */
videoWidth: number
/** The height of the original video source */
videoHeight: number
/** The fixed width of a single frame in the sprite sheet (default 480) */
frameWidth?: number
/** Optional custom class name for the container */
className?: string
}
interface Dimensions {
width: number
height: number
}
const GRID_COLS = 10
const GRID_ROWS = 10
const TOTAL_FRAMES = GRID_COLS * GRID_ROWS
export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
spriteUrl,
thumbnailUrl,
videoWidth,
videoHeight,
className = '',
}) => {
const containerRef = useRef<HTMLDivElement>(null)
const [containerSize, setContainerSize] = useState<Dimensions>({
width: 0,
height: 0,
})
const [naturalSize, setNaturalSize] = useState<Dimensions>({
width: 0,
height: 0,
})
const [isHovering, setIsHovering] = useState(false)
const [spriteLoaded, setSpriteLoaded] = useState(false)
const [loadingSprite, setLoadingSprite] = useState(false)
const [currentFrame, setCurrentFrame] = useState(0)
const [cursorX, setCursorX] = useState(0)
useEffect(() => {
if (!containerRef.current) return
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(containerRef.current)
return () => observer.disconnect()
}, [])
const loadSprite = useCallback(() => {
if (spriteLoaded || loadingSprite) return
setLoadingSprite(true)
const img = new Image()
img.src = spriteUrl
img.onload = () => {
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
setSpriteLoaded(true)
setLoadingSprite(false)
}
img.onerror = () => {
console.error('Failed to load sprite image')
setLoadingSprite(false)
}
}, [spriteUrl, spriteLoaded, loadingSprite])
const handleMouseEnter = () => {
setIsHovering(true)
loadSprite()
}
const handleMouseLeave = () => {
setIsHovering(false)
}
const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
if (!containerRef.current) return
const rect = containerRef.current.getBoundingClientRect()
const x = e.clientX - rect.left
const clampedX = Math.max(0, Math.min(x, rect.width))
setCursorX(clampedX)
const percentage = clampedX / rect.width
const frameIndex = Math.min(Math.floor(percentage * TOTAL_FRAMES), TOTAL_FRAMES - 1)
setCurrentFrame(frameIndex)
}
// Calculate styles for the inner sprite frame box
const spriteStyle: React.CSSProperties = useMemo(() => {
if (containerSize.width === 0 || containerSize.height === 0) return {}
let sourceAspect = videoWidth / videoHeight
if (naturalSize.width > 0 && naturalSize.height > 0) {
const singleFrameNaturalW = naturalSize.width / GRID_COLS
const singleFrameNaturalH = naturalSize.height / GRID_ROWS
sourceAspect = singleFrameNaturalW / singleFrameNaturalH
}
const containerAspect = containerSize.width / containerSize.height
let renderWidth, renderHeight
if (containerAspect > sourceAspect) {
renderHeight = containerSize.height
renderWidth = renderHeight * sourceAspect
} else {
renderWidth = containerSize.width
renderHeight = renderWidth / sourceAspect
}
// Using Math.ceil ensures we never have sub-pixel gaps (black lines)
// caused by flooring or rounding down.
const finalW = Math.ceil(renderWidth)
const finalH = Math.ceil(renderHeight)
// IMPORTANT: We calculate the sheet size based on the SNAPPED frame size.
// This slightly stretches the sprite if needed but ensures that every frame
// falls exactly on an integer pixel boundary, preventing "shaking" during playback.
const bgWidth = finalW * GRID_COLS
const bgHeight = finalH * GRID_ROWS
const colIndex = currentFrame % GRID_COLS
const rowIndex = Math.floor(currentFrame / GRID_COLS)
const bgPosX = -(colIndex * finalW)
const bgPosY = -(rowIndex * finalH)
return {
backgroundImage: `url(${spriteUrl})`,
backgroundSize: `${bgWidth}px ${bgHeight}px`,
backgroundPosition: `${bgPosX}px ${bgPosY}px`,
backgroundRepeat: 'no-repeat',
width: `${finalW}px`,
height: `${finalH}px`,
// Optional: helps with crisp edges on some screens, though default is usually fine
imageRendering: 'auto',
}
}, [containerSize, videoWidth, videoHeight, currentFrame, spriteUrl, naturalSize])
return (
<div
ref={containerRef}
className={`relative w-full h-full overflow-hidden cursor-crosshair group bg-gray-900 select-none ${className}`}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onMouseMove={handleMouseMove}
>
<img
src={thumbnailUrl}
alt="Thumbnail"
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
isHovering && spriteLoaded ? 'opacity-0' : 'opacity-100'
}`}
draggable={false}
/>
{isHovering && !spriteLoaded && (
<div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10">
<div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
</div>
)}
{spriteLoaded && (
<div
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-75 ${
isHovering ? 'opacity-100' : 'opacity-0'
}`}
>
<div style={spriteStyle} />
</div>
)}
{isHovering && (
<div
className="absolute top-0 bottom-0 w-0.5 bg-red-500 shadow-[0_0_4px_rgba(255,0,0,0.8)] z-20 pointer-events-none"
style={{ transform: `translateX(${cursorX}px)` }}
/>
)}
</div>
)
}
@@ -0,0 +1,59 @@
import { client } from '@/ui/api/client'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
export function TeamSelector() {
const navigate = useNavigate()
const { data: teamsData, isLoading } = useQuery({
queryKey: ['teams'],
queryFn: async () => {
const res = await client.api.teams.$get({
query: {},
})
if (!res.ok) throw new Error('Failed to get teams')
return await res.json()
},
})
if (isLoading) {
return <div>Loading...</div>
}
const teams = teamsData?.data
if (teams?.length === 1) {
navigate({ to: `/teams/${teams[0].id}` })
return null
}
return (
<Dialog open={true}>
<DialogContent>
<DialogHeader>
<DialogTitle>Select a Team</DialogTitle>
<DialogDescription>
You are a member of multiple teams. Please select one to continue.
</DialogDescription>
</DialogHeader>
<div className="space-y-2">
{teams?.map((team) => (
<div
key={team.id}
className="p-2 border rounded-md cursor-pointer hover:bg-gray-100"
onClick={() => navigate({ to: `/teams/${team.id}` })}
>
{team.name}
</div>
))}
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,71 @@
import { createContext, useContext, useEffect, useState } from 'react'
type Theme = 'dark' | 'light' | 'system'
type ThemeProviderProps = {
children: React.ReactNode
defaultTheme?: Theme
storageKey?: string
}
type ThemeProviderState = {
theme: Theme
setTheme: (theme: Theme) => void
}
const initialState: ThemeProviderState = {
theme: 'system',
setTheme: () => null,
}
const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
export function ThemeProvider({
children,
defaultTheme = 'system',
storageKey = 'vite-ui-theme',
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
)
useEffect(() => {
const root = window.document.documentElement
root.classList.remove('light', 'dark')
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
root.classList.add(systemTheme)
return
}
root.classList.add(theme)
}, [theme])
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme)
setTheme(theme)
},
}
return (
<ThemeProviderContext.Provider {...props} value={value}>
{children}
</ThemeProviderContext.Provider>
)
}
export const useTheme = () => {
const context = useContext(ThemeProviderContext)
if (context === undefined) throw new Error('useTheme must be used within a ThemeProvider')
return context
}
@@ -0,0 +1,84 @@
import { useEffect, useState } from 'react'
import { Monitor, Moon, Sun } from 'lucide-react'
import { cn } from '../lib/utils'
type Theme = 'light' | 'dark' | 'system'
export function ThemeSwitcher() {
const [theme, setTheme] = useState<Theme>('system')
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
const storedTheme = localStorage.getItem('theme') as Theme | null
if (storedTheme) {
setTheme(storedTheme)
}
}, [])
useEffect(() => {
if (!mounted) return
const root = document.documentElement
const applyTheme = (newTheme: Theme) => {
if (newTheme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
root.classList.remove('light', 'dark')
root.classList.add(systemTheme)
} else {
root.classList.remove('light', 'dark')
root.classList.add(newTheme)
}
}
applyTheme(theme)
localStorage.setItem('theme', theme)
if (theme === 'system') {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
const handleChange = () => applyTheme('system')
mediaQuery.addEventListener('change', handleChange)
return () => mediaQuery.removeEventListener('change', handleChange)
}
}, [theme, mounted])
if (!mounted) {
return (
<div className="flex items-center gap-1 rounded-lg bg-sidebar-accent p-1">
<div className="h-7 w-full rounded-md" />
</div>
)
}
const options: { value: Theme; icon: typeof Sun; label: string }[] = [
{ value: 'light', icon: Sun, label: 'Light' },
{ value: 'dark', icon: Moon, label: 'Dark' },
{ value: 'system', icon: Monitor, label: 'System' },
]
return (
<div className="space-y-2">
<div className="px-1 text-xs font-semibold text-sidebar-foreground/60">THEME</div>
<div className="flex items-center gap-1 rounded-lg bg-sidebar-accent p-1">
{options.map(({ value, icon: Icon, label }) => (
<button
key={value}
onClick={() => setTheme(value)}
className={cn(
'flex flex-1 items-center justify-center gap-2 rounded-md px-3 py-1.5 text-xs font-medium transition-colors',
theme === value
? 'bg-sidebar text-sidebar-foreground shadow-sm'
: 'text-sidebar-foreground/60 hover:text-sidebar-foreground',
)}
title={label}
>
<Icon className="h-3.5 w-3.5" />
<span className="hidden sm:inline">{label}</span>
</button>
))}
</div>
</div>
)
}
+84
View File
@@ -0,0 +1,84 @@
import { useTopNavStore } from '@/ui/stores/top-nav'
import { BreadcrumbNav } from './breadcrumb-nav'
import { ShumaiLogo } from '@/ui/components/ui/icons'
import { useUiStore } from '@/ui/stores/ui'
export function TopNav() {
const { projectState } = useTopNavStore()
const uiStore = useUiStore()
if (!projectState) {
return <TeamHeader />
}
const {
teamId,
projectId,
projectName,
ancestorFolders,
currentAsset,
isRootFolder,
fileId,
versions,
isPublic,
shareId,
onFolderClick,
} = projectState
const isFileView = !!fileId
const isLeftSidebarCollapsed = isFileView
? uiStore.fileViewLeftSidebarCollapsed
: uiStore.fileListLeftSidebarCollapsed
const onLeftSidebarToggle = isPublic
? undefined
: () =>
isFileView
? uiStore.setFileViewLeftSidebarCollapsed(!uiStore.fileViewLeftSidebarCollapsed)
: uiStore.setFileListLeftSidebarCollapsed(!uiStore.fileListLeftSidebarCollapsed)
const isRightSidebarCollapsed = isFileView
? uiStore.fileViewRightSidebarCollapsed
: uiStore.fileListRightSidebarCollapsed
const onRightSidebarToggle = () =>
isFileView
? uiStore.setFileViewRightSidebarCollapsed(!uiStore.fileViewRightSidebarCollapsed)
: uiStore.setFileListRightSidebarCollapsed(!uiStore.fileListRightSidebarCollapsed)
const displayStyle = projectId ? (uiStore.viewModes[projectId] ?? 'card') : 'card'
const onDisplayStyleChange = isPublic
? undefined
: (style: 'card' | 'list') => {
if (projectId) uiStore.setViewMode(projectId, style)
}
return (
<BreadcrumbNav
teamId={teamId}
projectId={projectId}
projectName={projectName}
ancestorFolders={ancestorFolders}
currentAsset={currentAsset}
isRootFolder={isRootFolder}
displayStyle={isFileView ? undefined : displayStyle}
onDisplayStyleChange={isFileView ? undefined : onDisplayStyleChange}
isLeftSidebarCollapsed={isLeftSidebarCollapsed}
onLeftSidebarToggle={onLeftSidebarToggle}
isRightSidebarCollapsed={isRightSidebarCollapsed}
onRightSidebarToggle={onRightSidebarToggle}
isPublic={isPublic}
shareId={shareId}
fileId={fileId}
versions={versions}
onFolderClick={onFolderClick}
/>
)
}
function TeamHeader() {
return (
<div className="flex h-14 flex-wrap items-center justify-center gap-2 border-b border-border bg-card px-4 py-2 flex-shrink-0">
<ShumaiLogo className="w-10 h-10 text-orange-600" />
</div>
)
}
@@ -0,0 +1,62 @@
import * as React from 'react'
import { ChevronDownIcon } from 'lucide-react'
import { Accordion as AccordionPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
function Accordion({ ...props }: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn('border-b last:border-b-0', className)}
{...props}
/>
)
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
'flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180',
className,
)}
{...props}
>
{children}
<ChevronDownIcon className="pointer-events-none size-4 shrink-0 translate-y-0.5 text-muted-foreground transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn('pt-0 pb-4', className)}>{children}</div>
</AccordionPrimitive.Content>
)
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
@@ -0,0 +1,179 @@
'use client'
import * as React from 'react'
import { AlertDialog as AlertDialogPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
import { Button } from '@/ui/components/ui/button'
function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
}
function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = 'default',
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: 'default' | 'sm'
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
'group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg',
className,
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
'grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]',
className,
)}
{...props}
/>
)
}
function AlertDialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
'flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end',
className,
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
'text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2',
className,
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
)
}
function AlertDialogMedia({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className,
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = 'default',
size = 'default',
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, 'variant' | 'size'>) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = 'outline',
size = 'default',
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, 'variant' | 'size'>) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}
+60
View File
@@ -0,0 +1,60 @@
import * as React from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/ui/lib/utils'
const alertVariants = cva(
'relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current',
{
variants: {
variant: {
default: 'bg-card text-card-foreground',
destructive:
'bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current',
},
},
defaultVariants: {
variant: 'default',
},
},
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<'div'> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-title"
className={cn('col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight', className)}
{...props}
/>
)
}
function AlertDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-description"
className={cn(
'col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed',
className,
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }
@@ -0,0 +1,9 @@
'use client'
import { AspectRatio as AspectRatioPrimitive } from 'radix-ui'
function AspectRatio({ ...props }: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
}
export { AspectRatio }
+94
View File
@@ -0,0 +1,94 @@
import * as React from 'react'
import { Avatar as AvatarPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
function Avatar({
className,
size = 'default',
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
size?: 'default' | 'sm' | 'lg'
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
'group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6',
className,
)}
{...props}
/>
)
}
function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn('aspect-square size-full', className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
'flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs',
className,
)}
{...props}
/>
)
}
function AvatarBadge({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="avatar-badge"
className={cn(
'absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground ring-2 ring-background select-none',
'group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden',
'group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2',
'group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2',
className,
)}
{...props}
/>
)
}
function AvatarGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="avatar-group"
className={cn(
'group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background',
className,
)}
{...props}
/>
)
}
function AvatarGroupCount({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="avatar-group-count"
className={cn(
'relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3',
className,
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback, AvatarBadge, AvatarGroup, AvatarGroupCount }
+46
View File
@@ -0,0 +1,46 @@
import * as React from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { Slot } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
const badgeVariants = cva(
'inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground [a&]:hover:bg-primary/90',
secondary: 'bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',
destructive:
'bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90',
outline:
'border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
ghost: '[a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
link: 'text-primary underline-offset-4 [a&]:hover:underline',
},
},
defaultVariants: {
variant: 'default',
},
},
)
function Badge({
className,
variant = 'default',
asChild = false,
...props
}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : 'span'
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }
+102
View File
@@ -0,0 +1,102 @@
import * as React from 'react'
import { ChevronRight, MoreHorizontal } from 'lucide-react'
import { Slot } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
function Breadcrumb({ ...props }: React.ComponentProps<'nav'>) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<'ol'>) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
'flex flex-wrap items-center gap-1.5 text-sm break-words text-muted-foreground sm:gap-2.5',
className,
)}
{...props}
/>
)
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="breadcrumb-item"
className={cn('inline-flex items-center gap-1.5', className)}
{...props}
/>
)
}
function BreadcrumbLink({
asChild,
className,
...props
}: React.ComponentProps<'a'> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : 'a'
return (
<Comp
data-slot="breadcrumb-link"
className={cn('transition-colors hover:text-foreground', className)}
{...props}
/>
)
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
className={cn('font-normal text-foreground', className)}
{...props}
/>
)
}
function BreadcrumbSeparator({ children, className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn('[&>svg]:size-3.5', className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
}
function BreadcrumbEllipsis({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn('flex size-9 items-center justify-center', className)}
{...props}
>
<MoreHorizontal className="size-4" />
<span className="sr-only">More</span>
</span>
)
}
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}
@@ -0,0 +1,78 @@
import { cva, type VariantProps } from 'class-variance-authority'
import { Slot } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
import { Separator } from '@/ui/components/ui/separator'
const buttonGroupVariants = cva(
"flex w-fit items-stretch has-[>[data-slot=button-group]]:gap-2 [&>*]:focus-visible:relative [&>*]:focus-visible:z-10 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",
{
variants: {
orientation: {
horizontal:
'[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none',
vertical:
'flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none',
},
},
defaultVariants: {
orientation: 'horizontal',
},
},
)
function ButtonGroup({
className,
orientation,
...props
}: React.ComponentProps<'div'> & VariantProps<typeof buttonGroupVariants>) {
return (
<div
role="group"
data-slot="button-group"
data-orientation={orientation}
className={cn(buttonGroupVariants({ orientation }), className)}
{...props}
/>
)
}
function ButtonGroupText({
className,
asChild = false,
...props
}: React.ComponentProps<'div'> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : 'div'
return (
<Comp
className={cn(
"flex items-center gap-2 rounded-md border bg-muted px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
)
}
function ButtonGroupSeparator({
className,
orientation = 'vertical',
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="button-group-separator"
orientation={orientation}
className={cn(
'relative m-0! self-stretch bg-input data-[orientation=vertical]:h-auto',
className,
)}
{...props}
/>
)
}
export { ButtonGroup, ButtonGroupSeparator, ButtonGroupText, buttonGroupVariants }
+62
View File
@@ -0,0 +1,62 @@
import * as React from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { Slot } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
const buttonVariants = cva(
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive:
'bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40',
outline:
'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2 has-[>svg]:px-3',
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: 'h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5',
lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
icon: 'size-9',
'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
'icon-sm': 'size-8',
'icon-lg': 'size-10',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
},
)
function Button({
className,
variant = 'default',
size = 'default',
asChild = false,
...props
}: React.ComponentProps<'button'> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : 'button'
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
+178
View File
@@ -0,0 +1,178 @@
import * as React from 'react'
import { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon } from 'lucide-react'
import { DayPicker, getDefaultClassNames, type DayButton } from 'react-day-picker'
import { cn } from '@/ui/lib/utils'
import { Button, buttonVariants } from '@/ui/components/ui/button'
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = 'label',
buttonVariant = 'ghost',
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>['variant']
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
'group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent',
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className,
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) => date.toLocaleString('default', { month: 'short' }),
...formatters,
}}
classNames={{
root: cn('w-fit', defaultClassNames.root),
months: cn('relative flex flex-col gap-4 md:flex-row', defaultClassNames.months),
month: cn('flex w-full flex-col gap-4', defaultClassNames.month),
nav: cn(
'absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1',
defaultClassNames.nav,
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
'size-(--cell-size) p-0 select-none aria-disabled:opacity-50',
defaultClassNames.button_previous,
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
'size-(--cell-size) p-0 select-none aria-disabled:opacity-50',
defaultClassNames.button_next,
),
month_caption: cn(
'flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)',
defaultClassNames.month_caption,
),
dropdowns: cn(
'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',
defaultClassNames.dropdowns,
),
dropdown_root: cn(
'relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50',
defaultClassNames.dropdown_root,
),
dropdown: cn('absolute inset-0 bg-popover opacity-0', defaultClassNames.dropdown),
caption_label: cn(
'font-medium select-none',
captionLayout === 'label'
? 'text-sm'
: 'flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground',
defaultClassNames.caption_label,
),
month_grid: 'w-full border-collapse',
weekdays: cn('flex', defaultClassNames.weekdays),
weekday: cn(
'flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none',
defaultClassNames.weekday,
),
week: cn('mt-2 flex w-full', defaultClassNames.week),
week_number_header: cn('w-(--cell-size) select-none', defaultClassNames.week_number_header),
week_number: cn(
'text-[0.8rem] text-muted-foreground select-none',
defaultClassNames.week_number,
),
day: cn(
'group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-md',
props.showWeekNumber
? '[&:nth-child(2)[data-selected=true]_button]:rounded-l-md'
: '[&:first-child[data-selected=true]_button]:rounded-l-md',
defaultClassNames.day,
),
range_start: cn('rounded-l-md bg-accent', defaultClassNames.range_start),
range_middle: cn('rounded-none', defaultClassNames.range_middle),
range_end: cn('rounded-r-md bg-accent', defaultClassNames.range_end),
today: cn(
'rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none',
defaultClassNames.today,
),
outside: cn(
'text-muted-foreground aria-selected:text-muted-foreground',
defaultClassNames.outside,
),
disabled: cn('text-muted-foreground opacity-50', defaultClassNames.disabled),
hidden: cn('invisible', defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return <div data-slot="calendar" ref={rootRef} className={cn(className)} {...props} />
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === 'left') {
return <ChevronLeftIcon className={cn('size-4', className)} {...props} />
}
if (orientation === 'right') {
return <ChevronRightIcon className={cn('size-4', className)} {...props} />
}
return <ChevronDownIcon className={cn('size-4', className)} {...props} />
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
'flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70',
defaultClassNames.day,
className,
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }
+75
View File
@@ -0,0 +1,75 @@
import * as React from 'react'
import { cn } from '@/ui/lib/utils'
function Card({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card"
className={cn(
'flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm',
className,
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-header"
className={cn(
'@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',
className,
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-title"
className={cn('leading-none font-semibold', className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-description"
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-action"
className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-content" className={cn('px-6', className)} {...props} />
}
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-footer"
className={cn('flex items-center px-6 [.border-t]:pt-6', className)}
{...props}
/>
)
}
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent }
+223
View File
@@ -0,0 +1,223 @@
'use client'
import * as React from 'react'
import useEmblaCarousel, { type UseEmblaCarouselType } from 'embla-carousel-react'
import { ArrowLeft, ArrowRight } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import { Button } from '@/ui/components/ui/button'
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: 'horizontal' | 'vertical'
setApi?: (api: CarouselApi) => void
}
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
throw new Error('useCarousel must be used within a <Carousel />')
}
return context
}
function Carousel({
orientation = 'horizontal',
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<'div'> & CarouselProps) {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === 'horizontal' ? 'x' : 'y',
},
plugins,
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) return
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'ArrowLeft') {
event.preventDefault()
scrollPrev()
} else if (event.key === 'ArrowRight') {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext],
)
React.useEffect(() => {
if (!api || !setApi) return
setApi(api)
}, [api, setApi])
React.useEffect(() => {
if (!api) return
onSelect(api)
api.on('reInit', onSelect)
api.on('select', onSelect)
return () => {
api?.off('select', onSelect)
}
}, [api, onSelect])
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation: orientation || (opts?.axis === 'y' ? 'vertical' : 'horizontal'),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
onKeyDownCapture={handleKeyDown}
className={cn('relative', className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
function CarouselContent({ className, ...props }: React.ComponentProps<'div'>) {
const { carouselRef, orientation } = useCarousel()
return (
<div ref={carouselRef} className="overflow-hidden" data-slot="carousel-content">
<div
className={cn('flex', orientation === 'horizontal' ? '-ml-4' : '-mt-4 flex-col', className)}
{...props}
/>
</div>
)
}
function CarouselItem({ className, ...props }: React.ComponentProps<'div'>) {
const { orientation } = useCarousel()
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
'min-w-0 shrink-0 grow-0 basis-full',
orientation === 'horizontal' ? 'pl-4' : 'pt-4',
className,
)}
{...props}
/>
)
}
function CarouselPrevious({
className,
variant = 'outline',
size = 'icon',
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
'absolute size-8 rounded-full',
orientation === 'horizontal'
? 'top-1/2 -left-12 -translate-y-1/2'
: '-top-12 left-1/2 -translate-x-1/2 rotate-90',
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft />
<span className="sr-only">Previous slide</span>
</Button>
)
}
function CarouselNext({
className,
variant = 'outline',
size = 'icon',
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel()
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
'absolute size-8 rounded-full',
orientation === 'horizontal'
? 'top-1/2 -right-12 -translate-y-1/2'
: '-bottom-12 left-1/2 -translate-x-1/2 rotate-90',
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight />
<span className="sr-only">Next slide</span>
</Button>
)
}
export { type CarouselApi, Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext }
+338
View File
@@ -0,0 +1,338 @@
import * as React from 'react'
import * as RechartsPrimitive from 'recharts'
import type { TooltipValueType } from 'recharts'
import { cn } from '@/ui/lib/utils'
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: '', dark: '.dark' } as const
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
type TooltipNameType = number | string
export type ChartConfig = Record<
string,
{
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
>
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error('useChart must be used within a <ChartContainer />')
}
return context
}
function ChartContainer({
id,
className,
children,
config,
initialDimension = INITIAL_DIMENSION,
...props
}: React.ComponentProps<'div'> & {
config: ChartConfig
children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>['children']
initialDimension?: {
width: number
height: number
}
}) {
const uniqueId = React.useId()
const chartId = `chart-${id ?? uniqueId.replace(/:/g, '')}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className,
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer initialDimension={initialDimension}>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(([, config]) => config.theme ?? config.color)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ?? itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join('\n')}
}
`,
)
.join('\n'),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = 'dot',
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<'div'> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: 'line' | 'dot' | 'dashed'
nameKey?: string
labelKey?: string
} & Omit<
RechartsPrimitive.DefaultTooltipContentProps<TooltipValueType, TooltipNameType>,
'accessibilityLayer'
>) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === 'string' ? (config[label]?.label ?? label) : itemConfig?.label
if (labelFormatter) {
return (
<div className={cn('font-medium', labelClassName)}>{labelFormatter(value, payload)}</div>
)
}
if (!value) {
return null
}
return <div className={cn('font-medium', labelClassName)}>{value}</div>
}, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== 'dot'
return (
<div
className={cn(
'grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl',
className,
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== 'none')
.map((item, index) => {
const key = `${nameKey ?? item.name ?? item.dataKey ?? 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color ?? item.payload?.fill ?? item.color
return (
<div
key={index}
className={cn(
'flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground',
indicator === 'dot' && 'items-center',
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
'shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)',
{
'h-2.5 w-2.5': indicator === 'dot',
'w-1': indicator === 'line',
'w-0 border-[1.5px] border-dashed bg-transparent':
indicator === 'dashed',
'my-0.5': nestLabel && indicator === 'dashed',
},
)}
style={
{
'--color-bg': indicatorColor,
'--color-border': indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
'flex flex-1 justify-between leading-none',
nestLabel ? 'items-end' : 'items-center',
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label ?? item.name}
</span>
</div>
{item.value != null && (
<span className="font-mono font-medium text-foreground tabular-nums">
{typeof item.value === 'number'
? item.value.toLocaleString()
: String(item.value)}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = 'bottom',
nameKey,
}: React.ComponentProps<'div'> & {
hideIcon?: boolean
nameKey?: string
} & RechartsPrimitive.DefaultLegendContentProps) {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
className={cn(
'flex items-center justify-center gap-4',
verticalAlign === 'top' ? 'pb-3' : 'pt-3',
className,
)}
>
{payload
.filter((item) => item.type !== 'none')
.map((item, index) => {
const key = `${nameKey ?? item.dataKey ?? 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={index}
className={cn(
'flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground',
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
if (typeof payload !== 'object' || payload === null) {
return undefined
}
const payloadPayload =
'payload' in payload && typeof payload.payload === 'object' && payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (key in payload && typeof payload[key as keyof typeof payload] === 'string') {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
) {
configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string
}
return configLabelKey in config ? config[configLabelKey] : config[key]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}
+29
View File
@@ -0,0 +1,29 @@
'use client'
import * as React from 'react'
import { CheckIcon } from 'lucide-react'
import { Checkbox as CheckboxPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
'peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary',
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }
@@ -0,0 +1,19 @@
import { Collapsible as CollapsiblePrimitive } from 'radix-ui'
function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
+280
View File
@@ -0,0 +1,280 @@
'use client'
import * as React from 'react'
import { Combobox as ComboboxPrimitive } from '@base-ui/react'
import { CheckIcon, ChevronDownIcon, XIcon } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import { Button } from '@/ui/components/ui/button'
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from '@/ui/components/ui/input-group'
const Combobox = ComboboxPrimitive.Root
function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />
}
function ComboboxTrigger({ className, children, ...props }: ComboboxPrimitive.Trigger.Props) {
return (
<ComboboxPrimitive.Trigger
data-slot="combobox-trigger"
className={cn("[&_svg:not([class*='size-'])]:size-4", className)}
{...props}
>
{children}
<ChevronDownIcon
data-slot="combobox-trigger-icon"
className="pointer-events-none size-4 text-muted-foreground"
/>
</ComboboxPrimitive.Trigger>
)
}
function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
return (
<ComboboxPrimitive.Clear
data-slot="combobox-clear"
render={<InputGroupButton variant="ghost" size="icon-xs" />}
className={cn(className)}
{...props}
>
<XIcon className="pointer-events-none" />
</ComboboxPrimitive.Clear>
)
}
function ComboboxInput({
className,
children,
disabled = false,
showTrigger = true,
showClear = false,
...props
}: ComboboxPrimitive.Input.Props & {
showTrigger?: boolean
showClear?: boolean
}) {
return (
<InputGroup className={cn('w-auto', className)}>
<ComboboxPrimitive.Input render={<InputGroupInput disabled={disabled} />} {...props} />
<InputGroupAddon align="inline-end">
{showTrigger && (
<InputGroupButton
size="icon-xs"
variant="ghost"
asChild
data-slot="input-group-button"
className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent"
disabled={disabled}
>
<ComboboxTrigger />
</InputGroupButton>
)}
{showClear && <ComboboxClear disabled={disabled} />}
</InputGroupAddon>
{children}
</InputGroup>
)
}
function ComboboxContent({
className,
side = 'bottom',
sideOffset = 6,
align = 'start',
alignOffset = 0,
anchor,
...props
}: ComboboxPrimitive.Popup.Props &
Pick<
ComboboxPrimitive.Positioner.Props,
'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor'
>) {
return (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Positioner
side={side}
sideOffset={sideOffset}
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="isolate z-50"
>
<ComboboxPrimitive.Popup
data-slot="combobox-content"
data-chips={!!anchor}
className={cn(
'group/combobox-content relative max-h-96 w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] origin-(--transform-origin) overflow-hidden rounded-md bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className,
)}
{...props}
/>
</ComboboxPrimitive.Positioner>
</ComboboxPrimitive.Portal>
)
}
function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
return (
<ComboboxPrimitive.List
data-slot="combobox-list"
className={cn(
'max-h-[min(calc(--spacing(96)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto p-1 data-empty:p-0',
className,
)}
{...props}
/>
)
}
function ComboboxItem({ className, children, ...props }: ComboboxPrimitive.Item.Props) {
return (
<ComboboxPrimitive.Item
data-slot="combobox-item"
className={cn(
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<ComboboxPrimitive.ItemIndicator
data-slot="combobox-item-indicator"
render={
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
}
>
<CheckIcon className="pointer-events-none size-4 pointer-coarse:size-5" />
</ComboboxPrimitive.ItemIndicator>
</ComboboxPrimitive.Item>
)
}
function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
return <ComboboxPrimitive.Group data-slot="combobox-group" className={cn(className)} {...props} />
}
function ComboboxLabel({ className, ...props }: ComboboxPrimitive.GroupLabel.Props) {
return (
<ComboboxPrimitive.GroupLabel
data-slot="combobox-label"
className={cn(
'px-2 py-1.5 text-xs text-muted-foreground pointer-coarse:px-3 pointer-coarse:py-2 pointer-coarse:text-sm',
className,
)}
{...props}
/>
)
}
function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) {
return <ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />
}
function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
return (
<ComboboxPrimitive.Empty
data-slot="combobox-empty"
className={cn(
'hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex',
className,
)}
{...props}
/>
)
}
function ComboboxSeparator({ className, ...props }: ComboboxPrimitive.Separator.Props) {
return (
<ComboboxPrimitive.Separator
data-slot="combobox-separator"
className={cn('-mx-1 my-1 h-px bg-border', className)}
{...props}
/>
)
}
function ComboboxChips({
className,
...props
}: React.ComponentPropsWithRef<typeof ComboboxPrimitive.Chips> & ComboboxPrimitive.Chips.Props) {
return (
<ComboboxPrimitive.Chips
data-slot="combobox-chips"
className={cn(
'flex min-h-9 flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 py-1.5 text-sm shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-[3px] has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1.5 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40',
className,
)}
{...props}
/>
)
}
function ComboboxChip({
className,
children,
showRemove = true,
...props
}: ComboboxPrimitive.Chip.Props & {
showRemove?: boolean
}) {
return (
<ComboboxPrimitive.Chip
data-slot="combobox-chip"
className={cn(
'flex h-[calc(--spacing(5.5))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0',
className,
)}
{...props}
>
{children}
{showRemove && (
<ComboboxPrimitive.ChipRemove
render={<Button variant="ghost" size="icon-xs" />}
className="-ml-1 opacity-50 hover:opacity-100"
data-slot="combobox-chip-remove"
>
<XIcon className="pointer-events-none" />
</ComboboxPrimitive.ChipRemove>
)}
</ComboboxPrimitive.Chip>
)
}
function ComboboxChipsInput({ className, children, ...props }: ComboboxPrimitive.Input.Props) {
return (
<ComboboxPrimitive.Input
data-slot="combobox-chip-input"
className={cn('min-w-16 flex-1 outline-none', className)}
{...props}
/>
)
}
function useComboboxAnchor() {
return React.useRef<HTMLDivElement | null>(null)
}
export {
Combobox,
ComboboxInput,
ComboboxContent,
ComboboxList,
ComboboxItem,
ComboboxGroup,
ComboboxLabel,
ComboboxCollection,
ComboboxEmpty,
ComboboxSeparator,
ComboboxChips,
ComboboxChip,
ComboboxChipsInput,
ComboboxTrigger,
ComboboxValue,
useComboboxAnchor,
}
+161
View File
@@ -0,0 +1,161 @@
'use client'
import * as React from 'react'
import { Command as CommandPrimitive } from 'cmdk'
import { SearchIcon } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
'flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground',
className,
)}
{...props}
/>
)
}
function CommandDialog({
title = 'Command Palette',
description = 'Search for a command to run...',
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn('overflow-hidden p-0', className)}
showCloseButton={showCloseButton}
>
<Command className="**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div data-slot="command-input-wrapper" className="flex h-9 items-center gap-2 border-b px-3">
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
'flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
{...props}
/>
</div>
)
}
function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn('max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto', className)}
{...props}
/>
)
}
function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
'overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground',
className,
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn('-mx-1 h-px bg-border', className)}
{...props}
/>
)
}
function CommandItem({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className,
)}
{...props}
/>
)
}
function CommandShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="command-shortcut"
className={cn('ml-auto text-xs tracking-widest text-muted-foreground', className)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}
@@ -0,0 +1,224 @@
'use client'
import * as React from 'react'
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'
import { ContextMenu as ContextMenuPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
}
function ContextMenuTrigger({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
}
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
}
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
}
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
}
function ContextMenuRadioGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />
}
function ContextMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.SubTrigger
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</ContextMenuPrimitive.SubTrigger>
)
}
function ContextMenuSubContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return (
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
'z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
className,
)}
{...props}
/>
)
}
function ContextMenuContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
'z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
)
}
function ContextMenuItem({
className,
inset,
variant = 'default',
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
variant?: 'default' | 'destructive'
}) {
return (
<ContextMenuPrimitive.Item
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
className,
)}
{...props}
/>
)
}
function ContextMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
return (
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
)
}
function ContextMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
return (
<ContextMenuPrimitive.RadioItem
data-slot="context-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
)
}
function ContextMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
className={cn('px-2 py-1.5 text-sm font-medium text-foreground data-[inset]:pl-8', className)}
{...props}
/>
)
}
function ContextMenuSeparator({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
className={cn('-mx-1 my-1 h-px bg-border', className)}
{...props}
/>
)
}
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="context-menu-shortcut"
className={cn('ml-auto text-xs tracking-widest text-muted-foreground', className)}
{...props}
/>
)
}
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}
@@ -0,0 +1,36 @@
import * as React from 'react'
import { Input } from './input'
interface DebouncedInputProps extends Omit<
React.ComponentProps<typeof Input>,
'onChange' | 'value'
> {
value: string | number
onChange: (value: string | number) => void
debounce?: number
}
export function DebouncedInput({
value: initialValue,
onChange,
debounce = 500,
...props
}: DebouncedInputProps) {
const [value, setValue] = React.useState(initialValue)
React.useEffect(() => {
setValue(initialValue)
}, [initialValue])
React.useEffect(() => {
const timeout = setTimeout(() => {
if (value !== initialValue) {
onChange(value)
}
}, debounce)
return () => clearTimeout(timeout)
}, [value, debounce, onChange, initialValue])
return <Input {...props} value={value} onChange={(e) => setValue(e.target.value)} />
}
+142
View File
@@ -0,0 +1,142 @@
import * as React from 'react'
import { XIcon } from 'lucide-react'
import { Dialog as DialogPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
import { Button } from '@/ui/components/ui/button'
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-header"
className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<'div'> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('text-lg leading-none font-semibold', className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
@@ -0,0 +1,20 @@
'use client'
import * as React from 'react'
import { Direction } from 'radix-ui'
function DirectionProvider({
dir,
direction,
children,
}: React.ComponentProps<typeof Direction.DirectionProvider> & {
direction?: React.ComponentProps<typeof Direction.DirectionProvider>['dir']
}) {
return (
<Direction.DirectionProvider dir={direction ?? dir}>{children}</Direction.DirectionProvider>
)
}
const useDirection = Direction.useDirection
export { DirectionProvider, useDirection }
+122
View File
@@ -0,0 +1,122 @@
import * as React from 'react'
import { Drawer as DrawerPrimitive } from 'vaul'
import { cn } from '@/ui/lib/utils'
function Drawer({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
}
function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
}
function DrawerPortal({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
}
function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
}
function DrawerOverlay({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
return (
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
)
}
function DrawerContent({
className,
children,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
'group/drawer-content fixed z-50 flex h-auto flex-col bg-background',
'data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b',
'data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t',
'data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm',
'data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm',
className,
)}
{...props}
>
<div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
)
}
function DrawerHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="drawer-header"
className={cn(
'flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left',
className,
)}
{...props}
/>
)
}
function DrawerFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="drawer-footer"
className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
)
}
function DrawerTitle({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn('font-semibold text-foreground', className)}
{...props}
/>
)
}
function DrawerDescription({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
)
}
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}
@@ -0,0 +1,228 @@
'use client'
import * as React from 'react'
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'
import { DropdownMenu as DropdownMenuPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
'z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
}
function DropdownMenuItem({
className,
inset,
variant = 'default',
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: 'default' | 'destructive'
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
className,
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn('-mx-1 my-1 h-px bg-border', className)}
{...props}
/>
)
}
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn('ml-auto text-xs tracking-widest text-muted-foreground', className)}
{...props}
/>
)
}
function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
'z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
className,
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
@@ -0,0 +1,35 @@
import { Input } from '@/ui/components/ui/input'
import { cn } from '@/ui/lib/utils'
import React from 'react'
export type EditableTextProps = React.ComponentPropsWithoutRef<'input'>
const EditableText = React.forwardRef<HTMLInputElement, EditableTextProps>(
({ className, onClick, onMouseDown, ...props }, ref) => {
return (
<Input
className={cn(
'h-auto min-h-0 w-full rounded-sm border px-1 py-0.5 text-base shadow-none transition-all outline-none focus-visible:ring-0',
!props.disabled
? 'border-blue-500 bg-muted/10 ring-1 ring-blue-500'
: 'border-transparent bg-transparent cursor-default opacity-100 disabled:opacity-100 disabled:cursor-default disabled:pointer-events-auto',
className,
)}
ref={ref}
onClick={(e) => {
e.stopPropagation()
onClick?.(e)
}}
onMouseDown={(e) => {
e.stopPropagation()
onMouseDown?.(e)
}}
{...props}
/>
)
},
)
EditableText.displayName = 'EditableText'
export { EditableText }
+94
View File
@@ -0,0 +1,94 @@
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/ui/lib/utils'
function Empty({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="empty"
className={cn(
'flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12',
className,
)}
{...props}
/>
)
}
function EmptyHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="empty-header"
className={cn('flex max-w-sm flex-col items-center gap-2 text-center', className)}
{...props}
/>
)
}
const emptyMediaVariants = cva(
'mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-transparent',
icon: "flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-6",
},
},
defaultVariants: {
variant: 'default',
},
},
)
function EmptyMedia({
className,
variant = 'default',
...props
}: React.ComponentProps<'div'> & VariantProps<typeof emptyMediaVariants>) {
return (
<div
data-slot="empty-icon"
data-variant={variant}
className={cn(emptyMediaVariants({ variant, className }))}
{...props}
/>
)
}
function EmptyTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="empty-title"
className={cn('text-lg font-medium tracking-tight', className)}
{...props}
/>
)
}
function EmptyDescription({ className, ...props }: React.ComponentProps<'p'>) {
return (
<div
data-slot="empty-description"
className={cn(
'text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary',
className,
)}
{...props}
/>
)
}
function EmptyContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="empty-content"
className={cn(
'flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance',
className,
)}
{...props}
/>
)
}
export { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyContent, EmptyMedia }
+234
View File
@@ -0,0 +1,234 @@
'use client'
import { useMemo } from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/ui/lib/utils'
import { Label } from '@/ui/components/ui/label'
import { Separator } from '@/ui/components/ui/separator'
function FieldSet({ className, ...props }: React.ComponentProps<'fieldset'>) {
return (
<fieldset
data-slot="field-set"
className={cn(
'flex flex-col gap-6',
'has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3',
className,
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = 'legend',
...props
}: React.ComponentProps<'legend'> & { variant?: 'legend' | 'label' }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
'mb-3 font-medium',
'data-[variant=legend]:text-base',
'data-[variant=label]:text-sm',
className,
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="field-group"
className={cn(
'group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4',
className,
)}
{...props}
/>
)
}
const fieldVariants = cva('group/field flex w-full gap-3 data-[invalid=true]:text-destructive', {
variants: {
orientation: {
vertical: ['flex-col [&>*]:w-full [&>.sr-only]:w-auto'],
horizontal: [
'flex-row items-center',
'[&>[data-slot=field-label]]:flex-auto',
'has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px',
],
responsive: [
'flex-col @md/field-group:flex-row @md/field-group:items-center [&>*]:w-full @md/field-group:[&>*]:w-auto [&>.sr-only]:w-auto',
'@md/field-group:[&>[data-slot=field-label]]:flex-auto',
'@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px',
],
},
},
defaultVariants: {
orientation: 'vertical',
},
})
function Field({
className,
orientation = 'vertical',
...props
}: React.ComponentProps<'div'> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="field-content"
className={cn('group/field-content flex flex-1 flex-col gap-1.5 leading-snug', className)}
{...props}
/>
)
}
function FieldLabel({ className, ...props }: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
'group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50',
'has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4',
'has-data-[state=checked]:border-primary has-data-[state=checked]:bg-primary/5 dark:has-data-[state=checked]:bg-primary/10',
className,
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="field-label"
className={cn(
'flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50',
className,
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<'p'>) {
return (
<p
data-slot="field-description"
className={cn(
'text-sm leading-normal font-normal text-muted-foreground group-has-[[data-orientation=horizontal]]/field:text-balance',
'last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5',
'[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary',
className,
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<'div'> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
'relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2',
className,
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<'div'> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors?.length) {
return null
}
const uniqueErrors = [...new Map(errors.map((error) => [error?.message, error])).values()]
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map((error, index) => error?.message && <li key={index}>{error.message}</li>)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn('text-sm font-normal text-destructive', className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}
+150
View File
@@ -0,0 +1,150 @@
import * as React from 'react'
import type { Label as LabelPrimitive } from 'radix-ui'
import { Slot } from 'radix-ui'
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from 'react-hook-form'
import { cn } from '@/ui/lib/utils'
import { Label } from '@/ui/components/ui/label'
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState } = useFormContext()
const formState = useFormState({ name: fieldContext.name })
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error('useFormField should be used within <FormField>')
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue)
function FormItem({ className, ...props }: React.ComponentProps<'div'>) {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div data-slot="form-item" className={cn('grid gap-2', className)} {...props} />
</FormItemContext.Provider>
)
}
function FormLabel({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField()
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn('data-[error=true]:text-destructive', className)}
htmlFor={formItemId}
{...props}
/>
)
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot.Root>) {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot.Root
data-slot="form-control"
id={formItemId}
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
aria-invalid={!!error}
{...props}
/>
)
}
function FormDescription({ className, ...props }: React.ComponentProps<'p'>) {
const { formDescriptionId } = useFormField()
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
)
}
function FormMessage({ className, ...props }: React.ComponentProps<'p'>) {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? '') : props.children
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn('text-sm text-destructive', className)}
{...props}
>
{body}
</p>
)
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}
@@ -0,0 +1,36 @@
import * as React from 'react'
import { HoverCard as HoverCardPrimitive } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
function HoverCard({ ...props }: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
}
function HoverCardTrigger({ ...props }: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
return <HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
}
function HoverCardContent({
className,
align = 'center',
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
return (
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
<HoverCardPrimitive.Content
data-slot="hover-card-content"
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
className,
)}
{...props}
/>
</HoverCardPrimitive.Portal>
)
}
export { HoverCard, HoverCardTrigger, HoverCardContent }
+222
View File
@@ -0,0 +1,222 @@
import React, { type SVGProps } from 'react'
/**
* Common props for the icons, extending standard SVG attributes.
*/
type IconProps = SVGProps<SVGSVGElement>
/**
* Shared props for consistent styling across this icon set.
* Uses the Material Symbols coordinate system.
*/
const defaultProps: IconProps = {
viewBox: '0 -960 960 960',
fill: 'currentColor',
xmlns: 'http://www.w3.org/2000/svg',
}
/**
* Icon: Dock To Left (Outline)
* Represents a window with a left sidebar panel.
*/
export const DockToLeft: React.FC<IconProps> = (props) => (
<svg {...defaultProps} {...props}>
<path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm120-80v-560H200v560h120Zm80 0h360v-560H400v560Z" />
</svg>
)
/**
* Icon: Dock To Right (Outline)
* Represents a window with a right sidebar panel.
*/
export const DockToRight: React.FC<IconProps> = (props) => (
<svg {...defaultProps} {...props}>
<path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm360-80v-560H200v560h360Zm200 0v-560H640v560h120Z" />
</svg>
)
/**
* Icon: Dock To Left (Filled)
* Represents a window where the left dock and frame are solid, highlighting the sidebar structure.
*/
export const DockToLeftFilled: React.FC<IconProps> = (props) => (
<svg {...defaultProps} {...props}>
<path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm560-80v-560H400v560h360Z" />
</svg>
)
/**
* Icon: Dock To Right (Filled)
* Represents a window where the right dock and frame are solid, highlighting the sidebar structure.
*/
export const DockToRightFilled: React.FC<IconProps> = (props) => (
<svg {...defaultProps} {...props}>
<path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm360-80v-560H200v560h360Z" />
</svg>
)
export const NotificationFillIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={30}
height={30}
viewBox="120 -792 720 720"
fill="none"
aria-hidden="true"
focusable="false"
{...props}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M 160 -180 v -72 h 80 v -252 q 0 -74.7 50 -132.75 T 420 -712.8 v -25.2 q 0 -22.5 17.5 -38.25 T 480 -792 q 25 0 42.5 15.75 T 540 -738 v 25.2 q 80 18 130 76.05 T 720 -504 v 252 h 80 v 72 H 160 Z M 480 -72 q -33 0 -56.5 -21.15 T 400 -144 h 160 q 0 29.7 -23.5 50.85 T 480 -72 Z"
fill="currentColor"
/>
</svg>
)
export const DrawAnnotation: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 0 24 24"
fill="none"
aria-hidden="true"
focusable="false"
{...props}
>
<path
d="M10.77 10.377a1 1 0 0 0-.132.437l-.105 1.665a.5.5 0 0 0 .793.436l1.32-.96a1 1 0 0 0 .278-.309l3.912-6.775a1.25 1.25 0 1 0-2.165-1.25l-3.901 6.756Z"
fill="currentColor"
/>
<path
d="M11.016 6.75a.758.758 0 0 1-.758.748c-2.938 0-4.882 1.71-5.517 3.95-.708 2.499.245 4.459 1.979 5.851 1.767 1.42 4.31 2.203 6.547 2.203.415 0 .749.335.745.748a.758.758 0 0 1-.758.748c-2.536 0-5.421-.873-7.485-2.531-2.098-1.686-3.38-4.225-2.475-7.414.818-2.883 3.354-5.051 6.977-5.051.415 0 .749.335.745.748Z"
fill="currentColor"
/>
<path
d="M17.147 8.315a.767.767 0 0 1 1.058-.168c1.666 1.188 2.508 2.542 2.733 3.876a4.5 4.5 0 0 1-.805 3.392c-.919 1.434-2.714 2.074-4.479 2.185-1.799.113-3.78-.302-5.292-1.216a.733.733 0 0 1-.242-1.022.768.768 0 0 1 1.042-.246c1.216.734 2.881 1.096 4.409 1 1.553-.097 2.755-.647 3.292-1.5l.015-.022.015-.021a3.025 3.025 0 0 0 .553-2.294c-.148-.876-.72-1.915-2.137-2.926a.733.733 0 0 1-.162-1.038Z"
fill="currentColor"
/>
</svg>
)
export const ShumaiLogo: React.FC<React.SVGProps<SVGSVGElement>> = (props) => {
return (
<svg viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
<defs>
<clipPath id="bg-clip">
<rect x="5" y="5" width="90" height="90" rx="22" />
</clipPath>
</defs>
{/* Background */}
<rect x="5" y="5" width="90" height="90" rx="22" fill="#D95A66" />
{/* Long Shadow */}
<path
d="M 35 75 L 65 75 L 80 60 L 75 30 L 175 130 L 135 175 Z"
fill="#A8384D"
clipPath="url(#bg-clip)"
/>
{/* Left Cream */}
<path d="M 25 30 Q 38 36 50 42 L 35 55 L 35 75 L 20 60 Z" fill="#FDF0D5" />
{/* Right Orange */}
<path d="M 50 42 Q 62 36 75 30 L 80 60 L 65 75 L 65 55 Z" fill="#E77A65" />
{/* Front Peach */}
<path d="M 35 75 L 65 75 L 65 55 L 50 42 L 35 55 Z" fill="#F5B895" />
{/* Top Pink */}
<path d="M 50 42 Q 38 36 25 30 Q 38 26 50 20 Q 62 26 75 30 Q 62 36 50 42 Z" fill="#F4B8B8" />
{/* Hole Left */}
<path d="M 50 25 L 42 30 L 50 35 Z" fill="#E57A5F" />
{/* Hole Right */}
<path d="M 50 25 L 58 30 L 50 35 Z" fill="#C2523C" />
</svg>
)
}
export const HomeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="24 24 152 152"
fill="none"
aria-hidden="true"
focusable="false"
{...props}
>
<path
d="M 44 170 L 44 100 L 24 100 L 100 30 L 126 54 L 126 36 L 142 36 L 142 69 L 176 100 L 156 100 L 156 170 L 120 170 L 120 136 A 20 20 0 0 0 80 136 L 80 170 Z"
fill="currentColor"
/>
</svg>
)
interface UploadCloudIconProps extends React.SVGProps<SVGSVGElement> {
uploading?: boolean
className?: string
}
/**
* Custom UploadCloudIcon component.
* Replaces the animated version with a custom SVG while maintaining prop compatibility.
*/
export function UploadCloudIcon({
uploading = false,
className = '',
...props
}: UploadCloudIconProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="15 15 70 70"
width={30}
height={30}
className={`${className} ${uploading ? 'animate-upload-breathing' : ''}`}
aria-hidden="true"
focusable="false"
style={uploading ? { transformOrigin: 'center' } : undefined}
{...props}
>
{uploading && (
<defs>
<linearGradient id="upload-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stopColor="#3b82f6">
<animate
attributeName="stop-color"
values="#3b82f6;#ec4899;#8b5cf6;#3b82f6"
dur="3s"
repeatCount="indefinite"
/>
</stop>
<stop offset="50%" stopColor="#8b5cf6">
<animate
attributeName="stop-color"
values="#8b5cf6;#3b82f6;#ec4899;#8b5cf6"
dur="3s"
repeatCount="indefinite"
/>
</stop>
<stop offset="100%" stopColor="#ec4899">
<animate
attributeName="stop-color"
values="#ec4899;#8b5cf6;#3b82f6;#ec4899"
dur="3s"
repeatCount="indefinite"
/>
</stop>
</linearGradient>
</defs>
)}
<path
d="M 44.1 75 H 30 A 15 15 0 0 1 30 45 A 20 20 0 0 1 70 45 A 15 15 0 0 1 70 75 H 55.9 V 60.2 H 61.9 L 50 45.3 L 38.1 60.2 H 44.1 Z"
fill={uploading ? 'url(#upload-gradient)' : 'currentColor'}
/>
</svg>
)
}
@@ -0,0 +1,156 @@
import * as React from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/ui/lib/utils'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Textarea } from '@/ui/components/ui/textarea'
function InputGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
'group/input-group relative flex w-full items-center rounded-md border border-input shadow-xs transition-[color,box-shadow] outline-none dark:bg-input/30',
'h-9 min-w-0 has-[>textarea]:h-auto',
// Variants based on alignment.
'has-[>[data-align=inline-start]]:[&>input]:pl-2',
'has-[>[data-align=inline-end]]:[&>input]:pr-2',
'has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3',
'has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3',
// Focus state.
'has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-[3px] has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50',
// Error state.
'has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-destructive/20 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40',
className,
)}
{...props}
/>
)
}
const inputGroupAddonVariants = cva(
"flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
{
variants: {
align: {
'inline-start': 'order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]',
'inline-end': 'order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]',
'block-start':
'order-first w-full justify-start px-3 pt-3 group-has-[>input]/input-group:pt-2.5 [.border-b]:pb-3',
'block-end':
'order-last w-full justify-start px-3 pb-3 group-has-[>input]/input-group:pb-2.5 [.border-t]:pt-3',
},
},
defaultVariants: {
align: 'inline-start',
},
},
)
function InputGroupAddon({
className,
align = 'inline-start',
...props
}: React.ComponentProps<'div'> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest('button')) {
return
}
e.currentTarget.parentElement?.querySelector('input')?.focus()
}}
{...props}
/>
)
}
const inputGroupButtonVariants = cva('flex items-center gap-2 text-sm shadow-none', {
variants: {
size: {
xs: "h-6 gap-1 rounded-[calc(var(--radius)-5px)] px-2 has-[>svg]:px-2 [&>svg:not([class*='size-'])]:size-3.5",
sm: 'h-8 gap-1.5 rounded-md px-2.5 has-[>svg]:px-2.5',
'icon-xs': 'size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0',
'icon-sm': 'size-8 p-0 has-[>svg]:p-0',
},
},
defaultVariants: {
size: 'xs',
},
})
function InputGroupButton({
className,
type = 'button',
variant = 'ghost',
size = 'xs',
...props
}: Omit<React.ComponentProps<typeof Button>, 'size'> &
VariantProps<typeof inputGroupButtonVariants>) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
)
}
function InputGroupText({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
className={cn(
"flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
)
}
function InputGroupInput({ className, ...props }: React.ComponentProps<'input'>) {
return (
<Input
data-slot="input-group-control"
className={cn(
'flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent',
className,
)}
{...props}
/>
)
}
function InputGroupTextarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
'flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent',
className,
)}
{...props}
/>
)
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
}
@@ -0,0 +1,70 @@
'use client'
import * as React from 'react'
import { OTPInput, OTPInputContext } from 'input-otp'
import { MinusIcon } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn('flex items-center gap-2 has-disabled:opacity-50', containerClassName)}
className={cn('disabled:cursor-not-allowed', className)}
{...props}
/>
)
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="input-otp-group" className={cn('flex items-center', className)} {...props} />
)
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<'div'> & {
index: number
}) {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
'relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md aria-invalid:border-destructive data-[active=true]:z-10 data-[active=true]:border-ring data-[active=true]:ring-[3px] data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40',
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
</div>
)}
</div>
)
}
function InputOTPSeparator({ ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
)
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
+21
View File
@@ -0,0 +1,21 @@
import * as React from 'react'
import { cn } from '@/ui/lib/utils'
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
return (
<input
type={type}
data-slot="input"
className={cn(
'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30',
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',
'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
className,
)}
{...props}
/>
)
}
export { Input }
+172
View File
@@ -0,0 +1,172 @@
import * as React from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { Slot } from 'radix-ui'
import { cn } from '@/ui/lib/utils'
import { Separator } from '@/ui/components/ui/separator'
function ItemGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
role="list"
data-slot="item-group"
className={cn('group/item-group flex flex-col', className)}
{...props}
/>
)
}
function ItemSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="item-separator"
orientation="horizontal"
className={cn('my-0', className)}
{...props}
/>
)
}
const itemVariants = cva(
'group/item flex flex-wrap items-center rounded-md border border-transparent text-sm transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors [a]:hover:bg-accent/50',
{
variants: {
variant: {
default: 'bg-transparent',
outline: 'border-border',
muted: 'bg-muted/50',
},
size: {
default: 'gap-4 p-4',
sm: 'gap-2.5 px-4 py-3',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
},
)
function Item({
className,
variant = 'default',
size = 'default',
asChild = false,
...props
}: React.ComponentProps<'div'> & VariantProps<typeof itemVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : 'div'
return (
<Comp
data-slot="item"
data-variant={variant}
data-size={size}
className={cn(itemVariants({ variant, size, className }))}
{...props}
/>
)
}
const itemMediaVariants = cva(
'flex shrink-0 items-center justify-center gap-2 group-has-[[data-slot=item-description]]/item:translate-y-0.5 group-has-[[data-slot=item-description]]/item:self-start [&_svg]:pointer-events-none',
{
variants: {
variant: {
default: 'bg-transparent',
icon: "size-8 rounded-sm border bg-muted [&_svg:not([class*='size-'])]:size-4",
image: 'size-10 overflow-hidden rounded-sm [&_img]:size-full [&_img]:object-cover',
},
},
defaultVariants: {
variant: 'default',
},
},
)
function ItemMedia({
className,
variant = 'default',
...props
}: React.ComponentProps<'div'> & VariantProps<typeof itemMediaVariants>) {
return (
<div
data-slot="item-media"
data-variant={variant}
className={cn(itemMediaVariants({ variant, className }))}
{...props}
/>
)
}
function ItemContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="item-content"
className={cn('flex flex-1 flex-col gap-1 [&+[data-slot=item-content]]:flex-none', className)}
{...props}
/>
)
}
function ItemTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="item-title"
className={cn('flex w-fit items-center gap-2 text-sm leading-snug font-medium', className)}
{...props}
/>
)
}
function ItemDescription({ className, ...props }: React.ComponentProps<'p'>) {
return (
<p
data-slot="item-description"
className={cn(
'line-clamp-2 text-sm leading-normal font-normal text-balance text-muted-foreground',
'[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary',
className,
)}
{...props}
/>
)
}
function ItemActions({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="item-actions" className={cn('flex items-center gap-2', className)} {...props} />
)
}
function ItemHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="item-header"
className={cn('flex basis-full items-center justify-between gap-2', className)}
{...props}
/>
)
}
function ItemFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="item-footer"
className={cn('flex basis-full items-center justify-between gap-2', className)}
{...props}
/>
)
}
export {
Item,
ItemMedia,
ItemContent,
ItemActions,
ItemGroup,
ItemSeparator,
ItemTitle,
ItemDescription,
ItemHeader,
ItemFooter,
}

Some files were not shown because too many files have changed in this diff Show More