Выставлены типы
This commit is contained in:
parent
50e4add1db
commit
55ccfba006
@ -9,12 +9,6 @@ import WorkSpace from "./workSpace";
|
||||
import Header from "./header";
|
||||
import { saveCondition, getCondition } from "./lsBacking";
|
||||
import type {ElementsOfObject} from "./questionTypes"
|
||||
//Значения, собираемые для отправки на бэк
|
||||
interface Values {
|
||||
title: string;
|
||||
children: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
const types = [
|
||||
{desc:"текст", value:"text"},
|
||||
@ -25,19 +19,6 @@ const types = [
|
||||
{desc: "описание", value: "description"},
|
||||
{desc:"ничего", value:"none"},
|
||||
]
|
||||
export const TextField = (props: any) => {
|
||||
|
||||
const [field, meta, helpers] = useField(props);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Textarea resize="none" width="80%" {...field} {...props} />
|
||||
{meta.touched && meta.error ? (
|
||||
<div className="error">{meta.error}</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
//Для первого ознакомления рекомендую свернуть все функции и почитать их названия и описания
|
||||
|
||||
@ -51,7 +32,7 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
|
||||
//Для всех последующих элементов
|
||||
|
||||
//Создаём массив, состоящий из id всех существующих модалок
|
||||
let indexes:any = []
|
||||
let indexes:Array<number> = []
|
||||
//И берём только последние числа от строк, превращая их в числа
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
//Строка состоит из чисел, разделённых пробелом.
|
||||
@ -63,7 +44,7 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
|
||||
indexes.push(Number(stringArr[0]))
|
||||
}
|
||||
//Сортируем в порядке возрастания
|
||||
indexes.sort(function compare(a:any, b:any):any {
|
||||
indexes.sort(function compare(a:number, b:number):number {
|
||||
if (a < b) { return -1;}
|
||||
if (a > b) { return 1;}
|
||||
return 0;
|
||||
@ -72,15 +53,15 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
|
||||
let max = indexes[indexes.length - 1]
|
||||
|
||||
//Создаём массив - маску от 0 до самого высокого значения id
|
||||
let mask:any = []
|
||||
let mask:Array<number> = []
|
||||
for (let i = 0; i <= max; i++) {
|
||||
mask.push(i)
|
||||
}
|
||||
|
||||
//Ищем разницу между существующими id окон и маской. Список пропущенных значений есть список доступных имён.
|
||||
let difference = indexes
|
||||
.filter((num:any):any => !mask.includes(num))
|
||||
.concat(mask.filter((num:any):any => !indexes.includes(num)));
|
||||
.filter((num:number):boolean => !mask.includes(num))
|
||||
.concat(mask.filter((num:number):boolean => !indexes.includes(num)));
|
||||
|
||||
// difference - массив нехватающих в списке номеров.
|
||||
// Если все окна у нас по порядку, без пропусков - нужно добавить новый номер
|
||||
@ -94,7 +75,7 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
|
||||
}
|
||||
|
||||
//Прохождение по полю children в поисках нужного id
|
||||
const getIndexById = (id:string, array:Array<ElementsOfObject>):number => {
|
||||
const getIndexById = (id:string, array:Array<ElementsOfObject>):number | undefined => {
|
||||
let index
|
||||
for (let i = 0; i <= array.length; i++) {
|
||||
if (array[i] !== undefined) {
|
||||
@ -107,14 +88,13 @@ const getIndexById = (id:string, array:Array<ElementsOfObject>):number => {
|
||||
if (typeof index === "number") {
|
||||
return index
|
||||
} else {
|
||||
console.log("Я не нашёл нужный индекс, вывел 0")
|
||||
return 0
|
||||
return undefined
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Извлечение информации из id для поиска пути к ребёнку.
|
||||
const getObjectFromId = (id:string, array:any):any => {
|
||||
const getObjectFromId = (id:string, array:Array<ElementsOfObject>): ElementsOfObject | undefined => {
|
||||
//Делим строку на массив чисел
|
||||
let IDs = id.split(" ")
|
||||
|
||||
@ -135,12 +115,12 @@ const getObjectFromId = (id:string, array:any):any => {
|
||||
//Счётчик вложенности
|
||||
let nestingCounter = 0
|
||||
//В пересчётах в каждом слое вложенности сюда сохраняется найденный объект
|
||||
let bufferObject
|
||||
let bufferObject: ElementsOfObject | undefined
|
||||
|
||||
//Считаем до какого уровня вложенности нам вообще искать ребёнка
|
||||
let stopIndex = IDs.length
|
||||
|
||||
const searchId = (array:any) => {
|
||||
const searchId = (array:Array<ElementsOfObject>) => {
|
||||
if (nestingCounter === stopIndex) {
|
||||
//Мы достигли нужного уровня вложенности
|
||||
return
|
||||
@ -150,7 +130,7 @@ const getObjectFromId = (id:string, array:any):any => {
|
||||
let calcId = getNewIdString(nestingCounter)
|
||||
return (
|
||||
//Здесь можно в заранее созданную переменную оповещать нашли ли мы нужный id. И обработать ошибку если нет
|
||||
array.forEach((element:any) => {
|
||||
array.forEach((element:ElementsOfObject) => {
|
||||
if (element.id === calcId) {
|
||||
//Записываем найденный объект и ищем на следующем уровне
|
||||
bufferObject = element
|
||||
@ -163,7 +143,12 @@ const getObjectFromId = (id:string, array:any):any => {
|
||||
|
||||
}
|
||||
searchId(array)
|
||||
return bufferObject
|
||||
if (bufferObject !== undefined && bufferObject.id === id) {
|
||||
return bufferObject
|
||||
} else {
|
||||
return undefined
|
||||
}
|
||||
|
||||
|
||||
//Есть два варианта поиска:
|
||||
//Рекурсивно пройтись по хранилищу тупо ожидая наткнуться на нужного ребёнка
|
||||
@ -175,7 +160,7 @@ const getObjectFromId = (id:string, array:any):any => {
|
||||
export default () => {
|
||||
//Id - строится на основании всех id родителя + свободное число от 0 до +бесконечности.
|
||||
//Разделение айдишников в строке посредством пробела
|
||||
const [stockroom, setStockroom] = React.useState<any>([
|
||||
const [stockroom, setStockroom] = React.useState<Array<ElementsOfObject>>([
|
||||
{id: "0", type: 7, children: [
|
||||
{
|
||||
id: "0 0", type: 7, children: [
|
||||
@ -211,9 +196,13 @@ export default () => {
|
||||
|
||||
//Функция пересоздаёт дерево с проверкой каждого объекта.
|
||||
// Если объект в фокусе - создаётся новый объект и в него высыпаются старые поля, затем новые поля
|
||||
const createNewTreeFields = (value:any, tree = stockroom) => {
|
||||
//ФУНКЦИЯ УДАЛЯЕТ ДЕТЕЙ У НЕ КОНТЕЙНЕРОВ (контейнер div и селект)
|
||||
const createNewTreeFields = (value:Object, tree = stockroom):Array<ElementsOfObject> => {
|
||||
return (
|
||||
tree.map((node: any) => {
|
||||
tree.map((node: ElementsOfObject) => {
|
||||
if (node.type !== 7 && node.type !== 1) {
|
||||
node.children = []
|
||||
}
|
||||
|
||||
if (node.id === focus) {
|
||||
let obj = {
|
||||
@ -233,9 +222,14 @@ export default () => {
|
||||
)
|
||||
}
|
||||
//Создание дерева с обновлённым объектом
|
||||
const createNewTreeObject = (value:any, tree = stockroom) => {
|
||||
//ФУНКЦИЯ УДАЛЯЕТ ДЕТЕЙ У НЕ КОНТЕЙНЕРОВ (контейнер div и селект)
|
||||
const createNewTreeObject = (value:ElementsOfObject, tree = stockroom):Array<ElementsOfObject> => {
|
||||
return (
|
||||
tree.map((node: any) => {
|
||||
tree.map((node: ElementsOfObject) => {
|
||||
if (node.type !== 7 && node.type !== 1) {
|
||||
node.children = []
|
||||
}
|
||||
|
||||
if (node.id === value.id) {
|
||||
return value
|
||||
} else if (node.children.length !== 0) {
|
||||
@ -250,81 +244,83 @@ export default () => {
|
||||
)
|
||||
}
|
||||
|
||||
// Изменение типа очищает все поля
|
||||
const typeHC = (type:any): void => {
|
||||
const typeHC = (type:number): void => {
|
||||
if (focus !== undefined) {
|
||||
setStockroom(createNewTreeFields({type:type}))
|
||||
}
|
||||
}
|
||||
const colorHC = (color:any) => {
|
||||
const colorHC = (color:string) => {
|
||||
if (focus !== undefined) {
|
||||
setStockroom(createNewTreeFields({color:color}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const createObject = (obj:any, type:number = 4) => {
|
||||
const createObject = (type:number = 4) => {
|
||||
if (focus !== undefined) {
|
||||
//Если фокусный элемент - контейнер, добавление происходит внутрь него
|
||||
//Если фокусный элемент - не контейнер, добавление происходит после объекта с фокусом
|
||||
const focusedObj = getObjectFromId(focus, stockroom)
|
||||
|
||||
if (focusedObj !== undefined) {
|
||||
if (focusedObj.children !== undefined && focusedObj.type === 7) {
|
||||
//Кладём внутрь фокусного объекта
|
||||
|
||||
if (focusedObj.type === 7) {
|
||||
//Кладём внутрь фокусного объекта
|
||||
//Находим свободный ид и прикрепляем его к родительскому id
|
||||
let newId = getFreeNumber(focusedObj.children).toString()
|
||||
newId = focusedObj.id + " " + newId
|
||||
//Создаём новый объект
|
||||
const newObj = {
|
||||
id: newId,
|
||||
type: type,
|
||||
children: []
|
||||
}
|
||||
|
||||
//Находим свободный ид и прикрепляем его к родительскому id
|
||||
let newId:any = getFreeNumber(focusedObj.children)
|
||||
newId = focusedObj.id + " " + newId
|
||||
//Создаём новый объект
|
||||
const newObj = {
|
||||
id: newId,
|
||||
type: type,
|
||||
children: []
|
||||
}
|
||||
focusedObj.children.push(newObj)
|
||||
|
||||
focusedObj.children.push(newObj)
|
||||
//Создаём дерево с обновлённым родителем
|
||||
const newTree = createNewTreeObject(focusedObj)
|
||||
setStockroom(newTree)
|
||||
|
||||
//Создаём дерево с обновлённым родителем
|
||||
const newTree = createNewTreeObject(focusedObj)
|
||||
setStockroom(newTree)
|
||||
} else {
|
||||
//Кладём рядом с фокусным объектом
|
||||
|
||||
} else {
|
||||
//Кладём рядом с фокусным объектом
|
||||
//Находим родителя
|
||||
//Отфигачиваем последний id
|
||||
let parentId:string | string[] = focus.split(" ")
|
||||
parentId.pop()
|
||||
parentId = parentId.join(' ')
|
||||
const parentObj = getObjectFromId(parentId, stockroom)
|
||||
|
||||
//Находим родителя
|
||||
//Отфигачиваем последний id
|
||||
let parentId:any = focus.split(" ")
|
||||
parentId.pop()
|
||||
parentId = parentId.join(' ')
|
||||
const parentObj = getObjectFromId(parentId, stockroom)
|
||||
if (parentObj !== undefined) {
|
||||
//Находим свободный ид и прикрепляем его к родительскому id
|
||||
let newId:string = getFreeNumber(parentObj.children).toString()
|
||||
newId = parentId + " " + newId
|
||||
//Создаём новый объект
|
||||
const newObj = {
|
||||
id: newId,
|
||||
type: type,
|
||||
children: []
|
||||
}
|
||||
|
||||
//Находим свободный ид и прикрепляем его к родительскому id
|
||||
let newId:any = getFreeNumber(parentObj.children)
|
||||
newId = parentId + " " + newId
|
||||
//Создаём новый объект
|
||||
const newObj = {
|
||||
id: newId,
|
||||
type: type,
|
||||
children: []
|
||||
}
|
||||
//Создаём новый массив для поля-children-родителя и присваиваем этот массив
|
||||
let newChildrenArr = []
|
||||
for (let i = 0; parentObj.children.length > i ; i++) {
|
||||
let node = parentObj.children[i]
|
||||
if (node.id === focus) {
|
||||
newChildrenArr.push(node)
|
||||
newChildrenArr.push(newObj)
|
||||
} else {
|
||||
newChildrenArr.push(node)
|
||||
}
|
||||
}
|
||||
parentObj.children = newChildrenArr
|
||||
|
||||
//Создаём новый массив для поля-children-родителя и присваиваем этот массив
|
||||
let newChildrenArr = []
|
||||
for (let i = 0; parentObj.children.length > i ; i++) {
|
||||
let node = parentObj.children[i]
|
||||
if (node.id === focus) {
|
||||
newChildrenArr.push(node)
|
||||
newChildrenArr.push(newObj)
|
||||
} else {
|
||||
newChildrenArr.push(node)
|
||||
//Создаём дерево с обновлённым родителем
|
||||
const newTree = createNewTreeObject(parentObj)
|
||||
setStockroom(newTree)
|
||||
}
|
||||
}
|
||||
parentObj.children = newChildrenArr
|
||||
|
||||
//Создаём дерево с обновлённым родителем
|
||||
const newTree = createNewTreeObject(parentObj)
|
||||
setStockroom(newTree)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -337,139 +333,30 @@ export default () => {
|
||||
const focusedObj = getObjectFromId(focus, stockroom)
|
||||
|
||||
//Отфигачиваем последний id
|
||||
let parentId:any = focus.split(" ")
|
||||
let parentId:string | string[] = focus.split(" ")
|
||||
parentId.pop()
|
||||
parentId = parentId.join(' ')
|
||||
|
||||
const parentObj = getObjectFromId(parentId, stockroom)
|
||||
|
||||
//Создаём новый массив для поля-children-родителя, не включая в него фокусный объект
|
||||
let newChildrenArr = []
|
||||
for (let i = 0; parentObj.children.length > i ; i++) {
|
||||
let node = parentObj.children[i]
|
||||
if (node.id !== focus) {
|
||||
newChildrenArr.push(node)
|
||||
if (parentObj !== undefined) {
|
||||
//Создаём новый массив для поля-children-родителя, не включая в него фокусный объект
|
||||
let newChildrenArr = []
|
||||
for (let i = 0; parentObj.children.length > i ; i++) {
|
||||
let node = parentObj.children[i]
|
||||
if (node.id !== focus) {
|
||||
newChildrenArr.push(node)
|
||||
}
|
||||
}
|
||||
parentObj.children = newChildrenArr
|
||||
|
||||
|
||||
let newTree = createNewTreeObject(parentObj)
|
||||
setStockroom(newTree)
|
||||
}
|
||||
parentObj.children = newChildrenArr
|
||||
|
||||
|
||||
let newTree = createNewTreeObject(parentObj)
|
||||
console.log(stockroom)
|
||||
console.log(newTree)
|
||||
setStockroom(newTree)
|
||||
}
|
||||
}
|
||||
|
||||
// const changeFocus = (id: number): void => {
|
||||
// //Не менять фокус если снова выбрано то же окно
|
||||
// if (focus !== id) {
|
||||
// //Хранилище с отменённым фокусом у объектов (по задумке у одного элемента)
|
||||
// let newArr = stockroom.map((e:ElementsOfObject) => {
|
||||
// e.isFocus = false
|
||||
// return e
|
||||
// })
|
||||
//
|
||||
// //Получаем индексы фокусированных объектов. Новый и, если есть, старый
|
||||
// let index = getIndexById(id, stockroom)
|
||||
//
|
||||
// //Устанавливаем новый фокус и пересоздаём массив
|
||||
// setFocus(id)
|
||||
// saveCondition("focus", id)
|
||||
//
|
||||
// newArr[index].isFocus = true
|
||||
// setStockroom([...newArr])
|
||||
// }
|
||||
// }
|
||||
// const changeBgColor = (color: string): void => {
|
||||
// if (focus !== undefined) {
|
||||
// let index = getIndexById(focus, stockroom)
|
||||
//
|
||||
// let newArr = stockroom
|
||||
// newArr[index].color = color
|
||||
// setStockroom([...newArr])
|
||||
// saveCondition("stockroom", newArr)
|
||||
// }
|
||||
// }
|
||||
// const changeText = (text: string): void => {
|
||||
// if (focus !== undefined) {
|
||||
// let index = getIndexById(focus, stockroom)
|
||||
// let newArr = stockroom
|
||||
// newArr[index].text = text
|
||||
// setStockroom([...newArr])
|
||||
// saveCondition("stockroom", newArr)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// const createObject = (obj:ElementsOfObject) => {
|
||||
//
|
||||
// //Получаем и присваиваем первый свободный айдишник (по возрастанию)
|
||||
// const free = getFreeNumber(stockroom)
|
||||
// obj.id = free
|
||||
//
|
||||
// //Хранилище с отменённым фокусом у объектов (по задумке у одного элемента)
|
||||
// let newArr = stockroom.map((e:ElementsOfObject) => {
|
||||
// e.isFocus = false
|
||||
// return e
|
||||
// })
|
||||
//
|
||||
// //Мы должны вставить новый объект следующим после того, на котором фокус. Это достигается позиционированием в массив
|
||||
// if (focus === undefined){ //фокуса нет - добавляем в конец массива
|
||||
// newArr.push(obj)
|
||||
// setStockroom([...newArr])
|
||||
// saveCondition("stockroom", newArr)
|
||||
// //Говорим стейту с фокусом, что фокус изменился
|
||||
// setFocus(newArr.length - 1)
|
||||
// } else { //фокус есть - добавляем после объекта с фокусом
|
||||
//
|
||||
//
|
||||
//
|
||||
// let index = getIndexById(focus, stockroom)
|
||||
// let current = stockroom[index]
|
||||
// //Объект в фокусе - контейнер. Новый объект создаётся с указанием, что контейнер - родитель
|
||||
// if (current.type === 7) {
|
||||
// obj.parent = current.id
|
||||
// }
|
||||
//
|
||||
// newArr.splice(index + 1, 0, obj)
|
||||
//
|
||||
// //Говорим стейту с фокусом, что фокус изменился
|
||||
// setFocus(index + 1)
|
||||
// setStockroom([...newArr])
|
||||
// saveCondition("stockroom", newArr)
|
||||
// }
|
||||
// }
|
||||
// const deleteObject = (id: number): void => {
|
||||
// let index = getIndexById(id, stockroom)
|
||||
// //Проверка, что объект с таким id существует
|
||||
// if (stockroom[index] !== undefined) {
|
||||
// //Если удалён был фокусный объект - фокус теперь неизвестен
|
||||
// if (stockroom[index].isFocus) {
|
||||
// setFocus(undefined)
|
||||
// }
|
||||
//
|
||||
// let newArr:any = []
|
||||
// //Если удалённый объект был хранилищем (контейнером, или селектом), мы не вложим в новый массив его и его потомков
|
||||
// if (stockroom[index].type === 1 || stockroom[index].type === 7) {
|
||||
// stockroom.forEach((e:any, i:number) => {
|
||||
// if (e.id !== id) {
|
||||
// if (e.parent !== id) {
|
||||
// newArr.push(e)
|
||||
// } else {
|
||||
// if (e.isFocus) {
|
||||
// setFocus(undefined)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// } else {
|
||||
// newArr = stockroom
|
||||
// newArr.splice(index, 1)
|
||||
// }
|
||||
// setStockroom([...newArr])
|
||||
// saveCondition("stockroom", newArr)
|
||||
// }
|
||||
// }
|
||||
return(
|
||||
<>
|
||||
<Header/>
|
||||
|
||||
@ -2,11 +2,9 @@
|
||||
interface ElementsOfObject {
|
||||
text?: string;
|
||||
id: string;
|
||||
// isFocus: boolean;
|
||||
color?: string;
|
||||
type: number
|
||||
parent: undefined | number
|
||||
children: Array<ElementsOfObject> | undefined
|
||||
children: Array<ElementsOfObject>
|
||||
}
|
||||
interface QuestionProps {
|
||||
type: number;
|
||||
|
||||
@ -6,22 +6,11 @@ import Viewer from "./viewer";
|
||||
|
||||
export default (props: any) => {
|
||||
|
||||
let current:any
|
||||
if (props.focus !== undefined) {
|
||||
if (props.stockroom !== undefined) {
|
||||
const index = props.getIndexById(props.focus, props.stockroom)
|
||||
|
||||
if (index !== undefined) {
|
||||
current = props.stockroom[index]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Select
|
||||
placeholder='тип вопроса'
|
||||
value={current === undefined ? 0 : current.type}
|
||||
// value={current === undefined ? 0 : current.type}
|
||||
onChange={e => {
|
||||
props.typeHC(Number(e.target.value))
|
||||
}}
|
||||
@ -48,7 +37,7 @@ export default (props: any) => {
|
||||
/>
|
||||
<Button
|
||||
onClick={() => {
|
||||
props.createObject({text: "", color: "", isFocus: true, type: 0, id: -1, parent: undefined})
|
||||
props.createObject()
|
||||
|
||||
}}
|
||||
>добавить</Button>
|
||||
|
||||
@ -3,7 +3,7 @@ import {
|
||||
Select, Checkbox, Button, Box, VStack, HStack, Textarea
|
||||
} from '@chakra-ui/react'
|
||||
|
||||
import {TextField} from "./createQuestion";
|
||||
// import {TextField} from "./createQuestion";
|
||||
import type {QuestionProps} from "./questionTypes"
|
||||
|
||||
export default ({focused, element, stockroom = [], changeFocus, keyInfo, shiftKeyInfo, focus} : any) => {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user