import { Tree } from 'antd';
import { useState } from 'react';
let findResult;
const treeList = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [
{
title: 'leaf',
key: '0-0-0-0',
disableCheckbox: true,
},
{
title: 'leaf',
key: '0-0-0-1',
},
],
},
{
title: 'parent 1-1',
key: '0-0-1',
children: [{ title: <span style={{ color: '#1890ff' }}>sss</span>, key: '0-0-1-0' }],
},
],
},
];
const findItem = (data, node, parentItem) => {
data.find((item) => {
if (item?.key === node?.key) {
if (parentItem) {
item.parent = parentItem;
return (findResult = item);
} else return (findResult = item);
} else if (item?.children?.length) {
return (findResult = findItem(item.children, node, item));
}
});
return findResult;
},
dealDrap = (dragNode, node, treeData, dropPosition) => {
let dragNodeResult, nodeResult;
findResult = '';
dragNodeResult = findItem(treeData, dragNode);
findResult = '';
nodeResult = findItem(treeData, node);
if (dropPosition === 0) {
if (dragNodeResult?.parent?.key === nodeResult?.key) return true;
return false;
}
if (dropPosition === 1 || dropPosition === -1) {
if (dragNodeResult?.parent && nodeResult?.parent) {
if (dragNodeResult?.parent?.key == nodeResult?.parent?.key) {
return true;
} else {
return false;
}
}
if (dragNodeResult?.parent && !nodeResult?.parent) {
return false;
}
if (!dragNodeResult?.parent && nodeResult?.parent) {
return false;
}
if (!dragNodeResult?.parent && !nodeResult?.parent) {
return true;
}
}
};
const TreeTuo = ({ canRandom }) => {
const [treeData, setTreeData] = useState(treeList),
onDrop = info => {
const dropKey = info.node.key;
const dragKey = info.dragNode.key;
const dropPos = info.node.pos.split('-');
const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
if (!canRandom) {
const dealData = JSON.parse(JSON.stringify(treeData));
const result = dealDrap(info.dragNode, info.node, [...dealData], dropPosition);
if (!result) return;
}
const loop = (data, key, callback) => {
for (let i = 0; i < data.length; i++) {
if (data[i].key === key) {
return callback(data[i], i, data);
}
if (data[i].children) {
loop(data[i].children, key, callback);
}
}
};
const data = [...treeData];
let dragObj;
loop(data, dragKey, (item, index, arr) => {
arr.splice(index, 1);
dragObj = item;
});
if (!info.dropToGap) {
loop(data, dropKey, item => {
item.children = item.children || [];
item.children.unshift(dragObj);
});
} else if (
(info.node.props.children || []).length > 0 &&
info.node.props.expanded &&
dropPosition === 1
) {
loop(data, dropKey, item => {
item.children = item.children || [];
item.children.unshift(dragObj);
});
} else {
let ar;
let i;
loop(data, dropKey, (item, index, arr) => {
ar = arr;
i = index;
});
if (dropPosition === -1) {
ar.splice(i, 0, dragObj);
} else {
ar.splice(i + 1, 0, dragObj);
}
}
setTreeData(data);
};
return <Tree draggable blockNode onDrop={onDrop} treeData={treeData} />;
};
export default TreeTuo;