| 1 | | import Foundation |
| 2 | | |
| 3 | | /// Refits the history chart's axis to the series its legend leaves on. The stylesheet |
| 4 | | /// does the hiding; without scripts the axis stays fitted to every series. |
| 5 | | enum SeriesRescaling { |
| 6 | | /// How the chart shows one choice of series: the transform that moves their points |
| 7 | | /// from the full axis to one fitted to them, and that axis's labels, top first. |
| 8 | | struct Scale: Codable, Equatable { |
| 9 | | let transform: String |
| 10 | | let values: [String] |
| 11 | | } |
| 12 | | |
| 13 | | /// The scales for the script to read, keyed by the shown series' names. Names and |
| 14 | | /// numbers only, so nothing in them can end the element early. |
| 15 | 13 | static func markup(_ scales: [String: Scale]) -> String { |
| 16 | 13 | let encoder = JSONEncoder() |
| 17 | 13 | encoder.outputFormatting = .sortedKeys |
| 18 | 13 | guard let json = try? encoder.encode(scales) else { |
| 19 | 0 | // Strings always encode; without scales the chart keeps its full axis. |
| 20 | 0 | return "" |
| 21 | 13 | } |
| 22 | 13 | return |
| 23 | 13 | #"<script type="application/json" class="trend-scales">\#(String(decoding: json, as: UTF8.self))</script>"# |
| 24 | 13 | } |
| 25 | | |
| 26 | | static let script = """ |
| 27 | | (() => { |
| 28 | | const chart = document.querySelector(".history-chart"); |
| 29 | | const data = chart.querySelector(".trend-scales"); |
| 30 | | if (!data) return; |
| 31 | | const scales = JSON.parse(data.textContent); |
| 32 | | const labels = chart.querySelectorAll(".trend-value"); |
| 33 | | const rescale = () => { |
| 34 | | const shown = [...chart.querySelectorAll("[data-toggle]:checked")] |
| 35 | | .map(toggle => toggle.dataset.toggle) |
| 36 | | .filter(name => chart.querySelector(`[data-series="${name}"]`)); |
| 37 | | // With every series hidden there is nothing to fit, and the axis stays. |
| 38 | | const scale = scales[shown.join(" ")]; |
| 39 | | if (!scale) return; |
| 40 | | for (const series of chart.querySelectorAll("[data-series]")) { |
| 41 | | series.setAttribute("transform", scale.transform); |
| 42 | | } |
| 43 | | scale.values.forEach((value, index) => labels[index].textContent = value); |
| 44 | | }; |
| 45 | | chart.addEventListener("change", rescale); |
| 46 | | // Going back to the page can restore unticked boxes. |
| 47 | | addEventListener("pageshow", rescale); |
| 48 | | })(); |
| 49 | | """ |
| 50 | | } |