Skip to content

Commit

Permalink
fix(@clayui/treeview) - Fix ClayTreeView broken when using filtered i…
Browse files Browse the repository at this point in the history
…tems
  • Loading branch information
ilzamcmed committed Nov 6, 2023
1 parent 90cfd6d commit 478980f
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion packages/clay-core/src/tree-view/useMultipleSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/

import {useControlledState} from '@clayui/shared';
import {Key, useCallback, useMemo, useRef} from 'react';
import {Key, useCallback, useEffect, useMemo, useRef} from 'react';

import {getKey} from '../collection';
import {ITreeProps, createImmutableTree} from './useTree';
Expand Down Expand Up @@ -139,6 +139,10 @@ export function useMultipleSelection<T extends Record<string, any>>(
key
) as LayoutInfo;

if (!keyMap) {
return false;
}

const children = [...keyMap.children];

const unselected = children.some(
Expand All @@ -165,6 +169,43 @@ export function useMultipleSelection<T extends Record<string, any>>(
}
}, [selectedKeys]);

/**
* This `useEffect` makes `useMemo` been called every time the items change and
* this can cause some performance issues. We cannot change the `useMemo` because
* it's needed in other treeview cases. This needs improvements in the future.
*/

useEffect(() => {
if (props.selectionMode === 'multiple-recursive' && !isUncontrolled) {
const newSelectedKeys = new Set(selectedKeys);

props.layoutKeys.current.forEach((keyMap, key) => {
if (!keyMap) {
return false;
}

const children = [...keyMap.children];

if (!children.length) {
return;
}

if (children.every((key) => selectedKeys.has(key))) {
newSelectedKeys.add(key);
indeterminateKeys.current.delete(key);
} else if (children.some((key) => selectedKeys.has(key))) {
newSelectedKeys.delete(key);
indeterminateKeys.current.add(key);
} else {
newSelectedKeys.delete(key);
indeterminateKeys.current.delete(key);
}
});

setSelectionKeys(newSelectedKeys);
}
}, [props.items]);

const toggleParentSelection = useCallback(
(
hasIndeterminate: boolean,
Expand Down

0 comments on commit 478980f

Please sign in to comment.