SPB Git

Repository Public

Rows.swift 16.2 KB 406 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/Rows.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 SwiftUI4243/// Round asset glyph: Bitcoin and Ethereum have their own mark, any other asset shows its initials.44public struct AssetGlyph: View {45    public enum Kind: Sendable, Equatable {46        case bitcoin47        case ethereum48        case token(symbol: String)49    }5051    let kind: Kind52    @ScaledMetric(relativeTo: .body) private var size: CGFloat = 405354    public init(_ kind: Kind) { self.kind = kind }5556    var tint: Color {57        switch kind {58        case .bitcoin: return QColor.bitcoin59        case .ethereum: return QColor.ethereum60        case .token: return QColor.textSecondary61        }62    }6364    public var body: some View {65        // Drawn with the chain identity system: the same marks as `ChainGlyph` and `TokenGlyph`.66        Group {67            switch kind {68            case .bitcoin: ChainGlyph(.bitcoin)69            case .ethereum: ChainGlyph(.ethereum)70            case .token(let symbol): TokenGlyph(symbol: symbol)71            }72        }73        .accessibilityHidden(true)74    }75}7677/// One asset of the portfolio: glyph, name, network note, balance and optional fiat value.78public struct AssetRow: View {79    let glyph: AssetGlyph.Kind80    let name: String81    let note: String?82    let units: String83    let decimals: Int84    let symbol: String85    let maxFractionDigits: Int?86    let fiat: String?87    let hidden: Bool88    var asset: QAssetIdentity?89    var change: QChange?90    @Environment(\.dynamicTypeSize) private var typeSize9192    /// - Parameters:93    ///   - note: secondary line under the name (network, "Testnet", token standard…).94    ///   - units/decimals/symbol: the balance in base units; formatted by `AmountText`.95    ///   - fiat: already formatted fiat value, or nil when no price is known.96    public init(glyph: AssetGlyph.Kind, name: String, note: String? = nil, units: String, decimals: Int, symbol: String,97                maxFractionDigits: Int? = 8, fiat: String? = nil, hidden: Bool = false) {98        self.glyph = glyph99        self.name = name100        self.note = note101        self.units = units102        self.decimals = decimals103        self.symbol = symbol104        self.maxFractionDigits = maxFractionDigits105        self.fiat = fiat106        self.hidden = hidden107    }108109    /// The multi-chain row: the glyph says which asset it is and, for a token, on which chain it lives; the caption110    /// names the network in words (with a "TEST" tag on a test network); the trailing side carries the balance, its111    /// fiat value and the change over 24 hours.112    ///113    /// - Parameters:114    ///   - asset: a native coin or a token, with its network.115    ///   - note: replaces the network name in the caption when given ("Sepolia · ERC-20").116    ///   - maxFractionDigits: nil applies `AssetPrecision` (four significant digits, never rounded up).117    ///   - change: change of the price over 24 hours, or nil when no price is known.118    public init(asset: QAssetIdentity, name: String, note: String? = nil, units: String, decimals: Int, symbol: String,119                maxFractionDigits: Int? = nil, fiat: String? = nil, change: QChange? = nil, hidden: Bool = false) {120        switch asset {121        case .native(let network): self.glyph = network.chain == .bitcoin ? .bitcoin : (network.chain == .ethereum ? .ethereum : .token(symbol: symbol))122        case .token(let tokenSymbol, _): self.glyph = .token(symbol: tokenSymbol)123        }124        self.asset = asset125        self.name = name126        self.note = note127        self.units = units128        self.decimals = decimals129        self.symbol = symbol130        self.maxFractionDigits = maxFractionDigits ?? AssetPrecision.fractionDigits(units: units, decimals: decimals)131        self.fiat = fiat132        self.change = change133        self.hidden = hidden134    }135136    /// The network in words; for a coin whose name is already the network's ("Bitcoin" on Bitcoin), "Native coin".137    nonisolated static func caption(for asset: QAssetIdentity, name: String) -> String {138        if case .native(let network) = asset, network.fullName.caseInsensitiveCompare(name) == .orderedSame { return "Native coin" }139        return asset.network.fullName140    }141142    @ViewBuilder var leading: some View {143        VStack(alignment: .leading, spacing: 3) {144            Text(name).font(QFont.headline).foregroundStyle(QColor.textPrimary).lineLimit(1)145            if let asset {146                HStack(spacing: 6) {147                    Text(note ?? Self.caption(for: asset, name: name)).font(QFont.caption).foregroundStyle(QColor.textSecondary).lineLimit(1)148                    if asset.network.isTest { QTestTag() }149                }150            } else if let note {151                Text(note).font(QFont.caption).foregroundStyle(QColor.textSecondary).lineLimit(1)152            }153        }154    }155156    @ViewBuilder func trailing(alignment: HorizontalAlignment) -> some View {157        if asset != nil {158            VStack(alignment: alignment, spacing: 3) {159                AmountText(units: units, decimals: decimals, symbol: symbol, maxFractionDigits: maxFractionDigits, hidden: hidden)160                    .compactingLargeAmounts()161                    .leadingAligned(alignment == .leading)162                if fiat != nil || change != nil {163                    // side by side, or one under the other when the text is very large164                    let layout = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(alignment: alignment, spacing: 2)) : AnyLayout(HStackLayout(spacing: 6))165                    layout {166                        if let fiat {167                            Text(hidden ? "••••" : fiat).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textSecondary).lineLimit(1)168                        }169                        if let change { ChangeLabel(change) }170                    }171                }172            }173        } else {174            AmountText(units: units, decimals: decimals, symbol: symbol, maxFractionDigits: maxFractionDigits, fiat: fiat, hidden: hidden)175        }176    }177178    public var body: some View {179        HStack(spacing: 12) {180            if let asset { AssetIdentityGlyph(asset) } else { AssetGlyph(glyph) }181            if asset != nil, typeSize >= .xxLarge {182                VStack(alignment: .leading, spacing: 4) {183                    leading184                    trailing(alignment: .leading)185                }186                Spacer(minLength: 0)187            } else {188                leading189                Spacer(minLength: 8)190                trailing(alignment: .trailing)191            }192        }193        .padding(.vertical, asset == nil ? 6 : QSpace.s)194        .frame(minHeight: asset == nil ? 52 : QMetric.rowMinHeight)195        .contentShape(Rectangle())196        .accessibilityElement(children: .combine)197    }198}199200/// One transaction: direction mark and label, counterparty, amount, status pill and time.201public struct TransactionRow: View {202    public enum Direction: Sendable, Equatable {203        case incoming, outgoing, selfTransfer, contract204205        var systemImage: String {206            switch self {207            case .incoming: return "arrow.down.left"208            case .outgoing: return "arrow.up.right"209            case .selfTransfer: return "arrow.triangle.2.circlepath"210            case .contract: return "doc.text"211            }212        }213214        var label: String {215            switch self {216            case .incoming: return "Received"217            case .outgoing: return "Sent"218            case .selfTransfer: return "Internal transfer"219            case .contract: return "Contract call"220            }221        }222223        var sign: AmountText.Sign {224            switch self {225            case .incoming: return .incoming226            case .outgoing: return .outgoing227            default: return .none228            }229        }230    }231232    public enum Status: Sendable, Equatable {233        /// In the mempool or below the confirmation target; `confirmations` and `target` are shown when given.234        case pending(confirmations: Int?, target: Int?)235        case confirmed236        case failed237        case replaced238239        var text: String {240            switch self {241            case .pending(let confirmations, let target):242                if let confirmations, let target { return "Pending \(confirmations)/\(target)" }243                if let confirmations, confirmations > 0 { return "Pending, \(confirmations) conf." }244                return "Pending"245            case .confirmed: return "Confirmed"246            case .failed: return "Failed"247            case .replaced: return "Replaced"248            }249        }250251        var systemImage: String {252            switch self {253            case .pending: return "clock"254            case .confirmed: return "checkmark"255            case .failed: return "xmark"256            case .replaced: return "arrow.uturn.backward"257            }258        }259260        var tone: QBadge.Tone {261            switch self {262            case .pending: return .warning263            case .confirmed: return .neutral264            case .failed: return .negative265            case .replaced: return .neutral266            }267        }268    }269270    let direction: Direction271    let title: String?272    let counterparty: String?273    let units: String274    let decimals: Int275    let symbol: String276    let maxFractionDigits: Int?277    let status: Status278    let date: Date?279    let hidden: Bool280    @ScaledMetric(relativeTo: .body) private var markSize: CGFloat = 36281    @Environment(\.dynamicTypeSize) private var typeSize282283    /// - Parameters:284    ///   - title: overrides the direction label ("Token approval"…).285    ///   - counterparty: address or name of the other side; addresses are truncated in the middle.286    ///   - date: time of the transaction, nil while it is unconfirmed and has no timestamp.287    public init(direction: Direction, title: String? = nil, counterparty: String? = nil, units: String, decimals: Int, symbol: String,288                maxFractionDigits: Int? = 8, status: Status, date: Date? = nil, hidden: Bool = false) {289        self.direction = direction290        self.title = title291        self.counterparty = counterparty292        self.units = units293        self.decimals = decimals294        self.symbol = symbol295        self.maxFractionDigits = maxFractionDigits296        self.status = status297        self.date = date298        self.hidden = hidden299    }300301    var timeText: String? {302        date.map { $0.formatted(.relative(presentation: .named, unitsStyle: .abbreviated)) }303    }304305    var mark: some View {306        Image(systemName: direction.systemImage)307            .font(.footnote.weight(.bold))308            .foregroundStyle(direction == .incoming ? QColor.positive : QColor.textPrimary)309            .frame(width: markSize, height: markSize)310            .background(QColor.surfaceRaised, in: Circle())311            .overlay(Circle().strokeBorder(QColor.stroke, lineWidth: 1))312            .accessibilityHidden(true)313    }314315    var leading: some View {316        VStack(alignment: .leading, spacing: 3) {317            Text(title ?? direction.label).font(QFont.headline).foregroundStyle(QColor.textPrimary).lineLimit(1)318            if let counterparty {319                Text(MiddleTruncation.truncate(counterparty, head: 8, tail: 6))320                    .font(QFont.mono)321                    .foregroundStyle(QColor.textSecondary)322                    .lineLimit(1)323            }324            if let timeText {325                Text(timeText).font(QFont.caption).foregroundStyle(QColor.textTertiary).lineLimit(1)326            }327        }328    }329330    var amount: some View {331        AmountText(units: units, decimals: decimals, symbol: symbol, maxFractionDigits: maxFractionDigits, sign: direction.sign, hidden: hidden)332    }333334    var pill: some View { QBadge(status.text, systemImage: status.systemImage, tone: status.tone) }335336    public var body: some View {337        Group {338            if typeSize >= .xxLarge {339                // Large text: the amount and the status go under the label instead of squeezing it.340                VStack(alignment: .leading, spacing: 8) {341                    HStack(spacing: 10) { mark; leading }342                    HStack(alignment: .center, spacing: 10) { amount; Spacer(minLength: 0); pill }343                }344            } else {345                HStack(alignment: .center, spacing: 12) {346                    mark347                    leading348                    Spacer(minLength: 8)349                    VStack(alignment: .trailing, spacing: 5) {350                        amount351                        pill352                    }353                }354            }355        }356        .padding(.vertical, 6)357        .contentShape(Rectangle())358        .accessibilityElement(children: .ignore)359        .accessibilityLabel(spoken)360    }361362    var spokenStatus: String {363        if case .pending(let confirmations, let target) = status, let confirmations {364            return target.map { "pending, \(confirmations) of \($0) confirmations" } ?? "pending, \(confirmations) confirmations"365        }366        return status.text367    }368369    var spoken: String {370        var parts = [title ?? direction.label]371        if hidden {372            parts.append("amount hidden")373        } else {374            parts.append(AmountFormat.format(units: units, decimals: decimals, maxFractionDigits: maxFractionDigits) + " " + symbol)375        }376        if let counterparty { parts.append("counterparty " + MiddleTruncation.truncate(counterparty, head: 6, tail: 4, ellipsis: " to ")) }377        parts.append(spokenStatus)378        if let timeText { parts.append(timeText) }379        return parts.joined(separator: ", ")380    }381}382383#if DEBUG384#Preview("Rows") {385    ScrollView {386        VStack(spacing: 4) {387            AssetRow(glyph: .bitcoin, name: "Preview asset", note: "Preview network", units: "150000", decimals: 8, symbol: "PRV", fiat: "preview fiat")388            Divider()389            AssetRow(glyph: .ethereum, name: "Preview asset", units: "1500000000000000", decimals: 18, symbol: "PRV")390            Divider()391            AssetRow(glyph: .token(symbol: "prv"), name: "Preview token", units: "42", decimals: 0, symbol: "PRV", hidden: true)392            Divider()393            TransactionRow(direction: .incoming, counterparty: "preview0counterparty0value0000", units: "21000", decimals: 8, symbol: "PRV",394                           status: .pending(confirmations: 1, target: 6), date: Date(timeIntervalSinceNow: -400))395            Divider()396            TransactionRow(direction: .outgoing, counterparty: "preview0counterparty0value0000", units: "5000000", decimals: 8, symbol: "PRV",397                           status: .confirmed, date: Date(timeIntervalSinceNow: -86_400))398            Divider()399            TransactionRow(direction: .contract, title: "Preview title", units: "0", decimals: 18, symbol: "PRV", status: .failed)400        }401        .padding()402    }403    .qScreen()404}405#endif406
Files main
Menu

Theme