Files
novalon-website/src/components/layout/header.tsx
T
zhangxiang e9bd965411 fix(nav): 「查看全部」不再靠中文标签反推路由,目的地改由导航项自身 href 提供
原实现(mega-dropdown.tsx:168):
  href={`/${label === '产品' ? 'products' : label === '解决方案' ? 'solutions' : 'services'}`}
第三个及以后任何标签都**静默落到 /services**。

为什么必须在 IA 改名之前修:改名前这个缺陷表现为一个刺眼的不合理跳转,很容易被发现;
改名后 /services 这条路由依然存在(本轮刻意不做任何 rename),于是它退化成一个
「看起来完全合理的错误目的地」—— 那类最难查的 bug。

- props 新增 viewAllHref;缺失时**整块不渲染**该链接(宁可少一个入口,不给错目的地)
- header.tsx 把 item.href 传下去(非下拉分支 :145 本来就用同一个值,两分支现已同源)
- 顺带把两处裸时长收进令牌:duration-200 → duration-hover、framer transition 补 ease-ink

单测(mega-dropdown.test.tsx,5 条新用例)已实测能失败:
修复前 4 failed / 5 passed,其中「产品→/products」那条通过正是
「防修一个坏一个」的基准 —— 它证明旧实现在前两个标签上确实是对的。

e2e(nav-keyboard.spec.ts,2 条 @a11y)是**浏览器层**负对照:单测只能证明组件契约,
「header 有没有真的把 href 接上」只有真实渲染看得见。
已实测该用例能失败:摘除 viewAllHref 传递 ⇒ 立刻判红「下拉「产品」没有渲染「查看全部」链接」,
恢复 ⇒ 2 passed。另含两条不变量:分母必须等于已登记的下拉数(新增导航项忘登记即判红,
不会"少测一个"悄悄放行)、各下拉目的地必须互不相同(原缺陷的表现形式正是多个标签塌到同一个
/services)。

首跑踩到本文件 :21-29 已记录的 dev/Fast Refresh hydration 竞态 —— click() 打在
hydration 后被整体替换的旧节点上、aria-expanded 恒 false。按仓库既有配方改为
把**交互本身**放进 toPass 重发,而非只重读断言。

门禁:type-check EXIT=0 · eslint --quiet 0 error · jest src/components/layout 全过 ·
e2e nav-keyboard@chromium 2 passed
2026-10-16 20:14:19 +08:00

284 lines
11 KiB
TypeScript

