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.
2831 public init(title: String, runs: [HistoryRun]) throws {
2931 guard !runs.isEmpty else { throw HistoryPageError.noRuns }
3030 self.title = title
3152 self.newestFirst = runs.sorted {
3252 ($0.totals.date, $1.folder) > ($1.totals.date, $0.folder)
3352 }
3430 }
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
4230 public var html: String {
4330 let latest = newestFirst[0]
4430 let header = SiteHeader(
4530 title: title, currentTab: .history, hasTestsPage: latest.totals.hasTestsPage == true,
4630 rootPath: String(Self.reportLink(latest).dropLast(IndexPage.sitePath.count)),
4730 run: ReportHeader(historyPath: "../index.html"))
4863 let regions = newestFirst.contains { $0.totals.regions != nil }
4965 let branches = newestFirst.contains { $0.totals.branches != nil }
5065 let conditions = newestFirst.contains { $0.totals.conditions != nil }
5130 let columns = Columns(regions: regions, branches: branches, conditions: conditions)
5265 let trend = CoverageTrend(runs: newestFirst.map(\.totals))
5330 return
5430 """
5530 <!doctype html>
5630 <html lang="en">
5730 <head>
5830 <meta charset="utf-8">
5930 <meta name="viewport" content="width=device-width, initial-scale=1">
6030 <title>History · \(escapingHTML(title))</title>
6130 <link rel="stylesheet" href="\(Self.stylesheetPath)">
6230 </head>
6330 <body class="history-page">
6430 <header class="page-header">
6530 \(header.html)
6630 </header>
6730 <main>
6830 <section class="history-chart" aria-label="Coverage trend">
6930 \(trend.chart)
7030 \(Self.legendMarkup(columns))
7130 </section>
7230 <table class="history">
7330 <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>
7430 <tbody>
7530 \(rows(columns))
7630 </tbody>
7730 </table>
7830 </main>
7930 <script>\(Self.localDateScript)</script>
8030 <script>\(ChartTooltip.script)</script>
8130 <script>\(SeriesRescaling.script)</script>
8230 </body>
8330 </html>
8430
8530 """
8630 }
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.
9030 private static func legendMarkup(_ columns: Columns) -> String {
9130 var series = [("lines", "Lines")]
9230 if columns.regions { series.append(("regions", "Regions")) }
9330 if columns.branches { series.append(("branches", "Branches")) }
9430 if columns.conditions { series.append(("conditions", "Conditions")) }
9536 let toggles = series.map { name, label in
9636 #"<li><label><input type="checkbox" data-toggle="\#(name)" checked>"#
9736 + #"<span class="swatch trend-\#(name)-swatch"></span>\#(label)</label></li>"#
9836 }
9930 let noData = #"<li><span class="swatch no-data-swatch"></span>Grey marks: no data</li>"#
10030 return #"<ul class="trend-legend">\#(toggles.joined())\#(noData)</ul>"#
10130 }
102
103 /// Relative to the page, with the folder's name encoded so any name stays one link.
10495 private static func reportLink(_ run: HistoryRun) -> String {
10595 let folder = run.folder.addingPercentEncoding(withAllowedCharacters: folderCharacters)
10695 return "\(folder ?? run.folder)/\(IndexPage.sitePath)"
10795 }
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
12030 private func rows(_ columns: Columns) -> String {
12165 newestFirst.enumerated().map { index, run in
12265 let previous = newestFirst.dropFirst(index + 1).first { $0.totals.unavailable == nil }
12365 return rowMarkup(run, previous: previous?.totals, columns: columns)
12465 }.joined(separator: "\n")
12530 }
126
12765 private func rowMarkup(_ run: HistoryRun, previous: RunTotals?, columns: Columns) -> String {
12865 let totals = run.totals
12965 let subject = escapingHTML(totals.subject ?? "")
13065 var cells =
13165 #"<td class="commit"><a href="\#(escapingHTML(Self.reportLink(run)))">"#
13265 + "\(escapingHTML(run.folder))</a></td>"
13365 + #"<td class="subject">\#(subject)</td>"#
13465 if let reason = totals.unavailable {
1353 cells +=
1363 #"<td class="lines"><span class="unavailable">\#(escapingHTML(reason))</span></td>"#
13762 } else {
13862 cells +=
13962 #"<td class="lines">\#(Self.metricMarkup(totals.lines, before: previous?.lines))</td>"#
14062 }
14165 if columns.regions {
1426 cells +=
1436 #"<td class="regions">\#(Self.metricMarkup(totals.unavailable == nil ? totals.regions : nil, before: previous?.regions))</td>"#
1446 }
14565 if columns.branches {
1461 cells +=
1471 #"<td class="branches">\#(Self.metricMarkup(totals.unavailable == nil ? totals.branches : nil, before: previous?.branches))</td>"#
1481 }
14965 if columns.conditions {
1501 cells +=
1511 #"<td class="conditions">\#(Self.metricMarkup(totals.unavailable == nil ? totals.conditions : nil, before: previous?.conditions))</td>"#
1521 }
15365 return "<tr>\(cells)" + #"<td class="date">\#(Self.dateMarkup(totals.date))</td></tr>"#
15465 }
155
156 private static func metricMarkup(_ count: RunTotals.Lines?, before: RunTotals.Lines?) -> String
15770 {
15870 guard let count else { return "—" }
15969 let summary = LineSummary(count: count.total, covered: count.covered)
16069 var text =
16169 #"<span class="percent \#(summary.tier.rawValue)">\#(summary.percentText)</span>"#
16269 if let before {
16334 let previous = LineSummary(count: before.total, covered: before.covered)
16434 let change = CoverageChange.points(summary.percent - previous.percent)
16534 text += #" <span class="change \#(change.styleName)">\#(change.text)</span>"#
16634 }
16769 return text
16870 }
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`.
18465 private static func dateMarkup(_ date: Date) -> String {
18565 let iso = date.formatted(.iso8601)
18665 let shown = iso.prefix(shownDateLength).replacingOccurrences(of: "T", with: " ")
18765 return #"<time datetime="\#(iso)">\#(shown) UTC</time>"#
18865 }
189
190 /// `2026-12-01T08:30`: up to the minute.
191 private static let shownDateLength = 16
192}