Files
supabase/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideListItems.tsx
Devanshu Sharma 36a4a774f7 refactor(docs): enhance the docs sidebar UI (#38869)
* refactor(docs): enhance NavigationMenuGuideListItems component

* cleanup..

* Resolve formatting conflicts in NavigationMenuGuideListItems

* Came up with a crazy recursive approach...

* some changes.

* More cleanups...

* more cleanups....

* formatting the stuff

* refactor(navigation): remove sample menu data and optimize icon rendering in RecursiveNavigation

* cleanup...

* feat: enhance navigation with recursive dropdown indicators and performance optimizations

- Add visual chevron indicators for expandable sidebar items
- Implement recursive navigation system using existing NavMenuSection types
- Auto-expand accordion sections containing current active page on load/refresh
- Extract LinkContainer as independent component to prevent recreation on renders
- Fix React 19 compatibility issues with ref handling using useCallback pattern
- Resolve duplicate key warnings with improved key generation strategy
- Optimize accordion transition timing (500ms duration with ease-in-out) to prevent element overlap
- Preserve existing icon logic with hasLightIcon support for theme variants
- Maintain backward compatibility with existing navigation data structures

Performance improvements:
- Memoized recursive components to prevent unnecessary re-renders
- Stable component references for better React reconciliation
- Proper TypeScript interfaces with explicit prop definitions

UX improvements:
- Smooth accordion animations with physics-based easing
- Clear visual indicators for expandable menu items
- Automatic expansion of sections containing current page
- Professional-grade transition animations

Technical details:
- Uses existing NavMenuSection recursive type structure
- Implements containsActivePath helper for active page detection
- Leverages Radix UI accordion with proper data-state attributes
- Maintains all existing functionality including dynamic menu injection

* Cleanup...

* feat: implement cookie-based persisted state for navigation accordion

- Replace localStorage with cookie-based persistence for SSR compatibility
- Add proper cookie helpers with SameSite=Lax and 30-day expiration
- Implement initialization state to prevent hydration mismatches
- Maintain auto-expand functionality for active page sections
- Preserve user's manual accordion state across page refreshes and sessions
- Add debounced cookie updates (300ms) for performance optimization
- Use proper cookie naming convention: 'supabase-docs-nav-state'

Benefits:
- SSR compatible: Works with server-side rendering
- Cross-session persistence: Maintains state across browser sessions
- Better security: Cookies are more secure than localStorage
- Performance: Debounced updates prevent excessive cookie writes
- User experience: Seamless navigation state preservation

* refactor: implement individual item-based persistence following reference pattern

- Replace global state management with individual item persistence
- Use sessionStorage with 'nav-expansion-' prefix for each item
- Follow the exact pattern from reference: usePersistedExpansionState hook
- Maintain auto-expansion for active page sections
- Simplify state management by removing complex global state
- Each accordion item manages its own expansion state independently
- Preserve user's manual toggle state across page refreshes
- Use sessionStorage instead of cookies for better performance

Benefits:
- Cleaner architecture: Each item manages its own state
- Better performance: No global state updates
- Simpler logic: Direct item-to-storage mapping
- Reference pattern compliance: Follows established patterns
- Individual control: Each section can be toggled independently
- Session persistence: Maintains state during browser session

* refactor: implement URL-driven navigation state following Supabase docs pattern

- Replace sessionStorage persistence with URL-driven expansion state
- Follow the established Supabase docs pattern: URL as single source of truth
- Remove individual item persistence hooks in favor of pathname-based logic
- Implement useUrlDrivenExpansion hook that determines open sections from current URL
- Use getSectionsContainingPath to find all sections that should be expanded
- Remove manual toggle functionality - sections open/close based on URL navigation
- Maintain smooth transitions and visual indicators for expandable sections
- Ensure consistency and reliability by using URL as the definitive state source

Benefits:
- Reliability: URL is always the single source of truth
- Consistency: Matches existing Supabase docs navigation behavior
- Simplicity: No complex state management or storage concerns
- Performance: No localStorage/sessionStorage operations
- SSR Compatible: Works perfectly with server-side rendering
- Predictable: Navigation state is always consistent with current page

* persistant state.

* file delete

* cleanup..

* file cleanup

* cleanup...

* cleanup..

* formatting..

* aww shit that it.

---------

Co-authored-by: Alan Daniel <stylesshjs@gmail.com>
2025-10-16 10:04:07 -04:00

230 lines
7.3 KiB
TypeScript

import * as Accordion from '@radix-ui/react-accordion'
import { usePathname } from 'next/navigation'
import { useTheme } from 'next-themes'
import { ChevronDown } from 'lucide-react'
import Image from 'next/legacy/image'
import Link from 'next/link'
import React, { useEffect, useRef } from 'react'
import MenuIconPicker from './MenuIconPicker'
const HeaderLink = React.memo(function HeaderLink(props: {
title: string
id: string
url: string
}) {
const pathname = usePathname()
return (
<span
className={[
' ',
!props.title && 'capitalize',
props.url === pathname ? 'text-brand-link' : 'hover:text-brand-link text-foreground',
].join(' ')}
>
{props.title ?? props.id}
</span>
)
})
const ContentAccordionLink = React.memo(function ContentAccordionLink(props: any) {
const pathname = usePathname()
const { resolvedTheme } = useTheme()
const activeItem = props.subItem.url === pathname
const activeItemRef = useRef<HTMLLIElement>(null)
const isChildActive =
props.subItem.items && props.subItem.items.some((child: any) => child.url === pathname)
const LinkContainer = (props) => {
const isExternal = props.url.startsWith('https://')
return (
<Link
href={props.url}
className={props.className}
target={isExternal ? '_blank' : undefined}
rel={isExternal ? 'noopener noreferrer' : undefined}
>
{props.children}
</Link>
)
}
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 && (
<>
<div className="h-px w-full bg-border my-3"></div>
<span className="font-mono text-xs uppercase text-foreground font-medium tracking-wider">
{props.parent.name}
</span>
</>
)}
{props.subItem.items && props.subItem.items.length > 0 ? (
<Accordion.Root
collapsible
type="single"
className="space-y-0.5"
defaultValue={isChildActive ? props.subItem.url : undefined}
>
<Accordion.Item key={props.subItem.url || props.subItem.name} value={props.subItem.url}>
<Accordion.Trigger
className={[
'flex items-center gap-2 w-full',
'cursor-pointer transition text-sm',
activeItem
? 'text-brand-link font-medium'
: 'hover:text-foreground text-foreground-lighter',
].join(' ')}
>
<span className="flex items-center justify-between w-full">
<div className="flex items-center gap-2">
{props.subItem.icon && (
<Image
alt={props.subItem.name}
src={`${props.subItem.icon}${!resolvedTheme?.includes('dark') ? '-light' : ''}.svg`}
width={15}
height={15}
/>
)}
{props.subItem.name}
</div>
<ChevronDown className="w-4 h-4 transition-transform data-open-parent:rotate-180" />
</span>
</Accordion.Trigger>
<Accordion.Content className="transition data-open:animate-slide-down data-closed:animate-slide-up ml-2">
{props.subItem.items
.filter((subItem) => subItem.enabled !== false)
.map((subSubItem) => {
return (
<li key={`${props.subItem.name}-${subSubItem.url}`}>
<Link
href={`${subSubItem.url}`}
className={[
'cursor-pointer transition text-sm',
subSubItem.url === pathname
? 'text-brand-link'
: 'hover:text-brand-link text-foreground-lighter',
].join(' ')}
>
{subSubItem.name}
</Link>
</li>
)
})}
</Accordion.Content>
</Accordion.Item>
</Accordion.Root>
) : (
<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',
activeItem
? 'text-brand-link font-medium'
: 'hover:text-foreground text-foreground-lighter',
].join(' ')}
parent={props.subItem.parent}
>
<div className="flex items-center gap-2">
{props.subItem.icon && (
<Image
alt={props.subItem.name}
src={`${props.subItem.icon}${!resolvedTheme?.includes('dark') ? '-light' : ''}.svg`}
width={15}
height={15}
/>
)}
{props.subItem.name}
</div>
</LinkContainer>
</li>
)}
</>
)
})
const ContentLink = React.memo(function ContentLink(props: any) {
const pathname = usePathname()
return (
<li className="mb-1.5">
<Link
href={props.url}
className={[
'cursor-pointer transition text-sm',
props.url === pathname
? 'text-brand-link'
: 'hover:text-foreground text-foreground-lighter',
].join(' ')}
>
{props.icon && (
<Image alt={props.icon} width={12} height={12} src={`${pathname}${props.icon}`} />
)}
{props.name}
</Link>
</li>
)
})
const Content = (props) => {
const { menu, id } = props
if (menu.enabled === false) {
return null
}
return (
<ul className={['relative w-full flex flex-col gap-0 pb-5'].join(' ')}>
<Link href={menu.url ?? ''}>
<div className="flex items-center gap-3 my-3 text-brand-link">
<MenuIconPicker icon={menu.icon} />
<HeaderLink title={menu.title} url={menu.url} id={id} />
</div>
</Link>
{menu.items
.filter((item) => item.enabled !== false)
.map((x) => {
return (
<div key={x.name}>
{x.items && x.items.length > 0 ? (
<div className="flex flex-col gap-2.5">
{x.items
.filter((item) => item.enabled !== false)
.map((subItem, subItemIndex) => {
return (
<ContentAccordionLink
key={subItem.name}
subItem={subItem}
subItemIndex={subItemIndex}
parent={x}
/>
)
})}
</div>
) : x.url ? (
<ContentLink url={x.url} icon={x.icon} name={x.name} key={x.name} />
) : null}
</div>
)
})}
</ul>
)
}
export default React.memo(Content)