Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Features/Filters/FiltersView.swift10// Description : Filters: region setting, language and site facets of the11// response, verified publication dates; sheet on iPhone,12// column on iPad.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 SwiftUI9394/// iPhone: a sheet with a draft, applied on demand.95struct FiltersSheet: View {96 @Environment(SearchModel.self) private var model97 @Environment(\.dismiss) private var dismiss98 @State private var draft = SearchFilters()99 @State private var region = RegionChoice.automatic100101 var body: some View {102 NavigationStack {103 FiltersForm(draft: $draft, region: $region)104 .navigationTitle("Filtres")105 .navigationBarTitleDisplayMode(.inline)106 .toolbar {107 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }108 ToolbarItem(placement: .confirmationAction) {109 Button("Appliquer") {110 // The region first: it is a setting; then the filters, which run the search once.111 let filtersChanged = draft != model.filters112 if filtersChanged, region != model.settings.region { model.settings.region = region } else { model.setRegion(region) }113 model.apply(draft)114 dismiss()115 }116 .fontWeight(.semibold)117 }118 }119 }120 .onAppear { draft = model.filters; region = model.settings.region }121 .presentationDetents([.large])122 }123}124125/// iPad: a column beside the results; each change applies at once.126struct FiltersPanel: View {127 @Environment(SearchModel.self) private var model128 @State private var draft = SearchFilters()129 @State private var region = RegionChoice.automatic130131 var body: some View {132 VStack(alignment: .leading, spacing: 0) {133 Text("Filtres").font(.headline).foregroundStyle(Theme.ink)134 .padding(.horizontal, 20).padding(.top, 16).padding(.bottom, 4)135 .accessibilityAddTraits(.isHeader)136 FiltersForm(draft: $draft, region: $region)137 }138 .background(Theme.paper)139 .onAppear { draft = model.filters; region = model.settings.region }140 .onChange(of: model.filters) { _, new in if draft != new { draft = new } }141 .onChange(of: model.settings.region) { _, new in if region != new { region = new } }142 .onChange(of: draft) { _, new in model.apply(new) }143 .onChange(of: region) { _, new in model.setRegion(new) }144 }145}146147struct FiltersForm: View {148 @Environment(SearchModel.self) private var model149 @Binding var draft: SearchFilters150 @Binding var region: RegionChoice151 @State private var siteText = ""152153 private var facets: Facets { model.head?.facets ?? Facets() }154 private var catalog: FilterCatalog { model.catalog }155156 var body: some View {157 Form {158 Section {159 choice(String(localized: "Toutes les dates"), count: nil, selected: !draft.hasDate) { draft.fresh = nil; draft.from = nil; draft.to = nil }160 // Period shortcuts: exactly those `/v2/filters` lists.161 ForEach(catalog.fresh, id: \.self) { f in162 choice(Format.fresh(f), count: nil, selected: draft.fresh == f) { draft.fresh = f; draft.from = nil; draft.to = nil }163 }164 Toggle("Depuis le", isOn: Binding(get: { draft.from != nil }, set: { draft.fresh = nil; draft.from = $0 ? (draft.to ?? Date()) : nil }))165 if let from = draft.from {166 DatePicker("Début", selection: Binding(get: { from }, set: { draft.from = $0; if let t = draft.to, t < $0 { draft.to = $0 } }), in: ...Date(), displayedComponents: .date)167 }168 Toggle("Jusqu’au", isOn: Binding(get: { draft.to != nil }, set: { draft.fresh = nil; draft.to = $0 ? Date() : nil }))169 if let to = draft.to {170 DatePicker("Fin", selection: Binding(get: { to }, set: { draft.to = $0; if let f = draft.from, f > $0 { draft.from = $0 } }), in: ...Date(), displayedComponents: .date)171 }172 } header: {173 Text("Date de publication")174 } footer: {175 Text("Porte sur la date de publication que le moteur a pu vérifier. Beaucoup de pages n’en déclarent aucune.")176 }177178 Section {179 choice(String(localized: "Toutes les langues"), count: nil, selected: draft.language == nil) { draft.language = nil }180 ForEach(languages) { f in181 choice(Format.languageName(f.value), count: f.count, selected: draft.language == f.value) { draft.language = f.value }182 }183 } header: {184 Text("Langue")185 }186187 if !kinds.isEmpty {188 Section {189 choice(String(localized: "Tous les types"), count: nil, selected: draft.kind == nil) { draft.kind = nil }190 ForEach(kinds) { f in191 choice(Format.kind(f.value), count: f.count, selected: draft.kind == f.value) { draft.kind = f.value }192 }193 } header: {194 Text("Type de page")195 } footer: {196 Text("Le type est une indication calculée par le moteur, pas une certitude.")197 }198 }199200 Section {201 choice(String(localized: "Tous les sites"), count: nil, selected: draft.site == nil) { draft.site = nil }202 ForEach(domains) { f in203 choice(f.value, count: f.count, selected: draft.site == f.value, mono: true) { draft.site = f.value }204 }205 HStack {206 TextField("Autre site : exemple.org", text: $siteText)207 .font(.data(.subheadline))208 .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)209 .submitLabel(.done)210 .onSubmit(applySite)211 if !siteText.isEmpty { Button("OK", action: applySite).font(.subheadline.weight(.semibold)) }212 }213 } header: {214 Text("Site")215 } footer: {216 if facets.candidates > 0 {217 Text("Décomptes établis parmi les \(Format.count(facets.candidates)) meilleurs résultats de cette recherche, et non sur l’index entier.")218 }219 }220221 Section {222 Picker("Région", selection: $region) {223 ForEach(regions, id: \.self) { r in Text(verbatim: Format.regionOption(r)).tag(r) }224 }225 if let applied = Format.applied(model.head?.region) {226 LabeledContent("Appliquée par le serveur") { Text(verbatim: applied) }227 .font(.footnote)228 }229 } header: {230 Text("Région")231 } footer: {232 Text("Les sites de la région sont modérément favorisés ; rien n’est exclu. Votre choix reste sur cet appareil ; l’adresse IP n’est jamais utilisée. En mode automatique, le serveur lit la région que déclare la langue de l’appareil.")233 }234235 if !draft.isEmpty {236 Section {237 Button("Réinitialiser les filtres", role: .destructive) { draft = SearchFilters() }238 }239 }240 }241 .scrollContentBackground(.hidden)242 .background(Theme.paper)243 .tint(Theme.accent)244 }245246 private func applySite() {247 var s = siteText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()248 if let host = URL(string: s)?.host { s = host }249 if s.hasPrefix("www.") { s.removeFirst(4) }250 guard !s.isEmpty, !s.contains(" ") else { return }251 draft.site = s252 siteText = ""253 }254255 /// The languages found among this search's candidates; a filter in force that the facets no longer list stays visible.256 private var languages: [Facet] {257 var list = facets.languages258 if list.isEmpty { list = catalog.languages.prefix(8).map { Facet(value: $0.value, count: 0) } }259 if let l = draft.language, !list.contains(where: { $0.value == l }) { list.insert(Facet(value: l, count: 0), at: 0) }260 return list261 }262263 /// Page types: only those `/v2/filters` lists, with the counts of this search when the answer carries them.264 private var kinds: [Facet] {265 let counts = Dictionary(facets.kinds.map { ($0.value, $0.count) }, uniquingKeysWith: { a, _ in a })266 var list = catalog.kinds.map { Facet(value: $0, count: counts[$0] ?? 0) }.sorted { $0.count > $1.count }267 if let k = draft.kind, !list.contains(where: { $0.value == k }) { list.insert(Facet(value: k, count: 0), at: 0) }268 return list269 }270271 private var domains: [Facet] {272 var list = facets.domains273 if let s = draft.site, !list.contains(where: { $0.value == s }) { list.insert(Facet(value: s, count: 0), at: 0) }274 return list275 }276277 /// Automatic, the regions the server lists (those the app can name), and "none". The current choice is always there.278 private var regions: [RegionChoice] {279 var list: [RegionChoice] = [.automatic]280 list += catalog.regions.compactMap { RegionChoice(rawValue: $0) }.filter { $0 != .automatic && $0 != .off }281 list.append(.off)282 if !list.contains(region) { list.insert(region, at: 1) }283 return list284 }285286 private func choice(_ label: String, count: Int?, selected: Bool, mono: Bool = false, pick: @escaping () -> Void) -> some View {287 Button(action: pick) {288 HStack {289 Text(verbatim: label).font(mono ? .data(.subheadline) : .body).foregroundStyle(Theme.ink)290 Spacer()291 if let count, count > 0 { Text(verbatim: Format.count(count)).font(.data(.footnote)).foregroundStyle(Theme.muted) }292 Image(systemName: "checkmark").fontWeight(.semibold).foregroundStyle(Theme.accent).opacity(selected ? 1 : 0)293 }294 .contentShape(Rectangle())295 }296 .buttonStyle(.plain)297 .accessibilityAddTraits(selected ? .isSelected : [])298 }299}300