This commit is contained in:
2026-04-24 13:41:54 +10:00
parent 2df7ed36de
commit a144621365
12 changed files with 295 additions and 86 deletions

View File

@@ -1,6 +1,6 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { Provider } from 'react-redux';
import {
createBrowserRouter,
RouterProvider,
@@ -9,8 +9,9 @@ import {
import List from "./list/List";
import Chart from "./chart/Chart";
import Main from "./main/Main";
import Quiz from "./quiz/QuizPage";
import ProjectDetails from "./projectDetails/ProjectDetails";
import store from './store';
const router = createBrowserRouter([
@@ -30,6 +31,10 @@ const router = createBrowserRouter([
path: "/chart",
element: <Chart />,
},
{
path: "/quiz",
element: <Quiz />,
},
]);
@@ -37,6 +42,8 @@ const router = createBrowserRouter([
import './styles/index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<RouterProvider router={router} />
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
</StrictMode>,
)

View File

@@ -0,0 +1,15 @@
import NavBar from "../components/Navbar";
import Footer from "../components/CustomFooter";
import Quiz from "./features/Quiz";
function QuizPage() {
return (
<>
<NavBar active="4" />
<Quiz />
<Footer />
</>
);
}
export default QuizPage;

View File

@@ -0,0 +1,41 @@
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { ListItem, ListItemText, ListItemButton, ListItemIcon} from '@mui/material';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
interface SortableItemProps {
item: string;
id: string;// чтобы тайпскрипт компилятор не жаловался, добавил в инетрфейс, хотя и так компилируется нормально
isDisabled:boolean;
}
export function SortableItem({ item ,isDisabled}: SortableItemProps) {
const id = item; /* идентификатор для useSortable */
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
} = useSortable({ id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
};
return (
<ListItem ref={ isDisabled ? undefined : setNodeRef } style={ style } { ...attributes } { ...listeners }>
<ListItemButton
sx={{
border: '1px solid gray',
borderRadius: '5px',
}}>
<ListItemIcon>
<DragIndicatorIcon />
</ListItemIcon>
<ListItemText primary={ item } />
</ListItemButton>
</ListItem>
);
}

View File

@@ -0,0 +1,52 @@
import { Grid, List, ListItem, ListItemButton, ListItemText } from '@mui/material';
import type {tTasks} from "../quizData"
import SortableList from '../features/SortableList';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { addList,mixUp } from './quizSlice';
interface ComponentProps {
tasks: tTasks;
index: number;
}
function Matching({tasks,index}: ComponentProps) {
const dispatch = useDispatch();
// Добавляем список ответов очередного задания в хранилище
useEffect(() => {
dispatch(addList({ index, items: answers }));
}, []);
useEffect(() => {
dispatch(mixUp());
}, []);
const answers: string[] = tasks.map((item) => String(item.answer));
return (
<Grid container spacing={2}>
<Grid size={6}>
<List>
{tasks.map((item, index) => (
<ListItem key={index}>
<ListItemButton
sx={{
border: '1px solid gray',
borderRadius: '5px',
textAlign: 'right',
}}>
<ListItemText primary={item.question} />
</ListItemButton>
</ListItem>
))}
</List>
</Grid>
<Grid size={6}>
<SortableList index={index} answers={answers}/>
</Grid>
</Grid>
);
}
export default Matching

View File

@@ -0,0 +1,72 @@
import { Box, Button, Container, Typography } from '@mui/material';
import { quiz } from "../quizData";
import { useSelector } from 'react-redux';
import {useState } from 'react';
import Matching from './Matching';
import type { RootState } from '../../store';
import store from '../../store';
import { useDispatch } from 'react-redux';
import { mixUp, startTesting, stopTesting } from './quizSlice';
function QuizStats() {
const checkTask = (index: number): string => {
useSelector((state: RootState) => state.lists.lists[index]);
let state = store.getState();
if (state.lists.correctAnswers.length <= index) {
return "";
}
let correctCounter = state.lists.lists[index].reduce((prev, answ, i) => prev + Number(state.lists.correctAnswers[index][i] === answ), 0)
if (correctCounter == state.lists.lists[index].length) {
return "все ответы верные"
}
return `верно ${correctCounter}/${state.lists.lists[index].length}`
}
return (
<Container sx={{ margin: "auto" }}>
<h3>Результаты теста</h3>
<Typography>Задание 1: {checkTask(0)}</Typography>
<Typography>Задание 2: {checkTask(1)}</Typography>
</Container>
)
}
function Quiz() {
const dispatch = useDispatch();
const [displayingResults, setDisplayingResults] = useState(false);
const resetQuiz = () => {
setDisplayingResults(false);
dispatch(mixUp());
dispatch(startTesting());
}
const checkQuiz = () => {
setDisplayingResults(true);
dispatch(stopTesting());
}
return (
<Container maxWidth="md">
{quiz.map((item, index) => (
<Box key={item.id} component="section" sx={{ m: 2, p: 2 }}>
<Typography variant="h5" gutterBottom>
{index + 1}. {item.title}
</Typography>
<Matching index={index} tasks={item.tasks} />
</Box>
))}
<Box sx={{ display: 'flex', justifyContent: 'space-around' }}>
<Button onClick={checkQuiz} variant="contained">Проверить</Button>
<Button onClick={resetQuiz} variant="contained">Начать снова</Button>
</Box>
{displayingResults && <QuizStats />}
</Container>
);
}
export default Quiz

View File

@@ -0,0 +1,45 @@
import { DndContext, closestCenter } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
import { useDispatch, useSelector } from 'react-redux';
import { setDraggedItems } from './quizSlice';
import type { RootState } from '../../store';
import List from '@mui/material/List';
import { SortableItem } from '../components/SortableItem'
interface ComponentProps {
index: number;
answers: string[];
}
function SortableList({ index}: ComponentProps) {
const dispatch = useDispatch();
const arr = useSelector((state: RootState) => state.lists.lists[index])
const isDisabled = useSelector((state: RootState) => state.lists.isTestingDone)
const draggedItems = arr || [];
const handleDragEnd = (event: any) => {
const { active, over } = event;
if (active.id !== over.id) {
const oldIndex = draggedItems.indexOf(active.id);
const newIndex = draggedItems.indexOf(over.id);
const newList = arrayMove(draggedItems, oldIndex, newIndex);
dispatch(setDraggedItems({ index, items: newList }));
}
};
return (
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={draggedItems}
strategy={verticalListSortingStrategy}>
<List>
{draggedItems.map((item) => (
<SortableItem key={item} item={item} id={item} isDisabled={isDisabled}/>
))}
</List>
</SortableContext>
</DndContext>
);
}
export default SortableList;

View File

@@ -0,0 +1,73 @@
import { createSlice } from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';
function shuffle<T>(array:Array<T>):Array<T> {
let currentIndex = array.length;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
let randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
interface QuizState {
userAnswers: string[][]; // хранит перемещаемые элементы каждого списка ответов
correctAnswers:string[][] |boolean[][];// ответы для вопрсов, в случае с matching просто правильная последоавтельность, для sorting аналогично, для choosе последоватеьность boolean
isTestingDone:boolean// запрет на взаимодействие с квизом после окончания тестирования, чтобю юзер не наглел
}
const initialState: QuizState = {
userAnswers: [],
correctAnswers:[],
isTestingDone:false
};
const listsSlice = createSlice({
name: 'lists',
initialState,
reducers: {
addList: (state, action: PayloadAction<{index: number; items: string[]}>)=>{
const { index, items } = action.payload;
state.userAnswers.splice(index, 1, items); // с нулём создаётся по 2 экземпляра, видно в отладке
state.correctAnswers.splice(index, 1, items);
},
setDraggedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => {
const { index, items } = action.payload;
if (index >= 0 && index < state.userAnswers.length) {
state.userAnswers[index] = items; // обновляем конкретный список
}
},
setCheckedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => {
const { index, items } = action.payload;
if (index >= 0 && index < state.userAnswers.length) {
state.userAnswers[index] = items; // обновляем конкретный список
}
},
mixUp: (state) => {
state.userAnswers=state.userAnswers.map((list)=>
{
return shuffle(list);
})
},
stopTesting:(state)=>{
state.isTestingDone=true;
},
startTesting:(state)=>{
state.isTestingDone=false;
}
},
});
// Экспортируем действия и редьюсер
export const { addList, setDraggedItems,mixUp,startTesting,stopTesting } = listsSlice.actions;
export type {QuizState}
export default listsSlice.reducer;

View File

@@ -0,0 +1,92 @@
export type tTasks ={
"question": string; /* вопрос задания*/
"answer": string|number|boolean; /* ответ задания*/
}[]
export type tQuizzes = {
"id": number,
"type": "M" | "S" | "C", /* Match Sort Choose*/
"title": string, /* формулировка задания */
"tasks": tTasks,
}[];
export const quiz: tQuizzes = [
{
"id": 1,
"type": "M",
"title": "вопросй",
"tasks": [
{
"question": "адын?",
"answer": "адын"
},
{
"question": "2",
"answer": "2"
},
{
"question": "3",
"answer": "3"
},
{
"question": "4",
"answer": "4"
},
]
},
{
"id": 2,
"type": "S",
"title": "Вопрос 2 СОРТИРУЙ",
"tasks": [
{
"question": "1",
"answer": 1
},
{
"question": "22",
"answer": 2
},
{
"question": "333",
"answer": 3
},
{
"question": "4444",
"answer": 4
},
{
"question": "5555",
"answer": 5
},
]
}
,
{
"id": 2,
"type": "C",
"title": "Вопрос 3 Выбирай!",
"tasks": [
{
"question": "да",
"answer": true
},
{
"question": "нет",
"answer": false
},
{
"question": "и снова да",
"answer": true
},
{
"question": "нет",
"answer": false
},
{
"question": "дааа",
"answer": true
},
]
}
]

15
site/src/store.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { configureStore } from '@reduxjs/toolkit';
import listsReducer from './quiz/features/quizSlice';
const store = configureStore({
reducer: {
quiz: listsReducer,
},
devTools: { trace: true ,traceLimit: 25},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;