randomizing

pull/2/head
bvn13 2023-05-01 14:42:58 +03:00
parent 847835b343
commit 4be51a2859
7 changed files with 76 additions and 24 deletions

View File

@ -46539,9 +46539,10 @@ Please use another name.` : formatMuiErrorMessage(18));
// src/components/survey/Survey.tsx // src/components/survey/Survey.tsx
var import_jsx_runtime27 = __toESM(require_jsx_runtime()); var import_jsx_runtime27 = __toESM(require_jsx_runtime());
var Survey = ({ survey }) => { var Survey = ({ survey }) => {
var _a; var _a, _b, _c;
const [activeStep, setActiveStep] = React40.useState(-1); const [activeStep, setActiveStep] = React40.useState(-1);
const [results, setResults] = React40.useState(store.getState()); const [results, setResults] = React40.useState(store.getState());
const [preparedSurvey, setPreparedSurvey] = React40.useState({});
const handleNext = (group, value) => { const handleNext = (group, value) => {
if (group !== void 0 && value !== void 0) { if (group !== void 0 && value !== void 0) {
store.dispatch(addAnswer({ store.dispatch(addAnswer({
@ -46558,10 +46559,34 @@ Please use another name.` : formatMuiErrorMessage(18));
store.dispatch(setContents([])); store.dispatch(setContents([]));
setActiveStep(-1); setActiveStep(-1);
}; };
const randomizeIfNeeded = (isNeeded, array) => {
if (isNeeded) {
return array.sort((a3, b3) => 0.5 - Math.random());
} else {
return array;
}
};
(0, import_react21.useEffect)(() => { (0, import_react21.useEffect)(() => {
store.dispatch(setContents([])); store.dispatch(setContents([]));
return store.subscribe(() => setResults(store.getState())); return store.subscribe(() => setResults(store.getState()));
}, []); }, []);
(0, import_react21.useEffect)(() => {
if (void 0 !== survey) {
setPreparedSurvey({
title: survey.title,
settings: survey.settings,
intro: survey.intro,
questions: randomizeIfNeeded(survey.settings.randomizeQuestions, survey.questions).map((q2) => {
return {
group: q2.group,
title: q2.title,
question: q2.question,
options: randomizeIfNeeded(survey.settings.randomizeOptions, q2.options)
};
})
});
}
}, [survey]);
const prepare2 = (text) => { const prepare2 = (text) => {
if (text !== void 0) { if (text !== void 0) {
return text.replaceAll("\n", "<br/>").replaceAll("<script", "script"); return text.replaceAll("\n", "<br/>").replaceAll("<script", "script");
@ -46570,8 +46595,8 @@ Please use another name.` : formatMuiErrorMessage(18));
} }
}; };
return /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)("div", { children: [ return /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)("div", { children: [
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("h1", { style: { fontSize: "4em" }, children: survey == null ? void 0 : survey.title }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("h1", { style: { fontSize: "4em" }, children: preparedSurvey == null ? void 0 : preparedSurvey.title }),
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("div", { dangerouslySetInnerHTML: { __html: prepare2(survey == null ? void 0 : survey.intro) } }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("div", { dangerouslySetInnerHTML: { __html: prepare2(preparedSurvey == null ? void 0 : preparedSurvey.intro) } }),
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("br", {}), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("br", {}),
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { sx: { maxWidth: 400 }, children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)( /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { sx: { maxWidth: 400 }, children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
Button_default, Button_default,
@ -46585,9 +46610,9 @@ Please use another name.` : formatMuiErrorMessage(18));
) }), ) }),
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("br", {}), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("br", {}),
/* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Box_default, { sx: { maxWidth: 400 }, children: [ /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Box_default, { sx: { maxWidth: 400 }, children: [
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Stepper_default, { activeStep, orientation: "vertical", children: survey == null ? void 0 : survey.questions.map( /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Stepper_default, { activeStep, orientation: "vertical", children: (_a = preparedSurvey == null ? void 0 : preparedSurvey.questions) == null ? void 0 : _a.map(
(question, index) => /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Step_default, { children: [ (question, index) => /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Step_default, { children: [
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)(StepLabel_default, { optional: index === (survey == null ? void 0 : survey.questions.length) - 1 ? /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Typography_default, { variant: "caption", children: "Last step" }) : null, children: "Question " + (index + 1) }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(StepLabel_default, { optional: index === (preparedSurvey == null ? void 0 : preparedSurvey.questions.length) - 1 ? /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Typography_default, { variant: "caption", children: "Last step" }) : null, children: "Question " + (index + 1) }),
/* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(StepContent_default, { children: [ /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(StepContent_default, { children: [
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("h4", { children: question.title }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("h4", { children: question.title }),
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Typography_default, { children: question.question }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Typography_default, { children: question.question }),
@ -46608,9 +46633,9 @@ Please use another name.` : formatMuiErrorMessage(18));
] }) ] })
] }, prepare2(question.title)) ] }, prepare2(question.title))
) }), ) }),
activeStep === (survey == null ? void 0 : survey.questions.length) && /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Paper_default, { square: true, elevation: 0, sx: { p: 3 }, children: [ activeStep === ((_b = preparedSurvey == null ? void 0 : preparedSurvey.questions) == null ? void 0 : _b.length) && /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Paper_default, { square: true, elevation: 0, sx: { p: 3 }, children: [
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Typography_default, { children: "All steps completed - you're finished" }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Typography_default, { children: "All steps completed - you're finished" }),
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("ul", { children: (_a = results.data.resultsByGroup) == null ? void 0 : _a.map( /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("ul", { children: (_c = results.data.resultsByGroup) == null ? void 0 : _c.map(
(result, index) => /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)("li", { children: [ (result, index) => /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)("li", { children: [
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("span", { children: result.group }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("span", { children: result.group }),
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)("span", { children: ": " }), /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("span", { children: ": " }),

File diff suppressed because one or more lines are too long

View File

@ -2,8 +2,8 @@
"title": "АGILE-КОМПАС", "title": "АGILE-КОМПАС",
"intro": "Agile-компас (с) Keterina Lengold\n\nВ этом тесте 15 вопросов, которые помогут определить оптимальную комбинацию целей на спринт по сферам и уровням.\n\nВаша задача — вспомнить, как часто за последний месяц вы испытывали то, что указано в каждом вопросе.\n\nЭтот тест рекомендуется проходить каждый спринт перед постановкой целей.", "intro": "Agile-компас (с) Keterina Lengold\n\nВ этом тесте 15 вопросов, которые помогут определить оптимальную комбинацию целей на спринт по сферам и уровням.\n\nВаша задача — вспомнить, как часто за последний месяц вы испытывали то, что указано в каждом вопросе.\n\nЭтот тест рекомендуется проходить каждый спринт перед постановкой целей.",
"settings": { "settings": {
"randomizeQuestions": false, "randomizeQuestions": true,
"randomizeOptions": false "randomizeOptions": true
}, },
"questions": [ "questions": [
{ {

View File

@ -2,8 +2,8 @@
"title": "Шкала депрессии Бека", "title": "Шкала депрессии Бека",
"intro": "Методика 'Шкала депрессии Бека' используется для диагностики уровня депрессии. Тест-опросник депрессии (Beck Depression Inventory) был предложен Аароном Т. Беком в 1961 году на основе клинических наблюдений, позволивших выявить перечень симптомов депрессии.\n\nИнструкция к тесту\nНеобходимо выбрать одно утверждение в каждой группе, которое лучше всего описывает состояние за прошедшую неделю, включая сегодняшний день. Прежде чем сделать выбор, нужно внимательно прочитать все утверждения в каждой группе.", "intro": "Методика 'Шкала депрессии Бека' используется для диагностики уровня депрессии. Тест-опросник депрессии (Beck Depression Inventory) был предложен Аароном Т. Беком в 1961 году на основе клинических наблюдений, позволивших выявить перечень симптомов депрессии.\n\nИнструкция к тесту\nНеобходимо выбрать одно утверждение в каждой группе, которое лучше всего описывает состояние за прошедшую неделю, включая сегодняшний день. Прежде чем сделать выбор, нужно внимательно прочитать все утверждения в каждой группе.",
"settings": { "settings": {
"randomizeQuestions": false, "randomizeQuestions": true,
"randomizeOptions": false "randomizeOptions": true
}, },
"questions": [ "questions": [
{ {

View File

@ -2,8 +2,8 @@
"title": "АGILE-КОМПАС", "title": "АGILE-КОМПАС",
"intro": "Agile-компас (с) Keterina Lengold\n\nВ этом тесте 15 вопросов, которые помогут определить оптимальную комбинацию целей на спринт по сферам и уровням.\n\nВаша задача — вспомнить, как часто за последний месяц вы испытывали то, что указано в каждом вопросе.\n\nЭтот тест рекомендуется проходить каждый спринт перед постановкой целей.", "intro": "Agile-компас (с) Keterina Lengold\n\nВ этом тесте 15 вопросов, которые помогут определить оптимальную комбинацию целей на спринт по сферам и уровням.\n\nВаша задача — вспомнить, как часто за последний месяц вы испытывали то, что указано в каждом вопросе.\n\nЭтот тест рекомендуется проходить каждый спринт перед постановкой целей.",
"settings": { "settings": {
"randomizeQuestions": false, "randomizeQuestions": true,
"randomizeOptions": false "randomizeOptions": true
}, },
"questions": [ "questions": [
{ {

View File

@ -2,8 +2,8 @@
"title": "Шкала депрессии Бека", "title": "Шкала депрессии Бека",
"intro": "Методика 'Шкала депрессии Бека' используется для диагностики уровня депрессии. Тест-опросник депрессии (Beck Depression Inventory) был предложен Аароном Т. Беком в 1961 году на основе клинических наблюдений, позволивших выявить перечень симптомов депрессии.\n\nИнструкция к тесту\nНеобходимо выбрать одно утверждение в каждой группе, которое лучше всего описывает состояние за прошедшую неделю, включая сегодняшний день. Прежде чем сделать выбор, нужно внимательно прочитать все утверждения в каждой группе.", "intro": "Методика 'Шкала депрессии Бека' используется для диагностики уровня депрессии. Тест-опросник депрессии (Beck Depression Inventory) был предложен Аароном Т. Беком в 1961 году на основе клинических наблюдений, позволивших выявить перечень симптомов депрессии.\n\nИнструкция к тесту\nНеобходимо выбрать одно утверждение в каждой группе, которое лучше всего описывает состояние за прошедшую неделю, включая сегодняшний день. Прежде чем сделать выбор, нужно внимательно прочитать все утверждения в каждой группе.",
"settings": { "settings": {
"randomizeQuestions": false, "randomizeQuestions": true,
"randomizeOptions": false "randomizeOptions": true
}, },
"questions": [ "questions": [
{ {

View File

@ -4,7 +4,7 @@ import {useEffect} from "react";
import {SurveyDto} from "../../api/Api"; import {SurveyDto} from "../../api/Api";
import {Box, Button, Paper, Step, StepContent, StepLabel, Stepper, Typography} from "@mui/material"; import {Box, Button, Paper, Step, StepContent, StepLabel, Stepper, Typography} from "@mui/material";
import {store} from "../../store/store"; import {store} from "../../store/store";
import {setContents, addAnswer} from "../../store/actions/data"; import {addAnswer, setContents} from "../../store/actions/data";
import {ResultByGroup} from "../../store/initialState"; import {ResultByGroup} from "../../store/initialState";
interface Props { interface Props {
@ -14,6 +14,7 @@ interface Props {
const Survey: React.FC<Props> = ({survey}) => { const Survey: React.FC<Props> = ({survey}) => {
const [activeStep, setActiveStep] = React.useState(-1) const [activeStep, setActiveStep] = React.useState(-1)
const [results, setResults] = React.useState(store.getState()) const [results, setResults] = React.useState(store.getState())
const [preparedSurvey, setPreparedSurvey] = React.useState({} as SurveyDto)
const handleNext = (group: string | undefined, value: number | undefined) => { const handleNext = (group: string | undefined, value: number | undefined) => {
if (group !== undefined && value !== undefined) { if (group !== undefined && value !== undefined) {
@ -34,11 +35,37 @@ const Survey: React.FC<Props> = ({survey}) => {
setActiveStep(-1) setActiveStep(-1)
}; };
const randomizeIfNeeded = (isNeeded: boolean, array: any[]) => {
if (isNeeded) {
return array.sort((a, b) => 0.5 - Math.random())
} else {
return array
}
}
useEffect(() => { useEffect(() => {
store.dispatch(setContents([] as ResultByGroup[])) store.dispatch(setContents([] as ResultByGroup[]))
return store.subscribe(() => setResults(store.getState())) return store.subscribe(() => setResults(store.getState()))
}, []) }, [])
useEffect(() => {
if (undefined !== survey) {
setPreparedSurvey({
title: survey.title,
settings: survey.settings,
intro: survey.intro,
questions: randomizeIfNeeded(survey.settings.randomizeQuestions, survey.questions).map(q => {
return {
group: q.group,
title: q.title,
question: q.question,
options: randomizeIfNeeded(survey.settings.randomizeOptions, q.options)
}
})
})
}
}, [survey])
const prepare = (text: string | undefined) => { const prepare = (text: string | undefined) => {
if (text !== undefined) { if (text !== undefined) {
return text return text
@ -51,8 +78,8 @@ const Survey: React.FC<Props> = ({survey}) => {
return ( return (
<div> <div>
<h1 style={{fontSize: '4em'}}>{survey?.title}</h1> <h1 style={{fontSize: '4em'}}>{preparedSurvey?.title}</h1>
<div dangerouslySetInnerHTML={{__html: prepare(survey?.intro)}}></div> <div dangerouslySetInnerHTML={{__html: prepare(preparedSurvey?.intro)}}></div>
<br/> <br/>
<Box sx={{maxWidth: 400}}> <Box sx={{maxWidth: 400}}>
<Button <Button
@ -67,10 +94,10 @@ const Survey: React.FC<Props> = ({survey}) => {
<br/> <br/>
<Box sx={{maxWidth: 400}}> <Box sx={{maxWidth: 400}}>
<Stepper activeStep={activeStep} orientation={"vertical"}> <Stepper activeStep={activeStep} orientation={"vertical"}>
{survey?.questions.map((question, index) => {preparedSurvey?.questions?.map((question, index) =>
<Step key={prepare(question.title)}> <Step key={prepare(question.title)}>
<StepLabel optional={ <StepLabel optional={
index === survey?.questions.length - 1 ? ( index === preparedSurvey?.questions.length - 1 ? (
<Typography variant="caption">Last step</Typography> <Typography variant="caption">Last step</Typography>
) : null ) : null
}> }>
@ -99,7 +126,7 @@ const Survey: React.FC<Props> = ({survey}) => {
</Step> </Step>
)} )}
</Stepper> </Stepper>
{activeStep === survey?.questions.length && ( {activeStep === preparedSurvey?.questions?.length && (
<Paper square elevation={0} sx={{p: 3}}> <Paper square elevation={0} sx={{p: 3}}>
<Typography>All steps completed - you&apos;re finished</Typography> <Typography>All steps completed - you&apos;re finished</Typography>
<div> <div>