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

CardsView.swift (13979B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import PhotosUI
      3 import SwiftUI
      4 import UIKit
      5 
      6 /// The certification cards: one row per card, a tap shows it full size (to hand the iPhone over at a dive shop).
      7 struct CardsView: View {
      8     @Environment(CardStore.self) private var store
      9     @State private var editing: CertificationCard?
     10     @State private var shown: CertificationCard?
     11 
     12     var body: some View {
     13         List {
     14             if store.cards.isEmpty {
     15                 ContentUnavailableView("No cards yet", systemImage: "person.text.rectangle",
     16                                        description: Text("Add your certification cards, with a photo of each side, to have them with you."))
     17             }
     18             ForEach(store.cards) { card in
     19                 Button { shown = card } label: { CardRow(card: card) }
     20                     .buttonStyle(.plain)
     21                     .swipeActions {
     22                         Button("Delete", role: .destructive) { store.delete(card) }
     23                         Button("Edit") { editing = card }
     24                     }
     25             }
     26             Section {
     27                 Button { editing = CertificationCard() } label: { Label("Add a card", systemImage: "plus.circle") }
     28             } footer: {
     29                 BackupFootnote()
     30             }
     31         }
     32         .listStyle(.insetGrouped)
     33         .navigationTitle("Certification cards")
     34         .navigationBarTitleDisplayMode(.inline)
     35         .sheet(item: $editing) { CardEditView(card: $0) }
     36         .fullScreenCover(item: $shown) { card in
     37             CardFullScreen(cardID: card.id) { editing = $0 }
     38         }
     39         .onAppear {
     40             store.sync()
     41             if LaunchOptions.flag("-showCard"), let first = store.cards.last { shown = first }
     42             if LaunchOptions.flag("-editCard"), let first = store.cards.last { editing = first }
     43         }
     44     }
     45 }
     46 
     47 /// Where the cards are kept, in one line.
     48 struct BackupFootnote: View {
     49     @Environment(CardStore.self) private var store
     50 
     51     var body: some View {
     52         switch store.backup {
     53         case .unknown, .working:
     54             Text("Checking the iCloud backup…")
     55         case .notBuiltIn:
     56             Text("The cards are kept on this iPhone, and in its iPhone backup. The automatic copy to iCloud Drive comes in a later version.")
     57         case .unavailable:
     58             Text("The cards are only on this iPhone: sign in to iCloud and turn iCloud Drive on to have them backed up automatically.")
     59         case .done(let date):
     60             Text("Backed up automatically in iCloud Drive (\(date.formatted(date: .abbreviated, time: .shortened))). They come back on a new iPhone signed in to the same account.")
     61         case .failed(let message):
     62             Text("The iCloud backup failed: \(message)")
     63         }
     64     }
     65 }
     66 
     67 struct CardRow: View {
     68     @Environment(CardStore.self) private var store
     69     let card: CertificationCard
     70 
     71     var body: some View {
     72         HStack(spacing: 12) {
     73             let _ = store.photoVersion
     74             Group {
     75                 if let image = store.photo(of: card, side: .front) ?? store.photo(of: card, side: .back) {
     76                     Image(uiImage: image).resizable().scaledToFill()
     77                 } else {
     78                     ZStack {
     79                         Color.accentColor.opacity(0.15)
     80                         Image(systemName: "person.text.rectangle").foregroundStyle(Color.accentColor)
     81                     }
     82                 }
     83             }
     84             .frame(width: 72, height: 46)
     85             .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
     86             VStack(alignment: .leading, spacing: 3) {
     87                 Text(card.title.isEmpty ? String(localized: "Certification") : card.title)
     88                     .font(.body.weight(.medium))
     89                 Text([card.agency, card.number].filter { !$0.isEmpty }.joined(separator: " · "))
     90                     .font(.caption)
     91                     .foregroundStyle(.secondary)
     92             }
     93             Spacer(minLength: 8)
     94             if let date = card.issuedDate {
     95                 Text(date.formatted(Date.FormatStyle(timeZone: TimeZone(identifier: "UTC")!).year()))
     96                     .font(.caption.monospacedDigit())
     97                     .foregroundStyle(.secondary)
     98             }
     99         }
    100         .padding(.vertical, 2)
    101         .contentShape(Rectangle())
    102     }
    103 }
    104 
    105 /// The card on the whole screen, front then back, on a dark background.
    106 struct CardFullScreen: View {
    107     @Environment(CardStore.self) private var store
    108     @Environment(\.dismiss) private var dismiss
    109     let cardID: UUID
    110     let onEdit: (CertificationCard) -> Void
    111 
    112     var body: some View {
    113         NavigationStack {
    114             ScrollView {
    115                 if let card = store.card(id: cardID) {
    116                     VStack(spacing: 16) {
    117                         let _ = store.photoVersion
    118                         ForEach(CertificationCard.Side.allCases, id: \.self) { side in
    119                             if let image = store.photo(of: card, side: side) {
    120                                 Image(uiImage: image)
    121                                     .resizable()
    122                                     .scaledToFit()
    123                                     .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
    124                             }
    125                         }
    126                         VStack(spacing: 6) {
    127                             Text(card.title).font(.title3.weight(.semibold))
    128                             Text(card.agency).foregroundStyle(.secondary)
    129                             if !card.number.isEmpty {
    130                                 Text(card.number)
    131                                     .font(.title2.monospaced().weight(.medium))
    132                                     .textSelection(.enabled)
    133                             }
    134                             if let date = card.issuedDate {
    135                                 Text(date.formatted(Date.FormatStyle(timeZone: TimeZone(identifier: "UTC")!).day().month(.wide).year()))
    136                                     .font(.callout)
    137                                     .foregroundStyle(.secondary)
    138                             }
    139                             if !card.notes.isEmpty { Text(card.notes).font(.callout).multilineTextAlignment(.center) }
    140                         }
    141                         .frame(maxWidth: .infinity)
    142                         .padding()
    143                     }
    144                     .padding()
    145                 }
    146             }
    147             .toolbar {
    148                 ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } }
    149                 ToolbarItem(placement: .confirmationAction) {
    150                     Button("Edit") {
    151                         guard let card = store.card(id: cardID) else { return }
    152                         dismiss()
    153                         // The edit sheet belongs to the list, which can only show it once this cover is gone.
    154                         DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { onEdit(card) }
    155                     }
    156                 }
    157             }
    158         }
    159     }
    160 }
    161 
    162 struct CardEditView: View {
    163     @Environment(CardStore.self) private var store
    164     @Environment(\.dismiss) private var dismiss
    165     @State var card: CertificationCard
    166     @State private var hasDate = false
    167     @State private var date = Date()
    168     @State private var loaded = false
    169     /// Photos picked in this sheet, written when the card is saved (nil inside: photo removed).
    170     @State private var picked: [CertificationCard.Side: UIImage?] = [:]
    171 
    172     private static let agencies = ["PADI", "SSI", "NAUI", "CMAS", "FQAS", "ACUC", "SDI", "TDI", "GUE", "IANTD", "RAID", "BSAC", "DAN"]
    173 
    174     private var isNew: Bool { store.card(id: card.id) == nil }
    175 
    176     var body: some View {
    177         NavigationStack {
    178             Form {
    179                 Section {
    180                     HStack {
    181                         TextField("Agency", text: $card.agency)
    182                             .textInputAutocapitalization(.characters)
    183                             .autocorrectionDisabled()
    184                         Menu {
    185                             ForEach(Self.agencies, id: \.self) { name in Button(name) { card.agency = name } }
    186                         } label: {
    187                             Image(systemName: "chevron.up.chevron.down").foregroundStyle(.secondary)
    188                         }
    189                     }
    190                     TextField("Certification (Advanced Open Water…)", text: $card.title)
    191                     TextField("Card number", text: $card.number)
    192                         .autocorrectionDisabled()
    193                         .textInputAutocapitalization(.characters)
    194                     Toggle("Date issued", isOn: $hasDate.animation())
    195                     if hasDate {
    196                         DatePicker("Date issued", selection: $date, in: ...Date(), displayedComponents: .date)
    197                             .labelsHidden()
    198                             .environment(\.timeZone, TimeZone(identifier: "UTC")!)
    199                     }
    200                 }
    201                 Section("Front") { photoRow(.front) }
    202                 Section("Back") { photoRow(.back) }
    203                 Section("Notes") {
    204                     TextField("Instructor, dive centre…", text: $card.notes, axis: .vertical)
    205                         .lineLimit(1...4)
    206                 }
    207             }
    208             .navigationTitle(isNew ? String(localized: "New card") : String(localized: "Card"))
    209             .navigationBarTitleDisplayMode(.inline)
    210             .toolbar {
    211                 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
    212                 ToolbarItem(placement: .confirmationAction) {
    213                     Button("Save", action: save)
    214                         .disabled(card.agency.isEmpty && card.title.isEmpty && card.number.isEmpty && picked.isEmpty)
    215                 }
    216             }
    217             .onAppear {
    218                 guard !loaded else { return }
    219                 loaded = true
    220                 if let issued = card.issuedDate {
    221                     hasDate = true
    222                     date = issued
    223                 }
    224             }
    225         }
    226     }
    227 
    228     private func image(_ side: CertificationCard.Side) -> UIImage? {
    229         if let change = picked[side] { return change }
    230         return store.photo(of: card, side: side)
    231     }
    232 
    233     @ViewBuilder private func photoRow(_ side: CertificationCard.Side) -> some View {
    234         if let image = image(side) {
    235             Image(uiImage: image)
    236                 .resizable()
    237                 .scaledToFit()
    238                 .frame(maxHeight: 190)
    239                 .frame(maxWidth: .infinity)
    240                 .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
    241         }
    242         PhotoSourceButtons(hasPhoto: image(side) != nil) { picked[side] = .some($0) }
    243     }
    244 
    245     private func save() {
    246         var saved = card
    247         saved.agency = saved.agency.trimmingCharacters(in: .whitespacesAndNewlines)
    248         saved.title = saved.title.trimmingCharacters(in: .whitespacesAndNewlines)
    249         saved.number = saved.number.trimmingCharacters(in: .whitespacesAndNewlines)
    250         saved.issuedDate = hasDate ? date : nil
    251         for (side, image) in picked {
    252             store.setPhoto(image, of: saved, side: side)
    253             if side == .front { saved.hasFront = image != nil } else { saved.hasBack = image != nil }
    254         }
    255         store.save(saved)
    256         dismiss()
    257     }
    258 }
    259 
    260 /// "Take a photo", "Choose a photo" and, when there is one, "Remove".
    261 private struct PhotoSourceButtons: View {
    262     let hasPhoto: Bool
    263     /// The new photo, or nil to remove the current one.
    264     let onChange: (UIImage?) -> Void
    265     @State private var item: PhotosPickerItem?
    266     @State private var usingCamera = false
    267 
    268     var body: some View {
    269         HStack(spacing: 18) {
    270             if UIImagePickerController.isSourceTypeAvailable(.camera) {
    271                 Button { usingCamera = true } label: { Label("Take a photo", systemImage: "camera") }
    272             }
    273             PhotosPicker(selection: $item, matching: .images) { Label("Choose a photo", systemImage: "photo") }
    274             if hasPhoto {
    275                 Spacer(minLength: 0)
    276                 Button(role: .destructive) { onChange(nil) } label: { Image(systemName: "trash") }
    277                     .accessibilityLabel("Remove the photo")
    278             }
    279         }
    280         // Several buttons in one row of a form: each must answer for itself.
    281         .buttonStyle(.borderless)
    282         .font(.callout)
    283         .onChange(of: item) {
    284             guard let item else { return }
    285             Task {
    286                 if let data = try? await item.loadTransferable(type: Data.self), let image = UIImage(data: data) { onChange(image) }
    287                 self.item = nil
    288             }
    289         }
    290         .fullScreenCover(isPresented: $usingCamera) {
    291             CameraPicker { image in
    292                 usingCamera = false
    293                 if let image { onChange(image) }
    294             }
    295             .ignoresSafeArea()
    296         }
    297     }
    298 }
    299 
    300 private struct CameraPicker: UIViewControllerRepresentable {
    301     let onDone: (UIImage?) -> Void
    302 
    303     func makeUIViewController(context: Context) -> UIImagePickerController {
    304         let picker = UIImagePickerController()
    305         picker.sourceType = .camera
    306         picker.delegate = context.coordinator
    307         return picker
    308     }
    309 
    310     func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}
    311 
    312     func makeCoordinator() -> Coordinator { Coordinator(onDone: onDone) }
    313 
    314     final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    315         let onDone: (UIImage?) -> Void
    316         init(onDone: @escaping (UIImage?) -> Void) { self.onDone = onDone }
    317 
    318         func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
    319             onDone(info[.originalImage] as? UIImage)
    320         }
    321 
    322         func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { onDone(nil) }
    323     }
    324 }