1import Foundation
2
3/// Coverage cards and every module, each folding out its files.
4public struct IndexPage: Sendable {
5 public static let sitePath = "index.html"
6 private let title: String
7 private let modules: [ModuleTotals]
8 private let tests: TestRun?
9 private let run: ReportHeader
10 private let comparison: BaselineComparison?
11 private let hasRegions: Bool
12 private let hasBranches: Bool
13 private let trend: CoverageTrend
14 private let hasConditions: Bool
15
16 /// - Parameters:
17 /// - title: the site's name, shown as given in the page's title and heading.
18 /// - tests: results add the Tests tab; counts alone do not create a page.
19 /// - commit: the commit the report was built from, shortened in the header.
20 /// - subject: the commit's first message line.
21 /// - historyPath: the History destination relative to the report root, if available.
22 /// - trend: the line series shown in the coverage card.
23 /// - baseline: an earlier run to compare with; with it, the table gets a change
24 /// column.
25 public init(
26 title: String, files: [FileTotals], tests: TestRun?, commit: String?,
27 baseline: RunTotals? = nil, subject: String? = nil, historyPath: String? = nil,
28 trend: CoverageTrend = CoverageTrend(runs: [])
2981 ) {
3081 self.trend = trend
3181 self.comparison = baseline.map(BaselineComparison.init)
3281 self.title = title
3381 self.modules = ModuleTotals.grouping(files)
34169 self.hasRegions = files.contains { $0.regions != nil }
35172 self.hasBranches = files.contains { $0.branches != nil }
36174 self.hasConditions = files.contains { $0.conditions != nil }
3781 self.tests = tests
3881 self.run = ReportHeader(commit: commit, subject: subject, historyPath: historyPath)
3981 }
40
4181 public var html: String {
4281 """
4381 <!doctype html>
4481 <html lang="en">
4581 <head>
4681 <meta charset="utf-8">
4781 <meta name="viewport" content="width=device-width, initial-scale=1">
4881 <title>\(escapingHTML(title))</title>
4981 <link rel="stylesheet" href="\(SiteStylesheet.fileName)">
5081 </head>
5181 <body class="\(bodyClasses)">
5281 <header class="page-header">
5381 \(SiteHeader(title: title, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: "", run: run).html)
5481 </header>
5581 <main>
5681 \(cardsMarkup)
5781 <p class="legend"><span class="key high"></span>90% and up \
5881 <span class="key medium"></span>75% and up <span class="key low"></span>below 75%</p>
5981 <div class="toolbar" data-needs-script hidden>
6081 <input id="filter" type="search" placeholder="Filter files" aria-label="Filter files">\(compactToggle)
6181 </div>
6281 <div class="row columns" data-needs-script hidden>\
6381 <button type="button" data-sort="name" data-first="ascending">File</button>\(barHeading)\
6481 <button type="button" data-sort="percent" data-first="ascending">Lines</button>\
6581 <button type="button" data-sort="missed" data-first="descending">Missed</button>\
6681 \(comparison == nil ? "" : Self.sortButton("change", title: "Change", cell: "change"))\
6781 \(regionHeadings)\
6881 \(hasBranches ? #"<span class="branches">Branches</span>"# : "")\
6981 \(hasConditions ? #"<span class="conditions">Conditions</span>"# : "")</div>
7081 <div class="modules">
71204 \(modules.map(moduleMarkup).joined(separator: "\n"))
7281 </div>
7381 </main>
7481 <script>\(Self.sortAndFilterScript)</script>
7581 </body>
7681 </html>
7781
7881 """
7981 }
80
81 /// Whether rows have more to sum up than their lines.
82675 private var hasOtherMetrics: Bool { hasRegions || hasBranches || hasConditions }
83
8481 private var barHeading: String {
8581 hasOtherMetrics
8681 ? Self.sortButton("overall", title: "Overall", cell: "bar")
8781 : #"<span class="bar"></span>"#
8881 }
89
90 /// Switches the table to one column per metric. Lines alone already have just one.
9181 private var compactToggle: String {
9281 guard hasRegions else { return "" }
9328 return "\n"
9428 + #"<label class="compact-toggle"><input id="compact" type="checkbox"> Compact</label>"#
9581 }
96
9781 private var regionHeadings: String {
9881 guard hasRegions else { return "" }
9928 let change =
10028 comparison == nil
10128 ? "" : Self.sortButton("regionChange", title: "Change", cell: "regions-change")
10228 return Self.sortButton("regionPercent", title: "Regions", cell: "regions")
10328 + #"<button type="button" class="regions-missed" data-sort="regionMissed" data-first="descending">Missed</button>"#
10428 + change
10581 }
106
107 /// A heading that sorts by a share or change, the worst rows first.
10887 private static func sortButton(_ key: String, title: String, cell: String) -> String {
10987 #"<button type="button" class="\#(cell)" data-sort="\#(key)" data-first="ascending">\#(title)</button>"#
11087 }
111
112 /// The classes the stylesheet keys its extra columns on.
11381 private var bodyClasses: String {
11481 var classes = ["index-page"]
11581 if comparison != nil { classes.append("has-baseline") }
11681 if hasRegions { classes.append("has-regions") }
11781 if hasBranches { classes.append("has-branches") }
11881 if hasConditions { classes.append("has-conditions") }
11981 return classes.joined(separator: " ")
12081 }
121
12281 private var hasTestsPage: Bool {
12381 if case .results = tests { true } else { false }
12481 }
125
126 /// Lines alone fill one row of cards. With regions, the two coverage cards share
127 /// the first row and their missed counts the second, so neither metric leads.
12881 private var cardsMarkup: String {
129123 let total = LineSummary(adding: modules.map(\.lines))
130123 let files = modules.flatMap(\.files)
13181 let lineCard = lineCard(total)
13281 let missedLines = Self.card(
13381 title: "Missed lines", value: groupingDigits(total.count - total.covered),
13481 detail: comparison.map { Self.missedChangeSpan($0.missedLineChange(now: total)) } ?? "")
13581 let newFiles = comparison.map { "\($0.newFileCount(in: files)) new since baseline" } ?? ""
13681 let fileCard = Self.card(
13781 title: "Files", value: groupingDigits(files.count), detail: newFiles)
13881 let rows =
139174 if let regions = CoverageCount(addingPresent: files.map(\.regions)) {
14028 Self.cardRow(
14128 [lineCard, regionCard(regions)], classes: "cards pair",
14228 label: "Coverage summary")
14328 + Self.cardRow(
14428 [missedLines, missedRegionCard(regions), fileCard], classes: "cards counts",
14528 label: "Coverage counts")
14653 } else {
14753 Self.cardRow(
14853 [lineCard, missedLines, fileCard], classes: "cards", label: "Coverage summary")
14953 }
15081 return rows + otherMetricCards(files)
15181 }
152
15381 private func lineCard(_ total: LineSummary) -> String {
15481 let change =
15581 comparison.map { Self.changeSpan($0.changeOfTotal(now: total)) + " since baseline · " }
15681 ?? ""
15781 return Self.card(
15881 title: "Line coverage", value: total.percentText,
15981 detail: change
16081 + "\(groupingDigits(total.covered)) of \(groupingDigits(total.count)) lines"
16181 + trend.sparkline)
16281 }
163
16428 private func regionCard(_ regions: CoverageCount) -> String {
16528 Self.card(
16628 title: "Region coverage", value: regions.percentText,
16728 detail: metricDetail(
16828 regions, noun: "regions", change: comparison?.regionChange(now: regions))
16928 + trend.regionSparkline)
17028 }
171
17228 private func missedRegionCard(_ regions: CoverageCount) -> String {
17328 let detail =
17428 comparison.map { baseline in
17510 baseline.missedRegionChange(now: regions).map(Self.missedChangeSpan)
17610 ?? Self.changeSpan(.new) + " since baseline"
17718 } ?? ""
17828 return Self.card(
17928 title: "Missed regions", value: groupingDigits(regions.total - regions.covered),
18028 detail: detail)
18128 }
182
183 /// Fewer missed is the improvement, so a fall is styled as `up`.
18423 private static func missedChangeSpan(_ difference: Int) -> String {
18523 let style = difference < 0 ? "up" : difference > 0 ? "down" : "flat"
18623 let sign = difference > 0 ? "+" : ""
18723 return
18823 #"<span class="change \#(style)">\#(sign)\#(groupingDigits(difference)) since baseline</span>"#
18923 }
190
191 /// Branch and condition cards, for the exports that count them.
19281 private func otherMetricCards(_ files: [FileTotals]) -> String {
19381 var cards = [String]()
194174 if let branches = CoverageCount(addingPresent: files.map(\.branches)) {
1955 cards.append(
1965 Self.card(
1975 title: "Branch coverage", value: branches.percentText,
1985 detail: metricDetail(
1995 branches, noun: "outcomes", change: comparison?.branchChange(now: branches))
2005 ))
2015 }
202174 if let conditions = CoverageCount(addingPresent: files.map(\.conditions)) {
2033 cards.append(
2043 Self.card(
2053 title: "Condition coverage", value: conditions.percentText,
2063 detail: metricDetail(
2073 conditions, noun: "conditions",
2083 change: comparison?.conditionChange(now: conditions))))
2093 }
21081 return cards.isEmpty
21181 ? "" : Self.cardRow(cards, classes: "cards secondary", label: "Additional coverage")
21281 }
213
214114 private static func cardRow(_ cards: [String], classes: String, label: String) -> String {
215114 #"<section class="\#(classes)" aria-label="\#(label)">"# + cards.joined() + "</section>"
216114 }
217
218307 private static func card(title: String, value: String, detail: String) -> String {
219307 #"<article class="card"><h2>\#(title)</h2><p class="value">\#(value)</p><p class="detail">\#(detail)</p></article>"#
220307 }
221
222 private func metricDetail(
223 _ count: CoverageCount, noun: String, change: CoverageChange?
22436 ) -> String {
22536 let delta = change.map { Self.changeSpan($0) + " since baseline · " } ?? ""
22636 return delta + "\(groupingDigits(count.covered)) of \(groupingDigits(count.total)) \(noun)"
22736 }
228
229 /// Shows the controls, sorts modules and the files inside each by the clicked column
230 /// (a second click reverses it), and filters files by path, opening the modules
231 /// that still have matches. Without scripts the modules still fold out by hand.
232 private static let sortAndFilterScript = """
233 (() => {
234 const list = document.querySelector(".modules");
235 const modules = [...list.querySelectorAll("details.module")];
236 const buttons = [...document.querySelectorAll("button[data-sort]")];
237 const filter = document.getElementById("filter");
238 document.querySelectorAll("[data-needs-script]").forEach(element => element.hidden = false);
239 let key = "name";
240 let ascending = true;
241 const value = row => key === "name" ? row.dataset.name.toLowerCase() : parseFloat(row.dataset[key]);
242 const order = (a, b) => {
243 const [x, y] = [value(a), value(b)];
244 // Rows without the value go last, whichever way the rest are sorted.
245 if (Number.isNaN(x) || Number.isNaN(y)) return Number.isNaN(x) - Number.isNaN(y);
246 return (x < y ? -1 : x > y ? 1 : 0) * (ascending ? 1 : -1);
247 };
248 const sort = () => {
249 for (const module of modules.sort(order)) {
250 module.append(...[...module.querySelectorAll("a.file")].sort(order));
251 list.append(module);
252 }
253 for (const button of buttons) {
254 button.dataset.direction = button.dataset.sort === key ? (ascending ? "ascending" : "descending") : "";
255 }
256 };
257 for (const button of buttons) {
258 button.addEventListener("click", () => {
259 ascending = button.dataset.sort === key ? !ascending : button.dataset.first === "ascending";
260 key = button.dataset.sort;
261 sort();
262 });
263 }
264 filter.addEventListener("input", () => {
265 const query = filter.value.trim().toLowerCase();
266 for (const module of modules) {
267 let hasMatch = false;
268 for (const file of module.querySelectorAll("a.file")) {
269 const path = (module.dataset.name + "/" + file.dataset.name).toLowerCase();
270 file.hidden = query !== "" && !path.includes(query);
271 hasMatch = hasMatch || !file.hidden;
272 }
273 module.hidden = !hasMatch;
274 module.open = query !== "" && hasMatch;
275 }
276 });
277 const compact = document.getElementById("compact");
278 if (compact) {
279 const storageKey = "covane.compact";
280 // Browsers may refuse storage; the view then just starts out normal.
281 try { compact.checked = localStorage.getItem(storageKey) === "true"; } catch {}
282 const shareColumns = { missed: "percent", change: "percent", regionMissed: "regionPercent", regionChange: "regionPercent" };
283 const apply = () => {
284 document.body.classList.toggle("compact", compact.checked);
285 // Never leave the rows ordered by a column the compact view hides.
286 if (compact.checked && key in shareColumns) {
287 key = shareColumns[key];
288 ascending = true;
289 }
290 sort();
291 };
292 compact.addEventListener("change", () => {
293 try { localStorage.setItem(storageKey, compact.checked); } catch {}
294 apply();
295 });
296 apply();
297 } else {
298 sort();
299 }
300 })();
301 """
302
303 /// A `<details>` per module, so its files fold out without any script.
304123 private func moduleMarkup(_ module: ModuleTotals) -> String {
305174 let files = module.files.map { file in
306174 let values = RowValues(
307174 name: String(file.relativePath.dropFirst(module.name.count + 1)),
308174 lines: file.lines,
309174 change: comparison?.change(ofFile: file.relativePath, now: file.lines),
310174 regions: file.regions,
311174 regionChange: file.regions.flatMap { now in
31230 comparison?.regionChange(ofFile: file.relativePath, now: now)
31330 },
314174 branches: file.branches, conditions: file.conditions)
315174 return
316174 #"<a class="row file" href="\#(escapingHTML(SourcePage.sitePath(for: file.relativePath)))""#
317174 + "\(sortKeys(values))>\(cells(values))</a>"
318174 }
319123 let values = RowValues(
320123 name: module.name, lines: module.lines,
321123 change: comparison?.change(ofModule: module.name, now: module.lines),
322123 regions: module.regions,
323123 regionChange: module.regions.flatMap { now in
32428 comparison?.regionChange(ofModule: module.name, now: now)
32528 },
326123 branches: module.branches, conditions: module.conditions)
327123 return """
328123 <details class="module"\(sortKeys(values))>
329123 <summary class="row">\(cells(values))</summary>
330123 \(files.joined(separator: "\n"))
331123 </details>
332123 """
333123 }
334
335 /// The values the index's sort script orders rows by, unformatted, so it compares
336 /// numbers rather than the text shown. A value a row lacks, or a change from
337 /// nothing, has no key.
338297 private func sortKeys(_ row: RowValues) -> String {
339297 var keys =
340297 #" data-name="\#(escapingHTML(row.name))""#
341297 + #" data-percent="\#(Self.sortNumber(row.lines.percent))""#
342297 + #" data-missed="\#(row.lines.count - row.lines.covered)" data-lines="\#(row.lines.count)""#
343297 if case .points(let points) = row.change {
34434 keys += #" data-change="\#(Self.sortNumber(points))""#
34534 }
346297 if let regions = row.regions {
34758 let share = LineSummary(count: regions.total, covered: regions.covered)
34858 keys +=
34958 #" data-region-percent="\#(Self.sortNumber(share.percent))""#
35058 + #" data-region-missed="\#(regions.total - regions.covered)""#
35158 }
352297 if case .points(let points) = row.regionChange {
35312 keys += #" data-region-change="\#(Self.sortNumber(points))""#
35412 }
355297 if let overall = overall(of: row) {
35671 keys += #" data-overall="\#(Self.sortNumber(overall.percent))""#
35771 }
358297 return keys
359297 }
360
361472 private static func sortNumber(_ value: Double) -> String {
362472 String(format: "%.2f", value)
363472 }
364
365110 private static func changeSpan(_ change: CoverageChange) -> String {
366110 #"<span class="change \#(change.styleName)">\#(change.text)</span>"#
367110 }
368
369 /// What one module's or file's row shows. The changes are nil without a baseline.
370 private struct RowValues {
371 let name: String
372 let lines: LineSummary
373 let change: CoverageChange?
374 let regions: CoverageCount?
375 let regionChange: CoverageChange?
376 let branches: CoverageCount?
377 let conditions: CoverageCount?
378 }
379
380297 private func cells(_ row: RowValues) -> String {
381297 let tier = row.lines.tier.rawValue
382297 let changeCell = row.change.map(Self.changeSpan) ?? ""
383297 let branchCell = hasBranches ? Self.countCell(row.branches, className: "branches") : ""
384297 let conditionCell =
385297 hasConditions ? Self.countCell(row.conditions, className: "conditions") : ""
386297 return #"<span class="name">\#(escapingHTML(row.name))</span>"#
387297 + barMarkup(row)
388297 + #"<span class="percent \#(tier)">\#(row.lines.percentText)</span>"#
389297 + #"<span class="missed">\#(groupingDigits(row.lines.count - row.lines.covered))</span>"#
390297 + changeCell
391297 + (hasRegions ? regionCells(row) : "")
392297 + branchCell + conditionCell
393297 }
394
395 /// The row summed up across its metrics; nil on a page of lines alone, whose bar
396 /// needs no summing up.
397594 private func overall(of row: RowValues) -> OverallCoverage? {
398594 guard hasOtherMetrics else { return nil }
399142 return OverallCoverage(
400142 lines: row.lines, regions: row.regions, branches: row.branches,
401142 conditions: row.conditions)
402594 }
403
404297 private func barMarkup(_ row: RowValues) -> String {
405297 let overall = overall(of: row)
406297 let tier = overall?.tier ?? row.lines.tier
407297 let width = overall?.percentText ?? row.lines.percentText
408297 let tooltip = overall.map { #" title="\#($0.breakdown)""# } ?? ""
409297 return
410297 #"<span class="bar"\#(tooltip)><span class="fill \#(tier.rawValue)" style="width: \#(width)"></span></span>"#
411297 }
412
413 /// Share, missed and, with a baseline, change, as for lines; dashes where this row
414 /// has no region data while others do.
41561 private func regionCells(_ row: RowValues) -> String {
41661 let share =
41761 row.regions.map { regions in
41858 #"<span class="percent \#(regions.tier.rawValue)">\#(regions.percentText)</span>"#
41958 } ?? "–"
42061 let missed = row.regions.map { groupingDigits($0.total - $0.covered) } ?? "–"
42161 let change =
42261 comparison == nil
42361 ? ""
42461 : #"<span class="regions-change">\#(row.regionChange.map(Self.changeSpan) ?? "–")</span>"#
42561 return #"<span class="regions">\#(share)</span>"#
42661 + #"<span class="regions-missed">\#(missed)</span>"# + change
42761 }
428
429 /// The share in its tier colour and the counts it comes from; a dash where this
430 /// file or module has no data while others do.
43118 private static func countCell(_ count: CoverageCount?, className: String) -> String {
43218 guard let count else { return #"<span class="\#(className)">–</span>"# }
43317 return #"<span class="\#(className)"><span class="percent \#(count.tier.rawValue)">"#
43417 + "\(count.percentText)</span> \(groupingDigits(count.covered))/"
43517 + "\(groupingDigits(count.total))</span>"
43618 }
437}