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 = () => ( export const CropIcon: FC = () => (
<svg <svg

@ -3,53 +3,29 @@ import { Box, ListItem } from "@mui/material";
import QuestionsPageCard from "./QuestionPageCard"; import QuestionsPageCard from "./QuestionPageCard";
import { ReactComponent as PlusIcon } from "../../../assets/icons/plus.svg";
type DraggableListItemProps = { type DraggableListItemProps = {
index: number; index: number;
dropPlaceIndex: number; isDragging: boolean;
}; };
export const DraggableListItem = ({ export const DraggableListItem = ({
index, index,
dropPlaceIndex, isDragging,
}: DraggableListItemProps) => ( }: DraggableListItemProps) => (
<Draggable draggableId={String(index)} index={index}> <Draggable draggableId={String(index)} index={index}>
{(provided, snapshot) => ( {(provided) => (
<ListItem ref={provided.innerRef} {...provided.draggableProps}> <ListItem
ref={provided.innerRef}
{...provided.draggableProps}
sx={{ padding: 0 }}
>
<Box sx={{ width: "100%", position: "relative" }}> <Box sx={{ width: "100%", position: "relative" }}>
<QuestionsPageCard <QuestionsPageCard
key={index} key={index}
totalIndex={index} totalIndex={index}
draggableProps={provided.dragHandleProps} 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> </Box>
</ListItem> </ListItem>
)} )}

@ -1,3 +1,4 @@
import { useState } from "react";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { import {
Box, Box,
@ -16,6 +17,7 @@ import SwitchQuestionsPage from "../SwitchQuestionsPage";
import { import {
questionStore, questionStore,
updateQuestionsList, updateQuestionsList,
createQuestion,
copyQuestion, copyQuestion,
removeQuestion, removeQuestion,
} from "@root/questions"; } from "@root/questions";
@ -39,12 +41,14 @@ import Slider from "@icons/questionsPage/slider";
import Download from "@icons/questionsPage/download"; import Download from "@icons/questionsPage/download";
import Page from "@icons/questionsPage/page"; import Page from "@icons/questionsPage/page";
import RatingIcon from "@icons/questionsPage/rating"; import RatingIcon from "@icons/questionsPage/rating";
import { ReactComponent as PlusIcon } from "../../../assets/icons/plus.svg";
import type { DraggableProvidedDragHandleProps } from "react-beautiful-dnd"; import type { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
interface Props { interface Props {
totalIndex: number; totalIndex: number;
draggableProps: DraggableProvidedDragHandleProps | null | undefined; draggableProps: DraggableProvidedDragHandleProps | null | undefined;
isDragging: boolean;
} }
const IconAndrom = (isExpanded: boolean, switchState: string) => { const IconAndrom = (isExpanded: boolean, switchState: string) => {
@ -133,7 +137,9 @@ const IconAndrom = (isExpanded: boolean, switchState: string) => {
export default function QuestionsPageCard({ export default function QuestionsPageCard({
totalIndex, totalIndex,
draggableProps, draggableProps,
isDragging,
}: Props) { }: Props) {
const [plusVisible, setPlusVisible] = useState<boolean>(false);
const quizId = Number(useParams().quizId); const quizId = Number(useParams().quizId);
const theme = useTheme(); const theme = useTheme();
const { listQuestions } = questionStore(); const { listQuestions } = questionStore();
@ -141,125 +147,165 @@ export default function QuestionsPageCard({
listQuestions[quizId][totalIndex]; listQuestions[quizId][totalIndex];
return ( return (
<Paper <>
id={String(totalIndex)} <Paper
sx={{ id={String(totalIndex)}
maxWidth: "796px",
width: "100%",
borderRadius: "12px",
margin: "20px 0",
backgroundColor: isExpanded ? "white" : "#333647",
}}
>
<Box
sx={{ sx={{
maxWidth: "796px",
width: "100%", width: "100%",
maxWidth: "760px", borderRadius: "12px",
display: "flex", backgroundColor: isExpanded ? "white" : "#333647",
alignItems: "center",
gap: "10px",
padding: "20px",
}} }}
> >
<FormControl fullWidth variant="standard" sx={{ p: 0 }}>
<TextField
fullWidth
value={listQuestions[quizId][totalIndex].title}
placeholder={"Заголовок вопроса"}
onChange={(e) => {
updateQuestionsList(quizId, totalIndex, {
title: e.target.value,
});
console.log(listQuestions[quizId][totalIndex].title);
}}
InputProps={{
startAdornment: (
<InputAdornment position="start">
{IconAndrom(isExpanded, switchState)}
</InputAdornment>
),
}}
sx={{
"& .MuiInputBase-root": {
color: isExpanded ? "#9A9AAF" : "white",
backgroundColor: isExpanded
? theme.palette.background.default
: "transparent",
height: "48px",
borderRadius: "10px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
paddingLeft: switchState.length === 0 ? 0 : "18px",
},
}}
/>
</FormControl>
<IconButton
onClick={() =>
updateQuestionsList(quizId, totalIndex, { expanded: !isExpanded })
}
>
{isExpanded ? <ExpandMoreIcon /> : <ExpandLessIcon fill="#7E2AEA" />}
</IconButton>
{isExpanded ? (
<></>
) : (
<Box sx={{ display: "flex", borderRight: "solid 1px white" }}>
<FormControlLabel
control={
<Checkbox
icon={<HideIcon color={"#7E2AEA"} />}
checkedIcon={<CrossedEyeIcon />}
/>
}
label={""}
sx={{
color: theme.palette.grey2.main,
ml: "-9px",
mr: 0,
userSelect: "none",
}}
/>
<IconButton onClick={() => copyQuestion(quizId, totalIndex)}>
<CopyIcon color={"white"} />
</IconButton>
<IconButton
sx={{ cursor: "pointer", borderRadius: "6px", padding: "2px" }}
onClick={() => removeQuestion(quizId, totalIndex)}
>
<DeleteIcon color={"white"} />
</IconButton>
</Box>
)}
<OneIcon />
<IconButton {...draggableProps}>
<PointsIcon />
</IconButton>
</Box>
{isExpanded && (
<Box <Box
sx={{ sx={{
width: "100%",
maxWidth: "760px",
display: "flex", display: "flex",
flexDirection: "column", alignItems: "center",
padding: 0, gap: "10px",
borderRadius: "12px", padding: "20px",
}} }}
> >
{switchState.length === 0 ? ( <FormControl fullWidth variant="standard" sx={{ p: 0 }}>
<TypeQuestions totalIndex={totalIndex} /> <TextField
fullWidth
value={listQuestions[quizId][totalIndex].title}
placeholder={"Заголовок вопроса"}
onChange={(e) => {
updateQuestionsList(quizId, totalIndex, {
title: e.target.value,
});
console.log(listQuestions[quizId][totalIndex].title);
}}
InputProps={{
startAdornment: (
<InputAdornment position="start">
{IconAndrom(isExpanded, switchState)}
</InputAdornment>
),
}}
sx={{
"& .MuiInputBase-root": {
color: isExpanded ? "#9A9AAF" : "white",
backgroundColor: isExpanded
? theme.palette.background.default
: "transparent",
height: "48px",
borderRadius: "10px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
paddingLeft: switchState.length === 0 ? 0 : "18px",
},
}}
/>
</FormControl>
<IconButton
onClick={() =>
updateQuestionsList(quizId, totalIndex, { expanded: !isExpanded })
}
>
{isExpanded ? (
<ExpandMoreIcon />
) : (
<ExpandLessIcon fill="#7E2AEA" />
)}
</IconButton>
{isExpanded ? (
<></>
) : ( ) : (
<SwitchQuestionsPage totalIndex={totalIndex} /> <Box sx={{ display: "flex", borderRight: "solid 1px white" }}>
<FormControlLabel
control={
<Checkbox
icon={<HideIcon color={"#7E2AEA"} />}
checkedIcon={<CrossedEyeIcon />}
/>
}
label={""}
sx={{
color: theme.palette.grey2.main,
ml: "-9px",
mr: 0,
userSelect: "none",
}}
/>
<IconButton onClick={() => copyQuestion(quizId, totalIndex)}>
<CopyIcon color={"white"} />
</IconButton>
<IconButton
sx={{ cursor: "pointer", borderRadius: "6px", padding: "2px" }}
onClick={() => removeQuestion(quizId, totalIndex)}
>
<DeleteIcon color={"white"} />
</IconButton>
</Box>
)} )}
<OneIcon />
<IconButton {...draggableProps}>
<PointsIcon />
</IconButton>
</Box> </Box>
)} {isExpanded && (
</Paper> <Box
sx={{
display: "flex",
flexDirection: "column",
padding: 0,
borderRadius: "12px",
}}
>
{switchState.length === 0 ? (
<TypeQuestions totalIndex={totalIndex} />
) : (
<SwitchQuestionsPage totalIndex={totalIndex} />
)}
</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"; import type { DropResult } from "react-beautiful-dnd";
export const DraggableList = () => { export const DraggableList = () => {
const [draggableId, setDraggableId] = useState<number>(-1);
const [dropPlaceIndex, setDropPlaceIndex] = useState<number>(-1);
const quizId = Number(useParams().quizId); const quizId = Number(useParams().quizId);
const { listQuestions } = questionStore(); const { listQuestions } = questionStore();
const onDrop = () => {
setDraggableId(-1);
setDropPlaceIndex(-1);
};
const onDragEnd = ({ destination, source }: DropResult) => { const onDragEnd = ({ destination, source }: DropResult) => {
if (destination) { if (destination) {
const newItems = reorder( const newItems = reorder(
@ -35,29 +28,15 @@ export const DraggableList = () => {
}; };
return ( return (
<DragDropContext <DragDropContext onDragEnd={onDragEnd}>
onDragStart={({ draggableId }) => setDraggableId(Number(draggableId))}
onDragUpdate={({ destination }) => {
setDropPlaceIndex(destination?.index ?? -1);
}}
onDragEnd={onDragEnd}
>
<Droppable droppableId="droppable-list"> <Droppable droppableId="droppable-list">
{(provided) => ( {(provided, snapshot) => (
<Box <Box ref={provided.innerRef} {...provided.droppableProps}>
ref={provided.innerRef}
{...provided.droppableProps}
onMouseUp={onDrop}
>
{listQuestions[quizId]?.map((_, index) => ( {listQuestions[quizId]?.map((_, index) => (
<DraggableListItem <DraggableListItem
key={index} key={index}
index={index} index={index}
dropPlaceIndex={ isDragging={snapshot.isDraggingOver}
dropPlaceIndex < draggableId
? dropPlaceIndex - 1
: dropPlaceIndex
}
/> />
))} ))}
{provided.placeholder} {provided.placeholder}

@ -52,6 +52,7 @@ export default function SliderOptions({ totalIndex }: Props) {
}); });
}} }}
onBlur={({ target }) => { onBlur={({ target }) => {
const start = listQuestions[quizId][totalIndex].content.start;
const min = Number(target.value); const min = Number(target.value);
const max = Number( const max = Number(
listQuestions[quizId][totalIndex].content.range.split("—")[1] listQuestions[quizId][totalIndex].content.range.split("—")[1]
@ -68,6 +69,15 @@ export default function SliderOptions({ totalIndex }: Props) {
content: clonContent, content: clonContent,
}); });
} }
if (start < min) {
updateQuestionsList(quizId, totalIndex, {
content: {
...listQuestions[quizId][totalIndex].content,
start: min,
},
});
}
}} }}
/> />
<Typography></Typography> <Typography></Typography>
@ -88,10 +98,13 @@ export default function SliderOptions({ totalIndex }: Props) {
}); });
}} }}
onBlur={({ target }) => { onBlur={({ target }) => {
const start = listQuestions[quizId][totalIndex].content.start;
const step = listQuestions[quizId][totalIndex].content.step;
const min = Number( const min = Number(
listQuestions[quizId][totalIndex].content.range.split("—")[0] listQuestions[quizId][totalIndex].content.range.split("—")[0]
); );
const max = Number(target.value); const max = Number(target.value);
const range = max - min;
if (max <= min) { if (max <= min) {
const clonContent = listQuestions[quizId][totalIndex].content; const clonContent = listQuestions[quizId][totalIndex].content;
@ -104,6 +117,34 @@ export default function SliderOptions({ totalIndex }: Props) {
content: clonContent, 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> </Box>
@ -120,7 +161,12 @@ export default function SliderOptions({ totalIndex }: Props) {
<Typography>Начальное значение</Typography> <Typography>Начальное значение</Typography>
<CustomNumberField <CustomNumberField
placeholder={"50"} 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)} value={String(listQuestions[quizId][totalIndex].content.start)}
onChange={({ target }) => { onChange={({ target }) => {
const clonContent = listQuestions[quizId][totalIndex].content; const clonContent = listQuestions[quizId][totalIndex].content;
@ -129,21 +175,6 @@ export default function SliderOptions({ totalIndex }: Props) {
content: clonContent, 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>
<Box sx={{ width: "100%" }}> <Box sx={{ width: "100%" }}>
@ -171,11 +202,11 @@ export default function SliderOptions({ totalIndex }: Props) {
const range = max - min; const range = max - min;
const step = Number(target.value); const step = Number(target.value);
if (step > range) { if (step > max) {
updateQuestionsList(quizId, totalIndex, { updateQuestionsList(quizId, totalIndex, {
content: { content: {
...listQuestions[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 { useState } from "react";
import { Typography, Box, useTheme, ButtonBase } from "@mui/material"; import { Typography, Box, useTheme, ButtonBase } from "@mui/material";
import UploadBox from "@ui_kit/UploadBox"; 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 UploadIcon from "../../../assets/icons/UploadIcon";
import * as React from "react"; import * as React from "react";
import { questionStore, updateQuestionsList } from "@root/questions"; import { questionStore, updateQuestionsList } from "@root/questions";
@ -67,7 +67,7 @@ export default function UploadImage({ totalIndex }: UploadImageProps) {
/> />
</ButtonBase> </ButtonBase>
<UploadImageModal open={open} onClose={handleClose} imgHC={imgHC} /> <UploadImageModal open={open} onClose={handleClose} imgHC={imgHC} />
<CroppingModal <CropModal
opened={opened} opened={opened}
onClose={() => setOpened(false)} onClose={() => setOpened(false)}
picture={listQuestions[quizId][totalIndex].content.back} picture={listQuestions[quizId][totalIndex].content.back}

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

@ -124,7 +124,7 @@ export const updateVariants = (
questionStore.setState({ listQuestions }); questionStore.setState({ listQuestions });
}; };
export const createQuestion = (quizId: number) => { export const createQuestion = (quizId: number, placeIndex = -1) => {
const id = getRandom(1000000, 10000000); const id = getRandom(1000000, 10000000);
const newData = { ...questionStore.getState()["listQuestions"] }; const newData = { ...questionStore.getState()["listQuestions"] };
@ -132,73 +132,77 @@ export const createQuestion = (quizId: number) => {
newData[quizId] = []; newData[quizId] = [];
} }
newData[quizId].push({ newData[quizId].splice(
id, placeIndex < 0 ? newData[quizId].length : placeIndex,
title: "", 0,
description: "", {
type: "", id,
required: true, title: "",
deleted: true, description: "",
page: 0, type: "",
content: { required: true,
largeCheck: false, deleted: true,
large: "", page: 0,
multi: false, content: {
own: false, largeCheck: false,
innerNameCheck: false, large: "",
innerName: "", multi: false,
back: "", own: false,
placeholder: "", innerNameCheck: false,
type: "all", innerName: "",
autofill: true, back: "",
default: "", placeholder: "",
images: [], type: "all",
number: false, autofill: true,
single: false, default: "",
xy: "", images: [],
format: "carousel", number: false,
text: "", single: false,
picture: "", xy: "",
video: "", format: "carousel",
dateRange: false,
time: false,
form: "star",
steps: 5,
range: "0—100",
start: 50,
step: 1,
chooseRange: false,
required: false,
replText: "",
ratingExpanded: false,
ratingDescription: "",
variants: [
{
answer: "",
hints: "",
},
],
hint: {
text: "", text: "",
picture: "",
video: "", video: "",
}, dateRange: false,
rule: { time: false,
or: true, form: "star",
show: true, steps: 5,
reqs: [ range: "0—100",
start: 50,
step: 1,
chooseRange: false,
required: false,
replText: "",
ratingExpanded: false,
ratingDescription: "",
variants: [
{ {
id: "", answer: "",
vars: [], hints: "",
}, },
], ],
hint: {
text: "",
video: "",
},
rule: {
or: true,
show: true,
reqs: [
{
id: "",
vars: [],
},
],
},
}, },
}, version: 0,
version: 0, parent_ids: [0],
parent_ids: [0], created_at: "",
created_at: "", updated_at: "",
updated_at: "", expanded: false,
expanded: false, }
}); );
questionStore.setState({ listQuestions: newData }); questionStore.setState({ listQuestions: newData });
}; };

@ -30,16 +30,28 @@ export default function CustomNumberField({
const inputValue = event.target.value; const inputValue = event.target.value;
if ( if (
Number(inputValue) >= min && inputValue === "" ||
Number(inputValue) <= max && inputValue.match(/^\d*$/) ||
(inputValue === "" || (inputValue[0] === "-" && inputValue.slice(1).match(/^\d*$/))
inputValue.match(/^\d*$/) ||
(inputValue[0] === "-" && inputValue.slice(1).match(/^\d*$/)))
) { ) {
onChange?.({ ...event, target: { ...event.target, value: inputValue } }); 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 ( return (
<CustomTextField <CustomTextField
placeholder={placeholder} placeholder={placeholder}
@ -47,7 +59,7 @@ export default function CustomNumberField({
error={error} error={error}
onChange={onInputChange} onChange={onInputChange}
onKeyDown={onKeyDown} onKeyDown={onKeyDown}
onBlur={onBlur} onBlur={onInputBlur}
value={value} 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 { Box, Button } from "@mui/material";
import { FC, useState } from "react"; import { FC, useState } from "react";
import { CroppingModal } from "./CroppingModal"; import { CropModal } from "./CropModal";
const ImageCrop: FC = () => { const ImageCrop: FC = () => {
const [opened, setOpened] = useState<boolean>(false); const [opened, setOpened] = useState<boolean>(false);
return ( return (
<Box> <Box>
<CroppingModal opened={opened} onClose={() => setOpened(false)} />
<Button onClick={() => setOpened(true)}>Открыть модалку</Button> <Button onClick={() => setOpened(true)}>Открыть модалку</Button>
<CropModal opened={opened} onClose={() => setOpened(false)} />
</Box> </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]);
}