Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/CommandCenter/CommandCenterView.swift4// Description: AI Command Center — a sheet with the search field first: open a conversation, switch model, search,5// create a project, toggle web search or a tool, start an Arena, open a panel or a space. Every command6// acts on the real stores; the hardware keyboard drives it (arrows, Return, Escape).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import SwiftUI1314struct CommandCenterView: View {15 /// Called when a conversation is shown (the compact layout then displays the detail column).16 let onOpen: () -> Void1718 @Environment(AppEnvironment.self) private var env19 @Environment(\.dismiss) private var dismiss20 @Environment(\.accessibilityReduceMotion) private var reduceMotion21 @State private var query = ""22 @State private var index = CommandCenterIndex(CommandCenterInput())23 @State private var groups: [CommandCenterIndex.Group] = []24 @State private var selection: String?25 @State private var appeared = false26 @State private var showNewProject = false27 @State private var projectName = ""28 @State private var notice: String?29 @FocusState private var focused: Bool3031 private var flat: [CommandItem] { groups.flatMap(\.items) }3233 var body: some View {34 VStack(spacing: 0) {35 field36 Divider().overlay(Color.hairline)37 ScrollViewReader { proxy in38 ScrollView {39 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: []) {40 let order = Dictionary(flat.enumerated().map { ($0.element.id, $0.offset) }, uniquingKeysWith: { a, _ in a })41 ForEach(groups) { group in42 Text(group.section.title).font(.spMicro).tracking(0.4).textCase(.uppercase).foregroundStyle(Color.muted)43 .padding(.horizontal, 20).padding(.top, 16).padding(.bottom, 6)44 .accessibilityAddTraits(.isHeader)45 ForEach(group.items) { item in46 let position = order[item.id] ?? 047 rowView(item)48 .id(item.id)49 // results stagger in once, when the sheet opens (24 ms per item, 8 items at most)50 .opacity(appeared || reduceMotion ? 1 : 0).offset(y: appeared || reduceMotion ? 0 : 8)51 .animation(reduceMotion ? nil : Motion.snappy.delay(Motion.stagger(position)), value: appeared)52 }53 }54 if groups.isEmpty {55 ContentUnavailableView.search(text: query).padding(.top, 40)56 }57 }58 .padding(.bottom, 24)59 }60 .scrollDismissesKeyboard(.interactively)61 .onChange(of: selection) { _, id in if let id { withAnimation(Motion.fade) { proxy.scrollTo(id, anchor: .center) } } }62 }63 }64 .background(Color.appBackground)65 .overlay(alignment: .bottom) {66 if let notice { Text(notice).font(.footnote).foregroundStyle(Color.textPrimary).padding(.horizontal, 14).padding(.vertical, 10).floatSurface(cornerRadius: 14).padding(.bottom, 14).transition(.opacity.combined(with: .offset(y: 8))) }67 }68 .animation(Motion.snappy(reduceMotion), value: notice)69 .presentationDragIndicator(.visible)70 .onAppear { rebuild(); focused = true; appeared = true }71 .onChange(of: query) { refilter() }72 .onChange(of: env.catalog.revision) { rebuild() }73 .onChange(of: env.conversations.active.count) { rebuild() }74 .alert("Nouveau projet", isPresented: $showNewProject) {75 TextField("Nom", text: $projectName)76 Button("Annuler", role: .cancel) { projectName = "" }77 Button("Créer") { createProject(projectName); projectName = "" }78 } message: { Text("Le projet est créé sur le serveur ; une nouvelle conversation s’y ouvre.") }79 }8081 // MARK: field8283 private var field: some View {84 HStack(spacing: 10) {85 Image(systemName: "command").font(.system(size: 15, weight: .semibold)).foregroundStyle(Color.accentColor)86 TextField("Conversation, modèle, action…", text: $query)87 .font(.body).focused($focused)88 .autocorrectionDisabled().textInputAutocapitalization(.never)89 .submitLabel(.go)90 .onSubmit { if let item = selected ?? flat.first { run(item) } }91 .onKeyPress(.downArrow) { move(1); return .handled }92 .onKeyPress(.upArrow) { move(-1); return .handled }93 .onKeyPress(.escape) { dismiss(); return .handled }94 .accessibilityIdentifier("command.field")95 if !query.isEmpty {96 Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(Color.muted).frame(width: 36, height: 44).contentShape(.rect) }97 .buttonStyle(.plain).accessibilityLabel(String(localized: "Effacer"))98 }99 Button { dismiss() } label: { Text("Fermer").font(.subheadline).frame(minHeight: 44).contentShape(.rect) }100 .accessibilityIdentifier("command.close")101 }102 .padding(.leading, 20).padding(.trailing, 14).padding(.top, 14).padding(.bottom, 4)103 }104105 private var selected: CommandItem? { selection.flatMap { id in flat.first { $0.id == id } } }106107 /// Arrow keys of a hardware keyboard move the selection through every section.108 private func move(_ delta: Int) {109 let list = flat110 guard !list.isEmpty else { return }111 let current = selection.flatMap { id in list.firstIndex { $0.id == id } }112 let next = current.map { min(max($0 + delta, 0), list.count - 1) } ?? (delta > 0 ? 0 : list.count - 1)113 selection = list[next].id114 }115116 // MARK: rows117118 private func rowView(_ item: CommandItem) -> some View {119 let isSelected = selection == item.id120 return Button { run(item) } label: {121 HStack(spacing: 12) {122 Group {123 if item.section == .models, item.creatorName != nil { ModelMark(logo: item.logo, name: item.creatorName ?? "?", size: 20, color: true) }124 else { Image(systemName: item.symbol).font(.system(size: 14, weight: .medium)).foregroundStyle(item.section == .actions ? Color.accentColor : Color.textSecondary) }125 }126 .frame(width: 30, height: 30)127 .background(item.section == .models && item.creatorName != nil ? Color.clear : Color.surface2, in: .rect(cornerRadius: 8, style: .continuous))128 VStack(alignment: .leading, spacing: 1) {129 HStack(spacing: 6) {130 Text(item.title).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(1)131 RouteBadge(route: item.route)132 }133 if let s = item.subtitle, !s.isEmpty { Text(s).font(.caption).foregroundStyle(Color.muted).lineLimit(1) }134 }135 Spacer(minLength: 4)136 if let on = item.isOn {137 if case .selectModel = item.action { Image(systemName: "checkmark").font(.footnote.weight(.bold)).foregroundStyle(Color.accentColor) }138 else if case .theme = item.action { Image(systemName: "checkmark").font(.footnote.weight(.bold)).foregroundStyle(Color.accentColor) }139 else {140 Text(on ? String(localized: "activé") : String(localized: "désactivé")).font(.spMicro).foregroundStyle(on ? Color.accentColor : Color.muted)141 .padding(.horizontal, 7).padding(.vertical, 3).background(on ? Color.accentSoft : Color.surface2, in: .capsule)142 }143 }144 }145 .padding(.horizontal, 12).frame(minHeight: 48)146 .background(isSelected ? Color.accentSoft : Color.clear, in: .rect(cornerRadius: Radius.control, style: .continuous))147 .overlay(RoundedRectangle(cornerRadius: Radius.control, style: .continuous).strokeBorder(isSelected ? Color.accentColor.opacity(0.5) : .clear, lineWidth: 0.75))148 .contentShape(.rect)149 }150 .buttonStyle(PressScale(scale: 0.98))151 .padding(.horizontal, 8)152 .accessibilityElement(children: .combine)153 .accessibilityAddTraits(isSelected ? .isSelected : [])154 .accessibilityValue(item.isOn.map { $0 ? String(localized: "activé") : String(localized: "désactivé") } ?? "")155 .accessibilityIdentifier("command.item")156 }157158 // MARK: index159160 private func rebuild() {161 var input = CommandCenterInput()162 input.conversations = env.conversations.active163 input.models = env.catalog.selectable164 input.preferredModelIds = (env.catalog.dockModels + env.catalog.favorites + env.catalog.recents).map(\.id)165 input.currentModelId = env.preferences.routingMode == .manual && env.preferences.presetId == nil ? env.catalog.effectiveModelId(preferred: env.preferences.modelId) : nil166 input.projects = env.catalog.projects167 input.prompts = env.prompts.prompts168 input.tools = env.settings.tools169 input.webSearch = env.preferences.webSearch170 input.toolsEnabled = env.preferences.toolsEnabled171 input.disabledTools = env.preferences.disabledTools172 input.followUps = env.settings.followUpsEnabled173 input.theme = env.preferences.theme.rawValue174 input.currentConversationId = env.router.current?.conversationId175 input.hasOpenConversation = env.router.current?.conversationId != nil && !(env.router.current?.messages.isEmpty ?? true)176 index = CommandCenterIndex(input)177 refilter()178 }179180 private func refilter() {181 groups = index.results(for: query)182 // while typing, Return runs the first result: show it as selected183 selection = query.trimmingCharacters(in: .whitespaces).isEmpty ? nil : groups.first?.items.first?.id184 }185186 // MARK: execution187188 private func close() { env.router.sheet = nil; dismiss() }189190 /// Replaces this sheet by another one (the router presents one sheet at a time).191 private func present(_ sheet: AppRouter.Sheet) {192 dismiss()193 Task { @MainActor in try? await Task.sleep(for: .milliseconds(420)); env.router.sheet = sheet }194 }195196 private func flash(_ text: String) {197 notice = text198 Task { try? await Task.sleep(for: .seconds(1.8)); if notice == text { notice = nil } }199 }200201 private func run(_ item: CommandItem) {202 env.haptics.selection()203 switch item.action {204 case .newConversation: env.startNewConversation(); onOpen(); close()205 case .searchMessages: present(.search)206 case .openConversation(let id): env.open(id); onOpen(); close()207 case .selectModel(let id):208 withAnimation(Motion.smooth(reduceMotion)) { env.select(model: id) }209 close()210 case .routing(let mode):211 if let m = RoutingMode(rawValue: mode) { env.preferences.routingMode = m; env.preferences.presetId = nil }212 close()213 case .toggleWebSearch:214 env.preferences.webSearch.toggle()215 flash(env.preferences.webSearch ? String(localized: "Recherche web activée pour les prochains messages.") : String(localized: "Recherche web désactivée."))216 rebuild()217 case .toggleTools:218 env.preferences.toolsEnabled.toggle()219 flash(env.preferences.toolsEnabled ? String(localized: "Outils activés.") : String(localized: "Outils désactivés."))220 rebuild()221 case .toggleTool(let name):222 if env.preferences.disabledTools.contains(name) { env.preferences.disabledTools.remove(name) } else { env.preferences.disabledTools.insert(name) }223 rebuild()224 case .arena:225 let current = env.router.current226 env.router.arenaSeed = ArenaSeed(prompt: current?.composerText ?? "", conversationId: nil, projectId: current?.projectId ?? current?.conversation?.projectId)227 present(.arena)228 case .space(let name):229 let sheets: [String: AppRouter.Sheet] = ["explorer": .explorer, "constellation": .constellation, "prompts": .prompts, "projects": .projects, "research": .research, "images": .images, "settings": .settings]230 if let s = sheets[name] { present(s) }231 case .panel(let name):232 env.router.pendingPanel = name; onOpen(); close()233 case .newProject:234 let typed = query.trimmingCharacters(in: .whitespacesAndNewlines)235 // « nouveau projet Thèse » is not a name; the name is asked for explicitly236 projectName = CommandCenterIndex.fold(typed).hasPrefix("nouveau") || CommandCenterIndex.fold(typed).hasPrefix("projet") || CommandCenterIndex.fold(typed).hasPrefix("new") ? "" : typed237 showNewProject = true238 case .newConversationInProject(let id): env.startNewConversation(projectId: id); onOpen(); close()239 case .insertPrompt(let id):240 guard let p = env.prompts.prompts.first(where: { $0.id == id }) else { return }241 env.prompts.markUsed(p)242 env.router.pendingComposerText = p.body243 env.router.focusComposerToken += 1244 onOpen(); close()245 case .theme(let raw):246 if let t = AppTheme(rawValue: raw) { env.preferences.theme = t }247 rebuild()248 case .toggleFollowUps:249 let target = !env.settings.followUpsEnabled250 Task {251 if let e = await env.settings.setFollowUps(target) { flash(e) }252 else { flash(target ? String(localized: "Suggestions de suite activées.") : String(localized: "Suggestions de suite désactivées.")) }253 rebuild()254 }255 }256 }257258 private func createProject(_ raw: String) {259 let name = String(raw.trimmingCharacters(in: .whitespacesAndNewlines).prefix(120))260 guard !name.isEmpty else { return }261 Task {262 if let p = await env.catalog.createProject(name: name) { env.haptics.success(); env.startNewConversation(projectId: p.id); onOpen(); close() }263 else { env.haptics.error(); flash(String(localized: "Le projet n’a pas pu être créé.")) }264 }265 }266}267