summaryrefslogtreecommitdiff
path: root/TalerWallet1/Views/Main/MainView.swift
blob: 301ad27d1620abc548f18e2d2cbb2a2e4364fbb9 (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
/*
 * This file is part of GNU Taler, ©2022-23 Taler Systems S.A.
 * See LICENSE.md
 */
import SwiftUI
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 stack: CallStack
    @EnvironmentObject private var viewState: ViewState         // popToRootView()
    @EnvironmentObject private var controller: Controller
    @State private var sheetPresented = false
    @State private var urlToOpen: URL? = nil
    @Binding var soundPlayed: Bool
    @AppStorage("talerFont") var talerFont: Int = 0         // extension mustn't define this, so it must be here

    func sheetDismissed() -> Void {
        symLog.log("sheet dismiss")
    }
    var body: some View {
#if DEBUG
        let _ = Self._printChanges()
        let _ = symLog.vlog()       // just to get the # to compare it with .onAppear & onDisappear
#endif
        Group {
            if controller.backendState == .ready {
                Content(symLog: symLog, stack: stack.push("Content"), talerFont: $talerFont)
                // any change to rootViewId triggers popToRootView behaviour
                    .id(viewState.rootViewId)
                    .onAppear() {
                        controller.playSound(1008)     // Startup chime
                        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)
        }
    } // body
}
// MARK: - TabBar
enum Tab {
    case balances, exchanges, settings
}

// MARK: - Content
extension MainView {
    struct Content: View {
        let symLog: SymLogV?
        let stack: CallStack
        @State private var shouldReloadBalances = 0
        @State private var balances: [Balance] = []
        @Binding var talerFont: Int
        @AppStorage("iconOnly") var iconOnly: Bool = false
        @EnvironmentObject private var controller: Controller
        @EnvironmentObject private var model: WalletModel
        let balancesTitle = String(localized: "Balances")
        let exchangesTitle = String(localized: "Exchanges")
        let settingsTitle = String(localized: "Settings")
#if TABBAR  // Taler Wallet
        @State private var selectedTab: Tab = .balances

        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
//                    if homeNavigationStack.isEmpty {
                        //User already on home view, scroll to top
//                    } else {
//                        homeNavigationStack = []
//                    }
                }
                //Set the tab to the tabbed tab
                self.selectedTab = tappedTab
            }
        }
#else       // GNU Taler
        @State var sidebarVisible: Bool = false
        func hamburgerAction() {
            withAnimation(.easeInOut(duration: 0.25)) {
                sidebarVisible = !sidebarVisible
            }
        }

        var views: [SidebarItem] {[
            SidebarItem(name: balancesTitle,
                    sysImage: "chart.bar.xaxis",  // creditcard.fill     // TODO: Wallet Icon
                        view: AnyView(BalancesListView(stack: stack.push(balancesTitle),
                                                    navTitle: balancesTitle,
                                                    balances: $balances,
                                        shouldReloadBalances: $shouldReloadBalances,
                                             hamburgerAction: hamburgerAction)
                                     )),
            SidebarItem(name: exchangesTitle,
                    sysImage: "building.columns",
                        view: AnyView(ExchangeListView(stack: stack.push(exchangesTitle),
//                                                    balances: $balances,
                                                    navTitle: exchangesTitle,
                                             hamburgerAction: hamburgerAction)
                                     )),
            SidebarItem(name: settingsTitle,    // TODO: "About"?
                    sysImage: "gearshape.fill",
                        view: AnyView(SettingsView(stack: stack.push(settingsTitle),
                                                navTitle: settingsTitle,
                                         hamburgerAction: hamburgerAction)
                                     ))
        ]}
        @State var currentView: Int = 0
#endif

        var body: some View {
#if DEBUG
            // "@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 _ = symLog?.vlog()       // just to get the identity # to compare with .onAppear & .onDisappear
#endif
          Group {
#if TABBAR  // Taler Wallet
//            let labelStyle = iconOnly ? IconOnlyLabelStyle() : TitleAndIconLabelStyle()    // labelStyle doesn't work
            TabView(selection: tabSelection()) {
                NavigationView {
                    BalancesListView(stack: stack.push(balancesTitle),
                                  navTitle: balancesTitle,
                                  balances: $balances,
                      shouldReloadBalances: $shouldReloadBalances)
                }.navigationViewStyle(.stack)
                .tabItem {
                    Image(systemName: "chart.bar.xaxis")             // creditcard     system will automatically use filled variant
                    if !iconOnly { Text(balancesTitle) }
                }
                .tag(Tab.balances)
                .badge(0)         // TODO: set badge if transaction finished in background

                NavigationView {
                    ExchangeListView(stack: stack.push(exchangesTitle),
//                                  balances: $balances,
                                  navTitle: exchangesTitle)
                }.navigationViewStyle(.stack)
                .tabItem {
                    Image(systemName: "building.columns")
                    if !iconOnly { Text(exchangesTitle) }
                }
                .tag(Tab.exchanges)

                NavigationView {
                    SettingsView(stack: stack.push(), navTitle: settingsTitle)
                }.navigationViewStyle(.stack)
                .tabItem {
                    Image(systemName: "gear")                   // system will automatically use filled variant
                    if !iconOnly { Text(settingsTitle) }
                }
                .tag(Tab.settings)
            }
//            .animation(.linear(duration: LAUNCHDURATION), value: selectedTab)     doesn't work. Needs CustomTabView
#else       // GNU Taler
            ZStack(alignment: .leading) {
                NavigationView {   // the one and only for all non-sheet views
                    VStack(alignment: .leading) {   // only needed for backslide transition
                        views[currentView].view
                            .id(views[currentView].name)
                            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
                            .transition(.backslide)
                    }   .id(talerFont)
                        .navigationBarTitleDisplayMode(.automatic)
                        .background(NavigationBarBuilder { navigationController in
                            //                            navigationController.navigationBar.barTintColor = .red
                            navigationController.navigationBar.titleTextAttributes =
                                [.font: TalerFont.uiFont(talerFont, size: 24, relativeTo: .title2)]
                            navigationController.navigationBar.largeTitleTextAttributes =
                                [.font: TalerFont.uiFont(talerFont, size: 38, relativeTo: .largeTitle)]
                        })
                }
                .navigationViewStyle(.stack)
                .talerNavBar(talerFont: talerFont)

                // The side view is above (Z-Axis) the current view
                SideBarView(stack: stack.push(),
                            views: views,
                      currentView: $currentView,
                   sidebarVisible: sidebarVisible,
                  hamburgerAction: hamburgerAction)
            }
#endif
          }
            .onNotification(.BalanceChange) { notification in
              // reload balances on receiving BalanceChange notification ...
                symLog?.log(".onNotification(.BalanceChange) ==> reload")
                shouldReloadBalances += 1
            }
            .onChange(of: balances) { newArray in
                for balance in newArray {
                    let scope = balance.scopeInfo
                    if controller.info(for: scope.currency) == nil {
                        Task { // runs on MainActor
                            symLog?.log("get info for: \(scope.currency)")
                            do {
                                let info = try await model.getCurrencyInfo(scope: scope)
                                symLog?.log("added: \(scope.currency)")
                                await controller.setInfo(info)
                            } catch {    // TODO: error handling - couldn't get CurrencyInfo
                                symLog?.log("error: \(error)")
                            }
                        }
                    }
                }
            }
        } // body
    } // Content
}