Дерево. Функция создания

This commit is contained in:
krokodilka 2022-08-08 04:23:24 +03:00
parent 7efa51acb5
commit 7b65426dab
7 changed files with 531 additions and 354 deletions

@ -49,9 +49,12 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
//Создаём массив, состоящий из id всех существующих модалок
let indexes:any = []
//И берём только последние числа от строк, превращая их в числа
for (let i = 0; i < array.length; i++) {
indexes.push(array[i].id)
indexes.push(Number(array[i].id.slice(-1)))
}
console.log("indexes")
console.log(indexes)
//Сортируем в порядке возрастания
indexes.sort(function compare(a:any, b:any):any {
if (a < b) { return -1;}
@ -59,7 +62,11 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
return 0;
}
)
console.log("filtred indexes")
console.log(indexes)
let max = indexes[indexes.length - 1]
console.log("max value")
console.log(max)
//Создаём массив - маску от 0 до самого высокого значения id
let mask:any = []
@ -75,6 +82,7 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
// difference - массив нехватающих в списке номеров.
// Если все окна у нас по порядку, без пропусков - нужно добавить новый номер
if (difference.length === 0) {
console.log("+1")
return(max + 1)
} else {
//Иначе добавить нехватающий
@ -82,10 +90,13 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
}
}
}
const getIndexById = (id:number, array:Array<ElementsOfObject>):number => {
const getIndexById = (id:string, array:Array<ElementsOfObject>):number => {
let index
// id = id.slice(-1)
console.log("ищу id " + id)
for (let i = 0; i <= array.length; i++) {
if (array[i] !== undefined) {
console.log("B " + array[i].id)
if (array[i].id === id) {
index = i
break
@ -99,212 +110,337 @@ const getIndexById = (id:number, array:Array<ElementsOfObject>):number => {
return 0
}
}
const getObjectFromId = (id:string, array:any):any => {
let indexes = id.split("")
//буфер содержит id всех родителей (от ребёнка до первого родителя)
let bufer = []
for (let i = 0; i < indexes.length; i++) {
let val = (id.length - i)
bufer.push(id.substring(0, val))
}
console.log(bufer)
let parentObj = array
for (let i = 0; i < indexes.length - 1; i++) {
let id = bufer[bufer.length - i - 1]
parentObj = parentObj[getIndexById(id, parentObj)].children
}
if (parentObj.length > 1) {
parentObj = parentObj[Number(id.slice(-1))]
}
if (Array.isArray(parentObj)) {
return parentObj[0]
} else {
return parentObj
}
}
export default () => {
const [stockroom, setStockroom] = React.useState<Array<ElementsOfObject>>([])
const [focus, setFocus] = React.useState<number | undefined>() //Хранит id объекта
// const [stockroom, setStockroom] = React.useState<Array<ElementsOfObject>>([
const [stockroom, setStockroom] = React.useState<any>([
{id:"0", type:7, children:[
{id:"00", children:[], type:4}
]
},
{id:"1", type:7, children:[
{id:"10", children:[
{id:"100", children:[], type:4},
{id:"101", children:[], type:4}
], type:7}
]
},
{id:"2",type:4, children:[]}
])
const [focus, setFocus] = React.useState<string | undefined>("101") //Хранит путь объекта
// React.useEffect(() => {
// console.log(focus)
// if (focus !== undefined) {
// let elem = document.getElementById(focus + "")
// if (elem !== null) {
// console.log(elem)
// elem.focus()
// }
// }
// },[focus])
const setNewFocus = (value:string, multiFocus:boolean) => {
//Фокусы ставятся или удаляются от клика по уже созданным элементам.
if (multiFocus) {
//Клик ЛКМ + shift - мультивыбор
//При пересоздании массива для изменения фокуса объекта отменяются фокусы у всех элементов массива
//Изменение типа очищает все поля, кроме фокуса
const typeHC = (type:number): void => {
if (focus !== undefined) {
let index = getIndexById(focus, stockroom)
let newArr = stockroom
newArr[index].type = type
newArr[index].color = ""
newArr[index].text = ""
setStockroom([...newArr])
saveCondition("stockroom", newArr)
} else {
//Клик ЛКМ - единичный выбор.
setFocus(value)
}
}
const changeFocus = (id: number): void => {
//Не менять фокус если снова выбрано то же окно
if (focus !== id) {
//Хранилище с отменённым фокусом у объектов (по задумке у одного элемента)
let newArr = stockroom.map((e:ElementsOfObject) => {
e.isFocus = false
return e
})
// Изменение типа очищает все поля
const createNewTree = (value:any, tree = stockroom, ignoreFocus = false) => {
console.log("focus")
console.log(focus)
return (
tree.map((node: any) => {
console.log(node.id)
//Получаем индексы фокусированных объектов. Новый и, если есть, старый
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 (node.id === focus && !ignoreFocus) {
console.log(node)
let obj = {
...node,
...value,
}
console.log(obj)
return (obj)
} else if (node.children.length !== 0) {
return {
...node,
children: createNewTree(value, node.children)
}
} else {
return node
}
})
//Мы должны вставить новый объект следующим после того, на котором фокус. Это достигается позиционированием в массив
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 typeHC = (type:any): void => {
if (focus !== undefined) {
setStockroom(createNewTree({type:type}))
}
}
const colorHC = (color:any) => {
if (focus !== undefined) {
setStockroom(createNewTree({color:color}))
}
}
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)
}
const createObject = (obj:any, type:number = 4) => {
if (focus !== undefined) {
const focusedObj = getObjectFromId(focus, stockroom)
const creacteNew = (arr = stockroom) => {
return arr.map((node: any) => {
if (node.children.length !== 0) {
console.log(node)
return {
...node,
children: creacteNew(node.children)
}
} else {
console.log("просто возвращаю")
console.log(node)
return node
}
})
} else {
newArr = stockroom
newArr.splice(index, 1)
}
setStockroom([...newArr])
saveCondition("stockroom", newArr)
console.log(focusedObj)
if (focus.length > 1) {
const parentObj = getObjectFromId(focus.slice(0,-1), stockroom)
console.log(parentObj)
console.log(parentObj.children)
let newId:any = getFreeNumber(parentObj.children)
newId = focus.slice(0,-1) + newId
console.log(newId)
const newObj = {
id: newId,
type: type,
children: []
}
let newCildrenArr = []
console.log(parentObj.children.length)
for (let i = 0; parentObj.children.length > i ; i++) {
let node = parentObj.children[i]
console.log("работаю с этой нодой")
console.log(node)
if (node.id === focus) {
newCildrenArr.push(node)
newCildrenArr.push(newObj)
} else {
newCildrenArr.push(node)
}
}
parentObj.children = newCildrenArr
const newTree = creacteNew()
console.log(newTree)
setFocus(newId+"")
setStockroom(newTree)
} else {
let newId:any = getFreeNumber(stockroom)
let newCildrenArr = []
const newObj = {
id: newId+"",
type: 4,
children: []
}
for (let i = 0; stockroom.length > i ; i++) {
let node = stockroom[i]
console.log("работаю с этой нодой")
console.log(node)
if (node.id === focus) {
newCildrenArr.push(node)
newCildrenArr.push(newObj)
} else {
newCildrenArr.push(node)
}
}
console.log(newCildrenArr)
setFocus(newId+"")
setStockroom(newCildrenArr)
}
}
}
console.log("render")
// 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(
<>
<Formik
initialValues={{
children: '',
title: '',
description:'описание',
}}
onSubmit={(values, actions) => {
// console.log(JSON.stringify(values))
console.log(getCondition())
console.log(stockroom)
}}
<Header/>
<HStack
justifyContent="space-between"
alignItems="normal"
>
{(props: FormikProps<Values>) => (
<VStack
minWidth="200px"
bgColor="lightgray"
height="98vh"
padding="10px"
>
<Form>
<Header/>
<HStack
justifyContent="space-between"
alignItems="normal"
>
<VStack
minWidth="200px"
bgColor="lightgray"
height="98vh"
padding="10px"
>
</VStack>
</VStack>
<VStack>
<WorkSpace
stockroom={stockroom}
setNewFocus={setNewFocus}
focus={focus}
/>
</VStack>
<VStack>
<WorkSpace
stockroom={stockroom}
changeFocus={changeFocus}
/>
</VStack>
<VStack
minWidth="250px"
bgColor="lightgray"
height="98vh"
padding="10px"
overflow="auto"
>
<Settings
types={types}
stockroom={stockroom}
typeHC={typeHC}
focus={focus}
changeFocus={changeFocus}
changeBgColor={changeBgColor}
changeText={changeText}
getIndexById={getIndexById}
createObject={createObject}
deleteObject={deleteObject}
/>
</VStack>
</HStack>
</Form>
)}
</Formik>
<VStack
minWidth="250px"
bgColor="lightgray"
height="98vh"
padding="10px"
overflow="auto"
>
<Settings
types={types}
stockroom={stockroom}
typeHC={typeHC}
focus={focus}
changeFocus={stockroom}
changeBgColor={colorHC}
changeText={stockroom}
getIndexById={getIndexById}
createObject={createObject}
deleteObject={stockroom}
/>
{/*<Button onClick={() => {*/}
{/* typeHC(5)*/}
{/*}}>info</Button>*/}
</VStack>
</HStack>
</>
)
}

@ -1,11 +1,12 @@
//Поля объектов, используемых для отображения созданных пользователем инструментов
interface ElementsOfObject {
text?: string;
id: number;
isFocus: boolean;
id: string;
// isFocus: boolean;
color?: string;
type: number
parent: undefined | number
children: Array<ElementsOfObject> | undefined
}
interface QuestionProps {
type: number;

@ -42,51 +42,51 @@ export default (props: any) => {
getIndexById={props.getIndexById}
current={current}
/>
<Button type="submit">Создать вопрос</Button>
{current === undefined ?
null
:
current.type === 5 ?
<SunEditor
width="200px"
onChange={(e:any)=> {
let visual = document.getElementById(current.id)
if (visual !== null) {
visual.innerHTML = e
}
props.changeText(e)
}}
// imageUploadHandler={(e:any)=>console.log(e)}
// onImageUpload={(e:any)=>console.log(e)}
// showController={(e:any)=>console.log(e)}
// hideToolbar={false}
defaultValue={current.text}
setOptions={{
buttonList: [
[
'undo', 'redo',
'font', 'fontSize', 'formatBlock',
'paragraphStyle', 'blockquote',
'bold', 'underline', 'italic', 'strike', 'subscript', 'superscript',
'fontColor', 'hiliteColor', 'textStyle',
'removeFormat',
'outdent', 'indent',
'align', 'horizontalRule', 'list', 'lineHeight',
'table', 'link', 'image', 'video',
'fullScreen', 'showBlocks', 'codeView',
'preview', 'print', 'save', 'template',
]
]
}}
/>
:
<Textarea
onChange={(e) => props.changeText(e.target.value)}
placeholder="Текст"
maxWidth="300px"
value={current.text}
/>
}
{/*<Button type="submit">Создать вопрос</Button>*/}
{/*{current === undefined ?*/}
{/* null*/}
{/* :*/}
{/* current.type === 5 ?*/}
{/* <SunEditor*/}
{/* width="200px"*/}
{/* onChange={(e:any)=> {*/}
{/* let visual = document.getElementById(current.id)*/}
{/* if (visual !== null) {*/}
{/* visual.innerHTML = e*/}
{/* }*/}
{/* props.changeText(e)*/}
{/* }}*/}
{/* // imageUploadHandler={(e:any)=>console.log(e)}*/}
{/* // onImageUpload={(e:any)=>console.log(e)}*/}
{/* // showController={(e:any)=>console.log(e)}*/}
{/* // hideToolbar={false}*/}
{/* defaultValue={current.text}*/}
{/* setOptions={{*/}
{/* buttonList: [*/}
{/* [*/}
{/* 'undo', 'redo',*/}
{/* 'font', 'fontSize', 'formatBlock',*/}
{/* 'paragraphStyle', 'blockquote',*/}
{/* 'bold', 'underline', 'italic', 'strike', 'subscript', 'superscript',*/}
{/* 'fontColor', 'hiliteColor', 'textStyle',*/}
{/* 'removeFormat',*/}
{/* 'outdent', 'indent',*/}
{/* 'align', 'horizontalRule', 'list', 'lineHeight',*/}
{/* 'table', 'link', 'image', 'video',*/}
{/* 'fullScreen', 'showBlocks', 'codeView',*/}
{/* 'preview', 'print', 'save', 'template',*/}
{/* ]*/}
{/* ]*/}
{/* }}*/}
{/* />*/}
{/* :*/}
{/* <Textarea*/}
{/* onChange={(e) => props.changeText(e.target.value)}*/}
{/* placeholder="Текст"*/}
{/* maxWidth="300px"*/}
{/* value={current.text}*/}
{/* />*/}
{/*}*/}
</>
)
}

@ -6,10 +6,26 @@ import {TextField} from "./createQuestion";
import Description from "./description"
import type {QuestionProps} from "./questionTypes"
export default ({element, stockroom = [], changeFocus, keyInfo} : any) => {
export default ({focused, element, stockroom = [], changeFocus, keyInfo, shiftKeyInfo, focus} : any) => {
switch(element.type) {
case 0://Тип элемента вопроса - текст?
return (<TextField name="text" placeholder="текст" type="text" key={keyInfo}/>)
return(
<Button
key={keyInfo}
backgroundColor={element.color}
sx={{border: element.id == focus? focused.border : "solid black 1px"}}
onClick={(event:any) => {
shiftKeyInfo(event, element.id)
event.target.blur()
}}
>{element.text}</Button>
)
// return (<TextField name="text"
// sx={{border: element.id == focus? focused.border : "solid black 1px"}}
// placeholder="текст"
// type="text" key={keyInfo}
// onClick={(event:any) => shiftKeyInfo(event, element.id)}/>)
break;
case 1://Тип элемента вопроса - селект?
return (
@ -20,12 +36,29 @@ export default ({element, stockroom = [], changeFocus, keyInfo} : any) => {
// })
// }
// </Select>
<></>
<Button
key={keyInfo}
backgroundColor={element.color}
sx={{border: element.id == focus? focused.border : "solid black 1px"}}
onClick={(event:any) => {
shiftKeyInfo(event, element.id)
event.target.blur()
}}
>{element.text}</Button>
)
break;
case 2://Тип элемента вопроса - чекбокс?
return(
<>
<Button
key={keyInfo}
backgroundColor={element.color}
sx={{border: element.id == focus? focused.border : "solid black 1px"}}
onClick={(event:any) => {
shiftKeyInfo(event, element.id)
event.target.blur()
}}
>{element.text}</Button>
{/*{*/}
{/* stockroom.map((e:any, i:number) => {*/}
{/* return <Checkbox key={i}>{e.text}</Checkbox>*/}
@ -35,15 +68,17 @@ export default ({element, stockroom = [], changeFocus, keyInfo} : any) => {
)
break;
case 3://Тип элемента вопроса - файл?
return (<input type="file" key={keyInfo}/>)
return (<input type="file" key={keyInfo} onClick={(event:any) => shiftKeyInfo(event, element.id)}
style={{border: element.id == focus? focused.border : "solid black 1px"}}/>)
break;
case 4://Тип элемента вопроса - кнопка?
return(
<Button
key={keyInfo}
backgroundColor={element.color}
onClick={(event: any) => {
changeFocus(element.id)
sx={{border: element.id == focus? focused.border : "solid black 1px"}}
onClick={(event:any) => {
shiftKeyInfo(event, element.id)
event.target.blur()
}}
>{element.text}</Button>
@ -56,6 +91,8 @@ export default ({element, stockroom = [], changeFocus, keyInfo} : any) => {
border="solid 1px #d2d2d2"
padding="10px"
key={keyInfo}
sx={{border: element.id == focus? focused.border : "solid black 1px"}}
onClick={(event:any) => shiftKeyInfo(event, element.id)}
/>
)
break;

@ -32,33 +32,33 @@ export default (props: any) => {
}}
>добавить</Button>
<Button
onClick={() => {
props.createObject({text: "контейнер", isFocus: true, type: 7, id: -1, parent: undefined})
{/*<Button*/}
{/* onClick={() => {*/}
{/* props.createObject({text: "контейнер", isFocus: true, type: 7, id: -1, parent: undefined})*/}
}}
>контейнер</Button>
{/* }}*/}
{/*>контейнер</Button>*/}
{
props.stockroom.length === 0 ?
null
:
<VStack style={{
boxShadow:"rgba(0, 0, 0, 0.3) 0px 0px 2px, rgba(0, 0, 0, 0.3) 0px 4px 8px",
padding:"5px",
width:"150px",
borderRadius:"4px",
maxHeight:"30vh",
minHeight:"50px",
overflow:"auto",
}}>
<Viewer
stockroom={props.stockroom}
changeFocus={props.changeFocus}
deleteObject={props.deleteObject}
/>
</VStack>
}
{/*{*/}
{/* props.stockroom.length === 0 ?*/}
{/* null*/}
{/* :*/}
{/* <VStack style={{*/}
{/* boxShadow:"rgba(0, 0, 0, 0.3) 0px 0px 2px, rgba(0, 0, 0, 0.3) 0px 4px 8px",*/}
{/* padding:"5px",*/}
{/* width:"150px",*/}
{/* borderRadius:"4px",*/}
{/* maxHeight:"30vh",*/}
{/* minHeight:"50px",*/}
{/* overflow:"auto",*/}
{/* }}>*/}
{/* <Viewer*/}
{/* stockroom={props.stockroom}*/}
{/* changeFocus={props.changeFocus}*/}
{/* deleteObject={props.deleteObject}*/}
{/* />*/}
{/* </VStack>*/}
{/*}*/}
</>
)
}

@ -1,89 +1,104 @@
import React from 'react';
import Types from "./types"
import {QuestionProps} from "./questionTypes";
import Description from "./description";
import {TextField} from "./createQuestion";
import {Box} from "@chakra-ui/react";
export default ({stockroom, changeFocus} : any) => {
const focused = {
border: "solid 2px blue"
}
export default ({stockroom, setNewFocus, focus} : any) => {
if (stockroom.length !== 0) {
// На основе хранилища с плоскими объектами строится хранилище с вложенностями.
// фокусы - массив со значениями (для мультифокуса)
// focus.split(" ")
console.log("строю с нуля на основании этого массива")
console.log(stockroom)
//Мы разворачиваем стартовый массив и вкладываем элементы в начало результирующего массива.
let reverseStockroom: any
let arrayStorage: any = {}
let newStorage: any = []
//Создаём хранилище со всеми вложенностями. Ключи - id родителя
stockroom.reverse().forEach((e: any, i: number) => {
if (e.parent !== undefined) {
if (arrayStorage[e.parent] === undefined) {
arrayStorage[e.parent] = []
}
arrayStorage[e.parent].unshift(e)
const shiftKeyInfo = (event:any, id:any) => {
event.stopPropagation()
if (event.shiftKey) {
setNewFocus(id, true)
} else {
setNewFocus(id, false)
}
})
}
//Если есть какие-то вложенности
if (Object.keys(arrayStorage).length !== 0) {
//Теперь у нас есть массив со всеми вложенностями.
//Будем проходиться по хранилищу задом наперёд, ибо не имеем пометок где заканчивается хранилище, но знаем где оно начинается
reverseStockroom = stockroom.reverse();
//Важно помнить, что мы проходимся по массиву линейно и совпадение id текущего элемента и id в arrayStorage может быть единожды.
//Это значит, что найдя id в arrayStorage мы можем что-либо сделать с этим массивом и больше уже больше никогда его не тронем.
//Возможны 4 состояния объекта:
//родитель_дети
//нет_______нет - просто вложить в результирующий массив
//нет________да - вложить в результирующий массив с полем children
//да________нет - этот объект уже был использован в массиве arrayStorage. Оставить в покое
//да_________да - этот объект уже был использован в массиве arrayStorage. В его поле children нужно вложить массив его детей
// в массиве arrayStorage вложить в поле children родителя массив с детьми и ждать, пока очередь дойдёт до родителя
reverseStockroom.forEach((e: any, i: number) => {
if (arrayStorage[e.id] === undefined) {
//Объект не содержит потомков. Дети - нет
if (e.parent === undefined) {
//Родитель - нет
newStorage.push(e)
} //else Родитель - да
} else {
//Объект содержит потомков. Дети - да
if (e.parent === undefined) { //является ли объект вложенным?
//Родитель - нет
e.children = arrayStorage[e.id]
newStorage.push(e)
} else {
//Родитель - да
arrayStorage[e.parent].forEach((el:any) => {
if (el.id === e.id) {
el.children = arrayStorage[e.id]
}
})
}
}
})
console.log("Я нашёл вложенности")
console.log(newStorage)
// console.log("строю с нуля на основании этого массива")
// console.log(stockroom)
//
// //Мы разворачиваем стартовый массив и вкладываем элементы в начало результирующего массива.
// let reverseStockroom: any
// let arrayStorage: any = {}
// let newStorage: any = []
//
// //Создаём хранилище со всеми вложенностями. Ключи - id родителя
// stockroom.reverse().forEach((e: any, i: number) => {
// if (e.parent !== undefined) {
// if (arrayStorage[e.parent] === undefined) {
// arrayStorage[e.parent] = []
// }
// arrayStorage[e.parent].unshift(e)
// }
// })
//
// //Если есть какие-то вложенности
// if (Object.keys(arrayStorage).length !== 0) {
// //Теперь у нас есть массив со всеми вложенностями.
//
// //Будем проходиться по хранилищу задом наперёд, ибо не имеем пометок где заканчивается хранилище, но знаем где оно начинается
// reverseStockroom = stockroom.reverse();
//
// //Важно помнить, что мы проходимся по массиву линейно и совпадение id текущего элемента и id в arrayStorage может быть единожды.
// //Это значит, что найдя id в arrayStorage мы можем что-либо сделать с этим массивом и больше уже больше никогда его не тронем.
// //Возможны 4 состояния объекта:
// //родитель_дети
// //нет_______нет - просто вложить в результирующий массив
// //нет________да - вложить в результирующий массив с полем children
// //да________нет - этот объект уже был использован в массиве arrayStorage. Оставить в покое
// //да_________да - этот объект уже был использован в массиве arrayStorage. В его поле children нужно вложить массив его детей
// // в массиве arrayStorage вложить в поле children родителя массив с детьми и ждать, пока очередь дойдёт до родителя
//
// reverseStockroom.forEach((e: any, i: number) => {
// if (arrayStorage[e.id] === undefined) {
// //Объект не содержит потомков. Дети - нет
// if (e.parent === undefined) {
// //Родитель - нет
// newStorage.push(e)
// } //else Родитель - да
// } else {
// //Объект содержит потомков. Дети - да
// if (e.parent === undefined) { //является ли объект вложенным?
// //Родитель - нет
// e.children = arrayStorage[e.id]
// newStorage.push(e)
// } else {
// //Родитель - да
// arrayStorage[e.parent].forEach((el:any) => {
// if (el.id === e.id) {
// el.children = arrayStorage[e.id]
// }
// })
// }
// }
// })
// console.log("Я нашёл вложенности")
// console.log(newStorage)
function isContains (e:any) {
return(
e.map((element:any) => {
e.map((element:any, i:number) => {
console.log(element)
if (element.children === undefined) {
if (element.children === undefined || element.children.length === 0) {
console.log("элемент без потомков")
return(
<Types
element={element} keyInfo={element.id} changeFocus={changeFocus} key={element.id}
element={element} keyInfo={element.id} setNewFocus={setNewFocus} key={i} shiftKeyInfo={shiftKeyInfo} focused={focused} focus={focus}
/>
)
} else {
console.log("элемент с потомками")
return(
<div key={element.id} style={{border:"solid black 1px", padding: "10px"}}>
<div key={i} style={{border: element.id == focus? focused.border : "solid black 1px", padding: "10px"}}
onClick={(event:any) => {
shiftKeyInfo(event, element.id)
}}
>
{isContains(element.children)}
</div>
)
@ -92,18 +107,7 @@ export default ({stockroom, changeFocus} : any) => {
)
}
return isContains(newStorage)
} else {
//Если вложенностей нет
console.log("Вложенностей нет")
return(stockroom.map((e: any, i: number) => {
return (
<Types
element={e} keyInfo={e.id} changeFocus={changeFocus} key={e.id}
/>
)
}))
}
return isContains(stockroom)
} else {
return <></>
}

@ -3,7 +3,6 @@ import ReactDOM from 'react-dom/client';
import {BrowserRouter, Routes, Route } from "react-router-dom";
import { ChakraProvider } from '@chakra-ui/react';
import { SnackbarProvider } from 'notistack';
import Kit from "./kit";
import CreateScope from "./create/createScope";
import CreateQuestion from "./create/createQuestion";
@ -14,17 +13,17 @@ const root = ReactDOM.createRoot(
root.render(
// <React.StrictMode>
<ChakraProvider>
<SnackbarProvider maxSnack={3}>
<BrowserRouter>
<Routes>
<Route path="/">
<Route element={<CreateScope/>} path="/createScope"/>
</Route>
<Route element={<CreateQuestion/>} path="kit"/>
</Routes>
</BrowserRouter>
</SnackbarProvider>
</ChakraProvider>
<ChakraProvider>
<SnackbarProvider maxSnack={3}>
<BrowserRouter>
<Routes>
<Route path="/">
<Route element={<CreateScope/>} path="/createScope"/>
</Route>
<Route element={<CreateQuestion/>} path="kit"/>
</Routes>
</BrowserRouter>
</SnackbarProvider>
</ChakraProvider>
// </React.StrictMode>
);