SPB Git

Repository Public

Format.swift 13.7 KB 271 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Components/Format.swift10// Description      : Display formats: counts, dates, language and region names,11//                    URL breadcrumb, result totals, error wording.12// Module           : Components13// Repository       : https://git.spboucher.ai/sp-search-ios14// Project Website  : https://search.spboucher.ai15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import SPSearchKit9293enum Format {94    static func count(_ n: Int) -> String { n.formatted(.number) }9596    static func compact(_ n: Int) -> String { n.formatted(.number.notation(.compactName).precision(.fractionLength(0...1))) }9798    static func bytes(_ n: Int64) -> String { n.formatted(.byteCount(style: .file)) }99100    static func relative(_ date: Date, now: Date = Date()) -> String {101        if abs(now.timeIntervalSince(date)) < 60 { return String(localized: "à l’instant") }102        let f = RelativeDateTimeFormatter()103        f.unitsStyle = .full104        f.dateTimeStyle = .numeric105        return f.localizedString(for: date, relativeTo: now)106    }107108    static func day(_ date: Date) -> String { date.formatted(.dateTime.day().month(.abbreviated).year()) }109110    /// "Français", "English"… in the app's language; an unknown code is shown as written.111    static func languageName(_ code: String) -> String {112        let c = code.lowercased()113        if c == "und" || c.isEmpty { return String(localized: "Langue indéterminée") }114        guard let name = Locale.current.localizedString(forLanguageCode: c) else { return code.uppercased() }115        return name.prefix(1).uppercased(with: Locale.current) + name.dropFirst()116    }117118    /// "Canada", "Canada (Québec)", as the system names the country; a code it cannot name is shown in capitals.119    static func regionName(_ code: String) -> String {120        let c = code.trimmingCharacters(in: .whitespaces).lowercased()121        let country = c.split(separator: "-").first.map(String.init) ?? c122        let name = Locale.current.localizedString(forRegionCode: country.uppercased()) ?? country.uppercased()123        return c == "ca-qc" ? "\(name) (\(String(localized: "Québec")))" : name124    }125126    static func regionOption(_ r: RegionChoice) -> String {127        switch r {128        case .automatic: String(localized: "Automatique")129        case .off: String(localized: "Aucune adaptation")130        case .quebec: "\(regionName("ca")) — \(String(localized: "Québec"))"131        default: regionName(r.rawValue)132        }133    }134135    /// What the server reports it applied, never an assumption.136    static func applied(_ region: AppliedRegion?) -> String? {137        guard let region else { return nil }138        switch region.source {139        case .off: return String(localized: "Aucune adaptation")140        case .choice: return region.value.map(regionName)141        case .browser:142            guard let v = region.value else { return String(localized: "Automatique : aucune") }143            return String(localized: "Automatique : \(regionName(v))")144        case .none:145            if let v = region.value { return regionName(v) }146            return String(localized: "Automatique : aucune")147        }148    }149150    static func total(_ t: ResultTotal) -> String {151        if t.value == 0 { return String(localized: "Aucun résultat") }152        let n = count(t.value)153        switch t.relation {154        case .exact: return t.value == 1 ? String(localized: "1 résultat") : String(localized: "\(n) résultats")155        case .atLeast: return String(localized: "Plus de \(n) résultats")156        case .estimate: return String(localized: "Environ \(n) résultats")157        }158    }159160    /// "ulaval.ca › grands-dossiers › copibec": the host without `www.`, then at most three path segments.161    static func breadcrumb(_ url: String, domain: String) -> String {162        guard let u = URL(string: url), var host = u.host else { return domain.isEmpty ? url : domain }163        if host.hasPrefix("www.") { host.removeFirst(4) }164        let parts = u.pathComponents.filter { $0 != "/" && !$0.isEmpty }.map { $0.removingPercentEncoding ?? $0 }165        guard !parts.isEmpty else { return host }166        let shown = parts.prefix(3).joined(separator: " › ")167        return host + " › " + shown + (parts.count > 3 ? " › …" : "")168    }169170    /// What happened, in the reader's words. The server's own message is quoted when it gave one.171    static func error(_ e: SearchError) -> (title: String, detail: String) {172        switch e {173        case .offline:174            return (String(localized: "Pas de connexion"), String(localized: "L’appareil n’est pas relié à Internet."))175        case .timedOut:176            return (String(localized: "Le moteur n’a pas répondu à temps"), String(localized: "La demande a été abandonnée après 15 secondes."))177        case .rateLimited(let s):178            return (String(localized: "Trop de recherches en peu de temps"),179                    String(localized: "Le moteur limite chaque adresse à 60 recherches par minute. Réessayez dans \(Int(s.rounded(.up))) s."))180        case .unavailable(let m):181            return (String(localized: "Le moteur est momentanément indisponible"), m ?? String(localized: "Il a répondu « service indisponible » (503)."))182        case .badRequest(let m):183            return (String(localized: "Le moteur a refusé cette requête"), m.isEmpty ? String(localized: "Il a répondu « requête invalide » (400).") : m)184        case .http(let status, let m):185            return (String(localized: "La recherche a échoué"), m ?? String(localized: "Le serveur a répondu par le code \(status)."))186        case .invalidResponse:187            return (String(localized: "Réponse illisible"), String(localized: "Le serveur a répondu autre chose que ce que l’app attend."))188        case .network(let code):189            // The code is written as it is (no digit grouping): it is what a reader would quote when reporting the failure.190            return (String(localized: "Le moteur est injoignable"),191                    String(localized: "La connexion au moteur n’a pas pu être établie. Réessayez dans un instant (code \(String(code)))."))192        case .cancelled:193            return (String(localized: "Recherche annulée"), "")194        }195    }196197    /// Understated hints: what the server reports about this answer, in plain words.198    static func notice(_ n: SearchNotice) -> String {199        switch n {200        case .phraseUnsupported, .phraseUnverified: String(localized: "La phrase exacte n’a pas pu être vérifiée pour une partie des résultats : leur texte n’est pas conservé par l’index, ou la page l’interdit.")201        case .relaxedToAnyTerm: String(localized: "Aucun document ne contenait tous les termes : la recherche a été élargie aux documents qui en contiennent au moins un.")202        case .depthLimit: String(localized: "La profondeur maximale de pagination est atteinte : précisez la requête pour voir d’autres résultats.")203        case .partialShards: String(localized: "Certains segments de l’index n’ont pas répondu.")204        case .cursorExpired: String(localized: "Le curseur de pagination a expiré : les résultats reprennent depuis le début.")205        case .degradedMetadata: String(localized: "L’index principal est injoignable : les résultats sont affichés sans extraits adaptés ni vérification d’adresse.")206        case .semanticUnavailable: String(localized: "Le classement sémantique est momentanément indisponible : les résultats reposent sur les mots de la requête.")207        case .unknown(let code): String(localized: "Avis du moteur : \(code)")208        }209    }210211    /// "Adresse vérifiée il y a 2 heures": the crawler's last technical check of the address. Never a claim about212    /// the content. nil when nothing is known.213    static func validation(_ r: SearchResult, now: Date = Date()) -> (text: String, warning: Bool)? {214        let date = r.validation?.validatedAt ?? r.checkedAt215        switch r.validation?.state {216        case .unreachable:217            guard let date else { return (String(localized: "Dernière vérification de l’adresse en échec"), true) }218            return (String(localized: "Dernière vérification de l’adresse en échec \(relative(date, now: now))"), true)219        case .redirected:220            guard let date else { return nil }221            return (String(localized: "Adresse vérifiée \(relative(date, now: now)) · redirigée"), false)222        case .changed:223            guard let date else { return nil }224            return (String(localized: "Adresse vérifiée \(relative(date, now: now)) · contenu modifié"), false)225        case .ok, .unknown, nil:226            guard let date else { return nil }227            return (String(localized: "Adresse vérifiée \(relative(date, now: now))"), false)228        }229    }230231    /// Name of a category of `/v2/filters`; an identifier the app does not know yet is shown as the server writes it.232    static func vertical(_ id: String) -> String {233        switch id {234        case "web": String(localized: "Web")235        case "news": String(localized: "Actualités")236        default: id.prefix(1).uppercased() + id.dropFirst()237        }238    }239240    /// Label of a period shortcut of `/v2/filters`.241    static func fresh(_ id: String) -> String {242        switch id {243        case "day": String(localized: "Dernières 24 heures")244        case "week": String(localized: "Dernière semaine")245        case "month": String(localized: "Dernier mois")246        case "year": String(localized: "Dernière année")247        default: id248        }249    }250251    /// A page type as the server names it: the known ones in words, the others as written.252    static func kind(_ id: String) -> String { PageKind(rawValue: id)?.label ?? id.prefix(1).uppercased() + id.dropFirst() }253254    static func engineLevel(_ level: EngineStatus.Level) -> String {255        switch level {256        case .ok: String(localized: "En service")257        case .degraded: String(localized: "Service dégradé")258        case .down: String(localized: "En panne")259        case .off: String(localized: "Arrêté")260        case .unknown: String(localized: "État inconnu")261        }262    }263264    /// "ulaval.ca › admission": the server's short address when it gave one, else built from the address.265    static func displayURL(_ r: SearchResult) -> String { r.displayURL ?? breadcrumb(r.url, domain: r.domain) }266267    static func duration(seconds: Int) -> String {268        Duration.seconds(seconds).formatted(.units(allowed: [.days, .hours, .minutes], width: .wide, maximumUnitCount: 1))269    }270}271
Files main
Menu

Theme