Skip to content

Commit 86cf480

Browse files
committed
perf: optimize tree node searching with flattened data
1 parent 37d7cfc commit 86cf480

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

src/OptionList.tsx

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -157,14 +157,15 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
157157
}
158158
}, [searchValue]);
159159

160-
// ========================== Get First Selectable Node ==========================
161-
const getFirstMatchingNode = (
162-
nodes: EventDataNode<any>[],
163-
searchVal?: string,
164-
): EventDataNode<any> | null => {
165-
const flattenedNodes = flattenTreeData(nodes, mergedExpandedKeys, fieldNames);
160+
// ========================== Flatten Tree Data ==========================
161+
const flattenedTreeData = React.useMemo(() => {
162+
const expandKeys = searchValue ? true : mergedExpandedKeys;
163+
return flattenTreeData(memoTreeData, expandKeys, fieldNames);
164+
}, [memoTreeData, searchValue, mergedExpandedKeys]);
166165

167-
const matchedNode = flattenedNodes.find(node => {
166+
// ========================== Get First Selectable Node ==========================
167+
const getFirstMatchingNode = (searchVal?: string): EventDataNode<any> | null => {
168+
const matchedNode = flattenedTreeData.find(node => {
168169
const rawNode = node.data as EventDataNode<any>;
169170
if (rawNode.disabled || rawNode.selectable === false) {
170171
return false;
@@ -189,7 +190,7 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
189190

190191
// Prioritize activating the searched node
191192
if (searchValue) {
192-
const firstNode = getFirstMatchingNode(memoTreeData, searchValue);
193+
const firstNode = getFirstMatchingNode(searchValue);
193194
setActiveKey(firstNode ? firstNode[fieldNames.value] : null);
194195
return;
195196
}
@@ -201,7 +202,7 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
201202
}
202203

203204
// If no search value and no checked nodes, activate the first node
204-
const firstNode = getFirstMatchingNode(memoTreeData, '');
205+
const firstNode = getFirstMatchingNode();
205206
setActiveKey(firstNode ? firstNode[fieldNames.value] : null);
206207
}, [open, searchValue]);
207208

0 commit comments

Comments
 (0)