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
25789 static let lines = Metric(name: "lines", title: "Lines", count: { $0.lines })
26639 static let regions = Metric(name: "regions", title: "Regions", count: { $0.regions })
27637 static let branches = Metric(name: "branches", title: "Branches", count: { $0.branches })
28 static let conditions = Metric(
29615 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
39212 var coordinates: String {
40212 "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))"
41212 }
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 var axis: ClosedRange<Double>
61 /// False when no run has a value, so the axis is only a placeholder.
62 let plotsValues: Bool
63
64281 func x(ofRun index: Int) -> Double {
65281 let plotWidth = width - CoverageTrend.padding * 2
66281 return CoverageTrend.padding
67281 + (runCount == 1
68281 ? plotWidth / 2 : Double(index) / Double(runCount - 1) * plotWidth)
69281 }
70
71581 func y(of fraction: Double) -> Double {
72581 CoverageTrend.padding
73581 + (axis.upperBound - fraction) / (axis.upperBound - axis.lowerBound)
74581 * (height - CoverageTrend.padding * 2)
75581 }
76 }
77
78 /// Accepts runs in any order; points are ordered by date, then commit.
79143 public init(runs: [RunTotals]) {
80183 self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") }
81143 }
82
83 /// A compact line-only chart; empty when no runs were supplied.
8486 public var sparkline: String {
8586 guard !runs.isEmpty else { return "" }
8631 return sparkline(of: .lines)
8786 }
88
89 /// A compact region-only chart; empty when no run recorded regions.
9031 public var regionSparkline: String {
9131 guard !fractions(of: [.regions]).isEmpty else { return "" }
926 return sparkline(of: .regions)
9331 }
94
9537 private func sparkline(of metric: Metric) -> String {
9637 let plot = plot(
9737 width: Self.sparklineWidth, height: Self.sparklineHeight, fitting: [metric])
9837 let segments = segments(of: metric, in: plot)
9937 let loneDots = segments.filter { $0.count == 1 }.joined().map { point in
10023 #"<circle class="trend-\#(metric.name)" cx="\#(Self.number(point.x))" cy="\#(Self.number(point.y))" r="\#(Self.pointRadius)"/>"#
10123 }
10237 let noData = noDataDots(of: metric, in: plot)
10337 let missing = noData.map { dot in
1041 #"<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>"#
1051 }
10637 return svg(
10737 plot, attributes: #"role="img""#,
10837 contents: Self.polylines(segments, through: noData, of: metric) + loneDots.joined()
10937 + missing.joined())
11037 }
111
112 /// Lines and any recorded region, branch and condition series, with a percentage axis, a
113 /// marker on every recorded value and no-data markers; empty when no runs were
114 /// supplied. Runs sit a fixed distance apart until they fill the width available.
11560 public var chart: String {
11660 guard !runs.isEmpty else { return "" }
11759 let metrics = [Metric.lines, .regions, .branches, .conditions]
11859 let plot = plot(width: chartWidth, height: Self.chartHeight, fitting: metrics)
119236 let series = metrics.map { seriesMarkup($0, in: plot) }
12059 let unmeasured = unmeasuredDots(among: metrics, in: plot).map(Self.marker)
12159 let values = axisValues(in: plot)
12259 // Stretched only when the page is narrower than the runs need; strokes and dots
12359 // don't scale, so they keep their shape.
12459 let drawing = svg(
12559 plot, attributes: #"preserveAspectRatio="none" role="group""#,
12659 contents: series.joined() + unmeasured.joined())
12759 return #"<div class="trend-plot">"#
12859 + #"<div class="trend-values">\#(Self.valueLabels(values, in: plot))</div>"#
12959 + #"<div class="trend-area">\#(Self.gridLines(values, in: plot))"#
13059 + #"<div class="trend-data" style="width: min(100%, \#(Self.number(naturalWidth))px)">"#
13159 + drawing + "</div></div></div>" + scalesMarkup(of: metrics, from: plot)
13260 }
133
134 /// The metric's lines and dots, grouped so the legend can hide them together; empty
135 /// when it was never measured.
136236 private func seriesMarkup(_ metric: Metric, in plot: Plot) -> String {
137236 let segments = segments(of: metric, in: plot)
138236 guard !segments.isEmpty else { return "" }
13966 let noData = noDataDots(of: metric, in: plot)
14066 let contents =
14166 Self.polylines(segments, through: noData, of: metric)
142219 + segments.joined().map { Self.marker($0, of: metric) }.joined()
14366 + noData.map(Self.marker).joined()
14466 return #"<g data-series="\#(metric.name)">\#(contents)</g>"#
145236 }
146
14719 private static func marker(_ noData: NoDataDot) -> String {
14819 dot(
14919 x: noData.x, y: noData.y, style: "trend-unavailable",
15019 title: title(of: noData.run, showing: "No coverage data"))
15119 }
152
153 /// The width at which runs sit `widestRunSpacing` apart; a lone run gets one space.
154118 private var naturalWidth: Double {
155118 Double(max(runs.count - 1, 1)) * Self.widestRunSpacing + Self.padding * 2
156118 }
157
15859 private var chartWidth: Double {
15959 min(naturalWidth, Self.widestChartWidth)
16059 }
161
162257 private var unavailableRuns: [(index: Int, run: RunTotals)] {
163777 runs.enumerated().filter { $0.element.unavailable != nil }.map { ($0.offset, $0.element) }
164257 }
165
166 /// The metric's value at its last measurement before a run; nil if it had none.
16787 private func fraction(of metric: Metric, before index: Int) -> Double? {
16887 runs[..<index].reversed().lazy.compactMap { Self.recorded(metric, in: $0) }.first
16987 .map(Self.fraction)
17087 }
171
1722909 private static func recorded(_ metric: Metric, in run: RunTotals) -> RunTotals.Lines? {
1732909 guard run.unavailable == nil, let count = metric.count(run), count.total > 0 else {
1741999 return nil
1751999 }
176910 return count
1772909 }
178
179 /// The runs without data that none of the metrics was measured before.
180154 private func unmeasuredRuns(among metrics: [Metric]) -> [(index: Int, run: RunTotals)] {
181154 unavailableRuns.filter { index, _ in
18272 metrics.allSatisfy { fraction(of: $0, before: index) == nil }
18333 }
184154 }
185
186 /// A run without data keeps the metric where it was last measured.
187103 private func noDataDots(of metric: Metric, in plot: Plot) -> [NoDataDot] {
188103 unavailableRuns.compactMap { index, run in
18915 fraction(of: metric, before: index).map { prior in
19011 NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: prior))
19111 }
19215 }
193103 }
194
195 /// Runs without data and with nothing measured before them sit at zero.
19659 private func unmeasuredDots(among metrics: [Metric], in plot: Plot) -> [NoDataDot] {
19759 unmeasuredRuns(among: metrics).map { index, run in
1989 NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: 0))
1999 }
20059 }
201
202 /// Fractions covered that the metrics plot, widened to the minimum span and kept
203 /// inside 0...1; nil when they plot nothing.
20496 private func axis(fitting metrics: [Metric]) -> ClosedRange<Double>? {
20596 var fractions = fractions(of: metrics)
20696 if !fractions.isEmpty, !unmeasuredRuns(among: metrics).isEmpty { fractions.append(0) }
20796 return Self.axis(spanning: fractions)
20896 }
209
210414 private func fractions(of metrics: [Metric]) -> [Double] {
2111229 runs.flatMap { run in
2121920 metrics.compactMap { Self.recorded($0, in: run).map(Self.fraction) }
2131229 }
214414 }
215
216147 private static func axis(spanning fractions: [Double]) -> ClosedRange<Double>? {
217147 guard let low = fractions.min(), let high = fractions.max() else { return nil }
218133 let extra = max(0, minimumSpan - (high - low)) / 2
219133 let upper = min(1, high + extra)
220133 let lower = max(0, min(low - extra, upper - minimumSpan))
221133 return lower...upper
222147 }
223
22496 private func plot(width: Double, height: Double, fitting metrics: [Metric]) -> Plot {
22596 let axis = axis(fitting: metrics)
22696 return Plot(
22796 width: width, height: height, runCount: runs.count, axis: axis ?? 0...1,
22896 plotsValues: axis != nil)
22996 }
230
231 /// The metric's points, split wherever a run lacks it.
232273 private func segments(of metric: Metric, in plot: Plot) -> [[Point]] {
233273 var segments: [[Point]] = []
234273 var points: [Point] = []
235924 for (index, run) in runs.enumerated() {
236924 if let count = Self.recorded(metric, in: run) {
237261 points.append(
238261 Point(
239261 run: run, count: count, x: plot.x(ofRun: index),
240261 y: plot.y(of: Self.fraction(count))))
241663 } else if !points.isEmpty {
24211 segments.append(points)
24311 points = []
24411 }
245924 }
246273 if !points.isEmpty { segments.append(points) }
247273 return segments
248273 }
249
250 /// A line through each segment, and a dashed bridge across each gap between two,
251 /// passing through the gap's no-data dots.
252 private static func polylines(
253 _ segments: [[Point]], through noData: [NoDataDot], of metric: Metric
254103 ) -> String {
255103 let bridges = zip(segments, segments.dropFirst()).compactMap { earlier, later in
2566 earlier.last.flatMap { from in
2576 later.first.map { to in
2586 let between = noData.filter { $0.x > from.x && $0.x < to.x }
2596 let points = [from.coordinates] + between.map(\.coordinates) + [to.coordinates]
2606 return
2616 #"<polyline class="trend-\#(metric.name) trend-gap" points="\#(points.joined(separator: " "))"/>"#
2626 }
2636 }
2646 }
265104 let lines = segments.filter { $0.count > 1 }.map { segment in
266200 #"<polyline class="trend-\#(metric.name)" points="\#(segment.map(\.coordinates).joined(separator: " "))"/>"#
26743 }
268103 return bridges.joined() + lines.joined()
269103 }
270
271 /// A dot whose title names the run and the value, for pointers and screen readers.
272219 private static func marker(_ point: Point, of metric: Metric) -> String {
273219 let summary = LineSummary(count: point.count.total, covered: point.count.covered)
274219 let value =
275219 "\(metric.title) \(summary.percentText) "
276219 + "(\(groupingDigits(summary.covered)) of \(groupingDigits(summary.count)))"
277219 return dot(
278219 x: point.x, y: point.y, style: "trend-\(metric.name)",
279219 title: title(of: point.run, showing: value))
280219 }
281
282 /// The run and what its dot shows, with the commit message on a line of its own.
283238 private static func title(of run: RunTotals, showing value: String) -> String {
284238 let message = run.subject.flatMap { $0.isEmpty ? nil : "\n\($0)" } ?? ""
285238 return "\(label(of: run)) · \(value)\(message)"
286238 }
287
288 /// A zero-length path with round caps: unlike a circle, it stays round when the
289 /// chart is stretched.
290238 private static func dot(x: Double, y: Double, style: String, title: String) -> String {
291238 #"<path class="\#(style) trend-dot" d="M\#(number(x)),\#(number(y))h0">"#
292238 + "<title>\(escapingHTML(title))</title></path>"
293238 }
294
29596 private func svg(_ plot: Plot, attributes: String, contents: String) -> String {
29696 #"<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>"#
29796 }
298
299 /// The top, middle and bottom of the axis; none when nothing is plotted. The axis
300 /// fits the plotted values rather than starting at 0%, so readers need them.
301110 private func axisValues(in plot: Plot) -> [Double] {
302110 guard plot.plotsValues else { return [] }
303101 let middle = (plot.axis.lowerBound + plot.axis.upperBound) / 2
304101 return [plot.axis.upperBound, middle, plot.axis.lowerBound]
305110 }
306
307 /// Every choice of the recorded series, keyed by their names in order, for the
308 /// legend's script; empty with fewer than two, when there is nothing to refit.
30959 private func scalesMarkup(of metrics: [Metric], from drawn: Plot) -> String {
310236 let recorded = metrics.filter { !fractions(of: [$0]).isEmpty }
31159 guard recorded.count > 1 else { return "" }
31213 // The dots at zero stay whichever series show, so every axis has to reach them.
31313 let zeroDots: [Double] = unmeasuredRuns(among: metrics).isEmpty ? [] : [0]
31429 let choices = recorded.reduce([[Metric]]([[]])) { choices, metric in
31551 choices + choices.map { $0 + [metric] }
31629 }
31764 let scales = choices.compactMap { shown -> (String, SeriesRescaling.Scale)? in
31864 guard !shown.isEmpty,
31964 let axis = Self.axis(spanning: fractions(of: shown) + zeroDots)
32064 else { return nil }
32151 var refitted = drawn
32251 refitted.axis = axis
32351 let scale = SeriesRescaling.Scale(
32451 transform: Self.transform(from: drawn, to: refitted),
325153 values: axisValues(in: refitted).map(Self.percent))
32676 return (shown.map(\.name).joined(separator: " "), scale)
32764 }
32813 return SeriesRescaling.markup(Dictionary(uniqueKeysWithValues: scales))
32959 }
330
331 /// Both axes are linear, so one vertical scale and shift moves every point.
33251 private static func transform(from drawn: Plot, to refitted: Plot) -> String {
33351 let stretch = span(of: drawn.axis) / span(of: refitted.axis)
33451 let shift =
33551 padding * (1 - stretch)
33651 + (refitted.axis.upperBound - drawn.axis.upperBound) / span(of: refitted.axis)
33751 * (drawn.height - padding * 2)
338102 let format = { (value: Double) in
339102 String(format: "%.4f", locale: Locale(identifier: "en_US_POSIX"), value)
340102 }
34151 return "matrix(1 0 0 \(format(stretch)) 0 \(format(shift)))"
34251 }
343
344153 private static func span(of axis: ClosedRange<Double>) -> Double {
345153 axis.upperBound - axis.lowerBound
346153 }
347
348 /// HTML across the whole chart, so the grid reaches the edge before the runs do.
34959 private static func gridLines(_ values: [Double], in plot: Plot) -> String {
350150 values.map { value in
351150 #"<span class="trend-grid" style="top: \#(number(plot.y(of: value)))px"></span>"#
352150 }.joined()
35359 }
354
355 /// HTML rather than SVG text, which would be squeezed with the chart on a phone.
35659 private static func valueLabels(_ values: [Double], in plot: Plot) -> String {
357150 values.map { value in
358150 #"<span class="trend-value" style="top: \#(number(plot.y(of: value)))px">"#
359150 + "\(percent(value))</span>"
360150 }.joined()
36159 }
362
363 /// The short commit, or the month and day for a run without one.
364239 private static func label(of run: RunTotals) -> String {
365239 if let commit = run.commit, !commit.isEmpty {
366232 return String(commit.prefix(PublishedLayout.shortCommitLength))
367232 }
3687 return String(
3697 run.date.formatted(.iso8601).dropFirst(yearPrefixLength).prefix(monthDayLength))
370239 }
371
372 /// The lengths of `2026-` and `12-01` in an ISO 8601 date.
373 private static let yearPrefixLength = 5
374 private static let monthDayLength = 5
375
376879 private static func fraction(_ count: RunTotals.Lines) -> Double {
377879 Double(count.covered) / Double(count.total)
378879 }
379
380303 private static func percent(_ fraction: Double) -> String {
381303 String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100)
382303 }
383
3841509 private static func number(_ value: Double) -> String {
3851509 String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value)
3861509 }
387}