refactored quiz slice, site loads

This commit is contained in:
=
2026-04-24 16:09:47 +10:00
parent a144621365
commit 1335275ed7
4 changed files with 55 additions and 48 deletions

View File

@@ -10,25 +10,26 @@ import { mixUp, startTesting, stopTesting } from './quizSlice';
function QuizStats() { function QuizStats() {
const checkTask = (index: number): string => { const correctCount = (index: number):number => {
useSelector((state: RootState) => state.lists.lists[index]); let quiz = useSelector((state: RootState) => state.quiz);
let state = store.getState(); let state = store.getState();
if (state.lists.correctAnswers.length <= index) { if (state.quiz.correctAnswers.length <= index) {
return ""; return 0;
} }
let correctCounter = state.lists.lists[index].reduce((prev, answ, i) => prev + Number(state.lists.correctAnswers[index][i] === answ), 0) return quiz.userAnswers[index].reduce((prev, answ, i) => prev + Number(quiz.correctAnswers[index][i] === answ), 0);
}
if (correctCounter == state.lists.lists[index].length) { const quizPartText = (counter:number, len:number):string=>{
if (counter == len) {
return "все ответы верные" return "все ответы верные"
} }
return `верно ${correctCounter}/${state.lists.lists[index].length}` return `верно ${counter}/${len}`
} }
return ( return (
<Container sx={{ margin: "auto" }}> <Container sx={{ margin: "auto" }}>
<h3>Результаты теста</h3> <h3>Результаты теста</h3>
<Typography>Задание 1: {checkTask(0)}</Typography> {/* <Typography>Задание 1: {checkTask(0)}</Typography> */}
<Typography>Задание 2: {checkTask(1)}</Typography> {/* <Typography>Задание 2: {checkTask(1)}</Typography> */}
</Container> </Container>
) )
} }
@@ -42,6 +43,7 @@ function Quiz() {
dispatch(mixUp()); dispatch(mixUp());
dispatch(startTesting()); dispatch(startTesting());
} }
const checkQuiz = () => { const checkQuiz = () => {
setDisplayingResults(true); setDisplayingResults(true);
dispatch(stopTesting()); dispatch(stopTesting());
@@ -55,7 +57,7 @@ function Quiz() {
<Typography variant="h5" gutterBottom> <Typography variant="h5" gutterBottom>
{index + 1}. {item.title} {index + 1}. {item.title}
</Typography> </Typography>
<Matching index={index} tasks={item.tasks} /> {[<Matching index={index} tasks={item.tasks} />,<>S</>,<>c</>][(["M","S","C"].indexOf(item.type))]}
</Box> </Box>
))} ))}

View File

