Branchwell

Lumen & Gesso / website · lumengesso.com / app / components / ImageDrop.tsx

1'use client';
2
3import { useEffect, useRef, useState, type ChangeEvent, type DragEvent } from 'react';
4import { CropModal } from './CropModal';
5import { ACCEPTED_IMAGE_ACCEPT, validateUpload } from '../lib/upload-limits';
6
7type ImageDropProps = {
8 /** Prompt heading shown in the empty state. */
9 title: string;
10 /** Prompt sub-line shown in the empty state. */
11 hint: string;
12 /** CSS aspect-ratio for the zone (default square). */
13 ratio?: string;
14 /** When true, a picked image opens the square crop tool before it's accepted. */
15 crop?: boolean;
16 /** Extra class names appended to the zone (layout/variant hooks). */
17 className?: string;
18 /**
19 * Optional pre-existing File to seed the preview from. The parent
20 * (e.g. the wizard Builder) holds the picked File in its own state,
21 * but this component unmounts when the customer navigates between
22 * steps. Passing the persisted File back in as `value` lets the
23 * preview survive that round-trip. New picks via the file input or
24 * drag-drop still go through `onChange`.
25 */
26 value?: File | null;
27 /** Receives the accepted image File. Local only — no network upload. */
28 onChange?: (file: File) => void;
29 /**
30 * When provided, a remove (×) button appears over the preview so the
31 * customer can clear the image entirely (back to the empty prompt),
32 * not just replace it. Opt-in — pet-photo slots manage their own
33 * removal at the slot level, so they leave this unset.
34 */
35 onClear?: () => void;
36};
37
38// A drag-and-drop / click-to-browse image upload zone. Accepts a single
39// image and previews it locally via an object URL. Deliberately does NOT
40// upload anywhere — the File is handed to onChange for the caller to
41// hold; wiring it to a backend is a later step. When `crop` is set, the
42// picked image is routed through the square CropModal first.
43export function ImageDrop({ title, hint, ratio = '1', crop = false, className, value, onChange, onClear }: ImageDropProps) {
44 const inputRef = useRef<HTMLInputElement>(null);
45 const [preview, setPreview] = useState<string | null>(null);
46 const [dragging, setDragging] = useState(false);
47 const [pendingCrop, setPendingCrop] = useState<File | null>(null);
48 const [error, setError] = useState<string | null>(null);
49
50 // Single source of truth for the preview object URL: the parent-held
51 // `value` File. We create the URL here, hand it to the <img>, and
52 // revoke it on cleanup. New picks (file input, drag-drop, crop output)
53 // are routed up via onChange so the parent updates state; this effect
54 // re-runs with the new File and regenerates the URL.
55 //
56 // Owning the URL lifecycle in one effect (rather than also creating
57 // URLs in finalize) is what makes the preview survive step-switch
58 // unmount/remount cycles AND React's strict-mode double-invoke
59 // (where unmount-cleanup-then-remount would otherwise leave the
60 // `<img>` pointing at a revoked URL).
61 useEffect(() => {
62 if (!value) { setPreview(null); return; }
63 const url = URL.createObjectURL(value);
64 setPreview(url);
65 return () => URL.revokeObjectURL(url);
66 }, [value]);
67
68 // Commit an accepted (already-cropped, if applicable) file. Hand it
69 // up to the parent; the value-sync effect above takes care of the
70 // preview on the next render.
71 const finalize = (file: File) => {
72 onChange?.(file);
73 };
74
75 const handleFile = (file: File | undefined | null) => {
76 if (!file) return;
77 // Enforce type (JPG/PNG only) + size (≤10MB). Mirror of the
78 // server-side check in /api/orders so the customer gets instant
79 // feedback instead of a failed submit. Rejects HEIC, WebP, GIF,
80 // oversized files, etc.
81 const validationError = validateUpload(file);
82 if (validationError) {
83 setError(validationError);
84 return;
85 }
86 setError(null);
87 if (crop) setPendingCrop(file);
88 else finalize(file);
89 };
90
91 const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
92 handleFile(e.target.files?.[0]);
93 e.target.value = ''; // allow re-picking the same file
94 };
95 const onDrop = (e: DragEvent<HTMLDivElement>) => {
96 e.preventDefault();
97 setDragging(false);
98 handleFile(e.dataTransfer.files?.[0]);
99 };
100 const openPicker = () => inputRef.current?.click();
101
102 return (
103 <>
104 <div
105 className={`imagedrop${dragging ? ' is-dragging' : ''}${preview ? ' has-image' : ''}${className ? ` ${className}` : ''}`}
106 style={{ aspectRatio: ratio }}
107 role="button"
108 tabIndex={0}
109 aria-label={title}
110 onClick={openPicker}
111 onKeyDown={(e) => {
112 if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPicker(); }
113 }}
114 onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
115 onDragLeave={() => setDragging(false)}
116 onDrop={onDrop}
117 >
118 {preview ? (
119 <>
120 {/* eslint-disable-next-line @next/next/no-img-element */}
121 <img src={preview} alt="" className="imagedrop__img" />
122 <div className="imagedrop__overlay">
123 <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
124 <path d="M3 12a9 9 0 0 1 14.8-6.9" />
125 <path d="M18 2.5V6.5h-4" />
126 <path d="M21 12a9 9 0 0 1-14.8 6.9" />
127 <path d="M6 21.5V17.5h4" />
128 </svg>
129 Replace image
130 </div>
131 {onClear && (
132 <button
133 type="button"
134 className="imagedrop__remove"
135 aria-label="Remove image"
136 onClick={(e) => {
137 // Stop the click from bubbling to the zone, which would
138 // otherwise re-open the file picker right after clearing.
139 e.stopPropagation();
140 setError(null);
141 onClear();
142 }}
143 >
144 <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
145 <path d="M3 3l6 6M9 3l-6 6" />
146 </svg>
147 </button>
148 )}
149 </>
150 ) : (
151 <div className="imagedrop__prompt">
152 <svg className="imagedrop__icon" width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
153 <path d="M12 15.5V4" />
154 <path d="m7.5 8.5 4.5-4.5 4.5 4.5" />
155 <path d="M4.5 14.5v3a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3" />
156 </svg>
157 <div className="imagedrop__title">{title}</div>
158 <div className="imagedrop__hint">{hint}</div>
159 </div>
160 )}
161 <input ref={inputRef} type="file" accept={ACCEPTED_IMAGE_ACCEPT} hidden onChange={onInputChange} />
162 </div>
163
164 {error && <p className="imagedrop__error" role="alert">{error}</p>}
165
166 {pendingCrop && (
167 <CropModal
168 file={pendingCrop}
169 onCancel={() => setPendingCrop(null)}
170 onCrop={(cropped) => { setPendingCrop(null); finalize(cropped); }}
171 />
172 )}
173 </>
174 );
175}