import React, { useEffect, useState } from 'react';
import Box from '@mui/material/Box';
import Popper from '@mui/material/Popper';
import ClickAwayListener from '@mui/material/ClickAwayListener';
import TextField from '@mui/material/TextField';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import InputAdornment from '@mui/material/InputAdornment';
import Chip from '@mui/material/Chip';
import IconButton from '@mui/material/IconButton';
import { SimpleTreeView, TreeItem } from '@mui/x-tree-view';
import ClearIcon from '@mui/icons-material/Clear';
import KeyboardArrowDown from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUp from '@mui/icons-material/KeyboardArrowUp';
import './MultiLevelCheckboxTree.scss';
import { MaterialTooltip } from '@/components/common/MaterialTooltip';
interface TreeNode {
project_code: string;
name: string;
values?: TreeNode[];
showNode?: boolean;
}
interface MultiLevelCheckboxTreeProps {
treeData: TreeNode[];
onSelectionChange: (selectedIds: string[]) => void;
initialCheckedItems?: string[];
}
const MultiLevelCheckboxTree: React.FC = ({
treeData,
onSelectionChange,
initialCheckedItems,
}) => {
const [checked, setChecked] = useState<string[]>(initialCheckedItems || []);
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState('');
const [tree, setTree] = useState<TreeNode[]>(treeData);
useEffect(() => {
setTree(treeData);
}, [treeData]);
const collectIds = (node: TreeNode): string[] => {
const childIds = node.values ? node.values.flatMap(collectIds) : [];
return [node.project_code, ...childIds];
};
const updateParentCheckStatus = (node: TreeNode, checkedList: string[]) => {
console.log('SEARCH PARENT');
// Получаем id всех дочерних узлов
const childIds = node.values ? node.values.flatMap(collectIds) : [];
const allChildrenChecked = childIds.every((id) => checkedList.includes(id));
// Создаем новую версию checkedList
let newCheckedList = [...checkedList];
// Добавляем узел в newCheckedList, если все дочерние выбраны
if (allChildrenChecked && !newCheckedList.includes(node.project_code)) {
newCheckedList.push(node.project_code);
}
// Убираем узел из newCheckedList, если не все дочерние выбраны
else if (!allChildrenChecked && newCheckedList.includes(node.project_code)) {
newCheckedList = newCheckedList.filter((id) => id !== node.project_code);
}
// Обновляем состояние с новым массивом
setChecked(newCheckedList);
onSelectionChange(newCheckedList);
// Обрабатываем родительский узел
const parentNode = findParentNode(tree, node.project_code);
if (parentNode) {
updateParentCheckStatus(parentNode, newCheckedList);
}
console.log(parentNode);
};
const findParentNode = (nodes: TreeNode[], childCode: string): TreeNode | undefined => {
for (const node of nodes) {
if (node.values && node.values.some((child) => child.project_code === childCode)) {
return node;
}
if (node.values) {
const foundParent = findParentNode(node.values, childCode);
if (foundParent) return foundParent;
}
}
return undefined;
};
const handleToggle = (node: TreeNode) => (event: React.MouseEvent) => {
event.stopPropagation();
const nodeIds = collectIds(node);
const isSelected = nodeIds.every((id) => checked.includes(id));
let newChecked = [...checked];
if (isSelected) {
newChecked = newChecked.filter((id) => !nodeIds.includes(id));
} else {
newChecked = [...new Set([...newChecked, ...nodeIds])];
}
setChecked(newChecked);
onSelectionChange(newChecked);
updateParentCheckStatus(node, newChecked);
};
const renderTree = (node: TreeNode) => {
if (inputValue && !node.showNode) return null;
const nodeIds = collectIds(node);
const isChecked = nodeIds.every((id) => checked.includes(id));
return (
<TreeItem
key={node.project_code}
itemId={node.project_code}
label={
<FormControlLabel
control={
<Checkbox
checked={isChecked}
tabIndex={-1}
disableRipple
onClick={handleToggle(node)}
sx={{ color: 'white' }}
/>
}
label={node.name}
sx={{
color: 'white',
'& .MuiFormControlLabel-label': {
fontFamily: 'Oswald, sans-serif',
fontSize: '16px',
},
}}
/>
}
>
{Array.isArray(node.values) ? node.values.map(renderTree) : null}
);
};
const handleClick = (event: React.MouseEvent) => {
setOpen(!open);
setAnchorEl(anchorEl ? null : event.currentTarget);
};
const handleClickAway = () => {
setOpen(false);
setAnchorEl(null);
};
const getNodeNameById = (project_code: string): string => {
const findNode = (nodes: TreeNode[]): TreeNode | undefined => {
for (const node of nodes) {
if (node.project_code === project_code) return node;
if (node.values) {
const found = findNode(node.values);
if (found) return found;
}
}
return undefined;
};
const node = findNode(tree);
return node ? node.name : '';
};
const searchNodes = (nodes: TreeNode[], query: string) => {
if (!query.length) return nodes;
const newItems: TreeNode[] = structuredClone(nodes);
newItems.forEach((node) => {
const shouldAddNode = node.name.toLowerCase().includes(query.toLowerCase());
if (shouldAddNode) {
node.showNode = true;
} else {
if (node.values && node.values.length) {
const newChildren = searchNodes(node.values, query);
if (newChildren.some((item) => item.showNode)) {
node.showNode = true;
}
node.values = structuredClone(newChildren);
}
}
});
return newItems;
};
const findNodeById = (nodes: TreeNode[], id: string): TreeNode | undefined => {
for (const node of nodes) {
if (node.project_code === id) return node;
if (node.values) {
const found = findNodeById(node.values, id);
if (found) return found;
}
}
return undefined;
};
const handleDeleteChip = (id: string) => () => {
const node = findNodeById(tree, id);
if (node) {
const nodeIds = collectIds(node);
const newChecked = checked.filter((checkedId) => !nodeIds.includes(checkedId));
setChecked(newChecked);
onSelectionChange(newChecked);
}
};
const handleClearAll = (event: React.MouseEvent) => {
event.stopPropagation();
setChecked([]);
onSelectionChange([]);
};
const handleInputChange = (event: React.ChangeEvent) => {
const value = event.target.value;
setInputValue(value);
setTree(() => {
const foundItems = searchNodes(treeData, value);
return [...foundItems];
});
};
const getChips = () => {
const chips: string[] = [];
const addChips = (nodes: TreeNode[]) => {
nodes.forEach((node) => {
const nodeIds = collectIds(node);
const isSelected = nodeIds.every((id) => checked.includes(id));
if (isSelected) {
chips.push(node.project_code);
} else {
if (node.values) {
addChips(node.values);
}
}
});
};
addChips(tree);
return chips;
};
return (
<Box
sx={{
width: 300,
position: 'relative',
maxHeight: '100px',
height: 'fit-content',
borderRadius: '8px',
border: '1px solid #546780',
backgroundColor: '#3a4d67',
}}
>
<TextField
className="multilevel__input"
placeholder={checked.length === 0 ? 'Выберите проекты' : ''}
value={inputValue}
onClick={handleClick}
onChange={handleInputChange}
multiline
InputProps={{
sx: {
minHeight: '40px',
height: 'fit-content',
maxHeight: '100px',
padding: 0,
},
startAdornment: (
<InputAdornment
position="start"
className="start-adornment"
sx={{ marginRight: 0 }}
>
<Box
sx={{
display: 'flex',
flexWrap: 'wrap',
rowGap: '15px',
height: 'fit-content',
maxHeight: '100px',
overflowY: 'auto',
maxWidth: '225px',
paddingTop: '10px',
paddingLeft: '5px',
marginBottom: '5px',
}}
>
{getChips().map((id, index) => (
<Chip
key={id}
label={getNodeNameById(id)}
onDelete={handleDeleteChip(id)}
deleteIcon={<ClearIcon style={{ color: 'white' }} />}
variant="outlined"
sx={{
marginRight: 4,
color: 'white',
width: '180px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
'&:hover': {
cursor: 'pointer',
},
'& .MuiChip-label': {
fontFamily: 'Oswald, sans-serif',
fontSize: '14px',
},
}}
/>
))}
),
endAdornment: (
<InputAdornment
position="end"
style={{
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
}}
>
{checked.length > 0 && (
<IconButton size="small" onClick={handleClearAll} style={{ color: 'white' }}>
)}
{open ? (
<KeyboardArrowUp style={{ color: 'white', marginRight: 7 }} />
) : (
<KeyboardArrowDown style={{ color: 'white', marginRight: 7 }} />
)}
),
}}
sx={{
overflow: 'hidden',
height: 'fit-content',
maxHeight: '100px',
width: '100%',
}}
/>
{/TODO перепроверить все z-index по всему проекту!/}
<Popper
sx={{
width: '100%',
maxWidth: 300,
maxHeight: '300px',
overflowY: 'auto',
zIndex: 99,
}}
open={open}
anchorEl={anchorEl}
placement="bottom-start"
>
<Box
sx={{
maxWidth: 300,
padding: 1,
height: 'fit-content',
backgroundColor: '#2d3b53',
border: '1px solid rgba(255, 255, 255, 0.3)',
borderRadius: '8px',
}}
>
<SimpleTreeView sx={{ color: 'white' }}>
{tree.map((node) => renderTree(node))}
);
};
export default MultiLevelCheckboxTree;
Вот весь код, посмотри