| 1 | 'use client' |
| 2 | |
| 3 | import Image from 'next/image' |
| 4 | import { useState } |
| 5 | import { Button } |
| 6 | import { |
| 7 | Dialog, |
| 8 | DialogContent, |
| 9 | DialogDescription, |
| 10 | DialogFooter, |
| 11 | DialogHeader, |
| 12 | DialogTitle, |
| 13 | } from '@/components/ui/dialog' |
| 14 | import { cn } |
| 15 | |
| 16 | export interface MediaItem |
| 17 | contentType: string |
| 18 | createdAt: Date |
| 19 | id: string |
| 20 | name: string |
| 21 | } |
| 22 | |
| 23 | interface MediaLibraryDialogProps { |
| 24 | mediaItems: MediaItem |
| 25 | onOpenChange: (open |
| 26 | /** Receives the media item ID */ |
| 27 | onSelect: (id |
| 28 | open: boolean |
| 29 | } |
| 30 | |
| 31 | export function MediaLibraryDialog({ |
| 32 | open, |
| 33 | onOpenChange, |
| 34 | mediaItems, |
| 35 | onSelect, |
| 36 | }: MediaLibraryDialogProps) |
| 37 | const [selectedId, |
| 38 | |
| 39 | const handleSelect = |
| 40 | if (!selectedId) |
| 41 | return |
| 42 | } |
| 43 | onSelect(selectedId) |
| 44 | onOpenChange(false) |
| 45 | setSelectedId(null) |
| 46 | } |
| 47 | |
| 48 | return ( |
| 49 | <Dialog onOpenChange={ |
| 50 | <DialogContent className=' |
| 51 | <DialogHeader> |
| 52 | <DialogTitle>Media Library</DialogTitle |
| 53 | <DialogDescription> |
| 54 | Choose from previously uploaded images. |
| 55 | </DialogDescription> |
| 56 | </DialogHeader> |
| 57 | |
| 58 | {mediaItems.length === |
| 59 | <p className='py-8 text-center text-muted-foreground text-sm |
| 60 | No images uploaded yet. Upload one to get started. |
| 61 | </p> |
| 62 | ) : ( |
| 63 | <div className='grid max-h-[360px] grid-cols-3 gap-2 overflow-y-auto sm:grid-cols-4 |
| 64 | {mediaItems.map(( |
| 65 | <button |
| 66 | className={cn( |
| 67 | 'group relative aspect-square overflow-hidden rounded-md border bg-muted transition-all hover:border-1 hover:border-primary', |
| 68 | selectedId === item. |
| 69 | )} |
| 70 | key={item.id |
| 71 | onClick={() => |
| 72 | type='button' |
| 73 | > |
| 74 | <Image |
| 75 | alt={item.name |
| 76 | className='object-contain p-1' |
| 77 | fill |
| 78 | src={`/api/files/${item |
| 79 | unoptimized |
| 80 | /> |
| 81 | </button> |
| 82 | ))} |
| 83 | </div> |
| 84 | )} |
| 85 | |
| 86 | <DialogFooter> |
| 87 | <Button disabled={ |
| 88 | Use Selected |
| 89 | </Button> |
| 90 | </DialogFooter> |
| 91 | </DialogContent> |
| 92 | </Dialog> |
| 93 | ) |
| 94 | } |