taler-ios

iOS apps for GNU Taler (wallet)
Log | Files | Refs | README | LICENSE

ExchangeListView.swift (8376B)


      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  */
      8 import SwiftUI
      9 import taler_swift
     10 import SymLog
     11 
     12 @MainActor
     13 fileprivate
     14 func addExchange(_ exchange: String, model: WalletModel) -> Void {
     15     Task { // runs on MainActor
     16         if let _ = try? await model.addExchange(uri: exchange) {
     17 //            symLog.log("added: \(exchange)")
     18 //            View.announce("added: \(exchange)")
     19             if UIAccessibility.isVoiceOverRunning {
     20                 UIAccessibility.post(notification: .announcement, argument: "added: \(exchange)")
     21             }
     22             Controller.shared.hapticNotification(.success)
     23             NotificationCenter.default.post(name: .ExchangeAdded, object: nil, userInfo: nil)
     24             NotificationCenter.default.post(name: .BalanceChange, object: nil, userInfo: nil)       // TODO: ExchangeAdded should suffice
     25         }
     26     }
     27 }
     28 
     29 /// This view shows the list of exchanges
     30 struct ExchangeListView: View {
     31     private let symLog = SymLogV(0)
     32     let stack: CallStack
     33     @Binding var url: URL?
     34 
     35     @EnvironmentObject private var model: WalletModel
     36     @EnvironmentObject private var controller: Controller
     37 #if DEBUG
     38     @AppStorage("developerMode") var developerMode: Bool = true
     39 #else
     40     @AppStorage("developerMode") var developerMode: Bool = false
     41 #endif
     42 
     43     @State private var showAlert: Bool = false
     44     @State private var urlTaken: Bool = false
     45     @State private var newExchange: String = EXCHANGE + DEMO        // without HTTPS
     46 
     47     func checkExchanges() {
     48         var hasNoDEMO = true
     49         var hasNoTEST = true
     50         for balance in controller.balances {
     51             if let baseUrl = balance.scopeInfo.url {
     52                 if baseUrl.contains(EXCHANGE + DEMO) {
     53                     hasNoDEMO = false
     54                 } else if baseUrl.contains(EXCHANGE + TEST) {
     55                     hasNoTEST = false
     56                 }
     57             }
     58         }
     59         newExchange = hasNoDEMO ? EXCHANGE + DEMO
     60                                 : hasNoTEST && developerMode ? EXCHANGE + TEST
     61                                                              : EMPTYSTRING
     62     }
     63 
     64     var body: some View {
     65         let a11yLabelStr = String(localized: "Add payment service", comment: "a11y for the + button")
     66         let plusButton = PlusButton(accessibilityLabelStr: a11yLabelStr) {
     67             showAlert = true
     68         }
     69         let addTitleStr = String(localized: "Add payment service", comment: "title of the addExchange alert")
     70         let addButtonStr = String(localized: "Add", comment: "button in the addExchange alert")
     71         let enterURL = String(localized: "Enter the URL")
     72         let listView = ExchangeListCommonV(symLog: symLog, stack: stack.push(),
     73                                       newExchange:  $newExchange,
     74                                    checkExchanges: checkExchanges)
     75                         .navigationTitle(TITLE_EXCHANGES)
     76                         .navigationBarItems(trailing: plusButton)
     77                         .task {
     78                             if let newUrl = url, !urlTaken {
     79                                 urlTaken = true         // make sure to do this only once
     80                                 newExchange = newUrl.trimmedString
     81                                 showAlert = true
     82                             } else {
     83                                 checkExchanges()
     84                             }
     85                         }
     86         if #available(iOS 16.4, *) {
     87             listView.alert(addTitleStr, isPresented: $showAlert) {
     88                     TextField("Address of the payment service", text: $newExchange)
     89                         .accessibilityLabel(enterURL)
     90 //                    .textFieldStyle(.roundedBorder)   Yikes: when adding style the alert will stop showing the textfield! Don't do this.
     91                     Button(addButtonStr) {
     92                         addExchange(newExchange, model: model)
     93                         DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
     94                             checkExchanges()
     95                         }
     96                     }
     97                     Button("Cancel", role: .cancel) { }
     98                 } message: {
     99                     Text(enterURL)
    100                         .accessibilityHidden(true)
    101                 }
    102         } else {    // iOS 15 cannot have a textfield in an alert, so we must
    103             listView
    104                 .textFieldAlert(isPresented: $showAlert,
    105                                       title: addTitleStr,
    106                                    doneText: addButtonStr,
    107                                        text: $newExchange) { text in
    108                     addExchange(text, model: model)
    109                 }
    110         }
    111     }
    112 }
    113 // MARK: -
    114 struct ExchangeListCommonV: View {
    115     let symLog: SymLogV?
    116     let stack: CallStack
    117     @Binding var newExchange: String
    118     let checkExchanges: () -> Void
    119 
    120     @EnvironmentObject private var controller: Controller
    121     @EnvironmentObject private var model: WalletModel
    122     @AppStorage("minimalistic") var minimalistic: Bool = false
    123     @AppStorage("myListStyle") var myListStyle: MyListStyle = .automatic
    124 #if DEBUG
    125     @AppStorage("developerMode") var developerMode: Bool = true
    126 #else
    127     @AppStorage("developerMode") var developerMode: Bool = false
    128 #endif
    129 
    130     var body: some View {
    131 #if PRINT_CHANGES
    132         let _ = Self._printChanges()
    133         let _ = symLog?.vlog()       // just to get the # to compare it with .onAppear & onDisappear
    134 #endif
    135 #if DEBUG
    136         let excSection = Section {
    137             let cyclos = "https://guava.box.fdold.eu"
    138             Button(cyclos) {
    139                 addExchange(cyclos, model: model)
    140             }
    141 
    142             let exchanges = ["glsint.fdold.eu", "taler.magnetbank.hu", "stage.taler-ops.ch", "e.netzbon-basel.ch"]
    143             ForEach(exchanges, id: \.self) { exchange in
    144                 let urlStr = "exchange." + exchange
    145                 Button(urlStr) {
    146                     addExchange(urlStr, model: model)
    147                 }
    148 //                Link(exchange, destination: URL(string: urlStr)!)
    149             }
    150         }
    151 #endif
    152         let balanceList = List {
    153             ForEachWithIndex(array: controller.balances) { index, balance in
    154                 ExchangeSectionView(stack: stack.push(),
    155                                   balance: balance,
    156                                  thousand: index * MAXEXCHANGES,        // unique ID
    157                             developerMode: developerMode) {
    158                     DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    159                         checkExchanges()
    160                     }
    161                 }
    162             }
    163 #if DEBUG
    164             if developerMode {
    165                 excSection
    166             }
    167 #endif
    168         }
    169 
    170         let emptyList = List {
    171             Section {
    172                 Text("There are no payment services yet.")
    173                     .talerFont(.title3)
    174             }
    175             Section {
    176                 let plus = Image(systemName: PLUS)
    177                 if !minimalistic {
    178                     Text("Tap the \(plus) button to add a service.")
    179                         .listRowSeparator(.hidden)
    180                     Text("You can also scan a withdrawal QR code from your bank in the Action menu to automatically add a payment service.")
    181                 } else {
    182                     Text("Tap \(plus) or scan a withdrawal QR code from your bank to add a payment service.")
    183                 }
    184             }
    185                 .talerFont(.body)
    186 #if DEBUG
    187             if developerMode {
    188                 excSection
    189             }
    190 #endif
    191         }
    192 
    193         Group {
    194             if controller.balances.isEmpty {
    195                 emptyList
    196             } else {
    197                 balanceList                 // sorted by wallet-core
    198             }
    199         }
    200         .listStyle(myListStyle.style).anyView
    201 //        .ignoresSafeArea(.keyboard, edges: .bottom)
    202         .refreshable {
    203             controller.hapticNotification(.success)
    204             symLog?.log("refreshing")
    205 //            await reloadExchanges()
    206             NotificationCenter.default.post(name: .BalanceChange, object: nil, userInfo: nil)
    207             DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    208                 checkExchanges()
    209             }
    210         }
    211         .onAppear() {
    212             DebugViewC.shared.setViewID(VIEW_PAYMENT_SERVICES, stack: stack.push())
    213         }
    214     } // body
    215 }