SPB Git

Repository Public

Transfer.swift 48.8 KB 1,104 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/Transfer.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// 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// MARK: - Chunked address4445/// An address in full, in groups of four with the first and last groups emphasised (see `AddressChunks`). The groups46/// never break in the middle; VoiceOver spells the address group by group.47public struct ChunkedAddressText: View {48    let address: String49    let font: Font50    let alignment: TextAlignment5152    public init(_ address: String, font: Font = QFont.monoLarge, alignment: TextAlignment = .leading) {53        self.address = address54        self.font = font55        self.alignment = alignment56    }5758    var attributed: AttributedString {59        var out = AttributedString()60        for chunk in AddressChunks.chunks(address) {61            var part = AttributedString(chunk.text)62            switch chunk.role {63            case .prefix:64                part.foregroundColor = QColor.textTertiary65            case .emphasized:66                part.foregroundColor = QColor.textPrimary67                part.font = font.weight(.bold)68                part.underlineStyle = .single69            case .plain:70                part.foregroundColor = QColor.textSecondary71            }72            out.append(part)73            // a narrow no-break space would glue the groups together: a regular space lets the line break between them74            if chunk.role != .prefix { out.append(AttributedString(" ")) }75        }76        return out77    }7879    public var body: some View {80        Text(attributed)81            .font(font)82            .multilineTextAlignment(alignment)83            .lineSpacing(5)84            .fixedSize(horizontal: false, vertical: true)85            .privacySensitive()86            .accessibilityLabel(AddressChunks.spoken(address))87    }88}8990// MARK: - Review9192/// Hairline between two rows of a card.93public struct QSeparator: View {94    public init() {}95    public var body: some View {96        Rectangle().fill(QColor.stroke).frame(height: QMetric.hairline).accessibilityHidden(true)97    }98}99100/// A titled card of the review screen. Its rows are separated by hairlines; an optional footnote sits under it.101public struct ReviewSection<Content: View>: View {102    let title: String?103    let footnote: String?104    let content: Content105106    public init(_ title: String? = nil, footnote: String? = nil, @ViewBuilder content: () -> Content) {107        self.title = title108        self.footnote = footnote109        self.content = content()110    }111112    public var body: some View {113        VStack(alignment: .leading, spacing: QSpace.s) {114            if let title { QEyebrow(title).padding(.leading, 2) }115            VStack(alignment: .leading, spacing: 0) {116                Group(subviews: content) { subviews in117                    ForEach(Array(subviews.enumerated()), id: \.element.id) { index, subview in118                        subview.padding(.horizontal, QMetric.padding).padding(.vertical, 13)119                        if index < subviews.count - 1 { QSeparator().padding(.leading, QMetric.padding) }120                    }121                }122            }123            .frame(maxWidth: .infinity, alignment: .leading)124            .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous))125            .overlay(RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))126            if let footnote {127                Text(footnote).font(QFont.caption).foregroundStyle(QColor.textSecondary)128                    .fixedSize(horizontal: false, vertical: true)129                    .padding(.horizontal, 2)130            }131        }132    }133}134135/// One line of a review: a label, the value, an optional second value (fiat, a note) and an optional copy control.136public struct ReviewRow: View {137    public enum Emphasis: Sendable {138        /// Label on the left, value on the right.139        case standard140        /// The line the user must read (amount, total): larger value.141        case strong142        /// A hash or an identifier: monospaced, wrapped at any character, under its label.143        case mono144        /// An address: in full, in groups, first and last groups emphasised, under its label.145        case address146    }147148    let label: String149    let value: String150    let secondary: String?151    let emphasis: Emphasis152    let copyValue: String?153    @Environment(\.dynamicTypeSize) private var typeSize154155    /// - Parameter copyValue: when given, a copy control copies exactly this string.156    public init(_ label: String, value: String, secondary: String? = nil, emphasis: Emphasis = .standard, copyValue: String? = nil) {157        self.label = label158        self.value = value159        self.secondary = secondary160        self.emphasis = emphasis161        self.copyValue = copyValue162    }163164    var stacked: Bool { emphasis == .mono || emphasis == .address || typeSize.isAccessibilitySize }165166    @ViewBuilder var valueView: some View {167        switch emphasis {168        case .standard:169            Text(value).font(QFont.callout.monospacedDigit()).foregroundStyle(QColor.textPrimary)170        case .strong:171            Text(value).font(Font.system(.title3, design: .rounded, weight: .semibold).monospacedDigit()).foregroundStyle(QColor.textPrimary)172        case .mono:173            Text(UnbrokenValue.wrappable(value)).font(QFont.mono).foregroundStyle(QColor.textPrimary)174        case .address:175            ChunkedAddressText(value, font: QFont.mono.weight(.medium))176        }177    }178179    var spokenValue: String {180        switch emphasis {181        case .mono: return MiddleTruncation.grouped(value)182        case .address: return AddressChunks.spoken(value)183        default: return value184        }185    }186187    public var body: some View {188        HStack(alignment: .center, spacing: QSpace.s) {189            Group {190                if stacked {191                    VStack(alignment: .leading, spacing: 4) {192                        Text(label).font(QFont.callout).foregroundStyle(QColor.textSecondary)193                        valueView194                        if let secondary {195                            Text(secondary).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textSecondary)196                        }197                    }198                    .frame(maxWidth: .infinity, alignment: .leading)199                } else {200                    HStack(alignment: .firstTextBaseline, spacing: QSpace.m) {201                        Text(label).font(QFont.callout).foregroundStyle(QColor.textSecondary)202                        Spacer(minLength: QSpace.s)203                        VStack(alignment: .trailing, spacing: 2) {204                            valueView.multilineTextAlignment(.trailing)205                            if let secondary {206                                Text(secondary).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textSecondary)207                                    .multilineTextAlignment(.trailing)208                            }209                        }210                    }211                }212            }213            .fixedSize(horizontal: false, vertical: true)214            .privacySensitive()215            .accessibilityElement(children: .ignore)216            .accessibilityLabel([label, spokenValue, secondary].compactMap { $0 }.joined(separator: ": "))217            if let copyValue {218                CopyButton(copyValue, title: "Copy \(label.lowercased())")219                    .padding(.vertical, -10)220                    .padding(.trailing, -8)221            }222        }223    }224}225226/// The network of a transaction about to be signed, as a full-width block at the top of every review: the chain227/// glyph, the network name and one sentence. A main network says that the funds are real, on a solid band; a test228/// network is hatched and dashed and says that its coins have no value. The optional notice (unaudited software)229/// is part of the block, so that it cannot be scrolled apart from the network it qualifies.230public struct NetworkReviewBanner: View {231    let network: QNetwork232    let unauditedNotice: String?233    @Environment(\.dynamicTypeSize) private var typeSize234235    /// - Parameter unauditedNotice: the sentence shown on a main network while the software is not audited, or nil.236    public init(network: QNetwork, unauditedNotice: String? = nil) {237        self.network = network238        self.unauditedNotice = unauditedNotice239    }240241    var tone: Color { network.isTest ? QColor.blue : QColor.warning }242243    var headline: String { network.isTest ? "Test network · no monetary value" : "Main network · real funds" }244245    var message: String {246        (network.isTest ? "This transaction moves test coins. They cannot be exchanged for money."247                        : "This transaction moves real funds and cannot be undone once it is broadcast.")248            + (network.detail.map { " \($0)." } ?? "")249    }250251    public var body: some View {252        let shape = RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous)253        VStack(alignment: .leading, spacing: 0) {254            // the band: solid for real funds, hatched for a test network255            ZStack {256                if network.isTest {257                    QColor.surfaceRaised258                    QHatch(spacing: 6).stroke(tone, lineWidth: 1.4)259                } else {260                    tone261                }262            }263            .frame(height: 8)264            .clipped()265            .accessibilityHidden(true)266            let layout = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(alignment: .leading, spacing: QSpace.m))267                                                      : AnyLayout(HStackLayout(alignment: .top, spacing: QSpace.m))268            layout {269                ChainGlyph(network)270                VStack(alignment: .leading, spacing: 4) {271                    Label(headline.uppercased(), systemImage: network.isTest ? "flask" : "exclamationmark.triangle.fill")272                        .labelStyle(QTightLabelStyle())273                        .font(QFont.eyebrow)274                        .kerning(0.8)275                        .foregroundStyle(tone)276                    Text(network.fullName).font(QFont.title).foregroundStyle(QColor.textPrimary)277                    Text(message).font(QFont.callout).foregroundStyle(QColor.textSecondary)278                }279                .fixedSize(horizontal: false, vertical: true)280            }281            .frame(maxWidth: .infinity, alignment: .leading)282            .padding(QMetric.padding)283            if let unauditedNotice, !network.isTest {284                QSeparator()285                Label(unauditedNotice, systemImage: "exclamationmark.shield")286                    .labelStyle(QTightLabelStyle(spacing: 10))287                    .font(QFont.footnote)288                    .foregroundStyle(QColor.textPrimary)289                    .fixedSize(horizontal: false, vertical: true)290                    .padding(.horizontal, QMetric.padding)291                    .padding(.vertical, 12)292            }293        }294        .frame(maxWidth: .infinity, alignment: .leading)295        .background(QColor.surface)296        .clipShape(shape)297        .overlay {298            if network.isTest {299                shape.strokeBorder(tone, style: StrokeStyle(lineWidth: 1.5, dash: [7, 5]))300            } else {301                shape.strokeBorder(tone, lineWidth: 1.5)302            }303        }304        .accessibilityElement(children: .ignore)305        .accessibilityAddTraits(.isHeader)306        .accessibilityLabel("\(network.fullName). \(headline). \(message)" + (network.isTest ? "" : (unauditedNotice.map { " " + $0 } ?? "")))307    }308}309310/// Icon and title on the first baseline with a fixed gap (the system style spaces them too far apart for eyebrows).311struct QTightLabelStyle: LabelStyle {312    var spacing: CGFloat = 5313314    func makeBody(configuration: Configuration) -> some View {315        HStack(alignment: .firstTextBaseline, spacing: spacing) {316            configuration.icon317            configuration.title318        }319    }320}321322// MARK: - Fee323324/// One fee option, already formatted by the caller. Chain-neutral: the same control serves sat/vB, gas, compute325/// units and energy.326public struct FeeTier: Identifiable, Sendable, Equatable {327    public enum Kind: String, Sendable, CaseIterable { case slow, normal, fast, custom }328329    public let kind: Kind330    public let title: String331    /// Expected delay in words ("about 10 min", "next block"), or nil when it is not known.332    public let timeHint: String?333    /// The fee in the native coin, formatted ("0.00012 BTC"), or nil while it is being estimated.334    public let fee: String?335    /// The same fee in fiat, or nil.336    public let fiat: String?337    /// The rate behind it ("12 sat/vB", "0.8 gwei"), or nil.338    public let rate: String?339340    public var id: Kind { kind }341342    public init(_ kind: Kind, title: String? = nil, timeHint: String? = nil, fee: String?, fiat: String? = nil, rate: String? = nil) {343        self.kind = kind344        self.title = title ?? Self.defaultTitle(kind)345        self.timeHint = timeHint346        self.fee = fee347        self.fiat = fiat348        self.rate = rate349    }350351    public static func defaultTitle(_ kind: Kind) -> String {352        switch kind {353        case .slow: return "Slow"354        case .normal: return "Normal"355        case .fast: return "Fast"356        case .custom: return "Custom"357        }358    }359}360361/// Choice of the fee: slow, normal, fast or custom, each with its delay, its cost and its fiat value. The selected362/// tier carries a filled radio mark and a heavier border, not just a colour.363public struct FeeTierPicker: View {364    let tiers: [FeeTier]365    @Binding var selection: FeeTier.Kind366    let onEditCustom: (() -> Void)?367    @Environment(\.dynamicTypeSize) private var typeSize368369    /// - Parameter onEditCustom: called when the custom tier is chosen (or tapped again) to open its editor.370    public init(tiers: [FeeTier], selection: Binding<FeeTier.Kind>, onEditCustom: (() -> Void)? = nil) {371        self.tiers = tiers372        self._selection = selection373        self.onEditCustom = onEditCustom374    }375376    @ViewBuilder func cost(_ tier: FeeTier, alignment: HorizontalAlignment) -> some View {377        VStack(alignment: alignment, spacing: 2) {378            if let fee = tier.fee {379                Text(fee).font(QFont.amount).foregroundStyle(QColor.textPrimary).lineLimit(1).minimumScaleFactor(0.75)380            } else if tier.kind == .custom {381                Text("Set").font(QFont.callout).foregroundStyle(QColor.textSecondary)382            } else {383                Text("—").font(QFont.amount).foregroundStyle(QColor.textTertiary).accessibilityLabel("Not estimated")384            }385            if let fiat = tier.fiat {386                Text(fiat).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textSecondary).lineLimit(1)387            }388        }389    }390391    func row(_ tier: FeeTier) -> some View {392        let selected = tier.kind == selection393        let shape = RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous)394        return Button {395            selection = tier.kind396            if tier.kind == .custom { onEditCustom?() }397        } label: {398            HStack(alignment: .center, spacing: QSpace.m) {399                Image(systemName: selected ? "largecircle.fill.circle" : "circle")400                    .font(.title3)401                    .foregroundStyle(selected ? QColor.violet : QColor.strokeStrong)402                    .accessibilityHidden(true)403                VStack(alignment: .leading, spacing: 2) {404                    Text(tier.title).font(QFont.headline).foregroundStyle(QColor.textPrimary)405                    if let hint = [tier.timeHint, tier.rate].compactMap({ $0 }).joined(separator: " · ").nilIfEmpty {406                        Text(hint).font(QFont.caption).foregroundStyle(QColor.textSecondary)407                    }408                    if typeSize.isAccessibilitySize { cost(tier, alignment: .leading).padding(.top, 2) }409                }410                .fixedSize(horizontal: false, vertical: true)411                Spacer(minLength: QSpace.s)412                if !typeSize.isAccessibilitySize { cost(tier, alignment: .trailing) }413                if tier.kind == .custom, onEditCustom != nil {414                    Image(systemName: "slider.horizontal.3").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary)415                        .accessibilityHidden(true)416                }417            }418            .padding(.horizontal, 14)419            .padding(.vertical, 12)420            .frame(maxWidth: .infinity, minHeight: QMetric.rowMinHeight, alignment: .leading)421            .background(selected ? QColor.surfaceRaised : QColor.surface, in: shape)422            .overlay(shape.strokeBorder(selected ? QColor.violet : QColor.stroke, lineWidth: selected ? 1.5 : 1))423            .contentShape(shape)424        }425        .buttonStyle(QPressableStyle())426        .accessibilityElement(children: .ignore)427        .accessibilityLabel([tier.title, tier.timeHint, tier.rate, tier.fee, tier.fiat].compactMap { $0 }.joined(separator: ", "))428        .accessibilityAddTraits(selected ? [.isSelected, .isButton] : .isButton)429    }430431    public var body: some View {432        VStack(spacing: QSpace.s) {433            ForEach(tiers) { row($0) }434        }435        .qHaptic(.selection, trigger: selection)436        .qAnimation(value: selection)437    }438}439440extension String {441    var nilIfEmpty: String? { isEmpty ? nil : self }442}443444// MARK: - Amount entry445446/// The amount of a payment: one large figure, the unit it is typed in with a control to switch between the coin and447/// fiat, the converted value, the available balance with MAX, and a line for a limit or an error.448public struct AmountEntryCard: View {449    @Binding var text: String450    let unit: String451    let maxFractionDigits: Int452    let converted: String?453    let onSwitchUnit: (() -> Void)?454    let balance: String?455    let onMax: (() -> Void)?456    let note: String?457    let error: String?458    @FocusState private var focused: Bool459    @State private var switches = 0460461    /// - Parameters:462    ///   - text: digits and one decimal separator, at most `maxFractionDigits` fraction digits (see `AmountFormat.parse`).463    ///   - unit: what is being typed ("BTC", or "USD" after a switch).464    ///   - converted: the same amount in the other unit, already formatted ("≈ $12.40"), or nil when no price is known.465    ///   - onSwitchUnit: when given, a control swaps the typed unit; the caller converts `text` and updates `unit`.466    ///   - balance: the spendable balance, formatted ("0.0421 BTC"), or nil.467    ///   - onMax: when given, MAX calls it; the caller writes the spendable amount into `text`.468    ///   - note: an inline limit or remark ("Mainnet limit: 0.001 BTC per transaction").469    ///   - error: a validation message; it replaces the note and marks the field.470    public init(text: Binding<String>, unit: String, maxFractionDigits: Int, converted: String? = nil, onSwitchUnit: (() -> Void)? = nil,471                balance: String? = nil, onMax: (() -> Void)? = nil, note: String? = nil, error: String? = nil) {472        self._text = text473        self.unit = unit474        self.maxFractionDigits = maxFractionDigits475        self.converted = converted476        self.onSwitchUnit = onSwitchUnit477        self.balance = balance478        self.onMax = onMax479        self.note = note480        self.error = error481    }482483    var separator: String { Locale.current.decimalSeparator ?? "." }484485    func chip(_ title: String, systemImage: String? = nil, label: String, action: @escaping () -> Void) -> some View {486        Button(action: action) {487            HStack(spacing: 5) {488                if let systemImage { Image(systemName: systemImage).imageScale(.small) }489                Text(title)490            }491            .font(.footnote.weight(.bold))492            .foregroundStyle(QColor.textPrimary)493            .padding(.horizontal, 12)494            .frame(minHeight: 34)495            .background(QColor.surfaceRaised, in: Capsule())496            .overlay(Capsule().strokeBorder(QColor.stroke, lineWidth: 1))497            .frame(minWidth: QMetric.minTap, minHeight: QMetric.minTap)498            .contentShape(Rectangle())499        }500        .buttonStyle(QPressableStyle())501        .accessibilityLabel(label)502    }503504    public var body: some View {505        let shape = RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous)506        VStack(alignment: .leading, spacing: 0) {507            VStack(alignment: .leading, spacing: QSpace.xs) {508                HStack(alignment: .center) {509                    QEyebrow("Amount")510                    Spacer(minLength: QSpace.s)511                    if let onSwitchUnit {512                        chip(unit, systemImage: "arrow.up.arrow.down", label: "Typing in \(unit). Switch unit") {513                            switches += 1514                            onSwitchUnit()515                        }516                        .padding(.vertical, -6)517                    }518                }519                HStack(alignment: .firstTextBaseline, spacing: QSpace.s) {520                    TextField("0", text: $text)521                        .font(QFont.display)522                        .foregroundStyle(QColor.textPrimary)523                        #if os(iOS)524                        .keyboardType(maxFractionDigits > 0 ? .decimalPad : .numberPad)525                        #endif526                        .autocorrectionDisabled()527                        .focused($focused)528                        .minimumScaleFactor(0.5)529                        .onChange(of: text) { _, new in530                            let clean = AmountFormat.sanitize(new, maxFractionDigits: maxFractionDigits, decimalSeparator: separator)531                            if clean != new { text = clean }532                        }533                        .accessibilityLabel("Amount in \(unit)")534                    Text(unit)535                        .font(Font.system(.title3, design: .rounded, weight: .medium))536                        .foregroundStyle(QColor.textSecondary)537                        .lineLimit(1)538                }539                if converted != nil || onSwitchUnit != nil {540                    // the line keeps its place while a price loads, so that the card does not jump541                    Text(converted ?? " ")542                        .font(QFont.callout.monospacedDigit())543                        .foregroundStyle(QColor.textSecondary)544                        .lineLimit(1)545                        .qNumericTransition()546                        .accessibilityHidden(converted == nil)547                }548            }549            .padding(QMetric.padding)550            if balance != nil || onMax != nil {551                QSeparator()552                HStack(alignment: .center, spacing: QSpace.s) {553                    VStack(alignment: .leading, spacing: 1) {554                        Text("Available").font(QFont.caption).foregroundStyle(QColor.textSecondary)555                        Text(balance ?? "—").font(QFont.amount).foregroundStyle(QColor.textPrimary).lineLimit(1).minimumScaleFactor(0.7)556                            .privacySensitive()557                    }558                    .accessibilityElement(children: .combine)559                    Spacer(minLength: QSpace.s)560                    if let onMax {561                        chip("MAX", label: "Use the maximum spendable amount", action: onMax)562                    }563                }564                .padding(.horizontal, QMetric.padding)565                .padding(.vertical, 6)566            }567            if let line = error ?? note {568                QSeparator()569                Label(line, systemImage: error != nil ? "exclamationmark.circle" : "info.circle")570                    .labelStyle(QTightLabelStyle(spacing: 8))571                    .font(QFont.footnote)572                    .foregroundStyle(error != nil ? QColor.negative : QColor.textSecondary)573                    .fixedSize(horizontal: false, vertical: true)574                    .padding(.horizontal, QMetric.padding)575                    .padding(.vertical, 12)576                    .accessibilityLabel((error != nil ? "Error: " : "") + line)577            }578        }579        .frame(maxWidth: .infinity, alignment: .leading)580        .background(QColor.surface, in: shape)581        .overlay(shape.strokeBorder(error != nil ? QColor.negative : (focused ? QColor.violet : QColor.stroke),582                                    lineWidth: error != nil || focused ? 1.5 : 1))583        .qAnimation(value: focused)584        .qAnimation(value: error)585        .qHaptic(.selection, trigger: switches)586        .qHaptic(trigger: error) { $0 == nil ? nil : .warning }587    }588}589590// MARK: - Recipient591592/// A remark about the recipient, decided by the caller (the UI module does not know address formats).593public struct RecipientNote: Identifiable, Sendable, Equatable {594    public let id: String595    public let text: String596    public let tone: QTone597    public let systemImage: String598599    public init(id: String? = nil, text: String, tone: QTone = .neutral, systemImage: String = "info.circle") {600        self.id = id ?? text601        self.text = text602        self.tone = tone603        self.systemImage = systemImage604    }605606    /// Nothing was ever sent to this address from this wallet.607    public static func firstPayment(_ text: String = "First payment to this address. Check it against the recipient's own screen.") -> RecipientNote {608        RecipientNote(id: "first", text: text, tone: .warning, systemImage: "person.crop.circle.badge.questionmark")609    }610611    /// The address belongs to this wallet.612    public static func ownAddress(_ text: String = "This is one of your own addresses.") -> RecipientNote {613        RecipientNote(id: "own", text: text, tone: .info, systemImage: "arrow.triangle.swap")614    }615616    /// The checksum of the address was verified.617    public static func checksumValid(_ text: String = "Checksum verified.") -> RecipientNote {618        RecipientNote(id: "checksum", text: text, tone: .positive, systemImage: "checkmark.seal")619    }620621    /// The address format (or the way it was typed) carries no checksum: a typing error cannot be detected.622    public static func noChecksum(_ text: String = "This address has no checksum: a mistyped character cannot be detected. Compare every group.") -> RecipientNote {623        RecipientNote(id: "nochecksum", text: text, tone: .warning, systemImage: "exclamationmark.triangle")624    }625}626627/// The recipient of a payment: the address field with paste and scan, its validity, the address in groups for628/// comparison once it is valid, and the remarks that apply (first payment, own address, checksum).629public struct RecipientCard: View {630    @Binding var text: String631    let title: String632    let placeholder: String633    let validity: FieldValidity634    let notes: [RecipientNote]635    let network: QNetwork?636    let onScan: (() -> Void)?637638    /// - Parameter network: when given, the card says on which network the address must live.639    public init(text: Binding<String>, title: String = "Recipient", placeholder: String = "Recipient address", validity: FieldValidity = .empty,640                notes: [RecipientNote] = [], network: QNetwork? = nil, onScan: (() -> Void)? = nil) {641        self._text = text642        self.title = title643        self.placeholder = placeholder644        self.validity = validity645        self.notes = notes646        self.network = network647        self.onScan = onScan648    }649650    var isValid: Bool {651        if case .valid = validity { return true }652        return false653    }654655    public var body: some View {656        VStack(alignment: .leading, spacing: QSpace.m) {657            // on one line when both fit, the network under the title otherwise: its name is never cut658            ViewThatFits(in: .horizontal) {659                HStack(alignment: .center, spacing: QSpace.s) {660                    QEyebrow(title)661                    Spacer(minLength: QSpace.s)662                    if let network { NetworkBadge(network, style: .plain).fixedSize() }663                }664                VStack(alignment: .leading, spacing: QSpace.s) {665                    QEyebrow(title)666                    if let network { NetworkBadge(network, style: .plain) }667                }668            }669            AddressField(text: $text, placeholder: placeholder, validity: validity, onScan: onScan)670            if isValid, !text.isEmpty {671                VStack(alignment: .leading, spacing: 6) {672                    Text("Compare with the recipient's address").font(QFont.caption).foregroundStyle(QColor.textSecondary)673                    ChunkedAddressText(text, font: QFont.mono.weight(.medium))674                }675                .padding(12)676                .frame(maxWidth: .infinity, alignment: .leading)677                .background(QColor.surfaceSunken, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))678            }679            if !notes.isEmpty {680                VStack(alignment: .leading, spacing: QSpace.s) {681                    ForEach(notes) { note in682                        Label(note.text, systemImage: note.systemImage)683                            .labelStyle(QTightLabelStyle(spacing: 8))684                            .font(QFont.footnote)685                            .foregroundStyle(note.tone == .neutral ? QColor.textSecondary : note.tone.color)686                            .fixedSize(horizontal: false, vertical: true)687                    }688                }689            }690        }691        .padding(QMetric.padding)692        .frame(maxWidth: .infinity, alignment: .leading)693        .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous))694        .overlay(RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))695        .qAnimation(value: isValid)696    }697}698699// MARK: - Confirmation700701/// The last gesture before a signature: the key is dragged to the end of its track, which a stray tap cannot do.702/// With VoiceOver or Switch Control running — or when `prefersButton` is set — the same action is a standard703/// button, since a drag is not available to everyone.704public struct SlideToConfirm: View {705    let title: String706    let buttonTitle: String707    let isEnabled: Bool708    let isWorking: Bool709    let prefersButton: Bool710    let onConfirm: () -> Void711712    @State private var offset: CGFloat = 0713    @State private var committed = false714    @State private var commits = 0715    @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver716    @Environment(\.accessibilitySwitchControlEnabled) private var switchControl717    @Environment(\.accessibilityReduceMotion) private var reduceMotion718    @ScaledMetric(relativeTo: .body) private var height: CGFloat = 60719720    /// - Parameters:721    ///   - title: what the gesture does ("Slide to sign and send").722    ///   - buttonTitle: label of the button that replaces the slider for assistive technologies.723    ///   - isWorking: true while the signature or the broadcast runs: the control shows progress and ignores input.724    public init(_ title: String = "Slide to sign", buttonTitle: String = "Sign", isEnabled: Bool = true, isWorking: Bool = false,725                prefersButton: Bool = false, onConfirm: @escaping () -> Void) {726        self.title = title727        self.buttonTitle = buttonTitle728        self.isEnabled = isEnabled729        self.isWorking = isWorking730        self.prefersButton = prefersButton731        self.onConfirm = onConfirm732    }733734    /// The fraction of the track after which releasing the key confirms.735    public nonisolated static let threshold = 0.88736737    /// Whether a release at `offset` on a track of `travel` points confirms.738    public nonisolated static func confirms(offset: CGFloat, travel: CGFloat) -> Bool {739        travel > 0 && Double(offset / travel) >= threshold740    }741742    func commit() {743        guard !committed else { return }744        committed = true745        commits += 1746        onConfirm()747        Task { @MainActor in748            try? await Task.sleep(for: .seconds(1.2))749            if !isWorking { reset() }750        }751    }752753    func reset() {754        withAnimation(QMotion.resolved(QMotion.emphasized, reduceMotion: reduceMotion)) {755            committed = false756            offset = 0757        }758    }759760    var slider: some View {761        let h = min(height, 76)762        let inset: CGFloat = 4763        let key = h - inset * 2764        let shape = RoundedRectangle(cornerRadius: QMetric.radiusSmall + 4, style: .continuous)765        let keyShape = RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous)766        return GeometryReader { geo in767            let travel = max(0, geo.size.width - key - inset * 2)768            let x = committed ? travel : min(max(0, offset), travel)769            let progress = travel > 0 ? x / travel : 0770            ZStack(alignment: .leading) {771                shape.fill(QColor.surfaceSunken)772                // the part already travelled773                keyShape.fill(QColor.violet.opacity(0.22))774                    .frame(width: x + key)775                    .padding(inset)776                Text(committed ? (isWorking ? "Signing" : "Confirmed") : title)777                    .font(QFont.headline)778                    .foregroundStyle(QColor.textPrimary)779                    .lineLimit(1)780                    .minimumScaleFactor(0.7)781                    .opacity(committed ? 1 : max(0, 1 - progress * 1.6))782                    .frame(maxWidth: .infinity)783                    .padding(.leading, key + inset * 2)784                    .padding(.trailing, 46)785                HStack(spacing: -4) {786                    ForEach(0..<3, id: \.self) { index in787                        Image(systemName: "chevron.right")788                            .font(.footnote.weight(.bold))789                            .foregroundStyle(QColor.textTertiary.opacity(0.35 + Double(index) * 0.25))790                    }791                }792                .frame(maxWidth: .infinity, alignment: .trailing)793                .padding(.trailing, 16)794                .opacity(committed ? 0 : max(0, 1 - progress * 2.5))795                .accessibilityHidden(true)796                Group {797                    if committed, isWorking {798                        ProgressView().tint(QColor.onAccent)799                    } else {800                        Image(systemName: committed ? "checkmark" : "arrow.right")801                            .font(.system(size: key * 0.36, weight: .bold))802                            .contentTransition(.symbolEffect(.replace))803                    }804                }805                .foregroundStyle(QColor.onAccent)806                .frame(width: key, height: key)807                .background(QColor.accentGradient, in: keyShape)808                .offset(x: x + inset)809                .gesture(810                    DragGesture(minimumDistance: 2)811                        .onChanged { value in812                            guard !committed, isEnabled, !isWorking else { return }813                            offset = min(max(0, value.translation.width), travel)814                        }815                        .onEnded { _ in816                            guard !committed, isEnabled, !isWorking else { return }817                            if Self.confirms(offset: offset, travel: travel) {818                                withAnimation(QMotion.resolved(QMotion.standard, reduceMotion: reduceMotion)) { offset = travel }819                                commit()820                            } else {821                                withAnimation(QMotion.resolved(QMotion.emphasized, reduceMotion: reduceMotion)) { offset = 0 }822                            }823                        }824                )825            }826            .overlay(shape.strokeBorder(QColor.stroke, lineWidth: 1))827        }828        .frame(height: h)829        .opacity(isEnabled ? 1 : 0.4)830        .allowsHitTesting(isEnabled && !isWorking)831        .accessibilityElement(children: .ignore)832        .accessibilityLabel(buttonTitle)833        .accessibilityHint("Slide the key to the end of the track, or activate to confirm.")834        .accessibilityAddTraits(.isButton)835        .accessibilityAction { if isEnabled, !isWorking { commit() } }836    }837838    public var body: some View {839        Group {840            if voiceOver || switchControl || prefersButton {841                LoadingButton(buttonTitle, loadingTitle: "Signing", systemImage: "signature", state: isWorking ? .loading : .idle) {842                    commits += 1843                    onConfirm()844                }845                .disabled(!isEnabled)846            } else {847                slider848            }849        }850        .qHaptic(.committed, trigger: commits)851        .onChange(of: isWorking) { _, working in852            if !working, committed { reset() }853        }854    }855}856857// MARK: - Result858859/// Outcome of a send: broadcast, waiting, or failed. A mark (check, clock, cross) in the same container as the chain860/// glyphs, a title, one sentence, the transaction identifier with a copy control, and a slot for the actions861/// (explorer link, done).862public struct ResultView<Actions: View>: View {863    public enum Status: Sendable, Equatable {864        /// Accepted by the network.865        case sent866        /// Signed and handed over; not confirmed yet.867        case pending868        case failed869870        var tone: QTone {871            switch self {872            case .sent: return .positive873            case .pending: return .info874            case .failed: return .critical875            }876        }877878        var systemImage: String {879            switch self {880            case .sent: return "checkmark"881            case .pending: return "clock"882            case .failed: return "xmark"883            }884        }885886        var defaultTitle: String {887            switch self {888            case .sent: return "Sent"889            case .pending: return "Waiting for confirmation"890            case .failed: return "Not sent"891            }892        }893    }894895    let status: Status896    let title: String?897    let message: String898    let identifierLabel: String899    let identifier: String?900    let network: QNetwork?901    let actions: Actions902    @State private var appeared = false903    @Environment(\.accessibilityReduceMotion) private var reduceMotion904    @Environment(\.dynamicTypeSize) private var typeSize905    @ScaledMetric(relativeTo: .title) private var mark: CGFloat = 64906907    /// - Parameters:908    ///   - identifier: the transaction identifier, shown truncated in the middle with a copy control, or nil.909    ///   - actions: the controls under the result (a link to an explorer, a "Done" button).910    public init(status: Status, title: String? = nil, message: String, identifierLabel: String = "Transaction ID", identifier: String? = nil,911                network: QNetwork? = nil, @ViewBuilder actions: () -> Actions) {912        self.status = status913        self.title = title914        self.message = message915        self.identifierLabel = identifierLabel916        self.identifier = identifier917        self.network = network918        self.actions = actions()919    }920921    public var body: some View {922        let side = min(mark, 96)923        let shape = RoundedRectangle(cornerRadius: side * 0.3, style: .continuous)924        VStack(spacing: QSpace.xl) {925            VStack(spacing: QSpace.l) {926                Image(systemName: status.systemImage)927                    .font(.system(size: side * 0.4, weight: .semibold))928                    .foregroundStyle(status.tone.color)929                    .frame(width: side, height: side)930                    .background(QColor.surfaceRaised, in: shape)931                    .overlay {932                        if status == .pending {933                            shape.strokeBorder(status.tone.color, style: StrokeStyle(lineWidth: 1.5, dash: [6, 4]))934                        } else {935                            shape.strokeBorder(status.tone.color, lineWidth: 1.5)936                        }937                    }938                    .scaleEffect(appeared || reduceMotion ? 1 : 0.86)939                    .opacity(appeared ? 1 : 0)940                    .accessibilityHidden(true)941                VStack(spacing: QSpace.s) {942                    Text(title ?? status.defaultTitle).font(QFont.titleLarge).foregroundStyle(QColor.textPrimary)943                        .accessibilityAddTraits(.isHeader)944                    Text(message).font(QFont.callout).foregroundStyle(QColor.textSecondary)945                    if let network { NetworkBadge(network).padding(.top, QSpace.xs) }946                }947                .multilineTextAlignment(.center)948                .fixedSize(horizontal: false, vertical: true)949            }950            if let identifier {951                HStack(alignment: .center, spacing: QSpace.s) {952                    VStack(alignment: .leading, spacing: 3) {953                        Text(identifierLabel).font(QFont.caption).foregroundStyle(QColor.textSecondary)954                        Text(UnbrokenValue.wrappable(MiddleTruncation.truncate(identifier, head: 10, tail: 10)))955                            .font(QFont.mono)956                            .foregroundStyle(QColor.textPrimary)957                            .lineLimit(typeSize.isAccessibilitySize ? 3 : 1)958                            .minimumScaleFactor(typeSize.isAccessibilitySize ? 1 : 0.8)959                    }960                    .accessibilityElement(children: .ignore)961                    .accessibilityLabel("\(identifierLabel): \(MiddleTruncation.grouped(identifier))")962                    Spacer(minLength: QSpace.s)963                    CopyButton(identifier, title: "Copy \(identifierLabel.lowercased())")964                }965                .padding(.leading, QMetric.padding)966                .padding(.trailing, 6)967                .padding(.vertical, 8)968                .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))969                .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))970            }971            VStack(spacing: QSpace.m) { actions }972        }973        .frame(maxWidth: .infinity)974        .onAppear {975            withAnimation(QMotion.resolved(QMotion.emphasized, reduceMotion: reduceMotion)) { appeared = true }976        }977        .qHaptic(trigger: appeared) { shown in978            guard shown else { return nil }979            return status == .failed ? .failed : (status == .sent ? .sent : nil)980        }981    }982}983984public extension ResultView where Actions == EmptyView {985    init(status: Status, title: String? = nil, message: String, identifierLabel: String = "Transaction ID", identifier: String? = nil,986         network: QNetwork? = nil) {987        self.init(status: status, title: title, message: message, identifierLabel: identifierLabel, identifier: identifier, network: network) {988            EmptyView()989        }990    }991}992993// MARK: - Receive994995/// The receiving address of an account: the network it belongs to, the QR code, the address in groups with its first996/// and last groups emphasised, and copy and share controls. On a chain without a checksum the card says that the997/// comparison is the user's to make.998public struct AddressCard: View {999    let address: String1000    let network: QNetwork1001    let qrPayload: String?1002    let caption: String?1003    let hasChecksum: Bool1004    let showsShare: Bool1005    @ScaledMetric(relativeTo: .body) private var qrSide: CGFloat = 20810061007    /// - Parameters:1008    ///   - qrPayload: what the code encodes when it differs from the address (a payment URI); the address by default.1009    ///   - caption: one line under the network ("Native SegWit · account 1"), or nil.1010    ///   - hasChecksum: false for address formats in which a mistyped character cannot be detected.1011    public init(address: String, network: QNetwork, qrPayload: String? = nil, caption: String? = nil, hasChecksum: Bool = true,1012                showsShare: Bool = true) {1013        self.address = address1014        self.network = network1015        self.qrPayload = qrPayload1016        self.caption = caption1017        self.hasChecksum = hasChecksum1018        self.showsShare = showsShare1019    }10201021    var notice: String {1022        network.isTest ? "Test network. Coins received here have no monetary value."1023                       : "Send only \(network.chain.name) network assets to this address. Anything sent from another network is lost."1024    }10251026    public var body: some View {1027        let shape = RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous)1028        VStack(spacing: 0) {1029            HStack(alignment: .center, spacing: QSpace.m) {1030                ChainGlyph(network)1031                VStack(alignment: .leading, spacing: 3) {1032                    HStack(spacing: 6) {1033                        Text(network.fullName).font(QFont.headline).foregroundStyle(QColor.textPrimary)1034                        if network.isTest { QTestTag() }1035                    }1036                    if let caption {1037                        Text(caption).font(QFont.caption).foregroundStyle(QColor.textSecondary)1038                    }1039                }1040                .fixedSize(horizontal: false, vertical: true)1041                Spacer(minLength: 0)1042            }1043            .padding(QMetric.padding)1044            .accessibilityElement(children: .combine)1045            .accessibilityLabel(network.spokenName + (caption.map { ", " + $0 } ?? ""))1046            QSeparator()1047            VStack(spacing: QSpace.l) {1048                QRCodeView(payload: qrPayload ?? address, label: "QR code of the \(network.fullName) address")1049                    .frame(maxWidth: min(qrSide, 280))1050                VStack(spacing: QSpace.s) {1051                    ChunkedAddressText(address, alignment: .center)1052                    Text(hasChecksum ? "The first and last groups are underlined to help you compare."1053                                     : "This format has no checksum. Compare every group with what the sender sees.")1054                        .font(QFont.caption)1055                        .foregroundStyle(hasChecksum ? QColor.textSecondary : QColor.warning)1056                        .multilineTextAlignment(.center)1057                        .fixedSize(horizontal: false, vertical: true)1058                }1059            }1060            .padding(.horizontal, QMetric.padding)1061            .padding(.vertical, QSpace.xl)1062            .frame(maxWidth: .infinity)1063            QSeparator()1064            HStack(spacing: 0) {1065                CopyButton(address, title: "Copy address", style: .labelled)1066                    .frame(maxWidth: .infinity)1067                if showsShare {1068                    Rectangle().fill(QColor.stroke).frame(width: QMetric.hairline, height: 24).accessibilityHidden(true)1069                    ShareLink(item: address) {1070                        HStack(spacing: 6) {1071                            Image(systemName: "square.and.arrow.up")1072                            Text("Share")1073                        }1074                            .font(.callout.weight(.medium))1075                            .foregroundStyle(QColor.violet)1076                            .frame(maxWidth: .infinity, minHeight: QMetric.minTap)1077                            .contentShape(Rectangle())1078                    }1079                    .buttonStyle(.plain)1080                    .frame(maxWidth: .infinity)1081                }1082            }1083            .padding(.vertical, 4)1084            QSeparator()1085            Label(notice, systemImage: network.isTest ? "flask" : "exclamationmark.triangle")1086                .labelStyle(QTightLabelStyle(spacing: 8))1087                .font(QFont.footnote)1088                .foregroundStyle(QColor.textSecondary)1089                .fixedSize(horizontal: false, vertical: true)1090                .frame(maxWidth: .infinity, alignment: .leading)1091                .padding(.horizontal, QMetric.padding)1092                .padding(.vertical, 12)1093        }1094        .background(QColor.surface, in: shape)1095        .overlay {1096            if network.isTest {1097                shape.strokeBorder(QColor.strokeStrong, style: StrokeStyle(lineWidth: 1, dash: [7, 5]))1098            } else {1099                shape.strokeBorder(QColor.stroke, lineWidth: 1)1100            }1101        }1102    }1103}1104
Files main
Menu

Theme