Adjust menu item spacing and highlighting, scroll to active menu item on page load

This commit is contained in:
Terry Sutton
2023-05-04 23:06:42 -02:30
parent ed5b19418d
commit 29fe25026e
3 changed files with 84 additions and 44 deletions

View File

@@ -2,7 +2,7 @@ import { useTheme } from 'common/Providers'
import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from 'next/router'
import React from 'react'
import React, { useEffect, useRef } from 'react'
import { IconChevronLeft } from '~/../../packages/ui'
import * as Accordion from '@radix-ui/react-accordion'
@@ -43,6 +43,8 @@ const HeaderLink = React.memo(function HeaderLink(props: {
const ContentAccordionLink = React.memo(function ContentAccordionLink(props: any) {
const router = useRouter()
const { isDarkMode } = useTheme()
const activeItem = props.subItem.url === router.pathname
const activeItemRef = useRef(null)
const LinkContainer = (props) => {
return (
@@ -52,6 +54,15 @@ const ContentAccordionLink = React.memo(function ContentAccordionLink(props: any
)
}
useEffect(() => {
// scroll to active item
if (activeItem && activeItemRef.current) {
// this is a hack, but seems a common one on Stackoverflow
setTimeout(() => {
activeItemRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}, 0)
}
})
return (
<>
{props.subItemIndex === 0 && (
@@ -63,15 +74,15 @@ const ContentAccordionLink = React.memo(function ContentAccordionLink(props: any
</>
)}
<Accordion.Item key={props.subItem.label} value={props.subItem.url}>
<li key={props.subItem.name}>
<li key={props.subItem.name} ref={activeItem ? activeItemRef : null}>
<LinkContainer
url={props.subItem.url}
className={[
'flex items-center gap-2',
'cursor-pointer transition text-sm',
props.subItem.url === router.pathname
? 'text-brand-900'
: 'hover:text-brand-900 text-scale-1000',
activeItem
? 'text-brand-900 font-medium'
: 'hover:text-scale-1200 dark:hover:text-scale-1100 text-scale-1000',
].join(' ')}
parent={props.subItem.parent}
>
@@ -120,14 +131,14 @@ const ContentLink = React.memo(function ContentLink(props: any) {
const router = useRouter()
return (
<li>
<li className="mb-1.5">
<Link href={`${props.url}`} passHref>
<a
className={[
'cursor-pointer transition text-sm',
props.url === router.pathname
? 'text-brand-900'
: 'hover:text-brand-900 text-scale-1000',
: 'hover:text-scale-1200 dark:hover:text-scale-1100 text-scale-1000',
].join(' ')}
>
{props.icon && (
@@ -179,15 +190,17 @@ const Content = (props) => {
return (
<div key={x.name}>
{x.items && x.items.length > 0 ? (
<div className="flex flex-col gap-1">
<div className="flex flex-col gap-2.5">
{x.items.map((subItem, subItemIndex) => {
return (
<ContentAccordionLink
key={subItem.name}
subItem={subItem}
subItemIndex={subItemIndex}
parent={x}
/>
<>
<ContentAccordionLink
key={subItem.name}
subItem={subItem}
subItemIndex={subItemIndex}
parent={x}
/>
</>
)
})}
</div>