1import Foundation
2
3/// The site's front page: the run's headline 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 commit: String?
10 private let comparison: BaselineComparison?
11 private let hasBranches: Bool
12 private let hasConditions: Bool
13
14 /// - Parameters:
15 /// - title: the site's name, shown as given in the page's title and heading.
16 /// - tests: the run's tests; nil leaves them out of the headline. With results, the
17 /// headline links the test results page beside this one.
18 /// - commit: the commit the report was built from, shown as given.
19 /// - baseline: an earlier run to compare with; with it, the table gets a change
20 /// column.
21 public init(
22 title: String, files: [FileTotals], tests: TestRun?, commit: String?,
23 baseline: RunTotals? = nil
2437 ) {
2537 self.comparison = baseline.map(BaselineComparison.init)
2637 self.title = title
2737 self.modules = ModuleTotals.grouping(files)
28109 self.hasBranches = files.contains { $0.branches != nil }
29111 self.hasConditions = files.contains { $0.conditions != nil }
3037 self.tests = tests
3137 self.commit = commit
3237 }
33
3437 public var html: String {
3537 """
3637 <!doctype html>
3737 <html lang="en">
3837 <head>
3937 <meta charset="utf-8">
4037 <meta name="viewport" content="width=device-width, initial-scale=1">
4137 <title>\(escapingHTML(title))</title>
4237 <link rel="stylesheet" href="\(SiteStylesheet.fileName)">
4337 </head>
4437 <body class="\(bodyClasses)">
4537 <header class="page-header">
4637 \(SiteHeader(title: title, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: "").html)
4737 \(headlineMarkup)
4837 </header>
4937 <main>
5037 <p class="legend"><span class="key high"></span>90% and up \
5137 <span class="key medium"></span>75% and up <span class="key low"></span>below 75%</p>
5237 <div class="toolbar" data-needs-script hidden>
5337 <input id="filter" type="search" placeholder="Filter files" aria-label="Filter files">
5437 </div>
5537 <div class="row columns" data-needs-script hidden>\
5637 <button type="button" data-sort="name" data-first="ascending">File</button><span class="bar"></span>\
5737 <button type="button" data-sort="percent" data-first="ascending">Lines</button>\
5837 \(comparison == nil ? "" : #"<span class="change">Change</span>"#)\
5937 <button type="button" data-sort="missed" data-first="descending">Missed</button>\
6037 <button type="button" data-sort="lines" data-first="descending">Total</button>\
6137 \(hasBranches ? #"<span class="branches">Branches</span>"# : "")\
6237 \(hasConditions ? #"<span class="conditions">Conditions</span>"# : "")</div>
6337 <div class="modules">
64106 \(modules.map(moduleMarkup).joined(separator: "\n"))
6537 </div>
6637 </main>
6737 <script>\(Self.sortAndFilterScript)</script>
6837 </body>
6937 </html>
7037
7137 """
7237 }
73
74 /// The classes the stylesheet keys its extra columns on.
7537 private var bodyClasses: String {
7637 var classes = ["index-page"]
7737 if comparison != nil { classes.append("has-baseline") }
7837 if hasBranches { classes.append("has-branches") }
7937 if hasConditions { classes.append("has-conditions") }
8037 return classes.joined(separator: " ")
8137 }
82
8337 private var hasTestsPage: Bool {
8437 if case .results = tests { true } else { false }
8537 }
86
8737 private var headlineMarkup: String {
8869 let total = LineSummary(adding: modules.map(\.lines))
8937 let totalChange =
9037 comparison.map { Self.changeSpan($0.changeOfTotal(now: total)) + " " } ?? ""
9137 var parts = [
9237 #"<span class="percent \#(total.tier.rawValue)">\#(total.percentText)</span> "#
9337 + totalChange
9437 + "\(groupingDigits(total.covered)) of \(groupingDigits(total.count)) lines"
9537 ]
9637 if let tests {
977 let counts = tests.counts
987 parts.append(
997 "\(counts.totalText): \(groupingDigits(counts.passed)) passed, "
1007 + "\(groupingDigits(counts.failed)) failed, \(groupingDigits(counts.skipped)) skipped"
1017 )
1027 if case .results = tests {
1034 parts.append(#"<a href="\#(TestsPage.sitePath)">Test results</a>"#)
1044 }
1057 }
10637 if let commit {
10713 parts.append("commit \(escapingHTML(commit))")
10813 }
10937 return #"<p class="totals">"# + parts.joined(separator: " · ") + "</p>"
11037 }
111
112 /// Shows the controls, sorts modules and the files inside each by the clicked column
113 /// (a second click reverses it), and filters files by path, opening the modules
114 /// that still have matches. Without scripts the modules still fold out by hand.
115 private static let sortAndFilterScript = """
116 (() => {
117 const list = document.querySelector(".modules");
118 const modules = [...list.querySelectorAll("details.module")];
119 const buttons = [...document.querySelectorAll("button[data-sort]")];
120 const filter = document.getElementById("filter");
121 document.querySelectorAll("[data-needs-script]").forEach(element => element.hidden = false);
122 let key = "name";
123 let ascending = true;
124 const value = row => key === "name" ? row.dataset.name.toLowerCase() : parseFloat(row.dataset[key]);
125 const order = (a, b) => {
126 const [x, y] = [value(a), value(b)];
127 return (x < y ? -1 : x > y ? 1 : 0) * (ascending ? 1 : -1);
128 };
129 const sort = () => {
130 for (const module of modules.sort(order)) {
131 module.append(...[...module.querySelectorAll("a.file")].sort(order));
132 list.append(module);
133 }
134 for (const button of buttons) {
135 button.dataset.direction = button.dataset.sort === key ? (ascending ? "ascending" : "descending") : "";
136 }
137 };
138 for (const button of buttons) {
139 button.addEventListener("click", () => {
140 ascending = button.dataset.sort === key ? !ascending : button.dataset.first === "ascending";
141 key = button.dataset.sort;
142 sort();
143 });
144 }
145 filter.addEventListener("input", () => {
146 const query = filter.value.trim().toLowerCase();
147 for (const module of modules) {
148 let hasMatch = false;
149 for (const file of module.querySelectorAll("a.file")) {
150 const path = (module.dataset.name + "/" + file.dataset.name).toLowerCase();
151 file.hidden = query !== "" && !path.includes(query);
152 hasMatch = hasMatch || !file.hidden;
153 }
154 module.hidden = !hasMatch;
155 module.open = query !== "" && hasMatch;
156 }
157 });
158 sort();
159 })();
160 """
161
162 /// A `<details>` per module, so its files fold out without any script.
16369 private func moduleMarkup(_ module: ModuleTotals) -> String {
164111 let files = module.files.map { file in
165111 let name = String(file.relativePath.dropFirst(module.name.count + 1))
166111 let fileChange = comparison?.change(ofFile: file.relativePath, now: file.lines)
167111 return
168111 #"<a class="row file" href="\#(escapingHTML(SourcePage.sitePath(for: file.relativePath)))""#
169111 + "\(Self.sortKeys(name: name, lines: file.lines))>"
170111 + "\(cells(name: name, lines: file.lines, change: fileChange, branches: file.branches, conditions: file.conditions))</a>"
171111 }
17269 let moduleChange = comparison?.change(ofModule: module.name, now: module.lines)
17369 return """
17469 <details class="module"\(Self.sortKeys(name: module.name, lines: module.lines))>
17569 <summary class="row">\(cells(name: module.name, lines: module.lines, change: moduleChange, branches: module.branches, conditions: module.conditions))</summary>
17669 \(files.joined(separator: "\n"))
17769 </details>
17869 """
17969 }
180
181 /// The values the index's sort script orders rows by, unformatted, so it compares
182 /// numbers rather than the text shown.
183180 private static func sortKeys(name: String, lines: LineSummary) -> String {
184180 #" data-name="\#(escapingHTML(name))""#
185180 + #" data-percent="\#(String(format: "%.2f", lines.percent))""#
186180 + #" data-missed="\#(lines.count - lines.covered)" data-lines="\#(lines.count)""#
187180 }
188
18933 private static func changeSpan(_ change: LineChange) -> String {
19033 #"<span class="change \#(change.styleName)">\#(change.text)</span>"#
19133 }
192
193 private func cells(
194 name: String, lines: LineSummary, change: LineChange?, branches: CoverageCount?,
195 conditions: CoverageCount?
196180 ) -> String {
197180 let tier = lines.tier.rawValue
198180 let changeCell = change.map(Self.changeSpan) ?? ""
199180 let branchCell = hasBranches ? Self.countCell(branches, className: "branches") : ""
200180 let conditionCell = hasConditions ? Self.countCell(conditions, className: "conditions") : ""
201180 return #"<span class="name">\#(escapingHTML(name))</span>"#
202180 + #"<span class="bar"><span class="fill \#(tier)" style="width: \#(lines.percentText)"></span></span>"#
203180 + #"<span class="percent \#(tier)">\#(lines.percentText)</span>"# + changeCell
204180 + #"<span class="missed">\#(groupingDigits(lines.count - lines.covered))</span>"#
205180 + #"<span class="lines">\#(groupingDigits(lines.count))</span>"#
206180 + branchCell + conditionCell
207180 }
208
209 /// The share in its tier colour and the counts it comes from; a dash where this
210 /// file or module has no data while others do.
21112 private static func countCell(_ count: CoverageCount?, className: String) -> String {
21212 guard let count else { return #"<span class="\#(className)">–</span>"# }
21311 return #"<span class="\#(className)"><span class="percent \#(count.tier.rawValue)">"#
21411 + "\(count.percentText)</span> \(groupingDigits(count.covered))/"
21511 + "\(groupingDigits(count.total))</span>"
21612 }
217}