Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Explorer/ExplorerView.swift4// Description: OpenRouter Model Explorer — search, filter chips, sort, favourites, recents and a compare tray over the5// unified catalogue. Every figure shown comes from the catalogue or the local bench, with its source.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI1213struct ExplorerView: View {14 /// True when pushed inside another navigation stack (the model sheet).15 var embedded = false1617 @Environment(AppEnvironment.self) private var env18 @Environment(\.dismiss) private var dismiss19 @Environment(\.horizontalSizeClass) private var sizeClass20 @Environment(\.accessibilityReduceMotion) private var reduceMotion21 @State private var query = ModelQuery()22 @State private var results: [AIModel] = []23 @State private var resultsKey = ""24 @State private var compare: [String] = []25 @State private var showFilters = false26 @State private var showCompare = false27 @State private var notice: String?2829 /// 2–3 models side by side on iPhone, up to 4 on iPad.30 private var compareLimit: Int { sizeClass == .regular ? 4 : 3 }3132 var body: some View {33 if embedded { content } else { NavigationStack { content.toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }.navigationDestination(for: AIModel.self) { ModelDetailView(model: $0) } } }34 }3536 private var content: some View {37 List {38 Section {39 chips.listRowInsets(EdgeInsets()).listRowBackground(Color.clear).listRowSeparator(.hidden)40 HStack {41 Text(results.count == 1 ? String(localized: "1 modèle") : String(localized: "\(results.count) modèles")).font(.spCaption).foregroundStyle(Color.muted).monospacedDigit().contentTransition(.numericText())42 Spacer()43 Menu {44 Picker("Trier", selection: $query.sort) { ForEach(ModelSort.allCases) { Text($0.label).tag($0) } }45 } label: { Label(query.sort.label, systemImage: "arrow.up.arrow.down").font(.spCaption).foregroundStyle(Color.textSecondary).frame(minHeight: 36).contentShape(.rect) }46 .accessibilityLabel(String(localized: "Trier : \(query.sort.label)"))47 .accessibilityIdentifier("explorer.sort")48 }49 .listRowBackground(Color.clear).listRowSeparator(.hidden)50 }51 Section {52 ForEach(results) { m in row(m) }53 }54 if results.isEmpty && !env.catalog.selectable.isEmpty {55 ContentUnavailableView { Label("Aucun modèle", systemImage: "line.3.horizontal.decrease.circle") } description: { Text("Aucun modèle du catalogue ne correspond à ces critères.") } actions: {56 Button("Effacer les filtres") { withAnimation(Motion.snappy(reduceMotion)) { query.clearFilters(); query.text = "" } }57 }58 .listRowSeparator(.hidden)59 }60 }61 .listStyle(.plain)62 .scrollContentBackground(.hidden)63 .background(Color.appBackground)64 .searchable(text: $query.text, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Nom, créateur ou identifiant"))65 .autocorrectionDisabled().textInputAutocapitalization(.never)66 .navigationTitle("Explorateur de modèles")67 .navigationBarTitleDisplayMode(.inline)68 .refreshable { await env.catalog.refreshModels() }69 .safeAreaInset(edge: .bottom) { if !compare.isEmpty { compareTray.transition(.move(edge: .bottom).combined(with: .opacity)) } }70 .animation(Motion.smooth(reduceMotion), value: compare)71 .onChange(of: query, initial: true) { rebuild() }72 .onChange(of: env.catalog.revision) { rebuild() }73 .sheet(isPresented: $showFilters) { ExplorerFilterSheet(query: $query, models: env.catalog.selectable).presentationDetents([.large]) }74 .sheet(isPresented: $showCompare) { ModelCompareView(models: compare.compactMap { env.catalog.model($0) }) }75 .overlay(alignment: .top) {76 if let notice { Text(notice).font(.footnote).padding(.horizontal, 14).padding(.vertical, 10).floatSurface(cornerRadius: 14).padding(.top, 8).transition(.opacity) }77 }78 }7980 private func rebuild() {81 let key = "\(query.hashValueKey)|\(env.catalog.revision)"82 guard key != resultsKey else { return }83 resultsKey = key84 results = query.apply(to: env.catalog.selectable)85 }8687 // MARK: filter chips8889 private var chips: some View {90 ScrollView(.horizontal, showsIndicators: false) {91 HStack(spacing: 8) {92 Button { showFilters = true } label: { ChipLabel(text: query.hasFilters ? String(localized: "Filtres · \(query.activeFilterCount)") : String(localized: "Filtres"), systemImage: "line.3.horizontal.decrease", selected: query.hasFilters) }93 .buttonStyle(PressScale()).accessibilityIdentifier("explorer.filters")94 toggleChip(String(localized: "Favoris"), "star", query.favoritesOnly) { query.favoritesOnly.toggle() }95 toggleChip(String(localized: "Récents"), "clock", query.sort == .recentlyUsed) { query.sort = query.sort == .recentlyUsed ? .recommended : .recentlyUsed }96 if !env.catalog.local.isEmpty { toggleChip(String(localized: "Local"), "desktopcomputer", query.route == "local") { query.route = query.route == "local" ? nil : "local" } }97 toggleChip("OpenRouter", nil, query.route == "openrouter") { query.route = query.route == "openrouter" ? nil : "openrouter" }98 toggleChip(String(localized: "Direct"), nil, query.route == "direct") { query.route = query.route == "direct" ? nil : "direct" }99 toggleChip(String(localized: "Gratuit"), nil, query.freeOnly) { query.freeOnly.toggle() }100 toggleChip(String(localized: "Poids ouverts"), nil, query.openWeightOnly) { query.openWeightOnly.toggle() }101 ForEach([ModelCapability.vision, .reasoning, .tools, .imageGeneration]) { c in102 toggleChip(c.label, c.symbol, query.capabilities.contains(c)) { if query.capabilities.contains(c) { query.capabilities.remove(c) } else { query.capabilities.insert(c) } }103 }104 toggleChip(String(localized: "≥ 400k"), nil, query.minContext == 400_000) { query.minContext = query.minContext == 400_000 ? nil : 400_000 }105 ForEach(query.makers.sorted(), id: \.self) { slug in106 Button { withAnimation(Motion.snappy(reduceMotion)) { _ = query.makers.remove(slug) } } label: { ChipLabel(text: AIModel.providerLabel(slug), systemImage: "xmark", selected: true) }.buttonStyle(PressScale())107 }108 }109 .padding(.horizontal, 16).padding(.vertical, 6)110 }111 }112113 private func toggleChip(_ title: String, _ symbol: String?, _ on: Bool, _ action: @escaping () -> Void) -> some View {114 Button { env.haptics.selection(); withAnimation(Motion.snappy(reduceMotion)) { action() } } label: { ChipLabel(text: title, systemImage: symbol, selected: on) }115 .buttonStyle(PressScale())116 .accessibilityAddTraits(on ? .isSelected : [])117 }118119 // MARK: rows120121 private func row(_ m: AIModel) -> some View {122 let picked = compare.contains(m.id)123 return NavigationLink(value: m) {124 HStack(spacing: 8) {125 ModelRowLabel(model: m, selected: false, isDefault: false, inDock: env.catalog.isInDock(m.id))126 if picked { Image(systemName: "checkmark.circle.fill").foregroundStyle(Color.accentColor).accessibilityLabel(String(localized: "dans la comparaison")) }127 }128 }129 .listRowBackground(picked ? Color.accentSoft : Color.clear)130 .swipeActions(edge: .leading, allowsFullSwipe: true) {131 Button { env.haptics.soften(); Task { await env.catalog.toggleFavorite(m) } } label: { Label(m.favorite ? "Retirer" : "Favori", systemImage: m.favorite ? "star.slash" : "star.fill") }.tint(.orange)132 }133 .swipeActions(edge: .trailing, allowsFullSwipe: true) {134 Button { toggleCompare(m) } label: { Label(picked ? "Retirer" : "Comparer", systemImage: "square.split.2x1") }.tint(.accentColor)135 }136 .contextMenu {137 Button { env.select(model: m.id); flash(String(localized: "\(m.displayName) sélectionné pour les prochains messages.")) } label: { Label("Utiliser ce modèle", systemImage: "checkmark.circle") }138 Button { toggleCompare(m) } label: { Label(picked ? "Retirer de la comparaison" : "Ajouter à la comparaison", systemImage: "square.split.2x1") }139 Button { Task { await env.catalog.toggleFavorite(m) } } label: { Label(m.favorite ? "Retirer des favoris" : "Ajouter aux favoris", systemImage: "star") }140 Button { UIPasteboard.general.string = m.id } label: { Label("Copier l’identifiant", systemImage: "doc.on.doc") }141 }142 .accessibilityIdentifier("explorer.row")143 }144145 private func toggleCompare(_ m: AIModel) {146 env.haptics.selection()147 if let i = compare.firstIndex(of: m.id) { compare.remove(at: i) }148 else if compare.count >= compareLimit { flash(String(localized: "\(compareLimit) modèles au plus dans une comparaison sur cet écran.")) }149 else { compare.append(m.id) }150 }151152 private func flash(_ text: String) {153 withAnimation(Motion.snappy(reduceMotion)) { notice = text }154 Task { try? await Task.sleep(for: .seconds(2.4)); if notice == text { withAnimation(Motion.fade) { notice = nil } } }155 }156157 // MARK: compare tray158159 private var compareTray: some View {160 HStack(spacing: 10) {161 HStack(spacing: -6) {162 ForEach(compare.compactMap { env.catalog.model($0) }) { m in163 ModelMark(m, size: 20, color: true).frame(width: 34, height: 34).background(Color.surface, in: .circle).overlay(Circle().strokeBorder(Color.hairline, lineWidth: 0.75))164 }165 }166 Text(compare.count < 2 ? String(localized: "Ajoute un 2ᵉ modèle") : String(localized: "\(compare.count) modèles")).font(.spCaption).foregroundStyle(Color.textSecondary)167 Spacer(minLength: 4)168 Button { withAnimation(Motion.snappy(reduceMotion)) { compare = [] } } label: { Image(systemName: "xmark").font(.system(size: 11, weight: .bold)).foregroundStyle(Color.muted).frame(width: 40, height: 44).contentShape(.rect) }169 .buttonStyle(.plain).accessibilityLabel(String(localized: "Vider la comparaison"))170 Button { showCompare = true } label: { Text("Comparer").font(.subheadline.weight(.semibold)).foregroundStyle(.white).padding(.horizontal, 16).frame(minHeight: 36).background(compare.count >= 2 ? Color.accentColor : Color.muted.opacity(0.5), in: .capsule) }171 .buttonStyle(PressScale()).disabled(compare.count < 2)172 .accessibilityIdentifier("explorer.compare")173 }174 .padding(.leading, 12).padding(.trailing, 8).padding(.vertical, 6)175 .floatSurface(cornerRadius: Radius.float)176 .padding(.horizontal, 12).padding(.bottom, 6)177 }178}179180extension ModelQuery {181 /// Cheap identity of a query for memoising derived lists.182 var hashValueKey: String { "\(text)|\(makers.sorted())|\(route ?? "")|\(capabilities.map(\.rawValue).sorted())|\(categories.sorted())|\(maxInputPrice ?? -1)|\(minContext ?? -1)|\(freeOnly)\(openWeightOnly)\(favoritesOnly)\(verifiedOnly)|\(sort.rawValue)" }183}184185/// Every filter of the Explorer in one sheet (maker, route, capability, categories, price, context, free, open-weight).186struct ExplorerFilterSheet: View {187 @Binding var query: ModelQuery188 let models: [AIModel]189 @Environment(AppEnvironment.self) private var env190 @Environment(\.dismiss) private var dismiss191 @State private var rules: [String: String] = [:]192 @State private var showAllMakers = false193194 var body: some View {195 let makers = ModelQuery.makers(in: models)196 let presentCategories = Set(models.flatMap(\.categories))197 NavigationStack {198 Form {199 Section("Route") {200 Picker("Route", selection: $query.route) { Text("Toutes").tag(String?.none); Text("Directe").tag(String?.some("direct")); Text("Locale").tag(String?.some("local")); Text("OpenRouter").tag(String?.some("openrouter")) }.pickerStyle(.segmented)201 Toggle("Vérifiés par le banc local seulement", isOn: $query.verifiedOnly)202 Toggle("Favoris seulement", isOn: $query.favoritesOnly)203 }204 Section("Créateur") {205 ForEach(showAllMakers ? makers : Array(makers.prefix(8)), id: \.slug) { m in206 Button { if query.makers.contains(m.slug) { query.makers.remove(m.slug) } else { query.makers.insert(m.slug) } } label: {207 HStack(spacing: 10) {208 ModelMark(logo: LogoRegistry.slug(for: m.slug), name: m.name, size: 20, color: true)209 Text(m.name).foregroundStyle(Color.textPrimary)210 Spacer()211 Text("\(m.count)").font(.footnote.monospacedDigit()).foregroundStyle(Color.muted)212 Image(systemName: query.makers.contains(m.slug) ? "checkmark.circle.fill" : "circle").foregroundStyle(query.makers.contains(m.slug) ? Color.accentColor : Color.muted)213 }214 .contentShape(.rect)215 }216 .buttonStyle(.plain)217 .accessibilityAddTraits(query.makers.contains(m.slug) ? .isSelected : [])218 }219 if makers.count > 8 { Button(showAllMakers ? String(localized: "Réduire") : String(localized: "Les \(makers.count) créateurs")) { showAllMakers.toggle() } }220 }221 Section("Capacités") {222 ForEach(ModelCapability.allCases) { c in223 Toggle(isOn: Binding(get: { query.capabilities.contains(c) }, set: { on in if on { query.capabilities.insert(c) } else { query.capabilities.remove(c) } })) { Label(c.label, systemImage: c.symbol) }224 }225 }226 Section {227 ForEach(ModelQuery.categoryOrder.filter(presentCategories.contains), id: \.self) { c in228 Toggle(isOn: Binding(get: { query.categories.contains(c) }, set: { on in if on { query.categories.insert(c) } else { query.categories.remove(c) } })) {229 VStack(alignment: .leading, spacing: 2) {230 Text(ModelQuery.categoryLabel(c))231 if let r = rules[c] { Text(r).font(.caption2).foregroundStyle(Color.muted) }232 }233 }234 }235 } header: { Text("Catégories") } footer: { Text("Les catégories sont dérivées de faits seulement ; la règle de chacune est celle que le serveur publie.") }236 Section("Prix et contexte") {237 Picker("Prix d’entrée maximal", selection: $query.maxInputPrice) {238 Text("Tous").tag(Double?.none)239 ForEach([0.0, 0.5, 1, 3, 10], id: \.self) { p in Text(p == 0 ? String(localized: "Gratuit") : "≤ \(Format.price(p)) $ / M").tag(Double?.some(p)) }240 }241 Picker("Contexte minimal", selection: $query.minContext) {242 Text("Tous").tag(Int?.none)243 ForEach([32_000, 128_000, 200_000, 400_000, 1_000_000], id: \.self) { n in Text("≥ \(Format.tokens(n))").tag(Int?.some(n)) }244 }245 Toggle("Gratuits", isOn: $query.freeOnly)246 Toggle("Poids ouverts", isOn: $query.openWeightOnly)247 }248 }249 .navigationTitle("Filtres").navigationBarTitleDisplayMode(.inline)250 .toolbar {251 ToolbarItem(placement: .cancellationAction) { Button("Effacer") { query.clearFilters() }.disabled(!query.hasFilters) }252 ToolbarItem(placement: .confirmationAction) { Button("Voir \(query.apply(to: models).count)") { dismiss() }.fontWeight(.semibold) }253 }254 .task { if rules.isEmpty, let r = try? await env.api.providers() { rules = r.categoryRules } }255 }256 }257}258