repometry 0.4.1 → 0.5.0

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.
Files changed (190) hide show
  1. package/README.md +4 -0
  2. package/package.json +1 -1
  3. package/target/main/resources/report/json/report-v2.schema.json +13 -1
  4. package/target/main/resources/viewer/files.css +7 -3
  5. package/target/main/resources/viewer/styles.css +2 -2
  6. package/target/main/ts/api/git/git.d.ts +1 -0
  7. package/target/main/ts/api/git/git.js +12 -0
  8. package/target/main/ts/api/git/inspection-source.js +2 -8
  9. package/target/main/ts/api/git/local.d.ts +1 -1
  10. package/target/main/ts/api/git/local.js +39 -5
  11. package/target/main/ts/api/process/docker-tool-runner.d.ts +13 -0
  12. package/target/main/ts/api/process/docker-tool-runner.js +108 -0
  13. package/target/main/ts/api/process/failure.d.ts +1 -0
  14. package/target/main/ts/api/process/failure.js +12 -0
  15. package/target/main/ts/api/process/plugin.d.ts +10 -0
  16. package/target/main/ts/api/process/plugin.js +96 -0
  17. package/target/main/ts/compose/analyze-snapshot.d.ts +3 -2
  18. package/target/main/ts/compose/analyze-snapshot.js +82 -29
  19. package/target/main/ts/compose/inspect.d.ts +5 -0
  20. package/target/main/ts/compose/inspect.js +10 -6
  21. package/target/main/ts/core/engine/execute.d.ts +3 -1
  22. package/target/main/ts/core/engine/execute.js +14 -2
  23. package/target/main/ts/core/engine/operation-cache.d.ts +14 -0
  24. package/target/main/ts/core/engine/operation-cache.js +66 -0
  25. package/target/main/ts/core/engine/plan.d.ts +1 -0
  26. package/target/main/ts/core/engine/plan.js +22 -3
  27. package/target/main/ts/core/engine/plugin.d.ts +8 -1
  28. package/target/main/ts/core/engine/plugin.js +1 -3
  29. package/target/main/ts/core/engine/report-products.js +2 -13
  30. package/target/main/ts/core/model/clone-source.js +1 -1
  31. package/target/main/ts/core/model/code-structure.d.ts +3 -0
  32. package/target/main/ts/core/model/code-structure.js +4 -1
  33. package/target/main/ts/core/model/finding-ignore.js +1 -1
  34. package/target/main/ts/core/model/finding.js +1 -1
  35. package/target/main/ts/core/model/line-coverage.d.ts +5 -1
  36. package/target/main/ts/core/model/line-coverage.js +14 -11
  37. package/target/main/ts/core/model/measurement.js +1 -1
  38. package/target/main/ts/core/model/plugin-data.d.ts +2 -0
  39. package/target/main/ts/core/model/plugin-data.js +15 -1
  40. package/target/main/ts/core/model/quality-summary.js +1 -1
  41. package/target/main/ts/core/model/scanner-import.js +1 -1
  42. package/target/main/ts/core/model/snapshot.d.ts +1 -0
  43. package/target/main/ts/core/model/snapshot.js +5 -1
  44. package/target/main/ts/core/model/source.d.ts +3 -0
  45. package/target/main/ts/core/model/source.js +15 -0
  46. package/target/main/ts/core/ports/tool-runner.d.ts +18 -0
  47. package/target/main/ts/core/ports/tool-runner.js +2 -0
  48. package/target/main/ts/plugin.d.ts +7 -1
  49. package/target/main/ts/plugin.js +3 -1
  50. package/target/main/ts/plugins/coverage/coverage.d.ts +5 -2
  51. package/target/main/ts/plugins/coverage/coverage.js +35 -10
  52. package/target/main/ts/plugins/language-js/function-facts.d.ts +1 -0
  53. package/target/main/ts/plugins/language-js/function-facts.js +30 -4
  54. package/target/main/ts/report/html/app/viewer-chart-bars.d.ts +11 -0
  55. package/target/main/ts/report/html/app/viewer-chart-bars.js +54 -0
  56. package/target/main/ts/report/html/app/viewer-chart-label.d.ts +15 -0
  57. package/target/main/ts/report/html/app/viewer-chart-label.js +43 -0
  58. package/target/main/ts/report/html/app/viewer-chart-line.d.ts +24 -0
  59. package/target/main/ts/report/html/app/viewer-chart-line.js +89 -0
  60. package/target/main/ts/report/html/app/viewer-chart-points.d.ts +49 -0
  61. package/target/main/ts/report/html/app/viewer-chart-points.js +74 -0
  62. package/target/main/ts/report/html/app/viewer-chart-scale.d.ts +21 -0
  63. package/target/main/ts/report/html/app/viewer-chart-scale.js +93 -0
  64. package/target/main/ts/report/html/app/viewer-chart-svg.d.ts +28 -0
  65. package/target/main/ts/report/html/app/viewer-chart-svg.js +41 -0
  66. package/target/main/ts/report/html/app/viewer-chart-time.d.ts +26 -0
  67. package/target/main/ts/report/html/app/viewer-chart-time.js +150 -0
  68. package/target/main/ts/report/html/app/viewer-chart-tip.d.ts +4 -0
  69. package/target/main/ts/report/html/app/viewer-chart-tip.js +210 -0
  70. package/target/main/ts/report/html/app/viewer-chart-x.d.ts +12 -0
  71. package/target/main/ts/report/html/app/viewer-chart-x.js +50 -0
  72. package/target/main/ts/report/html/app/viewer-chart.d.ts +4 -98
  73. package/target/main/ts/report/html/app/viewer-chart.js +16 -677
  74. package/target/main/ts/report/html/app/viewer-code-map.d.ts +27 -0
  75. package/target/main/ts/report/html/app/viewer-code-map.js +175 -0
  76. package/target/main/ts/report/html/app/viewer-columns.d.ts +38 -0
  77. package/target/main/ts/report/html/app/viewer-columns.js +92 -0
  78. package/target/main/ts/report/html/app/viewer-commit-picker.d.ts +12 -0
  79. package/target/main/ts/report/html/app/viewer-commit-picker.js +229 -0
  80. package/target/main/ts/report/html/app/viewer-commits.d.ts +5 -9
  81. package/target/main/ts/report/html/app/viewer-commits.js +17 -216
  82. package/target/main/ts/report/html/app/viewer-controls.d.ts +43 -0
  83. package/target/main/ts/report/html/app/viewer-controls.js +141 -0
  84. package/target/main/ts/report/html/app/viewer-copy.d.ts +17 -0
  85. package/target/main/ts/report/html/app/viewer-copy.js +64 -0
  86. package/target/main/ts/report/html/app/viewer-diagnostics.d.ts +4 -0
  87. package/target/main/ts/report/html/app/viewer-diagnostics.js +60 -0
  88. package/target/main/ts/report/html/app/viewer-dom.d.ts +27 -0
  89. package/target/main/ts/report/html/app/viewer-dom.js +99 -0
  90. package/target/main/ts/report/html/app/viewer-file-aside.d.ts +19 -0
  91. package/target/main/ts/report/html/app/viewer-file-aside.js +124 -0
  92. package/target/main/ts/report/html/app/viewer-file-figures.d.ts +15 -0
  93. package/target/main/ts/report/html/app/viewer-file-figures.js +60 -0
  94. package/target/main/ts/report/html/app/viewer-file-source.d.ts +7 -0
  95. package/target/main/ts/report/html/app/viewer-file-source.js +119 -0
  96. package/target/main/ts/report/html/app/viewer-files.d.ts +2 -118
  97. package/target/main/ts/report/html/app/viewer-files.js +24 -2184
  98. package/target/main/ts/report/html/app/viewer-filter.d.ts +3 -51
  99. package/target/main/ts/report/html/app/viewer-filter.js +111 -450
  100. package/target/main/ts/report/html/app/viewer-hotspots.d.ts +4 -0
  101. package/target/main/ts/report/html/app/viewer-hotspots.js +131 -0
  102. package/target/main/ts/report/html/app/viewer-inspection.d.ts +69 -0
  103. package/target/main/ts/report/html/app/viewer-inspection.js +36 -0
  104. package/target/main/ts/report/html/app/viewer-issue-group.d.ts +27 -0
  105. package/target/main/ts/report/html/app/viewer-issue-group.js +174 -0
  106. package/target/main/ts/report/html/app/viewer-issues.d.ts +4 -0
  107. package/target/main/ts/report/html/app/viewer-issues.js +173 -0
  108. package/target/main/ts/report/html/app/viewer-language-bar.d.ts +9 -0
  109. package/target/main/ts/report/html/app/viewer-language-bar.js +72 -0
  110. package/target/main/ts/report/html/app/viewer-languages.d.ts +27 -0
  111. package/target/main/ts/report/html/app/viewer-languages.js +93 -0
  112. package/target/main/ts/report/html/app/viewer-layout.d.ts +14 -0
  113. package/target/main/ts/report/html/app/viewer-layout.js +134 -0
  114. package/target/main/ts/report/html/app/viewer-line-coverage.d.ts +47 -0
  115. package/target/main/ts/report/html/app/viewer-line-coverage.js +121 -0
  116. package/target/main/ts/report/html/app/viewer-locations.d.ts +16 -0
  117. package/target/main/ts/report/html/app/viewer-locations.js +31 -0
  118. package/target/main/ts/report/html/app/viewer-map-scale.d.ts +26 -0
  119. package/target/main/ts/report/html/app/viewer-map-scale.js +147 -0
  120. package/target/main/ts/report/html/app/viewer-map-shape.d.ts +42 -0
  121. package/target/main/ts/report/html/app/viewer-map-shape.js +102 -0
  122. package/target/main/ts/report/html/app/viewer-metric-format.d.ts +23 -0
  123. package/target/main/ts/report/html/app/viewer-metric-format.js +93 -0
  124. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +0 -20
  125. package/target/main/ts/report/html/app/viewer-metric-registry.js +0 -77
  126. package/target/main/ts/report/html/app/viewer-metrics-view.d.ts +4 -0
  127. package/target/main/ts/report/html/app/viewer-metrics-view.js +162 -0
  128. package/target/main/ts/report/html/app/viewer-metrics.d.ts +6 -1
  129. package/target/main/ts/report/html/app/viewer-metrics.js +53 -35
  130. package/target/main/ts/report/html/app/viewer-overview-cards.d.ts +12 -0
  131. package/target/main/ts/report/html/app/viewer-overview-cards.js +112 -0
  132. package/target/main/ts/report/html/app/viewer-overview-hotspots.d.ts +9 -0
  133. package/target/main/ts/report/html/app/viewer-overview-hotspots.js +173 -0
  134. package/target/main/ts/report/html/app/viewer-overview-lead.d.ts +12 -0
  135. package/target/main/ts/report/html/app/viewer-overview-lead.js +116 -0
  136. package/target/main/ts/report/html/app/viewer-profile-badges.d.ts +11 -0
  137. package/target/main/ts/report/html/app/viewer-profile-badges.js +119 -0
  138. package/target/main/ts/report/html/app/viewer-profile-table.d.ts +29 -0
  139. package/target/main/ts/report/html/app/viewer-profile-table.js +124 -0
  140. package/target/main/ts/report/html/app/viewer-profile.d.ts +2 -6
  141. package/target/main/ts/report/html/app/viewer-profile.js +6 -248
  142. package/target/main/ts/report/html/app/viewer-pull-sections.d.ts +4 -0
  143. package/target/main/ts/report/html/app/viewer-pull-sections.js +118 -0
  144. package/target/main/ts/report/html/app/viewer-pull-trend.d.ts +5 -0
  145. package/target/main/ts/report/html/app/viewer-pull-trend.js +63 -0
  146. package/target/main/ts/report/html/app/viewer-pulls.d.ts +0 -1
  147. package/target/main/ts/report/html/app/viewer-pulls.js +28 -178
  148. package/target/main/ts/report/html/app/viewer-query-field.d.ts +19 -0
  149. package/target/main/ts/report/html/app/viewer-query-field.js +203 -0
  150. package/target/main/ts/report/html/app/viewer-route.d.ts +34 -0
  151. package/target/main/ts/report/html/app/viewer-route.js +55 -0
  152. package/target/main/ts/report/html/app/viewer-shell.d.ts +20 -0
  153. package/target/main/ts/report/html/app/viewer-shell.js +116 -0
  154. package/target/main/ts/report/html/app/viewer-source-view.d.ts +49 -0
  155. package/target/main/ts/report/html/app/viewer-source-view.js +150 -0
  156. package/target/main/ts/report/html/app/viewer-source.d.ts +0 -84
  157. package/target/main/ts/report/html/app/viewer-source.js +7 -363
  158. package/target/main/ts/report/html/app/viewer-suggest.d.ts +13 -0
  159. package/target/main/ts/report/html/app/viewer-suggest.js +91 -0
  160. package/target/main/ts/report/html/app/viewer-sunburst.d.ts +5 -0
  161. package/target/main/ts/report/html/app/viewer-sunburst.js +40 -0
  162. package/target/main/ts/report/html/app/viewer-table-cells.d.ts +25 -0
  163. package/target/main/ts/report/html/app/viewer-table-cells.js +129 -0
  164. package/target/main/ts/report/html/app/viewer-table-rows.d.ts +54 -0
  165. package/target/main/ts/report/html/app/viewer-table-rows.js +95 -0
  166. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +16 -0
  167. package/target/main/ts/report/html/app/viewer-tokenizer.js +192 -0
  168. package/target/main/ts/report/html/app/viewer-totals.d.ts +14 -0
  169. package/target/main/ts/report/html/app/viewer-totals.js +89 -0
  170. package/target/main/ts/report/html/app/viewer-treemap.d.ts +24 -0
  171. package/target/main/ts/report/html/app/viewer-treemap.js +112 -0
  172. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +49 -0
  173. package/target/main/ts/report/html/app/viewer-trend-data.js +105 -0
  174. package/target/main/ts/report/html/app/viewer-trend-nav.d.ts +5 -0
  175. package/target/main/ts/report/html/app/viewer-trend-nav.js +85 -0
  176. package/target/main/ts/report/html/app/viewer-trend-points.d.ts +30 -0
  177. package/target/main/ts/report/html/app/viewer-trend-points.js +128 -0
  178. package/target/main/ts/report/html/app/viewer-trend-series.d.ts +26 -0
  179. package/target/main/ts/report/html/app/viewer-trend-series.js +98 -0
  180. package/target/main/ts/report/html/app/viewer-trends.d.ts +2 -70
  181. package/target/main/ts/report/html/app/viewer-trends.js +41 -392
  182. package/target/main/ts/report/html/app/viewer.js +152 -663
  183. package/target/main/ts/report/html/site/badges.js +41 -18
  184. package/target/main/ts/report/json/store/local-store.js +2 -12
  185. package/target/main/ts/report/json/store/operation-cache.d.ts +8 -0
  186. package/target/main/ts/report/json/store/operation-cache.js +32 -0
  187. package/target/main/ts/report/json/store/replace-file.d.ts +1 -0
  188. package/target/main/ts/report/json/store/replace-file.js +14 -0
  189. package/target/main/ts/report.d.ts +1 -0
  190. package/target/main/ts/report.js +1 -0
@@ -1,7 +1,10 @@
1
- import { formatQuery, ignoredLabel, isLockfile, languageColor, languageOf, languageShares, lockfilesLabel, matches, parseQuery, queryField, sameClause, sized, suggest, usePluginMeasures } from './viewer-filter.js';
2
- import { bandLabels as pluginBandLabels, bandOf, bandScale, catalogIndex, compareValues, entryValue, firstSortAscending, format, rollUp } from './viewer-metric-registry.js';
3
- import { extendCatalog, labelOf, pluginMetrics, pluginSpec, securityRisks, size } from './viewer-metrics.js';
4
- import { highlightCode, isSourceLayer, lineHits, lineSnippet, lineStates, renderExcerpt, renderSource, setSourceLayer } from './viewer-source.js';
1
+ import { diagnosticsView } from './viewer-diagnostics.js';
2
+ import { parentPath } from './viewer-dom.js';
3
+ import { fileView } from './viewer-file-source.js';
4
+ import { hotspotView } from './viewer-hotspots.js';
5
+ import { useDetails } from './viewer-inspection.js';
6
+ import { issuesView } from './viewer-issues.js';
7
+ import { metricsView } from './viewer-metrics-view.js';
5
8
  /**
6
9
  * The finding categories Repometry counts as code smells, mirroring core's quality summary (structure and
7
10
  * duplication), so the Overview's smell count links to exactly the findings it counts.
@@ -9,2192 +12,29 @@ import { highlightCode, isSourceLayer, lineHits, lineSnippet, lineStates, render
9
12
  export const codeSmellCategories = ['structure', 'duplication'];
10
13
  /** The finding categories behind the security level, as the Overview's security column counts them. */
