subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

StatsView.swift (11852B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Charts
      3 import SubsurfaceLog
      4 import SwiftUI
      5 
      6 struct StatsView: View {
      7     @Environment(AppModel.self) private var model
      8 
      9     private struct Bucket: Identifiable {
     10         let id: String
     11         let count: Int
     12         var label: String?
     13         var name: String { label ?? id }
     14     }
     15 
     16     /// Columns: one per category, the count written above, no vertical axis (the numbers are enough).
     17     private func columns(_ buckets: [Bucket], label: String) -> some View {
     18         let top = Double(max(buckets.map(\.count).max() ?? 1, 1))
     19         return Chart(buckets) { bucket in
     20             BarMark(x: .value(label, bucket.id), y: .value("Dives", bucket.count), width: .ratio(0.72))
     21                 .foregroundStyle(Color.accentColor.gradient)
     22                 .cornerRadius(4)
     23                 .annotation(position: .top, spacing: 3) {
     24                     if bucket.count > 0 {
     25                         Text("\(bucket.count)").font(.caption.monospacedDigit().weight(.medium)).foregroundStyle(.secondary)
     26                     }
     27                 }
     28         }
     29         .chartYScale(domain: 0...(top * 1.12))
     30         .chartYAxis(.hidden)
     31         // Chart labels have no room to grow with the iPhone text size.
     32         .dynamicTypeSize(...DynamicTypeSize.large)
     33         .chartXAxis {
     34             AxisMarks { value in
     35                 AxisValueLabel {
     36                     if let id = value.as(String.self) {
     37                         Text(buckets.first { $0.id == id }?.name ?? id).font(.caption)
     38                     }
     39                 }
     40             }
     41         }
     42     }
     43 
     44     /// Horizontal bars: the name of the range on the left, the count at the end of the bar. Drawn by hand rather
     45     /// than with a chart: the label and its bar stay on the same line whatever the text size.
     46     private func rows(_ buckets: [Bucket], label: String) -> some View {
     47         let top = CGFloat(max(buckets.map(\.count).max() ?? 1, 1))
     48         return Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 12) {
     49             ForEach(buckets) { bucket in
     50                 GridRow {
     51                     Text(bucket.name)
     52                         .font(.callout)
     53                         .lineLimit(1)
     54                         .fixedSize()
     55                     GeometryReader { geometry in
     56                         HStack(spacing: 6) {
     57                             RoundedRectangle(cornerRadius: 4, style: .continuous)
     58                                 .fill(Color.accentColor.gradient)
     59                                 .frame(width: max(bucket.count > 0 ? 3 : 0, (geometry.size.width - 40) * CGFloat(bucket.count) / top), height: 18)
     60                             Text("\(bucket.count)")
     61                                 .font(.caption.monospacedDigit().weight(.medium))
     62                                 .foregroundStyle(.secondary)
     63                                 .fixedSize()
     64                         }
     65                         .frame(maxHeight: .infinity, alignment: .center)
     66                     }
     67                     .frame(minHeight: 22)
     68                 }
     69             }
     70         }
     71     }
     72 
     73     var body: some View {
     74         NavigationStack {
     75             let dives = model.logbook.dives.filter { !$0.invalid && !$0.isPlanned }
     76             let units = model.units
     77             ScrollViewReader { proxy in
     78             List {
     79                 if dives.isEmpty {
     80                     ContentUnavailableView("No statistics yet", systemImage: "chart.bar",
     81                                            description: Text("They'll appear with your first dives."))
     82                 } else {
     83                     Section {
     84                         LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 2), spacing: 8) {
     85                             Figure(title: "Dives", value: "\(dives.count)", icon: "number")
     86                             Figure(title: "Time underwater", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds }), icon: "clock")
     87                             Figure(title: "Deepest", value: units.depth(dives.map(\.maxDepth).max() ?? 0), icon: "arrow.down.to.line")
     88                             Figure(title: "Longest", value: Units.duration(dives.map(\.durationSeconds).max() ?? 0), icon: "hourglass")
     89                             Figure(title: "Average depth", value: units.depth(dives.map(\.maxDepth).reduce(0, +) / Double(dives.count)), icon: "arrow.up.and.down")
     90                             Figure(title: "Average duration", value: Units.duration(dives.reduce(0) { $0 + $1.durationSeconds } / dives.count), icon: "timer")
     91                             if let cold = dives.compactMap(\.waterTemperature).min(), let warm = dives.compactMap(\.waterTemperature).max() {
     92                                 Figure(title: "Coldest water", value: units.temperature(cold), icon: "snowflake")
     93                                 Figure(title: "Warmest water", value: units.temperature(warm), icon: "sun.max")
     94                             }
     95                             let sacs = dives.compactMap(\.sac)
     96                             if !sacs.isEmpty {
     97                                 Figure(title: "Average SAC", value: units.sac(sacs.reduce(0, +) / Double(sacs.count)), icon: "lungs")
     98                             }
     99                             Figure(title: "Sites visited", value: "\(Set(dives.compactMap(\.siteUUID)).count)", icon: "mappin.and.ellipse")
    100                         }
    101                         .listRowSeparator(.hidden)
    102                     }
    103 
    104                     Section("Dives per year") {
    105                         EmptyView().id("years")
    106                         // Every year from the first to the last, including those without a dive.
    107                         let counts = Dictionary(grouping: dives, by: { DiveDate.year($0.when) }).mapValues(\.count)
    108                         let span = (counts.keys.min() ?? 0)...(counts.keys.max() ?? 0)
    109                         // Beyond six years, "’18" rather than "2018": otherwise the labels overlap.
    110                         let years = span.map { Bucket(id: String($0), count: counts[$0] ?? 0, label: span.count > 6 ? "’" + String(format: "%02d", $0 % 100) : nil) }
    111                         columns(years, label: String(localized: "Year"))
    112                             .frame(height: 190)
    113                             .padding(.vertical, 6)
    114                             .accessibilityLabel("Number of dives per year")
    115                     }
    116 
    117                     Section("Dives per month") {
    118                         EmptyView().id("months")
    119                         let counts = Dictionary(grouping: dives, by: { NaiveTime.components($0.when).month ?? 0 }).mapValues(\.count)
    120                         // Month initials, identical in English and French.
    121                         let initials = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]
    122                         // The identifier carries the rank of the month: several months share the same initial.
    123                         let months = (1...12).map { Bucket(id: "\($0)", count: counts[$0] ?? 0, label: initials[$0 - 1]) }
    124                         columns(months, label: String(localized: "Month"))
    125                             .frame(height: 170)
    126                             .padding(.vertical, 6)
    127                             .accessibilityLabel("Number of dives per month of the year")
    128                     }
    129 
    130                     Section("Maximum depth") {
    131                         EmptyView().id("depth")
    132                         let step = units.imperial ? 30.0 : 10.0
    133                         let grouped = Dictionary(grouping: dives, by: { Int(units.depthValue($0.maxDepth) / step) })
    134                         let unit = units.depthUnit
    135                         let buckets = (0...(grouped.keys.max() ?? 0)).map { index in
    136                             let from = Int(Double(index) * step)
    137                             let to = Int(Double(index + 1) * step)
    138                             return Bucket(id: String(localized: "\(from)–\(to) \(unit)"), count: grouped[index]?.count ?? 0)
    139                         }
    140                         rows(buckets, label: String(localized: "Depth"))
    141                             .padding(.vertical, 6)
    142                             .accessibilityLabel("Number of dives per depth range")
    143                     }
    144 
    145                     Section("Duration") {
    146                         EmptyView().id("duration")
    147                         let grouped = Dictionary(grouping: dives, by: { min($0.durationSeconds / 60 / 15, 5) })
    148                         let names = [String(localized: "Under 15 min"), String(localized: "15–30 min"), String(localized: "30–45 min"),
    149                                      String(localized: "45–60 min"), String(localized: "60–75 min"), String(localized: "75 min or more")]
    150                         let buckets = (0...(grouped.keys.max() ?? 0)).map { Bucket(id: names[$0], count: grouped[$0]?.count ?? 0) }
    151                         rows(buckets, label: String(localized: "Duration"))
    152                             .padding(.vertical, 6)
    153                             .accessibilityLabel("Number of dives per duration range")
    154                     }
    155 
    156                     Section("Gas") {
    157                         EmptyView().id("gas")
    158                         let gases = Dictionary(grouping: dives.filter { !$0.cylinders.isEmpty }, by: { gasFamily($0) })
    159                         ForEach(gases.keys.sorted(), id: \.self) { family in
    160                             LabeledContent(family, value: "\(gases[family]?.count ?? 0)")
    161                         }
    162                     }
    163 
    164                     Section("Most dived sites") {
    165                         let bySite = Dictionary(grouping: dives.filter { $0.siteUUID != nil }, by: { $0.siteUUID! })
    166                             .map { (name: model.logbook.sites[$0.key]?.name ?? "", count: $0.value.count) }
    167                             .filter { !$0.name.isEmpty }
    168                             .sorted { ($0.count, $1.name) > ($1.count, $0.name) }
    169                             .prefix(8)
    170                         ForEach(Array(bySite), id: \.name) { entry in
    171                             LabeledContent(entry.name, value: "\(entry.count)")
    172                         }
    173                     }
    174 
    175                     let buddies = topBuddies(dives)
    176                     if !buddies.isEmpty {
    177                         Section("Buddies") {
    178                             ForEach(buddies, id: \.name) { entry in
    179                                 LabeledContent(entry.name, value: "\(entry.count)")
    180                             }
    181                         }
    182                     }
    183                 }
    184             }
    185             .listStyle(.insetGrouped)
    186             .onAppear {
    187                 // Screenshot option: show a section further down.
    188                 if let target = LaunchOptions.value("-statsScroll") {
    189                     DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { proxy.scrollTo(target, anchor: .top) }
    190                 }
    191             }
    192             }
    193             .navigationTitle("Statistics")
    194         }
    195     }
    196 
    197     /// Gas family names are the same in English and French.
    198     private func gasFamily(_ dive: Dive) -> String {
    199         let used = dive.cylinders.filter { $0.use != "not used" }
    200         if used.contains(where: { $0.gas.hePermille > 0 }) { return "Trimix" }
    201         if used.contains(where: { !$0.gas.isAir }) { return "Nitrox" }
    202         return "Air"
    203     }
    204 
    205     private func topBuddies(_ dives: [Dive]) -> [(name: String, count: Int)] {
    206         var counts = [String: Int]()
    207         for dive in dives {
    208             for name in dive.buddy.split(separator: ",").map({ $0.trimmingCharacters(in: .whitespaces) }) where !name.isEmpty {
    209                 counts[name, default: 0] += 1
    210             }
    211         }
    212         return counts.map { (name: $0.key, count: $0.value) }.sorted { ($0.count, $1.name) > ($1.count, $0.name) }.prefix(8).map { $0 }
    213     }
    214 }