fix studio page

This commit is contained in:
songtianlun 2025-07-30 15:06:51 +08:00
parent 2707a510b5
commit 812a12d71b
2 changed files with 219 additions and 182 deletions

View File

@ -1,6 +1,6 @@
'use client'
import { useEffect, useState } from 'react'
import { useEffect, useState, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { useAuth } from '@/hooks/useAuth'
import { useRouter } from 'next/navigation'
@ -9,13 +9,12 @@ 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 { PromptDetailModal } from '@/components/studio/PromptDetailModal'
import {
Plus,
Search,
MoreHorizontal,
Edit,
Trash2,
Play,
FileText,
Calendar,
ChevronDown,
@ -51,7 +50,6 @@ 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[]>([])
@ -60,7 +58,6 @@ export default function StudioPage() {
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[]>([])
@ -68,6 +65,10 @@ export default function StudioPage() {
const [editingPrompt, setEditingPrompt] = useState<Prompt | null>(null)
const [isEditModalOpen, setIsEditModalOpen] = useState(false)
// Detail Modal
const [detailPrompt, setDetailPrompt] = useState<Prompt | null>(null)
const [isDetailModalOpen, setIsDetailModalOpen] = useState(false)
// Pagination
const [currentPage, setCurrentPage] = useState(1)
const itemsPerPage = 12
@ -79,7 +80,7 @@ export default function StudioPage() {
})
// Fetch prompts from API
const fetchPrompts = async () => {
const fetchPrompts = useCallback(async () => {
if (!user) return
try {
@ -105,9 +106,9 @@ export default function StudioPage() {
} finally {
setIsLoading(false)
}
}
}, [user, currentPage, itemsPerPage, searchQuery, selectedTag, sortField, sortOrder])
// Initial load effect
// Initialize and fetch tags only once
useEffect(() => {
if (!loading && !user) {
router.push('/signin')
@ -128,42 +129,19 @@ export default function StudioPage() {
}
}
fetchPrompts()
fetchTags()
}, [user, loading, router])
// Refetch when filters change
// Fetch prompts with debounced search
useEffect(() => {
if (!user) return
const fetchPromptsWithFilters = async () => {
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 timeoutId = setTimeout(() => {
fetchPrompts()
}, searchQuery ? 300 : 0) // Debounce search queries
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)
}
}
fetchPromptsWithFilters()
}, [currentPage, itemsPerPage, searchQuery, selectedTag, sortField, sortOrder, user])
return () => clearTimeout(timeoutId)
}, [currentPage, searchQuery, selectedTag, sortField, sortOrder, user, fetchPrompts])
// Since filtering and sorting is now done on the server,
// we just use the prompts directly
@ -195,90 +173,21 @@ export default function StudioPage() {
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 handleShowDetails = (prompt: Prompt) => {
setDetailPrompt(prompt)
setIsDetailModalOpen(true)
}
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 handleDetailModalClose = () => {
setIsDetailModalOpen(false)
setDetailPrompt(null)
}
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 handleDebugPrompt = (id: string) => {
router.push(`/studio/${id}`)
}
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', {
@ -396,25 +305,6 @@ export default function StudioPage() {
</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 */}
@ -436,9 +326,8 @@ export default function StudioPage() {
{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)}
className="bg-card rounded-lg border border-border p-4 hover:shadow-md transition-shadow cursor-pointer"
onClick={() => handleShowDetails(prompt)}
>
<div className="flex items-start justify-between mb-3">
<div className="flex-1">
@ -466,7 +355,7 @@ export default function StudioPage() {
{/* Tags */}
<div className="flex flex-wrap gap-1 mb-3">
{prompt.tags?.slice(0, 3).map((tag: any) => {
{prompt.tags?.slice(0, 3).map((tag: string | { name: string }) => {
const tagName = typeof tag === 'string' ? tag : tag?.name || '';
return (
<span
@ -500,33 +389,6 @@ export default function StudioPage() {
)}
</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>
@ -534,14 +396,6 @@ export default function StudioPage() {
<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>
@ -553,17 +407,9 @@ export default function StudioPage() {
{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' : ''
}`}
className="flex items-center p-3 bg-card rounded-lg border border-border hover:shadow-sm transition-shadow cursor-pointer"
onClick={() => handleShowDetails(prompt)}
>
<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">
@ -662,6 +508,15 @@ export default function StudioPage() {
userId={user?.id || ''}
/>
)}
{/* Detail Modal */}
<PromptDetailModal
prompt={detailPrompt}
isOpen={isDetailModalOpen}
onClose={handleDetailModalClose}
onEdit={handleEditPrompt}
onDebug={handleDebugPrompt}
/>
</div>
)
}

View File

@ -0,0 +1,182 @@
'use client'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { X, Edit, Play, Calendar, Tag } 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 PromptDetailModalProps {
prompt: Prompt | null
isOpen: boolean
onClose: () => void
onEdit: (id: string) => void
onDebug: (id: string) => void
}
export function PromptDetailModal({
prompt,
isOpen,
onClose,
onEdit,
onDebug
}: PromptDetailModalProps) {
const t = useTranslations('studio')
const tCommon = useTranslations('common')
const formatDate = (dateString: string) => {
return new Intl.DateTimeFormat('default', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(new Date(dateString))
}
if (!isOpen || !prompt) return null
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
{/* Backdrop */}
<div
className="absolute inset-0 bg-black/50"
onClick={onClose}
/>
{/* Modal */}
<div className="relative bg-background border border-border rounded-lg shadow-lg max-w-2xl w-full mx-4 max-h-[90vh] overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-border">
<div className="flex-1">
<h2 className="text-xl font-semibold text-foreground">
{prompt.name}
</h2>
{prompt.description && (
<p className="text-sm text-muted-foreground mt-1">
{prompt.description}
</p>
)}
</div>
<Button
variant="ghost"
size="sm"
onClick={onClose}
className="h-8 w-8 p-0"
>
<X className="h-4 w-4" />
</Button>
</div>
{/* Content */}
<div className="p-6 space-y-6 overflow-y-auto max-h-[60vh]">
{/* Tags */}
{prompt.tags && prompt.tags.length > 0 && (
<div className="space-y-2">
<div className="flex items-center text-sm font-medium text-foreground">
<Tag className="h-4 w-4 mr-2" />
{t('tags')}
</div>
<div className="flex flex-wrap gap-2">
{prompt.tags.map((tag: string | { name: string }) => {
const tagName = typeof tag === 'string' ? tag : tag?.name || '';
return (
<span
key={tagName}
className="inline-flex items-center px-3 py-1 text-sm font-medium bg-muted text-muted-foreground rounded-full"
>
{tagName}
</span>
);
})}
</div>
</div>
)}
{/* Prompt Content */}
<div className="space-y-2">
<h3 className="text-sm font-medium text-foreground">{t('promptContent')}</h3>
<div className="bg-muted rounded-lg p-4">
<pre className="text-sm text-foreground whitespace-pre-wrap break-words">
{prompt.content}
</pre>
</div>
</div>
{/* Metadata */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
<div className="space-y-3">
<div className="flex items-center text-muted-foreground">
<Calendar className="h-4 w-4 mr-2" />
<span className="font-medium">{t('createdAt')}:</span>
<span className="ml-2">{formatDate(prompt.createdAt)}</span>
</div>
<div className="flex items-center text-muted-foreground">
<Calendar className="h-4 w-4 mr-2" />
<span className="font-medium">{t('updatedAt')}:</span>
<span className="ml-2">{formatDate(prompt.updatedAt)}</span>
</div>
</div>
<div className="space-y-3">
{prompt.lastUsed && (
<div className="flex items-center text-muted-foreground">
<Calendar className="h-4 w-4 mr-2" />
<span className="font-medium">{t('lastUsed')}:</span>
<span className="ml-2">{formatDate(prompt.lastUsed)}</span>
</div>
)}
{prompt.currentVersion && (
<div className="flex items-center text-muted-foreground">
<span className="font-medium">{t('version')}:</span>
<span className="ml-2">v{prompt.currentVersion}</span>
</div>
)}
</div>
</div>
</div>
{/* Footer Actions */}
<div className="flex items-center justify-end space-x-3 p-6 border-t border-border">
<Button
variant="outline"
onClick={onClose}
>
{tCommon('close')}
</Button>
<Button
variant="outline"
onClick={() => {
onEdit(prompt.id)
onClose()
}}
className="flex items-center space-x-2"
>
<Edit className="h-4 w-4" />
<span>{tCommon('edit')}</span>
</Button>
<Button
onClick={() => {
onDebug(prompt.id)
onClose()
}}
className="flex items-center space-x-2"
>
<Play className="h-4 w-4" />
<span>{t('debugPrompt')}</span>
</Button>
</div>
</div>
</div>
)
}