11
14
  export const securityCategories = ['security', 'dependency', 'secret', 'infrastructure'];
12
- const integer = new Intl.NumberFormat();
13
- const percent = new Intl.NumberFormat(undefined, { style: 'percent', maximumFractionDigits: 1 });
14
- const collator = new Intl.Collator(undefined, { numeric: true });
15
- const pageSize = 50;
16
- const hotspotChoices = [
17
- ['complexity', labelOf('complexity')],
18
- ['cognitive', labelOf('cognitive')],
19
- ['missedLines', 'Uncovered lines'],
20
- ['duplication', 'Duplicated lines'],
21
- ['churn', 'Git churn'],
22
- ];
23
15
  const preferences = new WeakMap();
24
- /** The inspection's own catalog: its file and folder values are indexed by it, not by the history's. */
25
- let local = { catalog: undefined, index: new Map() };
26
- function useDetails(details) {
27
- const catalog = details.metrics.catalog;
28
- extendCatalog(catalog);
29
- local = { catalog, index: catalogIndex(catalog) };
30
- usePluginMeasures(pluginMetrics().filter(spec => spec.descriptor.scope === 'file' && measured(spec.descriptor)).map(spec => [spec.key, {
31
- label: spec.label, percent: spec.descriptor.unit === 'ratio', minutes: spec.descriptor.unit === 'minutes',
32
- read: (entry) => entryValue(local.index, entry, spec),
33
- }]));
34
- }
35
- /** Whether this inspection ran the metric: a ratio ran where its denominator did. */
36
- function measured(descriptor) {
37
- return local.index.has(descriptor.ratio?.over ?? descriptor.id);
38
- }
39
- /** Coverage kinds beside line coverage (branches, functions), where the coverage report has them. */
40
- function coverageKinds() {
41
- return pluginMetrics().filter(spec => spec.plugin === 'repometry' && spec.group === 'Coverage' && spec.descriptor.unit === 'ratio'
42
- && spec.descriptor.scope === 'file');
43
- }
44
- /** Registry metrics as Metrics columns, in the order the history lists them. */
45
- function pluginColumns(specs) {
46
- return specs.map(spec => ({
47
- label: spec.short,
48
- value: entry => entryValue(local.index, entry, spec),
49
- display: entry => format(spec, entryValue(local.index, entry, spec)),
50
- available: () => measured(spec.descriptor),
51
- defaultVisible: () => spec.column,
52
- ascending: firstSortAscending(spec),
53
- }));
54
- }
55
- export function renderFileView(container, view, details, navigation) {
56
- useDetails(details);
16
+ /** A reader's choices on these pages, kept per container while the viewer stays open. */
17
+ function preferencesOf(container, details) {
57
18
  // A small codebase reads best as one flat list; a large one starts from its folders.
58
19
  const settings = preferences.get(container) ?? { mode: details.metrics.files.length <= 1000 ? 'list' : 'tree', sort: 0, ascending: true,
59
20
  hotspot: 'complexity', columns: new Map(), unanalysed: false };
60
21
  preferences.set(container, settings);
22
+ return settings;
23
+ }
24
+ /** The pages that read one inspection: Metrics (or an open file), Hotspots, Findings and Diagnostics. */
25
+ export function renderFileView(container, view, details, navigation) {
26
+ useDetails(details);
27
+ const settings = preferencesOf(container, details);
61
28
  const selectedFile = details.metrics.files.find(file => file.path === navigation.file);
62
29
  const requested = selectedFile && view === 'metrics' ? parentPath(selectedFile.path) : navigation.directory;
63
30
  const directory = details.metrics.directories.find(entry => entry.path === requested)?.path ?? '';
64
- switch (view) {
65
- case 'metrics':
66
- container.replaceChildren(selectedFile && navigation.source
67
- ? fileView(details, navigation, selectedFile, navigation.source)
68
- : metricsView(details, navigation, settings, directory, selectedFile));
69
- break;
70
- case 'hotspots':
71
- container.replaceChildren(hotspotView(details, navigation, settings, directory));
72
- break;
73
- case 'issues':
74
- container.replaceChildren(issuesView(details, navigation));
75
- break;
76
- case 'diagnostics':
77
- container.replaceChildren(diagnosticsView(details, navigation));
78
- break;
79
- }
80
- }
81
- const builtinColumns = [
82
- { label: 'Path', value: entry => entry.path, display: entry => entry.path },
83
- { label: labelOf('code-lines'), value: entry => entry.quality?.codeLines ?? null, display: entry => count(entry.quality?.codeLines),
84
- available: directory => directory?.quality?.codeLines !== undefined },
85
- // Ignored files have physical lines only: where there are some and no sizes, the language bar weighs in physical
86
- // lines, and this column shows the numbers behind it. With sizes, the Size column does.
87
- { label: labelOf('lines'), value: entry => entry.lines, display: entry => count(entry.lines),
88
- defaultVisible: (directory, scope) => (scope.ignored && !scope.sized) || directory?.quality?.codeLines === undefined },
89
- { label: 'Size', value: entry => entry.bytes ?? null, display: entry => size(entry.bytes),
90
- available: directory => directory?.bytes !== undefined, defaultVisible: (_, scope) => scope.sized },
91
- { label: 'Functions', value: entry => entry.functions, display: entry => count(entry.functions), defaultVisible: () => false },
92
- { label: labelOf('complexity'), value: entry => entry.complexity?.maximum ?? null, display: entry => count(entry.complexity?.maximum) },
93
- { label: labelOf('cognitive'), value: entry => entry.quality?.cognitiveComplexity ?? null, display: entry => count(entry.quality?.cognitiveComplexity),
94
- available: directory => directory?.quality?.cognitiveComplexity !== undefined },
95
- { label: labelOf('coverage'), value: coverageRatio, display: coverageText, available: directory => directory ? coverageRatio(directory) !== null : true },
96
- { label: 'Duplication', value: duplicationRatio, display: duplicationText,
97
- available: directory => directory?.quality?.duplication !== undefined },
98
- { label: labelOf('effort'), value: entry => entry.quality?.maintainability?.effortMinutes ?? null,
99
- display: entry => duration(entry.quality?.maintainability?.effortMinutes),
100
- available: directory => directory?.quality?.maintainability !== undefined },
101
- { label: 'Git changes', value: entry => entry.quality?.churn ?? null,
102
- display: entry => count(entry.quality?.churn),
103
- available: directory => directory?.quality?.churn !== undefined, defaultVisible: () => false },
104
- { label: 'Diagnostics', value: entry => entry.diagnosticCount, display: entry => count(entry.diagnosticCount), defaultVisible: () => false },
105
- ];
106
- function isGroup(value) {
107
- return value === 'folders' || value === 'files' || value === 'components';
108
- }
109
- function metricsView(details, navigation, settings, directory, selectedFile) {
110
- const view = element('div', 'fx-view');
111
- const { metrics } = details;
112
- // The other coverage kinds sit beside line coverage; every other registry metric follows Repometry's own columns,
113
- // except the counts a ratio is made of, which read through the ratio as line coverage's do.
114
- const kinds = coverageKinds();
115
- const afterCoverage = builtinColumns.findIndex(column => column.label === labelOf('coverage')) + 1;
116
- const columns = [...builtinColumns.slice(0, afterCoverage),
117
- ...pluginColumns(kinds), ...builtinColumns.slice(afterCoverage),
118
- ...pluginColumns(pluginMetrics().filter(spec => spec.descriptor.scope === 'file' && !spec.ratioPart && !kinds.includes(spec)))];
119
- const scopeFiles = metrics.files.filter(entry => inside(entry.path, directory));
120
- const scopeTotals = aggregate(directory, scopeFiles);
121
- const scopeIgnored = scopeFiles.some(entry => entry.analysed === false);
122
- const components = details.components ?? [];
123
- const facts = {
124
- components: componentIndex(components),
125
- findings: findingIndex(details.findings ?? []),
126
- };
127
- let clauses = parseQuery(navigation.query ?? '');
128
- let text = '';
129
- let group = isGroup(navigation.group) ? navigation.group : settings.mode === 'tree' ? 'folders' : 'files';
130
- // Every link out of the view carries the query and the grouping, so a file opened from a selection keeps it.
131
- const linkTo = (options = {}) => navigation.href('metrics', { ...options, query: formatQuery(clauses), group });
132
- const trail = element('div');
133
- view.append(trail);
134
- const split = element('div', 'fx-split');
135
- const main = element('div', 'fx-main');
136
- split.append(main, splitter(split));
137
- view.append(split);
138
- const field = queryField(clauses, {
139
- suggestions: typed => suggest(typed, scopeFiles, facts, clauses),
140
- change: (next, typed) => {
141
- clauses = next;
142
- text = typed;
143
- page = 0;
144
- remember();
145
- refresh();
146
- },
147
- });
148
- const grouping = segmented('Group by', [['folders', 'Folders'], ['files', 'Files'], ['components', 'Components']], group, value => {
149
- group = value;
150
- settings.mode = group === 'folders' ? 'tree' : 'list';
151
- page = 0;
152
- remember();
153
- refresh();
154
- });
155
- const tools = element('div', 'fx-tools fx-metrics-tools');
156
- const columnsMenu = element('details', 'fx-columns');
157
- const summary = element('summary', '', 'Columns');
158
- const toggles = element('div', 'fx-column-toggles');
159
- columnsMenu.append(summary, toggles);
160
- dismissible(columnsMenu);
161
- tools.append(field.element, grouping, columnsMenu);
162
- const languages = element('div', 'fx-languages');
163
- const hint = element('p', 'fx-hint');
164
- hint.hidden = true;
165
- function isVisible(index) {
166
- return index === 0 || Boolean(toggles.querySelector(`[value="${index}"]`)?.checked);
167
- }
168
- columns.forEach((column, index) => {
169
- if (index === 0 || column.available?.(scopeTotals) === false)
170
- return;
171
- const label = element('label', 'fx-column-toggle', column.label);
172
- const toggle = element('input');
173
- toggle.type = 'checkbox';
174
- toggle.value = String(index);
175
- toggle.checked = settings.columns.get(index) ?? column.defaultVisible?.(scopeTotals, { ignored: scopeIgnored, sized: sized(scopeFiles) }) ?? true;
176
- toggle.addEventListener('change', () => {
177
- settings.columns.set(index, toggle.checked);
178
- if (!isVisible(settings.sort)) {
179
- settings.sort = 0;
180
- settings.ascending = true;
181
- }
182
- page = 0;
183
- refresh();
184
- });
185
- label.prepend(toggle);
186
- toggles.append(label);
187
- });
188
- if (!isVisible(settings.sort)) {
189
- settings.sort = 0;
190
- settings.ascending = true;
191
- }
192
- const result = element('p', 'fx-note fx-results');
193
- result.setAttribute('aria-live', 'polite');
194
- const table = element('table', 'fx-table');
195
- const header = element('tr');
196
- const thead = element('thead');
197
- const body = element('tbody');
198
- const headers = columns.map(({ label }, index) => {
199
- const th = element('th', index ? 'numeric' : '');
200
- th.scope = 'col';
201
- const sort = element('button', 'fx-sort', label);
202
- sort.type = 'button';
203
- sort.addEventListener('click', () => {
204
- settings.ascending = settings.sort === index ? !settings.ascending : index === 0 || (columns[index].ascending ?? false);
205
- settings.sort = index;
206
- page = 0;
207
- refresh();
208
- });
209
- th.append(sort);
210
- header.append(th);
211
- return th;
212
- });
213
- thead.append(header);
214
- table.append(thead, body);
215
- const pager = element('div', 'fx-pager');
216
- const navigationState = navigationButtons('File pages', () => { page--; refresh(); }, () => { page++; refresh(); });
217
- // The count of what the list holds stands with the page buttons, under the table it counts.
218
- pager.append(result, navigationState.section);
219
- const tableWrap = scrollableTable(table, 'File and directory metrics');
220
- const note = element('p', 'fx-note');
221
- main.append(tools, languages, hint, tableWrap, pager, note);
222
- let page = 0;
223
- let current;
224
- /** The URL follows the query, without a new history entry per keystroke. */
225
- function remember() {
226
- history.replaceState(history.state, '', navigation.href('metrics', {
227
- directory, ...(selectedFile ? { file: selectedFile.path } : {}), query: formatQuery(clauses), group
228
- }));
229
- }
230
- function selected(...except) {
231
- const kept = clauses.filter(clause => !except.includes(clause.kind));
232
- return scopeFiles.filter(entry => matches(entry, kept, facts, text));
233
- }
234
- function refresh() {
235
- const files = selected();
236
- const filtering = clauses.length > 0 || text !== '';
237
- trail.replaceChildren(breadcrumbs('metrics', { ...navigation, href: (_, options) => linkTo(options) }, directory));
238
- renderLanguages(selected('lang', 'analysed'));
239
- const sort = columns[settings.sort] ?? columns[0];
240
- let rows;
241
- hint.hidden = true;
242
- if (group === 'components') {
243
- if (components.length === 0) {
244
- hint.hidden = false;
245
- hint.replaceChildren('No components are defined for this repository. Group paths into components in ', element('code', '', '.repometry/components.json'), ' to compare them here.');
246
- rows = [];
247
- }
248
- else {
249
- const chosen = new Set(files.map(entry => entry.path));
250
- rows = components.map(({ component, paths }) => ({
251
- entry: aggregate(component.name, paths.flatMap(path => chosen.has(path) ? [byPath.get(path)] : [])), kind: 'component'
252
- }))
253
- .filter(row => !filtering || row.entry.files > 0);
254
- const assigned = new Set(components.flatMap(({ paths }) => paths));
255
- const rest = files.filter(entry => !assigned.has(entry.path));
256
- if (rest.length)
257
- rows.push({ entry: aggregate('Not in a component', rest), kind: 'component' });
258
- }
259
- }
260
- else if (group === 'folders' && !filtering) {
261
- rows = [...metrics.directories.filter(entry => entry.path && parentPath(entry.path) === directory).map(entry => ({ entry, kind: 'folder' })),
262
- ...files.filter(entry => parentPath(entry.path) === directory).map(entry => ({ entry, kind: 'file' }))];
263
- }
264
- else if (group === 'folders') {
265
- // Filtered folders hold only what passes the query, and their totals count only that.
266
- const below = new Map();
267
- const here = [];
268
- for (const entry of files) {
269
- const rest = directory ? entry.path.slice(directory.length + 1) : entry.path;
270
- const slash = rest.indexOf('/');
271
- if (slash < 0)
272
- here.push(entry);
273
- else {
274
- const folder = (directory ? `${directory}/` : '') + rest.slice(0, slash);
275
- below.set(folder, [...below.get(folder) ?? [], entry]);
276
- }
277
- }
278
- rows = [...[...below].map(([path, entries]) => ({ entry: aggregate(path, entries), kind: 'folder' })),
279
- ...here.map(entry => ({ entry, kind: 'file' }))];
280
- }
281
- else
282
- rows = files.map(entry => ({ entry, kind: 'file' }));
283
- rows.sort((a, b) => {
284
- if (settings.sort === 0 && (a.kind === 'file') !== (b.kind === 'file'))
285
- return a.kind === 'file' ? 1 : -1;
286
- return compare(a.entry, b.entry, sort.value, settings.ascending);
287
- });
288
- headers.forEach((th, index) => {
289
- th.hidden = !isVisible(index);
290
- if (index === settings.sort)
291
- th.setAttribute('aria-sort', settings.ascending ? 'ascending' : 'descending');
292
- else
293
- th.removeAttribute('aria-sort');
294
- });
295
- headers[0].querySelector('button').textContent = group === 'components' ? 'Component' : 'Path';
296
- // The code comes first, whatever the sort: files no plugin read, and folders holding only such files, fold into
297
- // one row at the end. A query that asks for them, or a list of nothing else, shows them as they are.
298
- const unreadPaths = unreadFolders(scopeFiles);
299
- const unread = (row) => row.kind === 'file' ? row.entry.analysed === false
300
- : row.kind === 'folder' && unreadPaths.has(row.entry.path);
301
- const folded = clauses.some(clause => clause.kind === 'analysed' || clause.kind === 'lockfile') ? [] : rows.filter(unread);
302
- const read = folded.length ? rows.filter(row => !folded.includes(row)) : rows;
303
- const display = !folded.length || !read.length ? rows
304
- : [...read, { kind: 'unread' }, ...settings.unanalysed ? folded : []];
305
- const first = page * pageSize;
306
- const visible = display.slice(first, first + pageSize);
307
- const visibleColumns = columns.slice(1).filter((_, index) => isVisible(index + 1));
308
- body.replaceChildren(...visible.map(row => row.kind === 'unread' ? unreadRow(folded, visibleColumns.length + 1, settings.unanalysed, () => {
309
- settings.unanalysed = !settings.unanalysed;
310
- refresh();
311
- }) : metricsRow(row.entry, row.kind, group, visibleColumns, linkTo, selectedFile?.path, row.kind === 'component' && row.entry.path !== 'Not in a component' ? () => {
312
- group = 'files';
313
- settings.mode = 'list';
314
- grouping.querySelectorAll('button').forEach(button => button.setAttribute('aria-pressed', String(button.textContent === 'Files')));
315
- field.set([...clauses.filter(clause => clause.kind !== 'component'), { kind: 'component', value: row.entry.path }]);
316
- } : undefined)));
317
- const noun = group === 'components' ? 'components' : group === 'folders' ? 'entries' : 'files';
318
- // A filtered file list says how many of the folder's files it kept; other lists name the selection only once.
319
- const listsFiles = noun === 'files' && rows.length === files.length;
320
- const of = filtering && !(listsFiles && display.length <= pageSize) ? ` · ${count(files.length)} of ${count(scopeFiles.length)} files selected` : '';
321
- const range = entryRange(display, first, visible.length);
322
- result.textContent = rows.length === 0 ? (hint.hidden ? 'No files match this selection.' : '')
323
- : display.length > pageSize && range ? `${count(range[0])}–${count(range[1])} of ${count(rows.length)} ${noun}${of}`
324
- : display.length > pageSize ? `${count(rows.length)} ${noun}${of}`
325
- : filtering && listsFiles ? `${count(rows.length)} of ${count(scopeFiles.length)} files`
326
- : `${count(rows.length)} ${rows.length === 1 ? noun.replace(/s$/, '').replace('entrie', 'entry') : noun}${of}`;
327
- tableWrap.hidden = rows.length === 0;
328
- pager.hidden = !result.textContent;
329
- navigationState.section.hidden = display.length <= pageSize;
330
- navigationState.update(page, Math.ceil(display.length / pageSize));
331
- note.hidden = rows.length === 0;
332
- note.textContent = 'A dash marks an unavailable measurement. Totals include measured files.'
333
- + (visibleColumns.some(column => column.label === labelOf('effort')) ? ` ${labelOf('effort')} is assigned to each finding’s primary file.` : '');
334
- const aside = selectedFile ? fileDetails(details, selectedFile, { ...navigation, href: (target, options) => target === 'metrics' ? linkTo(options) : navigation.href(target, options) })
335
- : directorySummary(aggregate(directory, files), files.filter(entry => entry.analysed !== false).length, files.filter(entry => isLockfile(entry.path)).length, filtering ? `${count(files.length)} of ${count(scopeFiles.length)} files selected` : undefined);
336
- // Only the side panel is swapped: moving the list column would take focus out of the query field.
337
- if (current)
338
- current.replaceWith(aside);
339
- else
340
- split.append(aside);
341
- current = aside;
342
- }
343
- /** The languages of the selection as one bar; each name toggles its chip. */
344
- function renderLanguages(files) {
345
- // Lockfiles and the files no plugin read stand at the end in muted tones: categories, not languages.
346
- const { measure, shares } = languageShares(files);
347
- const total = shares.reduce((sum, [, weight]) => sum + weight, 0);
348
- languages.hidden = shares.length < 2 || total === 0;
349
- if (languages.hidden)
350
- return;
351
- const picked = new Set(clauses.flatMap(clause => clause.kind === 'lang' ? [clause.value.toLowerCase()] : []));
352
- const categories = {
353
- [lockfilesLabel]: { clause: { kind: 'lockfile', value: 'yes' }, color: 'var(--lockfile)', className: 'fx-language-lockfile' },
354
- [ignoredLabel]: { clause: { kind: 'analysed', value: 'no' }, color: 'var(--grade-none)', className: 'fx-language-unread' },
355
- };
356
- const chosen = (clause) => clauses.some(other => sameClause(other, clause));
357
- const anyPicked = picked.size > 0 || Object.values(categories).some(category => chosen(category.clause));
358
- const bar = element('div', 'fx-language-bar');
359
- bar.setAttribute('aria-hidden', 'true');
360
- const legend = element('div', 'fx-language-legend');
361
- legend.setAttribute('role', 'group');
362
- const measured = measure === 'bytes' ? 'size' : labelOf(measure).toLowerCase();
363
- legend.setAttribute('aria-label', `Languages by ${measured}`);
364
- for (const [language, weight] of shares) {
365
- const category = categories[language];
366
- const pressed = category ? chosen(category.clause) : picked.has(language.toLowerCase());
367
- const color = category?.color ?? languageColor(language);
368
- const segment = element('span', !anyPicked || pressed ? 'fx-language-segment' : 'fx-language-segment fx-off');
369
- segment.style.flexGrow = String(weight);
370
- segment.style.background = color;
371
- bar.append(segment);
372
- const toggle = element('button', category ? `fx-language ${category.className}` : 'fx-language');
373
- toggle.type = 'button';
374
- toggle.setAttribute('aria-pressed', String(pressed));
375
- const dot = element('span', 'fx-language-dot');
376
- dot.style.background = color;
377
- toggle.append(dot, element('span', 'fx-language-name', language), element('span', 'fx-language-share', percent.format(weight / total)));
378
- toggle.addEventListener('click', () => {
379
- const clause = category?.clause ?? { kind: 'lang', value: language };
380
- field.set(pressed
381
- ? clauses.filter(other => category ? other.kind !== clause.kind
382
- : !(other.kind === 'lang' && other.value.toLowerCase() === language.toLowerCase()))
383
- : [...clauses, clause]);
384
- });
385
- legend.append(toggle);
386
- }
387
- // The bar says what it weighs, so its shares can be checked against a column of the table.
388
- legend.append(element('span', 'fx-language-measure', `Share of ${measured}`));
389
- languages.replaceChildren(bar, legend);
390
- }
391
- const byPath = new Map(metrics.files.map(entry => [entry.path, entry]));
392
- refresh();
393
- return view;
394
- }
395
- /** Totals for any set of files, measured the way folder totals are: sums, the peak, and ratios of sums. */
396
- function aggregate(path, files) {
397
- const sum = (read) => {
398
- let total = null;
399
- for (const entry of files) {
400
- const value = read(entry);
401
- if (value !== null && value !== undefined)
402
- total = (total ?? 0) + value;
403
- }
404
- return total;
405
- };
406
- const peak = files.reduce((max, entry) => entry.complexity?.maximum == null ? max : Math.max(max ?? 0, entry.complexity.maximum), null);
407
- const covered = files.filter(entry => entry.lineCoverage);
408
- const values = rollUp(local.catalog, files);
409
- const quality = {};
410
- const codeLines = sum(entry => entry.quality?.codeLines);
411
- if (codeLines !== null)
412
- quality.codeLines = codeLines;
413
- const comments = sum(entry => entry.quality?.commentLines);
414
- if (comments !== null)
415
- quality.commentLines = comments;
416
- const classes = sum(entry => entry.quality?.classes);
417
- if (classes !== null)
418
- quality.classes = classes;
419
- const cognitive = sum(entry => entry.quality?.cognitiveComplexity);
420
- if (cognitive !== null)
421
- quality.cognitiveComplexity = cognitive;
422
- const churn = sum(entry => entry.quality?.churn);
423
- if (churn !== null)
424
- quality.churn = churn;
425
- if (files.some(entry => entry.quality?.duplication)) {
426
- quality.duplication = { duplicatedLines: sum(entry => entry.quality?.duplication?.duplicatedLines) ?? 0,
427
- codeLines: sum(entry => entry.quality?.duplication?.codeLines) ?? 0 };
428
- }
429
- if (files.some(entry => entry.quality?.maintainability)) {
430
- quality.maintainability = { smells: sum(entry => entry.quality?.maintainability?.smells) ?? 0,
431
- effortMinutes: sum(entry => entry.quality?.maintainability?.effortMinutes) };
432
- }
433
- return {
434
- path, files: files.length, lines: sum(entry => entry.lines), functions: sum(entry => entry.functions),
435
- complexity: files.some(entry => entry.complexity)
436
- ? { sum: sum(entry => entry.complexity?.sum) ?? 0, maximum: peak, measuredFunctions: sum(entry => entry.complexity?.measuredFunctions) ?? 0 } : null,
437
- lineCoverage: covered.length ? { covered: sum(entry => entry.lineCoverage?.covered) ?? 0, total: sum(entry => entry.lineCoverage?.total) ?? 0 } : null,
438
- diagnosticCount: sum(entry => entry.diagnosticCount) ?? 0,
439
- sizeMeasuredFiles: files.filter(entry => entry.lines !== null).length, coverageMeasuredFiles: covered.length,
440
- ...(Object.keys(quality).length ? { quality } : {}),
441
- ...(values ? { values } : {}),
442
- // A partial sum would understate the size: only a scope where every file has one gets a total.
443
- ...(sized(files) ? { bytes: sum(entry => entry.bytes) ?? 0 } : {}),
444
- };
445
- }
446
- function componentIndex(components) {
447
- const index = new Map();
448
- for (const { component, paths } of components)
449
- for (const path of paths)
450
- index.set(path, [...index.get(path) ?? [], component.name]);
451
- return index;
452
- }
453
- function findingIndex(findings) {
454
- const index = new Map();
455
- for (const finding of findings) {
456
- for (const path of new Set(allLocations(finding).map(location => location.path)))
457
- index.set(path, (index.get(path) ?? 0) + 1);
458
- }
459
- return index;
460
- }
461
- function metricsRow(entry, kind, group, visibleColumns, linkTo, selectedFile, open) {
462
- const row = element('tr');
463
- const name = element('th', 'fx-path-column');
464
- name.scope = 'row';
465
- const flat = kind === 'file' && group !== 'folders';
466
- const anchor = kind === 'component'
467
- ? open ? Object.assign(element('button', 'fx-entry fx-entry-button', entry.path), { type: 'button', onclick: open })
468
- : element('span', 'fx-entry fx-entry-muted', entry.path)
469
- : link(linkTo(kind === 'folder' ? { directory: entry.path } : { directory: parentPath(entry.path), file: entry.path }), flat ? '' : basename(entry.path), 'fx-entry');
470
- if (flat) {
471
- // In the flat list the folder is context and the file name is the subject.
472
- const slash = entry.path.lastIndexOf('/');
473
- const label = element('span', 'fx-entry-label');
474
- if (slash >= 0) {
475
- // A long folder wraps after a slash, never inside a name.
476
- const folder = element('span', 'fx-entry-folder');
477
- for (const part of entry.path.slice(0, slash + 1).split(/(?<=\/)/))
478
- folder.append(part, element('wbr'));
479
- label.append(folder);
480
- }
481
- label.append(element('span', 'fx-entry-name', entry.path.slice(slash + 1)));
482
- anchor.append(label);
483
- }
484
- const icon = element('span', kind === 'file' ? 'fx-file-icon' : kind === 'folder' ? 'fx-folder-icon' : 'fx-component-icon');
485
- icon.setAttribute('aria-hidden', 'true');
486
- const lockfile = kind === 'file' && isLockfile(entry.path);
487
- if (kind === 'file')
488
- icon.style.color = lockfile ? 'var(--lockfile)' : languageColor(languageOf(entry.path));
489
- anchor.prepend(icon);
490
- if (kind !== 'component')
491
- anchor.setAttribute('title', entry.path);
492
- if (entry.path === selectedFile) {
493
- anchor.setAttribute('aria-current', 'true');
494
- row.dataset.selected = '';
495
- }
496
- name.append(anchor);
497
- if (lockfile)
498
- name.append(element('span', 'fx-entry-tag', 'Lockfile'));
499
- if (kind !== 'file' && 'files' in entry)
500
- name.append(element('span', 'fx-entry-count', count(entry.files)));
501
- row.append(name, ...visibleColumns.map(column => {
502
- const cell = element('td', 'numeric', column.display(entry));
503
- if (column.value(entry) === 0)
504
- cell.classList.add('fx-zero');
505
- if (column.label === 'Duplication')
506
- cell.title = duplicationContext(entry) ?? '';
507
- return cell;
508
- }));
509
- return row;
510
- }
511
- /** The folders all of whose files are only counted, found in one pass over the files. */
512
- export function unreadFolders(files) {
513
- const read = new Map();
514
- for (const file of files) {
515
- const analysed = file.analysed !== false;
516
- for (let slash = file.path.lastIndexOf('/'); slash > 0; slash = file.path.lastIndexOf('/', slash - 1)) {
517
- const folder = file.path.slice(0, slash);
518
- read.set(folder, (read.get(folder) ?? false) || analysed);
519
- }
520
- }
521
- return new Set([...read].filter(([, analysed]) => !analysed).map(([folder]) => folder));
522
- }
523
- /** The fold at the end of the list: how many entries no plugin read, opening and closing in place. */
524
- function unreadRow(entries, span, expanded, toggle) {
525
- const lockfiles = entries.filter(row => row.kind === 'file' && isLockfile(row.entry.path)).length;
526
- const files = entries.filter(row => row.kind === 'file').length - lockfiles;
527
- const folders = entries.length - files - lockfiles;
528
- const parts = [
529
- lockfiles ? `${count(lockfiles)} ${lockfiles === 1 ? 'lockfile' : 'lockfiles'}` : '',
530
- files ? `${count(files)} ${files === 1 ? 'file' : 'files'}` : '',
531
- folders ? `${count(folders)} ${folders === 1 ? 'folder' : 'folders'}` : '',
532
- ].filter(Boolean);
533
- const row = element('tr', 'fx-unread');
534
- const cell = element('td');
535
- cell.colSpan = span;
536
- const button = element('button', 'fx-unread-toggle', `${[parts.slice(0, -1).join(', '), parts.at(-1)].filter(Boolean).join(' and ')} ignored`);
537
- button.type = 'button';
538
- button.setAttribute('aria-expanded', String(expanded));
539
- button.addEventListener('click', toggle);
540
- cell.append(button);
541
- row.append(cell);
542
- return row;
543
- }
544
- function directorySummary(entry, analysed, lockfiles, selection) {
545
- const panel = element('aside', 'fx-aside');
546
- panel.setAttribute('aria-label', selection ? 'Selection totals' : 'Folder totals');
547
- const heading = element('div', 'fx-aside-heading');
548
- heading.append(element('h2', '', selection ? 'Selection' : entry.path ? basename(entry.path) : 'All files'));
549
- // The breadcrumbs above name the folder; only a selection needs its words here.
550
- if (selection)
551
- heading.append(element('p', 'fx-aside-path fx-aside-selection', selection));
552
- const facts = element('dl', 'fx-kv');
553
- // A measurement the inspection did not take leaves no row behind.
554
- const quality = entry.quality;
555
- facts.append(...[
556
- // Every tracked file counts here; Trends counts the analysed ones, so both say which they are.
557
- fact('Tracked files', count(entry.files)),
558
- analysed === entry.files ? null : fact(labelOf('files'), count(analysed)),
559
- lockfiles ? fact(lockfilesLabel, count(lockfiles)) : null,
560
- quality?.codeLines !== undefined ? fact(labelOf('code-lines'), count(quality.codeLines)) : null,
561
- // Physical lines are what the language bar weighs once some files are ignored, so its total stands here too.
562
- quality?.codeLines === undefined || analysed !== entry.files ? fact(labelOf('lines'), count(entry.lines)) : null,
563
- entry.bytes === undefined ? null : fact('Size', size(entry.bytes)),
564
- entry.functions === null ? null : fact(labelOf('functions'), count(entry.functions)),
565
- fact(labelOf('complexity'), count(entry.complexity?.maximum)),
566
- quality?.cognitiveComplexity === undefined ? null : fact(labelOf('cognitive'), count(quality.cognitiveComplexity)),
567
- quality?.duplication === undefined ? null : fact(labelOf('duplication'), duplicationText(entry)),
568
- quality?.maintainability === undefined ? null : fact(labelOf('effort'), duration(quality.maintainability.effortMinutes)),
569
- coverageRatio(entry) === null ? null : fact(labelOf('coverage'), coverageText(entry)),
570
- // Other plugins' totals follow Repometry's own, where this inspection ran them and they roll up; the counts behind
571
- // a ratio read through it.
572
- ...pluginMetrics().filter(spec => spec.descriptor.scope === 'file' && spec.descriptor.aggregate !== 'none' && !spec.ratioPart
573
- && measured(spec.descriptor)).map(spec => fact(spec.short, format(spec, entryValue(local.index, entry, spec)))),
574
- ].filter(item => item !== null));
575
- panel.append(heading, facts);
576
- return panel;
577
- }
578
- function fileDetails(details, entry, navigation, hooks = {}) {
579
- const panel = element('aside', 'fx-aside fx-file');
580
- panel.setAttribute('aria-label', 'File details');
581
- const heading = element('div', 'fx-aside-heading');
582
- // The breadcrumbs above name the folder, so the title is the file alone.
583
- const title = element('h2', '', basename(entry.path));
584
- const close = link(navigation.href('metrics', { directory: parentPath(entry.path) }), '', 'fx-close');
585
- close.setAttribute('aria-label', 'Close file details');
586
- close.title = 'Close file details';
587
- heading.append(title, close);
588
- const facts = element('dl', 'fx-kv');
589
- const quality = entry.quality;
590
- if (quality?.codeLines !== undefined)
591
- facts.append(fact(labelOf('code-lines'), count(quality.codeLines)));
592
- facts.append(fact(labelOf('lines'), count(entry.lines)));
593
- if (entry.bytes !== undefined)
594
- facts.append(fact('Size', size(entry.bytes)));
595
- if (quality?.commentLines !== undefined)
596
- facts.append(fact(labelOf('comments'), count(quality.commentLines)));
597
- facts.append(fact(labelOf('functions'), count(entry.functions)));
598
- if (quality?.classes)
599
- facts.append(fact(labelOf('classes'), count(quality.classes)));
600
- facts.append(fact(labelOf('complexity'), count(entry.complexity?.maximum)));
601
- if (quality?.cognitiveComplexity !== undefined)
602
- facts.append(fact(labelOf('cognitive'), count(quality.cognitiveComplexity)));
603
- facts.append(fact(labelOf('coverage'), coverageText(entry), coverageContext(entry)));
604
- for (const spec of coverageKinds()) {
605
- const value = measured(spec.descriptor) ? entryValue(local.index, entry, spec) : null;
606
- if (value !== null)
607
- facts.append(fact(spec.short, format(spec, value)));
608
- }
609
- if (quality?.duplication)
610
- facts.append(fact(labelOf('duplication'), duplicationText(entry), duplicationContext(entry)));
611
- if (quality?.maintainability)
612
- facts.append(fact(labelOf('effort'), duration(quality.maintainability.effortMinutes)));
613
- if (quality?.churn !== undefined) {
614
- const window = details.metrics.churnWindow;
615
- facts.append(fact('Git changes', count(quality.churn), window ? `${count(window.lookbackDays)}-day window` : undefined));
616
- }
617
- panel.append(heading, facts);
618
- const findings = details.findings?.filter(item => atPath(item, entry.path));
619
- const links = element('p', 'fx-aside-links');
620
- if (findings?.length)
621
- links.append(link(navigation.href('issues', { file: entry.path }), quantity(findings.length, 'finding'), 'fx-inline-link'));
622
- if (entry.diagnosticCount)
623
- links.append(link(navigation.href('diagnostics', { file: entry.path }), quantity(entry.diagnosticCount, 'diagnostic'), 'fx-inline-link'));
624
- if (links.childElementCount)
625
- panel.append(links);
626
- // The side column has room for the functions, most complex first; a long file folds the rest away.
627
- const functions = details.functions.filter(record => record.path === entry.path)
628
- .sort((a, b) => b.complexity - a.complexity);
629
- if (functions.length) {
630
- const section = element('section', 'fx-aside-section');
631
- const list = (records) => hooks.reveal ? sourceFunctionList(records, hooks.reveal, hooks.text) : functionList(records);
632
- section.append(element('h3', '', 'Functions by complexity'), list(functions.slice(0, 10)));
633
- if (functions.length > 10) {
634
- const rest = element('details', 'fx-functions');
635
- rest.append(element('summary', '', `${functions.length - 10} more`), list(functions.slice(10)));
636
- section.append(rest);
637
- }
638
- panel.append(section);
639
- }
640
- return panel;
641
- }
642
- /** Functions as buttons that bring their first line into view; an anonymous one is named by that line's code. */
643
- function sourceFunctionList(functions, reveal, text) {
644
- const list = element('ol', 'fx-function-list fx-function-jumps');
645
- list.append(...functions.map(record => {
646
- const row = element('li');
647
- const snippet = record.name === '(anonymous)' && text && record.line !== null ? lineSnippet(text, record.line) : null;
648
- const button = element('button', 'fx-function-jump');
649
- button.type = 'button';
650
- button.disabled = record.line === null;
651
- const name = element(snippet ? 'code' : 'span', 'fx-function-name');
652
- if (snippet)
653
- name.append(...highlightCode(record.path, snippet));
654
- else
655
- name.textContent = record.name;
656
- button.append(name);
657
- if (record.line !== null)
658
- button.append(element('span', 'fx-function-line', `${record.line}`));
659
- button.addEventListener('click', () => { if (record.line !== null)
660
- reveal(record.line); });
661
- row.append(button, element('strong', 'fx-function-score', count(record.complexity)));
662
- return row;
663
- }));
664
- return list;
665
- }
666
- /**
667
- * An open file: its source with the inspection laid on its lines, and its figures and functions beside it. The
668
- * functions lead into the code, and a chosen line goes into the URL so the place can be shared.
669
- */
670
- function fileView(details, navigation, file, load) {
671
- const view = element('div', 'fx-view');
672
- const keep = { query: navigation.query ?? '', group: navigation.group ?? '' };
673
- const nav = { ...navigation,
674
- href: (target, options) => target === 'metrics' ? navigation.href('metrics', { ...keep, ...options }) : navigation.href(target, options) };
675
- view.append(breadcrumbs('metrics', nav, parentPath(file.path)));
676
- const split = element('div', 'fx-split fx-split-source');
677
- const main = element('section', 'fx-source panel');
678
- main.setAttribute('aria-label', 'Source');
679
- const head = element('div', 'fx-source-head');
680
- const language = languageOf(file.path);
681
- const dot = element('span', 'fx-language-dot');
682
- dot.style.background = languageColor(language);
683
- // The folder is in the breadcrumbs right above; the head names the file alone, with its full path on hover.
684
- const name = element('code', 'fx-source-path', basename(file.path));
685
- name.title = file.path;
686
- // The whole path from the repository root is a click away; a refused clipboard shows it in the name's place, selected.
687
- const named = element('span', 'fx-source-name');
688
- named.append(name, copyPathButton(file.path, () => {
689
- name.textContent = file.path;
690
- return name;
691
- }));
692
- const meta = element('span', 'fx-source-meta');
693
- meta.append(dot, `${language} · ${count(file.lines)} lines`);
694
- // Lines show the findings, or the tests' coverage where the file has it; without coverage the head stays as it was.
695
- const coverage = fileCoverage(details, file.path);
696
- let layer = coverage ? sourceLayer(navigation.layer) : 'issues';
697
- let line = navigation.line;
698
- const place = () => nav.href('metrics', { directory: parentPath(file.path), file: file.path, ...line ? { line } : {},
699
- ...layer === 'coverage' ? { layer } : {} });
700
- const toggle = coverage ? segmented('Lines show', [['issues', 'Issues'], ['coverage', 'Coverage']], layer, value => {
701
- layer = value;
702
- rememberLayer(layer);
703
- setSourceLayer(body, layer);
704
- history.replaceState(history.state, '', place());
705
- }) : null;
706
- toggle?.classList.add('fx-source-layer');
707
- const tools = element('div', 'fx-source-tools');
708
- tools.append(...toggle ? [toggle] : [], meta);
709
- head.append(named, tools);
710
- // The forge's page for the file, at the chosen line, whether or not the text opens here.
711
- const page = navigation.sourcePage?.(file.path, navigation.line);
712
- const forge = page ? link(page.href, `View on ${page.provider}`, 'fx-source-forge') : null;
713
- if (forge) {
714
- forge.target = '_blank';
715
- forge.rel = 'noopener noreferrer';
716
- meta.append(' · ', forge);
717
- }
718
- const body = element('div', 'fx-source-body');
719
- body.append(element('p', 'fx-note fx-source-wait', 'Loading source…'));
720
- main.append(head, body);
721
- let aside = fileDetails(details, file, nav);
722
- split.append(main, splitter(split), aside);
723
- view.append(split);
724
- const functions = details.functions.filter(record => record.path === file.path);
725
- const notes = (details.findings ?? []).flatMap(finding => {
726
- const line = finding.path === file.path ? finding.line : finding.related?.find(location => location.path === file.path)?.line;
727
- return line ? [{ line, level: finding.level, title: finding.rule, message: finding.message }] : [];
728
- });
729
- void load(file.path).then(text => {
730
- if (text === null) {
731
- // No locator, a private repository, a commit never pushed: one quiet state, and the forge's page when there is one.
732
- body.replaceChildren(element('p', 'fx-source-missing', 'Source not available'));
733
- // Nothing to shade: the head is the one a file without coverage has.
734
- toggle?.remove();
735
- return;
736
- }
737
- const choose = (chosen) => {
738
- line = chosen;
739
- history.replaceState(history.state, '', place());
740
- const moved = navigation.sourcePage?.(file.path, chosen);
741
- if (forge && moved)
742
- forge.href = moved.href;
743
- };
744
- const reveal = renderSource(body, text, {
745
- path: file.path,
746
- functions: functions.flatMap(record => record.line === null ? [] : [{ line: record.line, complexity: record.complexity, name: record.name }]),
747
- notes, line: navigation.line, choose,
748
- coverage: coverage ? lineStates(coverage) : undefined, hits: coverage ? lineHits(coverage) : undefined, layer,
749
- });
750
- const next = fileDetails(details, file, nav, { text, reveal: line => { reveal(line); choose(line); } });
751
- aside.replaceWith(next);
752
- aside = next;
753
- });
754
- return view;
755
- }
756
- /** A file's line coverage, where the inspection's coverage report names the file. */
757
- function fileCoverage(details, path) {
758
- const coverage = details.lineCoverage;
759
- return coverage && Object.hasOwn(coverage, path) ? coverage[path] : undefined;
760
- }
761
- const layerKey = 'repometry.source-layer';
762
- /** The URL's choice of what lines show, else the one made earlier in this session, else the findings. */
763
- function sourceLayer(requested) {
764
- if (isSourceLayer(requested))
765
- return requested;
766
- try {
767
- const stored = sessionStorage.getItem(layerKey);
768
- return isSourceLayer(stored) ? stored : 'issues';
769
- }
770
- catch {
771
- return 'issues';
772
- }
773
- }
774
- function rememberLayer(layer) {
775
- try {
776
- sessionStorage.setItem(layerKey, layer);
777
- }
778
- catch {
779
- // Blocked storage only forgets the choice; the URL still carries it.
780
- }
781
- }
782
- /**
783
- * The entries a page shows, 1-based, counting rows and not the fold of ignored files, which takes a place in the list
784
- * but is no entry of its own. None where the page holds only the fold.
785
- */
786
- export function entryRange(display, first, shown) {
787
- const entries = (from, to) => display.slice(from, to).filter(row => row.kind !== 'unread').length;
788
- const before = entries(0, first);
789
- const here = entries(first, first + shown);
790
- return here ? [before + 1, before + here] : null;
791
- }
792
- /**
793
- * The top of a relative colour scale, per level: files against files, folders against the folders at their depth. One
794
- * scale for both would let a folder's sum outshine every file in it, and the map would read hot folders over pale files.
795
- */
796
- export function relativePeaks(entries) {
797
- const level = (path, folder) => folder ? `folder:${path.split('/').length}` : 'file';
798
- const peaks = new Map();
799
- for (const { path, folder, score } of entries)
800
- peaks.set(level(path, folder), Math.max(peaks.get(level(path, folder)) ?? 1, score));
801
- return (path, folder) => peaks.get(level(path, folder)) ?? 1;
802
- }
803
- const maxRanked = 10;
804
- const chartCenter = 200;
805
- const innerRadius = 47;
806
- const outerRadius = 196;
807
- const fullCircle = 2 * Math.PI;
808
- const startAngle = -Math.PI / 2;
809
- function hotspotView(details, navigation, settings, directory) {
810
- const view = element('div', 'fx-view');
811
- // The window is part of what churn means, so it is in the metric's name rather than in a sentence about it.
812
- const days = details.metrics.churnWindow?.lookbackDays;
813
- // Repometry's rankings, then every other plugin's metric this inspection ran that has a worse end to rank by.
814
- const choices = [
815
- ...hotspotChoices.map(([value, name]) => [value, value === 'churn' && days ? `Changes in ${count(days)} days` : name]),
816
- ...pluginMetrics().filter(spec => spec.hotspot && measured(spec.descriptor)).map(spec => [spec.key, spec.label]),
817
- ];
818
- const linked = choices.find(([value]) => value === navigation.rank)?.[0];
819
- if (linked)
820
- settings.hotspot = linked;
821
- if (!choices.some(([value]) => value === settings.hotspot))
822
- settings.hotspot = 'complexity';
823
- const selector = choice('Rank by', choices, settings.hotspot);
824
- selector.label.classList.add('fx-field-bare');
825
- const tools = element('div', 'fx-tools fx-hotspot-tools');
826
- tools.append(breadcrumbs('hotspots', navigation, directory));
827
- const content = element('div', 'fx-hotspot-content');
828
- const provenance = element('p', 'fx-note fx-churn-provenance');
829
- view.append(tools, provenance, content);
830
- selector.select.addEventListener('change', () => {
831
- settings.hotspot = choices.find(([value]) => value === selector.select.value)?.[0] ?? 'complexity';
832
- history.replaceState(history.state, '', navigation.href('hotspots', { directory, rank: settings.hotspot }));
833
- render();
834
- });
835
- const files = details.metrics.files.filter(entry => inside(entry.path, directory));
836
- const byPath = new Map(files.map(entry => [entry.path, entry]));
837
- function render() {
838
- const metric = settings.hotspot;
839
- const caveat = metric === 'churn' ? churnCaveat(details.metrics.churnWindow) : '';
840
- provenance.hidden = !caveat;
841
- provenance.textContent = caveat;
842
- const plugin = pluginSpec(metric);
843
- const ranked = plugin ? pluginRanking(files, plugin) : (details.metrics.hotspots[metric] ?? []).flatMap(path => {
844
- const entry = byPath.get(path);
845
- return entry ? [entry] : [];
846
- });
847
- const hasMeasures = files.some(entry => hotspotScore(entry, metric) !== null);
848
- const mapSection = renderSunburst(details, { metric, directory, href: navigation.href, reshape: () => render(), controls: selector.label });
849
- const ranking = rankFiles(ranked, metric, navigation, hasMeasures, bandLimits(details, metric));
850
- content.replaceChildren(mapSection, ranking);
851
- }
852
- // The ranking is the page's side column: its heading stands on the page title's baseline, as a sidebar's does.
853
- liftToTitle(content, ':scope > .fx-rank h2');
854
- render();
855
- return view;
856
- }
857
- export function renderSunburst(details, options) {
858
- const { metrics } = details;
859
- const { metric, directory = '', compact = false, href } = options;
860
- const limits = bandLimits(details, metric);
861
- const shape = options.shape ?? mapShape();
862
- const panel = element('section', compact ? 'fx-sunburst fx-sunburst-compact' : 'panel fx-sunburst');
863
- panel.dataset.shape = shape;
864
- const selected = metrics.directories.find(entry => entry.path === directory);
865
- const useCodeLines = selected?.quality?.codeLines !== undefined;
866
- // The compact map has no title of its own: the switch alone heads it.
867
- const heading = element('div', 'fx-map-heading');
868
- // The view kind heads the map, at the left; what it is coloured by sits at the right. A title would only repeat
869
- // what the switch and the map already say, so the panel is named for screen readers alone.
870
- if (!compact)
871
- panel.setAttribute('aria-label', 'Code map');
872
- if (options.reshape) {
873
- const reshape = options.reshape;
874
- heading.append(segmented('Map shape', [['rings', 'Sunburst'], ['tiles', 'Treemap']], shape, value => {
875
- rememberMapShape(value);
876
- reshape(value);
877
- }));
878
- }
879
- if (options.controls)
880
- heading.append(options.controls);
881
- if (heading.childElementCount)
882
- panel.append(heading);
883
- const byParent = new Map();
884
- const levels = options.levels && spreadLevels(options.levels);
885
- let measured = levels !== undefined;
886
- function add(entry, folder) {
887
- const area = useCodeLines ? entry.quality?.codeLines : entry.lines;
888
- if (!area || !inside(entry.path, directory))
889
- return;
890
- measured ||= hotspotScore(entry, metric) !== null;
891
- const parent = parentPath(entry.path);
892
- // Nothing measured is nothing to count: a file without functions has no complexity, not an unknown one.
893
- const score = levels ? levels.get(entry.path) ?? 0 : hotspotScore(entry, metric) ?? 0;
894
- const branch = { entry, folder, area, score };
895
- const siblings = byParent.get(parent);
896
- if (siblings)
897
- siblings.push(branch);
898
- else
899
- byParent.set(parent, [branch]);
900
- }
901
- for (const folder of metrics.directories) {
902
- if (folder.path)
903
- add(folder, true);
904
- }
905
- for (const file of metrics.files)
906
- add(file, false);
907
- const root = byParent.get(directory);
908
- if (!root || root.length === 0) {
909
- panel.append(element('p', 'fx-note', 'No measured lines to show for this folder.'));
910
- return panel;
911
- }
912
- const units = useCodeLines ? 'code lines' : 'physical lines';
913
- let depth = 1;
914
- const originalDepth = directory ? directory.split('/').length : 0;
915
- for (const group of byParent.values()) {
916
- group.sort((a, b) => collator.compare(a.entry.path, b.entry.path));
917
- for (const entry of group)
918
- depth = Math.max(depth, entry.entry.path.split('/').length - originalDepth);
919
- }
920
- const peakOf = relativePeaks([...byParent.values()].flat().map(branch => ({ path: branch.entry.path, folder: branch.folder, score: branch.score })));
921
- const chartDepth = Math.min(depth, compact ? 4 : 5);
922
- const ring = (outerRadius - innerRadius) / chartDepth;
923
- const plugin = pluginSpec(metric);
924
- const heat = plugin ? bandScale(plugin) === 'heat' : metric !== 'churn';
925
- // Grey marks no data: a metric this inspection did not measure at all (no coverage report) is not a map of zeros.
926
- const grey = options.muted === true || !measured;
927
- panel.dataset.palette = levels ? 'grade' : grey ? 'none' : heat ? 'heat' : 'neutral';
928
- // A file no plugin read, or a folder of nothing else, has no measure: grey. Scanners read every file, so the
929
- // security map colours them all.
930
- const unread = unreadFolders(metrics.files);
931
- const shadeOf = (branch) => levels ? branch.score
932
- : branch.entry.analysed === false || unread.has(branch.entry.path) ? 'none' : band(branch.entry, metric, branch.score, peakOf(branch.entry.path, branch.folder), limits);
933
- const reading = (branch) => levels ? securityLevels[branch.score] : `${count(branch.score)} ${scoreLabel(metric)}`;
934
- // What the map encodes is said to assistive technology; on screen the legend's scale carries it.
935
- const description = `${shape === 'tiles' ? 'Tile' : 'Wedge'} size shows ${units}. ${levels ? 'Colour shows the worst security finding.' : meaningOf(metric)}`;
936
- // The scale runs the panel's width under the title row: the key to the whole map.
937
- if (!compact)
938
- panel.append(grey ? element('p', 'fx-note', 'Nothing measured for this map, so it shows sizes only.') : levels ? levelLegend() : sunburstLegend(metric, limits));
939
- const canvas = svgElement('svg');
940
- canvas.classList.add('fx-sunburst-chart');
941
- const width = shape === 'tiles' ? compact ? 400 : 640 : 400;
942
- const height = shape === 'tiles' ? compact ? 320 : 420 : 400;
943
- canvas.setAttribute('viewBox', `0 0 ${width} ${height}`);
944
- if (shape === 'tiles')
945
- canvas.classList.add('fx-treemap');
946
- canvas.setAttribute('role', 'group');
947
- canvas.setAttribute('aria-label', `Code map of ${directory || 'the repository root'}. ${description}`);
948
- // Values appear on hover or focus only, so the map does not repeat the ranking beside it.
949
- // The readout holds its room and fills on hover or focus; the map needs no sentence telling to point at it.
950
- const summary = element('p', 'fx-map-summary fx-map-hint fx-map-hint-quiet');
951
- let sectors = 0;
952
- let smallWedges = false;
953
- // One outline drawn above every wedge, so neighbours never paint over it.
954
- const outline = svgElement('path');
955
- outline.classList.add('fx-wedge-outline');
956
- outline.setAttribute('aria-hidden', 'true');
957
- function inspect(branch, tile) {
958
- // The pointed wedge keeps its colour together with its parents and its contents; the rest of the map fades.
959
- const own = branch.entry.path;
960
- canvas.setAttribute('data-inspecting', '');
961
- for (const wedge of canvas.querySelectorAll('.fx-wedge')) {
962
- const other = wedge.dataset.path;
963
- wedge.toggleAttribute('data-related', other === own || own.startsWith(`${other}/`) || other.startsWith(`${own}/`));
964
- }
965
- outline.setAttribute('d', tile.querySelector('path').getAttribute('d'));
966
- canvas.append(outline);
967
- summary.classList.remove('fx-map-hint');
968
- const path = element('code', 'fx-path', branch.entry.path);
969
- const score = reading(branch);
970
- const additional = metric === 'missedLines' ? ` · ${coverageText(branch.entry)} covered`
971
- : metric === 'duplication' ? ` · ${duplicationText(branch.entry)} duplicated` : '';
972
- summary.replaceChildren(path, element('strong', '', score + additional));
973
- }
974
- function draw(children, first, last, level) {
975
- if (level >= chartDepth)
976
- return;
977
- const total = children.reduce((sum, branch) => sum + branch.area, 0);
978
- const scale = (last - first) / total;
979
- let start = first;
980
- for (const branch of children) {
981
- const end = start + branch.area * scale;
982
- if (end - start >= 0.018 && sectors < 144) {
983
- sectors++;
984
- const tile = svgElement('a');
985
- tile.classList.add('fx-wedge');
986
- tile.setAttribute('href', branch.folder ? href('hotspots', { directory: branch.entry.path })
987
- : href('metrics', { directory: parentPath(branch.entry.path), file: branch.entry.path }));
988
- const measurement = reading(branch);
989
- const label = `${branch.entry.path} · ${count(branch.area)} ${units} · ${measurement}`;
990
- tile.setAttribute('aria-label', label);
991
- tile.dataset.path = branch.entry.path;
992
- const path = svgElement('path');
993
- const radius = innerRadius + level * ring;
994
- path.setAttribute('d', sectorPath(radius, radius + ring, start, end));
995
- path.setAttribute('data-band', String(shadeOf(branch)));
996
- tile.append(path);
997
- tile.addEventListener('focus', () => inspect(branch, tile));
998
- tile.addEventListener('pointerenter', () => inspect(branch, tile));
999
- canvas.append(tile);
1000
- draw(byParent.get(branch.entry.path) ?? [], start, end, level + 1);
1001
- }
1002
- else
1003
- smallWedges = true;
1004
- start = end;
1005
- }
1006
- }
1007
- /** The same tree as tiles: folders frame their contents under a name strip, files fill the space by size. */
1008
- function tiles(children, x, y, w, h, level) {
1009
- for (const { branch, box } of squarify(children, x, y, w, h)) {
1010
- if (box.w < 2 || box.h < 2 || sectors >= 600) {
1011
- smallWedges = true;
1012
- continue;
1013
- }
1014
- sectors++;
1015
- const tile = svgElement('a');
1016
- tile.classList.add('fx-wedge');
1017
- if (branch.folder)
1018
- tile.classList.add('fx-tile-folder');
1019
- tile.setAttribute('href', branch.folder ? href('hotspots', { directory: branch.entry.path })
1020
- : href('metrics', { directory: parentPath(branch.entry.path), file: branch.entry.path }));
1021
- const measurement = reading(branch);
1022
- tile.setAttribute('aria-label', `${branch.entry.path} · ${count(branch.area)} ${units} · ${measurement}`);
1023
- tile.dataset.path = branch.entry.path;
1024
- const path = svgElement('path');
1025
- path.setAttribute('d', `M${box.x.toFixed(1)},${box.y.toFixed(1)}h${box.w.toFixed(1)}v${box.h.toFixed(1)}h${(-box.w).toFixed(1)}z`);
1026
- const shade = shadeOf(branch);
1027
- path.setAttribute('data-band', String(shade));
1028
- tile.append(path);
1029
- // A chain of folders that each hold one folder is one frame: src/main/ts/ rather than three nested ones.
1030
- let inner = byParent.get(branch.entry.path) ?? [];
1031
- let name = basename(branch.entry.path);
1032
- while (inner.length === 1 && inner[0].folder) {
1033
- name += `/${basename(inner[0].entry.path)}`;
1034
- inner = byParent.get(inner[0].entry.path) ?? [];
1035
- }
1036
- const open = branch.folder && inner.length > 0 && level + 1 < chartDepth + 1 && box.w > 28 && box.h > 28;
1037
- const strip = open && box.w > 64 && box.h > 44 ? 15 : open ? 3 : 0;
1038
- if ((!branch.folder || !open || strip > 3) && box.w > (branch.folder ? 64 : 44) && box.h > (open ? 0 : 17)) {
1039
- const label = svgElement('text');
1040
- label.classList.add('fx-tile-label');
1041
- if (shade !== 'none' && shade >= 3)
1042
- label.classList.add('fx-tile-label-light');
1043
- label.setAttribute('x', (box.x + 4).toFixed(1));
1044
- label.setAttribute('y', (box.y + 11.5).toFixed(1));
1045
- label.textContent = fit(name + (branch.folder ? '/' : ''), box.w - 8);
1046
- tile.append(label);
1047
- }
1048
- tile.addEventListener('focus', () => inspect(branch, tile));
1049
- tile.addEventListener('pointerenter', () => inspect(branch, tile));
1050
- canvas.append(tile);
1051
- if (open)
1052
- tiles(inner, box.x + 3, box.y + strip, box.w - 6, box.h - strip - 3, level + 1);
1053
- }
1054
- }
1055
- if (shape === 'tiles')
1056
- tiles(root, 0, 0, width, height, 0);
1057
- else
1058
- draw(root, startAngle, startAngle + fullCircle, 0);
1059
- const hint = summary.textContent;
1060
- const reset = () => {
1061
- canvas.removeAttribute('data-inspecting');
1062
- for (const wedge of canvas.querySelectorAll('.fx-wedge[data-related]'))
1063
- wedge.removeAttribute('data-related');
1064
- outline.remove();
1065
- summary.classList.add('fx-map-hint');
1066
- summary.textContent = hint;
1067
- };
1068
- canvas.addEventListener('pointerleave', reset);
1069
- canvas.addEventListener('focusout', event => {
1070
- if (!canvas.contains(event.relatedTarget))
1071
- reset();
1072
- });
1073
- const center = svgElement('g');
1074
- center.setAttribute('aria-hidden', 'true');
1075
- const total = root.reduce((sum, branch) => sum + branch.area, 0);
1076
- const value = svgElement('text');
1077
- value.setAttribute('x', String(chartCenter));
1078
- value.setAttribute('y', String(chartCenter + 1));
1079
- value.classList.add('fx-sunburst-value');
1080
- value.textContent = count(total);
1081
- const label = svgElement('text');
1082
- label.setAttribute('x', String(chartCenter));
1083
- label.setAttribute('y', String(chartCenter + 21));
1084
- label.classList.add('fx-sunburst-unit');
1085
- label.textContent = units;
1086
- center.append(value, label);
1087
- // The compact map sits beside the scope line, which already states the total; tiles have no centre to hold it.
1088
- if (!compact && shape === 'rings')
1089
- canvas.append(center);
1090
- panel.append(canvas, summary);
1091
- return panel;
1092
- }
1093
- /**
1094
- * Squarified treemap layout: rows of tiles kept as close to square as the areas allow, largest first, so sizes stay
1095
- * comparable at a glance.
1096
- */
1097
- function squarify(children, x, y, w, h) {
1098
- const items = [...children].sort((a, b) => b.area - a.area);
1099
- const total = items.reduce((sum, item) => sum + item.area, 0);
1100
- const placed = [];
1101
- if (total <= 0 || w <= 0 || h <= 0)
1102
- return placed;
1103
- const scale = (w * h) / total;
1104
- let box = { x, y, w, h };
1105
- let row = [];
1106
- const worst = (line, side) => {
1107
- const areas = line.map(item => item.area * scale);
1108
- const sum = areas.reduce((a, b) => a + b, 0);
1109
- return Math.max(...areas.map(area => Math.max((side * side * area) / (sum * sum), (sum * sum) / (side * side * area))));
1110
- };
1111
- const lay = (line) => {
1112
- const sum = line.reduce((acc, item) => acc + item.area * scale, 0);
1113
- const vertical = box.w >= box.h;
1114
- const thickness = sum / (vertical ? box.h : box.w);
1115
- let offset = 0;
1116
- for (const item of line) {
1117
- const length = (item.area * scale) / thickness;
1118
- placed.push({ branch: item, box: vertical
1119
- ? { x: box.x, y: box.y + offset, w: thickness, h: length }
1120
- : { x: box.x + offset, y: box.y, w: length, h: thickness } });
1121
- offset += length;
1122
- }
1123
- box = vertical ? { x: box.x + thickness, y: box.y, w: box.w - thickness, h: box.h }
1124
- : { x: box.x, y: box.y + thickness, w: box.w, h: box.h - thickness };
1125
- };
1126
- for (const item of items) {
1127
- const side = Math.min(box.w, box.h);
1128
- if (row.length === 0 || worst([...row, item], side) <= worst(row, side))
1129
- row.push(item);
1130
- else {
1131
- lay(row);
1132
- row = [item];
1133
- }
1134
- }
1135
- if (row.length)
1136
- lay(row);
1137
- return placed;
1138
- }
1139
- /** A label cut to the room it has, at about six pixels a character. */
1140
- function fit(text, room) {
1141
- const chars = Math.floor(room / 6.2);
1142
- return text.length <= chars ? text : chars > 2 ? `${text.slice(0, chars - 1)}…` : '';
1143
- }
1144
- /**
1145
- * The handle between a list and its side panel: a line that shows on hover and drags the panel wider or narrower.
1146
- * Arrow keys move it too, a double click restores the default, and the width is remembered for this viewer.
1147
- */
1148
- export function splitter(split) {
1149
- const handle = element('div', 'fx-splitter');
1150
- handle.tabIndex = 0;
1151
- handle.setAttribute('role', 'separator');
1152
- handle.setAttribute('aria-orientation', 'vertical');
1153
- handle.setAttribute('aria-label', 'Resize the side panel');
1154
- handle.title = 'Drag to resize; double-click to reset';
1155
- const key = 'repometry.aside';
1156
- const limits = () => ({ low: 224, high: Math.max(224, split.clientWidth * .55) });
1157
- const apply = (width) => {
1158
- if (width === null)
1159
- split.style.removeProperty('--aside');
1160
- else {
1161
- const { low, high } = limits();
1162
- const clamped = Math.round(Math.min(high, Math.max(low, width)));
1163
- split.style.setProperty('--aside', `${clamped}px`);
1164
- handle.setAttribute('aria-valuenow', String(clamped));
1165
- }
1166
- };
1167
- const save = (width) => {
1168
- try {
1169
- if (width === null)
1170
- localStorage.removeItem(key);
1171
- else
1172
- localStorage.setItem(key, String(Math.round(width)));
1173
- }
1174
- catch {
1175
- // Without storage the width lasts for this page only.
1176
- }
1177
- };
1178
- const current = () => split.lastElementChild instanceof HTMLElement && split.lastElementChild !== handle
1179
- ? split.lastElementChild.getBoundingClientRect().width : 320;
1180
- try {
1181
- const stored = Number(localStorage.getItem(key));
1182
- if (stored > 0)
1183
- requestAnimationFrame(() => apply(stored));
1184
- }
1185
- catch {
1186
- // Storage may be blocked; the default width stands.
1187
- }
1188
- handle.addEventListener('pointerdown', event => {
1189
- event.preventDefault();
1190
- handle.setPointerCapture(event.pointerId);
1191
- split.classList.add('fx-resizing');
1192
- const right = split.getBoundingClientRect().right;
1193
- const move = (next) => apply(right - next.clientX - handle.offsetWidth / 2);
1194
- const stop = () => {
1195
- split.classList.remove('fx-resizing');
1196
- save(current());
1197
- handle.removeEventListener('pointermove', move);
1198
- handle.removeEventListener('pointerup', stop);
1199
- handle.removeEventListener('pointercancel', stop);
1200
- };
1201
- handle.addEventListener('pointermove', move);
1202
- handle.addEventListener('pointerup', stop);
1203
- handle.addEventListener('pointercancel', stop);
1204
- });
1205
- handle.addEventListener('keydown', event => {
1206
- if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')
1207
- return;
1208
- event.preventDefault();
1209
- apply(current() + (event.key === 'ArrowLeft' ? 24 : -24));
1210
- save(current());
1211
- });
1212
- handle.addEventListener('dblclick', () => { apply(null); save(null); });
1213
- liftToTitle(split, ':scope > .fx-aside h2');
1214
- return handle;
1215
- }
1216
- /**
1217
- * Raises a side column so its heading stands on the page title's baseline: the list and its summary read as one
1218
- * row of headings. What sits between the title and the panel (a folder path, a toolbar) varies, so the distance is
1219
- * measured, and measured again whenever the page above the panel changes height. One column on a narrow screen: no lift.
1220
- */
1221
- function liftToTitle(split, headingSelector) {
1222
- const baseline = (node) => {
1223
- const range = document.createRange();
1224
- range.selectNodeContents(node);
1225
- const box = range.getBoundingClientRect();
1226
- // The text box ends below the baseline by the descent, about a fifth of its height.
1227
- return box.bottom - box.height * .2;
1228
- };
1229
- const measure = () => {
1230
- const title = split.closest('section')?.querySelector(':scope > h2');
1231
- const heading = split.querySelector(headingSelector);
1232
- const columns = getComputedStyle(split).gridTemplateColumns.split(' ').length;
1233
- if (!split.isConnected || !title || !heading || columns < 2) {
1234
- split.style.removeProperty('--lift');
1235
- return;
1236
- }
1237
- // The column may be sticky, and once the page scrolls its box no longer sits where the layout put it. So the
1238
- // heading is measured inside its column, and the column's place is taken from the grid, which never sticks:
1239
- // unlifted, a first-row column starts at the top of the grid's content box.
1240
- let column = heading;
1241
- while (column.parentElement && column.parentElement !== split)
1242
- column = column.parentElement;
1243
- const style = getComputedStyle(split);
1244
- const top = split.getBoundingClientRect().top + parseFloat(style.borderTopWidth) + parseFloat(style.paddingTop);
1245
- const offset = baseline(heading) - column.getBoundingClientRect().top;
1246
- const current = parseFloat(split.style.getPropertyValue('--lift')) || 0;
1247
- const next = Math.max(0, Math.round(top + offset - baseline(title)));
1248
- if (next !== current)
1249
- split.style.setProperty('--lift', `${next}px`);
1250
- };
1251
- const observer = new ResizeObserver(() => {
1252
- if (!split.isConnected) {
1253
- observer.disconnect();
1254
- return;
1255
- }
1256
- measure();
1257
- });
1258
- requestAnimationFrame(() => {
1259
- measure();
1260
- // The page section, not the view: a view may be laid out through display: contents and never resize itself.
1261
- const page = split.closest('section') ?? split.parentElement;
1262
- if (page)
1263
- observer.observe(page);
1264
- });
1265
- }
1266
- /**
1267
- * The compact map's stand-in while the inspection loads: the same frame, switch and canvas size in a flat tone, so the
1268
- * column keeps its shape and the map fades in where it will stand.
1269
- */
1270
- export function mapStub() {
1271
- const shape = mapShape();
1272
- const panel = element('section', 'fx-sunburst fx-sunburst-compact fx-map-stub');
1273
- panel.dataset.shape = shape;
1274
- panel.setAttribute('aria-busy', 'true');
1275
- const heading = element('div', 'fx-map-heading');
1276
- heading.append(segmented('Map shape', [['rings', 'Sunburst'], ['tiles', 'Treemap']], shape, value => {
1277
- rememberMapShape(value);
1278
- panel.replaceWith(mapStub());
1279
- }));
1280
- const canvas = svgElement('svg');
1281
- canvas.classList.add('fx-sunburst-chart');
1282
- canvas.setAttribute('aria-hidden', 'true');
1283
- if (shape === 'tiles') {
1284
- canvas.classList.add('fx-treemap');
1285
- canvas.setAttribute('viewBox', '0 0 400 320');
1286
- const tile = svgElement('rect');
1287
- tile.setAttribute('width', '400');
1288
- tile.setAttribute('height', '320');
1289
- tile.setAttribute('rx', '3');
1290
- canvas.append(tile);
1291
- }
1292
- else {
1293
- canvas.setAttribute('viewBox', '0 0 400 400');
1294
- const ring = svgElement('circle');
1295
- ring.setAttribute('cx', '200');
1296
- ring.setAttribute('cy', '200');
1297
- ring.setAttribute('r', String((outerRadius + innerRadius) / 2));
1298
- ring.setAttribute('stroke-width', String(outerRadius - innerRadius));
1299
- canvas.append(ring);
1300
- }
1301
- panel.append(heading, canvas, element('p', 'fx-map-summary fx-map-hint fx-map-hint-quiet'));
1302
- return panel;
1303
- }
1304
- function mapShape() {
1305
- try {
1306
- return localStorage.getItem('repometry.map') === 'tiles' ? 'tiles' : 'rings';
1307
- }
1308
- catch {
1309
- return 'rings';
1310
- }
1311
- }
1312
- function rememberMapShape(shape) {
1313
- try {
1314
- localStorage.setItem('repometry.map', shape);
1315
- }
1316
- catch {
1317
- // A private window or blocked storage only loses the remembered choice.
1318
- }
1319
- }
1320
- const bandMeaning = {
1321
- complexity: 'Colour shows the most complex function.',
1322
- cognitive: 'Colour shows cognitive complexity relative to the highest file, or folder at the same depth.',
1323
- missedLines: 'Colour shows the share of uncovered lines.',
1324
- duplication: 'Colour shows the share of duplicated code lines.',
1325
- churn: 'Colour shows Git changes relative to the busiest file, or folder at the same depth.',
1326
- };
1327
- /** The band limits used when the profile sets none. */
1328
- const defaultLimits = { complexity: [5, 10, 20, 50], missedLines: [.05, .15, .3, .5], duplication: [.03, .1, .25] };
1329
- const scaled = (metric) => metric in defaultLimits;
1330
- /** The profile's limits for a metric with a meaningful scale, when they are well formed; otherwise the defaults. */
1331
- export function bandLimits(details, metric) {
1332
- if (!scaled(metric))
1333
- return undefined;
1334
- const given = details.bands?.[metric];
1335
- const size = defaultLimits[metric].length;
1336
- return given && given.length === size && given.every((value, index) => Number.isFinite(value) && (index === 0 || value > given[index - 1]))
1337
- ? given : defaultLimits[metric];
1338
- }
1339
- /** The legend's words for the bands, written from the limits: 1–5, 6–10 … 51+, or <5%, 5–15% … 50%+. */
1340
- function bandLabels(metric, limits) {
1341
- const percent = (value) => `${+(value * 100).toFixed(1)}%`;
1342
- if (metric === 'complexity') {
1343
- return [...limits.map((limit, index) => `${index === 0 ? 1 : limits[index - 1] + 1}–${limit}`), `${limits.at(-1) + 1}+`];
1344
- }
1345
- const ranges = [...limits.map((limit, index) => index === 0 ? `<${percent(limit)}`
1346
- : `${percent(limits[index - 1]).replace('%', '')}–${percent(limit)}`), `${percent(limits.at(-1))}+`];
1347
- return metric === 'duplication' ? ['0%', ...ranges] : ranges;
1348
- }
1349
- /** Maps a score to one of five colour bands: by the profile's limits where the metric has a meaningful scale. */
1350
- /** What the map's colour shows, said to assistive technology. */
1351
- function meaningOf(metric) {
1352
- const plugin = pluginSpec(metric);
1353
- if (!plugin)
1354
- return bandMeaning[metric];
1355
- return `Colour shows ${plugin.label.toLowerCase()}${plugin.descriptor.bands ? '' : ' relative to the highest file, or folder at the same depth'}.`;
1356
- }
1357
- export function band(entry, metric, score, highest, limits = scaled(metric) ? defaultLimits[metric] : undefined) {
1358
- const plugin = pluginSpec(metric);
1359
- if (plugin)
1360
- return bandOf(plugin, score, highest);
1361
- const step = (value, bounds) => {
1362
- const index = bounds.findIndex(limit => value <= limit);
1363
- return index < 0 ? bounds.length : index;
1364
- };
1365
- if (metric === 'complexity')
1366
- return step(score, limits);
1367
- if (metric === 'missedLines') {
1368
- const total = entry.lineCoverage?.total ?? 0;
1369
- return total > 0 ? step(score / total, limits) : 0;
1370
- }
1371
- if (metric === 'duplication') {
1372
- const lines = entry.quality?.codeLines ?? 0;
1373
- return score === 0 ? 0 : lines > 0 ? 1 + step(score / lines, limits) : 0;
1374
- }
1375
- return Math.min(4, Math.floor(score / highest * 5));
1376
- }
1377
- /** What a place on the security map reads as: the risk of its worst finding, the words the security grade uses. */
1378
- const securityLevels = securityRisks;
1379
- /** Each file's worst level spread to the folders above it. */
1380
- export function spreadLevels(files) {
1381
- const spread = new Map(files);
1382
- for (const [path, level] of files) {
1383
- for (let slash = path.lastIndexOf('/'); slash > 0; slash = path.lastIndexOf('/', slash - 1)) {
1384
- const folder = path.slice(0, slash);
1385
- spread.set(folder, Math.max(level, spread.get(folder) ?? 0));
1386
- }
1387
- }
1388
- return spread;
1389
- }
1390
- function levelLegend() {
1391
- const legend = element('p', 'fx-scale fx-note fx-scale-labelled');
1392
- const bar = element('span', 'fx-scale-bar');
1393
- bar.setAttribute('aria-hidden', 'true');
1394
- const words = element('span', 'fx-scale-words');
1395
- for (const [index, word] of ['None', 'Low', 'Medium', 'High', 'Critical'].entries()) {
1396
- const swatch = element('span');
1397
- swatch.dataset.band = String(index);
1398
- bar.append(swatch);
1399
- words.append(element('span', '', word));
1400
- }
1401
- legend.dataset.palette = 'grade';
1402
- legend.append(bar, words);
1403
- return legend;
1404
- }
1405
- function sunburstLegend(metric, limits) {
1406
- const legend = element('p', 'fx-scale fx-note');
1407
- const plugin = pluginSpec(metric);
1408
- const labels = plugin ? pluginBandLabels(plugin) ?? undefined : scaled(metric) && limits ? bandLabels(metric, limits) : undefined;
1409
- const bar = element('span', 'fx-scale-bar');
1410
- bar.setAttribute('aria-hidden', 'true');
1411
- for (let index = 0; index < 5; index++) {
1412
- const swatch = element('span');
1413
- swatch.dataset.band = String(index);
1414
- bar.append(swatch);
1415
- }
1416
- if (labels) {
1417
- // Each word stands under its band.
1418
- legend.classList.add('fx-scale-labelled');
1419
- const words = element('span', 'fx-scale-words');
1420
- words.append(...labels.map(label => element('span', '', label)));
1421
- legend.append(bar, words);
1422
- }
1423
- else
1424
- legend.append(element('span', '', 'Lower'), bar, element('span', '', 'Higher'));
1425
- return legend;
1426
- }
1427
- function sectorPath(inner, outer, first, last) {
1428
- const large = last - first > Math.PI ? 1 : 0;
1429
- const radius = (r, angle) => `${(chartCenter + r * Math.cos(angle)).toFixed(3)},${(chartCenter + r * Math.sin(angle)).toFixed(3)}`;
1430
- if (last - first >= fullCircle - 0.00001) {
1431
- const middle = first + Math.PI;
1432
- return `M${radius(outer, first)} A${outer},${outer} 0 1 1 ${radius(outer, middle)} A${outer},${outer} 0 1 1 ${radius(outer, first)}
1433
- M${radius(inner, first)} A${inner},${inner} 0 1 0 ${radius(inner, middle)} A${inner},${inner} 0 1 0 ${radius(inner, first)} Z`;
1434
- }
1435
- return `M${radius(outer, first)} A${outer},${outer} 0 ${large} 1 ${radius(outer, last)}
1436
- L${radius(inner, last)} A${inner},${inner} 0 ${large} 0 ${radius(inner, first)} Z`;
1437
- }
1438
- function svgElement(tag) {
1439
- return document.createElementNS('http://www.w3.org/2000/svg', tag);
1440
- }
1441
- /**
1442
- * Files by another plugin's metric, worst first. Where lower is better a zero is nothing to fix and stays off the list,
1443
- * as with Repometry's own rankings; where higher is better every measured file ranks.
1444
- */
1445
- function pluginRanking(files, spec) {
1446
- const order = compareValues(firstSortAscending(spec));
1447
- return files.flatMap(entry => {
1448
- const value = entryValue(local.index, entry, spec);
1449
- return value === null || (spec.descriptor.better !== 'higher' && value <= 0) ? [] : [{ entry, value }];
1450
- }).sort((a, b) => order(a.value, b.value) || collator.compare(a.entry.path, b.entry.path)).map(({ entry }) => entry);
1451
- }
1452
- const rankTitles = {
1453
- complexity: labelOf('complexity'),
1454
- cognitive: labelOf('cognitive'),
1455
- missedLines: 'Uncovered lines',
1456
- duplication: 'Duplicated lines',
1457
- churn: 'Git changes',
1458
- };
1459
- /** What makes the churn count incomplete, when anything does: missing history, a shallow checkout, a capped scan. */
1460
- function churnCaveat(window) {
1461
- if (!window)
1462
- return 'Git history is unavailable for this inspection.';
1463
- return [window.shallow ? 'The checkout is shallow, so older changes are missing.' : '',
1464
- window.capReached ? `Only the latest ${count(window.maxCommits)} commits were scanned.` : ''].filter(Boolean).join(' ');
1465
- }
1466
- function rankFiles(entries, metric, navigation, hasMeasures, limits) {
1467
- const panel = element('section', 'fx-rank');
1468
- // The bars speak the map's colours: the same bands, the same palette.
1469
- const plugin = pluginSpec(metric);
1470
- panel.dataset.palette = plugin ? bandScale(plugin) : metric === 'churn' ? 'neutral' : 'heat';
1471
- const heading = rankTitle(metric);
1472
- panel.append(element('h2', '', `${heading} by file`));
1473
- if (!entries.length) {
1474
- panel.append(element('p', 'fx-note', hasMeasures
1475
- ? `No files with ${heading.toLowerCase()} above zero.`
1476
- : `No measurements for ${heading.toLowerCase()} in this folder.`));
1477
- return panel;
1478
- }
1479
- const list = element('ol', 'fx-ranking');
1480
- const navigationState = navigationButtons('Ranking pages', () => { page--; render(); }, () => { page++; render(); });
1481
- navigationState.section.hidden = entries.length <= maxRanked;
1482
- // The longest bar is the highest value, whichever end of the scale the list starts from.
1483
- const peak = entries.reduce((max, entry) => Math.max(max, hotspotScore(entry, metric) ?? 0), 0) || 1;
1484
- let page = 0;
1485
- function render() {
1486
- const offset = page * maxRanked;
1487
- list.start = offset + 1;
1488
- list.replaceChildren(...entries.slice(offset, offset + maxRanked).map(entry => {
1489
- const row = element('li');
1490
- const title = link(fileHref(navigation, entry.path), basename(entry.path), 'fx-rank-link');
1491
- const path = element('span', 'fx-rank-path', parentPath(entry.path) || '/');
1492
- title.append(path);
1493
- const value = hotspotScore(entry, metric) ?? 0;
1494
- const mark = element('span', 'fx-rank-mark');
1495
- mark.style.setProperty('--length', `${value / peak * 100}%`);
1496
- mark.dataset.band = String(band(entry, metric, value, peak, limits));
1497
- mark.setAttribute('aria-hidden', 'true');
1498
- row.append(title, mark, element('strong', 'fx-rank-score', count(value)));
1499
- return row;
1500
- }));
1501
- navigationState.update(page, Math.ceil(entries.length / maxRanked));
1502
- }
1503
- panel.append(list, navigationState.section);
1504
- render();
1505
- return panel;
1506
- }
1507
- function functionList(functions) {
1508
- const list = element('ol', 'fx-function-list');
1509
- list.append(...functions.map(record => {
1510
- const row = element('li');
1511
- const subject = element('div');
1512
- subject.append(element('strong', '', record.line === null ? record.name : `${record.name} · line ${record.line}`));
1513
- row.append(subject, element('strong', 'fx-function-score', count(record.complexity)));
1514
- return row;
1515
- }));
1516
- return list;
1517
- }
1518
- const issueCategories = {
1519
- structure: 'Structure', duplication: 'Duplication', lint: 'Lint', security: 'Security',
1520
- dependency: 'Dependencies', secret: 'Secrets', infrastructure: 'Infrastructure',
1521
- };
1522
- const issueLevels = { high: 'High', medium: 'Medium', low: 'Low', unknown: 'Unknown' };
1523
- const levelOrder = { high: 0, medium: 1, low: 2, unknown: 3 };
1524
- function issuesView(details, navigation) {
1525
- const { findings, metrics } = details;
1526
- const view = element('div', 'fx-view fx-events');
1527
- if (findings === undefined) {
1528
- view.append(element('p', 'fx-note', 'Findings are unavailable for this inspection. Reinspect this commit to collect them.'));
1529
- return view;
1530
- }
1531
- const path = navigation.file;
1532
- const scoped = path ? findings.filter(item => atPath(item, path)) : findings;
1533
- if (path) {
1534
- const scope = element('div', 'fx-file-heading');
1535
- scope.append(element('code', 'fx-path', path), link(navigation.href('issues'), 'All findings', 'fx-inline-link'));
1536
- view.append(scope);
1537
- }
1538
- if (!scoped.length) {
1539
- view.append(element('p', 'fx-note', path ? 'No findings recorded for this file.' : 'No findings recorded for this commit.'));
1540
- return view;
1541
- }
1542
- // One line of controls, as on Metrics: a search, the severities as a switch, and selects that appear only where they
1543
- // can narrow something. The counts live in the sidebar, which follows the filters.
1544
- const search = searchField('Search findings', 'Search rules, messages and paths');
1545
- search.label.classList.add('fx-field-bare');
1546
- // A link may arrive with a search, as the Profile's rules do: the list opens narrowed to it.
1547
- search.input.value = navigation.query ?? '';
1548
- const present = ['high', 'medium', 'low', 'unknown'].filter(value => scoped.some(item => item.level === value));
1549
- // A link may name a severity and categories, as the Overview's figures do: the list opens filtered, the controls show it.
1550
- let level = present.find(value => value === navigation.level) ?? '';
1551
- const severity = segmented('Severity', [['', 'All'], ...present.map(value => [value, issueLevels[value]])], level, value => {
1552
- level = value;
1553
- reset();
1554
- });
1555
- const tally = (values, labels) => choices('', values, labels).slice(1)
1556
- .map(([value, name]) => [value, name, values.filter(item => item === value).length]);
1557
- const tools = multiChoice('Tool', 'All tools', 'tools', tally(scoped.map(item => item.tool)), reset);
1558
- const category = multiChoice('Category', 'All categories', 'categories', tally(scoped.map(item => item.category), issueCategories), reset, navigation.category?.split(','));
1559
- const toolbar = element('div', 'fx-tools fx-metrics-tools');
1560
- toolbar.append(search.label);
1561
- if (present.length > 1)
1562
- toolbar.append(severity);
1563
- toolbar.append(category.element, tools.element);
1564
- const status = element('p', 'fx-note fx-results');
1565
- status.setAttribute('aria-live', 'polite');
1566
- const list = element('div', 'fx-issue-list');
1567
- const nav = navigationButtons('Finding pages', () => { page--; render(); }, () => { page++; render(); });
1568
- const split = element('div', 'fx-split');
1569
- const main = element('div', 'fx-main');
1570
- main.append(toolbar, status, list, nav.section);
1571
- let aside = element('aside');
1572
- split.append(main, splitter(split), aside);
1573
- view.append(split);
1574
- const files = new Set(metrics.files.map(entry => entry.path));
1575
- let page = 0;
1576
- function render() {
1577
- const query = search.input.value.trim().toLowerCase();
1578
- const groups = new Map();
1579
- const chosen = [];
1580
- for (const item of scoped) {
1581
- if ((tools.values.size && !tools.values.has(item.tool))
1582
- || (category.values.size && !category.values.has(item.category))
1583
- || (level && item.level !== level)
1584
- || !contains(query, [item.rule, item.message, item.path, ...(item.related?.map(location => location.path) ?? [])]))
1585
- continue;
1586
- chosen.push(item);
1587
- const key = JSON.stringify([item.tool, item.rule, item.category, item.level]);
1588
- const group = groups.get(key);
1589
- if (group)
1590
- group.push(item);
1591
- else
1592
- groups.set(key, [item]);
1593
- }
1594
- const sorted = [...groups.values()].sort((a, b) => levelOrder[a[0].level] - levelOrder[b[0].level]
1595
- || b.length - a.length || collator.compare(a[0].rule, b[0].rule));
1596
- const rows = sorted.slice(page * pageSize, (page + 1) * pageSize);
1597
- list.replaceChildren(...rows.map(group => issueGroup(group, navigation, files)));
1598
- // The sidebar carries the counts; on screen this line speaks only when nothing matches, and it tells a screen
1599
- // reader what the filters left.
1600
- status.textContent = chosen.length === 0 ? 'No findings match these filters.'
1601
- : `${quantity(chosen.length, 'finding')} in ${quantity(groups.size, 'rule')}`;
1602
- status.classList.toggle('visually-hidden', chosen.length > 0);
1603
- nav.section.hidden = sorted.length <= pageSize;
1604
- nav.update(page, Math.ceil(sorted.length / pageSize));
1605
- const next = issueSummary(chosen, groups.size, navigation, files);
1606
- aside.replaceWith(next);
1607
- aside = next;
1608
- }
1609
- function reset() {
1610
- page = 0;
1611
- remember();
1612
- render();
1613
- }
1614
- /** The URL follows the filters, without a new history entry per change, so the view can be shared and reloaded. */
1615
- function remember() {
1616
- history.replaceState(history.state, '', navigation.href('issues', {
1617
- ...(path ? { file: path } : {}), query: search.input.value.trim(), level,
1618
- category: [...category.values].join(','),
1619
- }));
1620
- }
1621
- search.input.addEventListener('input', reset);
1622
- render();
1623
- return view;
1624
- }
1625
- /** Totals for the findings the filters select: how many, how much work, of what kind, and where they gather. */
1626
- function issueSummary(findings, rules, navigation, files) {
1627
- const panel = element('aside', 'fx-aside');
1628
- panel.setAttribute('aria-label', 'Findings summary');
1629
- const heading = element('div', 'fx-aside-heading');
1630
- heading.append(element('h2', '', 'Findings'));
1631
- const facts = element('dl', 'fx-kv');
1632
- facts.append(fact('Findings', count(findings.length)), fact('Rules', count(rules)));
1633
- const effort = findings.reduce((sum, item) => sum + (item.effortMinutes ?? 0), 0);
1634
- if (findings.some(item => item.effortMinutes !== undefined))
1635
- facts.append(fact(labelOf('effort'), duration(effort)));
1636
- // One severity would only repeat the total.
1637
- const levels = ['high', 'medium', 'low', 'unknown'].map(value => [value, findings.filter(item => item.level === value).length])
1638
- .filter(([, total]) => total > 0);
1639
- if (levels.length > 1)
1640
- for (const [value, total] of levels)
1641
- facts.append(fact(issueLevels[value], count(total)));
1642
- panel.append(heading, facts);
1643
- const categories = new Map();
1644
- for (const item of findings)
1645
- categories.set(item.category, (categories.get(item.category) ?? 0) + 1);
1646
- if (categories.size > 1) {
1647
- const section = element('section', 'fx-aside-section');
1648
- const rows = element('dl', 'fx-kv');
1649
- for (const [name, total] of [...categories].sort((a, b) => b[1] - a[1])) {
1650
- rows.append(fact(issueCategories[name] ?? name, count(total)));
1651
- }
1652
- section.append(element('h3', '', 'By category'), rows);
1653
- panel.append(section);
1654
- }
1655
- const places = new Map();
1656
- for (const item of findings)
1657
- for (const location of new Set(allLocations(item).map(place => place.path)))
1658
- places.set(location, (places.get(location) ?? 0) + 1);
1659
- if (places.size) {
1660
- const section = element('section', 'fx-aside-section');
1661
- const top = element('ol', 'fx-function-list fx-top-files');
1662
- for (const [file, total] of [...places].sort((a, b) => b[1] - a[1] || collator.compare(a[0], b[0])).slice(0, 5)) {
1663
- const row = element('li');
1664
- const name = files.has(file) ? link(navigation.href('issues', { file }), basename(file), 'fx-top-file') : element('span', 'fx-top-file', basename(file));
1665
- name.title = file;
1666
- row.append(name, element('strong', 'fx-function-score', count(total)));
1667
- top.append(row);
1668
- }
1669
- section.append(element('h3', '', 'Most affected files'), top);
1670
- panel.append(section);
1671
- }
1672
- return panel;
1673
- }
1674
- function issueGroup(group, navigation, files) {
1675
- const item = group[0];
1676
- const details = element('details', 'fx-issue');
1677
- const summary = element('summary', 'fx-issue-summary');
1678
- const identity = element('span');
1679
- const title = element('strong', '', item.rule);
1680
- const tool = element('span', 'fx-note', `${item.tool} · ${issueCategories[item.category] ?? item.category}`);
1681
- identity.append(title, tool);
1682
- const severity = element('span', 'fx-state', issueLevels[item.level]);
1683
- severity.dataset.state = item.level;
1684
- const effort = group.reduce((sum, finding) => sum + (finding.effortMinutes ?? 0), 0);
1685
- summary.append(identity, severity, element('span', 'fx-issue-count', group.some(finding => finding.effortMinutes !== undefined)
1686
- ? `${quantity(group.length, 'occurrence')} · ${duration(effort)}` : quantity(group.length, 'occurrence')));
1687
- const locations = element('ul', 'fx-event-list fx-occurrences');
1688
- // The excerpts mark their lines in the finding's own colour, as its severity badge does.
1689
- locations.dataset.level = item.level;
1690
- // The occurrences, and the source they load, are built when the group is first opened: a page of closed groups
1691
- // requests nothing.
1692
- details.addEventListener('toggle', () => { if (details.open && !locations.childElementCount)
1693
- locations.append(...group.map(occurrence)); });
1694
- function occurrence(finding) {
1695
- const row = element('li', 'fx-occurrence');
1696
- const places = allLocations(finding);
1697
- const primary = places[0];
1698
- // Each occurrence is bound to its code: the place, the message, and the lines themselves.
1699
- const head = element('div', 'fx-occurrence-head');
1700
- if (primary) {
1701
- const label = formatLocation(primary);
1702
- head.append(files.has(primary.path)
1703
- ? link(navigation.href('metrics', { directory: parentPath(primary.path), file: primary.path, ...(primary.line ? { line: primary.line } : {}) }), label, 'fx-location')
1704
- : element('code', 'fx-location', label));
1705
- }
1706
- if (finding.effortMinutes !== undefined)
1707
- head.append(element('span', 'fx-occurrence-effort', duration(finding.effortMinutes)));
1708
- const message = element('p', 'fx-occurrence-message', finding.message);
1709
- row.append(head, message);
1710
- const start = primary?.line;
1711
- if (primary && start !== undefined && files.has(primary.path) && navigation.source) {
1712
- const slot = element('div', 'fx-occurrence-code');
1713
- row.append(slot);
1714
- void navigation.source(primary.path).then(text => {
1715
- if (text === null) {
1716
- // An excerpt that cannot load leaves no gap; where the forge has the file, the place is one link away.
1717
- const page = navigation.sourcePage?.(primary.path, start);
1718
- if (!page) {
1719
- slot.remove();
1720
- return;
1721
- }
1722
- const away = link(page.href, `View on ${page.provider}`, 'fx-source-forge');
1723
- away.target = '_blank';
1724
- away.rel = 'noopener noreferrer';
1725
- slot.replaceChildren(away);
1726
- slot.classList.add('fx-occurrence-away');
1727
- return;
1728
- }
1729
- slot.append(renderExcerpt(text, { path: primary.path, line: start, endLine: primary.endLine,
1730
- more: line => navigation.href('metrics', { directory: parentPath(primary.path), file: primary.path, line }) }));
1731
- // A tool that could not name the function said "(anonymous)"; its first line says which one it is.
1732
- const snippet = lineSnippet(text, start, 48);
1733
- if (snippet && finding.message.startsWith('(anonymous)')) {
1734
- const name = element('code', 'fx-occurrence-name');
1735
- name.append(...highlightCode(primary.path, snippet));
1736
- message.replaceChildren(name, finding.message.slice('(anonymous)'.length));
1737
- }
1738
- });
1739
- }
1740
- const others = places.slice(1);
1741
- if (others.length) {
1742
- const paths = element('ul', 'fx-event-paths');
1743
- paths.append(...others.map(location => {
1744
- const path = element('li');
1745
- const label = formatLocation(location);
1746
- path.append(files.has(location.path)
1747
- ? link(navigation.href('metrics', { directory: parentPath(location.path), file: location.path, ...(location.line ? { line: location.line } : {}) }), `Also ${label}`, 'fx-inline-link')
1748
- : element('code', 'fx-path', label));
1749
- return path;
1750
- }));
1751
- row.append(paths);
1752
- }
1753
- const ignore = ignoreSnippet(finding);
1754
- if (ignore)
1755
- row.append(ignore);
1756
- return row;
1757
- }
1758
- details.append(summary, locations);
1759
- return details;
1760
- }
1761
- function ignoreSnippet(finding) {
1762
- const { tool, rule, path } = finding;
1763
- if ([tool, rule].some(value => !value.trim() || /[\0\r\n]/.test(value)))
1764
- return undefined;
1765
- const pathIsLiteral = Boolean(path && !/[\0\r\n\\*?{}[\]()]/.test(path) && !/^[#!]|^[a-z]:/i.test(path)
1766
- && path.split('/').every(part => part && part !== '.' && part !== '..'));
1767
- const record = { tool, rule, ...(pathIsLiteral ? { path } : {}) };
1768
- const details = element('details', 'fx-ignore');
1769
- const title = element('summary', '', 'Ignore rule');
1770
- const hint = element('p', 'fx-note', 'Add this entry to the profile’s ignore array and rerun the inspection. '
1771
- + (pathIsLiteral ? 'It matches this rule in the file shown.' : 'It matches this rule across the repository.'));
1772
- const input = element('textarea', 'fx-ignore-code');
1773
- input.readOnly = true;
1774
- input.rows = Object.keys(record).length + 2;
1775
- input.wrap = 'off';
1776
- input.value = JSON.stringify(record, null, 2);
1777
- input.setAttribute('aria-label', 'Profile ignore rule JSON');
1778
- const copy = element('button', 'fx-copy');
1779
- copy.type = 'button';
1780
- copy.title = 'Copy rule';
1781
- copy.setAttribute('aria-label', 'Copy rule');
1782
- copy.append(copyIcon());
1783
- const feedback = element('p', 'fx-note fx-copy-status');
1784
- feedback.setAttribute('role', 'status');
1785
- let reset;
1786
- copy.addEventListener('click', async () => {
1787
- clearTimeout(reset);
1788
- try {
1789
- if (!navigator.clipboard)
1790
- throw new Error('Clipboard unavailable');
1791
- await navigator.clipboard.writeText(input.value);
1792
- copy.classList.add('fx-copied');
1793
- copy.title = 'Copied';
1794
- feedback.textContent = 'Copied.';
1795
- feedback.classList.add('visually-hidden');
1796
- reset = setTimeout(() => {
1797
- copy.classList.remove('fx-copied');
1798
- copy.title = 'Copy rule';
1799
- feedback.textContent = '';
1800
- }, 1500);
1801
- }
1802
- catch {
1803
- input.focus();
1804
- input.select();
1805
- feedback.classList.remove('visually-hidden');
1806
- feedback.textContent = 'Rule selected. Press your copy shortcut.';
1807
- }
1808
- });
1809
- const code = element('div', 'fx-ignore-box');
1810
- code.append(input, copy);
1811
- details.append(title, hint, code, feedback);
1812
- return details;
1813
- }
1814
- /**
1815
- * Copies a file's path from the repository root. Where the browser refuses the clipboard, `show` puts the path on the
1816
- * page and it is selected, for the reader's own copy shortcut.
1817
- */
1818
- function copyPathButton(path, show) {
1819
- const label = 'Copy path';
1820
- const copy = element('button', 'fx-copy fx-copy-inline');
1821
- copy.type = 'button';
1822
- copy.title = `${label}: ${path}`;
1823
- copy.setAttribute('aria-label', label);
1824
- copy.append(copyIcon());
1825
- const status = element('span', 'visually-hidden');
1826
- status.setAttribute('role', 'status');
1827
- copy.append(status);
1828
- let reset;
1829
- copy.addEventListener('click', async () => {
1830
- clearTimeout(reset);
1831
- try {
1832
- if (!navigator.clipboard)
1833
- throw new Error('Clipboard unavailable');
1834
- await navigator.clipboard.writeText(path);
1835
- copy.classList.add('fx-copied');
1836
- status.textContent = 'Path copied';
1837
- reset = setTimeout(() => { copy.classList.remove('fx-copied'); status.textContent = ''; }, 1500);
1838
- }
1839
- catch {
1840
- window.getSelection()?.selectAllChildren(show());
1841
- status.textContent = 'Path selected. Press your copy shortcut.';
1842
- }
1843
- });
1844
- return copy;
1845
- }
1846
- /** The common copy glyph, two offset sheets, with the check it turns into once copied. */
1847
- export function copyIcon() {
1848
- const svg = svgElement('svg');
1849
- svg.setAttribute('viewBox', '0 0 16 16');
1850
- svg.setAttribute('aria-hidden', 'true');
1851
- const shapes = [
1852
- ['rect', { class: 'fx-copy-sheets', x: '5.5', y: '5.5', width: '8', height: '8', rx: '1.5' }],
1853
- ['path', { class: 'fx-copy-sheets', d: 'M10.5 3.5v-.5A1.5 1.5 0 0 0 9 1.5H3A1.5 1.5 0 0 0 1.5 3v6A1.5 1.5 0 0 0 3 10.5h.5' }],
1854
- ['path', { class: 'fx-copy-check', d: 'M3 8.5l3 3 7-7' }],
1855
- ];
1856
- for (const [tag, attributes] of shapes) {
1857
- const shape = svgElement(tag);
1858
- for (const [name, value] of Object.entries(attributes))
1859
- shape.setAttribute(name, value);
1860
- svg.append(shape);
1861
- }
1862
- return svg;
1863
- }
1864
- function allLocations(finding) {
1865
- return [
1866
- ...(finding.path ? [{ path: finding.path, line: finding.line, endLine: finding.endLine }] : []),
1867
- ...(finding.related ?? []),
1868
- ];
1869
- }
1870
- function atPath(finding, path) {
1871
- return finding.path === path || (finding.related?.some(location => location.path === path) ?? false);
1872
- }
1873
- function formatLocation(location) {
1874
- if (location.line === undefined)
1875
- return location.path;
1876
- const end = location.endLine !== undefined && location.endLine > location.line ? `–${location.endLine}` : '';
1877
- return `${location.path}:${location.line}${end}`;
1878
- }
1879
- const diagnosticStates = { failed: 'Failed', blocked: 'Blocked', partial: 'Partial' };
1880
- function diagnosticsView(details, navigation) {
1881
- const { diagnostics, metrics } = details;
1882
- const view = element('section', 'fx-view panel fx-events');
1883
- const path = navigation.file;
1884
- const scoped = path ? diagnostics.filter(row => row.path === path) : diagnostics;
1885
- if (path) {
1886
- const scope = element('div', 'fx-file-heading');
1887
- scope.append(element('code', 'fx-path', path), link(navigation.href('diagnostics'), 'All diagnostics', 'fx-inline-link'));
1888
- view.append(scope);
1889
- }
1890
- if (!scoped.length) {
1891
- view.append(element('p', 'fx-note', path ? 'No analysis diagnostics for this file.' : 'No analysis diagnostics for this commit.'));
1892
- return view;
1893
- }
1894
- const search = searchField('Search diagnostics', 'Operation, path or message');
1895
- const operation = choice('Operation', choices('All operations', scoped.map(row => row.operation)), '');
1896
- const state = choice('State', choices('All states', scoped.map(row => row.state), diagnosticStates), '');
1897
- const tools = element('div', 'fx-tools');
1898
- tools.append(search.label, operation.label, state.label);
1899
- const result = element('p', 'fx-note fx-results');
1900
- result.setAttribute('aria-live', 'polite');
1901
- const events = element('ul', 'fx-event-list');
1902
- const nav = navigationButtons('Diagnostic pages', () => { page--; render(); }, () => { page++; render(); });
1903
- view.append(tools, result, events, nav.section);
1904
- const files = new Set(metrics.files.map(entry => entry.path));
1905
- let page = 0;
1906
- function render() {
1907
- const query = search.input.value.trim().toLowerCase();
1908
- const matches = scoped.filter(row => (!state.select.value || state.select.value === row.state)
1909
- && (!operation.select.value || operation.select.value === row.operation)
1910
- && contains(query, [row.operation, row.path, row.message]));
1911
- result.textContent = matches.length ? quantity(matches.length, 'diagnostic') : 'No diagnostics match these filters.';
1912
- events.replaceChildren(...matches.slice(page * pageSize, (page + 1) * pageSize).map(row => {
1913
- const item = element('li');
1914
- const heading = element('div', 'fx-event-heading');
1915
- const state = element('span', 'fx-state', diagnosticStates[row.state]);
1916
- state.dataset.state = row.state;
1917
- heading.append(element('code', 'fx-path', row.operation), state);
1918
- item.append(heading, element('p', '', row.message));
1919
- if (row.path) {
1920
- item.append(files.has(row.path) ? link(fileHref(navigation, row.path), row.path, 'fx-inline-link')
1921
- : element('code', 'fx-path', row.path));
1922
- }
1923
- return item;
1924
- }));
1925
- nav.section.hidden = matches.length <= pageSize;
1926
- nav.update(page, Math.ceil(matches.length / pageSize));
1927
- }
1928
- const reset = () => { page = 0; render(); };
1929
- search.input.addEventListener('input', reset);
1930
- operation.select.addEventListener('change', reset);
1931
- state.select.addEventListener('change', reset);
1932
- render();
1933
- return view;
1934
- }
1935
- export function navigationButtons(label, previous, next) {
1936
- const section = element('nav', 'fx-page-buttons');
1937
- section.setAttribute('aria-label', label);
1938
- const back = element('button', 'button', 'Previous');
1939
- const forward = element('button', 'button', 'Next');
1940
- back.type = forward.type = 'button';
1941
- back.addEventListener('click', previous);
1942
- forward.addEventListener('click', next);
1943
- const pageLabel = element('span', 'fx-note');
1944
- pageLabel.setAttribute('aria-live', 'polite');
1945
- section.append(back, pageLabel, forward);
1946
- return { section, update: (page, pages) => {
1947
- back.disabled = page === 0;
1948
- forward.disabled = page + 1 >= pages;
1949
- pageLabel.textContent = `${count(page + 1)} of ${count(pages)}`;
1950
- } };
1951
- }
1952
- function breadcrumbs(view, navigation, directory) {
1953
- const nav = element('nav', 'fx-breadcrumbs');
1954
- nav.setAttribute('aria-label', 'Folder path');
1955
- const list = element('ol');
1956
- const leading = element('li');
1957
- if (directory === '') {
1958
- leading.setAttribute('aria-current', 'location');
1959
- leading.textContent = 'repo';
1960
- }
1961
- else
1962
- leading.append(link(navigation.href(view), 'repo'));
1963
- list.append(leading);
1964
- const segments = directory === '' ? [] : directory.split('/');
1965
- segments.forEach((part, index) => {
1966
- const item = element('li');
1967
- if (index === segments.length - 1) {
1968
- item.setAttribute('aria-current', 'location');
1969
- item.textContent = part;
1970
- }
1971
- else
1972
- item.append(link(navigation.href(view, { directory: segments.slice(0, index + 1).join('/') }), part));
1973
- list.append(item);
1974
- });
1975
- nav.append(list);
1976
- // At the root the trail is a single label that says nothing the page title does not.
1977
- nav.hidden = directory === '';
1978
- return nav;
1979
- }
1980
- function fact(label, value, context) {
1981
- const pair = element('div');
1982
- pair.append(element('dt', '', label), element('dd', '', value));
1983
- if (context)
1984
- pair.append(element('dd', 'fx-note', context));
1985
- return pair;
1986
- }
1987
- function scrollableTable(table, label) {
1988
- const region = element('div', 'table-scroll fx-table-scroll');
1989
- region.setAttribute('role', 'region');
1990
- region.setAttribute('aria-label', label);
1991
- region.tabIndex = 0;
1992
- region.append(table);
1993
- return region;
1994
- }
1995
- export function searchField(text, placeholder) {
1996
- const label = element('label', 'fx-field');
1997
- label.append(element('span', 'fx-field-text', text));
1998
- const input = element('input');
1999
- input.type = 'search';
2000
- input.placeholder = placeholder;
2001
- input.spellcheck = false;
2002
- label.append(input);
2003
- return { label, input };
2004
- }
2005
- /** Two or three exclusive views as one segmented switch; the pressed segment is the current view. */
2006
- function segmented(text, options, selected, change) {
2007
- const group = element('div', 'fx-segmented');
2008
- group.setAttribute('role', 'group');
2009
- group.setAttribute('aria-label', text);
2010
- const buttons = options.map(([value, name]) => {
2011
- const button = element('button', '', name);
2012
- button.type = 'button';
2013
- button.setAttribute('aria-pressed', String(value === selected));
2014
- button.addEventListener('click', () => {
2015
- for (const other of buttons)
2016
- other.setAttribute('aria-pressed', String(other === button));
2017
- change(value);
2018
- });
2019
- return button;
2020
- });
2021
- group.append(...buttons);
2022
- return group;
2023
- }
2024
- /** A details menu that closes on a click elsewhere or on Escape, as a menu does. */
2025
- function dismissible(menu) {
2026
- const close = (event) => {
2027
- if (event instanceof KeyboardEvent ? event.key === 'Escape' : !menu.contains(event.target)) {
2028
- if (menu.open && event instanceof KeyboardEvent)
2029
- menu.querySelector('summary')?.focus();
2030
- menu.open = false;
2031
- }
2032
- };
2033
- menu.addEventListener('toggle', () => {
2034
- if (menu.open) {
2035
- document.addEventListener('pointerdown', close, true);
2036
- document.addEventListener('keydown', close);
2037
- }
2038
- else {
2039
- document.removeEventListener('pointerdown', close, true);
2040
- document.removeEventListener('keydown', close);
2041
- }
2042
- });
2043
- }
2044
- /**
2045
- * A dropdown of checkboxes: none ticked means all. The button names what is chosen, so the filter reads at a glance;
2046
- * each option carries its count. It hides itself when there is nothing to choose between.
2047
- */
2048
- export function multiChoice(text, all, plural, options, change, initial = []) {
2049
- const offered = new Set(options.map(([value]) => value));
2050
- const values = new Set([...initial].filter(value => offered.has(value)));
2051
- const menu = element('details', 'fx-columns fx-multi');
2052
- menu.hidden = options.length < 2;
2053
- const summary = element('summary', '', all);
2054
- summary.setAttribute('aria-label', `${text}: ${all}`);
2055
- const list = element('div', 'fx-column-toggles');
2056
- list.setAttribute('role', 'group');
2057
- list.setAttribute('aria-label', text);
2058
- const names = new Map(options.map(([value, name]) => [value, name]));
2059
- function label() {
2060
- const chosen = options.filter(([value]) => values.has(value)).map(([, name]) => name);
2061
- // Two choices read by name, so a filtered view says what it holds; more read as a count.
2062
- summary.textContent = chosen.length === 0 ? all : chosen.length <= 2 ? chosen.join(', ') : `${chosen.length} ${plural}`;
2063
- summary.title = chosen.join(', ');
2064
- summary.setAttribute('aria-label', `${text}: ${chosen.length ? chosen.join(', ') : all}`);
2065
- menu.classList.toggle('fx-multi-active', chosen.length > 0);
2066
- }
2067
- for (const [value, name, count] of options) {
2068
- const row = element('label', 'fx-column-toggle');
2069
- const box = element('input');
2070
- box.type = 'checkbox';
2071
- box.value = value;
2072
- box.checked = values.has(value);
2073
- box.addEventListener('change', () => {
2074
- if (box.checked)
2075
- values.add(value);
2076
- else
2077
- values.delete(value);
2078
- label();
2079
- change();
2080
- });
2081
- row.append(box, element('span', 'fx-multi-name', names.get(value) ?? name), element('span', 'fx-multi-count', count.toLocaleString()));
2082
- list.append(row);
2083
- }
2084
- menu.append(summary, list);
2085
- dismissible(menu);
2086
- label();
2087
- return { element: menu, values };
2088
- }
2089
- function choice(text, options, selected) {
2090
- const label = element('label', 'fx-field');
2091
- label.append(element('span', 'fx-field-text', text));
2092
- const select = element('select');
2093
- for (const [value, name] of options) {
2094
- const option = element('option', '', name);
2095
- option.value = value;
2096
- select.append(option);
2097
- }
2098
- select.value = selected;
2099
- label.append(select);
2100
- return { label, select };
2101
- }
2102
- function choices(first, values, labels) {
2103
- const unique = [...new Set(values)].map(value => [value, labels?.[value] ?? value]);
2104
- return [['', first], ...unique.sort((a, b) => collator.compare(a[1], b[1]))];
2105
- }
2106
- function fileHref(navigation, file) {
2107
- return navigation.href('metrics', { directory: parentPath(file), file });
2108
- }
2109
- function compare(a, b, measurement, ascending) {
2110
- const left = measurement(a);
2111
- const right = measurement(b);
2112
- if (left === null || right === null)
2113
- return (left === null ? 1 : 0) - (right === null ? 1 : 0) || collator.compare(a.path, b.path);
2114
- const difference = typeof left === 'number' && typeof right === 'number' ? left - right : collator.compare(String(left), String(right));
2115
- return (ascending ? difference : -difference) || collator.compare(a.path, b.path);
2116
- }
2117
- function hotspotScore(entry, metric) {
2118
- const plugin = pluginSpec(metric);
2119
- if (plugin)
2120
- return entryValue(local.index, entry, plugin);
2121
- if (metric === 'complexity')
2122
- return entry.complexity?.maximum ?? null;
2123
- if (metric === 'cognitive')
2124
- return entry.quality?.cognitiveComplexity ?? null;
2125
- if (metric === 'duplication')
2126
- return entry.quality?.duplication?.duplicatedLines ?? null;
2127
- if (metric === 'churn')
2128
- return entry.quality?.churn ?? null;
2129
- const coverage = entry.lineCoverage;
2130
- return coverage && coverage.total > 0 ? coverage.total - coverage.covered : null;
2131
- }
2132
- function rankTitle(metric) {
2133
- return pluginSpec(metric)?.label ?? rankTitles[metric];
2134
- }
2135
- function scoreLabel(metric) {
2136
- return rankTitle(metric).toLowerCase();
2137
- }
2138
- function coverageRatio(entry) {
2139
- const coverage = entry.lineCoverage;
2140
- return coverage && coverage.total > 0 ? coverage.covered / coverage.total : null;
2141
- }
2142
- function coverageText(entry) {
2143
- const value = coverageRatio(entry);
2144
- return value === null ? '—' : percent.format(value);
2145
- }
2146
- function coverageContext(entry) {
2147
- const value = entry.lineCoverage;
2148
- return value && value.total > 0 ? `${count(value.covered)} of ${count(value.total)} lines` : undefined;
2149
- }
2150
- function duplicationRatio(entry) {
2151
- const value = entry.quality?.duplication;
2152
- return value && value.codeLines > 0 ? value.duplicatedLines / value.codeLines : null;
2153
- }
2154
- function duplicationText(entry) {
2155
- const value = duplicationRatio(entry);
2156
- return value === null ? '—' : percent.format(value);
2157
- }
2158
- function duplicationContext(entry) {
2159
- const value = entry.quality?.duplication;
2160
- return value && value.codeLines > 0 ? `${count(value.duplicatedLines)} of ${count(value.codeLines)} code lines` : undefined;
2161
- }
2162
- function duration(value) {
2163
- if (value == null)
2164
- return '—';
2165
- const remainder = value % 60;
2166
- const hours = Math.floor(value / 60);
2167
- const minutes = `${count(remainder)} min`;
2168
- return hours === 0 ? minutes : `${count(hours)} h${remainder === 0 ? '' : ` ${minutes}`}`;
2169
- }
2170
- function parentPath(path) {
2171
- return path.slice(0, Math.max(0, path.lastIndexOf('/')));
2172
- }
2173
- function basename(path) {
2174
- return path.slice(path.lastIndexOf('/') + 1);
2175
- }
2176
- function inside(path, directory) {
2177
- return directory === '' || path.startsWith(`${directory}/`);
2178
- }
2179
- function contains(query, strings) {
2180
- return query === '' || strings.some(value => value?.toLowerCase().includes(query));
2181
- }
2182
- function count(value) {
2183
- return value == null ? '—' : integer.format(value);
2184
- }
2185
- function quantity(amount, noun) {
2186
- return `${count(amount)} ${noun}${amount === 1 ? '' : 's'}`;
2187
- }
2188
- function link(href, label, className) {
2189
- const result = element('a', className, label);
2190
- result.href = href;
2191
- return result;
2192
- }
2193
- function element(tag, className, label) {
2194
- const result = document.createElement(tag);
2195
- if (className)
2196
- result.className = className;
2197
- if (label)
2198
- result.textContent = label;
2199
- return result;
31
+ const pages = {
32
+ metrics: () => selectedFile && navigation.source
33
+ ? fileView(details, navigation, selectedFile, navigation.source)
34
+ : metricsView(details, navigation, settings, directory, selectedFile),
35
+ hotspots: () => hotspotView(details, navigation, settings, directory),
36
+ issues: () => issuesView(details, navigation),
37
+ diagnostics: () => diagnosticsView(details, navigation),
38
+ };
39
+ container.replaceChildren(pages[view]());
2200
40
  }