Skip to content

Commit

Permalink
refactor: simplify sub menu rendering by passing sub items as children
Browse files Browse the repository at this point in the history
  • Loading branch information
isqua committed Oct 23, 2023
1 parent 6e436d3 commit 4f1de4b
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/components/Menu/Section/Section.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useState, type PropsWithChildren } from 'react'
import { type MenuItem, type PageId, type SectionHighlight } from '../../../features/toc'
import { useIsLoading, useMenuItems } from '../Context/hooks'
import { Item } from '../Item/Item'
Expand All @@ -9,11 +9,10 @@ type SectionProps = {
highlight?: SectionHighlight
}

type SubMenuProps = {
type ItemToggleProps = PropsWithChildren<{
item: MenuItem
level: number
isLoading: boolean
}
}>

export function Section({ parentId, level, highlight }: SectionProps): JSX.Element {
const isLoading = useIsLoading()
Expand All @@ -26,16 +25,19 @@ export function Section({ parentId, level, highlight }: SectionProps): JSX.Eleme
return (<Item isLoading={isLoading} key={item.id} item={item} />)
}

const subMenuHighlight = item.highlight === 'active' ? 'child' : item.highlight

return (
<SubMenu isLoading={isLoading} key={item.id} item={item} level={level + 1} />
<ItemToggle isLoading={isLoading} key={item.id} item={item}>
<Section highlight={subMenuHighlight} parentId={item.id} level={level + 1} />
</ItemToggle>
)
})}
</>
)
}

function SubMenu({ item, level, isLoading }: SubMenuProps): JSX.Element {
const subMenuHighlight = item.highlight === 'active' ? 'child' : item.highlight
function ItemToggle({ item, children, isLoading }: ItemToggleProps): JSX.Element {
const [ isOpen, setOpen ] = useState(isLoading ? true : item.defaultOpenState)

const onToggle = () => {
Expand All @@ -51,9 +53,7 @@ function SubMenu({ item, level, isLoading }: SubMenuProps): JSX.Element {
open={isOpen}
onToggle={onToggle}
/>
{isOpen && (
<Section highlight={subMenuHighlight} parentId={item.id} level={level} />
)}
{isOpen && children}
</>
)
}

0 comments on commit 4f1de4b

Please sign in to comment.