mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 19:04:23 +00:00
initial commit
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
import type { AncestorFolder } from '@/dtos/asset'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
DockToLeft,
|
||||
DockToLeftFilled,
|
||||
DockToRight,
|
||||
DockToRightFilled,
|
||||
} from '@/ui/components/ui/icons'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { ChevronDown, LayoutGrid, List } 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
|
||||
}
|
||||
|
||||
export function BreadcrumbNav({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
ancestorFolders,
|
||||
currentAsset,
|
||||
isRootFolder,
|
||||
displayStyle,
|
||||
onDisplayStyleChange,
|
||||
isLeftSidebarCollapsed,
|
||||
onLeftSidebarToggle,
|
||||
isRightSidebarCollapsed,
|
||||
onRightSidebarToggle,
|
||||
isPublic = false,
|
||||
onFolderClick,
|
||||
}: BreadcrumbNavProps) {
|
||||
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>
|
||||
<DropdownMenuItem onClick={() => console.log('Download')}>
|
||||
Download
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => console.log('Rename')}>Rename</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => console.log('Delete')}>Delete</DropdownMenuItem>
|
||||
</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,189 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { AttachmentInfo, CommentInfo } from '@/dtos/asset'
|
||||
import type { UserInfo } from '@/dtos/team'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Download, File } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { Avatar, AvatarFallback } from '../ui/avatar'
|
||||
import { Skeleton } from '../ui/skeleton'
|
||||
import Markdown from 'react-markdown'
|
||||
|
||||
interface MessageCardProps {
|
||||
teamId?: string
|
||||
message: CommentInfo
|
||||
isReply?: boolean
|
||||
hasReplies?: boolean
|
||||
isLastReply?: boolean
|
||||
getUser: (id: string) => UserInfo
|
||||
onReply: (message: CommentInfo) => void
|
||||
onViewAttachment: (attachment: AttachmentInfo) => void
|
||||
rootParentId?: string
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const AI_PLACEHOLDERS: Record<string, string> = {
|
||||
__CHAT__: 'Generating...',
|
||||
__AUTOFILL__: 'Autofilling metadata...',
|
||||
__EMBEDDING__: 'Generating embeddings...',
|
||||
__TRANSCRIPTION__: 'Transcribing...',
|
||||
__RUNNING__: 'Generating...',
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
export const MessageCard: React.FC<MessageCardProps> = ({
|
||||
teamId,
|
||||
message: initialMessage,
|
||||
isReply,
|
||||
hasReplies,
|
||||
isLastReply,
|
||||
getUser,
|
||||
onReply,
|
||||
onViewAttachment,
|
||||
}) => {
|
||||
const isRunning =
|
||||
initialMessage.isAi && !!initialMessage.message && initialMessage.message in AI_PLACEHOLDERS
|
||||
|
||||
const { data: polledMessage } = useQuery({
|
||||
queryKey: ['teams', teamId, 'comments', initialMessage.id],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].comments[':commentId'].$get({
|
||||
param: { teamId: teamId!, commentId: initialMessage.id! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch comment')
|
||||
return (await res.json()) as CommentInfo
|
||||
},
|
||||
enabled: !!teamId && isRunning,
|
||||
refetchInterval: (query) => {
|
||||
const data = query.state.data as CommentInfo
|
||||
if (data && (!data.message || !(data.message in AI_PLACEHOLDERS))) {
|
||||
return false
|
||||
}
|
||||
return 2000
|
||||
},
|
||||
})
|
||||
|
||||
const message = polledMessage || initialMessage
|
||||
const creator = message.creator
|
||||
const showSkeleton = message.isAi && !!message.message && message.message in AI_PLACEHOLDERS
|
||||
const loadingText = (message.message && AI_PLACEHOLDERS[message.message]) || 'Generating...'
|
||||
|
||||
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 handleReply = () => {
|
||||
onReply(message)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`relative flex gap-4 ${isReply ? 'mt-4' : 'mt-6'} group`}>
|
||||
{hasReplies && !isReply && (
|
||||
<div className="absolute left-[1rem] top-[2rem] bottom-[-1.5rem] w-0.5 bg-foreground/10 -translate-x-1/2 z-0" />
|
||||
)}
|
||||
|
||||
{isReply && !isLastReply && (
|
||||
<div className="absolute left-[1rem] top-[2rem] bottom-[-1.5rem] w-0.5 bg-foreground/10 -translate-x-1/2 z-0" />
|
||||
)}
|
||||
|
||||
{/* Avatar */}
|
||||
<div>
|
||||
<Avatar>
|
||||
<AvatarFallback>{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>
|
||||
|
||||
{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.isAi ? (
|
||||
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
|
||||
<Markdown>{message.message!}</Markdown>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm leading-relaxed whitespace-pre-wrap break-words text-wrap break-all">
|
||||
{renderFormattedMessage(message.message!)}
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* 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>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,727 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { CommentInfo } from '@/dtos/asset'
|
||||
import type { UserInfo } from '@/dtos/team'
|
||||
import type { BotInfo } from '@/dtos/project'
|
||||
import type { PostAttachmentRequest, PostAttachmentResponse } from '@/dtos/asset'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowUp,
|
||||
Brush,
|
||||
ChevronDown,
|
||||
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 { ProgressCircle } from '../ui/progress-circle'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
|
||||
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[]) => void
|
||||
replyingTo?: CommentInfo | null
|
||||
onCancelReply?: () => void
|
||||
users?: UserInfo[]
|
||||
bots?: BotInfo[]
|
||||
initialText?: string
|
||||
hideAnnotationControl?: boolean
|
||||
disableMentions?: boolean
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
|
||||
const [viewingFile, setViewingFile] = useState<File | null>(null)
|
||||
|
||||
// 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])
|
||||
|
||||
// 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())
|
||||
|
||||
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)
|
||||
|
||||
// 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-start justify-between bg-gray-50 p-2 rounded-xl border border-l-4 border-gray-200 border-l-blue-500">
|
||||
<div className="flex flex-col text-sm">
|
||||
<span className="font-semibold text-blue-600 mb-0.5">Replying to thread</span>
|
||||
<span className="text-gray-600 line-clamp-1">{replyingTo.message}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={onCancelReply}
|
||||
className="text-gray-400 hover:text-gray-600 p-1 rounded-full hover:bg-gray-200/50"
|
||||
>
|
||||
<XIcon className="w-4 h-4" />
|
||||
</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 className="w-full px-4 pt-1 pb-1">
|
||||
<div
|
||||
ref={editorRef}
|
||||
contentEditable={!isDrawing}
|
||||
suppressContentEditableWarning
|
||||
onInput={handleInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
data-placeholder={
|
||||
isDrawing ? 'Drawing active...' : replyingTo ? 'Reply...' : 'Message...'
|
||||
}
|
||||
className="w-full bg-transparent border-none focus:ring-0 resize-none max-h-60 min-h-[40px] leading-relaxed py-2 focus:outline-none overflow-y-auto"
|
||||
/>
|
||||
</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}
|
||||
/>
|
||||
<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-primary text-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)
|
||||
}
|
||||
@@ -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 / 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 / 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 / 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 / scale}
|
||||
lineCap="round"
|
||||
lineJoin="round"
|
||||
visible={false}
|
||||
/>
|
||||
<Rect ref={currentRectRef} strokeWidth={2 / scale} visible={false} />
|
||||
<Arrow
|
||||
ref={currentArrowRef}
|
||||
points={[]}
|
||||
strokeWidth={2 / scale}
|
||||
pointerLength={10 / scale}
|
||||
pointerWidth={10 / scale}
|
||||
visible={false}
|
||||
/>
|
||||
</Group>
|
||||
</Layer>
|
||||
</Stage>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DrawingCanvas
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Menu } from 'lucide-react'
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import { UserMenu } from './user-menu'
|
||||
|
||||
interface DualSidebarItemProps {
|
||||
icon: React.ReactNode
|
||||
label: string
|
||||
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
|
||||
onClick={toggleMobileMenu}
|
||||
className="md:hidden fixed top-4 left-4 z-50 p-2 rounded-md bg-white/50 dark:bg-slate-800/50 backdrop-blur-sm text-slate-800 dark:text-slate-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
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-orange-400/10 to-transparent"></div>
|
||||
{/* Level 1: Icon Bar */}
|
||||
<nav className="w-16 bg-slate-100 dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 flex flex-col items-center pb-4 pt-2 space-y-2 flex-shrink-0">
|
||||
<div className="flex-1 space-y-2">
|
||||
{sidebarItems.map((item, index) => (
|
||||
<div key={item.props.label} className="relative group">
|
||||
<button
|
||||
onClick={() => handleItemClick(index)}
|
||||
aria-label={item.props.label}
|
||||
aria-expanded={activeItem === index}
|
||||
className={`p-3 rounded-lg transition-all duration-200 outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-blue-500 dark:focus-visible:ring-offset-slate-900 ${
|
||||
activeItem === index
|
||||
? 'bg-blue-600 text-white shadow-lg'
|
||||
: 'text-slate-500 hover:bg-slate-200 dark:hover:bg-slate-800 dark:text-slate-400'
|
||||
}`}
|
||||
>
|
||||
{item.props.icon}
|
||||
</button>
|
||||
<span
|
||||
className="absolute left-full ml-4 px-2 py-1 text-sm bg-slate-800 text-white rounded-md shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap"
|
||||
role="tooltip"
|
||||
>
|
||||
{item.props.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-auto">
|
||||
<UserMenu />
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Level 2: Content Panel */}
|
||||
<div
|
||||
className={`transition-all duration-300 ease-in-out bg-white dark:bg-slate-900/95 backdrop-blur-sm shadow-lg overflow-hidden ${
|
||||
activeItem !== null
|
||||
? 'w-[calc(100vw-4rem)] md:w-80 border-r border-slate-200 dark:border-slate-800'
|
||||
: 'w-0'
|
||||
}`}
|
||||
>
|
||||
<div className="w-[calc(100vw-4rem)] md:w-80 h-full flex flex-col">
|
||||
{activeItemContent && (
|
||||
<>
|
||||
<header className="h-16 flex items-center px-4 font-bold text-lg border-b border-slate-200 dark:border-slate-800 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 '@/dtos/metadata'
|
||||
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 { type FieldInfo as MetadataFieldInfo, type FieldInfo, FieldType } from '@/dtos/metadata'
|
||||
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 { 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 '@/dtos/metadata'
|
||||
|
||||
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 '@/dtos/metadata'
|
||||
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 '@/dtos/metadata'
|
||||
|
||||
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 '@/dtos/metadata'
|
||||
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,221 @@
|
||||
import type { AssetInfo } from '@/dtos/asset'
|
||||
import {
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
} from '@/ui/components/ui/context-menu'
|
||||
import { Download, Edit, FolderPlus, Trash2, UploadCloud, History, FileText } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '../ui/alert-dialog'
|
||||
|
||||
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
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
isRecentlyDeleted?: boolean
|
||||
onOpenAgentsMd?: (item: AssetInfo | null) => void
|
||||
isShareView?: boolean
|
||||
onRemoveFromShare?: (items: AssetInfo[]) => void
|
||||
}
|
||||
|
||||
export function FileBrowserContextMenu({
|
||||
item,
|
||||
selectedIds,
|
||||
onRename,
|
||||
onDelete,
|
||||
onDownload,
|
||||
onRestore,
|
||||
onNewFolder,
|
||||
onUploadFile,
|
||||
onUploadFolder,
|
||||
folders,
|
||||
files,
|
||||
isRecentlyDeleted,
|
||||
onOpenAgentsMd,
|
||||
isShareView,
|
||||
onRemoveFromShare,
|
||||
}: FileBrowserContextMenuProps) {
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
|
||||
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 deleteCount = itemsToDelete.length
|
||||
const itemsToRestore = itemsToModify
|
||||
|
||||
const handleRename = () => {
|
||||
if (item) {
|
||||
onRename(item)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
setIsDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
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={handleDelete} className="text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Delete</span>
|
||||
</ContextMenuItem>
|
||||
</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>
|
||||
|
||||
{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>
|
||||
</ContextMenuContent>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{contextMenuContent}
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
You are about to delete {deleteCount} item(s). Deleted items can be recovered for 30
|
||||
days before being permanently deleted.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
onDelete(itemsToDelete)
|
||||
setIsDeleteDialogOpen(false)
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,685 @@
|
||||
'use client'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
|
||||
import type { AssetInfo } from '@/dtos/asset'
|
||||
import type { SearchCondition, SearchSort } from '@/dtos/search'
|
||||
import type { CreateUploadTaskRequest } from '@/dtos/upload'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
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 { FileBrowserContextMenu } from './context-menu'
|
||||
|
||||
import { FileBrowserGridView } from './grid-view'
|
||||
import { FileBrowserListView } from './list-view'
|
||||
import { FileBrowserToolbar } from './toolbar'
|
||||
import { FileCard } from './file-card'
|
||||
import { FileListItem } from './file-list-item'
|
||||
import { FolderCard } from './folder-card'
|
||||
import { Button } from '../ui/button'
|
||||
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
|
||||
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>
|
||||
}
|
||||
|
||||
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,
|
||||
}: FileBrowserProps) {
|
||||
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const {
|
||||
editingItemId,
|
||||
setEditingItemId,
|
||||
handleNewFolder,
|
||||
handleDelete,
|
||||
handleRename,
|
||||
handleRestore,
|
||||
handleDownload,
|
||||
handleAction,
|
||||
onRenameSubmit,
|
||||
} = 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 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 formatSize = (bytes: number) => {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(0)} MB`
|
||||
}
|
||||
|
||||
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[]) => {
|
||||
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: assetId,
|
||||
files: root,
|
||||
},
|
||||
})
|
||||
},
|
||||
[assetId, createUploadTaskMutation, teamId],
|
||||
)
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
processAndUploadFiles(event.target.files!)
|
||||
}
|
||||
|
||||
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>
|
||||
<ContextMenuTrigger asChild disabled={isShareView || isPublic}>
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
className="flex-1 overflow-y-auto bg-background relative flex flex-col"
|
||||
onContextMenu={(e) => onContextMenu(e)}
|
||||
>
|
||||
{!isShareView && !isPublic && onFilterChange && onSortChange && (
|
||||
<FileBrowserToolbar
|
||||
projectId={projectId}
|
||||
fields={fields || []}
|
||||
filterConditions={filterConditions || []}
|
||||
onFilterChange={onFilterChange}
|
||||
sort={sort}
|
||||
onSortChange={onSortChange}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
/>
|
||||
)}
|
||||
{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>
|
||||
)}
|
||||
|
||||
{selectedCount > 0 && (
|
||||
<div className="border-t border-border bg-card px-4 py-3 flex items-center justify-between">
|
||||
<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}
|
||||
onRestore={handleRestore}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
/>
|
||||
</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}
|
||||
/>
|
||||
{renderContent()}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
import type { AssetInfo, FieldValueInfo } from '@/dtos/asset'
|
||||
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 '@/dtos/metadata'
|
||||
|
||||
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' &&
|
||||
!!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.teams[':teamId'].files[':fileId'].$get({
|
||||
param: { teamId: teamId || '', 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.type === 'version_stack' && (
|
||||
<Badge className="absolute right-2 top-2 z-10">v{displayItem.fileCount}</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>
|
||||
<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,284 @@
|
||||
import type { AssetInfo, FieldValueInfo } from '@/dtos/asset'
|
||||
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 '@/dtos/metadata'
|
||||
|
||||
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' &&
|
||||
!!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.teams[':teamId'].files[':fileId'].$get({
|
||||
param: { teamId: teamId || '', 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.type === 'version_stack' && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-xs shrink-0">
|
||||
v{displayItem.fileCount}
|
||||
</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,341 @@
|
||||
import type { AssetInfo, ChildPreview } from '@/dtos/asset'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
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'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import { EditableText } from '@/ui/components/ui/editable-text'
|
||||
|
||||
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-zinc-200 dark:bg-zinc-800/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-zinc-200 dark:bg-zinc-800/50 rounded-sm">
|
||||
{renderItem(safeChildren[0])}
|
||||
</div>
|
||||
<div className="overflow-hidden h-full bg-zinc-200 dark:bg-zinc-800/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-zinc-200 dark:bg-zinc-800/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-zinc-200 dark:bg-zinc-800/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-zinc-200 dark:bg-zinc-800/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: 3,
|
||||
tabSlope: 10,
|
||||
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 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 : 2}
|
||||
className={cn(
|
||||
'transition-colors duration-200 fill-foreground/10 dark:fill-slate-800 dark:stroke-slate-600 group-hover:stroke-indigo-400 dark:group-hover:stroke-indigo-400',
|
||||
(isSelected || isChecked || showDropFeedback) &&
|
||||
'stroke-indigo-500 dark:stroke-indigo-400',
|
||||
)}
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div className="relative w-[calc(100%-0.2rem)] mb-[0.1rem] flex flex-1 flex-col p-2 mt-4 bg-secondary 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-black/30 bg-black/5 data-[state=checked]:bg-indigo-600 data-[state=checked]:border-indigo-600"
|
||||
/>
|
||||
</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-slate-800 dark:text-slate-100 text-lg leading-tight truncate h-auto p-0"
|
||||
title={name}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between text-slate-500 dark:text-slate-400">
|
||||
<span className="text-xs tracking-wide opacity-80">
|
||||
{item.fileCount || 0} {(item.fileCount || 0) === 1 ? 'Item' : 'Items'}
|
||||
</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="p-1.5 -mr-2 rounded-full hover:bg-slate-200/50 dark:hover:bg-slate-700/50 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 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 '@/dtos/asset'
|
||||
import type { SearchSort } from '@/dtos/search'
|
||||
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 '@/dtos/asset'
|
||||
import type { FieldInfo } from '@/dtos/metadata'
|
||||
import type { SearchSort } from '@/dtos/search'
|
||||
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,203 @@
|
||||
import type { SearchCondition, SearchSort } from '@/dtos/search'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { FieldsManager } from '../fields-manager'
|
||||
import { ManageFieldsDialog } from '../manage-fields-dialog'
|
||||
import { MembersDialog } from '../members-dialog'
|
||||
import { FilterPanel } from '../search/filter-panel'
|
||||
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 { ListFilter, SlidersHorizontal } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Separator } from '../ui/separator'
|
||||
|
||||
type FileBrowserToolbarProps = {
|
||||
projectId: string
|
||||
fields: MetadataFieldInfo[]
|
||||
filterConditions: SearchCondition[]
|
||||
onFilterChange: (conditions: SearchCondition[]) => void
|
||||
sort?: SearchSort
|
||||
onSortChange: (sort?: SearchSort) => void
|
||||
isRecentlyDeleted?: boolean
|
||||
}
|
||||
|
||||
export function FileBrowserToolbar({
|
||||
projectId,
|
||||
fields,
|
||||
filterConditions,
|
||||
onFilterChange,
|
||||
sort,
|
||||
onSortChange,
|
||||
isRecentlyDeleted,
|
||||
}: FileBrowserToolbarProps) {
|
||||
const [popoverOpen, setPopoverOpen] = useState(false)
|
||||
const [filterPopoverOpen, setFilterPopoverOpen] = useState(false)
|
||||
const [manageDialogOpen, setManageDialogOpen] = useState(false)
|
||||
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
|
||||
|
||||
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">
|
||||
<SlidersHorizontal className="h-4 w-4 mr-2" />
|
||||
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" />
|
||||
|
||||
<Popover open={filterPopoverOpen} onOpenChange={setFilterPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant={filterConditions.length > 0 ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
className="h-8"
|
||||
disabled={isRecentlyDeleted}
|
||||
>
|
||||
<ListFilter className="h-4 w-4 mr-1" />
|
||||
Filter
|
||||
{filterConditions.length > 0 && (
|
||||
<span className="ml-1 rounded-full bg-primary/20 px-1.5 py-0.5 text-[10px]">
|
||||
{filterConditions.length}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="center">
|
||||
<FilterPanel fields={fields} conditions={filterConditions} onChange={onFilterChange} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<Separator orientation="vertical" />
|
||||
<SortControl
|
||||
fields={fields}
|
||||
sort={sort}
|
||||
onSortChange={onSortChange}
|
||||
disabled={isRecentlyDeleted}
|
||||
/>
|
||||
</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}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
'use client'
|
||||
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { AssetInfo } from '@/dtos/asset'
|
||||
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 queryClient = useQueryClient()
|
||||
|
||||
const $createFolder = client.api.teams[':teamId'].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.teams[':teamId'].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.teams[':teamId'].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.teams[':teamId'].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.teams[':teamId'].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.teams[':teamId'].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.teams[':teamId'].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 handleDelete = (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) {
|
||||
deleteFiles(
|
||||
{ param: { teamId: teamId }, json: { ids: fileIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
deleteFolders(
|
||||
{ param: { teamId: teamId }, json: { ids: folderIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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(
|
||||
{ param: { teamId: teamId }, json: { ids: fileIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['projects', projectId, 'recently-deleted', 'file'],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
restoreFolders(
|
||||
{ param: { teamId: teamId }, 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(
|
||||
{ param: { teamId: teamId }, 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: { teamId: teamId, folderId: item.id! }, json: { name: newName } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
} else {
|
||||
renameFile(
|
||||
{
|
||||
param: { teamId: teamId, 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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
import type { AssetInfo, AssetInfoPaginatedList } from '@/dtos/asset'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
|
||||
import type { SearchCondition, SearchSort } from '@/dtos/search'
|
||||
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 { useUiStore } from '@/ui/stores/ui'
|
||||
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
||||
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { BreadcrumbNav } from './breadcrumb-nav'
|
||||
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'
|
||||
import { PointerActivationConstraints } from '@dnd-kit/dom'
|
||||
import { DragDropProvider, DragOverlay, KeyboardSensor, PointerSensor } from '@dnd-kit/react'
|
||||
import { SnapToPointer } from './dnd-modifiers'
|
||||
import { cn } from '../lib/utils'
|
||||
|
||||
type FileSystemManagerProps = {
|
||||
teamId: string
|
||||
projectId: string
|
||||
projectName: string
|
||||
assetId: string
|
||||
rootFolderId: string
|
||||
}
|
||||
|
||||
export default function FileSystemManager({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
assetId,
|
||||
rootFolderId,
|
||||
}: FileSystemManagerProps) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { loadedProjectId, setFields } = useFieldStore()
|
||||
const $patchMetadata = client.api.teams[':teamId'].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 [filterConditions, setFilterConditions] = useState<SearchCondition[]>([])
|
||||
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 isFiltering = filterConditions.length > 0
|
||||
|
||||
const {
|
||||
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
fileListRightSidebarCollapsed: isRightSidebarCollapsed,
|
||||
setFileListRightSidebarCollapsed: setIsRightSidebarCollapsed,
|
||||
viewModes,
|
||||
setViewMode,
|
||||
} = useUiStore()
|
||||
|
||||
const displayStyle = viewModes[projectId] ?? 'card'
|
||||
const setDisplayStyle = (style: 'card' | 'list') => {
|
||||
setViewMode(projectId, style)
|
||||
}
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const { data: folderInfo } = isRecentlyDeleted
|
||||
? { data: undefined }
|
||||
: useQuery({
|
||||
queryKey: ['folders', teamId, assetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId, folderId: assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
})
|
||||
|
||||
const {
|
||||
data: foldersData,
|
||||
fetchNextPage: fetchNextFoldersPage,
|
||||
hasNextPage: hasNextPageFolders,
|
||||
isFetchingNextPage: isFetchingNextFoldersPage,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: isRecentlyDeleted
|
||||
? ['projects', projectId, 'recently-deleted', 'folder']
|
||||
: ['search', teamId, assetId, 'folder', filterConditions, sort],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
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
|
||||
}
|
||||
if (isFiltering) {
|
||||
return { data: [], pageInfo: { total: 0 } }
|
||||
}
|
||||
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].search.$post({
|
||||
param: { teamId: teamId, 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],
|
||||
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.teams[':teamId'].folders[':folderId'].search.$post({
|
||||
param: { teamId: teamId, folderId: assetId },
|
||||
json: {
|
||||
assetType: 'file',
|
||||
after: pageParam as string,
|
||||
recursively: isFiltering,
|
||||
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.id },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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: { teamId: teamId, fileId: fileId },
|
||||
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: [
|
||||
'folders',
|
||||
teamId,
|
||||
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 h-screen flex-col bg-background">
|
||||
<BreadcrumbNav
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
ancestorFolders={folderInfo?.ancestorFolders ?? []}
|
||||
currentAsset={
|
||||
isRecentlyDeleted
|
||||
? { name: 'Recently Deleted', type: 'folder' }
|
||||
: { name: folderInfo?.name, type: 'folder' }
|
||||
}
|
||||
isRootFolder={assetId === rootFolderId}
|
||||
displayStyle={displayStyle}
|
||||
onDisplayStyleChange={setDisplayStyle}
|
||||
isLeftSidebarCollapsed={isLeftSidebarCollapsed}
|
||||
onLeftSidebarToggle={() => setIsLeftSidebarCollapsed(!isLeftSidebarCollapsed)}
|
||||
isRightSidebarCollapsed={isRightSidebarCollapsed}
|
||||
onRightSidebarToggle={() => setIsRightSidebarCollapsed(!isRightSidebarCollapsed)}
|
||||
/>
|
||||
|
||||
<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}
|
||||
/>
|
||||
|
||||
{!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,122 @@
|
||||
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 '@/dtos/asset'
|
||||
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 {
|
||||
teamId: string
|
||||
projectId: string
|
||||
currentAssetId: string
|
||||
parentFolderId: string
|
||||
onCollapse: () => void
|
||||
}
|
||||
|
||||
export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
|
||||
teamId,
|
||||
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',
|
||||
teamId,
|
||||
parentFolderId,
|
||||
'children',
|
||||
{
|
||||
assetType: 'file',
|
||||
},
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId: teamId, 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,404 @@
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { AssetInfo, AttachmentInfo, CommentInfo, FieldValueInfo } from '@/dtos/asset'
|
||||
import type { UserInfo } from '@/dtos/team'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { useInfiniteQuery, useQueryClient, useQuery, useMutation } 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 { ScrollArea } from './ui/scroll-area'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { GuestIdentityPopup } from './guest-identity-popup'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
export function FileViewerRightSidebar({
|
||||
teamId,
|
||||
projectId,
|
||||
file,
|
||||
onSaveField,
|
||||
members,
|
||||
onCommentSelect,
|
||||
hideAnnotationControl = false,
|
||||
readOnly = false,
|
||||
publicFields,
|
||||
isPublic = false,
|
||||
shareId,
|
||||
}: 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[]
|
||||
} | 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']
|
||||
: ['teams', teamId, '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.teams[':teamId'].files[':fileId'].comments.$get({
|
||||
param: { teamId: teamId, 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: '',
|
||||
// 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,
|
||||
guestUserId,
|
||||
}: {
|
||||
text: string
|
||||
attachmentIds: string[]
|
||||
annotations?: Annotation[]
|
||||
guestUserId?: string
|
||||
}) => {
|
||||
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: replyingTo?.id,
|
||||
annotations: annotations,
|
||||
},
|
||||
},
|
||||
{
|
||||
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.teams[':teamId'].files[':fileId'].comments.$post({
|
||||
param: { teamId: teamId, fileId: file!.id! },
|
||||
json: {
|
||||
message: text,
|
||||
attachmentIds: attachmentIds,
|
||||
replyToId: replyingTo?.id,
|
||||
annotations: annotations,
|
||||
},
|
||||
})
|
||||
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']
|
||||
: ['teams', teamId, '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[],
|
||||
) => {
|
||||
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 })
|
||||
setIsGuestPopupOpen(true)
|
||||
return
|
||||
}
|
||||
createComment({ text, attachmentIds, annotations, guestUserId })
|
||||
} else {
|
||||
createComment({ text, attachmentIds, annotations })
|
||||
}
|
||||
} else {
|
||||
createComment({ text, attachmentIds, annotations })
|
||||
}
|
||||
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">
|
||||
{/* 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-4 h-full flex flex-col px-2">
|
||||
<TabsList className="w-full">
|
||||
<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-auto mt-4">
|
||||
<ScrollArea className="flex-1 px-4">
|
||||
<div className="space-y-4">
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id} onClick={() => onCommentSelect?.(comment)}>
|
||||
<MessageCard
|
||||
teamId={teamId}
|
||||
message={comment}
|
||||
getUser={getUser}
|
||||
onReply={setReplyingTo}
|
||||
onViewAttachment={setViewingAttachment}
|
||||
hasReplies={!!comment.replies?.length}
|
||||
/>
|
||||
{comment.replies?.map((reply, index) => (
|
||||
<MessageCard
|
||||
teamId={teamId}
|
||||
isReply={true}
|
||||
key={reply.id}
|
||||
message={reply}
|
||||
getUser={getUser}
|
||||
onReply={setReplyingTo}
|
||||
onViewAttachment={setViewingAttachment}
|
||||
hasReplies={false}
|
||||
isLastReply={index === (comment.replies?.length ?? 0) - 1}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<div ref={ref} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
{(!readOnly || isPublic) && (
|
||||
<div className="mt-4">
|
||||
<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}
|
||||
/>
|
||||
</GuestIdentityPopup>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="fields" className="flex-1 overflow-auto">
|
||||
<div className="mt-4">
|
||||
{sortedFields && sortedFields.length > 0 && (
|
||||
<div className="space-y-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}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import type { AssetInfo } from '@/dtos/asset'
|
||||
import { useScreenSize } from '@/ui/hooks/useScreenSize'
|
||||
import { getBestTranscode } from '@/ui/lib/media'
|
||||
import { Minus, Plus } 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
|
||||
annotations?: Annotation[]
|
||||
}
|
||||
|
||||
export function FileViewer({ file, videoRef, onPlay, onPause, 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 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
|
||||
}
|
||||
}
|
||||
|
||||
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">
|
||||
<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"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{isVideo && (
|
||||
<VideoPlayer
|
||||
data={file}
|
||||
playerRef={videoRef}
|
||||
onPlay={onPlay}
|
||||
onPause={onPause}
|
||||
annotations={displayAnnotations}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
import type { AssetInfoPaginatedList, AssetInfo } from '@/dtos/asset'
|
||||
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,
|
||||
ChevronRight,
|
||||
Clapperboard,
|
||||
Folder,
|
||||
Loader2,
|
||||
Trash2,
|
||||
Plus,
|
||||
MoreHorizontal,
|
||||
Share2,
|
||||
LayoutGrid,
|
||||
} 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 '@/dtos/share'
|
||||
|
||||
interface FolderTreeProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
projectName: string
|
||||
rootFolderId: string
|
||||
dragState?: DragState
|
||||
}
|
||||
|
||||
export function FolderTree({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
rootFolderId,
|
||||
dragState,
|
||||
}: FolderTreeProps) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const isRecentlyDeleted = useMatch({
|
||||
from: '/projects/$projectId/recently-deleted',
|
||||
shouldThrow: false,
|
||||
})
|
||||
|
||||
const { data: shareLinksData } = useQuery({
|
||||
queryKey: ['shares', teamId, projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$get({
|
||||
param: { teamId, 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,
|
||||
})
|
||||
|
||||
const { mutate: createShareLink } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$post({
|
||||
param: { teamId, 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', teamId, 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 overflow-hidden h-full">
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-4">
|
||||
<div>
|
||||
<header className="flex items-center justify-between px-2 mb-1">
|
||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
Assets
|
||||
</h3>
|
||||
<button className="text-muted-foreground hover:text-foreground">
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</header>
|
||||
<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}
|
||||
/>
|
||||
<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>
|
||||
<header className="flex items-center justify-between px-2 mb-1">
|
||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
Collections
|
||||
</h3>
|
||||
<button className="text-muted-foreground hover:text-foreground">
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</header>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<header className="flex items-center justify-between px-2 mb-1">
|
||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
Share Links
|
||||
</h3>
|
||||
<div className="flex items-center gap-1">
|
||||
<button className="text-muted-foreground hover:text-foreground">
|
||||
<MoreHorizontal className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => createShareLink()}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="space-y-0.5">
|
||||
<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>
|
||||
</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
|
||||
}
|
||||
|
||||
function FolderTreeItem({
|
||||
teamId,
|
||||
projectId,
|
||||
folder,
|
||||
level,
|
||||
isRoot,
|
||||
dragState,
|
||||
}: 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',
|
||||
teamId,
|
||||
folder.id,
|
||||
'children',
|
||||
{
|
||||
assetType: 'folder',
|
||||
},
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId: teamId, 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 (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,
|
||||
})
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
id: `tree:${folder.id!}`,
|
||||
data: {
|
||||
type: 'folder',
|
||||
item: folder,
|
||||
},
|
||||
disabled: dragState?.draggedIds.has(folder.id!),
|
||||
})
|
||||
|
||||
const setNodeRef = (node: HTMLDivElement | null) => {
|
||||
setDraggableRef(node)
|
||||
setDroppableRef(node)
|
||||
}
|
||||
|
||||
const isValidDropTarget = useMemo(() => {
|
||||
if (!dragState?.isActive) return false
|
||||
if (dragState.draggedIds.has(folder.id!)) return false
|
||||
return true
|
||||
}, [dragState, folder.id])
|
||||
|
||||
const showDropFeedback = isOver && isValidDropTarget
|
||||
|
||||
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 && '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}
|
||||
/>
|
||||
))}
|
||||
{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 '@/dtos/metadata'
|
||||
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.projects[':projectId'].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.projects[':projectId'].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: { projectId: projectId, 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: { projectId: projectId, 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,108 @@
|
||||
import type { NotificationInfo } from '@/dtos/notification'
|
||||
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-red-500',
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex-1 min-w-0 flex flex-col justify-center pl-2">
|
||||
<div className="text-sm text-slate-800 dark:text-slate-200 break-all leading-snug">
|
||||
{message}
|
||||
</div>
|
||||
<div className="text-[11px] text-slate-500 dark:text-slate-400 mt-1">
|
||||
{formatTimeAgo(createdAt || '')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasPreview && (
|
||||
<div className="w-18 h-18 ml-2 rounded-md overflow-hidden flex-shrink-0 bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 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,150 @@
|
||||
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'
|
||||
|
||||
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],
|
||||
)
|
||||
|
||||
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) {
|
||||
await markReadMutation.mutateAsync({
|
||||
teamId,
|
||||
notificationId: topId,
|
||||
})
|
||||
// Invalidate queries
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['notifications', teamId],
|
||||
})
|
||||
// Refetch to update UI state immediately
|
||||
refetch()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full w-full bg-white dark:bg-slate-900">
|
||||
<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-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-slate-100"
|
||||
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-slate-400" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && notifications.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-40 text-slate-500 dark:text-slate-400">
|
||||
<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-slate-400" />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferResponseType, InferRequestType } from 'hono/client'
|
||||
import type { ProjectInfo } from '@/dtos/project'
|
||||
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 { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2, Upload } 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('')
|
||||
|
||||
// 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)
|
||||
} else {
|
||||
setName('')
|
||||
setCoverImageKey(undefined)
|
||||
setCoverImagePreview(undefined)
|
||||
}
|
||||
}
|
||||
}, [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)
|
||||
navigate({
|
||||
to: '/projects/$projectId',
|
||||
params: { projectId: data.id! },
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const $put = client.api.teams[':teamId'].projects[':projectId'].$put
|
||||
const { mutate: updateProject } = useMutation<
|
||||
InferResponseType<typeof $put>,
|
||||
Error,
|
||||
InferRequestType<typeof $put>['json']
|
||||
>({
|
||||
mutationFn: async (payload) => {
|
||||
const res = await $put({
|
||||
param: { teamId: teamId, 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) => {
|
||||
if (typeof data === 'object' && 'key' in data) {
|
||||
setCoverImageKey(data.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 handleSubmit = () => {
|
||||
if (!name.trim()) return
|
||||
|
||||
if (mode === 'create') {
|
||||
createProject({
|
||||
name: name.trim(),
|
||||
coverImageKey: coverImageKey,
|
||||
})
|
||||
} else if (mode === 'edit' && project?.id) {
|
||||
updateProject({
|
||||
name: name.trim(),
|
||||
coverImageKey: coverImageKey,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{mode === 'create' ? 'Create Project' : 'Project Settings'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{mode === 'create'
|
||||
? 'Configure your new project.'
|
||||
: 'Update your project configuration.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
{/* Cover Image Upload Section */}
|
||||
<div className="flex flex-col items-center justify-center gap-2">
|
||||
<Label>Cover Image</Label>
|
||||
<div
|
||||
className="relative w-full h-40 border-2 border-dashed rounded-lg flex items-center justify-center cursor-pointer overflow-hidden hover:bg-muted/50 transition-colors"
|
||||
onClick={handleImageAreaClick}
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept="image/*"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
{isUploading ? (
|
||||
<div className="absolute inset-0 bg-background/50 flex items-center justify-center z-10">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{coverImagePreview ? (
|
||||
<img
|
||||
src={coverImagePreview}
|
||||
alt="Cover Preview"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-1 text-muted-foreground">
|
||||
<Upload className="w-8 h-8" />
|
||||
<span className="text-sm">Upload Image</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="name" className="text-right">
|
||||
Name
|
||||
</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" onClick={handleSubmit} disabled={!name.trim() || isUploading}>
|
||||
{mode === 'create' ? 'Create' : 'Save'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
'use client'
|
||||
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useState, useMemo, useRef } from 'react'
|
||||
import { BreadcrumbNav } from './breadcrumb-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 '@/dtos/asset'
|
||||
import { FieldInfo } from '@/dtos/metadata'
|
||||
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, setIsRightSidebarCollapsed] = useState(false)
|
||||
const videoRef = useRef<Player | null>(null)
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
|
||||
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: {
|
||||
type: string
|
||||
targetType?: string | null
|
||||
id?: string
|
||||
name?: string
|
||||
}) => {
|
||||
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.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) => {
|
||||
const newAnnotations = comment.annotations as Annotation[]
|
||||
if (newAnnotations && newAnnotations.length > 0) {
|
||||
setAnnotations(newAnnotations)
|
||||
if (videoRef.current) {
|
||||
videoRef.current.pause()
|
||||
}
|
||||
} else {
|
||||
setAnnotations([])
|
||||
}
|
||||
}
|
||||
|
||||
const handlePlay = () => {
|
||||
setAnnotations([])
|
||||
}
|
||||
|
||||
if (shareInfo.isExpired || shareInfo.isDisabled) {
|
||||
return (
|
||||
<div className="flex h-screen 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>
|
||||
)
|
||||
}
|
||||
|
||||
if (!isPasswordValid) {
|
||||
return (
|
||||
<div className="flex h-screen 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>
|
||||
)
|
||||
}
|
||||
|
||||
const currentFolderName =
|
||||
currentFolderId === shareInfo.rootFolderId
|
||||
? shareInfo.name
|
||||
: folders.find((f) => f.id === currentFolderId)?.name || shareInfo.name
|
||||
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background">
|
||||
<BreadcrumbNav
|
||||
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?.type === 'version_stack' ? viewingFileData.fileCount : undefined,
|
||||
}}
|
||||
isRootFolder={currentFolderId === shareInfo.rootFolderId && !viewingFileId}
|
||||
displayStyle="card"
|
||||
onDisplayStyleChange={() => {}}
|
||||
isLeftSidebarCollapsed={true}
|
||||
onLeftSidebarToggle={() => {}}
|
||||
isRightSidebarCollapsed={isRightSidebarCollapsed}
|
||||
onRightSidebarToggle={() => setIsRightSidebarCollapsed(!isRightSidebarCollapsed)}
|
||||
isPublic={true}
|
||||
onFolderClick={handleBreadcrumbClick}
|
||||
/>
|
||||
|
||||
<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}
|
||||
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}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</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,395 @@
|
||||
import type { SearchCondition, SearchConditionOperator } from '@/dtos/search'
|
||||
import { type FieldInfo } from '@/dtos/metadata'
|
||||
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
|
||||
}
|
||||
|
||||
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 }: 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,
|
||||
})),
|
||||
]
|
||||
|
||||
const handleAddCondition = () => {
|
||||
onChange([
|
||||
...conditions,
|
||||
{
|
||||
field: 'name',
|
||||
operator: 'contains',
|
||||
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">
|
||||
<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,120 @@
|
||||
import type { SearchSort } from '@/dtos/search'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
|
||||
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'
|
||||
import { ArrowDownWideNarrow } from 'lucide-react'
|
||||
|
||||
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}
|
||||
>
|
||||
<ArrowDownWideNarrow className="h-4 w-4 mr-1" />
|
||||
{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>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper">
|
||||
{allFields.map((f) => (
|
||||
<SelectItem key={f.id} value={f.id}>
|
||||
{f.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-muted-foreground w-8">from</span>
|
||||
<Select value={isAsc ? 'asc' : 'desc'} onValueChange={handleOrderChange}>
|
||||
<SelectTrigger className="flex-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper">
|
||||
<SelectItem value="asc">{dirOptions.asc}</SelectItem>
|
||||
<SelectItem value="desc">{dirOptions.desc}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
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 '@/dtos/agent'
|
||||
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', 'transcription']),
|
||||
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.teams[':teamId'].providers[':id'].models.$get({
|
||||
param: { teamId, 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.teams[':teamId'].agents[':agentId'].$put({
|
||||
param: { teamId, 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>
|
||||
<SelectItem value="transcription">Transcription</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,371 @@
|
||||
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,
|
||||
Type,
|
||||
Puzzle,
|
||||
} from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { AgentInfo, AgentType } from '@/dtos/agent'
|
||||
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 },
|
||||
{ type: 'transcription', label: 'Transcription', icon: Type },
|
||||
]
|
||||
|
||||
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,
|
||||
transcription: 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.teams[':teamId'].agents[':agentId'].$delete({
|
||||
param: { teamId, 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.teams[':teamId'].agents[':agentId'].$put({
|
||||
param: { teamId: params.teamId, 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-red-600 hover:bg-red-700"
|
||||
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-slate-400" />
|
||||
</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-slate-400" />
|
||||
</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-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-800 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
className="px-6 py-4 flex items-center justify-between cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors"
|
||||
onClick={() => toggleSection(section.type)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="font-semibold text-slate-900 dark:text-white">
|
||||
{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 === 'transcription' ||
|
||||
section.type === 'embedding') &&
|
||||
typeAgents.length > 0
|
||||
) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setCreateType(section.type)
|
||||
setIsCreateDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'w-5 h-5 text-slate-400 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-slate-200 dark:border-slate-800 hover:border-blue-500/50 dark:hover:border-blue-400/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-slate-100 dark:bg-slate-800 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-slate-400" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-bold text-slate-900 dark:text-white block truncate">
|
||||
{agent.name}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 text-xs text-slate-500 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-slate-400 hover:text-slate-600 dark:hover:text-slate-300"
|
||||
>
|
||||
<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-slate-200 dark:border-slate-800 rounded-xl bg-slate-50/50 dark:bg-slate-900/20">
|
||||
<div className="w-10 h-10 rounded-full bg-white dark:bg-slate-800 flex items-center justify-center shadow-sm mb-3">
|
||||
<Icon className="w-5 h-5 text-slate-400" />
|
||||
</div>
|
||||
<p className="text-sm text-slate-500">No {section.label} agents found</p>
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
className="text-blue-600 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,946 @@
|
||||
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 '@/dtos/provider'
|
||||
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.teams[':teamId'].providers[':id'].models.$get({
|
||||
param: { teamId, 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.teams[':teamId'].providers[':id'].$put({
|
||||
param: { teamId, 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.teams[':teamId'].providers[':id'].$delete({
|
||||
param: { teamId, 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-blue-600" />
|
||||
</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-slate-900 dark:text-white flex items-center gap-2">
|
||||
<Cpu className="w-5 h-5 text-blue-600" />
|
||||
Configured AI Providers
|
||||
</h3>
|
||||
<Button
|
||||
onClick={() => setIsCreateDialogOpen(true)}
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white 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-slate-400" />
|
||||
<Input
|
||||
placeholder="Search providers..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-10 bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 focus-visible:ring-2 focus-visible:ring-blue-500 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-blue-300 dark:hover:border-blue-700 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-slate-100 dark:bg-slate-800 rounded-xl group-hover:bg-blue-50 dark:group-hover:bg-blue-900/20 transition-colors">
|
||||
<Globe className="w-6 h-6 text-slate-600 dark:text-slate-400 group-hover:text-blue-600 dark:group-hover:text-blue-400" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-bold text-slate-900 dark:text-white 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-slate-500 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-slate-300 dark:bg-slate-700 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-slate-300 dark:bg-slate-700 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-slate-400 hover:text-slate-600 dark:hover:text-slate-300"
|
||||
>
|
||||
<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-red-500 focus:text-red-500 gap-2 cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" /> Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ChevronRight className="flex-none w-5 h-5 text-slate-300 group-hover:text-blue-500 transition-colors" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{providers?.length === 0 && (
|
||||
<div className="text-center py-12 bg-slate-50 dark:bg-slate-900/50 rounded-2xl border-2 border-dashed border-slate-200 dark:border-slate-800">
|
||||
<Cpu className="w-12 h-12 text-slate-300 mx-auto mb-4" />
|
||||
<h4 className="text-slate-900 dark:text-white font-medium">
|
||||
No Providers Configured
|
||||
</h4>
|
||||
<p className="text-sm text-slate-500 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-slate-300 mx-auto mb-4" />
|
||||
<h4 className="text-slate-900 dark:text-white font-medium">No matches found</h4>
|
||||
<p className="text-sm text-slate-500 mt-1">
|
||||
Try adjusting your search for "{searchQuery}"
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
className="mt-4 text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:hover:bg-blue-900/20"
|
||||
>
|
||||
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-red-600 hover:bg-red-700 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,637 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Code, Github, 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'
|
||||
// @ts-ignore - Import browser distribution to avoid Node.js built-ins in the bundle
|
||||
import JSZip from 'jszip/dist/jszip.min.js'
|
||||
import { SkillInfo } from '@/dtos/skill'
|
||||
|
||||
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.teams[':teamId'].skills[':id'].$delete({
|
||||
param: { teamId, 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 className="border-slate-200 dark:border-slate-800">
|
||||
<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-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 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-blue-500" />
|
||||
</div>
|
||||
) : skills.length === 0 ? (
|
||||
<div className="text-center py-12 border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-xl">
|
||||
<div className="mx-auto w-12 h-12 bg-slate-50 dark:bg-slate-900 rounded-full flex items-center justify-center mb-4 text-slate-400">
|
||||
<Puzzle className="w-6 h-6" />
|
||||
</div>
|
||||
<h3 className="text-lg font-medium text-slate-900 dark:text-white">
|
||||
No skills installed
|
||||
</h3>
|
||||
<p className="text-slate-500 dark:text-slate-400 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-red-600 hover:bg-red-700 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-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 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-slate-900 dark:text-white 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-slate-500 dark:text-slate-400 line-clamp-2">
|
||||
{skill.description || 'No description provided.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-between text-[10px] text-slate-400 dark:text-slate-500 uppercase tracking-wider font-semibold">
|
||||
<span>Updated {new Date(skill.updatedAt).toLocaleDateString()}</span>
|
||||
<div className="px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400">
|
||||
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
|
||||
}
|
||||
|
||||
setIsProcessing(true)
|
||||
|
||||
try {
|
||||
let fileToUpload: File | Blob
|
||||
let fileName: string
|
||||
let contentType = 'application/zip'
|
||||
|
||||
// Check if it's a ZIP file or a collection of files (folder)
|
||||
const isZip = files.length === 1 && files[0].name.toLowerCase().endsWith('.zip')
|
||||
|
||||
if (isZip) {
|
||||
fileToUpload = files[0]
|
||||
fileName = files[0].name
|
||||
contentType = files[0].type || 'application/zip'
|
||||
} else {
|
||||
const zip = new JSZip()
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const f = files[i]
|
||||
// Use relative path for folder structure if available
|
||||
const path = f.webkitRelativePath || f.name
|
||||
zip.file(path, f)
|
||||
}
|
||||
fileToUpload = await zip.generateAsync({ type: 'blob' })
|
||||
fileName = 'skill_package.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/folder or a GitHub repository.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 pt-4">
|
||||
{/* File/Folder 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"
|
||||
// @ts-ignore
|
||||
webkitdirectory=""
|
||||
directory=""
|
||||
multiple
|
||||
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 or folder
|
||||
</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.teams[':teamId'].skills[':id'].config.$patch({
|
||||
param: { teamId, 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 '@/dtos/ai'
|
||||
|
||||
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 '@/dtos/agent'
|
||||
|
||||
export type ProviderSettings = AiProviderSettings
|
||||
export type Agent = AgentInfo
|
||||
@@ -0,0 +1,307 @@
|
||||
import type { AncestorFolder, AssetInfo, AssetInfoPaginatedList } from '@/dtos/asset'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { BreadcrumbNav } from './breadcrumb-nav'
|
||||
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 type { ShareLinkInfo } from '@/dtos/share'
|
||||
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.teams[':teamId'].shares[':shareId'].$get({
|
||||
param: { teamId, 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 && !currentFolderId) {
|
||||
setCurrentFolderId(shareRootId)
|
||||
}
|
||||
}, [shareRootId, currentFolderId])
|
||||
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
|
||||
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
|
||||
|
||||
const {
|
||||
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
fileListRightSidebarCollapsed: isRightSidebarCollapsed,
|
||||
setFileListRightSidebarCollapsed: setIsRightSidebarCollapsed,
|
||||
viewModes,
|
||||
setViewMode,
|
||||
} = useUiStore()
|
||||
|
||||
const displayStyle = viewModes[projectId] ?? 'card'
|
||||
const setDisplayStyle = (style: 'card' | 'list') => {
|
||||
setViewMode(projectId, style)
|
||||
}
|
||||
|
||||
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.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId, 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.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId, 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 = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
|
||||
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.teams[':teamId'].shares[':shareId'].assets[':assetId'].$delete
|
||||
const { mutate: removeFromShare } = useMutation({
|
||||
mutationFn: async (assetId: string) => {
|
||||
const res = await $removeFromShare({
|
||||
param: { teamId, 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())
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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">
|
||||
<BreadcrumbNav
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
ancestorFolders={ancestorFolders}
|
||||
currentAsset={{
|
||||
name:
|
||||
currentFolderId === shareRootId
|
||||
? shareLink.name
|
||||
: folders.find((f) => f.id === currentFolderId)?.name || shareLink.name,
|
||||
type: 'folder',
|
||||
}}
|
||||
isRootFolder={currentFolderId === shareRootId}
|
||||
displayStyle={displayStyle}
|
||||
onDisplayStyleChange={setDisplayStyle}
|
||||
isLeftSidebarCollapsed={isLeftSidebarCollapsed}
|
||||
onLeftSidebarToggle={() => setIsLeftSidebarCollapsed(!isLeftSidebarCollapsed)}
|
||||
isRightSidebarCollapsed={isRightSidebarCollapsed}
|
||||
onRightSidebarToggle={() => setIsRightSidebarCollapsed(!isRightSidebarCollapsed)}
|
||||
onFolderClick={handleBreadcrumbClick}
|
||||
/>
|
||||
|
||||
<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 teamId={teamId} 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,243 @@
|
||||
import { ShareLinkInfo, UpdateShareLinkRequest } from '@/dtos/share'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
|
||||
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 {
|
||||
teamId: string
|
||||
shareLink: ShareLinkInfo
|
||||
}
|
||||
|
||||
export function ShareSettingsSidebar({ teamId, 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.teams[':teamId'].shares[':shareId'].$put
|
||||
const { mutate: updateShare } = useMutation({
|
||||
mutationFn: async (json: UpdateShareLinkRequest) => {
|
||||
const res = await $updateShare({
|
||||
param: { teamId, shareId: shareLink.id },
|
||||
json,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', teamId, 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 '@/dtos/asset'
|
||||
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'
|
||||
@@ -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 → Z</>
|
||||
) : (
|
||||
<>from Z → A</>
|
||||
)
|
||||
) : isAsc ? (
|
||||
<>Oldest → Newest</>
|
||||
) : (
|
||||
<>Newest → 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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
import { buttonVariants } 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(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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 p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-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", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Action
|
||||
className={cn(buttonVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
className={cn(buttonVariants({ variant: "outline" }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||
|
||||
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(
|
||||
"bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="avatar-badge"
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground ring-background absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full ring-2 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(
|
||||
"*:data-[slot=avatar]:ring-background group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarGroupCount({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="avatar-group-count"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 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,
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1,64 @@
|
||||
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 };
|
||||
@@ -0,0 +1,211 @@
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import { DayButton, DayPicker, getDefaultClassNames } 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(
|
||||
"bg-background group/calendar p-3 [--cell-size:2rem] [[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 }),
|
||||
"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"h-[--cell-size] w-[--cell-size] select-none p-0 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(
|
||||
"has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"bg-popover absolute inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md pl-2 pr-1 text-sm [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal",
|
||||
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-muted-foreground select-none text-[0.8rem]",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"group/day relative aspect-square h-full w-full select-none p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"bg-accent rounded-l-md",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("bg-accent rounded-r-md", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"bg-accent text-accent-foreground rounded-md 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(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 flex aspect-square h-auto w-full min-w-[--cell-size] flex-col gap-1 font-normal leading-none data-[range-end=true]:rounded-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
@@ -0,0 +1,92 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Checkbox };
|
||||
@@ -0,0 +1,200 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
|
||||
import { Check, ChevronRight, Circle } from "lucide-react";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
const ContextMenu = ContextMenuPrimitive.Root;
|
||||
|
||||
const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
|
||||
|
||||
const ContextMenuGroup = ContextMenuPrimitive.Group;
|
||||
|
||||
const ContextMenuPortal = ContextMenuPrimitive.Portal;
|
||||
|
||||
const ContextMenuSub = ContextMenuPrimitive.Sub;
|
||||
|
||||
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;
|
||||
|
||||
const ContextMenuSubTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean;
|
||||
}
|
||||
>(({ className, inset, children, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
|
||||
inset && "pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRight className="ml-auto h-4 w-4" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
));
|
||||
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
|
||||
|
||||
const ContextMenuSubContent = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
|
||||
|
||||
const ContextMenuContent = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
));
|
||||
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
|
||||
|
||||
const ContextMenuItem = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
inset && "pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
|
||||
|
||||
const ContextMenuCheckboxItem = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
|
||||
>(({ className, children, checked, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
));
|
||||
ContextMenuCheckboxItem.displayName =
|
||||
ContextMenuPrimitive.CheckboxItem.displayName;
|
||||
|
||||
const ContextMenuRadioItem = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<Circle className="h-2 w-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
));
|
||||
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
|
||||
|
||||
const ContextMenuLabel = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean;
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-semibold text-foreground",
|
||||
inset && "pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
|
||||
|
||||
const ContextMenuSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
|
||||
|
||||
const ContextMenuShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
ContextMenuShortcut.displayName = "ContextMenuShortcut";
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
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)} />
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
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,257 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
|
||||
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(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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 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 p-1 shadow-md",
|
||||
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(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none 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(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none 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("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
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(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
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(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
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 };
|
||||
@@ -0,0 +1,242 @@
|
||||
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 data-[invalid=true]:text-destructive flex w-full gap-3",
|
||||
{
|
||||
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]]:[&>[role=checkbox],[role=radio]]:mt-px has-[>[data-slot=field-content]]:items-start",
|
||||
],
|
||||
responsive: [
|
||||
"@md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto flex-col [&>*]:w-full [&>.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]:bg-primary/5 has-data-[state=checked]:border-primary 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 font-medium leading-snug 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-muted-foreground text-sm font-normal leading-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
|
||||
"nth-last-2:-mt-1 last:mt-0 [[data-variant=legend]+&]:-mt-1.5",
|
||||
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||
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="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
|
||||
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) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (errors?.length === 1 && errors[0]?.message) {
|
||||
return errors[0].message
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||
{errors.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-destructive text-sm font-normal", className)}
|
||||
{...props}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLegend,
|
||||
FieldSeparator,
|
||||
FieldSet,
|
||||
FieldContent,
|
||||
FieldTitle,
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import type * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
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>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } =
|
||||
useFormField();
|
||||
|
||||
return (
|
||||
<Slot
|
||||
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-muted-foreground text-sm", 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-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
};
|
||||
@@ -0,0 +1,160 @@
|
||||
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={24}
|
||||
height={24}
|
||||
viewBox="0 -960 960 960"
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
clipRule="evenodd"
|
||||
d="M160-200v-80h80v-280q0-83 50-147.5T420-792v-28q0-25 17.5-42.5T480-880q25 0 42.5 17.5T540-820v28q80 20 130 84.5T720-560v280h80v80H160ZM480-80q-33 0-56.5-23.5T400-160h160q0 33-23.5 56.5T480-80Z"
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
"use client"
|
||||
|
||||
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 border-input dark:bg-input/30 shadow-xs relative flex w-full items-center rounded-md border outline-none transition-[color,box-shadow]",
|
||||
"h-9 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]:ring-ring has-[[data-slot=input-group-control]:focus-visible]:ring-1",
|
||||
|
||||
// Error state.
|
||||
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
|
||||
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const inputGroupAddonVariants = cva(
|
||||
"text-muted-foreground flex h-auto cursor-text select-none items-center justify-center gap-2 py-1.5 text-sm font-medium 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.4rem] has-[>kbd]:mr-[-0.35rem]",
|
||||
"block-start":
|
||||
"[.border-b]:pb-3 order-first w-full justify-start px-3 pt-3 group-has-[>input]/input-group:pt-2.5",
|
||||
"block-end":
|
||||
"[.border-t]:pt-3 order-last w-full justify-start px-3 pb-3 group-has-[>input]/input-group:pb-2.5",
|
||||
},
|
||||
},
|
||||
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(
|
||||
"text-muted-foreground flex items-center gap-2 text-sm [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",
|
||||
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,25 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
ref={ref}
|
||||
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}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
Input.displayName = "Input";
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { Label as LabelPrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
|
||||
@@ -0,0 +1,49 @@
|
||||
import React from "react";
|
||||
|
||||
interface ProgressCircleProps {
|
||||
progress: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const ProgressCircle: React.FC<ProgressCircleProps> = ({
|
||||
progress,
|
||||
className,
|
||||
}) => {
|
||||
const radius = 20;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const offset = circumference - (progress / 100) * circumference;
|
||||
|
||||
return (
|
||||
<svg width="50" height="50" viewBox="0 0 50 50" className={className}>
|
||||
<circle
|
||||
cx="25"
|
||||
cy="25"
|
||||
r={radius}
|
||||
className="stroke-current text-gray-200"
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
/>
|
||||
<circle
|
||||
cx="25"
|
||||
cy="25"
|
||||
r={radius}
|
||||
className="stroke-current text-blue-600"
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={offset}
|
||||
style={{ transition: "stroke-dashoffset 0.3s" }}
|
||||
transform="rotate(-90 25 25)"
|
||||
/>
|
||||
<text
|
||||
x="50%"
|
||||
y="50%"
|
||||
textAnchor="middle"
|
||||
dy=".3em"
|
||||
className="text-xs font-semibold text-gray-700"
|
||||
>
|
||||
{`${Math.round(progress)}%`}
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
const ScrollArea = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
));
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
|
||||
|
||||
const ScrollBar = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
>(({ className, orientation = "vertical", ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none select-none transition-colors",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
));
|
||||
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -0,0 +1,190 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
import { Select as SelectPrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-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-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "item-aligned",
|
||||
align = "center",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover 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",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-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 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 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
data-slot="select-item-indicator"
|
||||
className="absolute right-2 flex size-3.5 items-center justify-center"
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Skeleton };
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SliderPrimitive from "@radix-ui/react-slider";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Slider({
|
||||
className,
|
||||
defaultValue,
|
||||
value,
|
||||
min = 0,
|
||||
max = 100,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
|
||||
const _values = React.useMemo(
|
||||
() =>
|
||||
Array.isArray(value)
|
||||
? value
|
||||
: Array.isArray(defaultValue)
|
||||
? defaultValue
|
||||
: [min, max],
|
||||
[value, defaultValue, min, max],
|
||||
);
|
||||
|
||||
return (
|
||||
<SliderPrimitive.Root
|
||||
data-slot="slider"
|
||||
defaultValue={defaultValue}
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
className={cn(
|
||||
"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track
|
||||
data-slot="slider-track"
|
||||
className={cn(
|
||||
"bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",
|
||||
)}
|
||||
>
|
||||
<SliderPrimitive.Range
|
||||
data-slot="slider-range"
|
||||
className={cn(
|
||||
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",
|
||||
)}
|
||||
/>
|
||||
</SliderPrimitive.Track>
|
||||
{Array.from({ length: _values.length }, (_, index) => (
|
||||
<SliderPrimitive.Thumb
|
||||
data-slot="slider-thumb"
|
||||
key={index}
|
||||
className="border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
|
||||
/>
|
||||
))}
|
||||
</SliderPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Slider };
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import { useTheme } from "next-themes";
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner";
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme();
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { Toaster };
|
||||
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { Switch as SwitchPrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"peer group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground",
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Switch };
|
||||
@@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("text-muted-foreground mt-4 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
const Tabs = TabsPrimitive.Root;
|
||||
|
||||
const TabsList = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsList.displayName = TabsPrimitive.List.displayName;
|
||||
|
||||
const TabsTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
|
||||
|
||||
const TabsContent = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName;
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground 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 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Textarea };
|
||||
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { Toggle as TogglePrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "@/ui/lib/utils";
|
||||
|
||||
const toggleVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground 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 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline:
|
||||
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 min-w-9 px-2",
|
||||
sm: "h-8 min-w-8 px-1.5",
|
||||
lg: "h-10 min-w-10 px-2.5",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TogglePrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive.Root
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants };
|
||||
@@ -0,0 +1,131 @@
|
||||
import React, { useId } from "react";
|
||||
|
||||
interface UploadCloudIconProps extends React.SVGProps<SVGSVGElement> {
|
||||
uploading?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const CLOUD_PATH =
|
||||
"M17.5 19C19.9853 19 22 16.9853 22 14.5C22 12.132 20.177 10.244 17.819 10.035C17.65 6.94 15.11 4.5 12 4.5C9.22 4.5 6.91 6.47 6.32 9.1C3.89 9.5 2 11.5 2 14C2 16.76 4.24 19 7 19H17.5Z";
|
||||
const ARROW_PATH = "M12 6.5L16 10.5L14.6 11.9L12 9.3L9.4 11.9L8 10.5L12 6.5Z";
|
||||
|
||||
export function UploadCloudIcon({
|
||||
uploading = false,
|
||||
className = "",
|
||||
...props
|
||||
}: UploadCloudIconProps) {
|
||||
const id = useId();
|
||||
const safeId = id.replace(/:/g, "");
|
||||
const clipId = `cloud-clip-${safeId}`;
|
||||
const maskId = `cloud-mask-${safeId}`;
|
||||
const launchAnimId = `launch-${safeId}`;
|
||||
const spinAnimId = `spin-${safeId}`;
|
||||
|
||||
return (
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className={className}
|
||||
style={{ overflow: "visible" }}
|
||||
{...props}
|
||||
>
|
||||
<style>
|
||||
{`
|
||||
@keyframes ${launchAnimId} {
|
||||
0% { transform: translateY(3px); opacity: 0; }
|
||||
20% { opacity: 1; }
|
||||
80% { opacity: 1; }
|
||||
100% { transform: translateY(-6px); opacity: 0; }
|
||||
}
|
||||
@keyframes ${spinAnimId} {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
|
||||
<defs>
|
||||
{/*
|
||||
Scaled clip path for uploading state.
|
||||
Scaling down the cloud path creates the requested "padding"
|
||||
between the cloud border and the animating arrow.
|
||||
*/}
|
||||
<clipPath id={clipId}>
|
||||
<path
|
||||
d={CLOUD_PATH}
|
||||
transform="translate(12, 12) scale(0.75) translate(-12, -12)"
|
||||
/>
|
||||
</clipPath>
|
||||
|
||||
{/*
|
||||
Mask for static state.
|
||||
This creates a transparent "cutout" of the arrow in the center of the cloud.
|
||||
*/}
|
||||
<mask id={maskId}>
|
||||
<rect width="24" height="24" fill="white" />
|
||||
{/* Translated down by 2.5px to visually center the arrow in the cloud body */}
|
||||
<path d={ARROW_PATH} fill="black" transform="translate(0, 2.5)" />
|
||||
</mask>
|
||||
</defs>
|
||||
|
||||
{/*
|
||||
Cloud Background
|
||||
- Static: Uses mask to show cutout arrow.
|
||||
- Uploading: No mask (solid fill), arrow rendered on top.
|
||||
*/}
|
||||
<path
|
||||
d={CLOUD_PATH}
|
||||
fill="currentColor"
|
||||
mask={!uploading ? `url(#${maskId})` : undefined}
|
||||
style={{ transition: "all 0.2s ease" }}
|
||||
/>
|
||||
|
||||
{/*
|
||||
Animated Arrow
|
||||
Only visible when uploading.
|
||||
It is white (to contrast with the colored cloud) and clipped by the scaled cloud shape.
|
||||
*/}
|
||||
<g
|
||||
clipPath={`url(#${clipId})`}
|
||||
style={{ opacity: uploading ? 1 : 0, transition: "opacity 0.2s" }}
|
||||
>
|
||||
<path
|
||||
d={ARROW_PATH}
|
||||
fill="white"
|
||||
style={
|
||||
uploading
|
||||
? {
|
||||
animation: `${launchAnimId} 0.8s cubic-bezier(0.4, 0, 0.2, 1) infinite`,
|
||||
}
|
||||
: {}
|
||||
}
|
||||
/>
|
||||
</g>
|
||||
|
||||
{/*
|
||||
Spinning Blue Arc
|
||||
r="12.5" places it outside the 24x24 box (diameter 25).
|
||||
overflow: visible on SVG ensures it's seen.
|
||||
*/}
|
||||
<circle
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="12.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeDasharray="9.8 68.7"
|
||||
fill="none"
|
||||
style={{
|
||||
transformOrigin: "center",
|
||||
animation: `${spinAnimId} 1s linear infinite`,
|
||||
opacity: uploading ? 1 : 0,
|
||||
transition: "opacity 0.3s ease-in-out",
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { TaskInfo } from '@/dtos/upload'
|
||||
import { useTeamId } from '@/ui/hooks/use-team-id'
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
|
||||
function UploadTaskItem({ task }: { task: TaskInfo }) {
|
||||
const progress =
|
||||
task.total && task.total > 0 ? `${((task.uploaded ?? 0) / task.total) * 100}%` : '0%'
|
||||
return (
|
||||
<div className="p-2 rounded-md transition-colors hover:bg-slate-100 dark:hover:bg-slate-800">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium truncate">{task.name ?? 'unknown'}</span>
|
||||
<span className="text-xs text-slate-500 dark:text-slate-400">
|
||||
{task.uploaded}/{task.total}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 h-1 w-full bg-slate-200 dark:bg-slate-700 rounded-full">
|
||||
<div className="h-1 bg-blue-600 rounded-full" style={{ width: progress }} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function UploadTasks() {
|
||||
const teamId = useTeamId()
|
||||
const {
|
||||
data: tasksData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isLoading,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['teams', teamId, 'upload', 'tasks'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId'].upload.tasks.$get({
|
||||
param: { teamId: teamId! },
|
||||
query: { after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch upload tasks')
|
||||
return await res.json()
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => {
|
||||
return lastPage.pageInfo?.cursor || undefined
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const { ref, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col space-y-2">
|
||||
{tasks?.map((task) => (
|
||||
<UploadTaskItem key={task.id} task={task} />
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div ref={ref} className="flex items-center justify-center p-2">
|
||||
{isFetchingNextPage && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
'use client'
|
||||
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import type { AssetInfo } from '@/dtos/asset'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import type { DragEndEvent, DragStartEvent } from '@dnd-kit/react'
|
||||
import type { DragState } from './dnd-types'
|
||||
|
||||
interface UseFileSystemDndProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
assetId: string
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
selectedIds: Set<string>
|
||||
onClearSelection: () => void
|
||||
}
|
||||
|
||||
export function useFileSystemDnd({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
folders,
|
||||
files,
|
||||
selectedIds,
|
||||
onClearSelection,
|
||||
}: UseFileSystemDndProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [dragState, setDragState] = useState<DragState | undefined>(undefined)
|
||||
|
||||
const $reparent = client.api.projects[':projectId'].reparent.$post
|
||||
const { mutate: reparentAssets } = useMutation<
|
||||
InferResponseType<typeof $reparent, 204>,
|
||||
Error,
|
||||
InferRequestType<typeof $reparent>
|
||||
>({
|
||||
mutationFn: async (req) => {
|
||||
const res = await $reparent(req)
|
||||
if (!res.ok) throw new Error('Failed to move assets')
|
||||
return null as unknown as InferResponseType<typeof $reparent, 204>
|
||||
},
|
||||
})
|
||||
|
||||
const $reorderFolder = client.api.teams[':teamId'].folders[':folderId'].order.$patch
|
||||
const { mutate: reorderFolder } = useMutation<
|
||||
InferResponseType<typeof $reorderFolder, 200>,
|
||||
Error,
|
||||
InferRequestType<typeof $reorderFolder>
|
||||
>({
|
||||
mutationFn: async (req) => {
|
||||
const res = await $reorderFolder(req)
|
||||
if (!res.ok) throw new Error('Failed to reorder folder')
|
||||
return (await res.json()) as unknown as InferResponseType<typeof $reorderFolder, 200>
|
||||
},
|
||||
})
|
||||
|
||||
const $reorderFile = client.api.teams[':teamId'].files[':fileId'].order.$patch
|
||||
const { mutate: reorderFile } = useMutation<
|
||||
InferResponseType<typeof $reorderFile, 200>,
|
||||
Error,
|
||||
InferRequestType<typeof $reorderFile>
|
||||
>({
|
||||
mutationFn: async (req) => {
|
||||
const res = await $reorderFile(req)
|
||||
if (!res.ok) throw new Error('Failed to reorder file')
|
||||
return (await res.json()) as unknown as InferResponseType<typeof $reorderFile, 200>
|
||||
},
|
||||
})
|
||||
|
||||
const $addAssetToShare = client.api.teams[':teamId'].shares[':shareId'].assets.$post
|
||||
const { mutate: addAssetToShare } = useMutation<
|
||||
{ addedCount: number },
|
||||
Error,
|
||||
InferRequestType<typeof $addAssetToShare>
|
||||
>({
|
||||
mutationFn: async (req) => {
|
||||
const res = await $addAssetToShare(req)
|
||||
if (!res.ok) throw new Error('Failed to add asset to share')
|
||||
return (await res.json()) as { addedCount: number }
|
||||
},
|
||||
})
|
||||
|
||||
const handleDragStart = (event: DragStartEvent) => {
|
||||
const active = event.operation.source
|
||||
if (!active) return
|
||||
|
||||
const activeId = (active.id as string).split(':').pop()!
|
||||
const activeData = active.data as { type: string; item: AssetInfo } | undefined
|
||||
|
||||
if (!activeData) return
|
||||
|
||||
let draggedIds: Set<string>
|
||||
let draggedItems: AssetInfo[]
|
||||
|
||||
// If active item is in selection, we drag the whole selection
|
||||
if (selectedIds.has(activeId)) {
|
||||
draggedIds = new Set(selectedIds)
|
||||
draggedItems = [...folders, ...files].filter((item) => selectedIds.has(item.id!))
|
||||
} else {
|
||||
// Otherwise we drag only the active item
|
||||
draggedIds = new Set([activeId])
|
||||
draggedItems = [activeData.item]
|
||||
}
|
||||
|
||||
const hasFolders = draggedItems.some((item) => item.type === 'folder')
|
||||
|
||||
setDragState({
|
||||
isActive: true,
|
||||
draggedIds,
|
||||
hasFolders,
|
||||
itemCount: draggedIds.size,
|
||||
})
|
||||
}
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { target } = event.operation
|
||||
|
||||
if (target && dragState) {
|
||||
const targetId = (target.id as string).split(':').pop()!
|
||||
const targetData = target.data as { type: string; item: AssetInfo } | undefined
|
||||
|
||||
if (targetData?.type === 'share-link') {
|
||||
const shareId = targetId
|
||||
const assetIds = Array.from(dragState.draggedIds)
|
||||
|
||||
addAssetToShare(
|
||||
{
|
||||
param: { teamId, shareId },
|
||||
json: { assetIds },
|
||||
},
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
if (data.addedCount === 0) {
|
||||
toast.info('Assets already exists in share')
|
||||
} else {
|
||||
toast.success(`Added ${data.addedCount} item(s) to share link`)
|
||||
}
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['shares', teamId, projectId],
|
||||
})
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Failed to add to share: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
setDragState(undefined)
|
||||
return
|
||||
}
|
||||
|
||||
let isValid = false
|
||||
|
||||
if (targetData && !dragState.draggedIds.has(targetId)) {
|
||||
if (targetData.type === 'folder' || targetData.type === 'reorder') {
|
||||
isValid = true
|
||||
} else if (targetData.type === 'file') {
|
||||
// Can only drop single file onto single file
|
||||
if (!dragState.hasFolders && dragState.itemCount === 1) {
|
||||
isValid = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targetData?.type === 'reorder') {
|
||||
const { position, item: targetItem } = targetData as unknown as {
|
||||
position: 'before' | 'after'
|
||||
item: AssetInfo
|
||||
}
|
||||
|
||||
const isFolder = dragState.hasFolders
|
||||
const draggedId = Array.from(dragState.draggedIds)[0]
|
||||
|
||||
if (isFolder) {
|
||||
reorderFolder(
|
||||
{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
param: { teamId: teamId, folderId: draggedId } as any,
|
||||
json:
|
||||
position === 'before'
|
||||
? { beforeIndex: targetItem.sortIndex ?? undefined }
|
||||
: { afterIndex: targetItem.sortIndex ?? undefined },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success('Folder reordered')
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Failed to reorder: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
} else {
|
||||
reorderFile(
|
||||
{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
param: { teamId: teamId, fileId: draggedId } as any,
|
||||
json:
|
||||
position === 'before'
|
||||
? { beforeIndex: targetItem.sortIndex ?? undefined }
|
||||
: { afterIndex: targetItem.sortIndex ?? undefined },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success('File reordered')
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Failed to reorder: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
} else if (isValid) {
|
||||
// Execute API
|
||||
reparentAssets(
|
||||
{
|
||||
param: { projectId: projectId },
|
||||
json: {
|
||||
assetIds: Array.from(dragState.draggedIds),
|
||||
newParentId: targetId,
|
||||
},
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success('Assets moved successfully')
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
})
|
||||
// Clear selection after move
|
||||
onClearSelection()
|
||||
},
|
||||
onError: () => {
|
||||
toast.error('Failed to move assets')
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
setDragState(undefined)
|
||||
}
|
||||
|
||||
return {
|
||||
dragState,
|
||||
handleDragStart,
|
||||
handleDragEnd,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Avatar, AvatarFallback } from '@/ui/components/ui/avatar'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { useTeamId } from '@/ui/hooks/use-team-id'
|
||||
import { useAuthStore } from '@/ui/stores/auth'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useTheme } from './theme-provider'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { signOut } from '@/ui/lib/auth-client'
|
||||
|
||||
export function UserMenu() {
|
||||
const { clearAuth } = useAuthStore()
|
||||
const teamId = useTeamId()
|
||||
|
||||
const { data: me } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId: teamId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
const { setTheme } = useTheme()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleLogout = async () => {
|
||||
await signOut()
|
||||
clearAuth()
|
||||
navigate({ to: '/login' })
|
||||
}
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return 'U'
|
||||
const names = name.split(' ')
|
||||
if (names.length > 1) {
|
||||
return `${names[0][0]}${names[names.length - 1][0]}`.toUpperCase()
|
||||
}
|
||||
return name.substring(0, 2).toUpperCase()
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Avatar>
|
||||
<AvatarFallback className="text-black bg-orange-500/80">
|
||||
{getInitials(me?.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56" align="end" forceMount>
|
||||
{me && (
|
||||
<>
|
||||
<DropdownMenuLabel className="font-normal">
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-sm font-medium leading-none">{me.name}</p>
|
||||
<p className="text-xs leading-none text-muted-foreground">{me.role}</p>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuLabel>Theme</DropdownMenuLabel>
|
||||
<DropdownMenuItem onClick={() => setTheme('light')}>Light</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('dark')}>Dark</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('system')}>System</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/teams/$teamId/settings',
|
||||
params: { teamId: teamId! },
|
||||
})
|
||||
}
|
||||
disabled={!teamId}
|
||||
>
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-red-500 focus:text-red-500" onClick={handleLogout}>
|
||||
Log out
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import type { MediaMetadata } from '@/dtos/asset'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
const formatTime = (seconds: number): string => {
|
||||
if (isNaN(seconds)) return '00:00'
|
||||
const date = new Date(seconds * 1000)
|
||||
const hh = date.getUTCHours()
|
||||
const mm = date.getUTCMinutes()
|
||||
const ss = date.getUTCSeconds().toString().padStart(2, '0')
|
||||
if (hh) {
|
||||
return `${hh}:${mm.toString().padStart(2, '0')}:${ss}`
|
||||
}
|
||||
return `${mm}:${ss}`
|
||||
}
|
||||
|
||||
interface ProgressBarProps {
|
||||
duration: number
|
||||
currentTime: number
|
||||
previewUrl?: string
|
||||
onSeek: (time: number) => void
|
||||
buffered?: number
|
||||
metadata?: MediaMetadata
|
||||
}
|
||||
|
||||
const ProgressBar: React.FC<ProgressBarProps> = ({
|
||||
duration,
|
||||
currentTime,
|
||||
previewUrl,
|
||||
onSeek,
|
||||
buffered = 0,
|
||||
metadata,
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const previewVideoRef = useRef<HTMLVideoElement>(null)
|
||||
const [hoverPosition, setHoverPosition] = useState<number | null>(null) // 0 to 1
|
||||
const [isHovering, setIsHovering] = useState(false)
|
||||
|
||||
// Load the preview video in background
|
||||
useEffect(() => {
|
||||
if (previewVideoRef.current && previewUrl) {
|
||||
previewVideoRef.current.load()
|
||||
}
|
||||
}, [previewUrl])
|
||||
|
||||
const handleMouseMove = useCallback(
|
||||
(e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!containerRef.current) return
|
||||
|
||||
const rect = containerRef.current.getBoundingClientRect()
|
||||
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width))
|
||||
const percentage = x / rect.width
|
||||
|
||||
setHoverPosition(percentage)
|
||||
setIsHovering(true)
|
||||
|
||||
if (previewVideoRef.current && duration) {
|
||||
const seekTime = percentage * duration
|
||||
// Use fastSeek if available for smoother scrubbing, otherwise currentTime
|
||||
const vid = previewVideoRef.current
|
||||
if (Number.isFinite(seekTime)) {
|
||||
vid.currentTime = seekTime
|
||||
}
|
||||
}
|
||||
},
|
||||
[duration],
|
||||
)
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
setIsHovering(false)
|
||||
setHoverPosition(null)
|
||||
}
|
||||
|
||||
const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!containerRef.current || !duration) return
|
||||
const rect = containerRef.current.getBoundingClientRect()
|
||||
const x = e.clientX - rect.left
|
||||
const percentage = x / rect.width
|
||||
onSeek(percentage * duration)
|
||||
}
|
||||
|
||||
const progressPercent = duration > 0 ? (currentTime / duration) * 100 : 0
|
||||
const hoverPercent = hoverPosition !== null ? hoverPosition * 100 : 0
|
||||
|
||||
// Calculate preview tooltip position
|
||||
// Logic: Interpolate translation based on position to keep preview fully visible
|
||||
// 0% -> translateX(0%) (Left aligned)
|
||||
// 50% -> translateX(-50%) (Center aligned)
|
||||
// 100% -> translateX(-100%) (Right aligned)
|
||||
const getTooltipStyle = () => {
|
||||
if (hoverPosition === null) return {}
|
||||
return {
|
||||
left: `${hoverPercent}%`,
|
||||
transform: `translateX(-${hoverPercent}%)`,
|
||||
}
|
||||
}
|
||||
|
||||
// Dynamic Size Calculation
|
||||
const MAX_PREVIEW_SIZE = 180
|
||||
let previewDimensions: React.CSSProperties = {
|
||||
width: `${MAX_PREVIEW_SIZE}px`,
|
||||
height: 'auto',
|
||||
}
|
||||
|
||||
if (metadata && metadata.originalWidth && metadata.originalHeight) {
|
||||
const { originalWidth, originalHeight } = metadata
|
||||
|
||||
if (originalWidth >= originalHeight) {
|
||||
// Landscape or Square: Constrain width
|
||||
const height = (MAX_PREVIEW_SIZE * originalHeight) / originalWidth
|
||||
previewDimensions = {
|
||||
width: `${MAX_PREVIEW_SIZE}px`,
|
||||
height: `${height}px`,
|
||||
}
|
||||
} else {
|
||||
// Portrait: Constrain height
|
||||
const width = (MAX_PREVIEW_SIZE * originalWidth) / originalHeight
|
||||
previewDimensions = {
|
||||
width: `${width}px`,
|
||||
height: `${MAX_PREVIEW_SIZE}px`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="group relative h-1.5 w-full cursor-pointer touch-none rounded-full bg-gray-300 transition-colors duration-200 dark:bg-white/20"
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{/* Hidden Preview Video Element */}
|
||||
<video
|
||||
ref={previewVideoRef}
|
||||
src={previewUrl}
|
||||
className="hidden"
|
||||
preload="auto"
|
||||
muted
|
||||
playsInline
|
||||
/>
|
||||
|
||||
{/* Hover Preview Tooltip */}
|
||||
{isHovering && duration > 0 && (
|
||||
<div
|
||||
className="pointer-events-none absolute bottom-full z-50 mb-3 flex w-max flex-col"
|
||||
style={getTooltipStyle()}
|
||||
>
|
||||
<div className="relative overflow-hidden rounded-lg border-2 border-gray-300 bg-white shadow-2xl dark:border-white/50 dark:bg-black">
|
||||
<video
|
||||
src={previewUrl}
|
||||
className="bg-black object-cover"
|
||||
style={previewDimensions}
|
||||
muted
|
||||
ref={(el) => {
|
||||
if (el && previewVideoRef.current) {
|
||||
el.currentTime = previewVideoRef.current.currentTime
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="absolute bottom-0 w-full bg-white/80 py-0.5 text-center text-xs font-medium text-gray-900 dark:bg-black/60 dark:text-white">
|
||||
{formatTime(hoverPosition! * duration)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Buffered Bar */}
|
||||
<div
|
||||
className="absolute top-0 left-0 h-full rounded-full bg-gray-400 transition-all duration-200 dark:bg-white/30"
|
||||
style={{ width: `${buffered}%` }}
|
||||
/>
|
||||
|
||||
{/* Hover Highlight Bar */}
|
||||
{isHovering && (
|
||||
<div
|
||||
className="absolute top-0 left-0 h-full rounded-full bg-gray-500/40 dark:bg-white/40"
|
||||
style={{ width: `${hoverPercent}%` }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Play Progress Bar */}
|
||||
<div
|
||||
className="relative absolute top-0 left-0 h-full rounded-full bg-blue-600 dark:bg-blue-500"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
>
|
||||
{/* Thumb (Playhead) - visible on group hover or active */}
|
||||
<div className="absolute top-1/2 right-0 h-3.5 w-3.5 -translate-y-1/2 translate-x-1/2 scale-0 rounded-full border border-gray-200 bg-white shadow-md transition-transform duration-100 group-hover:scale-100 dark:border-none" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ProgressBar
|
||||
@@ -0,0 +1,16 @@
|
||||
export const formatTime = (seconds: number): string => {
|
||||
if (isNaN(seconds)) return '00:00'
|
||||
const date = new Date(seconds * 1000)
|
||||
const hh = date.getUTCHours()
|
||||
const mm = date.getUTCMinutes()
|
||||
const ss = date.getUTCSeconds().toString().padStart(2, '0')
|
||||
if (hh) {
|
||||
return `${hh}:${mm.toString().padStart(2, '0')}:${ss}`
|
||||
}
|
||||
return `${mm}:${ss}`
|
||||
}
|
||||
|
||||
export const formatFrame = (seconds: number, fps: number): number => {
|
||||
if (isNaN(seconds) || !fps) return 0
|
||||
return Math.floor(seconds * fps)
|
||||
}
|
||||
@@ -0,0 +1,805 @@
|
||||
import type { AssetInfo, VideoTranscode } from '@/dtos/asset'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import {
|
||||
Download,
|
||||
Maximize,
|
||||
Minimize,
|
||||
Minus,
|
||||
Pause,
|
||||
Play,
|
||||
Plus,
|
||||
Repeat,
|
||||
Settings,
|
||||
Volume2,
|
||||
VolumeX,
|
||||
} from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import videojs from 'video.js'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from '../ui/dropdown-menu'
|
||||
import { Slider } from '../ui/slider'
|
||||
import ProgressBar from './progress-bar'
|
||||
import { formatFrame, formatTime } from './utils'
|
||||
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import DrawingCanvas from '../drawing-canvas'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
|
||||
export interface PlayerState {
|
||||
isPlaying: boolean
|
||||
progress: number // 0 to 100
|
||||
currentTime: number
|
||||
duration: number
|
||||
volume: number
|
||||
isMuted: boolean
|
||||
isLooping: boolean
|
||||
playbackRate: number
|
||||
isFullScreen: boolean
|
||||
showFrames: boolean // Toggle between time (02:30) and frames (1234)
|
||||
currentResolution: string // 'Original' or '720p', '480p' etc.
|
||||
currentSrc?: string
|
||||
}
|
||||
|
||||
interface VideoPlayerProps {
|
||||
data: AssetInfo
|
||||
playerRef?: React.RefObject<Player | null>
|
||||
onPlay?: () => void
|
||||
onPause?: () => void
|
||||
annotations?: Annotation[]
|
||||
}
|
||||
|
||||
type DisplayTranscode = VideoTranscode & { resolution: string }
|
||||
|
||||
interface ControlBarProps {
|
||||
state: PlayerState
|
||||
zoom: number
|
||||
isControlsVisible: boolean
|
||||
buffered: number
|
||||
data: AssetInfo
|
||||
resolutions: DisplayTranscode[]
|
||||
togglePlay: () => void
|
||||
toggleLoop: () => void
|
||||
handleSeek: (time: number) => void
|
||||
toggleMute: () => void
|
||||
handleVolumeChange: (newVolume: number) => void
|
||||
setState: React.Dispatch<React.SetStateAction<PlayerState>>
|
||||
changePlaybackRate: (rate: number) => void
|
||||
changeResolution: (res: DisplayTranscode) => void
|
||||
handleDownload: (url: string, resolution: string) => void
|
||||
toggleFullScreen: () => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
}
|
||||
|
||||
const ControlBar: React.FC<ControlBarProps> = ({
|
||||
state,
|
||||
zoom,
|
||||
isControlsVisible,
|
||||
buffered,
|
||||
data,
|
||||
resolutions,
|
||||
togglePlay,
|
||||
toggleLoop,
|
||||
handleSeek,
|
||||
toggleMute,
|
||||
handleVolumeChange,
|
||||
setState,
|
||||
changePlaybackRate,
|
||||
changeResolution,
|
||||
handleDownload,
|
||||
toggleFullScreen,
|
||||
onZoomChange,
|
||||
}) => {
|
||||
if (!data.media?.metadata) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'transition-all duration-300 ease-in-out z-20',
|
||||
state.isFullScreen
|
||||
? 'absolute bottom-0 left-0 right-0 px-4 py-4 bg-black/60 backdrop-blur-md text-white'
|
||||
: 'relative w-full bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-4 py-3 z-10 transition-colors duration-200',
|
||||
isControlsVisible
|
||||
? 'opacity-100 translate-y-0'
|
||||
: 'opacity-0 translate-y-4 pointer-events-none',
|
||||
)}
|
||||
>
|
||||
{/* Progress Bar */}
|
||||
<div className="mb-4 px-1">
|
||||
<ProgressBar
|
||||
duration={state.duration}
|
||||
currentTime={state.currentTime}
|
||||
buffered={buffered}
|
||||
previewUrl={data.media.videoPreview?.url}
|
||||
onSeek={handleSeek}
|
||||
metadata={{
|
||||
...data.media.metadata,
|
||||
frameRate: data.media.metadata.frameRate || 30,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Lower Controls Row */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-between',
|
||||
state.isFullScreen ? 'text-white/90' : 'text-gray-700 dark:text-white/90',
|
||||
)}
|
||||
>
|
||||
{/* Left Side: Play, Vol, Time */}
|
||||
<div className="flex items-center gap-4">
|
||||
<button onClick={togglePlay} className="hover:text-blue-500 transition-colors">
|
||||
{state.isPlaying ? (
|
||||
<Pause className="w-6 h-6 fill-current" />
|
||||
) : (
|
||||
<Play className="w-6 h-6 fill-current" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={toggleLoop}
|
||||
className={cn('transition-colors', state.isLooping ? 'text-blue-500' : 'text-gray-400')}
|
||||
title="Loop"
|
||||
>
|
||||
<Repeat className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-3 group/vol">
|
||||
<button onClick={toggleMute} className="hover:text-blue-500">
|
||||
{state.isMuted || state.volume === 0 ? (
|
||||
<VolumeX className="w-6 h-6" />
|
||||
) : (
|
||||
<Volume2 className="w-6 h-6" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="w-0 overflow-hidden group-hover/vol:w-24 transition-all duration-300 ease-in-out">
|
||||
<div className="w-24 px-1">
|
||||
<Slider
|
||||
value={state.isMuted ? [0] : [state.volume]}
|
||||
onValueChange={(v) => handleVolumeChange(v[0])}
|
||||
max={1}
|
||||
step={0.05}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="min-w-[100px] cursor-pointer text-sm font-medium tabular-nums hover:text-blue-500"
|
||||
onClick={() => setState((p) => ({ ...p, showFrames: !p.showFrames }))}
|
||||
title="Click to toggle Time/Frames"
|
||||
>
|
||||
{state.showFrames
|
||||
? `${formatFrame(state.currentTime, data.media.metadata.frameRate ?? 30)} / ${formatFrame(state.duration, data.media.metadata.frameRate ?? 30)}`
|
||||
: `${formatTime(state.currentTime)} / ${formatTime(state.duration)}`}
|
||||
<span className="ml-1 text-xs text-gray-400">{state.showFrames ? 'fr' : ''}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
|
||||
<div className="relative flex items-center gap-3">
|
||||
{/* Zoom Controls */}
|
||||
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5">
|
||||
<button
|
||||
onClick={() => onZoomChange(zoom * 0.8)}
|
||||
className="p-1 hover:text-blue-500 rounded"
|
||||
>
|
||||
<Minus size={14} />
|
||||
</button>
|
||||
<span className="text-xs w-8 text-center tabular-nums">{Math.round(zoom * 100)}%</span>
|
||||
<button
|
||||
onClick={() => onZoomChange(zoom * 1.2)}
|
||||
className="p-1 hover:text-blue-500 rounded"
|
||||
>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Playback Rate */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="w-8 text-sm font-bold hover:text-blue-500">
|
||||
{state.playbackRate}x
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
{[0.5, 1, 1.5, 2].map((rate) => (
|
||||
<DropdownMenuItem
|
||||
key={rate}
|
||||
onClick={() => changePlaybackRate(rate)}
|
||||
className={cn(
|
||||
'rounded py-1 px-2 text-left text-xs',
|
||||
state.playbackRate === rate
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800',
|
||||
)}
|
||||
>
|
||||
{rate}x
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Resolution Selector */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex items-center gap-1 rounded border border-gray-300 px-2 py-0.5 text-sm font-semibold hover:bg-gray-200 dark:border-white/20 dark:hover:bg-white/10">
|
||||
<Settings className="h-3.5 w-3.5" />
|
||||
<span>{state.currentResolution}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuLabel>Quality</DropdownMenuLabel>
|
||||
{resolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => changeResolution(res)}
|
||||
className={cn(
|
||||
'flex w-full items-center justify-between',
|
||||
state.currentResolution === res.resolution
|
||||
? 'text-blue-500'
|
||||
: 'text-gray-700 dark:text-gray-300',
|
||||
)}
|
||||
>
|
||||
<span>{res.resolution}</span>
|
||||
<span className="pl-5 text-xs text-gray-400 dark:text-gray-500">
|
||||
{res.width}x{res.height}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Download */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="transition-colors hover:text-blue-500" title="Download">
|
||||
<Download className="h-5 w-5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuLabel>Download</DropdownMenuLabel>
|
||||
{resolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => handleDownload(res.url ?? '', res.resolution)}
|
||||
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
|
||||
>
|
||||
<span>{res.resolution}</span>
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">MP4</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Fullscreen */}
|
||||
<button onClick={toggleFullScreen} className="transition-colors hover:text-blue-500">
|
||||
{state.isFullScreen ? (
|
||||
<Minimize className="h-6 w-6" />
|
||||
) : (
|
||||
<Maximize className="h-6 w-6" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
data,
|
||||
playerRef: passedPlayerRef,
|
||||
onPlay,
|
||||
onPause,
|
||||
annotations,
|
||||
}) => {
|
||||
const localPlayerRef = useRef<Player | null>(null)
|
||||
const playerRef = passedPlayerRef || localPlayerRef
|
||||
// We use a container ref to manually append the video element
|
||||
const videoContainerRef = useRef<HTMLDivElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const controlsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
|
||||
|
||||
// Store
|
||||
const {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
addAnnotation,
|
||||
annotations: draftAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
// Combine annotations
|
||||
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
|
||||
|
||||
// Resize Observer for container
|
||||
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()
|
||||
}, [])
|
||||
|
||||
// Fit to screen initial
|
||||
useEffect(() => {
|
||||
if (containerSize.width > 0 && containerSize.height > 0) {
|
||||
// Only if not already set or reset?
|
||||
// Actually, we want to start fit.
|
||||
const vidW = data.media?.metadata?.originalWidth ?? 1920
|
||||
const vidH = data.media?.metadata?.originalHeight ?? 1080
|
||||
const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH)
|
||||
// Only set if zoom is 1 (initial).
|
||||
if (zoom === 1) {
|
||||
setZoom(scale)
|
||||
}
|
||||
}
|
||||
}, [containerSize.width, containerSize.height, data.media?.metadata])
|
||||
|
||||
if (!data.media?.original?.downloadUrl || !data.media.metadata) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<p className="text-muted-foreground">Media is not available.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Initial resolution setup
|
||||
const originalRes = {
|
||||
url: data.media.original.downloadUrl,
|
||||
width: data.media.metadata.originalWidth ?? 0,
|
||||
height: data.media.metadata.originalHeight ?? 0,
|
||||
resolution: 'Original',
|
||||
} as DisplayTranscode
|
||||
|
||||
const resolutions: DisplayTranscode[] = (data.media.videoTranscodes ?? []).map((t) => ({
|
||||
...t,
|
||||
resolution: t.isRaw ? 'Original' : `${t.height}p`,
|
||||
}))
|
||||
|
||||
// Logic to select best resolution based on screen size
|
||||
const getInitialResolution = (): DisplayTranscode => {
|
||||
if (typeof window === 'undefined') return originalRes
|
||||
|
||||
// Use device pixel ratio for high DPI screens
|
||||
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
|
||||
|
||||
// Strategy: Find smallest resolution that is >= screenWidth.
|
||||
// Filter out raw versions unless they are the only option.
|
||||
|
||||
const nonRaw = resolutions.filter((r) => !r.isRaw)
|
||||
const candidates = nonRaw.length > 0 ? nonRaw : resolutions
|
||||
|
||||
// 1. Sort by width ascending
|
||||
const sortedResolutions = [...candidates].sort((a, b) => {
|
||||
const wA = a.width ?? 0
|
||||
const wB = b.width ?? 0
|
||||
if (wA !== wB) return wA - wB
|
||||
// If equal width, prefer non-raw (optimized)
|
||||
return (a.isRaw ? 1 : 0) - (b.isRaw ? 1 : 0)
|
||||
})
|
||||
|
||||
// 2. Find first one >= screenWidth
|
||||
const bestFit = sortedResolutions.find((r) => (r.width ?? 0) >= screenWidth)
|
||||
|
||||
// 3. If found, return it. If not (all are smaller), return the last one (largest).
|
||||
return bestFit || sortedResolutions[sortedResolutions.length - 1] || originalRes
|
||||
}
|
||||
|
||||
const initialRes = getInitialResolution()
|
||||
|
||||
// State
|
||||
const [state, setState] = useState<PlayerState>({
|
||||
isPlaying: false,
|
||||
progress: 0,
|
||||
currentTime: 0,
|
||||
duration: data.media.metadata.duration || 0,
|
||||
volume: 1,
|
||||
isMuted: false,
|
||||
isLooping: false,
|
||||
playbackRate: 1,
|
||||
isFullScreen: false,
|
||||
showFrames: false,
|
||||
currentResolution: initialRes.resolution,
|
||||
currentSrc: initialRes.url,
|
||||
})
|
||||
|
||||
const [buffered, setBuffered] = useState(0)
|
||||
const [isControlsVisible, setIsControlsVisible] = useState(true)
|
||||
|
||||
// Initialize Video.js
|
||||
useEffect(() => {
|
||||
if (!videoContainerRef.current) return
|
||||
|
||||
// 1. Create the video element manually
|
||||
// This avoids conflicts with React Strict Mode where the DOM might not match React's virtual DOM expectations after Video.js modifies it.
|
||||
const videoElement = document.createElement('video-js')
|
||||
videoElement.classList.add('vjs-big-play-centered', '!h-full', '!w-full')
|
||||
|
||||
// Hide it, but keep it in DOM
|
||||
videoElement.style.opacity = '0'
|
||||
videoElement.style.pointerEvents = 'none'
|
||||
|
||||
// Append to our container
|
||||
videoContainerRef.current.appendChild(videoElement)
|
||||
|
||||
// 2. Initialize the player
|
||||
const player = (playerRef.current = videojs(videoElement, {
|
||||
controls: false,
|
||||
autoplay: false,
|
||||
preload: 'auto',
|
||||
playsinline: true,
|
||||
sources: [
|
||||
{
|
||||
src: state.currentSrc,
|
||||
type: data.media?.mimeType || 'video/mp4',
|
||||
},
|
||||
],
|
||||
}))
|
||||
|
||||
// Extract video element for Konva
|
||||
const htmlVid = videoElement.querySelector('video')
|
||||
if (htmlVid) {
|
||||
setVideoHtmlEl(htmlVid)
|
||||
} else {
|
||||
// Fallback: try player.tech().el()
|
||||
// Wait for ready?
|
||||
player.ready(() => {
|
||||
const techEl = player.tech({ iWillNotUseThisInPlugins: true })?.el() as HTMLVideoElement
|
||||
if (techEl) setVideoHtmlEl(techEl)
|
||||
})
|
||||
}
|
||||
|
||||
player.on('play', () => {
|
||||
setState((p) => ({ ...p, isPlaying: true }))
|
||||
onPlay?.()
|
||||
})
|
||||
player.on('pause', () => {
|
||||
setState((p) => ({ ...p, isPlaying: false }))
|
||||
onPause?.()
|
||||
})
|
||||
player.on('ended', () => setState((p) => ({ ...p, isPlaying: false })))
|
||||
|
||||
player.on('timeupdate', () => {
|
||||
const current = player.currentTime() || 0
|
||||
const duration = player.duration() || data.media?.metadata?.duration || 0
|
||||
|
||||
const bufferedEnd = player.bufferedEnd()
|
||||
if (duration > 0) {
|
||||
setBuffered((bufferedEnd / duration) * 100)
|
||||
}
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentTime: current,
|
||||
duration: duration || prev.duration,
|
||||
progress: duration > 0 ? (current / duration) * 100 : 0,
|
||||
}))
|
||||
})
|
||||
|
||||
player.on('volumechange', () => {
|
||||
const vol = player.volume()
|
||||
const muted = player.muted()
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
volume: vol || 0,
|
||||
isMuted: muted || false,
|
||||
}))
|
||||
})
|
||||
|
||||
player.on('ratechange', () => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
playbackRate: player.playbackRate() || 1,
|
||||
}))
|
||||
})
|
||||
|
||||
player.on('error', () => {
|
||||
console.error('VideoJS Error:', player.error())
|
||||
})
|
||||
|
||||
// Set initial state
|
||||
player.volume(state.volume)
|
||||
|
||||
// 4. Cleanup
|
||||
return () => {
|
||||
if (player && !player.isDisposed()) {
|
||||
player.dispose()
|
||||
playerRef.current = null
|
||||
}
|
||||
}
|
||||
}, [data])
|
||||
|
||||
const handleMouseMove = useCallback(() => {
|
||||
// Always show controls on movement
|
||||
setIsControlsVisible(true)
|
||||
|
||||
if (controlsTimeoutRef.current) {
|
||||
clearTimeout(controlsTimeoutRef.current)
|
||||
}
|
||||
|
||||
// Only set auto-hide timer if we are in fullscreen and playing
|
||||
// If paused, controls should remain visible so user can see what to do
|
||||
if (state.isFullScreen && state.isPlaying) {
|
||||
controlsTimeoutRef.current = setTimeout(() => {
|
||||
setIsControlsVisible(false)
|
||||
}, 2000)
|
||||
}
|
||||
}, [state.isFullScreen, state.isPlaying])
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
// If we leave the player area in fullscreen, hide controls (optional preference, usually good)
|
||||
if (state.isFullScreen && state.isPlaying) {
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
setIsControlsVisible(false)
|
||||
}
|
||||
}, [state.isFullScreen, state.isPlaying])
|
||||
|
||||
// Clean up timeout on unmount or state change
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Ensure controls are visible when pausing or entering fullscreen initially
|
||||
useEffect(() => {
|
||||
if (!state.isPlaying) {
|
||||
setIsControlsVisible(true)
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
} else {
|
||||
// If we just started playing (or re-entered playing state), trigger the timer logic
|
||||
handleMouseMove()
|
||||
}
|
||||
}, [state.isPlaying, state.isFullScreen, handleMouseMove])
|
||||
|
||||
// -- Event Handlers --
|
||||
|
||||
const togglePlay = useCallback(() => {
|
||||
// Disable click-to-play if drawing
|
||||
if (useAnnotationStore.getState().isDrawing) return
|
||||
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
if (player.paused() || player.ended()) {
|
||||
const playPromise = player.play()
|
||||
if (playPromise !== undefined) {
|
||||
playPromise.catch((error) => {
|
||||
// Ignore AbortError which happens when pausing rapidly after playing
|
||||
if (error.name === 'AbortError') return
|
||||
console.error('Play failed:', error)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
player.pause()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const toggleLoop = () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
const newLoop = !state.isLooping
|
||||
player.loop(newLoop)
|
||||
setState((prev) => ({ ...prev, isLooping: newLoop }))
|
||||
}
|
||||
|
||||
const handleSeek = (time: number) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
player.currentTime(time)
|
||||
setState((prev) => ({ ...prev, currentTime: time }))
|
||||
}
|
||||
|
||||
const handleVolumeChange = (newVolume: number) => {
|
||||
// Optimistic update to prevent slider jumping and ensure immediate UI feedback
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
volume: newVolume,
|
||||
isMuted: newVolume === 0, // If dragging to 0, consider it muted
|
||||
}))
|
||||
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
// Set volume first so if we unmute, it is at the correct level
|
||||
player.volume(newVolume)
|
||||
|
||||
// Manage mute state based on volume
|
||||
if (newVolume > 0 && player.muted()) {
|
||||
player.muted(false)
|
||||
} else if (newVolume === 0 && !player.muted()) {
|
||||
player.muted(true)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleMute = () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
const isMuted = player.muted()
|
||||
if (isMuted) {
|
||||
player.muted(false)
|
||||
// If volume was 0 (e.g. user dragged to 0), restore to default 0.5 so they hear something
|
||||
if (player.volume() === 0) {
|
||||
player.volume(0.5)
|
||||
}
|
||||
} else {
|
||||
player.muted(true)
|
||||
}
|
||||
}
|
||||
|
||||
const changePlaybackRate = (rate: number) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
player.playbackRate(rate)
|
||||
}
|
||||
|
||||
const changeResolution = (res: DisplayTranscode) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
const wasPlaying = !player.paused()
|
||||
const currentTime = player.currentTime()
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentResolution: res.resolution,
|
||||
currentSrc: res.url,
|
||||
}))
|
||||
|
||||
player.src({ type: data.media?.mimeType || 'video/mp4', src: res.url })
|
||||
|
||||
player.one('loadedmetadata', () => {
|
||||
player.currentTime(currentTime)
|
||||
if (wasPlaying) {
|
||||
const playPromise = player.play()
|
||||
if (playPromise !== undefined) {
|
||||
playPromise.catch((error) => {
|
||||
if (error.name === 'AbortError') return
|
||||
console.error('Play after seek failed:', error)
|
||||
})
|
||||
}
|
||||
}
|
||||
player.playbackRate(state.playbackRate)
|
||||
})
|
||||
}
|
||||
|
||||
const toggleFullScreen = () => {
|
||||
if (!containerRef.current) return
|
||||
if (!document.fullscreenElement) {
|
||||
containerRef.current.requestFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: true }))
|
||||
} else {
|
||||
document.exitFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: false }))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = (url: string, resolution: string) => {
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = `${data.name}-${resolution}.mp4`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
}
|
||||
|
||||
// Listen for fullscreen change events (ESC key)
|
||||
useEffect(() => {
|
||||
const onFsChange = () => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
isFullScreen: !!document.fullscreenElement,
|
||||
}))
|
||||
}
|
||||
document.addEventListener('fullscreenchange', onFsChange)
|
||||
return () => document.removeEventListener('fullscreenchange', onFsChange)
|
||||
}, [])
|
||||
|
||||
// Calculate center pan
|
||||
const vidW = data.media?.metadata?.originalWidth ?? 1920
|
||||
const vidH = data.media?.metadata?.originalHeight ?? 1080
|
||||
|
||||
const scale = zoom
|
||||
const panX = (containerSize.width - vidW * scale) / 2
|
||||
const panY = (containerSize.height - vidH * scale) / 2
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group shadow-2xl font-sans select-none flex flex-col mx-auto transition-all duration-300 relative',
|
||||
state.isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
|
||||
!isControlsVisible && state.isFullScreen ? 'cursor-none' : '',
|
||||
)}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
{/* Video Area */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
'w-full bg-black cursor-pointer relative flex items-center justify-center overflow-hidden flex-1 min-h-0',
|
||||
)}
|
||||
onClick={togglePlay}
|
||||
data-vjs-player
|
||||
>
|
||||
{/* Hidden VideoJS container */}
|
||||
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
|
||||
|
||||
{/* Drawing Canvas (Visible) */}
|
||||
{videoHtmlEl && containerSize.width > 0 && (
|
||||
<DrawingCanvas
|
||||
width={containerSize.width}
|
||||
height={containerSize.height}
|
||||
mediaDimensions={{
|
||||
width: vidW,
|
||||
height: vidH,
|
||||
}}
|
||||
videoElement={videoHtmlEl}
|
||||
annotations={displayAnnotations}
|
||||
scale={scale}
|
||||
offset={{ x: panX, y: panY }}
|
||||
className="absolute inset-0"
|
||||
onClick={togglePlay}
|
||||
// Drawing Props
|
||||
isDrawing={isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={addAnnotation}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Big Play Button Overlay (when paused) */}
|
||||
{!state.isPlaying && !isDrawing && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
|
||||
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse">
|
||||
<Play className="w-10 h-10 text-white ml-1 fill-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ControlBar
|
||||
state={state}
|
||||
zoom={zoom}
|
||||
isControlsVisible={isControlsVisible}
|
||||
buffered={buffered}
|
||||
data={data}
|
||||
resolutions={resolutions}
|
||||
togglePlay={togglePlay}
|
||||
toggleLoop={toggleLoop}
|
||||
handleSeek={handleSeek}
|
||||
toggleMute={toggleMute}
|
||||
handleVolumeChange={handleVolumeChange}
|
||||
setState={setState}
|
||||
changePlaybackRate={changePlaybackRate}
|
||||
changeResolution={changeResolution}
|
||||
handleDownload={handleDownload}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
onZoomChange={setZoom}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VideoPlayer
|
||||
Reference in New Issue
Block a user