Merge branch 'crop-modal-fixes' into 'main'

fix: CropModal

See merge request frontend/squiz!14
This commit is contained in:
Nastya 2023-09-13 15:11:49 +00:00
commit 1e4404a3d5
15 changed files with 802 additions and 604 deletions

@ -1,4 +1,4 @@
import { FC } from "react";
import { FC, SVGProps } from "react";
export const CropIcon: FC = () => (
<svg

@ -3,53 +3,29 @@ import { Box, ListItem } from "@mui/material";
import QuestionsPageCard from "./QuestionPageCard";
import { ReactComponent as PlusIcon } from "../../../assets/icons/plus.svg";
type DraggableListItemProps = {
index: number;
dropPlaceIndex: number;
isDragging: boolean;
};
export const DraggableListItem = ({
index,
dropPlaceIndex,
isDragging,
}: DraggableListItemProps) => (
<Draggable draggableId={String(index)} index={index}>
{(provided, snapshot) => (
<ListItem ref={provided.innerRef} {...provided.draggableProps}>
{(provided) => (
<ListItem
ref={provided.innerRef}
{...provided.draggableProps}
sx={{ padding: 0 }}
>
<Box sx={{ width: "100%", position: "relative" }}>
<QuestionsPageCard
key={index}
totalIndex={index}
draggableProps={provided.dragHandleProps}
isDragging={isDragging}
/>
{dropPlaceIndex === index && !snapshot.mode && (
<Box
sx={{
position: "absolute",
bottom: "-10px",
display: "flex",
width: "100%",
maxWidth: "825px",
alignItems: "center",
columnGap: "10px",
}}
>
<Box
sx={{
boxSizing: "border-box",
width: "100%",
height: "1px",
backgroundPosition: "bottom",
backgroundRepeat: "repeat-x",
backgroundSize: "20px 1px",
backgroundImage:
"radial-gradient(circle, #7E2AEA 6px, #F2F3F7 1px)",
}}
/>
<PlusIcon />
</Box>
)}
</Box>
</ListItem>
)}

@ -1,3 +1,4 @@
import { useState } from "react";
import { useParams } from "react-router-dom";
import {
Box,
@ -16,6 +17,7 @@ import SwitchQuestionsPage from "../SwitchQuestionsPage";
import {
questionStore,
updateQuestionsList,
createQuestion,
copyQuestion,
removeQuestion,
} from "@root/questions";
@ -39,12 +41,14 @@ import Slider from "@icons/questionsPage/slider";
import Download from "@icons/questionsPage/download";
import Page from "@icons/questionsPage/page";
import RatingIcon from "@icons/questionsPage/rating";
import { ReactComponent as PlusIcon } from "../../../assets/icons/plus.svg";
import type { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
interface Props {
totalIndex: number;
draggableProps: DraggableProvidedDragHandleProps | null | undefined;
isDragging: boolean;
}
const IconAndrom = (isExpanded: boolean, switchState: string) => {
@ -133,7 +137,9 @@ const IconAndrom = (isExpanded: boolean, switchState: string) => {
export default function QuestionsPageCard({
totalIndex,
draggableProps,
isDragging,
}: Props) {
const [plusVisible, setPlusVisible] = useState<boolean>(false);
const quizId = Number(useParams().quizId);
const theme = useTheme();
const { listQuestions } = questionStore();
@ -141,13 +147,13 @@ export default function QuestionsPageCard({
listQuestions[quizId][totalIndex];
return (
<>
<Paper
id={String(totalIndex)}
sx={{
maxWidth: "796px",
width: "100%",
borderRadius: "12px",
margin: "20px 0",
backgroundColor: isExpanded ? "white" : "#333647",
}}
>
@ -206,7 +212,11 @@ export default function QuestionsPageCard({
updateQuestionsList(quizId, totalIndex, { expanded: !isExpanded })
}
>
{isExpanded ? <ExpandMoreIcon /> : <ExpandLessIcon fill="#7E2AEA" />}
{isExpanded ? (
<ExpandMoreIcon />
) : (
<ExpandLessIcon fill="#7E2AEA" />
)}
</IconButton>
{isExpanded ? (
<></>
@ -261,5 +271,41 @@ export default function QuestionsPageCard({
</Box>
)}
</Paper>
<Box
onMouseEnter={() => setPlusVisible(true)}
onMouseLeave={() => setPlusVisible(false)}
sx={{
maxWidth: "825px",
display: "flex",
alignItems: "center",
height: "40px",
cursor: "pointer",
}}
>
<Box
onClick={() => createQuestion(quizId, totalIndex + 1)}
sx={{
display: plusVisible && !isDragging ? "flex" : "none",
width: "100%",
alignItems: "center",
columnGap: "10px",
}}
>
<Box
sx={{
boxSizing: "border-box",
width: "100%",
height: "1px",
backgroundPosition: "bottom",
backgroundRepeat: "repeat-x",
backgroundSize: "20px 1px",
backgroundImage:
"radial-gradient(circle, #7E2AEA 6px, #F2F3F7 1px)",
}}
/>
<PlusIcon />
</Box>
</Box>
</>
);
}

@ -12,16 +12,9 @@ import { reorder } from "./helper";
import type { DropResult } from "react-beautiful-dnd";
export const DraggableList = () => {
const [draggableId, setDraggableId] = useState<number>(-1);
const [dropPlaceIndex, setDropPlaceIndex] = useState<number>(-1);
const quizId = Number(useParams().quizId);
const { listQuestions } = questionStore();
const onDrop = () => {
setDraggableId(-1);
setDropPlaceIndex(-1);
};
const onDragEnd = ({ destination, source }: DropResult) => {
if (destination) {
const newItems = reorder(
@ -35,29 +28,15 @@ export const DraggableList = () => {
};
return (
<DragDropContext
onDragStart={({ draggableId }) => setDraggableId(Number(draggableId))}
onDragUpdate={({ destination }) => {
setDropPlaceIndex(destination?.index ?? -1);
}}
onDragEnd={onDragEnd}
>
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable-list">
{(provided) => (
<Box
ref={provided.innerRef}
{...provided.droppableProps}
onMouseUp={onDrop}
>
{(provided, snapshot) => (
<Box ref={provided.innerRef} {...provided.droppableProps}>
{listQuestions[quizId]?.map((_, index) => (
<DraggableListItem
key={index}
index={index}
dropPlaceIndex={
dropPlaceIndex < draggableId
? dropPlaceIndex - 1
: dropPlaceIndex
}
isDragging={snapshot.isDraggingOver}
/>
))}
{provided.placeholder}

@ -52,6 +52,7 @@ export default function SliderOptions({ totalIndex }: Props) {
});
}}
onBlur={({ target }) => {
const start = listQuestions[quizId][totalIndex].content.start;
const min = Number(target.value);
const max = Number(
listQuestions[quizId][totalIndex].content.range.split("—")[1]
@ -68,6 +69,15 @@ export default function SliderOptions({ totalIndex }: Props) {
content: clonContent,
});
}
if (start < min) {
updateQuestionsList(quizId, totalIndex, {
content: {
...listQuestions[quizId][totalIndex].content,
start: min,
},
});
}
}}
/>
<Typography></Typography>
@ -88,10 +98,13 @@ export default function SliderOptions({ totalIndex }: Props) {
});
}}
onBlur={({ target }) => {
const start = listQuestions[quizId][totalIndex].content.start;
const step = listQuestions[quizId][totalIndex].content.step;
const min = Number(
listQuestions[quizId][totalIndex].content.range.split("—")[0]
);
const max = Number(target.value);
const range = max - min;
if (max <= min) {
const clonContent = listQuestions[quizId][totalIndex].content;
@ -104,6 +117,34 @@ export default function SliderOptions({ totalIndex }: Props) {
content: clonContent,
});
}
if (start > max) {
updateQuestionsList(quizId, totalIndex, {
content: {
...listQuestions[quizId][totalIndex].content,
start: max,
},
});
}
if (step > max) {
updateQuestionsList(quizId, totalIndex, {
content: {
...listQuestions[quizId][totalIndex].content,
step: max,
},
});
if (range % step) {
setStepError(
`Шаг должен делить без остатка диапазон ${max} - ${min} = ${
max - min
}`
);
} else {
setStepError("");
}
}
}}
/>
</Box>
@ -120,7 +161,12 @@ export default function SliderOptions({ totalIndex }: Props) {
<Typography>Начальное значение</Typography>
<CustomNumberField
placeholder={"50"}
min={0}
min={Number(
listQuestions[quizId][totalIndex].content.range.split("—")[0]
)}
max={Number(
listQuestions[quizId][totalIndex].content.range.split("—")[1]
)}
value={String(listQuestions[quizId][totalIndex].content.start)}
onChange={({ target }) => {
const clonContent = listQuestions[quizId][totalIndex].content;
@ -129,21 +175,6 @@ export default function SliderOptions({ totalIndex }: Props) {
content: clonContent,
});
}}
onBlur={({ target }) => {
const start = Number(target.value);
const min = Number(
listQuestions[quizId][totalIndex].content.range.split("—")[0]
);
if (start < min) {
updateQuestionsList(quizId, totalIndex, {
content: {
...listQuestions[quizId][totalIndex].content,
start: min,
},
});
}
}}
/>
</Box>
<Box sx={{ width: "100%" }}>
@ -171,11 +202,11 @@ export default function SliderOptions({ totalIndex }: Props) {
const range = max - min;
const step = Number(target.value);
if (step > range) {
if (step > max) {
updateQuestionsList(quizId, totalIndex, {
content: {
...listQuestions[quizId][totalIndex].content,
step: range,
step: max,
},
});
}

@ -2,7 +2,7 @@ import { useParams } from "react-router-dom";
import { useState } from "react";
import { Typography, Box, useTheme, ButtonBase } from "@mui/material";
import UploadBox from "@ui_kit/UploadBox";
import { CroppingModal } from "@ui_kit/Modal/CroppingModal";
import { CropModal } from "@ui_kit/Modal/CropModal";
import UploadIcon from "../../../assets/icons/UploadIcon";
import * as React from "react";
import { questionStore, updateQuestionsList } from "@root/questions";
@ -67,7 +67,7 @@ export default function UploadImage({ totalIndex }: UploadImageProps) {
/>
</ButtonBase>
<UploadImageModal open={open} onClose={handleClose} imgHC={imgHC} />
<CroppingModal
<CropModal
opened={opened}
onClose={() => setOpened(false)}
picture={listQuestions[quizId][totalIndex].content.back}

@ -3,7 +3,7 @@ import { Box, Typography, useTheme } from "@mui/material";
import AddImage from "@icons/questionsPage/addImage";
import AddVideofile from "@icons/questionsPage/addVideofile";
import { useState } from "react";
import { CroppingModal } from "@ui_kit/Modal/CroppingModal";
import { CropModal } from "@ui_kit/Modal/CropModal";
export default function ImageAndVideoButtons() {
const theme = useTheme();
@ -13,7 +13,7 @@ export default function ImageAndVideoButtons() {
return (
<Box sx={{ display: "flex", alignItems: "center", gap: "12px", mt: "20px", mb: "20px" }}>
<AddImage onClick={() => setOpened(true)} />
<CroppingModal opened={opened} onClose={() => setOpened(false)} />
<CropModal opened={opened} onClose={() => setOpened(false)} />
<Typography
sx={{
fontWeight: 400,

@ -124,7 +124,7 @@ export const updateVariants = (
questionStore.setState({ listQuestions });
};
export const createQuestion = (quizId: number) => {
export const createQuestion = (quizId: number, placeIndex = -1) => {
const id = getRandom(1000000, 10000000);
const newData = { ...questionStore.getState()["listQuestions"] };
@ -132,7 +132,10 @@ export const createQuestion = (quizId: number) => {
newData[quizId] = [];
}
newData[quizId].push({
newData[quizId].splice(
placeIndex < 0 ? newData[quizId].length : placeIndex,
0,
{
id,
title: "",
description: "",
@ -198,7 +201,8 @@ export const createQuestion = (quizId: number) => {
created_at: "",
updated_at: "",
expanded: false,
});
}
);
questionStore.setState({ listQuestions: newData });
};

@ -30,16 +30,28 @@ export default function CustomNumberField({
const inputValue = event.target.value;
if (
Number(inputValue) >= min &&
Number(inputValue) <= max &&
(inputValue === "" ||
inputValue === "" ||
inputValue.match(/^\d*$/) ||
(inputValue[0] === "-" && inputValue.slice(1).match(/^\d*$/)))
(inputValue[0] === "-" && inputValue.slice(1).match(/^\d*$/))
) {
onChange?.({ ...event, target: { ...event.target, value: inputValue } });
}
};
const onInputBlur = (event: FocusEvent<HTMLInputElement>) => {
const inputValue = event.target.value;
if (Number(inputValue) < min) {
onChange?.({ ...event, target: { ...event.target, value: String(min) } });
}
if (Number(inputValue) > max) {
onChange?.({ ...event, target: { ...event.target, value: String(max) } });
}
onBlur?.(event);
};
return (
<CustomTextField
placeholder={placeholder}
@ -47,7 +59,7 @@ export default function CustomNumberField({
error={error}
onChange={onInputChange}
onKeyDown={onKeyDown}
onBlur={onBlur}
onBlur={onInputBlur}
value={value}
/>
);

@ -0,0 +1,356 @@
import React, { useState, useRef, useEffect, FC } from "react";
import ReactCrop, { Crop, PixelCrop } from "react-image-crop";
import {
Box,
Button,
Modal,
Slider,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import { canvasPreview } from "./utils/canvasPreview";
import { useDebounceEffect } from "./utils/useDebounceEffect";
import { ResetIcon } from "@icons/ResetIcon";
import "react-image-crop/dist/ReactCrop.css";
import { CropIcon } from "@icons/CropIcon";
interface Iprops {
opened: boolean;
onClose: React.Dispatch<React.SetStateAction<boolean>>;
picture?: string;
}
export const CropModal: FC<Iprops> = ({ opened, onClose, picture }) => {
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",
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`,
},
},
};
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 = () => {
if (!previewCanvasRef.current) {
throw new Error("Crop canvas does not exist");
}
const canvasCopy = document.createElement("canvas");
const ctx = canvasCopy.getContext("2d");
canvasCopy.width = previewCanvasRef.current.width;
canvasCopy.height = previewCanvasRef.current.height;
ctx!.filter = `brightness(${100 - darken}%)`;
ctx!.drawImage(previewCanvasRef.current, 0, 0);
canvasCopy.toBlob((blob) => {
if (!blob) {
throw new Error("Failed to create blob");
}
if (blobUrlRef.current) {
URL.revokeObjectURL(blobUrlRef.current);
}
blobUrlRef.current = URL.createObjectURL(blob);
hiddenAnchorRef.current!.href = blobUrlRef.current;
hiddenAnchorRef.current!.click();
setImgSrc(blobUrlRef.current);
});
};
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 = () => {
if (imgRef.current) {
const imageWidth = imgRef.current.naturalWidth;
const imageHeight = imgRef.current.naturalHeight;
const aspect = imageWidth / imageHeight;
console.log(aspect);
console.log(width);
if (aspect <= 1.333) {
setWidth(240);
}
if (aspect >= 1.5) {
setWidth(580);
}
if (aspect >= 1.778) {
setWidth(580);
}
}
};
return (
<>
<Modal
open={opened}
onClose={onClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={styleModal}>
<Box
sx={{
height: "320px",
padding: "10px",
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
{imgSrc && (
<ReactCrop
crop={crop}
onChange={(_, percentCrop) => setCrop(percentCrop)}
onComplete={(c) => setCompletedCrop(c)}
maxWidth={500}
minWidth={50}
maxHeight={320}
minHeight={50}
>
<img
onLoad={getImageSize}
ref={imgRef}
alt="Crop me"
src={imgSrc}
style={{
filter: `brightness(${100 - darken}%)`,
transform: ` rotate(${rotate}deg)`,
maxWidth: "580px",
maxHeight: "320px",
}}
width={width}
/>
</ReactCrop>
)}
</Box>
<Box
sx={{
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);
}}
/>
</Box>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Затемнение
</Typography>
<Slider
sx={styleSlider}
value={darken}
min={0}
max={100}
step={1}
onChange={(_, newValue) => setDarken(newValue as number)}
/>
</Box>
</Box>
<Box
sx={{
marginTop: "40px",
width: "100%",
display: "flex",
justifyContent: "end",
}}
>
<input
style={{ display: "none", zIndex: "-999" }}
ref={fileInputRef}
type="file"
accept="image/*"
onChange={onSelectFile}
/>
<Button
onClick={() => fileInputRef.current?.click()}
disableRipple
sx={{
width: "215px",
height: "48px",
color: "#7E2AEA",
borderRadius: "8px",
border: "1px solid #7E2AEA",
marginRight: "10px",
}}
>
Загрузить оригинал
</Button>
<Button
onClick={onDownloadCropClick}
disableRipple
sx={{
width: "149px",
height: "48px",
color: "white",
background: "#7E2AEA",
borderRadius: "8px",
marginRight: "6px",
}}
>
<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>
)}
<div>
<a
href="#hidden"
ref={hiddenAnchorRef}
download
style={{
display: "none",
}}
>
Hidden download
</a>
</div>
</>
);
};

@ -1,345 +0,0 @@
import React, { FC, useEffect, useRef, useState } from "react";
import { saveAs } from "file-saver";
import ReactCrop, { Crop } from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";
import {
Box,
Button,
Modal,
Slider,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import quiz from "../../assets/quiz-template-6.png";
import { ResetIcon } from "@icons/ResetIcon";
interface Iprops {
opened: boolean;
onClose: () => void;
picture?: string | ArrayBuffer;
}
export const CroppingModal: FC<Iprops> = ({ opened, onClose, picture }) => {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(786));
const style = {
position: "absolute" as "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",
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`,
},
},
};
const [src, setSrc] = useState<string | ArrayBuffer | null>(quiz);
const [crop, setCrop] = useState<Crop>({
unit: "px",
y: 0,
x: 0,
width: 100,
height: 100,
});
const [completedCrop, setCompletedCrop] = useState<Crop | null>(null);
const [imageSize, setImageSize] = useState(580);
const [darken, setDarken] = useState(0);
const fileInputRef = useRef<HTMLInputElement>(null);
console.log(src);
useEffect(() => {
if (picture) {
setSrc(picture);
}
}, [picture]);
const onCropComplete = (crop: Crop) => {
setCompletedCrop(crop);
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
if (event.target && event.target.result) {
setSrc(event.target.result);
}
};
reader.readAsDataURL(file);
}
};
const handleDownloadClick = async () => {
if (completedCrop && src) {
const croppedImageUrl = await getCroppedAndDarkenedImg(
src,
completedCrop,
"cropped.jpeg",
darken
);
saveAs(croppedImageUrl, "cropped-image.jpeg");
}
};
const getCroppedAndDarkenedImg = (
image: string | ArrayBuffer,
crop: Crop,
fileName: string,
darken: number
): Promise<string> => {
const img = new Image();
img.src = image as string;
let scaleX = 360 / 580;
let scaleY = 219 / 320;
if (img.naturalWidth) {
scaleX = img.naturalWidth / 580;
}
if (img.naturalHeight) {
scaleY = img.naturalHeight / 320;
}
console.log(scaleX);
console.log(scaleY);
const canvas = document.createElement("canvas");
canvas.width = crop.width!;
canvas.height = crop.height!;
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error("Canvas context is null");
}
ctx.drawImage(
img,
crop.x! * scaleX,
crop.y! * scaleY,
crop.width! * scaleX,
crop.height! * scaleY,
0,
0,
crop.width!,
crop.height!
);
const imageData = ctx.getImageData(0, 0, crop.width!, crop.height!);
const newImageData = imageData.data.map((value, index) => {
if ((index + 1) % 4 === 0) {
return value;
}
return value * (1 - darken / 100);
});
imageData.data.set(newImageData);
ctx.putImageData(imageData, 0, 0);
return new Promise<string>((resolve, reject) => {
canvas.toBlob((blob) => {
if (!blob) {
reject(new Error("Canvas is empty"));
return;
}
const file = new File([blob], fileName, { type: "image/jpeg" });
const imageUrl = window.URL.createObjectURL(file);
resolve(imageUrl);
}, "image/jpeg");
});
};
return (
<Modal
open={opened}
onClose={onClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<Box
sx={{
height: "320px",
padding: "10px",
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<ReactCrop
crop={crop}
onChange={(newCrop) => setCrop(newCrop)}
onComplete={onCropComplete}
>
{src && (
<img
src={src as string}
style={{
filter: `brightness(${100 - darken}%)`,
maxWidth: "580px",
}}
width={580 * (imageSize / 200)}
height={320}
alt="Crop"
/>
)}
</ReactCrop>
</Box>
<Box
sx={{
color: "#7E2AEA",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "16xp",
fontWeight: "600",
marginBottom: "50px",
}}
>
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>
{Math.round(crop.width)}
</Typography>
x
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>
{Math.round(crop.width)}
</Typography>
px
</Box>
<Box
sx={{
display: isMobile ? "block" : "flex",
alignItems: "end",
justifyContent: "space-between",
}}
>
<ResetIcon
onClick={() => {
setCrop((prevCrop: Crop) => ({
...prevCrop,
unit: "px",
x: 210,
y: 10,
width: 210,
height: 300,
}));
setDarken(0);
setImageSize(580);
}}
style={{ marginBottom: "10px", cursor: "pointer" }}
/>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Размер
</Typography>
<Slider
sx={styleSlider}
value={imageSize}
min={50}
max={200}
step={1}
onChange={(_, newValue) => setImageSize(newValue as number)}
/>
</Box>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Затемнение
</Typography>
<Slider
sx={styleSlider}
value={darken}
min={0}
max={100}
step={1}
onChange={(_, newValue) => setDarken(newValue as number)}
/>
</Box>
</Box>
<Box
sx={{
marginTop: "40px",
width: "100%",
display: "flex",
justifyContent: "end",
}}
>
<input
ref={fileInputRef}
type="file"
accept="image/*"
id="fileInput"
style={{ display: "none" }}
onChange={handleFileChange}
/>
<Button
onClick={() => fileInputRef.current?.click()}
disableRipple
sx={{
width: "215px",
height: "48px",
color: "#7E2AEA",
borderRadius: "8px",
border: "1px solid #7E2AEA",
marginRight: "10px",
}}
>
Загрузить оригинал
</Button>
<Button
onClick={handleDownloadClick}
disableRipple
sx={{
width: "149px",
height: "48px",
color: "white",
background: "#7E2AEA",
borderRadius: "8px",
}}
>
Обрезать
</Button>
</Box>
</Box>
</Modal>
);
};

@ -1,13 +1,13 @@
import { Box, Button } from "@mui/material";
import { FC, useState } from "react";
import { CroppingModal } from "./CroppingModal";
import { CropModal } from "./CropModal";
const ImageCrop: FC = () => {
const [opened, setOpened] = useState<boolean>(false);
return (
<Box>
<CroppingModal opened={opened} onClose={() => setOpened(false)} />
<Button onClick={() => setOpened(true)}>Открыть модалку</Button>
<CropModal opened={opened} onClose={() => setOpened(false)} />
</Box>
);
};

@ -0,0 +1,76 @@
.ReactCrop__drag-bar,
.ord-e {
background-color: #7e2aea;
}
.ReactCrop__crop-selection:not(.ReactCrop--no-animate .ReactCrop__crop-selection) {
background-image: none;
}
.ReactCrop__drag-bar.ord-e {
right: 0;
top: 0;
width: 3px;
height: 100%;
margin-right: -3px;
}
.ReactCrop__drag-bar.ord-s {
bottom: 0;
left: 0;
width: 100%;
height: 3px;
margin-bottom: -3px;
}
.ReactCrop__drag-bar.ord-n {
bottom: 0;
left: 0;
width: 100%;
height: 3px;
margin-bottom: -3px;
}
.ReactCrop__drag-bar.ord-w {
top: 0;
left: 0;
width: 3px;
height: 100%;
margin-left: -3px;
}
/* кружочки */
.ReactCrop .ord-nw:after {
background-color: #7e2aea;
}
.ReactCrop .ord-n:after {
background-color: #7e2aea;
}
.ReactCrop .ord-ne:after {
background-color: #7e2aea;
}
.ReactCrop .ord-se:after {
background-color: #7e2aea;
}
.ReactCrop .ord-e:after {
background-color: #7e2aea;
}
.ReactCrop .ord-s:after {
background-color: #7e2aea;
}
.ReactCrop .ord-sw:after {
background-color: #7e2aea;
}
.ReactCrop .ord-w:after {
background-color: #7e2aea;
}
/* кружочки */

@ -0,0 +1,50 @@
import { PixelCrop } from "react-image-crop";
const TO_RADIANS = Math.PI / 180;
export async function canvasPreview(image: HTMLImageElement, canvas: HTMLCanvasElement, crop: PixelCrop, rotate = 0) {
const scale = 1;
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;
// devicePixelRatio slightly increases sharpness on retina devices
// at the expense of slightly slower render times and needing to
// size the image back down if you want to download/upload and be
// true to the images natural size.
const pixelRatio = window.devicePixelRatio;
// const pixelRatio = 1
canvas.width = Math.floor(crop.width * scaleX * pixelRatio);
canvas.height = Math.floor(crop.height * scaleY * pixelRatio);
ctx.scale(pixelRatio, pixelRatio);
ctx.imageSmoothingQuality = "high";
const cropX = crop.x * scaleX;
const cropY = crop.y * scaleY;
const rotateRads = rotate * TO_RADIANS;
const centerX = image.naturalWidth / 2;
const centerY = image.naturalHeight / 2;
ctx.save();
// 5) Move the crop origin to the canvas origin (0,0)
ctx.translate(-cropX, -cropY);
// 4) Move the origin to the center of the original position
ctx.translate(centerX, centerY);
// 3) Rotate around the origin
ctx.rotate(rotateRads);
// 2) Scale the image
ctx.scale(scale, scale);
// 1) Move the center of the image to the origin (0,0)
ctx.translate(-centerX, -centerY);
ctx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight, 0, 0, image.naturalWidth, image.naturalHeight);
ctx.restore();
}

@ -0,0 +1,13 @@
import { useEffect, DependencyList } from "react";
export function useDebounceEffect(fn: () => void, waitTime: number, deps?: DependencyList) {
useEffect(() => {
const time = setTimeout(() => {
fn();
}, waitTime);
return () => {
clearTimeout(time);
};
}, [deps, fn, waitTime]);
}