SPB Git

Repository Public

ResultsView.swift 18.7 KB 429 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Features/Results/ResultsView.swift10// Description      : Results: correction, honest total, hints, top card, rows,11//                    paging by cursor, related searches; loading, empty and12//                    error states.13// Module           : Features14// Repository       : https://git.spboucher.ai/sp-search-ios15// Project Website  : https://search.spboucher.ai16// Created          : 2026-12-0117// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SPSearchKit92import SwiftUI9394struct ResultsView: View {95    @Environment(SearchModel.self) private var model96    var open: (URL) -> Void97    var openExternally: (URL) -> Void98    var preview: (SearchResult) -> Void99100    var body: some View {101        ScrollView {102            LazyVStack(alignment: .leading, spacing: 0) {103                switch model.phase {104                case .idle:105                    EmptyView()106                case .loading:107                    SkeletonList()108                case .failed(let error):109                    ErrorState(error: error) { model.retry() }110                case .loaded:111                    loaded112                }113            }114            .padding(.horizontal, 20).padding(.top, 14).padding(.bottom, 28)115            .frame(maxWidth: Theme.column, alignment: .leading)116            .frame(maxWidth: .infinity)117        }118        .refreshable { await model.refresh() }119        .scrollDismissesKeyboard(.interactively)120    }121122    /// The first result becomes the top card when the server attached sitelinks to it or read the query as navigational.123    private var topCard: SearchResult? {124        guard let first = model.results.first else { return nil }125        return (!first.sitelinks.isEmpty || model.head?.query?.isNavigational == true) ? first : nil126    }127128    @ViewBuilder private var loaded: some View {129        if let c = model.correction { CorrectionBanner(correction: c).padding(.bottom, 12) }130        if let head = model.head, !model.results.isEmpty {131            ResultsSummary(head: head).padding(.bottom, 10)132        }133        if !model.filters.isEmpty { ActiveFilters().padding(.bottom, 12) }134        VStack(alignment: .leading, spacing: 8) {135            if let e = model.refreshError {136                NoticeRow(text: String(localized: "L’actualisation a échoué : \(Format.error(e).title). Les résultats affichés sont ceux d’avant."), symbol: "exclamationmark.triangle")137            }138            if model.pages.partial {139                NoticeRow(text: String(localized: "Résultats partiels : une partie de l’index n’a pas répondu, la liste peut être incomplète."), symbol: "exclamationmark.triangle")140            }141            ForEach(model.pages.notices.filter { $0 != .partialShards || !model.pages.partial }, id: \.self) { n in142                NoticeRow(text: Format.notice(n))143            }144        }145        .padding(.bottom, model.pages.notices.isEmpty && !model.pages.partial && model.refreshError == nil ? 0 : 12)146        if model.results.isEmpty {147            EmptyState()148        } else {149            let top = topCard150            ForEach(Array(model.results.enumerated()), id: \.element.id) { index, result in151                Group {152                    if index == 0, top != nil {153                        TopCard(result: result, terms: model.highlightTerms, open: open, openExternally: openExternally, preview: preview)154                            .padding(.bottom, 8)155                    } else {156                        if index > (top == nil ? 0 : 1) { Rule() }157                        ResultRow(result: result, terms: model.highlightTerms, open: open, openExternally: openExternally, preview: preview)158                    }159                }160                .modifier(Entrance(index: index % SearchModel.pageSize, alreadyShown: model.revealed.contains(result.id)) {161                    model.revealed.insert(result.id)162                })163            }164            Rule()165            MoreFooter()166            if let related = model.head?.related, !related.isEmpty, !model.pages.canLoadMore || model.pages.pageCount >= 1 {167                RelatedSearches(queries: related)168            }169        }170    }171}172173/// "Résultats pour université laval — Chercher plutôt univeristé lavla", or a mere proposal when nothing was applied.174struct CorrectionBanner: View {175    @Environment(SearchModel.self) private var model176    let correction: QueryInfo.Correction177178    var body: some View {179        VStack(alignment: .leading, spacing: 4) {180            if correction.applied {181                Text("Résultats pour \(Text(verbatim: correction.suggestion).font(.display(.body, weight: .semibold)).italic())")182                    .font(.body).foregroundStyle(Theme.ink)183                Button { model.searchVerbatim(correction.original) } label: {184                    Text("Chercher plutôt \(Text(verbatim: correction.original).fontWeight(.semibold))")185                        .font(.subheadline).multilineTextAlignment(.leading)186                }187                .accessibilityHint("Relance la recherche telle qu’elle a été écrite")188            } else {189                Button { model.submit(correction.suggestion) } label: {190                    Text("Essayez avec \(Text(verbatim: correction.suggestion).font(.display(.body, weight: .semibold)).italic())")191                        .font(.body).multilineTextAlignment(.leading)192                }193                .accessibilityHint("Lance cette recherche")194            }195        }196        .frame(maxWidth: .infinity, alignment: .leading)197        .fixedSize(horizontal: false, vertical: true)198    }199}200201/// "Environ 5 321 résultats · 41 ms": the server's own total, with the relation it declares, and its timing.202struct ResultsSummary: View {203    let head: SearchResponse204205    var body: some View {206        Text(verbatim: details)207            .font(.data(.caption))208            .foregroundStyle(Theme.muted)209            .fixedSize(horizontal: false, vertical: true)210            .accessibilityAddTraits(.isHeader)211    }212213    private var details: String {214        var parts = [Format.total(head.total)]215        if head.elapsedMS > 0 { parts.append("\(head.elapsedMS) ms") }216        if head.coverage.shardsTotal > 0, head.coverage.shardsOK < head.coverage.shardsTotal {217            parts.append(String(localized: "\(head.coverage.shardsOK) segments sur \(head.coverage.shardsTotal)"))218        }219        return parts.joined(separator: " · ")220    }221}222223/// Related searches the server drew from its index.224struct RelatedSearches: View {225    @Environment(SearchModel.self) private var model226    let queries: [String]227228    var body: some View {229        VStack(alignment: .leading, spacing: 0) {230            Eyebrow("Recherches associées").padding(.top, 22).padding(.bottom, 8)231            ForEach(queries, id: \.self) { q in232                Button { model.submit(q) } label: {233                    HStack(spacing: 12) {234                        Image(systemName: "magnifyingglass").font(.footnote).foregroundStyle(Theme.muted).frame(minWidth: 20).accessibilityHidden(true)235                        Text(verbatim: q).font(.body).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)236                        Spacer(minLength: 8)237                        Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ruleStrong).accessibilityHidden(true)238                    }239                    .padding(.vertical, 12)240                    .contentShape(Rectangle())241                }242                .buttonStyle(.plain)243                .accessibilityHint("Lance cette recherche")244                Rule()245            }246        }247    }248}249250/// The filters in force, each removable in one tap.251struct ActiveFilters: View {252    @Environment(SearchModel.self) private var model253254    var body: some View {255        FlowLayout(spacing: 8) {256            if let l = model.filters.language {257                chip(String(localized: "Langue : \(Format.languageName(l))")) { var f = model.filters; f.language = nil; model.apply(f) }258            }259            if let s = model.filters.site {260                chip(String(localized: "Site : \(s)")) { var f = model.filters; f.site = nil; model.apply(f) }261            }262            if let k = model.filters.kind {263                chip(String(localized: "Type : \(Format.kind(k))")) { var f = model.filters; f.kind = nil; model.apply(f) }264            }265            if let fresh = model.filters.fresh {266                chip(Format.fresh(fresh)) { var f = model.filters; f.fresh = nil; model.apply(f) }267            } else if model.filters.from != nil || model.filters.to != nil {268                chip(dates) { var f = model.filters; f.from = nil; f.to = nil; model.apply(f) }269            }270        }271    }272273    private var dates: String {274        switch (model.filters.from, model.filters.to) {275        case (let a?, let b?): String(localized: "Du \(Format.day(a)) au \(Format.day(b))")276        case (let a?, nil): String(localized: "Depuis le \(Format.day(a))")277        case (nil, let b?): String(localized: "Jusqu’au \(Format.day(b))")278        default: ""279        }280    }281282    private func chip(_ text: String, remove: @escaping () -> Void) -> some View {283        Button(action: remove) {284            HStack(spacing: 6) {285                Text(verbatim: text)286                Image(systemName: "xmark").imageScale(.small).foregroundStyle(Theme.muted)287            }288        }289        .buttonStyle(ChipStyle())290        .accessibilityLabel(Text("Retirer le filtre \(text)"))291    }292}293294/// An understated hint: a small sign, a line of text, no box.295struct NoticeRow: View {296    let text: String297    var symbol = "info.circle"298299    var body: some View {300        HStack(alignment: .firstTextBaseline, spacing: 8) {301            Image(systemName: symbol).font(.footnote).foregroundStyle(Theme.warn).accessibilityHidden(true)302            Text(verbatim: text).font(.footnote).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true)303        }304        .accessibilityElement(children: .combine)305    }306}307308/// End of the list: fetches the next page when it scrolls into view, waits out a rate limit, says when there is nothing more.309struct MoreFooter: View {310    @Environment(SearchModel.self) private var model311312    var body: some View {313        Group {314            switch model.more {315            case .idle where model.pages.canLoadMore, .loading:316                HStack(spacing: 10) {317                    ProgressView()318                    Text("Chargement de la suite…")319                }320                .frame(maxWidth: .infinity)321                // Runs when the footer comes into view, and again after each page while it stays in view.322                .task(id: model.pages.pageCount) { model.loadMoreIfNeeded() }323            case .waiting(let until):324                VStack(spacing: 4) {325                    Text("Limite de débit atteinte")326                        .font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink)327                    TimelineView(.periodic(from: .now, by: 1)) { context in328                        Text("Le moteur demande d’attendre : la suite sera chargée dans \(max(0, Int(until.timeIntervalSince(context.date).rounded(.up)))) s.")329                    }330                }331                .frame(maxWidth: .infinity)332            case .failed(let error):333                VStack(spacing: 8) {334                    Text(verbatim: Format.error(error).title).font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink)335                    Text(verbatim: Format.error(error).detail).multilineTextAlignment(.center)336                    Button("Réessayer") { model.retryMore() }.buttonStyle(ChipStyle())337                }338                .frame(maxWidth: .infinity)339            case .idle:340                VStack(spacing: 6) {341                    Text(model.results.count == 1 ? "Fin de la liste : 1 résultat affiché." : "Fin de la liste : \(Format.count(model.results.count)) résultats affichés.")342                }343                .frame(maxWidth: .infinity)344            }345        }346        .font(.footnote)347        .foregroundStyle(Theme.muted)348        .padding(.vertical, 14)349    }350}351352/// Placeholder rows while the first page is on its way.353struct SkeletonList: View {354    var body: some View {355        VStack(alignment: .leading, spacing: 0) {356            bar(width: 190, height: 12).padding(.bottom, 16)357            ForEach(0..<5, id: \.self) { i in358                if i > 0 { Rule() }359                VStack(alignment: .leading, spacing: 10) {360                    HStack(spacing: 10) {361                        RoundedRectangle(cornerRadius: 6).fill(Theme.sunk).frame(width: 28, height: 28)362                        VStack(alignment: .leading, spacing: 5) { bar(width: 120, height: 10); bar(width: 170, height: 8) }363                    }364                    bar(width: .infinity, height: 18)365                    bar(width: .infinity, height: 11)366                    bar(width: 240, height: 11)367                }368                .padding(.vertical, 16)369            }370        }371        .modifier(Breathing())372        .accessibilityElement(children: .ignore)373        .accessibilityLabel("Recherche en cours")374    }375376    private func bar(width: CGFloat, height: CGFloat) -> some View {377        RoundedRectangle(cornerRadius: 2).fill(Theme.sunk).frame(maxWidth: width == .infinity ? .infinity : width, minHeight: height, maxHeight: height)378    }379}380381/// No result: says so, recalls that the index is partial, and offers the one useful action when filters are on.382struct EmptyState: View {383    @Environment(SearchModel.self) private var model384385    var body: some View {386        VStack(alignment: .leading, spacing: 12) {387            Text("Aucun résultat pour « \(model.query) »")388                .font(.display(.title2)).foregroundStyle(Theme.ink)389                .accessibilityAddTraits(.isHeader)390            if let docs = model.head?.coverage.documents, docs > 0 {391                Text("L’index contient \(Format.count(docs)) documents, soit une partie seulement du Web public : l’absence de résultat ne signifie pas que la page n’existe pas.")392            } else {393                Text("L’index ne couvre qu’une partie du Web : l’absence de résultat ne signifie pas que la page n’existe pas.")394            }395            VStack(alignment: .leading, spacing: 6) {396                Text("— Vérifiez l’orthographe ou essayez des termes plus généraux.")397                if !model.filters.isEmpty { Text("— Retirez un filtre (langue, site, type, dates).") }398            }399            if !model.filters.isEmpty {400                Button("Retirer tous les filtres") { model.apply(SearchFilters()) }.buttonStyle(ChipStyle())401            }402        }403        .font(.subheadline)404        .foregroundStyle(Theme.muted)405        .padding(.top, 8)406        .fixedSize(horizontal: false, vertical: true)407    }408}409410struct ErrorState: View {411    let error: SearchError412    var retry: () -> Void413414    var body: some View {415        let words = Format.error(error)416        VStack(alignment: .leading, spacing: 10) {417            Image(systemName: error == .offline ? "wifi.slash" : "exclamationmark.triangle")418                .font(.title2).foregroundStyle(Theme.danger).accessibilityHidden(true)419            Text(verbatim: words.title).font(.display(.title2)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)420                .fixedSize(horizontal: false, vertical: true)421            if !words.detail.isEmpty {422                Text(verbatim: words.detail).font(.subheadline).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true)423            }424            Button("Réessayer", action: retry).buttonStyle(ChipStyle()).padding(.top, 4)425        }426        .padding(.top, 24)427    }428}429
Files main
Menu

Theme