import { create } from "zustand"; import { persist } from "zustand/middleware"; type Variants = { answer: string; answerLong: string; hints: string; }; interface Question { id: number; title: string; description: string; type: string; required: boolean; deleted: true; page: number; content: { variants: Variants[]; own: boolean; multi: boolean; }; version: number; parent_ids: number[]; created_at: string; updated_at: string; } interface QuestionStore { listQuestions: any; openedModalSettings: string; } export const questionStore = create()( persist( () => ({ listQuestions: [], openedModalSettings: "", }), { name: "question", } ) ); export const updateQuestionsList = (index: number, data: Partial) => { const array = [...questionStore.getState()["listQuestions"]]; array.splice(index, 1, { ...array[index], ...data }); questionStore.setState({ listQuestions: array }); }; export const updateQuestionsListDragAndDrop = (updatedQuestions: Question[]) => { questionStore.setState({ listQuestions: updatedQuestions }); }; export const createQuestion = (id: number) => { const idQ = getRandom(1000000, 10000000); const newData = [...questionStore.getState()["listQuestions"]]; //пересоздание массива newData.push({ id: idQ, title: "", description: "", type: "", required: true, deleted: true, page: 0, content: { variants: [ { answer: "", answerLong: "", hints: "", }, ], own: true, multi: true, }, version: 0, parent_ids: [0], created_at: "", updated_at: "", }); questionStore.setState({ listQuestions: newData }); }; export const removeQuestion = (index: number) => { const array = [...questionStore.getState()["listQuestions"]]; array.splice(index, 1); questionStore.setState({ listQuestions: array }); }; export const resetSomeField = (data: Record) => { questionStore.setState(data); }; export const findQuestionById = (id_question: number) => { let found = null; questionStore.getState()["listQuestions"].some((quiz: Question, index: number) => { if (quiz.id === id_question) { found = { quiz, index }; return true; } }); return found; }; function getRandom(min: number, max: number) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }