|
| 1 | +import { |
| 2 | + ReactNode, |
| 3 | + useState, |
| 4 | +} from 'react'; |
| 5 | +import { |
| 6 | + IoChevronDownOutline, |
| 7 | + IoChevronUpOutline, |
| 8 | +} from 'react-icons/io5'; |
| 9 | +import { NavLink } from 'react-router'; |
| 10 | +import { Button } from '@ifrc-go/ui'; |
| 11 | +import { _cs } from '@togglecorp/fujs'; |
| 12 | + |
| 13 | +import styles from './styles.module.css'; |
| 14 | + |
| 15 | +export interface NavigationItem { |
| 16 | + title: string; |
| 17 | + to?: string; |
| 18 | + icon?: ReactNode; |
| 19 | + variant: 'root' | 'group' | 'leaf'; |
| 20 | + children?: NavigationItem[]; |
| 21 | + |
| 22 | +} |
| 23 | +function Navigation({ navigationItem }: { navigationItem: NavigationItem[] }) { |
| 24 | + const [openIndexes, setOpenIndexes] = useState( |
| 25 | + navigationItem.map((_, i) => i), |
| 26 | + ); |
| 27 | + |
| 28 | + const toggleAccordion = (index: number) => { |
| 29 | + setOpenIndexes((prev) => (prev.includes(index) |
| 30 | + ? prev.filter((i) => i !== index) |
| 31 | + : [...prev, index])); |
| 32 | + }; |
| 33 | + |
| 34 | + return ( |
| 35 | + <nav className={styles.nav}> |
| 36 | + {navigationItem.map((item, index) => { |
| 37 | + const isOpen = openIndexes.includes(index); |
| 38 | + return ( |
| 39 | + <div |
| 40 | + key={item.title} |
| 41 | + className={_cs( |
| 42 | + styles[item.variant ?? 'leaf'], |
| 43 | + )} |
| 44 | + > |
| 45 | + <Button |
| 46 | + name={item.title} |
| 47 | + type="button" |
| 48 | + className={styles.navHeaderContainer} |
| 49 | + childrenContainerClassName={styles.navHeader} |
| 50 | + onClick={() => toggleAccordion(index)} |
| 51 | + variant="tertiary" |
| 52 | + icons={item.icon} |
| 53 | + > |
| 54 | + {item.title} |
| 55 | + {isOpen ? <IoChevronUpOutline /> : <IoChevronDownOutline />} |
| 56 | + </Button> |
| 57 | + {isOpen && ( |
| 58 | + <div |
| 59 | + className={_cs( |
| 60 | + styles.navContent, |
| 61 | + styles[item.variant ?? 'leaf'], |
| 62 | + )} |
| 63 | + > |
| 64 | + {item.children && item.children.map((child) => { |
| 65 | + if (!child.to && child.children) { |
| 66 | + return ( |
| 67 | + <Navigation |
| 68 | + key={child.title} |
| 69 | + navigationItem={[child]} |
| 70 | + /> |
| 71 | + ); |
| 72 | + } |
| 73 | + return ( |
| 74 | + <NavLink |
| 75 | + key={child.to} |
| 76 | + to={child.to ?? ''} |
| 77 | + className={({ isActive }) => _cs( |
| 78 | + styles.routeLink, |
| 79 | + isActive && styles.activeRoute, |
| 80 | + styles[child.variant ?? 'leaf'], |
| 81 | + |
| 82 | + )} |
| 83 | + > |
| 84 | + {child.title} |
| 85 | + </NavLink> |
| 86 | + ); |
| 87 | + })} |
| 88 | + |
| 89 | + </div> |
| 90 | + )} |
| 91 | + </div> |
| 92 | + ); |
| 93 | + })} |
| 94 | + </nav> |
| 95 | + ); |
| 96 | +} |
| 97 | + |
| 98 | +export default Navigation; |
0 commit comments