| 1 | | import Foundation |
| 2 | | |
| 3 | | /// Coverage over time, including gaps for missing metrics and runs without data. |
| 4 | | public 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 | | |
| 25 | 518 | static let lines = Metric(name: "lines", title: "Lines", count: { $0.lines }) |
| 26 | 382 | static let regions = Metric(name: "regions", title: "Regions", count: { $0.regions }) |
| 27 | 384 | static let branches = Metric(name: "branches", title: "Branches", count: { $0.branches }) |
| 28 | | static let conditions = Metric( |
| 29 | 382 | 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 | | |
| 39 | 195 | var coordinates: String { |
| 40 | 195 | "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))" |
| 41 | 195 | } |
| 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 | | |
| 50 | 5 | var coordinates: String { |
| 51 | 5 | "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))" |
| 52 | 5 | } |
| 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 | | |
| 64 | 256 | func x(ofRun index: Int) -> Double { |
| 65 | 256 | let plotWidth = width - CoverageTrend.padding * 2 |
| 66 | 256 | return CoverageTrend.padding |
| 67 | 256 | + (runCount == 1 |
| 68 | 256 | ? plotWidth / 2 : Double(index) / Double(runCount - 1) * plotWidth) |
| 69 | 256 | } |
| 70 | | |
| 71 | 526 | func y(of fraction: Double) -> Double { |
| 72 | 526 | CoverageTrend.padding |
| 73 | 526 | + (axis.upperBound - fraction) / (axis.upperBound - axis.lowerBound) |
| 74 | 526 | * (height - CoverageTrend.padding * 2) |
| 75 | 526 | } |
| 76 | | } |
| 77 | | |
| 78 | | /// Accepts runs in any order; points are ordered by date, then commit. |
| 79 | 114 | public init(runs: [RunTotals]) { |
| 80 | 175 | self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") } |
| 81 | 114 | } |
| 82 | | |
| 83 | | /// A compact line-only chart; empty when no runs were supplied. |
| 84 | 64 | public var sparkline: String { |
| 85 | 64 | guard !runs.isEmpty else { return "" } |
| 86 | 30 | let plot = plot( |
| 87 | 30 | width: Self.sparklineWidth, height: Self.sparklineHeight, fitting: [.lines]) |
| 88 | 30 | let segments = segments(of: .lines, in: plot) |
| 89 | 30 | let loneDots = segments.filter { $0.count == 1 }.joined().map { point in |
| 90 | 17 | #"<circle class="trend-lines" cx="\#(Self.number(point.x))" cy="\#(Self.number(point.y))" r="\#(Self.pointRadius)"/>"# |
| 91 | 17 | } |
| 92 | 30 | let noData = noDataDots(of: .lines, in: plot) |
| 93 | 30 | let missing = noData.map { dot in |
| 94 | 1 | #"<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>"# |
| 95 | 1 | } |
| 96 | 30 | return svg( |
| 97 | 30 | plot, attributes: #"role="img""#, |
| 98 | 30 | contents: Self.polylines(segments, through: noData, of: .lines) + loneDots.joined() |
| 99 | 30 | + missing.joined()) |
| 100 | 64 | } |
| 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. |
| 105 | 55 | public var chart: String { |
| 106 | 55 | guard !runs.isEmpty else { return "" } |
| 107 | 54 | let metrics = [Metric.lines, .regions, .branches, .conditions] |
| 108 | 54 | let plot = plot(width: chartWidth, height: Self.chartHeight, fitting: metrics) |
| 109 | 216 | let series = metrics.map { seriesMarkup($0, in: plot) } |
| 110 | 54 | let unmeasured = unmeasuredDots(among: metrics, in: plot).map(Self.marker) |
| 111 | 54 | let values = axisValues(in: plot) |
| 112 | 54 | // Stretched only when the page is narrower than the runs need; strokes and dots |
| 113 | 54 | // don't scale, so they keep their shape. |
| 114 | 54 | let drawing = svg( |
| 115 | 54 | plot, attributes: #"preserveAspectRatio="none" role="group""#, |
| 116 | 54 | contents: series.joined() + unmeasured.joined()) |
| 117 | 54 | return #"<div class="trend-plot">"# |
| 118 | 54 | + #"<div class="trend-values">\#(Self.valueLabels(values, in: plot))</div>"# |
| 119 | 54 | + #"<div class="trend-area">\#(Self.gridLines(values, in: plot))"# |
| 120 | 54 | + #"<div class="trend-data" style="width: min(100%, \#(Self.number(naturalWidth))px)">"# |
| 121 | 54 | + drawing + "</div></div></div>" |
| 122 | 55 | } |
| 123 | | |
| 124 | | /// The metric's lines and dots, grouped so the legend can hide them together; empty |
| 125 | | /// when it was never measured. |
| 126 | 216 | private func seriesMarkup(_ metric: Metric, in plot: Plot) -> String { |
| 127 | 216 | let segments = segments(of: metric, in: plot) |
| 128 | 216 | guard !segments.isEmpty else { return "" } |
| 129 | 58 | let noData = noDataDots(of: metric, in: plot) |
| 130 | 58 | let contents = |
| 131 | 58 | Self.polylines(segments, through: noData, of: metric) |
| 132 | 203 | + segments.joined().map { Self.marker($0, of: metric) }.joined() |
| 133 | 58 | + noData.map(Self.marker).joined() |
| 134 | 58 | return #"<g data-series="\#(metric.name)">\#(contents)</g>"# |
| 135 | 216 | } |
| 136 | | |
| 137 | 18 | private static func marker(_ noData: NoDataDot) -> String { |
| 138 | 18 | dot( |
| 139 | 18 | x: noData.x, y: noData.y, style: "trend-unavailable", |
| 140 | 18 | title: title(of: noData.run, showing: "No coverage data")) |
| 141 | 18 | } |
| 142 | | |
| 143 | | /// The width at which runs sit `widestRunSpacing` apart; a lone run gets one space. |
| 144 | 108 | private var naturalWidth: Double { |
| 145 | 108 | Double(max(runs.count - 1, 1)) * Self.widestRunSpacing + Self.padding * 2 |
| 146 | 108 | } |
| 147 | | |
| 148 | 54 | private var chartWidth: Double { |
| 149 | 54 | min(naturalWidth, Self.widestChartWidth) |
| 150 | 54 | } |
| 151 | | |
| 152 | 212 | private var unavailableRuns: [(index: Int, run: RunTotals)] { |
| 153 | 699 | runs.enumerated().filter { $0.element.unavailable != nil }.map { ($0.offset, $0.element) } |
| 154 | 212 | } |
| 155 | | |
| 156 | | /// The metric's value at its last measurement before a run; nil if it had none. |
| 157 | 72 | private func fraction(of metric: Metric, before index: Int) -> Double? { |
| 158 | 72 | runs[..<index].reversed().lazy.compactMap { Self.recorded(metric, in: $0) }.first |
| 159 | 72 | .map(Self.fraction) |
| 160 | 72 | } |
| 161 | | |
| 162 | 1807 | private static func recorded(_ metric: Metric, in run: RunTotals) -> RunTotals.Lines? { |
| 163 | 1807 | guard run.unavailable == nil, let count = metric.count(run), count.total > 0 else { |
| 164 | 1273 | return nil |
| 165 | 1273 | } |
| 166 | 534 | return count |
| 167 | 1807 | } |
| 168 | | |
| 169 | | /// The runs without data that none of the metrics was measured before. |
| 170 | 124 | private func unmeasuredRuns(among metrics: [Metric]) -> [(index: Int, run: RunTotals)] { |
| 171 | 124 | unavailableRuns.filter { index, _ in |
| 172 | 59 | metrics.allSatisfy { fraction(of: $0, before: index) == nil } |
| 173 | 29 | } |
| 174 | 124 | } |
| 175 | | |
| 176 | | /// A run without data keeps the metric where it was last measured. |
| 177 | 88 | private func noDataDots(of metric: Metric, in plot: Plot) -> [NoDataDot] { |
| 178 | 88 | unavailableRuns.compactMap { index, run in |
| 179 | 13 | fraction(of: metric, before: index).map { prior in |
| 180 | 11 | NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: prior)) |
| 181 | 11 | } |
| 182 | 13 | } |
| 183 | 88 | } |
| 184 | | |
| 185 | | /// Runs without data and with nothing measured before them sit at zero. |
| 186 | 54 | private func unmeasuredDots(among metrics: [Metric], in plot: Plot) -> [NoDataDot] { |
| 187 | 54 | unmeasuredRuns(among: metrics).map { index, run in |
| 188 | 8 | NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: 0)) |
| 189 | 8 | } |
| 190 | 54 | } |
| 191 | | |
| 192 | | /// Fractions covered that the metrics plot, widened to the minimum span and kept |
| 193 | | /// inside 0...1; nil when they plot nothing. |
| 194 | 84 | private func axis(fitting metrics: [Metric]) -> ClosedRange<Double>? { |
| 195 | 84 | var fractions: [Double] = [] |
| 196 | 248 | for run in runs { |
| 197 | 872 | for metric in metrics { |
| 198 | 872 | guard let count = Self.recorded(metric, in: run) else { continue } |
| 199 | 237 | fractions.append(Self.fraction(count)) |
| 200 | 248 | } |
| 201 | 248 | } |
| 202 | 84 | if !fractions.isEmpty, !unmeasuredRuns(among: metrics).isEmpty { fractions.append(0) } |
| 203 | 84 | guard let low = fractions.min(), let high = fractions.max() else { return nil } |
| 204 | 70 | let extra = max(0, Self.minimumSpan - (high - low)) / 2 |
| 205 | 70 | let upper = min(1, high + extra) |
| 206 | 70 | let lower = max(0, min(low - extra, upper - Self.minimumSpan)) |
| 207 | 70 | return lower...upper |
| 208 | 84 | } |
| 209 | | |
| 210 | 84 | private func plot(width: Double, height: Double, fitting metrics: [Metric]) -> Plot { |
| 211 | 84 | let axis = axis(fitting: metrics) |
| 212 | 84 | return Plot( |
| 213 | 84 | width: width, height: height, runCount: runs.count, axis: axis ?? 0...1, |
| 214 | 84 | plotsValues: axis != nil) |
| 215 | 84 | } |
| 216 | | |
| 217 | | /// The metric's points, split wherever a run lacks it. |
| 218 | 246 | private func segments(of metric: Metric, in plot: Plot) -> [[Point]] { |
| 219 | 246 | var segments: [[Point]] = [] |
| 220 | 246 | var points: [Point] = [] |
| 221 | 872 | for (index, run) in runs.enumerated() { |
| 222 | 872 | if let count = Self.recorded(metric, in: run) { |
| 223 | 237 | points.append( |
| 224 | 237 | Point( |
| 225 | 237 | run: run, count: count, x: plot.x(ofRun: index), |
| 226 | 237 | y: plot.y(of: Self.fraction(count)))) |
| 227 | 635 | } else if !points.isEmpty { |
| 228 | 11 | segments.append(points) |
| 229 | 11 | points = [] |
| 230 | 11 | } |
| 231 | 872 | } |
| 232 | 246 | if !points.isEmpty { segments.append(points) } |
| 233 | 246 | return segments |
| 234 | 246 | } |
| 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 |
| 240 | 88 | ) -> String { |
| 241 | 88 | let bridges = zip(segments, segments.dropFirst()).compactMap { earlier, later in |
| 242 | 6 | earlier.last.flatMap { from in |
| 243 | 6 | later.first.map { to in |
| 244 | 6 | let between = noData.filter { $0.x > from.x && $0.x < to.x } |
| 245 | 6 | let points = [from.coordinates] + between.map(\.coordinates) + [to.coordinates] |
| 246 | 6 | return |
| 247 | 6 | #"<polyline class="trend-\#(metric.name) trend-gap" points="\#(points.joined(separator: " "))"/>"# |
| 248 | 6 | } |
| 249 | 6 | } |
| 250 | 6 | } |
| 251 | 89 | let lines = segments.filter { $0.count > 1 }.map { segment in |
| 252 | 183 | #"<polyline class="trend-\#(metric.name)" points="\#(segment.map(\.coordinates).joined(separator: " "))"/>"# |
| 253 | 35 | } |
| 254 | 88 | return bridges.joined() + lines.joined() |
| 255 | 88 | } |
| 256 | | |
| 257 | | /// A dot whose title names the run and the value, for pointers and screen readers. |
| 258 | 203 | private static func marker(_ point: Point, of metric: Metric) -> String { |
| 259 | 203 | let summary = LineSummary(count: point.count.total, covered: point.count.covered) |
| 260 | 203 | let value = |
| 261 | 203 | "\(metric.title) \(summary.percentText) " |
| 262 | 203 | + "(\(groupingDigits(summary.covered)) of \(groupingDigits(summary.count)))" |
| 263 | 203 | return dot( |
| 264 | 203 | x: point.x, y: point.y, style: "trend-\(metric.name)", |
| 265 | 203 | title: title(of: point.run, showing: value)) |
| 266 | 203 | } |
| 267 | | |
| 268 | | /// The run and what its dot shows, with the commit message on a line of its own. |
| 269 | 221 | private static func title(of run: RunTotals, showing value: String) -> String { |
| 270 | 221 | let message = run.subject.flatMap { $0.isEmpty ? nil : "\n\($0)" } ?? "" |
| 271 | 221 | return "\(label(of: run)) · \(value)\(message)" |
| 272 | 221 | } |
| 273 | | |
| 274 | | /// A zero-length path with round caps: unlike a circle, it stays round when the |
| 275 | | /// chart is stretched. |
| 276 | 221 | private static func dot(x: Double, y: Double, style: String, title: String) -> String { |
| 277 | 221 | #"<path class="\#(style) trend-dot" d="M\#(number(x)),\#(number(y))h0">"# |
| 278 | 221 | + "<title>\(escapingHTML(title))</title></path>" |
| 279 | 221 | } |
| 280 | | |
| 281 | 84 | private func svg(_ plot: Plot, attributes: String, contents: String) -> String { |
| 282 | 84 | #"<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>"# |
| 283 | 84 | } |
| 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. |
| 287 | 54 | private func axisValues(in plot: Plot) -> [Double] { |
| 288 | 54 | guard plot.plotsValues else { return [] } |
| 289 | 45 | let middle = (plot.axis.lowerBound + plot.axis.upperBound) / 2 |
| 290 | 45 | return [plot.axis.upperBound, middle, plot.axis.lowerBound] |
| 291 | 54 | } |
| 292 | | |
| 293 | | /// HTML across the whole chart, so the grid reaches the edge before the runs do. |
| 294 | 54 | private static func gridLines(_ values: [Double], in plot: Plot) -> String { |
| 295 | 135 | values.map { value in |
| 296 | 135 | #"<span class="trend-grid" style="top: \#(number(plot.y(of: value)))px"></span>"# |
| 297 | 135 | }.joined() |
| 298 | 54 | } |
| 299 | | |
| 300 | | /// HTML rather than SVG text, which would be squeezed with the chart on a phone. |
| 301 | 54 | private static func valueLabels(_ values: [Double], in plot: Plot) -> String { |
| 302 | 135 | values.map { value in |
| 303 | 135 | #"<span class="trend-value" style="top: \#(number(plot.y(of: value)))px">"# |
| 304 | 135 | + "\(percent(value))</span>" |
| 305 | 135 | }.joined() |
| 306 | 54 | } |
| 307 | | |
| 308 | | /// The short commit, or the month and day for a run without one. |
| 309 | 222 | private static func label(of run: RunTotals) -> String { |
| 310 | 222 | if let commit = run.commit, !commit.isEmpty { |
| 311 | 215 | return String(commit.prefix(PublishedLayout.shortCommitLength)) |
| 312 | 215 | } |
| 313 | 7 | return String( |
| 314 | 7 | run.date.formatted(.iso8601).dropFirst(yearPrefixLength).prefix(monthDayLength)) |
| 315 | 222 | } |
| 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 | | |
| 321 | 504 | private static func fraction(_ count: RunTotals.Lines) -> Double { |
| 322 | 504 | Double(count.covered) / Double(count.total) |
| 323 | 504 | } |
| 324 | | |
| 325 | 135 | private static func percent(_ fraction: Double) -> String { |
| 326 | 135 | String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100) |
| 327 | 135 | } |
| 328 | | |
| 329 | 1370 | private static func number(_ value: Double) -> String { |
| 330 | 1370 | String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value) |
| 331 | 1370 | } |
| 332 | | } |