641 lines
22 KiB
TypeScript
641 lines
22 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useState } from 'react'
|
|
import { useTranslations } from 'next-intl'
|
|
import { useAuth } from '@/hooks/useAuth'
|
|
import { useRouter } from 'next/navigation'
|
|
import { Header } from '@/components/layout/Header'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { LoadingSpinner } from '@/components/ui/loading-spinner'
|
|
import { EditPromptModal } from '@/components/studio/EditPromptModal'
|
|
import {
|
|
Plus,
|
|
Search,
|
|
MoreHorizontal,
|
|
Edit,
|
|
Trash2,
|
|
Play,
|
|
FileText,
|
|
Calendar,
|
|
ChevronDown,
|
|
Grid,
|
|
List
|
|
} from 'lucide-react'
|
|
|
|
interface Prompt {
|
|
id: string
|
|
name: string
|
|
description: string | null
|
|
content: string
|
|
tags: string[]
|
|
createdAt: string
|
|
updatedAt: string
|
|
lastUsed?: string | null
|
|
currentVersion?: number
|
|
usage?: number
|
|
}
|
|
|
|
interface PaginationInfo {
|
|
page: number
|
|
limit: number
|
|
total: number
|
|
totalPages: number
|
|
}
|
|
|
|
type SortField = 'name' | 'createdAt' | 'updatedAt' | 'lastUsed'
|
|
type SortOrder = 'asc' | 'desc'
|
|
type ViewMode = 'grid' | 'list'
|
|
|
|
export default function StudioPage() {
|
|
const { user, loading } = useAuth()
|
|
const router = useRouter()
|
|
const t = useTranslations('studio')
|
|
const tCommon = useTranslations('common')
|
|
|
|
const [prompts, setPrompts] = useState<Prompt[]>([])
|
|
const [filteredPrompts, setFilteredPrompts] = useState<Prompt[]>([])
|
|
const [searchQuery, setSearchQuery] = useState('')
|
|
const [selectedTag, setSelectedTag] = useState<string>('')
|
|
const [sortField, setSortField] = useState<SortField>('updatedAt')
|
|
const [sortOrder, setSortOrder] = useState<SortOrder>('desc')
|
|
const [viewMode, setViewMode] = useState<ViewMode>('grid')
|
|
const [selectedPrompts, setSelectedPrompts] = useState<string[]>([])
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
const [allTags, setAllTags] = useState<string[]>([])
|
|
|
|
// Edit Modal
|
|
const [editingPrompt, setEditingPrompt] = useState<Prompt | null>(null)
|
|
const [isEditModalOpen, setIsEditModalOpen] = useState(false)
|
|
|
|
// Pagination
|
|
const [currentPage, setCurrentPage] = useState(1)
|
|
const itemsPerPage = 12
|
|
const [pagination, setPagination] = useState<PaginationInfo>({
|
|
page: 1,
|
|
limit: 12,
|
|
total: 0,
|
|
totalPages: 0
|
|
})
|
|
|
|
useEffect(() => {
|
|
if (!loading && !user) {
|
|
router.push('/signin')
|
|
} else if (user) {
|
|
fetchPrompts()
|
|
fetchTags()
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [user, loading, router])
|
|
|
|
// Fetch prompts from API
|
|
const fetchPrompts = async () => {
|
|
if (!user) return
|
|
|
|
try {
|
|
setIsLoading(true)
|
|
const params = new URLSearchParams({
|
|
userId: user.id,
|
|
page: currentPage.toString(),
|
|
limit: itemsPerPage.toString(),
|
|
search: searchQuery,
|
|
tag: selectedTag,
|
|
sortBy: sortField,
|
|
sortOrder: sortOrder
|
|
})
|
|
|
|
const response = await fetch(`/api/prompts?${params}`)
|
|
if (response.ok) {
|
|
const data = await response.json()
|
|
setPrompts(data.prompts)
|
|
setPagination(data.pagination)
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching prompts:', error)
|
|
} finally {
|
|
setIsLoading(false)
|
|
}
|
|
}
|
|
|
|
// Fetch tags from API
|
|
const fetchTags = async () => {
|
|
if (!user) return
|
|
|
|
try {
|
|
const response = await fetch(`/api/tags?userId=${user.id}`)
|
|
if (response.ok) {
|
|
const tags = await response.json()
|
|
setAllTags(tags.map((tag: { name: string }) => tag.name))
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching tags:', error)
|
|
}
|
|
}
|
|
|
|
// Refetch when filters change
|
|
useEffect(() => {
|
|
if (user) {
|
|
fetchPrompts()
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [currentPage, itemsPerPage, searchQuery, selectedTag, sortField, sortOrder, user])
|
|
|
|
// Since filtering and sorting is now done on the server,
|
|
// we just use the prompts directly
|
|
useEffect(() => {
|
|
setFilteredPrompts(prompts)
|
|
}, [prompts])
|
|
|
|
const handleCreatePrompt = () => {
|
|
router.push('/studio/new')
|
|
}
|
|
|
|
const handleEditPrompt = (id: string) => {
|
|
router.push(`/studio/${id}`)
|
|
}
|
|
|
|
const handleQuickEdit = (prompt: Prompt) => {
|
|
setEditingPrompt(prompt)
|
|
setIsEditModalOpen(true)
|
|
}
|
|
|
|
const handleEditModalClose = () => {
|
|
setIsEditModalOpen(false)
|
|
setEditingPrompt(null)
|
|
}
|
|
|
|
const handleEditModalSave = (updatedPrompt: Prompt) => {
|
|
// Update the prompt in the local state
|
|
setPrompts(prev => prev.map(p => p.id === updatedPrompt.id ? updatedPrompt : p))
|
|
setFilteredPrompts(prev => prev.map(p => p.id === updatedPrompt.id ? updatedPrompt : p))
|
|
}
|
|
|
|
const handleDeletePrompt = async (id: string) => {
|
|
if (!user || !confirm(t('confirmDelete'))) return
|
|
|
|
try {
|
|
const response = await fetch(`/api/prompts/${id}?userId=${user.id}`, {
|
|
method: 'DELETE'
|
|
})
|
|
|
|
if (response.ok) {
|
|
await fetchPrompts() // Refresh the list
|
|
setSelectedPrompts(prev => prev.filter(pId => pId !== id))
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting prompt:', error)
|
|
}
|
|
}
|
|
|
|
const handleDuplicatePrompt = async (prompt: Prompt) => {
|
|
if (!user) return
|
|
|
|
try {
|
|
const response = await fetch('/api/prompts/bulk', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
action: 'duplicate',
|
|
promptIds: [prompt.id],
|
|
userId: user.id
|
|
})
|
|
})
|
|
|
|
if (response.ok) {
|
|
await fetchPrompts() // Refresh the list
|
|
}
|
|
} catch (error) {
|
|
console.error('Error duplicating prompt:', error)
|
|
}
|
|
}
|
|
|
|
const handleBulkDelete = async () => {
|
|
if (!user || selectedPrompts.length === 0) return
|
|
|
|
if (!confirm(`Delete ${selectedPrompts.length} selected prompts?`)) return
|
|
|
|
try {
|
|
const response = await fetch('/api/prompts/bulk', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
action: 'delete',
|
|
promptIds: selectedPrompts,
|
|
userId: user.id
|
|
})
|
|
})
|
|
|
|
if (response.ok) {
|
|
await fetchPrompts() // Refresh the list
|
|
setSelectedPrompts([])
|
|
}
|
|
} catch (error) {
|
|
console.error('Error bulk deleting prompts:', error)
|
|
}
|
|
}
|
|
|
|
const handleSelectPrompt = (id: string) => {
|
|
setSelectedPrompts(prev =>
|
|
prev.includes(id)
|
|
? prev.filter(pId => pId !== id)
|
|
: [...prev, id]
|
|
)
|
|
}
|
|
|
|
const handleSelectAll = () => {
|
|
const currentPagePrompts = filteredPrompts.slice(
|
|
(currentPage - 1) * itemsPerPage,
|
|
currentPage * itemsPerPage
|
|
)
|
|
|
|
if (selectedPrompts.length === currentPagePrompts.length) {
|
|
setSelectedPrompts([])
|
|
} else {
|
|
setSelectedPrompts(currentPagePrompts.map(p => p.id))
|
|
}
|
|
}
|
|
|
|
const formatDate = (dateString: string) => {
|
|
return new Intl.DateTimeFormat('default', {
|
|
year: 'numeric',
|
|
month: 'short',
|
|
day: 'numeric'
|
|
}).format(new Date(dateString))
|
|
}
|
|
|
|
// Use server-side pagination
|
|
const currentPrompts = filteredPrompts
|
|
|
|
if (loading || isLoading) {
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center">
|
|
<div className="text-center">
|
|
<LoadingSpinner size="lg" />
|
|
<p className="mt-4 text-muted-foreground">{t('loadingStudio')}</p>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
if (!user) {
|
|
return null
|
|
}
|
|
|
|
return (
|
|
<div className="min-h-screen">
|
|
<Header />
|
|
|
|
<div className="max-w-7xl mx-auto px-4 py-8">
|
|
{/* Header */}
|
|
<div className="mb-8">
|
|
<div className="flex items-center justify-between mb-4">
|
|
<div>
|
|
<h1 className="text-3xl font-bold text-foreground">{t('title')}</h1>
|
|
<p className="text-muted-foreground mt-1">{t('myPrompts')}</p>
|
|
</div>
|
|
<Button onClick={handleCreatePrompt} className="flex items-center space-x-2">
|
|
<Plus className="h-4 w-4" />
|
|
<span>{t('createPrompt')}</span>
|
|
</Button>
|
|
</div>
|
|
|
|
{/* Search and Filters */}
|
|
<div className="flex flex-col sm:flex-row gap-4 mb-6">
|
|
{/* Search */}
|
|
<div className="flex-1 relative">
|
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
|
<Input
|
|
placeholder={t('searchPrompts')}
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
className="pl-9"
|
|
/>
|
|
</div>
|
|
|
|
{/* Tag Filter */}
|
|
<div className="relative">
|
|
<select
|
|
value={selectedTag}
|
|
onChange={(e) => setSelectedTag(e.target.value)}
|
|
className="appearance-none bg-background border border-input rounded-md px-3 py-2 pr-8 min-w-[120px] focus:outline-none focus:ring-2 focus:ring-ring"
|
|
>
|
|
<option value="">{t('allTags')}</option>
|
|
{allTags.map(tag => (
|
|
<option key={tag} value={tag}>{tag}</option>
|
|
))}
|
|
</select>
|
|
<ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
|
|
</div>
|
|
|
|
{/* Sort */}
|
|
<div className="relative">
|
|
<select
|
|
value={`${sortField}-${sortOrder}`}
|
|
onChange={(e) => {
|
|
const [field, order] = e.target.value.split('-')
|
|
setSortField(field as SortField)
|
|
setSortOrder(order as SortOrder)
|
|
}}
|
|
className="appearance-none bg-background border border-input rounded-md px-3 py-2 pr-8 min-w-[140px] focus:outline-none focus:ring-2 focus:ring-ring"
|
|
>
|
|
<option value="updatedAt-desc">{t('sortByUpdated')} ({t('descending')})</option>
|
|
<option value="updatedAt-asc">{t('sortByUpdated')} ({t('ascending')})</option>
|
|
<option value="createdAt-desc">{t('sortByDate')} ({t('descending')})</option>
|
|
<option value="createdAt-asc">{t('sortByDate')} ({t('ascending')})</option>
|
|
<option value="name-asc">{t('sortByName')} ({t('ascending')})</option>
|
|
<option value="name-desc">{t('sortByName')} ({t('descending')})</option>
|
|
<option value="lastUsed-desc">{t('lastUsed')} ({t('descending')})</option>
|
|
<option value="lastUsed-asc">{t('lastUsed')} ({t('ascending')})</option>
|
|
</select>
|
|
<ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
|
|
</div>
|
|
|
|
{/* View Mode Toggle */}
|
|
<div className="flex items-center border border-input rounded-md">
|
|
<Button
|
|
variant={viewMode === 'grid' ? 'default' : 'ghost'}
|
|
size="sm"
|
|
onClick={() => setViewMode('grid')}
|
|
className="rounded-r-none"
|
|
>
|
|
<Grid className="h-4 w-4" />
|
|
</Button>
|
|
<Button
|
|
variant={viewMode === 'list' ? 'default' : 'ghost'}
|
|
size="sm"
|
|
onClick={() => setViewMode('list')}
|
|
className="rounded-l-none"
|
|
>
|
|
<List className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Bulk Actions */}
|
|
{selectedPrompts.length > 0 && (
|
|
<div className="flex items-center justify-between mb-4 p-3 bg-muted rounded-lg">
|
|
<span className="text-sm text-muted-foreground">
|
|
{selectedPrompts.length} {t('selectedItems')}
|
|
</span>
|
|
<div className="flex items-center space-x-2">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={handleBulkDelete}
|
|
className="text-destructive hover:text-destructive"
|
|
>
|
|
<Trash2 className="h-4 w-4 mr-1" />
|
|
{t('bulkDelete')}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Content */}
|
|
{filteredPrompts.length === 0 ? (
|
|
<div className="text-center py-12">
|
|
<FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
|
<h3 className="text-lg font-semibold text-foreground mb-2">{t('noPrompts')}</h3>
|
|
<p className="text-muted-foreground mb-4">{t('createFirstPrompt')}</p>
|
|
<Button onClick={handleCreatePrompt}>
|
|
<Plus className="h-4 w-4 mr-2" />
|
|
{t('createPrompt')}
|
|
</Button>
|
|
</div>
|
|
) : (
|
|
<>
|
|
{/* Prompts Grid/List */}
|
|
{viewMode === 'grid' ? (
|
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-8">
|
|
{currentPrompts.map((prompt) => (
|
|
<div
|
|
key={prompt.id}
|
|
className={`bg-card rounded-lg border border-border p-4 hover:shadow-md transition-shadow cursor-pointer ${
|
|
selectedPrompts.includes(prompt.id) ? 'ring-2 ring-primary' : ''
|
|
}`}
|
|
onClick={() => handleSelectPrompt(prompt.id)}
|
|
>
|
|
<div className="flex items-start justify-between mb-3">
|
|
<div className="flex-1">
|
|
<h3 className="font-semibold text-foreground truncate mb-1">
|
|
{prompt.name}
|
|
</h3>
|
|
<p className="text-sm text-muted-foreground line-clamp-2">
|
|
{prompt.description}
|
|
</p>
|
|
</div>
|
|
<div className="relative ml-2">
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
className="h-8 w-8 p-0"
|
|
onClick={(e) => {
|
|
e.stopPropagation()
|
|
handleQuickEdit(prompt)
|
|
}}
|
|
>
|
|
<Edit className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Tags */}
|
|
<div className="flex flex-wrap gap-1 mb-3">
|
|
{prompt.tags.slice(0, 3).map((tag) => (
|
|
<span
|
|
key={tag}
|
|
className="inline-flex items-center px-2 py-1 text-xs font-medium bg-muted text-muted-foreground rounded-full"
|
|
>
|
|
{tag}
|
|
</span>
|
|
))}
|
|
{prompt.tags.length > 3 && (
|
|
<span className="text-xs text-muted-foreground">
|
|
+{prompt.tags.length - 3}
|
|
</span>
|
|
)}
|
|
</div>
|
|
|
|
{/* Metadata */}
|
|
<div className="text-xs text-muted-foreground space-y-1">
|
|
<div className="flex items-center">
|
|
<Calendar className="h-3 w-3 mr-1" />
|
|
<span className="hidden sm:inline">{t('updatedAt')}: </span>
|
|
{formatDate(prompt.updatedAt)}
|
|
</div>
|
|
{prompt.lastUsed && (
|
|
<div>
|
|
<span className="hidden sm:inline">{t('lastUsed')}: </span>
|
|
<span className="sm:hidden">Used: </span>
|
|
{formatDate(prompt.lastUsed)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Action Buttons */}
|
|
<div className="flex items-center justify-between mt-4 pt-3 border-t border-border">
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={(e) => {
|
|
e.stopPropagation()
|
|
handleEditPrompt(prompt.id)
|
|
}}
|
|
className="flex items-center space-x-1"
|
|
>
|
|
<Edit className="h-3 w-3" />
|
|
<span className="text-xs">{tCommon('edit')}</span>
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={(e) => {
|
|
e.stopPropagation()
|
|
handleEditPrompt(prompt.id)
|
|
}}
|
|
className="flex items-center space-x-1"
|
|
>
|
|
<Play className="h-3 w-3" />
|
|
<span className="text-xs">{t('debugPrompt')}</span>
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<div className="space-y-4 mb-8">
|
|
{/* List Header */}
|
|
<div className="flex items-center p-3 bg-muted rounded-lg text-sm font-medium text-muted-foreground">
|
|
<div className="w-8">
|
|
<input
|
|
type="checkbox"
|
|
checked={selectedPrompts.length === currentPrompts.length && currentPrompts.length > 0}
|
|
onChange={handleSelectAll}
|
|
className="rounded"
|
|
/>
|
|
</div>
|
|
<div className="flex-1">{t('promptName')}</div>
|
|
<div className="w-32">{t('updatedAt')}</div>
|
|
<div className="w-32">{t('lastUsed')}</div>
|
|
<div className="w-20">{t('tags')}</div>
|
|
<div className="w-16"></div>
|
|
</div>
|
|
|
|
{/* List Items */}
|
|
{currentPrompts.map((prompt) => (
|
|
<div
|
|
key={prompt.id}
|
|
className={`flex items-center p-3 bg-card rounded-lg border border-border hover:shadow-sm transition-shadow ${
|
|
selectedPrompts.includes(prompt.id) ? 'ring-2 ring-primary' : ''
|
|
}`}
|
|
>
|
|
<div className="w-8">
|
|
<input
|
|
type="checkbox"
|
|
checked={selectedPrompts.includes(prompt.id)}
|
|
onChange={() => handleSelectPrompt(prompt.id)}
|
|
className="rounded"
|
|
/>
|
|
</div>
|
|
<div className="flex-1">
|
|
<div className="font-medium text-foreground">{prompt.name}</div>
|
|
<div className="text-sm text-muted-foreground truncate">
|
|
{prompt.description}
|
|
</div>
|
|
</div>
|
|
<div className="w-32 text-sm text-muted-foreground">
|
|
{formatDate(prompt.updatedAt)}
|
|
</div>
|
|
<div className="w-32 text-sm text-muted-foreground">
|
|
{prompt.lastUsed ? formatDate(prompt.lastUsed) : t('never')}
|
|
</div>
|
|
<div className="w-20">
|
|
<span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-muted text-muted-foreground rounded-full">
|
|
{prompt.tags.length}
|
|
</span>
|
|
</div>
|
|
<div className="w-16 flex items-center justify-end space-x-1">
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => handleQuickEdit(prompt)}
|
|
className="h-8 w-8 p-0"
|
|
title="Quick Edit"
|
|
>
|
|
<Edit className="h-3 w-3" />
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => handleEditPrompt(prompt.id)}
|
|
className="h-8 w-8 p-0"
|
|
title="Full Edit"
|
|
>
|
|
<MoreHorizontal className="h-3 w-3" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
{/* Pagination */}
|
|
{pagination.totalPages > 1 && (
|
|
<div className="flex items-center justify-between">
|
|
<div className="text-sm text-muted-foreground">
|
|
{t('page')} {pagination.page} {t('of')} {pagination.totalPages} {t('total')} {pagination.total}
|
|
</div>
|
|
|
|
<div className="flex items-center space-x-2">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={pagination.page === 1}
|
|
onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
|
|
>
|
|
Previous
|
|
</Button>
|
|
|
|
{Array.from({ length: Math.min(5, pagination.totalPages) }, (_, i) => {
|
|
const page = i + 1
|
|
return (
|
|
<Button
|
|
key={page}
|
|
variant={pagination.page === page ? 'default' : 'outline'}
|
|
size="sm"
|
|
onClick={() => setCurrentPage(page)}
|
|
>
|
|
{page}
|
|
</Button>
|
|
)
|
|
})}
|
|
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={pagination.page === pagination.totalPages}
|
|
onClick={() => setCurrentPage(prev => Math.min(pagination.totalPages, prev + 1))}
|
|
>
|
|
Next
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
|
|
{/* Edit Modal */}
|
|
{editingPrompt && (
|
|
<EditPromptModal
|
|
prompt={editingPrompt}
|
|
isOpen={isEditModalOpen}
|
|
onClose={handleEditModalClose}
|
|
onSave={handleEditModalSave}
|
|
userId={user?.id || ''}
|
|
/>
|
|
)}
|
|
</div>
|
|
)
|
|
} |