taler-ios

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

ErrorView.swift (15696B)


      1 /*
      2  * This file is part of GNU Taler, ©2022-26 Taler Systems S.A.
      3  * See LICENSE.md
      4  */
      5 /**
      6  * @author Iván Ávalos
      7  * @author Marc Stibane
      8  */
      9 import SwiftUI
     10 import taler_swift
     11 
     12 enum BannerType {
     13     case error
     14     case networkUnavailable
     15     case warning5sec
     16 }
     17 
     18 struct ErrorBanner: View {
     19     let type: BannerType
     20     
     21     init(_ type: BannerType) {
     22         self.type = type
     23     }
     24 
     25     var errorText: String {
     26         switch type {
     27             case .error:
     28                 return String(localized: "An error occurred…")
     29             case .networkUnavailable:
     30                 return String(localized: "Network unavailable!")
     31             case .warning5sec:
     32                 return String(localized: "Network is slow…")
     33         }
     34     }
     35 
     36     var errorColor: Color {
     37         switch type {
     38             case .error:
     39                 return .red
     40             case .networkUnavailable:
     41                 return .red
     42             case .warning5sec:
     43                 return .yellow
     44         }
     45     }
     46 
     47     @ScaledMetric var frameHeight: CGFloat = 60          // relative to fontSize
     48 
     49     var body: some View {
     50         let text = Text(errorText)
     51             .foregroundStyle(.white)
     52             .talerFont(.title2)
     53         Group {
     54             if #available(iOS 26.0, *) {
     55                 ContainerRelativeShape()
     56                     .fill(errorColor)
     57                     .frame(height: frameHeight)
     58                     .overlay {
     59                         ZStack {
     60                             VStack(spacing: 0) {
     61                                 Color.clear
     62                                 Rectangle()
     63                                     .fill(errorColor)
     64                             }
     65                             text
     66                         }
     67                     }
     68             } else {  // ContainerRelativeShape exists since iOS 14, but doesn't work correctly
     69                 text
     70                     .frame(maxWidth: .infinity, alignment: .center)
     71                     .frame(height: frameHeight)
     72                     .background {
     73                         let radius = 12.0
     74                         if #available(iOS 16.4, *) {
     75                             let radii = RectangleCornerRadii(topLeading: radius,
     76                                                           bottomLeading: 0,
     77                                                          bottomTrailing: 0,
     78                                                             topTrailing: radius)
     79                             UnevenRoundedRectangle(cornerRadii: radii, style: .continuous)
     80                                 .fill(errorColor)
     81                         } else {
     82                             RoundedRectangle(cornerRadius: radius)
     83                                 .fill(errorColor)
     84                                 .overlay {
     85                                     VStack(spacing: 0) {
     86                                         Color.clear
     87                                         Rectangle()
     88                                             .fill(errorColor)
     89                                     }
     90                                 }
     91                         }
     92                     }
     93             }
     94         }
     95         .transition(.move(edge: .top).combined(with: .scale))
     96     }
     97 }
     98 
     99 enum ErrorData {
    100     case message(title: String, message: String)
    101     case error(Error)
    102 }
    103 
    104 struct ErrorView: View {
    105     let stack: CallStack?
    106     var title: String
    107     var titleA11y: String?
    108     var exclam: Bool
    109     var message: String? = nil
    110     var requestUrl: String? = nil
    111     var copyable: Bool
    112 
    113     var onDismiss: (() -> Void)?
    114 
    115     init(_ stack: CallStack?, title: String, titleA11y: String? = nil,
    116           exclam: Bool = true, message: String? = nil,
    117       requestUrl: String? = nil, copyable: Bool = false,
    118        onDismiss: (() -> Void)? = nil
    119     ) {
    120         self.stack = stack
    121         self.title = title
    122         self.exclam = exclam
    123         self.titleA11y = titleA11y
    124         self.message = message
    125         self.requestUrl = requestUrl
    126         self.copyable = copyable
    127         self.onDismiss = onDismiss
    128     }
    129 
    130     /// wallet-core errors that are expected outcomes, rather than faults, keyed by `TalerErrorCode` from taler-error-codes.ts.
    131     static func titleForExpected(code: Int) -> String? {
    132         switch code {
    133                 // 7001 WALLET_UNEXPECTED_EXCEPTION, and 7048 WALLET_CORE_API_BAD_REQUEST
    134                 // both stay Internal core errors - to be found while debugging, not in production
    135             case 7000,          // WALLET_EXCHANGE_PROTOCOL_VERSION_INCOMPATIBLE
    136                  7017,          // WALLET_BANK_INTEGRATION_PROTOCOL_VERSION_INCOMPATIBLE
    137                  7047:          // WALLET_TRANSACTION_PROTOCOL_VIOLATION
    138                 String(localized: "Incompatible protocol version",
    139                          comment: "error title: 7000,7017, 7047: the server speaks a protocol this app does not")
    140         // 7002, 7003, 7005, 7013 and 7032 are mapped to INTERNET ERROR
    141 //            case 7002:          // WALLET_RECEIVED_MALFORMED_RESPONSE
    142 //                String(localized: "Bad response from server",
    143 //                       comment: "error title: 7002: the server sent an invalid response")
    144 //            case 7003:          // WALLET_NETWORK_ERROR
    145 //                String(localized: "",
    146 //                       comment: "error title: 7003: ")
    147 //            case 7005:          // WALLET_UNEXPECTED_REQUEST_ERROR
    148 //                String(localized: "",
    149 //                       comment: "error title: 7005: ")
    150 //            case 7013:          // WALLET_HTTP_REQUEST_GENERIC_TIMEOUT
    151 //                String(localized: "Network timeout",
    152 //                         comment: "error title: 7013: the server didn't respond in time")
    153             case 7026,          // WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE
    154                  7027:          // WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE
    155                 String(localized: "Insufficient balance",
    156                          comment: "error title: 7026, 7027: not enough funds for transaction")
    157 //            case 7032:          // WALLET_EXCHANGE_UNAVAILABLE
    158 //                String(localized: "",
    159 //                       comment: "error title: 7032: ")
    160             case 7035:          // WALLET_TALER_URI_MALFORMED
    161                 String(localized: "The talerURI is unknown or invalid",
    162                          comment: "error title: 7035: scanned talerURI is not valid")
    163             case 7036:          // WALLET_CORE_REQUEST_CANCELLED
    164                 String(localized: "User cancelled",
    165                          comment: "error title: 7036: the request was cancelled")
    166             case 7037:          // WALLET_EXCHANGE_TOS_NOT_ACCEPTED
    167                 String(localized: "Terms of Services must be accepted",
    168                        comment: "error title: 7037: user didn't accept yet")
    169             case 7041:          // WALLET_PEER_PULL_DEBIT_PURSE_GONE
    170                 String(localized: "Invoice expired",
    171                          comment: "error title: 7041: the payer waited too long")
    172             case 7046,          // WALLET_REQUEST_TRANSACTION_STATE_UNSUPPORTED
    173                  7049,          // WALLET_MERCHANT_ORDER_NOT_FOUND
    174                  7052:          // WALLET_TRANSACTION_NOT_FOUND
    175                 String(localized: "Transaction Error",
    176                        comment: "error title: 7046,7049: illegal state / tx deleted?")
    177             case 7051:          // WALLET_PURCHASE_NOT_FOUND
    178                 String(localized: "Purchase missing",
    179                        comment: "error title: 7051: refund needs a matching purchase")
    180             case 7054:          // WALLET_KYC_LIMIT_EXCEEDED
    181                 String(localized: "Limit exceeded",
    182                          comment: "error title: 7054: the payment service refused the amount")
    183             case 7055:          // WALLET_NO_SUITABLE_EXCHANGE
    184                 String(localized: "No suitable payment service",
    185                          comment: "error title: 7055: no exchange can serve this request")
    186             case 7057:          // WALLET_PEER_CONTRACT_NOT_FOUND
    187                 String(localized: "Unknown contract",
    188                          comment: "error title: 7057: the exchange does not know this peer-to-peer contract")
    189             case 7059:          // WALLET_PEER_PULL_DEBIT_ALREADY_PAID
    190                 String(localized: "Already paid",
    191                        comment: "error title: 7059: this request has already been paid")
    192             case 7064:          // WALLET_CONTRACT_TERMS_UNSUPPORTED
    193                 String(localized: "Transaction Error",
    194                          comment: "error title: 7064: the exchange does not support the contract terms")
    195             default: nil
    196         }
    197     }
    198 
    199     init(_ stack: CallStack?, error: Error, devMode: Bool, onDismiss: (() -> Void)? = nil) {
    200         let internetError = String(localized: "Network problem")
    201         let internetMessage = String(localized: "Please check your internet connection and try again.")
    202         let walletCoreError = String(localized: "Internal core error")
    203         let initializationError = String(localized: "Initialization error")
    204         let serializationError = String(localized: "Serialization error")
    205         let deserializationError = String(localized: "Deserialization error")
    206         let wrongParameters = String(localized: "Wrong parameters")
    207         let unknownError = String(localized: "Unknown error")
    208 
    209         switch error {
    210             case let walletError as WalletBackendError:
    211                 switch walletError {
    212                     case .walletCoreError(let walletBackendResponseError):
    213                         if let responseError = walletBackendResponseError {
    214                             let hint = responseError.errorResponse?.hint ?? responseError.hint      // nested one preferred
    215                             let code = responseError.code
    216                             // Limits, quotas and similar conditions are ordinary outcomes the user can act on
    217                             if let expectedTitle = Self.titleForExpected(code: code) {
    218                                 self.init(stack, title: expectedTitle,
    219                                    exclam: false,     // TODO: less alarming icon than exclamation mark?
    220                                   message: hint ?? internetMessage,
    221                                requestUrl: responseError.requestUrl,
    222                                  copyable: devMode,
    223                                 onDismiss: onDismiss)
    224                                 break
    225                             }
    226                             if code == 7002 || code == 7003 || code == 7005 || code == 7013 || code == 7032 {
    227                                 self.init(stack, title: internetError,
    228                                    exclam: true,
    229                                   message: hint ?? internetMessage,
    230                                requestUrl: responseError.requestUrl,
    231                                  copyable: devMode,
    232                                 onDismiss: onDismiss)
    233                                 break
    234                             }
    235                             if !devMode, let hint {
    236                                 // prefer hint for regular users
    237                                 self.init(stack, title: walletCoreError, message: hint, copyable: true, onDismiss: onDismiss)
    238                                 break
    239                             }
    240                             if let json = responseError.toJSON() {
    241                                 // raw JSON for developers, or if there is no hint
    242                                 self.init(stack, title: walletCoreError, message: json, copyable: true, onDismiss: onDismiss)
    243                                 break
    244                             } else if let hint {
    245                                 // should never happen
    246                                 self.init(stack, title: walletCoreError, message: hint, copyable: true, onDismiss: onDismiss)
    247                                 break
    248 //                            } else if let message = responseError.message {
    249 //                                self.init(stack, title: walletCoreError, message: message, copyable: true, onDismiss: onDismiss)
    250 //                                break
    251                             }
    252                         }
    253                         self.init(stack, title: walletCoreError, copyable: false, onDismiss: onDismiss)
    254                     case .initializationError:
    255                         self.init(stack, title: initializationError, copyable: false, onDismiss: onDismiss)
    256                     case .serializationError:
    257                         self.init(stack, title: serializationError, copyable: false, onDismiss: onDismiss)
    258                     case .deserializationError:
    259                         self.init(stack, title: deserializationError, copyable: false, onDismiss: onDismiss)
    260                     case .wrongParameters:
    261                         self.init(stack, title: wrongParameters, copyable: false, onDismiss: onDismiss)
    262                 }
    263             default:
    264                 self.init(stack, title: unknownError, message: error.localizedDescription, copyable: false, onDismiss: onDismiss)
    265         }
    266     }
    267 
    268     init(_ stack: CallStack?, data: ErrorData, devMode: Bool, onDismiss: (() -> Void)? = nil) {
    269         switch data {
    270             case .message(let title, let message):
    271                 self.init(stack, title: title, message: message, copyable: false, onDismiss: onDismiss)
    272             case .error(let error):
    273                 self.init(stack, error: error, devMode: devMode, onDismiss: onDismiss)
    274         }
    275     }
    276 
    277 //    @ScaledMetric                     // relative to fontSize
    278     var frameSize: CGFloat = 50
    279 
    280     @ViewBuilder
    281     func content() -> some View {
    282         if let message {
    283             if copyable {
    284                 if #available(iOS 16.4, *) {
    285                     Text(message).monospaced()
    286                 } else {
    287                     Text(message).font(.system(.body, design: .monospaced))
    288                 }
    289 
    290                 CopyButton(message, vertical: false)
    291                     .accessibilityLabel(Text("Copy the error JSON", comment: "a11y"))
    292                     .padding()
    293             } else {
    294                 if let requestUrl {
    295                     Text(requestUrl)
    296                         .multilineTextAlignment(.center)
    297                         .padding()
    298                 }
    299                 Text(message)
    300                     .multilineTextAlignment(.center)
    301                     .padding()
    302             }
    303         }
    304     }
    305 
    306     var body: some View {
    307         ScrollView {
    308             VStack {
    309                 Image(systemName: EXCLAMATION)
    310                     .resizable()
    311                     .frame(width: frameSize, height: frameSize)
    312                     .aspectRatio(contentMode: .fit)
    313                     .foregroundStyle(exclam ? WalletColors().attention : WalletColors().gray1)
    314                     .padding()
    315                     .accessibilityHidden(true)
    316                 Text(title)
    317                     .talerFont(.title)
    318                     .padding(.bottom)
    319                     .accessibilityLabel(Text(titleA11y ?? title))
    320             }   .accessibilityAddTraits(.isHeader)
    321                 .accessibilitySortPriority(2)
    322             content()
    323                 .accessibilitySortPriority(1)
    324         }
    325         .padding()
    326         .safeAreaInset(edge: .bottom) {
    327             Button("OK", role: .cancel) {
    328                 if let onDismiss {
    329                     onDismiss()
    330                 } else {
    331                     dismissTop(stack?.push())
    332                 }
    333             }
    334             .buttonStyle(TalerButtonStyle(type: .bordered))
    335             .padding(.bottom)
    336             .padding(.horizontal)
    337         }
    338     }
    339 }