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
25798 static let lines = Metric(name: "lines", title: "Lines", count: { $0.lines })
26648 static let regions = Metric(name: "regions", title: "Regions", count: { $0.regions })
27646 static let branches = Metric(name: "branches", title: "Branches", count: { $0.branches })
28 static let conditions = Metric(
29624 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
39215 var coordinates: String {
40215 "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))"
41215 }
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
64284 func x(ofRun index: Int) -> Double {
65284 let plotWidth = width - CoverageTrend.padding * 2
66284 return CoverageTrend.padding
67284 + (runCount == 1
68284 ? plotWidth / 2 : Double(index) / Double(runCount - 1) * plotWidth)
69284 }
70
71590 func y(of fraction: Double) -> Double {
72590 CoverageTrend.padding
73590 + (axis.upperBound - fraction) / (axis.upperBound - axis.lowerBound)
74590 * (height - CoverageTrend.padding * 2)
75590 }
76 }
77
78 /// Accepts runs in any order; points are ordered by date, then commit.
79142 public init(runs: [RunTotals]) {
80186 self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") }
81142 }
82
83 /// A compact line-only chart; empty when no runs were supplied.
8484 public var sparkline: String {
8584 guard !runs.isEmpty else { return "" }
8631 return sparkline(of: .lines)
8784 }
88
89 /// A compact region-only chart; empty when no run recorded regions.
9030 public var regionSparkline: String {
9130 guard !fractions(of: [.regions]).isEmpty else { return "" }
926 return sparkline(of: .regions)
9330 }
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.
11561 public var chart: String {
11661 guard !runs.isEmpty else { return "" }
11760 let metrics = [Metric.lines, .regions, .branches, .conditions]
11860 let plot = plot(width: chartWidth, height: Self.chartHeight, fitting: metrics)
119240 let series = metrics.map { seriesMarkup($0, in: plot) }
12060 let unmeasured = unmeasuredDots(among: metrics, in: plot).map(Self.marker)
12160 let values = axisValues(in: plot)
12260 // Stretched only when the page is narrower than the runs need; strokes and dots
12360 // don't scale, so they keep their shape.
12460 let drawing = svg(
12560 plot, attributes: #"preserveAspectRatio="none" role="group""#,
12660 contents: series.joined() + unmeasured.joined())
12760 return #"<div class="trend-plot">"#
12860 + #"<div class="trend-values">\#(Self.valueLabels(values, in: plot))</div>"#
12960 + #"<div class="trend-area">\#(Self.gridLines(values, in: plot))"#
13060 + #"<div class="trend-data" style="width: min(100%, \#(Self.number(naturalWidth))px)">"#
13160 + drawing + "</div></div></div>" + scalesMarkup(of: metrics, from: plot)
13261 }
133
134 /// The metric's lines and dots, grouped so the legend can hide them together; empty
135 /// when it was never measured.
136240 private func seriesMarkup(_ metric: Metric, in plot: Plot) -> String {
137240 let segments = segments(of: metric, in: plot)
138240 guard !segments.isEmpty else { return "" }
13967 let noData = noDataDots(of: metric, in: plot)
14067 let contents =
14167 Self.polylines(segments, through: noData, of: metric)
142222 + segments.joined().map { Self.marker($0, of: metric) }.joined()
14367 + noData.map(Self.marker).joined()
14467 return #"<g data-series="\#(metric.name)">\#(contents)</g>"#
145240 }
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.
154120 private var naturalWidth: Double {
155120 Double(max(runs.count - 1, 1)) * Self.widestRunSpacing + Self.padding * 2
156120 }
157
15860 private var chartWidth: Double {
15960 min(naturalWidth, Self.widestChartWidth)
16060 }
161
162260 private var unavailableRuns: [(index: Int, run: RunTotals)] {
163786 runs.enumerated().filter { $0.element.unavailable != nil }.map { ($0.offset, $0.element) }
164260 }
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
1722944 private static func recorded(_ metric: Metric, in run: RunTotals) -> RunTotals.Lines? {
1732944 guard run.unavailable == nil, let count = metric.count(run), count.total > 0 else {
1742026 return nil
1752026 }
176918 return count
1772944 }
178
179 /// The runs without data that none of the metrics was measured before.
180156 private func unmeasuredRuns(among metrics: [Metric]) -> [(index: Int, run: RunTotals)] {
181156 unavailableRuns.filter { index, _ in
18272 metrics.allSatisfy { fraction(of: $0, before: index) == nil }
18333 }
184156 }
185
186 /// A run without data keeps the metric where it was last measured.
187104 private func noDataDots(of metric: Metric, in plot: Plot) -> [NoDataDot] {
188104 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 }
193104 }
194
195 /// Runs without data and with nothing measured before them sit at zero.
19660 private func unmeasuredDots(among metrics: [Metric], in plot: Plot) -> [NoDataDot] {
19760 unmeasuredRuns(among: metrics).map { index, run in
1989 NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: 0))
1999 }
20060 }
201
202 /// Fractions covered that the metrics plot, widened to the minimum span and kept
203 /// inside 0...1; nil when they plot nothing.
20497 private func axis(fitting metrics: [Metric]) -> ClosedRange<Double>? {
20597 var fractions = fractions(of: metrics)
20697 if !fractions.isEmpty, !unmeasuredRuns(among: metrics).isEmpty { fractions.append(0) }
20797 return Self.axis(spanning: fractions)
20897 }
209
210418 private func fractions(of metrics: [Metric]) -> [Double] {
2111244 runs.flatMap { run in
2121944 metrics.compactMap { Self.recorded($0, in: run).map(Self.fraction) }
2131244 }
214418 }
215
216148 private static func axis(spanning fractions: [Double]) -> ClosedRange<Double>? {
217148 guard let low = fractions.min(), let high = fractions.max() else { return nil }
218134 let extra = max(0, minimumSpan - (high - low)) / 2
219134 let upper = min(1, high + extra)
220134 let lower = max(0, min(low - extra, upper - minimumSpan))
221134 return lower...upper
222148 }
223
22497 private func plot(width: Double, height: Double, fitting metrics: [Metric]) -> Plot {
22597 let axis = axis(fitting: metrics)
22697 return Plot(
22797 width: width, height: height, runCount: runs.count, axis: axis ?? 0...1,
22897 plotsValues: axis != nil)
22997 }
230
231 /// The metric's points, split wherever a run lacks it.
232277 private func segments(of metric: Metric, in plot: Plot) -> [[Point]] {
233277 var segments: [[Point]] = []
234277 var points: [Point] = []
235935 for (index, run) in runs.enumerated() {
236935 if let count = Self.recorded(metric, in: run) {
237264 points.append(
238264 Point(
239264 run: run, count: count, x: plot.x(ofRun: index),
240264 y: plot.y(of: Self.fraction(count))))
241671 } else if !points.isEmpty {
24211 segments.append(points)
24311 points = []
24411 }
245935 }
246277 if !points.isEmpty { segments.append(points) }
247277 return segments
248277 }
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
254104 ) -> String {
255104 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 }
265105 let lines = segments.filter { $0.count > 1 }.map { segment in
266203 #"<polyline class="trend-\#(metric.name)" points="\#(segment.map(\.coordinates).joined(separator: " "))"/>"#
26744 }
268104 return bridges.joined() + lines.joined()
269104 }
270
271 /// A dot whose title names the run and the value, for pointers and screen readers.
272222 private static func marker(_ point: Point, of metric: Metric) -> String {
273222 let summary = LineSummary(count: point.count.total, covered: point.count.covered)
274222 let value =
275222 "\(metric.title) \(summary.percentText) "
276222 + "(\(groupingDigits(summary.covered)) of \(groupingDigits(summary.count)))"
277222 return dot(
278222 x: point.x, y: point.y, style: "trend-\(metric.name)",
279222 title: title(of: point.run, showing: value))
280222 }
281
282 /// The run and what its dot shows, with the commit message on a line of its own.
283241 private static func title(of run: RunTotals, showing value: String) -> String {
284241 let message = run.subject.flatMap { $0.isEmpty ? nil : "\n\($0)" } ?? ""
285241 return "\(label(of: run)) · \(value)\(message)"
286241 }
287
288 /// A zero-length path with round caps: unlike a circle, it stays round when the
289 /// chart is stretched.
290241 private static func dot(x: Double, y: Double, style: String, title: String) -> String {
291241 #"<path class="\#(style) trend-dot" d="M\#(number(x)),\#(number(y))h0">"#
292241 + "<title>\(escapingHTML(title))</title></path>"
293241 }
294
29597 private func svg(_ plot: Plot, attributes: String, contents: String) -> String {
29697 #"<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>"#
29797 }
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.
301111 private func axisValues(in plot: Plot) -> [Double] {
302111 guard plot.plotsValues else { return [] }
303102 let middle = (plot.axis.lowerBound + plot.axis.upperBound) / 2
304102 return [plot.axis.upperBound, middle, plot.axis.lowerBound]
305111 }
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.
30960 private func scalesMarkup(of metrics: [Metric], from drawn: Plot) -> String {
310240 let recorded = metrics.filter { !fractions(of: [$0]).isEmpty }
31160 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))
32960 }
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.
34960 private static func gridLines(_ values: [Double], in plot: Plot) -> String {
350153 values.map { value in
351153 #"<span class="trend-grid" style="top: \#(number(plot.y(of: value)))px"></span>"#
352153 }.joined()
35360 }
354
355 /// HTML rather than SVG text, which would be squeezed with the chart on a phone.
35660 private static func valueLabels(_ values: [Double], in plot: Plot) -> String {
357153 values.map { value in
358153 #"<span class="trend-value" style="top: \#(number(plot.y(of: value)))px">"#
359153 + "\(percent(value))</span>"
360153 }.joined()
36160 }
362
363 /// The short commit, or the month and day for a run without one.
364242 private static func label(of run: RunTotals) -> String {
365242 if let commit = run.commit, !commit.isEmpty {
366235 return String(commit.prefix(PublishedLayout.shortCommitLength))
367235 }
3687 return String(
3697 run.date.formatted(.iso8601).dropFirst(yearPrefixLength).prefix(monthDayLength))
370242 }
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
376888 private static func fraction(_ count: RunTotals.Lines) -> Double {
377888 Double(count.covered) / Double(count.total)
378888 }
379
380306 private static func percent(_ fraction: Double) -> String {
381306 String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100)
382306 }
383
3841530 private static func number(_ value: Double) -> String {
3851530 String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value)
3861530 }
387}