@@ -14,8 +14,8 @@ interface ComponentProps {
function SortableList({ index}: ComponentProps) { function SortableList({ index}: ComponentProps) {
const dispatch = useDispatch(); const dispatch = useDispatch();
const arr = useSelector((state: RootState) => state.lists.lists[index]) const arr = useSelector((state: RootState) => state.quiz.userAnswers[index])
const isDisabled = useSelector((state: RootState) => state.lists.isTestingDone) const isDisabled = useSelector((state: RootState) => state.quiz.isTestingDone)
const draggedItems = arr || []; const draggedItems = arr || [];
const handleDragEnd = (event: any) => { const handleDragEnd = (event: any) => {
@@ -30,11 +30,11 @@ function SortableList({ index}: ComponentProps) {
return ( return (
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}> <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={draggedItems} <SortableContext items={draggedItems.map((x)=> String(x))}
strategy={verticalListSortingStrategy}> strategy={verticalListSortingStrategy}>
<List> <List>
{draggedItems.map((item) => ( {draggedItems.map((item) => (
<SortableItem key={item} item={item} id={item} isDisabled={isDisabled}/> <SortableItem key={String(item)} item={String(item)} id={String(item)} isDisabled={isDisabled}/>
))} ))}
</List> </List>
</SortableContext> </SortableContext>

View File

@@ -1,7 +1,7 @@
import { createSlice } from '@reduxjs/toolkit'; import { createSlice } from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit'; import type { PayloadAction } from '@reduxjs/toolkit';
function shuffle<T>(array:Array<T>):Array<T> { function shuffle<T>(array: Array<T>): Array<T> {
let currentIndex = array.length; let currentIndex = array.length;
// While there remain elements to shuffle... // While there remain elements to shuffle...
@@ -19,55 +19,60 @@ function shuffle<T>(array:Array<T>):Array<T> {
} }
interface QuizState { interface QuizState {
userAnswers: string[][]; // хранит перемещаемые элементы каждого списка ответов userAnswers: (string | boolean)[][]; // хранит перемещаемые элементы каждого списка ответов
correctAnswers:string[][] |boolean[][];// ответы для вопрсов, в случае с matching просто правильная последоавтельность, для sorting аналогично, для choosе последоватеьность boolean correctAnswers: (string | boolean)[][];// ответы для вопрсов, в случае с matching просто правильная последоавтельность, для sorting аналогично, для choosе последоватеьность boolean
isTestingDone:boolean// запрет на взаимодействие с квизом после окончания тестирования, чтобю юзер не наглел quizTypes: Array<"M" | "S" | "C">;
isTestingDone: boolean// запрет на взаимодействие с квизом после окончания тестирования, чтобю юзер не наглел
} }
const initialState: QuizState = { const initialState: QuizState = {
userAnswers: [], userAnswers: [],
correctAnswers:[], correctAnswers: [],
isTestingDone:false quizTypes: [],
isTestingDone: false,
}; };
const listsSlice = createSlice({ const listsSlice = createSlice({
name: 'lists', name: 'lists',
initialState, initialState,
reducers: { reducers: {
addList: (state, action: PayloadAction<{index: number; items: string[]}>)=>{ addList: (state, action: PayloadAction<{ index: number; items: string[]; answers: (string|boolean)[]; quizType : "S" | "M" | "C"}>) => {
const { index, items } = action.payload; const { index, items,answers,quizType} = action.payload;
state.userAnswers.splice(index, 1, items); // с нулём создаётся по 2 экземпляра, видно в отладке state.userAnswers.splice(index, 1, items); // с нулём создаётся по 2 экземпляра, видно в отладке
state.correctAnswers.splice(index, 1, items); state.quizTypes.splice(index, 1, quizType); //
state.correctAnswers.splice(index, 1, answers);
}, },
setDraggedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => { setDraggedItems: (state, action: PayloadAction<{ index: number; items: (string|boolean)[] }>) => {
const { index, items } = action.payload; const { index, items } = action.payload;
if (index >= 0 && index < state.userAnswers.length) { if (index >= 0 && index < state.userAnswers.length) {
state.userAnswers[index] = items; // обновляем конкретный список state.userAnswers[index] = items; // обновляем конкретный список
} }
}, },
setCheckedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => { setCheckedItems: (state, action: PayloadAction<{ index: number; items: (string|boolean)[] }>) => {
const { index, items } = action.payload; const { index, items } = action.payload;
if (index >= 0 && index < state.userAnswers.length) { if (index >= 0 && index < state.userAnswers.length) {
state.userAnswers[index] = items; // обновляем конкретный список state.userAnswers[index] = items; // обновляем конкретный список
} }
}, },
mixUp: (state) => { mixUp: (state) => {
state.userAnswers=state.userAnswers.map((list)=> state.userAnswers = state.userAnswers.map((list) => {
{ if(typeof(list[0])==="boolean"){
return shuffle(list); return list.map(()=>false);
}) }
return shuffle<string|boolean>(list);
})
}, },
stopTesting:(state)=>{ stopTesting: (state) => {
state.isTestingDone=true; state.isTestingDone = true;
}, },
startTesting:(state)=>{ startTesting: (state) => {
state.isTestingDone=false; state.isTestingDone = false;
} }
}, },
}); });
// Экспортируем действия и редьюсер // Экспортируем действия и редьюсер
export const { addList, setDraggedItems,mixUp,startTesting,stopTesting } = listsSlice.actions; export const { addList, setDraggedItems, mixUp, startTesting, stopTesting } = listsSlice.actions;
export type {QuizState} export type { QuizState }
export default listsSlice.reducer; export default listsSlice.reducer;

View File

@@ -63,7 +63,7 @@ export const quiz: tQuizzes = [
} }
, ,
{ {
"id": 2, "id": 3,
"type": "C", "type": "C",
"title": "Вопрос 3 Выбирай!", "title": "Вопрос 3 Выбирай!",
"tasks": [ "tasks": [