refactor crop modal

This commit is contained in:
nflnkr 2023-10-19 17:11:07 +03:00
parent 00a250c676
commit ed920affbc

@ -1,66 +1,27 @@
import React, { useState, useRef, useEffect, FC } from "react";
import ReactCrop, { Crop, PixelCrop } from "react-image-crop";
import { import {
Box, Box,
Button, Button,
IconButton,
Modal, Modal,
Slider, Slider,
SxProps,
Theme,
Typography, Typography,
useMediaQuery, useMediaQuery,
useTheme, useTheme,
} from "@mui/material"; } from "@mui/material";
import React, { FC, useEffect, useRef, useState } from "react";
import ReactCrop, { Crop, PixelCrop } from "react-image-crop";
import { canvasPreview } from "./utils/canvasPreview"; import { canvasPreview } from "./utils/canvasPreview";
import { useDebounceEffect } from "./utils/useDebounceEffect";
import { ResetIcon } from "@icons/ResetIcon"; import { ResetIcon } from "@icons/ResetIcon";
import "react-image-crop/dist/ReactCrop.css";
import { CropIcon } from "@icons/CropIcon"; import { CropIcon } from "@icons/CropIcon";
import "react-image-crop/dist/ReactCrop.css";
interface Iprops {
opened: boolean;
onClose: React.Dispatch<React.SetStateAction<boolean>>;
picture?: string;
onCropPress?: (imageUrl: string) => void;
}
export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress }) => { const styleSlider: SxProps<Theme> = {
const [imgSrc, setImgSrc] = useState("");
const imgRef = useRef<HTMLImageElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const previewCanvasRef = useRef<HTMLCanvasElement>(null);
const hiddenAnchorRef = useRef<HTMLAnchorElement>(null);
const blobUrlRef = useRef("");
const [crop, setCrop] = useState<Crop>();
const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
const [rotate, setRotate] = useState(0);
const [darken, setDarken] = useState(0);
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(786));
useEffect(() => {
if (picture) {
setImgSrc(picture);
}
}, [picture]);
const styleModal = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: isMobile ? "343px" : "620px",
bgcolor: "background.paper",
boxShadow: 24,
padding: "20px",
borderRadius: "8px",
};
const styleSlider = {
width: isMobile ? "350px" : "250px",
color: "#7E2AEA", color: "#7E2AEA",
height: "12px", height: "12px",
"& .MuiSlider-track": { "& .MuiSlider-track": {
@ -84,33 +45,55 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
}, },
}; };
const rotateImage = () => { interface Iprops {
const newRotation = (rotate + 90) % 360; opened: boolean;
setRotate(newRotation); onClose: () => void;
}; picture?: string;
onCropPress?: (imageUrl: string) => void;
}
export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress }) => {
const theme = useTheme();
const [crop, setCrop] = useState<Crop>();
const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
const [darken, setDarken] = useState(0);
const [rotate, setRotate] = useState(0);
const [imgSrc, setImgSrc] = useState("");
const [width, setWidth] = useState<number>(0);
const blobUrlRef = useRef("");
const fileInputRef = useRef<HTMLInputElement>(null);
const imgRef = useRef<HTMLImageElement>(null);
const isMobile = useMediaQuery(theme.breakpoints.down(786));
useEffect(() => {
if (picture) setImgSrc(picture);
}, [picture]);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (!event.target.files?.length) return;
const onSelectFile = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
setCrop(undefined); setCrop(undefined);
const reader = new FileReader(); try {
reader.addEventListener("load", () => const url = URL.createObjectURL(event.target.files[0]);
setImgSrc(reader.result?.toString() || "") setImgSrc(url);
); } catch (error) {
reader.readAsDataURL(event.target.files[0]); console.error("Failed to create object url for image", error);
} }
}; };
const onDownloadCropClick = () => { const handleCropClick = () => {
if (!previewCanvasRef.current) { if (!completedCrop) throw new Error("No completed crop");
throw new Error("Crop canvas does not exist"); if (!imgRef.current) throw new Error("No image");
}
const canvasCopy = document.createElement("canvas"); const canvasCopy = document.createElement("canvas");
const ctx = canvasCopy.getContext("2d"); const ctx = canvasCopy.getContext("2d");
canvasCopy.width = previewCanvasRef.current.width; if (!ctx) throw new Error("No 2d context");
canvasCopy.height = previewCanvasRef.current.height;
ctx!.filter = `brightness(${100 - darken}%)`; canvasCopy.width = completedCrop.width;
ctx!.drawImage(previewCanvasRef.current, 0, 0); canvasCopy.height = completedCrop.height;
ctx.filter = `brightness(${100 - darken}%)`;
canvasPreview(imgRef.current, canvasCopy, completedCrop, rotate);
canvasCopy.toBlob((blob) => { canvasCopy.toBlob((blob) => {
if (!blob) { if (!blob) {
@ -120,36 +103,13 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
URL.revokeObjectURL(blobUrlRef.current); URL.revokeObjectURL(blobUrlRef.current);
} }
blobUrlRef.current = URL.createObjectURL(blob); blobUrlRef.current = URL.createObjectURL(blob);
hiddenAnchorRef.current!.href = blobUrlRef.current;
hiddenAnchorRef.current!.click();
setImgSrc(blobUrlRef.current); setImgSrc(blobUrlRef.current);
onCropPress?.(blobUrlRef.current); onCropPress?.(blobUrlRef.current);
setCrop(undefined);
}); });
}; };
useDebounceEffect(
async () => {
if (
completedCrop?.width &&
completedCrop?.height &&
imgRef.current &&
previewCanvasRef.current
) {
canvasPreview(
imgRef.current,
previewCanvasRef.current,
completedCrop,
rotate
);
}
},
100,
[completedCrop, rotate]
);
const [width, setWidth] = useState<number>(0);
const getImageSize = () => { const getImageSize = () => {
if (imgRef.current) { if (imgRef.current) {
const imageWidth = imgRef.current.naturalWidth; const imageWidth = imgRef.current.naturalWidth;
@ -170,22 +130,34 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
} }
}; };
function handleSaveClick() {
onClose();
}
return ( return (
<>
<Modal <Modal
open={opened} open={opened}
onClose={onClose} onClose={onClose}
aria-labelledby="modal-modal-title" aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description" aria-describedby="modal-modal-description"
> >
<Box sx={styleModal}> <Box sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
bgcolor: "background.paper",
boxShadow: 24,
padding: "20px",
borderRadius: "8px",
width: isMobile ? "343px" : "620px",
}}>
<Box <Box
sx={{ sx={{
height: "320px", height: "320px",
padding: "10px", padding: "10px",
backgroundSize: "cover", backgroundSize: "cover",
backgroundRepeat: "no-repeat", backgroundRepeat: "no-repeat",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
@ -243,16 +215,17 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
justifyContent: "space-between", justifyContent: "space-between",
}} }}
> >
<ResetIcon <IconButton onClick={() => setRotate(r => (r + 90) % 360)}>
onClick={rotateImage} <ResetIcon />
style={{ marginBottom: "10px", cursor: "pointer" }} </IconButton>
/>
<Box> <Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}> <Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Размер Размер
</Typography> </Typography>
<Slider <Slider
sx={styleSlider} sx={[styleSlider, {
width: isMobile ? "350px" : "250px",
}]}
value={width} value={width}
min={50} min={50}
max={580} max={580}
@ -267,7 +240,9 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
Затемнение Затемнение
</Typography> </Typography>
<Slider <Slider
sx={styleSlider} sx={[styleSlider, {
width: isMobile ? "350px" : "250px",
}]}
value={darken} value={darken}
min={0} min={0}
max={100} max={100}
@ -281,16 +256,20 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
marginTop: "40px", marginTop: "40px",
width: "100%", width: "100%",
display: "flex", display: "flex",
justifyContent: "end",
}} }}
> >
<input <Button
style={{ display: "none", zIndex: "-999" }} onClick={handleSaveClick}
ref={fileInputRef} disableRipple
type="file" sx={{
accept="image/*" height: "48px",
onChange={onSelectFile} color: "#7E2AEA",
/> borderRadius: "8px",
border: "1px solid #7E2AEA",
marginRight: "10px",
px: "20px",
}}
>Сохранить</Button>
<Button <Button
onClick={() => fileInputRef.current?.click()} onClick={() => fileInputRef.current?.click()}
disableRipple disableRipple
@ -301,12 +280,20 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
borderRadius: "8px", borderRadius: "8px",
border: "1px solid #7E2AEA", border: "1px solid #7E2AEA",
marginRight: "10px", marginRight: "10px",
ml: "auto",
}} }}
> >
Загрузить оригинал Загрузить оригинал
<input
style={{ display: "none", zIndex: "-999" }}
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleFileChange}
/>
</Button> </Button>
<Button <Button
onClick={onDownloadCropClick} onClick={handleCropClick}
disableRipple disableRipple
variant="contained" variant="contained"
sx={{ sx={{
@ -322,33 +309,5 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
</Box> </Box>
</Box> </Box>
</Modal> </Modal>
{completedCrop && (
<div>
<canvas
ref={previewCanvasRef}
style={{
display: "none",
zIndex: "-999",
border: "1px solid black",
objectFit: "contain",
width: completedCrop.width,
height: completedCrop.height,
}}
/>
</div>
)}
<div>
<a
href="#hidden"
ref={hiddenAnchorRef}
download
style={{
display: "none",
}}
>
Hidden download
</a>
</div>
</>
); );
}; };