Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraUI/Formatting.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 Foundation42import QyvoraCore4344/// Pure formatting and parsing rules for amounts expressed in integer base units (satoshi, wei, token units).45///46/// Everything works on decimal digit strings, so a 256-bit wei amount never goes through a floating-point value.47/// Display truncates (never rounds up): the wallet must not show more than the user owns.48public enum AmountFormat {49 /// Keeps only ASCII digits and drops leading zeros ("" becomes "0").50 public static func normalizedUnits(_ units: String) -> String {51 let digits = units.filter { $0.isASCII && $0.isNumber }52 let trimmed = digits.drop(while: { $0 == "0" })53 return trimmed.isEmpty ? "0" : String(trimmed)54 }5556 /// Formats `units` base units of an asset with `decimals` decimals.57 ///58 /// - `maxFractionDigits`: fraction digits kept (truncation). `nil` keeps them all.59 /// - `minFractionDigits`: zero padding of the fraction.60 /// - A non-zero amount that truncates to zero is shown as "<0.0001" (with the separators requested).61 public static func format(62 units: String, decimals: Int, maxFractionDigits: Int? = nil, minFractionDigits: Int = 0,63 groupingSeparator: String = ",", decimalSeparator: String = "."64 ) -> String {65 let digits = normalizedUnits(units)66 let decimals = max(0, decimals)67 let padded = String(repeating: "0", count: max(0, decimals + 1 - digits.count)) + digits68 let integerPart = String(padded.dropLast(decimals))69 var fraction = String(padded.suffix(decimals))70 let limit = min(decimals, max(0, maxFractionDigits ?? decimals))71 let truncatedAway = fraction.dropFirst(limit).contains { $0 != "0" }72 fraction = String(fraction.prefix(limit))73 while fraction.count > minFractionDigits, fraction.last == "0" { fraction.removeLast() }74 if fraction.count < minFractionDigits {75 fraction += String(repeating: "0", count: minFractionDigits - fraction.count)76 }77 let isZeroShown = integerPart.allSatisfy { $0 == "0" } && fraction.allSatisfy { $0 == "0" }78 if isZeroShown, truncatedAway, limit > 0 {79 return "<0" + decimalSeparator + String(repeating: "0", count: limit - 1) + "1"80 }81 if isZeroShown, truncatedAway { return "<1" }82 let grouped = group(integerPart, separator: groupingSeparator)83 return fraction.isEmpty ? grouped : grouped + decimalSeparator + fraction84 }8586 /// Inserts `separator` every three digits from the right.87 public static func group(_ integerDigits: String, separator: String) -> String {88 guard !separator.isEmpty, integerDigits.count > 3 else { return integerDigits }89 var out = ""90 let chars = Array(integerDigits)91 for (i, c) in chars.enumerated() {92 if i > 0, (chars.count - i) % 3 == 0 { out += separator }93 out.append(c)94 }95 return out96 }9798 /// Parses a user-entered decimal amount into base units (decimal digit string).99 ///100 /// Accepts "." or "," as the decimal separator and ignores spaces. Returns nil for an empty or malformed101 /// text, for more than one separator, and for more fraction digits than the asset has (no silent rounding).102 public static func parse(_ text: String, decimals: Int) -> String? {103 let compact = text.filter { !$0.isWhitespace }104 guard !compact.isEmpty else { return nil }105 let parts = compact.split(omittingEmptySubsequences: false) { $0 == "." || $0 == "," }106 guard parts.count <= 2 else { return nil }107 let integerPart = String(parts[0])108 let fraction = parts.count == 2 ? String(parts[1]) : ""109 guard !(integerPart.isEmpty && fraction.isEmpty) else { return nil }110 guard (integerPart + fraction).allSatisfy({ $0.isASCII && $0.isNumber }) else { return nil }111 guard fraction.count <= max(0, decimals) else { return nil }112 let padded = fraction + String(repeating: "0", count: max(0, decimals) - fraction.count)113 return normalizedUnits(integerPart + padded)114 }115116 /// Filters keyboard input for an amount field: digits and one decimal separator, at most117 /// `maxFractionDigits` fraction digits, no superfluous leading zeros. Idempotent.118 public static func sanitize(_ input: String, maxFractionDigits: Int, decimalSeparator: String = ".") -> String {119 var integerPart = ""120 var fraction = ""121 var seenSeparator = false122 for c in input {123 if c.isASCII, c.isNumber {124 if seenSeparator {125 if fraction.count < maxFractionDigits { fraction.append(c) }126 } else {127 integerPart.append(c)128 }129 } else if c == "." || c == "," || String(c) == decimalSeparator {130 if !seenSeparator, maxFractionDigits > 0 { seenSeparator = true }131 }132 }133 while integerPart.count > 1, integerPart.first == "0" { integerPart.removeFirst() }134 if seenSeparator {135 return (integerPart.isEmpty ? "0" : integerPart) + decimalSeparator + fraction136 }137 return integerPart138 }139140 /// True when the amount is zero (or the text holds no digit).141 public static func isZero(units: String) -> Bool { normalizedUnits(units) == "0" }142}143144public extension AmountFormat {145 /// Convenience for 256-bit amounts (wei, token units).146 static func format(_ value: UInt256, decimals: Int, maxFractionDigits: Int? = nil) -> String {147 format(units: value.description, decimals: decimals, maxFractionDigits: maxFractionDigits)148 }149}150151/// Middle truncation of addresses, hashes and identifiers.152public enum MiddleTruncation {153 /// Keeps `head` leading and `tail` trailing characters around an ellipsis. Strings that would not get154 /// shorter are returned unchanged.155 public static func truncate(_ text: String, head: Int = 8, tail: Int = 6, ellipsis: String = "…") -> String {156 let head = max(0, head), tail = max(0, tail)157 guard text.count > head + tail + ellipsis.count else { return text }158 return String(text.prefix(head)) + ellipsis + String(text.suffix(tail))159 }160161 /// Splits an address in groups of four characters, which is how it should be read aloud or compared.162 public static func grouped(_ text: String, size: Int = 4) -> String {163 guard size > 0 else { return text }164 var out = ""165 for (i, c) in text.enumerated() {166 if i > 0, i % size == 0 { out.append(" ") }167 out.append(c)168 }169 return out170 }171}172173/// Display form of long values that have no natural break (addresses, hashes, keys, call data).174///175/// When such a value does not fit on one line the system breaks it like a long word and draws a hyphen at the break.176/// The hyphen is not part of the value: a user who reads or retypes the address gets a wrong one. The display form177/// carries a zero-width break opportunity after every character, so the line breaks anywhere and nothing is drawn at178/// the break. It is for display only: what is copied, compared or parsed is always the original string.179public enum UnbrokenValue {180 /// Zero-width space (U+200B): a line may break here, and nothing is drawn.181 public static let breakOpportunity: Character = "\u{200B}"182183 /// `text` with a break opportunity after every character. For display only.184 public static func wrappable(_ text: String) -> String {185 var out = String()186 out.reserveCapacity(text.utf8.count * 4)187 for c in text {188 out.append(c)189 out.append(breakOpportunity)190 }191 return out192 }193194 /// The exact original of a display form: every break opportunity removed.195 public static func original(_ displayed: String) -> String {196 displayed.filter { $0 != breakOpportunity }197 }198199 /// Prose in which every long unbroken token (an address, a hash, call data) is made wrappable; ordinary words are200 /// left alone, so that sentences still break between words.201 public static func wrappingLongTokens(_ text: String, longerThan limit: Int = 20) -> String {202 guard text.contains(where: { !$0.isWhitespace }) else { return text }203 return text.split(separator: " ", omittingEmptySubsequences: false)204 .map { $0.count > limit ? wrappable(String($0)) : String($0) }205 .joined(separator: " ")206 }207}208209/// Helpers for recovery-phrase entry. The word list itself is supplied by the caller.210public enum SeedPhraseInput {211 /// Lower-cases, trims and splits a pasted phrase on any whitespace or line break.212 public static func split(_ text: String) -> [String] {213 text.lowercased().split(whereSeparator: { $0.isWhitespace || $0.isNewline }).map(String.init)214 }215216 /// Normalises what is typed in a single word cell: lower case, letters only.217 public static func normalizeWord(_ text: String) -> String {218 String(text.lowercased().filter { $0.isLetter })219 }220221 /// Writes `pasted` words into `words` starting at `index`, without growing the array.222 /// Returns the index of the cell that should receive the focus next (nil when the phrase is full).223 @discardableResult224 public static func distribute(_ pasted: [String], into words: inout [String], startingAt index: Int) -> Int? {225 guard index >= 0, index < words.count else { return nil }226 var i = index227 for word in pasted where i < words.count {228 words[i] = normalizeWord(word)229 i += 1230 }231 return i < words.count ? i : nil232 }233234 /// Number of cells that hold a word accepted by `isValid`.235 public static func validCount(_ words: [String], isValid: (String) -> Bool) -> Int {236 words.filter { !$0.isEmpty && isValid($0) }.count237 }238239 /// True when every cell holds an accepted word.240 public static func isComplete(_ words: [String], isValid: (String) -> Bool) -> Bool {241 !words.isEmpty && words.allSatisfy { !$0.isEmpty && isValid($0) }242 }243}244245/// Lock-out countdown text for the PIN pad: "0:42", "12:05", "1:02:03".246public enum CountdownFormat {247 public static func text(_ seconds: TimeInterval) -> String {248 let total = max(0, Int(seconds.rounded(.up)))249 let h = total / 3600, m = (total % 3600) / 60, s = total % 60250 if h > 0 { return "\(h):" + String(format: "%02d:%02d", m, s) }251 return "\(m):" + String(format: "%02d", s)252 }253}254255/// Normalised shares of a set of non-negative values (used by `SegmentedSummaryBar`).256public enum Proportions {257 /// Returns one fraction per value, summing to 1 when at least one value is positive; all zeros otherwise.258 /// Negative and non-finite values count as zero.259 public static func fractions(_ values: [Double]) -> [Double] {260 let clean = values.map { $0.isFinite && $0 > 0 ? $0 : 0 }261 let total = clean.reduce(0, +)262 guard total > 0 else { return clean.map { _ in 0 } }263 return clean.map { $0 / total }264 }265266 /// "42%", "<1%" for a positive share below one percent.267 public static func percentText(_ fraction: Double) -> String {268 guard fraction > 0 else { return "0%" }269 let percent = fraction * 100270 if percent < 1 { return "<1%" }271 return "\(Int(percent.rounded()))%"272 }273}274