1import Foundation
2
3/// Coverage over time, including gaps for missing metrics and runs without data.
4public struct CoverageTrend: Sendable {
5 private let runs: [RunTotals]
6 private static let padding = 4.0
7 private static let sparklineWidth = 120.0
8 private static let sparklineHeight = 32.0
9 private static let widestChartWidth = 1000.0
10 /// The distance between runs until the chart is full: close, but with each run's dots
11 /// easy to point at.
12 private static let widestRunSpacing = 80.0
13 private static let chartHeight = 160.0
14 private static let pointRadius = 2
15 private static let unavailableRadius = 3
16 /// The least share of coverage the vertical axis spans, so a 0.1-point change isn't
17 /// drawn as a cliff.
18 private static let minimumSpan = 0.035
19
20 private struct Metric: Sendable {
21 let name: String
22 let title: String
23 let count: @Sendable (RunTotals) -> RunTotals.Lines?
24
25518 static let lines = Metric(name: "lines", title: "Lines", count: { $0.lines })
26382 static let regions = Metric(name: "regions", title: "Regions", count: { $0.regions })
27384 static let branches = Metric(name: "branches", title: "Branches", count: { $0.branches })
28 static let conditions = Metric(
29382 name: "conditions", title: "Conditions", count: { $0.conditions })
30 }
31
32 /// One recorded value and where it is drawn.
33 private struct Point {
34 let run: RunTotals
35 let count: RunTotals.Lines
36 let x: Double
37 let y: Double
38
39195 var coordinates: String {
40195 "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))"
41195 }
42 }
43
44 /// Where a run without data is marked.
45 private struct NoDataDot {
46 let run: RunTotals
47 let x: Double
48 let y: Double
49
505 var coordinates: String {
515 "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))"
525 }
53 }
54
55 /// Where runs and fractions covered fall inside an SVG of a given size.
56 private struct Plot {
57 let width: Double
58 let height: Double
59 let runCount: Int
60 let axis: ClosedRange<Double>
61 /// False when no run has a value, so the axis is only a placeholder.
62 let plotsValues: Bool
63
64256 func x(ofRun index: Int) -> Double {
65256 let plotWidth = width - CoverageTrend.padding * 2
66256 return CoverageTrend.padding
67256 + (runCount == 1
68256 ? plotWidth / 2 : Double(index) / Double(runCount - 1) * plotWidth)
69256 }
70
71526 func y(of fraction: Double) -> Double {
72526 CoverageTrend.padding
73526 + (axis.upperBound - fraction) / (axis.upperBound - axis.lowerBound)
74526 * (height - CoverageTrend.padding * 2)
75526 }
76 }
77
78 /// Accepts runs in any order; points are ordered by date, then commit.
79114 public init(runs: [RunTotals]) {
80175 self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") }
81114 }
82
83 /// A compact line-only chart; empty when no runs were supplied.
8464 public var sparkline: String {
8564 guard !runs.isEmpty else { return "" }
8630 let plot = plot(
8730 width: Self.sparklineWidth, height: Self.sparklineHeight, fitting: [.lines])
8830 let segments = segments(of: .lines, in: plot)
8930 let loneDots = segments.filter { $0.count == 1 }.joined().map { point in
9017 #"<circle class="trend-lines" cx="\#(Self.number(point.x))" cy="\#(Self.number(point.y))" r="\#(Self.pointRadius)"/>"#
9117 }
9230 let noData = noDataDots(of: .lines, in: plot)
9330 let missing = noData.map { dot in
941 #"<circle class="trend-unavailable" cx="\#(Self.number(dot.x))" cy="\#(Self.number(dot.y))" r="\#(Self.unavailableRadius)"><title>\#(escapingHTML(Self.label(of: dot.run))) · No coverage data</title></circle>"#
951 }
9630 return svg(
9730 plot, attributes: #"role="img""#,
9830 contents: Self.polylines(segments, through: noData, of: .lines) + loneDots.joined()
9930 + missing.joined())
10064 }
101
102 /// Lines and any recorded region, branch and condition series, with a percentage axis, a
103 /// marker on every recorded value and no-data markers; empty when no runs were
104 /// supplied. Runs sit a fixed distance apart until they fill the width available.
10555 public var chart: String {
10655 guard !runs.isEmpty else { return "" }
10754 let metrics = [Metric.lines, .regions, .branches, .conditions]
10854 let plot = plot(width: chartWidth, height: Self.chartHeight, fitting: metrics)
109216 let series = metrics.map { seriesMarkup($0, in: plot) }
11054 let unmeasured = unmeasuredDots(among: metrics, in: plot).map(Self.marker)
11154 let values = axisValues(in: plot)
11254 // Stretched only when the page is narrower than the runs need; strokes and dots
11354 // don't scale, so they keep their shape.
11454 let drawing = svg(
11554 plot, attributes: #"preserveAspectRatio="none" role="group""#,
11654 contents: series.joined() + unmeasured.joined())
11754 return #"<div class="trend-plot">"#
11854 + #"<div class="trend-values">\#(Self.valueLabels(values, in: plot))</div>"#
11954 + #"<div class="trend-area">\#(Self.gridLines(values, in: plot))"#
12054 + #"<div class="trend-data" style="width: min(100%, \#(Self.number(naturalWidth))px)">"#
12154 + drawing + "</div></div></div>"
12255 }
123
124 /// The metric's lines and dots, grouped so the legend can hide them together; empty
125 /// when it was never measured.
126216 private func seriesMarkup(_ metric: Metric, in plot: Plot) -> String {
127216 let segments = segments(of: metric, in: plot)
128216 guard !segments.isEmpty else { return "" }
12958 let noData = noDataDots(of: metric, in: plot)
13058 let contents =
13158 Self.polylines(segments, through: noData, of: metric)
132203 + segments.joined().map { Self.marker($0, of: metric) }.joined()
13358 + noData.map(Self.marker).joined()
13458 return #"<g data-series="\#(metric.name)">\#(contents)</g>"#
135216 }
136
13718 private static func marker(_ noData: NoDataDot) -> String {
13818 dot(
13918 x: noData.x, y: noData.y, style: "trend-unavailable",
14018 title: title(of: noData.run, showing: "No coverage data"))
14118 }
142
143 /// The width at which runs sit `widestRunSpacing` apart; a lone run gets one space.
144108 private var naturalWidth: Double {
145108 Double(max(runs.count - 1, 1)) * Self.widestRunSpacing + Self.padding * 2
146108 }
147
14854 private var chartWidth: Double {
14954 min(naturalWidth, Self.widestChartWidth)
15054 }
151
152212 private var unavailableRuns: [(index: Int, run: RunTotals)] {
153699 runs.enumerated().filter { $0.element.unavailable != nil }.map { ($0.offset, $0.element) }
154212 }
155
156 /// The metric's value at its last measurement before a run; nil if it had none.
15772 private func fraction(of metric: Metric, before index: Int) -> Double? {
15872 runs[..<index].reversed().lazy.compactMap { Self.recorded(metric, in: $0) }.first
15972 .map(Self.fraction)
16072 }
161
1621807 private static func recorded(_ metric: Metric, in run: RunTotals) -> RunTotals.Lines? {
1631807 guard run.unavailable == nil, let count = metric.count(run), count.total > 0 else {
1641273 return nil
1651273 }
166534 return count
1671807 }
168
169 /// The runs without data that none of the metrics was measured before.
170124 private func unmeasuredRuns(among metrics: [Metric]) -> [(index: Int, run: RunTotals)] {
171124 unavailableRuns.filter { index, _ in
17259 metrics.allSatisfy { fraction(of: $0, before: index) == nil }
17329 }
174124 }
175
176 /// A run without data keeps the metric where it was last measured.
17788 private func noDataDots(of metric: Metric, in plot: Plot) -> [NoDataDot] {
17888 unavailableRuns.compactMap { index, run in
17913 fraction(of: metric, before: index).map { prior in
18011 NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: prior))
18111 }
18213 }
18388 }
184
185 /// Runs without data and with nothing measured before them sit at zero.
18654 private func unmeasuredDots(among metrics: [Metric], in plot: Plot) -> [NoDataDot] {
18754 unmeasuredRuns(among: metrics).map { index, run in
1888 NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: 0))
1898 }
19054 }
191
192 /// Fractions covered that the metrics plot, widened to the minimum span and kept
193 /// inside 0...1; nil when they plot nothing.
19484 private func axis(fitting metrics: [Metric]) -> ClosedRange<Double>? {
19584 var fractions: [Double] = []
196248 for run in runs {
197872 for metric in metrics {
198872 guard let count = Self.recorded(metric, in: run) else { continue }
199237 fractions.append(Self.fraction(count))
200248 }
201248 }
20284 if !fractions.isEmpty, !unmeasuredRuns(among: metrics).isEmpty { fractions.append(0) }
20384 guard let low = fractions.min(), let high = fractions.max() else { return nil }
20470 let extra = max(0, Self.minimumSpan - (high - low)) / 2
20570 let upper = min(1, high + extra)
20670 let lower = max(0, min(low - extra, upper - Self.minimumSpan))
20770 return lower...upper
20884 }
209
21084 private func plot(width: Double, height: Double, fitting metrics: [Metric]) -> Plot {
21184 let axis = axis(fitting: metrics)
21284 return Plot(
21384 width: width, height: height, runCount: runs.count, axis: axis ?? 0...1,
21484 plotsValues: axis != nil)
21584 }
216
217 /// The metric's points, split wherever a run lacks it.
218246 private func segments(of metric: Metric, in plot: Plot) -> [[Point]] {
219246 var segments: [[Point]] = []
220246 var points: [Point] = []
221872 for (index, run) in runs.enumerated() {
222872 if let count = Self.recorded(metric, in: run) {
223237 points.append(
224237 Point(
225237 run: run, count: count, x: plot.x(ofRun: index),
226237 y: plot.y(of: Self.fraction(count))))
227635 } else if !points.isEmpty {
22811 segments.append(points)
22911 points = []
23011 }
231872 }
232246 if !points.isEmpty { segments.append(points) }
233246 return segments
234246 }
235
236 /// A line through each segment, and a dashed bridge across each gap between two,
237 /// passing through the gap's no-data dots.
238 private static func polylines(
239 _ segments: [[Point]], through noData: [NoDataDot], of metric: Metric
24088 ) -> String {
24188 let bridges = zip(segments, segments.dropFirst()).compactMap { earlier, later in
2426 earlier.last.flatMap { from in
2436 later.first.map { to in
2446 let between = noData.filter { $0.x > from.x && $0.x < to.x }
2456 let points = [from.coordinates] + between.map(\.coordinates) + [to.coordinates]
2466 return
2476 #"<polyline class="trend-\#(metric.name) trend-gap" points="\#(points.joined(separator: " "))"/>"#
2486 }
2496 }
2506 }
25189 let lines = segments.filter { $0.count > 1 }.map { segment in
252183 #"<polyline class="trend-\#(metric.name)" points="\#(segment.map(\.coordinates).joined(separator: " "))"/>"#
25335 }
25488 return bridges.joined() + lines.joined()
25588 }
256
257 /// A dot whose title names the run and the value, for pointers and screen readers.
258203 private static func marker(_ point: Point, of metric: Metric) -> String {
259203 let summary = LineSummary(count: point.count.total, covered: point.count.covered)
260203 let value =
261203 "\(metric.title) \(summary.percentText) "
262203 + "(\(groupingDigits(summary.covered)) of \(groupingDigits(summary.count)))"
263203 return dot(
264203 x: point.x, y: point.y, style: "trend-\(metric.name)",
265203 title: title(of: point.run, showing: value))
266203 }
267
268 /// The run and what its dot shows, with the commit message on a line of its own.
269221 private static func title(of run: RunTotals, showing value: String) -> String {
270221 let message = run.subject.flatMap { $0.isEmpty ? nil : "\n\($0)" } ?? ""
271221 return "\(label(of: run)) · \(value)\(message)"
272221 }
273
274 /// A zero-length path with round caps: unlike a circle, it stays round when the
275 /// chart is stretched.
276221 private static func dot(x: Double, y: Double, style: String, title: String) -> String {
277221 #"<path class="\#(style) trend-dot" d="M\#(number(x)),\#(number(y))h0">"#
278221 + "<title>\(escapingHTML(title))</title></path>"
279221 }
280
28184 private func svg(_ plot: Plot, attributes: String, contents: String) -> String {
28284 #"<svg class="coverage-trend" viewBox="0 0 \#(Self.number(plot.width)) \#(Self.number(plot.height))" \#(attributes) aria-label="Coverage history"><title>Coverage history</title>\#(contents)</svg>"#
28384 }
284
285 /// The top, middle and bottom of the axis; none when nothing is plotted. The axis
286 /// fits the plotted values rather than starting at 0%, so readers need them.
28754 private func axisValues(in plot: Plot) -> [Double] {
28854 guard plot.plotsValues else { return [] }
28945 let middle = (plot.axis.lowerBound + plot.axis.upperBound) / 2
29045 return [plot.axis.upperBound, middle, plot.axis.lowerBound]
29154 }
292
293 /// HTML across the whole chart, so the grid reaches the edge before the runs do.
29454 private static func gridLines(_ values: [Double], in plot: Plot) -> String {
295135 values.map { value in
296135 #"<span class="trend-grid" style="top: \#(number(plot.y(of: value)))px"></span>"#
297135 }.joined()
29854 }
299
300 /// HTML rather than SVG text, which would be squeezed with the chart on a phone.
30154 private static func valueLabels(_ values: [Double], in plot: Plot) -> String {
302135 values.map { value in
303135 #"<span class="trend-value" style="top: \#(number(plot.y(of: value)))px">"#
304135 + "\(percent(value))</span>"
305135 }.joined()
30654 }
307
308 /// The short commit, or the month and day for a run without one.
309222 private static func label(of run: RunTotals) -> String {
310222 if let commit = run.commit, !commit.isEmpty {
311215 return String(commit.prefix(PublishedLayout.shortCommitLength))
312215 }
3137 return String(
3147 run.date.formatted(.iso8601).dropFirst(yearPrefixLength).prefix(monthDayLength))
315222 }
316
317 /// The lengths of `2026-` and `12-01` in an ISO 8601 date.
318 private static let yearPrefixLength = 5
319 private static let monthDayLength = 5
320
321504 private static func fraction(_ count: RunTotals.Lines) -> Double {
322504 Double(count.covered) / Double(count.total)
323504 }
324
325135 private static func percent(_ fraction: Double) -> String {
326135 String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100)
327135 }
328
3291370 private static func number(_ value: Double) -> String {
3301370 String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value)
3311370 }
332}