WalletMain.swift (23617B)
1 /* 2 * This file is part of GNU Taler, ©2022-26 Taler Systems S.A. 3 * See LICENSE.md 4 */ 5 /** 6 * @author Marc Stibane 7 * @author Iván Ávalos 8 */ 9 import SwiftUI 10 import os.log 11 import SymLog 12 import AVFoundation 13 import taler_swift 14 15 // MARK: - 16 struct ActionType: Hashable { 17 let animationDisabled: Bool 18 } 19 // MARK: - Content 20 21 struct WalletMain: View { 22 let logger: Logger 23 let stack: CallStack 24 @Binding var selectedBalance: Balance? 25 @Binding var talerFontIndex: Int 26 #if TALER_NIGHTLY 27 @Binding var sheetType: SheetType? 28 #else 29 @Binding var showActionSheet: Bool 30 @Binding var showScanner: Bool 31 #endif 32 @EnvironmentObject private var controller: Controller 33 @EnvironmentObject private var model: WalletModel 34 @EnvironmentObject private var tabBarModel: TabBarModel 35 @EnvironmentObject private var viewState: ViewState // popToRootView() 36 @EnvironmentObject private var viewState2: ViewState2 // popToRootView() 37 @EnvironmentObject private var wrapper: NamespaceWrapper 38 @Environment(\.accessibilityVoiceOverEnabled) private var voiceOverEnabled 39 #if DEBUG 40 @AppStorage("developerMode") var developerMode: Bool = true 41 #else 42 @AppStorage("developerMode") var developerMode: Bool = false 43 #endif 44 @AppStorage("minimalistic") var minimalistic: Bool = false 45 @AppStorage("tapped") var tapped: Int = 0 46 @AppStorage("dragged") var dragged: Int = 0 47 @AppStorage("oimEuro") var oimEuro: Bool = false 48 49 @State private var showBubble: Bool = true 50 @State private var shouldReloadBalances = 0 51 @State private var shouldReloadContacts = 0 52 @State private var shouldReloadMessages = 0 53 @State private var didRefreshMailbox: Bool = false 54 @State private var shouldReloadTransactions = 0 55 @State private var selectedTab: TalerTab = .balances 56 @State private var showKycAlert: Bool = false 57 @State private var kycURI: URL? 58 59 @State private var amountToTransfer = Amount.zero(currency: EMPTYSTRING) // Update currency when used 60 @State private var amountLastUsed = Amount.zero(currency: EMPTYSTRING) // Update currency when used 61 @State private var summary: String = EMPTYSTRING 62 @State private var iconID: String? = nil 63 @State private var showRealCashHint = true 64 65 private var openKycButton: some View { 66 Button("Legitimization") { 67 showKycAlert = false 68 if let kycURI { 69 UIApplication.shared.open(kycURI) 70 } else { 71 // YIKES! 72 } 73 } 74 } 75 76 private var dismissAlertButton: some View { 77 Button("Cancel", role: .cancel) { 78 showKycAlert = false 79 } 80 } 81 82 public var isShowing: Bool { 83 let notTapped = tapped < BUBBLE 84 let notDragged = dragged < BUBBLE && tapped >= TAPPED 85 return showBubble && (notTapped || notDragged) 86 } 87 88 // @available(iOS, deprecated: 26.0) 89 // \|/ this doesn't work - should give a compiler warning when called from 26+, but doesn't 90 @available(iOS, obsoleted: 26.0) 91 private func tabSelection() -> Binding<TalerTab> { 92 Binding { //this is the get block 93 self.selectedTab 94 } set: { tappedTab in 95 if tappedTab == self.selectedTab { 96 // User tapped on the tab twice == Pop to root view 97 switch tappedTab { 98 case .balances: 99 ViewState.shared.popToRootView(nil) 100 case .settings: 101 ViewState2.shared.popToRootView(nil) 102 case .actions: 103 if #available(iOS 26.0, *) { 104 logger.log(level: .debug, "TODO: show Action sheet again if it's not active already") 105 106 } else { 107 break 108 } 109 } 110 // if homeNavigationStack.isEmpty { 111 // User already on home view, scroll to top 112 // } else { 113 // pop to root 114 // homeNavigationStack = [] 115 // } 116 } else { // Set the tab to the tabbed tab 117 self.selectedTab = tappedTab 118 if #available(iOS 26.0, *) { 119 if tappedTab == .actions { 120 logger.log(level: .debug, "TODO: show Action sheet") 121 122 } 123 } // else the custom tabBar will handle the Action sheet 124 } 125 } 126 } 127 128 private var isBalances: Bool { self.selectedTab == .balances} 129 private func triggerAction(_ action: Int) { 130 tabBarModel.actionSelected = action < 0 ? action 131 : isBalances ? action // 1..4 132 : action + 4 // 5..8 133 } 134 135 private static func className() -> String {"\(self)"} 136 private static var name: String { Self.className() } 137 138 private var tabContent: some View { 139 /// Destinations for the 4 actions 140 let sendDest = SendAmountV(stack: stack.push(Self.name), 141 selectedBalance: $selectedBalance, // if nil shows currency picker 142 amountLastUsed: $amountLastUsed, // currency needs to be updated! 143 summary: $summary, 144 iconID: $iconID, 145 oimEuro: oimEuro) 146 let requestDest = RequestPayment(stack: stack.push(Self.name), 147 selectedBalance: selectedBalance, 148 amountLastUsed: $amountLastUsed, // currency needs to be updated! 149 summary: $summary, 150 iconID: $iconID, 151 oimEuro: oimEuro) 152 let depositDest = DepositSelectV(stack: stack.push(Self.name), 153 selectedBalance: selectedBalance, 154 amountLastUsed: $amountLastUsed) 155 let manualWithdrawDest = ManualWithdraw(stack: stack.push(Self.name), 156 url: nil, 157 selectedBalance: selectedBalance, 158 amountLastUsed: $amountLastUsed, // currency needs to be updated! 159 amountToTransfer: $amountToTransfer, 160 exchange: nil, // only for withdraw-exchange 161 maySwitchCurrencies: true, 162 isSheet: false) 163 /// tab titles 164 let balancesTitle = TalerTab.balances.title // "Balances" 165 let actionTitle = TalerTab.actions.title // "Actions" 166 let settingsTitle = TalerTab.settings.title // "Settings" 167 /// each NavigationView needs its own NavLinks 168 let balanceActions = Group { // actionSelected will hide the tabBar 169 NavLink(1, $tabBarModel.actionSelected) { sendDest } 170 NavLink(2, $tabBarModel.actionSelected) { requestDest } 171 NavLink(3, $tabBarModel.actionSelected) { depositDest } 172 NavLink(4, $tabBarModel.actionSelected) { manualWithdrawDest } 173 if #available(iOS 26.0, *) { 174 NavLink(-1, $tabBarModel.actionSelected) { 175 SettingsView(stack: stack.push(), 176 navTitle: settingsTitle) 177 } 178 } 179 } 180 let settingsActions = Group { 181 NavLink(5, $tabBarModel.actionSelected) { sendDest } 182 NavLink(6, $tabBarModel.actionSelected) { requestDest } 183 NavLink(7, $tabBarModel.actionSelected) { depositDest } 184 NavLink(8, $tabBarModel.actionSelected) { manualWithdrawDest } 185 } 186 /// NavigationViews for Balances & Settings 187 let balancesStack = NavigationView { 188 ZStack(alignment: .trailing) { 189 if controller.balances.isEmpty { 190 WalletEmptyHeader(stack: stack.push(), 191 showBubble: isShowing, 192 showRealCashHint: $showRealCashHint) 193 } else { 194 // if #available(iOS 17.0, *) { 195 // CarouselView(stack: stack.push(balancesTitle), 196 // selectedBalance: $selectedBalance, // needed for sheets, gets set in TransactionsListView 197 // reloadTransactions: $shouldReloadTransactions) 198 // } else { // Fallback on earlier versions 199 BalancesListView(stack: stack.push(balancesTitle), 200 title: balancesTitle, 201 showBubble: isShowing, 202 selectedBalance: $selectedBalance, // needed for sheets, gets set in TransactionsListView 203 showRealCashHint: $showRealCashHint, 204 reloadTransactions: $shouldReloadTransactions) 205 .accessibilitySortPriority(1) // Reads third 206 // } iOS 15 + 16 207 } 208 if #available(iOS 26.0, *) { 209 // floating Settings & Action buttons 210 let buttons = VStack(alignment: .trailing) { 211 if voiceOverEnabled { 212 SettingsButton26(sortPriority: 0) 213 } 214 Spacer() 215 ActionItem(stack: stack.push(), 216 tab: TalerTab.actions, 217 onTap: onActionTab, 218 onDrag: onActionDrag) 219 .accessibilitySortPriority(2) // Reads second 220 .matchedTransitionSource(id: "unique_transition_id", in: wrapper.namespace) 221 // .navigationTransition(.zoom(sourceID: "unique_transition_id", in: wrapper.namespace)) 222 } 223 .padding(.horizontal) 224 #if OIM 225 if !controller.oimModeActive { // hide for OIM 226 buttons 227 } 228 #else 229 ZStack(alignment: .bottomTrailing) { 230 buttons 231 ActionsBubble(showIt: $showBubble, isShowing: isShowing) 232 } // ZStack 233 #endif 234 } // iOS 26 235 }.background(balanceActions) 236 237 }.navigationViewStyle(.stack) 238 .accessibilitySortPriority(3) // Reads first 239 240 if #available(iOS 26.0, *) { 241 // no TabView, just a single NavigationView, containing the BalancesListView 242 // with floating Liquid Glass Actions button 243 return balancesStack.id(viewState.rootViewId) // change rootViewId to trigger popToRootView behaviour 244 } else { 245 // iOS 15..18: TabView with 3 tabs, middle is Actions 246 let settingsStack = NavigationView { 247 SettingsView(stack: stack.push(), 248 navTitle: settingsTitle) 249 .background(settingsActions) 250 }.navigationViewStyle(.stack) 251 /// invisible tabItems, used for a11y 252 let a11yBalanceTab = TalerTab.balances.label 253 .accessibilityLabel(balancesTitle) 254 .labelStyle(.titleOnly) 255 let a11yActionsTab = Label(TalerTab.actions) 256 .accessibilityLabel(actionTitle) 257 .labelStyle(.titleOnly) 258 let a11ySettingsTab = Label(TalerTab.settings) 259 .accessibilityLabel(settingsTitle) 260 .labelStyle(.titleOnly) 261 return TabView(selection: tabSelection()) { 262 balancesStack.id(viewState.rootViewId) // change rootViewId to trigger popToRootView behaviour 263 .tag(TalerTab.balances) 264 .tabItem { a11yBalanceTab } 265 Color.clear // can't use EmptyView: VoiceOver wouldn't have the Actions tab 266 .tag(TalerTab.actions) 267 .tabItem { a11yActionsTab } 268 settingsStack.id(viewState2.rootViewId) // change rootViewId to trigger popToRootView behaviour 269 .tag(TalerTab.settings) 270 .tabItem { a11ySettingsTab } 271 } // TabView 272 } 273 } 274 275 func onActionTab() { 276 logger.log("onActionTab: showActionSheet = true") 277 controller.removeURLs(after: 60*60) // TODO: specify time after which scanned URLs are deleted 278 withAnimation { 279 #if TALER_NIGHTLY 280 sheetType = .action 281 #else 282 showActionSheet = true 283 #endif 284 } 285 } 286 287 #if TALER_NIGHTLY 288 var showScanner: Bool { sheetType == .scanner } 289 #endif 290 func onActionDrag(_ stack: CallStack) { 291 if !showScanner { // gets called multiple times - log only once 292 #if DEBUG 293 if let caller = stack.peek() { 294 logger.log("showScanner = true (onActionDrag: \(caller.file):\(caller.function))") 295 } 296 #endif 297 withAnimation { 298 #if TALER_NIGHTLY 299 sheetType = .scanner 300 #else 301 showScanner = true 302 #endif 303 } 304 } 305 } 306 307 func tabBarView() -> some View { 308 // iOS 15..18: custom tabBar (with Actions button) is rendered on top of the TabView, 309 // and overlays the native iOS tabBar (which is still used for VoiceOver) 310 TabBarView(stack: stack.push(), 311 selection: tabSelection(), 312 hidden: $tabBarModel.tabBarHidden, 313 onActionTab: onActionTab, 314 onActionDrag: onActionDrag) 315 .ignoresSafeArea(.keyboard, edges: .bottom) 316 .accessibilityHidden(true) // for a11y we use the original tabBar, not our custom one 317 } 318 319 var body: some View { 320 #if PRINT_CHANGES 321 // "@self" marks that the view value itself has changed, and "@identity" marks that the 322 // identity of the view has changed (that is, that the persistent data associated with 323 // the view has been recycled for a new instance of the same type) 324 if #available(iOS 17.1, *) { 325 // logs at INFO level, “com.apple.SwiftUI” subsystem, category “Changed Body Properties” 326 let _ = Self._logChanges() 327 } else { 328 let _ = Self._printChanges() 329 } 330 #endif 331 ZStack(alignment: .bottom) { 332 tabContent // incl. the (transparent) SwiftUI tabBar 333 if #unavailable(iOS 26.0) { 334 tabBarView() 335 ActionsBubble(showIt: $showBubble, isShowing: isShowing) 336 } 337 } // ZStack 338 .frame(maxWidth: .infinity, maxHeight: .infinity) 339 .onNotification(.SendAction) { notification in 340 if let actionType = notification.userInfo?[NOTIFICATIONANIMATION] as? ActionType { 341 if actionType.animationDisabled { 342 var transaction = Transaction() 343 transaction.disablesAnimations = true 344 withTransaction(transaction) { 345 triggerAction(1) 346 } 347 } else { triggerAction(1) } 348 } else { triggerAction(1) } 349 } 350 .onNotification(.RequestAction) { triggerAction(2) } 351 .onNotification(.DepositAction) { triggerAction(3) } 352 .onNotification(.WithdrawAction){ triggerAction(4) } 353 .onNotification(.SettingsAction){ triggerAction(-1) } 354 .onNotification(.KYCrequired) { notification in 355 // show an alert with the KYC link (button) which opens in Safari 356 if let transition = notification.userInfo?[TRANSACTIONTRANSITION] as? TransactionTransition { 357 if let kycString = transition.experimentalUserData { 358 if let urlForKYC = URL(string: kycString) { 359 logger.log(".onNotification(.KYCrequired): \(kycString)") 360 kycURI = urlForKYC 361 showKycAlert = true 362 } 363 } else { 364 // TODO: no KYC URI 365 } 366 } 367 } 368 .onNotification(.ShareAction){ notification in 369 if let actionData = notification.userInfo?[NOTIFICATIONSHARE] as? ShareType { 370 let textToShare = actionData.textToShare 371 let image = actionData.image 372 ShareSheet.shareSheet(textToShare: textToShare, image: image) 373 } 374 } 375 .alert("You need to pass a legitimization procedure.", 376 isPresented: $showKycAlert, 377 actions: { openKycButton 378 dismissAlertButton }, 379 message: { Text("Tap the button to go to the legitimization website.") }) 380 .onNotification(.BalanceChange) { notification in 381 logger.info(".onNotification(.BalanceChange) ==> reload balances") 382 // if let date = notification.userInfo?[NOTIFICATIONTIME] as? Date { 383 // 384 // } 385 shouldReloadBalances += 1 386 } 387 .onNotification(.ContactAdded) { 388 shouldReloadContacts += 1 389 } 390 .onNotification(.MailboxMessageAdded) { 391 shouldReloadMessages += 1 392 } 393 .onNotification(.TransactionDeleted) { notification in 394 logger.info(".onNotification(.TransactionDeleted) ==> reload balances") 395 shouldReloadTransactions += 1 396 } 397 .onNotification(.TransactionExpired) { notification in 398 logger.info(".onNotification(.TransactionExpired) ==> reload balances") 399 shouldReloadTransactions += 1 400 } 401 .onNotification(.TransactionScanned) { 402 shouldReloadTransactions += 1 403 } 404 .onNotification(.TransactionDone) { 405 shouldReloadTransactions += 1 406 // selectedTab = .balances // automatically switch to Balances 407 } 408 .onNotification(.TransactionError) { notification in 409 // TODO: reload pending ?? 410 } 411 .onNotification(.GeneralError) { notification in 412 if let error = notification.userInfo?[NOTIFICATIONERROR] as? Error { 413 model.setError(error) 414 controller.playSound(0) 415 } 416 } 417 .task(id: shouldReloadBalances) { // runs once at launch, then on each .BalanceChange 418 // symLog.log(".task shouldReloadBalances \(shouldReloadBalances)") 419 await controller.loadBalances(stack.push("refreshing balances")) 420 await controller.loadDiscounts(stack.push("refreshing discounts")) 421 await controller.loadSubscriptions(stack.push("refreshing passes")) 422 } // task 423 .task(id: shouldReloadContacts) { // runs once at launch, then on each .ContactAdded 424 await contactsThenMailbox(stack.push("shouldReloadContacts: \(shouldReloadContacts)")) 425 } 426 .task(id: shouldReloadMessages) { // runs once at launch, then on each .MailboxMessageAdded 427 if shouldReloadMessages > 0 { // skip the one at launch 428 await controller.refreshMailbox(stack.push("refreshing mailbox")) 429 } 430 } 431 } // body 432 433 private func contactsThenMailbox(_ stack: CallStack) async { 434 if let count = await controller.loadContacts(stack.push("refreshing contacts")) { 435 if count != 0 { 436 // on cold launch we see how many contacts we have 437 // later how many changed, negative if any got deleted 438 } 439 } 440 441 if !didRefreshMailbox { // do this only once 442 didRefreshMailbox = true 443 await controller.refreshMailbox(stack.push("refreshing mailbox")) 444 } 445 } 446 } // Content 447 // MARK: - Bubble 448 struct ActionsBubble: View { 449 @Binding var showIt: Bool 450 let isShowing: Bool 451 @AppStorage("tapped") var tapped: Int = 0 452 453 var body: some View { 454 if isShowing { 455 VStack { 456 Text(tapped < BUBBLE ? "Tap the Actions button to start transactions, or scan a QR code." 457 : "Drag the Actions button upwards to directly start the QR scanner.") 458 .talerFont(.title) 459 .padding(10) 460 .foregroundColor(WalletColors().onPrimary) 461 .padding(.bottom, 20) 462 } .padding(.horizontal, 30) 463 .background { 464 BubblePath() 465 .fill(WalletColors().primaryAccent.opacity(0.6)) 466 .padding(.horizontal, 30) 467 } 468 .padding(.bottom, Bool.iOS26 ? 70 : 90) 469 .contentShape(.rect) 470 .onTapGesture { 471 showIt = false 472 } 473 } 474 } 475 } 476 struct BubblePath: Shape { 477 let is26 = Bool.iOS26 // true: point to the bottom right, false: point to the middle 478 func path(in rect: CGRect) -> Path { 479 var path = Path() 480 481 let cornerRadius: CGFloat = is26 ? 20: 12 482 let arrowWidth: CGFloat = 40 483 let arrowHeight: CGFloat = 20 484 485 path.move(to: CGPoint(x: cornerRadius, y: 0)) // top-left 486 path.addLine(to: CGPoint(x: rect.width - cornerRadius, y: 0)) // top-right 487 path.addArc(center: CGPoint(x: rect.width - cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false) 488 if is26 { 489 path.addLine(to: CGPoint(x: rect.width, 490 y: rect.height - arrowHeight)) // bottom-right 491 path.addLine(to: CGPoint(x: rect.width - arrowWidth / 2, 492 y: rect.height)) 493 path.addLine(to: CGPoint(x: rect.width - arrowWidth, 494 y: rect.height - arrowHeight)) 495 } else { 496 path.addLine(to: CGPoint(x: rect.width, 497 y: rect.height - cornerRadius - arrowHeight)) // bottom-right 498 path.addArc(center: CGPoint(x: rect.width - cornerRadius, 499 y: rect.height - cornerRadius - arrowHeight), 500 radius: cornerRadius, startAngle: Angle(degrees: 0), 501 endAngle: Angle(degrees: 90), clockwise: false) 502 path.addLine(to: CGPoint(x: rect.width / 2 + arrowWidth / 2, 503 y: rect.height - arrowHeight)) 504 path.addLine(to: CGPoint(x: rect.width / 2, y: rect.height)) 505 path.addLine(to: CGPoint(x: rect.width / 2, y: rect.height)) 506 path.addLine(to: CGPoint(x: rect.width / 2 - arrowWidth / 2, y: rect.height - arrowHeight)) 507 } 508 path.addLine(to: CGPoint(x: cornerRadius, y: rect.height - arrowHeight)) // bottom-left 509 path.addArc(center: CGPoint(x: cornerRadius, y: rect.height - cornerRadius - arrowHeight), radius: cornerRadius, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false) 510 path.addLine(to: CGPoint(x: 0, y: cornerRadius)) 511 path.addArc(center: CGPoint(x: cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false) 512 513 return path 514 } 515 }