import _ from 'lodash'; import type { CheckInfo } from 'rc-tree/lib/Tree'; import type { Key } from 'react'; import { useEffect, useState } from 'react'; import type { CheckedType } from '.'; import { getDeepKey } from '../utils'; export const useOptionLevel = ({ treeData, key = 'id' }: { treeData: any; key?: string }) => { const extractIds = getDeepKey(key); const [expandedKeys, setExpandedKeys] = useState([]); const [defaultExpandAll, setDefaultExpandAll] = useState(true); const onExpand = (val) => { setExpandedKeys(val); }; useEffect(() => { if (defaultExpandAll) { setExpandedKeys(extractIds(treeData)?.map((item) => `${item}`)); } else { setExpandedKeys([]); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [treeData, setExpandedKeys, defaultExpandAll]); return { expandedKeys, setDefaultExpandAll, onExpand, defaultExpandAll }; }; export const useRelation = (params?: { key?: string; id?: string }) => { const { key = 'key', id = 'id' } = params || {}; const [checkStrictly, setCheckStrictly] = useState(false); const extractKeys = getDeepKey(key); const getRemain = (checked: CheckedType, info: CheckInfo, disabledIds?: string[]): Key[] => { const keys = Array.isArray(checked) ? checked : checked.checked; // 如果是关联状态 if (checkStrictly) { // 首先要算出e.node.children的所有id const childrenIds = extractKeys(info?.node?.children || [])?.filter( (item: any) => !disabledIds?.includes?.(item) && !disabledIds?.includes?.(`${item}`), ); // 拿出所有的父节点 const parentList: any = []; let itemNode = info?.node; while (itemNode?.parentNode) { itemNode = itemNode?.parentNode; if ( itemNode?.id && !disabledIds?.includes?.(itemNode?.id) && !disabledIds?.includes?.(`${itemNode?.id}`) ) { parentList.push(itemNode); } } // 如果是勾选状态 if (info.checked) { const parentIds = _.reduce( parentList, (arr: string[], node) => { if (node) { const parentChildrenIds = node?.children?.map((item: any) => `${item?.[id]}`); // 判断父节点的子节点ID是否都在里面,都在就需要把父节点的id也要放到选中里面。 const isFullSelect = _.difference(parentChildrenIds, [...keys, ...arr])?.length === 0; if (isFullSelect) { return [...arr, `${node?.[id]}`]; } } return arr; }, [], ); // 需要把e.node.children的所有id都加进去 return [...parentIds, ...keys, ...childrenIds]; } // 如果是非勾选状态 const parentIds = parentList?.map((item: any) => `${item?.[id]}`); // 需要把e.node.children的所有id都去掉 return _.difference(keys, [...childrenIds, ...parentIds]); } // 如果处于非管理状态,就直接保存就好 return keys; }; return { checkStrictly, setCheckStrictly, getRemain }; };