'use client';
import { useState, useEffect, useCallback } from 'react';
import { StaticLink } from '@/components/ui/static-link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { Menu, X, MessageCircle } from 'lucide-react';
import { AnimatePresence, motion } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { useSiteConfig, type NavigationItem } from '@/lib/site-config';
import { MegaDropdown } from '@/components/layout/mega-dropdown';
import { useFocusTrap } from '@/hooks/use-focus-trap';
import { cn } from '@/lib/utils';
import { ThemeToggle } from '@/components/theme/theme-toggle';
function HeaderContent() {
const [isOpen, setIsOpen] = useState(false);
const [isScrolled, setIsScrolled] = useState(false);
const [openDropdown, setOpenDropdown] = useState<string | null>(null);
const pathname = usePathname();
const focusTrapRef = useFocusTrap<HTMLDivElement>(isOpen, {
onEscape: () => setIsOpen(false),
});
useEffect(() => {
const handleScroll = () => {
setIsScrolled(window.scrollY > 20);
};
const handleGlobalKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen) {
setIsOpen(false);
}
};
window.addEventListener('scroll', handleScroll, { passive: true });
window.addEventListener('keydown', handleGlobalKeyDown);
return () => {
window.removeEventListener('scroll', handleScroll);
window.removeEventListener('keydown', handleGlobalKeyDown);
};
}, [isOpen]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
// Escape 关闭菜单;Enter/Space 已由原生 button 的 onClick 处理,
// 此处不再拦截,避免键盘操作时重复触发 toggle。
if (e.key === 'Escape' && isOpen) {
e.preventDefault();
setIsOpen(false);
}
}, [isOpen]);
const config = useSiteConfig();
const handleNavClick = useCallback(() => {
// StaticLink 新契约:onClick 先于导航执行,不调 preventDefault 即由
// next/link 完成客户端跳转,此处只负责关闭抽屉。
setIsOpen(false);
}, []);
const isActive = useCallback((item: NavigationItem) => {
if (item.id === 'contact') {
return pathname === '/contact';
}
if (item.id === 'home') {
return pathname === '/';
}
if (item.id === 'products') {
return pathname === '/products' || pathname.startsWith('/products/');
}
if (item.id === 'solutions') {
return pathname === '/solutions' || pathname.startsWith('/solutions/');
}
if (item.id === 'cases') {
return pathname === '/cases' || pathname.startsWith('/cases/');
}
if (item.id === 'services') {
return pathname === '/services' || pathname.startsWith('/services/');
}
return pathname === `/${item.id}`;
}, [pathname]);
return (
<>
<motion.header
initial={false}
animate={{
height: isScrolled ? 64 : 80,
}}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="fixed top-0 left-0 right-0 z-50 transition-colors duration-normal bg-bg-primary border-b border-border-primary"
>
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10">
<div className="flex items-center justify-between h-16 md:h-full">
<StaticLink
href="/"
className="relative flex items-center group/logo"
aria-label="返回首页"
>
{/* Logo 明暗双版:浅色背景用 logo.svg(黑字),深色背景用 logo-white.svg(白字)。
按 html[data-theme] 显隐(规则见 globals.css),修复黑字在深色背景被吞的 bug。 */}
<Image
src="/logo.svg"
alt={config.name}
width={106}
height={40}
className="logo-on-light relative transition-all duration-normal ease-out group-hover/logo:scale-[1.02] w-auto h-8 md:h-10"
loading="eager"
priority
suppressHydrationWarning
/>
<Image
src="/logo-white.svg"
alt={config.name}
width={106}
height={40}
className="logo-on-dark relative transition-all duration-normal ease-out group-hover/logo:scale-[1.02] w-auto h-8 md:h-10"
loading="eager"
suppressHydrationWarning
/>
</StaticLink>
<nav className="hidden md:flex items-center gap-0.5" role="navigation" aria-label="主导航" data-testid="desktop-navigation">
{config.mainNav.map((item) => (
item.hasDropdown ? (
<MegaDropdown
key={item.id}
label={item.label}
groups={config.megaDropdown[item.dropdownKey!] ?? []}
/* 「查看全部」落点 = 导航项自身 href,不靠标签反推(原缺陷见 mega-dropdown.tsx props 注释) */
viewAllHref={item.href}
isOpen={openDropdown === item.id}
isActive={isActive(item)}
onToggle={() => {
setOpenDropdown((prev) => prev === item.id ? null : item.id);
}}
onOpen={() => setOpenDropdown(item.id)}
onClose={() => setOpenDropdown((prev) => prev === item.id ? null : prev)}
/>
) : (
<div key={item.id} className="relative -mx-2 px-2 py-2">
<StaticLink
href={item.href}
onClick={handleNavClick}
className={cn(
'relative inline-flex items-center px-3 py-2 text-sm font-medium',
'transition-all duration-normal ease-out',
isActive(item)
? 'text-text-primary'
: 'text-text-secondary hover:text-text-primary hover:bg-bg-secondary'
)}
aria-current={isActive(item) ? 'page' : undefined}
>
{item.label}
<span
className={cn(
'absolute -bottom-0.5 left-3 right-3 h-0.5 bg-brand',
'transition-all duration-normal ease-out',
isActive(item)
? 'opacity-100 scale-x-100'
: 'opacity-0 scale-x-0'
)}
/>
</StaticLink>
</div>
)
))}
</nav>
<div className="hidden md:flex items-center gap-3">
<ThemeToggle />
<Button
size="sm"
asChild
className=""
>
<StaticLink href="/contact" data-testid="consult-button" aria-label="预约咨询">
<MessageCircle className="w-4 h-4" />
<span className="hidden lg:inline">预约咨询</span>
<span className="lg:hidden" aria-hidden="true">咨询</span>
</StaticLink>
</Button>
</div>
<button
className="md:hidden p-2 -mr-2 text-text-secondary hover:text-text-primary hover:bg-bg-secondary rounded-sm transition-all duration-normal ease-out active:scale-95"
onClick={() => setIsOpen((prev) => !prev)}
onKeyDown={handleKeyDown}
aria-expanded={isOpen}
/* 面板仅在 isOpen 时挂载:关闭时不给 aria-controls,避免指向不存在的 id。 */
aria-controls={isOpen ? 'mobile-menu' : undefined}
aria-label={isOpen ? '关闭菜单' : '打开菜单'}
data-testid="mobile-menu-button"
style={{ minWidth: '44px', minHeight: '44px' }}
>
{isOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
</button>
</div>
</div>
</motion.header>
<AnimatePresence mode="wait">
{isOpen && (
<motion.div
ref={focusTrapRef}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 z-40 md:hidden"
>
<div
className="absolute inset-0 bg-black/50 backdrop-blur-sm"
onClick={() => setIsOpen(false)}
aria-hidden="true"
/>
<motion.div
initial={{ x: '100%' }}
animate={{ x: 0 }}
exit={{ x: '100%' }}
transition={{ duration: 0.25, ease: [0.22, 1, 0.36, 1] }}
className="absolute top-16 right-0 bottom-0 left-0 bg-bg-primary/98 backdrop-blur-xl overflow-y-auto"
id="mobile-menu"
role="navigation"
aria-label="移动端导航"
data-testid="mobile-navigation"
>
{/* 桌面端 ThemeToggle 在 `hidden md:flex` 容器内,移动端只有抽屉可达;
w-11 h-11 = 44px,满足触摸目标下限。放在 nav 之外,避免混入导航链接列表。 */}
<div className="max-w-container mx-auto px-4 sm:px-6 pt-6 flex items-center justify-between">
<span className="text-sm text-text-secondary">外观主题</span>
<ThemeToggle className="w-11 h-11" />
</div>
<nav className="max-w-container mx-auto px-4 sm:px-6 py-6">
{config.mainNav.map((item, index) => (
<motion.div
key={item.id}
initial={{ x: 20, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
transition={{ delay: index * 0.05 }}
>
<StaticLink
href={item.href}
onClick={handleNavClick}
className={`
block px-4 py-4 text-base font-medium
transition-all duration-normal ease-out
${isActive(item)
? 'text-text-primary bg-bg-secondary'
: 'text-text-secondary hover:text-text-primary hover:bg-bg-secondary'
}
`}
style={{ minHeight: '48px', display: 'flex', alignItems: 'center' }}
>
{item.label}
</StaticLink>
</motion.div>
))}
<div className="mt-6 px-4 pt-6 border-t border-border-primary">
<Button
className="w-full"
asChild
size="lg"
>
<StaticLink href="/contact" onClick={() => setIsOpen(false)}>
<MessageCircle className="w-4 h-4" />
预约咨询
</StaticLink>
</Button>
</div>
</nav>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</>
);
}
export function Header() {
return <HeaderContent />;
}