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

DiveDetailView.swift (14156B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import MapKit
      3 import SubsurfaceLog
      4 import SwiftUI
      5 
      6 struct DiveDetailView: View {
      7     @Environment(AppModel.self) private var model
      8     @Environment(\.dismiss) private var dismiss
      9     let diveID: String
     10 
     11     @State private var computers: [DiveComputer] = []
     12     @State private var loadedFor: [String] = []
     13     @State private var computerIndex = 0
     14     @State private var editing = LaunchOptions.flag("-edit")
     15     @State private var confirmingDelete = false
     16     @State private var exporting = false
     17     @State private var error: String?
     18     @State private var photoAccess = PhotoAccess()
     19     @State private var photos: [DivePhoto] = []
     20     @State private var photosLoading = false
     21     @State private var photoZone = TimeZone.current
     22 
     23     var body: some View {
     24         if let dive = model.dive(id: diveID) {
     25             content(dive)
     26         } else {
     27             ContentUnavailableView("Dive not found", systemImage: "questionmark.circle",
     28                                    description: Text("It was deleted or renumbered from another device."))
     29         }
     30     }
     31 
     32     private func content(_ dive: Dive) -> some View {
     33         let site = model.logbook.site(of: dive)
     34         let units = model.units
     35         return ScrollViewReader { proxy in
     36           List {
     37             Section {
     38                 VStack(alignment: .leading, spacing: 6) {
     39                     Text(model.siteName(of: dive))
     40                         .font(.title2.bold())
     41                     Text(DiveDate.full(dive).capitalizedFirst)
     42                         .font(.subheadline)
     43                         .foregroundStyle(.secondary)
     44                     HStack(spacing: 10) {
     45                         if let trip = model.logbook.trip(of: dive), !trip.location.isEmpty {
     46                             Label(trip.location, systemImage: "suitcase")
     47                         }
     48                         if dive.rating > 0 { Stars(value: dive.rating) }
     49                     }
     50                     .font(.caption)
     51                     .foregroundStyle(.secondary)
     52                 }
     53                 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 3), spacing: 8) {
     54                     Figure(title: "Max depth", value: units.depth(dive.maxDepth), icon: "arrow.down.to.line")
     55                     Figure(title: "Duration", value: Units.duration(dive.durationSeconds), icon: "clock")
     56                     if let t = dive.waterTemperature { Figure(title: "Water", value: units.temperature(t), icon: "thermometer.medium") }
     57                     if let mean = dive.meanDepth { Figure(title: "Avg depth", value: units.depth(mean), icon: "arrow.up.and.down") }
     58                     if let sac = dive.sac { Figure(title: "SAC", value: units.sac(sac), icon: "lungs") }
     59                     if let t = dive.airTemperature { Figure(title: "Air", value: units.temperature(t), icon: "sun.max") }
     60                 }
     61                 .listRowSeparator(.hidden)
     62             }
     63 
     64             Section("Profile") {
     65                 if computers.count > 1 {
     66                     Picker("Computer", selection: $computerIndex) {
     67                         ForEach(computers.indices, id: \.self) { index in
     68                             Text(computers[index].model.isEmpty ? String(localized: "Computer \(index + 1)") : computers[index].model).tag(index)
     69                         }
     70                     }
     71                 }
     72                 if computers.indices.contains(computerIndex), computers[computerIndex].samples.count > 1 {
     73                     ProfileChart(data: ProfileData(computer: computers[computerIndex], units: units), units: units,
     74                                  photoOffsets: photos.compactMap(\.offset))
     75                         .padding(.vertical, 4)
     76                 } else if loadedFor == dive.computerBlobs.map(\.hex) {
     77                     Text("No profile recorded for this dive.")
     78                         .foregroundStyle(.secondary)
     79                 } else {
     80                     ProgressView().frame(maxWidth: .infinity, minHeight: 220)
     81                 }
     82             }
     83 
     84             Section("Photos") {
     85                 PhotoStrip(access: photoAccess, photos: photos, loading: photosLoading,
     86                            emptyText: DivePhotoFinder.timeIsGuessed(dive)
     87                                ? String(localized: "No photos from that day in this iPhone's photo library.")
     88                                : String(localized: "No photos around this dive in this iPhone's photo library."),
     89                            onGranted: { Task { await loadPhotos(dive); await model.refreshPhotoPresence() } },
     90                            caption: { photoCaption($0) })
     91                     .id("photos")
     92             }
     93 
     94             if !dive.buddy.isEmpty || !dive.divemaster.isEmpty {
     95                 Section("Team") {
     96                     if !dive.buddy.isEmpty { LabeledContent("Buddy", value: dive.buddy) }
     97                     if !dive.divemaster.isEmpty { LabeledContent("Guide", value: dive.divemaster) }
     98                 }
     99             }
    100 
    101             if !dive.cylinders.isEmpty || !dive.weights.isEmpty || !dive.suit.isEmpty {
    102                 Section("Equipment") {
    103                     ForEach(Array(dive.cylinders.enumerated()), id: \.offset) { _, cylinder in
    104                         VStack(alignment: .leading, spacing: 2) {
    105                             HStack {
    106                                 Text(cylinder.description.isEmpty ? String(localized: "Cylinder") : cylinder.description)
    107                                 Spacer()
    108                                 Text(cylinder.gas.label)
    109                                     .font(.callout.weight(.semibold))
    110                                     .foregroundStyle(cylinder.gas.isAir ? Color.secondary : Color.green)
    111                             }
    112                             if let start = cylinder.startBar, let end = cylinder.endBar, start > end {
    113                                 Text(verbatim: "\(units.pressure(start)) → \(units.pressure(end))")
    114                                     .font(.caption)
    115                                     .foregroundStyle(.secondary)
    116                             } else if let use = cylinder.use, use == "not used" {
    117                                 Text("Not used").font(.caption).foregroundStyle(.secondary)
    118                             }
    119                         }
    120                     }
    121                     if dive.totalWeight > 0 { LabeledContent("Weights", value: units.weight(dive.totalWeight)) }
    122                     if !dive.suit.isEmpty { LabeledContent("Suit", value: dive.suit) }
    123                 }
    124             }
    125 
    126             if dive.visibility > 0 || dive.current > 0 || dive.waveSize > 0 || !dive.tags.isEmpty {
    127                 Section("Conditions") {
    128                     if dive.visibility > 0 { LabeledContent("Visibility") { Stars(value: dive.visibility) } }
    129                     if dive.current > 0 { LabeledContent("Current") { Stars(value: dive.current) } }
    130                     if dive.waveSize > 0 { LabeledContent("Waves") { Stars(value: dive.waveSize) } }
    131                     if !dive.tags.isEmpty { TagChips(tags: dive.tags) }
    132                 }
    133             }
    134 
    135             if !dive.notes.isEmpty {
    136                 Section("Notes") {
    137                     EmptyView().id("notes")
    138                     Text(dive.notes).textSelection(.enabled)
    139                 }
    140             }
    141 
    142             if let site, let latitude = site.latitude, let longitude = site.longitude {
    143                 Section("Site") {
    144                     let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    145                     Map(initialPosition: .region(MKCoordinateRegion(center: coordinate, latitudinalMeters: 6000, longitudinalMeters: 6000))) {
    146                         Marker(site.name, systemImage: "water.waves", coordinate: coordinate).tint(Color.accentColor)
    147                     }
    148                     .frame(height: 170)
    149                     .listRowInsets(EdgeInsets())
    150                     .allowsHitTesting(false)
    151                     if !site.description.isEmpty { Text(site.description).font(.callout) }
    152                     if !site.notes.isEmpty { Text(site.notes).font(.callout).foregroundStyle(.secondary) }
    153                 }
    154             }
    155 
    156             if computers.indices.contains(computerIndex) {
    157                 let computer = computers[computerIndex]
    158                 Section("Computer") {
    159                     EmptyView().id("bottom")
    160                     LabeledContent("Model", value: computer.isManual
    161                         ? String(localized: "Manually entered dive")
    162                         : (computer.model.isEmpty ? String(localized: "Unknown") : computer.model))
    163                     if computer.diveMode != "OC" { LabeledContent("Mode", value: computer.diveMode) }
    164                     if !computer.events.isEmpty {
    165                         DisclosureGroup("Events (\(computer.events.count))") {
    166                             ForEach(Array(computer.events.enumerated()), id: \.offset) { _, event in
    167                                 let gas: String = event.gas?.label ?? String(localized: "change")
    168                                 LabeledContent(Units.clock(event.time), value: event.isGasChange ? String(localized: "Gas: \(gas)") : event.name)
    169                                     .font(.callout)
    170                             }
    171                         }
    172                     }
    173                     if !computer.extra.isEmpty {
    174                         DisclosureGroup("Details (\(computer.extra.count))") {
    175                             ForEach(Array(computer.extra.enumerated()), id: \.offset) { _, pair in
    176                                 LabeledContent(pair.key, value: pair.value).font(.callout)
    177                             }
    178                         }
    179                     }
    180                 }
    181             }
    182         }
    183           .listStyle(.insetGrouped)
    184           .onChange(of: loadedFor) {
    185               // Screenshot option: show the bottom of the dive sheet.
    186               if let target = LaunchOptions.value("-scroll") {
    187                   DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { proxy.scrollTo(target, anchor: .bottom) }
    188               }
    189           }
    190         }
    191         .navigationTitle(dive.number > 0 ? String(localized: "Dive \(dive.number)") : String(localized: "Dive"))
    192         .navigationBarTitleDisplayMode(.inline)
    193         .toolbar {
    194             ToolbarItemGroup(placement: .topBarTrailing) {
    195                 Button("Edit") { editing = true }
    196                 Menu {
    197                     Button("Merge with other dives…", systemImage: "arrow.triangle.merge") {
    198                         // The list takes over: it opens in selection mode with this dive already picked.
    199                         model.mergeRequest = diveID
    200                         dismiss()
    201                     }
    202                     .disabled(model.logbook.dives.count < 2)
    203                     Button("Export as UDDF…", systemImage: "square.and.arrow.up") { exporting = true }
    204                     Button("Delete dive", systemImage: "trash", role: .destructive) { confirmingDelete = true }
    205                 } label: {
    206                     Label("More actions", systemImage: "ellipsis.circle")
    207                 }
    208             }
    209         }
    210         .sheet(isPresented: $editing) { DiveEditView(dive: dive) }
    211         .modifier(UDDFExport(isPresented: $exporting, dives: model.dive(id: diveID).map { [$0] } ?? [],
    212                              fileName: model.dive(id: diveID).map { "dive-\($0.number)" } ?? "dive"))
    213         .confirmationDialog("Delete this dive from the logbook?", isPresented: $confirmingDelete, titleVisibility: .visible) {
    214             Button("Delete", role: .destructive) {
    215                 Task {
    216                     do {
    217                         try await model.apply(.deleteDive(when: dive.when, number: dive.number))
    218                         dismiss()
    219                     } catch {
    220                         self.error = AppModel.describe(error)
    221                     }
    222                 }
    223             }
    224         } message: {
    225             Text("The deletion will be sent to the Subsurface cloud at the next sync.")
    226         }
    227         .alert("Action failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
    228             Button("OK", role: .cancel) {}
    229         } message: {
    230             Text(error ?? "")
    231         }
    232         .task(id: dive.computerBlobs.map(\.hex)) {
    233             let loaded = await model.profile(of: dive)
    234             computers = loaded
    235             // By default, the first computer: the primary one of a merged dive (or the first that has a profile).
    236             computerIndex = loaded.firstIndex { $0.samples.count > 1 } ?? 0
    237             loadedFor = dive.computerBlobs.map(\.hex)
    238             await loadPhotos(dive)
    239         }
    240     }
    241 
    242     /// Time elapsed between entering and leaving the water (longer than the time underwater for a merged dive).
    243     private func elapsed(_ dive: Dive) -> Int {
    244         max(dive.durationSeconds, computers.compactMap { $0.samples.last?.time }.max() ?? 0)
    245     }
    246 
    247     private func loadPhotos(_ dive: Dive) async {
    248         guard photoAccess.granted else { return }
    249         photosLoading = photos.isEmpty
    250         let zone = await SiteTimeZone.zone(for: model.logbook.site(of: dive))
    251         photoZone = zone
    252         photos = DivePhotoFinder.photos(for: dive, elapsed: elapsed(dive), zone: zone)
    253         photosLoading = false
    254     }
    255 
    256     /// "10:36 · 12.4 m" for a photo taken underwater, the time alone otherwise.
    257     private func photoCaption(_ photo: DivePhoto) -> String {
    258         var parts = [String]()
    259         if let taken = photo.asset.creationDate {
    260             parts.append(taken.formatted(Date.FormatStyle(timeZone: photoZone).hour().minute()))
    261         }
    262         if let offset = photo.offset, computers.indices.contains(computerIndex),
    263            let sample = ProfileData(computer: computers[computerIndex], units: model.units).sample(at: Double(offset) / 60) {
    264             parts.append(model.units.depth(sample.depth))
    265             let clock: String = Units.clock(offset)
    266             parts.append(String(localized: "\(clock) into the dive"))
    267         }
    268         return parts.joined(separator: " · ")
    269     }
    270 }