Skip to content

Commit 913a78b

Browse files
authored
fix: refactor child validation logic in useValidateChildren for improved clarity (#23)
1 parent 5b1c6d6 commit 913a78b

File tree

1 file changed

+23
-30
lines changed

1 file changed

+23
-30
lines changed

lib/hooks/useValidateChildren.ts

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -24,43 +24,36 @@ export const useValidateChildren = ({ items, children }: UseValidateChildrenProp
2424
const navKeys = new Set<string>();
2525
const contentKeys = new Set<string>();
2626

27-
const isNav = (child: ReactNode) => isValidElement(child) && child.type === DualScrollSyncNav;
27+
const collectNavKeys = (node: ReactNode) => {
28+
if (isValidElement<DualScrollSyncNavItemProps>(node) && node.props.sectionKey) {
29+
navKeys.add(node.props.sectionKey);
30+
}
31+
};
2832

29-
const isContent = (child: ReactNode) =>
30-
isValidElement(child) && child.type === DualScrollSyncContent;
33+
const collectContentKeys = (node: ReactNode) => {
34+
if (isValidElement<DualScrollSyncContentSectionProps>(node) && node.props.sectionKey) {
35+
contentKeys.add(node.props.sectionKey);
36+
}
37+
};
3138

3239
const visit = (node: ReactNode) => {
3340
Children.forEach(node, (child) => {
3441
if (!isValidElement(child)) return;
3542

36-
if (child.type === Fragment) {
37-
visit((child.props as PropsWithChildren).children);
38-
return;
39-
}
40-
41-
if (isNav(child)) {
42-
Children.forEach((child.props as PropsWithChildren).children, (navItem) => {
43-
if (isValidElement<DualScrollSyncNavItemProps>(navItem) && navItem.props.sectionKey) {
44-
navKeys.add(navItem.props.sectionKey);
43+
switch (child.type) {
44+
case Fragment:
45+
visit((child.props as PropsWithChildren).children);
46+
break;
47+
case DualScrollSyncNav:
48+
Children.forEach((child.props as PropsWithChildren).children, collectNavKeys);
49+
break;
50+
case DualScrollSyncContent:
51+
Children.forEach((child.props as PropsWithChildren).children, collectContentKeys);
52+
break;
53+
default:
54+
if ((child.props as PropsWithChildren)?.children) {
55+
visit((child.props as PropsWithChildren).children);
4556
}
46-
});
47-
return;
48-
}
49-
50-
if (isContent(child)) {
51-
Children.forEach((child.props as PropsWithChildren).children, (section) => {
52-
if (
53-
isValidElement<DualScrollSyncContentSectionProps>(section) &&
54-
section.props.sectionKey
55-
) {
56-
contentKeys.add(section.props.sectionKey);
57-
}
58-
});
59-
return;
60-
}
61-
62-
if ((child.props as PropsWithChildren)?.children) {
63-
visit((child.props as PropsWithChildren).children);
6457
}
6558
});
6659
};

0 commit comments

Comments
 (0)