Explorar o código

Scroll the settings menu to the page that is open (#651)

* Scroll the settings menu to the page that is open

* Look again when the settings menu appears after the window widens
Bernt Christian Egeland hai 1 semana
pai
achega
f298033bd3

+ 75 - 0
src/__tests__/app/settings/settings-nav-current-page.test.tsx

@@ -0,0 +1,75 @@
+import { render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { SettingsNav } from '@/app/(authenticated)/settings/settings-nav'
+
+let pathname = '/settings/about'
+vi.mock('next/navigation', () => ({
+  usePathname: () => pathname,
+  useRouter: () => ({ push: vi.fn() }),
+}))
+
+/**
+ * The settings menu is longer than the window. Landing on a page far down it,
+ * from a link or the search, has to bring that page's row into view.
+ */
+describe('the settings menu and the page that is open', () => {
+  const scrolled: string[] = []
+  const original = Element.prototype.scrollIntoView
+  beforeEach(() => {
+    scrolled.length = 0
+    Element.prototype.scrollIntoView = function (this: Element) {
+      scrolled.push(this.getAttribute('href') ?? '')
+    }
+  })
+  afterEach(() => {
+    Element.prototype.scrollIntoView = original
+    vi.unstubAllGlobals()
+  })
+
+  it('brings the open page into view and marks it as the current one', () => {
+    pathname = '/settings/about'
+    render(<SettingsNav isCloud supportEnabled />)
+
+    expect(scrolled).toEqual(['/settings/about'])
+    expect(screen.getByRole('link', { name: /About/ })).toHaveAttribute('aria-current', 'page')
+  })
+
+  it('follows when another page opens', () => {
+    pathname = '/settings/about'
+    const { rerender } = render(<SettingsNav isCloud supportEnabled />)
+    pathname = '/settings/company'
+    rerender(<SettingsNav isCloud supportEnabled />)
+
+    expect(scrolled).toEqual(['/settings/about', '/settings/company'])
+  })
+
+  it('looks again when the list appears after the window widens', () => {
+    let resized: () => void = () => undefined
+    vi.stubGlobal(
+      'ResizeObserver',
+      class {
+        constructor(callback: () => void) {
+          resized = callback
+        }
+        observe() {
+          // nothing to watch in a test
+        }
+        disconnect() {
+          // nothing to release in a test
+        }
+      }
+    )
+    pathname = '/settings/about'
+    render(<SettingsNav isCloud supportEnabled />)
+    scrolled.length = 0
+    const nav = screen.getByRole('navigation')
+
+    // Hidden so far (no height); nothing to do while it stays hidden.
+    resized()
+    expect(scrolled).toEqual([])
+
+    Object.defineProperty(nav, 'offsetHeight', { configurable: true, value: 600 })
+    resized()
+    expect(scrolled).toEqual(['/settings/about'])
+  })
+})

+ 28 - 2
src/app/(authenticated)/settings/settings-nav.tsx

@@ -1,6 +1,6 @@
 'use client'
 
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import Link from 'next/link'
 import { usePathname, useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
@@ -203,6 +203,31 @@ export function SettingsNav({
 
   const pages = visibleSettingsPages({ isCloud, supportEnabled })
 
+  // The list is longer than the window: after a link or the search lands on a
+  // page further down, bring that page's row into view so the person can see
+  // where they are. "nearest" moves nothing when the row is already visible.
+  const navRef = useRef<HTMLElement>(null)
+  const showCurrent = useCallback(() => {
+    navRef.current
+      ?.querySelector<HTMLElement>('[aria-current="page"]')
+      ?.scrollIntoView?.({ block: 'nearest' })
+  }, [])
+  useEffect(showCurrent, [pathname, showCurrent])
+  // On a narrow window this list is hidden and cannot scroll; when the window
+  // widens and it appears, the page has not changed, so look again then.
+  useEffect(() => {
+    const nav = navRef.current
+    if (!nav || typeof ResizeObserver === 'undefined') return
+    let shown = nav.offsetHeight > 0
+    const observer = new ResizeObserver(() => {
+      const now = nav.offsetHeight > 0
+      if (now && !shown) showCurrent()
+      shown = now
+    })
+    observer.observe(nav)
+    return () => observer.disconnect()
+  }, [showCurrent])
+
   const newPill = (item: SettingsPage) =>
     newItems.includes(item.href) ? (
       <span className="shrink-0 rounded bg-primary/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-primary">
@@ -236,7 +261,7 @@ export function SettingsNav({
   }
 
   return (
-    <nav className="flex flex-col gap-4">
+    <nav ref={navRef} className="flex flex-col gap-4">
       <SettingsSearch features={features} isCloud={isCloud} supportEnabled={supportEnabled} />
       {SETTINGS_CATEGORIES.map((category) => {
         const visibleItems = pages.filter((p) => p.category === category)
@@ -255,6 +280,7 @@ export function SettingsNav({
                   <Link
                     key={item.href}
                     href={item.href}
+                    aria-current={isActive ? 'page' : undefined}
                     className={cn(
                       'flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors',
                       isActive