|
| 1 | +import { useCallback, useEffect, useState } from "react"; |
| 2 | +import { |
| 3 | + ArrowLeftIcon, |
| 4 | + ArrowRightIcon, |
| 5 | + StarIcon, |
| 6 | + TrashIcon, |
| 7 | +} from "@heroicons/react/24/outline"; |
| 8 | +import { StarIcon as StarSolid } from "@heroicons/react/24/solid"; |
| 9 | +import { supabase } from "../../supabase/supabaseClient"; |
| 10 | +import Spinner from "../../components/Spinner"; |
| 11 | + |
| 12 | +const BUCKET = "lego-images"; |
| 13 | +const MAX_BYTES = 5 * 1024 * 1024; // must match the bucket's 5 MB limit |
| 14 | +const ALLOWED = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp" }; |
| 15 | + |
| 16 | +// Upload, reorder, delete and choose the main photo for one set. |
| 17 | +// The main photo is automatically copied to lego_sets.image_url by a |
| 18 | +// database trigger, so shop listings and the cart always show it. |
| 19 | +export default function ImageManager({ setId }) { |
| 20 | + const [images, setImages] = useState(null); |
| 21 | + const [busy, setBusy] = useState(false); |
| 22 | + const [error, setError] = useState(null); |
| 23 | + |
| 24 | + // Fetches this set's photos in their saved order. |
| 25 | + const fetchImages = useCallback( |
| 26 | + () => |
| 27 | + supabase |
| 28 | + .from("set_images") |
| 29 | + .select("*") |
| 30 | + .eq("set_id", setId) |
| 31 | + .order("sort_order") |
| 32 | + .order("image_id"), |
| 33 | + [setId], |
| 34 | + ); |
| 35 | + |
| 36 | + async function load() { |
| 37 | + const { data, error } = await fetchImages(); |
| 38 | + if (error) setError(error.message); |
| 39 | + else setImages(data); |
| 40 | + } |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + let cancelled = false; |
| 44 | + fetchImages().then(({ data, error }) => { |
| 45 | + if (cancelled) return; |
| 46 | + if (error) setError(error.message); |
| 47 | + else setImages(data); |
| 48 | + }); |
| 49 | + return () => { |
| 50 | + cancelled = true; |
| 51 | + }; |
| 52 | + }, [fetchImages]); |
| 53 | + |
| 54 | + // Wraps each action: shows a spinner, reports errors, reloads afterwards. |
| 55 | + async function run(action) { |
| 56 | + setBusy(true); |
| 57 | + setError(null); |
| 58 | + try { |
| 59 | + await action(); |
| 60 | + } catch (err) { |
| 61 | + setError(err.message ?? String(err)); |
| 62 | + } |
| 63 | + await load(); |
| 64 | + setBusy(false); |
| 65 | + } |
| 66 | + |
| 67 | + function handleUpload(e) { |
| 68 | + const files = Array.from(e.target.files ?? []); |
| 69 | + e.target.value = ""; // allow picking the same file again later |
| 70 | + if (files.length === 0) return; |
| 71 | + |
| 72 | + const bad = files.find((f) => !ALLOWED[f.type] || f.size > MAX_BYTES); |
| 73 | + if (bad) { |
| 74 | + setError(`"${bad.name}" must be a JPG, PNG or WebP image under 5 MB.`); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + run(async () => { |
| 79 | + let nextOrder = images.reduce((m, i) => Math.max(m, i.sort_order), -1) + 1; |
| 80 | + let needsPrimary = !images.some((i) => i.is_primary); |
| 81 | + |
| 82 | + for (const file of files) { |
| 83 | + const path = `sets/${setId}/${crypto.randomUUID()}.${ALLOWED[file.type]}`; |
| 84 | + const { error: upErr } = await supabase.storage |
| 85 | + .from(BUCKET) |
| 86 | + .upload(path, file, { contentType: file.type, cacheControl: "31536000" }); |
| 87 | + if (upErr) throw upErr; |
| 88 | + |
| 89 | + const { data: pub } = supabase.storage.from(BUCKET).getPublicUrl(path); |
| 90 | + const { error: dbErr } = await supabase.from("set_images").insert({ |
| 91 | + set_id: setId, |
| 92 | + url: pub.publicUrl, |
| 93 | + storage_path: path, |
| 94 | + sort_order: nextOrder++, |
| 95 | + is_primary: needsPrimary, |
| 96 | + }); |
| 97 | + if (dbErr) { |
| 98 | + // Don't leave an orphaned file behind. |
| 99 | + await supabase.storage.from(BUCKET).remove([path]); |
| 100 | + throw dbErr; |
| 101 | + } |
| 102 | + needsPrimary = false; |
| 103 | + } |
| 104 | + }); |
| 105 | + } |
| 106 | + |
| 107 | + function makeMain(image) { |
| 108 | + run(async () => { |
| 109 | + // Only one main photo per set is allowed, so clear the old one first. |
| 110 | + const { error: clearErr } = await supabase |
| 111 | + .from("set_images") |
| 112 | + .update({ is_primary: false }) |
| 113 | + .eq("set_id", setId) |
| 114 | + .eq("is_primary", true); |
| 115 | + if (clearErr) throw clearErr; |
| 116 | + const { error } = await supabase |
| 117 | + .from("set_images") |
| 118 | + .update({ is_primary: true }) |
| 119 | + .eq("image_id", image.image_id); |
| 120 | + if (error) throw error; |
| 121 | + }); |
| 122 | + } |
| 123 | + |
| 124 | + // Swap a photo with its neighbour (-1 = left, +1 = right). |
| 125 | + function move(index, direction) { |
| 126 | + const other = images[index + direction]; |
| 127 | + const image = images[index]; |
| 128 | + if (!other) return; |
| 129 | + run(async () => { |
| 130 | + // Renumber everything in the new order so ties can't happen. |
| 131 | + const order = [...images]; |
| 132 | + order[index] = other; |
| 133 | + order[index + direction] = image; |
| 134 | + for (let i = 0; i < order.length; i++) { |
| 135 | + if (order[i].sort_order !== i) { |
| 136 | + const { error } = await supabase |
| 137 | + .from("set_images") |
| 138 | + .update({ sort_order: i }) |
| 139 | + .eq("image_id", order[i].image_id); |
| 140 | + if (error) throw error; |
| 141 | + } |
| 142 | + } |
| 143 | + }); |
| 144 | + } |
| 145 | + |
| 146 | + function remove(image) { |
| 147 | + if (!window.confirm("Delete this photo?")) return; |
| 148 | + run(async () => { |
| 149 | + const { error } = await supabase |
| 150 | + .from("set_images") |
| 151 | + .delete() |
| 152 | + .eq("image_id", image.image_id); |
| 153 | + if (error) throw error; |
| 154 | + |
| 155 | + // Older photos can be shared between sets (e.g. one theme picture), |
| 156 | + // so only delete the file if nothing else still uses it. |
| 157 | + if (image.storage_path) { |
| 158 | + const { count } = await supabase |
| 159 | + .from("set_images") |
| 160 | + .select("image_id", { count: "exact", head: true }) |
| 161 | + .eq("storage_path", image.storage_path); |
| 162 | + if (count === 0) { |
| 163 | + await supabase.storage.from(BUCKET).remove([image.storage_path]); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + // If the main photo was deleted, promote the next one. |
| 168 | + if (image.is_primary) { |
| 169 | + const next = images.find((i) => i.image_id !== image.image_id); |
| 170 | + if (next) { |
| 171 | + await supabase.from("set_images").update({ is_primary: true }).eq("image_id", next.image_id); |
| 172 | + } |
| 173 | + } |
| 174 | + }); |
| 175 | + } |
| 176 | + |
| 177 | + if (!images) { |
| 178 | + return error ? <p className="text-red-600">{error}</p> : <Spinner />; |
| 179 | + } |
| 180 | + |
| 181 | + return ( |
| 182 | + <div> |
| 183 | + <p className="text-sm text-gray-500 mb-4"> |
| 184 | + JPG, PNG or WebP, up to 5 MB each. The ★ photo is the main one shown in the shop. |
| 185 | + </p> |
| 186 | + |
| 187 | + {error && <p className="mb-4 rounded-md bg-red-50 text-red-700 px-4 py-2">{error}</p>} |
| 188 | + |
| 189 | + <ul className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4 mb-4"> |
| 190 | + {images.map((img, index) => ( |
| 191 | + <li |
| 192 | + key={img.image_id} |
| 193 | + className={`relative rounded-lg border-2 p-2 bg-gray-50 ${ |
| 194 | + img.is_primary ? "border-red-500" : "border-transparent" |
| 195 | + }`} |
| 196 | + > |
| 197 | + <img src={img.url} alt="" className="w-full aspect-square object-contain" /> |
| 198 | + <div className="flex justify-between items-center mt-2"> |
| 199 | + <button |
| 200 | + type="button" |
| 201 | + title="Move left" |
| 202 | + disabled={busy || index === 0} |
| 203 | + onClick={() => move(index, -1)} |
| 204 | + className="p-1 rounded hover:bg-gray-200 disabled:opacity-30" |
| 205 | + > |
| 206 | + <ArrowLeftIcon className="h-5 w-5" /> |
| 207 | + </button> |
| 208 | + <button |
| 209 | + type="button" |
| 210 | + title={img.is_primary ? "Main photo" : "Make main photo"} |
| 211 | + disabled={busy || img.is_primary} |
| 212 | + onClick={() => makeMain(img)} |
| 213 | + className="p-1 rounded hover:bg-gray-200" |
| 214 | + > |
| 215 | + {img.is_primary ? ( |
| 216 | + <StarSolid className="h-5 w-5 text-red-500" /> |
| 217 | + ) : ( |
| 218 | + <StarIcon className="h-5 w-5" /> |
| 219 | + )} |
| 220 | + </button> |
| 221 | + <button |
| 222 | + type="button" |
| 223 | + title="Delete photo" |
| 224 | + disabled={busy} |
| 225 | + onClick={() => remove(img)} |
| 226 | + className="p-1 rounded hover:bg-red-100 text-red-600" |
| 227 | + > |
| 228 | + <TrashIcon className="h-5 w-5" /> |
| 229 | + </button> |
| 230 | + <button |
| 231 | + type="button" |
| 232 | + title="Move right" |
| 233 | + disabled={busy || index === images.length - 1} |
| 234 | + onClick={() => move(index, 1)} |
| 235 | + className="p-1 rounded hover:bg-gray-200 disabled:opacity-30" |
| 236 | + > |
| 237 | + <ArrowRightIcon className="h-5 w-5" /> |
| 238 | + </button> |
| 239 | + </div> |
| 240 | + </li> |
| 241 | + ))} |
| 242 | + </ul> |
| 243 | + |
| 244 | + <label |
| 245 | + className={`inline-flex items-center gap-2 rounded-xl px-4 py-2 font-semibold text-white bg-red-600 hover:bg-red-700 cursor-pointer ${ |
| 246 | + busy ? "opacity-50 pointer-events-none" : "" |
| 247 | + }`} |
| 248 | + > |
| 249 | + {busy ? <Spinner size="h-4 w-4" /> : "+"} Add photos |
| 250 | + <input |
| 251 | + type="file" |
| 252 | + accept="image/jpeg,image/png,image/webp" |
| 253 | + multiple |
| 254 | + onChange={handleUpload} |
| 255 | + className="sr-only" |
| 256 | + /> |
| 257 | + </label> |
| 258 | + </div> |
| 259 | + ); |
| 260 | +} |
0 commit comments