/** * 导航激活判定的**唯一实现**。 * * 为什么要抽出来:此前全站有三套激活语法 —— * 1. header.tsx 内联的 `isActive(item)`(宽松前缀) * 2. mobile-tab-bar.tsx 手写的 per-id `if` 阶梯(switch 在 **id** 上而不是 href) * 3. footer 自己另有一套 * 第 2 套在 IA 改名时尤其危险:id 一变(products→capabilities…),阶梯对每一项 * 都静默返回 `false` ⇒ tab bar 照常渲染、只是永不高亮。那是典型的「绿但空洞」: * 页面没坏、门禁没红,唯独功能悄悄没了。 */ /** 首页只精确匹配,否则任何路径都会把「首页」点亮 */ const EXACT_ROOTS = new Set(['/', '/contact']); /** * 前缀匹配并归一化尾斜杠:`/solutions` 点亮 `/solutions` 与 `/solutions/manufacturing`, * 但**不**点亮 `/solutionship` 这类同前缀的无关路由(因此按 path segment 切,而不是 startsWith 裸串)。 */ export function isNavItemActive(pathname: string, href: string): boolean { if (!href || !pathname) return false; // 外链(如独立产品站)不参与"当前页"高亮 if (href.startsWith('http')) return false; const normalize = (p: string) => (p.length > 1 ? p.replace(/\/+$/, '') : p); const target = normalize(href); // split() 的下标在 noUncheckedIndexedAccess 下是 `string | undefined` ⇒ 显式兜回原串, // 不用 `!`(那等于把「真的没 query」与「类型没收窄」混成一谈) const withoutQuery = pathname.split('?')[0] ?? pathname; const current = normalize(withoutQuery.split('#')[0] ?? withoutQuery); if (EXACT_ROOTS.has(target)) return current === target; // 原先这里还有一条 `if (target === '') return current === '/'` —— 那是**不可达分支**: // 函数开头已 `if (!href || !pathname) return false`,空 href 永远走不到下面。 // 留着它会让覆盖率报告显示一条"有测试没覆盖到的分支",诱导出一个假测试。 return current === target || current.startsWith(`${target}/`); }