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 hasBranches: Bool
12 private let trend: CoverageTrend
13 private let hasConditions: Bool
14
15 /// - Parameters:
16 /// - title: the site's name, shown as given in the page's title and heading.
17 /// - tests: results add the Tests tab; counts alone do not create a page.
18 /// - commit: the commit the report was built from, shortened in the header.
19 /// - subject: the commit's first message line.
20 /// - historyPath: the History destination relative to the report root, if available.
21 /// - trend: the line series shown in the coverage card.
22 /// - baseline: an earlier run to compare with; with it, the table gets a change
23 /// column.
24 public init(
25 title: String, files: [FileTotals], tests: TestRun?, commit: String?,
26 baseline: RunTotals? = nil, subject: String? = nil, historyPath: String? = nil,
27 trend: CoverageTrend = CoverageTrend(runs: [])
2843 ) {
2943 self.trend = trend
3043 self.comparison = baseline.map(BaselineComparison.init)
3143 self.title = title
3243 self.modules = ModuleTotals.grouping(files)
33124 self.hasBranches = files.contains { $0.branches != nil }
34126 self.hasConditions = files.contains { $0.conditions != nil }
3543 self.tests = tests
3643 self.run = ReportHeader(commit: commit, subject: subject, historyPath: historyPath)
3743 }
38
3943 public var html: String {
4043 """
4143 <!doctype html>
4243 <html lang="en">
4343 <head>
4443 <meta charset="utf-8">
4543 <meta name="viewport" content="width=device-width, initial-scale=1">
4643 <title>\(escapingHTML(title))</title>
4743 <link rel="stylesheet" href="\(SiteStylesheet.fileName)">
4843 </head>
4943 <body class="\(bodyClasses)">
5043 <header class="page-header">
5143 \(SiteHeader(title: title, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: "", run: run).html)
5243 </header>
5343 <main>
5443 \(cardsMarkup)
5543 <p class="legend"><span class="key high"></span>90% and up \
5643 <span class="key medium"></span>75% and up <span class="key low"></span>below 75%</p>
5743 <div class="toolbar" data-needs-script hidden>
5843 <input id="filter" type="search" placeholder="Filter files" aria-label="Filter files">
5943 </div>
6043 <div class="row columns" data-needs-script hidden>\
6143 <button type="button" data-sort="name" data-first="ascending">File</button><span class="bar"></span>\
6243 <button type="button" data-sort="percent" data-first="ascending">Lines</button>\
6343 <button type="button" data-sort="missed" data-first="descending">Missed</button>\
6443 \(comparison == nil ? "" : #"<span class="change">Change</span>"#)\
6543 \(hasBranches ? #"<span class="branches">Branches</span>"# : "")\
6643 \(hasConditions ? #"<span class="conditions">Conditions</span>"# : "")</div>
6743 <div class="modules">
68123 \(modules.map(moduleMarkup).joined(separator: "\n"))
6943 </div>
7043 </main>
7143 <script>\(Self.sortAndFilterScript)</script>
7243 </body>
7343 </html>
7443
7543 """
7643 }
77
78 /// The classes the stylesheet keys its extra columns on.
7943 private var bodyClasses: String {
8043 var classes = ["index-page"]
8143 if comparison != nil { classes.append("has-baseline") }
8243 if hasBranches { classes.append("has-branches") }
8343 if hasConditions { classes.append("has-conditions") }
8443 return classes.joined(separator: " ")
8543 }
86
8743 private var hasTestsPage: Bool {
8843 if case .results = tests { true } else { false }
8943 }
90
9143 private var cardsMarkup: String {
9280 let total = LineSummary(adding: modules.map(\.lines))
9380 let files = modules.flatMap(\.files)
9443 let coverageChange =
9543 comparison.map { Self.changeSpan($0.changeOfTotal(now: total)) + " since baseline · " }
9643 ?? ""
9743 let missedChange =
9843 comparison.map { baseline in
997 let difference = baseline.missedLineChange(now: total)
1007 let style = difference < 0 ? "up" : difference > 0 ? "down" : "flat"
1017 let sign = difference > 0 ? "+" : ""
1027 return
1037 #"<span class="change \#(style)">\#(sign)\#(groupingDigits(difference)) since baseline</span>"#
10436 } ?? ""
10543 let newFiles = comparison.map { "\($0.newFileCount(in: files)) new since baseline" } ?? ""
10643 let cards = [
10743 Self.card(
10843 title: "Line coverage", value: total.percentText,
10943 detail: coverageChange
11043 + "\(groupingDigits(total.covered)) of \(groupingDigits(total.count)) lines"
11143 + trend.sparkline),
11243 Self.card(
11343 title: "Missed lines", value: groupingDigits(total.count - total.covered),
11443 detail: missedChange),
11543 Self.card(title: "Files", value: groupingDigits(files.count), detail: newFiles),
11643 ]
11743 var additional = [String]()
118126 if let branches = CoverageCount(addingPresent: files.map(\.branches)) {
1194 additional.append(
1204 Self.card(
1214 title: "Branch coverage", value: branches.percentText,
1224 detail: metricDetail(
1234 branches, noun: "outcomes", change: comparison?.branchChange(now: branches))
1244 ))
1254 }
126126 if let conditions = CoverageCount(addingPresent: files.map(\.conditions)) {
1273 additional.append(
1283 Self.card(
1293 title: "Condition coverage", value: conditions.percentText,
1303 detail: metricDetail(
1313 conditions, noun: "conditions",
1323 change: comparison?.conditionChange(now: conditions))))
1333 }
13443 let secondary =
13543 additional.isEmpty
13643 ? ""
13743 : #"<section class="cards secondary" aria-label="Additional coverage">"#
1384 + additional.joined() + "</section>"
13943 return #"<section class="cards" aria-label="Coverage summary">"# + cards.joined()
14043 + "</section>" + secondary
14143 }
142
143136 private static func card(title: String, value: String, detail: String) -> String {
144136 #"<article class="card"><h2>\#(title)</h2><p class="value">\#(value)</p><p class="detail">\#(detail)</p></article>"#
145136 }
146
147 private func metricDetail(
148 _ count: CoverageCount, noun: String, change: CoverageChange?
1497 ) -> String {
1507 let delta = change.map { Self.changeSpan($0) + " since baseline · " } ?? ""
1517 return delta + "\(groupingDigits(count.covered)) of \(groupingDigits(count.total)) \(noun)"
1527 }
153
154 /// Shows the controls, sorts modules and the files inside each by the clicked column
155 /// (a second click reverses it), and filters files by path, opening the modules
156 /// that still have matches. Without scripts the modules still fold out by hand.
157 private static let sortAndFilterScript = """
158 (() => {
159 const list = document.querySelector(".modules");
160 const modules = [...list.querySelectorAll("details.module")];
161 const buttons = [...document.querySelectorAll("button[data-sort]")];
162 const filter = document.getElementById("filter");
163 document.querySelectorAll("[data-needs-script]").forEach(element => element.hidden = false);
164 let key = "name";
165 let ascending = true;
166 const value = row => key === "name" ? row.dataset.name.toLowerCase() : parseFloat(row.dataset[key]);
167 const order = (a, b) => {
168 const [x, y] = [value(a), value(b)];
169 return (x < y ? -1 : x > y ? 1 : 0) * (ascending ? 1 : -1);
170 };
171 const sort = () => {
172 for (const module of modules.sort(order)) {
173 module.append(...[...module.querySelectorAll("a.file")].sort(order));
174 list.append(module);
175 }
176 for (const button of buttons) {
177 button.dataset.direction = button.dataset.sort === key ? (ascending ? "ascending" : "descending") : "";
178 }
179 };
180 for (const button of buttons) {
181 button.addEventListener("click", () => {
182 ascending = button.dataset.sort === key ? !ascending : button.dataset.first === "ascending";
183 key = button.dataset.sort;
184 sort();
185 });
186 }
187 filter.addEventListener("input", () => {
188 const query = filter.value.trim().toLowerCase();
189 for (const module of modules) {
190 let hasMatch = false;
191 for (const file of module.querySelectorAll("a.file")) {
192 const path = (module.dataset.name + "/" + file.dataset.name).toLowerCase();
193 file.hidden = query !== "" && !path.includes(query);
194 hasMatch = hasMatch || !file.hidden;
195 }
196 module.hidden = !hasMatch;
197 module.open = query !== "" && hasMatch;
198 }
199 });
200 sort();
201 })();
202 """
203
204 /// A `<details>` per module, so its files fold out without any script.
20580 private func moduleMarkup(_ module: ModuleTotals) -> String {
206126 let files = module.files.map { file in
207126 let name = String(file.relativePath.dropFirst(module.name.count + 1))
208126 let fileChange = comparison?.change(ofFile: file.relativePath, now: file.lines)
209126 return
210126 #"<a class="row file" href="\#(escapingHTML(SourcePage.sitePath(for: file.relativePath)))""#
211126 + "\(Self.sortKeys(name: name, lines: file.lines))>"
212126 + "\(cells(name: name, lines: file.lines, change: fileChange, branches: file.branches, conditions: file.conditions))</a>"
213126 }
21480 let moduleChange = comparison?.change(ofModule: module.name, now: module.lines)
21580 return """
21680 <details class="module"\(Self.sortKeys(name: module.name, lines: module.lines))>
21780 <summary class="row">\(cells(name: module.name, lines: module.lines, change: moduleChange, branches: module.branches, conditions: module.conditions))</summary>
21880 \(files.joined(separator: "\n"))
21980 </details>
22080 """
22180 }
222
223 /// The values the index's sort script orders rows by, unformatted, so it compares
224 /// numbers rather than the text shown.
225206 private static func sortKeys(name: String, lines: LineSummary) -> String {
226206 #" data-name="\#(escapingHTML(name))""#
227206 + #" data-percent="\#(String(format: "%.2f", lines.percent))""#
228206 + #" data-missed="\#(lines.count - lines.covered)" data-lines="\#(lines.count)""#
229206 }
230
23145 private static func changeSpan(_ change: CoverageChange) -> String {
23245 #"<span class="change \#(change.styleName)">\#(change.text)</span>"#
23345 }
234
235 private func cells(
236 name: String, lines: LineSummary, change: CoverageChange?, branches: CoverageCount?,
237 conditions: CoverageCount?
238206 ) -> String {
239206 let tier = lines.tier.rawValue
240206 let changeCell = change.map(Self.changeSpan) ?? ""
241206 let branchCell = hasBranches ? Self.countCell(branches, className: "branches") : ""
242206 let conditionCell = hasConditions ? Self.countCell(conditions, className: "conditions") : ""
243206 return #"<span class="name">\#(escapingHTML(name))</span>"#
244206 + #"<span class="bar"><span class="fill \#(tier)" style="width: \#(lines.percentText)"></span></span>"#
245206 + #"<span class="percent \#(tier)">\#(lines.percentText)</span>"#
246206 + #"<span class="missed">\#(groupingDigits(lines.count - lines.covered))</span>"#
247206 + changeCell
248206 + branchCell + conditionCell
249206 }
250
251 /// The share in its tier colour and the counts it comes from; a dash where this
252 /// file or module has no data while others do.
25316 private static func countCell(_ count: CoverageCount?, className: String) -> String {
25416 guard let count else { return #"<span class="\#(className)">–</span>"# }
25515 return #"<span class="\#(className)"><span class="percent \#(count.tier.rawValue)">"#
25615 + "\(count.percentText)</span> \(groupingDigits(count.covered))/"
25715 + "\(groupingDigits(count.total))</span>"
25816 }
259}