Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/ModelsScreen.swift3// Description: Model Explorer: instant search and filters over the whole catalogue (direct + OpenRouter), dense sortable rows with favourite / dock / compare, compare tray, registry refresh; opens the Live Model Intelligence detail.4import SwiftUI5import SPChatCore67struct ModelsScreen: View {8 @Bindable var window: WindowModel9 @Environment(AppEnvironment.self) private var env10 @State private var model: ExplorerModel11 @State private var detail: DetailTarget?12 @State private var showCompare = false13 @FocusState private var searchFocused: Bool1415 struct DetailTarget: Identifiable { let id: String }1617 /// `model` is only passed by tests and previews (a screen normally owns a fresh Explorer state).18 init(window: WindowModel, model: ExplorerModel = ExplorerModel()) { self.window = window; _model = State(initialValue: model) }1920 var body: some View {21 VStack(spacing: 0) {22 ExplorerHeader(model: model, searchFocused: $searchFocused, refresh: refreshRegistry)23 Rectangle().fill(DS.C.border).frame(height: 1)24 content25 }26 .background(DS.C.bg)27 .overlay(alignment: .bottom) {28 if !model.compare.isEmpty {29 CompareTray(model: model, open: { showCompare = true }, arena: openArena)30 .padding(.bottom, 16).transition(.move(edge: .bottom).combined(with: .opacity))31 }32 }33 .motion(DS.Motion.smooth, value: model.compare.isEmpty)34 .onChange(of: env.catalog.models, initial: true) {35 model.setIndex(env.catalog.fullIndex)36 model.pruneCompare { env.catalog.model($0) != nil }37 }38 .onChange(of: window.explorerModelId, initial: true) { openRequestedDetail() }39 .task { await load() }40 .sheet(item: $detail) { target in41 ModelDetailView(modelId: target.id, window: window, explorer: model, close: { detail = nil })42 }43 .sheet(isPresented: $showCompare) {44 ModelCompareView(models: model.compare.compactMap { env.catalog.model($0) }, defaultModelId: env.catalog.models.defaultModel, categoryRules: model.categoryRules,45 close: { showCompare = false }, arena: { showCompare = false; openArena() })46 }47 }4849 // MARK: Content5051 @ViewBuilder private var content: some View {52 if env.catalog.models.models.isEmpty {53 if env.catalog.loaded {54 EmptyStateView(systemImage: "cpu", title: "Catalogue vide", message: "Actualise le registre pour interroger les fournisseurs.").frame(maxWidth: .infinity, maxHeight: .infinity)55 } else {56 ProgressView("Chargement du catalogue…").frame(maxWidth: .infinity, maxHeight: .infinity)57 }58 } else if model.results.isEmpty {59 VStack(spacing: 12) {60 EmptyStateView(systemImage: "magnifyingglass", title: "Aucun modèle ne correspond",61 message: model.query.includeNonChat ? "Aucune ligne du catalogue ne répond à cette recherche et à ces filtres." : "Active « Tous les types » pour chercher aussi parmi les modèles d'image, de voix, d'embedding et les modèles masqués.")62 if model.query.hasFilters || !model.query.text.isEmpty { Button("Effacer la recherche et les filtres") { model.clearAll() } }63 }64 .frame(maxWidth: .infinity, maxHeight: .infinity)65 } else {66 VStack(spacing: 0) {67 ExplorerColumns()68 Rectangle().fill(DS.C.border).frame(height: 1)69 ScrollView {70 LazyVStack(spacing: 0) {71 ForEach(model.results) { m in72 ExplorerRow(model: m, isDefault: env.catalog.models.defaultModel == m.id, inDock: env.catalog.models.dock.contains(m.id), dockFull: env.catalog.models.dock.count >= 8,73 compared: model.isCompared(m.id), compareFull: model.compareIsFull,74 open: { detail = DetailTarget(id: m.id) }, favorite: { toggleFavorite(m) }, dock: { toggleDock(m) }, compare: { toggleCompare(m) },75 hide: { toggleHidden(m) }, makeDefault: { makeDefault(m) }, start: { start(m) })76 .equatable()77 }78 Text("Prix en $ US par million de jetons, tels que publiés (liste vérifiée pour les modèles directs, catalogue OpenRouter pour les autres). Seuls les modèles de chat disponibles peuvent être choisis dans une conversation.")79 .font(DS.F.caption).foregroundStyle(DS.C.muted).frame(maxWidth: .infinity, alignment: .leading)80 .padding(.horizontal, 24).padding(.top, 14).padding(.bottom, model.compare.isEmpty ? 20 : 84)81 }82 }83 .accessibilityIdentifier("models-list")84 }85 }86 }8788 // MARK: Data and actions8990 private func load() async {91 if env.catalog.models.models.isEmpty { await env.catalog.reloadModels() }92 if model.categoryRules.isEmpty, let overview = try? await env.api.providers() { model.categoryRules = overview.categoryRules }93 }9495 private func openRequestedDetail() {96 guard let id = window.explorerModelId else { return }97 window.explorerModelId = nil98 detail = DetailTarget(id: id)99 }100101 private func refreshRegistry() {102 Task {103 do { try await env.catalog.refreshCatalog(); env.toasts.show("Registre actualisé") } catch { env.toasts.error(error) }104 }105 }106107 private func toggleFavorite(_ m: AIModel) {108 Task { do { try await env.catalog.setFavorite(m.id, !m.favorite); env.toasts.show(m.favorite ? "Retiré des favoris" : "Ajouté aux favoris") } catch { env.toasts.error(error) } }109 }110 private func toggleDock(_ m: AIModel) {111 let was = env.catalog.models.dock.contains(m.id)112 Task { do { try await env.catalog.toggleDock(m.id); env.toasts.show(was ? "Retiré du dock" : "Ajouté au dock") } catch { env.toasts.error(error) } }113 }114 private func toggleHidden(_ m: AIModel) {115 Task { do { try await env.catalog.setHidden(m.id, !m.hidden); env.toasts.show(m.hidden ? "Modèle réaffiché dans le sélecteur" : "Modèle masqué du sélecteur") } catch { env.toasts.error(error) } }116 }117 private func makeDefault(_ m: AIModel) {118 guard m.canBeDefault else { return }119 Task { do { try await env.catalog.setDefault(m.id); env.toasts.show("\(m.displayName) est le modèle par défaut") } catch { env.toasts.error(error) } }120 }121 private func toggleCompare(_ m: AIModel) {122 if !model.toggleCompare(m.id) { env.toasts.show("La comparaison est limitée à \(ExplorerModel.maxCompare) modèles.", isError: true) }123 }124 private func start(_ m: AIModel) { window.startConversation(withModel: m.id, env: env) }125 private func openArena() {126 guard model.canCompare else { return }127 window.arenaModelIds = model.compare128 window.destination = .library(.compare)129 }130}131132// MARK: - Header (title, search, filters)133134private struct ExplorerHeader: View {135 @Bindable var model: ExplorerModel136 var searchFocused: FocusState<Bool>.Binding137 let refresh: () -> Void138 @Environment(AppEnvironment.self) private var env139140 var body: some View {141 VStack(alignment: .leading, spacing: 14) {142 HStack(alignment: .firstTextBaseline, spacing: 12) {143 VStack(alignment: .leading, spacing: 4) {144 Text("Explorateur de modèles").font(DS.F.display).tracking(-0.5).foregroundStyle(DS.C.text)145 Text(summary).font(DS.F.uiRegular).foregroundStyle(DS.C.muted).lineLimit(1)146 }147 Spacer(minLength: 12)148 if env.catalog.isRefreshingCatalog {149 HStack(spacing: 6) { ProgressView().controlSize(.small); Text("Actualisation… jusqu'à deux minutes").font(DS.F.caption).foregroundStyle(DS.C.muted) }150 .accessibilityElement(children: .combine)151 }152 Button(action: refresh) { Label("Actualiser le registre", systemImage: "arrow.triangle.2.circlepath") }153 .disabled(env.catalog.isRefreshingCatalog)154 .help("Le serveur relit la liste de chaque fournisseur et le catalogue OpenRouter (jusqu'à 2 minutes).")155 }156 HStack(spacing: 10) {157 searchField158 Toggle("Tous les types", isOn: $model.query.includeNonChat).toggleStyle(.switch).controlSize(.small).font(DS.F.caption).foregroundStyle(DS.C.text2)159 .help("Affiche aussi les modèles qui ne servent pas à converser (image, synthèse vocale, transcription, embedding…), ainsi que les modèles masqués ou indisponibles.")160 sortMenu161 }162 filters163 }164 .padding(.horizontal, 24).padding(.top, 20).padding(.bottom, 14)165 .background(DS.C.bgElev)166 }167168 private var summary: String {169 let all = env.catalog.models.models170 var parts = ["\(all.count) modèles", "\(all.filter { $0.isVerified }.count) vérifiés par le banc"]171 let catalog = all.filter(\.isCatalogOnly).count172 if catalog > 0 { parts.append("\(catalog) au catalogue OpenRouter") }173 if let d = env.catalog.models.refreshedAt { parts.append("registre actualisé le \(ExplorerText.dateTime(d))") }174 return parts.joined(separator: " · ")175 }176177 private var searchField: some View {178 HStack(spacing: 8) {179 Image(systemName: "magnifyingglass").font(.system(size: 13, weight: .medium)).foregroundStyle(DS.C.muted)180 TextField("Rechercher un modèle, un fabricant, un identifiant…", text: $model.query.text).textFieldStyle(.plain).font(.system(size: 14)).focused(searchFocused)181 .accessibilityLabel("Rechercher dans le catalogue").accessibilityIdentifier("explorer-search")182 if !model.query.text.isEmpty { IconButton(systemImage: "xmark.circle.fill", label: "Effacer la recherche") { model.query.text = "" } }183 }184 .padding(.horizontal, 12).frame(height: 34)185 .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))186 .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(searchFocused.wrappedValue ? DS.C.accent : DS.C.border, lineWidth: searchFocused.wrappedValue ? 1.5 : 1))187 .motion(DS.Motion.fade, value: searchFocused.wrappedValue)188 }189190 private var sortMenu: some View {191 Menu {192 Picker("Tri", selection: $model.query.sort) { ForEach(ModelSort.allCases, id: \.self) { Text($0.label).tag($0) } }.pickerStyle(.inline).labelsHidden()193 } label: {194 Label("Tri : \(model.query.sort.label)", systemImage: "arrow.up.arrow.down")195 }196 .menuStyle(.borderlessButton).fixedSize().font(DS.F.caption).accessibilityLabel("Trier les modèles")197 }198199 /// One line when the window is wide enough, else the chips (scrollable) above the count.200 private var filters: some View {201 ViewThatFits(in: .horizontal) {202 HStack(spacing: 6) { filterChips; Spacer(minLength: 8); filterStatus }203 VStack(alignment: .leading, spacing: 8) {204 ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 6) { filterChips } }205 HStack(spacing: 6) { filterStatus; Spacer(minLength: 0) }206 }207 }208 .motion(DS.Motion.snappy, value: model.query.hasFilters)209 }210211 @ViewBuilder private var filterChips: some View {212 Group {213 FilterChip(title: "Fabricant", count: model.query.makers.count) { MakerFilterList(model: model) }214 FilterChip(title: "Route", count: model.query.routes.count) {215 OptionList {216 OptionRow(title: "Direct", subtitle: "OpenAI, Anthropic, xAI — vérifiés par le banc", selected: model.query.routes.contains("direct")) { model.toggle(route: "direct") }217 OptionRow(title: "Local (MacLustr)", subtitle: "MacLustr AI, ton service d'inférence — 0 $", selected: model.query.routes.contains("local")) { model.toggle(route: "local") }218 OptionRow(title: "OpenRouter", subtitle: "Catalogue OpenRouter", selected: model.query.routes.contains("openrouter")) { model.toggle(route: "openrouter") }219 }220 }221 FilterChip(title: "Capacités", count: model.query.capabilities.count) {222 OptionList {223 ForEach(ModelFacet.capabilities, id: \.self) { c in224 OptionRow(title: ModelFacet.capabilityLabel(c), systemImage: ModelFacet.capabilitySymbol(c), selected: model.query.capabilities.contains(c)) { model.toggle(capability: c) }225 }226 }227 }228 FilterChip(title: "Catégories", count: model.query.categories.count) {229 OptionList(width: 380) {230 ForEach(ModelFacet.categories.filter { $0 != "free" && $0 != "open-weight" }, id: \.self) { c in231 OptionRow(title: ModelFacet.label(c), subtitle: model.categoryRules[c], systemImage: ModelFacet.symbol(c), selected: model.query.categories.contains(c)) { model.toggle(category: c) }232 .help(model.categoryRules[c] ?? ModelFacet.label(c))233 }234 }235 }236 FilterChip(title: model.query.maxInputPrice.map { "Entrée ≤ \(ExplorerText.price($0)) / M" } ?? "Prix max", count: model.query.maxInputPrice == nil ? 0 : 1, showsCount: false) {237 OptionList {238 OptionRow(title: "Sans plafond", selected: model.query.maxInputPrice == nil, radio: true) { model.query.maxInputPrice = nil }239 ForEach(ExplorerText.priceCeilings, id: \.self) { p in240 OptionRow(title: "Entrée ≤ \(ExplorerText.price(p)) par M", selected: model.query.maxInputPrice == p, radio: true) { model.query.maxInputPrice = p }241 }242 }243 }244 FilterChip(title: model.query.minContext.map { "Contexte ≥ \(Format.tokens($0))" } ?? "Contexte min", count: model.query.minContext == nil ? 0 : 1, showsCount: false) {245 OptionList {246 OptionRow(title: "Sans minimum", selected: model.query.minContext == nil, radio: true) { model.query.minContext = nil }247 ForEach(ExplorerText.contextFloors, id: \.self) { n in248 OptionRow(title: "Au moins \(Format.tokens(n)) jetons", selected: model.query.minContext == n, radio: true) { model.query.minContext = n }249 }250 }251 }252 Rectangle().fill(DS.C.border).frame(width: 1, height: 16).padding(.horizontal, 2)253 Button { model.query.freeOnly.toggle() } label: { Label("Gratuit", systemImage: "gift") }254 .buttonStyle(ChipStyle(selected: model.query.freeOnly)).help(model.categoryRules["free"] ?? "Modèles gratuits")255 Button { model.query.openWeightOnly.toggle() } label: { Label("Poids ouverts", systemImage: "lock.open") }256 .buttonStyle(ChipStyle(selected: model.query.openWeightOnly)).help(model.categoryRules["open-weight"] ?? "Modèles à poids ouverts")257 Button { model.query.favoritesOnly.toggle() } label: { Label("Favoris", systemImage: model.query.favoritesOnly ? "star.fill" : "star") }258 .buttonStyle(ChipStyle(selected: model.query.favoritesOnly)).help("Seulement mes favoris")259 }260 .fixedSize()261 }262263 @ViewBuilder private var filterStatus: some View {264 Group {265 if model.query.hasFilters {266 Button("Effacer les filtres") { model.clearFilters() }.buttonStyle(.plain).font(DS.F.caption).foregroundStyle(DS.C.accent)267 .accessibilityIdentifier("explorer-clear-filters")268 }269 Text(resultCount).font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted).contentTransition(.numericText()).lineLimit(1).fixedSize()270 .accessibilityIdentifier("explorer-count")271 }272 .fixedSize()273 }274275 private var resultCount: String {276 let n = model.results.count, total = model.universeCount277 if n == total { return n == 1 ? "1 modèle" : "\(n) modèles" }278 return "\(n) sur \(total)"279 }280}281282// MARK: - Filter chips and their popovers283284/// A filter chip that opens a popover; shows the number of active choices.285private struct FilterChip<Content: View>: View {286 let title: String287 let count: Int288 var showsCount = true289 @ViewBuilder let content: () -> Content290 @State private var open = false291292 var body: some View {293 Button { open.toggle() } label: {294 HStack(spacing: 4) {295 Text(title)296 if showsCount, count > 0 { Text("\(count)").font(.system(size: 10, weight: .bold).monospacedDigit()).padding(.horizontal, 4).background(DS.C.accent.opacity(0.18), in: Capsule()) }297 Image(systemName: "chevron.down").font(.system(size: 8, weight: .bold)).opacity(0.7)298 }299 }300 .buttonStyle(ChipStyle(selected: count > 0))301 .accessibilityLabel(count > 0 ? "\(title), \(count) actif\(count > 1 ? "s" : "")" : title)302 .popover(isPresented: $open, arrowEdge: .bottom) { content() }303 }304}305306private struct OptionList<Content: View>: View {307 var width: CGFloat = 280308 @ViewBuilder let content: () -> Content309 var body: some View { VStack(alignment: .leading, spacing: 1) { content() }.padding(6).frame(width: width) }310}311312private struct OptionRow: View {313 let title: String314 var subtitle: String?315 var systemImage: String?316 let selected: Bool317 var radio = false318 let action: () -> Void319 @State private var hovering = false320321 var body: some View {322 Button(action: action) {323 HStack(alignment: .firstTextBaseline, spacing: 8) {324 Image(systemName: selected ? (radio ? "largecircle.fill.circle" : "checkmark.square.fill") : (radio ? "circle" : "square"))325 .font(.system(size: 13)).foregroundStyle(selected ? DS.C.accent : DS.C.muted).frame(width: 16)326 if let systemImage { Image(systemName: systemImage).font(.system(size: 11)).foregroundStyle(DS.C.text2).frame(width: 16) }327 VStack(alignment: .leading, spacing: 1) {328 Text(title).font(DS.F.ui).foregroundStyle(DS.C.text)329 if let subtitle { Text(subtitle).font(.system(size: 11)).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true) }330 }331 Spacer(minLength: 0)332 }333 .padding(.horizontal, 8).padding(.vertical, 5).frame(maxWidth: .infinity, alignment: .leading)334 .background(hovering ? DS.C.surface2 : .clear, in: RoundedRectangle(cornerRadius: DS.R.chip, style: .continuous))335 .contentShape(Rectangle())336 }337 .buttonStyle(.plain).onHover { hovering = $0 }338 .accessibilityAddTraits(selected ? .isSelected : [])339 }340}341342/// Maker filter: logo, name and number of models of every maker of the catalogue, with a quick search.343private struct MakerFilterList: View {344 @Bindable var model: ExplorerModel345 @State private var filter = ""346347 private var makers: [ExplorerModel.MakerFacet] {348 let q = filter.trimmingCharacters(in: .whitespaces)349 return q.isEmpty ? model.makers : model.makers.filter { $0.name.localizedCaseInsensitiveContains(q) || $0.slug.localizedCaseInsensitiveContains(q) }350 }351352 var body: some View {353 VStack(spacing: 0) {354 HStack(spacing: 6) {355 Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundStyle(DS.C.muted)356 TextField("Fabricant", text: $filter).textFieldStyle(.plain).font(DS.F.uiRegular).accessibilityLabel("Filtrer les fabricants")357 if !model.query.makers.isEmpty { Button("Aucun") { model.query.makers = [] }.buttonStyle(.plain).font(DS.F.caption).foregroundStyle(DS.C.accent) }358 }359 .padding(.horizontal, 12).padding(.vertical, 9)360 Rectangle().fill(DS.C.border).frame(height: 1)361 ScrollView {362 LazyVStack(spacing: 1) {363 ForEach(makers) { maker in MakerRow(maker: maker, selected: model.query.makers.contains(maker.slug)) { model.toggle(maker: maker.slug) } }364 if makers.isEmpty { Text("Aucun fabricant").font(DS.F.caption).foregroundStyle(DS.C.muted).padding(.vertical, 14) }365 }366 .padding(6)367 }368 .frame(height: min(CGFloat(max(makers.count, 2)) * 31 + 12, 340))369 }370 .frame(width: 270)371 }372}373374private struct MakerRow: View {375 let maker: ExplorerModel.MakerFacet376 let selected: Bool377 let action: () -> Void378 @State private var hovering = false379 var body: some View {380 Button(action: action) {381 HStack(spacing: 8) {382 Image(systemName: selected ? "checkmark.square.fill" : "square").font(.system(size: 13)).foregroundStyle(selected ? DS.C.accent : DS.C.muted).frame(width: 16)383 ModelMark(logo: maker.logo ?? maker.slug, name: maker.name, size: 16)384 Text(maker.name).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(1)385 Spacer(minLength: 6)386 Text("\(maker.count)").font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted)387 }388 .padding(.horizontal, 8).frame(height: 30)389 .background(hovering ? DS.C.surface2 : .clear, in: RoundedRectangle(cornerRadius: DS.R.chip, style: .continuous))390 .contentShape(Rectangle())391 }392 .buttonStyle(.plain).onHover { hovering = $0 }393 .accessibilityLabel("\(maker.name), \(maker.count) modèle\(maker.count > 1 ? "s" : "")").accessibilityAddTraits(selected ? .isSelected : [])394 }395}396397// MARK: - Rows398399enum ExplorerLayout {400 static let capabilities: CGFloat = 92401 static let context: CGFloat = 62402 static let price: CGFloat = 74403 static let actions: CGFloat = 78404 static let horizontal: CGFloat = 24405}406407/// Column titles aligned with the rows.408private struct ExplorerColumns: View {409 var body: some View {410 HStack(spacing: 12) {411 Text("Modèle").frame(maxWidth: .infinity, alignment: .leading)412 Text("Capacités").frame(width: ExplorerLayout.capabilities, alignment: .leading)413 Text("Contexte").frame(width: ExplorerLayout.context, alignment: .trailing)414 Text("Entrée / M").frame(width: ExplorerLayout.price, alignment: .trailing)415 Text("Sortie / M").frame(width: ExplorerLayout.price, alignment: .trailing)416 Color.clear.frame(width: ExplorerLayout.actions, height: 1)417 }418 .font(DS.F.micro).tracking(0.4).textCase(.uppercase).foregroundStyle(DS.C.muted)419 .padding(.horizontal, ExplorerLayout.horizontal).frame(height: 28).background(DS.C.bg)420 .accessibilityHidden(true)421 }422}423424/// One model of the catalogue: 40 pt, hairline below, no box. `Equatable` on its data so that scrolling and typing in425/// the search field only re-render the rows whose model changed.426struct ExplorerRow: View, Equatable {427 let model: AIModel428 let isDefault: Bool429 let inDock: Bool430 let dockFull: Bool431 let compared: Bool432 let compareFull: Bool433 let open: () -> Void434 let favorite: () -> Void435 let dock: () -> Void436 let compare: () -> Void437 let hide: () -> Void438 let makeDefault: () -> Void439 let start: () -> Void440 @State private var hovering = false441442 nonisolated static func == (a: ExplorerRow, b: ExplorerRow) -> Bool {443 a.model == b.model && a.isDefault == b.isDefault && a.inDock == b.inDock && a.dockFull == b.dockFull && a.compared == b.compared && a.compareFull == b.compareFull444 }445446 var body: some View {447 HStack(spacing: 12) {448 Button(action: open) {449 HStack(spacing: 12) {450 identity.frame(maxWidth: .infinity, alignment: .leading)451 CapabilityGlyphs(model: model).frame(width: ExplorerLayout.capabilities, alignment: .leading)452 Text(model.contextWindow.map { Format.tokens($0) } ?? "—").frame(width: ExplorerLayout.context, alignment: .trailing)453 Text(model.hasVariablePrice ? "variable" : model.isFree ? "gratuit" : ExplorerText.price(model.inputPrice)).frame(width: ExplorerLayout.price, alignment: .trailing)454 Text(model.hasVariablePrice ? "variable" : model.isFree ? "gratuit" : ExplorerText.price(model.outputPrice)).frame(width: ExplorerLayout.price, alignment: .trailing)455 }456 .font(.system(size: 12).monospacedDigit()).foregroundStyle(DS.C.text2)457 .frame(maxHeight: .infinity).contentShape(Rectangle())458 }459 .buttonStyle(.plain)460 .accessibilityLabel(accessibilityText).accessibilityHint("Ouvre la fiche du modèle")461 actions.frame(width: ExplorerLayout.actions, alignment: .trailing)462 }463 .padding(.horizontal, ExplorerLayout.horizontal).frame(height: 40)464 .background(compared ? DS.C.accentSoft : (hovering ? DS.C.surface2.opacity(0.6) : .clear))465 .overlay(alignment: .bottom) { Rectangle().fill(DS.C.border.opacity(0.7)).frame(height: 1).padding(.leading, ExplorerLayout.horizontal + 30) }466 .opacity(model.hidden || !model.available ? 0.55 : 1)467 .onHover { hovering = $0 }468 .contextMenu {469 Button("Ouvrir la fiche", action: open)470 if model.isSelectableForChat { Button("Démarrer une conversation avec ce modèle", action: start) }471 Divider()472 Button(model.favorite ? "Retirer des favoris" : "Mettre en favori", action: favorite)473 if model.isSelectableForChat { Button(inDock ? "Retirer du dock" : "Ajouter au dock", action: dock).disabled(!inDock && dockFull) }474 Button(compared ? "Retirer de la comparaison" : "Ajouter à la comparaison", action: compare).disabled(!compared && compareFull)475 Button(model.hidden ? "Réafficher dans le sélecteur" : "Masquer du sélecteur", action: hide)476 if model.canBeDefault { Button("Définir par défaut", action: makeDefault).disabled(isDefault) }477 Divider()478 Button("Copier l'identifiant") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(model.id, forType: .string) }479 }480 }481482 private var identity: some View {483 HStack(spacing: 10) {484 ModelMark(model, size: 18)485 Text(model.displayName).font(.system(size: 13, weight: .medium)).foregroundStyle(DS.C.text).lineLimit(1).truncationMode(.tail).layoutPriority(1)486 RouteBadge(route: model.route)487 if isDefault { Tag(text: "défaut", color: DS.C.accent) }488 if !["chat"].contains(model.kind) { Tag(text: ExplorerText.kind(model.kind).lowercased(), color: DS.C.text2) }489 if model.isCatalogOnly { CatalogNotice() }490 else if !model.isVerified { Text(ExplorerText.status(model).label.lowercased()).font(.system(size: 10.5, weight: .medium)).foregroundStyle(model.status == "unavailable" ? DS.C.danger : DS.C.muted).lineLimit(1) }491 if model.hidden { Image(systemName: "eye.slash").font(.system(size: 10.5)).foregroundStyle(DS.C.muted).help("Masqué du sélecteur").accessibilityLabel("Masqué du sélecteur") }492 Spacer(minLength: 0)493 }494 }495496 private var actions: some View {497 HStack(spacing: 2) {498 RowToggle(systemImage: compared ? "checkmark.rectangle.stack.fill" : "rectangle.stack.badge.plus", on: compared, visible: hovering || compared,499 label: compared ? "Retirer \(model.displayName) de la comparaison" : "Ajouter \(model.displayName) à la comparaison", action: compare)500 .disabled(!compared && compareFull)501 RowToggle(systemImage: inDock ? "dock.rectangle" : "dock.rectangle", on: inDock, visible: (hovering || inDock) && model.isSelectableForChat,502 label: inDock ? "Retirer \(model.displayName) du dock" : (dockFull ? "Le dock contient déjà 8 modèles" : "Ajouter \(model.displayName) au dock"), action: dock)503 .disabled((!inDock && dockFull) || !model.isSelectableForChat)504 RowToggle(systemImage: model.favorite ? "star.fill" : "star", on: model.favorite, visible: hovering || model.favorite,505 label: model.favorite ? "Retirer \(model.displayName) des favoris" : "Mettre \(model.displayName) en favori", action: favorite)506 }507 }508509 private var accessibilityText: String {510 var parts = [ModelIdentity(model).accessibilityText]511 if let c = model.contextWindow { parts.append("contexte \(Format.tokens(c))") }512 if model.isFree { parts.append("gratuit") } else if let i = model.inputPrice, let o = model.outputPrice, i >= 0, o >= 0 { parts.append("\(Format.price(i)) dollars en entrée, \(Format.price(o)) dollars en sortie par million de jetons") }513 if isDefault { parts.append("modèle par défaut") }514 return parts.joined(separator: ", ")515 }516}517518/// Icon toggle of a row: iris when on, discreet otherwise, hidden (but still reachable by VoiceOver) until the row is hovered.519private struct RowToggle: View {520 let systemImage: String521 let on: Bool522 let visible: Bool523 let label: String524 let action: () -> Void525 var body: some View {526 Button(action: action) {527 Image(systemName: systemImage).font(.system(size: 12, weight: .medium)).foregroundStyle(on ? DS.C.accent : DS.C.muted).frame(width: 24, height: 24).contentShape(Rectangle())528 }529 .buttonStyle(.plain).opacity(visible ? 1 : 0).help(label).accessibilityLabel(label).accessibilityAddTraits(on ? .isSelected : [])530 }531}532533/// Micro label in a hairline capsule (« défaut », « image »…).534struct Tag: View {535 let text: String536 var color: Color = DS.C.text2537 var body: some View {538 Text(text).font(.system(size: 10, weight: .semibold)).foregroundStyle(color).lineLimit(1)539 .padding(.horizontal, 5).padding(.vertical, 1.5).overlay(Capsule().strokeBorder(color.opacity(0.35), lineWidth: 1)).fixedSize()540 }541}542543// MARK: - Compare tray544545/// Floating tray listing the models picked for comparison (2–4).546private struct CompareTray: View {547 @Bindable var model: ExplorerModel548 let open: () -> Void549 let arena: () -> Void550 @Environment(AppEnvironment.self) private var env551552 var body: some View {553 HStack(spacing: 10) {554 Text("Comparer").font(DS.F.micro).tracking(0.5).textCase(.uppercase).foregroundStyle(DS.C.muted)555 ForEach(model.compare, id: \.self) { id in556 HStack(spacing: 4) {557 ModelChip(identity: env.catalog.identity(for: id, short: true), markSize: 14, font: DS.F.caption)558 Button { model.toggleCompare(id) } label: { Image(systemName: "xmark").font(.system(size: 8, weight: .bold)).foregroundStyle(DS.C.muted).frame(width: 14, height: 14).contentShape(Rectangle()) }559 .buttonStyle(.plain).accessibilityLabel("Retirer \(env.catalog.identity(for: id).name) de la comparaison")560 }561 .padding(.leading, 8).padding(.trailing, 5).frame(height: 26)562 .background(DS.C.surface2, in: Capsule()).overlay(Capsule().strokeBorder(DS.C.border, lineWidth: 1))563 }564 if !model.canCompare { Text("Choisis au moins 2 modèles").font(DS.F.caption).foregroundStyle(DS.C.muted) }565 Rectangle().fill(DS.C.border).frame(width: 1, height: 18)566 Button("Tableau comparatif", action: open).buttonStyle(.borderedProminent).tint(DS.C.accent).controlSize(.small).disabled(!model.canCompare)567 .accessibilityIdentifier("explorer-compare")568 Button("Ouvrir dans l'Arena", action: arena).controlSize(.small).disabled(!model.canCompare)569 IconButton(systemImage: "xmark.circle", label: "Vider la comparaison") { model.clearCompare() }570 }571 .padding(.horizontal, 14).frame(height: 46)572 .floatSurface(radius: 23)573 .fixedSize()574 .motion(DS.Motion.snappy, value: model.compare)575 }576}577