SPB Git

Repository Public

RouteEcran.swift 15.8 KB 325 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : Groupe Ka — app iOS native7// File             : GroupeKa/Features/API/RouteEcran.swift8// Module           : Groupe Ka9// Repository       : https://git.spboucher.ai/groupe-ka-ios10// Project Website  : Not specified11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//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 Observation42import SwiftUI4344/// Console de requêtes d'une route : les valeurs saisies, l'adresse composée, la réponse brute.45@MainActor46@Observable47final class Console {48    var valeurs: [String: String] = [:]49    private(set) var reponse: ReponseBrute?50    private(set) var erreur: String?51    private(set) var enCours = false52    private(set) var texte = ""53    private(set) var tronque = false5455    static let limiteAffichage = 600005657    /// Préremplit avec l'exemple publié de la route, sinon avec les valeurs par défaut des paramètres requis.58    func preparer(_ route: RouteAPI) {59        guard valeurs.isEmpty else { return }60        if let ex = route.exemple, let u = URLComponents(string: ex) {61            let modele = route.chemin.split(separator: "/"), reel = u.path.split(separator: "/")62            if modele.count == reel.count {63                for (m, r) in zip(modele, reel) where m.hasPrefix("{") { valeurs[String(m.dropFirst().dropLast())] = String(r) }64            }65            for q in u.queryItems ?? [] { valeurs[q.name] = q.value ?? "" }66        }67        for p in route.params where valeurs[p.nom] == nil && p.requis { valeurs[p.nom] = p.exemple ?? p.valeurs.first ?? "" }68    }6970    /// Le chemin et la requête qui seront appelés ; `nil` s'il manque un paramètre de chemin.71    func adresse(_ route: RouteAPI) -> String? {72        var chemin = route.chemin73        var requete: [(String, String)] = []74        for p in route.params {75            let v = (valeurs[p.nom] ?? "").trimmingCharacters(in: .whitespaces)76            if p.dans == "path" {77                guard !v.isEmpty else { return nil }78                var permis = CharacterSet.urlPathAllowed79                permis.remove(charactersIn: "/:")80                chemin = chemin.replacingOccurrences(of: "{\(p.nom)}", with: v.addingPercentEncoding(withAllowedCharacters: permis) ?? v)81            } else if !v.isEmpty {82                requete.append((p.nom, v))83            }84        }85        return API.requete(chemin, requete)86    }8788    func envoyer(_ route: RouteAPI) async {89        guard let a = adresse(route), !enCours else { return }90        enCours = true91        defer { enCours = false }92        do {93            let r = try await API.partagee.brut(a)94            reponse = r95            erreur = nil96            let complet = Self.joli(r.corps)97            tronque = complet.count > Self.limiteAffichage98            texte = tronque ? String(complet.prefix(Self.limiteAffichage)) : complet99        } catch {100            reponse = nil101            texte = ""102            erreur = (error as? APIErreur)?.errorDescription ?? "L'appel a échoué."103        }104    }105106    /// JSON remis en page ; tout autre contenu (CSV) tel quel107    nonisolated static func joli(_ d: Data) -> String {108        if let o = try? JSONSerialization.jsonObject(with: d, options: [.fragmentsAllowed]),109           let p = try? JSONSerialization.data(withJSONObject: o, options: [.prettyPrinted, .withoutEscapingSlashes, .fragmentsAllowed, .sortedKeys]),110           let s = String(data: p, encoding: .utf8) { return s }111        return String(data: d, encoding: .utf8) ?? "\(d.count) octets illisibles en texte"112    }113}114115/// Une route : ce qu'elle rend, ses paramètres, son exemple, et la console pour l'appeler.116struct RouteEcran: View {117    let id: String118    let groupes: [(groupe: String, texte: String, routes: [RouteAPI])]119    let enCours: Bool120    @Environment(AppEtat.self) private var app121    @State private var console = Console()122    @State private var copie = false123    @FocusState private var champ: String?124125    private var route: RouteAPI? { groupes.flatMap(\.routes).first { $0.id == id } }126127    var body: some View {128        ScrollView {129            Colonne(largeurMax: 820) {130                if let r = route { VStack(alignment: .leading, spacing: 0) { contenu(r) } } else {131                    Constat(titre: enCours ? "Lecture de la spécification…" : "Route inconnue",132                            texte: enCours ? nil : "La spécification de l'API ne décrit pas de route « \(id) ».")133                }134            }135            .padding(.bottom, 28)136        }137        .scrollDismissesKeyboard(.interactively)138        .safeAreaInset(edge: .top, spacing: 0) { EnTete(titre: "Référence", retour: { app.cheminAPI = [] }) }139        .fondPapier()140        .toolbar(.hidden, for: .navigationBar)141        .task(id: route?.id) {142            guard let r = route else { return }143            console.preparer(r)144            if app.options.envoyer, console.reponse == nil { await console.envoyer(r) }145        }146    }147148    @ViewBuilder149    private func contenu(_ r: RouteAPI) -> some View {150        VStack(alignment: .leading, spacing: 0) {151            Cote(texte: r.groupe).padding(.top, 16)152            Text(r.resume).ka(.serif, 30, graisse: 500, style: .title1, plafond: 1.6).tracking(-0.6).foregroundStyle(Ka.encre).padding(.top, 2)153                .fixedSize(horizontal: false, vertical: true)154                .accessibilityAddTraits(.isHeader)155                .accessibilityIdentifier("route-ecran-\(r.id)")156            CheminRoute(chemin: r.chemin, taille: 15).padding(.top, 6)157            if !r.description.isEmpty {158                Text(Self.balise(r.description)).ka(.sans, 15, style: .subheadline).foregroundStyle(Ka.encre2).lineSpacing(2).padding(.top, 10)159                    .fixedSize(horizontal: false, vertical: true)160            }161            if !r.codes.isEmpty {162                Text("Réponses : " + r.codes.joined(separator: " · ")).ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre3).padding(.top, 10).monospacedDigit()163            }164        }165        .padding(.bottom, 24)166167        if !r.params.isEmpty {168            VStack(alignment: .leading, spacing: 0) {169                TitreSection(titre: "Paramètres").padding(.bottom, 8)170                ForEach(r.params) { p in parametre(p) }171            }172            .padding(.bottom, 24)173        }174175        VStack(alignment: .leading, spacing: 12) {176            TitreSection(titre: "Console", note: "L'appel part de cet appareil vers l'API publique, sans clé ni compte.")177            if let a = console.adresse(r) {178                VStack(alignment: .leading, spacing: 3) {179                    Cote(texte: "Adresse appelée")180                    Text("GET " + a).ka(.sans, 14, graisse: 500, style: .footnote).foregroundStyle(Ka.encre).textSelection(.enabled)181                        .fixedSize(horizontal: false, vertical: true)182                        .accessibilityIdentifier("adresse-appelee")183                }184            } else {185                Text("Il manque un paramètre de chemin.").ka(.sans, 14, graisse: 500, style: .footnote).foregroundStyle(Ka.encre)186            }187            Button { champ = nil; Task { await console.envoyer(r) } } label: {188                Text(console.enCours ? "Appel en cours…" : "Envoyer")189            }190            .buttonStyle(BoutonPlein())191            .disabled(console.adresse(r) == nil || console.enCours)192            .accessibilityIdentifier("envoyer")193194            if let e = console.erreur {195                Text(e).ka(.sans, 15, graisse: 500, style: .subheadline).foregroundStyle(Ka.encre).padding(.top, 4)196            }197            if let rep = console.reponse { reponse(rep) }198        }199    }200201    /// les `mots entre accents graves` de la description passent en encre plus forte202    static func balise(_ texte: String) -> AttributedString {203        var sortie = AttributedString()204        for (i, m) in texte.split(separator: "`", omittingEmptySubsequences: false).enumerated() {205            var a = AttributedString(String(m))206            if i % 2 == 1 { a.foregroundColor = Ka.encre; a.font = KaFont.police(.sans, 14.5, graisse: 600) }207            sortie += a208        }209        return sortie210    }211212    private func parametre(_ p: RouteAPI.Param) -> some View {213        VStack(alignment: .leading, spacing: 6) {214            Rangee(espace: 8, interligne: 2) {215                Text(p.nom).ka(.sans, 15, graisse: 600, style: .subheadline).foregroundStyle(Ka.encre)216                Cote(texte: [p.dans == "path" ? "chemin" : "requête", p.type, p.requis ? "requis" : nil, p.defaut.map { "défaut \($0)" }].compactMap { $0 }.joined(separator: " · "))217            }218            if !p.description.isEmpty {219                Text(Self.balise(p.description)).ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre2).fixedSize(horizontal: false, vertical: true)220            }221            if p.valeurs.isEmpty {222                TextField(p.exemple ?? p.defaut ?? (p.requis ? "valeur requise" : "facultatif"), text: Binding(get: { console.valeurs[p.nom] ?? "" }, set: { console.valeurs[p.nom] = $0 }))223                    .font(KaFont.police(.sans, 16))224                    .textInputAutocapitalization(.never)225                    .autocorrectionDisabled()226                    .keyboardType(p.type == "integer" || p.type == "number" ? .numbersAndPunctuation : .default)227                    .focused($champ, equals: p.nom)228                    .padding(.vertical, 8)229                    .overlay(alignment: .bottom) { Filet(couleur: Ka.filet2) }230                    .accessibilityLabel("Valeur de \(p.nom)")231                    .accessibilityIdentifier("param-\(p.nom)")232            } else {233                // valeurs permises : on en touche une (la retoucher la retire, si le paramètre est facultatif)234                ScrollView(.horizontal, showsIndicators: false) {235                    HStack(spacing: 2) {236                        ForEach(p.valeurs, id: \.self) { v in237                            let pris = console.valeurs[p.nom] == v238                            Button {239                                if pris, !p.requis { console.valeurs[p.nom] = "" } else { console.valeurs[p.nom] = v }240                            } label: {241                                VStack(spacing: 4) {242                                    Text(v).ka(.sans, 15, graisse: pris ? 600 : 400, style: .subheadline).foregroundStyle(pris ? Ka.encre : Ka.encre2)243                                    Rectangle().fill(pris ? Ka.encre : .clear).frame(height: 1.5)244                                }245                                .fixedSize()246                                .padding(.trailing, 14)247                                .frame(minHeight: 40)248                                .contentShape(Rectangle())249                            }250                            .buttonStyle(.plain)251                            .accessibilityAddTraits(pris ? .isSelected : [])252                            .accessibilityIdentifier("param-\(p.nom)-\(v)")253                        }254                    }255                }256            }257        }258        .padding(.vertical, 10)259        .overlay(alignment: .top) { Filet() }260    }261262    @ViewBuilder263    private func reponse(_ r: ReponseBrute) -> some View {264        VStack(alignment: .leading, spacing: 10) {265            Filet(couleur: Ka.encre)266            Rangee(espace: 18, interligne: 6) {267                mesure("statut", "\(r.statut)").accessibilityIdentifier("statut")268                mesure("durée", Fmt.delai(Double(r.dureeMs)) ?? "")269                mesure("taille", Fmt.compact(Double(r.corps.count)) + " o")270            }271            // la limite de débit, telle que le serveur la dit dans ses en-têtes272            if let l = r.entete("ratelimit-limit"), let reste = r.entete("ratelimit-remaining") {273                Text("Limite de débit : \(reste) jetons restants sur \(l)" + (r.entete("ratelimit-reset").map { ", remise à niveau dans \($0) s" } ?? "")274                    + (r.entete("retry-after").map { " ; réessayer dans \($0) s" } ?? ""))275                    .ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre2).fixedSize(horizontal: false, vertical: true)276            }277            let autres = ["content-type", "cache-control", "etag"].compactMap { n in r.entete(n).map { "\(n) : \($0)" } }278            if !autres.isEmpty {279                Text(autres.joined(separator: "\n")).ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3).textSelection(.enabled)280                    .fixedSize(horizontal: false, vertical: true)281            }282            Rangee(espace: 18, interligne: 0) {283                LienTexte(titre: copie ? "Copié" : "Copier la réponse", couleur: Ka.encre, fleche: nil) {284                    UIPasteboard.general.string = Console.joli(r.corps)285                    copie = true286                    Task { try? await Task.sleep(for: .seconds(2)); copie = false }287                }288                ShareLink(item: Console.joli(r.corps), subject: Text("GET \(r.url.path)")) {289                    Text("Partager").ka(.sans, 15, graisse: 600, style: .subheadline).underline(true, color: Ka.encre.opacity(0.5)).foregroundStyle(Ka.encre)290                        .frame(minHeight: 44)291                }292                ShareLink(item: r.url) {293                    Text("Partager l'adresse").ka(.sans, 15, graisse: 600, style: .subheadline).underline(true, color: Ka.encre.opacity(0.5)).foregroundStyle(Ka.encre)294                        .frame(minHeight: 44)295                }296            }297            ScrollView(.horizontal, showsIndicators: true) {298                Text(console.texte)299                    .font(.system(size: 12.5, design: .monospaced))300                    .foregroundStyle(Ka.encre)301                    .textSelection(.enabled)302                    .padding(12)303                    .fixedSize(horizontal: true, vertical: true)304            }305            .background(Ka.sol)306            .overlay(Rectangle().strokeBorder(Ka.filet2, lineWidth: 1))307            .accessibilityLabel("Corps de la réponse")308            .accessibilityIdentifier("corps-reponse")309            if console.tronque {310                Text("Affichage limité aux \(Fmt.nombre(Double(Console.limiteAffichage))) premiers caractères ; « Copier » et « Partager » donnent la réponse entière.")311                    .ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3).fixedSize(horizontal: false, vertical: true)312            }313        }314        .padding(.top, 6)315    }316317    private func mesure(_ nom: String, _ valeur: String) -> some View {318        VStack(alignment: .leading, spacing: 1) {319            Text(valeur).ka(.serif, 24, graisse: 500, style: .title2, plafond: 1.5).foregroundStyle(Ka.encre).monospacedDigit()320            Text(nom).ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3)321        }322        .accessibilityElement(children: .combine)323    }324}325
Files main
Menu

Theme