@hia-doc/renderer-html 0.1.1 → 0.1.3

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
@@ -49,24 +49,28 @@ export function renderHtmlDocument(document, options = {}) {
49
49
  };
50
50
  }
51
51
  export function renderProjectHtmlDocument(projectInput, options = {}) {
52
- const normalizedProjectInput = normalizeProjectRelationGraphInput(projectInput);
52
+ const sourcePreparedProjectInput = applyProjectSourcePresentationPolicy(projectInput, options);
53
+ const normalizedProjectInput = normalizeProjectRelationGraphInput(sourcePreparedProjectInput);
53
54
  const pageTitle = options.title ?? normalizedProjectInput.project.title ?? normalizedProjectInput.project.name;
54
55
  const includeThemeAssets = options.includeThemeAssets ?? true;
56
+ const siteLayout = options.projectSite?.layout ?? "split-site";
55
57
  const navigationIndex = createProjectNavigationIndex(normalizedProjectInput, pageTitle, options);
56
- const files = [
57
- {
58
- path: "index.html",
59
- contents: renderProjectIndexHtml(pageTitle, normalizedProjectInput, options),
60
- contentType: "text/html; charset=utf-8",
61
- role: "entry"
62
- },
63
- {
64
- path: "project-index.json",
65
- contents: `${JSON.stringify(navigationIndex, null, 2)}\n`,
66
- contentType: "application/json; charset=utf-8",
67
- role: "index"
68
- }
69
- ];
58
+ const files = siteLayout === "single-page"
59
+ ? [
60
+ {
61
+ path: "index.html",
62
+ contents: renderProjectIndexHtml(pageTitle, normalizedProjectInput, options),
63
+ contentType: "text/html; charset=utf-8",
64
+ role: "entry"
65
+ }
66
+ ]
67
+ : createProjectSplitSiteFiles(pageTitle, normalizedProjectInput, navigationIndex, options);
68
+ files.push({
69
+ path: "project-index.json",
70
+ contents: `${JSON.stringify(navigationIndex, null, 2)}\n`,
71
+ contentType: "application/json; charset=utf-8",
72
+ role: "index"
73
+ });
70
74
  if (includeThemeAssets) {
71
75
  for (const asset of getDefaultThemeAssets()) {
72
76
  files.push({
@@ -83,6 +87,42 @@ export function renderProjectHtmlDocument(projectInput, options = {}) {
83
87
  manifest: createProjectManifest(normalizedProjectInput, files, pageTitle, options, navigationIndex)
84
88
  };
85
89
  }
90
+ /**
91
+ * 在 renderer 公共入口执行源码呈现边界,保证直接库调用与 CLI 调用具有同一隐私语义。
92
+ * Enforces source-presentation boundaries at the renderer API so direct library and CLI calls share the same privacy semantics.
93
+ */
94
+ function applyProjectSourcePresentationPolicy(projectInput, options) {
95
+ const presentation = options.projectSite?.source?.presentation ?? "link";
96
+ return {
97
+ ...projectInput,
98
+ entries: projectInput.entries.map((entry) => {
99
+ if (!entry.source) {
100
+ return entry;
101
+ }
102
+ const { preview, fetchUrl, linkUrl, ...locator } = entry.source;
103
+ const previewDefaultExpanded = options.projectSite?.source?.defaultExpanded ?? preview?.defaultExpanded;
104
+ const source = {
105
+ ...locator,
106
+ ...(presentation !== "none" && linkUrl ? { linkUrl } : {}),
107
+ ...(presentation === "embed" && preview ? {
108
+ preview: {
109
+ ...preview,
110
+ ...(previewDefaultExpanded !== undefined ? { defaultExpanded: previewDefaultExpanded } : {})
111
+ }
112
+ } : {}),
113
+ ...(presentation === "fetch" && fetchUrl ? {
114
+ fetchUrl,
115
+ fetchTrigger: options.projectSite?.source?.fetchTrigger ?? entry.source.fetchTrigger ?? "on-expand",
116
+ fetchMaxLines: options.projectSite?.source?.maxLines ?? entry.source.fetchMaxLines ?? 400
117
+ } : {})
118
+ };
119
+ return {
120
+ ...entry,
121
+ source
122
+ };
123
+ })
124
+ };
125
+ }
86
126
  function createManifest(document, files, options) {
87
127
  return {
88
128
  schemaVersion: HIA_RENDER_HTML_MANIFEST_SCHEMA_VERSION,
@@ -171,6 +211,8 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
171
211
  ...(entry.input ? { input: entry.input } : {}),
172
212
  ...(entry.source ? { source: omitProjectSourcePreview(entry.source) } : {}),
173
213
  ...(entry.symbolId ? { symbolId: entry.symbolId } : {}),
214
+ ...(entry.hierarchy ? { hierarchy: entry.hierarchy } : {}),
215
+ contentPath: createProjectEntryContentPath(entry.id),
174
216
  ...(entry.docSourceMap ? { docSourceMap: entry.docSourceMap } : {})
175
217
  }))
176
218
  .sort(compareProjectNavigationEntries),
@@ -178,11 +220,122 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
178
220
  navigationTree: collectProjectNavigationTree(projectInput.entries),
179
221
  profiles: [...(projectInput.profiles ?? [])].sort(compareProjectProfiles),
180
222
  docSourceMaps: [...(projectInput.docSourceMaps ?? [])].sort(compareProjectDocSourceMaps),
223
+ site: {
224
+ layout: options.projectSite?.layout ?? "split-site",
225
+ ...(options.projectSite?.layout === "single-page" ? {} : {
226
+ navigationRootPath: "navigation/root.json",
227
+ searchIndexPath: "search/index.json",
228
+ relationIndexPath: "relations/project.json"
229
+ }),
230
+ sourcePresentation: options.projectSite?.source?.presentation ?? "link"
231
+ },
181
232
  ...(projectInput.relationGraph && projectInput.relationGraph.relationCount > 0
182
233
  ? { relationGraph: projectInput.relationGraph }
183
234
  : {})
184
235
  };
185
236
  }
237
+ /**
238
+ * 生成大型项目默认使用的 split-site 文件集合;入口页只保留应用壳。
239
+ * Generates the split-site file set used by large projects by default; the entry page only keeps the application shell.
240
+ */
241
+ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, options) {
242
+ const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
243
+ const files = [
244
+ {
245
+ path: "index.html",
246
+ contents: renderProjectSplitSiteHtml(pageTitle, projectInput, options),
247
+ contentType: "text/html; charset=utf-8",
248
+ role: "entry"
249
+ },
250
+ ...createProjectNavigationShardFiles(navigationIndex.navigationTree),
251
+ {
252
+ path: "search/index.json",
253
+ contents: `${JSON.stringify({
254
+ contract: "hia-project-search-index",
255
+ contractVersion: "0.1.0-draft",
256
+ entries: projectInput.entries.map((entry) => ({
257
+ id: entry.id,
258
+ name: entry.name,
259
+ kind: entry.kind,
260
+ view: entry.view,
261
+ contentPath: createProjectEntryContentPath(entry.id),
262
+ searchText: createProjectEntrySearchText(entry)
263
+ }))
264
+ }, null, 2)}\n`,
265
+ contentType: "application/json; charset=utf-8",
266
+ role: "index"
267
+ },
268
+ {
269
+ path: "relations/project.json",
270
+ contents: `${JSON.stringify(projectInput.relationGraph ?? createProjectRelationGraph(projectInput.entries), null, 2)}\n`,
271
+ contentType: "application/json; charset=utf-8",
272
+ role: "index"
273
+ }
274
+ ];
275
+ for (const entry of projectInput.entries) {
276
+ files.push({
277
+ path: createProjectEntryContentPath(entry.id),
278
+ contents: renderProjectEntry(entry, localeModel.locales, localeModel.selectedLocale),
279
+ contentType: "text/html; charset=utf-8",
280
+ role: "asset"
281
+ });
282
+ }
283
+ return files;
284
+ }
285
+ function createProjectNavigationShardFiles(nodes) {
286
+ const files = [];
287
+ const emittedPaths = new Set();
288
+ const emitChildren = (nodeId, children, root = false) => {
289
+ const shardPath = root ? "navigation/root.json" : createProjectNavigationChildrenPath(nodeId);
290
+ if (emittedPaths.has(shardPath)) {
291
+ return;
292
+ }
293
+ emittedPaths.add(shardPath);
294
+ files.push({
295
+ path: shardPath,
296
+ contents: `${JSON.stringify({
297
+ contract: "hia-project-navigation-shard",
298
+ contractVersion: "0.1.0-draft",
299
+ nodeId,
300
+ children: children.map(toLazyProjectNavigationNode)
301
+ }, null, 2)}\n`,
302
+ contentType: "application/json; charset=utf-8",
303
+ role: "index"
304
+ });
305
+ for (const child of children) {
306
+ if (child.children && child.children.length > 0) {
307
+ emitChildren(child.id, child.children);
308
+ }
309
+ }
310
+ };
311
+ emitChildren("root", nodes, true);
312
+ return files;
313
+ }
314
+ function toLazyProjectNavigationNode(node) {
315
+ const { children: _children, ...lazyNode } = node;
316
+ return {
317
+ ...lazyNode,
318
+ ...(node.children && node.children.length > 0
319
+ ? { childrenPath: createProjectNavigationChildrenPath(node.id) }
320
+ : {}),
321
+ ...(node.entryId ? { contentPath: createProjectEntryContentPath(node.entryId) } : {})
322
+ };
323
+ }
324
+ function createProjectEntryContentPath(entryId) {
325
+ return `entries/${stableProjectArtifactName(entryId)}.html`;
326
+ }
327
+ function createProjectNavigationChildrenPath(nodeId) {
328
+ return `navigation/${stableProjectArtifactName(nodeId)}.json`;
329
+ }
330
+ function stableProjectArtifactName(value) {
331
+ let hash = 2166136261;
332
+ for (const character of value) {
333
+ hash ^= character.codePointAt(0) ?? 0;
334
+ hash = Math.imul(hash, 16777619);
335
+ }
336
+ const slug = value.toLowerCase().replace(/[^a-z0-9._-]+/gu, "-").replace(/^-|-$/gu, "").slice(0, 72) || "item";
337
+ return `${slug}-${(hash >>> 0).toString(16).padStart(8, "0")}`;
338
+ }
186
339
  function omitProjectSourcePreview(source) {
187
340
  const { preview: _preview, ...sourceWithoutPreview } = source;
188
341
  return sourceWithoutPreview;
@@ -232,6 +385,291 @@ function renderIndexHtml(pageTitle, document, options) {
232
385
  "</html>"
233
386
  ].join("");
234
387
  }
