Files
chinese-family-tree-2/components/members/photo-gallery.tsx
T
freedakgmail b25f4bea02 0.0.9.0
2025-11-24 16:07:24 +08:00

172 lines
5.4 KiB
TypeScript

"use client"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { X, Upload, Image as ImageIcon, Plus, ZoomIn } from "lucide-react"
import { useDialog } from "@/components/ui/alert-dialog-custom"
import imageCompression from "browser-image-compression"
interface PhotoGalleryProps {
photoIds?: string[]
onChange: (photoIds: string[]) => void
readonly?: boolean
}
export function PhotoGallery({ photoIds = [], onChange, readonly = false }: PhotoGalleryProps) {
const { showAlert, showConfirm } = useDialog()
const [photos, setPhotos] = useState<{ id: string; url: string }[]>([])
const [selectedPhoto, setSelectedPhoto] = useState<string | null>(null)
const [isUploading, setIsUploading] = useState(false)
// 加载照片
useEffect(() => {
// photoIds 现在直接是 URL 数组
const loadedPhotos = photoIds.map((url) => ({ id: url, url }))
setPhotos(loadedPhotos)
}, [photoIds])
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files
if (!files || files.length === 0) return
setIsUploading(true)
try {
const newPhotoIds: string[] = []
for (const file of Array.from(files)) {
if (!file.type.startsWith('image/')) continue
// 压缩图片
const options = {
maxSizeMB: 2,
maxWidthOrHeight: 1920,
useWebWorker: true,
}
const compressedFile = await imageCompression(file, options)
// 上传到服务器
const formData = new FormData()
formData.append('file', compressedFile)
const response = await fetch('/api/upload', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('上传失败')
}
const { url } = await response.json()
newPhotoIds.push(url)
}
// 更新照片列表
onChange([...photoIds, ...newPhotoIds])
} catch (error) {
console.error('上传照片失败:', error)
await showAlert('上传照片失败', '错误')
} finally {
setIsUploading(false)
e.target.value = ''
}
}
const handleDelete = async (photoId: string) => {
const confirmed = await showConfirm('确定要删除这张照片吗?', '删除照片')
if (confirmed) {
onChange(photoIds.filter(id => id !== photoId))
}
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium"> ({photos.length})</h3>
{!readonly && (
<label>
<input
type="file"
multiple
accept="image/*"
className="hidden"
onChange={handleUpload}
disabled={isUploading}
/>
<Button
type="button"
variant="outline"
size="sm"
disabled={isUploading}
asChild
>
<span>
<Plus className="mr-2 h-4 w-4" />
{isUploading ? '上传中...' : '添加照片'}
</span>
</Button>
</label>
)}
</div>
{photos.length > 0 ? (
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{photos.map((photo) => (
<div key={photo.id} className="relative group aspect-square">
<img
src={photo.url}
alt="家族照片"
className="w-full h-full object-cover rounded-lg border border-border cursor-pointer hover:opacity-90 transition-opacity"
onClick={() => setSelectedPhoto(photo.url)}
/>
{!readonly && (
<Button
type="button"
variant="destructive"
size="icon"
className="absolute top-2 right-2 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => handleDelete(photo.id)}
>
<X className="h-3 w-3" />
</Button>
)}
<Button
type="button"
variant="secondary"
size="icon"
className="absolute bottom-2 right-2 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => setSelectedPhoto(photo.url)}
>
<ZoomIn className="h-3 w-3" />
</Button>
</div>
))}
</div>
) : (
<div className="text-center py-8 text-muted-foreground text-sm border border-dashed rounded-lg">
</div>
)}
{/* 照片预览对话框 */}
<Dialog open={!!selectedPhoto} onOpenChange={() => setSelectedPhoto(null)}>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
{selectedPhoto && (
<img
src={selectedPhoto}
alt="照片预览"
className="w-full h-auto max-h-[70vh] object-contain"
/>
)}
</DialogContent>
</Dialog>
</div>
)
}