@hia-doc/renderer-html 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,13 @@
1
- import { canonicalizeDocumentationLocale, getI18nField, resolveI18nFieldText, validateDocumentationSourceCommentProjection } from "@hia-doc/core";
2
- import { DEFAULT_THEME_CSS_PATH, DEFAULT_THEME_JS_PATH, getDefaultThemeAssets } from "@hia-doc/theme-default";
1
+ import { canonicalizeDocumentationLocale, getI18nField, resolveI18nFieldText, validateBusinessFlowDocumentationProjection, validateDocumentationSourceCommentProjection } from "@hia-doc/core";
2
+ import { relocateDefaultThemeAssets } from "./theme-assets.js";
3
+ import { DEFAULT_THEME_CSS_PATH, DEFAULT_THEME_JS_PATH, PORTAL_THEME_SCHEMES, PORTAL_THEME_SKIN_IDS, getDefaultDocumentationPortalThemeReference, getDefaultThemeAssets, getPortalThemeSchemeLabel, getPortalThemeSkinLabel } from "@hia-doc/theme-default";
3
4
  import { DOCUMENTATION_PORTAL_SEMANTIC_PATH_KINDS, getDocumentationPortalLabels, resolveDocumentationPortalInformationArchitecture, resolveDocumentationPortalUiLocale } from "./information-architecture.js";
5
+ import { PORTAL_PRESENTATION_PROFILE_PATH, createPortalPresentationBundle } from "./presentation-profile.js";
6
+ import { DOCUMENTATION_PORTAL_UI_LOCALE_PROFILE_ID, DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH, DOCUMENTATION_PORTAL_UI_LOCALE_SURFACE_ID, DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES, createDocumentationPortalUiLocaleAdoption, resolveDocumentationPortalUiMessage } from "./portal-ui-locale.js";
4
7
  export * from "./information-architecture.js";
8
+ export * from "./portal-ui-locale.js";
9
+ export * from "./presentation-profile.js";
10
+ export { renderThemeAssets } from "./theme-assets.js";
5
11
  export const HIA_RENDER_HTML_MANIFEST_SCHEMA_VERSION = "0.1.0";
