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
835 public init(folder: String, totals: RunTotals) {
935 self.folder = folder
1035 self.totals = totals
1135 }
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.
2821 public init(title: String, runs: [HistoryRun]) throws {
2921 guard !runs.isEmpty else { throw HistoryPageError.noRuns }
3020 self.title = title
3135 self.newestFirst = runs.sorted {
3235 ($0.totals.date, $1.folder) > ($1.totals.date, $0.folder)
3335 }
3420 }
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
4220 public var html: String {
4320 let latest = newestFirst[0]
4420 let header = SiteHeader(
4520 title: title, currentTab: .history, hasTestsPage: latest.totals.hasTestsPage == true,
4620 rootPath: String(Self.reportLink(latest).dropLast(IndexPage.sitePath.count)),
4720 run: ReportHeader(historyPath: "../index.html"))
4843 let branches = newestFirst.contains { $0.totals.branches != nil }
4943 let conditions = newestFirst.contains { $0.totals.conditions != nil }
5043 let trend = CoverageTrend(runs: newestFirst.map(\.totals))
5120 return
5220 """
5320 <!doctype html>
5420 <html lang="en">
5520 <head>
5620 <meta charset="utf-8">
5720 <meta name="viewport" content="width=device-width, initial-scale=1">
5820 <title>History · \(escapingHTML(title))</title>
5920 <link rel="stylesheet" href="\(Self.stylesheetPath)">
6020 </head>
6120 <body class="history-page">
6220 <header class="page-header">
6320 \(header.html)
6420 </header>
6520 <main>
6620 <section class="history-chart" aria-label="Coverage trend">
6720 \(trend.chart)
6820 \(Self.legendMarkup(branches: branches, conditions: conditions))
6920 </section>
7020 <table class="history">
7120 <thead><tr><th>Commit</th><th>Message</th><th>Lines</th>\(branches ? "<th>Branches</th>" : "")\(conditions ? "<th>Conditions</th>" : "")<th class="date">Date</th></tr></thead>
7220 <tbody>
7320 \(rows(branches: branches, conditions: conditions))
7420 </tbody>
7520 </table>
7620 </main>
7720 <script>\(Self.localDateScript)</script>
7820 </body>
7920 </html>
8020
8120 """
8220 }
83
84 /// Keys each recorded series, and the no-data marker, to its colour in the chart.
8520 private static func legendMarkup(branches: Bool, conditions: Bool) -> String {
8620 var keys = [("trend-lines-swatch", "Lines")]
8720 if branches { keys.append(("trend-branches-swatch", "Branches")) }
8820 if conditions { keys.append(("trend-conditions-swatch", "Conditions")) }
8920 keys.append(("no-data-swatch", "Grey marks: no data"))
9042 let items = keys.map { swatch, name in
9142 #"<li><span class="swatch \#(swatch)"></span>\#(name)</li>"#
9242 }
9320 return #"<ul class="trend-legend">\#(items.joined())</ul>"#
9420 }
95
96 /// Relative to the page, with the folder's name encoded so any name stays one link.
9763 private static func reportLink(_ run: HistoryRun) -> String {
9863 let folder = run.folder.addingPercentEncoding(withAllowedCharacters: folderCharacters)
9963 return "\(folder ?? run.folder)/\(IndexPage.sitePath)"
10063 }
101
102 /// Unreserved characters only: `#`, `?`, `%` and spaces in a name must not end the path.
103 private static let folderCharacters = CharacterSet(
104 charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
105
10620 private func rows(branches: Bool, conditions: Bool) -> String {
10743 newestFirst.enumerated().map { index, run in
10843 let previous = newestFirst.dropFirst(index + 1).first { $0.totals.unavailable == nil }
10943 return rowMarkup(
11043 run, previous: previous?.totals, branches: branches, conditions: conditions)
11143 }.joined(separator: "\n")
11220 }
113
114 private func rowMarkup(
115 _ run: HistoryRun, previous: RunTotals?, branches: Bool, conditions: Bool
11643 ) -> String {
11743 let totals = run.totals
11843 let subject = escapingHTML(totals.subject ?? "")
11943 var cells =
12043 #"<td class="commit"><a href="\#(escapingHTML(Self.reportLink(run)))">"#
12143 + "\(escapingHTML(run.folder))</a></td>"
12243 + #"<td class="subject">\#(subject)</td>"#
12343 if let reason = totals.unavailable {
1243 cells +=
1253 #"<td class="lines"><span class="unavailable">\#(escapingHTML(reason))</span></td>"#
12640 } else {
12740 cells +=
12840 #"<td class="lines">\#(Self.metricMarkup(totals.lines, before: previous?.lines))</td>"#
12940 }
13043 if branches {
1311 cells +=
1321 #"<td class="branches">\#(Self.metricMarkup(totals.unavailable == nil ? totals.branches : nil, before: previous?.branches))</td>"#
1331 }
13443 if conditions {
1351 cells +=
1361 #"<td class="conditions">\#(Self.metricMarkup(totals.unavailable == nil ? totals.conditions : nil, before: previous?.conditions))</td>"#
1371 }
13843 return "<tr>\(cells)" + #"<td class="date">\#(Self.dateMarkup(totals.date))</td></tr>"#
13943 }
140
141 private static func metricMarkup(_ count: RunTotals.Lines?, before: RunTotals.Lines?) -> String
14242 {
14342 guard let count else { return "—" }
14442 let summary = LineSummary(count: count.total, covered: count.covered)
14542 var text =
14642 #"<span class="percent \#(summary.tier.rawValue)">\#(summary.percentText)</span>"#
14742 if let before {
14821 let previous = LineSummary(count: before.total, covered: before.covered)
14921 let change = CoverageChange.points(summary.percent - previous.percent)
15021 text += #" <span class="change \#(change.styleName)">\#(change.text)</span>"#
15121 }
15242 return text
15342 }
154
155 /// Rewrites each date in the viewer's time zone, which the build can't know. Without
156 /// scripts the dates stay in UTC and say so.
157 private static let localDateScript = """
158 (() => {
159 const two = number => String(number).padStart(2, "0");
160 for (const time of document.querySelectorAll("time[datetime]")) {
161 const date = new Date(time.dateTime);
162 time.textContent = `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} `
163 + `${two(date.getHours())}:${two(date.getMinutes())}`;
164 }
165 })();
166 """
167
168 /// The machine-readable date with a short text beside it, `2026-12-01 08:30 UTC`.
16943 private static func dateMarkup(_ date: Date) -> String {
17043 let iso = date.formatted(.iso8601)
17143 let shown = iso.prefix(shownDateLength).replacingOccurrences(of: "T", with: " ")
17243 return #"<time datetime="\#(iso)">\#(shown) UTC</time>"#
17343 }
174
175 /// `2026-12-01T08:30`: up to the minute.
176 private static let shownDateLength = 16
177}