SPB Git

Repository Public

Address.swift 12.5 KB 315 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/Address.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 SwiftUI42#if canImport(UIKit)43import UIKit44#endif4546/// An address or a hash in monospace, truncated in the middle, or shown in full on several lines (`head: .max`).47/// The full form wraps at any character and never shows a hyphen; the copy control always copies the exact value.48/// VoiceOver reads the full value in groups of four.49public struct AddressText: View {50    let address: String51    let head: Int52    let tail: Int53    let copyable: Bool54    let kind: String5556    /// - Parameters:57    ///   - kind: what the value is ("Address", "Transaction hash"…), used for the accessibility label.58    ///   - head/tail: characters kept on each side; pass `Int.max` for `head` to show the full value wrapped.59    public init(_ address: String, head: Int = 8, tail: Int = 6, copyable: Bool = true, kind: String = "Address") {60        self.address = address61        self.head = head62        self.tail = tail63        self.copyable = copyable64        self.kind = kind65    }6667    var showsFull: Bool { head == .max }6869    public var body: some View {70        HStack(alignment: .center, spacing: 4) {71            Text(showsFull ? UnbrokenValue.wrappable(address) : MiddleTruncation.truncate(address, head: head, tail: tail))72                .font(QFont.mono)73                .foregroundStyle(QColor.textPrimary)74                .lineLimit(showsFull ? nil : 1)75                .fixedSize(horizontal: false, vertical: true)76                .frame(maxWidth: showsFull ? .infinity : nil, alignment: .leading)77                .accessibilityLabel("\(kind): \(MiddleTruncation.grouped(address))")78            if copyable {79                CopyButton(address, title: "Copy \(kind.lowercased())")80            }81        }82    }83}8485/// Validity of a text field, decided by the caller (the UI module does not know address formats).86public enum FieldValidity: Sendable, Equatable {87    case empty88    case checking89    /// Valid; the optional note says what was recognised ("Bitcoin Testnet, native SegWit").90    case valid(String?)91    case invalid(String)92}9394/// The whitespace-free form an address field keeps: spaces and line breaks of a paste or of dictation are dropped.95public enum AddressInput {96    public static func sanitized(_ text: String) -> String {97        text.contains(where: { $0.isWhitespace || $0.isNewline }) ? text.filter { !$0.isWhitespace && !$0.isNewline } : text98    }99}100101#if canImport(UIKit)102/// Multi-line entry of an unbroken value. SwiftUI's vertical `TextField` breaks a long address like a word and draws103/// a hyphen at the break, which then reads as part of the address. This text view wraps by character: the line breaks104/// anywhere and nothing is drawn that the user did not type.105struct UnhyphenatedTextInput: UIViewRepresentable {106    @Binding var text: String107    @Binding var isFocused: Bool108    let label: String109110    func makeCoordinator() -> Coordinator { Coordinator(self) }111112    func makeUIView(context: Context) -> UITextView {113        let view = UITextView()114        view.delegate = context.coordinator115        view.backgroundColor = .clear116        view.isScrollEnabled = false117        view.textContainerInset = .zero118        view.textContainer.lineFragmentPadding = 0119        view.textContainer.lineBreakMode = .byCharWrapping120        view.textContainer.maximumNumberOfLines = 6121        view.autocorrectionType = .no122        view.autocapitalizationType = .none123        view.spellCheckingType = .no124        view.smartDashesType = .no125        view.smartQuotesType = .no126        view.smartInsertDeleteType = .no127        view.keyboardType = .asciiCapable128        view.returnKeyType = .done129        view.adjustsFontForContentSizeCategory = true130        view.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: .monospacedSystemFont(ofSize: 13, weight: .regular))131        view.textColor = UIColor(QColor.textPrimary)132        view.tintColor = UIColor(QColor.violet)133        view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)134        view.setContentHuggingPriority(.defaultLow, for: .horizontal)135        view.accessibilityLabel = label136        view.text = text137        return view138    }139140    func updateUIView(_ view: UITextView, context: Context) {141        context.coordinator.parent = self142        if view.text != text { view.text = text }143        view.accessibilityLabel = label144    }145146    func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize? {147        let width = max(40, proposal.width ?? 280)148        let fitted = uiView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude))149        return CGSize(width: width, height: ceil(fitted.height))150    }151152    final class Coordinator: NSObject, UITextViewDelegate {153        var parent: UnhyphenatedTextInput154        init(_ parent: UnhyphenatedTextInput) { self.parent = parent }155156        func textViewDidChange(_ textView: UITextView) {157            let clean = AddressInput.sanitized(textView.text ?? "")158            if clean != textView.text { textView.text = clean }159            if parent.text != clean { parent.text = clean }160        }161162        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText replacement: String) -> Bool {163            // the return key closes the keyboard: an address has no line break164            if replacement == "\n" {165                textView.resignFirstResponder()166                return false167            }168            return true169        }170171        func textViewDidBeginEditing(_ textView: UITextView) { parent.isFocused = true }172        func textViewDidEndEditing(_ textView: UITextView) { parent.isFocused = false }173    }174}175#endif176177/// Address entry with paste, an optional scan action and an inline validity line. A long address wraps at any178/// character and is never shown with a hyphen.179public struct AddressField: View {180    @Binding var text: String181    let placeholder: String182    let validity: FieldValidity183    let onScan: (() -> Void)?184    #if canImport(UIKit)185    @State private var focused = false186    #else187    @FocusState private var focused: Bool188    #endif189190    public init(text: Binding<String>, placeholder: String = "Recipient address", validity: FieldValidity = .empty, onScan: (() -> Void)? = nil) {191        self._text = text192        self.placeholder = placeholder193        self.validity = validity194        self.onScan = onScan195    }196197    var borderColor: Color {198        switch validity {199        case .invalid: return QColor.negative200        case .valid: return QColor.positive201        default: return focused ? QColor.violet : QColor.stroke202        }203    }204205    public var body: some View {206        VStack(alignment: .leading, spacing: 8) {207            HStack(alignment: .center, spacing: 4) {208                entry209                    .onChange(of: text) { _, new in210                        let trimmed = AddressInput.sanitized(new)211                        if trimmed != new { text = trimmed }212                    }213                if !text.isEmpty {214                    iconButton("xmark.circle.fill", label: "Clear") { text = "" }215                        .foregroundStyle(QColor.textTertiary)216                }217                PasteButton(payloadType: String.self) { strings in218                    if let first = strings.first {219                        Task { @MainActor in text = AddressInput.sanitized(first) }220                    }221                }222                .labelStyle(.iconOnly)223                .buttonBorderShape(.capsule)224                .tint(QColor.violet)225                .accessibilityLabel("Paste")226                if let onScan {227                    iconButton("qrcode.viewfinder", label: "Scan a QR code", action: onScan)228                        .foregroundStyle(QColor.violet)229                }230            }231            .padding(.leading, 14)232            .padding(.trailing, 6)233            .padding(.vertical, 6)234            .frame(minHeight: 52)235            .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))236            .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(borderColor, lineWidth: focused ? 1.5 : 1))237            .animation(.snappy(duration: 0.2), value: focused)238            validityLine239        }240    }241242    /// The text entry itself. On iOS a character-wrapping text view (no hyphen at a line break), with the placeholder243    /// drawn behind it while it is empty.244    @ViewBuilder var entry: some View {245        #if canImport(UIKit)246        UnhyphenatedTextInput(text: $text, isFocused: $focused, label: placeholder)247            .frame(maxWidth: .infinity, alignment: .leading)248            .background(alignment: .leading) {249                if text.isEmpty {250                    Text(placeholder).font(QFont.mono).foregroundStyle(QColor.textTertiary).lineLimit(1).accessibilityHidden(true)251                }252            }253        #else254        TextField(placeholder, text: $text, axis: .vertical)255            .font(QFont.mono)256            .foregroundStyle(QColor.textPrimary)257            .lineLimit(1...4)258            .autocorrectionDisabled()259            .focused($focused)260            .accessibilityLabel(placeholder)261        #endif262    }263264    func iconButton(_ systemImage: String, label: String, action: @escaping () -> Void) -> some View {265        Button(action: action) {266            Image(systemName: systemImage)267                .font(.title3)268                .frame(minWidth: 40, minHeight: 44)269                .contentShape(Rectangle())270        }271        .buttonStyle(.plain)272        .accessibilityLabel(label)273    }274275    @ViewBuilder var validityLine: some View {276        switch validity {277        case .empty:278            EmptyView()279        case .checking:280            HStack(spacing: 6) {281                ProgressView().controlSize(.small)282                Text("Checking").font(QFont.caption).foregroundStyle(QColor.textSecondary)283            }284        case .valid(let note):285            Label(note ?? "Valid address", systemImage: "checkmark.circle")286                .font(QFont.caption)287                .foregroundStyle(QColor.positive)288                .fixedSize(horizontal: false, vertical: true)289        case .invalid(let reason):290            Label(reason, systemImage: "exclamationmark.circle")291                .font(QFont.caption)292                .foregroundStyle(QColor.negative)293                .fixedSize(horizontal: false, vertical: true)294        }295    }296}297298#if DEBUG299private struct AddressPreview: View {300    @State private var text = ""301    var body: some View {302        VStack(alignment: .leading, spacing: 24) {303            AddressText("preview0address0value0not0a0real0address0000")304            AddressText("preview0address0value0not0a0real0address0000", head: .max, copyable: false)305            AddressField(text: $text, validity: text.isEmpty ? .empty : .invalid("Preview: validity is supplied by the caller")) {}306            AddressField(text: .constant("preview0address0value"), validity: .valid("Preview note from the caller"))307        }308        .padding()309        .qScreen()310    }311}312313#Preview("Addresses") { AddressPreview() }314#endif315
Files main
Menu

Theme