p6/7 started (Freezing due to no experience in redux)

This commit is contained in:
2026-04-16 22:52:43 +10:00
parent 4f8f033306
commit 0b76fc69e5
12 changed files with 420 additions and 7 deletions

View File

@@ -82,7 +82,11 @@ function NavBar({ active }: ComponentProps) {
Контакты
</Button>
</Link>
<Link to="/quiz">
<Button variant={active == '4' ? 'contained' : 'text'} color="info" size="medium">
Проверь себя
</Button>
</Link>
</Box>
<Box sx={{ display: { xs: 'flex', md: 'none' } }}>
<IconButton aria-label="Menu button" onClick={toggleDrawer(true)}>
@@ -108,6 +112,9 @@ function NavBar({ active }: ComponentProps) {
<Link style={{ textDecoration: 'none' }} to="/chart">
<StyledMenuItem selected={active == '3'}>Диаграммы</StyledMenuItem>
</Link>
<Link style={{ textDecoration: 'none' }} to="/quiz">
<StyledMenuItem selected={active == '4'}>Проверь Себя</StyledMenuItem>
</Link>
</MenuList>
</Drawer>
</Box>

View File

@@ -10,7 +10,7 @@ import List from "./list/List";
import Main from "./main/Main";
import Building from "./building/Building";
import Chart from "./chart/Chart";
import Testing from "./testing/Testing";
const router = createBrowserRouter([
{
path: "",
@@ -20,6 +20,10 @@ const router = createBrowserRouter([
path: "/list",
element: <List />,
},
{
path: "/quiz",
element: <Testing />,
},
{
path: "/chart",
element: <Chart />,

0
labs/lab8/src/store.tsx Normal file
View File

View File

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

View File

@@ -0,0 +1,40 @@
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;// чтобы тайпскрипт компилятор не жаловался, добавил в инетрфейс, хотя и так компилируется нормально
}
export function SortableItem({ item }: SortableItemProps) {
const id = item; /* идентификатор для useSortable */
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
} = useSortable({ id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
};
return (
<ListItem ref={ 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,36 @@
import { Grid, List, ListItem, ListItemButton, ListItemText } from '@mui/material';
import type {tTasks} from "../quizData"
import SortableList from '../features/SortableList';
interface ComponentProps {
tasks: tTasks;
}
function Matching({tasks}: ComponentProps) {
const answers: string[] = tasks.map((item) => 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 answers={answers} />
</Grid>
</Grid>
);
}
export default Matching

View File

@@ -0,0 +1,25 @@
import { Box, Button, Container, Typography } from '@mui/material';
import { quiz } from "../quizData";
import Matching from './Matching';
function Quiz() {
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 tasks={item.tasks} />
</Box>
))}
<Box sx={{ display: 'flex', justifyContent:'space-around' }}>
<Button variant="contained">Проверить</Button>
<Button variant="contained">Начать снова</Button>
</Box>
</Container>
);
}
export default Quiz

View File

@@ -0,0 +1,39 @@
import { DndContext, closestCenter } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
import { useState } from 'react';
import List from '@mui/material/List';
import {SortableItem} from '../components/SortableItem'
interface ComponentProps {
answers: string[];
}
function SortableList({ answers }: ComponentProps ) {
const [draggedItems, setDraggedItems] = useState(answers);
const handleDragEnd = (event: any) => {
const { active, over } = event;
if (active.id !== over.id) {
setDraggedItems((draggedItems) => {
const oldIndex = draggedItems.indexOf(active.id);
const newIndex = draggedItems.indexOf(over.id);
return arrayMove(draggedItems, oldIndex, newIndex);
});
}
};
return (
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={ draggedItems }
strategy={verticalListSortingStrategy}>
<List>
{draggedItems.map((item) => (
<SortableItem key={ item } item={item} id={ item } />
))}
</List>
</SortableContext>
</DndContext>
);
}
export default SortableList;

View File

@@ -0,0 +1,30 @@
import { createSlice } from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';
interface ListsState {
lists: string[][]; // хранит перемещаемые элементы каждого списка ответов
}
const initialState: ListsState = {
lists: [],
};
const listsSlice = createSlice({
name: 'lists',
initialState,
reducers: {
addList: (state, action: PayloadAction<{index: number; items: string[]}>)=>{
const { index, items } = action.payload;
state.lists.splice(index, 0, items);
},
setDraggedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => {
const { index, items } = action.payload;
if (index >= 0 && index < state.lists.length) {
state.lists[index] = items; // обновляем конкретный список
}
},
},
});
// Экспортируем действия и редьюсер
export const { addList, setDraggedItems } = listsSlice.actions;
export default listsSlice.reducer;

View File

@@ -0,0 +1,64 @@
export type tTasks ={
"question": string; /* вопрос задания*/
"answer": string; /* ответ задания*/
}[]
export type tQuizzes = {
"id": number,
"type": "M" | "S", /* типы заданий, М - сопоставление*/
"title": string, /* формулировка задания */
"tasks": tTasks,
}[];
export const quiz: tQuizzes = [
{
"id": 1,
"type": "M",
"title": "Сопоставьте сооружение и город, в котором оно расположено.",
"tasks": [
{
"question": "Башня Аль-Хамра",
"answer": "Кувейт"
},
{
"question": "Башня CITIC",
"answer": "Гуанчжоу"
},
{
"question": "Телебашня «Коктобе»",
"answer": "Алматы"
},
{
"question": "Си-Эн Тауэр",
"answer": "Торонто"
},
]
},
{
"id": 2,
"type": "M",
"title": "Сопоставьте сооружение и его высоту.",
"tasks": [
{
"question": "Tokyo Skytree",
"answer": "634"
},
{
"question": "Бурдж-Халифа",
"answer": "838"
},
{
"question": "Эмпайр-стейт-билдинг",
"answer": "448.7"
},
{
"question": "Останкинская башня",
"answer": "540.1"
},
{
"question": "Lotte World Tower",
"answer": "555"
},
]
}
]