| 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: 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 | | |
| 32 | 405 | static let lines = Metric(name: "lines", title: "Lines", count: { $0.lines }) |
| 33 | 370 | static let branches = Metric(name: "branches", title: "Branches", count: { $0.branches }) |
| 34 | | static let conditions = Metric( |
| 35 | 370 | 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 | | |
| 45 | 372 | var coordinates: String { |
| 46 | 372 | "\(CoverageTrend.number(x)),\(CoverageTrend.number(y))" |
| 47 | 372 | } |
| 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. |
| 56 | 72 | var stripHeight = 0.0 |
| 57 | | let runCount: Int |
| 58 | | let axis: ClosedRange<Double> |
| 59 | | |
| 60 | 72 | var drawingHeight: Double { height + stripHeight } |
| 61 | | |
| 62 | 519 | func x(ofRun index: Int) -> Double { |
| 63 | 519 | let plotWidth = width - CoverageTrend.padding * 2 |
| 64 | 519 | return CoverageTrend.padding |
| 65 | 519 | + (runCount == 1 |
| 66 | 519 | ? plotWidth / 2 : Double(index) / Double(runCount - 1) * plotWidth) |
| 67 | 519 | } |
| 68 | | |
| 69 | 607 | func y(of fraction: Double) -> Double { |
| 70 | 607 | CoverageTrend.padding |
| 71 | 607 | + (axis.upperBound - fraction) / (axis.upperBound - axis.lowerBound) |
| 72 | 607 | * (height - CoverageTrend.padding * 2) |
| 73 | 607 | } |
| 74 | | } |
| 75 | | |
| 76 | | /// Accepts runs in any order; points are ordered by date, then commit. |
| 77 | 102 | public init(runs: [RunTotals]) { |
| 78 | 352 | self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") } |
| 79 | 102 | } |
| 80 | | |
| 81 | | /// A compact line-only chart; empty when no runs were supplied. |
| 82 | 62 | public var sparkline: String { |
| 83 | 62 | guard !runs.isEmpty else { return "" } |
| 84 | 28 | let plot = plot(width: Self.sparklineWidth, height: Self.sparklineHeight) |
| 85 | 28 | let segments = segments(of: .lines, in: plot) |
| 86 | 28 | let loneDots = segments.filter { $0.count == 1 }.joined().map { point in |
| 87 | 17 | #"<circle class="trend-lines" cx="\#(Self.number(point.x))" cy="\#(Self.number(point.y))" r="\#(Self.pointRadius)"/>"# |
| 88 | 17 | } |
| 89 | 28 | let missing = unavailableRuns.map { index, run in |
| 90 | 0 | #"<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>"# |
| 91 | 0 | } |
| 92 | 28 | return svg( |
| 93 | 28 | plot, attributes: #"role="img""#, |
| 94 | 28 | contents: Self.polylines(segments, of: .lines) + loneDots.joined() + missing.joined()) |
| 95 | 62 | } |
| 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. |
| 100 | 45 | public var chart: String { |
| 101 | 45 | guard !runs.isEmpty else { return "" } |
| 102 | 44 | var plot = plot(width: chartWidth, height: Self.chartHeight) |
| 103 | 44 | plot.stripHeight = Self.noDataStripHeight |
| 104 | 132 | let series = [Metric.lines, .branches, .conditions].map { metric in |
| 105 | 132 | let segments = segments(of: metric, in: plot) |
| 106 | 373 | let markers = segments.joined().map { Self.marker($0, of: metric) } |
| 107 | 132 | return Self.polylines(segments, of: metric) + markers.joined() |
| 108 | 132 | } |
| 109 | 44 | let missing = unavailableRuns.map { index, run in |
| 110 | 11 | Self.dot( |
| 111 | 11 | x: plot.x(ofRun: index), y: plot.height + plot.stripHeight / 2, |
| 112 | 11 | style: "trend-unavailable", |
| 113 | 11 | title: "\(Self.label(of: run)) · No coverage data") |
| 114 | 11 | } |
| 115 | 44 | let values = axisValues(in: plot) |
| 116 | 44 | // Stretched only when the page is narrower than the runs need; strokes and dots |
| 117 | 44 | // don't scale, so they keep their shape. |
| 118 | 44 | let drawing = svg( |
| 119 | 44 | plot, attributes: #"preserveAspectRatio="none" role="group""#, |
| 120 | 44 | contents: series.joined() + missing.joined()) |
| 121 | 44 | return #"<div class="trend-plot">"# |
| 122 | 44 | + #"<div class="trend-values">\#(Self.valueLabels(values, in: plot))</div>"# |
| 123 | 44 | + #"<div class="trend-area">\#(Self.gridLines(values, in: plot))"# |
| 124 | 44 | + #"<div class="trend-data" style="width: min(100%, \#(Self.number(naturalWidth))px)">"# |
| 125 | 44 | + drawing |
| 126 | 44 | + #"<div class="trend-commits">\#(commitLabels(in: plot))</div></div></div></div>"# |
| 127 | 45 | } |
| 128 | | |
| 129 | | /// The width at which runs sit `widestRunSpacing` apart; a lone run gets one space. |
| 130 | 88 | private var naturalWidth: Double { |
| 131 | 88 | Double(max(runs.count - 1, 1)) * Self.widestRunSpacing + Self.padding * 2 |
| 132 | 88 | } |
| 133 | | |
| 134 | 44 | private var chartWidth: Double { |
| 135 | 44 | min(naturalWidth, Self.widestChartWidth) |
| 136 | 44 | } |
| 137 | | |
| 138 | 72 | private var unavailableRuns: [(index: Int, run: RunTotals)] { |
| 139 | 416 | runs.enumerated().filter { $0.element.unavailable != nil }.map { ($0.offset, $0.element) } |
| 140 | 72 | } |
| 141 | | |
| 142 | | /// Fractions covered that every series plots, widened to the minimum span and kept |
| 143 | | /// inside 0...1. |
| 144 | 116 | private var axis: ClosedRange<Double>? { |
| 145 | 116 | var fractions: [Double] = [] |
| 146 | 775 | for run in runs where run.unavailable == nil { |
| 147 | 2325 | for count in [run.lines, run.branches, run.conditions] { |
| 148 | 2325 | guard let count, count.total > 0 else { continue } |
| 149 | 782 | fractions.append(Self.fraction(count)) |
| 150 | 782 | } |
| 151 | 775 | } |
| 152 | 116 | guard let low = fractions.min(), let high = fractions.max() else { return nil } |
| 153 | 91 | let extra = max(0, Self.minimumSpan - (high - low)) / 2 |
| 154 | 91 | let upper = min(1, high + extra) |
| 155 | 91 | let lower = max(0, min(low - extra, upper - Self.minimumSpan)) |
| 156 | 91 | return lower...upper |
| 157 | 116 | } |
| 158 | | |
| 159 | 72 | private func plot(width: Double, height: Double) -> Plot { |
| 160 | 72 | Plot(width: width, height: height, runCount: runs.count, axis: axis ?? 0...1) |
| 161 | 72 | } |
| 162 | | |
| 163 | | /// The metric's points, split wherever a run lacks it. |
| 164 | 160 | private func segments(of metric: Metric, in plot: Plot) -> [[Point]] { |
| 165 | 160 | var segments: [[Point]] = [] |
| 166 | 160 | var points: [Point] = [] |
| 167 | 1178 | for (index, run) in runs.enumerated() { |
| 168 | 1178 | if run.unavailable == nil, let count = metric.count(run), count.total > 0 { |
| 169 | 403 | points.append( |
| 170 | 403 | Point( |
| 171 | 403 | run: run, count: count, x: plot.x(ofRun: index), |
| 172 | 403 | y: plot.y(of: Self.fraction(count)))) |
| 173 | 775 | } else if !points.isEmpty { |
| 174 | 7 | segments.append(points) |
| 175 | 7 | points = [] |
| 176 | 7 | } |
| 177 | 1178 | } |
| 178 | 160 | if !points.isEmpty { segments.append(points) } |
| 179 | 160 | return segments |
| 180 | 160 | } |
| 181 | | |
| 182 | | /// A line through each segment, and a dashed bridge across each gap between two. |
| 183 | 160 | private static func polylines(_ segments: [[Point]], of metric: Metric) -> String { |
| 184 | 160 | let bridges = zip(segments, segments.dropFirst()).compactMap { earlier, later in |
| 185 | 5 | earlier.last.flatMap { from in |
| 186 | 5 | later.first.map { to in |
| 187 | 5 | #"<polyline class="trend-\#(metric.name) trend-gap" points="\#(from.coordinates) \#(to.coordinates)"/>"# |
| 188 | 5 | } |
| 189 | 5 | } |
| 190 | 5 | } |
| 191 | 160 | let lines = segments.filter { $0.count > 1 }.map { segment in |
| 192 | 362 | #"<polyline class="trend-\#(metric.name)" points="\#(segment.map(\.coordinates).joined(separator: " "))"/>"# |
| 193 | 28 | } |
| 194 | 160 | return bridges.joined() + lines.joined() |
| 195 | 160 | } |
| 196 | | |
| 197 | | /// A dot whose title names the run and the value, for pointers and screen readers. |
| 198 | 373 | private static func marker(_ point: Point, of metric: Metric) -> String { |
| 199 | 373 | let summary = LineSummary(count: point.count.total, covered: point.count.covered) |
| 200 | 373 | let value = |
| 201 | 373 | "\(metric.title) \(summary.percentText) " |
| 202 | 373 | + "(\(groupingDigits(summary.covered)) of \(groupingDigits(summary.count)))" |
| 203 | 373 | return dot( |
| 204 | 373 | x: point.x, y: point.y, style: "trend-\(metric.name)", |
| 205 | 373 | title: "\(label(of: point.run)) · \(value)") |
| 206 | 373 | } |
| 207 | | |
| 208 | | /// A zero-length path with round caps: unlike a circle, it stays round when the |
| 209 | | /// chart is stretched. |
| 210 | 384 | private static func dot(x: Double, y: Double, style: String, title: String) -> String { |
| 211 | 384 | #"<path class="\#(style) trend-dot" d="M\#(number(x)),\#(number(y))h0">"# |
| 212 | 384 | + "<title>\(escapingHTML(title))</title></path>" |
| 213 | 384 | } |
| 214 | | |
| 215 | 72 | private func svg(_ plot: Plot, attributes: String, contents: String) -> String { |
| 216 | 72 | #"<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>"# |
| 217 | 72 | } |
| 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. |
| 221 | 44 | private func axisValues(in plot: Plot) -> [Double] { |
| 222 | 44 | guard axis != nil else { return [] } |
| 223 | 34 | let middle = (plot.axis.lowerBound + plot.axis.upperBound) / 2 |
| 224 | 34 | return [plot.axis.upperBound, middle, plot.axis.lowerBound] |
| 225 | 44 | } |
| 226 | | |
| 227 | | /// HTML across the whole chart, so the grid reaches the edge before the runs do. |
| 228 | 44 | private static func gridLines(_ values: [Double], in plot: Plot) -> String { |
| 229 | 102 | values.map { value in |
| 230 | 102 | #"<span class="trend-grid" style="top: \#(number(plot.y(of: value)))px"></span>"# |
| 231 | 102 | }.joined() |
| 232 | 44 | } |
| 233 | | |
| 234 | | /// HTML rather than SVG text, which would be squeezed with the chart on a phone. |
| 235 | 44 | private static func valueLabels(_ values: [Double], in plot: Plot) -> String { |
| 236 | 102 | values.map { value in |
| 237 | 102 | #"<span class="trend-value" style="top: \#(number(plot.y(of: value)))px">"# |
| 238 | 102 | + "\(percent(value))</span>" |
| 239 | 102 | }.joined() |
| 240 | 44 | } |
| 241 | | |
| 242 | | /// Up to `picks` of the indices below `count`, evenly spaced and always including |
| 243 | | /// the first and the last. |
| 244 | 88 | private static func evenlySpaced(_ picks: Int, below count: Int) -> [Int] { |
| 245 | 88 | let picks = min(picks, count) |
| 246 | 88 | guard picks > 1 else { return Array(0..<picks) } |
| 247 | 164 | return (0..<picks).map { pick in |
| 248 | 164 | Int((Double(pick * (count - 1)) / Double(picks - 1)).rounded()) |
| 249 | 164 | } |
| 250 | 88 | } |
| 251 | | |
| 252 | | /// Commits under evenly spaced runs, each showing its message on hover. |
| 253 | 44 | private func commitLabels(in plot: Plot) -> String { |
| 254 | 44 | let labelled = Self.evenlySpaced(Self.maximumCommitLabels, below: runs.count) |
| 255 | 44 | let kept = Self.evenlySpaced(Self.maximumNarrowCommitLabels, below: labelled.count) |
| 256 | 105 | return labelled.enumerated().map { position, index in |
| 257 | 105 | // The outermost labels turn inward so they stay inside the chart. |
| 258 | 105 | let edge = |
| 259 | 105 | runs.count == 1 |
| 260 | 105 | ? "" : index == 0 ? " first" : index == runs.count - 1 ? " last" : "" |
| 261 | 105 | let minor = kept.contains(position) ? "" : " minor" |
| 262 | 105 | let left = Self.number(plot.x(ofRun: index) / plot.width * 100) |
| 263 | 105 | let message = runs[index].subject.flatMap { $0.isEmpty ? nil : $0 } |
| 264 | 105 | let tooltip = message.map { #" title="\#(escapingHTML($0))""# } ?? "" |
| 265 | 105 | return |
| 266 | 105 | #"<span class="trend-commit\#(edge)\#(minor)" style="left: \#(left)%"\#(tooltip)>"# |
| 267 | 105 | + "\(escapingHTML(Self.label(of: runs[index])))</span>" |
| 268 | 105 | }.joined() |
| 269 | 44 | } |
| 270 | | |
| 271 | | /// The short commit, or the month and day for a run without one. |
| 272 | 489 | private static func label(of run: RunTotals) -> String { |
| 273 | 489 | if let commit = run.commit, !commit.isEmpty { |
| 274 | 479 | return String(commit.prefix(PublishedLayout.shortCommitLength)) |
| 275 | 479 | } |
| 276 | 10 | return String( |
| 277 | 10 | run.date.formatted(.iso8601).dropFirst(yearPrefixLength).prefix(monthDayLength)) |
| 278 | 489 | } |
| 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 | | |
| 284 | 1185 | private static func fraction(_ count: RunTotals.Lines) -> Double { |
| 285 | 1185 | Double(count.covered) / Double(count.total) |
| 286 | 1185 | } |
| 287 | | |
| 288 | 102 | private static func percent(_ fraction: Double) -> String { |
| 289 | 102 | String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100) |
| 290 | 102 | } |
| 291 | | |
| 292 | 2043 | private static func number(_ value: Double) -> String { |
| 293 | 2043 | String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value) |
| 294 | 2043 | } |
| 295 | | } |