SPB Git

Repository Public

ResultRow.swift 16.5 KB 357 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Features/Results/ResultRow.swift10// Description      : A web result as a native row, and the top card of a11//                    navigational search with its sitelinks.12// Module           : Features13// 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 SPSearchKit91import SwiftUI92import UIKit9394/// What a result says besides its text: marks, publication, address check. Shared by the row, the card and the preview.95enum ResultText {96    /// The server's marks when it sent them (V2, code points); on a V1 server, the query terms found in the text.97    /// Marked words stand out by weight and ink; nothing relies on colour alone.98    static func snippet(_ r: SearchResult, terms: [String]) -> AttributedString {99        ink(r.serverHighlights ? Highlighter.attributed(r.snippet, codePoints: r.highlights) : Highlighter.attributed(r.snippet, terms: terms))100    }101102    static func title(_ r: SearchResult) -> AttributedString {103        r.serverHighlights ? Highlighter.attributed(r.title, codePoints: r.titleHighlights) : AttributedString(r.title)104    }105106    static func ink(_ marked: AttributedString) -> AttributedString {107        var a = marked108        for run in a.runs where run.inlinePresentationIntent == .stronglyEmphasized { a[run.range].foregroundColor = Theme.ink }109        return a110    }111112    /// "Encyclopédie · Français · Publié le 3 nov. 2026". The publication date appears only when the engine verified113    /// one; the date of the crawler's visit is never shown as a publication date.114    static func facts(_ r: SearchResult) -> String {115        var parts: [String] = []116        if r.kind != .page { parts.append(r.kind.label) }117        if let l = r.language { parts.append(Format.languageName(l)) }118        if let d = r.publishedAt { parts.append(String(localized: "Publié le \(Format.day(d))")) }119        return parts.joined(separator: " · ")120    }121122    static func site(_ r: SearchResult) -> String { r.siteName ?? (r.domain.isEmpty ? (URL(string: r.url)?.host ?? r.url) : r.domain) }123124    static func spoken(_ r: SearchResult, now: Date = Date()) -> String {125        var parts = [r.title, site(r)]126        if !r.snippet.isEmpty { parts.append(r.snippet) }127        let f = facts(r)128        if !f.isEmpty { parts.append(f) }129        if let v = Format.validation(r, now: now) { parts.append(v.text) }130        return parts.filter { !$0.isEmpty }.joined(separator: ". ")131    }132}133134/// Site line of a result: icon, name, short address.135struct SiteLine: View {136    let result: SearchResult137    var iconSize: CGFloat = 28138139    var body: some View {140        HStack(alignment: .center, spacing: 10) {141            FaviconView(path: result.faviconPath, name: ResultText.site(result), size: iconSize)142            VStack(alignment: .leading, spacing: 1) {143                Text(verbatim: ResultText.site(result))144                    .font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(1)145                // Without a site name the first line is already the domain: the address is repeated only when it says more.146                if Format.displayURL(result) != ResultText.site(result) {147                    Text(verbatim: Format.displayURL(result))148                        .font(.data(.caption2)).foregroundStyle(Theme.muted).lineLimit(1).truncationMode(.tail)149                }150            }151        }152    }153}154155/// "Adresse vérifiée il y a 2 heures": a technical check of the URL by the crawler, worded as such.156struct ValidationLine: View {157    let result: SearchResult158159    var body: some View {160        if let v = Format.validation(result) {161            HStack(alignment: .firstTextBaseline, spacing: 5) {162                Image(systemName: v.warning ? "exclamationmark.triangle" : "checkmark.circle").imageScale(.small).accessibilityHidden(true)163                Text(verbatim: v.text).fixedSize(horizontal: false, vertical: true)164            }165            .font(.caption)166            .foregroundStyle(v.warning ? Theme.warn : Theme.muted)167        }168    }169}170171/// Context menu and VoiceOver actions common to every result.172struct ResultMenu: ViewModifier {173    let result: SearchResult174    var open: (URL) -> Void175    var openExternally: (URL) -> Void176    var preview: (SearchResult) -> Void177    @Environment(SearchModel.self) private var model178    @Environment(FavoritesModel.self) private var favorites179180    func body(content: Content) -> some View {181        let saved = favorites.contains(result.url)182        content183            .contextMenu {184                if let url = result.link {185                    Button { open(url) } label: { Label("Ouvrir", systemImage: "safari") }186                    Button { openExternally(url) } label: { Label("Ouvrir dans le navigateur", systemImage: "arrow.up.right.square") }187                }188                Button { preview(result) } label: { Label("Aperçu", systemImage: "doc.text.magnifyingglass") }189                Button { favorites.toggle(result) } label: {190                    Label(saved ? "Retirer des favoris" : "Ajouter aux favoris", systemImage: saved ? "star.slash" : "star")191                }192                if let url = result.link {193                    ShareLink(item: url, subject: Text(verbatim: result.title)) { Label("Partager…", systemImage: "square.and.arrow.up") }194                    Button { UIPasteboard.general.url = url } label: { Label("Copier le lien", systemImage: "doc.on.doc") }195                }196                if !result.domain.isEmpty {197                    Button { model.moreFromSite(result.domain) } label: { Label("Plus de résultats de ce site", systemImage: "text.magnifyingglass") }198                }199            }200            .accessibilityAction(named: Text("Aperçu")) { preview(result) }201            .accessibilityAction(named: saved ? Text("Retirer des favoris") : Text("Ajouter aux favoris")) { favorites.toggle(result) }202            .accessibilityAction(named: Text("Plus de résultats de ce site")) { model.moreFromSite(result.domain) }203    }204}205206struct ResultRow: View {207    let result: SearchResult208    let terms: [String]209    var open: (URL) -> Void210    var openExternally: (URL) -> Void211    var preview: (SearchResult) -> Void212    @Environment(FavoritesModel.self) private var favorites213214    var body: some View {215        Button { if let url = result.link { open(url) } } label: {216            VStack(alignment: .leading, spacing: 7) {217                SiteLine(result: result).padding(.trailing, 44)218                Text(ResultText.title(result))219                    .font(.display(.title3))220                    .foregroundStyle(Theme.ink)221                    .multilineTextAlignment(.leading)222                    .lineLimit(3)223                    .padding(.top, 2)224                if !result.snippet.isEmpty {225                    Text(ResultText.snippet(result, terms: terms))226                        .font(.subheadline)227                        .foregroundStyle(Theme.muted)228                        .multilineTextAlignment(.leading)229                        .lineLimit(4)230                }231                let facts = ResultText.facts(result)232                if !facts.isEmpty {233                    Text(verbatim: facts).font(.caption).foregroundStyle(Theme.muted).multilineTextAlignment(.leading)234                }235                ValidationLine(result: result)236            }237            .padding(.vertical, 16)238            .frame(maxWidth: .infinity, alignment: .leading)239            .contentShape(Rectangle())240        }241        .buttonStyle(RowPress())242        .disabled(result.link == nil)243        .overlay(alignment: .topTrailing) { PreviewButton(result: result, preview: preview).padding(.top, 8) }244        .modifier(ResultMenu(result: result, open: open, openExternally: openExternally, preview: preview))245        .accessibilityElement(children: .ignore)246        .accessibilityLabel(Text(verbatim: ResultText.spoken(result) + (favorites.contains(result.url) ? ". " + String(localized: "Dans vos favoris") : "")))247        .accessibilityHint("Ouvre la page")248        .accessibilityAddTraits(.isLink)249    }250}251252/// Opens the preview sheet; a filled star replaces the sign when the result is a favorite.253struct PreviewButton: View {254    let result: SearchResult255    var preview: (SearchResult) -> Void256    @Environment(FavoritesModel.self) private var favorites257258    var body: some View {259        Button { preview(result) } label: {260            Image(systemName: favorites.contains(result.url) ? "star.fill" : "ellipsis")261                .font(.footnote.weight(.semibold))262                .foregroundStyle(favorites.contains(result.url) ? Theme.accent : Theme.muted)263                .frame(minWidth: 44, minHeight: 44)264                .contentShape(Rectangle())265        }266        .accessibilityLabel("Aperçu")267    }268}269270/// First result of a navigational search: the site itself, larger, with the other pages the server lists for it.271struct TopCard: View {272    let result: SearchResult273    let terms: [String]274    var open: (URL) -> Void275    var openExternally: (URL) -> Void276    var preview: (SearchResult) -> Void277    @Environment(SearchModel.self) private var model278    @Environment(FavoritesModel.self) private var favorites279    @Environment(\.dynamicTypeSize) private var typeSize280281    var body: some View {282        VStack(alignment: .leading, spacing: 0) {283            Button { if let url = result.link { open(url) } } label: {284                VStack(alignment: .leading, spacing: 10) {285                    SiteLine(result: result, iconSize: 36).padding(.trailing, 40)286                    Text(ResultText.title(result))287                        .font(.display(.title, weight: .medium))288                        .foregroundStyle(Theme.ink)289                        .multilineTextAlignment(.leading)290                        .lineLimit(3)291                    if !result.snippet.isEmpty {292                        Text(ResultText.snippet(result, terms: terms))293                            .font(.subheadline).foregroundStyle(Theme.muted)294                            .multilineTextAlignment(.leading).lineLimit(4)295                    }296                    ValidationLine(result: result)297                }298                .padding(16)299                .frame(maxWidth: .infinity, alignment: .leading)300                .contentShape(Rectangle())301            }302            .buttonStyle(RowPress())303            .disabled(result.link == nil)304            .overlay(alignment: .topTrailing) { PreviewButton(result: result, preview: preview).padding(.top, 6).padding(.trailing, 2) }305            .modifier(ResultMenu(result: result, open: open, openExternally: openExternally, preview: preview))306            .accessibilityElement(children: .ignore)307            .accessibilityLabel(Text(verbatim: ResultText.spoken(result)))308            .accessibilityHint("Ouvre la page")309            .accessibilityAddTraits(.isLink)310311            if !result.sitelinks.isEmpty {312                Rule()313                let columns = typeSize.isAccessibilitySize ? [GridItem(.flexible())] : [GridItem(.flexible(), spacing: 0), GridItem(.flexible(), spacing: 0)]314                LazyVGrid(columns: columns, alignment: .leading, spacing: 0) {315                    ForEach(result.sitelinks) { link in316                        Button { if let url = link.link { open(url) } } label: {317                            HStack(spacing: 6) {318                                Text(verbatim: link.title).font(.subheadline.weight(.medium)).foregroundStyle(Theme.accent)319                                    .multilineTextAlignment(.leading).lineLimit(2)320                                Spacer(minLength: 4)321                                Image(systemName: "chevron.right").font(.caption2.weight(.semibold)).foregroundStyle(Theme.ruleStrong).accessibilityHidden(true)322                            }323                            .padding(.horizontal, 16).padding(.vertical, 12)324                            .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)325                            .contentShape(Rectangle())326                        }327                        .buttonStyle(RowPress())328                        .accessibilityHint("Ouvre la page")329                    }330                }331            }332            if result.moreFromSite > 0, !result.domain.isEmpty {333                Rule()334                Button { model.moreFromSite(result.domain) } label: {335                    HStack {336                        Text("Plus de résultats de \(result.domain)").font(.footnote.weight(.medium)).foregroundStyle(Theme.ink)337                        Spacer()338                        Text(verbatim: Format.count(result.moreFromSite)).font(.data(.caption)).foregroundStyle(Theme.muted)339                    }340                    .padding(.horizontal, 16).padding(.vertical, 12)341                    .contentShape(Rectangle())342                }343                .buttonStyle(RowPress())344            }345        }346        .background(Theme.raised, in: RoundedRectangle(cornerRadius: 14, style: .continuous))347        .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).stroke(Theme.rule, lineWidth: 1))348    }349}350351/// Pressed row: the content dims slightly; no scaling, no shadow.352struct RowPress: ButtonStyle {353    func makeBody(configuration: Configuration) -> some View {354        configuration.label.opacity(configuration.isPressed ? 0.6 : 1)355    }356}357
Files main
Menu

Theme