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

DiveEditView.swift (19522B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import SubsurfaceLog
      3 import SwiftUI
      4 
      5 /// Edits the "logbook" fields of a dive. Only the fields that actually changed are sent.
      6 struct DiveEditView: View {
      7     @Environment(AppModel.self) private var model
      8     @Environment(\.dismiss) private var dismiss
      9     let dive: Dive
     10 
     11     @State private var siteUUID: UInt32?
     12     @State private var buddy = ""
     13     @State private var divemaster = ""
     14     @State private var suit = ""
     15     @State private var tags = ""
     16     @State private var rating = 0
     17     @State private var visibility = 0
     18     @State private var notes = ""
     19     @State private var cylinders: [Cylinder] = []
     20     @State private var weights: [WeightSystem] = []
     21     @State private var loaded = false
     22     @State private var saving = false
     23     @State private var error: String?
     24 
     25     var body: some View {
     26         NavigationStack {
     27             Form {
     28                 Section {
     29                     NavigationLink {
     30                         SitePicker(selection: $siteUUID)
     31                     } label: {
     32                         LabeledContent("Site", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? String(localized: "None"))
     33                     }
     34                 }
     35                 Section("Team") {
     36                     TextField("Buddy", text: $buddy)
     37                     TextField("Guide", text: $divemaster)
     38                 }
     39                 Section("Conditions") {
     40                     StarPicker(title: "Rating", value: $rating)
     41                     StarPicker(title: "Visibility", value: $visibility)
     42                     TextField("Suit", text: $suit)
     43                     TextField("Tags, separated by commas", text: $tags)
     44                         .textInputAutocapitalization(.never)
     45                 }
     46                 Section {
     47                     ForEach(cylinders.indices, id: \.self) { index in
     48                         NavigationLink {
     49                             CylinderEditor(cylinder: $cylinders[index])
     50                         } label: {
     51                             CylinderLabel(cylinder: cylinders[index])
     52                         }
     53                         // Only the last one can go: the profile refers to the cylinders by their position.
     54                         .deleteDisabled(index != cylinders.count - 1)
     55                     }
     56                     .onDelete { cylinders.remove(atOffsets: $0) }
     57                     Button { cylinders.append(Cylinder()) } label: { Label("Add a cylinder", systemImage: "plus.circle") }
     58                 } header: {
     59                     Text("Cylinders")
     60                 }
     61                 Section {
     62                     ForEach(weights.indices, id: \.self) { index in
     63                         HStack {
     64                             TextField("Belt, pockets…", text: $weights[index].description)
     65                             TextField("0", value: weightBinding(index), format: .number.precision(.fractionLength(0...1)))
     66                                 .keyboardType(.decimalPad)
     67                                 .multilineTextAlignment(.trailing)
     68                                 .frame(width: 70)
     69                             Text(model.units.weightUnit).foregroundStyle(.secondary)
     70                         }
     71                     }
     72                     .onDelete { weights.remove(atOffsets: $0) }
     73                     Button { weights.append(WeightSystem()) } label: { Label("Add weights", systemImage: "plus.circle") }
     74                 } header: {
     75                     Text("Weights")
     76                 } footer: {
     77                     let total = weights.reduce(0) { $0 + $1.kilograms }
     78                     if weights.count > 1, total > 0 { Text("Total: \(model.units.weight(total))") }
     79                 }
     80                 Section("Notes") {
     81                     TextEditor(text: $notes)
     82                         .frame(minHeight: 140)
     83                 }
     84                 if let error {
     85                     Section { Text(error).foregroundStyle(.red) }
     86                 }
     87             }
     88             .navigationTitle(dive.number > 0 ? String(localized: "Dive \(dive.number)") : String(localized: "Dive"))
     89             .navigationBarTitleDisplayMode(.inline)
     90             .toolbar {
     91                 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
     92                 ToolbarItem(placement: .confirmationAction) {
     93                     Button("Save", action: save).disabled(saving || (changes.isEmpty && !equipmentChanged))
     94                 }
     95             }
     96             .onAppear {
     97                 guard !loaded else { return }
     98                 loaded = true
     99                 siteUUID = dive.siteUUID
    100                 buddy = dive.buddy
    101                 divemaster = dive.divemaster
    102                 suit = dive.suit
    103                 tags = dive.tags.joined(separator: ", ")
    104                 rating = dive.rating
    105                 visibility = dive.visibility
    106                 notes = dive.notes
    107                 cylinders = dive.cylinders
    108                 weights = dive.weights
    109             }
    110         }
    111     }
    112 
    113     private var cleanTags: [String] {
    114         tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
    115     }
    116 
    117     private var changes: [String: String] {
    118         var fields = [String: String]()
    119         func trimmed(_ text: String) -> String { text.trimmingCharacters(in: .whitespacesAndNewlines) }
    120         if siteUUID != dive.siteUUID { fields[DiveField.site.rawValue] = siteUUID.map { String($0, radix: 16) } ?? "" }
    121         if trimmed(buddy) != dive.buddy { fields[DiveField.buddy.rawValue] = trimmed(buddy) }
    122         if trimmed(divemaster) != dive.divemaster { fields[DiveField.divemaster.rawValue] = trimmed(divemaster) }
    123         if trimmed(suit) != dive.suit { fields[DiveField.suit.rawValue] = trimmed(suit) }
    124         if cleanTags != dive.tags { fields[DiveField.tags.rawValue] = cleanTags.joined(separator: ",") }
    125         if rating != dive.rating { fields[DiveField.rating.rawValue] = String(rating) }
    126         if visibility != dive.visibility { fields[DiveField.visibility.rawValue] = String(visibility) }
    127         if trimmed(notes) != dive.notes { fields[DiveField.notes.rawValue] = trimmed(notes) }
    128         return fields
    129     }
    130 
    131     /// Weight of one line, in the units on screen.
    132     private func weightBinding(_ index: Int) -> Binding<Double?> {
    133         Binding {
    134             let kilograms = weights[index].kilograms
    135             return kilograms > 0 ? (model.units.weightValue(kilograms) * 10).rounded() / 10 : nil
    136         } set: {
    137             weights[index].kilograms = $0.map { model.units.kilogramsFromDisplay($0) } ?? 0
    138         }
    139     }
    140 
    141     /// Lines left empty are not kept.
    142     private var cleanCylinders: [Cylinder] {
    143         var kept = cylinders
    144         while let last = kept.last, kept.count > dive.cylinders.count, last == Cylinder() { kept.removeLast() }
    145         return kept
    146     }
    147 
    148     private var cleanWeights: [WeightSystem] {
    149         weights.filter { $0.kilograms > 0 }.map { weight in
    150             var clean = weight
    151             clean.description = weight.description.trimmingCharacters(in: .whitespacesAndNewlines)
    152             return clean
    153         }
    154     }
    155 
    156     private var equipmentChanged: Bool { cleanCylinders != dive.cylinders || cleanWeights != dive.weights }
    157 
    158     private func save() {
    159         saving = true
    160         Task {
    161             do {
    162                 if !changes.isEmpty {
    163                     try await model.apply(.editDive(when: dive.when, number: dive.number, fields: changes))
    164                 }
    165                 if equipmentChanged {
    166                     let new = cleanCylinders
    167                     let unchanged = new.indices.filter { $0 < dive.cylinders.count && new[$0] == dive.cylinders[$0] }
    168                     try await model.apply(.setEquipment(when: dive.when, number: dive.number,
    169                                                         cylinders: new != dive.cylinders ? new : nil, unchangedCylinders: Array(unchanged),
    170                                                         weights: cleanWeights != dive.weights ? cleanWeights : nil))
    171                 }
    172                 dismiss()
    173             } catch {
    174                 self.error = AppModel.describe(error)
    175                 saving = false
    176             }
    177         }
    178     }
    179 }
    180 
    181 /// One cylinder in the list: its name, its gas, its pressures.
    182 struct CylinderLabel: View {
    183     @Environment(AppModel.self) private var model
    184     let cylinder: Cylinder
    185 
    186     var body: some View {
    187         HStack {
    188             Text(cylinder.description.isEmpty ? String(localized: "Cylinder") : cylinder.description)
    189             Spacer()
    190             VStack(alignment: .trailing, spacing: 2) {
    191                 Text(cylinder.gas.label)
    192                     .foregroundStyle(cylinder.gas.isAir ? Color.secondary : Color.green)
    193                 if let start = cylinder.startBar, let end = cylinder.endBar {
    194                     Text(verbatim: "\(model.units.pressure(start)) → \(model.units.pressure(end))")
    195                         .font(.caption)
    196                         .foregroundStyle(.secondary)
    197                 }
    198             }
    199         }
    200     }
    201 }
    202 
    203 /// Edits one cylinder. The logbook is metric: pressures are converted to and from the units on screen.
    204 struct CylinderEditor: View {
    205     @Environment(AppModel.self) private var model
    206     @Binding var cylinder: Cylinder
    207 
    208     private static let presets: [(name: String, liters: Double, bar: Double)] = [
    209         ("AL80", 11.1, 207), ("AL63", 9.0, 207), ("AL40", 5.7, 207), ("HP100", 12.9, 237), ("HP130", 16.8, 237),
    210         ("10 L 232 bar", 10, 232), ("12 L 232 bar", 12, 232), ("15 L 232 bar", 15, 232),
    211     ]
    212 
    213     var body: some View {
    214         Form {
    215             Section {
    216                 TextField("Name (AL80, steel 100…)", text: $cylinder.description)
    217                 Menu {
    218                     ForEach(Self.presets, id: \.name) { preset in
    219                         Button(preset.name) {
    220                             cylinder.description = preset.name
    221                             cylinder.volumeLiters = preset.liters
    222                             cylinder.workPressureBar = preset.bar
    223                         }
    224                     }
    225                 } label: {
    226                     Label("Common cylinders", systemImage: "list.bullet")
    227                 }
    228                 field("Volume", $cylinder.volumeLiters, unit: "L", digits: 1)
    229                 field("Working pressure", pressure(\.workPressureBar), unit: model.units.pressureUnit, digits: 0)
    230             }
    231             Section("Gas") {
    232                 field("Oxygen", percent(\.o2Permille, empty: 0), unit: "%", digits: 0, prompt: "21")
    233                 field("Helium", percent(\.hePermille, empty: 0), unit: "%", digits: 0)
    234             }
    235             Section("Pressure") {
    236                 field("Start", pressure(\.startBar), unit: model.units.pressureUnit, digits: 0)
    237                 field("End", pressure(\.endBar), unit: model.units.pressureUnit, digits: 0)
    238             }
    239         }
    240         .navigationTitle(cylinder.description.isEmpty ? String(localized: "Cylinder") : cylinder.description)
    241         .navigationBarTitleDisplayMode(.inline)
    242     }
    243 
    244     private func field(_ title: LocalizedStringKey, _ value: Binding<Double?>, unit: String, digits: Int, prompt: String = "") -> some View {
    245         HStack {
    246             Text(title)
    247             Spacer()
    248             TextField(prompt, value: value, format: .number.precision(.fractionLength(0...digits)))
    249                 .keyboardType(.decimalPad)
    250                 .multilineTextAlignment(.trailing)
    251                 .frame(width: 90)
    252             Text(unit).foregroundStyle(.secondary).frame(minWidth: 28, alignment: .leading)
    253         }
    254     }
    255 
    256     private func pressure(_ path: WritableKeyPath<Cylinder, Double?>) -> Binding<Double?> {
    257         Binding {
    258             cylinder[keyPath: path].map { model.units.pressureValue($0).rounded() }
    259         } set: {
    260             cylinder[keyPath: path] = $0.flatMap { $0 > 0 ? model.units.barFromDisplay($0) : nil }
    261         }
    262     }
    263 
    264     /// A gas fraction, in percent on screen and per mille in the logbook (0 % of oxygen stands for air).
    265     private func percent(_ path: WritableKeyPath<GasMix, Int>, empty: Int) -> Binding<Double?> {
    266         Binding {
    267             let permille = cylinder.gas[keyPath: path]
    268             return permille > 0 ? Double(permille) / 10 : nil
    269         } set: {
    270             cylinder.gas[keyPath: path] = $0.map { Int(($0 * 10).rounded()).clamped(to: 0...1000) } ?? empty
    271         }
    272     }
    273 }
    274 
    275 private extension Int {
    276     func clamped(to range: ClosedRange<Int>) -> Int { Swift.min(Swift.max(self, range.lowerBound), range.upperBound) }
    277 }
    278 
    279 /// Picks an existing site, or creates a site from its name.
    280 struct SitePicker: View {
    281     @Environment(AppModel.self) private var model
    282     @Environment(\.dismiss) private var dismiss
    283     @Binding var selection: UInt32?
    284     @State private var search = ""
    285     @State private var creating = false
    286     @State private var newName = ""
    287     @State private var error: String?
    288 
    289     var body: some View {
    290         let sites = model.logbook.sites.values
    291             .filter { !$0.name.isEmpty && (search.isEmpty || $0.name.localizedCaseInsensitiveContains(search)) }
    292             .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
    293         List {
    294             Section {
    295                 Button { creating = true } label: { Label("New site…", systemImage: "plus.circle") }
    296                 Button { selection = nil; dismiss() } label: {
    297                     HStack {
    298                         Text("No site").foregroundStyle(Color.primary)
    299                         Spacer()
    300                         if selection == nil { Image(systemName: "checkmark") }
    301                     }
    302                 }
    303             }
    304             Section {
    305                 ForEach(sites) { site in
    306                     Button { selection = site.uuid; dismiss() } label: {
    307                         HStack {
    308                             VStack(alignment: .leading) {
    309                                 Text(site.name).foregroundStyle(Color.primary)
    310                                 if let country = site.country { Text(country).font(.caption).foregroundStyle(.secondary) }
    311                             }
    312                             Spacer()
    313                             if selection == site.uuid { Image(systemName: "checkmark") }
    314                         }
    315                     }
    316                 }
    317             }
    318         }
    319         .navigationTitle("Site")
    320         .searchable(text: $search, prompt: "Search for a site")
    321         .alert("New site", isPresented: $creating) {
    322             TextField("Site name", text: $newName)
    323             Button("Cancel", role: .cancel) { newName = "" }
    324             Button("Create") { create() }
    325         } message: {
    326             Text("The location can be added later in Subsurface.")
    327         }
    328         .alert("Action failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
    329             Button("OK", role: .cancel) {}
    330         } message: {
    331             Text(error ?? "")
    332         }
    333     }
    334 
    335     private func create() {
    336         let name = newName.trimmingCharacters(in: .whitespacesAndNewlines)
    337         newName = ""
    338         guard !name.isEmpty else { return }
    339         if let existing = model.logbook.sites.values.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) {
    340             selection = existing.uuid
    341             dismiss()
    342             return
    343         }
    344         let uuid = model.newSiteUUID()
    345         Task {
    346             do {
    347                 try await model.apply(.addSite(uuid: uuid, name: name, latitude: nil, longitude: nil))
    348                 selection = uuid
    349                 dismiss()
    350             } catch {
    351                 self.error = AppModel.describe(error)
    352             }
    353         }
    354     }
    355 }
    356 
    357 /// Manual entry of a dive made without a computer.
    358 struct NewDiveView: View {
    359     @Environment(AppModel.self) private var model
    360     @Environment(\.dismiss) private var dismiss
    361 
    362     @State private var date = Date()
    363     @State private var minutes = 40
    364     @State private var depthText = ""
    365     @State private var temperatureText = ""
    366     @State private var siteUUID: UInt32?
    367     @State private var buddy = ""
    368     @State private var notes = ""
    369     @State private var rating = 0
    370     @State private var saving = false
    371     @State private var error: String?
    372 
    373     var body: some View {
    374         NavigationStack {
    375             Form {
    376                 Section {
    377                     DatePicker("Start", selection: $date, in: ...Date.now)
    378                     Stepper(value: $minutes, in: 1...600) {
    379                         LabeledContent("Duration", value: String(localized: "\(minutes) min"))
    380                     }
    381                     LabeledContent("Max depth (\(model.units.depthUnit))") {
    382                         TextField("0", text: $depthText)
    383                             .keyboardType(.decimalPad)
    384                             .multilineTextAlignment(.trailing)
    385                     }
    386                     LabeledContent("Water (\(model.units.temperatureUnit))") {
    387                         TextField("–", text: $temperatureText)
    388                             .keyboardType(.numbersAndPunctuation)
    389                             .multilineTextAlignment(.trailing)
    390                     }
    391                 }
    392                 Section {
    393                     NavigationLink {
    394                         SitePicker(selection: $siteUUID)
    395                     } label: {
    396                         LabeledContent("Site", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? String(localized: "None"))
    397                     }
    398                     TextField("Buddy", text: $buddy)
    399                     StarPicker(title: "Rating", value: $rating)
    400                 }
    401                 Section("Notes") {
    402                     TextEditor(text: $notes).frame(minHeight: 100)
    403                 }
    404                 if let error {
    405                     Section { Text(error).foregroundStyle(.red) }
    406                 }
    407             }
    408             .navigationTitle("New dive")
    409             .navigationBarTitleDisplayMode(.inline)
    410             .toolbar {
    411                 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
    412                 ToolbarItem(placement: .confirmationAction) {
    413                     Button("Add", action: save).disabled(saving || depth == nil)
    414                 }
    415             }
    416         }
    417     }
    418 
    419     private func parse(_ text: String) -> Double? {
    420         Double(text.replacingOccurrences(of: ",", with: ".").trimmingCharacters(in: .whitespaces))
    421     }
    422 
    423     private var depth: Double? {
    424         guard let value = parse(depthText), value > 0 else { return nil }
    425         let meters = model.units.metersFromDisplay(value)
    426         return meters <= 350 ? meters : nil
    427     }
    428 
    429     private func save() {
    430         guard let depth else { return }
    431         saving = true
    432         var dive = NewDive(when: DiveDate.naive(from: date), number: model.logbook.nextNumber, durationSeconds: minutes * 60,
    433                            maxDepth: (depth * 10).rounded() / 10)
    434         dive.siteUUID = siteUUID
    435         dive.buddy = buddy.trimmingCharacters(in: .whitespacesAndNewlines)
    436         dive.notes = notes.trimmingCharacters(in: .whitespacesAndNewlines)
    437         dive.rating = rating
    438         if let t = parse(temperatureText) { dive.waterTemperature = (model.units.celsiusFromDisplay(t) * 10).rounded() / 10 }
    439         Task {
    440             do {
    441                 try await model.apply(.addDive(dive))
    442                 dismiss()
    443             } catch {
    444                 self.error = AppModel.describe(error)
    445                 saving = false
    446             }
    447         }
    448     }
    449 }