Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨Allow cropping image before uploading (#1892)

Luke Vella5acf128e3881
diff --git a/apps/web/package.json b/apps/web/package.json
index f493a3b22..211872b98 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -93,6 +93,7 @@
"react-hook-form": "^7.42.1",
"react-hook-form-persist": "^3.0.0",
"react-i18next": "^15.5.1",
+ "react-image-crop": "^11.0.10",
"react-remove-scroll": "^2.5.6",
"react-use": "^17.6.0",
"smoothscroll-polyfill": "^0.4.4",
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 6ac44f60c..8a47e2cbd 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -465,5 +465,7 @@
"loading": "Loading...",
"endOfList": "You've reached the end of the list",
"attendeeCount": "{count, plural, =0 {No attendees} one {1 attendee} other {# attendees}}",
- "participantCount": "{count, plural, one {1 participant} other {# participants}}"
+ "participantCount": "{count, plural, one {1 participant} other {# participants}}",
+ "imageCropDialogTitle": "Crop Image",
+ "cropPreview": "Crop preview"
}
diff --git a/apps/web/src/components/image-upload.tsx b/apps/web/src/components/image-upload.tsx
deleted file mode 100644
index 3bef00945..000000000
--- a/apps/web/src/components/image-upload.tsx
+++ /dev/null
@@ -1,178 +0,0 @@
-"use client";
-
-import { cn } from "@rallly/ui";
-import { Button } from "@rallly/ui/button";
-import { toast } from "@rallly/ui/sonner";
-import React from "react";
-import { z } from "zod";
-import { Trans } from "@/components/trans";
-import { useTranslation } from "@/i18n/client";
-import { useFeatureFlag } from "@/lib/feature-flags/client";
-import { useSafeAction } from "@/lib/safe-action/client";
-import { getImageUploadUrlAction } from "@/lib/storage/actions";
-import { uploadImage } from "@/lib/storage/image-upload";
-
-const allowedMimeTypes = z.enum(["image/jpeg", "image/png"]);
-
-export interface ImageUploadControlProps {
- keyPrefix: "avatars" | "spaces";
- onUploadSuccess: (imageKey: string) => Promise<void> | void;
- onRemoveSuccess: () => Promise<void> | void;
- hasCurrentImage?: boolean;
-}
-
-export interface ImageUploadPreviewProps {
- className?: string;
- children?: React.ReactNode;
-}
-
-export function ImageUpload({
- className,
- children,
-}: {
- className?: string;
- children?: React.ReactNode;
-}) {
- return (
- <div className={cn("flex items-center gap-x-4", className)}>{children}</div>
- );
-}
-
-export function ImageUploadControl({
- keyPrefix,
- onUploadSuccess,
- onRemoveSuccess,
- hasCurrentImage = false,
-}: ImageUploadControlProps) {
- const isStorageEnabled = useFeatureFlag("storage");
-
- const { t } = useTranslation();
- const [isRemoving, startRemoving] = React.useTransition();
- const [isUploading, startUploading] = React.useTransition();
- const getUploadUrl = useSafeAction(getImageUploadUrlAction);
-
- const handleFileChange = async (
- event: React.ChangeEvent<HTMLInputElement>,
- ) => {
- const file = event.target.files?.[0];
-
- if (!file) return;
-
- const parsedFileType = allowedMimeTypes.safeParse(file.type);
-
- if (!parsedFileType.success) {
- toast.message(
- t("invalidFileType", {
- defaultValue: "Invalid file type",
- }),
- {
- description: t("invalidFileTypeDescription", {
- defaultValue: "Please upload a JPG or PNG file.",
- }),
- },
- );
- return;
- }
-
- const fileType = parsedFileType.data;
-
- if (file.size > 2 * 1024 * 1024) {
- toast.message(
- t("fileTooLarge", {
- defaultValue: "File too large",
- }),
- {
- description: t("fileTooLargeDescription", {
- defaultValue: "Please upload a file smaller than 2MB.",
- }),
- },
- );
- return;
- }
-
- startUploading(async () => {
- try {
- const result = await getUploadUrl.executeAsync({
- keyPrefix,
- fileType,
- fileSize: file.size,
- });
-
- if (!result.data) {
- throw new Error("Failed to get upload URL");
- }
-
- const { url, fields } = result.data;
-
- await uploadImage({
- file,
- url,
- fileType,
- });
-
- onUploadSuccess(fields.key);
- } catch {
- toast.error(
- t("errorUploadPicture", {
- defaultValue: "Failed to upload",
- }),
- {
- description: t("errorUploadPictureDescription", {
- defaultValue:
- "There was an issue uploading your picture. Please try again later.",
- }),
- },
- );
- }
- });
- };
-
- const handleRemove = async () => {
- startRemoving(async () => {
- await onRemoveSuccess();
- });
- };
-
- return (
- <div className="flex flex-col gap-y-2">
- <div className="flex gap-2">
- <Button
- loading={isUploading}
- disabled={!isStorageEnabled}
- onClick={() => {
- document.getElementById("image-upload")?.click();
- }}
- >
- <Trans i18nKey="uploadImage" defaults="Upload" />
- </Button>
- {hasCurrentImage ? (
- <Button loading={isRemoving} variant="ghost" onClick={handleRemove}>
- <Trans i18nKey="removeImage" defaults="Remove" />
- </Button>
- ) : null}
- </div>
- <p className="text-muted-foreground text-xs">
- <Trans
- i18nKey="imageUploadDescription"
- defaults="Up to 2MB, JPG or PNG"
- />
- </p>
- <input
- id="image-upload"
- type="file"
- accept="image/*"
- onChange={handleFileChange}
- className="hidden"
- />
- </div>
- );
-}
-
-export function ImageUploadPreview({
- className,
- children,
-}: ImageUploadPreviewProps) {
- return (
- <div className={cn("relative overflow-hidden", className)}>{children}</div>
- );
-}
diff --git a/apps/web/src/components/image-upload/image-crop-dialog.tsx b/apps/web/src/components/image-upload/image-crop-dialog.tsx
new file mode 100644
index 000000000..bca0d7de3
--- /dev/null
+++ b/apps/web/src/components/image-upload/image-crop-dialog.tsx
@@ -0,0 +1,139 @@
+"use client";
+
+import { Button } from "@rallly/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@rallly/ui/dialog";
+import React from "react";
+import type { Crop, PixelCrop } from "react-image-crop";
+import ReactCrop, { centerCrop, makeAspectCrop } from "react-image-crop";
+import "react-image-crop/dist/ReactCrop.css";
+import { Trans } from "@/components/trans";
+import { useTranslation } from "@/i18n/client";
+import { getCroppedImg } from "@/lib/image-processing";
+
+export interface ImageCropDialogProps {
+ /** Whether the dialog is open */
+ open: boolean;
+ /** Image URL to crop */
+ imageSrc: string | null;
+ /** Original file being cropped */
+ originalFile: File | null;
+ /** Loading state during upload */
+ isUploading?: boolean;
+ /** Callback when dialog should close */
+ onClose: () => void;
+ /** Callback when crop is complete with the cropped file */
+ onCropComplete: (croppedFile: File) => Promise<void>;
+}
+
+export function ImageCropDialog({
+ open,
+ imageSrc,
+ originalFile,
+ isUploading = false,
+ onClose,
+ onCropComplete,
+}: ImageCropDialogProps) {
+ const { t } = useTranslation();
+ const [crop, setCrop] = React.useState<Crop>();
+ const [completedCrop, setCompletedCrop] = React.useState<PixelCrop>();
+ const imgRef = React.useRef<HTMLImageElement>(null);
+
+ const onImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
+ const { width, height } = e.currentTarget;
+ const crop = centerCrop(
+ makeAspectCrop(
+ {
+ unit: "%",
+ width: 90,
+ },
+ 1, // 1:1 aspect ratio
+ width,
+ height,
+ ),
+ width,
+ height,
+ );
+ setCrop(crop);
+ };
+
+ const handleCropComplete = async () => {
+ if (!completedCrop || !imgRef.current || !originalFile) return;
+
+ try {
+ const croppedFile = await getCroppedImg(
+ imgRef.current,
+ completedCrop,
+ originalFile.name,
+ originalFile.type,
+ );
+
+ await onCropComplete(croppedFile);
+ } catch (error) {
+ console.error("Failed to crop image:", error);
+ throw error; // Re-throw to let parent handle the error
+ }
+ };
+
+ // Reset crop state when dialog opens/closes
+ React.useEffect(() => {
+ if (!open) {
+ setCrop(undefined);
+ setCompletedCrop(undefined);
+ }
+ }, [open]);
+
+ return (
+ <Dialog open={open} onOpenChange={onClose}>
+ <DialogContent className="w-fit">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="imageCropDialogTitle" defaults="Crop Image" />
+ </DialogTitle>
+ </DialogHeader>
+
+ {imageSrc && (
+ <div className="flex justify-center">
+ <ReactCrop
+ crop={crop}
+ onChange={(_, percentCrop) => setCrop(percentCrop)}
+ onComplete={(c) => setCompletedCrop(c)}
+ aspect={1}
+ minWidth={100}
+ minHeight={100}
+ className="max-h-96"
+ >
+ {/* biome-ignore lint/performance/noImgElement: required for react-image-crop */}
+ <img
+ ref={imgRef}
+ alt={t("cropPreview", {
+ defaultValue: "Crop preview",
+ })}
+ src={imageSrc}
+ onLoad={onImageLoad}
+ className="max-h-96 max-w-full"
+ />
+ </ReactCrop>
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button
+ variant="primary"
+ className="w-full"
+ loading={isUploading}
+ onClick={handleCropComplete}
+ disabled={!completedCrop}
+ >
+ <Trans i18nKey="uploadImage" defaults="Crop & Upload" />
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/components/image-upload/image-upload.tsx b/apps/web/src/components/image-upload/image-upload.tsx
new file mode 100644
index 000000000..ea8c78722
--- /dev/null
+++ b/apps/web/src/components/image-upload/image-upload.tsx
@@ -0,0 +1,223 @@
+"use client";
+
+import { cn } from "@rallly/ui";
+import { Button } from "@rallly/ui/button";
+import { toast } from "@rallly/ui/sonner";
+import React from "react";
+import { ImageCropDialog } from "@/components/image-upload/image-crop-dialog";
+import type {
+ ImageUploadControlProps,
+ ImageUploadPreviewProps,
+ ImageUploadProps,
+} from "@/components/image-upload/types";
+import { allowedMimeTypes } from "@/components/image-upload/types";
+import { Trans } from "@/components/trans";
+import { useTranslation } from "@/i18n/client";
+import { useFeatureFlag } from "@/lib/feature-flags/client";
+import {
+ createImagePreviewUrl,
+ validateImageFile,
+} from "@/lib/image-processing";
+import { useSafeAction } from "@/lib/safe-action/client";
+import { getImageUploadUrlAction } from "@/lib/storage/actions";
+import { uploadImage } from "@/lib/storage/image-upload";
+
+export function ImageUpload({ className, children }: ImageUploadProps) {
+ return (
+ <div className={cn("flex items-center gap-x-4", className)}>{children}</div>
+ );
+}
+
+export function ImageUploadControl({
+ keyPrefix,
+ onUploadSuccess,
+ onRemoveSuccess,
+ hasCurrentImage = false,
+}: ImageUploadControlProps) {
+ const isStorageEnabled = useFeatureFlag("storage");
+
+ const { t } = useTranslation();
+ const [isRemoving, startRemoving] = React.useTransition();
+ const [isUploading, startUploading] = React.useTransition();
+ const getUploadUrl = useSafeAction(getImageUploadUrlAction);
+
+ // Cropping state
+ const [showCropDialog, setShowCropDialog] = React.useState(false);
+ const [imageToCrop, setImageToCrop] = React.useState<string | null>(null);
+ const [originalFile, setOriginalFile] = React.useState<File | null>(null);
+ const [imagePreviewCleanup, setImagePreviewCleanup] = React.useState<
+ (() => void) | null
+ >(null);
+
+ // File input ref to avoid ID collisions
+ const fileInputRef = React.useRef<HTMLInputElement>(null);
+
+ const handleFileChange = async (
+ event: React.ChangeEvent<HTMLInputElement>,
+ ) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+
+ // Validate the file
+ const validation = validateImageFile(file);
+ if (!validation.success) {
+ switch (validation.error) {
+ case "invalidFileType":
+ toast.message(
+ t("invalidFileType", {
+ defaultValue: "Invalid file type",
+ }),
+ {
+ description: t("invalidFileTypeDescription", {
+ defaultValue: "Please upload a JPG or PNG file.",
+ }),
+ },
+ );
+ break;
+ case "fileTooLarge":
+ toast.message(
+ t("fileTooLarge", {
+ defaultValue: "File too large",
+ }),
+ {
+ description: t("fileTooLargeDescription", {
+ defaultValue: "Please upload a file smaller than 2MB.",
+ }),
+ },
+ );
+ break;
+ default: {
+ // Exhaustive check - this should never happen
+ const _exhaustive: never = validation.error;
+ throw new Error(`Unhandled validation error: ${_exhaustive}`);
+ }
+ }
+ return;
+ }
+
+ // Create preview URL and show cropping dialog
+ const { url, cleanup } = createImagePreviewUrl(file);
+ setOriginalFile(file);
+ setImageToCrop(url);
+ setImagePreviewCleanup(() => cleanup);
+ setShowCropDialog(true);
+
+ // Reset the input
+ event.target.value = "";
+ };
+
+ const handleCropComplete = async (croppedFile: File) => {
+ if (!originalFile) return;
+
+ const parsedFileType = allowedMimeTypes.parse(croppedFile.type);
+
+ startUploading(async () => {
+ try {
+ const result = await getUploadUrl.executeAsync({
+ keyPrefix,
+ fileType: parsedFileType,
+ fileSize: croppedFile.size,
+ });
+
+ if (!result.data) {
+ throw new Error("Failed to get upload URL");
+ }
+
+ const { url, fields } = result.data;
+
+ await uploadImage({
+ file: croppedFile,
+ url,
+ fileType: parsedFileType,
+ });
+
+ onUploadSuccess(fields.key);
+ handleCloseCropDialog();
+ } catch {
+ toast.error(
+ t("errorUploadPicture", {
+ defaultValue: "Failed to upload",
+ }),
+ {
+ description: t("errorUploadPictureDescription", {
+ defaultValue:
+ "There was an issue uploading your picture. Please try again later.",
+ }),
+ },
+ );
+ }
+ });
+ };
+
+ const handleCloseCropDialog = () => {
+ setShowCropDialog(false);
+ setImageToCrop(null);
+ setOriginalFile(null);
+
+ // Cleanup the image preview URL
+ if (imagePreviewCleanup) {
+ imagePreviewCleanup();
+ setImagePreviewCleanup(null);
+ }
+ };
+
+ const handleRemove = async () => {
+ startRemoving(async () => {
+ await onRemoveSuccess();
+ });
+ };
+
+ return (
+ <>
+ <div className="flex flex-col gap-y-2">
+ <div className="flex gap-2">
+ <Button
+ loading={isUploading}
+ disabled={!isStorageEnabled}
+ onClick={() => {
+ fileInputRef.current?.click();
+ }}
+ >
+ <Trans i18nKey="uploadImage" defaults="Upload" />
+ </Button>
+ {hasCurrentImage ? (
+ <Button loading={isRemoving} variant="ghost" onClick={handleRemove}>
+ <Trans i18nKey="removeImage" defaults="Remove" />
+ </Button>
+ ) : null}
+ </div>
+ <p className="text-muted-foreground text-xs">
+ <Trans
+ i18nKey="imageUploadDescription"
+ defaults="Up to 2MB, JPG or PNG"
+ />
+ </p>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ onChange={handleFileChange}
+ className="hidden"
+ />
+ </div>
+
+ <ImageCropDialog
+ open={showCropDialog}
+ imageSrc={imageToCrop}
+ originalFile={originalFile}
+ isUploading={isUploading}
+ onClose={handleCloseCropDialog}
+ onCropComplete={handleCropComplete}
+ />
+ </>
+ );
+}
+
+export function ImageUploadPreview({
+ className,
+ children,
+}: ImageUploadPreviewProps) {
+ return (
+ <div className={cn("relative overflow-hidden", className)}>{children}</div>
+ );
+}
diff --git a/apps/web/src/components/image-upload/index.ts b/apps/web/src/components/image-upload/index.ts
new file mode 100644
index 000000000..0d0b9c263
--- /dev/null
+++ b/apps/web/src/components/image-upload/index.ts
@@ -0,0 +1 @@
+export * from "./image-upload";
diff --git a/apps/web/src/components/image-upload/types.ts b/apps/web/src/components/image-upload/types.ts
new file mode 100644
index 000000000..635e8bab3
--- /dev/null
+++ b/apps/web/src/components/image-upload/types.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+
+export const allowedMimeTypes = z.enum(["image/jpeg", "image/png"]);
+export type AllowedMimeType = z.infer<typeof allowedMimeTypes>;
+
+export interface ImageUploadControlProps {
+ keyPrefix: "avatars" | "spaces";
+ onUploadSuccess: (imageKey: string) => Promise<void> | void;
+ onRemoveSuccess: () => Promise<void> | void;
+ hasCurrentImage?: boolean;
+}
+
+export interface ImageUploadPreviewProps {
+ className?: string;
+ children?: React.ReactNode;
+}
+
+export interface ImageUploadProps {
+ className?: string;
+ children?: React.ReactNode;
+}
diff --git a/apps/web/src/lib/image-processing.ts b/apps/web/src/lib/image-processing.ts
new file mode 100644
index 000000000..536b4850c
--- /dev/null
+++ b/apps/web/src/lib/image-processing.ts
@@ -0,0 +1,224 @@
+import type { PixelCrop } from "react-image-crop";
+
+// Configuration for image optimization
+export const IMAGE_OPTIMIZATION = {
+ // Maximum dimensions for the output image
+ MAX_WIDTH: 800,
+ MAX_HEIGHT: 800,
+ // JPEG quality (0.1 to 1.0, higher = better quality but larger size)
+ JPEG_QUALITY: 0.85,
+ // PNG quality (0.1 to 1.0)
+ PNG_QUALITY: 0.9,
+ // Convert PNG to JPEG if the result is significantly smaller
+ CONVERT_PNG_TO_JPEG_THRESHOLD: 0.7,
+} as const;
+
+/**
+ * Converts a cropped image to an optimized file with compression and format selection
+ * @param image - The source image element
+ * @param crop - The crop coordinates
+ * @param fileName - Original filename
+ * @param fileType - Original file MIME type
+ * @returns Promise resolving to optimized File
+ */
+export function getCroppedImg(
+ image: HTMLImageElement,
+ crop: PixelCrop,
+ fileName: string,
+ fileType: string,
+): Promise<File> {
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+ if (!ctx) {
+ throw new Error("No 2d context");
+ }
+
+ const scaleX = image.naturalWidth / image.width;
+ const scaleY = image.naturalHeight / image.height;
+
+ // Calculate the actual crop dimensions
+ const cropWidth = crop.width * scaleX;
+ const cropHeight = crop.height * scaleY;
+
+ // Calculate optimized dimensions while maintaining aspect ratio
+ const aspectRatio = cropWidth / cropHeight;
+ let outputWidth = cropWidth;
+ let outputHeight = cropHeight;
+
+ // Resize if the image is larger than our maximum dimensions
+ if (
+ outputWidth > IMAGE_OPTIMIZATION.MAX_WIDTH ||
+ outputHeight > IMAGE_OPTIMIZATION.MAX_HEIGHT
+ ) {
+ if (aspectRatio > 1) {
+ // Width is the constraining dimension
+ outputWidth = Math.min(IMAGE_OPTIMIZATION.MAX_WIDTH, outputWidth);
+ outputHeight = outputWidth / aspectRatio;
+ } else {
+ // Height is the constraining dimension
+ outputHeight = Math.min(IMAGE_OPTIMIZATION.MAX_HEIGHT, outputHeight);
+ outputWidth = outputHeight * aspectRatio;
+ }
+ }
+
+ // Set canvas dimensions to the optimized size
+ canvas.width = outputWidth;
+ canvas.height = outputHeight;
+
+ // Enable high-quality image scaling
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = "high";
+
+ // Draw the cropped and resized image
+ ctx.drawImage(
+ image,
+ crop.x * scaleX,
+ crop.y * scaleY,
+ cropWidth,
+ cropHeight,
+ 0,
+ 0,
+ outputWidth,
+ outputHeight,
+ );
+
+ return new Promise((resolve, reject) => {
+ // Function to create file with given type and quality
+ const createFile = (mimeType: string, quality: number, suffix = "") => {
+ canvas.toBlob(
+ (blob) => {
+ if (!blob) {
+ reject(new Error("Canvas is empty"));
+ return;
+ }
+ const newFileName = `${fileName.replace(/\.[^/.]+$/, "")}${suffix}.${mimeType.split("/")[1]}`;
+ const file = new File([blob], newFileName, {
+ type: mimeType,
+ lastModified: Date.now(),
+ });
+ resolve(file);
+ },
+ mimeType,
+ quality,
+ );
+ };
+
+ // Optimize based on original file type
+ if (fileType === "image/jpeg") {
+ createFile("image/jpeg", IMAGE_OPTIMIZATION.JPEG_QUALITY);
+ } else if (fileType === "image/png") {
+ // For PNG files, we'll compare PNG vs JPEG compression
+ // First create a JPEG version
+ canvas.toBlob(
+ (jpegBlob) => {
+ if (!jpegBlob) {
+ // Fallback to PNG if JPEG creation fails
+ createFile("image/png", IMAGE_OPTIMIZATION.PNG_QUALITY);
+ return;
+ }
+
+ // Create PNG version
+ canvas.toBlob(
+ (pngBlob) => {
+ if (!pngBlob) {
+ // Use the JPEG if PNG creation fails
+ const jpegFileName = `${fileName.replace(/\.[^/.]+$/, "")}.jpg`;
+ const jpegFile = new File([jpegBlob], jpegFileName, {
+ type: "image/jpeg",
+ lastModified: Date.now(),
+ });
+ resolve(jpegFile);
+ return;
+ }
+
+ // Compare file sizes and use the more efficient format
+ const jpegSize = jpegBlob.size;
+ const pngSize = pngBlob.size;
+
+ if (
+ jpegSize <
+ pngSize * IMAGE_OPTIMIZATION.CONVERT_PNG_TO_JPEG_THRESHOLD
+ ) {
+ // JPEG is significantly smaller, use it
+ const jpegFileName = `${fileName.replace(/\.[^/.]+$/, "")}.jpg`;
+ const jpegFile = new File([jpegBlob], jpegFileName, {
+ type: "image/jpeg",
+ lastModified: Date.now(),
+ });
+ resolve(jpegFile);
+ } else {
+ // PNG is more efficient or the difference isn't significant
+ const pngFile = new File([pngBlob], fileName, {
+ type: "image/png",
+ lastModified: Date.now(),
+ });
+ resolve(pngFile);
+ }
+ },
+ "image/png",
+ IMAGE_OPTIMIZATION.PNG_QUALITY,
+ );
+ },
+ "image/jpeg",
+ IMAGE_OPTIMIZATION.JPEG_QUALITY,
+ );
+ } else {
+ // For other formats, default to JPEG
+ createFile("image/jpeg", IMAGE_OPTIMIZATION.JPEG_QUALITY, "_optimized");
+ }
+ });
+}
+
+/**
+ * Creates an object URL from a File and provides cleanup functionality
+ * @param file - The file to create URL for
+ * @returns Object with URL and cleanup function
+ */
+export function createImagePreviewUrl(file: File) {
+ const url = URL.createObjectURL(file);
+ const cleanup = () => URL.revokeObjectURL(url);
+ return { url, cleanup };
+}
+
+export type ImageValidationErrorCode = "invalidFileType" | "fileTooLarge";
+
+export interface ImageValidationSuccess {
+ success: true;
+}
+
+export interface ImageValidationError {
+ success: false;
+ error: ImageValidationErrorCode;
+ description: string;
+}
+
+export type ImageValidationResult =
+ | ImageValidationSuccess
+ | ImageValidationError;
+
+/**
+ * Validates if a file is an allowed image type
+ * @param file - File to validate
+ * @returns Object with success boolean and optional error message
+ */
+export function validateImageFile(file: File): ImageValidationResult {
+ const allowedMimeTypes = ["image/jpeg", "image/png"];
+
+ if (!allowedMimeTypes.includes(file.type)) {
+ return {
+ success: false,
+ error: "invalidFileType",
+ description: "Please upload a JPG or PNG file.",
+ };
+ }
+
+ if (file.size > 2 * 1024 * 1024) {
+ return {
+ success: false,
+ error: "fileTooLarge",
+ description: "Please upload a file smaller than 2MB.",
+ };
+ }
+
+ return { success: true };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 923ae7816..5da15a2e8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -80,7 +80,7 @@ importers:
version: 8.1.0([email protected])
'@vercel/analytics':
specifier: ^1.5.0
dayjs:
specifier: ^1.11.13
version: 1.11.13
@@ -119,7 +119,7 @@ importers:
next-seo:
specifier: ^6.1.0
react:
specifier: ^19.1.0
version: 19.1.0
@@ -394,6 +394,9 @@ importers:
react-i18next:
specifier: ^15.5.1
+ react-image-crop:
+ specifier: ^11.0.10
+ version: 11.0.10([email protected])
react-remove-scroll:
specifier: ^2.5.6
version: 2.6.3(@types/[email protected])([email protected])
@@ -7766,6 +7769,11 @@ packages:
typescript:
optional: true
+ resolution: {integrity: sha512-+5FfDXUgYLLqBh1Y/uQhIycpHCbXkI50a+nbfkB1C0xXXUTwkisHDo2QCB1SQJyHCqIuia4FeyReqXuMDKWQTQ==}
+ peerDependencies:
+ react: '>=16.13.1'
+
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
@@ -13649,7 +13657,7 @@ snapshots:
dependencies:
crypto-js: 4.2.0
optionalDependencies:
react: 19.1.0
@@ -16788,7 +16796,7 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
dependencies:
react: 19.1.0
@@ -17395,6 +17403,10 @@ snapshots:
react-dom: 19.1.0([email protected])
typescript: 5.8.3
+ dependencies:
+ react: 19.1.0
+