summaryrefslogtreecommitdiff
path: root/TalerWallet1/Views/Main/MainView.swift
blob: 9d7effe4553371d19dba186d9a7bbecb5ab9a00a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
 * This file is part of GNU Taler, ©2022-23 Taler Systems S.A.
 * See LICENSE.md
 */
/**
 * @author Marc Stibane
 * @author Iván Ávalos
 */
import SwiftUI
import os.log
import SymLog

// Use this to delay instantiation when using `NavigationLink`, etc...
struct LazyView<Content: View>: View {
    var content: () -> Content
    var body: some View {
        self.content()
    }
}

struct MainView: View {
    private let symLog = SymLogV(0)
    let logger: Logger
    let stack: CallStack
    @Binding var soundPlayed: Bool

#if DEBUG
    @AppStorage("developerMode") var developerMode: Bool = true
#else
    @AppStorage("developerMode") var developerMode: Bool = false
#endif

    @EnvironmentObject private var controller: Controller
    @EnvironmentObject private var model: WalletModel
    @AppStorage("talerFontIndex") var talerFontIndex: Int = 0       // extension mustn't define this, so it must be here
    @AppStorage("playSoundsI") var playSoundsI: Int = 1             // extension mustn't define this, so it must be here
    @AppStorage("playSoundsB") var playSoundsB: Bool = false

    @State private var sheetPresented = false
    @State private var urlToOpen: URL? = nil

    func sheetDismissed() -> Void {
        logger.info("sheet dismiss")
    }
    var body: some View {
#if PRINT_CHANGES
        let _ = Self._printChanges()
        let _ = symLog.vlog()       // just to get the # to compare it with .onAppear & onDisappear
#endif
        Group {
            if controller.backendState == .ready {
                Content(logger: logger, stack: stack.push("Content"), talerFontIndex: $talerFontIndex)
                    .onAppear() {
#if DEBUG
                        if playSoundsI != 0  && playSoundsB && !soundPlayed {
                            controller.playSound(1008)     // Startup chime
                        }
#endif
                        soundPlayed = true
                    }
            } else if controller.backendState == .error {
                ErrorView(errortext: nil)            // TODO: show Error View
            } else {
                LaunchAnimationView()
            }
        }
        .animation(.linear(duration: LAUNCHDURATION), value: controller.backendState)
        .overlay(alignment: .top) {
            // Show the viewID on top of the app's NavigationView
            DebugViewV()
                .id("ViewID")
        }
        .onOpenURL { url in
            symLog.log(".onOpenURL: \(url)")
            // will be called on a taler:// scheme either
            // by user tapping such link in a browser (bank website)
            // or when launching the app from iOS Camera.app scanning a QR code
            urlToOpen = url     // raise sheet
        }
        .sheet(item: $urlToOpen, onDismiss: sheetDismissed) { url in
            let sheet = AnyView(URLSheet(stack: stack.push(), urlToOpen: url))
            Sheet(sheetView: sheet)
        }
        .sheet(isPresented: $model.showError) {
            model.cleanError()
        } content: {
            if let error = model.error {
                ErrorSheet(data: error, devMode: developerMode) {
                    model.cleanError()
                }.interactiveDismissDisabled()
            }
        }
    } // body
}
// MARK: - TabBar
enum Tab {
    case balances
#if false
    case exchanges
#endif
    case settings
}

// MARK: - Content
extension MainView {
    struct Content: View {
        let logger: Logger
        let stack: CallStack
        @State private var shouldReloadBalances = 0
        @State private var balances: [Balance] = []
        @Binding var talerFontIndex: Int
        @AppStorage("minimalistic") var minimalistic: Bool = false
        @EnvironmentObject private var controller: Controller
        @EnvironmentObject private var model: WalletModel
        @EnvironmentObject private var viewState: ViewState     // popToRootView()
        @EnvironmentObject private var viewState2: ViewState2     // popToRootView()
        let balancesTitle = String(localized: "TitleBalances", defaultValue: "Balances")
//        let exchangesTitle = String(localized: "TitleExchanges", defaultValue: "Banking")
        let settingsTitle = String(localized: "TitleSettings", defaultValue: "Settings")
        @State private var selectedTab: Tab = .balances
        @State private var showKycAlert: Bool = false
        @State private var kycURI: URL?

#if DEBUG
        @AppStorage("developerMode") var developerMode: Bool = true
#else
        @AppStorage("developerMode") var developerMode: Bool = false
#endif

        private var openKycButton: some View {
            Button("KYC") {
                showKycAlert = false
                if let kycURI {
                    UIApplication.shared.open(kycURI)
                } else {
                    // YIKES!
                }
            }
        }
        private var dismissAlertButton: some View {
            Button("Cancel", role: .cancel) {
                showKycAlert = false
            }
        }

