Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/CommandPalette.swift3// Description: The native command palette (⌘K) — fuzzy search over commands, folders and mailboxes of the window, with the web client's scoped4// prefixes (`>` commands, `#` folders, `@` mailboxes, `/` search the mail), shown as a level-2 glass panel over the window.5import SPMailCore6import SwiftUI78struct PaletteItem: Identifiable {9 enum Kind: String, Sendable { case command, folder, mailbox, search, label }10 let id: String11 let kind: Kind12 let title: String13 var subtitle: String?14 let icon: String15 var shortcut: String?16 var isEnabled = true17 let run: @MainActor () -> Void18}1920@MainActor21enum CommandPalette {22 /// Everything the palette can do in this window, in display order.23 static func items(for scene: MailScene) -> [PaletteItem] {24 let app = scene.app25 let target = scene.replyTarget(), has = scene.hasSelection26 func command(_ id: String, _ title: String, _ icon: String, _ shortcut: String? = nil, enabled: Bool = true, _ run: @escaping @MainActor () -> Void) -> PaletteItem {27 PaletteItem(id: "cmd." + id, kind: .command, title: title, icon: icon, shortcut: shortcut, isEnabled: enabled, run: run)28 }29 var out: [PaletteItem] = [30 command("new", L("Nouveau message"), "square.and.pencil", "⌘N") { Task { await scene.compose(.new) } },31 command("reply", L("Répondre"), "arrowshape.turn.up.left", "⌘R", enabled: target != nil) { if let e = target { Task { await scene.compose(.reply(e)) } } },32 command("replyAll", L("Répondre à tous"), "arrowshape.turn.up.left.2", "⇧⌘R", enabled: target != nil) { if let e = target { Task { await scene.compose(.replyAll(e)) } } },33 command("forward", L("Transférer"), "arrowshape.turn.up.right", "⇧⌘F", enabled: target != nil) { if let e = target { Task { await scene.compose(.forward(e)) } } },34 command("archive", L("Archiver"), "archivebox", "⌃⌘A", enabled: has) { Task { await scene.perform(.archive) } },35 command("delete", L("Supprimer"), "trash", "⌘⌫", enabled: has) { Task { await scene.perform(.delete) } },36 command("junk", L("Indésirable"), "xmark.bin", "⇧⌘J", enabled: has) { Task { await scene.perform(.junk) } },37 command("flag", L("Drapeau"), "flag", "⇧⌘L", enabled: has) { Task { await scene.toggleFlag() } },38 command("read", L("Marquer comme lu / non lu"), "envelope.badge", "⇧⌘U", enabled: has) { Task { await scene.toggleRead() } },39 command("snooze", L("Mettre en veille"), "clock", "⌃⌘Z", enabled: has) { Task { await scene.snooze(ids: scene.list.selectedIds) } },40 command("pin", L("Épingler / désépingler"), "pin", "⇧⌘P", enabled: has) { Task { await scene.togglePin() } },41 command("remind", L("Me le rappeler…"), "bell", "⌃⌘R", enabled: target != nil && app.next.has(.reminders)) { scene.remindSelection() },42 command("newLabel", L("Nouveau libellé…"), "tag", enabled: app.next.has(.labels)) { scene.next.labelEdit = LabelEditRequest(label: nil) },43 command("refresh", L("Relever le courrier"), "arrow.clockwise", "⇧⌘N") { Task { await scene.refresh() } },44 command("search", L("Rechercher dans le courrier"), "magnifyingglass", "⌘F") { scene.openSearch() },45 command("folder", L("Nouveau dossier…"), "folder.badge.plus") { scene.newFolderRequest += 1 },46 command("studio", L("Studio de modèles"), "rectangle.3.group", "⇧⌘M") { scene.studioRequest += 1 },47 command("next", L("Conversation suivante"), "chevron.down", "⌥⌘↓") { scene.selectAdjacent(1) },48 command("previous", L("Conversation précédente"), "chevron.up", "⌥⌘↑") { scene.selectAdjacent(-1) },49 ]50 #if os(iOS)51 out.append(command("settings", L("Réglages"), "gearshape", "⌘,") { scene.showSettings = true })52 #endif53 for t in SPTheme.allCases { out.append(command("theme." + t.rawValue, L("Thème : \(t.title)"), "circle.lefthalf.filled", enabled: app.settings.theme != t) { app.settings.theme = t }) }54 for d in Density.allCases { out.append(command("density." + d.rawValue, L("Densité : \(d.title)"), "list.bullet", enabled: app.settings.density != d) { app.settings.density = d }) }55 if app.settings.lockEnabled { out.append(command("lock", L("Verrouiller SP Mail"), "lock", "⌃⌘L") { app.lockIfNeeded(force: true) }) }5657 func folder(_ item: SidebarItem, _ title: String, _ icon: String, _ shortcut: String? = nil, subtitle: String? = nil) -> PaletteItem {58 PaletteItem(id: "folder.\(item)", kind: .folder, title: title, subtitle: subtitle, icon: icon, shortcut: shortcut) { scene.selection = item }59 }60 out.append(folder(.unified(.inbox), L("Toutes les boîtes"), "tray.2", "⌘0"))61 for (n, item) in scene.sidebarOrder.enumerated() {62 let shortcut = n < 9 ? "⌘\(n + 1)" : nil63 switch item {64 case .mailbox(let id): if let m = scene.mailboxes.first(where: { $0.id == id }) { out.append(folder(item, MailScene.title(of: m), MailScene.icon(of: m), shortcut, subtitle: scene.currentBox?.address)) }65 case .unread: out.append(folder(item, L("Non lus"), "envelope.badge", shortcut, subtitle: scene.currentBox?.address))66 case .flagged: out.append(folder(item, L("Avec drapeau"), "flag", shortcut, subtitle: scene.currentBox?.address))67 case .outbox: out.append(folder(item, L("Boîte d’envoi"), "arrow.up.circle", shortcut))68 default: break69 }70 }71 for v in [UnifiedView.unread, .flagged, .drafts, .sent] { out.append(folder(.unified(v), UnifiedListView.title(v), "tray.2")) }72 out.append(folder(.scheduled, L("Programmés"), "clock.badge"))73 // SP Mail Next screens, smart folders and labels — only what this server offers74 let next = app.next75 if next.has(.dashboard) { out.append(folder(.dashboard, L("Centre de commande"), "square.grid.2x2", "⇧⌘C")) }76 if next.has(.contacts) { out.append(folder(.contacts, L("Contacts"), "person.2")) }77 if next.has(.attachments) { out.append(folder(.attachments, L("Pièces jointes"), "paperclip")) }78 if next.has(.snooze) { out.append(folder(.snoozed, L("En veille"), "clock")) }79 if next.has(.reminders) { out.append(folder(.followUps, L("Suivis"), "bell")) }80 for saved in next.savedSearches { out.append(folder(.savedSearch(saved.id), saved.name, "sparkle.magnifyingglass", subtitle: L("Recherche enregistrée"))) }81 let keywords = has ? scene.selectionKeywords : []82 for label in next.labels where !label.keyword.isEmpty {83 // with a selection a label is applied to it (or removed); without one, the label opens as a list84 let on = keywords.contains(label.keyword)85 out.append(PaletteItem(id: "label." + label.id, kind: .label, title: label.name, subtitle: has ? (on ? L("Retirer le libellé de la sélection") : L("Appliquer le libellé à la sélection")) : L("Afficher le libellé"), icon: "tag") {86 if has { Task { await scene.perform(.keyword(label.keyword, !on)) } } else { scene.selection = .label(label.id) }87 })88 }89 for a in app.accounts where a.id != scene.currentAccount {90 out.append(PaletteItem(id: "mailbox." + a.id, kind: .mailbox, title: a.address, subtitle: a.display_name, icon: "person.crop.circle") { Task { await scene.switchAccount(a.id) } })91 }92 return out93 }9495 /// Case- and diacritic-insensitive subsequence match; higher is better, nil is no match.96 static func score(_ query: String, in text: String) -> Int? {97 func fold(_ s: String) -> [Character] { Array(s.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)) }98 let q = fold(query).filter { !$0.isWhitespace }, t = fold(text)99 guard !q.isEmpty else { return 0 }100 var score = 0, ti = 0, streak = 0101 for c in q {102 var found = false103 while ti < t.count {104 if t[ti] == c {105 streak += 1106 score += 1 + streak * 2107 if ti == 0 { score += 8 } else if !t[ti - 1].isLetter && !t[ti - 1].isNumber { score += 5 }108 ti += 1; found = true109 break110 }111 streak = 0; ti += 1112 }113 if !found { return nil }114 }115 return score - t.count / 8116 }117118 /// The results for a query. A leading `>` keeps commands, `#` folders and labels, `@` mailboxes; `/` offers to search the mail for the rest.119 static func search(_ raw: String, in items: [PaletteItem], scene: MailScene? = nil) -> [PaletteItem] {120 var query = raw.trimmingCharacters(in: .whitespaces)121 var kind: PaletteItem.Kind?122 if let first = query.first, let k: PaletteItem.Kind = [">": .command, "#": .folder, "@": .mailbox, "/": .search][first] {123 kind = k124 query = String(query.dropFirst()).trimmingCharacters(in: .whitespaces)125 }126 if kind == .search {127 guard !query.isEmpty, let scene else { return [] }128 let text = query129 return [PaletteItem(id: "search", kind: .search, title: L("Rechercher « \(text) » dans le courrier"), icon: "magnifyingglass") { scene.openSearch(text) }]130 }131 let pool = items.filter { kind == nil || $0.kind == kind || (kind == .folder && $0.kind == .label) }132 if query.isEmpty { return pool }133 let ranked = pool.compactMap { item in score(query, in: item.title).map { (item, $0) } }.sorted { $0.1 > $1.1 }.map(\.0)134 if kind == nil, let scene, query.count >= 2 {135 let text = query136 return ranked + [PaletteItem(id: "search", kind: .search, title: L("Rechercher « \(text) » dans le courrier"), icon: "magnifyingglass") { scene.openSearch(text) }]137 }138 return ranked139 }140}141142struct CommandPaletteOverlay: View {143 @Bindable var scene: MailScene144 @State private var query = ""145 @State private var index = 0146 @State private var items: [PaletteItem] = []147 @FocusState private var focused: Bool148149 private var results: [PaletteItem] { CommandPalette.search(query, in: items, scene: scene) }150151 var body: some View {152 let results = results153 ZStack(alignment: .top) {154 SPColor.overlay.ignoresSafeArea().onTapGesture { close() }.accessibilityHidden(true)155 VStack(spacing: 0) {156 HStack(spacing: SPSpacing.m) {157 Image(systemName: "magnifyingglass").foregroundStyle(SPColor.text3)158 TextField("Commande, dossier, boîte…", text: $query)159 .textFieldStyle(.plain).font(.title3).focused($focused).autocorrectionDisabled()160 #if os(iOS)161 .textInputAutocapitalization(.never).submitLabel(.go)162 #endif163 .onSubmit { run(results) }164 .accessibilityLabel(Text("Palette de commandes"))165 ShortcutHint(text: "esc")166 }167 .padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.l)168 Divider().overlay(SPColor.border)169 ScrollViewReader { proxy in170 ScrollView {171 LazyVStack(spacing: 1) {172 ForEach(Array(results.enumerated()), id: \.element.id) { n, item in173 Button { index = n; run(results) } label: { row(item, selected: n == index) }174 .buttonStyle(.plain).disabled(!item.isEnabled).id(item.id)175 }176 if results.isEmpty { Text("Aucun résultat").font(SPFont.callout).foregroundStyle(SPColor.text3).padding(SPSpacing.x3) }177 }178 .padding(SPSpacing.s)179 }180 .frame(maxHeight: 380)181 .onChange(of: index) { _, n in if results.indices.contains(n) { proxy.scrollTo(results[n].id) } }182 }183 Divider().overlay(SPColor.border)184 Text("> commandes # dossiers et libellés @ boîtes / recherche").font(.caption).foregroundStyle(SPColor.text3)185 .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.m)186 }187 .frame(maxWidth: 640)188 .spGlass(RoundedRectangle(cornerRadius: SPRadius.dialog, style: .continuous))189 .clipShape(RoundedRectangle(cornerRadius: SPRadius.dialog, style: .continuous))190 .padding(.horizontal, SPSpacing.xl).padding(.top, 72)191 .onKeyPress(.downArrow) { index = min(index + 1, max(0, results.count - 1)); return .handled }192 .onKeyPress(.upArrow) { index = max(index - 1, 0); return .handled }193 .onKeyPress(.escape) { close(); return .handled }194 .accessibilityAddTraits(.isModal)195 }196 .onAppear { items = CommandPalette.items(for: scene); focused = true }197 .onChange(of: query) { _, _ in index = 0 }198 .transition(.opacity)199 }200201 private func row(_ item: PaletteItem, selected: Bool) -> some View {202 HStack(spacing: SPSpacing.l) {203 Image(systemName: item.icon).frame(width: 22).foregroundStyle(selected ? SPColor.accent : SPColor.text2)204 VStack(alignment: .leading, spacing: 0) {205 Text(item.title).font(.body).foregroundStyle(SPColor.text).lineLimit(1)206 if let s = item.subtitle, !s.isEmpty { Text(s).font(.caption).foregroundStyle(SPColor.text3).lineLimit(1) }207 }208 Spacer(minLength: SPSpacing.m)209 if let s = item.shortcut { ShortcutHint(text: s) }210 }211 .opacity(item.isEnabled ? 1 : 0.45)212 .padding(.horizontal, SPSpacing.l).padding(.vertical, SPSpacing.m)213 #if os(iOS)214 .frame(minHeight: 44)215 #endif216 .background(selected ? AnyShapeStyle(SPColor.accentSoft) : AnyShapeStyle(.clear), in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))217 .contentShape(Rectangle())218 }219220 private func run(_ results: [PaletteItem]) {221 guard results.indices.contains(index), results[index].isEnabled else { return }222 let item = results[index]223 close()224 item.run()225 }226 private func close() { spWithAnimation(SPMotion.press) { scene.showPalette = false } }227}228