388
+ function renderProjectSplitSiteHtml(pageTitle, projectInput, options) {
389
+ const projectName = projectInput.project.title ?? projectInput.project.name;
390
+ const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
391
+ const views = collectProjectViews(projectInput.entries);
392
+ const entryCounts = countEntriesByView(projectInput.entries);
393
+ const selectedChinese = localeModel.selectedLocale.toLowerCase().startsWith("zh");
394
+ const labels = selectedChinese
395
+ ? {
396
+ hierarchy: "层级导航",
397
+ loading: "正在加载文档导航...",
398
+ open: "打开",
399
+ relations: "项目关系",
400
+ select: "请从左侧层级树选择一个文档节点。",
401
+ search: "搜索",
402
+ searchPlaceholder: "名称、类型、源码或选择器",
403
+ requiresServer: "按需加载站点需要通过 HTTP(S) 提供;请使用本地静态服务器打开该目录。"
404
+ }
405
+ : {
406
+ hierarchy: "Hierarchy",
407
+ loading: "Loading documentation navigation...",
408
+ open: "Open",
409
+ relations: "Project relations",
410
+ select: "Select a documentation node from the hierarchy.",
411
+ search: "Search",
412
+ searchPlaceholder: "Name, kind, source, selector",
413
+ requiresServer: "The lazy site must be served over HTTP(S); open this directory through a local static server."
414
+ };
415
+ return [
416
+ "<!doctype html>",
417
+ `<html lang="${escapeHtml(localeModel.selectedLocale)}">`,
418
+ "<head>",
419
+ "<meta charset=\"utf-8\">",
420
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
421
+ `<title>${escapeHtml(pageTitle)}</title>`,
422
+ "<link rel=\"icon\" href=\"data:,\">",
423
+ `<link rel="stylesheet" href="${escapeHtml(DEFAULT_THEME_CSS_PATH)}">`,
424
+ "</head>",
425
+ "<body>",
426
+ "<div class=\"hia-shell hia-project-shell hia-project-split-site\">",
427
+ "<aside class=\"hia-sidebar\">",
428
+ `<h1>${escapeHtml(projectName)}</h1>`,
429
+ renderLocaleControl(localeModel.locales, localeModel.selectedLocale),
430
+ renderProjectViewControl(views, entryCounts),
431
+ [
432
+ "<label class=\"hia-project-search\">",
433
+ `<span>${escapeHtml(labels.search)}</span>`,
434
+ `<input type="search" data-hia-project-search placeholder="${escapeHtml(labels.searchPlaceholder)}">`,
435
+ "</label>"
436
+ ].join(""),
437
+ `<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>`,
438
+ `<button type="button" class="hia-project-secondary-action" data-hia-project-relations>${escapeHtml(labels.relations)}</button>`,
439
+ "</aside>",
440
+ `<main class="hia-main hia-project-main" data-hia-project-content><p class="hia-project-empty">${escapeHtml(labels.select)}</p></main>`,
441
+ "</div>",
442
+ `<script src="${escapeHtml(DEFAULT_THEME_JS_PATH)}"></script>`,
443
+ renderProjectSplitSiteScript(labels.requiresServer, labels.open),
444
+ "</body>",
445
+ "</html>"
446
+ ].join("");
447
+ }
448
+ /**
449
+ * 生成 split-site 与 single-page 共用的 fetch 源码加载逻辑。
450
+ *
451
+ * @lang zh-CN 该脚本默认在 details 展开时加载源码,并保留 manual 按钮模式作为显式配置。
452
+ * @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.
453
+ */
454
+ function renderProjectSourceFetchClientLines(rootExpression) {
455
+ return [
456
+ " async function loadSourceFetch(details) {",
457
+ " if (details.dataset.loaded === 'true' || details.dataset.loading === 'true') return;",
458
+ " const code = details.querySelector('code');",
459
+ " const button = details.querySelector('[data-hia-source-fetch-button]');",
460
+ " const status = details.querySelector('[data-hia-source-fetch-status]');",
461
+ " details.dataset.loading = 'true';",
462
+ " details.setAttribute('aria-busy', 'true');",
463
+ " if (status) {",
464
+ " status.hidden = false;",
465
+ " status.textContent = 'Loading source / 正在加载源码...';",
466
+ " }",
467
+ " try {",
468
+ " const response = await fetch(details.dataset.hiaSourceFetch || '', { credentials: 'omit' });",
469
+ " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
470
+ " const lines = (await response.text()).split(/\\r?\\n/u);",
471
+ " const start = Math.max(1, Number(details.dataset.hiaSourceStart || 1));",
472
+ " const maxLines = Math.max(1, Number(details.dataset.hiaSourceMaxLines || 400));",
473
+ " const declaredEnd = Number(details.dataset.hiaSourceEnd || 0);",
474
+ " const end = declaredEnd >= start ? Math.min(declaredEnd, start + maxLines - 1) : start + maxLines - 1;",
475
+ " if (code) code.textContent = lines.slice(start - 1, end).join('\\n');",
476
+ " details.dataset.loaded = 'true';",
477
+ " if (button) button.hidden = true;",
478
+ " if (status) status.hidden = true;",
479
+ " } catch (error) {",
480
+ " if (status) status.textContent = `Source load failed / 源码加载失败: ${String(error?.message || error)}`;",
481
+ " if (button) {",
482
+ " button.hidden = false;",
483
+ " button.textContent = 'Retry source / 重试加载源码';",
484
+ " }",
485
+ " } finally {",
486
+ " delete details.dataset.loading;",
487
+ " details.removeAttribute('aria-busy');",
488
+ " }",
489
+ " }",
490
+ ` function bindSourceFetch(root = ${rootExpression}) {`,
491
+ " for (const details of root?.querySelectorAll('details[data-hia-source-fetch]') || []) {",
492
+ " const button = details.querySelector('[data-hia-source-fetch-button]');",
493
+ " if (button) button.addEventListener('click', () => loadSourceFetch(details));",
494
+ " if (details.dataset.hiaSourceFetchTrigger !== 'manual') {",
495
+ " details.addEventListener('toggle', () => {",
496
+ " if (details.open) void loadSourceFetch(details);",
497
+ " });",
498
+ " if (details.open) void loadSourceFetch(details);",
499
+ " }",
500
+ " }",
501
+ " }"
502
+ ];
503
+ }
504
+ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
505
+ return [
506
+ "<script>",
507
+ "(() => {",
508
+ " const config = { navigation: 'navigation/root.json', search: 'search/index.json', relations: 'relations/project.json' };",
509
+ " const treeHost = document.querySelector('[data-hia-project-tree]');",
510
+ " const contentHost = document.querySelector('[data-hia-project-content]');",
511
+ " const search = document.querySelector('[data-hia-project-search]');",
512
+ " const locale = document.querySelector('[data-hia-locale-control]');",
513
+ " const viewButtons = Array.from(document.querySelectorAll('[data-hia-project-view]'));",
514
+ " let rootNodes = [];",
515
+ " let searchEntries = null;",
516
+ " let activeView = 'all';",
517
+ " async function readJson(target) {",
518
+ " const response = await fetch(target, { credentials: 'omit' });",
519
+ " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
520
+ " return response.json();",
521
+ " }",
522
+ " function showLoadError(error) {",
523
+ ` const hint = location.protocol === 'file:' ? ${JSON.stringify(fileProtocolMessage)} : String(error?.message || error);`,
524
+ " if (contentHost) contentHost.innerHTML = '';",
525
+ " const message = document.createElement('p');",
526
+ " message.className = 'hia-project-load-error';",
527
+ " message.textContent = hint;",
528
+ " (contentHost || treeHost)?.append(message);",
529
+ " }",
530
+ " function nodeMatchesView(node) {",
531
+ " return activeView === 'all' || (Array.isArray(node.views) && node.views.includes(activeView));",
532
+ " }",
533
+ " function createTreeList(nodes) {",
534
+ " const list = document.createElement('ul');",
535
+ " list.className = 'hia-project-hierarchy-list';",
536
+ " for (const node of nodes.filter(nodeMatchesView)) list.append(createTreeNode(node));",
537
+ " return list;",
538
+ " }",
539
+ " function createTreeNode(node) {",
540
+ " const item = document.createElement('li');",
541
+ " item.dataset.hiaProjectNav = node.views?.[0] || 'other';",
542
+ " if (node.childrenPath) {",
543
+ " const details = document.createElement('details');",
544
+ " const summary = document.createElement('summary');",
545
+ " const summaryLabel = document.createElement('span');",
546
+ " summaryLabel.textContent = `${node.label} (${node.entryCount})`;",
547
+ " summary.append(summaryLabel);",
548
+ " if (node.entryId && node.contentPath) {",
549
+ " const openButton = document.createElement('button');",
550
+ " openButton.type = 'button';",
551
+ " openButton.className = 'hia-project-entry-link hia-project-tree-open';",
552
+ ` openButton.textContent = ${JSON.stringify(openLabel)};`,
553
+ " openButton.addEventListener('click', (event) => {",
554
+ " event.preventDefault();",
555
+ " event.stopPropagation();",
556
+ " loadEntry(node.entryId, node.contentPath, true);",
557
+ " });",
558
+ " summary.append(openButton);",
559
+ " }",
560
+ " details.append(summary);",
561
+ " details.addEventListener('toggle', async () => {",
562
+ " if (!details.open || details.dataset.loaded === 'true') return;",
563
+ " details.dataset.loaded = 'true';",
564
+ " const loading = document.createElement('p');",
565
+ " loading.className = 'hia-project-loading';",
566
+ " loading.textContent = '...';",
567
+ " details.append(loading);",
568
+ " try {",
569
+ " const shard = await readJson(node.childrenPath);",
570
+ " loading.replaceWith(createTreeList(Array.isArray(shard.children) ? shard.children : []));",
571
+ " } catch (error) {",
572
+ " loading.textContent = String(error?.message || error);",
573
+ " }",
574
+ " });",
575
+ " item.append(details);",
576
+ " } else if (node.entryId && node.contentPath) {",
577
+ " const button = document.createElement('button');",
578
+ " button.type = 'button';",
579
+ " button.className = 'hia-project-entry-link';",
580
+ " button.textContent = node.label;",
581
+ " button.addEventListener('click', () => loadEntry(node.entryId, node.contentPath, true));",
582
+ " item.append(button);",
583
+ " } else {",
584
+ " const label = document.createElement('span');",
585
+ " label.textContent = node.label;",
586
+ " item.append(label);",
587
+ " }",
588
+ " return item;",
589
+ " }",
590
+ " function renderRoot() {",
591
+ " if (!treeHost) return;",
592
+ " treeHost.innerHTML = '';",
593
+ " treeHost.append(createTreeList(rootNodes));",
594
+ " }",
595
+ " function applyLocale() {",
596
+ " const selected = String(locale?.value || document.documentElement.lang || 'und');",
597
+ " document.documentElement.lang = selected;",
598
+ " for (const block of document.querySelectorAll('[data-hia-locale]')) {",
599
+ " block.hidden = block.getAttribute('data-hia-locale') !== selected;",
600
+ " }",
601
+ " }",
602
+ ...renderProjectSourceFetchClientLines("contentHost"),
603
+ " async function loadEntry(entryId, contentPath, updateHash) {",
604
+ " if (!contentHost) return;",
605
+ " contentHost.innerHTML = '<p class=\"hia-project-loading\">...</p>';",
606
+ " try {",
607
+ " const response = await fetch(contentPath, { credentials: 'omit' });",
608
+ " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
609
+ " contentHost.innerHTML = await response.text();",
610
+ " applyLocale();",
611
+ " bindSourceFetch();",
612
+ " if (updateHash) history.replaceState(null, '', `#entry=${encodeURIComponent(entryId)}`);",
613
+ " } catch (error) {",
614
+ " showLoadError(error);",
615
+ " }",
616
+ " }",
617
+ " async function ensureSearchIndex() {",
618
+ " if (searchEntries) return searchEntries;",
619
+ " const index = await readJson(config.search);",
620
+ " searchEntries = Array.isArray(index.entries) ? index.entries : [];",
621
+ " return searchEntries;",
622
+ " }",
623
+ " async function runSearch() {",
624
+ " const query = String(search?.value || '').trim().toLowerCase();",
625
+ " if (!query) { renderRoot(); return; }",
626
+ " try {",
627
+ " const entries = await ensureSearchIndex();",
628
+ " const matches = entries.filter((entry) => (activeView === 'all' || entry.view === activeView) && String(entry.searchText || '').includes(query)).slice(0, 200);",
629
+ " if (!treeHost) return;",
630
+ " treeHost.innerHTML = '';",
631
+ " const nodes = matches.map((entry) => ({ id: entry.id, label: `${entry.name} · ${entry.kind}`, entryId: entry.id, contentPath: entry.contentPath, views: [entry.view], entryCount: 1 }));",
632
+ " treeHost.append(createTreeList(nodes));",
633
+ " } catch (error) { showLoadError(error); }",
634
+ " }",
635
+ " for (const button of viewButtons) {",
636
+ " button.addEventListener('click', () => {",
637
+ " activeView = button.dataset.hiaProjectView || 'all';",
638
+ " for (const candidate of viewButtons) candidate.setAttribute('aria-pressed', String(candidate === button));",
639
+ " runSearch();",
640
+ " });",
641
+ " }",
642
+ " search?.addEventListener('input', runSearch);",
643
+ " locale?.addEventListener('change', applyLocale);",
644
+ " document.querySelector('[data-hia-project-relations]')?.addEventListener('click', async () => {",
645
+ " try {",
646
+ " const graph = await readJson(config.relations);",
647
+ " if (!contentHost) return;",
648
+ " contentHost.innerHTML = '';",
649
+ " const article = document.createElement('article');",
650
+ " article.className = 'hia-symbol';",
651
+ " const heading = document.createElement('h2');",
652
+ " heading.textContent = 'Relations';",
653
+ " const summary = document.createElement('p');",
654
+ " summary.textContent = `${graph.nodeCount || 0} node(s), ${graph.relationCount || 0} relation(s).`;",
655
+ " article.append(heading, summary);",
656
+ " contentHost.append(article);",
657
+ " } catch (error) { showLoadError(error); }",
658
+ " });",
659
+ " readJson(config.navigation).then((shard) => {",
660
+ " rootNodes = Array.isArray(shard.children) ? shard.children : [];",
661
+ " renderRoot();",
662
+ " const hash = location.hash.startsWith('#entry=') ? decodeURIComponent(location.hash.slice(7)) : '';",
663
+ " if (hash) ensureSearchIndex().then((entries) => {",
664
+ " const entry = entries.find((candidate) => candidate.id === hash);",
665
+ " if (entry) loadEntry(entry.id, entry.contentPath, false);",
666
+ " });",
667
+ " }).catch(showLoadError);",
668
+ " viewButtons.find((button) => button.dataset.hiaProjectView === 'all')?.setAttribute('aria-pressed', 'true');",
669
+ "})();",
670
+ "</script>"
671
+ ].join("");
672
+ }
235
673
  function renderProjectIndexHtml(pageTitle, projectInput, options) {
236
674
  const projectName = projectInput.project.title ?? projectInput.project.name;
237
675
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
@@ -367,6 +805,7 @@ function renderProjectEntry(entry, locales, selectedLocale) {
367
805
  const summary = renderProjectEntrySummary(entry, locales, selectedLocale);
368
806
  const input = entry.input ? renderProjectEntryInput(entry.input) : "";
369
807
  const profile = entry.profile ? renderProjectEntryProfile(entry.profile) : "";
808
+ const hierarchy = entry.hierarchy ? renderProjectEntryHierarchy(entry.hierarchy) : "";
370
809
  const source = entry.source ? renderProjectEntrySource(entry.source) : "";
371
810
  const docSourceMap = entry.docSourceMap ? renderProjectEntryDocSourceMap(entry.docSourceMap) : "";
372
811
  const diagnostics = renderProjectDiagnostics(entry.diagnostics ?? []);
@@ -380,14 +819,31 @@ function renderProjectEntry(entry, locales, selectedLocale) {
380
819
  summary,
381
820
  input,
382
821
  profile,
822
+ hierarchy,
383
823
  source,
384
824
  docSourceMap,
385
825
  diagnostics,
386
826
  "</article>"
387
827
  ].join("");
388
828
  }
829
+ function renderProjectEntryHierarchy(hierarchy) {
830
+ const details = [
831
+ hierarchy.assembly ? `<dt>Assembly</dt><dd>${escapeHtml(hierarchy.assembly)}</dd>` : "",
832
+ hierarchy.namespace ? `<dt>Namespace</dt><dd>${escapeHtml(hierarchy.namespace)}</dd>` : "",
833
+ hierarchy.containingType ? `<dt>Containing Type</dt><dd>${escapeHtml(hierarchy.containingType)}</dd>` : "",
834
+ hierarchy.symbolDocumentationId ? `<dt>Documentation ID</dt><dd>${escapeHtml(hierarchy.symbolDocumentationId)}</dd>` : "",
835
+ hierarchy.parentSymbolId ? `<dt>Parent</dt><dd>${escapeHtml(hierarchy.parentSymbolId)}</dd>` : "",
836
+ hierarchy.baseTypeIds && hierarchy.baseTypeIds.length > 0
837
+ ? `<dt>Inheritance</dt><dd>${escapeHtml(hierarchy.baseTypeIds.join(" -> "))}</dd>`
838
+ : "",
839
+ hierarchy.interfaceIds && hierarchy.interfaceIds.length > 0
840
+ ? `<dt>Interfaces</dt><dd>${escapeHtml(hierarchy.interfaceIds.join(", "))}</dd>`
841
+ : ""
842
+ ].join("");
843
+ return details ? `<dl class="hia-project-meta hia-project-hierarchy-meta">${details}</dl>` : "";
844
+ }
389
845
  function renderProjectEntrySummary(entry, locales, selectedLocale) {
390
- const field = entry.i18n?.fields.description;
846
+ const field = entry.i18n?.fields.description ?? entry.i18n?.fields.summary;
391
847
  if (!field && !entry.summary) {
392
848
  return "";
393
849
  }
@@ -423,7 +879,27 @@ function renderProjectEntrySource(source) {
423
879
  source.confidence ? `<dt>Confidence</dt><dd>${escapeHtml(source.confidence)}</dd>` : ""
424
880
  ].join("");
425
881
  const preview = source.preview ? renderProjectSourcePreview(source.preview, source.path) : "";
426
- return `<section class="hia-source-section"><h3>Source</h3><dl class="hia-project-meta">${sourceDetails}</dl>${preview}</section>`;
882
+ const fetchPreview = source.fetchUrl ? renderProjectSourceFetch(source) : "";
883
+ return `<section class="hia-source-section"><h3>Source</h3><dl class="hia-project-meta">${sourceDetails}</dl>${preview}${fetchPreview}</section>`;
884
+ }
885
+ function renderProjectSourceFetch(source) {
886
+ const startLine = source.range?.start.line ?? 1;
887
+ const endLine = source.range?.end?.line;
888
+ const fetchTrigger = source.fetchTrigger ?? "on-expand";
889
+ const maxLines = source.fetchMaxLines ?? 400;
890
+ const caption = endLine ? `${source.path}:${startLine}-${endLine}` : `${source.path}:${startLine}`;
891
+ const endAttribute = endLine ? ` data-hia-source-end="${escapeHtml(String(endLine))}"` : "";
892
+ const manualButton = fetchTrigger === "manual"
893
+ ? "<button type=\"button\" class=\"hia-source-fetch-button\" data-hia-source-fetch-button>Load source / 加载源码</button>"
894
+ : "";
895
+ return [
896
+ `<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))}">`,
897
+ `<summary>${escapeHtml(caption)}</summary>`,
898
+ manualButton,
899
+ "<p class=\"hia-project-loading\" data-hia-source-fetch-status hidden></p>",
900
+ `<pre class="hia-source-code"><code data-language="${escapeHtml(source.language ?? "")}"></code></pre>`,
901
+ "</details>"
902
+ ].join("");
427
903
  }
428
904
  function renderProjectEntryDocSourceMap(docSourceMap) {
429
905
  const sourceRange = docSourceMap.sourceRange ? `:${docSourceMap.sourceRange.start.line}${docSourceMap.sourceRange.end ? `-${docSourceMap.sourceRange.end.line}` : ""}` : "";
@@ -578,6 +1054,7 @@ function renderProjectViewScript() {
578
1054
  " const search = document.querySelector('[data-hia-project-search]');",
579
1055
  " const empty = document.querySelector('[data-hia-project-empty]');",
580
1056
  " let activeView = 'all';",
1057
+ ...renderProjectSourceFetchClientLines("document"),
581
1058
  " function matchesFilter(item, view, query) {",
582
1059
  " const viewName = item.dataset.hiaProjectEntry || item.dataset.hiaProjectNav || 'other';",
583
1060
  " const text = (item.dataset.hiaProjectSearchText || '').toLowerCase();",
@@ -611,6 +1088,7 @@ function renderProjectViewScript() {
611
1088
  " }, window.location.protocol === 'file:' || window.location.origin === 'null' ? '*' : window.location.origin);",
612
1089
  " });",
613
1090
  " }",
1091
+ " bindSourceFetch();",
614
1092
  " activate('all');",
615
1093
  "})();",
616
1094
  "</script>"
@@ -812,7 +1290,7 @@ function collectProjectNavigationTree(entries) {
812
1290
  }
813
1291
  const children = view === "dotnet"
814
1292
  ? collectDotNetNavigationTree(viewEntries)
815
- : collectSourceNavigationTree(viewEntries);
1293
+ : collectSemanticSourceNavigationTree(viewEntries);
816
1294
  return [{
817
1295
  id: `view:${view}`,
818
1296
  kind: "view",
@@ -827,17 +1305,34 @@ function collectDotNetNavigationTree(entries) {
827
1305
  const roots = new Map();
828
1306
  for (const entry of entries) {
829
1307
  const parts = getDotNetNavigationParts(entry);
830
- const namespaceNode = getOrCreateProjectTreeChild(roots, `dotnet:namespace:${slugProjectGroupLabel(parts.namespaceLabel)}`, "namespace", parts.namespaceLabel);
831
- addProjectTreeEntry(namespaceNode, entry);
832
- const typeNode = getOrCreateProjectTreeChild(namespaceNode.childrenById, `${namespaceNode.id}:type:${slugProjectGroupLabel(parts.typeLabel)}`, "type", parts.typeLabel);
833
- namespaceNode.children = [...namespaceNode.childrenById.values()];
1308
+ const assemblyNode = getOrCreateProjectTreeChild(roots, `dotnet:${parts.rootKind}:${slugProjectGroupLabel(parts.assemblyLabel)}`, parts.rootKind, parts.assemblyLabel);
1309
+ addProjectTreeEntry(assemblyNode, entry);
1310
+ let namespaceParent = assemblyNode;
1311
+ const namespaceSegments = parts.namespaceLabel === "(global namespace)"
1312
+ ? [parts.namespaceLabel]
1313
+ : parts.namespaceLabel.split(".").filter(Boolean);
1314
+ let qualifiedNamespace = "";
1315
+ for (const namespaceSegment of namespaceSegments) {
1316
+ qualifiedNamespace = qualifiedNamespace
1317
+ ? `${qualifiedNamespace}.${namespaceSegment}`
1318
+ : namespaceSegment;
1319
+ const namespaceNode = getOrCreateProjectTreeChild(namespaceParent.childrenById, `${assemblyNode.id}:namespace:${slugProjectGroupLabel(qualifiedNamespace)}`, "namespace", namespaceSegment);
1320
+ namespaceParent.children = [...namespaceParent.childrenById.values()];
1321
+ addProjectTreeEntry(namespaceNode, entry);
1322
+ namespaceParent = namespaceNode;
1323
+ }
1324
+ const typeNode = getOrCreateProjectTreeChild(namespaceParent.childrenById, `${namespaceParent.id}:type:${slugProjectGroupLabel(parts.typeId)}`, "type", parts.typeLabel);
1325
+ namespaceParent.children = [...namespaceParent.childrenById.values()];
834
1326
  addProjectTreeEntry(typeNode, entry);
835
- if (entry.kind === "dotnet-type") {
1327
+ if (isDotNetTypeNavigationEntry(entry)) {
836
1328
  typeNode.entryId = entry.id;
837
1329
  assignProjectTreeEntryRefs(typeNode, entry);
1330
+ if (entry.kind === "dotnet-type") {
1331
+ addDotNetInheritanceNodes(typeNode, entry);
1332
+ }
838
1333
  continue;
839
1334
  }
840
- const entryNode = getOrCreateProjectTreeChild(typeNode.childrenById, `${typeNode.id}:entry:${slugProjectGroupLabel(entry.id)}`, "entry", parts.memberLabel);
1335
+ const entryNode = getOrCreateProjectTreeChild(typeNode.childrenById, `${typeNode.id}:entry:${entry.id}`, "entry", parts.memberLabel);
841
1336
  typeNode.children = [...typeNode.childrenById.values()];
842
1337
  addProjectTreeEntry(entryNode, entry);
843
1338
  entryNode.entryId = entry.id;
@@ -845,9 +1340,34 @@ function collectDotNetNavigationTree(entries) {
845
1340
  }
846
1341
  return sortProjectTreeNodes([...roots.values()].map(finalizeProjectTreeBuilder));
847
1342
  }
848
- function collectSourceNavigationTree(entries) {
1343
+ function addDotNetInheritanceNodes(typeNode, entry) {
1344
+ for (const baseTypeId of entry.hierarchy?.baseTypeIds ?? []) {
1345
+ const relationNode = getOrCreateProjectTreeChild(typeNode.childrenById, `${typeNode.id}:base:${slugProjectGroupLabel(baseTypeId)}`, "relation", `Base: ${baseTypeId.replace(/^T:/u, "")}`);
1346
+ relationNode.views.add(entry.view);
1347
+ }
1348
+ for (const interfaceId of entry.hierarchy?.interfaceIds ?? []) {
1349
+ const relationNode = getOrCreateProjectTreeChild(typeNode.childrenById, `${typeNode.id}:interface:${slugProjectGroupLabel(interfaceId)}`, "relation", `Interface: ${interfaceId.replace(/^T:/u, "")}`);
1350
+ relationNode.views.add(entry.view);
1351
+ }
1352
+ typeNode.children = [...typeNode.childrenById.values()];
1353
+ }
1354
+ /**
1355
+ * 为非 .NET 领域保留源码目录,同时在 adapter 提供 parentSymbolId 时恢复 module/class/member 层级。
1356
+ * Preserves source grouping for non-.NET domains while restoring module/class/member hierarchy when adapters provide parentSymbolId.
1357
+ */
1358
+ function collectSemanticSourceNavigationTree(entries) {
849
1359
  const roots = new Map();
1360
+ const nodesByEntryId = new Map();
1361
+ const entriesBySymbolId = new Map();
1362
+ const fileNodesByEntryId = new Map();
850
1363
  for (const entry of entries) {
1364
+ if (entry.symbolId) {
1365
+ entriesBySymbolId.set(entry.symbolId, entry);
1366
+ }
1367
+ const entryNode = getOrCreateProjectTreeChild(nodesByEntryId, `entry:${entry.id}`, isProjectTypeLikeKind(entry.kind) ? "type" : "entry", entry.name);
1368
+ addProjectTreeEntry(entryNode, entry);
1369
+ entryNode.entryId = entry.id;
1370
+ assignProjectTreeEntryRefs(entryNode, entry);
851
1371
  const sourceRootLabel = getProjectSourceRoot(entry.source?.path);
852
1372
  const sourcePathLabel = entry.source?.path?.replaceAll("\\", "/") || "unknown-source";
853
1373
  const rootNode = getOrCreateProjectTreeChild(roots, `source-root:${slugProjectGroupLabel(sourceRootLabel)}`, "source-root", sourceRootLabel);
@@ -856,14 +1376,46 @@ function collectSourceNavigationTree(entries) {
856
1376
  rootNode.children = [...rootNode.childrenById.values()];
857
1377
  addProjectTreeEntry(fileNode, entry);
858
1378
  assignProjectTreeSourcePath(fileNode, entry.source?.path);
859
- const entryNode = getOrCreateProjectTreeChild(fileNode.childrenById, `${fileNode.id}:entry:${slugProjectGroupLabel(entry.id)}`, "entry", entry.name);
860
- fileNode.children = [...fileNode.childrenById.values()];
861
- addProjectTreeEntry(entryNode, entry);
862
- entryNode.entryId = entry.id;
863
- assignProjectTreeEntryRefs(entryNode, entry);
1379
+ fileNodesByEntryId.set(entry.id, fileNode);
1380
+ }
1381
+ for (const entry of entries) {
1382
+ const entryNode = nodesByEntryId.get(`entry:${entry.id}`);
1383
+ const parentEntry = entry.hierarchy?.parentSymbolId
1384
+ ? entriesBySymbolId.get(entry.hierarchy.parentSymbolId)
1385
+ : undefined;
1386
+ const parentNode = parentEntry
1387
+ ? nodesByEntryId.get(`entry:${parentEntry.id}`)
1388
+ : undefined;
1389
+ const sameSource = parentEntry?.source?.path === entry.source?.path;
1390
+ if (entryNode && parentEntry && parentNode && sameSource && parentNode !== entryNode) {
1391
+ parentNode.childrenById.set(entryNode.id, entryNode);
1392
+ incrementProjectNavigationAncestorCounts(parentEntry, entriesBySymbolId, nodesByEntryId);
1393
+ continue;
1394
+ }
1395
+ const fileNode = fileNodesByEntryId.get(entry.id);
1396
+ if (entryNode && fileNode) {
1397
+ fileNode.childrenById.set(entryNode.id, entryNode);
1398
+ }
864
1399
  }
865
1400
  return sortProjectTreeNodes([...roots.values()].map(finalizeProjectTreeBuilder));
866
1401
  }
1402
+ function incrementProjectNavigationAncestorCounts(parentEntry, entriesBySymbolId, nodesByEntryId) {
1403
+ const visited = new Set();
1404
+ let current = parentEntry;
1405
+ while (current && !visited.has(current.id)) {
1406
+ visited.add(current.id);
1407
+ const node = nodesByEntryId.get(`entry:${current.id}`);
1408
+ if (node) {
1409
+ node.entryCount += 1;
1410
+ }
1411
+ current = current.hierarchy?.parentSymbolId
1412
+ ? entriesBySymbolId.get(current.hierarchy.parentSymbolId)
1413
+ : undefined;
1414
+ }
1415
+ }
1416
+ function isProjectTypeLikeKind(kind) {
1417
+ return /(?:^|[-_])(class|interface|type|module|namespace|enum|struct|record)(?:$|[-_])/iu.test(kind);
1418
+ }
867
1419
  function getOrCreateProjectTreeChild(map, id, kind, label) {
868
1420
  const existing = map.get(id);
869
1421
  if (existing) {
@@ -897,7 +1449,8 @@ function assignProjectTreeSourcePath(node, sourcePath) {
897
1449
  }
898
1450
  }
899
1451
  function finalizeProjectTreeBuilder(node) {
900
- const children = sortProjectTreeNodes(node.children.map(finalizeProjectTreeBuilder));
1452
+ const childBuilders = node.childrenById.size > 0 ? [...node.childrenById.values()] : node.children;
1453
+ const children = sortProjectTreeNodes(childBuilders.map(finalizeProjectTreeBuilder));
901
1454
  return {
902
1455
  id: node.id,
903
1456
  kind: node.kind,
@@ -923,22 +1476,37 @@ function projectTreeKindOrder(kind) {
923
1476
  if (kind === "view") {
924
1477
  return 0;
925
1478
  }
1479
+ if (kind === "surface" || kind === "project") {
1480
+ return 2;
1481
+ }
926
1482
  if (kind === "namespace") {
927
- return 1;
1483
+ return 3;
928
1484
  }
929
1485
  if (kind === "type") {
930
- return 2;
1486
+ return 4;
1487
+ }
1488
+ if (kind === "relation") {
1489
+ return 5;
1490
+ }
1491
+ if (kind === "assembly") {
1492
+ return 1;
931
1493
  }
932
1494
  if (kind === "source-root") {
933
- return 3;
1495
+ return 6;
934
1496
  }
935
1497
  if (kind === "source-file") {
936
- return 4;
1498
+ return 7;
937
1499
  }
938
- return 5;
1500
+ return 8;
939
1501
  }
940
1502
  function getDotNetNavigationParts(entry) {
941
- const symbolId = entry.symbolId || (entry.id.match(/^[A-Z]:/) ? entry.id : "");
1503
+ const fallback = getDotNetNonAssemblyNavigationParts(entry);
1504
+ const assemblyLabel = entry.hierarchy?.assembly || fallback.assemblyLabel;
1505
+ const semanticNamespace = entry.hierarchy?.namespace;
1506
+ const semanticContainingType = entry.hierarchy?.containingType;
1507
+ const symbolId = entry.hierarchy?.symbolDocumentationId
1508
+ || (entry.symbolId?.match(/^[A-Z]:/) ? entry.symbolId : "")
1509
+ || (entry.id.match(/^[A-Z]:/) ? entry.id : "");
942
1510
  const symbolBody = symbolId.match(/^[A-Z]:/) ? symbolId.slice(2) : "";
943
1511
  const normalizedSymbol = symbolBody.replace(/\(.+$/, "");
944
1512
  const segments = normalizedSymbol.split(".").filter((segment) => segment.length > 0);
@@ -947,17 +1515,60 @@ function getDotNetNavigationParts(entry) {
947
1515
  const typeIndex = entry.kind === "dotnet-type" ? segments.length - 1 : Math.max(0, segments.length - 2);
948
1516
  const typeLabel = segments[typeIndex] ?? entry.name;
949
1517
  const namespaceLabel = segments.slice(0, typeIndex).join(".") || "(global namespace)";
950
- return { memberLabel, namespaceLabel, typeLabel };
1518
+ return {
1519
+ assemblyLabel,
1520
+ memberLabel,
1521
+ namespaceLabel: semanticNamespace || namespaceLabel,
1522
+ rootKind: entry.hierarchy?.assembly ? "assembly" : fallback.rootKind,
1523
+ typeId: semanticContainingType ? `T:${semanticContainingType}` : `T:${segments.slice(0, typeIndex + 1).join(".")}`,
1524
+ typeLabel: semanticContainingType?.split(".").pop() || typeLabel
1525
+ };
951
1526
  }
952
1527
  const sourceStem = entry.source?.path
953
1528
  ? entry.source.path.replaceAll("\\", "/").split("/").pop()?.replace(/\.[^.]+$/, "")
954
1529
  : undefined;
955
1530
  return {
1531
+ assemblyLabel,
956
1532
  memberLabel: entry.name,
1533
+ namespaceLabel: semanticNamespace || fallback.namespaceLabel,
1534
+ rootKind: entry.hierarchy?.assembly ? "assembly" : fallback.rootKind,
1535
+ typeId: semanticContainingType ? `T:${semanticContainingType}` : symbolId || entry.id,
1536
+ typeLabel: semanticContainingType?.split(".").pop() || sourceStem || entry.name
1537
+ };
1538
+ }
1539
+ function getDotNetNonAssemblyNavigationParts(entry) {
1540
+ if (entry.kind === "dotnet-project" || entry.kind === "dotnet-solution") {
1541
+ return {
1542
+ assemblyLabel: ".NET Project Structure",
1543
+ namespaceLabel: entry.kind === "dotnet-solution" ? "Solutions" : "Projects",
1544
+ rootKind: "project"
1545
+ };
1546
+ }
1547
+ if (entry.kind === "aspnet-endpoint" || entry.kind === "dotnet-markup-comment") {
1548
+ const sourceDirectories = (entry.source?.path ?? "")
1549
+ .replaceAll("\\", "/")
1550
+ .split("/")
1551
+ .slice(0, -1)
1552
+ .filter((segment) => segment && segment !== "src" && segment !== "Portal");
1553
+ const category = entry.kind === "aspnet-endpoint" ? "Endpoints" : "Markup";
1554
+ return {
1555
+ assemblyLabel: "ASP.NET Surfaces",
1556
+ namespaceLabel: [category, ...sourceDirectories].join("."),
1557
+ rootKind: "surface"
1558
+ };
1559
+ }
1560
+ return {
1561
+ assemblyLabel: ".NET Other",
957
1562
  namespaceLabel: "(global namespace)",
958
- typeLabel: sourceStem || entry.name
1563
+ rootKind: "assembly"
959
1564
  };
960
1565
  }
1566
+ function isDotNetTypeNavigationEntry(entry) {
1567
+ return entry.kind === "dotnet-type"
1568
+ || entry.kind === "dotnet-project"
1569
+ || entry.kind === "dotnet-solution"
1570
+ || entry.kind === "aspnet-endpoint";
1571
+ }
961
1572
  function collectProjectNavigationGroupsBy(entries, kind, keyFactory) {
962
1573
  const groups = new Map();
963
1574
  for (const entry of entries) {
@@ -1050,6 +1661,12 @@ function createProjectEntrySearchText(entry) {
1050
1661
  entry.summary,
1051
1662
  entry.signature,
1052
1663
  entry.symbolId,
1664
+ entry.hierarchy?.assembly,
1665
+ entry.hierarchy?.namespace,
1666
+ entry.hierarchy?.containingType,
1667
+ entry.hierarchy?.parentSymbolId,
1668
+ ...(entry.hierarchy?.baseTypeIds ?? []),
1669
+ ...(entry.hierarchy?.interfaceIds ?? []),
1053
1670
  entry.view,
1054
1671
  entry.profile?.profileId,
1055
1672
  entry.input?.kind,