refactor crop modal & add original image restore
This commit is contained in:
parent
ed920affbc
commit
45dddd888d
@ -20,6 +20,7 @@ export const QUIZ_QUESTION_IMAGES: Omit<QuizQuestionImages, "id"> = {
|
|||||||
answer: "",
|
answer: "",
|
||||||
hints: "",
|
hints: "",
|
||||||
extendedText: "",
|
extendedText: "",
|
||||||
|
originalImageUrl: "",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
largeCheck: false,
|
largeCheck: false,
|
||||||
|
@ -11,7 +11,7 @@ export const QUIZ_QUESTION_VARIMG: Omit<QuizQuestionVarImg, "id"> = {
|
|||||||
innerNameCheck: false,
|
innerNameCheck: false,
|
||||||
innerName: "",
|
innerName: "",
|
||||||
required: false,
|
required: false,
|
||||||
variants: [{ answer: "", hints: "", extendedText: "" }],
|
variants: [{ answer: "", hints: "", extendedText: "", originalImageUrl: "" }],
|
||||||
largeCheck: false,
|
largeCheck: false,
|
||||||
replText: "",
|
replText: "",
|
||||||
},
|
},
|
||||||
|
@ -1,35 +1,35 @@
|
|||||||
import type {
|
import type {
|
||||||
QuizQuestionBase,
|
ImageQuestionVariant,
|
||||||
QuestionVariant,
|
QuestionBranchingRule,
|
||||||
QuestionHint,
|
QuestionHint,
|
||||||
QuestionBranchingRule,
|
QuizQuestionBase
|
||||||
} from "./shared";
|
} from "./shared";
|
||||||
|
|
||||||
export interface QuizQuestionImages extends QuizQuestionBase {
|
export interface QuizQuestionImages extends QuizQuestionBase {
|
||||||
type: "images";
|
type: "images";
|
||||||
content: {
|
content: {
|
||||||
/** Чекбокс "Вариант "свой ответ"" */
|
/** Чекбокс "Вариант "свой ответ"" */
|
||||||
own: boolean;
|
own: boolean;
|
||||||
/** Чекбокс "Можно несколько" */
|
/** Чекбокс "Можно несколько" */
|
||||||
multi: boolean;
|
multi: boolean;
|
||||||
/** Пропорции */
|
/** Пропорции */
|
||||||
xy: "1:1" | "1:2" | "2:1";
|
xy: "1:1" | "1:2" | "2:1";
|
||||||
/** Чекбокс "Внутреннее название вопроса" */
|
/** Чекбокс "Внутреннее название вопроса" */
|
||||||
innerNameCheck: boolean;
|
innerNameCheck: boolean;
|
||||||
/** Поле "Внутреннее название вопроса" */
|
/** Поле "Внутреннее название вопроса" */
|
||||||
innerName: string;
|
innerName: string;
|
||||||
/** Чекбокс "Большие картинки" */
|
/** Чекбокс "Большие картинки" */
|
||||||
large: boolean;
|
large: boolean;
|
||||||
/** Форма */
|
/** Форма */
|
||||||
format: "carousel" | "masonry";
|
format: "carousel" | "masonry";
|
||||||
/** Чекбокс "Необязательный вопрос" */
|
/** Чекбокс "Необязательный вопрос" */
|
||||||
required: boolean;
|
required: boolean;
|
||||||
/** Варианты (картинки) */
|
/** Варианты (картинки) */
|
||||||
variants: QuestionVariant[];
|
variants: ImageQuestionVariant[];
|
||||||
hint: QuestionHint;
|
hint: QuestionHint;
|
||||||
rule: QuestionBranchingRule;
|
rule: QuestionBranchingRule;
|
||||||
back: string;
|
back: string;
|
||||||
autofill: boolean;
|
autofill: boolean;
|
||||||
largeCheck: boolean;
|
largeCheck: boolean;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -11,47 +11,52 @@ import type { QuizQuestionVariant } from "./variant";
|
|||||||
import type { QuizQuestionVarImg } from "./varimg";
|
import type { QuizQuestionVarImg } from "./varimg";
|
||||||
|
|
||||||
export interface QuestionBranchingRule {
|
export interface QuestionBranchingRule {
|
||||||
/** Радиокнопка "Все условия обязательны" */
|
/** Радиокнопка "Все условия обязательны" */
|
||||||
or: boolean;
|
or: boolean;
|
||||||
show: boolean;
|
show: boolean;
|
||||||
title: string;
|
title: string;
|
||||||
reqs: {
|
reqs: {
|
||||||
id: string;
|
id: string;
|
||||||
/** Список выбранных вариантов */
|
/** Список выбранных вариантов */
|
||||||
vars: number[];
|
vars: number[];
|
||||||
}[];
|
}[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QuestionHint {
|
export interface QuestionHint {
|
||||||
/** Текст подсказки */
|
/** Текст подсказки */
|
||||||
text: string;
|
text: string;
|
||||||
/** URL видео подсказки */
|
/** URL видео подсказки */
|
||||||
video: string;
|
video: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type QuestionVariant = {
|
export type QuestionVariant = {
|
||||||
/** Текст */
|
/** Текст */
|
||||||
answer: string;
|
answer: string;
|
||||||
/** Текст подсказки */
|
/** Текст подсказки */
|
||||||
hints: string;
|
hints: string;
|
||||||
/** Дополнительное поле для текста, emoji, ссылки на картинку */
|
/** Дополнительное поле для текста, emoji, ссылки на картинку */
|
||||||
extendedText: string;
|
extendedText: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export interface ImageQuestionVariant extends QuestionVariant {
|
||||||
|
/** Оригинал изображения (до кропа) */
|
||||||
|
originalImageUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface QuizQuestionBase {
|
export interface QuizQuestionBase {
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
type: string;
|
type: string;
|
||||||
expanded: boolean;
|
expanded: boolean;
|
||||||
required: boolean;
|
required: boolean;
|
||||||
deleted: boolean;
|
deleted: boolean;
|
||||||
deleteTimeoutId: number;
|
deleteTimeoutId: number;
|
||||||
content: {
|
content: {
|
||||||
hint: QuestionHint;
|
hint: QuestionHint;
|
||||||
rule: QuestionBranchingRule;
|
rule: QuestionBranchingRule;
|
||||||
back: string;
|
back: string;
|
||||||
autofill: boolean;
|
autofill: boolean;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QuizQuestionInitial extends QuizQuestionBase {
|
export interface QuizQuestionInitial extends QuizQuestionBase {
|
||||||
@ -59,18 +64,18 @@ export interface QuizQuestionInitial extends QuizQuestionBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type AnyQuizQuestion =
|
export type AnyQuizQuestion =
|
||||||
| QuizQuestionVariant
|
| QuizQuestionVariant
|
||||||
| QuizQuestionImages
|
| QuizQuestionImages
|
||||||
| QuizQuestionVarImg
|
| QuizQuestionVarImg
|
||||||
| QuizQuestionEmoji
|
| QuizQuestionEmoji
|
||||||
| QuizQuestionText
|
| QuizQuestionText
|
||||||
| QuizQuestionSelect
|
| QuizQuestionSelect
|
||||||
| QuizQuestionDate
|
| QuizQuestionDate
|
||||||
| QuizQuestionNumber
|
| QuizQuestionNumber
|
||||||
| QuizQuestionFile
|
| QuizQuestionFile
|
||||||
| QuizQuestionPage
|
| QuizQuestionPage
|
||||||
| QuizQuestionRating
|
| QuizQuestionRating
|
||||||
| QuizQuestionInitial;
|
| QuizQuestionInitial;
|
||||||
|
|
||||||
export type QuizQuestionType = AnyQuizQuestion["type"];
|
export type QuizQuestionType = AnyQuizQuestion["type"];
|
||||||
|
|
||||||
|
@ -1,27 +1,27 @@
|
|||||||
import type {
|
import type {
|
||||||
QuizQuestionBase,
|
ImageQuestionVariant,
|
||||||
QuestionVariant,
|
QuestionBranchingRule,
|
||||||
QuestionHint,
|
QuestionHint,
|
||||||
QuestionBranchingRule,
|
QuizQuestionBase
|
||||||
} from "./shared";
|
} from "./shared";
|
||||||
|
|
||||||
export interface QuizQuestionVarImg extends QuizQuestionBase {
|
export interface QuizQuestionVarImg extends QuizQuestionBase {
|
||||||
type: "varimg";
|
type: "varimg";
|
||||||
content: {
|
content: {
|
||||||
/** Чекбокс "Вариант "свой ответ"" */
|
/** Чекбокс "Вариант "свой ответ"" */
|
||||||
own: boolean;
|
own: boolean;
|
||||||
/** Чекбокс "Внутреннее название вопроса" */
|
/** Чекбокс "Внутреннее название вопроса" */
|
||||||
innerNameCheck: boolean;
|
innerNameCheck: boolean;
|
||||||
/** Поле "Внутреннее название вопроса" */
|
/** Поле "Внутреннее название вопроса" */
|
||||||
innerName: string;
|
innerName: string;
|
||||||
/** Чекбокс "Необязательный вопрос" */
|
/** Чекбокс "Необязательный вопрос" */
|
||||||
required: boolean;
|
required: boolean;
|
||||||
variants: QuestionVariant[];
|
variants: ImageQuestionVariant[];
|
||||||
hint: QuestionHint;
|
hint: QuestionHint;
|
||||||
rule: QuestionBranchingRule;
|
rule: QuestionBranchingRule;
|
||||||
back: string;
|
back: string;
|
||||||
autofill: boolean;
|
autofill: boolean;
|
||||||
largeCheck: boolean;
|
largeCheck: boolean;
|
||||||
replText: string;
|
replText: string;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -10,13 +10,13 @@ import { reorder } from "./helper";
|
|||||||
|
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import type { DropResult } from "react-beautiful-dnd";
|
import type { DropResult } from "react-beautiful-dnd";
|
||||||
import type { QuestionVariant } from "../../../model/questionTypes/shared";
|
import type { ImageQuestionVariant, QuestionVariant } from "../../../model/questionTypes/shared";
|
||||||
|
|
||||||
type AnswerDraggableListProps = {
|
type AnswerDraggableListProps = {
|
||||||
variants: QuestionVariant[];
|
variants: QuestionVariant[];
|
||||||
totalIndex: number;
|
totalIndex: number;
|
||||||
additionalContent?: (variant: QuestionVariant, index: number) => ReactNode;
|
additionalContent?: (variant: QuestionVariant | ImageQuestionVariant, index: number) => ReactNode;
|
||||||
additionalMobile?: (variant: QuestionVariant, index: number) => ReactNode;
|
additionalMobile?: (variant: QuestionVariant | ImageQuestionVariant, index: number) => ReactNode;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const AnswerDraggableList = ({
|
export const AnswerDraggableList = ({
|
||||||
|
@ -29,6 +29,7 @@ import SwitchOptionsAndPict from "./switchOptionsAndPict";
|
|||||||
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
|
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
|
||||||
import { produce } from "immer";
|
import { produce } from "immer";
|
||||||
import type { QuizQuestionVarImg } from "../../../model/questionTypes/varimg";
|
import type { QuizQuestionVarImg } from "../../../model/questionTypes/varimg";
|
||||||
|
import { openCropModal } from "@root/cropModal";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
totalIndex: number;
|
totalIndex: number;
|
||||||
@ -36,7 +37,6 @@ interface Props {
|
|||||||
|
|
||||||
export default function OptionsAndPicture({ totalIndex }: Props) {
|
export default function OptionsAndPicture({ totalIndex }: Props) {
|
||||||
const [isUploadImageModalOpen, setIsUploadImageModalOpen] = useState(false);
|
const [isUploadImageModalOpen, setIsUploadImageModalOpen] = useState(false);
|
||||||
const [isCropModalOpen, setIsCropModalOpen] = useState<boolean>(false);
|
|
||||||
const [switchState, setSwitchState] = useState("setting");
|
const [switchState, setSwitchState] = useState("setting");
|
||||||
const [currentIndex, setCurrentIndex] = useState<number>(0);
|
const [currentIndex, setCurrentIndex] = useState<number>(0);
|
||||||
const quizId = Number(useParams().quizId);
|
const quizId = Number(useParams().quizId);
|
||||||
@ -62,7 +62,10 @@ export default function OptionsAndPicture({ totalIndex }: Props) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
setIsUploadImageModalOpen(false);
|
setIsUploadImageModalOpen(false);
|
||||||
setIsCropModalOpen(true);
|
openCropModal(
|
||||||
|
question.content.variants[currentIndex]?.extendedText,
|
||||||
|
question.content.variants[currentIndex]?.originalImageUrl
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -78,8 +81,13 @@ export default function OptionsAndPicture({ totalIndex }: Props) {
|
|||||||
<AddOrEditImageButton
|
<AddOrEditImageButton
|
||||||
imageSrc={variant.extendedText}
|
imageSrc={variant.extendedText}
|
||||||
onImageClick={() => {
|
onImageClick={() => {
|
||||||
|
if (!("originalImageUrl" in variant)) return;
|
||||||
|
|
||||||
setCurrentIndex(index);
|
setCurrentIndex(index);
|
||||||
if (variant.extendedText) return setIsCropModalOpen(true);
|
if (variant.extendedText) return openCropModal(
|
||||||
|
variant.extendedText,
|
||||||
|
variant.originalImageUrl
|
||||||
|
);
|
||||||
|
|
||||||
setIsUploadImageModalOpen(true);
|
setIsUploadImageModalOpen(true);
|
||||||
}}
|
}}
|
||||||
@ -98,8 +106,13 @@ export default function OptionsAndPicture({ totalIndex }: Props) {
|
|||||||
<AddOrEditImageButton
|
<AddOrEditImageButton
|
||||||
imageSrc={variant.extendedText}
|
imageSrc={variant.extendedText}
|
||||||
onImageClick={() => {
|
onImageClick={() => {
|
||||||
|
if (!("originalImageUrl" in variant)) return;
|
||||||
|
|
||||||
setCurrentIndex(index);
|
setCurrentIndex(index);
|
||||||
if (variant.extendedText) return setIsCropModalOpen(true);
|
if (variant.extendedText) return openCropModal(
|
||||||
|
variant.extendedText,
|
||||||
|
variant.originalImageUrl
|
||||||
|
);
|
||||||
|
|
||||||
setIsUploadImageModalOpen(true);
|
setIsUploadImageModalOpen(true);
|
||||||
}}
|
}}
|
||||||
@ -119,10 +132,7 @@ export default function OptionsAndPicture({ totalIndex }: Props) {
|
|||||||
imgHC={uploadImage}
|
imgHC={uploadImage}
|
||||||
/>
|
/>
|
||||||
<CropModal
|
<CropModal
|
||||||
opened={isCropModalOpen}
|
onSaveImageClick={url => {
|
||||||
onClose={() => setIsCropModalOpen(false)}
|
|
||||||
picture={question.content.variants[currentIndex]?.extendedText}
|
|
||||||
onCropPress={url => {
|
|
||||||
const content = produce(question.content, draft => {
|
const content = produce(question.content, draft => {
|
||||||
draft.variants[currentIndex].extendedText = url;
|
draft.variants[currentIndex].extendedText = url;
|
||||||
});
|
});
|
||||||
@ -329,6 +339,7 @@ export default function OptionsAndPicture({ totalIndex }: Props) {
|
|||||||
answer: "",
|
answer: "",
|
||||||
hints: "",
|
hints: "",
|
||||||
extendedText: "",
|
extendedText: "",
|
||||||
|
originalImageUrl: "",
|
||||||
});
|
});
|
||||||
updateQuestionsList<QuizQuestionVarImg>(quizId, totalIndex, {
|
updateQuestionsList<QuizQuestionVarImg>(quizId, totalIndex, {
|
||||||
content: clonedContent,
|
content: clonedContent,
|
||||||
|
@ -20,6 +20,7 @@ import SwitchAnswerOptionsPict from "./switchOptionsPict";
|
|||||||
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
|
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
|
||||||
import { produce } from "immer";
|
import { produce } from "immer";
|
||||||
import type { QuizQuestionImages } from "../../../model/questionTypes/images";
|
import type { QuizQuestionImages } from "../../../model/questionTypes/images";
|
||||||
|
import { openCropModal } from "@root/cropModal";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
totalIndex: number;
|
totalIndex: number;
|
||||||
@ -27,7 +28,6 @@ interface Props {
|
|||||||
|
|
||||||
export default function OptionsPicture({ totalIndex }: Props) {
|
export default function OptionsPicture({ totalIndex }: Props) {
|
||||||
const [isUploadImageModalOpen, setIsUploadImageModalOpen] = useState(false);
|
const [isUploadImageModalOpen, setIsUploadImageModalOpen] = useState(false);
|
||||||
const [isCropModalOpen, setIsCropModalOpen] = useState<boolean>(false);
|
|
||||||
const [currentIndex, setCurrentIndex] = useState<number>(0);
|
const [currentIndex, setCurrentIndex] = useState<number>(0);
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const isMobile = useMediaQuery(theme.breakpoints.down(790));
|
const isMobile = useMediaQuery(theme.breakpoints.down(790));
|
||||||
@ -45,20 +45,26 @@ export default function OptionsPicture({ totalIndex }: Props) {
|
|||||||
const [file] = Array.from(files);
|
const [file] = Array.from(files);
|
||||||
|
|
||||||
const clonedContent = { ...question.content };
|
const clonedContent = { ...question.content };
|
||||||
clonedContent.variants[currentIndex].extendedText =
|
|
||||||
URL.createObjectURL(file);
|
const url = URL.createObjectURL(file);
|
||||||
|
clonedContent.variants[currentIndex].extendedText = url;
|
||||||
|
clonedContent.variants[currentIndex].originalImageUrl = url;
|
||||||
|
|
||||||
updateQuestionsList<QuizQuestionImages>(quizId, totalIndex, {
|
updateQuestionsList<QuizQuestionImages>(quizId, totalIndex, {
|
||||||
content: clonedContent,
|
content: clonedContent,
|
||||||
});
|
});
|
||||||
|
|
||||||
setIsUploadImageModalOpen(false);
|
setIsUploadImageModalOpen(false);
|
||||||
setIsCropModalOpen(true);
|
openCropModal(
|
||||||
|
question.content.variants[currentIndex]?.extendedText,
|
||||||
|
question.content.variants[currentIndex]?.originalImageUrl,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const addNewAnswer = () => {
|
const addNewAnswer = () => {
|
||||||
const answerNew = question.content.variants.slice();
|
const answerNew = question.content.variants.slice();
|
||||||
answerNew.push({ answer: "", hints: "", extendedText: "" });
|
answerNew.push({ answer: "", hints: "", extendedText: "", originalImageUrl: "" });
|
||||||
|
|
||||||
updateQuestionsList<QuizQuestionImages>(quizId, totalIndex, {
|
updateQuestionsList<QuizQuestionImages>(quizId, totalIndex, {
|
||||||
content: { ...question.content, variants: answerNew },
|
content: { ...question.content, variants: answerNew },
|
||||||
@ -77,8 +83,15 @@ export default function OptionsPicture({ totalIndex }: Props) {
|
|||||||
<AddOrEditImageButton
|
<AddOrEditImageButton
|
||||||
imageSrc={variant.extendedText}
|
imageSrc={variant.extendedText}
|
||||||
onImageClick={() => {
|
onImageClick={() => {
|
||||||
|
if (!("originalImageUrl" in variant)) return;
|
||||||
|
|
||||||
setCurrentIndex(index);
|
setCurrentIndex(index);
|
||||||
if (variant.extendedText) return setIsCropModalOpen(true);
|
if (variant.extendedText) {
|
||||||
|
return openCropModal(
|
||||||
|
variant.extendedText,
|
||||||
|
variant.originalImageUrl
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
setIsUploadImageModalOpen(true);
|
setIsUploadImageModalOpen(true);
|
||||||
}}
|
}}
|
||||||
@ -97,8 +110,15 @@ export default function OptionsPicture({ totalIndex }: Props) {
|
|||||||
<AddOrEditImageButton
|
<AddOrEditImageButton
|
||||||
imageSrc={variant.extendedText}
|
imageSrc={variant.extendedText}
|
||||||
onImageClick={() => {
|
onImageClick={() => {
|
||||||
|
if (!("originalImageUrl" in variant)) return;
|
||||||
|
|
||||||
setCurrentIndex(index);
|
setCurrentIndex(index);
|
||||||
if (variant.extendedText) return setIsCropModalOpen(true);
|
if (variant.extendedText) {
|
||||||
|
return openCropModal(
|
||||||
|
variant.extendedText,
|
||||||
|
variant.originalImageUrl
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
setIsUploadImageModalOpen(true);
|
setIsUploadImageModalOpen(true);
|
||||||
}}
|
}}
|
||||||
@ -118,10 +138,7 @@ export default function OptionsPicture({ totalIndex }: Props) {
|
|||||||
imgHC={uploadImage}
|
imgHC={uploadImage}
|
||||||
/>
|
/>
|
||||||
<CropModal
|
<CropModal
|
||||||
opened={isCropModalOpen}
|
onSaveImageClick={url => {
|
||||||
onClose={() => setIsCropModalOpen(false)}
|
|
||||||
picture={question.content.variants[currentIndex]?.extendedText}
|
|
||||||
onCropPress={url => {
|
|
||||||
const content = produce(question.content, draft => {
|
const content = produce(question.content, draft => {
|
||||||
draft.variants[currentIndex].extendedText = url;
|
draft.variants[currentIndex].extendedText = url;
|
||||||
});
|
});
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import { useParams } from "react-router-dom";
|
import { useParams } from "react-router-dom";
|
||||||
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 { CropModal } from "@ui_kit/Modal/CropModal";
|
import { CropModal } from "@ui_kit/Modal/CropModal";
|
||||||
@ -10,6 +9,7 @@ import { UploadImageModal } from "./UploadImageModal";
|
|||||||
|
|
||||||
import type { DragEvent } from "react";
|
import type { DragEvent } from "react";
|
||||||
import type { QuizQuestionImages } from "../../../model/questionTypes/images";
|
import type { QuizQuestionImages } from "../../../model/questionTypes/images";
|
||||||
|
import { openCropModal } from "@root/cropModal";
|
||||||
|
|
||||||
type UploadImageProps = {
|
type UploadImageProps = {
|
||||||
totalIndex: number;
|
totalIndex: number;
|
||||||
@ -36,10 +36,9 @@ export default function UploadImage({ totalIndex }: UploadImageProps) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
handleClose();
|
handleClose();
|
||||||
setOpened(true);
|
openCropModal(question.content.back, question.content.back);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const [opened, setOpened] = useState<boolean>(false);
|
|
||||||
|
|
||||||
const handleDrop = (event: DragEvent<HTMLDivElement>) => {
|
const handleDrop = (event: DragEvent<HTMLDivElement>) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@ -72,11 +71,7 @@ export default function UploadImage({ totalIndex }: UploadImageProps) {
|
|||||||
/>
|
/>
|
||||||
</ButtonBase>
|
</ButtonBase>
|
||||||
<UploadImageModal open={open} onClose={handleClose} imgHC={imgHC} />
|
<UploadImageModal open={open} onClose={handleClose} imgHC={imgHC} />
|
||||||
<CropModal
|
<CropModal />
|
||||||
opened={opened}
|
|
||||||
onClose={() => setOpened(false)}
|
|
||||||
picture={question.content.back}
|
|
||||||
/>
|
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -2,18 +2,16 @@ 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 { CropModal } from "@ui_kit/Modal/CropModal";
|
import { CropModal } from "@ui_kit/Modal/CropModal";
|
||||||
|
import { openCropModal } from "@root/cropModal";
|
||||||
|
|
||||||
export default function ImageAndVideoButtons() {
|
export default function ImageAndVideoButtons() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
const [opened, setOpened] = useState<boolean>(false);
|
|
||||||
|
|
||||||
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={() => openCropModal("", "")} />
|
||||||
<CropModal opened={opened} onClose={() => setOpened(false)} />
|
<CropModal />
|
||||||
<Typography
|
<Typography
|
||||||
sx={{
|
sx={{
|
||||||
fontWeight: 400,
|
fontWeight: 400,
|
||||||
|
60
src/stores/cropModal.ts
Normal file
60
src/stores/cropModal.ts
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import { devtools } from "zustand/middleware";
|
||||||
|
|
||||||
|
|
||||||
|
type CropModalStore = {
|
||||||
|
isCropModalOpen: boolean;
|
||||||
|
imageUrl: string | null;
|
||||||
|
originalImageUrl: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const initialState: CropModalStore = {
|
||||||
|
isCropModalOpen: false,
|
||||||
|
imageUrl: null,
|
||||||
|
originalImageUrl: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useCropModalStore = create<CropModalStore>()(
|
||||||
|
devtools(
|
||||||
|
() => initialState,
|
||||||
|
{
|
||||||
|
name: "CropModalStore",
|
||||||
|
enabled: process.env.NODE_ENV === "development",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const openCropModal = (imageUrl: string, originalImageUrl: string) => useCropModalStore.setState(
|
||||||
|
{
|
||||||
|
isCropModalOpen: true,
|
||||||
|
imageUrl,
|
||||||
|
originalImageUrl,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
{
|
||||||
|
type: "openCropModal",
|
||||||
|
imageUrl,
|
||||||
|
originalImageUrl,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export const closeCropModal = () => useCropModalStore.setState(
|
||||||
|
initialState,
|
||||||
|
false,
|
||||||
|
"closeCropModal"
|
||||||
|
);
|
||||||
|
|
||||||
|
export const setCropModalImageUrl = (imageUrl: string | null) => useCropModalStore.setState(
|
||||||
|
{ imageUrl },
|
||||||
|
false,
|
||||||
|
{
|
||||||
|
type: "setCropModalImageUrl",
|
||||||
|
imageUrl,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export const resetToOriginalImage = () => useCropModalStore.setState(
|
||||||
|
state => ({ imageUrl: state.originalImageUrl }),
|
||||||
|
false,
|
||||||
|
"resetToOriginalImage"
|
||||||
|
);
|
@ -1,17 +1,14 @@
|
|||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { persist } from "zustand/middleware";
|
import { devtools, persist } from "zustand/middleware";
|
||||||
|
|
||||||
import { QuizQuestionEmoji } from "../model/questionTypes/emoji";
|
|
||||||
import { QuizQuestionImages } from "../model/questionTypes/images";
|
|
||||||
import { QuizQuestionVariant } from "../model/questionTypes/variant";
|
|
||||||
import { QuizQuestionVarImg } from "../model/questionTypes/varimg";
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
AnyQuizQuestion,
|
AnyQuizQuestion,
|
||||||
QuizQuestionType,
|
ImageQuestionVariant,
|
||||||
QuestionVariant,
|
QuestionVariant,
|
||||||
|
QuizQuestionType
|
||||||
} from "../model/questionTypes/shared";
|
} from "../model/questionTypes/shared";
|
||||||
|
|
||||||
|
import { produce, setAutoFreeze } from "immer";
|
||||||
import { QUIZ_QUESTION_BASE } from "../constants/base";
|
import { QUIZ_QUESTION_BASE } from "../constants/base";
|
||||||
import { QUIZ_QUESTION_DATE } from "../constants/date";
|
import { QUIZ_QUESTION_DATE } from "../constants/date";
|
||||||
import { QUIZ_QUESTION_EMOJI } from "../constants/emoji";
|
import { QUIZ_QUESTION_EMOJI } from "../constants/emoji";
|
||||||
@ -24,218 +21,220 @@ import { QUIZ_QUESTION_SELECT } from "../constants/select";
|
|||||||
import { QUIZ_QUESTION_TEXT } from "../constants/text";
|
import { QUIZ_QUESTION_TEXT } from "../constants/text";
|
||||||
import { QUIZ_QUESTION_VARIANT } from "../constants/variant";
|
import { QUIZ_QUESTION_VARIANT } from "../constants/variant";
|
||||||
import { QUIZ_QUESTION_VARIMG } from "../constants/varimg";
|
import { QUIZ_QUESTION_VARIMG } from "../constants/varimg";
|
||||||
import { setAutoFreeze } from "immer";
|
|
||||||
|
|
||||||
|
|
||||||
setAutoFreeze(false);
|
setAutoFreeze(false);
|
||||||
|
|
||||||
interface QuestionStore {
|
interface QuestionStore {
|
||||||
listQuestions: Record<string, AnyQuizQuestion[]>;
|
listQuestions: Record<string, AnyQuizQuestion[]>;
|
||||||
openedModalSettings: string;
|
openedModalSettings: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
let isFirstPartialize = true;
|
let isFirstPartialize = true;
|
||||||
|
|
||||||
export const questionStore = create<QuestionStore>()(
|
export const questionStore = create<QuestionStore>()(
|
||||||
persist<QuestionStore>(
|
persist(
|
||||||
() => ({
|
devtools(
|
||||||
listQuestions: {},
|
() => ({
|
||||||
openedModalSettings: "",
|
listQuestions: {},
|
||||||
}),
|
openedModalSettings: "",
|
||||||
{
|
}),
|
||||||
name: "question",
|
{
|
||||||
partialize: (state: QuestionStore) => {
|
name: "Question",
|
||||||
if (isFirstPartialize) {
|
enabled: process.env.NODE_ENV === "development",
|
||||||
isFirstPartialize = false;
|
trace: process.env.NODE_ENV === "development",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
{
|
||||||
|
name: "question",
|
||||||
|
partialize: (state: QuestionStore) => {
|
||||||
|
if (isFirstPartialize) {
|
||||||
|
isFirstPartialize = false;
|
||||||
|
|
||||||
Object.keys(state.listQuestions).forEach((quizId) => {
|
Object.keys(state.listQuestions).forEach((quizId) => {
|
||||||
[...state.listQuestions[quizId]].forEach(({ id, deleted }) => {
|
[...state.listQuestions[quizId]].forEach(({ id, deleted }) => {
|
||||||
if (deleted) {
|
if (deleted) {
|
||||||
const removedItemIndex = state.listQuestions[quizId].findIndex(
|
const removedItemIndex = state.listQuestions[quizId].findIndex(
|
||||||
(item) => item.id === id
|
(item) => item.id === id
|
||||||
);
|
);
|
||||||
|
|
||||||
state.listQuestions[quizId].splice(removedItemIndex, 1);
|
state.listQuestions[quizId].splice(removedItemIndex, 1);
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return state;
|
|
||||||
},
|
|
||||||
merge: (persistedState, currentState) => {
|
|
||||||
const state = persistedState as QuestionStore;
|
|
||||||
|
|
||||||
// replace blob urls with ""
|
|
||||||
Object.values(state.listQuestions).forEach(questions => {
|
|
||||||
questions.forEach(question => {
|
|
||||||
if (question.type === "page" && question.content.picture.startsWith("blob:")) {
|
|
||||||
question.content.picture = "";
|
|
||||||
}
|
|
||||||
if (question.type === "images") {
|
|
||||||
question.content.variants.forEach(variant => {
|
|
||||||
if (variant.extendedText.startsWith("blob:")) {
|
|
||||||
variant.extendedText = "";
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
if (question.type === "varimg") {
|
}
|
||||||
question.content.variants.forEach(variant => {
|
|
||||||
if (variant.extendedText.startsWith("blob:")) {
|
return state;
|
||||||
variant.extendedText = "";
|
},
|
||||||
|
merge: (persistedState, currentState) => {
|
||||||
|
const state = persistedState as QuestionStore;
|
||||||
|
|
||||||
|
// replace blob urls with ""
|
||||||
|
Object.values(state.listQuestions).forEach(questions => {
|
||||||
|
questions.forEach(question => {
|
||||||
|
if (question.type === "page") {
|
||||||
|
if (question.content.picture.startsWith("blob:")) {
|
||||||
|
question.content.picture = "";
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
}
|
if (question.type === "images") {
|
||||||
|
question.content.variants.forEach(variant => {
|
||||||
|
if (variant.extendedText.startsWith("blob:")) {
|
||||||
|
variant.extendedText = "";
|
||||||
|
}
|
||||||
|
if (variant.originalImageUrl.startsWith("blob:")) {
|
||||||
|
variant.originalImageUrl = "";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (question.type === "varimg") {
|
||||||
|
question.content.variants.forEach(variant => {
|
||||||
|
if (variant.extendedText.startsWith("blob:")) {
|
||||||
|
variant.extendedText = "";
|
||||||
|
}
|
||||||
|
if (variant.originalImageUrl.startsWith("blob:")) {
|
||||||
|
variant.originalImageUrl = "";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...currentState,
|
...currentState,
|
||||||
...state,
|
...state,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
export const updateQuestionsList = <T = AnyQuizQuestion>(
|
export const updateQuestionsList = <T = AnyQuizQuestion>(
|
||||||
quizId: number,
|
quizId: number,
|
||||||
index: number,
|
index: number,
|
||||||
data: Partial<T>
|
data: Partial<T>
|
||||||
) => {
|
) => {
|
||||||
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
||||||
questionListClone[quizId][index] = {
|
questionListClone[quizId][index] = {
|
||||||
...questionListClone[quizId][index],
|
...questionListClone[quizId][index],
|
||||||
...data,
|
...data,
|
||||||
};
|
};
|
||||||
questionStore.setState({ listQuestions: questionListClone });
|
questionStore.setState({ listQuestions: questionListClone });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const updateQuestionsListDragAndDrop = (
|
export const updateQuestionsListDragAndDrop = (
|
||||||
quizId: number,
|
quizId: number,
|
||||||
updatedQuestions: AnyQuizQuestion[]
|
updatedQuestions: AnyQuizQuestion[]
|
||||||
) => {
|
) => {
|
||||||
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
||||||
questionStore.setState({
|
questionStore.setState({
|
||||||
listQuestions: { ...questionListClone, [quizId]: updatedQuestions },
|
listQuestions: { ...questionListClone, [quizId]: updatedQuestions },
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const updateVariants = (
|
export const updateVariants = (
|
||||||
quizId: number,
|
quizId: number,
|
||||||
index: number,
|
index: number,
|
||||||
variants: QuestionVariant[]
|
variants: ImageQuestionVariant[] | QuestionVariant[],
|
||||||
) => {
|
) => setProducedState(state => {
|
||||||
const listQuestions = { ...questionStore.getState()["listQuestions"] };
|
const question = state.listQuestions[quizId][index];
|
||||||
|
|
||||||
switch (listQuestions[quizId][index].type) {
|
if ("variants" in question.content) question.content.variants = variants;
|
||||||
case "emoji":
|
});
|
||||||
const emojiState = listQuestions[quizId][index] as QuizQuestionEmoji;
|
|
||||||
emojiState.content.variants = variants;
|
|
||||||
return questionStore.setState({ listQuestions });
|
|
||||||
|
|
||||||
case "images":
|
|
||||||
const imagesState = listQuestions[quizId][index] as QuizQuestionImages;
|
|
||||||
imagesState.content.variants = variants;
|
|
||||||
return questionStore.setState({ listQuestions });
|
|
||||||
|
|
||||||
case "variant":
|
|
||||||
const variantState = listQuestions[quizId][index] as QuizQuestionVariant;
|
|
||||||
variantState.content.variants = variants;
|
|
||||||
return questionStore.setState({ listQuestions });
|
|
||||||
|
|
||||||
case "varimg":
|
|
||||||
const varImgState = listQuestions[quizId][index] as QuizQuestionVarImg;
|
|
||||||
varImgState.content.variants = variants;
|
|
||||||
return questionStore.setState({ listQuestions });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const createQuestion = (
|
export const createQuestion = (
|
||||||
quizId: number,
|
quizId: number,
|
||||||
questionType: QuizQuestionType = "nonselected",
|
questionType: QuizQuestionType = "nonselected",
|
||||||
placeIndex = -1
|
placeIndex = -1
|
||||||
) => {
|
) => {
|
||||||
const id = getRandom();
|
const id = getRandom();
|
||||||
const newData = { ...questionStore.getState()["listQuestions"] };
|
const newData = { ...questionStore.getState()["listQuestions"] };
|
||||||
|
|
||||||
if (!newData[quizId]) {
|
if (!newData[quizId]) {
|
||||||
newData[quizId] = [];
|
newData[quizId] = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultObject = [
|
const defaultObject = [
|
||||||
QUIZ_QUESTION_BASE,
|
QUIZ_QUESTION_BASE,
|
||||||
QUIZ_QUESTION_DATE,
|
QUIZ_QUESTION_DATE,
|
||||||
QUIZ_QUESTION_EMOJI,
|
QUIZ_QUESTION_EMOJI,
|
||||||
QUIZ_QUESTION_FILE,
|
QUIZ_QUESTION_FILE,
|
||||||
QUIZ_QUESTION_IMAGES,
|
QUIZ_QUESTION_IMAGES,
|
||||||
QUIZ_QUESTION_NUMBER,
|
QUIZ_QUESTION_NUMBER,
|
||||||
QUIZ_QUESTION_PAGE,
|
QUIZ_QUESTION_PAGE,
|
||||||
QUIZ_QUESTION_RATING,
|
QUIZ_QUESTION_RATING,
|
||||||
QUIZ_QUESTION_SELECT,
|
QUIZ_QUESTION_SELECT,
|
||||||
QUIZ_QUESTION_TEXT,
|
QUIZ_QUESTION_TEXT,
|
||||||
QUIZ_QUESTION_VARIANT,
|
QUIZ_QUESTION_VARIANT,
|
||||||
QUIZ_QUESTION_VARIMG,
|
QUIZ_QUESTION_VARIMG,
|
||||||
].find((defaultObjectItem) => defaultObjectItem.type === questionType);
|
].find((defaultObjectItem) => defaultObjectItem.type === questionType);
|
||||||
|
|
||||||
if (defaultObject) {
|
if (defaultObject) {
|
||||||
newData[quizId].splice(
|
newData[quizId].splice(
|
||||||
placeIndex < 0 ? newData[quizId].length : placeIndex,
|
placeIndex < 0 ? newData[quizId].length : placeIndex,
|
||||||
0,
|
0,
|
||||||
{ ...defaultObject, id }
|
{ ...defaultObject, id }
|
||||||
);
|
);
|
||||||
|
|
||||||
questionStore.setState({ listQuestions: newData });
|
questionStore.setState({ listQuestions: newData });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const copyQuestion = (quizId: number, copiedQuestionIndex: number) => {
|
export const copyQuestion = (quizId: number, copiedQuestionIndex: number) => {
|
||||||
const listQuestions = { ...questionStore.getState()["listQuestions"] };
|
const listQuestions = { ...questionStore.getState()["listQuestions"] };
|
||||||
|
|
||||||
const copiedQuiz = listQuestions[quizId][copiedQuestionIndex]
|
const copiedQuiz = listQuestions[quizId][copiedQuestionIndex];
|
||||||
copiedQuiz.id = getRandom()
|
copiedQuiz.id = getRandom();
|
||||||
listQuestions[quizId].splice(
|
listQuestions[quizId].splice(
|
||||||
copiedQuestionIndex,
|
copiedQuestionIndex,
|
||||||
0,
|
0,
|
||||||
copiedQuiz
|
copiedQuiz
|
||||||
);
|
);
|
||||||
|
|
||||||
questionStore.setState({ listQuestions });
|
questionStore.setState({ listQuestions });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const removeQuestionForce = (quizId: number, removedId: number) => {
|
export const removeQuestionForce = (quizId: number, removedId: number) => {
|
||||||
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
||||||
const removedItemIndex = questionListClone[quizId].findIndex(
|
const removedItemIndex = questionListClone[quizId].findIndex(
|
||||||
({ id }) => id === removedId
|
({ id }) => id === removedId
|
||||||
);
|
);
|
||||||
questionListClone[quizId].splice(removedItemIndex, 1);
|
questionListClone[quizId].splice(removedItemIndex, 1);
|
||||||
questionStore.setState({ listQuestions: questionListClone });
|
questionStore.setState({ listQuestions: questionListClone });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const removeQuestion = (quizId: number, index: number) => {
|
export const removeQuestion = (quizId: number, index: number) => {
|
||||||
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
const questionListClone = { ...questionStore.getState()["listQuestions"] };
|
||||||
questionListClone[quizId][index].deleted = true;
|
questionListClone[quizId][index].deleted = true;
|
||||||
questionStore.setState({ listQuestions: questionListClone });
|
questionStore.setState({ listQuestions: questionListClone });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const resetSomeField = (data: Record<string, string>) => {
|
export const resetSomeField = (data: Record<string, string>) => {
|
||||||
questionStore.setState(data);
|
questionStore.setState(data);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const findQuestionById = (quizId: number) => {
|
export const findQuestionById = (quizId: number) => {
|
||||||
let found = null;
|
let found = null;
|
||||||
questionStore
|
questionStore
|
||||||
.getState()
|
.getState()
|
||||||
["listQuestions"][quizId].some((quiz: AnyQuizQuestion, index: number) => {
|
["listQuestions"][quizId].some((quiz: AnyQuizQuestion, index: number) => {
|
||||||
if (quiz.id === quizId) {
|
if (quiz.id === quizId) {
|
||||||
found = { quiz, index };
|
found = { quiz, index };
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
return false;
|
||||||
});
|
});
|
||||||
return found;
|
return found;
|
||||||
};
|
};
|
||||||
|
|
||||||
function getRandom() {
|
function getRandom() {
|
||||||
const min = Math.ceil(1000000);
|
const min = Math.ceil(1000000);
|
||||||
const max = Math.floor(10000000);
|
const max = Math.floor(10000000);
|
||||||
return Math.floor(Math.random() * (max - min)) + min;
|
return Math.floor(Math.random() * (max - min)) + min;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setProducedState<A extends string | { type: unknown; }>(
|
||||||
|
recipe: (state: QuestionStore) => void,
|
||||||
|
action?: A,
|
||||||
|
) {
|
||||||
|
questionStore.setState(state => produce(state, recipe), false, action);
|
||||||
|
}
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
import { CropIcon } from "@icons/CropIcon";
|
||||||
|
import { ResetIcon } from "@icons/ResetIcon";
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
Button,
|
Button,
|
||||||
@ -10,15 +12,11 @@ import {
|
|||||||
useMediaQuery,
|
useMediaQuery,
|
||||||
useTheme,
|
useTheme,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import React, { FC, useEffect, useRef, useState } from "react";
|
import { closeCropModal, resetToOriginalImage, setCropModalImageUrl, useCropModalStore } from "@root/cropModal";
|
||||||
|
import { FC, useRef, useState } from "react";
|
||||||
import ReactCrop, { Crop, PixelCrop } from "react-image-crop";
|
import ReactCrop, { Crop, PixelCrop } from "react-image-crop";
|
||||||
|
|
||||||
import { canvasPreview } from "./utils/canvasPreview";
|
|
||||||
|
|
||||||
import { ResetIcon } from "@icons/ResetIcon";
|
|
||||||
|
|
||||||
import { CropIcon } from "@icons/CropIcon";
|
|
||||||
import "react-image-crop/dist/ReactCrop.css";
|
import "react-image-crop/dist/ReactCrop.css";
|
||||||
|
import { canvasPreview } from "./utils/canvasPreview";
|
||||||
|
|
||||||
|
|
||||||
const styleSlider: SxProps<Theme> = {
|
const styleSlider: SxProps<Theme> = {
|
||||||
@ -45,45 +43,25 @@ const styleSlider: SxProps<Theme> = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
interface Iprops {
|
interface Props {
|
||||||
opened: boolean;
|
onSaveImageClick?: (imageUrl: string) => void;
|
||||||
onClose: () => void;
|
|
||||||
picture?: string;
|
|
||||||
onCropPress?: (imageUrl: string) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress }) => {
|
export const CropModal: FC<Props> = ({ onSaveImageClick }) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
const isCropModalOpen = useCropModalStore(state => state.isCropModalOpen);
|
||||||
|
const imageUrl = useCropModalStore(state => state.imageUrl);
|
||||||
const [crop, setCrop] = useState<Crop>();
|
const [crop, setCrop] = useState<Crop>();
|
||||||
const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
|
const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
|
||||||
const [darken, setDarken] = useState(0);
|
const [darken, setDarken] = useState(0);
|
||||||
const [rotate, setRotate] = useState(0);
|
const [rotate, setRotate] = useState(0);
|
||||||
const [imgSrc, setImgSrc] = useState("");
|
|
||||||
const [width, setWidth] = useState<number>(0);
|
const [width, setWidth] = useState<number>(0);
|
||||||
const blobUrlRef = useRef("");
|
const cropImageElementRef = useRef<HTMLImageElement>(null);
|
||||||
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(() => {
|
const handleCropClick = async () => {
|
||||||
if (picture) setImgSrc(picture);
|
|
||||||
}, [picture]);
|
|
||||||
|
|
||||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
if (!event.target.files?.length) return;
|
|
||||||
|
|
||||||
setCrop(undefined);
|
|
||||||
try {
|
|
||||||
const url = URL.createObjectURL(event.target.files[0]);
|
|
||||||
setImgSrc(url);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to create object url for image", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCropClick = () => {
|
|
||||||
if (!completedCrop) throw new Error("No completed crop");
|
if (!completedCrop) throw new Error("No completed crop");
|
||||||
if (!imgRef.current) throw new Error("No image");
|
if (!cropImageElementRef.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");
|
||||||
@ -93,31 +71,34 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
|
|||||||
canvasCopy.height = completedCrop.height;
|
canvasCopy.height = completedCrop.height;
|
||||||
ctx.filter = `brightness(${100 - darken}%)`;
|
ctx.filter = `brightness(${100 - darken}%)`;
|
||||||
|
|
||||||
canvasPreview(imgRef.current, canvasCopy, completedCrop, rotate);
|
await canvasPreview(cropImageElementRef.current, canvasCopy, completedCrop, rotate);
|
||||||
|
|
||||||
canvasCopy.toBlob((blob) => {
|
canvasCopy.toBlob((blob) => {
|
||||||
if (!blob) {
|
if (!blob) {
|
||||||
throw new Error("Failed to create blob");
|
throw new Error("Failed to create blob");
|
||||||
}
|
}
|
||||||
if (blobUrlRef.current) {
|
const newImageUrl = URL.createObjectURL(blob);
|
||||||
URL.revokeObjectURL(blobUrlRef.current);
|
|
||||||
}
|
|
||||||
blobUrlRef.current = URL.createObjectURL(blob);
|
|
||||||
|
|
||||||
setImgSrc(blobUrlRef.current);
|
setCropModalImageUrl(newImageUrl);
|
||||||
onCropPress?.(blobUrlRef.current);
|
|
||||||
setCrop(undefined);
|
setCrop(undefined);
|
||||||
|
setCompletedCrop(undefined);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function handleSaveClick() {
|
||||||
|
if (imageUrl) onSaveImageClick?.(imageUrl);
|
||||||
|
setCrop(undefined);
|
||||||
|
setCompletedCrop(undefined);
|
||||||
|
closeCropModal();
|
||||||
|
}
|
||||||
|
|
||||||
const getImageSize = () => {
|
const getImageSize = () => {
|
||||||
if (imgRef.current) {
|
if (cropImageElementRef.current) {
|
||||||
const imageWidth = imgRef.current.naturalWidth;
|
const imageWidth = cropImageElementRef.current.naturalWidth;
|
||||||
const imageHeight = imgRef.current.naturalHeight;
|
const imageHeight = cropImageElementRef.current.naturalHeight;
|
||||||
|
|
||||||
const aspect = imageWidth / imageHeight;
|
const aspect = imageWidth / imageHeight;
|
||||||
|
|
||||||
|
|
||||||
if (aspect <= 1.333) {
|
if (aspect <= 1.333) {
|
||||||
setWidth(240);
|
setWidth(240);
|
||||||
}
|
}
|
||||||
@ -130,14 +111,10 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleSaveClick() {
|
|
||||||
onClose();
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open={opened}
|
open={isCropModalOpen}
|
||||||
onClose={onClose}
|
onClose={closeCropModal}
|
||||||
aria-labelledby="modal-modal-title"
|
aria-labelledby="modal-modal-title"
|
||||||
aria-describedby="modal-modal-description"
|
aria-describedby="modal-modal-description"
|
||||||
>
|
>
|
||||||
@ -163,7 +140,7 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
|
|||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{imgSrc && (
|
{imageUrl && (
|
||||||
<ReactCrop
|
<ReactCrop
|
||||||
crop={crop}
|
crop={crop}
|
||||||
onChange={(_, percentCrop) => setCrop(percentCrop)}
|
onChange={(_, percentCrop) => setCrop(percentCrop)}
|
||||||
@ -175,9 +152,9 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
|
|||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
onLoad={getImageSize}
|
onLoad={getImageSize}
|
||||||
ref={imgRef}
|
ref={cropImageElementRef}
|
||||||
alt="Crop me"
|
alt="Crop me"
|
||||||
src={imgSrc}
|
src={imageUrl}
|
||||||
style={{
|
style={{
|
||||||
filter: `brightness(${100 - darken}%)`,
|
filter: `brightness(${100 - darken}%)`,
|
||||||
transform: ` rotate(${rotate}deg)`,
|
transform: ` rotate(${rotate}deg)`,
|
||||||
@ -271,7 +248,7 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
|
|||||||
}}
|
}}
|
||||||
>Сохранить</Button>
|
>Сохранить</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => fileInputRef.current?.click()}
|
onClick={resetToOriginalImage}
|
||||||
disableRipple
|
disableRipple
|
||||||
sx={{
|
sx={{
|
||||||
width: "215px",
|
width: "215px",
|
||||||
@ -284,18 +261,12 @@ export const CropModal: FC<Iprops> = ({ opened, onClose, picture, onCropPress })
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Загрузить оригинал
|
Загрузить оригинал
|
||||||
<input
|
|
||||||
style={{ display: "none", zIndex: "-999" }}
|
|
||||||
ref={fileInputRef}
|
|
||||||
type="file"
|
|
||||||
accept="image/*"
|
|
||||||
onChange={handleFileChange}
|
|
||||||
/>
|
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={handleCropClick}
|
onClick={handleCropClick}
|
||||||
disableRipple
|
disableRipple
|
||||||
variant="contained"
|
variant="contained"
|
||||||
|
disabled={!completedCrop}
|
||||||
sx={{
|
sx={{
|
||||||
padding: "10px 20px",
|
padding: "10px 20px",
|
||||||
borderRadius: "8px",
|
borderRadius: "8px",
|
||||||
|
@ -1,13 +1,14 @@
|
|||||||
import { Box, Button } from "@mui/material";
|
import { Box, Button } from "@mui/material";
|
||||||
import { FC, useState } from "react";
|
import { FC } from "react";
|
||||||
import { CropModal } from "./CropModal";
|
import { CropModal } from "./CropModal";
|
||||||
|
import { openCropModal } from "@root/cropModal";
|
||||||
|
|
||||||
const ImageCrop: FC = () => {
|
const ImageCrop: FC = () => {
|
||||||
const [opened, setOpened] = useState<boolean>(false);
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
<Button onClick={() => setOpened(true)}>Открыть модалку</Button>
|
<Button onClick={() => openCropModal("", "")}>Открыть модалку</Button>
|
||||||
<CropModal opened={opened} onClose={() => setOpened(false)} />
|
<CropModal />
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
Loading…
Reference in New Issue
Block a user