SPB Git

Repository Public

SearchScreen.swift 21.2 KB 509 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Features/Search/SearchScreen.swift10// Description      : Root screen: home, search field, suggestions, results;11//                    sheets, links, Spotlight items and intents arrive here.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 SwiftUI9293enum SheetKind: String, Identifiable {94    case filters, history, favorites, settings95    var id: String { rawValue }96}9798struct SearchScreen: View {99    @Environment(SearchModel.self) private var model100    @Environment(AppSettings.self) private var settings101    @Environment(FavoritesModel.self) private var favorites102    @Environment(VoiceSearch.self) private var voice103    @Environment(Router.self) private var router104    @Environment(\.horizontalSizeClass) private var hSize105    @Environment(\.accessibilityReduceMotion) private var reduceMotion106    @Environment(\.openURL) private var openURL107    @Environment(\.scenePhase) private var scenePhase108    @Environment(\.dynamicTypeSize) private var typeSize109    @FocusState private var focused: Bool110    @State private var sheet: SheetKind?111    @State private var safari: SafariItem?112    @State private var preview: SearchResult?113    @Namespace private var space114115    private var wide: Bool { hSize == .regular }116    /// Home at rest: the mark, the name and the field take the stage.117    private var hero: Bool { !model.hasSearch && !focused }118119    var body: some View {120        ZStack {121            Theme.paper.ignoresSafeArea()122            VStack(spacing: 0) {123                if hero {124                    homeBar125                    Spacer(minLength: 0).frame(maxHeight: wide ? 90 : 36)126                    HeroHeader(space: space)127                        .padding(.bottom, 26)128                        .transition(.opacity)129                }130                fieldRow131                    .padding(.horizontal, 16)132                    .padding(.top, hero ? 0 : 8).padding(.bottom, hero ? 6 : 10)133                    .frame(maxWidth: hero ? 680 : .infinity)134                if !hero, !focused, !model.verticals.isEmpty {135                    VerticalTabs()136                }137                if !hero { Rule() }138                content139            }140            shortcuts141        }142        .animation(reduceMotion ? nil : .snappy(duration: 0.32), value: hero)143        .animation(reduceMotion ? nil : .easeOut(duration: 0.18), value: focused)144        .sheet(item: $sheet) { kind in145            switch kind {146            case .filters: FiltersSheet()147            case .history: HistoryView { q in sheet = nil; run(q) }148            case .favorites: FavoritesView { url in sheet = nil; open(url) }149            case .settings: SettingsView()150            }151        }152        .sheet(item: $preview) { result in153            PreviewSheet(result: result, open: { url in preview = nil; open(url) }, openExternally: { openURL($0) },154                         moreFromSite: { preview = nil; model.moreFromSite($0) })155        }156        .sheet(isPresented: Binding(get: { voice.state == .listening }, set: { if !$0 { voice.cancel() } })) {157            VoicePanel()158        }159        .fullScreenCover(item: $safari) { item in SafariView(url: item.url).ignoresSafeArea() }160        .haptic(.selection, trigger: model.vertical)161        .haptic(.success, trigger: favorites.items.count)162        .task { await start() }163        .onChange(of: router.pending) { _, _ in consume() }164        .onChange(of: scenePhase) { _, phase in165            guard phase == .active else { return }166            voice.refreshAvailability()167            Task { await model.loadStatus(force: true) }168        }169    }170171    // MARK: Parts172173    private var homeBar: some View {174        HStack(spacing: typeSize.isAccessibilitySize ? 10 : 2) {175            Spacer()176            barButton("star", label: "Favoris") { sheet = .favorites }177            barButton("clock.arrow.circlepath", label: "Historique") { sheet = .history }178            barButton("gearshape", label: "Réglages") { sheet = .settings }179        }180        .padding(.horizontal, 8)181    }182183    private func barButton(_ symbol: String, label: LocalizedStringKey, action: @escaping () -> Void) -> some View {184        Button(action: action) {185            Image(systemName: symbol).font(.body.weight(.medium)).foregroundStyle(Theme.ink).frame(minWidth: 44, minHeight: 44).contentShape(Rectangle())186        }187        .accessibilityLabel(label)188    }189190    /// Mark, field and the buttons of the search on one line; at the largest text sizes the buttons move to a line191    /// of their own so the field keeps its width.192    private var fieldRow: some View {193        VStack(alignment: .trailing, spacing: 4) {194            HStack(spacing: 10) {195                if !hero {196                    Button { focused = false; model.goHome() } label: {197                        MarkView(size: 30).matchedGeometryEffect(id: "mark", in: space).frame(width: 36, height: 44)198                    }199                    .accessibilityLabel("Accueil")200                }201                SearchField(text: Binding(get: { model.text }, set: { model.updateText($0) }), focused: $focused, prominent: hero,202                            onVoice: voice.isAvailable ? { startVoice() } : nil) { submit() }203                if focused {204                    Button("Annuler") { cancelEditing() }205                        .font(.body.weight(.medium))206                } else if model.hasSearch, !typeSize.isAccessibilitySize {207                    searchButtons208                }209            }210            if !focused, model.hasSearch, typeSize.isAccessibilitySize {211                HStack(spacing: 10) { searchButtons }212            }213        }214        .font(.body.weight(.medium))215        .foregroundStyle(Theme.ink)216    }217218    @ViewBuilder private var searchButtons: some View {219        if !wide {220            Button { sheet = .filters } label: {221                Image(systemName: "line.3.horizontal.decrease")222                    .frame(minWidth: 40, minHeight: 44)223                    .overlay(alignment: .topTrailing) {224                        if model.filters.count > 0 {225                            Text(verbatim: "\(model.filters.count)").font(.caption2.weight(.bold)).foregroundStyle(Theme.paper)226                                .frame(minWidth: 16, minHeight: 16).background(Theme.accent, in: Circle()).offset(x: 2, y: 4)227                        }228                    }229            }230            .accessibilityLabel(model.filters.count > 0 ? Text("Filtres, \(model.filters.count) actifs") : Text("Filtres"))231        }232        Menu {233            ShareLink(item: model.link.webURL) { Label("Partager cette recherche", systemImage: "square.and.arrow.up") }234            Divider()235            Button { sheet = .favorites } label: { Label("Favoris", systemImage: "star") }236            Button { sheet = .history } label: { Label("Historique", systemImage: "clock.arrow.circlepath") }237            Button { sheet = .settings } label: { Label("Réglages", systemImage: "gearshape") }238        } label: {239            Image(systemName: "ellipsis").frame(minWidth: 36, minHeight: 44).contentShape(Rectangle())240        }241        .accessibilityLabel("Plus")242    }243244    @ViewBuilder private var content: some View {245        if focused {246            SuggestionsPanel(onPick: { run($0) }, onFill: { model.updateText($0) }, onOpen: { focused = false; open($0) })247                .transition(.opacity)248        } else if model.hasSearch {249            HStack(spacing: 0) {250                ResultsView(open: open, openExternally: { openURL($0) }, preview: { preview = $0 })251                if wide {252                    Rectangle().fill(Theme.rule).frame(width: 1).ignoresSafeArea(edges: .bottom)253                    FiltersPanel().frame(width: 340)254                }255            }256        } else {257            HomeView(onPick: { run($0) }, onShowHistory: { sheet = .history })258                .transition(.opacity)259        }260    }261262    /// ⌘K and ⌘F put the cursor in the field (hardware keyboard).263    private var shortcuts: some View {264        Group {265            Button("Rechercher") { focused = true }.keyboardShortcut("k", modifiers: .command)266            Button("Rechercher") { focused = true }.keyboardShortcut("f", modifiers: .command)267        }268        .frame(width: 0, height: 0).opacity(0).accessibilityHidden(true)269    }270271    // MARK: Actions272273    private func submit() {274        focused = false275        model.submit()276    }277278    private func run(_ query: String) {279        focused = false280        model.submit(query)281    }282283    private func cancelEditing() {284        focused = false285        model.updateText(model.query)286    }287288    private func startVoice() {289        focused = false290        Task { await voice.start { text in run(text) } }291    }292293    /// A page opens in the in-app Safari view, or in the default browser when the reader prefers it.294    private func open(_ url: URL) {295        if settings.openInApp { safari = SafariItem(url: url) } else { openURL(url) }296    }297298    /// A request left by a universal link, the widget, Spotlight or a shortcut.299    private func consume() {300        guard let request = router.pending else { return }301        router.pending = nil302        sheet = nil; preview = nil; safari = nil303        switch request {304        case .search(let link):305            focused = false306            Task { await model.open(link) }307        case .focus:308            model.goHome()309            focused = true310        case .home:311            focused = false312            model.goHome()313        case .page(let url):314            open(url)315        }316    }317318    private func start() async {319        #if DEBUG320        if let url = LaunchOptions.openURL { SPSearchApp.route(url) }321        #endif322        var presetState = router.pending != nil323        consume()324        #if DEBUG325        if LaunchOptions.stub || LaunchOptions.vertical != nil { await model.loadCatalog() }326        if let v = LaunchOptions.vertical { model.setVertical(v) }327        if let q = LaunchOptions.query { model.submit(q); presetState = true }328        if let s = LaunchOptions.sheet {329            presetState = true330            if let kind = SheetKind(rawValue: s) {331                sheet = kind332            } else if s == "voice" {333                voice.debugShow("université laval admission")334            } else if s == "preview" {335                await model.searchTask?.value336                preview = model.results.first337            } else if s == "verbatim", let q = LaunchOptions.query {338                await model.searchTask?.value339                model.searchVerbatim(q)340            }341        }342        if LaunchOptions.pages > 1 {343            await model.searchTask?.value344            for _ in 1..<LaunchOptions.pages { model.loadMoreIfNeeded(); await model.moreTask?.value }345        }346        if LaunchOptions.focus { focused = true; presetState = true }347        if LaunchOptions.home { presetState = true }348        if let t = LaunchOptions.typed { focused = true; model.updateText(t); presetState = true }349        #endif350        async let catalog: Void = model.loadCatalog()351        async let status: Void = model.loadStatus()352        _ = await (catalog, status)353        // From the second launch on, the cursor is in the field straight away; the first launch shows the home screen.354        let returning = settings.launchedBefore355        settings.launchedBefore = true356        if returning, !presetState, router.pending == nil {357            try? await Task.sleep(for: .milliseconds(400))358            if !model.hasSearch, sheet == nil, voice.state != .listening { focused = true }359        }360    }361}362363/// Mark and name above the field on the home screen.364struct HeroHeader: View {365    let space: Namespace.ID366    @ScaledMetric(relativeTo: .largeTitle) private var nameSize: CGFloat = 50367368    var body: some View {369        VStack(spacing: 16) {370            MarkView(size: 60).matchedGeometryEffect(id: "mark", in: space)371            Text(verbatim: "SPSearch")372                .font(.system(size: min(nameSize, 76), weight: .medium, design: .serif))373                .tracking(-1.2)374                .foregroundStyle(Theme.ink)375                .lineLimit(1).minimumScaleFactor(0.6)376                .accessibilityAddTraits(.isHeader)377            Text("Moteur de recherche indépendant")378                .font(.eyebrow).textCase(.uppercase).tracking(1.4)379                .foregroundStyle(Theme.muted)380                .multilineTextAlignment(.center)381                .fixedSize(horizontal: false, vertical: true)382        }383        .padding(.horizontal, 20)384        .accessibilityElement(children: .combine)385    }386}387388/// The categories `/v2/filters` lists, when there is more than the Web. Nothing is shown otherwise.389struct VerticalTabs: View {390    @Environment(SearchModel.self) private var model391392    var body: some View {393        ScrollView(.horizontal, showsIndicators: false) {394            HStack(spacing: 22) {395                ForEach(model.verticals) { v in396                    let selected = v.id == model.vertical397                    Button { model.setVertical(v.id) } label: {398                        Text(verbatim: Format.vertical(v.id))399                            .font(.subheadline.weight(selected ? .semibold : .regular))400                            .foregroundStyle(selected ? Theme.ink : Theme.muted)401                            .padding(.vertical, 9)402                            .overlay(alignment: .bottom) { Rectangle().fill(selected ? Theme.accent : .clear).frame(height: 2) }403                            .contentShape(Rectangle())404                    }405                    .buttonStyle(.plain)406                    .accessibilityAddTraits(selected ? [.isSelected] : [])407                    .accessibilityHint("Change la catégorie de la recherche")408                }409            }410            .padding(.horizontal, 20)411        }412        .frame(maxWidth: .infinity, alignment: .leading)413    }414}415416struct SearchField: View {417    @Binding var text: String418    var focused: FocusState<Bool>.Binding419    var prominent: Bool420    /// nil hides the microphone (dictation cannot stay on the device, or a permission was refused).421    var onVoice: (() -> Void)?422    var onSubmit: () -> Void423424    var body: some View {425        HStack(spacing: 10) {426            Image(systemName: "magnifyingglass")427                .font(.body.weight(.semibold))428                .foregroundStyle(focused.wrappedValue ? Theme.accent : Theme.muted)429                .accessibilityHidden(true)430            TextField("Rechercher dans l’index", text: $text)431                .focused(focused)432                .font(prominent ? .title3 : .body)433                .foregroundStyle(Theme.ink)434                .submitLabel(.search)435                .textInputAutocapitalization(.never)436                .autocorrectionDisabled()437                .onSubmit(onSubmit)438                .accessibilityLabel("Rechercher dans l’index SPIndex")439                .accessibilityIdentifier("search.field")440            if !text.isEmpty {441                Button { text = ""; focused.wrappedValue = true } label: {442                    Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ruleStrong).frame(minWidth: 30, minHeight: 30)443                }444                .accessibilityLabel("Effacer le texte")445            } else if let onVoice {446                Button(action: onVoice) {447                    Image(systemName: "mic").font(.body.weight(.medium)).foregroundStyle(Theme.ink).frame(minWidth: 34, minHeight: 34).contentShape(Rectangle())448                }449                .accessibilityLabel("Recherche vocale")450                .accessibilityHint("Dicte la recherche ; la reconnaissance se fait sur l’appareil")451            }452        }453        .padding(.leading, 16).padding(.trailing, 8)454        .padding(.vertical, prominent ? 14 : 7)455        .frame(minHeight: prominent ? 58 : 44)456        .glassSurface(cornerRadius: prominent ? 20 : 14, interactive: false)457        .overlay(RoundedRectangle(cornerRadius: prominent ? 20 : 14, style: .continuous)458            .stroke(focused.wrappedValue ? Theme.accent : Theme.ruleStrong.opacity(0.55), lineWidth: focused.wrappedValue ? 1.5 : 0.75))459        .contentShape(Rectangle())460        .onTapGesture { focused.wrappedValue = true }461    }462}463464/// Listening panel of the voice search: what is heard, the input level, and two ways out.465struct VoicePanel: View {466    @Environment(VoiceSearch.self) private var voice467    @Environment(\.accessibilityReduceMotion) private var reduceMotion468469    var body: some View {470        VStack(spacing: 18) {471            Eyebrow("Recherche vocale")472            Text(verbatim: voice.transcript.isEmpty ? String(localized: "Dites votre recherche…") : voice.transcript)473                .font(.display(.title2))474                .foregroundStyle(voice.transcript.isEmpty ? Theme.muted : Theme.ink)475                .multilineTextAlignment(.center)476                .frame(maxWidth: .infinity, minHeight: 70)477                .accessibilityAddTraits(.updatesFrequently)478            LevelBar(level: voice.level)479                .animation(reduceMotion ? nil : .linear(duration: 0.08), value: voice.level)480            Text("La reconnaissance se fait sur cet appareil : l’audio n’est envoyé nulle part.")481                .font(.caption).foregroundStyle(Theme.muted).multilineTextAlignment(.center)482            HStack(spacing: 12) {483                Button("Annuler") { voice.cancel() }.buttonStyle(ChipStyle())484                Button("Rechercher") { voice.finish() }.buttonStyle(ChipStyle()).disabled(voice.transcript.isEmpty)485            }486        }487        .padding(24)488        .frame(maxWidth: .infinity)489        .presentationDetents([.height(320), .medium])490        .presentationDragIndicator(.visible)491        .presentationBackground(Theme.paper)492    }493}494495struct LevelBar: View {496    let level: Double497    var body: some View {498        GeometryReader { geo in499            ZStack(alignment: .leading) {500                Capsule().fill(Theme.sunk)501                Capsule().fill(Theme.accent).frame(width: max(6, geo.size.width * level))502            }503        }504        .frame(height: 6)505        .frame(maxWidth: 220)506        .accessibilityHidden(true)507    }508}509
Files main
Menu

Theme