SitesView.swift (10890B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import MapKit 3 import SubsurfaceLog 4 import SwiftUI 5 6 struct SitesView: View { 7 @Environment(AppModel.self) private var model 8 @State private var mode = LaunchOptions.flag("-sitesList") ? 1 : 0 9 @State private var selection: UInt32? 10 @State private var search = "" 11 12 private struct Entry: Identifiable { 13 let site: DiveSite 14 let count: Int 15 var id: UInt32 { site.uuid } 16 } 17 18 private struct Pin: Identifiable { 19 let entry: Entry 20 let hasPhotos: Bool 21 var id: String { "\(entry.site.uuid)-\(hasPhotos)" } 22 } 23 24 private var entries: [Entry] { 25 var counts = [UInt32: Int]() 26 for dive in model.logbook.dives { 27 if let uuid = dive.siteUUID { counts[uuid, default: 0] += 1 } 28 } 29 return model.logbook.sites.values 30 .filter { !$0.name.isEmpty || $0.hasLocation } 31 .map { Entry(site: $0, count: counts[$0.uuid] ?? 0) } 32 .sorted { $0.site.name.localizedCaseInsensitiveCompare($1.site.name) == .orderedAscending } 33 } 34 35 var body: some View { 36 NavigationStack { 37 let all = entries 38 Group { 39 if mode == 0 { 40 map(all.filter { $0.site.hasLocation }) 41 } else { 42 list(all) 43 } 44 } 45 .navigationTitle("Sites") 46 .navigationBarTitleDisplayMode(.inline) 47 .toolbar { 48 ToolbarItem(placement: .principal) { 49 Picker("View", selection: $mode) { 50 Text("Map").tag(0) 51 Text("List").tag(1) 52 } 53 .pickerStyle(.segmented) 54 .frame(width: 180) 55 } 56 } 57 .task(id: model.logbook.dives.count) { await model.refreshPhotoPresence() } 58 .navigationDestination(for: UInt32.self) { SiteDetailView(uuid: $0) } 59 .navigationDestination(for: String.self) { DiveDetailView(diveID: $0) } 60 } 61 } 62 63 private func map(_ located: [Entry]) -> some View { 64 Map(selection: $selection) { 65 // The identity of the pin changes with the presence of photos: otherwise the map keeps the old one. 66 ForEach(located.map { Pin(entry: $0, hasPhotos: model.sitesWithPhotos.contains($0.site.uuid)) }) { pin in 67 let entry = pin.entry 68 // A pink camera when the photo library has photos of a dive made here. 69 let hasPhotos = pin.hasPhotos 70 Marker(entry.site.name, systemImage: hasPhotos ? "camera.fill" : "water.waves", 71 coordinate: CLLocationCoordinate2D(latitude: entry.site.latitude ?? 0, longitude: entry.site.longitude ?? 0)) 72 .tint(hasPhotos ? Color.pink : Color.accentColor) 73 .tag(entry.site.uuid) 74 } 75 } 76 .mapStyle(.hybrid(elevation: .flat)) 77 .overlay { 78 if located.isEmpty { 79 ContentUnavailableView("No sites with a location", systemImage: "mappin.slash", 80 description: Text("Dive sites located in Subsurface will appear here.")) 81 .background(.regularMaterial) 82 } 83 } 84 .safeAreaInset(edge: .bottom) { 85 if let selection, let entry = located.first(where: { $0.site.uuid == selection }) { 86 NavigationLink(value: entry.site.uuid) { 87 HStack { 88 VStack(alignment: .leading, spacing: 2) { 89 Text(entry.site.name).font(.headline).foregroundStyle(Color.primary) 90 Text(countLabel(entry.count)).font(.caption).foregroundStyle(.secondary) 91 } 92 Spacer() 93 Image(systemName: "chevron.right").foregroundStyle(.secondary) 94 } 95 .padding() 96 .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) 97 .padding(.horizontal) 98 .padding(.bottom, 8) 99 } 100 } 101 } 102 } 103 104 private func list(_ all: [Entry]) -> some View { 105 let shown = search.isEmpty ? all : all.filter { 106 $0.site.name.localizedCaseInsensitiveContains(search) || ($0.site.country ?? "").localizedCaseInsensitiveContains(search) 107 } 108 return List(shown) { entry in 109 NavigationLink(value: entry.site.uuid) { 110 HStack { 111 VStack(alignment: .leading, spacing: 2) { 112 Text(entry.site.name.isEmpty ? String(localized: "Unnamed site") : entry.site.name) 113 if let country = entry.site.country { 114 Text(country).font(.caption).foregroundStyle(.secondary) 115 } 116 } 117 Spacer() 118 if model.sitesWithPhotos.contains(entry.site.uuid) { 119 Image(systemName: "camera.fill") 120 .font(.caption) 121 .foregroundStyle(.pink) 122 .accessibilityLabel("Has photos") 123 } 124 Text("\(entry.count)") 125 .font(.callout.monospacedDigit()) 126 .foregroundStyle(.secondary) 127 } 128 } 129 } 130 .searchable(text: $search, prompt: "Search sites") 131 .overlay { 132 if all.isEmpty { ContentUnavailableView("No sites", systemImage: "map") } 133 } 134 } 135 136 private func countLabel(_ count: Int) -> String { 137 count == 0 ? String(localized: "No dives") : (count == 1 ? String(localized: "1 dive") : String(localized: "\(count) dives")) 138 } 139 } 140 141 struct SiteDetailView: View { 142 @Environment(AppModel.self) private var model 143 let uuid: UInt32 144 @State private var photoAccess = PhotoAccess() 145 @State private var photos: [DivePhoto] = [] 146 @State private var photosLoading = false 147 @State private var photoZone = TimeZone.current 148 149 var body: some View { 150 let site = model.logbook.sites[uuid] 151 let dives = model.logbook.dives.filter { $0.siteUUID == uuid } 152 List { 153 if let site, let latitude = site.latitude, let longitude = site.longitude { 154 Section { 155 let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) 156 Map(initialPosition: .region(MKCoordinateRegion(center: coordinate, latitudinalMeters: 8000, longitudinalMeters: 8000))) { 157 Marker(site.name, systemImage: "water.waves", coordinate: coordinate).tint(Color.accentColor) 158 } 159 .mapStyle(.hybrid(elevation: .flat)) 160 .frame(height: 220) 161 .listRowInsets(EdgeInsets()) 162 LabeledContent("Position", value: String(format: "%.5f, %.5f", latitude, longitude)) 163 .textSelection(.enabled) 164 Button { 165 let item = MKMapItem(placemark: MKPlacemark(coordinate: coordinate)) 166 item.name = site.name 167 item.openInMaps() 168 } label: { 169 Label("Open in Maps", systemImage: "arrow.triangle.turn.up.right.diamond") 170 } 171 } 172 } 173 if let site, !site.description.isEmpty || !site.notes.isEmpty || site.country != nil { 174 Section("About") { 175 if let country = site.country { LabeledContent("Country", value: country) } 176 if !site.description.isEmpty { Text(site.description) } 177 if !site.notes.isEmpty { Text(site.notes).foregroundStyle(.secondary) } 178 } 179 } 180 if !dives.isEmpty { 181 Section("Summary") { 182 LabeledContent("Dives", value: "\(dives.count)") 183 LabeledContent("Deepest", value: model.units.depth(dives.map(\.maxDepth).max() ?? 0)) 184 LabeledContent("Time spent", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds })) 185 } 186 Section("Photos") { 187 PhotoStrip(access: photoAccess, photos: photos, loading: photosLoading, 188 emptyText: String(localized: "No photos of your dives here in this iPhone's photo library."), 189 onGranted: { Task { await loadPhotos(dives); await model.refreshPhotoPresence() } }, 190 caption: { photo in 191 photo.asset.creationDate?.formatted(Date.FormatStyle(date: .abbreviated, time: .shortened, timeZone: photoZone)) ?? "" 192 }) 193 } 194 Section("Dives") { 195 ForEach(dives) { dive in 196 NavigationLink(value: dive.id) { 197 HStack { 198 Text(dive.number > 0 ? "\(dive.number)" : "–") 199 .font(.footnote.monospacedDigit().weight(.semibold)) 200 .frame(minWidth: 30, alignment: .leading) 201 .foregroundStyle(Color.accentColor) 202 Text(DiveDate.day(dive)) 203 Spacer() 204 Text("\(model.units.depth(dive.maxDepth)) · \(Units.duration(dive.durationSeconds))") 205 .font(.callout.monospacedDigit()) 206 .foregroundStyle(.secondary) 207 } 208 } 209 } 210 } 211 } 212 } 213 .navigationTitle(site?.name ?? String(localized: "Site")) 214 .navigationBarTitleDisplayMode(.inline) 215 .task(id: dives.map(\.id)) { await loadPhotos(dives) } 216 } 217 218 /// Photos of all the dives made here, most recent first (at most 40 dives, 300 photos). 219 private func loadPhotos(_ dives: [Dive]) async { 220 guard photoAccess.granted else { return } 221 photosLoading = photos.isEmpty 222 let zone = await SiteTimeZone.zone(for: model.logbook.sites[uuid]) 223 photoZone = zone 224 var found = [DivePhoto]() 225 var seen = Set<String>() 226 for dive in dives.prefix(40) { 227 for photo in DivePhotoFinder.photos(for: dive, elapsed: dive.durationSeconds, zone: zone, limit: 60) where seen.insert(photo.id).inserted { 228 found.append(photo) 229 } 230 if found.count >= 300 { break } 231 } 232 photos = found 233 photosLoading = false 234 } 235 }