SPB Git

Repository Public

Amount.swift 12.0 KB 280 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/Amount.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import QyvoraCore4344/// An amount in integer base units, formatted with monospaced digits. An optional second line carries the45/// fiat value the caller computed; the privacy mode replaces both with bullets.46public struct AmountText: View {47    public enum Style: Sendable { case balance, row, compact }48    public enum Sign: Sendable { case none, incoming, outgoing }4950    let units: String51    let decimals: Int52    let symbol: String53    let maxFractionDigits: Int?54    let fiat: String?55    let style: Style56    let sign: Sign57    let hidden: Bool58    var compactsLargeAmounts = false59    var alignsLeading = false60    @Environment(\.redactionReasons) private var redaction6162    /// - Parameters:63    ///   - units: the amount in base units, as a decimal digit string (any size).64    ///   - decimals: decimals of the asset (8 for BTC, 18 for ETH, the token's own value otherwise).65    ///   - fiat: an already formatted fiat value, or nil when no price is known (nothing is shown then).66    public init(units: String, decimals: Int, symbol: String, maxFractionDigits: Int? = nil, fiat: String? = nil,67                style: Style = .row, sign: Sign = .none, hidden: Bool = false) {68        self.units = units69        self.decimals = decimals70        self.symbol = symbol71        self.maxFractionDigits = maxFractionDigits72        self.fiat = fiat73        self.style = style74        self.sign = sign75        self.hidden = hidden76    }7778    public init(units: UInt64, decimals: Int, symbol: String, maxFractionDigits: Int? = nil, fiat: String? = nil,79                style: Style = .row, sign: Sign = .none, hidden: Bool = false) {80        self.init(units: String(units), decimals: decimals, symbol: symbol, maxFractionDigits: maxFractionDigits, fiat: fiat,81                  style: style, sign: sign, hidden: hidden)82    }8384    public init(units: UInt256, decimals: Int, symbol: String, maxFractionDigits: Int? = nil, fiat: String? = nil,85                style: Style = .row, sign: Sign = .none, hidden: Bool = false) {86        self.init(units: units.description, decimals: decimals, symbol: symbol, maxFractionDigits: maxFractionDigits, fiat: fiat,87                  style: style, sign: sign, hidden: hidden)88    }8990    var isHidden: Bool { hidden || redaction.contains(.privacy) }9192    /// Writes amounts of one million units or more in compact notation ("1.23M"), for rows where a meme-token93    /// balance would otherwise be truncated. Smaller amounts are unchanged.94    /// Aligns the figure and its fiat line on the leading edge, for rows that stack at accessibility sizes.95    func leadingAligned(_ enabled: Bool = true) -> AmountText {96        var copy = self97        copy.alignsLeading = enabled98        return copy99    }100101    public func compactingLargeAmounts(_ enabled: Bool = true) -> AmountText {102        var copy = self103        copy.compactsLargeAmounts = enabled104        return copy105    }106107    var formatted: String {108        let locale = Locale.current109        if compactsLargeAmounts, let short = AmountFormat.compact(units: units, decimals: decimals, decimalSeparator: locale.decimalSeparator ?? ".") {110            return short111        }112        return AmountFormat.format(units: units, decimals: decimals, maxFractionDigits: maxFractionDigits,113                                   groupingSeparator: locale.groupingSeparator ?? ",", decimalSeparator: locale.decimalSeparator ?? ".")114    }115116    var signPrefix: String {117        guard !AmountFormat.isZero(units: units) else { return "" }118        switch sign {119        case .none: return ""120        case .incoming: return "+"121        case .outgoing: return "−"122        }123    }124125    var figureFont: Font {126        switch style {127        case .balance: return QFont.balance128        case .row: return QFont.amount129        case .compact: return Font.system(.footnote, design: .rounded, weight: .medium).monospacedDigit()130        }131    }132133    var symbolFont: Font {134        switch style {135        case .balance: return Font.system(.title3, design: .rounded, weight: .medium)136        case .row: return Font.system(.footnote, design: .rounded, weight: .medium)137        case .compact: return Font.system(.caption2, design: .rounded, weight: .medium)138        }139    }140141    var spokenValue: String {142        if isHidden { return "Amount hidden" }143        let direction: String144        switch sign {145        case .none: direction = ""146        case .incoming: direction = "received "147        case .outgoing: direction = "sent "148        }149        return direction + formatted + " " + symbol + (fiat.map { ", " + $0 } ?? "")150    }151152    public var body: some View {153        VStack(alignment: style == .balance || alignsLeading ? .leading : .trailing, spacing: style == .balance ? 4 : 2) {154            HStack(alignment: .firstTextBaseline, spacing: style == .balance ? 8 : 4) {155                Text(isHidden ? "••••••" : signPrefix + formatted)156                    .font(figureFont)157                    .foregroundStyle(sign == .incoming && !isHidden ? QColor.positive : QColor.textPrimary)158                    .contentTransition(.numericText())159                    .lineLimit(1)160                    .minimumScaleFactor(style == .balance ? 0.45 : 0.7)161                Text(symbol)162                    .font(symbolFont)163                    .foregroundStyle(QColor.textSecondary)164                    .lineLimit(1)165                    .layoutPriority(1)166            }167            if let fiat {168                Text(isHidden ? "••••" : fiat)169                    .font(style == .balance ? QFont.callout.monospacedDigit() : QFont.caption.monospacedDigit())170                    .foregroundStyle(QColor.textSecondary)171                    .contentTransition(.numericText())172                    .lineLimit(1)173            }174        }175        .animation(.snappy(duration: 0.25), value: units)176        .animation(.snappy(duration: 0.25), value: isHidden)177        .accessibilityElement(children: .ignore)178        .accessibilityLabel(spokenValue)179    }180}181182/// Decimal amount entry. The text binding only ever holds digits and one decimal separator with at most183/// `maxFractionDigits` fraction digits; convert it with `AmountFormat.parse`.184public struct AmountField: View {185    @Binding var text: String186    let symbol: String187    let maxFractionDigits: Int188    let fiat: String?189    let error: String?190    let onMax: (() -> Void)?191    @FocusState private var focused: Bool192193    /// - Parameters:194    ///   - fiat: an already formatted counter-value shown under the field, or nil.195    ///   - error: validation message supplied by the caller (insufficient funds, below dust…), or nil.196    ///   - onMax: when given, a MAX button calls it; the caller writes the spendable amount into `text`.197    public init(text: Binding<String>, symbol: String, maxFractionDigits: Int, fiat: String? = nil, error: String? = nil,198                onMax: (() -> Void)? = nil) {199        self._text = text200        self.symbol = symbol201        self.maxFractionDigits = maxFractionDigits202        self.fiat = fiat203        self.error = error204        self.onMax = onMax205    }206207    var separator: String { Locale.current.decimalSeparator ?? "." }208209    public var body: some View {210        VStack(alignment: .leading, spacing: 8) {211            HStack(alignment: .firstTextBaseline, spacing: 10) {212                TextField("0", text: $text)213                    .font(Font.system(.largeTitle, design: .rounded, weight: .semibold).monospacedDigit())214                    .foregroundStyle(QColor.textPrimary)215                    #if os(iOS)216                    .keyboardType(maxFractionDigits > 0 ? .decimalPad : .numberPad)217                    #endif218                    .autocorrectionDisabled()219                    .focused($focused)220                    .minimumScaleFactor(0.5)221                    .onChange(of: text) { _, new in222                        let clean = AmountFormat.sanitize(new, maxFractionDigits: maxFractionDigits, decimalSeparator: separator)223                        if clean != new { text = clean }224                    }225                    .accessibilityLabel("Amount in \(symbol)")226                Text(symbol)227                    .font(Font.system(.title3, design: .rounded, weight: .medium))228                    .foregroundStyle(QColor.textSecondary)229                if let onMax {230                    Button("MAX", action: onMax)231                        .font(.footnote.weight(.bold))232                        .foregroundStyle(QColor.violet)233                        .padding(.horizontal, 12)234                        .frame(minHeight: 36)235                        .background(QColor.surfaceRaised, in: Capsule())236                        .overlay(Capsule().strokeBorder(QColor.stroke, lineWidth: 1))237                        .frame(minHeight: 44)238                        .buttonStyle(.plain)239                        .accessibilityLabel("Use the maximum spendable amount")240                }241            }242            Rectangle()243                .fill(error != nil ? QColor.negative : (focused ? QColor.violet : QColor.stroke))244                .frame(height: focused || error != nil ? 2 : 1)245                .animation(.snappy(duration: 0.2), value: focused)246            if let error {247                Label(error, systemImage: "exclamationmark.circle")248                    .font(QFont.caption)249                    .foregroundStyle(QColor.negative)250                    .fixedSize(horizontal: false, vertical: true)251            } else if let fiat {252                Text(fiat).font(QFont.callout.monospacedDigit()).foregroundStyle(QColor.textSecondary)253                    .contentTransition(.numericText())254            }255        }256    }257}258259#if DEBUG260private struct AmountPreview: View {261    @State private var text = ""262    @State private var hidden = false263264    var body: some View {265        VStack(alignment: .leading, spacing: 28) {266            AmountText(units: "123456789", decimals: 8, symbol: "PREVIEW", fiat: "preview fiat line", style: .balance, hidden: hidden)267            AmountText(units: UInt64(42_000), decimals: 8, symbol: "PREVIEW", maxFractionDigits: 6, sign: .incoming, hidden: hidden)268            AmountText(units: "1", decimals: 18, symbol: "PREVIEW", maxFractionDigits: 4, style: .compact, sign: .outgoing)269            Toggle("Hide amounts", isOn: $hidden)270            AmountField(text: $text, symbol: "PREVIEW", maxFractionDigits: 8, fiat: "preview fiat line") { text = "1" }271            AmountField(text: .constant("9"), symbol: "PREVIEW", maxFractionDigits: 8, error: "Preview validation message")272        }273        .padding()274        .qScreen()275    }276}277278#Preview("Amounts") { AmountPreview() }279#endif280
Files main
Menu

Theme