| 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 | 808 | static let lines = Metric(name: "lines", title: "Lines", count: { $0.lines }) |
| 26 | 648 | static let regions = Metric(name: "regions", title: "Regions", count: { $0.regions }) |
| 27 | 646 | static let branches = Metric(name: "branches", title: "Branches", count: { $0.branches }) |
| 28 | | static let conditions = Metric( |
| 29 | 624 | 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 | 215 | var coordinates: String { |
| 40 | 215 | "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))" |
| 41 | 215 | } |
| 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 | | var axis: ClosedRange<Double> |
| 61 | | /// False when no run has a value, so the axis is only a placeholder. |
| 62 | | let plotsValues: Bool |
| 63 | | |
| 64 | 289 | func x(ofRun index: Int) -> Double { |
| 65 | 289 | let plotWidth = width - CoverageTrend.padding * 2 |
| 66 | 289 | return CoverageTrend.padding |
| 67 | 289 | + (runCount == 1 |
| 68 | 289 | ? plotWidth / 2 : Double(index) / Double(runCount - 1) * plotWidth) |
| 69 | 289 | } |
| 70 | | |
| 71 | 595 | func y(of fraction: Double) -> Double { |
| 72 | 595 | CoverageTrend.padding |
| 73 | 595 | + (axis.upperBound - fraction) / (axis.upperBound - axis.lowerBound) |
| 74 | 595 | * (height - CoverageTrend.padding * 2) |
| 75 | 595 | } |
| 76 | | } |
| 77 | | |
| 78 | | /// Accepts runs in any order; points are ordered by date, then commit. |
| 79 | 147 | public init(runs: [RunTotals]) { |
| 80 | 186 | self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") } |
| 81 | 147 | } |
| 82 | | |
| 83 | | /// A compact line-only chart; empty when no runs were supplied. |
| 84 | 89 | public var sparkline: String { |
| 85 | 89 | guard !runs.isEmpty else { return "" } |
| 86 | 36 | return sparkline(of: .lines) |
| 87 | 89 | } |
| 88 | | |
| 89 | | /// A compact region-only chart; empty when no run recorded regions. |
| 90 | 30 | public var regionSparkline: String { |
| 91 | 30 | guard !fractions(of: [.regions]).isEmpty else { return "" } |
| 92 | 6 | return sparkline(of: .regions) |
| 93 | 30 | } |
| 94 | | |
| 95 | 42 | private func sparkline(of metric: Metric) -> String { |
| 96 | 42 | let plot = plot( |
| 97 | 42 | width: Self.sparklineWidth, height: Self.sparklineHeight, fitting: [metric]) |
| 98 | 42 | let segments = segments(of: metric, in: plot) |
| 99 | 42 | let loneDots = segments.filter { $0.count == 1 }.joined().map { point in |
| 100 | 28 | #"<circle class="trend-\#(metric.name)" cx="\#(Self.number(point.x))" cy="\#(Self.number(point.y))" r="\#(Self.pointRadius)"/>"# |
| 101 | 28 | } |
| 102 | 42 | let noData = noDataDots(of: metric, in: plot) |
| 103 | 42 | let missing = noData.map { dot in |
| 104 | 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>"# |
| 105 | 1 | } |
| 106 | 42 | return svg( |
| 107 | 42 | plot, attributes: #"role="img""#, |
| 108 | 42 | contents: Self.polylines(segments, through: noData, of: metric) + loneDots.joined() |
| 109 | 42 | + missing.joined()) |
| 110 | 42 | } |
| 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. |
| 115 | 61 | public var chart: String { |
| 116 | 61 | guard !runs.isEmpty else { return "" } |
| 117 | 60 | let metrics = [Metric.lines, .regions, .branches, .conditions] |
| 118 | 60 | let plot = plot(width: chartWidth, height: Self.chartHeight, fitting: metrics) |
| 119 | 240 | let series = metrics.map { seriesMarkup($0, in: plot) } |
| 120 | 60 | let unmeasured = unmeasuredDots(among: metrics, in: plot).map(Self.marker) |
| 121 | 60 | let values = axisValues(in: plot) |
| 122 | 60 | // Stretched only when the page is narrower than the runs need; strokes and dots |
| 123 | 60 | // don't scale, so they keep their shape. |
| 124 | 60 | let drawing = svg( |
| 125 | 60 | plot, attributes: #"preserveAspectRatio="none" role="group""#, |
| 126 | 60 | contents: series.joined() + unmeasured.joined()) |
| 127 | 60 | return #"<div class="trend-plot">"# |
| 128 | 60 | + #"<div class="trend-values">\#(Self.valueLabels(values, in: plot))</div>"# |
| 129 | 60 | + #"<div class="trend-area">\#(Self.gridLines(values, in: plot))"# |
| 130 | 60 | + #"<div class="trend-data" style="width: min(100%, \#(Self.number(naturalWidth))px)">"# |
| 131 | 60 | + drawing + "</div></div></div>" + scalesMarkup(of: metrics, from: plot) |
| 132 | 61 | } |
| 133 | | |
| 134 | | /// The metric's lines and dots, grouped so the legend can hide them together; empty |
| 135 | | /// when it was never measured. |
| 136 | 240 | private func seriesMarkup(_ metric: Metric, in plot: Plot) -> String { |
| 137 | 240 | let segments = segments(of: metric, in: plot) |
| 138 | 240 | guard !segments.isEmpty else { return "" } |
| 139 | 67 | let noData = noDataDots(of: metric, in: plot) |
| 140 | 67 | let contents = |
| 141 | 67 | Self.polylines(segments, through: noData, of: metric) |
| 142 | 222 | + segments.joined().map { Self.marker($0, of: metric) }.joined() |
| 143 | 67 | + noData.map(Self.marker).joined() |
| 144 | 67 | return #"<g data-series="\#(metric.name)">\#(contents)</g>"# |
| 145 | 240 | } |
| 146 | | |
| 147 | 19 | private static func marker(_ noData: NoDataDot) -> String { |
| 148 | 19 | dot( |
| 149 | 19 | x: noData.x, y: noData.y, style: "trend-unavailable", |
| 150 | 19 | title: title(of: noData.run, showing: "No coverage data")) |
| 151 | 19 | } |
| 152 | | |
| 153 | | /// The width at which runs sit `widestRunSpacing` apart; a lone run gets one space. |
| 154 | 120 | private var naturalWidth: Double { |
| 155 | 120 | Double(max(runs.count - 1, 1)) * Self.widestRunSpacing + Self.padding * 2 |
| 156 | 120 | } |
| 157 | | |
| 158 | 60 | private var chartWidth: Double { |
| 159 | 60 | min(naturalWidth, Self.widestChartWidth) |
| 160 | 60 | } |
| 161 | | |
| 162 | 270 | private var unavailableRuns: [(index: Int, run: RunTotals)] { |
| 163 | 796 | runs.enumerated().filter { $0.element.unavailable != nil }.map { ($0.offset, $0.element) } |
| 164 | 270 | } |
| 165 | | |
| 166 | | /// The metric's value at its last measurement before a run; nil if it had none. |
| 167 | 87 | private func fraction(of metric: Metric, before index: Int) -> Double? { |
| 168 | 87 | runs[..<index].reversed().lazy.compactMap { Self.recorded(metric, in: $0) }.first |
| 169 | 87 | .map(Self.fraction) |
| 170 | 87 | } |
| 171 | | |
| 172 | 2954 | private static func recorded(_ metric: Metric, in run: RunTotals) -> RunTotals.Lines? { |
| 173 | 2954 | guard run.unavailable == nil, let count = metric.count(run), count.total > 0 else { |
| 174 | 2025 | return nil |
| 175 | 2025 | } |
| 176 | 929 | return count |
| 177 | 2954 | } |
| 178 | | |
| 179 | | /// The runs without data that none of the metrics was measured before. |
| 180 | 161 | private func unmeasuredRuns(among metrics: [Metric]) -> [(index: Int, run: RunTotals)] { |
| 181 | 161 | unavailableRuns.filter { index, _ in |
| 182 | 72 | metrics.allSatisfy { fraction(of: $0, before: index) == nil } |
| 183 | 33 | } |
| 184 | 161 | } |
| 185 | | |
| 186 | | /// A run without data keeps the metric where it was last measured. |
| 187 | 109 | private func noDataDots(of metric: Metric, in plot: Plot) -> [NoDataDot] { |
| 188 | 109 | unavailableRuns.compactMap { index, run in |
| 189 | 15 | fraction(of: metric, before: index).map { prior in |
| 190 | 11 | NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: prior)) |
| 191 | 11 | } |
| 192 | 15 | } |
| 193 | 109 | } |
| 194 | | |
| 195 | | /// Runs without data and with nothing measured before them sit at zero. |
| 196 | 60 | private func unmeasuredDots(among metrics: [Metric], in plot: Plot) -> [NoDataDot] { |
| 197 | 60 | unmeasuredRuns(among: metrics).map { index, run in |
| 198 | 9 | NoDataDot(run: run, x: plot.x(ofRun: index), y: plot.y(of: 0)) |
| 199 | 9 | } |
| 200 | 60 | } |
| 201 | | |
| 202 | | /// Fractions covered that the metrics plot, widened to the minimum span and kept |
| 203 | | /// inside 0...1; nil when they plot nothing. |
| 204 | 102 | private func axis(fitting metrics: [Metric]) -> ClosedRange<Double>? { |
| 205 | 102 | var fractions = fractions(of: metrics) |
| 206 | 102 | if !fractions.isEmpty, !unmeasuredRuns(among: metrics).isEmpty { fractions.append(0) } |
| 207 | 102 | return Self.axis(spanning: fractions) |
| 208 | 102 | } |
| 209 | | |
| 210 | 423 | private func fractions(of metrics: [Metric]) -> [Double] { |
| 211 | 1249 | runs.flatMap { run in |
| 212 | 1948 | metrics.compactMap { Self.recorded($0, in: run).map(Self.fraction) } |
| 213 | 1249 | } |
| 214 | 423 | } |
| 215 | | |
| 216 | 153 | private static func axis(spanning fractions: [Double]) -> ClosedRange<Double>? { |
| 217 | 153 | guard let low = fractions.min(), let high = fractions.max() else { return nil } |
| 218 | 139 | let extra = max(0, minimumSpan - (high - low)) / 2 |
| 219 | 139 | let upper = min(1, high + extra) |
| 220 | 139 | let lower = max(0, min(low - extra, upper - minimumSpan)) |
| 221 | 139 | return lower...upper |
| 222 | 153 | } |
| 223 | | |
| 224 | 102 | private func plot(width: Double, height: Double, fitting metrics: [Metric]) -> Plot { |
| 225 | 102 | let axis = axis(fitting: metrics) |
| 226 | 102 | return Plot( |
| 227 | 102 | width: width, height: height, runCount: runs.count, axis: axis ?? 0...1, |
| 228 | 102 | plotsValues: axis != nil) |
| 229 | 102 | } |
| 230 | | |
| 231 | | /// The metric's points, split wherever a run lacks it. |
| 232 | 282 | private func segments(of metric: Metric, in plot: Plot) -> [[Point]] { |
| 233 | 282 | var segments: [[Point]] = [] |
| 234 | 282 | var points: [Point] = [] |
| 235 | 941 | for (index, run) in runs.enumerated() { |
| 236 | 941 | if let count = Self.recorded(metric, in: run) { |
| 237 | 269 | points.append( |
| 238 | 269 | Point( |
| 239 | 269 | run: run, count: count, x: plot.x(ofRun: index), |
| 240 | 269 | y: plot.y(of: Self.fraction(count)))) |
| 241 | 672 | } else if !points.isEmpty { |
| 242 | 11 | segments.append(points) |
| 243 | 11 | points = [] |
| 244 | 11 | } |
| 245 | 941 | } |
| 246 | 282 | if !points.isEmpty { segments.append(points) } |
| 247 | 282 | return segments |
| 248 | 282 | } |
| 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 |
| 254 | 109 | ) -> String { |
| 255 | 109 | let bridges = zip(segments, segments.dropFirst()).compactMap { earlier, later in |
| 256 | 6 | earlier.last.flatMap { from in |
| 257 | 6 | later.first.map { to in |
| 258 | 6 | let between = noData.filter { $0.x > from.x && $0.x < to.x } |
| 259 | 6 | let points = [from.coordinates] + between.map(\.coordinates) + [to.coordinates] |
| 260 | 6 | return |
| 261 | 6 | #"<polyline class="trend-\#(metric.name) trend-gap" points="\#(points.joined(separator: " "))"/>"# |
| 262 | 6 | } |
| 263 | 6 | } |
| 264 | 6 | } |
| 265 | 110 | let lines = segments.filter { $0.count > 1 }.map { segment in |
| 266 | 203 | #"<polyline class="trend-\#(metric.name)" points="\#(segment.map(\.coordinates).joined(separator: " "))"/>"# |
| 267 | 44 | } |
| 268 | 109 | return bridges.joined() + lines.joined() |
| 269 | 109 | } |
| 270 | | |
| 271 | | /// A dot whose title names the run and the value, for pointers and screen readers. |
| 272 | 222 | private static func marker(_ point: Point, of metric: Metric) -> String { |
| 273 | 222 | let summary = LineSummary(count: point.count.total, covered: point.count.covered) |
| 274 | 222 | let value = |
| 275 | 222 | "\(metric.title) \(summary.percentText) " |
| 276 | 222 | + "(\(groupingDigits(summary.covered)) of \(groupingDigits(summary.count)))" |
| 277 | 222 | return dot( |
| 278 | 222 | x: point.x, y: point.y, style: "trend-\(metric.name)", |
| 279 | 222 | title: title(of: point.run, showing: value)) |
| 280 | 222 | } |
| 281 | | |
| 282 | | /// The run and what its dot shows, with the commit message on a line of its own. |
| 283 | 241 | private static func title(of run: RunTotals, showing value: String) -> String { |
| 284 | 241 | let message = run.subject.flatMap { $0.isEmpty ? nil : "\n\($0)" } ?? "" |
| 285 | 241 | return "\(label(of: run)) · \(value)\(message)" |
| 286 | 241 | } |
| 287 | | |
| 288 | | /// A zero-length path with round caps: unlike a circle, it stays round when the |
| 289 | | /// chart is stretched. |
| 290 | 241 | private static func dot(x: Double, y: Double, style: String, title: String) -> String { |
| 291 | 241 | #"<path class="\#(style) trend-dot" d="M\#(number(x)),\#(number(y))h0">"# |
| 292 | 241 | + "<title>\(escapingHTML(title))</title></path>" |
| 293 | 241 | } |
| 294 | | |
| 295 | 102 | private func svg(_ plot: Plot, attributes: String, contents: String) -> String { |
| 296 | 102 | #"<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>"# |
| 297 | 102 | } |
| 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. |
| 301 | 111 | private func axisValues(in plot: Plot) -> [Double] { |
| 302 | 111 | guard plot.plotsValues else { return [] } |
| 303 | 102 | let middle = (plot.axis.lowerBound + plot.axis.upperBound) / 2 |
| 304 | 102 | return [plot.axis.upperBound, middle, plot.axis.lowerBound] |
| 305 | 111 | } |
| 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. |
| 309 | 60 | private func scalesMarkup(of metrics: [Metric], from drawn: Plot) -> String { |
| 310 | 240 | let recorded = metrics.filter { !fractions(of: [$0]).isEmpty } |
| 311 | 60 | guard recorded.count > 1 else { return "" } |
| 312 | 13 | // The dots at zero stay whichever series show, so every axis has to reach them. |
| 313 | 13 | let zeroDots: [Double] = unmeasuredRuns(among: metrics).isEmpty ? [] : [0] |
| 314 | 29 | let choices = recorded.reduce([[Metric]]([[]])) { choices, metric in |
| 315 | 51 | choices + choices.map { $0 + [metric] } |
| 316 | 29 | } |
| 317 | 64 | let scales = choices.compactMap { shown -> (String, SeriesRescaling.Scale)? in |
| 318 | 64 | guard !shown.isEmpty, |
| 319 | 64 | let axis = Self.axis(spanning: fractions(of: shown) + zeroDots) |
| 320 | 64 | else { return nil } |
| 321 | 51 | var refitted = drawn |
| 322 | 51 | refitted.axis = axis |
| 323 | 51 | let scale = SeriesRescaling.Scale( |
| 324 | 51 | transform: Self.transform(from: drawn, to: refitted), |
| 325 | 153 | values: axisValues(in: refitted).map(Self.percent)) |
| 326 | 76 | return (shown.map(\.name).joined(separator: " "), scale) |
| 327 | 64 | } |
| 328 | 13 | return SeriesRescaling.markup(Dictionary(uniqueKeysWithValues: scales)) |
| 329 | 60 | } |
| 330 | | |
| 331 | | /// Both axes are linear, so one vertical scale and shift moves every point. |
| 332 | 51 | private static func transform(from drawn: Plot, to refitted: Plot) -> String { |
| 333 | 51 | let stretch = span(of: drawn.axis) / span(of: refitted.axis) |
| 334 | 51 | let shift = |
| 335 | 51 | padding * (1 - stretch) |
| 336 | 51 | + (refitted.axis.upperBound - drawn.axis.upperBound) / span(of: refitted.axis) |
| 337 | 51 | * (drawn.height - padding * 2) |
| 338 | 102 | let format = { (value: Double) in |
| 339 | 102 | String(format: "%.4f", locale: Locale(identifier: "en_US_POSIX"), value) |
| 340 | 102 | } |
| 341 | 51 | return "matrix(1 0 0 \(format(stretch)) 0 \(format(shift)))" |
| 342 | 51 | } |
| 343 | | |
| 344 | 153 | private static func span(of axis: ClosedRange<Double>) -> Double { |
| 345 | 153 | axis.upperBound - axis.lowerBound |
| 346 | 153 | } |
| 347 | | |
| 348 | | /// HTML across the whole chart, so the grid reaches the edge before the runs do. |
| 349 | 60 | private static func gridLines(_ values: [Double], in plot: Plot) -> String { |
| 350 | 153 | values.map { value in |
| 351 | 153 | #"<span class="trend-grid" style="top: \#(number(plot.y(of: value)))px"></span>"# |
| 352 | 153 | }.joined() |
| 353 | 60 | } |
| 354 | | |
| 355 | | /// HTML rather than SVG text, which would be squeezed with the chart on a phone. |
| 356 | 60 | private static func valueLabels(_ values: [Double], in plot: Plot) -> String { |
| 357 | 153 | values.map { value in |
| 358 | 153 | #"<span class="trend-value" style="top: \#(number(plot.y(of: value)))px">"# |
| 359 | 153 | + "\(percent(value))</span>" |
| 360 | 153 | }.joined() |
| 361 | 60 | } |
| 362 | | |
| 363 | | /// The short commit, or the month and day for a run without one. |
| 364 | 242 | private static func label(of run: RunTotals) -> String { |
| 365 | 242 | if let commit = run.commit, !commit.isEmpty { |
| 366 | 235 | return String(commit.prefix(PublishedLayout.shortCommitLength)) |
| 367 | 235 | } |
| 368 | 7 | return String( |
| 369 | 7 | run.date.formatted(.iso8601).dropFirst(yearPrefixLength).prefix(monthDayLength)) |
| 370 | 242 | } |
| 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 | | |
| 376 | 898 | private static func fraction(_ count: RunTotals.Lines) -> Double { |
| 377 | 898 | Double(count.covered) / Double(count.total) |
| 378 | 898 | } |
| 379 | | |
| 380 | 306 | private static func percent(_ fraction: Double) -> String { |
| 381 | 306 | String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100) |
| 382 | 306 | } |
| 383 | | |
| 384 | 1550 | private static func number(_ value: Double) -> String { |
| 385 | 1550 | String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value) |
| 386 | 1550 | } |
| 387 | | } |