frontAnswerer/src/utils/hooks/useQuestionFlowControl.ts

175 lines
7.7 KiB
TypeScript
Raw Normal View History

import { QuizQuestionResult } from "@model/questionTypes/result";
import { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
import { setCurrentQuizStep, useQuizViewStore } from "@stores/quizView/store";
import { useCallback, useDebugValue, useMemo, useState } from "react";
import { isResultQuestionEmpty } from "../../pages/ViewPublicationPage/tools/checkEmptyData";
import { useQuizData } from "./useQuizData";
export function useQuestionFlowControl() {
const { settings, questions } = useQuizData();
const [currentQuestion, setCurrentQuestion] = useState<AnyTypedQuizQuestion>(getFirstQuestion);
const answers = useQuizViewStore(state => state.answers);
2024-02-10 10:46:13 +00:00
const linearQuestionIndex = questions.every(({ content }) => content.rule.parentId !== "root") // null when branching enabled
? questions.indexOf(currentQuestion)
: null;
function getFirstQuestion() {
if (questions.length === 0) throw new Error("No questions found");
if (settings.cfg.haveRoot) {
const nextQuestion = questions.find(
question => question.id === settings.cfg.haveRoot || question.content.id === settings.cfg.haveRoot
);
if (!nextQuestion) throw new Error("Root question not found");
return nextQuestion;
}
return questions[0];
}
const nextQuestionId = useMemo(() => {
console.log("Смотрим какой вопрос будет дальше. Что у нас сегодня вкусненького? Щя покажу от какого вопроса мы ищем следующий шаг");
console.log(currentQuestion);
console.log("От вот этого /|");
//вопрос обязателен, анализируем ответ и условия ветвления
if (answers.length) {
2024-02-10 10:46:13 +00:00
let readyBeNextQuestion = "";
const answer = answers.find(({ questionId }) => questionId === currentQuestion.id);
currentQuestion.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
);
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; // Ес­ли хоть один эле­мент от­ли­ча­ет­ся, мас­си­вы не рав­ны
}
return;
}
if (String(rules[0].answers[i]) === answer?.answer) {
readyBeNextQuestion = next; // Ес­ли хоть один эле­мент от­ли­ча­ет­ся, мас­си­вы не рав­ны
}
}
});
if (readyBeNextQuestion) return readyBeNextQuestion;
}
if (!currentQuestion.required) {//вопрос не обязателен и не нашли совпадений между ответами и условиями ветвления
console.log("вопрос не обязателен ищем дальше");
2024-02-10 10:46:13 +00:00
const defaultNextQuestionId = currentQuestion.content.rule.default;
if (defaultNextQuestionId.length > 1 && defaultNextQuestionId !== " ") return defaultNextQuestionId;
//Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт
//Кинуть на ребёнка надо даже если там нет дефолта
if (
["date", "page", "text", "number"].includes(currentQuestion.type)
&& currentQuestion.content.rule.children.length === 1
) return currentQuestion.content.rule.children[0];
}
//ничё не нашли, ищем резулт
console.log("ничё не нашли, ищем резулт ");
return questions.find(q => {
return q.type === "result" && q.content.rule.parentId === currentQuestion.content.id;
})?.id;
}, [answers, currentQuestion, questions]);
2024-02-10 10:46:13 +00:00
const prevQuestion = linearQuestionIndex !== null
? questions[linearQuestionIndex - 1]
: questions.find(q =>
q.id === currentQuestion.content.rule.parentId
|| q.content.id === currentQuestion.content.rule.parentId
);
2024-02-10 10:46:13 +00:00
const nextQuestion = linearQuestionIndex !== null
? questions[linearQuestionIndex + 1]
: questions.find(q => q.id === nextQuestionId || q.content.id === nextQuestionId);
2024-02-10 10:46:13 +00:00
const resultQuestion = useMemo(() => {
let resultQuestion: QuizQuestionResult | undefined;
2024-02-10 10:46:13 +00:00
if (currentQuestion.type === "result") resultQuestion = currentQuestion;
if (settings.cfg.haveRoot) {
resultQuestion = questions.find((question): question is QuizQuestionResult => {
return question.type === "result" && question.content.rule.parentId === currentQuestion.content.id;
});
} else {
resultQuestion = questions.find((question): question is QuizQuestionResult => {
return question.type === "result" && question.content.rule.parentId === "line";
});
}
2024-02-10 10:46:13 +00:00
if (resultQuestion && !isResultQuestionEmpty(resultQuestion)) return resultQuestion;
}, [currentQuestion, questions, settings.cfg.haveRoot]);
2024-02-10 10:46:13 +00:00
const showResult = useCallback(() => {
if (!resultQuestion) throw new Error("Result question not found");
setCurrentQuestion(resultQuestion);
2024-02-10 10:46:13 +00:00
if (settings.cfg.resultInfo.showResultForm === "after") {
setCurrentQuizStep("contactform");
}
2024-02-10 10:46:13 +00:00
}, [resultQuestion, settings.cfg.resultInfo.showResultForm]);
2024-02-10 10:46:13 +00:00
const showResultAfterContactForm = useCallback(() => {
if (!resultQuestion) throw new Error("Result question not found");
2024-02-10 10:46:13 +00:00
if (resultQuestion.type !== "result") throw new Error("Current question is not a result question");
2024-02-10 10:46:13 +00:00
setCurrentQuizStep("question");
}, [resultQuestion]);
2024-02-10 10:46:13 +00:00
const moveToPrevQuestion = useCallback(() => {
if (!prevQuestion) throw new Error("Previous question not found");
2024-02-10 10:46:13 +00:00
setCurrentQuestion(prevQuestion);
}, [prevQuestion]);
2024-02-10 10:46:13 +00:00
const moveToNextQuestion = useCallback(() => {
if (!nextQuestion) throw new Error("Next question not found");
2024-02-10 10:46:13 +00:00
if (nextQuestion.type === "result") return showResult();
2024-02-10 10:46:13 +00:00
setCurrentQuestion(nextQuestion);
}, [nextQuestion, showResult]);
2024-02-10 10:46:13 +00:00
const isPreviousButtonEnabled = Boolean(prevQuestion);
2024-02-10 10:46:13 +00:00
const isNextButtonEnabled = useMemo(() => {
const hasAnswer = answers.some(({ questionId }) => questionId === currentQuestion.id);
if ("required" in currentQuestion.content && currentQuestion.content.required) {
2024-02-10 10:46:13 +00:00
return hasAnswer;
}
2024-02-10 10:46:13 +00:00
return Boolean(nextQuestion);
}, [answers, currentQuestion.content, currentQuestion.id, nextQuestion]);
useDebugValue({
2024-02-10 10:46:13 +00:00
linearQuestionIndex,
currentQuestion,
2024-02-10 10:46:13 +00:00
prevQuestion,
nextQuestion,
resultQuestion,
});
return {
currentQuestion,
2024-02-10 10:46:13 +00:00
currentQuestionStepNumber: linearQuestionIndex && linearQuestionIndex + 1,
isNextButtonEnabled,
isPreviousButtonEnabled,
moveToPrevQuestion,
moveToNextQuestion,
showResultAfterContactForm,
};
}