|
| 1 | +import { lazy, Suspense, useCallback, useRef, useState } from "react"; |
| 2 | +import type { ChangeEvent, ReactElement } from "react"; |
| 3 | +import type { Area } from "react-easy-crop"; |
| 4 | +import type { ImageMeta } from "@metaobjectsdev/runtime-web"; |
| 5 | +import { useImageUploadAdapter } from "./image-adapter-provider.js"; |
| 6 | +import { cropToBlob } from "./crop-to-blob.js"; |
| 7 | + |
| 8 | +// react-easy-crop is an optional peer dependency — loaded lazily so consumers |
| 9 | +// who don't use <ImageUpload> never pay for it. |
| 10 | +const Cropper = lazy(() => import("react-easy-crop")); |
| 11 | + |
| 12 | +export interface ImageUploadProps { |
| 13 | + /** Current stored image key, or null/undefined when no image is set. */ |
| 14 | + value?: string | null; |
| 15 | + /** Called with the new stored image key, or null when the image is removed. */ |
| 16 | + onChange: (key: string | null) => void; |
| 17 | + /** Resolved view.image attrs (aspectRatio / maxEdge / store / accept / maxBytes). */ |
| 18 | + meta: ImageMeta; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Metadata-driven image upload + crop control. Renders a preview plus |
| 23 | + * Upload/Replace/Remove actions when idle, and a lazy-loaded crop UI |
| 24 | + * (react-easy-crop) while a picked file is being cropped. On save, crops the |
| 25 | + * selection to a bounded JPEG and hands the blob to the adapter supplied via |
| 26 | + * <ImageUploadAdapterProvider> — this component has no knowledge of the |
| 27 | + * storage backend, upload endpoint, or auth. |
| 28 | + * |
| 29 | + * Bound by the generated form's `view.image` field; usable standalone too. |
| 30 | + */ |
| 31 | +export function ImageUpload({ value, onChange, meta }: ImageUploadProps): ReactElement { |
| 32 | + const adapter = useImageUploadAdapter(); |
| 33 | + const [editing, setEditing] = useState<string | null>(null); // object URL being cropped |
| 34 | + const [crop, setCrop] = useState({ x: 0, y: 0 }); |
| 35 | + const [zoom, setZoom] = useState(1); |
| 36 | + const areaRef = useRef<Area | null>(null); |
| 37 | + const [busy, setBusy] = useState(false); |
| 38 | + const [error, setError] = useState<string | null>(null); |
| 39 | + const accept = (meta.accept ?? ["image/jpeg", "image/png", "image/webp"]).join(","); |
| 40 | + |
| 41 | + const onPick = (e: ChangeEvent<HTMLInputElement>) => { |
| 42 | + const file = e.target.files?.[0]; |
| 43 | + if (!file) return; |
| 44 | + if (meta.maxBytes && file.size > meta.maxBytes) return; // client guard; server re-enforces |
| 45 | + setError(null); |
| 46 | + setEditing(URL.createObjectURL(file)); |
| 47 | + }; |
| 48 | + |
| 49 | + const onSave = useCallback(async () => { |
| 50 | + if (!editing || !areaRef.current) return; |
| 51 | + setBusy(true); |
| 52 | + setError(null); |
| 53 | + try { |
| 54 | + const blob = await cropToBlob(editing, areaRef.current, meta.maxEdge ?? 2000); |
| 55 | + // exactOptionalPropertyTypes: only forward `store` when the caller supplied one. |
| 56 | + const { key } = await adapter.upload(blob, { ...(meta.store !== undefined && { store: meta.store }) }); |
| 57 | + onChange(key); |
| 58 | + URL.revokeObjectURL(editing); |
| 59 | + setEditing(null); |
| 60 | + } catch { |
| 61 | + // Crop/upload failed (adapter rejected the image, network drop, etc). |
| 62 | + // Leave `editing` in place so the user's crop selection isn't lost — |
| 63 | + // they can retry Save crop without re-picking the file. |
| 64 | + setError("Something went wrong saving that image. Try again."); |
| 65 | + } finally { |
| 66 | + setBusy(false); |
| 67 | + } |
| 68 | + }, [editing, meta.maxEdge, meta.store, adapter, onChange]); |
| 69 | + |
| 70 | + return ( |
| 71 | + <div className="metaobjects-image-upload"> |
| 72 | + {value && !editing && ( |
| 73 | + <img src={adapter.imageUrl(value)} alt="" className="metaobjects-image-preview" /> |
| 74 | + )} |
| 75 | + {!editing && ( |
| 76 | + <div className="metaobjects-image-actions"> |
| 77 | + <label className="metaobjects-form-submit"> |
| 78 | + {value ? "Replace" : "Upload"} |
| 79 | + <input type="file" accept={accept} onChange={onPick} hidden /> |
| 80 | + </label> |
| 81 | + {value && ( |
| 82 | + <button type="button" className="metaobjects-form-submit" onClick={() => onChange(null)}> |
| 83 | + Remove |
| 84 | + </button> |
| 85 | + )} |
| 86 | + </div> |
| 87 | + )} |
| 88 | + {editing && ( |
| 89 | + <div className="metaobjects-image-cropper"> |
| 90 | + <Suspense fallback={<p>Loading cropper…</p>}> |
| 91 | + <div style={{ position: "relative", height: 320 }}> |
| 92 | + <Cropper |
| 93 | + image={editing} |
| 94 | + crop={crop} |
| 95 | + zoom={zoom} |
| 96 | + aspect={meta.aspectRatio} |
| 97 | + onCropChange={setCrop} |
| 98 | + onZoomChange={setZoom} |
| 99 | + onCropComplete={(_croppedArea, croppedAreaPixels) => (areaRef.current = croppedAreaPixels)} |
| 100 | + /> |
| 101 | + </div> |
| 102 | + </Suspense> |
| 103 | + <div className="metaobjects-image-actions"> |
| 104 | + <button type="button" className="metaobjects-form-submit" disabled={busy} onClick={onSave}> |
| 105 | + {busy ? "Saving…" : "Save crop"} |
| 106 | + </button> |
| 107 | + <button |
| 108 | + type="button" |
| 109 | + className="metaobjects-form-submit" |
| 110 | + disabled={busy} |
| 111 | + onClick={() => { |
| 112 | + URL.revokeObjectURL(editing); |
| 113 | + setEditing(null); |
| 114 | + }} |
| 115 | + > |
| 116 | + Cancel |
| 117 | + </button> |
| 118 | + </div> |
| 119 | + {error && ( |
| 120 | + <span className="metaobjects-field-error" role="alert"> |
| 121 | + {error} |
| 122 | + </span> |
| 123 | + )} |
| 124 | + </div> |
| 125 | + )} |
| 126 | + </div> |
| 127 | + ); |
| 128 | +} |
0 commit comments