Browse Source

Reuse homepage navigation in blog with scoped language state

zhangwei123 1 month ago
parent
commit
fa956257c8

+ 19 - 0
docs/editorial/blog-navigation-verification.md

@@ -0,0 +1,19 @@
+# Shared homepage navigation — 2026-10-09
+
+Baseline: `a61bae39fd4fff39c4c64f1f8d22d95d8e34967d`.
+
+The blog now renders the existing `Navbar` component, not a styled duplicate. Logo, services/slot links, blog link, language button, login/dashboard/admin/logout states and mobile menu/overlay come from one implementation. The shared logo is keyboard-accessible and the mobile toggle exposes its expanded state and controlled menu. Authentication/storage/logout functions and endpoints are unchanged.
+
+`BlogNavbar` provides a small navigation-only context. It starts in English on the server and first client render, ignores stored/browser preferences on initialization, and never writes the document's language. Changing the EN/ZH site-navigation button changes only that scoped navigation region; its `lang` attribute follows the UI. The button's accessible name includes the visible target language and explains this scope. Article translations remain the existing route links. The homepage provider retains its original default Chinese initial state, preference detection and document-language behavior.
+
+Removed the separate blog header styles and narrowed blog anchor styling to the article/footer so it cannot override the shared navigation's active colors. Article JSON, blog route layouts, metadata/indexing/sitemap logic, homepage page source, auth implementation and existing footer are unchanged. Content SHA-256 stays `c83febff4928cc8e8e9861f9ea28de5b4d5a3d202e8c77f9752d9b0720c0d720`.
+
+Checks passed (exit 0):
+
+- `node scripts/check-blog-nav.cjs`: actual React SSR labels/links/actions; simulated provider preference/document-language isolation and mobile/auth branch handlers. Tests use fake session state, never a real account or backend.
+- Existing style/content/SEO fixture checks.
+- Nonincremental TypeScript check and focused ESLint across the changed TSX files (unused-variable checks; pre-existing explicit-any types were not broadened).
+- Default-noindex production build and HTTP suite: four blog pages retain English document language, content/schema/canonicals and noindex; shared nav/actions render server-side; sitemap remains empty; 13 excluded routes and ten existing route GETs pass.
+- Independent read-only source review found no blocking issue; accessible language-control naming was corrected during review.
+
+Limits: these tests do not establish real browser hydration, responsive pixels, keyboard/touch interactions or authenticated end-to-end behavior. Browser/preview access remains unavailable under previously verified environment restrictions, and full-project lint remains blocked by the pre-existing missing Next ESLint configuration. No push, credential change or deployment is included. A new local commit/bundle is the handoff.

+ 4 - 0
scripts/check-blog-http.mjs

