1import Foundation
2
3/// One published run: the folder it sits in (the commit's short hash) and its numbers.
4public struct HistoryRun: Sendable, Equatable {
5 public let folder: String
6 public let totals: RunTotals
7
842 public init(folder: String, totals: RunTotals) {
942 self.folder = folder
1042 self.totals = totals
1142 }
12}
13
14public enum HistoryPageError: Error, Equatable {
15 case noRuns
16}
17
18/// Coverage history above the published runs (DESIGN.md D7), newest first.
19public struct HistoryPage: Sendable {
20 /// The stylesheet's name; it sits beside the page.
21 public static let stylesheetPath = SiteStylesheet.fileName
22
23 /// - Parameters:
24 /// - title: the project's name, shown as given.
25 /// - runs: in any order; each run's report is `<folder>/index.html` beside the page.
26 /// - Throws: `HistoryPageError.noRuns` when `runs` is empty, since there is nothing
27 /// to display.
2830 public init(title: String, runs: [HistoryRun]) throws {
2930 guard !runs.isEmpty else { throw HistoryPageError.noRuns }
3029 self.title = title
3149 self.newestFirst = runs.sorted {
3249 ($0.totals.date, $1.folder) > ($1.totals.date, $0.folder)
3349 }
3429 }
35
36 private let title: String
37 private let newestFirst: [HistoryRun]
38
39 /// The newest run, including unavailable runs, for the site root redirect.
400 public var newestRunFolder: String { newestFirst[0].folder }
41
4229 public var html: String {
4329 let latest = newestFirst[0]
4429 let header = SiteHeader(
4529 title: title, currentTab: .history, hasTestsPage: latest.totals.hasTestsPage == true,
4629 rootPath: String(Self.reportLink(latest).dropLast(IndexPage.sitePath.count)),
4729 run: ReportHeader(historyPath: "../index.html"))
4860 let regions = newestFirst.contains { $0.totals.regions != nil }
4962 let branches = newestFirst.contains { $0.totals.branches != nil }
5062 let conditions = newestFirst.contains { $0.totals.conditions != nil }
5129 let columns = Columns(regions: regions, branches: branches, conditions: conditions)
5262 let trend = CoverageTrend(runs: newestFirst.map(\.totals))
5329 return
5429 """
5529 <!doctype html>
5629 <html lang="en">
5729 <head>
5829 <meta charset="utf-8">
5929 <meta name="viewport" content="width=device-width, initial-scale=1">
6029 <title>History · \(escapingHTML(title))</title>
6129 <link rel="stylesheet" href="\(Self.stylesheetPath)">
6229 </head>
6329 <body class="history-page">
6429 <header class="page-header">
6529 \(header.html)
6629 </header>
6729 <main>
6829 <section class="history-chart" aria-label="Coverage trend">
6929 \(trend.chart)
7029 \(Self.legendMarkup(columns))
7129 </section>
7229 <table class="history">
7329 <thead><tr><th>Commit</th><th>Message</th><th>Lines</th>\(regions ? #"<th class="regions">Regions</th>"# : "")\(branches ? #"<th class="branches">Branches</th>"# : "")\(conditions ? #"<th class="conditions">Conditions</th>"# : "")<th class="date">Date</th></tr></thead>
7429 <tbody>
7529 \(rows(columns))
7629 </tbody>
7729 </table>
7829 </main>
7929 <script>\(Self.localDateScript)</script>
8029 <script>\(ChartTooltip.script)</script>
8129 <script>\(SeriesRescaling.script)</script>
8229 </body>
8329 </html>
8429
8529 """
8629 }
87
88 /// Keys each recorded series, and the no-data marker, to its colour in the chart. A
89 /// series' key is a checkbox, which the stylesheet reads to hide it without a script.
9029 private static func legendMarkup(_ columns: Columns) -> String {
9129 var series = [("lines", "Lines")]
9229 if columns.regions { series.append(("regions", "Regions")) }
9329 if columns.branches { series.append(("branches", "Branches")) }
9429 if columns.conditions { series.append(("conditions", "Conditions")) }
9535 let toggles = series.map { name, label in
9635 #"<li><label><input type="checkbox" data-toggle="\#(name)" checked>"#
9735 + #"<span class="swatch trend-\#(name)-swatch"></span>\#(label)</label></li>"#
9835 }
9929 let noData = #"<li><span class="swatch no-data-swatch"></span>Grey marks: no data</li>"#
10029 return #"<ul class="trend-legend">\#(toggles.joined())\#(noData)</ul>"#
10129 }
102
103 /// Relative to the page, with the folder's name encoded so any name stays one link.
10491 private static func reportLink(_ run: HistoryRun) -> String {
10591 let folder = run.folder.addingPercentEncoding(withAllowedCharacters: folderCharacters)
10691 return "\(folder ?? run.folder)/\(IndexPage.sitePath)"
10791 }
108
109 /// Unreserved characters only: `#`, `?`, `%` and spaces in a name must not end the path.
110 private static let folderCharacters = CharacterSet(
111 charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
112
113 /// The optional metrics any run recorded, which the table and legend show.
114 private struct Columns {
115 let regions: Bool
116 let branches: Bool
117 let conditions: Bool
118 }
119
12029 private func rows(_ columns: Columns) -> String {
12162 newestFirst.enumerated().map { index, run in
12262 let previous = newestFirst.dropFirst(index + 1).first { $0.totals.unavailable == nil }
12362 return rowMarkup(run, previous: previous?.totals, columns: columns)
12462 }.joined(separator: "\n")
12529 }
126
12762 private func rowMarkup(_ run: HistoryRun, previous: RunTotals?, columns: Columns) -> String {
12862 let totals = run.totals
12962 let subject = escapingHTML(totals.subject ?? "")
13062 var cells =
13162 #"<td class="commit"><a href="\#(escapingHTML(Self.reportLink(run)))">"#
13262 + "\(escapingHTML(run.folder))</a></td>"
13362 + #"<td class="subject">\#(subject)</td>"#
13462 if let reason = totals.unavailable {
1353 cells +=
1363 #"<td class="lines"><span class="unavailable">\#(escapingHTML(reason))</span></td>"#
13759 } else {
13859 cells +=
13959 #"<td class="lines">\#(Self.metricMarkup(totals.lines, before: previous?.lines))</td>"#
14059 }
14162 if columns.regions {
1426 cells +=
1436 #"<td class="regions">\#(Self.metricMarkup(totals.unavailable == nil ? totals.regions : nil, before: previous?.regions))</td>"#
1446 }
14562 if columns.branches {
1461 cells +=
1471 #"<td class="branches">\#(Self.metricMarkup(totals.unavailable == nil ? totals.branches : nil, before: previous?.branches))</td>"#
1481 }
14962 if columns.conditions {
1501 cells +=
1511 #"<td class="conditions">\#(Self.metricMarkup(totals.unavailable == nil ? totals.conditions : nil, before: previous?.conditions))</td>"#
1521 }
15362 return "<tr>\(cells)" + #"<td class="date">\#(Self.dateMarkup(totals.date))</td></tr>"#
15462 }
155
156 private static func metricMarkup(_ count: RunTotals.Lines?, before: RunTotals.Lines?) -> String
15767 {
15867 guard let count else { return "—" }
15966 let summary = LineSummary(count: count.total, covered: count.covered)
16066 var text =
16166 #"<span class="percent \#(summary.tier.rawValue)">\#(summary.percentText)</span>"#
16266 if let before {
16332 let previous = LineSummary(count: before.total, covered: before.covered)
16432 let change = CoverageChange.points(summary.percent - previous.percent)
16532 text += #" <span class="change \#(change.styleName)">\#(change.text)</span>"#
16632 }
16766 return text
16867 }
169
170 /// Rewrites each date in the viewer's time zone, which the build can't know. Without
171 /// scripts the dates stay in UTC and say so.
172 private static let localDateScript = """
173 (() => {
174 const two = number => String(number).padStart(2, "0");
175 for (const time of document.querySelectorAll("time[datetime]")) {
176 const date = new Date(time.dateTime);
177 time.textContent = `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} `
178 + `${two(date.getHours())}:${two(date.getMinutes())}`;
179 }
180 })();
181 """
182
183 /// The machine-readable date with a short text beside it, `2026-12-01 08:30 UTC`.
18462 private static func dateMarkup(_ date: Date) -> String {
18562 let iso = date.formatted(.iso8601)
18662 let shown = iso.prefix(shownDateLength).replacingOccurrences(of: "T", with: " ")
18762 return #"<time datetime="\#(iso)">\#(shown) UTC</time>"#
18862 }
189
190 /// `2026-12-01T08:30`: up to the minute.
191 private static let shownDateLength = 16
192}