frontAnswerer/src/pages/ViewPublicationPage/Footer.tsx

340 lines
13 KiB
TypeScript
Raw Normal View History

2023-12-29 00:58:19 +00:00
import { Box, Button, Typography, useMediaQuery, useTheme } from "@mui/material";
import { useCallback, useMemo, useState } from "react";
2023-12-16 14:55:56 +00:00
2024-01-19 11:46:17 +00:00
import { getQuestionById } from "@stores/quizData/actions";
2023-12-16 14:55:56 +00:00
import { enqueueSnackbar } from "notistack";
import type { AnyTypedQuizQuestion, QuizQuestionBase } from "../../model/questionTypes/shared";
2023-12-29 00:58:19 +00:00
import { checkEmptyData } from "./tools/checkEmptyData";
2023-12-16 14:55:56 +00:00
2024-01-10 18:02:37 +00:00
import type { QuizQuestionResult } from "@model/questionTypes/result";
import { useQuestionsStore } from "@stores/quizData/store";
import { useQuizViewStore } from "@stores/quizView/store";
2024-01-10 18:02:37 +00:00
2023-12-16 14:55:56 +00:00
type FooterProps = {
setCurrentQuestion: (step: AnyTypedQuizQuestion) => void;
question: AnyTypedQuizQuestion;
setShowContactForm: (show: boolean) => void;
setShowResultForm: (show: boolean) => void;
2023-12-16 14:55:56 +00:00
};
2023-12-18 11:56:32 +00:00
export const Footer = ({ setCurrentQuestion, question, setShowContactForm, setShowResultForm }: FooterProps) => {
const theme = useTheme();
const { settings, items } = useQuestionsStore();
const answers = useQuizViewStore(state => state.answers);
const [stepNumber, setStepNumber] = useState(1);
2023-12-29 00:58:19 +00:00
const isMobileMini = useMediaQuery(theme.breakpoints.down(382));
const isLinear = !items.some(({ content }) => content.rule.parentId === "root");
2023-12-18 11:56:32 +00:00
const getNextQuestionId = useCallback(() => {
console.log("Смотрим какой вопрос будет дальше. Что у нас сегодня вкусненького? Щя покажу от какого вопроса мы ищем следующий шаг");
console.log(question);
console.log("От вот этого /|");
let readyBeNextQuestion = "";
2023-12-16 14:55:56 +00:00
//вопрос обязателен, анализируем ответ и условия ветвления
if (answers.length) {
const answer = answers.find(({ questionId }) => questionId === question.id);
2023-12-16 14:55:56 +00:00
(question as QuizQuestionBase).content.rule.main.forEach(({ next, rules }) => {
const longerArray = Math.max(
rules[0].answers.length,
answer?.answer && Array.isArray(answer?.answer) ? answer?.answer.length : [answer?.answer].length
);
2023-12-16 14:55:56 +00:00
for (
let i = 0;
i < longerArray;
i++ // Цикл по всем эле­мен­там бОльшего массива
) {
if (Array.isArray(answer?.answer)) {
if (answer?.answer.find((item) => String(item === rules[0].answers[i]))) {
readyBeNextQuestion = next; // Ес­ли хоть один эле­мент от­ли­ча­ет­ся, мас­си­вы не рав­ны
}
2023-12-16 14:55:56 +00:00
return;
}
2023-12-16 14:55:56 +00:00
if (String(rules[0].answers[i]) === answer?.answer) {
readyBeNextQuestion = next; // Ес­ли хоть один эле­мент от­ли­ча­ет­ся, мас­си­вы не рав­ны
}
}
});
2023-12-16 14:55:56 +00:00
if (readyBeNextQuestion) return readyBeNextQuestion;
}
2023-12-16 14:55:56 +00:00
if (!question.required) {//вопрос не обязателен и не нашли совпадений между ответами и условиями ветвления
console.log("вопрос не обязателен ищем дальше");
const defaultQ = question.content.rule.default;
if (defaultQ.length > 1 && defaultQ !== " ") return defaultQ;
//Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт
//Кинуть на ребёнка надо даже если там нет дефолта
if (
(question?.type === "date" ||
question?.type === "text" ||
question?.type === "number" ||
question?.type === "page") && question.content.rule.children.length === 1
) return question.content.rule.children[0];
2023-12-16 14:55:56 +00:00
}
//ничё не нашли, ищем резулт
console.log("ничё не нашли, ищем резулт ");
return items.find(q => {
console.log('q.type === "result"', q.type === "result");
console.log('q.content.rule.parentId', q.content.rule.parentId);
console.log('question.content.id', question.content.id);
return q.type === "result" && q.content.rule.parentId === question.content.id;
})?.id;
2023-12-16 14:55:56 +00:00
}, [answers, items, question]);
2023-12-16 14:55:56 +00:00
const isPreviousButtonDisabled = useMemo(() => {
// Логика для аргумента disabled у кнопки "Назад"
if (isLinear) {
const questionIndex = items.findIndex(({ id }) => id === question.id);
2023-12-29 00:58:19 +00:00
const previousQuestion = items[questionIndex - 1];
2023-12-29 00:58:19 +00:00
return previousQuestion ? false : true;
} else {
return question?.content.rule.parentId === "root" ? true : false;
}
}, [items, isLinear, question?.content.rule.parentId, question.id]);
const isNextButtonDisabled = useMemo(() => {
// Логика для аргумента disabled у кнопки "Далее"
const answer = answers.find(({ questionId }) => questionId === question.id);
if ("required" in question.content && question.content.required && answer) {
return false;
}
if ("required" in question.content && question.content.required && !answer) {
return true;
}
2023-12-29 00:58:19 +00:00
if (isLinear) {
return false;
}
2023-12-29 00:58:19 +00:00
const nextQuestionId = getNextQuestionId();
if (nextQuestionId) {
return false;
} else {
const nextQuestion = getQuestionById(question.content.rule.default);
2023-12-29 00:58:19 +00:00
if (nextQuestion?.type) {
return false;
}
}
}, [answers, getNextQuestionId, isLinear, question.content, question.id]);
const showResult = (nextQuestion: QuizQuestionResult) => {
if (!settings) return;
if (!nextQuestion) return;
const isEmpty = checkEmptyData({ resultData: nextQuestion });
if (nextQuestion) {
if (nextQuestion && settings?.cfg.resultInfo.showResultForm === "before") {
if (isEmpty) {
setShowContactForm(true); //до+пустая = кидать на ФК
} else {
setShowResultForm(true); //до+заполнена = показать
}
}
if (nextQuestion && settings?.cfg.resultInfo.showResultForm === "after") {
if (isEmpty) {
setShowContactForm(true); //после+пустая
} else {
setShowContactForm(true); //после+заполнена = показать ФК
}
}
}
};
const followPreviousStep = () => {
if (isLinear) {
setStepNumber(q => q - 1);
const questionIndex = items.findIndex(({ id }) => id === question.id);
const previousQuestion = items[questionIndex - 1];
if (previousQuestion) {
setCurrentQuestion(previousQuestion);
2023-12-16 14:55:56 +00:00
}
2023-12-18 11:56:32 +00:00
return;
}
2023-12-18 11:56:32 +00:00
if (question?.content.rule.parentId !== "root") {
const parent = getQuestionById(question?.content.rule.parentId);
if (parent?.type) {
setCurrentQuestion(parent);
} else {
enqueueSnackbar("не могу получить предыдущий вопрос");
}
} else {
enqueueSnackbar("вы находитесь на первом вопросе");
2023-12-16 14:55:56 +00:00
}
};
const followNextStep = () => {
if (isLinear) {
setStepNumber(q => q + 1);
const questionIndex = items.findIndex(({ id }) => id === question.id);
const nextQuestion = items[questionIndex + 1];
if (nextQuestion && nextQuestion.type !== "result") {
setCurrentQuestion(nextQuestion);
} else {
//@ts-ignore
showResult(items.find(q => q.content.rule.parentId === "line"));
}
return;
}
const nextQuestionId = getNextQuestionId();
if (nextQuestionId) {
const nextQuestion = getQuestionById(nextQuestionId);
if (nextQuestion?.type && nextQuestion.type === "result") {
showResult(nextQuestion);
} else {
//@ts-ignore
setCurrentQuestion(nextQuestion);
}
} else {
enqueueSnackbar("не могу получить последующий вопрос");
}
};
return (
2023-12-16 14:55:56 +00:00
<Box
sx={{
position: "relative",
padding: "15px 0",
borderTop: `1px solid ${theme.palette.grey[400]}`,
height: '75px',
display: "flex",
}}
2023-12-16 14:55:56 +00:00
>
<Box
sx={{
width: "100%",
maxWidth: "1000px",
padding: "0 10px",
margin: "0 auto",
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
{/*{mode[settings.cfg.theme] ? (*/}
{/* <NameplateLogoFQ style={{ fontSize: "34px", width:"200px", height:"auto" }} />*/}
{/*):(*/}
{/* <NameplateLogoFQDark style={{ fontSize: "34px", width:"200px", height:"auto" }} />*/}
{/*)}*/}
{isLinear &&
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
marginRight: "auto",
color: theme.palette.text.primary,
}}
>
<Typography>Шаг</Typography>
<Typography
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
fontWeight: "bold",
borderRadius: "50%",
width: "30px",
height: "30px",
color: "#FFF",
background: theme.palette.primary.main,
}}
>
{stepNumber}
</Typography>
<Typography>Из</Typography>
<Typography sx={{ fontWeight: "bold" }}>
{items.filter(q => q.type !== "result").length}
</Typography>
</Box>
}
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
marginRight: "auto",
// color: theme.palette.grey1.main,
}}
>
{/* <Typography>Шаг</Typography>
2023-12-29 00:58:19 +00:00
<Typography
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
fontWeight: "bold",
borderRadius: "50%",
width: "30px",
height: "30px",
color: "#FFF",
background: theme.palette.brightPurple.main,
}}
>
{stepNumber} */}
{/* </Typography> */}
{/* <Typography>Из</Typography>
2023-12-29 00:58:19 +00:00
<Typography sx={{ fontWeight: "bold" }}>
{questions.length}
</Typography> */}
</Box>
<Button
disabled={isPreviousButtonDisabled}
variant="contained"
sx={{ fontSize: "16px", padding: "10px 15px", }}
onClick={followPreviousStep}
>
{isMobileMini ? (
"←"
) : (
"← Назад"
)}
</Button>
<Button
disabled={isNextButtonDisabled}
variant="contained"
sx={{ fontSize: "16px", padding: "10px 15px" }}
onClick={followNextStep}
>
Далее
</Button>
</Box>
2023-12-16 14:55:56 +00:00
</Box>
);
2023-12-16 14:55:56 +00:00
};