返回 CodeWhale
docs-ia.test.ts
根目录 / web / lib / docs-ia.test.ts
1 /**
2 * Information-architecture contracts: docs-map registration, sitemap and
3 * hreflang preservation, navigation parity across breakpoints and locales,
4 * and the accessibility hooks (skip link, labelled nav, aria-current).
5 *
6 * These are deterministic source/unit contracts in the same style as
7 * public-copy.test.ts: they read the real sources and assert structure, so a
8 * future IA change fails here first instead of drifting silently.
9 */
10 import { existsSync, readFileSync } from "node:fs";
11 import { describe, expect, it } from "vitest";
12 import buildSitemap from "../app/sitemap";
13 import { DOC_TOPICS, docTopicHref, getTopic } from "./docs-map";
14 import { docsTopicIsCurrent } from "./docs-navigation";
15 import { locales } from "./i18n/config";
16 import { contentLocalesForPath } from "./i18n/content-locales";
17 import { getChrome, getHome } from "./i18n/dictionaries";
18 import {
19 currentNavHref,
20 footerLegalLinks,
21 footerProductLinks,
22 footerProjectLinks,
23 navLinks as buildNavLinks,
24 secondaryNavLinks as buildSecondaryNavLinks,
25 } from "./i18n/links";
26 import { SITE_URL } from "./page-meta";
27
28 const webRoot = new URL("../", import.meta.url);
29 const repoRoot = new URL("../../", import.meta.url);
30
31 function webText(path: string): string {
32 return readFileSync(new URL(path, webRoot), "utf8");
33 }
34
35 const sitemapEntries = buildSitemap();
36 const nav = webText("components/nav.tsx");
37 const navLinks = webText("components/nav-links.tsx");
38 const mobileMenu = webText("components/mobile-menu.tsx");
39 const footer = webText("components/footer.tsx");
40 const localeLayout = webText("app/[locale]/layout.tsx");
41 const css = webText("app/globals.css");
42
43 describe("docs-map registration", () => {
44 it("registers the guide and vocabulary topics as first-party pages", () => {
45 const guide = getTopic("guide");
46 const vocabulary = getTopic("vocabulary");
47 expect(guide?.hasPage).toBe(true);
48 expect(vocabulary?.hasPage).toBe(true);
49 expect(vocabulary?.category).toBe("core-concepts");
50 expect(docTopicHref(guide!, "en")).toBe("/en/docs/guide");
51 expect(docTopicHref(vocabulary!, "zh")).toBe("/zh/docs/vocabulary");
52 expect(docsTopicIsCurrent(vocabulary!, "en", "/en/docs/vocabulary")).toBe(true);
53 });
54
55 it("keeps every docs topic repo source on disk", () => {
56 for (const topic of DOC_TOPICS) {
57 const sources = Array.isArray(topic.repoSource) ? topic.repoSource : [topic.repoSource];
58 for (const source of sources) {
59 expect(existsSync(new URL(source, repoRoot)), `${topic.id}: ${source}`).toBe(true);
60 }
61 }
62 });
63
64 it("keeps topic labels and descriptions bilingual", () => {
65 for (const topic of DOC_TOPICS) {
66 for (const pair of [topic.label, topic.description]) {
67 expect(pair.en.trim().length, `${topic.id} en`).toBeGreaterThan(0);
68 expect(pair.zh.trim().length, `${topic.id} zh`).toBeGreaterThan(0);
69 }
70 }
71 });
72 });
73
74 describe("sitemap and hreflang preservation", () => {
75 it("indexes every first-party docs page", () => {
76 for (const topic of DOC_TOPICS) {
77 if (!topic.hasPage) continue;
78 const path = topic.sitePath ? `/${topic.sitePath}` : `/docs/${topic.slug}`;
79 expect(
80 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en${path}`),
81 path,
82 ).toBe(true);
83 }
84 expect(
85 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en/docs/guide`),
86 ).toBe(true);
87 expect(
88 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en/docs/vocabulary`),
89 ).toBe(true);
90 });
91
92 it("keeps sitemap and hreflang output aligned with real translation coverage", () => {
93 // 18 home locales + 10 guide locales + (en, zh) for every other route
94 // (including /product, /plugins, and /changelog, whose bodies ship en/zh only).
95 expect(sitemapEntries).toHaveLength(100);
96 expect(sitemapEntries.some(entry => entry.url.endsWith("/pricing"))).toBe(false);
97 for (const path of ["/product", "/plugins", "/computer-use", "/signin", "/signup", "/legal/terms", "/legal/privacy"]) {
98 expect(
99 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en${path}`),
100 path,
101 ).toBe(true);
102 }
103 for (const [path, expectedLocales] of [
104 ["/", locales],
105 ["/docs/guide", contentLocalesForPath("/docs/guide")],
106 ["/docs", ["en", "zh"]],
107 ] as const) {
108 const suffix = path === "/" ? "" : path;
109 const entry = sitemapEntries.find(
110 (candidate) => candidate.url === `${SITE_URL}/en${suffix}`,
111 );
112 expect(entry, path).toBeDefined();
113 expect(Object.keys(entry?.alternates?.languages ?? {}), path).toEqual([
114 ...expectedLocales,
115 ]);
116 }
117 expect(sitemapEntries.every((entry) => !("lastModified" in entry))).toBe(true);
118 });
119
120 it("keeps the new docs pages on the shared metadata helper", () => {
121 for (const route of ["guide", "vocabulary"]) {
122 const page = webText(`app/[locale]/docs/${route}/page.tsx`);
123 expect(page, route).toContain('import { buildPageMetadata } from "@/lib/page-meta"');
124 expect(page, route).toContain(`path: "/docs/${route}"`);
125 }
126 });
127
128 it("indexes public sign-in and create-account routes", () => {
129 for (const path of ["/signin", "/signup"]) {
130 expect(
131 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en${path}`),
132 path,
133 ).toBe(true);
134 expect(existsSync(new URL(`app/[locale]${path}/page.tsx`, webRoot)), path).toBe(true);
135 }
136 const entry = webText("components/public-account-entry.tsx");
137 expect(entry).toContain("CANONICAL_MARK_SRC");
138 expect(entry).toContain("installLocally");
139 expect(webText("app/[locale]/signin/page.tsx")).toContain('kind="sign-in"');
140 expect(webText("app/[locale]/signup/page.tsx")).toContain('kind="sign-up"');
141 expect(nav).toContain("APP_LOGIN_URL");
142 expect(nav).toContain("APP_SIGNUP_URL");
143 });
144 });
145
146 describe("navigation parity and accessibility", () => {
147 it("keeps desktop and mobile navigation on one shared link set", () => {
148 // Both surfaces consume the same `links` prop from nav.tsx — assert the
149 // wiring rather than duplicating the arrays.
150 expect(nav).toContain("<NavLinks links={links} primaryAria={chrome.navPrimaryAria} />");
151 expect(nav).toContain("links={links}");
152 expect(mobileMenu).toContain("[...links, ...moreLinks].map");
153 expect(navLinks).toContain("links.map");
154 // One generator feeds both surfaces — no per-locale hardcoded arrays.
155 expect(nav).toContain("navLinks(locale, chrome)");
156 expect(nav).not.toMatch(/const (EN|ZH)_LINKS/);
157 // The primary strip does not replace the compact menu until xl;
158 // translated labels are wider than English and used to push real controls
159 // beyond the clipped viewport at md widths.
160 // Wrapping is the escape valve for a translated strip that outgrows the
161 // 76rem container; the row gap stays tight so a second row does not
162 // double the sticky header's height.
163 expect(navLinks).toContain(
164 'className="hidden xl:flex min-w-0 shrink items-center gap-x-5 gap-y-1 flex-wrap"',
165 );
166 // Companion labels remain on the compact sheet. They must not return to
167 // the 76rem desktop strip — at 2xl they zeroed the wordmark on de/pt-BR.
168 expect(navLinks).not.toContain("nav-link-secondary");
169 expect(mobileMenu).toContain("l.secondary");
170 expect(mobileMenu).toContain("xl:hidden inline-flex");
171 expect(nav).toContain("paper-install-cta hidden xl:inline-flex");
172 // A fixed descendant of the blurred sticky header uses the header as its
173 // containing block and collapses. The open sheet must live at body scope.
174 expect(mobileMenu).toContain('import { createPortal } from "react-dom"');
175 expect(mobileMenu).toContain("createPortal(<div");
176 expect(mobileMenu).toContain("document.body");
177 expect(mobileMenu).toContain("element.inert = true");
178 expect(mobileMenu).toContain('if (e.key !== "Tab") return');
179 expect(mobileMenu).toContain('window.matchMedia("(min-width: 1280px)")');
180 expect(mobileMenu).toContain("if (event.matches) closeImmediately()");
181 // Locale and docs-route handlers are shared so a regional tag cannot
182 // nest (`/ja/pt-BR/...`) or hide the theme control on `/pt-BR/docs`.
183 expect(webText("components/locale-switcher.tsx")).toContain("replacePathLocale(pathname, code)");
184 expect(webText("components/theme-toggle.tsx")).toContain("isDocsPath(pathname)");
185 expect(webText("middleware.ts")).toContain("pathLocale(pathname)");
186 });
187
188 it("keeps nav link paths in exact locale-swap parity for every routed locale", () => {
189 // The hardcoded /en/ and /zh/ arrays are gone; assert the generated set
190 // directly, across every routed locale rather than only two of them.
191 const reference = buildNavLinks("en", getChrome("en")).map((l) =>
192 l.href.replace(/^\/en\//, ""),
193 );
194 expect(reference).toEqual(["product", "models", "plugins", "docs"]);
195 const moreReference = buildSecondaryNavLinks("en", getChrome("en")).map((l) =>
196 l.href.replace(/^\/en\//, ""),
197 );
198 expect(moreReference).toEqual(["docs/guide", "install", "faq", "community", "contribute"]);
199 for (const locale of locales) {
200 const links = buildNavLinks(locale, getChrome(locale));
201 expect(
202 links.map((l) => l.href.replace(new RegExp(`^/${locale}/`), "")),
203 `${locale} nav routes`,
204 ).toEqual(reference);
205 const more = buildSecondaryNavLinks(locale, getChrome(locale));
206 expect(
207 more.map((l) => l.href.replace(new RegExp(`^/${locale}/`), "")),
208 `${locale} secondary nav routes`,
209 ).toEqual(moreReference);
210 for (const link of [...links, ...more]) {
211 expect(link.href.startsWith(`/${locale}/`), `${locale} ${link.href}`).toBe(true);
212 expect(link.label.trim().length, `${locale} empty nav label`).toBeGreaterThan(0);
213 }
214 }
215 });
216
217 it("keeps footer link paths in exact locale-swap parity for every routed locale", () => {
218 const reference = footerProductLinks("en", getChrome("en")).map((l) =>
219 l.href.replace(/^\/en\//, ""),
220 );
221 expect(reference).toContain("product");
222 expect(reference).toContain("docs/guide");
223 expect(reference).toContain("faq");
224 for (const locale of locales) {
225 const product = footerProductLinks(locale, getChrome(locale));
226 expect(
227 product.map((l) => l.href.replace(new RegExp(`^/${locale}/`), "")),
228 `${locale} footer product routes`,
229 ).toEqual(reference);
230 const project = footerProjectLinks(locale, getChrome(locale));
231 expect(project.map((l) => l.href), `${locale} footer project routes`).toEqual([
232 "https://github.com/Hmbown/CodeWhale",
233 "https://github.com/Hmbown/CodeWhale/issues",
234 "https://discord.gg/37gfS3ksug",
235 `/${locale}/contribute`,
236 "https://github.com/Hmbown/CodeWhale/blob/main/LICENSE",
237 ]);
238 const legal = footerLegalLinks(locale, getChrome(locale));
239 expect(legal.map((l) => l.href), `${locale} footer legal`).toEqual([
240 `/${locale}/legal/terms`,
241 `/${locale}/legal/privacy`,
242 ]);
243 // Labels come from the dictionary, not hardcoded English, so every
244 // routed locale renders the footer legal links in its own language.
245 expect(legal.map((l) => l.label), `${locale} footer legal labels`).toEqual([
246 getChrome(locale).footerTerms,
247 getChrome(locale).footerPrivacy,
248 ]);
249 }
250 });
251
252 it("labels the primary nav and marks the current page accessibly", () => {
253 expect(navLinks).toContain("aria-label={primaryAria}");
254 expect(getChrome("en").navPrimaryAria).toBe("Primary");
255 expect(getChrome("zh").navPrimaryAria).toBe("主导航");
256 expect(navLinks).toContain('aria-current={isActive ? "page" : undefined}');
257 expect(mobileMenu).toContain('aria-current={isActive ? "page" : undefined}');
258 expect(mobileMenu).toContain('aria-expanded={open}');
259 expect(mobileMenu).toContain('aria-controls="mobile-menu"');
260 expect(mobileMenu).toContain('role="dialog"');
261 });
262
263 it("marks exactly one nav link as the current page on a nested route", () => {
264 // `/xx/docs` and `/xx/docs/guide` are both nav links, so the plain
265 // prefix test both surfaces used marked two links `aria-current="page"`
266 // on the guide route — and drew the nav underline under both.
267 for (const locale of locales) {
268 const links = [
269 ...buildNavLinks(locale, getChrome(locale)),
270 ...buildSecondaryNavLinks(locale, getChrome(locale)),
271 ];
272 const guide = `/${locale}/docs/guide`;
273 const naive = links.filter(
274 (l) => guide === l.href || guide.startsWith(`${l.href}/`),
275 );
276 expect(naive.length, `${locale} ancestor+page collision`).toBeGreaterThan(1);
277 expect(currentNavHref(links, guide), `${locale} current nav link`).toBe(guide);
278 // A route that is not itself a nav link still resolves to its section.
279 expect(
280 currentNavHref(links, `/${locale}/docs/configuration`),
281 `${locale} section fallback`,
282 ).toBe(`/${locale}/docs`);
283 expect(currentNavHref(links, `/${locale}`), `${locale} home`).toBeNull();
284 }
285 // Both surfaces resolve the current page through the shared helper
286 // rather than repeating the prefix test that collided.
287 expect(navLinks).toContain("currentNavHref(links, pathname)");
288 expect(mobileMenu).toContain("currentNavHref([...links, ...moreLinks], pathname)");
289 expect(navLinks).not.toContain("pathname.startsWith(");
290 expect(mobileMenu).not.toContain("pathname.startsWith(");
291 });
292
293 it("ships a keyboard-reachable skip link to the main landmark", () => {
294 expect(localeLayout).toContain('href="#main-content"');
295 expect(localeLayout).toContain('className="skip-link"');
296 expect(localeLayout).toContain('<main id="main-content">');
297 expect(css).toContain(".skip-link:focus-visible");
298 });
299
300 it("keeps the docs trail on the docs-map registry", () => {
301 const docsLayout = webText("app/[locale]/docs/layout.tsx");
302 const docsMap = webText("lib/docs-map.ts");
303 expect(docsMap).toContain("sidebar, breadcrumbs, and drift/parity checks");
304 expect(docsMap).toContain("export const DOC_CATEGORY_LABELS");
305 expect(docsLayout).toContain("<DocsBreadcrumb locale={locale} />");
306 expect(css).toContain(".docs-breadcrumb");
307 });
308
309 it("keeps responsive breakpoints for the getting-started steps", () => {
310 // 4-up grid by default, 2-up at the tablet breakpoint, 1-up on phones —
311 // the same responsive ladder as the existing workflow steps.
312 expect(css).toMatch(/\.gs-steps\s*\{[^}]*repeat\(4, minmax\(0, 1fr\)\)/);
313 expect(css).toMatch(
314 /@media \(max-width: 760px\)[\s\S]*?\.gs-steps\s*\{[^}]*repeat\(2, minmax\(0, 1fr\)\)/,
315 );
316 expect(css).toMatch(
317 /@media \(max-width: 520px\)[\s\S]*?\.gs-steps\s*\{\s*grid-template-columns: 1fr/,
318 );
319 });
320
321 it("keeps the footer discovery links alongside the pinned legal links", () => {
322 // The link sets moved to lib/i18n/links.ts, so assert the rendered
323 // contract for en AND zh rather than scraping literals out of the TSX.
324 for (const locale of ["en", "zh"]) {
325 const product = footerProductLinks(locale, getChrome(locale)).map((l) => l.href);
326 expect(product, `${locale} footer product`).toContain(`/${locale}/docs/guide`);
327 expect(product, `${locale} footer product`).toContain(`/${locale}/faq`);
328 }
329 const license = footerProjectLinks("en", getChrome("en")).at(-1);
330 expect(license).toEqual({
331 label: "MIT license",
332 href: "https://github.com/Hmbown/CodeWhale/blob/main/LICENSE",
333 });
334 // zh gets the footer legal labels from its dictionary, not English.
335 expect(footerLegalLinks("zh", getChrome("zh")).map((l) => l.label)).toEqual([
336 "服务条款",
337 "隐私政策",
338 ]);
339 expect(footer).toContain("footerProductLinks(locale, chrome)");
340 expect(footer).toContain("footerProjectLinks(locale, chrome)");
341 expect(footer).toContain("footerLegalLinks(locale, chrome)");
342 });
343 });
344
345 describe("homepage integration", () => {
346 const homepage = webText("app/[locale]/page.tsx");
347
348 it("renders the shared getting-started path on the homepage", () => {
349 expect(homepage).toContain('import { GettingStartedSteps } from "@/components/getting-started-steps"');
350 expect(homepage).toContain("<GettingStartedSteps locale={locale} />");
351 expect(homepage).toContain("product-start");
352 expect(homepage).toContain("/docs/guide");
353 expect(homepage).toContain("/docs/vocabulary");
354 });
355
356 it("keeps the previously pinned homepage facts intact", () => {
357 // Guard against the new band accidentally displacing the public-copy
358 // gate's required surface (the full contract lives in public-copy.test.ts).
359 expect(homepage).toContain("facts.latestPublishedRelease");
360 // The unreleased-source label is the EN dictionary value the page renders
361 // (plain "Unreleased", per docs/design/WEB_VOICE.md).
362 expect(homepage).toContain("d.sourceCandidate");
363 expect(getHome("en").sourceCandidate).toBe("Unreleased");
364 expect(homepage).toContain("src={TERMINAL_SCREENSHOT.src}");
365 for (const label of ["Plan", "Work", "Operate", "Ask", "Auto-Review", "Full Access"]) {
366 expect(homepage).toContain(label);
367 }
368 });
369 });
370
370 lines TYPESCRIPT