Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ export default function AdminUserImages({
file={avatarFile}
isWide={false}
maxFileSizeBytes={5 * 1024 * 1024}
userImageCrop={{
type: "avatar",
}}
/>
<Button
onClick={() => handleUpload("avatar")}
Expand All @@ -155,6 +158,9 @@ export default function AdminUserImages({
file={bannerFile}
isWide={true}
maxFileSizeBytes={5 * 1024 * 1024}
userImageCrop={{
type: "banner",
}}
/>
<Button
onClick={() => handleUpload("banner")}
Expand Down
33 changes: 23 additions & 10 deletions app/(website)/settings/components/UploadImageForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { UserFileUpload } from "@/lib/hooks/api/user/types";
import { useUserUpload } from "@/lib/hooks/api/user/useUserUpload";
import useSelf from "@/lib/hooks/useSelf";
import { useT } from "@/lib/i18n/utils";
import { cn } from "@/lib/utils";

type UploadImageFormProps = {
type: UserFileUpload;
Expand All @@ -18,11 +19,19 @@ type UploadImageFormProps = {
export default function UploadImageForm({ type }: UploadImageFormProps) {
const t = useT("pages.settings.components.uploadImage");
const [file, setFile] = useState<File | null>(null);
const [hasChanged, setHasChanged] = useState(false);
const [isFileUploading, setIsFileUploading] = useState(false);

const { self } = useSelf();

const { trigger: triggerUserUpload } = useUserUpload();
const { toast } = useToast();

const handleFileChange = (file: File | null) => {
setFile(file);
if (file) {
setHasChanged(true);
}
};

const localizedType = t(`types.${type}`);

Expand All @@ -33,13 +42,13 @@ export default function UploadImageForm({ type }: UploadImageFormProps) {
const urlToFetch = type === "avatar" ? self.avatar_url : self.banner_url;

fetch(urlToFetch).then(async (res) => {
const file = await res.blob();
setFile(new File([file], "file.png"));
const blob = await res.blob();
const ext = blob.type.split("/")[1] ?? "png";

setFile(new File([blob], `file.${ext}`, { type: blob.type }));
});
}, [file, self, type]);

const { toast } = useToast();

const uploadFile = async () => {
if (file === null)
return;
Expand All @@ -52,15 +61,16 @@ export default function UploadImageForm({ type }: UploadImageFormProps) {
type,
},
{
onSuccess(_data, _key, _config) {
onSuccess() {
toast({
title: t("toast.success", { type: localizedType }),
variant: "success",
className: "capitalize",
});
setIsFileUploading(false);
setHasChanged(false);
},
onError(err, _key, _config) {
onError(err) {
toast({
title: err?.message ?? t("toast.error"),
variant: "destructive",
Expand All @@ -74,16 +84,19 @@ export default function UploadImageForm({ type }: UploadImageFormProps) {
return (
<>
<ImageSelect
setFile={setFile}
setFile={handleFileChange}
file={file}
isWide={type === "banner"}
maxFileSizeBytes={5 * 1024 * 1024}
userImageCrop={{
type,
}}
/>
<Button
isLoading={isFileUploading}
onClick={uploadFile}
className="mt-2 w-40 text-sm"
variant="secondary"
className={cn("mt-2 w-40 text-sm", hasChanged && "text-black")}
variant={hasChanged ? "default" : "secondary"}
>
<CloudUpload />
{t("button", { type: localizedType })}
Expand Down
214 changes: 214 additions & 0 deletions components/General/ImageCropDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
"use client";

import { Grid, Image as ImageIcon, RotateCcw } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import type { Area } from "react-easy-crop";
import Cropper from "react-easy-crop";

import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Slider } from "@/components/ui/slider";
import { useToast } from "@/hooks/use-toast";
import { useT } from "@/lib/i18n/utils";

type ImageCropDialogProps = {
file: File | null;
type: "avatar" | "banner";
open: boolean;
onOpenChange: (open: boolean) => void;
onCropped: (file: File) => void;
};

async function getCroppedImage(
imageSrc: string,
cropAreaPixels: Area,
type: "avatar" | "banner",
): Promise<Blob> {
const bitmap = await createImageBitmap(
await fetch(imageSrc).then(r => r.blob()),
cropAreaPixels.x,
cropAreaPixels.y,
cropAreaPixels.width,
cropAreaPixels.height,
{
resizeWidth: type === "avatar" ? 512 : 2048,
resizeHeight: 512,
resizeQuality: "high",
},
);
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
canvas.getContext("bitmaprenderer")!.transferFromImageBitmap(bitmap);
bitmap.close();
return canvas.convertToBlob({
type: "image/png",
quality: 1,
});
}
const MIN_ZOOM = 1;
const MAX_ZOOM = 3;

export default function ImageCropDialog({
file,
type,
open,
onOpenChange,
onCropped,
}: ImageCropDialogProps) {
const t = useT("components.imageCropDialog");
const { toast } = useToast();

const [imageSrc, setImageSrc] = useState<string | null>(null);
const [crop, setCrop] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
const [zoom, setZoom] = useState(MIN_ZOOM);
const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [showGrid, setShowGrid] = useState(false);

const aspect = type === "avatar" ? 1 / 1 : 4 / 1;

useEffect(() => {
if (!file || !open) {
setImageSrc(null);
return;
}
const url = URL.createObjectURL(file);
setImageSrc(url);
return () => URL.revokeObjectURL(url);
}, [file, open]);

const onCropComplete = useCallback((_croppedArea: Area, croppedAreaPixelsParam: Area) => {
setCroppedAreaPixels(croppedAreaPixelsParam);
}, []);

const onDialogClose = useCallback(() => {
onOpenChange(false);
}, [onOpenChange]);

const handleSave = useCallback(async () => {
if (!imageSrc || !croppedAreaPixels || !file)
return;

try {
setIsSaving(true);
const blob = await getCroppedImage(imageSrc, croppedAreaPixels, type);
const croppedFile = new File([blob], file.name, { type: "image/png" });
onCropped(croppedFile);
onDialogClose();
}
catch (error) {
console.error("Failed to crop image", error);
toast({
title: t("cropError"),
variant: "destructive",
});
}
finally {
setIsSaving(false);
}
}, [croppedAreaPixels, file, imageSrc, onCropped, onDialogClose, type, toast, t]);

const handleReset = useCallback(() => {
setZoom(MIN_ZOOM);
setCrop({ x: 0, y: 0 });
}, []);

if (!file)
return null;

return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{type === "avatar" ? t("titleAvatar") : t("titleBanner")}</DialogTitle>
<DialogDescription>
{type === "avatar" ? t("descriptionAvatar") : t("descriptionBanner")}
</DialogDescription>
</DialogHeader>

<div className="space-y-4">
<div className="relative h-72 w-full overflow-hidden rounded-lg bg-black/60">
{imageSrc && (
<Cropper
image={imageSrc}
crop={crop}
zoom={zoom}
aspect={aspect}
cropShape={type === "avatar" ? "round" : "rect"}
showGrid={showGrid}
restrictPosition
onCropChange={setCrop}
onZoomChange={setZoom}
onCropComplete={onCropComplete}
minZoom={MIN_ZOOM}
maxZoom={MAX_ZOOM}
/>
)}
</div>

<div className="space-y-2">
<div className="flex items-center justify-center gap-2">
<ImageIcon className="size-4 text-muted-foreground" />
<Slider
min={MIN_ZOOM}
max={MAX_ZOOM}
step={0.01}
value={[zoom]}
onValueChange={value => setZoom(value[0])}
className="w-1/2"
/>
<ImageIcon className="size-6 text-muted-foreground" />
</div>

<div className="flex items-center justify-center gap-2 pt-1">
<Button
variant="ghost"
size="sm"
className="gap-1 px-2 text-muted-foreground"
onClick={() => setShowGrid(prev => !prev)}
>
{showGrid ? t("hideGrid") : t("showGrid")}
<Grid className="size-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="gap-1 px-2 text-muted-foreground"
onClick={handleReset}
>
<RotateCcw className="size-4" />
{t("reset")}
</Button>
</div>
</div>
</div>

<DialogFooter className="mt-4 gap-2">
<Button
variant="outline"
type="button"
onClick={onDialogClose}
disabled={isSaving}
>
{t("cancel")}
</Button>
<Button
type="button"
className="text-black"
onClick={handleSave}
isLoading={isSaving}
disabled={!imageSrc || !croppedAreaPixels}
>
{t("save")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
Loading
Loading