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: [])
2956 ) {
3056 self.trend = trend
3156 self.comparison = baseline.map(BaselineComparison.init)
3256 self.title = title
3356 self.modules = ModuleTotals.grouping(files)
34139 self.hasRegions = files.contains { $0.regions != nil }
35141 self.hasBranches = files.contains { $0.branches != nil }
36143 self.hasConditions = files.contains { $0.conditions != nil }
3756 self.tests = tests
3856 self.run = ReportHeader(commit: commit, subject: subject, historyPath: historyPath)
3956 }
40
4156 public var html: String {
4256 """
4356 <!doctype html>
4456 <html lang="en">
4556 <head>
4656 <meta charset="utf-8">
4756 <meta name="viewport" content="width=device-width, initial-scale=1">
4856 <title>\(escapingHTML(title))</title>
4956 <link rel="stylesheet" href="\(SiteStylesheet.fileName)">
5056 </head>
5156 <body class="\(bodyClasses)">
5256 <header class="page-header">
5356 \(SiteHeader(title: title, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: "", run: run).html)
5456 </header>
5556 <main>
5656 \(cardsMarkup)
5756 <p class="legend"><span class="key high"></span>90% and up \
5856 <span class="key medium"></span>75% and up <span class="key low"></span>below 75%</p>
5956 <div class="toolbar" data-needs-script hidden>
6056 <input id="filter" type="search" placeholder="Filter files" aria-label="Filter files">
6156 </div>
6256 <div class="row columns" data-needs-script hidden>\
6356 <button type="button" data-sort="name" data-first="ascending">File</button><span class="bar"></span>\
6456 <button type="button" data-sort="percent" data-first="ascending">Lines</button>\
6556 <button type="button" data-sort="missed" data-first="descending">Missed</button>\
6656 \(comparison == nil ? "" : #"<span class="change">Change</span>"#)\
6756 \(hasRegions ? #"<span class="regions">Regions</span>"# : "")\
6856 \(hasBranches ? #"<span class="branches">Branches</span>"# : "")\
6956 \(hasConditions ? #"<span class="conditions">Conditions</span>"# : "")</div>
7056 <div class="modules">
71149 \(modules.map(moduleMarkup).joined(separator: "\n"))
7256 </div>
7356 </main>
7456 <script>\(Self.sortAndFilterScript)</script>
7556 </body>
7656 </html>
7756
7856 """
7956 }
80
81 /// The classes the stylesheet keys its extra columns on.
8256 private var bodyClasses: String {
8356 var classes = ["index-page"]
8456 if comparison != nil { classes.append("has-baseline") }
8556 if hasRegions { classes.append("has-regions") }
8656 if hasBranches { classes.append("has-branches") }
8756 if hasConditions { classes.append("has-conditions") }
8856 return classes.joined(separator: " ")
8956 }
90
9156 private var hasTestsPage: Bool {
9256 if case .results = tests { true } else { false }
9356 }
94
9556 private var cardsMarkup: String {
9693 let total = LineSummary(adding: modules.map(\.lines))
9793 let files = modules.flatMap(\.files)
9856 let coverageChange =
9956 comparison.map { Self.changeSpan($0.changeOfTotal(now: total)) + " since baseline · " }
10056 ?? ""
10156 let missedChange =
10256 comparison.map { baseline in
1039 let difference = baseline.missedLineChange(now: total)
1049 let style = difference < 0 ? "up" : difference > 0 ? "down" : "flat"
1059 let sign = difference > 0 ? "+" : ""
1069 return
1079 #"<span class="change \#(style)">\#(sign)\#(groupingDigits(difference)) since baseline</span>"#
10847 } ?? ""
10956 let newFiles = comparison.map { "\($0.newFileCount(in: files)) new since baseline" } ?? ""
11056 let cards = [
11156 Self.card(
11256 title: "Line coverage", value: total.percentText,
11356 detail: coverageChange
11456 + "\(groupingDigits(total.covered)) of \(groupingDigits(total.count)) lines"
11556 + trend.sparkline),
11656 Self.card(
11756 title: "Missed lines", value: groupingDigits(total.count - total.covered),
11856 detail: missedChange),
11956 Self.card(title: "Files", value: groupingDigits(files.count), detail: newFiles),
12056 ]
12156 var additional = [String]()
122143 if let regions = CoverageCount(addingPresent: files.map(\.regions)) {
12311 additional.append(
12411 Self.card(
12511 title: "Region coverage", value: regions.percentText,
12611 detail: metricDetail(
12711 regions, noun: "regions", change: comparison?.regionChange(now: regions))))
12811 }
129143 if let branches = CoverageCount(addingPresent: files.map(\.branches)) {
1306 additional.append(
1316 Self.card(
1326 title: "Branch coverage", value: branches.percentText,
1336 detail: metricDetail(
1346 branches, noun: "outcomes", change: comparison?.branchChange(now: branches))
1356 ))
1366 }
137143 if let conditions = CoverageCount(addingPresent: files.map(\.conditions)) {
1383 additional.append(
1393 Self.card(
1403 title: "Condition coverage", value: conditions.percentText,
1413 detail: metricDetail(
1423 conditions, noun: "conditions",
1433 change: comparison?.conditionChange(now: conditions))))
1443 }
14556 let secondary =
14656 additional.isEmpty
14756 ? ""
14856 : #"<section class="cards secondary" aria-label="Additional coverage">"#
14915 + additional.joined() + "</section>"
15056 return #"<section class="cards" aria-label="Coverage summary">"# + cards.joined()
15156 + "</section>" + secondary
15256 }
153
154188 private static func card(title: String, value: String, detail: String) -> String {
155188 #"<article class="card"><h2>\#(title)</h2><p class="value">\#(value)</p><p class="detail">\#(detail)</p></article>"#
156188 }
157
158 private func metricDetail(
159 _ count: CoverageCount, noun: String, change: CoverageChange?
16020 ) -> String {
16120 let delta = change.map { Self.changeSpan($0) + " since baseline · " } ?? ""
16220 return delta + "\(groupingDigits(count.covered)) of \(groupingDigits(count.total)) \(noun)"
16320 }
164
165 /// Shows the controls, sorts modules and the files inside each by the clicked column
166 /// (a second click reverses it), and filters files by path, opening the modules
167 /// that still have matches. Without scripts the modules still fold out by hand.
168 private static let sortAndFilterScript = """
169 (() => {
170 const list = document.querySelector(".modules");
171 const modules = [...list.querySelectorAll("details.module")];
172 const buttons = [...document.querySelectorAll("button[data-sort]")];
173 const filter = document.getElementById("filter");
174 document.querySelectorAll("[data-needs-script]").forEach(element => element.hidden = false);
175 let key = "name";
176 let ascending = true;
177 const value = row => key === "name" ? row.dataset.name.toLowerCase() : parseFloat(row.dataset[key]);
178 const order = (a, b) => {
179 const [x, y] = [value(a), value(b)];
180 return (x < y ? -1 : x > y ? 1 : 0) * (ascending ? 1 : -1);
181 };
182 const sort = () => {
183 for (const module of modules.sort(order)) {
184 module.append(...[...module.querySelectorAll("a.file")].sort(order));
185 list.append(module);
186 }
187 for (const button of buttons) {
188 button.dataset.direction = button.dataset.sort === key ? (ascending ? "ascending" : "descending") : "";
189 }
190 };
191 for (const button of buttons) {
192 button.addEventListener("click", () => {
193 ascending = button.dataset.sort === key ? !ascending : button.dataset.first === "ascending";
194 key = button.dataset.sort;
195 sort();
196 });
197 }
198 filter.addEventListener("input", () => {
199 const query = filter.value.trim().toLowerCase();
200 for (const module of modules) {
201 let hasMatch = false;
202 for (const file of module.querySelectorAll("a.file")) {
203 const path = (module.dataset.name + "/" + file.dataset.name).toLowerCase();
204 file.hidden = query !== "" && !path.includes(query);
205 hasMatch = hasMatch || !file.hidden;
206 }
207 module.hidden = !hasMatch;
208 module.open = query !== "" && hasMatch;
209 }
210 });
211 sort();
212 })();
213 """
214
215 /// A `<details>` per module, so its files fold out without any script.
21693 private func moduleMarkup(_ module: ModuleTotals) -> String {
217143 let files = module.files.map { file in
218143 let name = String(file.relativePath.dropFirst(module.name.count + 1))
219143 let fileChange = comparison?.change(ofFile: file.relativePath, now: file.lines)
220143 return
221143 #"<a class="row file" href="\#(escapingHTML(SourcePage.sitePath(for: file.relativePath)))""#
222143 + "\(Self.sortKeys(name: name, lines: file.lines))>"
223143 + "\(cells(name: name, lines: file.lines, change: fileChange, counts: RowCounts(file)))</a>"
224143 }
22593 let moduleChange = comparison?.change(ofModule: module.name, now: module.lines)
22693 return """
22793 <details class="module"\(Self.sortKeys(name: module.name, lines: module.lines))>
22893 <summary class="row">\(cells(name: module.name, lines: module.lines, change: moduleChange, counts: RowCounts(module)))</summary>
22993 \(files.joined(separator: "\n"))
23093 </details>
23193 """
23293 }
233
234 /// The values the index's sort script orders rows by, unformatted, so it compares
235 /// numbers rather than the text shown.
236236 private static func sortKeys(name: String, lines: LineSummary) -> String {
237236 #" data-name="\#(escapingHTML(name))""#
238236 + #" data-percent="\#(String(format: "%.2f", lines.percent))""#
239236 + #" data-missed="\#(lines.count - lines.covered)" data-lines="\#(lines.count)""#
240236 }
241
24253 private static func changeSpan(_ change: CoverageChange) -> String {
24353 #"<span class="change \#(change.styleName)">\#(change.text)</span>"#
24453 }
245
246 /// The metrics a row may show beyond its lines.
247 private struct RowCounts {
248 let regions: CoverageCount?
249 let branches: CoverageCount?
250 let conditions: CoverageCount?
251
252143 init(_ file: FileTotals) {
253143 (regions, branches, conditions) = (file.regions, file.branches, file.conditions)
254143 }
255
25693 init(_ module: ModuleTotals) {
25793 (regions, branches, conditions) = (module.regions, module.branches, module.conditions)
25893 }
259 }
260
261 private func cells(
262 name: String, lines: LineSummary, change: CoverageChange?, counts: RowCounts
263236 ) -> String {
264236 let tier = lines.tier.rawValue
265236 let changeCell = change.map(Self.changeSpan) ?? ""
266236 let regionCell = hasRegions ? Self.countCell(counts.regions, className: "regions") : ""
267236 let branchCell = hasBranches ? Self.countCell(counts.branches, className: "branches") : ""
268236 let conditionCell =
269236 hasConditions ? Self.countCell(counts.conditions, className: "conditions") : ""
270236 return #"<span class="name">\#(escapingHTML(name))</span>"#
271236 + #"<span class="bar"><span class="fill \#(tier)" style="width: \#(lines.percentText)"></span></span>"#
272236 + #"<span class="percent \#(tier)">\#(lines.percentText)</span>"#
273236 + #"<span class="missed">\#(groupingDigits(lines.count - lines.covered))</span>"#
274236 + changeCell
275236 + regionCell + branchCell + conditionCell
276236 }
277
278 /// The share in its tier colour and the counts it comes from; a dash where this
279 /// file or module has no data while others do.
28046 private static func countCell(_ count: CoverageCount?, className: String) -> String {
28146 guard let count else { return #"<span class="\#(className)">–</span>"# }
28243 return #"<span class="\#(className)"><span class="percent \#(count.tier.rawValue)">"#
28343 + "\(count.percentText)</span> \(groupingDigits(count.covered))/"
28443 + "\(groupingDigits(count.total))</span>"
28546 }
286}