Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / UI / MainView.swift

MainView.swift332 lines · 13.4 KiBRaw
1import SwiftUI
2import MapKit
3import Combine
4
5/// Top-level screen. Mirrors Modern-Apps `MainPage.kt`: a top bar, a map, a bottom panel,
6/// and a floating add menu. Selection state (user or waypoint) drives the panels.
7@MainActor
8final class MainViewModel: ObservableObject {
9 @Published var users: [User] = []
10 @Published var waypoints: [Waypoint] = []
11 @Published var temporaryLinks: [TemporaryLink] = []
12 @Published var latestLocations: [Int64: LocationValue] = [:]
13
14 private var bag = Set<AnyCancellable>()
15
16 init() {
17 Database.shared.usersSubject
18 .receive(on: DispatchQueue.main)
19 .sink { [weak self] in self?.users = $0 }
20 .store(in: &bag)
21 Database.shared.waypointsSubject
22 .receive(on: DispatchQueue.main)
23 .sink { [weak self] in self?.waypoints = $0 }
24 .store(in: &bag)
25 Database.shared.temporaryLinksSubject
26 .receive(on: DispatchQueue.main)
27 .sink { [weak self] in self?.temporaryLinks = $0 }
28 .store(in: &bag)
29 Database.shared.latestLocationsSubject
30 .receive(on: DispatchQueue.main)
31 .sink { [weak self] in self?.latestLocations = $0 }
32 .store(in: &bag)
33 }
34}
35
36struct MainView: View {
37 @StateObject private var vm = MainViewModel()
38 @ObservedObject private var deepLink = DeepLinkRouter.shared
39
40 // Selection state
41 @State private var selectedUserId: Int64?
42 @State private var selectedWaypointId: Int64? // 0 means a new waypoint being created
43 @State private var isShowingPresent = true
44 @State private var historicalPosition: Coord?
45
46 // Waypoint editor state
47 @State private var waypointName = ""
48 @State private var waypointRange = "100"
49 @State private var waypointCoord = Coord.zero
50
51 // Dialogs
52 @State private var showShareInviteDialog = false
53 @State private var showAcceptPersonDialog = false
54 @State private var addPersonId: Int64?
55 /// Fingerprint from the invite link that set `addPersonId`, when it came from one.
56 @State private var addPersonFingerprint: String?
57 @State private var showAddLinkDialog = false
58 @State private var showMissingFeaturesDialog = false
59 @State private var showSecurityCode = false
60
61 @State private var mapCenter = MKCoordinateRegion(
62 center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
63 latitudinalMeters: 4000, longitudinalMeters: 4000
64 )
65 @State private var animateToCoord: Coord?
66
67 var body: some View {
68 NavigationStack {
69 VStack(spacing: 0) {
70 // Map fills remaining space, with FAB and HistoryBar overlaid.
71 ZStack(alignment: .bottomTrailing) {
72 MapContainer(
73 users: vm.users,
74 latestLocations: vm.latestLocations,
75 waypoints: vm.waypoints,
76 selectedUserId: selectedUserId,
77 selectedWaypoint: selectedWaypointPreview,
78 historicalPosition: isShowingPresent ? nil : historicalPosition,
79 onUserTap: { id in
80 selectedUserId = id
81 selectedWaypointId = nil
82 isShowingPresent = true
83 },
84 onMapTap: {
85 if selectedWaypointId == 0 {
86 // Don't deselect during waypoint creation.
87 } else {
88 selectedUserId = nil
89 selectedWaypointId = nil
90 }
91 },
92 onCenterChanged: { coord in
93 if selectedWaypointId == 0 {
94 waypointCoord = coord
95 }
96 },
97 animateToCoord: animateToCoord
98 )
99 if selectedUserId != nil {
100 HistoryBar(
101 userid: selectedUserId!,
102 isShowingPresent: $isShowingPresent,
103 historicalPosition: $historicalPosition
104 )
105 .frame(width: 105, height: 360, alignment: .bottomTrailing)
106 .padding(8)
107 }
108 addFAB
109 .padding(.trailing, 16)
110 .padding(.bottom, 16)
111 }
112 bottomPanel
113 }
114 .navigationTitle(Text(headerTitle))
115 .navigationBarTitleDisplayMode(.inline)
116 .toolbar { topBarToolbar }
117 .sheet(isPresented: $showShareInviteDialog) {
118 ShareInviteDialog(isPresented: $showShareInviteDialog)
119 }
120 .sheet(isPresented: $showAcceptPersonDialog, onDismiss: {
121 addPersonId = nil
122 addPersonFingerprint = nil
123 }) {
124 if let presetID = addPersonId {
125 AcceptPersonDialog(
126 presetID: presetID,
127 fingerprint: addPersonFingerprint,
128 isPresented: $showAcceptPersonDialog
129 )
130 }
131 }
132 .sheet(isPresented: $showAddLinkDialog) {
133 AddLinkDialog(isPresented: $showAddLinkDialog)
134 }
135 .sheet(isPresented: $showSecurityCode) {
136 if let uid = selectedUserId, let user = vm.users.first(where: { $0.id == uid }) {
137 SecurityCodeView(user: user, isPresented: $showSecurityCode)
138 }
139 }
140 .alert(Strings.missingFeaturesTitle, isPresented: $showMissingFeaturesDialog) {
141 Button(Strings.okButton, role: .cancel) {}
142 } message: { Text(Strings.missingFeaturesExplanation) }
143 .navigationDestination(for: User.self) { peer in
144 RangingView(peer: peer)
145 }
146 }
147 .onChange(of: selectedUserId) { _, new in
148 if let id = new, let coord = vm.latestLocations[id]?.coord {
149 animateToCoord = coord
150 }
151 }
152 .onChange(of: historicalPosition) { _, new in
153 if !isShowingPresent, let coord = new { animateToCoord = coord }
154 }
155 .onChange(of: selectedWaypointId) { _, new in
156 if let id = new, id != 0,
157 let wp = vm.waypoints.first(where: { $0.id == id }) {
158 animateToCoord = wp.coord
159 }
160 }
161 // A tapped findfamily://add/<id> invite prefills the accept dialog. @Published
162 // replays its current value on subscribe, so this catches cold-start links too.
163 .onReceive(deepLink.$pendingAddInvite.compactMap { $0 }) { invite in
164 addPersonId = invite.id
165 addPersonFingerprint = invite.fingerprint
166 showAcceptPersonDialog = true
167 deepLink.pendingAddInvite = nil
168 }
169 }
170
171 // MARK: - Top bar
172
173 @ToolbarContentBuilder
174 private var topBarToolbar: some ToolbarContent {
175 ToolbarItem(placement: .topBarLeading) {
176 if selectedUserId != nil || selectedWaypointId != nil {
177 Button {
178 selectedUserId = nil
179 selectedWaypointId = nil
180 } label: { Image(systemName: "chevron.backward") }
181 }
182 }
183 ToolbarItemGroup(placement: .topBarTrailing) {
184 if selectedUserId == nil && (selectedWaypointId == nil || selectedWaypointId == 0) {
185 BackupButtons()
186 } else if let uid = selectedUserId, uid != Networking.shared.userid,
187 let user = vm.users.first(where: { $0.id == uid }) {
188 Button {
189 showSecurityCode = true
190 } label: { Image(systemName: "checkmark.shield") }
191 Button(role: .destructive) {
192 Database.shared.deleteUser(user)
193 selectedUserId = nil
194 } label: { Image(systemName: "trash") }
195 } else if let wid = selectedWaypointId, wid != 0,
196 let wp = vm.waypoints.first(where: { $0.id == wid }) {
197 Button(role: .destructive) {
198 Database.shared.deleteWaypoint(wp)
199 selectedWaypointId = nil
200 } label: { Image(systemName: "trash") }
201 }
202 }
203 }
204
205 private var headerTitle: String {
206 if selectedUserId == nil && selectedWaypointId == nil { return Strings.appName }
207 return ""
208 }
209
210 // MARK: - FAB
211
212 @ViewBuilder
213 private var addFAB: some View {
214 if selectedUserId == nil && selectedWaypointId == nil {
215 AddMenu(
216 onShareInvite: {
217 showShareInviteDialog = true
218 },
219 onAddWaypoint: {
220 selectedWaypointId = 0
221 waypointName = ""
222 waypointRange = "100"
223 waypointCoord = Coord(
224 lat: mapCenter.center.latitude,
225 lon: mapCenter.center.longitude
226 )
227 },
228 onAddLink: {
229 showAddLinkDialog = true
230 }
231 )
232 } else if let wid = selectedWaypointId {
233 Button {
234 guard let rng = Double(waypointRange), !waypointName.isBlank else { return }
235 let existing = vm.waypoints.first(where: { $0.id == wid }) ?? Waypoint.newWaypoint
236 var w = existing
237 w.id = wid
238 w.name = waypointName
239 w.range = rng
240 w.coord = waypointCoord
241 _ = Database.shared.upsertWaypoint(w)
242 selectedWaypointId = nil
243 } label: {
244 Image(systemName: "checkmark")
245 .font(.title2)
246 .frame(width: 56, height: 56)
247 .background(Color.accentColor)
248 .foregroundStyle(.white)
249 .clipShape(Circle())
250 .shadow(radius: 4)
251 }
252 }
253 }
254
255 // MARK: - Bottom panel
256
257 /// Maximum height the bottom panel will grow to before scrolling.
258 private let bottomPanelMaxHeight: CGFloat = 360
259
260 @ViewBuilder
261 private var bottomPanel: some View {
262 Group {
263 if let uid = selectedUserId, let user = vm.users.first(where: { $0.id == uid }) {
264 UserDetailPanel(
265 user: user,
266 latest: vm.latestLocations[uid],
267 onChangeContact: { name, photo in
268 var u = user
269 u.name = name
270 u.photo = photo
271 Database.shared.upsertUser(u)
272 },
273 onToggleSending: { send in
274 // Manual toggle clears any pending auto-toggle (atomic, no clobber).
275 Database.shared.setSendingEnabledAndClearToggle(id: user.id, enabled: send)
276 },
277 onSetAutoToggle: { seconds in
278 let at = seconds.map { Date().addingTimeInterval($0) }
279 Database.shared.setSharingAutoToggleAt(id: user.id, at: at)
280 }
281 )
282 .padding(.vertical, 12)
283 .fixedSize(horizontal: false, vertical: true)
284 } else if selectedWaypointId != nil {
285 WaypointEditorPanel(name: $waypointName, range: $waypointRange)
286 .fixedSize(horizontal: false, vertical: true)
287 } else {
288 ScrollView {
289 DefaultList(
290 users: vm.users,
291 latestLocations: vm.latestLocations,
292 temporaryLinks: vm.temporaryLinks,
293 waypoints: vm.waypoints,
294 onSelectUser: { id in
295 selectedUserId = id
296 isShowingPresent = true
297 },
298 onSelectWaypoint: { wp in
299 selectedWaypointId = wp.id
300 waypointName = wp.name
301 waypointRange = String(Int(wp.range))
302 waypointCoord = wp.coord
303 },
304 onTapRequest: { id in
305 // An inbound sharing request, not an invite link, so there is
306 // no fingerprint to check against.
307 addPersonId = id
308 addPersonFingerprint = nil
309 showAcceptPersonDialog = true
310 }
311 )
312 }
313 .frame(maxHeight: bottomPanelMaxHeight)
314 }
315 }
316 .background(Color(.systemBackground))
317 }
318
319 private var selectedWaypointPreview: (coord: Coord, range: Double)? {
320 guard let wid = selectedWaypointId else { return nil }
321 let range = Double(waypointRange) ?? 0
322 if wid == 0 { return (waypointCoord, range) }
323 if let wp = vm.waypoints.first(where: { $0.id == wid }) {
324 return (waypointCoord == .zero ? wp.coord : waypointCoord, range)
325 }
326 return nil
327 }
328}
329
330private extension String {
331 var isBlank: Bool { trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
332}