|
1 | 1 | "use client"; |
2 | 2 |
|
3 | | -import { useState } from "react"; |
| 3 | +import { useRef, useState } from "react"; |
| 4 | +import ReactCrop, { centerCrop, makeAspectCrop, type Crop } from "react-image-crop"; |
| 5 | +import "react-image-crop/dist/ReactCrop.css"; |
| 6 | +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; |
| 7 | +import { Button } from "@/components/ui/button"; |
| 8 | +import { |
| 9 | + Dialog, |
| 10 | + DialogContent, |
| 11 | + DialogFooter, |
| 12 | + DialogHeader, |
| 13 | + DialogTitle, |
| 14 | +} from "@/components/ui/dialog"; |
4 | 15 | import { Input } from "@/components/ui/input"; |
5 | 16 | import { Label } from "@/components/ui/label"; |
6 | | -import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; |
7 | 17 |
|
8 | 18 | interface ImageUploadProps { |
9 | 19 | currentUrl?: string; |
10 | | - onFileSelect: (file: File) => void; |
| 20 | + onUploaded: (url: string) => void; |
11 | 21 | label?: string; |
| 22 | + name?: string; |
12 | 23 | } |
13 | 24 |
|
14 | | -export function ImageUpload({ currentUrl, onFileSelect, label = "Photo" }: ImageUploadProps) { |
15 | | - const [preview, setPreview] = useState<string | undefined>(currentUrl); |
| 25 | +function getCroppedBlob(image: HTMLImageElement, crop: Crop): Promise<Blob> { |
| 26 | + const canvas = document.createElement("canvas"); |
| 27 | + canvas.width = 800; |
| 28 | + canvas.height = 800; |
| 29 | + const ctx = canvas.getContext("2d")!; |
| 30 | + |
| 31 | + const scaleX = image.naturalWidth / image.width; |
| 32 | + const scaleY = image.naturalHeight / image.height; |
| 33 | + |
| 34 | + const px = |
| 35 | + crop.unit === "%" |
| 36 | + ? { |
| 37 | + x: (crop.x / 100) * image.width * scaleX, |
| 38 | + y: (crop.y / 100) * image.height * scaleY, |
| 39 | + w: (crop.width / 100) * image.width * scaleX, |
| 40 | + h: (crop.height / 100) * image.height * scaleY, |
| 41 | + } |
| 42 | + : { |
| 43 | + x: crop.x * scaleX, |
| 44 | + y: crop.y * scaleY, |
| 45 | + w: crop.width * scaleX, |
| 46 | + h: crop.height * scaleY, |
| 47 | + }; |
| 48 | + |
| 49 | + ctx.drawImage(image, px.x, px.y, px.w, px.h, 0, 0, 800, 800); |
| 50 | + |
| 51 | + return new Promise((resolve, reject) => { |
| 52 | + canvas.toBlob( |
| 53 | + (blob) => (blob ? resolve(blob) : reject(new Error("Canvas is empty"))), |
| 54 | + "image/jpeg", |
| 55 | + 0.95, |
| 56 | + ); |
| 57 | + }); |
| 58 | +} |
16 | 59 |
|
17 | | - const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 60 | +export function ImageUpload({ currentUrl, onUploaded, label = "Photo", name }: ImageUploadProps) { |
| 61 | + const [preview, setPreview] = useState<string | undefined>(currentUrl || undefined); |
| 62 | + const [imgSrc, setImgSrc] = useState(""); |
| 63 | + const [crop, setCrop] = useState<Crop>(); |
| 64 | + const [uploading, setUploading] = useState(false); |
| 65 | + const imgRef = useRef<HTMLImageElement>(null); |
| 66 | + const inputRef = useRef<HTMLInputElement>(null); |
| 67 | + |
| 68 | + const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
18 | 69 | const file = e.target.files?.[0]; |
19 | 70 | if (!file) return; |
20 | | - setPreview(URL.createObjectURL(file)); |
21 | | - onFileSelect(file); |
| 71 | + const reader = new FileReader(); |
| 72 | + reader.onload = () => setImgSrc(reader.result as string); |
| 73 | + reader.readAsDataURL(file); |
| 74 | + // reset so the same file can be re-selected |
| 75 | + e.target.value = ""; |
| 76 | + }; |
| 77 | + |
| 78 | + const onImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => { |
| 79 | + const { width, height } = e.currentTarget; |
| 80 | + setCrop(centerCrop(makeAspectCrop({ unit: "%", width: 90 }, 1, width, height), width, height)); |
| 81 | + }; |
| 82 | + |
| 83 | + const handleApply = async () => { |
| 84 | + if (!imgRef.current || !crop) return; |
| 85 | + setUploading(true); |
| 86 | + try { |
| 87 | + const blob = await getCroppedBlob(imgRef.current, crop); |
| 88 | + const form = new FormData(); |
| 89 | + form.append("file", blob, "avatar.jpg"); |
| 90 | + const res = await fetch("/api/user/avatar", { method: "POST", body: form }); |
| 91 | + if (!res.ok) throw new Error("Upload failed"); |
| 92 | + const { url } = await res.json(); |
| 93 | + setPreview(url); |
| 94 | + onUploaded(url); |
| 95 | + setImgSrc(""); |
| 96 | + } catch (err) { |
| 97 | + console.error(err); |
| 98 | + } finally { |
| 99 | + setUploading(false); |
| 100 | + } |
22 | 101 | }; |
23 | 102 |
|
24 | 103 | return ( |
25 | | - <div className="space-y-2"> |
26 | | - <Label>{label}</Label> |
27 | | - <div className="flex items-center gap-3"> |
28 | | - <Avatar className="h-14 w-14"> |
29 | | - <AvatarImage src={preview} /> |
30 | | - <AvatarFallback className="text-xs">IMG</AvatarFallback> |
31 | | - </Avatar> |
32 | | - <Input type="file" accept="image/*" onChange={handleChange} className="max-w-xs" /> |
| 104 | + <> |
| 105 | + <div className="space-y-2"> |
| 106 | + <Label>{label}</Label> |
| 107 | + <div className="flex items-center gap-3"> |
| 108 | + <Avatar className="h-14 w-14"> |
| 109 | + <AvatarImage src={preview} /> |
| 110 | + <AvatarFallback className="text-xs"> |
| 111 | + {name |
| 112 | + ? name.split(" ").map((n) => n[0]).join("").toUpperCase().slice(0, 2) |
| 113 | + : "?"} |
| 114 | + </AvatarFallback> |
| 115 | + </Avatar> |
| 116 | + <Input |
| 117 | + ref={inputRef} |
| 118 | + type="file" |
| 119 | + accept="image/*" |
| 120 | + onChange={handleFileChange} |
| 121 | + className="max-w-xs" |
| 122 | + /> |
| 123 | + </div> |
33 | 124 | </div> |
34 | | - </div> |
| 125 | + |
| 126 | + <Dialog open={!!imgSrc} onOpenChange={(open) => !open && setImgSrc("")}> |
| 127 | + <DialogContent className="max-w-lg"> |
| 128 | + <DialogHeader> |
| 129 | + <DialogTitle>Crop photo</DialogTitle> |
| 130 | + </DialogHeader> |
| 131 | + <div className="flex justify-center"> |
| 132 | + <ReactCrop |
| 133 | + crop={crop} |
| 134 | + onChange={(_, pct) => setCrop(pct)} |
| 135 | + aspect={1} |
| 136 | + circularCrop |
| 137 | + keepSelection |
| 138 | + > |
| 139 | + {/* eslint-disable-next-line @next/next/no-img-element */} |
| 140 | + <img ref={imgRef} src={imgSrc} onLoad={onImageLoad} alt="Crop preview" /> |
| 141 | + </ReactCrop> |
| 142 | + </div> |
| 143 | + <DialogFooter> |
| 144 | + <Button variant="outline" onClick={() => setImgSrc("")} disabled={uploading}> |
| 145 | + Cancel |
| 146 | + </Button> |
| 147 | + <Button onClick={handleApply} disabled={!crop || uploading}> |
| 148 | + {uploading ? "Uploading…" : "Apply"} |
| 149 | + </Button> |
| 150 | + </DialogFooter> |
| 151 | + </DialogContent> |
| 152 | + </Dialog> |
| 153 | + </> |
35 | 154 | ); |
36 | 155 | } |
0 commit comments