компонент createQuestion наделён комментариями. Умеет добавлять и удалять компоненты. WorkSpace правильно рендерит пустые контейнеры

This commit is contained in:
krokodilka 2022-08-11 08:34:03 +03:00
parent 06378eaa59
commit 50e4add1db
3 changed files with 210 additions and 100 deletions

@ -16,7 +16,6 @@ interface Values {
description: string; description: string;
} }
const types = [ const types = [
{desc:"текст", value:"text"}, {desc:"текст", value:"text"},
{desc:"селект", value:"select"}, {desc:"селект", value:"select"},
@ -40,6 +39,10 @@ export const TextField = (props: any) => {
); );
}; };
//Для первого ознакомления рекомендую свернуть все функции и почитать их названия и описания
//Заранее берётся поле children нужного родителя. Функция сама отделит все id от родительской части
//Вернёт число для текущего слоя вложенности (в случае чего надо будет ручками присоединить к строке родителя)
const getFreeNumber = (array:Array<ElementsOfObject>):number => { const getFreeNumber = (array:Array<ElementsOfObject>):number => {
// Для первого элемента в списке // Для первого элемента в списке
if (array.length === 0) { if (array.length === 0) {
@ -51,7 +54,13 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
let indexes:any = [] let indexes:any = []
//И берём только последние числа от строк, превращая их в числа //И берём только последние числа от строк, превращая их в числа
for (let i = 0; i < array.length; i++) { for (let i = 0; i < array.length; i++) {
indexes.push(Number(array[i].id.slice(-1))) //Строка состоит из чисел, разделённых пробелом.
//Делим строку на массив чисел
let stringArr = array[i].id.split(" ")
//Берём последний элемент массива
stringArr = stringArr.slice(-1)
indexes.push(Number(stringArr[0]))
} }
//Сортируем в порядке возрастания //Сортируем в порядке возрастания
indexes.sort(function compare(a:any, b:any):any { indexes.sort(function compare(a:any, b:any):any {
@ -83,6 +92,8 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
} }
} }
} }
//Прохождение по полю children в поисках нужного id
const getIndexById = (id:string, array:Array<ElementsOfObject>):number => { const getIndexById = (id:string, array:Array<ElementsOfObject>):number => {
let index let index
for (let i = 0; i <= array.length; i++) { for (let i = 0; i <= array.length; i++) {
@ -101,54 +112,91 @@ const getIndexById = (id:string, array:Array<ElementsOfObject>):number => {
} }
} }
//Извлечение информации из id для поиска пути к ребёнку.
const getObjectFromId = (id:string, array:any):any => { const getObjectFromId = (id:string, array:any):any => {
let indexes = id.split("") //Делим строку на массив чисел
//буфер содержит id всех родителей (от ребёнка до первого родителя) let IDs = id.split(" ")
let bufer = []
for (let i = 0; i < indexes.length; i++) { // o o o o o <--
let val = (id.length - i) // \ / \ / | Проходимся по каждому слою. Значит номер итерации укажет на количество элементов,
bufer.push(id.substring(0, val)) // o o o <-- кторые нужно добавить к строке currentIteration для получения id родителя на этом уровне вложенности.
} // \ / / (наверное, проще её создавать с нуля, зная сколько нужно будет элементов)
let parentObj = array // o <--
for (let i = 0; i < indexes.length - 1; i++) {
let id = bufer[bufer.length - i - 1] const getNewIdString = (index:number) => {
parentObj = parentObj[getIndexById(id, parentObj)].children let id = ""
} for (let i = 0; i < index ;i++) {
if (parentObj.length > 1) { id = id + " " + IDs[i]
parentObj = parentObj[Number(id.slice(-1))] }
} return id.slice(1) //убираем пробел в начале
if (Array.isArray(parentObj)) {
return parentObj[0]
} else {
return parentObj
} }
//Счётчик вложенности
let nestingCounter = 0
//В пересчётах в каждом слое вложенности сюда сохраняется найденный объект
let bufferObject
//Считаем до какого уровня вложенности нам вообще искать ребёнка
let stopIndex = IDs.length
const searchId = (array:any) => {
if (nestingCounter === stopIndex) {
//Мы достигли нужного уровня вложенности
return
} else {
nestingCounter = nestingCounter + 1
//Создаём строку id текущей вложенности, танцуя от знания порядкового номера этой вложенности
let calcId = getNewIdString(nestingCounter)
return (
//Здесь можно в заранее созданную переменную оповещать нашли ли мы нужный id. И обработать ошибку если нет
array.forEach((element:any) => {
if (element.id === calcId) {
//Записываем найденный объект и ищем на следующем уровне
bufferObject = element
searchId(element.children)
}
})
)
}
}
searchId(array)
return bufferObject
//Есть два варианта поиска:
//Рекурсивно пройтись по хранилищу тупо ожидая наткнуться на нужного ребёнка
//Проходиться по каждому слою вложенности, создавая id текущего слоя. Находить объект и повторять
//Навскидку второй вариант для ветвистых деревьев быстрее и позволит показать на каком уровне вложенности потанцевально может оборваться поиск...
//при (не дай боже) неверной записи фокусного id
} }
export default () => { export default () => {
//Id - строится на основании всех id родителя + свободное число от 0 до +бесконечности.
// const [stockroom, setStockroom] = React.useState<Array<ElementsOfObject>>([ //Разделение айдишников в строке посредством пробела
const [stockroom, setStockroom] = React.useState<any>([ const [stockroom, setStockroom] = React.useState<any>([
{id: "0", type: 7, children: [ {id: "0", type: 7, children: [
{ {
id: "00", type: 7, children: [ id: "0 0", type: 7, children: [
{id: "000", children: [], type: 4} // {id: "0 0 0", children: [], type: 4}
] ]
}, },
{ {
id: "01", type: 7, children: [ id: "0 1", type: 7, children: [
{ {
id: "010", children: [ id: "0 1 0", children: [
{id: "0100", children: [], type: 4}, {id: "0 1 0 0", children: [], type: 4},
{id: "0101", children: [], type: 4} {id: "0 1 0 1", children: [], type: 4}
], type: 7 ], type: 7
} }
] ]
}, },
{id: "02", type: 4, children: []} {id: "0 2", type: 4, children: []}
]} ]}
]) ])
const [focus, setFocus] = React.useState<string | undefined>("101") //Хранит путь объекта const [focus, setFocus] = React.useState<string | undefined>() //Хранит путь объекта (id)
// const [focus, setFocus] = React.useState<string | undefined>("1 0 1") //Хранит путь объекта
const setNewFocus = (value:string, multiFocus:boolean) => { const setNewFocus = (value:string, multiFocus:boolean) => {
//Фокусы ставятся или удаляются от клика по уже созданным элементам. //Фокусы ставятся или удаляются от клика по уже созданным элементам.
@ -160,103 +208,159 @@ export default () => {
setFocus(value) setFocus(value)
} }
} }
// Изменение типа очищает все поля
const createNewTree = (value:any, tree = stockroom) => {
return (
tree.map((node: any) => {
if (node.id === focus) { //Функция пересоздаёт дерево с проверкой каждого объекта.
let obj = { // Если объект в фокусе - создаётся новый объект и в него высыпаются старые поля, затем новые поля
...node, const createNewTreeFields = (value:any, tree = stockroom) => {
...value, return (
tree.map((node: any) => {
if (node.id === focus) {
let obj = {
...node,
...value,
}
return (obj)
} else if (node.children.length !== 0) {
return {
...node,
children: createNewTreeFields(value, node.children)
}
} else {
return node
} }
return (obj) })
} else if (node.children.length !== 0) { )
return { }
...node, //Создание дерева с обновлённым объектом
children: createNewTree(value, node.children) const createNewTreeObject = (value:any, tree = stockroom) => {
return (
tree.map((node: any) => {
if (node.id === value.id) {
return value
} else if (node.children.length !== 0) {
return {
...node,
children: createNewTreeObject(value, node.children)
}
} else {
return node
} }
} else { })
return node )
} }
})
)} // Изменение типа очищает все поля
const typeHC = (type:any): void => { const typeHC = (type:any): void => {
if (focus !== undefined) { if (focus !== undefined) {
setStockroom(createNewTree({type:type})) setStockroom(createNewTreeFields({type:type}))
} }
} }
const colorHC = (color:any) => { const colorHC = (color:any) => {
if (focus !== undefined) { if (focus !== undefined) {
setStockroom(createNewTree({color:color})) setStockroom(createNewTreeFields({color:color}))
} }
} }
const createObject = (obj:any, type:number = 4) => { const createObject = (obj:any, type:number = 4) => {
if (focus !== undefined) { if (focus !== undefined) {
//Созданный объект добавляется после объекта с фокусом
//Если фокусный элемент - контейнер, добавление происходит внутрь него //Если фокусный элемент - контейнер, добавление происходит внутрь него
// //Если фокусный элемент - не контейнер, добавление происходит после объекта с фокусом
const focusedObj = getObjectFromId(focus, stockroom) const focusedObj = getObjectFromId(focus, stockroom)
const creacteChildrens = (arr = stockroom) => {
return arr.map((node: any) => {
if (node.children.length !== 0) {
//Объект с детьми должен быть добавлен + должен произойти вызов для поля children
return (
{ ...node, children: creacteChildrens(node.children) }
)
} else {
//Объект без детей просто добавляется
return node
}
})
}
//Находим родителя
const parentObj = getObjectFromId(focus.slice(0,-1), stockroom)
//Находим свободный ид
let newId:any = getFreeNumber(parentObj.children)
newId = focus.slice(0,-1) + newId
//Создаём новый объект
const newObj = {
id: newId,
type: type,
children: []
}
if (focusedObj.type === 7) { if (focusedObj.type === 7) {
//Кладём внутрь фокусного объекта //Кладём внутрь фокусного объекта
console.log(focusedObj) //Находим свободный ид и прикрепляем его к родительскому id
let newId:any = getFreeNumber(focusedObj.children)
newId = focusedObj.id + " " + newId
//Создаём новый объект
const newObj = {
id: newId,
type: type,
children: []
}
focusedObj.children = [...focusedObj.children, newObj] focusedObj.children.push(newObj)
console.log(focusedObj) //Создаём дерево с обновлённым родителем
setStockroom(createNewTree(focusedObj)) const newTree = createNewTreeObject(focusedObj)
setStockroom(newTree)
} else { } else {
//Кладём рядом с фокусным объектом //Кладём рядом с фокусным объектом
//Создаём новый массив для поля children родителя и присваиваем его //Находим родителя
let newCildrenArr = [] //Отфигачиваем последний id
let parentId:any = focus.split(" ")
parentId.pop()
parentId = parentId.join(' ')
const parentObj = getObjectFromId(parentId, stockroom)
//Находим свободный ид и прикрепляем его к родительскому 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++) { for (let i = 0; parentObj.children.length > i ; i++) {
let node = parentObj.children[i] let node = parentObj.children[i]
if (node.id === focus) { if (node.id === focus) {
newCildrenArr.push(node) newChildrenArr.push(node)
newCildrenArr.push(newObj) newChildrenArr.push(newObj)
} else { } else {
newCildrenArr.push(node) newChildrenArr.push(node)
} }
} }
parentObj.children = newCildrenArr parentObj.children = newChildrenArr
//Создаём дерево с обновлённым родителем //Создаём дерево с обновлённым родителем
const newTree = creacteChildrens() const newTree = createNewTreeObject(parentObj)
setStockroom(newTree) setStockroom(newTree)
} }
} }
} }
const deleteObject = () => {
if (focus !== undefined) {
//Если просто запретить вкладывать объект при создании дерева - будет массив со значением undefined
//Поэтому скажем родителю, что его массив опустел
const focusedObj = getObjectFromId(focus, stockroom)
//Отфигачиваем последний id
let parentId:any = 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)
}
}
parentObj.children = newChildrenArr
let newTree = createNewTreeObject(parentObj)
console.log(stockroom)
console.log(newTree)
setStockroom(newTree)
}
}
// const changeFocus = (id: number): void => { // const changeFocus = (id: number): void => {
// //Не менять фокус если снова выбрано то же окно // //Не менять фокус если снова выбрано то же окно
// if (focus !== id) { // if (focus !== id) {
@ -407,7 +511,7 @@ export default () => {
changeText={stockroom} changeText={stockroom}
getIndexById={getIndexById} getIndexById={getIndexById}
createObject={createObject} createObject={createObject}
deleteObject={stockroom} deleteObject={deleteObject}
/> />
<Button onClick={() => { <Button onClick={() => {
console.log(stockroom) console.log(stockroom)

@ -52,6 +52,11 @@ export default (props: any) => {
}} }}
>добавить</Button> >добавить</Button>
<Button
onClick={() => {
props.deleteObject()
}}
>удалить фокусный</Button>
{/*<Button*/} {/*<Button*/}
{/* onClick={() => {*/} {/* onClick={() => {*/}
{/* props.createObject({text: "контейнер", isFocus: true, type: 7, id: -1, parent: undefined})*/} {/* props.createObject({text: "контейнер", isFocus: true, type: 7, id: -1, parent: undefined})*/}

@ -21,22 +21,23 @@ export default ({stockroom, setNewFocus, focus} : any) => {
return( return(
e.map((element:any, i:number) => { e.map((element:any, i:number) => {
if (element.children === undefined || element.children.length === 0) { // if (element.children.length === 0) {
if (element.type === 7) {
return( return(
<Types <div key={element.id} style={{border: element.id == focus? focused.border : "solid black 1px", padding: "10px"}}
element={element} keyInfo={element.id} setNewFocus={setNewFocus} key={i} shiftKeyInfo={shiftKeyInfo} focused={focused} focus={focus} onClick={(event:any) => {
/> shiftKeyInfo(event, element.id)
) }}
} else {
return(
<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)} {isContains(element.children)}
</div> </div>
) )
} else {
return(
<Types
element={element} keyInfo={element.id} setNewFocus={setNewFocus} key={element.id} shiftKeyInfo={shiftKeyInfo} focused={focused} focus={focus}
/>
)
} }
}) })
) )