6
12
  /**
7
13
  * 项目导航索引的中性 contract 名称;供静态 portal、搜索与宿主导航消费。
@@ -26,6 +32,8 @@ export const HIA_PROJECT_RELATION_GRAPH_CONTRACT_VERSION = "0.1.0-draft";
26
32
  export function renderHtmlDocument(document, options = {}) {
27
33
  const pageTitle = options.title ?? document.title;
28
34
  const includeThemeAssets = options.includeThemeAssets ?? true;
35
+ // <lang><zh-CN>即使调用者选择外部资源,也先验证明确颜色,避免静默忽略非法配置。</zh-CN><en>Validate explicit colors even with external resources, avoiding silently ignored invalid configuration.</en></lang>
36
+ const assets = getDefaultThemeAssets(options.theme ?? {});
29
37
  const files = [
30
38
  {
31
39
  path: "index.html",
@@ -35,7 +43,7 @@ export function renderHtmlDocument(document, options = {}) {
35
43
  }
36
44
  ];
37
45
  if (includeThemeAssets) {
38
- for (const asset of getDefaultThemeAssets()) {
46
+ for (const asset of assets) {
39
47
  files.push({
40
48
  path: asset.path,
41
49
  contents: asset.contents,
@@ -44,38 +52,94 @@ export function renderHtmlDocument(document, options = {}) {
44
52
  });
45
53
  }
46
54
  }
55
+ // <lang><zh-CN>资源路由在manifest前完成,使文件清单只包含本次真正拥有的文件。</zh-CN><en>Route assets before the manifest so the inventory contains only files owned by this output.</en></lang>
56
+ const routedFiles = relocateDefaultThemeAssets(files, options.themeAssets);
47
57
  return {
48
- files,
58
+ files: routedFiles,
49
59
  diagnostics: [],
50
- manifest: createManifest(document, files, options)
60
+ manifest: createManifest(document, routedFiles, options)
51
61
  };
52
62
  }
63
+ /**
64
+ * @lang zh-CN
65
+ * 把统一项目输入渲染为默认 split-site 或显式 single-page,并生成 exact presentation profile、内容寻址源码资源和 manifest linkage。
66
+ *
67
+ * @lang en
68
+ * Renders unified project input as the default split site or explicit single page, including an exact presentation profile, content-addressed source assets, and manifest linkage.
69
+ *
70
+ * @param projectInput - 已结构化的项目、entry 与关系输入;renderer 不自行读取路径。Structured project, entry, and relation input; the renderer performs no path read.
71
+ * @param options - locale、IA、源码模式和 Portal theme 选择。Locale, IA, source-mode, and Portal-theme selections.
72
+ * @returns 完整的内存文件集、diagnostics 与 body-free manifest。Complete in-memory file set, diagnostics, and body-free manifest.
73
+ * @throws 当显式 IA/theme/source-comment 选择或 renderer 生成的 exact profile 非法时 fail closed。Fails closed when explicit IA/theme/source-comment selections or the renderer-generated exact profile are invalid.
74
+ */
53
75
  export function renderProjectHtmlDocument(projectInput, options = {}) {
54
- const sourcePreparedProjectInput = applyProjectSourcePresentationPolicy(projectInput, options);
55
- const normalizedProjectInput = normalizeProjectRelationGraphInput(sourcePreparedProjectInput);
76
+ // <lang><zh-CN>关系图先规范化,确保 presentation identity 使用最终 relation facts,而不是调用者数组顺序。</zh-CN><en>Normalize the relation graph first so presentation identity uses final relation facts rather than caller array order.</en></lang>
77
+ const normalizedProjectInput = normalizeProjectRelationGraphInput(projectInput);
56
78
  const pageTitle = options.title ?? normalizedProjectInput.project.title ?? normalizedProjectInput.project.name;
57
79
  const includeThemeAssets = options.includeThemeAssets ?? true;
58
80
  const siteLayout = options.projectSite?.layout ?? "split-site";
59
81
  const portalContext = resolveProjectPortalContext(normalizedProjectInput, options, siteLayout);
60
- const navigationIndex = createProjectNavigationIndex(normalizedProjectInput, pageTitle, options, portalContext);
82
+ // <lang><zh-CN>颜色由主题owner单点校验,和普通文档使用同一个品牌资源工厂。</zh-CN><en>The theme owner validates colors centrally through the same branded-asset factory used by documents.</en></lang>
83
+ const assets = getDefaultThemeAssets(options.theme ?? {});
84
+ // <lang><zh-CN>bundle 是 profile、source asset 和 owner mapping 的唯一生成点;后续 HTML 只消费 body-free mapping。</zh-CN><en>The bundle is the sole generation point for profiles, source assets, and owner mappings; later HTML consumes only body-free mappings.</en></lang>
85
+ const presentationBundle = createPortalPresentationBundle({
86
+ projectId: normalizedProjectInput.project.id ?? `project:${normalizedProjectInput.project.name}`,
87
+ layout: siteLayout,
88
+ sourceMode: options.projectSite?.source?.presentation ?? "fetch",
89
+ maxLines: options.projectSite?.source?.maxLines ?? 400,
90
+ skinId: portalContext.theme.skinId,
91
+ scheme: portalContext.theme.scheme,
92
+ topics: normalizedProjectInput.entries.map((entry) => ({
93
+ entryId: entry.id,
94
+ topicKind: entry.kind,
95
+ relationIds: collectProjectPresentationRelationIds(entry, normalizedProjectInput.relationGraph)
96
+ })),
97
+ sources: normalizedProjectInput.entries
98
+ .filter((entry) => Boolean(entry.source))
99
+ .map((entry) => ({
100
+ entryId: entry.id,
101
+ sourcePath: entry.source.path,
102
+ ...(entry.source.preview?.content !== undefined ? { content: entry.source.preview.content } : {}),
103
+ ...(entry.source.range?.start.line ? { startLine: entry.source.range.start.line } : {}),
104
+ ...(entry.source.range?.end?.line ? { endLine: entry.source.range.end.line } : {}),
105
+ ...(entry.docSourceMap?.entryId ? { sourceMapId: entry.docSourceMap.entryId } : {})
106
+ }))
107
+ });
108
+ const sourcePreparedProjectInput = applyProjectSourcePresentationPolicy(normalizedProjectInput, options, presentationBundle);
109
+ const renderedProjectInput = {
110
+ ...sourcePreparedProjectInput,
111
+ diagnostics: [...(sourcePreparedProjectInput.diagnostics ?? []), ...presentationBundle.diagnostics]
112
+ };
113
+ const navigationIndex = createProjectNavigationIndex(renderedProjectInput, pageTitle, options, portalContext, presentationBundle);
61
114
  const files = siteLayout === "single-page"
62
115
  ? [
63
116
  {
64
117
  path: "index.html",
65
- contents: renderProjectIndexHtml(pageTitle, normalizedProjectInput, options),
118
+ contents: renderProjectIndexHtml(pageTitle, renderedProjectInput, options, portalContext),
66
119
  contentType: "text/html; charset=utf-8",
67
120
  role: "entry"
68
121
  }
69
122
  ]
70
- : createProjectSplitSiteFiles(pageTitle, normalizedProjectInput, navigationIndex, options, portalContext);
123
+ : createProjectSplitSiteFiles(pageTitle, renderedProjectInput, navigationIndex, options, portalContext);
124
+ // <lang><zh-CN>完整性 report 在所有可见/无脚本文件生成后追加,但 adoption 本身已在生成前通过 gate。</zh-CN><en>Append the completeness report after visible/no-script files, while the adoption itself has already passed its pre-render gate.</en></lang>
125
+ if (portalContext.uiLocaleAdoption) {
126
+ files.push({
127
+ path: DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH,
128
+ contents: `${portalContext.uiLocaleAdoption.reportJson}\n`,
129
+ contentType: "application/json; charset=utf-8",
130
+ role: "index"
131
+ });
132
+ }
71
133
  files.push({
72
134
  path: "project-index.json",
73
135
  contents: `${JSON.stringify(navigationIndex, null, 2)}\n`,
74
136
  contentType: "application/json; charset=utf-8",
75
137
  role: "index"
76
138
  });
139
+ // <lang><zh-CN>profile/source artifacts 在 navigation index 后追加;manifest 仍记录完整确定性文件清单。</zh-CN><en>Append profile/source artifacts after the navigation index while the manifest still records the full deterministic file inventory.</en></lang>
140
+ files.push(...presentationBundle.artifacts);
77
141
  if (includeThemeAssets) {
78
- for (const asset of getDefaultThemeAssets()) {
142
+ for (const asset of assets) {
79
143
  files.push({
80
144
  path: asset.path,
81
145
  contents: asset.contents,
@@ -84,21 +148,38 @@ export function renderProjectHtmlDocument(projectInput, options = {}) {
84
148
  });
85
149
  }
86
150
  }
151
+ // <lang><zh-CN>共享模式删除副本并重定位全部完整页面引用,manifest不再声称拥有外部文件。</zh-CN><en>Shared mode removes copies and relocates complete-page references; the manifest no longer claims external-file ownership.</en></lang>
152
+ const routedFiles = relocateDefaultThemeAssets(files, options.themeAssets);
87
153
  return {
88
- files,
89
- diagnostics: normalizedProjectInput.diagnostics ?? [],
90
- manifest: createProjectManifest(normalizedProjectInput, files, pageTitle, options, navigationIndex)
154
+ files: routedFiles,
155
+ diagnostics: renderedProjectInput.diagnostics ?? [],
156
+ manifest: createProjectManifest(renderedProjectInput, routedFiles, pageTitle, options, navigationIndex, presentationBundle, portalContext)
91
157
  };
92
158
  }
93
159
  /**
94
- * 在任何文件生成前完成 exact draft 与 single-page gate,避免 partial output。
95
- * Resolves the exact draft and single-page gate before any files are generated, preventing partial output.
160
+ * @lang zh-CN 在任何文件生成前解析 theme/locale 并完成 exact IA、source-comment 与 single-page gate,避免 partial output。
161
+ * @lang en Resolves theme/locale and enforces exact IA, source-comment, and single-page gates before file generation, preventing partial output.
162
+ *
163
+ * @param projectInput - 待验证的结构化 project input。Structured project input to validate.
164
+ * @param options - renderer 调用选项。Renderer invocation options.
165
+ * @param layout - 已解析的页面布局。Resolved page layout.
166
+ * @returns 只含已验证选择的 context。Context containing validated selections only.
167
+ * @throws 对任何不受支持的显式选择 fail closed。Fails closed for every unsupported explicit selection.
96
168
  */
97
169
  function resolveProjectPortalContext(projectInput, options, layout) {
98
170
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
99
- const uiLocale = resolveDocumentationPortalUiLocale(options.projectSite?.uiLocale, localeModel.selectedLocale);
100
171
  const explicitInformationArchitecture = options.projectSite?.informationArchitecture;
172
+ if (explicitInformationArchitecture && !options.projectSite?.uiLocale) {
173
+ throw new TypeError("HIA_PORTAL_UI_LOCALE_REQUIRED: Explicit Portal information architecture requires a caller-explicit UI locale.");
174
+ }
175
+ if (options.projectSite?.uiLocaleCompleteness && !explicitInformationArchitecture) {
176
+ throw new TypeError("HIA_PORTAL_UI_LOCALE_IA_REQUIRED: UI locale completeness identity requires explicit Portal information architecture.");
177
+ }
178
+ // <lang><zh-CN>非 IA 调用保留历史 fallback;adopted explicit IA 永远由上面的 caller-explicit gate 提供值。</zh-CN><en>Non-IA calls retain the historical fallback; adopted explicit IA always receives its value from the caller-explicit gate above.</en></lang>
179
+ const uiLocale = resolveDocumentationPortalUiLocale(options.projectSite?.uiLocale, localeModel.selectedLocale);
101
180
  const sourceCommentProjection = options.projectSite?.sourceCommentProjection;
181
+ // <lang><zh-CN>共用逐项优先级及闭集校验;旧项目调用保留兼容回退。</zh-CN><en>Share per-field precedence and closed-catalog validation, retaining fallback for legacy project calls.</en></lang>
182
+ const { skinId: requestedSkin, scheme: requestedScheme } = resolveThemeSelection(options);
102
183
  if (projectInput.documentationContinuity) {
103
184
  assertProjectDocumentationContinuitySummary(projectInput.documentationContinuity);
104
185
  }
@@ -108,6 +189,15 @@ function resolveProjectPortalContext(projectInput, options, layout) {
108
189
  throw new TypeError("HIA_PORTAL_IA_OWNER_ADOPTION_REQUIRES_IA: owner-adoption linkage requires explicit Portal information architecture.");
109
190
  }
110
191
  }
192
+ if (projectInput.businessFlowDocumentationProjection) {
193
+ // <lang><zh-CN>在生成任何文件前复用 W-P122 owner validator;renderer 不修复、补全或推断 flow facts。</zh-CN><en>Reuse the W-P122 owner validator before generating any file; the renderer repairs, completes, or infers no flow facts.</en></lang>
194
+ if (validateBusinessFlowDocumentationProjection(projectInput.businessFlowDocumentationProjection).length > 0) {
195
+ throw new TypeError("HIA_PORTAL_IA_BUSINESS_FLOW_INVALID: business-flow linkage must be an exact public projection.");
196
+ }
197
+ if (!explicitInformationArchitecture) {
198
+ throw new TypeError("HIA_PORTAL_IA_BUSINESS_FLOW_REQUIRES_IA: business-flow linkage requires explicit Portal information architecture.");
199
+ }
200
+ }
111
201
  if (sourceCommentProjection && !explicitInformationArchitecture) {
112
202
  throw new TypeError("HIA_PORTAL_SOURCE_COMMENT_REQUIRES_IA: source-comment projection requires explicit Portal information architecture.");
113
203
  }
@@ -128,9 +218,21 @@ function resolveProjectPortalContext(projectInput, options, layout) {
128
218
  if (explicitInformationArchitecture && layout === "single-page") {
129
219
  throw new TypeError("HIA_CONFIG_IA_SINGLE_PAGE_UNSUPPORTED: Explicit Portal IA is supported only with split-site in this draft.");
130
220
  }
221
+ // <lang><zh-CN>只有显式 IA surface 构造 W-P123 report;legacy P3/single-page 不伪报 completeness。</zh-CN><en>Only explicit-IA surfaces build a W-P123 report; legacy P3/single-page output does not claim completeness.</en></lang>
222
+ const uiLocaleAdoption = explicitInformationArchitecture
223
+ ? createDocumentationPortalUiLocaleAdoption({
224
+ contentLocale: localeModel.selectedLocale,
225
+ contentLocales: localeModel.locales,
226
+ defaultUiLocale: uiLocale,
227
+ profileId: options.projectSite?.uiLocaleCompleteness?.profileId ?? DOCUMENTATION_PORTAL_UI_LOCALE_PROFILE_ID,
228
+ surfaceId: options.projectSite?.uiLocaleCompleteness?.surfaceId ?? DOCUMENTATION_PORTAL_UI_LOCALE_SURFACE_ID
229
+ })
230
+ : undefined;
131
231
  return {
132
232
  uiLocale,
133
233
  labels: getDocumentationPortalLabels(uiLocale),
234
+ theme: { skinId: requestedSkin, scheme: requestedScheme },
235
+ ...(uiLocaleAdoption ? { uiLocaleAdoption } : {}),
134
236
  ...(sourceCommentProjection
135
237
  ? {
136
238
  sourceCommentProjection: {
@@ -234,30 +336,37 @@ function isExactObject(value, allowedFields) {
234
336
  && allowedFields.every((field) => Object.hasOwn(value, field));
235
337
  }
236
338
  /**
237
- * 在 renderer 公共入口执行源码呈现边界,保证直接库调用与 CLI 调用具有同一隐私语义。
238
- * Enforces source-presentation boundaries at the renderer API so direct library and CLI calls share the same privacy semantics.
339
+ * @lang zh-CN 在 renderer 公共入口执行源码呈现边界,剥离旧外链并只投影 bundle 已授权的正文或同源资源。
340
+ * @lang en Enforces source-presentation boundaries at the renderer API, stripping legacy external links and projecting only bundle-authorized bodies or same-origin assets.
341
+ *
342
+ * @param projectInput - 规范化后的 project input。Normalized project input.
343
+ * @param options - 显式 source presentation 选择。Explicit source-presentation selection.
344
+ * @param presentationBundle - 已 exact-valid 的 body-free owner mapping。Exact-valid body-free owner mapping.
345
+ * @returns 不改变 locator identity 的安全 project input。Safe project input preserving locator identity.
239
346
  */
240
- function applyProjectSourcePresentationPolicy(projectInput, options) {
241
- const presentation = options.projectSite?.source?.presentation ?? "link";
347
+ function applyProjectSourcePresentationPolicy(projectInput, options, presentationBundle) {
348
+ const presentation = options.projectSite?.source?.presentation ?? "fetch";
242
349
  return {
243
350
  ...projectInput,
244
351
  entries: projectInput.entries.map((entry) => {
245
352
  if (!entry.source) {
246
353
  return entry;
247
354
  }
248
- const { preview, fetchUrl, linkUrl, ...locator } = entry.source;
355
+ const { preview, fetchUrl: _legacyFetchUrl, linkUrl: _legacyLinkUrl, publicAsset: _existingPublicAsset, ...locator } = entry.source;
249
356
  const previewDefaultExpanded = options.projectSite?.source?.defaultExpanded ?? preview?.defaultExpanded;
357
+ const publicAsset = presentationBundle.sourceByEntryId.get(entry.id);
250
358
  const source = {
251
359
  ...locator,
252
- ...(presentation !== "none" && linkUrl ? { linkUrl } : {}),
360
+ ...(presentation === "link" && publicAsset ? { linkUrl: publicAsset.relativeUrl, publicAsset } : {}),
253
361
  ...(presentation === "embed" && preview ? {
254
362
  preview: {
255
363
  ...preview,
256
364
  ...(previewDefaultExpanded !== undefined ? { defaultExpanded: previewDefaultExpanded } : {})
257
365
  }
258
366
  } : {}),
259
- ...(presentation === "fetch" && fetchUrl ? {
260
- fetchUrl,
367
+ ...(presentation === "fetch" && publicAsset ? {
368
+ fetchUrl: publicAsset.relativeUrl,
369
+ publicAsset,
261
370
  fetchTrigger: options.projectSite?.source?.fetchTrigger ?? entry.source.fetchTrigger ?? "on-expand",
262
371
  fetchMaxLines: options.projectSite?.source?.maxLines ?? entry.source.fetchMaxLines ?? 400
263
372
  } : {})
@@ -269,6 +378,33 @@ function applyProjectSourcePresentationPolicy(projectInput, options) {
269
378
  })
270
379
  };
271
380
  }
381
+ /**
382
+ * @lang zh-CN 为独立 no-script 页面移除 fetch runtime metadata,并把 build-generated link 调整为页面相对路径。
383
+ * @lang en Removes fetch-runtime metadata for standalone no-script pages and adjusts build-generated links to page-relative paths.
384
+ *
385
+ * @param projectInput - 已应用 source policy 的 project input。Project input after source policy application.
386
+ * @returns 不含不可用 fetch control 的 page input。Page input without unavailable fetch controls.
387
+ */
388
+ function createProjectNoScriptProjectInput(projectInput) {
389
+ return {
390
+ ...projectInput,
391
+ entries: projectInput.entries.map((entry) => {
392
+ if (!entry.source) {
393
+ return entry;
394
+ }
395
+ const { fetchUrl, publicAsset: _publicAsset, linkUrl, ...source } = entry.source;
396
+ // <lang><zh-CN>无脚本页面把同源 fetch asset 降级成普通链接;这不会恢复被拒绝的外部 locator。</zh-CN><en>The no-script page degrades a same-origin fetch asset to a regular link without restoring a rejected external locator.</en></lang>
397
+ const noScriptLinkUrl = linkUrl ?? fetchUrl;
398
+ return {
399
+ ...entry,
400
+ source: {
401
+ ...source,
402
+ ...(noScriptLinkUrl ? { linkUrl: `../${noScriptLinkUrl}` } : {})
403
+ }
404
+ };
405
+ })
406
+ };
407
+ }
272
408
  function createManifest(document, files, options) {
273
409
  return {
274
410
  schemaVersion: HIA_RENDER_HTML_MANIFEST_SCHEMA_VERSION,
@@ -285,7 +421,71 @@ function createManifest(document, files, options) {
285
421
  }))
286
422
  };
287
423
  }
288
- function createProjectManifest(projectInput, files, pageTitle, options, navigationIndex) {
424
+ /** @lang zh-CN 从已验证 bundle 构造 manifest/index 共用的最小 profile 引用。 @lang en Builds the minimal manifest/index profile reference from a validated bundle. */
425
+ function createProjectPresentationProfileRef(presentationBundle) {
426
+ return {
427
+ contract: presentationBundle.profile.contract,
428
+ contractVersion: presentationBundle.profile.contractVersion,
429
+ path: PORTAL_PRESENTATION_PROFILE_PATH,
430
+ profileId: presentationBundle.profile.profileId,
431
+ status: presentationBundle.profile.status
432
+ };
433
+ }
434
+ /**
435
+ * @lang zh-CN
436
+ * 从已通过 W-P123 gate 的 adoption 构造 manifest/index 共用的 body-free 引用和计数。
437
+ *
438
+ * @lang en
439
+ * Builds the body-free manifest/index reference and counts from a W-P123 gate-complete adoption.
440
+ *
441
+ * @param adoption <lang><zh-CN>当前 Portal surface 的完整性结果。</lang><en>Completeness result for the current Portal surface.</en></lang>
442
+ * @returns <lang><zh-CN>不含 message text 或内容正文的引用。</lang><en>Reference containing no message text or content body.</en></lang>
443
+ */
444
+ function createProjectUiLocaleCompletenessRef(adoption) {
445
+ // <lang><zh-CN>P1 每次 adoption 只有一个 owner surface;evaluator 已保证集合非空。</zh-CN><en>Each P1 adoption owns one surface; the evaluator has already guaranteed a non-empty set.</en></lang>
446
+ const surfaceId = adoption.report.surfaces[0].surfaceId;
447
+ return {
448
+ contract: adoption.report.contract,
449
+ contractVersion: adoption.report.contractVersion,
450
+ evaluationCount: adoption.summary.evaluations,
451
+ exactCount: adoption.summary.exact,
452
+ path: DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH,
453
+ profileId: adoption.report.profileId,
454
+ status: adoption.report.status,
455
+ surfaceId,
456
+ uiLocaleCount: adoption.summary.uiLocales
457
+ };
458
+ }
459
+ /**
460
+ * @lang zh-CN 从已验证 W-P122 projection 构造 manifest 的 body-free ref/count。
461
+ * @lang en Builds a body-free manifest reference and counts from a validated W-P122 projection.
462
+ * @param projection exact-valid public dual projection。 / Exact-valid public dual projection.
463
+ * @returns 不含 label、node、edge 或 evidence body 的引用。 / Reference containing no labels, nodes, edges, or evidence bodies.
464
+ */
465
+ function createProjectBusinessFlowProjectionRef(projection) {
466
+ return {
467
+ contract: projection.contract,
468
+ contractVersion: projection.contractVersion,
469
+ flowCount: projection.sharedFacts.flows.length,
470
+ humanItemCount: projection.humanLinear.flows.reduce((total, flow) => total + flow.items.length, 0),
471
+ nodeCount: projection.sharedFacts.nodes.length,
472
+ path: "project-index.json",
473
+ relationCount: projection.sharedFacts.relations.length
474
+ };
475
+ }
476
+ /**
477
+ * @lang zh-CN 收集与 entry 关联的稳定 relation ids;relation kind 不参与 containment。
478
+ * @lang en Collects stable relation ids associated with an entry; relation kind does not become containment.
479
+ */
480
+ function collectProjectPresentationRelationIds(entry, relationGraph) {
481
+ const entryNodeIds = new Set(relationGraph?.nodes.filter((node) => node.entryId === entry.id).map(({ id }) => id) ?? []);
482
+ return (relationGraph?.relations ?? [])
483
+ .filter((relation) => relation.entryId === entry.id || entryNodeIds.has(relation.from) || entryNodeIds.has(relation.to))
484
+ .map(({ id }) => id)
485
+ .sort(compareStableText);
486
+ }
487
+ /** @lang zh-CN 构造含 profile linkage 的 body-free renderer manifest。 @lang en Builds a body-free renderer manifest with presentation-profile linkage. */
488
+ function createProjectManifest(projectInput, files, pageTitle, options, navigationIndex, presentationBundle, portalContext) {
289
489
  const projectId = projectInput.project.id ?? `project:${projectInput.project.name}`;
290
490
  const views = collectProjectViews(projectInput.entries);
291
491
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
@@ -307,6 +507,8 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
307
507
  name: projectInput.project.name,
308
508
  views,
309
509
  entryCounts: countEntriesByView(projectInput.entries),
510
+ theme: getDefaultDocumentationPortalThemeReference(),
511
+ presentationProfile: createProjectPresentationProfileRef(presentationBundle),
310
512
  ...(projectInput.project.productVersion ? { productVersion: projectInput.project.productVersion } : {}),
311
513
  navigationIndex: {
312
514
  contract: navigationIndex.contract,
@@ -328,6 +530,11 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
328
530
  }
329
531
  }
330
532
  : {}),
533
+ ...(projectInput.businessFlowDocumentationProjection
534
+ ? {
535
+ businessFlowDocumentationProjection: createProjectBusinessFlowProjectionRef(projectInput.businessFlowDocumentationProjection)
536
+ }
537
+ : {}),
331
538
  ...(projectInput.relationGraph && projectInput.relationGraph.relationCount > 0
332
539
  ? {
333
540
  relationGraph: {
@@ -341,11 +548,15 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
341
548
  : {}),
342
549
  ...(navigationIndex.site?.informationArchitecture
343
550
  ? { informationArchitecture: navigationIndex.site.informationArchitecture }
551
+ : {}),
552
+ ...(portalContext.uiLocaleAdoption
553
+ ? { uiLocaleCompleteness: createProjectUiLocaleCompletenessRef(portalContext.uiLocaleAdoption) }
344
554
  : {})
345
555
  }
346
556
  };
347
557
  }
348
- function createProjectNavigationIndex(projectInput, pageTitle, options, portalContext) {
558
+ /** @lang zh-CN 构造 owner route index,并附加 neutral topic/page/fragment identity 和 profile 引用。 @lang en Builds the owner route index with neutral topic/page/fragment identities and a profile reference. */
559
+ function createProjectNavigationIndex(projectInput, pageTitle, options, portalContext, presentationBundle) {
349
560
  const projectId = projectInput.project.id ?? `project:${projectInput.project.name}`;
350
561
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
351
562
  return {
@@ -380,6 +591,15 @@ function createProjectNavigationIndex(projectInput, pageTitle, options, portalCo
380
591
  ...(entry.symbolId ? { symbolId: entry.symbolId } : {}),
381
592
  ...(entry.hierarchy ? { hierarchy: entry.hierarchy } : {}),
382
593
  contentPath: createProjectEntryContentPath(entry.id),
594
+ ...(options.projectSite?.layout === "single-page" ? {} : { noScriptPagePath: createProjectNoScriptPagePath(entry.id) }),
595
+ ...(portalContext.uiLocaleAdoption && options.projectSite?.layout !== "single-page"
596
+ ? {
597
+ noScriptLocalePages: DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES.map((uiLocale) => ({
598
+ uiLocale,
599
+ path: createProjectLocalizedNoScriptPagePath(entry.id, uiLocale)
600
+ }))
601
+ }
602
+ : {}),
383
603
  ...(portalContext.informationArchitecture
384
604
  ? {
385
605
  presentationPath: createProjectEntryPresentationPath(entry, projectInput.entries, portalContext.informationArchitecture),
@@ -387,7 +607,14 @@ function createProjectNavigationIndex(projectInput, pageTitle, options, portalCo
387
607
  ...(entry.semanticPath ? { semanticPath: entry.semanticPath } : {})
388
608
  }
389
609
  : {}),
390
- ...(entry.docSourceMap ? { docSourceMap: entry.docSourceMap } : {})
610
+ ...(entry.docSourceMap ? { docSourceMap: entry.docSourceMap } : {}),
611
+ ...(presentationBundle.topicByEntryId.get(entry.id)
612
+ ? {
613
+ presentationTopicId: presentationBundle.topicByEntryId.get(entry.id).topicId,
614
+ presentationPageId: presentationBundle.topicByEntryId.get(entry.id).pageId,
615
+ presentationFragmentId: presentationBundle.topicByEntryId.get(entry.id).fragmentId
616
+ }
617
+ : {})
391
618
  }))
392
619
  .sort(compareProjectNavigationEntries),
393
620
  groups: collectProjectNavigationGroups(projectInput.entries),
@@ -399,16 +626,24 @@ function createProjectNavigationIndex(projectInput, pageTitle, options, portalCo
399
626
  : {}),
400
627
  ...(projectInput.documentationContinuity ? { documentationContinuity: projectInput.documentationContinuity } : {}),
401
628
  ...(projectInput.ownerAdoption ? { ownerAdoption: projectInput.ownerAdoption } : {}),
629
+ ...(projectInput.businessFlowDocumentationProjection
630
+ ? { businessFlowDocumentationProjection: projectInput.businessFlowDocumentationProjection }
631
+ : {}),
402
632
  site: {
403
633
  layout: options.projectSite?.layout ?? "split-site",
634
+ theme: getDefaultDocumentationPortalThemeReference(),
635
+ presentationProfile: createProjectPresentationProfileRef(presentationBundle),
404
636
  ...(options.projectSite?.layout === "single-page" ? {} : {
405
637
  navigationRootPath: "navigation/root.json",
406
638
  searchIndexPath: "search/index.json",
407
639
  relationIndexPath: "relations/project.json"
408
640
  }),
409
- sourcePresentation: options.projectSite?.source?.presentation ?? "link",
641
+ sourcePresentation: options.projectSite?.source?.presentation ?? "fetch",
410
642
  ...(portalContext.informationArchitecture
411
643
  ? { informationArchitecture: portalContext.informationArchitecture }
644
+ : {}),
645
+ ...(portalContext.uiLocaleAdoption
646
+ ? { uiLocaleCompleteness: createProjectUiLocaleCompletenessRef(portalContext.uiLocaleAdoption) }
412
647
  : {})
413
648
  },
414
649
  ...(projectInput.relationGraph && projectInput.relationGraph.relationCount > 0
@@ -417,8 +652,8 @@ function createProjectNavigationIndex(projectInput, pageTitle, options, portalCo
417
652
  };
418
653
  }
419
654
  /**
420
- * 生成大型项目默认使用的 split-site 文件集合;入口页只保留应用壳。
421
- * Generates the split-site file set used by large projects by default; the entry page only keeps the application shell.
655
+ * @lang zh-CN 生成大型项目默认使用的 split-site 文件集合;入口页只保留应用壳,entry/source 正文保持分离。
656
+ * @lang en Generates the default split-site file set for large projects; the entry page retains only the shell while entry/source bodies remain separate.
422
657
  */
423
658
  function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, options, portalContext) {
424
659
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
@@ -442,6 +677,7 @@ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, o
442
677
  kind: entry.kind,
443
678
  view: entry.view,
444
679
  contentPath: createProjectEntryContentPath(entry.id),
680
+ noScriptPagePath: createProjectNoScriptPagePath(entry.id),
445
681
  ...(informationArchitecture
446
682
  ? {
447
683
  presentationPath: createProjectEntryPresentationPath(entry, projectInput.entries, informationArchitecture),
@@ -461,9 +697,36 @@ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, o
461
697
  role: "index"
462
698
  }
463
699
  ];
700
+ // <lang><zh-CN>no-script 入口与逐 topic 页面保持独立,不把数千节点重新塞回应用壳。</zh-CN><en>The no-script index and per-topic pages stay separate so thousands of nodes are not embedded back into the application shell.</en></lang>
701
+ const noScriptProjectInput = createProjectNoScriptProjectInput(projectInput);
702
+ // <lang><zh-CN>按稳定 entry id 建立单次索引,避免大型项目为每页线性扫描全部节点。</zh-CN><en>Build a one-time stable-entry index so large projects do not scan every node for every page.</en></lang>
703
+ const noScriptEntryById = new Map(noScriptProjectInput.entries.map((entry) => [entry.id, entry]));
704
+ files.push({
705
+ path: "pages/index.html",
706
+ contents: renderProjectNoScriptIndexHtml(pageTitle, noScriptProjectInput, localeModel.selectedLocale, portalContext),
707
+ contentType: "text/html; charset=utf-8",
708
+ role: "entry"
709
+ });
710
+ // <lang><zh-CN>采用 W-P123 的 surface 为每个 UI locale 生成真实静态入口;legacy 默认路径仍保留。</zh-CN><en>A W-P123-adopted surface emits a real static entry for every UI locale while retaining the legacy default path.</en></lang>
711
+ if (portalContext.uiLocaleAdoption) {
712
+ for (const uiLocale of DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES) {
713
+ const localizedContext = withProjectUiLocale(portalContext, uiLocale);
714
+ files.push({
715
+ path: `pages/${uiLocale}/index.html`,
716
+ contents: renderProjectNoScriptIndexHtml(pageTitle, noScriptProjectInput, localeModel.selectedLocale, localizedContext, true),
717
+ contentType: "text/html; charset=utf-8",
718
+ role: "entry"
719
+ });
720
+ }
721
+ }
464
722
  // <lang zh-CN>canonical entry fragment 始终生成,保证旧 deep link 与不识别 IA 的 consumer 可回退。</lang>
465
723
  // <lang en>Canonical entry fragments are always emitted so old deep links and IA-unaware consumers retain a fallback.</lang>
466
724
  for (const entry of projectInput.entries) {
725
+ // <lang><zh-CN>索引与原输入由同一次确定性映射产生,因此对应 no-script entry 必须存在。</zh-CN><en>The index and original input come from the same deterministic mapping, so the matching no-script entry must exist.</en></lang>
726
+ const noScriptEntry = noScriptEntryById.get(entry.id);
727
+ if (!noScriptEntry) {
728
+ throw new Error(`HIA_RENDERER_NO_SCRIPT_ENTRY_MISSING: ${entry.id}`);
729
+ }
467
730
  files.push({
468
731
  path: createProjectEntryContentPath(entry.id),
469
732
  contents: informationArchitecture
@@ -472,6 +735,23 @@ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, o
472
735
  contentType: "text/html; charset=utf-8",
473
736
  role: "asset"
474
737
  });
738
+ files.push({
739
+ path: createProjectNoScriptPagePath(entry.id),
740
+ contents: renderProjectNoScriptEntryHtml(pageTitle, noScriptEntry, noScriptProjectInput, localeModel, portalContext),
741
+ contentType: "text/html; charset=utf-8",
742
+ role: "entry"
743
+ });
744
+ if (portalContext.uiLocaleAdoption) {
745
+ for (const uiLocale of DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES) {
746
+ const localizedContext = withProjectUiLocale(portalContext, uiLocale);
747
+ files.push({
748
+ path: createProjectLocalizedNoScriptPagePath(entry.id, uiLocale),
749
+ contents: renderProjectNoScriptEntryHtml(pageTitle, noScriptEntry, noScriptProjectInput, localeModel, localizedContext, true),
750
+ contentType: "text/html; charset=utf-8",
751
+ role: "entry"
752
+ });
753
+ }
754
+ }
475
755
  }
476
756
  // <lang zh-CN>semantic-container 只增加 presentation fragment,不替换 canonical fragment。</lang>
477
757
  // <lang en>Semantic containers add presentation fragments without replacing canonical fragments.</lang>
@@ -554,6 +834,17 @@ function toLazyProjectNavigationNode(node) {
554
834
  function createProjectEntryContentPath(entryId) {
555
835
  return `entries/${stableProjectArtifactName(entryId)}.html`;
556
836
  }
837
+ /** @lang zh-CN 为每个 neutral topic 生成稳定的 no-script owner page route。 @lang en Generates a stable no-script owner page route for every neutral topic. */
838
+ function createProjectNoScriptPagePath(entryId) {
839
+ return `pages/${stableProjectArtifactName(entryId)}.html`;
840
+ }
841
+ /**
842
+ * @lang zh-CN 为一个 UI locale 生成可直接访问的无脚本 owner page route。
843
+ * @lang en Generates a directly addressable no-script owner-page route for one UI locale.
844
+ */
845
+ function createProjectLocalizedNoScriptPagePath(entryId, uiLocale) {
846
+ return `pages/${uiLocale}/${stableProjectArtifactName(entryId)}.html`;
847
+ }
557
848
  /**
558
849
  * 计算 additive presentation location;canonical contentPath 永远由 entry id 单独计算。
559
850
  * Computes the additive presentation location; canonical contentPath is always computed independently from the entry id.
@@ -663,6 +954,39 @@ function compareProjectDocSourceMaps(left, right) {
663
954
  function compareStableText(left, right) {
664
955
  return left < right ? -1 : left > right ? 1 : 0;
665
956
  }
957
+ /**
958
+ * @lang zh-CN 生成无脚本也可读取的 theme root metadata;字段只来自内置 exact reference。
959
+ * @lang en Renders theme-root metadata readable without scripts; every field comes from the built-in exact reference.
960
+ *
961
+ * @param themeSelection - 可选的 Portal-owned build-time 默认 skin/scheme。Optional Portal-owned build-time default skin/scheme.
962
+ * @returns 适用于 `<html>` opening tag 的 escaped attributes。Escaped attributes for an opening `<html>` tag.
963
+ */
964
+ function renderDefaultThemeRootAttributes(themeSelection) {
965
+ // <lang><zh-CN>每次取得新 reference,避免 renderer 修改 theme owner 的共享对象。</zh-CN><en>Obtain a fresh reference each time so the renderer cannot mutate the theme owner's shared object.</en></lang>
966
+ const theme = getDefaultDocumentationPortalThemeReference();
967
+ return [
968
+ `data-hia-theme="${escapeHtml(theme.name)}"`,
969
+ `data-hia-theme-contract="${escapeHtml(theme.contract)}"`,
970
+ `data-hia-theme-contract-version="${escapeHtml(theme.contractVersion)}"`,
971
+ `data-hia-theme-color-scheme-policy="${escapeHtml(theme.colorSchemePolicy)}"`,
972
+ `data-hia-theme-disclosure="${escapeHtml(theme.disclosure)}"`,
973
+ ...(themeSelection
974
+ ? [
975
+ `data-hia-skin="${escapeHtml(themeSelection.skinId)}"`,
976
+ `data-hia-scheme="${escapeHtml(themeSelection.scheme)}"`
977
+ ]
978
+ : [])
979
+ ].join(" ");
980
+ }
981
+ /** @lang zh-CN 优先共用theme,逐项回退旧项目theme与默认值;未知选择在产生HTML前拒绝。 @lang en Prefers shared theme, falls back per field to legacy project theme and defaults, and rejects unknown selections before HTML generation. */
982
+ function resolveThemeSelection(options) {
983
+ // <lang><zh-CN>皮肤与配色独立解析,不从品牌颜色推断另一种主题。</zh-CN><en>Resolve skin and scheme independently without inferring another theme from brand colors.</en></lang>
984
+ const skinId = options.theme?.skinId ?? options.projectSite?.theme?.skinId ?? "portal.classic";
985
+ const scheme = options.theme?.scheme ?? options.projectSite?.theme?.scheme ?? "system";
986
+ if (!PORTAL_THEME_SKIN_IDS.includes(skinId) || !PORTAL_THEME_SCHEMES.includes(scheme))
987
+ throw new TypeError("HIA_PORTAL_THEME_SELECTION_INVALID: Portal skin and scheme must use the built-in closed catalog.");
988
+ return { skinId, scheme };
989
+ }
666
990
  function renderIndexHtml(pageTitle, document, options) {
667
991
  const selectedLocale = options.locale || document.defaultLocale;
668
992
  const locales = normalizeLocales(document, selectedLocale);
@@ -672,7 +996,7 @@ function renderIndexHtml(pageTitle, document, options) {
672
996
  const symbols = document.symbols.map((symbol) => renderSymbol(symbol, document, locales, selectedLocale)).join("");
673
997
  return [
674
998
  "<!doctype html>",
675
- `<html lang="${escapeHtml(selectedLocale)}">`,
999
+ `<html lang="${escapeHtml(selectedLocale)}" ${renderDefaultThemeRootAttributes(resolveThemeSelection(options))}>`,
676
1000
  "<head>",
677
1001
  "<meta charset=\"utf-8\">",
678
1002
  "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
@@ -696,6 +1020,82 @@ function renderIndexHtml(pageTitle, document, options) {
696
1020
  "</html>"
697
1021
  ].join("");
698
1022
  }
1023
+ /**
1024
+ * @lang zh-CN
1025
+ * 渲染一个带稳定 identity 的 UI 文本节点;译文先按纯文本解析,再进行 HTML 转义。
1026
+ *
1027
+ * @lang en
1028
+ * Renders a UI text node with a stable identity; translation is resolved as plain text before HTML escaping.
1029
+ */
1030
+ function renderProjectUiMessage(portalContext, messageId, values = {}, fallback = "") {
1031
+ if (!portalContext.uiLocaleAdoption) {
1032
+ return escapeHtml(fallback);
1033
+ }
1034
+ const valueAttribute = Object.keys(values).length > 0
1035
+ ? ` data-hia-ui-values="${escapeHtml(JSON.stringify(values))}"`
1036
+ : "";
1037
+ const text = resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, messageId, values);
1038
+ return `<span data-hia-ui-message="${escapeHtml(messageId)}"${valueAttribute}>${escapeHtml(text)}</span>`;
1039
+ }
1040
+ /** @lang zh-CN 解析 attribute/dynamic state 使用的 UI 纯文本,并为 legacy surface 保留既有 fallback。 @lang en Resolves UI plain text for attributes/dynamic state while retaining the existing fallback for legacy surfaces. */
1041
+ function resolveProjectUiPlainText(portalContext, messageId, values = {}, fallback = "") {
1042
+ return portalContext.uiLocaleAdoption
1043
+ ? resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, messageId, values)
1044
+ : fallback;
1045
+ }
1046
+ /** @lang zh-CN 为共享 legacy/adopted renderer helper 选择带 marker 的消息或原有文本。 @lang en Selects a marked message or original text for renderer helpers shared by legacy and adopted surfaces. */
1047
+ function renderOptionalProjectUiMessage(portalContext, messageId, fallback, values = {}) {
1048
+ return portalContext
1049
+ ? renderProjectUiMessage(portalContext, messageId, values, fallback)
1050
+ : escapeHtml(fallback);
1051
+ }
1052
+ /**
1053
+ * @lang zh-CN
1054
+ * 为不能包裹 span 的元素生成稳定 message marker,并返回已转义文本。
1055
+ *
1056
+ * @lang en
1057
+ * Creates a stable message marker for elements that cannot wrap a span and returns escaped text.
1058
+ */
1059
+ function renderProjectUiMarkedText(portalContext, messageId, values = {}) {
1060
+ if (!portalContext.uiLocaleAdoption) {
1061
+ return { attributes: "", text: "" };
1062
+ }
1063
+ const valueAttribute = Object.keys(values).length > 0
1064
+ ? ` data-hia-ui-values="${escapeHtml(JSON.stringify(values))}"`
1065
+ : "";
1066
+ return {
1067
+ attributes: ` data-hia-ui-message="${escapeHtml(messageId)}"${valueAttribute}`,
1068
+ text: escapeHtml(resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, messageId, values))
1069
+ };
1070
+ }
1071
+ /**
1072
+ * @lang zh-CN 复制 context 并只替换显式 UI locale,供 no-script locale 页面复用同一已验证 bundle/report。
1073
+ * @lang en Copies a context while replacing only its explicit UI locale so no-script locale pages reuse one validated bundle/report.
1074
+ */
1075
+ function withProjectUiLocale(portalContext, uiLocale) {
1076
+ return {
1077
+ ...portalContext,
1078
+ uiLocale,
1079
+ labels: getDocumentationPortalLabels(uiLocale)
1080
+ };
1081
+ }
1082
+ /** @lang zh-CN 渲染彼此独立的 UI/content locale 原生控件。 @lang en Renders independent native UI/content-locale controls. */
1083
+ function renderProjectLocaleControls(contentLocales, selectedContentLocale, portalContext) {
1084
+ if (!portalContext.uiLocaleAdoption) {
1085
+ return renderLocaleControl(contentLocales, selectedContentLocale);
1086
+ }
1087
+ const uiOptions = DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES.map((locale) => (`<option value="${escapeHtml(locale)}"${locale === portalContext.uiLocale ? " selected" : ""}>${escapeHtml(locale)}</option>`)).join("");
1088
+ const contentOptions = contentLocales.map((locale) => (`<option value="${escapeHtml(locale)}"${locale === selectedContentLocale ? " selected" : ""}>${escapeHtml(locale)}</option>`)).join("");
1089
+ return [
1090
+ "<div class=\"hia-language-switch hia-project-language-switch\">",
1091
+ `<label for="hia-ui-locale-control">${renderProjectUiMessage(portalContext, "portal.locale.uilabel")}</label>`,
1092
+ `<select id="hia-ui-locale-control" data-hia-ui-locale-control data-hia-ui-aria="portal.locale.uiaccessible" aria-label="${escapeHtml(resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, "portal.locale.uiaccessible"))}">${uiOptions}</select>`,
1093
+ `<label for="hia-locale-control">${renderProjectUiMessage(portalContext, "portal.locale.contentlabel")}</label>`,
1094
+ `<select id="hia-locale-control" data-hia-locale-control data-hia-ui-aria="portal.locale.contentaccessible" aria-label="${escapeHtml(resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, "portal.locale.contentaccessible"))}">${contentOptions}</select>`,
1095
+ "</div>"
1096
+ ].join("");
1097
+ }
1098
+ /** @lang zh-CN 渲染带 no-script theme 默认和可见选择器的 split-site 应用壳。 @lang en Renders the split-site shell with a no-script theme default and visible selectors. */
699
1099
  function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext) {
700
1100
  const projectName = projectInput.project.title ?? projectInput.project.name;
701
1101
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
@@ -704,7 +1104,7 @@ function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalCont
704
1104
  const labels = portalContext.labels;
705
1105
  return [
706
1106
  "<!doctype html>",
707
- `<html lang="${escapeHtml(localeModel.selectedLocale)}">`,
1107
+ `<html lang="${escapeHtml(portalContext.uiLocale)}" ${renderDefaultThemeRootAttributes(portalContext.theme)}>`,
708
1108
  "<head>",
709
1109
  "<meta charset=\"utf-8\">",
710
1110
  "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
@@ -716,72 +1116,228 @@ function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalCont
716
1116
  "<div class=\"hia-shell hia-project-shell hia-project-split-site\">",
717
1117
  "<aside class=\"hia-sidebar\">",
718
1118
  `<h1>${escapeHtml(projectName)}</h1>`,
719
- renderLocaleControl(localeModel.locales, localeModel.selectedLocale),
720
- renderProjectViewControl(views, entryCounts),
721
- renderProjectGeneratedDocumentationBindingProjection(projectInput.generatedDocumentationBindingProjection),
1119
+ renderProjectLocaleControls(localeModel.locales, localeModel.selectedLocale, portalContext),
1120
+ renderProjectThemeControl(portalContext.theme, portalContext),
1121
+ renderProjectViewControl(views, entryCounts, portalContext),
1122
+ renderProjectGeneratedDocumentationBindingProjection(projectInput.generatedDocumentationBindingProjection, portalContext),
722
1123
  [
723
1124
  "<label class=\"hia-project-search\">",
724
- `<span>${escapeHtml(labels.search)}</span>`,
725
- `<input type="search" data-hia-project-search placeholder="${escapeHtml(labels.searchPlaceholder)}">`,
1125
+ `<span>${renderProjectUiMessage(portalContext, "portal.search.label", {}, labels.search)}</span>`,
1126
+ `<input type="search" data-hia-project-search${portalContext.uiLocaleAdoption ? " data-hia-ui-placeholder=\"portal.search.placeholder\" data-hia-ui-aria=\"portal.search.accessible\"" : ""} placeholder="${escapeHtml(resolveProjectUiPlainText(portalContext, "portal.search.placeholder", {}, labels.searchPlaceholder))}" aria-label="${escapeHtml(resolveProjectUiPlainText(portalContext, "portal.search.accessible", {}, labels.search))}">`,
726
1127
  "</label>"
727
1128
  ].join(""),
728
- `<section class="hia-project-summary hia-project-hierarchy"><h2>${escapeHtml(labels.hierarchy)}</h2><div data-hia-project-tree><p class="hia-project-loading">${escapeHtml(labels.loading)}</p></div></section>`,
729
- `<button type="button" class="hia-project-secondary-action" data-hia-project-relations>${escapeHtml(labels.relations)}</button>`,
1129
+ `<section class="hia-project-summary hia-project-hierarchy"><h2>${renderProjectUiMessage(portalContext, "portal.navigation.hierarchy", {}, labels.hierarchy)}</h2><div data-hia-project-tree><p class="hia-project-loading" role="status">${renderProjectUiMessage(portalContext, "portal.navigation.loading", {}, labels.loading)}</p></div></section>`,
1130
+ `<button type="button" class="hia-project-secondary-action" data-hia-project-relations>${renderProjectUiMessage(portalContext, "portal.navigation.relations", {}, labels.relations)}</button>`,
730
1131
  "</aside>",
731
- `<main class="hia-main hia-project-main" data-hia-project-content><p class="hia-project-empty">${escapeHtml(labels.select)}</p></main>`,
1132
+ `<main class="hia-main hia-project-main" data-hia-project-content><p class="hia-project-empty">${renderProjectUiMessage(portalContext, "portal.navigation.select", {}, labels.select)}</p><noscript><p class="hia-noscript-notice"><a href="pages/index.html">${renderProjectUiMessage(portalContext, "portal.navigation.noscriptlink", {}, "No-script page index / 无脚本页面索引")}</a></p></noscript></main>`,
732
1133
  "</div>",
733
1134
  `<script src="${escapeHtml(DEFAULT_THEME_JS_PATH)}"></script>`,
734
- renderProjectSplitSiteScript(labels.requiresServer, labels.open, portalContext.informationArchitecture?.loadingStrategy ?? "lazy", labels.relations),
1135
+ renderProjectSplitSiteScript(portalContext, portalContext.informationArchitecture?.loadingStrategy ?? "lazy"),
735
1136
  "</body>",
736
1137
  "</html>"
737
1138
  ].join("");
738
1139
  }
739
1140
  /**
740
- * 生成 split-site 与 single-page 共用的 fetch 源码加载逻辑。
1141
+ * @lang zh-CN 渲染独立 no-script 多页索引;它不内嵌 topic 正文,也不依赖 dynamic navigation shard。
1142
+ * @lang en Renders the standalone no-script multi-page index without embedding topic bodies or depending on dynamic navigation shards.
1143
+ */
1144
+ function renderProjectNoScriptIndexHtml(pageTitle, projectInput, selectedContentLocale, portalContext, localizedRoute = false) {
1145
+ const projectName = projectInput.project.title ?? projectInput.project.name;
1146
+ const links = [...projectInput.entries].sort(compareProjectNavigationEntries).map((entry) => {
1147
+ // <lang><zh-CN>page path 是由固定 `pages/` 前缀与 opaque basename 组成,不需要平台路径 API。</zh-CN><en>The page path consists of the fixed `pages/` prefix and an opaque basename, so no platform path API is needed.</en></lang>
1148
+ const relativePage = `./${createProjectNoScriptPagePath(entry.id).slice("pages/".length)}`;
1149
+ return `<li><a href="${escapeHtml(relativePage)}">${escapeHtml(entry.name)}</a> <small>${escapeHtml(entry.kind)} / ${escapeHtml(formatProjectViewLabel(entry.view))}</small></li>`;
1150
+ }).join("");
1151
+ const documentLocale = portalContext.uiLocaleAdoption ? portalContext.uiLocale : selectedContentLocale;
1152
+ const interactivePath = localizedRoute ? "../../index.html" : "../index.html";
1153
+ const stylesheetPath = localizedRoute ? "../../assets/hia-default.css" : "../assets/hia-default.css";
1154
+ const alternateLinks = portalContext.uiLocaleAdoption
1155
+ ? DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES
1156
+ .filter((locale) => locale !== portalContext.uiLocale)
1157
+ .map((locale) => {
1158
+ const path = localizedRoute ? `../${locale}/index.html` : `./${locale}/index.html`;
1159
+ const label = resolveProjectUiPlainText(portalContext, "portal.noscript.localealternate", { locale }, locale);
1160
+ return `<a href="${escapeHtml(path)}" lang="${escapeHtml(locale)}">${escapeHtml(label)}</a>`;
1161
+ })
1162
+ .join(" · ")
1163
+ : "";
1164
+ const skinMessageId = `portal.theme.skin.${portalContext.theme.skinId.slice("portal.".length)}`;
1165
+ const schemeMessageId = `portal.theme.scheme.${portalContext.theme.scheme}`;
1166
+ return [
1167
+ "<!doctype html>",
1168
+ `<html lang="${escapeHtml(documentLocale)}" ${renderDefaultThemeRootAttributes(portalContext.theme)}>`,
1169
+ "<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
1170
+ `<title>${escapeHtml(pageTitle)} - ${escapeHtml(resolveProjectUiPlainText(portalContext, "portal.noscript.indextitle", {}, "No-script index"))}</title>`,
1171
+ `<link rel="icon" href="data:,"><link rel="stylesheet" href="${escapeHtml(stylesheetPath)}"></head>`,
1172
+ "<body><div class=\"hia-shell hia-project-shell\"><aside class=\"hia-sidebar\">",
1173
+ `<h1>${escapeHtml(projectName)}</h1><p><a href="${escapeHtml(interactivePath)}">${renderProjectUiMessage(portalContext, "portal.noscript.interactive", {}, "Interactive site / 交互站点")}</a></p>`,
1174
+ alternateLinks ? `<p>${alternateLinks}</p>` : "",
1175
+ `<p>${renderProjectUiMessage(portalContext, "portal.theme.skinlabel", {}, "Skin")}:${renderProjectUiMessage(portalContext, skinMessageId, {}, getPortalThemeSkinLabel(portalContext.theme.skinId))} · ${renderProjectUiMessage(portalContext, "portal.theme.schemelabel", {}, "Scheme")}:${renderProjectUiMessage(portalContext, schemeMessageId, {}, getPortalThemeSchemeLabel(portalContext.theme.scheme))}</p>`,
1176
+ `</aside><main class="hia-main hia-project-main"><h2>${renderProjectUiMessage(portalContext, "portal.noscript.pagesheading", {}, "Documentation pages / 文档页面")}</h2>`,
1177
+ `<nav aria-label="${escapeHtml(resolveProjectUiPlainText(portalContext, "portal.noscript.pagesaccessible", {}, "Documentation pages"))}"${portalContext.uiLocaleAdoption ? " data-hia-ui-aria=\"portal.noscript.pagesaccessible\"" : ""}><ul>${links}</ul></nav>`,
1178
+ "</main></div></body></html>"
1179
+ ].join("");
1180
+ }
1181
+ /**
1182
+ * @lang zh-CN 渲染一个可直接打开、无脚本仍可使用 native disclosure 阅读的 topic 页面。
1183
+ * @lang en Renders a directly addressable topic page readable through native disclosure without JavaScript.
1184
+ */
1185
+ function renderProjectNoScriptEntryHtml(pageTitle, entry, projectInput, localeModel, portalContext, localizedRoute = false) {
1186
+ const informationArchitecture = portalContext.informationArchitecture;
1187
+ const article = informationArchitecture
1188
+ ? renderProjectSemanticTopic(entry, projectInput, localeModel.locales, localeModel.selectedLocale, portalContext, informationArchitecture.memberPlacement === "with-parent")
1189
+ : renderProjectEntry(entry, localeModel.locales, localeModel.selectedLocale);
1190
+ const documentLocale = portalContext.uiLocaleAdoption ? portalContext.uiLocale : localeModel.selectedLocale;
1191
+ const pageIndexPath = "./index.html";
1192
+ const interactivePath = localizedRoute ? "../../index.html" : "../index.html";
1193
+ const stylesheetPath = localizedRoute ? "../../assets/hia-default.css" : "../assets/hia-default.css";
1194
+ const alternateLinks = portalContext.uiLocaleAdoption
1195
+ ? DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES
1196
+ .filter((locale) => locale !== portalContext.uiLocale)
1197
+ .map((locale) => {
1198
+ const path = localizedRoute
1199
+ ? `../${locale}/${stableProjectArtifactName(entry.id)}.html`
1200
+ : `./${locale}/${stableProjectArtifactName(entry.id)}.html`;
1201
+ const label = resolveProjectUiPlainText(portalContext, "portal.noscript.localealternate", { locale }, locale);
1202
+ return `<a href="${escapeHtml(path)}" lang="${escapeHtml(locale)}">${escapeHtml(label)}</a>`;
1203
+ })
1204
+ .join(" · ")
1205
+ : "";
1206
+ const skinMessageId = `portal.theme.skin.${portalContext.theme.skinId.slice("portal.".length)}`;
1207
+ const schemeMessageId = `portal.theme.scheme.${portalContext.theme.scheme}`;
1208
+ return [
1209
+ "<!doctype html>",
1210
+ `<html lang="${escapeHtml(documentLocale)}" ${renderDefaultThemeRootAttributes(portalContext.theme)}>`,
1211
+ "<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
1212
+ `<title>${escapeHtml(entry.name)} - ${escapeHtml(pageTitle)}</title>`,
1213
+ `<link rel="icon" href="data:,"><link rel="stylesheet" href="${escapeHtml(stylesheetPath)}"></head>`,
1214
+ "<body><div class=\"hia-shell hia-project-shell\"><aside class=\"hia-sidebar\">",
1215
+ `<h1>${escapeHtml(projectInput.project.title ?? projectInput.project.name)}</h1>`,
1216
+ `<p><a href="${pageIndexPath}">${renderProjectUiMessage(portalContext, "portal.noscript.pageindex", {}, "Page index / 页面索引")}</a></p><p><a href="${escapeHtml(interactivePath)}">${renderProjectUiMessage(portalContext, "portal.noscript.interactive", {}, "Interactive site / 交互站点")}</a></p>`,
1217
+ alternateLinks ? `<p>${alternateLinks}</p>` : "",
1218
+ `<p>${renderProjectUiMessage(portalContext, "portal.theme.skinlabel", {}, "Skin")}:${renderProjectUiMessage(portalContext, skinMessageId, {}, getPortalThemeSkinLabel(portalContext.theme.skinId))} · ${renderProjectUiMessage(portalContext, "portal.theme.schemelabel", {}, "Scheme")}:${renderProjectUiMessage(portalContext, schemeMessageId, {}, getPortalThemeSchemeLabel(portalContext.theme.scheme))}</p>`,
1219
+ "</aside><main class=\"hia-main hia-project-main\">",
1220
+ article,
1221
+ "</main></div></body></html>"
1222
+ ].join("");
1223
+ }
1224
+ /**
1225
+ * @lang zh-CN 生成 split-site 与 single-page 共用的受限 fetch reader;默认展开时加载,也保留显式 manual 模式。
1226
+ * @lang en Generates the constrained fetch reader shared by split-site and single-page output, loading on expansion by default while retaining explicit manual mode.
741
1227
  *
742
- * @lang zh-CN 该脚本默认在 details 展开时加载源码,并保留 manual 按钮模式作为显式配置。
743
- * @lang en Generates the shared fetch-source loader for split-site and single-page layouts, loading on details expansion by default while retaining an explicit manual button mode.
1228
+ * @param rootExpression - reader 扫描 `document` 或异步载入的 `contentHost`。Reader scan root: `document` or the asynchronously loaded `contentHost`.
1229
+ * @returns 可直接嵌入 owner script 的确定性 JavaScript 行。Deterministic JavaScript lines embeddable in the owner script.
744
1230
  */
745
1231
  function renderProjectSourceFetchClientLines(rootExpression) {
746
1232
  return [
747
- " async function loadSourceFetch(details) {",
748
- " if (details.dataset.loaded === 'true' || details.dataset.loading === 'true') return;",
749
- " const code = details.querySelector('code');",
750
- " const button = details.querySelector('[data-hia-source-fetch-button]');",
1233
+ " const sourceControllers = new WeakMap();",
1234
+ " const sourceTerminalStates = new Set(['ready', 'empty', 'denied', 'not-found', 'integrity-error', 'network-error', 'aborted']);",
1235
+ " function sourceUiMessage(messageId, fallback, values = {}) {",
1236
+ " return typeof uiMessage === 'function' && typeof config !== 'undefined' && config.ui ? uiMessage(messageId, values, fallback) : fallback;",
1237
+ " }",
1238
+ " function setSourceState(details, state, messageId = '', fallback = '', values = {}) {",
1239
+ " const loadButton = details.querySelector('[data-hia-source-fetch-button]');",
1240
+ " const resetButton = details.querySelector('[data-hia-source-reset]');",
751
1241
  " const status = details.querySelector('[data-hia-source-fetch-status]');",
752
- " details.dataset.loading = 'true';",
753
- " details.setAttribute('aria-busy', 'true');",
1242
+ " details.dataset.hiaSourceState = state;",
1243
+ " details.toggleAttribute('aria-busy', state === 'loading');",
754
1244
  " if (status) {",
755
- " status.hidden = false;",
756
- " status.textContent = 'Loading source / 正在加载源码...';",
1245
+ " status.hidden = state === 'idle';",
1246
+ " if (messageId) status.dataset.hiaUiMessage = messageId; else delete status.dataset.hiaUiMessage;",
1247
+ " if (Object.keys(values).length > 0) status.dataset.hiaUiValues = JSON.stringify(values); else delete status.dataset.hiaUiValues;",
1248
+ " status.textContent = messageId ? sourceUiMessage(messageId, fallback, values) : '';",
757
1249
  " }",
1250
+ " if (loadButton) loadButton.hidden = state !== 'idle';",
1251
+ " if (resetButton) {",
1252
+ " resetButton.hidden = state === 'idle';",
1253
+ " const resetMessageId = state === 'loading' ? 'portal.source.cancel' : 'portal.source.reset';",
1254
+ " resetButton.dataset.hiaUiMessage = resetMessageId;",
1255
+ " resetButton.textContent = sourceUiMessage(resetMessageId, state === 'loading' ? 'Cancel' : 'Reset');",
1256
+ " }",
1257
+ " }",
1258
+ " function sourceFailureState(response) {",
1259
+ " if (response.status === 401 || response.status === 403) return 'denied';",
1260
+ " if (response.status === 404) return 'not-found';",
1261
+ " return 'network-error';",
1262
+ " }",
1263
+ " function digestBase64(buffer) {",
1264
+ " return btoa(String.fromCharCode(...new Uint8Array(buffer)));",
1265
+ " }",
1266
+ " async function loadSourceFetch(details) {",
1267
+ " if ((details.dataset.hiaSourceState || 'idle') !== 'idle') return;",
1268
+ " const code = details.querySelector('code');",
1269
+ " const controller = new AbortController();",
1270
+ " const timeoutMs = Math.max(100, Number(details.dataset.hiaSourceTimeout || 10000));",
1271
+ " const timeout = setTimeout(() => controller.abort(), timeoutMs);",
1272
+ " sourceControllers.set(details, controller);",
1273
+ " setSourceState(details, 'loading', 'portal.source.status.loading', 'Loading source...');",
758
1274
  " try {",
759
- " const response = await fetch(details.dataset.hiaSourceFetch || '', { credentials: 'omit' });",
760
- " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
761
- " const lines = (await response.text()).split(/\\r?\\n/u);",
762
- " const start = Math.max(1, Number(details.dataset.hiaSourceStart || 1));",
1275
+ " /* <lang><zh-CN>只允许文档站同源且无 userinfo 的 content-addressed endpoint。</zh-CN><en>Allow only a same-origin content-addressed endpoint without userinfo.</en></lang> */",
1276
+ " const target = new URL(details.dataset.hiaSourceFetch || '', document.baseURI);",
1277
+ " if (target.origin !== location.origin || target.username || target.password) {",
1278
+ " setSourceState(details, 'denied', 'portal.source.status.denied', 'Source request denied.');",
1279
+ " return;",
1280
+ " }",
1281
+ " /* <lang><zh-CN>请求固定无凭据、同源且拒绝 redirect;signal 同时承担取消与超时。</zh-CN><en>The request is credential-free, same-origin, and redirect-denying; the signal covers cancellation and timeout.</en></lang> */",
1282
+ " const response = await fetch(target, { cache: 'default', credentials: 'omit', mode: 'same-origin', redirect: 'error', signal: controller.signal });",
1283
+ " if (!response.ok) {",
1284
+ " const state = sourceFailureState(response);",
1285
+ " const detail = `${response.status} ${response.statusText}`;",
1286
+ " setSourceState(details, state, 'portal.source.status.failed', `Source load failed: ${detail}`, { detail });",
1287
+ " return;",
1288
+ " }",
1289
+ " /* <lang><zh-CN>先验证字节数与 SHA-384,再把公开 asset 解码为不可执行纯文本。</zh-CN><en>Verify byte length and SHA-384 before decoding the public asset as non-executable plain text.</en></lang> */",
1290
+ " const bytes = await response.arrayBuffer();",
1291
+ " const maxBytes = Math.max(1, Number(details.dataset.hiaSourceMaxBytes || 1048576));",
1292
+ " const expectedBytes = Number(details.dataset.hiaSourceByteLength || 0);",
1293
+ " if (bytes.byteLength > maxBytes || (expectedBytes >= 0 && bytes.byteLength !== expectedBytes)) {",
1294
+ " setSourceState(details, 'integrity-error', 'portal.source.status.size', 'Source size verification failed.');",
1295
+ " return;",
1296
+ " }",
1297
+ " const digest = await crypto.subtle.digest('SHA-384', bytes);",
1298
+ " if (`sha384-${digestBase64(digest)}` !== details.dataset.hiaSourceIntegrity) {",
1299
+ " setSourceState(details, 'integrity-error', 'portal.source.status.integrity', 'Source integrity verification failed.');",
1300
+ " return;",
1301
+ " }",
1302
+ " /* <lang><zh-CN>非法 UTF-8 表示 asset 违反 text contract,归入 integrity-error。</zh-CN><en>Invalid UTF-8 violates the text-asset contract and maps to integrity-error.</en></lang> */",
1303
+ " let text;",
1304
+ " try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }",
1305
+ " catch { setSourceState(details, 'integrity-error', 'portal.source.status.decode', 'Source text decoding failed.'); return; }",
1306
+ " if (text.length === 0) {",
1307
+ " if (code) code.textContent = '';",
1308
+ " setSourceState(details, 'empty', 'portal.source.status.empty', 'Source asset is empty.');",
1309
+ " return;",
1310
+ " }",
1311
+ " /* <lang><zh-CN>只投影配置允许的行数,绝不执行或加入搜索索引。</zh-CN><en>Project only the configured line limit, never executing or search-indexing the body.</en></lang> */",
1312
+ " const lines = text.split(/\\r?\\n/u);",
763
1313
  " const maxLines = Math.max(1, Number(details.dataset.hiaSourceMaxLines || 400));",
764
- " const declaredEnd = Number(details.dataset.hiaSourceEnd || 0);",
765
- " const end = declaredEnd >= start ? Math.min(declaredEnd, start + maxLines - 1) : start + maxLines - 1;",
766
- " if (code) code.textContent = lines.slice(start - 1, end).join('\\n');",
767
- " details.dataset.loaded = 'true';",
768
- " if (button) button.hidden = true;",
769
- " if (status) status.hidden = true;",
1314
+ " if (code) code.textContent = lines.slice(0, maxLines).join('\\n');",
1315
+ " setSourceState(details, 'ready', 'portal.source.status.ready', 'Source ready.');",
770
1316
  " } catch (error) {",
771
- " if (status) status.textContent = `Source load failed / 源码加载失败: ${String(error?.message || error)}`;",
772
- " if (button) {",
773
- " button.hidden = false;",
774
- " button.textContent = 'Retry source / 重试加载源码';",
775
- " }",
1317
+ " const aborted = error?.name === 'AbortError';",
1318
+ " const detail = String(error?.message || error);",
1319
+ " setSourceState(details, aborted ? 'aborted' : 'network-error', aborted ? 'portal.source.status.aborted' : 'portal.source.status.failed', aborted ? 'Source load aborted.' : `Source load failed: ${detail}`, aborted ? {} : { detail });",
776
1320
  " } finally {",
777
- " delete details.dataset.loading;",
778
- " details.removeAttribute('aria-busy');",
1321
+ " clearTimeout(timeout);",
1322
+ " sourceControllers.delete(details);",
779
1323
  " }",
780
1324
  " }",
1325
+ " /* <lang><zh-CN>终态必须显式 reset 回 idle;loading 状态的同一操作只负责取消。</zh-CN><en>Terminal states require an explicit reset to idle; the same action only cancels while loading.</en></lang> */",
1326
+ " function resetSourceFetch(details) {",
1327
+ " const state = details.dataset.hiaSourceState || 'idle';",
1328
+ " if (state === 'loading') { sourceControllers.get(details)?.abort(); return; }",
1329
+ " if (!sourceTerminalStates.has(state)) return;",
1330
+ " const code = details.querySelector('code');",
1331
+ " if (code) code.textContent = '';",
1332
+ " setSourceState(details, 'idle');",
1333
+ " }",
781
1334
  ` function bindSourceFetch(root = ${rootExpression}) {`,
782
1335
  " for (const details of root?.querySelectorAll('details[data-hia-source-fetch]') || []) {",
783
1336
  " const button = details.querySelector('[data-hia-source-fetch-button]');",
1337
+ " const resetButton = details.querySelector('[data-hia-source-reset]');",
784
1338
  " if (button) button.addEventListener('click', () => loadSourceFetch(details));",
1339
+ " if (resetButton) resetButton.addEventListener('click', () => resetSourceFetch(details));",
1340
+ " setSourceState(details, details.dataset.hiaSourceState || 'idle');",
785
1341
  " if (details.dataset.hiaSourceFetchTrigger !== 'manual') {",
786
1342
  " details.addEventListener('toggle', () => {",
787
1343
  " if (details.open) void loadSourceFetch(details);",
@@ -792,30 +1348,63 @@ function renderProjectSourceFetchClientLines(rootExpression) {
792
1348
  " }"
793
1349
  ];
794
1350
  }
795
- function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStrategy, relationsLabel) {
1351
+ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1352
+ // <lang><zh-CN>只有 adopted surface 嵌入 public plain-text bundle;metadata-only report 仍不含译文。</zh-CN><en>Only adopted surfaces embed the public plain-text bundle; the metadata-only report still contains no translations.</en></lang>
1353
+ const uiConfig = portalContext.uiLocaleAdoption
1354
+ ? {
1355
+ bundles: portalContext.uiLocaleAdoption.bundles,
1356
+ initialLocale: portalContext.uiLocale,
1357
+ supportedLocales: DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES
1358
+ }
1359
+ : null;
1360
+ const fileProtocolMessage = resolveProjectUiPlainText(portalContext, "portal.navigation.requiresserver", {}, portalContext.labels.requiresServer);
796
1361
  return [
797
1362
  "<script>",
798
1363
  "(() => {",
799
- ` const config = { navigation: 'navigation/root.json', search: 'search/index.json', relations: 'relations/project.json', loadingStrategy: ${JSON.stringify(loadingStrategy)}, eagerContent: 'content/eager.json' };`,
1364
+ ` const config = { navigation: 'navigation/root.json', search: 'search/index.json', relations: 'relations/project.json', loadingStrategy: ${JSON.stringify(loadingStrategy)}, eagerContent: 'content/eager.json', ui: ${JSON.stringify(uiConfig)} };`,
800
1365
  " const treeHost = document.querySelector('[data-hia-project-tree]');",
801
1366
  " const contentHost = document.querySelector('[data-hia-project-content]');",
802
1367
  " const search = document.querySelector('[data-hia-project-search]');",
803
- " const locale = document.querySelector('[data-hia-locale-control]');",
1368
+ " const contentLocale = document.querySelector('[data-hia-locale-control]');",
1369
+ " const uiLocale = document.querySelector('[data-hia-ui-locale-control]');",
804
1370
  " const viewButtons = Array.from(document.querySelectorAll('[data-hia-project-view]'));",
805
1371
  " let rootNodes = [];",
806
1372
  " let searchEntries = null;",
807
1373
  " let eagerFragments = null;",
808
1374
  " let activeView = 'all';",
1375
+ " function uiMessage(messageId, values = {}, fallback = messageId) {",
1376
+ " const selected = String(uiLocale?.value || config.ui?.initialLocale || document.documentElement.lang || 'en');",
1377
+ " const template = config.ui?.bundles?.[selected]?.[messageId] || fallback;",
1378
+ " return template.replace(/\\{([A-Za-z][A-Za-z0-9_]*)\\}/gu, (_match, name) => String(values[name] ?? `{${name}}`));",
1379
+ " }",
1380
+ " function readUiValues(node) {",
1381
+ " try { return JSON.parse(node.getAttribute('data-hia-ui-values') || '{}'); } catch { return {}; }",
1382
+ " }",
1383
+ " function applyUiLocale(root = document) {",
1384
+ " if (!config.ui) return;",
1385
+ " const selected = String(uiLocale?.value || config.ui.initialLocale);",
1386
+ " if (!config.ui.supportedLocales.includes(selected)) return;",
1387
+ " document.documentElement.lang = selected;",
1388
+ " for (const node of root.querySelectorAll('[data-hia-ui-message]')) node.textContent = uiMessage(node.getAttribute('data-hia-ui-message'), readUiValues(node));",
1389
+ " for (const node of root.querySelectorAll('[data-hia-ui-placeholder]')) node.setAttribute('placeholder', uiMessage(node.getAttribute('data-hia-ui-placeholder')));",
1390
+ " for (const node of root.querySelectorAll('[data-hia-ui-aria]')) node.setAttribute('aria-label', uiMessage(node.getAttribute('data-hia-ui-aria')));",
1391
+ " try { localStorage.setItem('hia-doc-portal-ui-locale', selected); } catch {}",
1392
+ " document.dispatchEvent(new CustomEvent('hia:ui-locale-change', { detail: { uiLocale: selected } }));",
1393
+ " }",
809
1394
  " async function readJson(target) {",
810
1395
  " const response = await fetch(target, { credentials: 'omit' });",
811
1396
  " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
812
1397
  " return response.json();",
813
1398
  " }",
814
1399
  " function showLoadError(error) {",
815
- ` const hint = location.protocol === 'file:' ? ${JSON.stringify(fileProtocolMessage)} : String(error?.message || error);`,
1400
+ ` const detail = location.protocol === 'file:' ? ${JSON.stringify(fileProtocolMessage)} : String(error?.message || error);`,
1401
+ " const hint = location.protocol === 'file:' ? detail : uiMessage('portal.navigation.loaderror', { detail }, detail);",
816
1402
  " if (contentHost) contentHost.innerHTML = '';",
817
1403
  " const message = document.createElement('p');",
818
1404
  " message.className = 'hia-project-load-error';",
1405
+ " message.setAttribute('role', 'status');",
1406
+ " message.dataset.hiaUiMessage = location.protocol === 'file:' ? 'portal.navigation.requiresserver' : 'portal.navigation.loaderror';",
1407
+ " if (location.protocol !== 'file:') message.dataset.hiaUiValues = JSON.stringify({ detail });",
819
1408
  " message.textContent = hint;",
820
1409
  " (contentHost || treeHost)?.append(message);",
821
1410
  " }",
@@ -845,7 +1434,8 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
845
1434
  " const openButton = document.createElement('button');",
846
1435
  " openButton.type = 'button';",
847
1436
  " openButton.className = 'hia-project-entry-link hia-project-tree-open';",
848
- ` openButton.textContent = ${JSON.stringify(openLabel)};`,
1437
+ " openButton.dataset.hiaUiMessage = 'portal.navigation.open';",
1438
+ ` openButton.textContent = uiMessage('portal.navigation.open', {}, ${JSON.stringify(portalContext.labels.open)});`,
849
1439
  " openButton.addEventListener('click', (event) => {",
850
1440
  " event.preventDefault();",
851
1441
  " event.stopPropagation();",
@@ -863,7 +1453,9 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
863
1453
  " details.dataset.loaded = 'true';",
864
1454
  " const loading = document.createElement('p');",
865
1455
  " loading.className = 'hia-project-loading';",
866
- " loading.textContent = '...';",
1456
+ " loading.setAttribute('role', 'status');",
1457
+ " loading.dataset.hiaUiMessage = 'portal.navigation.loading';",
1458
+ ` loading.textContent = uiMessage('portal.navigation.loading', {}, ${JSON.stringify(portalContext.labels.loading)});`,
867
1459
  " details.append(loading);",
868
1460
  " try {",
869
1461
  " const shard = await readJson(node.childrenPath);",
@@ -891,11 +1483,16 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
891
1483
  " function renderRoot() {",
892
1484
  " if (!treeHost) return;",
893
1485
  " treeHost.innerHTML = '';",
894
- " treeHost.append(createTreeList(rootNodes));",
1486
+ " if (rootNodes.length > 0) { treeHost.append(createTreeList(rootNodes)); return; }",
1487
+ " /* <lang><zh-CN>空项目仍生成带稳定 message identity 的可翻译状态。</zh-CN><en>An empty project still renders a translatable state with a stable message identity.</en></lang> */",
1488
+ " const empty = document.createElement('p');",
1489
+ " empty.className = 'hia-project-empty';",
1490
+ " empty.dataset.hiaUiMessage = 'portal.common.noentries';",
1491
+ " empty.textContent = uiMessage('portal.common.noentries', {}, 'No project documentation entries.');",
1492
+ " treeHost.append(empty);",
895
1493
  " }",
896
- " function applyLocale() {",
897
- " const selected = String(locale?.value || document.documentElement.lang || 'und');",
898
- " document.documentElement.lang = selected;",
1494
+ " function applyContentLocale() {",
1495
+ " const selected = String(contentLocale?.value || 'und');",
899
1496
  " for (const block of document.querySelectorAll('[data-hia-locale]')) {",
900
1497
  " block.hidden = block.getAttribute('data-hia-locale') !== selected;",
901
1498
  " }",
@@ -930,11 +1527,12 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
930
1527
  " }",
931
1528
  " async function loadEntry(entry, updateHash) {",
932
1529
  " if (!contentHost) return;",
933
- " contentHost.innerHTML = '<p class=\"hia-project-loading\">...</p>';",
1530
+ ` contentHost.innerHTML = \`<p class="hia-project-loading" role="status" data-hia-ui-message="portal.navigation.loading">\${uiMessage('portal.navigation.loading', {}, ${JSON.stringify(portalContext.labels.loading)})}</p>\`;`,
934
1531
  " try {",
935
1532
  " const contentPath = entry.presentationPath || entry.contentPath;",
936
1533
  " contentHost.innerHTML = await readFragment(contentPath);",
937
- " applyLocale();",
1534
+ " applyContentLocale();",
1535
+ " applyUiLocale(contentHost);",
938
1536
  " bindSourceFetch();",
939
1537
  " const anchor = entry.memberAnchor || entry.entryId || entry.id;",
940
1538
  " const target = Array.from(contentHost.querySelectorAll('[id]')).find((item) => item.id === anchor);",
@@ -960,7 +1558,15 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
960
1558
  " if (!treeHost) return;",
961
1559
  " treeHost.innerHTML = '';",
962
1560
  " const nodes = matches.map((entry) => ({ id: entry.id, label: `${entry.name} · ${entry.kind}`, entryId: entry.id, contentPath: entry.contentPath, presentationPath: entry.presentationPath, memberAnchor: entry.memberAnchor, views: [entry.view], entryCount: 1 }));",
963
- " treeHost.append(createTreeList(nodes));",
1561
+ " if (nodes.length > 0) { treeHost.append(createTreeList(nodes)); return; }",
1562
+ " /* <lang><zh-CN>筛选空结果使用 polite status,同时保留独立的 message identity。</zh-CN><en>An empty filter result uses a polite status while retaining its own message identity.</en></lang> */",
1563
+ " const empty = document.createElement('p');",
1564
+ " empty.className = 'hia-project-empty';",
1565
+ " empty.setAttribute('role', 'status');",
1566
+ " empty.setAttribute('aria-live', 'polite');",
1567
+ " empty.dataset.hiaUiMessage = 'portal.common.nomatches';",
1568
+ " empty.textContent = uiMessage('portal.common.nomatches', {}, 'No entries match the current filters.');",
1569
+ " treeHost.append(empty);",
964
1570
  " } catch (error) { showLoadError(error); }",
965
1571
  " }",
966
1572
  " for (const button of viewButtons) {",
@@ -971,7 +1577,8 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
971
1577
  " });",
972
1578
  " }",
973
1579
  " search?.addEventListener('input', runSearch);",
974
- " locale?.addEventListener('change', applyLocale);",
1580
+ " contentLocale?.addEventListener('change', applyContentLocale);",
1581
+ " uiLocale?.addEventListener('change', () => applyUiLocale());",
975
1582
  " document.querySelector('[data-hia-project-relations]')?.addEventListener('click', async () => {",
976
1583
  " try {",
977
1584
  " const graph = await readJson(config.relations);",
@@ -980,9 +1587,12 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
980
1587
  " const article = document.createElement('article');",
981
1588
  " article.className = 'hia-symbol';",
982
1589
  " const heading = document.createElement('h2');",
983
- ` heading.textContent = ${JSON.stringify(relationsLabel)};`,
1590
+ " heading.dataset.hiaUiMessage = 'portal.navigation.relations';",
1591
+ ` heading.textContent = uiMessage('portal.navigation.relations', {}, ${JSON.stringify(portalContext.labels.relations)});`,
984
1592
  " const summary = document.createElement('p');",
985
- " summary.textContent = `${graph.nodeCount || 0} node(s), ${graph.relationCount || 0} relation(s).`;",
1593
+ " summary.dataset.hiaUiMessage = 'portal.navigation.relationsummary';",
1594
+ " summary.dataset.hiaUiValues = JSON.stringify({ nodes: graph.nodeCount || 0, relations: graph.relationCount || 0 });",
1595
+ " summary.textContent = uiMessage('portal.navigation.relationsummary', { nodes: graph.nodeCount || 0, relations: graph.relationCount || 0 }, `${graph.nodeCount || 0} nodes, ${graph.relationCount || 0} relations`);",
986
1596
  " article.append(heading, summary);",
987
1597
  " contentHost.append(article);",
988
1598
  " } catch (error) { showLoadError(error); }",
@@ -996,12 +1606,20 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStr
996
1606
  " if (entry) loadEntry({ ...entry, entryId: entry.id }, false);",
997
1607
  " });",
998
1608
  " }).catch(showLoadError);",
1609
+ " if (config.ui && uiLocale) {",
1610
+ " try {",
1611
+ " const saved = localStorage.getItem('hia-doc-portal-ui-locale');",
1612
+ " if (saved && config.ui.supportedLocales.includes(saved)) uiLocale.value = saved;",
1613
+ " } catch {}",
1614
+ " }",
1615
+ " applyContentLocale();",
1616
+ " applyUiLocale();",
999
1617
  " viewButtons.find((button) => button.dataset.hiaProjectView === 'all')?.setAttribute('aria-pressed', 'true');",
1000
1618
  "})();",
1001
1619
  "</script>"
1002
1620
  ].join("");
1003
1621
  }
1004
- function renderProjectIndexHtml(pageTitle, projectInput, options) {
1622
+ function renderProjectIndexHtml(pageTitle, projectInput, options, portalContext) {
1005
1623
  const projectName = projectInput.project.title ?? projectInput.project.name;
1006
1624
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
1007
1625
  const views = collectProjectViews(projectInput.entries);
@@ -1022,7 +1640,7 @@ function renderProjectIndexHtml(pageTitle, projectInput, options) {
1022
1640
  const diagnostics = renderProjectDiagnostics(projectInput.diagnostics ?? []);
1023
1641
  return [
1024
1642
  "<!doctype html>",
1025
- `<html lang="${escapeHtml(localeModel.selectedLocale)}">`,
1643
+ `<html lang="${escapeHtml(localeModel.selectedLocale)}" ${renderDefaultThemeRootAttributes(portalContext.theme)}>`,
1026
1644
  "<head>",
1027
1645
  "<meta charset=\"utf-8\">",
1028
1646
  "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
@@ -1035,6 +1653,7 @@ function renderProjectIndexHtml(pageTitle, projectInput, options) {
1035
1653
  "<aside class=\"hia-sidebar\">",
1036
1654
  `<h1>${escapeHtml(projectName)}</h1>`,
1037
1655
  renderLocaleControl(localeModel.locales, localeModel.selectedLocale),
1656
+ renderProjectThemeControl(portalContext.theme),
1038
1657
  renderProjectViewControl(views, entryCounts),
1039
1658
  renderProjectSearchControl(),
1040
1659
  renderProjectHierarchy(navigationTree),
@@ -1058,9 +1677,9 @@ function renderProjectIndexHtml(pageTitle, projectInput, options) {
1058
1677
  "</html>"
1059
1678
  ].join("");
1060
1679
  }
1061
- function renderProjectViewControl(views, entryCounts) {
1680
+ function renderProjectViewControl(views, entryCounts, portalContext) {
1062
1681
  const buttons = views
1063
- .map((view) => `<button type="button" class="hia-project-view-button" data-hia-project-view="${escapeHtml(view)}">${escapeHtml(formatProjectViewLabel(view))}<span>${escapeHtml(String(entryCounts[view] ?? 0))}</span></button>`)
1682
+ .map((view) => `<button type="button" class="hia-project-view-button" data-hia-project-view="${escapeHtml(view)}">${renderOptionalProjectUiMessage(portalContext, `portal.view.${view}`, formatProjectViewLabel(view))}<span>${escapeHtml(String(entryCounts[view] ?? 0))}</span></button>`)
1064
1683
  .join("");
1065
1684
  return `<div class="hia-project-views">${buttons}</div>`;
1066
1685
  }
@@ -1072,6 +1691,32 @@ function renderProjectSearchControl() {
1072
1691
  "</label>"
1073
1692
  ].join("");
1074
1693
  }
1694
+ /**
1695
+ * @lang zh-CN 渲染可见的 Portal-owned skin/scheme 选择器;无脚本默认由 `<html>` attributes 决定。
1696
+ * @lang en Renders visible Portal-owned skin/scheme selectors; `<html>` attributes own the no-script default.
1697
+ */
1698
+ function renderProjectThemeControl(theme, portalContext) {
1699
+ const skins = PORTAL_THEME_SKIN_IDS.map((skinId) => {
1700
+ const messageId = `portal.theme.skin.${skinId.slice("portal.".length)}`;
1701
+ const marked = portalContext?.uiLocaleAdoption
1702
+ ? renderProjectUiMarkedText(portalContext, messageId, {})
1703
+ : { attributes: "", text: escapeHtml(getPortalThemeSkinLabel(skinId)) };
1704
+ return `<option value="${escapeHtml(skinId)}"${skinId === theme.skinId ? " selected" : ""}${marked.attributes}>${marked.text}</option>`;
1705
+ }).join("");
1706
+ const schemes = PORTAL_THEME_SCHEMES.map((scheme) => {
1707
+ const messageId = `portal.theme.scheme.${scheme}`;
1708
+ const marked = portalContext?.uiLocaleAdoption
1709
+ ? renderProjectUiMarkedText(portalContext, messageId, {})
1710
+ : { attributes: "", text: escapeHtml(getPortalThemeSchemeLabel(scheme)) };
1711
+ return `<option value="${escapeHtml(scheme)}"${scheme === theme.scheme ? " selected" : ""}${marked.attributes}>${marked.text}</option>`;
1712
+ }).join("");
1713
+ return [
1714
+ "<div class=\"hia-theme-switch\" data-hia-theme-control>",
1715
+ `<label>${renderOptionalProjectUiMessage(portalContext, "portal.theme.skinlabel", "Skin / 皮肤")}<select data-hia-skin-control>${skins}</select></label>`,
1716
+ `<label>${renderOptionalProjectUiMessage(portalContext, "portal.theme.schemelabel", "Scheme / 配色")}<select data-hia-scheme-control>${schemes}</select></label>`,
1717
+ "</div>"
1718
+ ].join("");
1719
+ }
1075
1720
  function renderProjectGroupSummary(groups) {
1076
1721
  if (groups.length === 0) {
1077
1722
  return "";
@@ -1133,9 +1778,12 @@ function renderProjectNavItem(entry) {
1133
1778
  "</li>"
1134
1779
  ].join("");
1135
1780
  }
1781
+ /** @lang zh-CN 将项目条目作为完整API参考渲染;本地化正文与单文档复用同一formatter,不将导航摘要当完整正文。 @lang en Renders a project entry as a complete API reference, sharing the document field formatter rather than treating a navigation summary as full prose. */
1136
1782
  function renderProjectEntry(entry, locales, selectedLocale) {
1137
1783
  const signature = entry.signature ? `<pre class="hia-signature"><code>${escapeHtml(entry.signature)}</code></pre>` : "";
1138
1784
  const summary = renderProjectEntrySummary(entry, locales, selectedLocale);
1785
+ // <lang><zh-CN>只排除已作为主描述显示的一个字段,保留同时存在的summary/description及未知扩展字段。</zh-CN><en>Exclude only the one primary field already shown, retaining coexisting summary/description and unknown extensions.</en></lang>
1786
+ const otherFields = renderAdditionalI18nFields(entry, locales, selectedLocale, getPrimaryI18nFieldPath(entry));
1139
1787
  const input = entry.input ? renderProjectEntryInput(entry.input) : "";
1140
1788
  const profile = entry.profile ? renderProjectEntryProfile(entry.profile) : "";
1141
1789
  const hierarchy = entry.hierarchy ? renderProjectEntryHierarchy(entry.hierarchy) : "";
@@ -1151,6 +1799,7 @@ function renderProjectEntry(entry, locales, selectedLocale) {
1151
1799
  `<span class="hia-kind">${escapeHtml(formatProjectViewLabel(entry.view))}</span>`,
1152
1800
  signature,
1153
1801
  summary,
1802
+ otherFields,
1154
1803
  input,
1155
1804
  profile,
1156
1805
  hierarchy,
@@ -1175,16 +1824,17 @@ function renderProjectSemanticTopicInternal(entry, projectInput, locales, select
1175
1824
  nextAncestors.add(entry.id);
1176
1825
  const members = collectProjectEntryMembers(entry, projectInput.entries);
1177
1826
  const sections = [
1178
- renderProjectTopicSection("summary", labels.summary, renderProjectEntrySummary(entry, locales, selectedLocale)),
1179
- renderProjectTopicSection("declaration", labels.declaration, entry.signature ? `<pre class="hia-signature"><code>${escapeHtml(entry.signature)}</code></pre>` : ""),
1180
- renderProjectTopicSection("metadata", labels.metadata, renderProjectTopicMetadata(entry, projectInput.project.productVersion)),
1181
- renderProjectTopicSection("contract", labels.contract, renderProjectTopicContract(entry)),
1182
- renderProjectTopicSection("coverage", labels.coverage, renderProjectTopicCoverage(projectInput.documentationContinuity, projectInput.ownerAdoption, labels)),
1183
- renderProjectTopicSection("provenance", labels.provenance, renderProjectTopicProvenance(projectInput.documentationContinuity, projectInput.ownerAdoption, labels)),
1184
- renderProjectTopicSection("members", labels.members, renderProjectTopicMembers(members, projectInput, locales, selectedLocale, portalContext, includeMemberBodies, nextAncestors)),
1185
- renderProjectTopicSection("relations", labels.relations, renderProjectTopicRelations(entry, projectInput.relationGraph)),
1186
- renderProjectTopicSection("source", labels.source, renderProjectTopicSource(entry, portalContext.sourceCommentProjection)),
1187
- renderProjectTopicSection("diagnostics", labels.diagnostics, renderProjectTopicDiagnostics(entry.diagnostics ?? []))
1827
+ // <lang><zh-CN>显式IA保留既有section顺序,在正文分区内加入完整字段,避免建立第二条内容降级路径。</zh-CN><en>Explicit IA retains section order while including full fields inside the prose section, avoiding a second content-loss route.</en></lang>
1828
+ renderProjectTopicSection("summary", "portal.section.summary", labels.summary, renderProjectEntrySummary(entry, locales, selectedLocale) + renderAdditionalI18nFields(entry, locales, selectedLocale, getPrimaryI18nFieldPath(entry)), portalContext),
1829
+ renderProjectTopicSection("declaration", "portal.section.declaration", labels.declaration, entry.signature ? `<pre class="hia-signature"><code>${escapeHtml(entry.signature)}</code></pre>` : "", portalContext),
1830
+ renderProjectTopicSection("metadata", "portal.section.metadata", labels.metadata, renderProjectTopicMetadata(entry, projectInput.project.productVersion, portalContext), portalContext),
1831
+ renderProjectTopicSection("contract", "portal.section.contract", labels.contract, renderProjectTopicContract(entry, portalContext), portalContext),
1832
+ renderProjectTopicSection("coverage", "portal.section.coverage", labels.coverage, renderProjectTopicCoverage(projectInput.documentationContinuity, projectInput.ownerAdoption, portalContext), portalContext),
1833
+ renderProjectTopicSection("provenance", "portal.section.provenance", labels.provenance, renderProjectTopicProvenance(projectInput.documentationContinuity, projectInput.ownerAdoption, portalContext), portalContext),
1834
+ renderProjectTopicSection("members", "portal.section.members", labels.members, renderProjectTopicMembers(members, projectInput, locales, selectedLocale, portalContext, includeMemberBodies, nextAncestors), portalContext),
1835
+ renderProjectTopicSection("relations", "portal.section.relations", labels.relations, renderProjectTopicRelations(entry, projectInput.relationGraph, portalContext), portalContext),
1836
+ renderProjectTopicSection("source", "portal.section.source", labels.source, renderProjectTopicSource(entry, portalContext), portalContext),
1837
+ renderProjectTopicSection("diagnostics", "portal.section.diagnostics", labels.diagnostics, renderProjectTopicDiagnostics(entry.diagnostics ?? []), portalContext)
1188
1838
  ].join("");
1189
1839
  const searchText = createProjectEntrySearchText(entry);
1190
1840
  return [
@@ -1195,81 +1845,84 @@ function renderProjectSemanticTopicInternal(entry, projectInput, locales, select
1195
1845
  ].join("");
1196
1846
  }
1197
1847
  /** 空 section 不输出,从而保持“按适用性呈现”。Omits empty sections so topics remain applicability-aware. */
1198
- function renderProjectTopicSection(section, label, body) {
1199
- return body
1200
- ? `<section class="hia-project-topic-section" data-hia-topic-section="${section}"><h3>${escapeHtml(label)}</h3>${body}</section>`
1201
- : "";
1848
+ function renderProjectTopicSection(section, messageId, label, body, portalContext) {
1849
+ if (!body) {
1850
+ return "";
1851
+ }
1852
+ // <lang><zh-CN>首要阅读区默认展开;其余区保持原生 disclosure,可同时打开且不依赖脚本。</zh-CN><en>Primary reading sections start open; remaining sections use native disclosure, allow concurrent expansion, and require no script.</en></lang>
1853
+ const open = section === "summary" || section === "declaration" || section === "metadata" ? " open" : "";
1854
+ return `<details class="hia-project-topic-section" data-hia-topic-section="${section}"${open}><summary>${renderProjectUiMessage(portalContext, messageId, {}, label)}</summary><div class="hia-project-topic-section-body">${body}</div></details>`;
1202
1855
  }
1203
1856
  /** metadata 只含公开 entry/project facts;关系由 relations section 独立承载。Metadata contains public entry/project facts only; relations stay in their own section. */
1204
- function renderProjectTopicMetadata(entry, productVersion) {
1857
+ function renderProjectTopicMetadata(entry, productVersion, portalContext) {
1205
1858
  const items = [
1206
- `<dt>Kind</dt><dd>${escapeHtml(entry.kind)}</dd>`,
1207
- `<dt>View</dt><dd>${escapeHtml(entry.view)}</dd>`,
1208
- productVersion ? `<dt>Product Version</dt><dd>${escapeHtml(productVersion)}</dd>` : "",
1209
- entry.input ? `<dt>Input</dt><dd>${escapeHtml(entry.input.kind)}</dd>` : "",
1210
- entry.input?.path ? `<dt>Input Path</dt><dd>${escapeHtml(entry.input.path)}</dd>` : "",
1211
- entry.profile ? `<dt>Profile</dt><dd>${escapeHtml(entry.profile.profileId)}${entry.profile.profileVersion ? `@${escapeHtml(entry.profile.profileVersion)}` : ""}</dd>` : "",
1212
- entry.hierarchy?.assembly ? `<dt>Assembly</dt><dd>${escapeHtml(entry.hierarchy.assembly)}</dd>` : "",
1213
- entry.hierarchy?.namespace ? `<dt>Namespace</dt><dd>${escapeHtml(entry.hierarchy.namespace)}</dd>` : "",
1214
- entry.hierarchy?.containingType ? `<dt>Containing Type</dt><dd>${escapeHtml(entry.hierarchy.containingType)}</dd>` : "",
1215
- entry.hierarchy?.symbolDocumentationId ? `<dt>Documentation ID</dt><dd>${escapeHtml(entry.hierarchy.symbolDocumentationId)}</dd>` : ""
1859
+ `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.kind", {}, "Kind")}</dt><dd>${escapeHtml(entry.kind)}</dd>`,
1860
+ `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.view", {}, "View")}</dt><dd>${escapeHtml(entry.view)}</dd>`,
1861
+ productVersion ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.productversion", {}, "Product Version")}</dt><dd>${escapeHtml(productVersion)}</dd>` : "",
1862
+ entry.input ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.input", {}, "Input")}</dt><dd>${escapeHtml(entry.input.kind)}</dd>` : "",
1863
+ entry.input?.path ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.inputpath", {}, "Input Path")}</dt><dd>${escapeHtml(entry.input.path)}</dd>` : "",
1864
+ entry.profile ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.profile", {}, "Profile")}</dt><dd>${escapeHtml(entry.profile.profileId)}${entry.profile.profileVersion ? `@${escapeHtml(entry.profile.profileVersion)}` : ""}</dd>` : "",
1865
+ entry.hierarchy?.assembly ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.assembly", {}, "Assembly")}</dt><dd>${escapeHtml(entry.hierarchy.assembly)}</dd>` : "",
1866
+ entry.hierarchy?.namespace ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.namespace", {}, "Namespace")}</dt><dd>${escapeHtml(entry.hierarchy.namespace)}</dd>` : "",
1867
+ entry.hierarchy?.containingType ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.containingtype", {}, "Containing Type")}</dt><dd>${escapeHtml(entry.hierarchy.containingType)}</dd>` : "",
1868
+ entry.hierarchy?.symbolDocumentationId ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.documentationid", {}, "Documentation ID")}</dt><dd>${escapeHtml(entry.hierarchy.symbolDocumentationId)}</dd>` : ""
1216
1869
  ].join("");
1217
1870
  return `<dl class="hia-project-meta">${items}</dl>`;
1218
1871
  }
1219
1872
  /** contract section 与 input locator 分离,避免 path 被误当 contract identity。Separates contract identity from the input locator so paths are not mistaken for contracts. */
1220
- function renderProjectTopicContract(entry) {
1873
+ function renderProjectTopicContract(entry, portalContext) {
1221
1874
  if (!entry.input?.contract && !entry.input?.contractVersion && !entry.input?.artifactId) {
1222
1875
  return "";
1223
1876
  }
1224
1877
  const items = [
1225
- entry.input.contract ? `<dt>Contract</dt><dd>${escapeHtml(entry.input.contract)}</dd>` : "",
1226
- entry.input.contractVersion ? `<dt>Version</dt><dd>${escapeHtml(entry.input.contractVersion)}</dd>` : "",
1227
- entry.input.artifactId ? `<dt>Artifact</dt><dd>${escapeHtml(entry.input.artifactId)}</dd>` : ""
1878
+ entry.input.contract ? `<dt>${renderProjectUiMessage(portalContext, "portal.section.contract", {}, "Contract")}</dt><dd>${escapeHtml(entry.input.contract)}</dd>` : "",
1879
+ entry.input.contractVersion ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.version", {}, "Version")}</dt><dd>${escapeHtml(entry.input.contractVersion)}</dd>` : "",
1880
+ entry.input.artifactId ? `<dt>${renderProjectUiMessage(portalContext, "portal.metadata.artifact", {}, "Artifact")}</dt><dd>${escapeHtml(entry.input.artifactId)}</dd>` : ""
1228
1881
  ].join("");
1229
1882
  return `<dl class="hia-project-meta">${items}</dl>`;
1230
1883
  }
1231
1884
  /** continuity 缺失时不猜测成功,明确输出 unavailable。Never guesses continuity success; absence is rendered as unavailable. */
1232
- function renderProjectTopicCoverage(continuity, ownerAdoption, labels) {
1885
+ function renderProjectTopicCoverage(continuity, ownerAdoption, portalContext) {
1233
1886
  if (!continuity && !ownerAdoption) {
1234
- return `<p class="hia-project-unavailable">${escapeHtml(labels.unavailable)}</p>`;
1887
+ return `<p class="hia-project-unavailable">${renderProjectUiMessage(portalContext, "portal.common.unavailable", {}, portalContext.labels.unavailable)}</p>`;
1235
1888
  }
1236
1889
  return [
1237
1890
  "<dl class=\"hia-project-meta\">",
1238
1891
  ...(continuity ? [
1239
- `<dt>Continuity Status</dt><dd>${escapeHtml(continuity.status)}</dd>`,
1240
- `<dt>Entries</dt><dd>${escapeHtml(String(continuity.entries.baselineCount))} → ${escapeHtml(String(continuity.entries.currentCount))}</dd>`,
1241
- `<dt>Added / Removed / Unchanged</dt><dd>${escapeHtml(String(continuity.entries.addedCount))} / ${escapeHtml(String(continuity.entries.removedCount))} / ${escapeHtml(String(continuity.entries.unchangedCount))}</dd>`,
1242
- `<dt>Required Outputs</dt><dd>${continuity.requiredOutputsPreserved ? "preserved" : "not-preserved"}</dd>`
1892
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.continuitystatus", {}, "Continuity Status")}</dt><dd>${escapeHtml(continuity.status)}</dd>`,
1893
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.entries", {}, "Entries")}</dt><dd>${escapeHtml(String(continuity.entries.baselineCount))} → ${escapeHtml(String(continuity.entries.currentCount))}</dd>`,
1894
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.delta", {}, "Added / Removed / Unchanged")}</dt><dd>${escapeHtml(String(continuity.entries.addedCount))} / ${escapeHtml(String(continuity.entries.removedCount))} / ${escapeHtml(String(continuity.entries.unchangedCount))}</dd>`,
1895
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.requiredoutputs", {}, "Required Outputs")}</dt><dd>${renderProjectUiMessage(portalContext, continuity.requiredOutputsPreserved ? "portal.coverage.preserved" : "portal.coverage.notpreserved", {}, continuity.requiredOutputsPreserved ? "preserved" : "not-preserved")}</dd>`
1243
1896
  ] : []),
1244
1897
  ...(ownerAdoption ? [
1245
- `<dt>Owner Review Readiness</dt><dd>${escapeHtml(ownerAdoption.status)}</dd>`,
1246
- `<dt>Owner Input / Consent</dt><dd>${ownerAdoption.ownerInput.submitted ? "submitted" : "not-submitted"} / ${escapeHtml(ownerAdoption.ownerInput.consent)}</dd>`,
1247
- `<dt>Contract References</dt><dd>${escapeHtml(String(ownerAdoption.contracts.providedCount))} / ${escapeHtml(String(ownerAdoption.contracts.requiredCount))}</dd>`,
1898
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.ownerreadiness", {}, "Owner Review Readiness")}</dt><dd>${escapeHtml(ownerAdoption.status)}</dd>`,
1899
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.ownerinput", {}, "Owner Input / Consent")}</dt><dd>${renderProjectUiMessage(portalContext, ownerAdoption.ownerInput.submitted ? "portal.coverage.submitted" : "portal.coverage.notsubmitted", {}, ownerAdoption.ownerInput.submitted ? "submitted" : "not-submitted")} / ${escapeHtml(ownerAdoption.ownerInput.consent)}</dd>`,
1900
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.contractrefs", {}, "Contract References")}</dt><dd>${escapeHtml(String(ownerAdoption.contracts.providedCount))} / ${escapeHtml(String(ownerAdoption.contracts.requiredCount))}</dd>`,
1248
1901
  ...(ownerAdoption.workspaceHandoff ? [
1249
- `<dt>Repository Owners / Handoff Edges</dt><dd>${escapeHtml(String(ownerAdoption.workspaceHandoff.repositoryOwnerCount))} / ${escapeHtml(String(ownerAdoption.workspaceHandoff.handoffEdgeCount))}</dd>`
1902
+ `<dt>${renderProjectUiMessage(portalContext, "portal.coverage.handoffs", {}, "Repository Owners / Handoff Edges")}</dt><dd>${escapeHtml(String(ownerAdoption.workspaceHandoff.repositoryOwnerCount))} / ${escapeHtml(String(ownerAdoption.workspaceHandoff.handoffEdgeCount))}</dd>`
1250
1903
  ] : [])
1251
1904
  ] : []),
1252
1905
  "</dl>"
1253
1906
  ].join("");
1254
1907
  }
1255
1908
  /** provenance 只显示 exact contract 与三维 semantics,不回读 evidence body。Provenance shows only the exact contract and three semantic dimensions, without reading evidence bodies. */
1256
- function renderProjectTopicProvenance(continuity, ownerAdoption, labels) {
1909
+ function renderProjectTopicProvenance(continuity, ownerAdoption, portalContext) {
1257
1910
  if (!continuity && !ownerAdoption) {
1258
- return `<p class="hia-project-unavailable">${escapeHtml(labels.unavailable)}</p>`;
1911
+ return `<p class="hia-project-unavailable">${renderProjectUiMessage(portalContext, "portal.common.unavailable", {}, portalContext.labels.unavailable)}</p>`;
1259
1912
  }
1260
1913
  return [
1261
1914
  "<dl class=\"hia-project-meta\">",
1262
1915
  ...(continuity ? [
1263
- `<dt>Continuity Contract</dt><dd>${escapeHtml(continuity.contract)}@${escapeHtml(continuity.contractVersion)}</dd>`,
1264
- `<dt>Continuity Resolution</dt><dd>${escapeHtml(continuity.semantics.resolution)}</dd>`,
1265
- `<dt>Continuity Confidence</dt><dd>${escapeHtml(continuity.semantics.confidence)}</dd>`,
1266
- `<dt>Continuity Provenance</dt><dd>${escapeHtml(continuity.semantics.provenance)}</dd>`
1916
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.continuitycontract", {}, "Continuity Contract")}</dt><dd>${escapeHtml(continuity.contract)}@${escapeHtml(continuity.contractVersion)}</dd>`,
1917
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.continuityresolution", {}, "Continuity Resolution")}</dt><dd>${escapeHtml(continuity.semantics.resolution)}</dd>`,
1918
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.continuityconfidence", {}, "Continuity Confidence")}</dt><dd>${escapeHtml(continuity.semantics.confidence)}</dd>`,
1919
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.continuityprovenance", {}, "Continuity Provenance")}</dt><dd>${escapeHtml(continuity.semantics.provenance)}</dd>`
1267
1920
  ] : []),
1268
1921
  ...(ownerAdoption ? [
1269
- `<dt>Owner Kit Contract</dt><dd>${escapeHtml(ownerAdoption.contract)}@${escapeHtml(ownerAdoption.contractVersion)}</dd>`,
1270
- `<dt>Owner Kit Resolution</dt><dd>${escapeHtml(ownerAdoption.semantics.resolution)}</dd>`,
1271
- `<dt>Owner Kit Confidence</dt><dd>${escapeHtml(ownerAdoption.semantics.confidence)}</dd>`,
1272
- `<dt>Owner Kit Provenance</dt><dd>${escapeHtml(ownerAdoption.semantics.provenance)}</dd>`
1922
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.ownercontract", {}, "Owner Kit Contract")}</dt><dd>${escapeHtml(ownerAdoption.contract)}@${escapeHtml(ownerAdoption.contractVersion)}</dd>`,
1923
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.ownerresolution", {}, "Owner Kit Resolution")}</dt><dd>${escapeHtml(ownerAdoption.semantics.resolution)}</dd>`,
1924
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.ownerconfidence", {}, "Owner Kit Confidence")}</dt><dd>${escapeHtml(ownerAdoption.semantics.confidence)}</dd>`,
1925
+ `<dt>${renderProjectUiMessage(portalContext, "portal.provenance.ownerprovenance", {}, "Owner Kit Provenance")}</dt><dd>${escapeHtml(ownerAdoption.semantics.provenance)}</dd>`
1273
1926
  ] : []),
1274
1927
  "</dl>"
1275
1928
  ].join("");
@@ -1295,14 +1948,19 @@ function renderProjectTopicMembers(members, projectInput, locales, selectedLocal
1295
1948
  if (ancestors.has(member.id)) {
1296
1949
  return `<p><a href="${escapeHtml(createProjectEntryContentPath(member.id))}#${escapeHtml(member.id)}">${escapeHtml(member.name)}</a></p>`;
1297
1950
  }
1298
- return renderProjectSemanticTopicInternal(member, projectInput, locales, selectedLocale, portalContext, true, ancestors);
1951
+ return [
1952
+ `<details class="hia-project-member-card"><summary><span>${escapeHtml(member.name)}</span> <small>${escapeHtml(member.kind)}</small></summary>`,
1953
+ "<div class=\"hia-project-member-card-body\">",
1954
+ renderProjectSemanticTopicInternal(member, projectInput, locales, selectedLocale, portalContext, true, ancestors),
1955
+ "</div></details>"
1956
+ ].join("");
1299
1957
  }).join("")}</div>`;
1300
1958
  }
1301
1959
  /** inheritance/implements 与 project relation graph 都只进入 relations section。Inheritance, implements, and project graph edges appear only in the relations section. */
1302
- function renderProjectTopicRelations(entry, relationGraph) {
1960
+ function renderProjectTopicRelations(entry, relationGraph, portalContext) {
1303
1961
  const semanticItems = [
1304
- ...(entry.hierarchy?.baseTypeIds ?? []).map((id) => `<li><span class="hia-kind">inherits</span> ${escapeHtml(id)}</li>`),
1305
- ...(entry.hierarchy?.interfaceIds ?? []).map((id) => `<li><span class="hia-kind">implements</span> ${escapeHtml(id)}</li>`)
1962
+ ...(entry.hierarchy?.baseTypeIds ?? []).map((id) => `<li><span class="hia-kind">${renderProjectUiMessage(portalContext, "portal.relation.inherits", {}, "inherits")}</span> ${escapeHtml(id)}</li>`),
1963
+ ...(entry.hierarchy?.interfaceIds ?? []).map((id) => `<li><span class="hia-kind">${renderProjectUiMessage(portalContext, "portal.relation.implements", {}, "implements")}</span> ${escapeHtml(id)}</li>`)
1306
1964
  ];
1307
1965
  const entryNodeIds = new Set(relationGraph?.nodes.filter((node) => node.entryId === entry.id).map((node) => node.id) ?? []);
1308
1966
  const graphItems = relationGraph?.relations
@@ -1312,12 +1970,14 @@ function renderProjectTopicRelations(entry, relationGraph) {
1312
1970
  return items ? `<ul class="hia-project-relation-list">${items}</ul>` : "";
1313
1971
  }
1314
1972
  /** source 与 doc-source-map 保持既有 privacy policy;本函数不新增 source body。Source and doc-source-map retain the existing privacy policy; this function adds no source body. */
1315
- function renderProjectTopicSource(entry, options) {
1973
+ function renderProjectTopicSource(entry, portalContext) {
1316
1974
  return [
1317
- entry.source ? renderProjectEntrySource(entry.source, false) : "",
1318
- entry.sourceUsability ? renderProjectEntrySourceUsability(entry.sourceUsability, false) : "",
1319
- entry.docSourceMap ? renderProjectEntryDocSourceMap(entry.docSourceMap, false) : "",
1320
- entry.sourceCommentProjection && options ? renderProjectSourceCommentProjection(entry.sourceCommentProjection, options) : ""
1975
+ entry.source ? renderProjectEntrySource(entry.source, false, portalContext) : "",
1976
+ entry.sourceUsability ? renderProjectEntrySourceUsability(entry.sourceUsability, false, portalContext) : "",
1977
+ entry.docSourceMap ? renderProjectEntryDocSourceMap(entry.docSourceMap, false, portalContext) : "",
1978
+ entry.sourceCommentProjection && portalContext.sourceCommentProjection
1979
+ ? renderProjectSourceCommentProjection(entry.sourceCommentProjection, portalContext.sourceCommentProjection, portalContext)
1980
+ : ""
1321
1981
  ].join("");
1322
1982
  }
1323
1983
  /**
@@ -1352,30 +2012,30 @@ function selectProjectSourceCommentProjection(projection) {
1352
2012
  * @lang en
1353
2013
  * Renders metadata and optional plain-text bodies. Bodies require authorization from both the producer projection and renderer config.
1354
2014
  */
1355
- function renderProjectSourceCommentProjection(projection, options) {
2015
+ function renderProjectSourceCommentProjection(projection, options, portalContext) {
1356
2016
  const bodyAuthorized = options.contentPolicy === "explicit-projected-text"
1357
2017
  && projection.contentPolicy === "explicit-projected-text"
1358
2018
  && projection.privacy.projectedCommentTextIncluded;
1359
2019
  const metadata = [
1360
- `<dt>Comment Contract</dt><dd>${escapeHtml(`${projection.contract}@${projection.contractVersion}`)}</dd>`,
1361
- `<dt>Comment Locale</dt><dd>${escapeHtml(projection.requestedLocale)}</dd>`,
1362
- `<dt>Comment Status</dt><dd>${escapeHtml(projection.status)}</dd>`,
1363
- `<dt>Comment Entries</dt><dd>${escapeHtml(String(projection.entries.length))}</dd>`,
1364
- `<dt>Source Content Policy</dt><dd>${escapeHtml(projection.privacy.sourcesContentPolicy)}</dd>`
2020
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.commentcontract", "Comment Contract")}</dt><dd>${escapeHtml(`${projection.contract}@${projection.contractVersion}`)}</dd>`,
2021
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.commentlocale", "Comment Locale")}</dt><dd>${escapeHtml(projection.requestedLocale)}</dd>`,
2022
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.commentstatus", "Comment Status")}</dt><dd>${escapeHtml(projection.status)}</dd>`,
2023
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.commententries", "Comment Entries")}</dt><dd>${escapeHtml(String(projection.entries.length))}</dd>`,
2024
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.contentpolicy", "Source Content Policy")}</dt><dd>${escapeHtml(projection.privacy.sourcesContentPolicy)}</dd>`
1365
2025
  ].join("");
1366
2026
  const entries = projection.entries.map((entry) => {
1367
2027
  const range = entry.range
1368
- ? `<dt>Range</dt><dd>${escapeHtml(`${entry.range.start.line}:${entry.range.start.column}-${entry.range.end.line}:${entry.range.end.column}`)}</dd>`
2028
+ ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.range", "Range")}</dt><dd>${escapeHtml(`${entry.range.start.line}:${entry.range.start.column}-${entry.range.end.line}:${entry.range.end.column}`)}</dd>`
1369
2029
  : "";
1370
2030
  const body = bodyAuthorized && entry.projectedText !== undefined
1371
2031
  ? `<pre class="hia-source-comment"><code>${escapeHtml(entry.projectedText)}</code></pre>`
1372
2032
  : "";
1373
2033
  return [
1374
2034
  `<article class="hia-source-comment-entry" data-hia-source-comment-id="${escapeHtml(entry.commentId)}">`,
1375
- `<dl class="hia-project-meta"><dt>Comment</dt><dd>${escapeHtml(entry.commentId)}</dd>`,
1376
- `<dt>Resolution</dt><dd>${escapeHtml(entry.resolution)}</dd>`,
1377
- `<dt>Confidence</dt><dd>${escapeHtml(entry.confidence)}</dd>`,
1378
- `<dt>Provenance</dt><dd>${escapeHtml(entry.provenance.kind)}</dd>${range}</dl>`,
2035
+ `<dl class="hia-project-meta"><dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.comment", "Comment")}</dt><dd>${escapeHtml(entry.commentId)}</dd>`,
2036
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.resolution", "Resolution")}</dt><dd>${escapeHtml(entry.resolution)}</dd>`,
2037
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.confidence", "Confidence")}</dt><dd>${escapeHtml(entry.confidence)}</dd>`,
2038
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.section.provenance", "Provenance")}</dt><dd>${escapeHtml(entry.provenance.kind)}</dd>${range}</dl>`,
1379
2039
  body,
1380
2040
  "</article>"
1381
2041
  ].join("");
@@ -1405,15 +2065,9 @@ function renderProjectEntryHierarchy(hierarchy) {
1405
2065
  ].join("");
1406
2066
  return details ? `<dl class="hia-project-meta hia-project-hierarchy-meta">${details}</dl>` : "";
1407
2067
  }
2068
+ /** @lang zh-CN 仅选择主描述字段,使用原字段身份及共用的locale/fallback规则;不改写i18n模型。 @lang en Selects only the primary prose field with its original identity and shared locale/fallback rules, without rewriting the i18n model. */
1408
2069
  function renderProjectEntrySummary(entry, locales, selectedLocale) {
1409
- const field = entry.i18n?.fields.description ?? entry.i18n?.fields.summary;
1410
- if (!field && !entry.summary) {
1411
- return "";
1412
- }
1413
- const blocks = locales
1414
- .map((locale) => renderLocalizedBlock(field, locale, selectedLocale, createI18nResolveOptionsFromModel(entry.i18n), entry.summary ?? ""))
1415
- .join("");
1416
- return `<div class="hia-localized-set" data-hia-i18n-field="description">${blocks}</div>`;
2070
+ return renderI18nField(entry, getPrimaryI18nFieldPath(entry), locales, selectedLocale, entry.summary ?? "");
1417
2071
  }
1418
2072
  function renderProjectEntryInput(input) {
1419
2073
  const details = [
@@ -1429,39 +2083,39 @@ function renderProjectEntryProfile(profile) {
1429
2083
  const version = profile.profileVersion ? `@${profile.profileVersion}` : "";
1430
2084
  return `<p class="hia-project-profile">Profile ${escapeHtml(profile.profileId)}${escapeHtml(version)}</p>`;
1431
2085
  }
1432
- function renderProjectEntrySource(source, includeHeading = true) {
2086
+ function renderProjectEntrySource(source, includeHeading = true, portalContext) {
1433
2087
  const range = source.range ? `:${source.range.start.line}${source.range.end ? `-${source.range.end.line}` : ""}` : "";
1434
2088
  const label = `${source.path}${range}`;
1435
2089
  const sourceLabel = source.linkUrl
1436
2090
  ? `<a href="${escapeHtml(source.linkUrl)}">${escapeHtml(label)}</a>`
1437
2091
  : escapeHtml(label);
1438
2092
  const sourceDetails = [
1439
- `<dt>Source</dt><dd>${sourceLabel}</dd>`,
1440
- source.language ? `<dt>Language</dt><dd>${escapeHtml(source.language)}</dd>` : "",
1441
- source.rangeSource ? `<dt>Range Source</dt><dd>${escapeHtml(source.rangeSource)}</dd>` : "",
1442
- source.confidence ? `<dt>Confidence</dt><dd>${escapeHtml(source.confidence)}</dd>` : ""
2093
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.section.source", "Source")}</dt><dd>${sourceLabel}</dd>`,
2094
+ source.language ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.language", "Language")}</dt><dd>${escapeHtml(source.language)}</dd>` : "",
2095
+ source.rangeSource ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.rangesource", "Range Source")}</dt><dd>${escapeHtml(source.rangeSource)}</dd>` : "",
2096
+ source.confidence ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.confidence", "Confidence")}</dt><dd>${escapeHtml(source.confidence)}</dd>` : ""
1443
2097
  ].join("");
1444
- const preview = source.preview ? renderProjectSourcePreview(source.preview, source.path) : "";
1445
- const fetchPreview = source.fetchUrl ? renderProjectSourceFetch(source) : "";
1446
- const heading = includeHeading ? "<h3>Source</h3>" : "";
2098
+ const preview = source.preview ? renderProjectSourcePreview(source.preview, source.path, portalContext) : "";
2099
+ const fetchPreview = source.fetchUrl ? renderProjectSourceFetch(source, portalContext) : "";
2100
+ const heading = includeHeading ? `<h3>${renderOptionalProjectUiMessage(portalContext, "portal.section.source", "Source")}</h3>` : "";
1447
2101
  return `<section class="hia-source-section">${heading}<dl class="hia-project-meta">${sourceDetails}</dl>${preview}${fetchPreview}</section>`;
1448
2102
  }
1449
2103
  /**
1450
2104
  * @lang zh-CN 只渲染 source-usability allowlist metadata,不生成 link、fetch request、preview 或 source body。
1451
2105
  * @lang en Renders only allowlisted source-usability metadata and creates no link, fetch request, preview, or source body.
1452
2106
  */
1453
- function renderProjectEntrySourceUsability(sourceUsability, includeHeading = true) {
2107
+ function renderProjectEntrySourceUsability(sourceUsability, includeHeading = true, portalContext) {
1454
2108
  const projectIdentity = sourceUsability.projectIdentity;
1455
2109
  const details = [
1456
- `<dt>Resolution</dt><dd>${escapeHtml(sourceUsability.resolution)}</dd>`,
1457
- `<dt>Confidence</dt><dd>${escapeHtml(sourceUsability.confidence)}</dd>`,
1458
- projectIdentity ? `<dt>Project</dt><dd>${escapeHtml(projectIdentity.path)}</dd>` : "",
1459
- projectIdentity ? `<dt>Project Identity</dt><dd>${escapeHtml(projectIdentity.id)}</dd>` : "",
1460
- projectIdentity ? `<dt>Identity Policy</dt><dd>${escapeHtml(projectIdentity.policy)}</dd>` : "",
1461
- `<dt>Provenance</dt><dd>${escapeHtml(`${sourceUsability.provenance.producer}:${sourceUsability.provenance.activity}`)}</dd>`,
1462
- `<dt>Source Content Policy</dt><dd>${escapeHtml(sourceUsability.privacy.sourcesContentPolicy)}</dd>`
2110
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.resolution", "Resolution")}</dt><dd>${escapeHtml(sourceUsability.resolution)}</dd>`,
2111
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.confidence", "Confidence")}</dt><dd>${escapeHtml(sourceUsability.confidence)}</dd>`,
2112
+ projectIdentity ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.project", "Project")}</dt><dd>${escapeHtml(projectIdentity.path)}</dd>` : "",
2113
+ projectIdentity ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.projectidentity", "Project Identity")}</dt><dd>${escapeHtml(projectIdentity.id)}</dd>` : "",
2114
+ projectIdentity ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.identitypolicy", "Identity Policy")}</dt><dd>${escapeHtml(projectIdentity.policy)}</dd>` : "",
2115
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.section.provenance", "Provenance")}</dt><dd>${escapeHtml(`${sourceUsability.provenance.producer}:${sourceUsability.provenance.activity}`)}</dd>`,
2116
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.contentpolicy", "Source Content Policy")}</dt><dd>${escapeHtml(sourceUsability.privacy.sourcesContentPolicy)}</dd>`
1463
2117
  ].join("");
1464
- const heading = includeHeading ? "<h3>Source Usability</h3>" : "";
2118
+ const heading = includeHeading ? `<h3>${renderOptionalProjectUiMessage(portalContext, "portal.source.usability", "Source Usability")}</h3>` : "";
1465
2119
  return `<section class="hia-source-section hia-source-usability-section">${heading}<dl class="hia-project-meta">${details}</dl></section>`;
1466
2120
  }
1467
2121
  /**
@@ -1495,46 +2149,57 @@ function selectProjectSourceUsability(sourceUsability) {
1495
2149
  }
1496
2150
  };
1497
2151
  }
1498
- function renderProjectSourceFetch(source) {
2152
+ /**
2153
+ * @lang zh-CN 渲染一个只接受同源 publicAsset metadata 的源码 reader;缺少授权 asset 时不产生 fallback UI。
2154
+ * @lang en Renders a source reader that accepts same-origin public-asset metadata only and emits no fallback UI when authorization is absent.
2155
+ *
2156
+ * @param source - 已经 source policy 处理的 body-free source reference。Body-free source reference already processed by source policy.
2157
+ * @returns native details reader HTML;拒绝时为空字符串。Native details-reader HTML, or an empty string when refused.
2158
+ */
2159
+ function renderProjectSourceFetch(source, portalContext) {
2160
+ const publicAsset = source.publicAsset;
2161
+ if (!publicAsset || !source.fetchUrl) {
2162
+ return "";
2163
+ }
1499
2164
  const startLine = source.range?.start.line ?? 1;
1500
2165
  const endLine = source.range?.end?.line;
1501
2166
  const fetchTrigger = source.fetchTrigger ?? "on-expand";
1502
2167
  const maxLines = source.fetchMaxLines ?? 400;
1503
2168
  const caption = endLine ? `${source.path}:${startLine}-${endLine}` : `${source.path}:${startLine}`;
1504
- const endAttribute = endLine ? ` data-hia-source-end="${escapeHtml(String(endLine))}"` : "";
1505
2169
  const manualButton = fetchTrigger === "manual"
1506
- ? "<button type=\"button\" class=\"hia-source-fetch-button\" data-hia-source-fetch-button>Load source / 加载源码</button>"
2170
+ ? `<button type="button" class="hia-source-fetch-button" data-hia-source-fetch-button>${renderOptionalProjectUiMessage(portalContext, "portal.source.load", "Load source / 加载源码")}</button>`
1507
2171
  : "";
1508
2172
  return [
1509
- `<details class="hia-source-preview hia-project-source-preview" data-hia-source-fetch="${escapeHtml(source.fetchUrl ?? "")}" data-hia-source-fetch-trigger="${escapeHtml(fetchTrigger)}" data-hia-source-start="${escapeHtml(String(startLine))}"${endAttribute} data-hia-source-max-lines="${escapeHtml(String(maxLines))}">`,
2173
+ `<details class="hia-source-preview hia-project-source-preview" data-hia-source-fetch="${escapeHtml(source.fetchUrl)}" data-hia-source-fetch-trigger="${escapeHtml(fetchTrigger)}" data-hia-source-state="idle" data-hia-source-asset-id="${escapeHtml(publicAsset.assetId)}" data-hia-source-integrity="${escapeHtml(publicAsset.digest)}" data-hia-source-byte-length="${escapeHtml(String(publicAsset.byteLength))}" data-hia-source-max-bytes="1048576" data-hia-source-max-lines="${escapeHtml(String(maxLines))}" data-hia-source-timeout="10000">`,
1510
2174
  `<summary>${escapeHtml(caption)}</summary>`,
1511
2175
  manualButton,
1512
- "<p class=\"hia-project-loading\" data-hia-source-fetch-status hidden></p>",
2176
+ `<p class="hia-project-loading" data-hia-source-fetch-status role="status" aria-live="polite"${portalContext?.uiLocaleAdoption ? " data-hia-ui-message=\"portal.source.status.loading\"" : ""} hidden></p>`,
1513
2177
  `<pre class="hia-source-code"><code data-language="${escapeHtml(source.language ?? "")}"></code></pre>`,
2178
+ `<button type="button" class="hia-source-reset-button" data-hia-source-reset hidden>${renderOptionalProjectUiMessage(portalContext, "portal.source.reset", "Reset / 重置")}</button>`,
1514
2179
  "</details>"
1515
2180
  ].join("");
1516
2181
  }
1517
- function renderProjectEntryDocSourceMap(docSourceMap, includeHeading = true) {
2182
+ function renderProjectEntryDocSourceMap(docSourceMap, includeHeading = true, portalContext) {
1518
2183
  const sourceRange = docSourceMap.sourceRange ? `:${docSourceMap.sourceRange.start.line}${docSourceMap.sourceRange.end ? `-${docSourceMap.sourceRange.end.line}` : ""}` : "";
1519
2184
  const diagnostics = docSourceMap.diagnostics && docSourceMap.diagnostics.length > 0
1520
- ? `<dt>Diagnostics</dt><dd>${escapeHtml(docSourceMap.diagnostics.join(", "))}</dd>`
2185
+ ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.diagnostics", "Diagnostics")}</dt><dd>${escapeHtml(docSourceMap.diagnostics.join(", "))}</dd>`
1521
2186
  : "";
1522
2187
  const details = [
1523
- `<dt>Manifest</dt><dd>${escapeHtml(docSourceMap.path)}</dd>`,
1524
- `<dt>Entry</dt><dd>${escapeHtml(docSourceMap.entryId)}</dd>`,
1525
- docSourceMap.sourcePath ? `<dt>Original Source</dt><dd>${escapeHtml(docSourceMap.sourcePath)}${escapeHtml(sourceRange)}</dd>` : "",
1526
- docSourceMap.sourceRangeSource ? `<dt>Range Source</dt><dd>${escapeHtml(docSourceMap.sourceRangeSource)}</dd>` : "",
1527
- docSourceMap.sourceConfidence ? `<dt>Source Confidence</dt><dd>${escapeHtml(docSourceMap.sourceConfidence)}</dd>` : "",
1528
- docSourceMap.artifactPath ? `<dt>Generated Artifact</dt><dd>${escapeHtml(docSourceMap.artifactPath)}</dd>` : "",
1529
- docSourceMap.artifactSelector ? `<dt>Selector</dt><dd>${escapeHtml(docSourceMap.artifactSelector)}</dd>` : "",
1530
- docSourceMap.artifactConfidence ? `<dt>Artifact Confidence</dt><dd>${escapeHtml(docSourceMap.artifactConfidence)}</dd>` : "",
2188
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.manifest", "Manifest")}</dt><dd>${escapeHtml(docSourceMap.path)}</dd>`,
2189
+ `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.entry", "Entry")}</dt><dd>${escapeHtml(docSourceMap.entryId)}</dd>`,
2190
+ docSourceMap.sourcePath ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.original", "Original Source")}</dt><dd>${escapeHtml(docSourceMap.sourcePath)}${escapeHtml(sourceRange)}</dd>` : "",
2191
+ docSourceMap.sourceRangeSource ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.rangesource", "Range Source")}</dt><dd>${escapeHtml(docSourceMap.sourceRangeSource)}</dd>` : "",
2192
+ docSourceMap.sourceConfidence ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.sourceconfidence", "Source Confidence")}</dt><dd>${escapeHtml(docSourceMap.sourceConfidence)}</dd>` : "",
2193
+ docSourceMap.artifactPath ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.generatedartifact", "Generated Artifact")}</dt><dd>${escapeHtml(docSourceMap.artifactPath)}</dd>` : "",
2194
+ docSourceMap.artifactSelector ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.selector", "Selector")}</dt><dd>${escapeHtml(docSourceMap.artifactSelector)}</dd>` : "",
2195
+ docSourceMap.artifactConfidence ? `<dt>${renderOptionalProjectUiMessage(portalContext, "portal.source.artifactconfidence", "Artifact Confidence")}</dt><dd>${escapeHtml(docSourceMap.artifactConfidence)}</dd>` : "",
1531
2196
  diagnostics
1532
2197
  ].join("");
1533
- const actions = renderProjectDocSourceMapOpenRequests(docSourceMap);
2198
+ const actions = renderProjectDocSourceMapOpenRequests(docSourceMap, portalContext);
1534
2199
  const heading = includeHeading ? "<h3>Doc Source Map</h3>" : "";
1535
2200
  return `<section class="hia-source-section">${heading}<dl class="hia-project-meta">${details}</dl>${actions}</section>`;
1536
2201
  }
1537
- function renderProjectSourcePreview(preview, fallbackPath) {
2202
+ function renderProjectSourcePreview(preview, fallbackPath, portalContext) {
1538
2203
  if (!preview.content) {
1539
2204
  return "";
1540
2205
  }
@@ -1545,22 +2210,22 @@ function renderProjectSourcePreview(preview, fallbackPath) {
1545
2210
  const language = preview.language ? ` data-hia-source-language="${escapeHtml(preview.language)}"` : "";
1546
2211
  return [
1547
2212
  `<details class="hia-source-preview hia-project-source-preview"${open}>`,
1548
- `<summary>Source Preview ${escapeHtml(caption)}</summary>`,
2213
+ `<summary>${renderOptionalProjectUiMessage(portalContext, "portal.source.preview", `Source Preview ${caption}`, { caption })}</summary>`,
1549
2214
  `<pre class="hia-source-code"${language}><code>${escapeHtml(preview.content)}</code></pre>`,
1550
2215
  "</details>"
1551
2216
  ].join("");
1552
2217
  }
1553
- function renderProjectDocSourceMapOpenRequests(docSourceMap) {
2218
+ function renderProjectDocSourceMapOpenRequests(docSourceMap, portalContext) {
1554
2219
  const sourceLabel = docSourceMap.sourcePath && docSourceMap.sourceRange
1555
2220
  ? `${docSourceMap.sourcePath}:${docSourceMap.sourceRange.start.line}${docSourceMap.sourceRange.start.column ? `:${docSourceMap.sourceRange.start.column}` : ""}`
1556
2221
  : docSourceMap.sourcePath;
1557
2222
  const generatedLabel = docSourceMap.artifactPath ?? "";
1558
2223
  const buttons = [
1559
2224
  sourceLabel
1560
- ? `<button type="button" data-hia-open-request="source" data-hia-open-path="${escapeHtml(docSourceMap.sourcePath ?? "")}" data-hia-open-line="${escapeHtml(String(docSourceMap.sourceRange?.start.line ?? ""))}" data-hia-open-column="${escapeHtml(String(docSourceMap.sourceRange?.start.column ?? ""))}">Open Source ${escapeHtml(sourceLabel)}</button>`
2225
+ ? `<button type="button" data-hia-open-request="source" data-hia-open-path="${escapeHtml(docSourceMap.sourcePath ?? "")}" data-hia-open-line="${escapeHtml(String(docSourceMap.sourceRange?.start.line ?? ""))}" data-hia-open-column="${escapeHtml(String(docSourceMap.sourceRange?.start.column ?? ""))}">${renderOptionalProjectUiMessage(portalContext, "portal.source.opensource", `Open Source ${sourceLabel}`, { target: sourceLabel })}</button>`
1561
2226
  : "",
1562
2227
  generatedLabel
1563
- ? `<button type="button" data-hia-open-request="generated" data-hia-open-path="${escapeHtml(generatedLabel)}">Open Generated ${escapeHtml(generatedLabel)}</button>`
2228
+ ? `<button type="button" data-hia-open-request="generated" data-hia-open-path="${escapeHtml(generatedLabel)}">${renderOptionalProjectUiMessage(portalContext, "portal.source.opengenerated", `Open Generated ${generatedLabel}`, { target: generatedLabel })}</button>`
1564
2229
  : ""
1565
2230
  ].filter(Boolean).join("");
1566
2231
  return buttons ? `<div class="hia-source-actions">${buttons}</div>` : "";
@@ -1612,15 +2277,15 @@ function renderProjectDocSourceMaps(docSourceMaps) {
1612
2277
  * display locals/digests; it shows only safe source intent, restricted member
1613
2278
  * paths, instance-key state, targets, and quality dimensions.
1614
2279
  */
1615
- function renderProjectGeneratedDocumentationBindingProjection(projection) {
2280
+ function renderProjectGeneratedDocumentationBindingProjection(projection, portalContext) {
1616
2281
  if (!projection) {
1617
2282
  return "";
1618
2283
  }
1619
2284
  const summaryItems = [
1620
- `<li><span>Bindings / 绑定</span><strong>${escapeHtml(String(projection.summary.bindingCount))}</strong></li>`,
1621
- `<li><span>Expansions / 展开</span><strong>${escapeHtml(String(projection.summary.expansionCount))}</strong></li>`,
1622
- `<li><span>Targets / 目标</span><strong>${escapeHtml(String(projection.summary.targetCount))}</strong></li>`,
1623
- `<li><span>Diagnostics / 诊断</span><strong>${escapeHtml(String(projection.summary.diagnosticCount))}</strong></li>`,
2285
+ `<li><span>${renderOptionalProjectUiMessage(portalContext, "portal.binding.bindings", "Bindings / 绑定")}</span><strong>${escapeHtml(String(projection.summary.bindingCount))}</strong></li>`,
2286
+ `<li><span>${renderOptionalProjectUiMessage(portalContext, "portal.binding.expansions", "Expansions / 展开")}</span><strong>${escapeHtml(String(projection.summary.expansionCount))}</strong></li>`,
2287
+ `<li><span>${renderOptionalProjectUiMessage(portalContext, "portal.binding.targets", "Targets / 目标")}</span><strong>${escapeHtml(String(projection.summary.targetCount))}</strong></li>`,
2288
+ `<li><span>${renderOptionalProjectUiMessage(portalContext, "portal.binding.diagnostics", "Diagnostics / 诊断")}</span><strong>${escapeHtml(String(projection.summary.diagnosticCount))}</strong></li>`,
1624
2289
  `<li><span>sourcesContent</span><strong>${escapeHtml(projection.privacy.sourcesContentPolicy)}</strong></li>`
1625
2290
  ].join("");
1626
2291
  const bindings = projection.bindings.map((binding) => {
@@ -1629,7 +2294,7 @@ function renderProjectGeneratedDocumentationBindingProjection(projection) {
1629
2294
  const expansions = binding.expansions
1630
2295
  .map((expansion) => {
1631
2296
  const key = expansion.instanceKey.displayKey ?? expansion.instanceKey.status;
1632
- return `<li>${escapeHtml(expansion.id)} · key=${escapeHtml(key)} · ${escapeHtml(expansion.quality.resolutionKind)} / ${escapeHtml(expansion.quality.confidence)} / ${escapeHtml(expansion.quality.provenanceCoverage)} · ${escapeHtml(String(expansion.targetIds.length))} target(s)</li>`;
2297
+ return `<li>${escapeHtml(expansion.id)} · key=${escapeHtml(key)} · ${escapeHtml(expansion.quality.resolutionKind)} / ${escapeHtml(expansion.quality.confidence)} / ${escapeHtml(expansion.quality.provenanceCoverage)} · ${renderOptionalProjectUiMessage(portalContext, "portal.binding.targetcount", `${expansion.targetIds.length} target(s)`, { count: expansion.targetIds.length })}</li>`;
1633
2298
  })
1634
2299
  .join("");
1635
2300
  const targets = binding.targets
@@ -1640,17 +2305,17 @@ function renderProjectGeneratedDocumentationBindingProjection(projection) {
1640
2305
  `<strong>${escapeHtml(binding.id)}</strong>`,
1641
2306
  `<p>${escapeHtml(binding.sourceIntent.kind)}${binding.sourceIntent.field ? ` / ${escapeHtml(binding.sourceIntent.field)}` : ""} · ${escapeHtml(memberPath)} · ${escapeHtml(quality)}</p>`,
1642
2307
  `<p>scope=${escapeHtml(binding.scopeId)} · ${escapeHtml(binding.composition.relation)} / ${escapeHtml(binding.composition.mergePolicy)}</p>`,
1643
- expansions ? `<details><summary>Expansions / 展开 (${escapeHtml(String(binding.expansions.length))})</summary><ul>${expansions}</ul></details>` : "",
1644
- targets ? `<details><summary>Targets / 目标 (${escapeHtml(String(binding.targets.length))})</summary><ul>${targets}</ul></details>` : "",
2308
+ expansions ? `<details><summary>${renderOptionalProjectUiMessage(portalContext, "portal.binding.expansions", "Expansions / 展开")} (${escapeHtml(String(binding.expansions.length))})</summary><ul>${expansions}</ul></details>` : "",
2309
+ targets ? `<details><summary>${renderOptionalProjectUiMessage(portalContext, "portal.binding.targets", "Targets / 目标")} (${escapeHtml(String(binding.targets.length))})</summary><ul>${targets}</ul></details>` : "",
1645
2310
  "</li>"
1646
2311
  ].join("");
1647
2312
  }).join("");
1648
2313
  return [
1649
2314
  "<section class=\"hia-project-summary hia-generated-binding-relations\">",
1650
- "<h2>Generated Documentation Bindings / 生成式文档绑定</h2>",
2315
+ `<h2>${renderOptionalProjectUiMessage(portalContext, "portal.binding.heading", "Generated Documentation Bindings / 生成式文档绑定")}</h2>`,
1651
2316
  `<p>${escapeHtml(projection.contract)}@${escapeHtml(projection.contractVersion)} · ${escapeHtml(projection.status)}</p>`,
1652
2317
  `<ul class=\"hia-project-group-list\">${summaryItems}</ul>`,
1653
- bindings ? `<ul class=\"hia-project-relation-list\">${bindings}</ul>` : "<p>No binding relations available.</p>",
2318
+ bindings ? `<ul class=\"hia-project-relation-list\">${bindings}</ul>` : `<p>${renderOptionalProjectUiMessage(portalContext, "portal.binding.none", "No binding relations available.")}</p>`,
1654
2319
  "</section>"
1655
2320
  ].join("");
1656
2321
  }
@@ -2530,8 +3195,10 @@ function renderLocaleControl(locales, selectedLocale) {
2530
3195
  }
2531
3196
  function renderSymbol(symbol, document, locales, selectedLocale) {
2532
3197
  const signature = symbol.signature ? `<pre class="hia-signature"><code>${escapeHtml(symbol.signature)}</code></pre>` : "";
2533
- const description = renderI18nField(symbol, "description", locales, selectedLocale, symbol.summary);
2534
- const otherFields = renderAdditionalI18nFields(symbol, locales, selectedLocale);
3198
+ // <lang><zh-CN>纯.NET summary与description共用主字段选择,主字段只呈现一次,附加字段全部保留。</zh-CN><en>.NET summary and description share primary-field selection, showing the primary once and retaining every additional field.</en></lang>
3199
+ const primaryPath = getPrimaryI18nFieldPath(symbol);
3200
+ const description = renderI18nField(symbol, primaryPath, locales, selectedLocale, symbol.summary);
3201
+ const otherFields = renderAdditionalI18nFields(symbol, locales, selectedLocale, primaryPath);
2535
3202
  const source = renderSource(symbol);
2536
3203
  return [
2537
3204
  `<article class="hia-symbol" id="${escapeHtml(symbol.id)}">`,
@@ -2544,9 +3211,15 @@ function renderSymbol(symbol, document, locales, selectedLocale) {
2544
3211
  "</article>"
2545
3212
  ].join("");
2546
3213
  }
2547
- function renderAdditionalI18nFields(symbol, locales, selectedLocale) {
3214
+ /** @lang zh-CN description优先,其次summary,无模型时仍用description承载普通摘要回退。 @lang en Prefers description, then summary, retaining description for plain-summary fallback without a model. */
3215
+ function getPrimaryI18nFieldPath(owner) {
3216
+ return owner.i18n?.fields.description ? "description" : owner.i18n?.fields.summary ? "summary" : "description";
3217
+ }
3218
+ /** @lang zh-CN 按原顺序遍历所有附加字段;不按.NET字段清单过滤,不修改输入或把字段文本当HTML。 @lang en Iterates all additional fields in input order without a .NET whitelist, input mutation, or interpreting field text as HTML. */
3219
+ function renderAdditionalI18nFields(symbol, locales, selectedLocale, primaryPath = "description") {
2548
3220
  const fields = symbol.i18n?.fields || {};
2549
- const fieldEntries = Object.entries(fields).filter(([fieldPath]) => fieldPath !== "description");
3221
+ // <lang><zh-CN>只移除已显示的主字段,允许summary与description同时完整显示。</zh-CN><en>Remove only the already-rendered primary field, allowing summary and description to coexist completely.</en></lang>
3222
+ const fieldEntries = Object.entries(fields).filter(([fieldPath]) => fieldPath !== primaryPath);
2550
3223
  if (fieldEntries.length === 0) {
2551
3224
  return "";
2552
3225
  }
@@ -2560,13 +3233,18 @@ function renderAdditionalI18nFields(symbol, locales, selectedLocale) {
2560
3233
  .join("");
2561
3234
  return items ? `<section class="hia-i18n-fields"><h3>Localized Fields</h3><dl>${items}</dl></section>` : "";
2562
3235
  }
3236
+ /** @lang zh-CN 渲染每个locale的纯文本与明确fallback;所有locale均无正文时省略空字段。 @lang en Renders plain text and explicit fallback per locale, omitting fields with no prose in any locale. */
2563
3237
  function renderI18nField(symbol, fieldPath, locales, selectedLocale, fallbackText = "") {
2564
3238
  const field = getI18nField(symbol.i18n, fieldPath);
2565
3239
  if (!field && !fallbackText) {
2566
3240
  return "";
2567
3241
  }
3242
+ // <lang><zh-CN>缺译不等于空字段:先用现有解析规则核全部locale,保留任何可解析正文。</zh-CN><en>A missing translation is not an empty field: use existing resolution rules across all locales and retain any resolvable prose.</en></lang>
3243
+ const resolveOptions = createI18nResolveOptions(symbol);
3244
+ if (field && !fallbackText && !locales.some((locale) => resolveI18nFieldText(field, locale, resolveOptions).text.length > 0))
3245
+ return "";
2568
3246
  const blocks = locales
2569
- .map((locale) => renderLocalizedBlock(field, locale, selectedLocale, createI18nResolveOptions(symbol), fallbackText))
3247
+ .map((locale) => renderLocalizedBlock(field, locale, selectedLocale, resolveOptions, fallbackText))
2570
3248
  .join("");
2571
3249
  return `<div class="hia-localized-set" data-hia-i18n-field="${escapeHtml(fieldPath)}">${blocks}</div>`;
2572
3250
  }
@@ -2582,7 +3260,7 @@ function renderLocalizedBlock(field, locale, selectedLocale, options, fallbackTe
2582
3260
  ? `<span class="hia-fallback-badge">fallback: ${escapeHtml(resolved.resolvedLocale)}</span>`
2583
3261
  : "";
2584
3262
  return [
2585
- `<p class="hia-localized-text" data-hia-locale="${escapeHtml(locale)}"${fallbackAttrs}${hidden}>`,
3263
+ `<p class="hia-localized-text" data-hia-locale="${escapeHtml(locale)}" lang="${escapeHtml(locale)}"${fallbackAttrs}${hidden}>`,
2586
3264
  escapeHtml(resolved.text),
2587
3265
  fallbackBadge,
2588
3266
  "</p>"
@@ -2718,6 +3396,7 @@ function resolveProjectLocaleModel(projectInput, requestedLocale) {
2718
3396
  }
2719
3397
  return { selectedLocale, locales };
2720
3398
  }
3399
+ /** @lang zh-CN 从不修改的i18n owner读取默认/fallback语言,保持各渲染路径一致。 @lang en Reads default/fallback locales from an unmodified i18n owner consistently across rendering routes. */
2721
3400
  function createI18nResolveOptions(symbol) {
2722
3401
  return createI18nResolveOptionsFromModel(symbol.i18n);
2723
3402
  }