forked from synonymdev/bitkit-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAmountInputViewModel.swift
More file actions
451 lines (396 loc) · 18 KB
/
Copy pathAmountInputViewModel.swift
File metadata and controls
451 lines (396 loc) · 18 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import Foundation
import SwiftUI
@Observable
@MainActor
final class AmountInputViewModel {
var amountSats: UInt64 = 0
var displayText: String = ""
var errorKey: String?
/// Optional per-screen cap (e.g. the max sendable balance in the send flow).
/// When set, input is additionally blocked above this value, on top of `maxAmount`.
var maxAmountOverride: UInt64?
/// Incremented each time input is blocked by the screen-specific cap (`maxAmountOverride`),
/// so views can react (e.g. show a toast). Not bumped when only the global
/// `maxAmount` blocks input.
private(set) var maxExceededCount = 0
// MARK: - Constants
private let maxAmount: UInt64 = 999_999_999
private let maxModernBitcoinLength = 10
private let maxDecimalInputLength = 20
private let classicBitcoinDecimals = 8
private let fiatDecimals = 2
/// The active upper bound for input: the global `maxAmount`, further restricted by `maxAmountOverride` when set.
private var effectiveMaxAmount: UInt64 {
guard let maxAmountOverride else { return maxAmount }
return Swift.min(maxAmount, maxAmountOverride)
}
// MARK: - Private Properties
private var rawInputText: String = ""
init() {}
// MARK: - Public Methods
/// Handles number pad input and updates the amount state
/// - Parameters:
/// - key: The key pressed on the number pad
/// - currency: The current currency settings
func handleNumberPadInput(_ key: String, currency: CurrencyViewModel) {
let maxLength = getMaxLength(currency: currency)
let maxDecimals = getMaxDecimals(currency: currency)
let newText = NumberPadInputHandler.handleInput(
key: key,
current: rawInputText,
maxLength: maxLength,
maxDecimals: maxDecimals
)
// Deletions must always apply, even when the amount is above the cap (e.g. a
// prefilled invoice amount over the available balance, or a cap that dropped
// after input). The cap only blocks growing the amount; without this, each
// delete still leaves the amount over the cap and gets rejected, trapping the
// user with an invalid amount they can't reduce.
let isDeletion = key == "delete"
// For decimal input (classic Bitcoin and fiat), preserve the text as-is
// For integer input (modern Bitcoin), format the final amount
if currency.primaryDisplay == .bitcoin && currency.displayUnit == .modern {
let newAmount = convertToSats(newText, currency: currency)
if isDeletion || newAmount <= effectiveMaxAmount {
rawInputText = newText
displayText = formatDisplayTextFromAmount(newAmount, currency: currency)
amountSats = newAmount
errorKey = nil
} else {
notifyMaxExceededIfCapped()
Haptics.notify(.warning)
errorKey = key
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.errorKey = nil
}
}
} else {
// For decimal input, check limits before updating state
if !newText.isEmpty {
let newAmount = convertToSats(newText, currency: currency)
if isDeletion || newAmount <= effectiveMaxAmount {
// Update both raw input and display text
rawInputText = newText
// Format with grouping separators but not decimal formatting
if currency.primaryDisplay == .fiat {
displayText = formatFiatGroupingOnly(newText)
} else {
displayText = newText
}
amountSats = newAmount
errorKey = nil
} else {
// Block input when limit exceeded
notifyMaxExceededIfCapped()
Haptics.notify(.warning)
errorKey = key
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.errorKey = nil
}
}
} else {
// If input is empty, set sats to 0
rawInputText = newText
amountSats = 0
displayText = ""
errorKey = nil
}
}
}
/// Updates the amount from a given satoshi value
/// - Parameters:
/// - newAmountSats: The new amount in satoshis
/// - currency: The current currency settings
func updateFromSats(_ newAmountSats: UInt64, currency: CurrencyViewModel) {
amountSats = newAmountSats
displayText = formatDisplayTextFromAmount(newAmountSats, currency: currency)
// Update raw input text based on the formatted display
// Remove formatting separators (spaces for modern Bitcoin, commas for fiat)
if currency.primaryDisplay == .fiat {
rawInputText = displayText.replacingOccurrences(of: ",", with: "")
} else if currency.displayUnit == .modern {
// Modern Bitcoin uses spaces as grouping separators
rawInputText = displayText.replacingOccurrences(of: " ", with: "")
} else {
rawInputText = displayText
}
}
/// Toggles between Bitcoin and Fiat display modes while preserving input
/// - Parameter currency: The current currency settings
func togglePrimaryDisplay(currency: CurrencyViewModel) {
// Store the current raw input before toggling
let currentRawInput = rawInputText
currency.togglePrimaryDisplay()
// Update display text when currency changes
if amountSats > 0 {
displayText = formatDisplayTextFromAmount(amountSats, currency: currency)
// Update raw input text based on the formatted display
// Remove formatting separators (spaces for modern Bitcoin, commas for fiat)
if currency.primaryDisplay == .fiat {
rawInputText = displayText.replacingOccurrences(of: ",", with: "")
} else if currency.displayUnit == .modern {
// Modern Bitcoin uses spaces as grouping separators
rawInputText = displayText.replacingOccurrences(of: " ", with: "")
} else {
rawInputText = displayText
}
} else if !currentRawInput.isEmpty {
// Convert the raw input from the old currency to the new currency
if currency.primaryDisplay == .fiat {
// Converting from Bitcoin to Fiat
// First convert the Bitcoin input to sats, then to fiat
let sats = convertBitcoinToSats(currentRawInput, isModern: currency.displayUnit == .modern)
if let converted = currency.convert(sats: sats) {
rawInputText = converted.formatted.replacingOccurrences(of: ",", with: "")
displayText = formatFiatGroupingOnly(rawInputText)
}
} else {
// Converting from Fiat to Bitcoin
// First convert fiat to sats, then format for Bitcoin display
let cleanFiat = currentRawInput.replacingOccurrences(of: ",", with: "")
if let fiatValue = Double(cleanFiat), let sats = currency.convert(fiatAmount: fiatValue) {
let formatted = formatBitcoinFromSats(sats, isModern: currency.displayUnit == .modern)
displayText = formatted
// Remove spaces from rawInputText for modern Bitcoin
if currency.displayUnit == .modern {
rawInputText = formatted.replacingOccurrences(of: " ", with: "")
} else {
rawInputText = formatted
}
}
}
}
}
// MARK: - Helper Methods
func getNumberPadType(currency: CurrencyViewModel) -> NumberPadType {
let isBtc = currency.primaryDisplay == .bitcoin
let isModern = currency.displayUnit == .modern
return isModern && isBtc ? .integer : .decimal
}
func getMaxLength(currency: CurrencyViewModel) -> Int {
let isBtc = currency.primaryDisplay == .bitcoin
let isModern = currency.displayUnit == .modern
return isModern && isBtc ? maxModernBitcoinLength : maxDecimalInputLength
}
func getMaxDecimals(currency: CurrencyViewModel) -> Int {
let isBtc = currency.primaryDisplay == .bitcoin
let isModern = currency.displayUnit == .modern
return isModern && isBtc ? 0 : (isBtc ? classicBitcoinDecimals : fiatDecimals)
}
func getPlaceholder(currency: CurrencyViewModel) -> String {
if displayText.isEmpty {
// When nothing is typed, show simple placeholder
if currency.primaryDisplay == .bitcoin {
return currency.displayUnit == .modern ? "0" : "0.00000000"
} else {
// TODO: some currencies have no decimals
return "0.00"
}
} else {
// When typing, show remaining digits/decimals
if currency.primaryDisplay == .bitcoin {
if currency.displayUnit == .modern {
// Modern: no additional placeholder digits
return ""
} else {
// Classic: show decimal places
if displayText.contains(".") {
let parts = displayText.split(separator: ".", maxSplits: 1)
let decimalPart = parts.count > 1 ? String(parts[1]) : ""
let remainingDecimals = classicBitcoinDecimals - decimalPart.count
return remainingDecimals > 0 ? String(repeating: "0", count: remainingDecimals) : ""
} else {
return ".00000000"
}
}
} else {
// Fiat: show decimal places
if displayText.contains(".") {
let parts = displayText.split(separator: ".", maxSplits: 1)
let decimalPart = parts.count > 1 ? String(parts[1]) : ""
let remainingDecimals = fiatDecimals - decimalPart.count
return remainingDecimals > 0 ? String(repeating: "0", count: remainingDecimals) : ""
} else {
return ".00"
}
}
}
}
// MARK: - Private Methods
/// Signals blocked input to observers, but only when the screen-specific cap is the
/// limiting bound. Hitting the global `maxAmount` stays silent.
private func notifyMaxExceededIfCapped() {
if effectiveMaxAmount < maxAmount {
maxExceededCount += 1
}
}
private func formatDisplayTextFromAmount(_ amountSats: UInt64, currency: CurrencyViewModel) -> String {
if amountSats == 0 {
return ""
}
if currency.primaryDisplay == .bitcoin {
if currency.displayUnit == .modern {
// Format with grouping separators for modern Bitcoin
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = " "
return formatter.string(from: NSNumber(value: amountSats)) ?? String(amountSats)
} else {
// Classic Bitcoin - convert to BTC with proper formatting
let btcValue = Double(amountSats) / 100_000_000.0
return String(format: "%.8f", btcValue).replacingOccurrences(of: #"\.?0+$"#, with: "", options: .regularExpression)
}
} else {
// Fiat - convert using currency service
if let converted = currency.convert(sats: amountSats) {
return converted.formatted
}
return ""
}
}
private func formatFiatGroupingOnly(_ text: String) -> String {
// Remove any existing grouping separators for parsing
let cleanText = text.replacingOccurrences(of: ",", with: "")
// If the text ends with a decimal point, don't format it (preserve the decimal point)
if text.hasSuffix(".") {
// Only add grouping separators to the integer part
let integerPart = String(cleanText.dropLast()) // Remove the decimal point
if let intValue = Int(integerPart) {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = ","
let formattedInteger = formatter.string(from: NSNumber(value: intValue)) ?? integerPart
return formattedInteger + "."
}
return text
}
// If the text contains a decimal point, preserve the decimal structure
if text.contains(".") {
let parts = cleanText.split(separator: ".", maxSplits: 1)
let integerPart = String(parts[0])
let decimalPart = parts.count > 1 ? String(parts[1]) : ""
// Format only the integer part with grouping separators
if let intValue = Int(integerPart) {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = ","
let formattedInteger = formatter.string(from: NSNumber(value: intValue)) ?? integerPart
return formattedInteger + "." + decimalPart
}
return text
}
// For integer-only input, add grouping separators
if let intValue = Int(cleanText) {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = ","
return formatter.string(from: NSNumber(value: intValue)) ?? text
}
return text
}
private func convertBitcoinToSats(_ text: String, isModern: Bool) -> UInt64 {
guard !text.isEmpty else { return 0 }
if isModern {
// Remove grouping separators (spaces) before parsing
let cleanText = text.replacingOccurrences(of: " ", with: "")
return UInt64(cleanText) ?? 0
} else {
guard let btcValue = Double(text) else { return 0 }
return UInt64(btcValue * 100_000_000)
}
}
private func formatBitcoinFromSats(_ sats: UInt64, isModern: Bool) -> String {
if isModern {
// Format with grouping separators for modern Bitcoin
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = " "
return formatter.string(from: NSNumber(value: sats)) ?? String(sats)
} else {
// Classic Bitcoin - convert to BTC with proper formatting
let btcValue = Double(sats) / 100_000_000.0
return String(format: "%.8f", btcValue).replacingOccurrences(of: #"\.?0+$"#, with: "", options: .regularExpression)
}
}
private func convertToSats(_ text: String, currency: CurrencyViewModel) -> UInt64 {
guard !text.isEmpty else { return 0 }
if currency.primaryDisplay == .bitcoin {
if currency.displayUnit == .modern {
// Remove grouping separators (spaces) before parsing
let cleanText = text.replacingOccurrences(of: " ", with: "")
return UInt64(cleanText) ?? 0
} else {
guard let btcValue = Double(text) else { return 0 }
return UInt64(btcValue * 100_000_000)
}
} else {
// Remove grouping separators (commas) before parsing fiat
let cleanText = text.replacingOccurrences(of: ",", with: "")
guard let fiatValue = Double(cleanText) else { return 0 }
return currency.convert(fiatAmount: fiatValue) ?? 0
}
}
}
// MARK: - NumberPad Input Handler
/// Handles raw number pad input logic for different input types
enum NumberPadInputHandler {
static func handleInput(key: String, current: String, maxLength: Int, maxDecimals: Int) -> String {
// For integer-only input (maxDecimals = 0), treat as simple number input
if maxDecimals == 0 {
return handleIntegerInput(key: key, current: current, maxLength: maxLength)
}
// For decimal input, use the existing logic
return handleDecimalInput(key: key, current: current, maxLength: maxLength, maxDecimals: maxDecimals)
}
private static func handleIntegerInput(key: String, current: String, maxLength: Int) -> String {
if key == "delete" {
return String(current.dropLast())
}
if current == "0" {
// no leading zeros
if key != "delete" {
return key
}
}
// limit to maxLength
if current.count == maxLength {
return current
}
return "\(current)\(key)"
}
private static func handleDecimalInput(key: String, current: String, maxLength: Int, maxDecimals: Int) -> String {
let parts = current.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: false)
let decimalPart = parts.count > 1 ? String(parts[1]) : ""
if key == "delete" {
if current == "0." {
return ""
}
return String(current.dropLast())
}
if current == "0" {
// no leading zeros
if key != "." && key != "delete" {
return key
}
}
// limit to maxLength
if current.count == maxLength {
return current
}
// limit to maxDecimals
if decimalPart.count >= maxDecimals {
return current
}
if key == "." {
// no multiple decimal symbol
if current.contains(".") {
return current
}
// add leading zero
if current.isEmpty {
return "0\(key)"
}
}
return "\(current)\(key)"
}
}