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: room for a commit label beside
11 /// a neighbouring one, even next to the outermost label, which turns inward.
12 private static let widestRunSpacing = 80.0
13 private static let chartHeight = 160.0
14 /// The strip under the chart's scale that holds the no-data markers, so none reads
15 /// as a value.
16 private static let noDataStripHeight = 16.0
17 private static let pointRadius = 2
18 private static let unavailableRadius = 3
19 /// The least share of coverage the vertical axis spans, so a 0.1-point change isn't
20 /// drawn as a cliff.
21 private static let minimumSpan = 0.035
22 /// As many commit labels as fit side by side under a full-width chart, and on a
23 /// phone.
24 private static let maximumCommitLabels = 8
25 private static let maximumNarrowCommitLabels = 4
26
27 private struct Metric: Sendable {
28 let name: String
29 let title: String
30 let count: @Sendable (RunTotals) -> RunTotals.Lines?
31
32405 static let lines = Metric(name: "lines", title: "Lines", count: { $0.lines })
33370 static let branches = Metric(name: "branches", title: "Branches", count: { $0.branches })
34 static let conditions = Metric(
35370 name: "conditions", title: "Conditions", count: { $0.conditions })
36 }
37
38 /// One recorded value and where it is drawn.
39 private struct Point {
40 let run: RunTotals
41 let count: RunTotals.Lines
42 let x: Double
43 let y: Double
44
45372 var coordinates: String {
46372 "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))"
47372 }
48 }
49
50 /// Where runs and fractions covered fall inside an SVG of a given size.
51 private struct Plot {
52 let width: Double
53 /// The height the axis spans, with its padding.
54 let height: Double
55 /// Extra room under the axis.
5672 var stripHeight = 0.0
57 let runCount: Int
58 let axis: ClosedRange<Double>
59
6072 var drawingHeight: Double { height + stripHeight }
61
62519 func x(ofRun index: Int) -> Double {
63519 let plotWidth = width - CoverageTrend.padding * 2
64519 return CoverageTrend.padding
65519 + (runCount == 1
66519 ? plotWidth / 2 : Double(index) / Double(runCount - 1) * plotWidth)
67519 }
68
69607 func y(of fraction: Double) -> Double {
70607 CoverageTrend.padding
71607 + (axis.upperBound - fraction) / (axis.upperBound - axis.lowerBound)
72607 * (height - CoverageTrend.padding * 2)
73607 }
74 }
75
76 /// Accepts runs in any order; points are ordered by date, then commit.
77102 public init(runs: [RunTotals]) {
78352 self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") }
79102 }
80
81 /// A compact line-only chart; empty when no runs were supplied.
8262 public var sparkline: String {
8362 guard !runs.isEmpty else { return "" }
8428 let plot = plot(width: Self.sparklineWidth, height: Self.sparklineHeight)
8528 let segments = segments(of: .lines, in: plot)
8628 let loneDots = segments.filter { $0.count == 1 }.joined().map { point in
8717 #"<circle class="trend-lines" cx="\#(Self.number(point.x))" cy="\#(Self.number(point.y))" r="\#(Self.pointRadius)"/>"#
8817 }
8928 let missing = unavailableRuns.map { index, run in
900 #"<circle class="trend-unavailable" cx="\#(Self.number(plot.x(ofRun: index)))" cy="\#(Self.number(plot.height - Self.padding))" r="\#(Self.unavailableRadius)"><title>\#(escapingHTML(Self.label(of: run))) · No coverage data</title></circle>"#
910 }
9228 return svg(
9328 plot, attributes: #"role="img""#,
9428 contents: Self.polylines(segments, of: .lines) + loneDots.joined() + missing.joined())
9562 }
96
97 /// Lines and any recorded branch/condition series, with percentage and commit axes,
98 /// a marker on every recorded value and no-data markers; empty when no runs were
99 /// supplied. Runs sit a fixed distance apart until they fill the width available.
10045 public var chart: String {
10145 guard !runs.isEmpty else { return "" }
10244 var plot = plot(width: chartWidth, height: Self.chartHeight)
10344 plot.stripHeight = Self.noDataStripHeight
104132 let series = [Metric.lines, .branches, .conditions].map { metric in
105132 let segments = segments(of: metric, in: plot)
106373 let markers = segments.joined().map { Self.marker($0, of: metric) }
107132 return Self.polylines(segments, of: metric) + markers.joined()
108132 }
10944 let missing = unavailableRuns.map { index, run in
11011 Self.dot(
11111 x: plot.x(ofRun: index), y: plot.height + plot.stripHeight / 2,
11211 style: "trend-unavailable",
11311 title: "\(Self.label(of: run)) · No coverage data")
11411 }
11544 let values = axisValues(in: plot)
11644 // Stretched only when the page is narrower than the runs need; strokes and dots
11744 // don't scale, so they keep their shape.
11844 let drawing = svg(
11944 plot, attributes: #"preserveAspectRatio="none" role="group""#,
12044 contents: series.joined() + missing.joined())
12144 return #"<div class="trend-plot">"#
12244 + #"<div class="trend-values">\#(Self.valueLabels(values, in: plot))</div>"#
12344 + #"<div class="trend-area">\#(Self.gridLines(values, in: plot))"#
12444 + #"<div class="trend-data" style="width: min(100%, \#(Self.number(naturalWidth))px)">"#
12544 + drawing
12644 + #"<div class="trend-commits">\#(commitLabels(in: plot))</div></div></div></div>"#
12745 }
128
129 /// The width at which runs sit `widestRunSpacing` apart; a lone run gets one space.
13088 private var naturalWidth: Double {
13188 Double(max(runs.count - 1, 1)) * Self.widestRunSpacing + Self.padding * 2
13288 }
133
13444 private var chartWidth: Double {
13544 min(naturalWidth, Self.widestChartWidth)
13644 }
137
13872 private var unavailableRuns: [(index: Int, run: RunTotals)] {
139416 runs.enumerated().filter { $0.element.unavailable != nil }.map { ($0.offset, $0.element) }
14072 }
141
142 /// Fractions covered that every series plots, widened to the minimum span and kept
143 /// inside 0...1.
144116 private var axis: ClosedRange<Double>? {
145116 var fractions: [Double] = []
146775 for run in runs where run.unavailable == nil {
1472325 for count in [run.lines, run.branches, run.conditions] {
1482325 guard let count, count.total > 0 else { continue }
149782 fractions.append(Self.fraction(count))
150782 }
151775 }
152116 guard let low = fractions.min(), let high = fractions.max() else { return nil }
15391 let extra = max(0, Self.minimumSpan - (high - low)) / 2
15491 let upper = min(1, high + extra)
15591 let lower = max(0, min(low - extra, upper - Self.minimumSpan))
15691 return lower...upper
157116 }
158
15972 private func plot(width: Double, height: Double) -> Plot {
16072 Plot(width: width, height: height, runCount: runs.count, axis: axis ?? 0...1)
16172 }
162
163 /// The metric's points, split wherever a run lacks it.
164160 private func segments(of metric: Metric, in plot: Plot) -> [[Point]] {
165160 var segments: [[Point]] = []
166160 var points: [Point] = []
1671178 for (index, run) in runs.enumerated() {
1681178 if run.unavailable == nil, let count = metric.count(run), count.total > 0 {
169403 points.append(
170403 Point(
171403 run: run, count: count, x: plot.x(ofRun: index),
172403 y: plot.y(of: Self.fraction(count))))
173775 } else if !points.isEmpty {
1747 segments.append(points)
1757 points = []
1767 }
1771178 }
178160 if !points.isEmpty { segments.append(points) }
179160 return segments
180160 }
181
182 /// A line through each segment, and a dashed bridge across each gap between two.
183160 private static func polylines(_ segments: [[Point]], of metric: Metric) -> String {
184160 let bridges = zip(segments, segments.dropFirst()).compactMap { earlier, later in
1855 earlier.last.flatMap { from in
1865 later.first.map { to in
1875 #"<polyline class="trend-\#(metric.name) trend-gap" points="\#(from.coordinates) \#(to.coordinates)"/>"#
1885 }
1895 }
1905 }
191160 let lines = segments.filter { $0.count > 1 }.map { segment in
192362 #"<polyline class="trend-\#(metric.name)" points="\#(segment.map(\.coordinates).joined(separator: " "))"/>"#
19328 }
194160 return bridges.joined() + lines.joined()
195160 }
196
197 /// A dot whose title names the run and the value, for pointers and screen readers.
198373 private static func marker(_ point: Point, of metric: Metric) -> String {
199373 let summary = LineSummary(count: point.count.total, covered: point.count.covered)
200373 let value =
201373 "\(metric.title) \(summary.percentText) "
202373 + "(\(groupingDigits(summary.covered)) of \(groupingDigits(summary.count)))"
203373 return dot(
204373 x: point.x, y: point.y, style: "trend-\(metric.name)",
205373 title: "\(label(of: point.run)) · \(value)")
206373 }
207
208 /// A zero-length path with round caps: unlike a circle, it stays round when the
209 /// chart is stretched.
210384 private static func dot(x: Double, y: Double, style: String, title: String) -> String {
211384 #"<path class="\#(style) trend-dot" d="M\#(number(x)),\#(number(y))h0">"#
212384 + "<title>\(escapingHTML(title))</title></path>"
213384 }
214
21572 private func svg(_ plot: Plot, attributes: String, contents: String) -> String {
21672 #"<svg class="coverage-trend" viewBox="0 0 \#(Self.number(plot.width)) \#(Self.number(plot.drawingHeight))" \#(attributes) aria-label="Coverage history"><title>Coverage history</title>\#(contents)</svg>"#
21772 }
218
219 /// The top, middle and bottom of the axis; none when nothing is plotted. The axis
220 /// fits the plotted values rather than starting at 0%, so readers need them.
22144 private func axisValues(in plot: Plot) -> [Double] {
22244 guard axis != nil else { return [] }
22334 let middle = (plot.axis.lowerBound + plot.axis.upperBound) / 2
22434 return [plot.axis.upperBound, middle, plot.axis.lowerBound]
22544 }
226
227 /// HTML across the whole chart, so the grid reaches the edge before the runs do.
22844 private static func gridLines(_ values: [Double], in plot: Plot) -> String {
229102 values.map { value in
230102 #"<span class="trend-grid" style="top: \#(number(plot.y(of: value)))px"></span>"#
231102 }.joined()
23244 }
233
234 /// HTML rather than SVG text, which would be squeezed with the chart on a phone.
23544 private static func valueLabels(_ values: [Double], in plot: Plot) -> String {
236102 values.map { value in
237102 #"<span class="trend-value" style="top: \#(number(plot.y(of: value)))px">"#
238102 + "\(percent(value))</span>"
239102 }.joined()
24044 }
241
242 /// Up to `picks` of the indices below `count`, evenly spaced and always including
243 /// the first and the last.
24488 private static func evenlySpaced(_ picks: Int, below count: Int) -> [Int] {
24588 let picks = min(picks, count)
24688 guard picks > 1 else { return Array(0..<picks) }
247164 return (0..<picks).map { pick in
248164 Int((Double(pick * (count - 1)) / Double(picks - 1)).rounded())
249164 }
25088 }
251
252 /// Commits under evenly spaced runs, each showing its message on hover.
25344 private func commitLabels(in plot: Plot) -> String {
25444 let labelled = Self.evenlySpaced(Self.maximumCommitLabels, below: runs.count)
25544 let kept = Self.evenlySpaced(Self.maximumNarrowCommitLabels, below: labelled.count)
256105 return labelled.enumerated().map { position, index in
257105 // The outermost labels turn inward so they stay inside the chart.
258105 let edge =
259105 runs.count == 1
260105 ? "" : index == 0 ? " first" : index == runs.count - 1 ? " last" : ""
261105 let minor = kept.contains(position) ? "" : " minor"
262105 let left = Self.number(plot.x(ofRun: index) / plot.width * 100)
263105 let message = runs[index].subject.flatMap { $0.isEmpty ? nil : $0 }
264105 let tooltip = message.map { #" title="\#(escapingHTML($0))""# } ?? ""
265105 return
266105 #"<span class="trend-commit\#(edge)\#(minor)" style="left: \#(left)%"\#(tooltip)>"#
267105 + "\(escapingHTML(Self.label(of: runs[index])))</span>"
268105 }.joined()
26944 }
270
271 /// The short commit, or the month and day for a run without one.
272489 private static func label(of run: RunTotals) -> String {
273489 if let commit = run.commit, !commit.isEmpty {
274479 return String(commit.prefix(PublishedLayout.shortCommitLength))
275479 }
27610 return String(
27710 run.date.formatted(.iso8601).dropFirst(yearPrefixLength).prefix(monthDayLength))
278489 }
279
280 /// The lengths of `2026-` and `12-01` in an ISO 8601 date.
281 private static let yearPrefixLength = 5
282 private static let monthDayLength = 5
283
2841185 private static func fraction(_ count: RunTotals.Lines) -> Double {
2851185 Double(count.covered) / Double(count.total)
2861185 }
287
288102 private static func percent(_ fraction: Double) -> String {
289102 String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100)
290102 }
291
2922043 private static func number(_ value: Double) -> String {
2932043 String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value)
2942043 }
295}