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.
2829 public init(title: String, runs: [HistoryRun]) throws {
2929 guard !runs.isEmpty else { throw HistoryPageError.noRuns }
3028 self.title = title
3146 self.newestFirst = runs.sorted {
3246 ($0.totals.date, $1.folder) > ($1.totals.date, $0.folder)
3346 }
3428 }
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
4228 public var html: String {
4328 let latest = newestFirst[0]
4428 let header = SiteHeader(
4528 title: title, currentTab: .history, hasTestsPage: latest.totals.hasTestsPage == true,
4628 rootPath: String(Self.reportLink(latest).dropLast(IndexPage.sitePath.count)),
4728 run: ReportHeader(historyPath: "../index.html"))
4857 let regions = newestFirst.contains { $0.totals.regions != nil }
4959 let branches = newestFirst.contains { $0.totals.branches != nil }
5059 let conditions = newestFirst.contains { $0.totals.conditions != nil }
5128 let columns = Columns(regions: regions, branches: branches, conditions: conditions)
5259 let trend = CoverageTrend(runs: newestFirst.map(\.totals))
5328 return
5428 """
5528 <!doctype html>
5628 <html lang="en">
5728 <head>
5828 <meta charset="utf-8">
5928 <meta name="viewport" content="width=device-width, initial-scale=1">
6028 <title>History · \(escapingHTML(title))</title>
6128 <link rel="stylesheet" href="\(Self.stylesheetPath)">
6228 </head>
6328 <body class="history-page">
6428 <header class="page-header">
6528 \(header.html)
6628 </header>
6728 <main>
6828 <section class="history-chart" aria-label="Coverage trend">
6928 \(trend.chart)
7028 \(Self.legendMarkup(columns))
7128 </section>
7228 <table class="history">
7328 <thead><tr><th>Commit</th><th>Message</th><th>Lines</th>\(regions ? #"<th class="regions">Regions</th>"# : "")\(branches ? "<th>Branches</th>" : "")\(conditions ? "<th>Conditions</th>" : "")<th class="date">Date</th></tr></thead>
7428 <tbody>
7528 \(rows(columns))
7628 </tbody>
7728 </table>
7828 </main>
7928 <script>\(Self.localDateScript)</script>
8028 <script>\(ChartTooltip.script)</script>
8128 </body>
8228 </html>
8328
8428 """
8528 }
86
87 /// Keys each recorded series, and the no-data marker, to its colour in the chart. A
88 /// series' key is a checkbox, which the stylesheet reads to hide it without a script.
8928 private static func legendMarkup(_ columns: Columns) -> String {
9028 var series = [("lines", "Lines")]
9128 if columns.regions { series.append(("regions", "Regions")) }
9228 if columns.branches { series.append(("branches", "Branches")) }
9328 if columns.conditions { series.append(("conditions", "Conditions")) }
9434 let toggles = series.map { name, label in
9534 #"<li><label><input type="checkbox" data-toggle="\#(name)" checked>"#
9634 + #"<span class="swatch trend-\#(name)-swatch"></span>\#(label)</label></li>"#
9734 }
9828 let noData = #"<li><span class="swatch no-data-swatch"></span>Grey marks: no data</li>"#
9928 return #"<ul class="trend-legend">\#(toggles.joined())\#(noData)</ul>"#
10028 }
101
102 /// Relative to the page, with the folder's name encoded so any name stays one link.
10387 private static func reportLink(_ run: HistoryRun) -> String {
10487 let folder = run.folder.addingPercentEncoding(withAllowedCharacters: folderCharacters)
10587 return "\(folder ?? run.folder)/\(IndexPage.sitePath)"
10687 }
107
108 /// Unreserved characters only: `#`, `?`, `%` and spaces in a name must not end the path.
109 private static let folderCharacters = CharacterSet(
110 charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
111
112 /// The optional metrics any run recorded, which the table and legend show.
113 private struct Columns {
114 let regions: Bool
115 let branches: Bool
116 let conditions: Bool
117 }
118
11928 private func rows(_ columns: Columns) -> String {
12059 newestFirst.enumerated().map { index, run in
12159 let previous = newestFirst.dropFirst(index + 1).first { $0.totals.unavailable == nil }
12259 return rowMarkup(run, previous: previous?.totals, columns: columns)
12359 }.joined(separator: "\n")
12428 }
125
12659 private func rowMarkup(_ run: HistoryRun, previous: RunTotals?, columns: Columns) -> String {
12759 let totals = run.totals
12859 let subject = escapingHTML(totals.subject ?? "")
12959 var cells =
13059 #"<td class="commit"><a href="\#(escapingHTML(Self.reportLink(run)))">"#
13159 + "\(escapingHTML(run.folder))</a></td>"
13259 + #"<td class="subject">\#(subject)</td>"#
13359 if let reason = totals.unavailable {
1343 cells +=
1353 #"<td class="lines"><span class="unavailable">\#(escapingHTML(reason))</span></td>"#
13656 } else {
13756 cells +=
13856 #"<td class="lines">\#(Self.metricMarkup(totals.lines, before: previous?.lines))</td>"#
13956 }
14059 if columns.regions {
1416 cells +=
1426 #"<td class="regions">\#(Self.metricMarkup(totals.unavailable == nil ? totals.regions : nil, before: previous?.regions))</td>"#
1436 }
14459 if columns.branches {
1451 cells +=
1461 #"<td class="branches">\#(Self.metricMarkup(totals.unavailable == nil ? totals.branches : nil, before: previous?.branches))</td>"#
1471 }
14859 if columns.conditions {
1491 cells +=
1501 #"<td class="conditions">\#(Self.metricMarkup(totals.unavailable == nil ? totals.conditions : nil, before: previous?.conditions))</td>"#
1511 }
15259 return "<tr>\(cells)" + #"<td class="date">\#(Self.dateMarkup(totals.date))</td></tr>"#
15359 }
154
155 private static func metricMarkup(_ count: RunTotals.Lines?, before: RunTotals.Lines?) -> String
15664 {
15764 guard let count else { return "—" }
15863 let summary = LineSummary(count: count.total, covered: count.covered)
15963 var text =
16063 #"<span class="percent \#(summary.tier.rawValue)">\#(summary.percentText)</span>"#
16163 if let before {
16230 let previous = LineSummary(count: before.total, covered: before.covered)
16330 let change = CoverageChange.points(summary.percent - previous.percent)
16430 text += #" <span class="change \#(change.styleName)">\#(change.text)</span>"#
16530 }
16663 return text
16764 }
168
169 /// Rewrites each date in the viewer's time zone, which the build can't know. Without
170 /// scripts the dates stay in UTC and say so.
171 private static let localDateScript = """
172 (() => {
173 const two = number => String(number).padStart(2, "0");
174 for (const time of document.querySelectorAll("time[datetime]")) {
175 const date = new Date(time.dateTime);
176 time.textContent = `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} `
177 + `${two(date.getHours())}:${two(date.getMinutes())}`;
178 }
179 })();
180 """
181
182 /// The machine-readable date with a short text beside it, `2026-12-01 08:30 UTC`.
18359 private static func dateMarkup(_ date: Date) -> String {
18459 let iso = date.formatted(.iso8601)
18559 let shown = iso.prefix(shownDateLength).replacingOccurrences(of: "T", with: " ")
18659 return #"<time datetime="\#(iso)">\#(shown) UTC</time>"#
18759 }
188
189 /// `2026-12-01T08:30`: up to the minute.
190 private static let shownDateLength = 16
191}