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: [])
2976 ) {
3076 self.trend = trend
3176 self.comparison = baseline.map(BaselineComparison.init)
3276 self.title = title
3376 self.modules = ModuleTotals.grouping(files)
34159 self.hasRegions = files.contains { $0.regions != nil }
35162 self.hasBranches = files.contains { $0.branches != nil }
36164 self.hasConditions = files.contains { $0.conditions != nil }
3776 self.tests = tests
3876 self.run = ReportHeader(commit: commit, subject: subject, historyPath: historyPath)
3976 }
40
4176 public var html: String {
4276 """
4376 <!doctype html>
4476 <html lang="en">
4576 <head>
4676 <meta charset="utf-8">
4776 <meta name="viewport" content="width=device-width, initial-scale=1">
4876 <title>\(escapingHTML(title))</title>
4976 <link rel="stylesheet" href="\(SiteStylesheet.fileName)">
5076 </head>
5176 <body class="\(bodyClasses)">
5276 <header class="page-header">
5376 \(SiteHeader(title: title, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: "", run: run).html)
5476 </header>
5576 <main>
5676 \(cardsMarkup)
5776 <p class="legend"><span class="key high"></span>90% and up \
5876 <span class="key medium"></span>75% and up <span class="key low"></span>below 75%</p>
5976 <div class="toolbar" data-needs-script hidden>
6076 <input id="filter" type="search" placeholder="Filter files" aria-label="Filter files">\(compactToggle)
6176 </div>
6276 <div class="row columns" data-needs-script hidden>\
6376 <button type="button" data-sort="name" data-first="ascending">File</button>\(barHeading)\
6476 <button type="button" data-sort="percent" data-first="ascending">Lines</button>\
6576 <button type="button" data-sort="missed" data-first="descending">Missed</button>\
6676 \(comparison == nil ? "" : Self.sortButton("change", title: "Change", cell: "change"))\
6776 \(regionHeadings)\
6876 \(hasBranches ? #"<span class="branches">Branches</span>"# : "")\
6976 \(hasConditions ? #"<span class="conditions">Conditions</span>"# : "")</div>
7076 <div class="modules">
71189 \(modules.map(moduleMarkup).joined(separator: "\n"))
7276 </div>
7376 </main>
7476 <script>\(Self.sortAndFilterScript)</script>
7576 </body>
7676 </html>
7776
7876 """
7976 }
80
81 /// Whether rows have more to sum up than their lines.
82630 private var hasOtherMetrics: Bool { hasRegions || hasBranches || hasConditions }
83
8476 private var barHeading: String {
8576 hasOtherMetrics
8676 ? Self.sortButton("overall", title: "Overall", cell: "bar")
8776 : #"<span class="bar"></span>"#
8876 }
89
90 /// Switches the table to one column per metric. Lines alone already have just one.
9176 private var compactToggle: String {
9276 guard hasRegions else { return "" }
9328 return "\n"
9428 + #"<label class="compact-toggle"><input id="compact" type="checkbox"> Compact</label>"#
9576 }
96
9776 private var regionHeadings: String {
9876 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
10576 }
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.
11376 private var bodyClasses: String {
11476 var classes = ["index-page"]
11576 if comparison != nil { classes.append("has-baseline") }
11676 if hasRegions { classes.append("has-regions") }
11776 if hasBranches { classes.append("has-branches") }
11876 if hasConditions { classes.append("has-conditions") }
11976 return classes.joined(separator: " ")
12076 }
121
12276 private var hasTestsPage: Bool {
12376 if case .results = tests { true } else { false }
12476 }
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.
12876 private var cardsMarkup: String {
129113 let total = LineSummary(adding: modules.map(\.lines))
130113 let files = modules.flatMap(\.files)
13176 let lineCard = lineCard(total)
13276 let missedLines = Self.card(
13376 title: "Missed lines", value: groupingDigits(total.count - total.covered),
13476 detail: comparison.map { Self.missedChangeSpan($0.missedLineChange(now: total)) } ?? "")
13576 let newFiles = comparison.map { "\($0.newFileCount(in: files)) new since baseline" } ?? ""
13676 let fileCard = Self.card(
13776 title: "Files", value: groupingDigits(files.count), detail: newFiles)
13876 let rows =
139164 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")
14648 } else {
14748 Self.cardRow(
14848 [lineCard, missedLines, fileCard], classes: "cards", label: "Coverage summary")
14948 }
15076 return rows + otherMetricCards(files)
15176 }
152
15376 private func lineCard(_ total: LineSummary) -> String {
15476 let change =
15576 comparison.map { Self.changeSpan($0.changeOfTotal(now: total)) + " since baseline · " }
15676 ?? ""
15776 return Self.card(
15876 title: "Line coverage", value: total.percentText,
15976 detail: change
16076 + "\(groupingDigits(total.covered)) of \(groupingDigits(total.count)) lines"
16176 + trend.sparkline)
16276 }
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.
19276 private func otherMetricCards(_ files: [FileTotals]) -> String {
19376 var cards = [String]()
194164 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 }
202164 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 }
21076 return cards.isEmpty
21176 ? "" : Self.cardRow(cards, classes: "cards secondary", label: "Additional coverage")
21276 }
213
214109 private static func cardRow(_ cards: [String], classes: String, label: String) -> String {
215109 #"<section class="\#(classes)" aria-label="\#(label)">"# + cards.joined() + "</section>"
216109 }
217
218292 private static func card(title: String, value: String, detail: String) -> String {
219292 #"<article class="card"><h2>\#(title)</h2><p class="value">\#(value)</p><p class="detail">\#(detail)</p></article>"#
220292 }
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.
304113 private func moduleMarkup(_ module: ModuleTotals) -> String {
305164 let files = module.files.map { file in
306164 let values = RowValues(
307164 name: String(file.relativePath.dropFirst(module.name.count + 1)),
308164 lines: file.lines,
309164 change: comparison?.change(ofFile: file.relativePath, now: file.lines),
310164 regions: file.regions,
311164 regionChange: file.regions.flatMap { now in
31230 comparison?.regionChange(ofFile: file.relativePath, now: now)
31330 },
314164 branches: file.branches, conditions: file.conditions)
315164 return
316164 #"<a class="row file" href="\#(escapingHTML(SourcePage.sitePath(for: file.relativePath)))""#
317164 + "\(sortKeys(values))>\(cells(values))</a>"
318164 }
319113 let values = RowValues(
320113 name: module.name, lines: module.lines,
321113 change: comparison?.change(ofModule: module.name, now: module.lines),
322113 regions: module.regions,
323113 regionChange: module.regions.flatMap { now in
32428 comparison?.regionChange(ofModule: module.name, now: now)
32528 },
326113 branches: module.branches, conditions: module.conditions)
327113 return """
328113 <details class="module"\(sortKeys(values))>
329113 <summary class="row">\(cells(values))</summary>
330113 \(files.joined(separator: "\n"))
331113 </details>
332113 """
333113 }
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.
338277 private func sortKeys(_ row: RowValues) -> String {
339277 var keys =
340277 #" data-name="\#(escapingHTML(row.name))""#
341277 + #" data-percent="\#(Self.sortNumber(row.lines.percent))""#
342277 + #" data-missed="\#(row.lines.count - row.lines.covered)" data-lines="\#(row.lines.count)""#
343277 if case .points(let points) = row.change {
34434 keys += #" data-change="\#(Self.sortNumber(points))""#
34534 }
346277 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 }
352277 if case .points(let points) = row.regionChange {
35312 keys += #" data-region-change="\#(Self.sortNumber(points))""#
35412 }
355277 if let overall = overall(of: row) {
35671 keys += #" data-overall="\#(Self.sortNumber(overall.percent))""#
35771 }
358277 return keys
359277 }
360
361452 private static func sortNumber(_ value: Double) -> String {
362452 String(format: "%.2f", value)
363452 }
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
380277 private func cells(_ row: RowValues) -> String {
381277 let tier = row.lines.tier.rawValue
382277 let changeCell = row.change.map(Self.changeSpan) ?? ""
383277 let branchCell = hasBranches ? Self.countCell(row.branches, className: "branches") : ""
384277 let conditionCell =
385277 hasConditions ? Self.countCell(row.conditions, className: "conditions") : ""
386277 return #"<span class="name">\#(escapingHTML(row.name))</span>"#
387277 + barMarkup(row)
388277 + #"<span class="percent \#(tier)">\#(row.lines.percentText)</span>"#
389277 + #"<span class="missed">\#(groupingDigits(row.lines.count - row.lines.covered))</span>"#
390277 + changeCell
391277 + (hasRegions ? regionCells(row) : "")
392277 + branchCell + conditionCell
393277 }
394
395 /// The row summed up across its metrics; nil on a page of lines alone, whose bar
396 /// needs no summing up.
397554 private func overall(of row: RowValues) -> OverallCoverage? {
398554 guard hasOtherMetrics else { return nil }
399142 return OverallCoverage(
400142 lines: row.lines, regions: row.regions, branches: row.branches,
401142 conditions: row.conditions)
402554 }
403
404277 private func barMarkup(_ row: RowValues) -> String {
405277 let overall = overall(of: row)
406277 let tier = overall?.tier ?? row.lines.tier
407277 let width = overall?.percentText ?? row.lines.percentText
408277 let tooltip = overall.map { #" title="\#($0.breakdown)""# } ?? ""
409277 return
410277 #"<span class="bar"\#(tooltip)><span class="fill \#(tier.rawValue)" style="width: \#(width)"></span></span>"#
411277 }
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}