create element

This commit is contained in:
krokodilka 2022-08-10 14:45:40 +03:00
parent 7b65426dab
commit 06378eaa59
6 changed files with 110 additions and 303 deletions

@ -53,8 +53,6 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
for (let i = 0; i < array.length; i++) {
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;}
@ -62,11 +60,7 @@ 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 = []
@ -82,7 +76,6 @@ const getFreeNumber = (array:Array<ElementsOfObject>):number => {
// difference - массив нехватающих в списке номеров.
// Если все окна у нас по порядку, без пропусков - нужно добавить новый номер
if (difference.length === 0) {
console.log("+1")
return(max + 1)
} else {
//Иначе добавить нехватающий
@ -92,11 +85,8 @@ const getFreeNumber = (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
@ -119,7 +109,6 @@ const getObjectFromId = (id:string, array:any):any => {
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]
@ -140,18 +129,24 @@ export default () => {
// 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:[]}
{id: "0", type: 7, children: [
{
id: "00", type: 7, children: [
{id: "000", children: [], type: 4}
]
},
{
id: "01", type: 7, children: [
{
id: "010", children: [
{id: "0100", children: [], type: 4},
{id: "0101", children: [], type: 4}
], type: 7
}
]
},
{id: "02", type: 4, children: []}
]}
])
const [focus, setFocus] = React.useState<string | undefined>("101") //Хранит путь объекта
@ -166,20 +161,15 @@ export default () => {
}
}
// Изменение типа очищает все поля
const createNewTree = (value:any, tree = stockroom, ignoreFocus = false) => {
console.log("focus")
console.log(focus)
const createNewTree = (value:any, tree = stockroom) => {
return (
tree.map((node: any) => {
console.log(node.id)
if (node.id === focus && !ignoreFocus) {
console.log(node)
if (node.id === focus) {
let obj = {
...node,
...value,
}
console.log(obj)
return (obj)
} else if (node.children.length !== 0) {
return {
@ -205,42 +195,53 @@ export default () => {
const createObject = (obj:any, type:number = 4) => {
if (focus !== undefined) {
//Созданный объект добавляется после объекта с фокусом
//Если фокусный элемент - контейнер, добавление происходит внутрь него
//
const focusedObj = getObjectFromId(focus, stockroom)
const creacteNew = (arr = stockroom) => {
const creacteChildrens = (arr = stockroom) => {
return arr.map((node: any) => {
if (node.children.length !== 0) {
console.log(node)
return {
...node,
children: creacteNew(node.children)
}
//Объект с детьми должен быть добавлен + должен произойти вызов для поля children
return (
{ ...node, children: creacteChildrens(node.children) }
)
} else {
console.log("просто возвращаю")
console.log(node)
//Объект без детей просто добавляется
return node
}
})
}
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: []
}
//Находим родителя
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) {
//Кладём внутрь фокусного объекта
console.log(focusedObj)
focusedObj.children = [...focusedObj.children, newObj]
console.log(focusedObj)
setStockroom(createNewTree(focusedObj))
} else {
//Кладём рядом с фокусным объектом
//Создаём новый массив для поля 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)
@ -250,37 +251,9 @@ export default () => {
}
parentObj.children = newCildrenArr
const newTree = creacteNew()
console.log(newTree)
setFocus(newId+"")
//Создаём дерево с обновлённым родителем
const newTree = creacteChildrens()
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)
}
}
}
@ -436,9 +409,9 @@ export default () => {
createObject={createObject}
deleteObject={stockroom}
/>
{/*<Button onClick={() => {*/}
{/* typeHC(5)*/}
{/*}}>info</Button>*/}
<Button onClick={() => {
console.log(stockroom)
}}>info</Button>
</VStack>
</HStack>
</>

@ -1,74 +0,0 @@
import React from 'react';
import SunEditor from 'suneditor-react';
import { useField, Formik, Form, Field } from 'formik';
import {Box} from "@chakra-ui/react";
// @ts-ignore
export default ({name}) => {
const visual = React.useRef<HTMLDivElement | null>(null);
const [field, meta, helpers] = useField(name);
const [focus, setFocus] = React.useState(false)
React.useEffect(() => {
if (!focus) {
if (visual.current !== null) {
visual.current.innerHTML = meta.value
}
}
},[focus])
return(
<>
{
focus ?
<Field
as={SunEditor}
name="description"
onChange={(e:any)=> {
helpers.setValue(e, false)
console.log(e)
}}
// imageUploadHandler={(e:any)=>console.log(e)}
// onImageUpload={(e:any)=>console.log(e)}
// showController={(e:any)=>console.log(e)}
// hideToolbar={false}
defaultValue={meta.value}
onBlur={(e:any) => {
setTimeout(() => setFocus(false), 1000);
}}
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',
]
]
}}
/>
:
<Box
onClick={() => setFocus(true)}
border="solid 1px #d2d2d2"
padding="10px"
width="80%"
ref={visual}
tabIndex={0}
_focus={{
border:"solid 1px red"
}}
>
</Box>
}
</>
)
}

@ -1,7 +1,8 @@
import React from 'react';
import {Box, Button, Checkbox, Container, Select, Textarea} from "@chakra-ui/react";
import UserElements from "./userElements"
import SunEditor from "suneditor-react";
import {ChromePicker} from "react-color";
import Viewer from "./viewer";
export default (props: any) => {
@ -31,17 +32,53 @@ export default (props: any) => {
))
}
</Select>
<UserElements
stockroom={props.stockroom}
focus={props.focus}
changeFocus={props.changeFocus}
changeBgColor={props.changeBgColor}
changeText={props.changeText}
createObject={props.createObject}
deleteObject={props.deleteObject}
getIndexById={props.getIndexById}
current={current}
<ChromePicker
disableAlpha
color={
props.current === undefined ?
""
:
props.focus === undefined ?
""
:
props.current.color
}
onChange={e => {props.changeBgColor(e.hex)}}
/>
<Button
onClick={() => {
props.createObject({text: "", color: "", isFocus: true, type: 0, id: -1, parent: undefined})
}}
>добавить</Button>
{/*<Button*/}
{/* onClick={() => {*/}
{/* props.createObject({text: "контейнер", isFocus: true, type: 7, id: -1, parent: undefined})*/}
{/* }}*/}
{/*>контейнер</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>*/}
{/*}*/}
{/*<Button type="submit">Создать вопрос</Button>*/}
{/*{current === undefined ?*/}
{/* null*/}

@ -1,9 +1,9 @@
import React from 'react';
import {
Select, Checkbox, Button, Box
Select, Checkbox, Button, Box, VStack, HStack, Textarea
} from '@chakra-ui/react'
import {TextField} from "./createQuestion";
import Description from "./description"
import type {QuestionProps} from "./questionTypes"
export default ({focused, element, stockroom = [], changeFocus, keyInfo, shiftKeyInfo, focus} : any) => {

@ -1,64 +0,0 @@
import React from 'react';
import { Button, VStack, HStack, Textarea} from "@chakra-ui/react";
import {ChromePicker} from "react-color";
import Viewer from "./viewer";
import { useSnackbar } from 'notistack';
import type {ElementsOfObject, QuestionProps} from "./questionTypes"
export default (props: any) => {
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
return(
<>
<ChromePicker
disableAlpha
color={
props.current === undefined ?
""
:
props.focus === undefined ?
""
:
props.current.color
}
onChange={e => {props.changeBgColor(e.hex)}}
/>
<Button
onClick={() => {
props.createObject({text: "", color: "", isFocus: true, type: 0, id: -1, parent: undefined})
}}
>добавить</Button>
{/*<Button*/}
{/* onClick={() => {*/}
{/* props.createObject({text: "контейнер", isFocus: true, type: 7, id: -1, parent: undefined})*/}
{/* }}*/}
{/*>контейнер</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>*/}
{/*}*/}
</>
)
}

@ -7,8 +7,6 @@ const focused = {
export default ({stockroom, setNewFocus, focus} : any) => {
if (stockroom.length !== 0) {
// фокусы - массив со значениями (для мультифокуса)
// focus.split(" ")
const shiftKeyInfo = (event:any, id:any) => {
event.stopPropagation()
@ -19,80 +17,17 @@ export default ({stockroom, setNewFocus, focus} : any) => {
}
}
// 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, i:number) => {
console.log(element)
if (element.children === undefined || element.children.length === 0) {
console.log("элемент без потомков")
return(
<Types
element={element} keyInfo={element.id} setNewFocus={setNewFocus} key={i} shiftKeyInfo={shiftKeyInfo} focused={focused} focus={focus}
/>
)
} else {
console.log("элемент с потомками")
return(
<div key={i} style={{border: element.id == focus? focused.border : "solid black 1px", padding: "10px"}}
onClick={(event:any) => {