返回 CodeWhale
docs-breadcrumbs.ts
根目录 / web / lib / docs-breadcrumbs.ts
1 import {
2 DOC_CATEGORY_LABELS,
3 DOC_TOPICS,
4 docTopicHref,
5 type DocTopic,
6 } from "./docs-map";
7 import { docsTopicIsCurrent } from "./docs-navigation";
8 import { getDocsShell, pickText } from "./i18n/dictionaries";
9 import { SITE_URL } from "./page-meta";
10
11 export type DocsCrumb = {
12 name: string;
13 /** Omitted for the current page and for category groupings that have no URL. */
14 href?: string;
15 };
16
17 export function resolveDocsTopic(locale: string, pathname: string): DocTopic | undefined {
18 return DOC_TOPICS.find((topic) => docsTopicIsCurrent(topic, locale, pathname));
19 }
20
21 /**
22 * Visible trail: Home → Docs → category → topic. The hub stops at Docs.
23 * Chrome names come from the docs-shell dictionary; topic and category
24 * names are the docs-map pairs resolved through `pickText`, so no locale
25 * branch lives here.
26 */
27 export function resolveDocsBreadcrumbs(locale: string, pathname: string): DocsCrumb[] {
28 const t = getDocsShell(locale);
29 const home: DocsCrumb = { name: t.breadcrumbHome, href: `/${locale}` };
30 const docsHref = `/${locale}/docs`;
31 const topic = resolveDocsTopic(locale, pathname);
32 const normalized = pathname.split(/[?#]/)[0].replace(/\/+$/, "");
33
34 if (!topic || normalized === docsHref) {
35 return [home, { name: t.breadcrumbDocs }];
36 }
37
38 return [
39 home,
40 { name: t.breadcrumbDocs, href: docsHref },
41 { name: pickText(DOC_CATEGORY_LABELS[topic.category], locale) },
42 { name: pickText(topic.label, locale) },
43 ];
44 }
45
46 /**
47 * BreadcrumbList for the current docs URL.
48 * Category groupings have no unique URL, so the machine trail is Home → Docs → topic.
49 */
50 export function buildBreadcrumbListJsonLd(locale: string, pathname: string) {
51 const t = getDocsShell(locale);
52 const topic = resolveDocsTopic(locale, pathname);
53 const elements: { name: string; item: string }[] = [
54 { name: t.breadcrumbHome, item: `${SITE_URL}/${locale}` },
55 { name: t.breadcrumbDocs, item: `${SITE_URL}/${locale}/docs` },
56 ];
57 if (topic) {
58 elements.push({
59 name: pickText(topic.label, locale),
60 item: `${SITE_URL}${docTopicHref(topic, locale)}`,
61 });
62 }
63
64 return {
65 "@context": "https://schema.org",
66 "@type": "BreadcrumbList",
67 itemListElement: elements.map((element, index) => ({
68 "@type": "ListItem",
69 position: index + 1,
70 name: element.name,
71 item: element.item,
72 })),
73 };
74 }
75
75 lines TYPESCRIPT