        private func tabSelection() -> Binding<Tab> {
            Binding { //this is the get block
                self.selectedTab
            } set: { tappedTab in
                if tappedTab == self.selectedTab {
                    // User tapped on the tab twice == Pop to root view
                    switch tappedTab {
                        case .balances:
                            ViewState.shared.popToRootView(nil)
//                        case .exchanges:
//                            ViewState2.shared.popToRootView(nil)
                        default:
                            break
                    }
//                    if homeNavigationStack.isEmpty {
                        //User already on home view, scroll to top
//                    } else {
//                        homeNavigationStack = []
//                    }
                } else {    // Set the tab to the tabbed tab
                    self.selectedTab = tappedTab
                }
            }
        }

        var body: some View {
#if PRINT_CHANGES
            // "@self" marks that the view value itself has changed, and "@identity" marks that the
            // identity of the view has changed (that is, that the persistent data associated with
            // the view has been recycled for a new instance of the same type)
            if #available(iOS 17.1, *) {
                // logs at INFO level, “com.apple.SwiftUI” subsystem, category “Changed Body Properties”
                let _ = Self._logChanges()
            } else {
                let _ = Self._printChanges()
            }
            let delay: UInt = 0     // set to 5 to test delayed currency information
#else
            let delay: UInt = 0     // no delay for release builds
#endif
          Group {
//            let labelStyle = minimalistic ? IconOnlyLabelStyle() : TitleAndIconLabelStyle()    // labelStyle doesn't work
            TabView(selection: tabSelection()) {
                NavigationView {
                    BalancesListView(stack: stack.push(balancesTitle),
                                  navTitle: balancesTitle,
                                  balances: $balances,
                      shouldReloadBalances: $shouldReloadBalances)
                }.id(viewState.rootViewId)                // any change to rootViewId triggers popToRootView behaviour
                .navigationViewStyle(.stack)
                .tabItem {
                    Image(systemName: "chart.bar.xaxis")             // iOS will automatically use filled variant
                        .accessibilityLabel(balancesTitle)
                    if !minimalistic { Text(balancesTitle) }
                }
                .tag(Tab.balances)
                .badge(0)         // TODO: set badge if transaction finished in background
#if false
                NavigationView {
                    ExchangeListView(stack: stack.push(exchangesTitle),
                                  balances: $balances,
                                  navTitle: exchangesTitle)
                }.id(viewState2.rootViewId)                // any change to rootViewId triggers popToRootView behaviour
                .navigationViewStyle(.stack)
                .tabItem {
                    Image(systemName: "building.columns")    //  "arrow.triangle.2.circlepath")
                        .accessibilityLabel(exchangesTitle)
                    if !minimalistic { Text(exchangesTitle) }
                }
                .tag(Tab.exchanges)
#endif
                NavigationView {
                    SettingsView(stack: stack.push(),
                              balances: $balances,
                              navTitle: settingsTitle)
                }.navigationViewStyle(.stack)
                .tabItem {
                    Image(systemName: "gear")                   // system will automatically use filled variant
                        .accessibilityLabel(settingsTitle)
                    if !minimalistic { Text(settingsTitle) }
                }
                .tag(Tab.settings)
            }
//            .animation(.linear(duration: LAUNCHDURATION), value: selectedTab)     doesn't work. Needs CustomTabView
          } .onNotification(.KYCrequired) { notification in
              // show an alert with the KYC link (button) which opens in Safari
                if let transition = notification.userInfo?[TRANSACTIONTRANSITION] as? TransactionTransition {
                    if let kycString = transition.experimentalUserData {
                        if let urlForKYC = URL(string: kycString) {
                            logger.log(".onNotification(.KYCrequired): \(kycString)")
                            kycURI = urlForKYC
                            showKycAlert = true
                        }
                    } else {
                        // TODO: no KYC URI
                    }
                }
            }
            .alert("You need to pass a KYC procedure",
                 isPresented: $showKycAlert,
                 actions: {   openKycButton
                              dismissAlertButton },
                 message: {   Text("Tap the button to go to the KYC website.") })
            .onNotification(.BalanceChange) { notification in
              // reload balances on receiving BalanceChange notification ...
                logger.info(".onNotification(.BalanceChange) ==> reload")
                shouldReloadBalances += 1
            }
            .onNotification(.TransactionExpired) { notification in
                // reload balances on receiving BalanceChange notification ...
                logger.info(".onNotification(.TransactionExpired) ==> reload")
                shouldReloadBalances += 1
            }
            .onNotification(.TransactionDone) {
                shouldReloadBalances += 1
                selectedTab = .balances
            }
            .onNotification(.Error) { notification in
                if let error = notification.userInfo?[NOTIFICATIONERROR] as? Error {
                    model.showError(.error(error))
                    controller.playSound(0)
                }
            }
            .onChange(of: balances) { newArray in
                for balance in newArray {
                    let scope = balance.scopeInfo
                    if controller.hasInfo(for: scope.currency) == nil {
                        Task { // runs on MainActor
                            if let info = try? await model.getCurrencyInfoM(scope: scope, delay: delay) {
                                await controller.setInfo(info)
                            }
                        }
                    }
                }
            }
        } // body
    } // Content
}