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