@@ -28,6 +28,10 @@ for (const locale of new Set(visible.map(a => a.locale))) {
     const alternateCount = (html.match(/rel="alternate" hrefLang=/g) || []).length;
     assert.equal(alternateCount, variants.length + (variants.some(b => b.locale === 'en') ? 1 : 0), `Unexpected alternate: ${a.path}`);
     assert(!html.includes('nav.blogs'), 'Untranslated key');
+    assert(html.includes('data-blog-navigation'), 'Missing shared site navigation wrapper');
+    for (const target of ['/services', '/slots', '/login']) assert(html.includes(`href="${target}"`), `Missing shared navigation action: ${target}`);
+    assert(html.includes('aria-expanded="false"'), 'Mobile menu must SSR closed');
+    assert(html.includes('Login / Sign up') && html.includes('Slot Check'), 'Navigation must SSR in English');
     if (a.id) {
       assert(/<h1>.+?<\/h1>/.test(html), 'Missing server-rendered heading');
       assert(/<h2>.+?<\/h2>/.test(html), 'Missing server-rendered article body');

+ 91 - 0
scripts/check-blog-nav.cjs

@@ -0,0 +1,91 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+const React = require('react');
+const { renderToStaticMarkup } = require('react-dom/server');
+const root = process.cwd();
+function loader(overrides = {}, globals = {}) {
+  const cache = new Map();
+  function load(file) {
+    file = path.resolve(root, file);
+    if (!path.extname(file)) file += fs.existsSync(file + '.tsx') ? '.tsx' : '.ts';
+    if (cache.has(file)) return cache.get(file);
+    const module = { exports: {} }; cache.set(file, module.exports);
+    const source = ts.transpileModule(fs.readFileSync(file, 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022 } }).outputText;
+    const resolve = spec => {
+      if (Object.hasOwn(overrides, spec)) return overrides[spec];
+      if (spec.startsWith('@/')) return load('src/' + spec.slice(2));
+      if (spec.startsWith('.')) return load(path.resolve(path.dirname(file), spec));
+      return require(spec);
+    };
+    vm.runInNewContext(source, { module, exports: module.exports, require: resolve, ...globals }, { filename: file });
+    return module.exports;
+  }
+  return load;
+}
+const nextMocks = {
+  'next/navigation': { usePathname: () => '/blogs/netherlands-visa-appointments-dublin' },
+  'next/link': props => React.createElement('a', props, props.children),
+  '@/lib/auth': { isAdmin: () => false, logout: () => {} },
+};
+const loadSSR = loader(nextMocks);
+const BlogNavbar = loadSSR('src/components/blog/BlogNavbar.tsx').default;
+const html = renderToStaticMarkup(React.createElement(BlogNavbar, { blogHref: '/blogs' }));
+for (const text of ['Services', 'Slot Check', 'Visa guides', 'Login / Sign up']) assert(html.includes(text), `Missing shared menu item: ${text}`);
+for (const href of ['/', '/blogs', '/services', '/slots', '/login']) assert(html.includes(`href="${href}"`));
+assert(html.includes('lang="en"') && html.includes('aria-expanded="false"'));
+assert(html.includes('aria-label="STRATA home"'));
+assert(html.includes('aria-label="ZH / 中文: Switch navigation language'), 'Accessible language-control name must include its visible target');
+assert(html.includes('Switch navigation language (article language stays unchanged)'));
+assert(!html.includes('服务工单库') && !html.includes('nav.services'), 'Blog navigation must SSR in English');
+
+// Simulated provider hooks test browser-preference isolation and document-language ownership.
+function providerCase(options, expectedDefault, detect) {
+  const state = []; const effects = []; let index = 0; let reads = 0; const writes = [];
+  const fakeReact = { ...React,
+    createContext: () => ({ Provider: 'context-provider' }),
+    useState: initial => { const i = index++; if (!(i in state)) state[i] = initial; return [state[i], value => { state[i] = value; }]; },
+    useEffect: callback => effects.push(callback),
+  };
+  const document = { documentElement: { lang: 'en' } };
+  const load = loader({ react: fakeReact }, { document, navigator: { language: 'zh-CN' }, localStorage: { getItem: () => { reads++; return expectedDefault === 'en' ? 'zh' : 'en'; }, setItem: (...args) => writes.push(args) } });
+  const Provider = load('src/lib/i18n/LanguageContext.tsx').LanguageProvider;
+  const element = Provider({ children: null, ...options });
+  assert.equal(element.props.value.lang, expectedDefault);
+  effects.forEach(fn => fn());
+  assert.equal(reads > 0, detect);
+  assert.equal(state[0], 'en', 'Homepage honors stored English; blog ignores stored Chinese');
+  element.props.value.setLang('zh');
+  assert.equal(state[0], 'zh');
+  assert.deepEqual(writes[0], ['app_lang', 'zh']);
+  assert.equal(document.documentElement.lang, options.updateDocumentLanguage === false ? 'en' : 'zh-CN');
+}
+providerCase({ initialLang: 'en', detectPreference: false, updateDocumentLanguage: false }, 'en', false);
+providerCase({}, 'zh', true);
+
+// Simulated shared-Navbar hooks cover mobile/auth branches without a browser or real session.
+for (const [logged, admin, open] of [[false, false, false], [false, false, true], [true, false, true], [true, true, true]]) {
+  let index = 0; const states = [logged, admin, open]; const effects = []; const changes = []; let logoutCalls = 0; const events = [];
+  const fakeReact = { ...React, useState: () => { const i = index++; return [states[i], value => changes.push([i, value])]; }, useEffect: callback => effects.push(callback) };
+  const load = loader({ ...nextMocks, react: fakeReact,
+    '@/lib/i18n/LanguageContext': { useLanguage: () => ({ t: key => key.split('.').pop(), lang: 'en', setLang: () => {} }) },
+    '@/lib/auth': { isAdmin: () => admin, logout: () => { logoutCalls++; } },
+  }, { localStorage: { getItem: () => logged ? 'test-session-marker' : null }, window: { addEventListener: (name, callback) => events.push([name, callback]), removeEventListener: () => {} } });
+  const tree = load('src/components/Navbar.tsx').default({ showBlog: true, blogHref: '/blogs', navigationLanguageOnly: true });
+  const nodes = [];
+  function visit(node) { if (Array.isArray(node)) return node.forEach(visit); if (!node || typeof node !== 'object') return; nodes.push(node); visit(node.props?.children); }
+  visit(tree);
+  for (const href of ['/blogs', '/services', '/slots', logged ? '/dashboard' : '/login']) assert(nodes.some(n => n.props?.href === href));
+  assert.equal(nodes.some(n => n.props?.href === '/admin'), logged && admin);
+  assert.equal(nodes.some(n => n.props?.id === 'site-mobile-menu'), open);
+  const toggle = nodes.find(n => n.props?.['aria-label'] === 'Toggle Menu');
+  assert.equal(toggle.props['aria-expanded'], open); toggle.props.onClick();
+  assert(changes.some(([i, value]) => i === 2 && value === !open));
+  effects[0](); assert(events.some(([name]) => name === 'storage'));
+  assert(changes.some(([i, value]) => i === 0 && value === logged));
+  if (logged) { nodes.find(n => n.props?.title === 'logout').props.onClick(); assert.equal(logoutCalls, 1); assert(changes.some(([i, value]) => i === 2 && value === false)); }
+  if (open) { nodes.find(n => n.props?.className?.includes('fixed inset-0')).props.onClick(); assert(changes.some(([i, value]) => i === 2 && value === false)); }
+}
+console.log('PASS: shared navbar SSR links/actions and English labels; provider defaults and document-language isolation; simulated mobile toggle/overlay and logged-out/user/admin/logout/storage branches. This is not browser interaction or authenticated end-to-end QA.');

+ 5 - 2
scripts/check-blog-style.mjs

@@ -16,7 +16,10 @@ assert.equal(tokens['--blog-accent'], '#fcd34d');
 assert.equal(tokens['--blog-accent-hover'], '#fbbf24');
 assert.equal(tokens['--blog-line'], '2px solid var(--blog-ink)');
 assert.equal(tokens['--blog-shadow'], '4px 4px 0 var(--blog-ink)');
-assert.equal(declarations('.blog-header-inner')['min-height'], '64px');
+const sharedNav = fs.readFileSync('src/components/Navbar.tsx', 'utf8');
+assert(sharedNav.includes('items-center h-16'), 'Use the existing 64px shared navigation');
+assert(!css.includes('.blog-header'), 'Do not duplicate the shared navigation styles');
+assert(!/\.blog-body a/.test(css), 'Blog CSS must not override shared navigation anchor colors');
 assert.equal(declarations('.blog-hero')['box-shadow'], '8px 8px 0 var(--blog-ink)');
 assert.equal(declarations('.blog-main')['scroll-margin-top'], '88px');
 assert.equal(declarations('.blog-footer nav')['overflow-wrap'], 'anywhere');
@@ -32,7 +35,7 @@ const media = [];
 sheet.walkAtRules('media', rule => media.push(rule.params));
 assert(media.includes('(max-width: 1023px)') && media.includes('(max-width: 639px)'));
 assert(media.includes('(prefers-reduced-motion: reduce)'));
-assert(css.includes('.blog-body a:focus-visible'));
+assert(css.includes('.blog-main a:focus-visible'));
 const shell = fs.readFileSync('src/components/blog/BlogShell.tsx', 'utf8');
 assert(shell.includes('blog-brand-mark') && shell.includes('<Plane size={16}'));
 assert(!shell.includes('use client'), 'Do not reintroduce browser-dependent language state');

+ 16 - 12
src/components/Navbar.tsx

@@ -1,7 +1,7 @@
 'use client';
 
 import Link from 'next/link';
-import { useRouter, usePathname } from 'next/navigation';
+import { usePathname } from 'next/navigation';
 import { useEffect, useState } from 'react';
 import { 
   Plane,
@@ -19,8 +19,7 @@ import { isAdmin, logout } from '@/lib/auth';
 import LanguageSwitcher from '@/components/common/LanguageSwitcher';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 
-export default function Navbar({ showBlog = false }: { showBlog?: boolean }) {
-  const router = useRouter();
+export default function Navbar({ showBlog = false, blogHref = '/blogs', navigationLanguageOnly = false }: { showBlog?: boolean; blogHref?: string; navigationLanguageOnly?: boolean }) {
   const pathname = usePathname();
   const { t } = useLanguage();
   
@@ -54,6 +53,8 @@ export default function Navbar({ showBlog = false }: { showBlog?: boolean }) {
     setIsMobileMenuOpen(false);
   };
 
+  const isBlogActive = pathname === blogHref || pathname?.startsWith(`${blogHref}/`);
+  const languageTitle = navigationLanguageOnly ? 'Switch navigation language (article language stays unchanged)' : undefined;
   const isServicesActive = pathname === '/services';
   const isSlotsActive = pathname === '/slots';
   const isDashboardActive = pathname === '/dashboard';
@@ -64,9 +65,10 @@ export default function Navbar({ showBlog = false }: { showBlog?: boolean }) {
         <div className="flex justify-between items-center h-16 relative z-50 bg-white">
           
           {/* Logo 铭牌 */}
-          <div 
-            className="flex items-center gap-2 cursor-pointer group" 
-            onClick={() => router.push('/')}
+          <Link
+            href="/"
+            aria-label="STRATA home"
+            className="flex items-center gap-2 cursor-pointer group"
           >
             <div className="w-8 h-8 bg-amber-300 border-2 border-black flex items-center justify-center text-black shadow-[2px_2px_0px_#000] group-hover:bg-amber-400 transition">
               <Plane className="-rotate-45" size={16} />
@@ -79,11 +81,11 @@ export default function Navbar({ showBlog = false }: { showBlog?: boolean }) {
                 [ VAS DIRECTORY ]
               </span>
             </div>
-          </div>
+          </Link>
 
           {/* Desktop Nav 菜单 */}
           <div className="hidden md:flex items-center space-x-2">
-            {showBlog && <a href="/blogs" className="px-3 py-1.5 border-2 border-transparent text-xs font-bold uppercase hover:border-black flex items-center gap-1.5">
+            {showBlog && <a href={blogHref} aria-current={isBlogActive ? 'page' : undefined} className={`px-3 py-1.5 border-2 text-xs font-bold uppercase flex items-center gap-1.5 ${isBlogActive ? 'bg-black text-white border-black shadow-[2px_2px_0px_#000]' : 'border-transparent hover:border-black'}`}>
               <BookOpen size={14} />
               <span>{t('nav.blogs')}</span>
             </a>}
@@ -114,7 +116,7 @@ export default function Navbar({ showBlog = false }: { showBlog?: boolean }) {
 
           {/* Desktop Actions */}
           <div className="hidden md:flex items-center gap-3">
-            <LanguageSwitcher />
+            <LanguageSwitcher title={languageTitle} />
 
             {isLogged ? (
               <div className="flex items-center gap-2.5">
@@ -160,11 +162,13 @@ export default function Navbar({ showBlog = false }: { showBlog?: boolean }) {
 
           {/* Mobile Menu Button */}
           <div className="flex md:hidden items-center gap-2">
-            <LanguageSwitcher />
+            <LanguageSwitcher title={languageTitle} />
             <button
               onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
               className="p-1.5 bg-white border-2 border-black text-black shadow-[2px_2px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 active:shadow-none transition"
               aria-label="Toggle Menu"
+              aria-expanded={isMobileMenuOpen}
+              aria-controls="site-mobile-menu"
             >
               {isMobileMenuOpen ? <X size={20} /> : <Menu size={20} />}
             </button>
@@ -180,9 +184,9 @@ export default function Navbar({ showBlog = false }: { showBlog?: boolean }) {
             onClick={() => setIsMobileMenuOpen(false)}
           />
 
-          <div className="md:hidden bg-white border-b-2 border-black absolute w-full left-0 z-50 shadow-[0_8px_0px_#000] p-4 space-y-3 font-mono">
+          <div id="site-mobile-menu" className="md:hidden bg-white border-b-2 border-black absolute w-full left-0 z-50 shadow-[0_8px_0px_#000] p-4 space-y-3 font-mono">
             <div className="space-y-1.5 border-b-2 border-dashed border-neutral-300 pb-3">
-              {showBlog && <a href="/blogs" onClick={handleLinkClick} className="flex items-center gap-2 border-2 border-black px-3 py-2 text-sm font-bold">
+              {showBlog && <a href={blogHref} onClick={handleLinkClick} aria-current={isBlogActive ? 'page' : undefined} className={`flex items-center gap-2 border-2 border-black px-3 py-2 text-sm font-bold ${isBlogActive ? 'bg-amber-300 text-black' : ''}`}>
                 <BookOpen size={14} /> {t('nav.blogs')}
               </a>}
               <MobileLink href="/services" icon={Briefcase} onClick={handleLinkClick} active={isServicesActive}>

+ 18 - 0
src/components/blog/BlogNavbar.tsx

@@ -0,0 +1,18 @@
+'use client';
+
+import Navbar from '@/components/Navbar';
+import { LanguageProvider, useLanguage } from '@/lib/i18n/LanguageContext';
+
+function NavigationFrame({ blogHref }: { blogHref: string }) {
+  const { lang } = useLanguage();
+  // Navigation language is scoped here; the article's server-selected html lang never changes.
+  return <div className="sticky top-0 z-50" lang={lang === 'zh' ? 'zh-CN' : 'en'} data-blog-navigation>
+    <Navbar showBlog blogHref={blogHref} navigationLanguageOnly />
+  </div>;
+}
+
+export default function BlogNavbar({ blogHref }: { blogHref: string }) {
+  return <LanguageProvider initialLang="en" detectPreference={false} updateDocumentLanguage={false}>
+    <NavigationFrame blogHref={blogHref} />
+  </LanguageProvider>;
+}

+ 3 - 8
src/components/blog/BlogShell.tsx

@@ -1,8 +1,9 @@
 import type { ReactNode } from 'react';
-import { BookOpen, Briefcase, Plane } from 'lucide-react';
+import { Plane } from 'lucide-react';
 import type { BlogLocale } from '@/lib/blog/types';
 import { blogPath, indexingEnabled } from '@/lib/blog/data';
 import { copy } from '@/lib/blog/translations';
+import BlogNavbar from './BlogNavbar';
 
 function BlogBrand() {
   return <a className="blog-brand" href="/" aria-label="STRATA">
@@ -15,13 +16,7 @@ export function BlogShell({ locale, children }: { locale: BlogLocale; children:
   const t = copy[locale];
   return <>
     <a className="blog-skip" href="#blog-main">{t.guides}</a>
-    <header className="blog-header"><div className="blog-header-inner">
-      <BlogBrand />
-      <nav aria-label={t.guides}>
-        <a className="blog-nav-active" href={blogPath(locale)}><BookOpen size={14} aria-hidden="true" />{t.guides}</a>
-        <a href="/services"><Briefcase size={14} aria-hidden="true" />{t.services}</a>
-      </nav>
-    </div></header>
+    <BlogNavbar blogHref={blogPath(locale)} />
     {!indexingEnabled && <p className="blog-preview" role="status">{t.preview}</p>}
     <main id="blog-main" className="blog-main" tabIndex={-1}>{children}</main>
     <footer className="blog-footer"><div className="blog-footer-inner">

+ 4 - 15
src/components/blog/blog.css

@@ -18,23 +18,15 @@
   font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
   line-height: 1.65;
 }
-.blog-body a { color: inherit; text-underline-offset: .2em; }
-.blog-body a:hover { text-decoration: underline; }
-.blog-body a:focus-visible { outline: 3px solid var(--blog-ink); outline-offset: 4px; background: var(--blog-accent); color: var(--blog-ink); }
-.blog-header { width: 100%; background: var(--blog-surface); border-bottom: var(--blog-line); box-shadow: 0 4px 0 var(--blog-ink); position: sticky; top: 0; z-index: 50; }
-.blog-header-inner { max-width: 1280px; min-height: 64px; margin: auto; padding: 0 32px; display: flex; justify-content: space-between; align-items: center; gap: 24px; }
+.blog-main a, .blog-footer a { color: inherit; text-underline-offset: .2em; }
+.blog-main a:hover, .blog-footer a:hover { text-decoration: underline; }
+.blog-main a:focus-visible, .blog-footer a:focus-visible { outline: 3px solid var(--blog-ink); outline-offset: 4px; background: var(--blog-accent); color: var(--blog-ink); }
 .blog-brand { display: inline-flex; flex-shrink: 0; align-items: center; gap: 8px; text-decoration: none !important; font-family: var(--blog-mono); }
 .blog-brand-mark { width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; background: var(--blog-accent); border: var(--blog-line); box-shadow: 2px 2px 0 var(--blog-ink); }
 .blog-brand-mark svg { transform: rotate(-45deg); }
 .blog-brand-name { display: flex; flex-direction: column; line-height: 1; }
 .blog-brand strong { font-size: 16px; font-weight: 900; letter-spacing: -.4px; }
 .blog-brand small { margin-top: 4px; font-size: 9px; font-weight: 700; letter-spacing: .9px; color: #737373; }
-.blog-header nav { display: flex; align-items: center; gap: 8px; font-family: var(--blog-mono); }
-.blog-header nav a { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 40px; padding: 6px 12px; border: 2px solid transparent; font-size: 12px; font-weight: 700; text-transform: uppercase; text-decoration: none; }
-.blog-header nav a:hover { border-color: var(--blog-ink); background: #fafafa; }
-.blog-header nav .blog-nav-active { background: var(--blog-ink); color: var(--blog-surface); border-color: var(--blog-ink); box-shadow: 2px 2px 0 var(--blog-ink); }
-.blog-header nav .blog-nav-active:hover { background: var(--blog-ink); }
-.blog-header nav a:focus-visible { outline-offset: 4px; }
 .blog-main { scroll-margin-top: 88px; width: 100%; max-width: 1152px; flex-grow: 1; margin: auto; padding: 40px 32px 64px; }
 .blog-languages { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 32px; font-family: var(--blog-mono); font-size: 12px; }
 .blog-languages a { padding: 5px 10px; border: var(--blog-line); background: var(--blog-surface); font-weight: 700; text-decoration: none; }
@@ -103,10 +95,7 @@
   .blog-read { width: auto; align-self: flex-start; min-width: 180px; }
 }
 @media (max-width: 639px) {
-  .blog-header-inner { min-height: 64px; padding: 12px 16px; flex-wrap: wrap; gap: 12px; }
-  .blog-header nav { width: 100%; flex-wrap: wrap; }
-  .blog-header nav a { min-height: 44px; flex: 1 1 auto; font-size: 11px; padding: 6px 8px; }
-  .blog-main { scroll-margin-top: 152px; padding: 28px 20px 48px; }
+  .blog-main { scroll-margin-top: 88px; padding: 28px 20px 48px; }
   .blog-languages { margin-bottom: 24px; }
   .blog-hero { padding: 28px 20px; box-shadow: var(--blog-shadow); }
   .blog-hero h1, .blog-article h1 { letter-spacing: -.7px; }

+ 5 - 3
src/components/common/LanguageSwitcher.tsx

@@ -3,17 +3,19 @@
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import { Languages } from 'lucide-react';
 
-export default function LanguageSwitcher() {
+export default function LanguageSwitcher({ title = "Switch Language" }: { title?: string }) {
   const { lang, setLang } = useLanguage();
+  const targetLabel = lang === 'zh' ? 'EN / 英文' : 'ZH / 中文';
 
   return (
     <button
       onClick={() => setLang(lang === 'zh' ? 'en' : 'zh')}
       className="flex items-center gap-1.5 px-3 py-1.5 bg-white text-black border-2 border-black font-mono font-bold text-xs shadow-[2px_2px_0px_#000] hover:bg-amber-300 transition active:translate-x-0.5 active:translate-y-0.5 active:shadow-none uppercase select-none"
-      title="Switch Language"
+      title={title}
+      aria-label={`${targetLabel}: ${title}`}
     >
       <Languages size={14} className="text-black" />
-      <span>{lang === 'zh' ? 'EN / 英文' : 'ZH / 中文'}</span>
+      <span>{targetLabel}</span>
     </button>
   );
 }

+ 11 - 4
src/lib/i18n/LanguageContext.tsx

@@ -15,13 +15,18 @@ interface LanguageContextProps {
 
 const LanguageContext = createContext<LanguageContextProps | undefined>(undefined);
 
-export function LanguageProvider({ children }: { children: ReactNode }) {
+export function LanguageProvider({ children, initialLang = 'zh', detectPreference = true, updateDocumentLanguage = true }: { children: ReactNode; initialLang?: Lang; detectPreference?: boolean; updateDocumentLanguage?: boolean }) {
   // 默认初始状态设为 'zh',但在 useEffect 执行前我们不确定真实语言
-  const [lang, setLangState] = useState<Lang>('zh');
+  const [lang, setLangState] = useState<Lang>(initialLang);
   const [isLoaded, setIsLoaded] = useState(false);
 
   // 初始化逻辑:在客户端挂载后执行
   useEffect(() => {
+    // Route-owned content can keep its server-selected language independent of navigation UI.
+    if (!detectPreference) {
+      setIsLoaded(true);
+      return;
+    }
     // 1. 尝试从本地存储获取
     const savedLang = localStorage.getItem('app_lang') as Lang;
     
@@ -40,14 +45,16 @@ export function LanguageProvider({ children }: { children: ReactNode }) {
     
     // 标记加载完成
     setIsLoaded(true);
-  }, []);
+  }, [detectPreference]);
 
   // 切换语言并保存
   const setLang = (newLang: Lang) => {
     setLangState(newLang);
     localStorage.setItem('app_lang', newLang);
     // 可选:切换语言时更新 HTML 标签的 lang 属性,利于 SEO 和 浏览器翻译插件识别
-    document.documentElement.lang = newLang === 'zh' ? 'zh-CN' : 'en';
+    if (updateDocumentLanguage) {
+      document.documentElement.lang = newLang === 'zh' ? 'zh-CN' : 'en';
+    }
   };
 
   // 获取当前字典