refactor crop modal

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

@ -1,116 +1,99 @@
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";
const styleSlider: SxProps<Theme> = {
color: "#7E2AEA",
height: "12px",
"& .MuiSlider-track": {
border: "none",
},
"& .MuiSlider-rail": {
backgroundColor: "#F2F3F7",
border: `1px solid #9A9AAF`,
},
"& .MuiSlider-thumb": {
height: 26,
width: 26,
border: `6px solid #7E2AEA`,
backgroundColor: "white",
boxShadow: `0px 0px 0px 3px white,
0px 4px 4px 3px #C3C8DD`,
"&:focus, &:hover, &.Mui-active, &.Mui-focusVisible": {
boxShadow: `0px 0px 0px 3px white,
0px 4px 4px 3px #C3C8DD`,
},
},
};
interface Iprops { interface Iprops {
opened: boolean; opened: boolean;
onClose: React.Dispatch<React.SetStateAction<boolean>>; onClose: () => void;
picture?: string; picture?: string;
onCropPress?: (imageUrl: string) => void; onCropPress?: (imageUrl: string) => void;
} }
export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress }) => { export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress }) => {
const [imgSrc, setImgSrc] = useState(""); const theme = useTheme();
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 [crop, setCrop] = useState<Crop>();
const [completedCrop, setCompletedCrop] = useState<PixelCrop>(); const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
const [rotate, setRotate] = useState(0);
const [darken, setDarken] = useState(0); const [darken, setDarken] = useState(0);
const [rotate, setRotate] = useState(0);
const theme = useTheme(); 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)); const isMobile = useMediaQuery(theme.breakpoints.down(786));
useEffect(() => { useEffect(() => {
if (picture) { if (picture) setImgSrc(picture);
setImgSrc(picture);
}
}, [picture]); }, [picture]);
const styleModal = { const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
position: "absolute", if (!event.target.files?.length) return;
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: isMobile ? "343px" : "620px",
bgcolor: "background.paper",
boxShadow: 24,
padding: "20px",
borderRadius: "8px",
};
const styleSlider = { setCrop(undefined);
width: isMobile ? "350px" : "250px", try {
color: "#7E2AEA", const url = URL.createObjectURL(event.target.files[0]);
height: "12px", setImgSrc(url);
"& .MuiSlider-track": { } catch (error) {
border: "none", console.error("Failed to create object url for image", error);
},
"& .MuiSlider-rail": {
backgroundColor: "#F2F3F7",
border: `1px solid #9A9AAF`,
},
"& .MuiSlider-thumb": {
height: 26,
width: 26,
border: `6px solid #7E2AEA`,
backgroundColor: "white",
boxShadow: `0px 0px 0px 3px white,
0px 4px 4px 3px #C3C8DD`,
"&:focus, &:hover, &.Mui-active, &.Mui-focusVisible": {
boxShadow: `0px 0px 0px 3px white,
0px 4px 4px 3px #C3C8DD`,
},
},
};
const rotateImage = () => {
const newRotation = (rotate + 90) % 360;
setRotate(newRotation);
};
const onSelectFile = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
setCrop(undefined);
const reader = new FileReader();
reader.addEventListener("load", () =>
setImgSrc(reader.result?.toString() || "")
);
reader.readAsDataURL(event.target.files[0]);
} }
}; };
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,185 +130,184 @@ 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={{
<Box sx={styleModal}> position: "absolute",
<Box top: "50%",
sx={{ left: "50%",
height: "320px", transform: "translate(-50%, -50%)",
padding: "10px", bgcolor: "background.paper",
backgroundSize: "cover", boxShadow: 24,
backgroundRepeat: "no-repeat", padding: "20px",
borderRadius: "8px",
display: "flex", width: isMobile ? "343px" : "620px",
alignItems: "center", }}>
justifyContent: "center", <Box
}} sx={{
> height: "320px",
{imgSrc && ( padding: "10px",
<ReactCrop backgroundSize: "cover",
crop={crop} backgroundRepeat: "no-repeat",
onChange={(_, percentCrop) => setCrop(percentCrop)} display: "flex",
onComplete={(c) => setCompletedCrop(c)} alignItems: "center",
maxWidth={500} justifyContent: "center",
minWidth={50} }}
maxHeight={320} >
minHeight={50} {imgSrc && (
> <ReactCrop
<img crop={crop}
onLoad={getImageSize} onChange={(_, percentCrop) => setCrop(percentCrop)}
ref={imgRef} onComplete={(c) => setCompletedCrop(c)}
alt="Crop me" maxWidth={500}
src={imgSrc} minWidth={50}
style={{ maxHeight={320}
filter: `brightness(${100 - darken}%)`, minHeight={50}
transform: ` rotate(${rotate}deg)`, >
maxWidth: "580px", <img
maxHeight: "320px", onLoad={getImageSize}
}} ref={imgRef}
width={width} alt="Crop me"
/> src={imgSrc}
</ReactCrop> style={{
)} filter: `brightness(${100 - darken}%)`,
</Box> transform: ` rotate(${rotate}deg)`,
<Box maxWidth: "580px",
sx={{ maxHeight: "320px",
color: "#7E2AEA",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "16xp",
fontWeight: "600",
marginBottom: "50px",
}}
>
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>
{crop?.width ? Math.round(crop.width) + "px" : ""}
</Typography>
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>
{crop?.height ? Math.round(crop.height) + "px" : ""}
</Typography>
</Box>
<Box
sx={{
display: isMobile ? "block" : "flex",
alignItems: "end",
justifyContent: "space-between",
}}
>
<ResetIcon
onClick={rotateImage}
style={{ marginBottom: "10px", cursor: "pointer" }}
/>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Размер
</Typography>
<Slider
sx={styleSlider}
value={width}
min={50}
max={580}
step={1}
onChange={(_, newValue) => {
setWidth(newValue as number);
}} }}
width={width}
/> />
</Box> </ReactCrop>
<Box> )}
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}> </Box>
Затемнение <Box
</Typography> sx={{
<Slider color: "#7E2AEA",
sx={styleSlider} display: "flex",
value={darken} alignItems: "center",
min={0} justifyContent: "center",
max={100} fontSize: "16xp",
step={1} fontWeight: "600",
onChange={(_, newValue) => setDarken(newValue as number)} marginBottom: "50px",
/> }}
</Box> >
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>
{crop?.width ? Math.round(crop.width) + "px" : ""}
</Typography>
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>
{crop?.height ? Math.round(crop.height) + "px" : ""}
</Typography>
</Box>
<Box
sx={{
display: isMobile ? "block" : "flex",
alignItems: "end",
justifyContent: "space-between",
}}
>
<IconButton onClick={() => setRotate(r => (r + 90) % 360)}>
<ResetIcon />
</IconButton>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Размер
</Typography>
<Slider
sx={[styleSlider, {
width: isMobile ? "350px" : "250px",
}]}
value={width}
min={50}
max={580}
step={1}
onChange={(_, newValue) => {
setWidth(newValue as number);
}}
/>
</Box> </Box>
<Box <Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Затемнение
</Typography>
<Slider
sx={[styleSlider, {
width: isMobile ? "350px" : "250px",
}]}
value={darken}
min={0}
max={100}
step={1}
onChange={(_, newValue) => setDarken(newValue as number)}
/>
</Box>
</Box>
<Box
sx={{
marginTop: "40px",
width: "100%",
display: "flex",
}}
>
<Button
onClick={handleSaveClick}
disableRipple
sx={{ sx={{
marginTop: "40px", height: "48px",
width: "100%", color: "#7E2AEA",
display: "flex", borderRadius: "8px",
justifyContent: "end", border: "1px solid #7E2AEA",
marginRight: "10px",
px: "20px",
}}
>Сохранить</Button>
<Button
onClick={() => fileInputRef.current?.click()}
disableRipple
sx={{
width: "215px",
height: "48px",
color: "#7E2AEA",
borderRadius: "8px",
border: "1px solid #7E2AEA",
marginRight: "10px",
ml: "auto",
}} }}
> >
Загрузить оригинал
<input <input
style={{ display: "none", zIndex: "-999" }} style={{ display: "none", zIndex: "-999" }}
ref={fileInputRef} ref={fileInputRef}
type="file" type="file"
accept="image/*" accept="image/*"
onChange={onSelectFile} onChange={handleFileChange}
/> />
<Button </Button>
onClick={() => fileInputRef.current?.click()} <Button
disableRipple onClick={handleCropClick}
sx={{ disableRipple
width: "215px", variant="contained"
height: "48px", sx={{
color: "#7E2AEA", padding: "10px 20px",
borderRadius: "8px", borderRadius: "8px",
border: "1px solid #7E2AEA", background: theme.palette.brightPurple.main,
marginRight: "10px", fontSize: "18px",
}}
>
Загрузить оригинал
</Button>
<Button
onClick={onDownloadCropClick}
disableRipple
variant="contained"
sx={{
padding: "10px 20px",
borderRadius: "8px",
background: theme.palette.brightPurple.main,
fontSize: "18px",
}}
>
<CropIcon />
Обрезать
</Button>
</Box>
</Box>
</Modal>
{completedCrop && (
<div>
<canvas
ref={previewCanvasRef}
style={{
display: "none",
zIndex: "-999",
border: "1px solid black",
objectFit: "contain",
width: completedCrop.width,
height: completedCrop.height,
}} }}
/> >
</div> <CropIcon />
)} Обрезать
<div> </Button>
<a </Box>
href="#hidden" </Box>
ref={hiddenAnchorRef} </Modal>
download
style={{
display: "none",
}}
>
Hidden download
</a>
</div>
</>
); );
}; };