Repository Public
1// SP Wallet iOS2// File: Features/Swap/SwapHomeView.swift3// Description: Same-network swap: network, asset sold and bought (only what the server serves), exact amount, a tolerance the4// owner chooses, live quotes compared side by side with who EXECUTES and who only quotes, then the preparation of5// the route the owner picked. Reading quotes is always possible; nothing is prepared or approved by a quote.6// iPhone: one column. iPad: form on the left, routes on the right.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213struct SwapHomeView: View {14 @Environment(AppModel.self) private var model15 @Environment(\.horizontalSizeClass) private var sizeClass16 @State private var swap = SwapModel()1718 var body: some View {19 @Bindable var swap = swap20 ScrollView {21 VStack(alignment: .leading, spacing: Theme.Space.section) {22 FreshnessBanner()23 if !model.canOperate {24 Notice(tone: .warn, title: String(localized: "Échange indisponible en lecture seule"), message: String(localized: "Les cotations et un échange exigent une session ouverte et le serveur. Aucune opération n’est possible hors ligne."))25 .accessibilityIdentifier("swap.readonly")26 }27 if let e = swap.catalogError, !swap.catalogLoaded { ErrorNotice(error: e) { Task { await swap.load(model.env) } } }28 else if !swap.catalogLoaded { if model.canOperate { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 30) } }29 else if sizeClass == .regular {30 HStack(alignment: .top, spacing: 20) {31 VStack(alignment: .leading, spacing: Theme.Space.section) { form; prepareBlock }.frame(maxWidth: 440)32 VStack(alignment: .leading, spacing: Theme.Space.section) { quotes; providersCard }.frame(maxWidth: .infinity)33 }34 } else {35 form; quotes; prepareBlock; providersCard36 }37 }38 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)39 .frame(maxWidth: sizeClass == .regular ? 1100 : 620).frame(maxWidth: .infinity)40 }41 .scrollDismissesKeyboard(.immediately)42 .spPage()43 .navigationTitle(AppSection.swap.title)44 .task(id: model.canOperate) { if model.canOperate, !swap.catalogLoaded { await swap.load(model.env) } }45 .task(id: swap.quoteSignature + (model.canOperate ? "+" : "-")) { await swap.runQuotes(model.env, online: model.canOperate) }46 .sheet(item: $swap.start, onDismiss: { swap.requote(); Task { await model.refreshAll() } }) { OperationSheet(start: $0).wallet(model) }47 }4849 // MARK: form5051 private var balance: Balance? {52 guard let f = swap.from else { return nil }53 return model.portfolio.value?.balances.first { $0.network == f.network && SwapLogic.sameAssetId($0.asset, f.asset) }54 }55 private var amountCheck: SwapLogic.AmountCheck {56 guard let f = swap.from else { return .empty }57 return SwapLogic.checkAmount(swap.amount, decimals: f.decimals, balance: balance?.units)58 }5960 @ViewBuilder private var form: some View {61 @Bindable var swap = swap62 VStack(alignment: .leading, spacing: 14) {63 Text(String(localized: "Réseau")).spEyebrow()64 Menu {65 ForEach(swap.networks, id: \.id) { n in Button(n.name) { swap.pick(network: n.id) } }66 } label: {67 HStack(spacing: 12) {68 if let id = swap.network { NetworkIcon(network: id, size: 34) } else { Image(systemName: "network").font(.system(size: 22)).foregroundStyle(Theme.mute).frame(width: 34, height: 34) }69 Text(swap.network.map { id in swap.networks.first { $0.id == id }?.name ?? id } ?? String(localized: "Choisir un réseau")).font(.spHeadline).foregroundStyle(Theme.ink)70 Spacer()71 Image(systemName: "chevron.up.chevron.down").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.mute)72 }.frame(minHeight: 48).contentShape(Rectangle())73 }74 .disabled(!model.canOperate).accessibilityIdentifier("swap.network")75 if let id = swap.network {76 if let ex = swap.executor(on: id) {77 Pill(text: String(localized: "Exécution sur ce réseau : \(SwapLogic.providerName(ex, in: swap.providers))"), tone: .ok, icon: "checkmark.seal.fill")78 } else {79 Pill(text: String(localized: "Cotations seulement sur ce réseau : le portefeuille n’y exécute pas d’échange"), tone: .warn, icon: "eye")80 }81 }82 }.spCard()8384 if let id = swap.network {85 VStack(alignment: .leading, spacing: 12) {86 assetMenu(String(localized: "Tu vends"), swap.from, id: "swap.from", options: swap.assets(on: id)) { swap.pick(from: $0) }87 HStack {88 Rectangle().fill(Theme.hairline).frame(height: 0.5)89 Button { swap.flip() } label: { Image(systemName: "arrow.up.arrow.down").font(.system(size: 15, weight: .semibold)).frame(width: 44, height: 44).background(Theme.elev, in: Circle()) }90 .foregroundStyle(Theme.ink).disabled(swap.from == nil && swap.to == nil).accessibilityLabel(String(localized: "Inverser")).accessibilityIdentifier("swap.flip")91 Rectangle().fill(Theme.hairline).frame(height: 0.5)92 }93 assetMenu(String(localized: "Tu achètes"), swap.to, id: "swap.to", options: swap.assets(on: id).filter { $0.key != swap.from?.key }) { swap.pick(to: $0) }94 }.spCard()95 }9697 if let f = swap.from {98 VStack(alignment: .leading, spacing: 10) {99 Text(String(localized: "Montant vendu")).font(.spHeadline)100 HStack {101 TextField("0", text: $swap.amount).keyboardType(.decimalPad).font(.system(size: 30, weight: .semibold)).monospacedDigit().accessibilityIdentifier("swap.amount")102 Text(f.symbol).font(.spHeadline).foregroundStyle(Theme.mute)103 }104 HStack {105 Text(String(localized: "Disponible")).font(.spFootnote).foregroundStyle(Theme.mute)106 Spacer()107 if let d = balance?.display {108 Masked(text: Money.exact(d) + " " + f.symbol).font(.spFootnote.weight(.semibold)).monospacedDigit()109 Button(String(localized: "Tout")) { swap.amount = d }.font(.spFootnote.weight(.semibold)).buttonStyle(.bordered).accessibilityIdentifier("swap.max")110 } else { Text(String(localized: "solde indisponible")).font(.spFootnote).foregroundStyle(Theme.warn) }111 }112 if f.native == true || f.asset == "native" {113 Text(String(localized: "« Tout » met le solde entier : le serveur ne fournit pas la réserve de frais. Laisse de quoi payer les frais de réseau en \(f.symbol), sinon la préparation sera refusée."))114 .font(.spFootnote).foregroundStyle(Theme.mute)115 }116 if let p = amountCheck.problem { Label(p, systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(amountCheck == .aboveBalance ? Theme.warn : Theme.danger).accessibilityIdentifier("swap.amountProblem") }117 if amountCheck == .aboveBalance { Text(String(localized: "Les cotations restent consultables ; la préparation est désactivée.")).font(.spFootnote).foregroundStyle(Theme.mute) }118 Divider()119 HStack {120 Text(String(localized: "Tolérance de glissement")).font(.spCallout.weight(.semibold))121 Spacer()122 Text(swap.slippageBps.map { SwapLogic.slippageLabel($0) } ?? String(localized: "à choisir")).font(.spCallout.weight(.semibold)).foregroundStyle(swap.slippageBps == nil ? Theme.warn : Theme.ink)123 .accessibilityIdentifier("swap.slippage.current")124 }125 HStack(spacing: 8) {126 ForEach(SwapLogic.swapSlippagePresets, id: \.self) { bps in127 Button { swap.slippageBps = bps } label: {128 Text(SwapLogic.slippageLabel(bps)).font(.spCallout.weight(.semibold)).frame(maxWidth: .infinity, minHeight: 44)129 .foregroundStyle(swap.slippageBps == bps ? Theme.onPrimary : Theme.ink)130 .background(swap.slippageBps == bps ? Theme.primary : Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small))131 }132 .buttonStyle(.plain).accessibilityIdentifier("swap.slippage.\(bps)").accessibilityAddTraits(swap.slippageBps == bps ? .isSelected : [])133 }134 }135 Text(String(localized: "Le minimum garanti de chaque route en découle. Aucune tolérance n’est choisie à ta place ; les cotations démarrent une fois la tolérance choisie."))136 .font(.spFootnote).foregroundStyle(Theme.mute)137 }138 .spCard().disabled(!model.canOperate)139 }140 }141142 private func assetMenu(_ title: String, _ current: SwapAsset?, id: String, options: [SwapAsset], pick: @escaping (SwapAsset) -> Void) -> some View {143 VStack(alignment: .leading, spacing: 6) {144 Text(title).spEyebrow()145 Menu {146 ForEach(options) { a in Button(a.symbol + " — " + (a.name ?? a.asset)) { pick(a) } }147 } label: {148 HStack(spacing: 12) {149 if let a = current { AssetIcon(symbol: a.symbol, network: a.network, size: 36) } else { Circle().fill(Theme.elev).frame(width: 36, height: 36) }150 VStack(alignment: .leading, spacing: 1) {151 Text(current?.symbol ?? String(localized: "Choisir un actif")).font(.spHeadline).foregroundStyle(Theme.ink)152 if let n = current?.name { Text(n).font(.spFootnote).foregroundStyle(Theme.mute).lineLimit(1) }153 }154 Spacer()155 Image(systemName: "chevron.up.chevron.down").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.mute)156 }.frame(minHeight: 48).contentShape(Rectangle())157 }158 .disabled(!model.canOperate).accessibilityIdentifier(id)159 }160 }161162 // MARK: quotes163164 @ViewBuilder private var quotes: some View {165 if swap.from != nil, swap.to != nil {166 VStack(alignment: .leading, spacing: 12) {167 HStack {168 Text(String(localized: "Routes comparées")).font(.spHeadline)169 if swap.phase == .loading { ProgressView().padding(.leading, 4) }170 Spacer()171 if swap.quoteRequest != nil {172 Button { swap.requote() } label: { Label(String(localized: "Actualiser"), systemImage: "arrow.clockwise") }173 .font(.spCallout.weight(.semibold)).disabled(!model.canOperate).accessibilityIdentifier("swap.refresh")174 }175 }176 if swap.quoteRequest == nil {177 Text(missingInput).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("swap.quotes.waiting")178 } else {179 if swap.reachable == false {180 Notice(tone: .warn, title: String(localized: "Aucun fournisseur n’annonce cette paire"), message: String(localized: "Ce n’est pas un manque de liquidité momentané : la paire n’est couverte par aucun fournisseur actif."))181 }182 if let e = swap.quoteError { ErrorNotice(error: e) { swap.requote() }.accessibilityIdentifier("swap.quotes.error") }183 if swap.phase == .done, swap.routes.isEmpty {184 EmptyState(icon: "arrow.left.arrow.right", title: String(localized: "Aucune route pour le moment"), message: String(localized: "Aucun fournisseur n’a coté cette paire pour ce montant.")).accessibilityIdentifier("swap.quotes.empty")185 }186 if swap.phase == .done, !swap.routes.isEmpty, swap.pairExecutors.isEmpty {187 Notice(tone: .info, title: String(localized: "Comparaison seulement"), message: String(localized: "Le portefeuille n’exécute aucune de ces routes pour cette paire : les chiffres sont des cotations de fournisseurs."))188 .accessibilityIdentifier("swap.quotes.compareOnly")189 }190 TimelineView(.periodic(from: .now, by: 5)) { ctx in191 let ordered = swap.ordered192 let highlight = SwapLogic.bestPreparable(ordered, now: ctx.date)193 VStack(spacing: 10) {194 ForEach(Array(ordered.enumerated()), id: \.element.id) { k, r in195 RouteCardView(route: r, index: k, toSymbol: swap.to?.symbol ?? "", providers: swap.providers, now: ctx.date,196 selected: swap.selectedRouteId == r.id, highlighted: highlight?.id == r.id, serverBest: swap.best["best_price"] == r.id,197 select: { swap.select(r) })198 }199 }200 }201 if !swap.answers.isEmpty { providerAnswers }202 Text(String(localized: "Une cotation n’engage rien et ne déclenche rien. La route exécutable la mieux cotée est signalée ; c’est toi qui choisis."))203 .font(.spFootnote).foregroundStyle(Theme.mute)204 }205 }206 .spCard()207 }208 }209210 private var missingInput: String {211 if swap.quoteAmount == nil { return String(localized: "Saisis un montant pour voir les cotations.") }212 if swap.slippageBps == nil { return String(localized: "Choisis une tolérance de glissement pour démarrer les cotations.") }213 return String(localized: "Complète le formulaire pour voir les cotations.")214 }215216 private var providerAnswers: some View {217 VStack(alignment: .leading, spacing: 4) {218 Text(String(localized: "Fournisseurs sans route pour cette recherche")).spEyebrow()219 ForEach(Array(swap.answers.enumerated()), id: \.offset) { _, a in220 Text(SwapLogic.providerName(a.provider, in: swap.providers) + " : " + answerText(a)).font(.spFootnote).foregroundStyle(Theme.mute)221 }222 }223 }224 private func answerText(_ a: SwapProviderAnswer) -> String {225 let base: String = switch a.status {226 case "no_route": String(localized: "aucune route")227 case "skipped": String(localized: "non interrogé")228 case "error": String(localized: "erreur")229 default: a.status230 }231 return a.code.map { "\(base) (\($0))" } ?? base232 }233234 // MARK: prepare235236 private var canPrepare: Bool {237 model.canOperate && !swap.busy && !swap.serverLacksIntent && amountCheck.units != nil && swap.request() != nil && model.accounts.value != nil238 }239240 @ViewBuilder private var prepareBlock: some View {241 if swap.from != nil, swap.to != nil {242 if let m = swap.moved { quoteMovedNotice(m) }243 if let r = swap.refused { refusedNotice(r) }244 if let e = swap.error, swap.refused == nil { PrepareRefusalNotice(error: e, cleanup: swap.cleanup) }245 else if swap.serverLacksIntent { Notice(tone: .warn, title: SwapLogic.missingIntentTitle, message: SwapLogic.missingIntentMessage).accessibilityIdentifier("op.unsupported") }246 if let r = swap.selected {247 VStack(alignment: .leading, spacing: 0) {248 Text(String(localized: "Route choisie")).spEyebrow().padding(.bottom, 4)249 FieldRow(label: String(localized: "Fournisseur qui exécute"), value: SwapLogic.providerName(r.statedExecutor ?? r.providers.first ?? "", in: swap.providers))250 Divider()251 FieldRow(label: String(localized: "Minimum garanti affiché"), value: Money.exact(r.minAmountOutDisplay) + " " + (swap.to?.symbol ?? "")).accessibilityIdentifier("swap.selected.min")252 }.spCard(padding: 16)253 }254 Button { Task { await swap.prepare(model.env, accounts: model.accounts.value) } } label: { HStack { if swap.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Préparer et vérifier")) } }255 .buttonStyle(.spPrimary).disabled(!canPrepare).accessibilityIdentifier("swap.prepare")256 Text(prepareHint).font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("swap.prepareHint")257 }258 }259260 private var prepareHint: String {261 if swap.serverLacksIntent { return String(localized: "Les cotations restent consultables. La préparation sera de nouveau proposée à la réouverture de cet écran.") }262 if swap.selected == nil { return String(localized: "Choisis une route exécutable pour la préparer. Le serveur obtient alors une route ferme, la simule et vérifie les limites ; rien n’est signé à cette étape.") }263 return String(localized: "Le serveur obtient une route ferme, la simule et vérifie les limites. Si son minimum est inférieur au minimum affiché, rien n’est approuvé. Rien n’est signé à cette étape.")264 }265266 private func quoteMovedNotice(_ m: QuoteMoved) -> some View {267 VStack(alignment: .leading, spacing: 10) {268 Notice(tone: .warn, title: String(localized: "Le prix a bougé : rien n’a été préparé"), message: String(localized: "La route ferme du serveur est inférieure au minimum qui t’était affiché. Aucune proposition n’a été créée.")).accessibilityIdentifier("swap.quoteMoved")269 VStack(alignment: .leading, spacing: 0) {270 FieldRow(label: String(localized: "Cotation affichée — sortie attendue"), value: Money.exact(m.quoted.amountOutDisplay) + (m.fresh.symbol.map { " " + $0 } ?? ""))271 Divider(); FieldRow(label: String(localized: "Cotation affichée — minimum garanti"), value: Money.exact(m.quoted.minAmountOutDisplay) + (m.fresh.symbol.map { " " + $0 } ?? ""))272 Divider(); FieldRow(label: String(localized: "Maintenant — sortie attendue"), value: Money.exact(m.fresh.amountOutDisplay) + (m.fresh.symbol.map { " " + $0 } ?? ""), tone: .warn)273 Divider(); FieldRow(label: String(localized: "Maintenant — minimum garanti"), value: Money.exact(m.fresh.minAmountOutDisplay) + (m.fresh.symbol.map { " " + $0 } ?? ""), tone: .warn)274 if let d = m.deviationBps { Divider(); FieldRow(label: String(localized: "Écart"), value: (d < 0 ? "−" : "+") + SwapLogic.percent(bps: Double(d))) }275 }.spCard(padding: 16)276 Button { swap.requote() } label: { Label(String(localized: "Demander une nouvelle cotation"), systemImage: "arrow.clockwise") }.buttonStyle(.spSecondary).accessibilityIdentifier("swap.requote")277 }278 }279280 private func refusedNotice(_ r: (shownMin: String, firmMin: String, firmOut: String, symbol: String)) -> some View {281 VStack(alignment: .leading, spacing: 10) {282 Notice(tone: .warn, title: String(localized: "Minimum ferme inférieur au minimum affiché : rien n’a été approuvé"),283 message: String(localized: "Le serveur a préparé une route dont le minimum garanti est plus bas que celui de la cotation choisie. L’app l’a refusée.") + " " + (swap.cleanup.map { OperationCleanup.sentence($0) } ?? "")).accessibilityIdentifier("swap.refused")284 VStack(alignment: .leading, spacing: 0) {285 FieldRow(label: String(localized: "Minimum garanti affiché sur la route choisie"), value: Money.exact(r.shownMin) + " " + r.symbol)286 Divider(); FieldRow(label: String(localized: "Minimum de la préparation ferme (refusée)"), value: Money.exact(r.firmMin) + " " + r.symbol, tone: .warn)287 Divider(); FieldRow(label: String(localized: "Sortie attendue de la préparation ferme"), value: Money.exact(r.firmOut) + " " + r.symbol)288 }.spCard(padding: 16)289 Button { swap.requote() } label: { Label(String(localized: "Demander une nouvelle cotation"), systemImage: "arrow.clockwise") }.buttonStyle(.spSecondary).accessibilityIdentifier("swap.requote")290 Button { Task { await swap.prepare(model.env, accounts: model.accounts.value, acceptingFirmMinimum: true) } } label: { Text(String(localized: "Préparer au minimum ferme du moment")) }291 .buttonStyle(.spSecondary).disabled(!canPrepare).accessibilityIdentifier("swap.prepareFirm")292 Text(String(localized: "Ce second choix est le tien : le serveur prépare de nouveau, et la revue affichera le minimum réellement garanti (et dira s’il est inférieur à la cotation) avant toute approbation. Indisponible une fois la cotation expirée."))293 .font(.spFootnote).foregroundStyle(Theme.mute)294 }295 }296297 // MARK: providers298299 @ViewBuilder private var providersCard: some View {300 if let p = swap.providers {301 VStack(alignment: .leading, spacing: 8) {302 Text(String(localized: "Fournisseurs")).font(.spHeadline)303 if !p.executionEnabled { Notice(tone: .warn, title: String(localized: "Exécution désactivée sur ce serveur"), message: String(localized: "Tous les fournisseurs ne servent qu’à comparer.")) }304 ForEach(p.providers) { pr in305 HStack(alignment: .firstTextBaseline, spacing: 8) {306 Text(pr.name ?? pr.id).font(.spBody.weight(.medium)).foregroundStyle(Theme.ink)307 Spacer(minLength: 6)308 if !pr.enabled { Pill(text: String(localized: "désactivé"), tone: .neutral) }309 else if pr.state == "open" { Pill(text: String(localized: "en panne"), tone: .warn, icon: "exclamationmark.triangle.fill") }310 if p.isExecutor(pr.id) { Pill(text: String(localized: "Exécute"), tone: .ok, icon: "checkmark.seal.fill") }311 else { Pill(text: String(localized: "Cotation seulement"), tone: .neutral, icon: "eye") }312 }.frame(minHeight: 30)313 }314 if !p.needsKey.isEmpty {315 Text(String(localized: "Non interrogés (clé d’API non configurée sur le serveur) : \(p.needsKey.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute)316 }317 Text(String(localized: "« Exécute » est la déclaration du serveur ; où il exécute dépend du réseau (voir en haut).")).font(.spFootnote).foregroundStyle(Theme.mute)318 }319 .spCard().accessibilityIdentifier("swap.providers")320 }321 }322}323324/** One compared route: every figure is the provider's or the server's; an absent figure says so. */325struct RouteCardView: View {326 let route: SwapRoute327 let index: Int328 let toSymbol: String329 let providers: SwapProviders?330 let now: Date331 let selected: Bool332 let highlighted: Bool333 let serverBest: Bool334 let select: () -> Void335336 var body: some View {337 let r = route338 let prep = SwapLogic.preparability(r, now: now)339 let fresh = SwapLogic.freshness(of: r, now: now)340 VStack(alignment: .leading, spacing: 8) {341 HStack(alignment: .firstTextBaseline) {342 Text(r.providers.map { SwapLogic.providerName($0, in: providers) }.joined(separator: " + ")).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink)343 Spacer(minLength: 6)344 Label(SwapLogic.ageLabel(fresh), systemImage: fresh?.isExpired == true ? "clock.badge.exclamationmark" : "clock")345 .font(.system(size: 12, weight: .medium)).foregroundStyle(fresh?.isExpired == true ? Theme.warn : Theme.mute)346 .accessibilityIdentifier("swap.route.age.\(index)")347 }348 FlowPills() {349 if r.executable, let ex = r.statedExecutor, ex != "cctp" { Pill(text: String(localized: "Exécutable par le portefeuille (\(SwapLogic.providerName(ex, in: providers)))"), tone: .ok, icon: "checkmark.seal.fill") }350 else { Pill(text: String(localized: "Comparaison seulement"), tone: .neutral, icon: "eye") }351 if highlighted { Pill(text: String(localized: "Meilleure route exécutable"), tone: .info, icon: "star.fill") }352 if serverBest { Pill(text: String(localized: "Meilleur prix coté"), tone: .neutral, icon: "chart.line.uptrend.xyaxis") }353 if fresh?.isExpired == true { Pill(text: String(localized: "Périmée"), tone: .warn, icon: "clock.badge.exclamationmark") }354 if let lvl = r.risk?.level, lvl != .low { Pill(text: String(localized: "Risque : \(lvl.rawValue)"), tone: lvl == .high ? .danger : .warn, icon: "exclamationmark.triangle.fill") }355 }356 VStack(alignment: .leading, spacing: 2) {357 Text(String(localized: "Sortie attendue")).font(.spFootnote).foregroundStyle(Theme.mute)358 Text(Money.exact(r.amountOutDisplay) + " " + toSymbol).font(.system(size: 20, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink)359 .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("swap.route.out.\(index)")360 }361 line(String(localized: "Minimum garanti"), Money.exact(r.minAmountOutDisplay) + " " + toSymbol)362 line(String(localized: "Frais de réseau"), fees(r.card?.networkFee, kinds: ["network"]))363 line(String(localized: "Frais de protocole / fournisseur"), fees(r.card?.protocolFee, kinds: ["protocol", "provider", "bridge", "affiliate"]))364 line(String(localized: "Impact sur le prix"), r.priceImpactBps.map { SwapLogic.percent(bps: $0) } ?? String(localized: "non indiqué par le fournisseur"))365 line(String(localized: "Chemin"), path)366 if let s = r.estimatedSeconds { line(String(localized: "Durée estimée"), SwapLogic.duration(s)) }367 if let flags = r.risk?.flags, !flags.isEmpty { line(String(localized: "Signalements"), flags.map { $0.detail ?? $0.code }.joined(separator: " · ")) }368 switch prep {369 case .ready:370 Button { select() } label: {371 Label(selected ? String(localized: "Route choisie") : String(localized: "Choisir cette route"), systemImage: selected ? "checkmark.circle.fill" : "circle")372 .font(.spCallout.weight(.semibold)).frame(maxWidth: .infinity, minHeight: 44)373 .foregroundStyle(selected ? Theme.onPrimary : Theme.ink)374 .background(selected ? Theme.primary : Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small))375 }376 .buttonStyle(.plain).accessibilityIdentifier("swap.route.select.\(index)").accessibilityAddTraits(selected ? .isSelected : [])377 case .comparisonOnly(let code):378 Text(code == SwapLogic.useCCTPTool ? String(localized: "Transfert USDC par CCTP : il se prépare depuis l’outil « USDC (Circle CCTP) », avec les frais de la vitesse choisie.") : route.executability?.reason ?? (code.map { String(localized: "Non exécutable par le portefeuille (\($0)).") } ?? String(localized: "Non exécutable par le portefeuille.")))379 .font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("swap.route.compareOnly.\(index)")380 case .expired:381 Text(String(localized: "Cotation expirée : actualise pour pouvoir la préparer.")).font(.spFootnote).foregroundStyle(Theme.warn).accessibilityIdentifier("swap.route.expired.\(index)")382 case .unverifiableQuote:383 Text(String(localized: "L’empreinte servie ne correspond pas aux chiffres affichés : cette route n’est pas préparée.")).font(.spFootnote).foregroundStyle(Theme.danger)384 }385 }386 .padding(14)387 .frame(maxWidth: .infinity, alignment: .leading)388 .background(Theme.bg, in: RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous))389 .overlay(RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous).strokeBorder(selected ? Theme.primary : highlighted ? Theme.blue : Theme.hairline, lineWidth: selected ? 2 : highlighted ? 1.5 : 0.5))390 }391392 private var path: String {393 var s = route.path.map(\.symbol).joined(separator: " → ")394 let via = (route.steps ?? []).flatMap { $0.via ?? [] }395 if !via.isEmpty { s += " · " + String(localized: "via \(via.joined(separator: ", "))") }396 return s.isEmpty ? String(localized: "non indiqué") : s397 }398399 private func fees(_ group: RouteCard.FeeGroup?, kinds: [String]) -> String {400 let items = group?.items ?? (route.fees ?? []).filter { kinds.contains($0.kind) }401 let parts = items.compactMap { f -> String? in f.display.map { Money.brief($0, maxFraction: 8) + (f.symbol.map { " " + $0 } ?? "") } }402 guard !parts.isEmpty else { return String(localized: "non indiqués") }403 var s = parts.joined(separator: " + ")404 var notes: [String] = []405 if group?.estimated == true || items.contains(where: { $0.estimated == true }) { notes.append(String(localized: "estimés")) }406 if group?.includedInOutput == true || items.contains(where: { $0.includedInOutput == true }) { notes.append(String(localized: "déjà déduits de la sortie")) }407 if !notes.isEmpty { s += " (" + notes.joined(separator: ", ") + ")" }408 return s409 }410411 private func line(_ label: String, _ value: String) -> some View {412 HStack(alignment: .firstTextBaseline, spacing: 10) {413 Text(label).font(.spFootnote).foregroundStyle(Theme.mute)414 Spacer(minLength: 8)415 Text(value).font(.spFootnote.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.trailing).fixedSize(horizontal: false, vertical: true)416 }417 }418}419420/** Pills that wrap on several lines instead of being truncated. */421struct FlowPills: Layout {422 var spacing: CGFloat = 6423424 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {425 let width = proposal.width ?? .infinity426 var x: CGFloat = 0, y: CGFloat = 0, row: CGFloat = 0, maxX: CGFloat = 0427 for v in subviews {428 let s = v.sizeThatFits(ProposedViewSize(width: width, height: nil))429 if x > 0, x + s.width > width { x = 0; y += row + spacing; row = 0 }430 x += s.width + spacing; row = max(row, s.height); maxX = max(maxX, x - spacing)431 }432 return CGSize(width: min(maxX, width), height: y + row)433 }434435 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {436 var x = bounds.minX, y = bounds.minY, row: CGFloat = 0437 for v in subviews {438 let s = v.sizeThatFits(ProposedViewSize(width: bounds.width, height: nil))439 if x > bounds.minX, x + s.width > bounds.maxX { x = bounds.minX; y += row + spacing; row = 0 }440 v.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(s))441 x += s.width + spacing; row = max(row, s.height)442 }443 }444}445