Repository Public
1// SP Notes iOS2// File: Features/Commands/CommandRegistry.swift3// Description: The commands of the app as data: the places of a window (also behind ⌘1…9), the actions (new note, capture,4// sync, appearance, settings…) and the notes found by title. Used by the command palette (⌘K) and the menus.5// Includes the fuzzy matcher that ranks them and the model of the palette (query, results, keyboard selection).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesCore1213/// What a command does.14enum PaletteAction: Equatable, Sendable {15 case go(SidebarItem)16 case openNote(String)17 case newNote18 case newFolder19 case capture20 case sync21 case syncDetails22 case appearance(Appearance)23 case settings24}2526struct PaletteCommand: Identifiable, Equatable, Sendable {27 var id: String28 var title: String29 var subtitle: String?30 var symbol: String31 /// Other words that find the command.32 var keywords: [String] = []33 /// The hardware-keyboard shortcut, as shown (« ⌘N »).34 var shortcut: String?35 var action: PaletteAction36 var isNote: Bool { if case .openNote = action { return true } else { return false } }37}3839/// A place of a window with its name: sidebar rows, « Plus », palette, ⌘1…9.40struct ShellPlace: Identifiable, Equatable, Sendable {41 var item: SidebarItem42 var title: String43 var symbol: String44 var id: String { item.storageKey }45}4647@MainActor48enum CommandRegistry {49 /// The places reachable by number (⌘1…⌘9), in order: the fixed ones, then the hosted sections that are available.50 static func numberedPlaces(sections: HostedSectionRegistry) -> [ShellPlace] {51 var places = [52 ShellPlace(item: .today, title: String(localized: "Aujourd’hui"), symbol: "sun.max"),53 ShellPlace(item: .source(.smart(.all)), title: SmartList.all.title, symbol: SmartList.all.symbol),54 ShellPlace(item: .inbox, title: SmartList.inbox.title, symbol: SmartList.inbox.symbol),55 ShellPlace(item: .tasks, title: String(localized: "Tâches"), symbol: "checklist"),56 ShellPlace(item: .source(.smart(.favorites)), title: SmartList.favorites.title, symbol: SmartList.favorites.symbol),57 ]58 places += hostedPlaces(sections: sections)59 return Array(places.prefix(9))60 }6162 static func hostedPlaces(sections: HostedSectionRegistry) -> [ShellPlace] {63 sections.available.map { ShellPlace(item: .hosted($0.id), title: $0.title, symbol: $0.symbol) }64 }6566 /// Every command that does not depend on the text typed.67 static func commands(sections: HostedSectionRegistry, appearance: Appearance = .system) -> [PaletteCommand] {68 var list: [PaletteCommand] = []69 let numbered = numberedPlaces(sections: sections)70 for (index, place) in numbered.enumerated() {71 list.append(PaletteCommand(id: "go:\(place.id)", title: place.title, subtitle: String(localized: "Aller à"), symbol: place.symbol,72 shortcut: "⌘\(index + 1)", action: .go(place.item)))73 }74 for place in hostedPlaces(sections: sections) where !numbered.contains(place) {75 list.append(PaletteCommand(id: "go:\(place.id)", title: place.title, subtitle: String(localized: "Aller à"), symbol: place.symbol, action: .go(place.item)))76 }77 let go = String(localized: "Aller à")78 list.append(PaletteCommand(id: "go:search", title: String(localized: "Rechercher"), subtitle: go, symbol: "magnifyingglass", keywords: ["recherche", "trouver"], shortcut: "⌘F", action: .go(.search)))79 for section in NoteSection.editable {80 list.append(PaletteCommand(id: "go:section:\(section)", title: NoteSection.title(section), subtitle: go, symbol: NoteSection.symbol(section), action: .go(.source(.section(section)))))81 }82 list.append(PaletteCommand(id: "go:smart:archived", title: SmartList.archived.title, subtitle: go, symbol: SmartList.archived.symbol, keywords: ["archive"], action: .go(.source(.smart(.archived)))))83 list.append(PaletteCommand(id: "go:smart:trash", title: SmartList.trash.title, subtitle: go, symbol: SmartList.trash.symbol, keywords: ["supprimées"], action: .go(.source(.smart(.trash)))))84 let act = String(localized: "Action")85 list.append(PaletteCommand(id: "new-note", title: String(localized: "Nouvelle note"), subtitle: act, symbol: "square.and.pencil", keywords: ["créer", "écrire"], shortcut: "⌘N", action: .newNote))86 list.append(PaletteCommand(id: "capture", title: String(localized: "Capture rapide"), subtitle: act, symbol: "plus.circle", keywords: ["capturer", "ajouter"], shortcut: "⌥⌘N", action: .capture))87 list.append(PaletteCommand(id: "new-folder", title: String(localized: "Nouveau dossier"), subtitle: act, symbol: "folder.badge.plus", shortcut: "⇧⌘N", action: .newFolder))88 list.append(PaletteCommand(id: "sync", title: String(localized: "Synchroniser maintenant"), subtitle: act, symbol: "arrow.triangle.2.circlepath", keywords: ["synchro", "actualiser"], shortcut: "⌘R", action: .sync))89 list.append(PaletteCommand(id: "sync-details", title: String(localized: "État de la synchronisation"), subtitle: act, symbol: "icloud", keywords: ["synchro", "conflits"], action: .syncDetails))90 for choice in Appearance.allCases where choice != appearance {91 list.append(PaletteCommand(id: "appearance:\(choice.rawValue)", title: String(localized: "Apparence : \(choice.label)"), subtitle: act,92 symbol: choice == .dark ? "moon" : (choice == .light ? "sun.max" : "circle.lefthalf.filled"),93 keywords: choice == .dark ? ["sombre", "nuit", "thème"] : (choice == .light ? ["clair", "jour", "thème"] : ["automatique", "système", "thème"]),94 action: .appearance(choice)))95 }96 list.append(PaletteCommand(id: "settings", title: String(localized: "Réglages"), subtitle: act, symbol: "gearshape", keywords: ["préférences", "compte", "verrou"], shortcut: "⌘,", action: .settings))97 return list98 }99}100101/// Ranks a candidate against what is typed: case- and accent-insensitive; a prefix beats the start of a word, which beats a102/// substring, which beats letters in order (« nvn » finds « Nouvelle note »). nil = no match.103enum FuzzyMatch {104 static func fold(_ text: String) -> String {105 text.folding(options: [.diacriticInsensitive, .caseInsensitive, .widthInsensitive], locale: nil).lowercased()106 }107108 static func score(_ query: String, in candidate: String) -> Int? {109 let needle = fold(query).trimmingCharacters(in: .whitespaces)110 let hay = fold(candidate)111 guard !needle.isEmpty else { return 0 }112 guard !hay.isEmpty else { return nil }113 if hay == needle { return 1000 }114 if hay.hasPrefix(needle) { return 900 - min(hay.count - needle.count, 100) }115 if let range = hay.range(of: needle) {116 let atWordStart = range.lowerBound == hay.startIndex || !hay[hay.index(before: range.lowerBound)].isLetter && !hay[hay.index(before: range.lowerBound)].isNumber117 return (atWordStart ? 700 : 500) - min(hay.distance(from: hay.startIndex, to: range.lowerBound), 100)118 }119 // letters in order; a bonus for each one that starts a word or follows the previous match120 var score = 300121 var index = hay.startIndex122 var previous: String.Index?123 for character in needle where character != " " {124 guard let found = hay[index...].firstIndex(of: character) else { return nil }125 let startsWord = found == hay.startIndex || hay[hay.index(before: found)] == " " || hay[hay.index(before: found)] == "-"126 if startsWord { score += 12 }127 if let previous, hay.index(after: previous) == found { score += 6 }128 score -= min(hay.distance(from: index, to: found), 8)129 previous = found130 index = hay.index(after: found)131 }132 return max(score, 1)133 }134135 /// The best score of a command: its title, or a keyword (worth a little less).136 static func score(_ query: String, command: PaletteCommand) -> Int? {137 var best = score(query, in: command.title)138 for keyword in command.keywords { if let s = score(query, in: keyword), s - 150 > (best ?? Int.min) { best = max(s - 150, 1) } }139 return best140 }141142 /// Commands in the order to show them: best first, the registry order for equal scores; with nothing typed, all of them.143 static func rank(_ query: String, commands: [PaletteCommand]) -> [PaletteCommand] {144 guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return commands }145 return commands.enumerated()146 .compactMap { index, command in score(query, command: command).map { (command, $0, index) } }147 .sorted { $0.1 != $1.1 ? $0.1 > $1.1 : $0.2 < $1.2 }148 .map(\.0)149 }150}151152@MainActor153@Observable154final class CommandPaletteModel {155 var query = "" { didSet { if query != oldValue { refresh() } } }156 private(set) var results: [PaletteCommand] = []157 private(set) var selection = 0158 static let limit = 14159160 @ObservationIgnored private let commands: [PaletteCommand]161 /// Notes whose title or text matches (the local store); empty text → the recent notes.162 @ObservationIgnored private let notes: @Sendable (String) async -> [PaletteCommand]163 @ObservationIgnored private var noteResults: [PaletteCommand] = []164 @ObservationIgnored private var search: Task<Void, Never>?165166 init(commands: [PaletteCommand], notes: @escaping @Sendable (String) async -> [PaletteCommand] = { _ in [] }) {167 self.commands = commands168 self.notes = notes169 refresh()170 }171172 var selected: PaletteCommand? { results.indices.contains(selection) ? results[selection] : nil }173174 func move(_ delta: Int) {175 guard !results.isEmpty else { return }176 selection = (selection + delta + results.count) % results.count177 }178179 func select(_ command: PaletteCommand) { if let index = results.firstIndex(of: command) { selection = index } }180181 private func refresh() {182 compose(keepingSelection: false)183 search?.cancel()184 let text = query185 search = Task { [weak self, notes] in186 let found = await notes(text)187 guard !Task.isCancelled, let self, self.query == text else { return }188 self.noteResults = found189 self.compose(keepingSelection: true)190 }191 }192193 /// Commands first when they match well; notes after them, in the order of the store's search.194 private func compose(keepingSelection: Bool) {195 let ranked = FuzzyMatch.rank(query, commands: commands)196 var list = Array(ranked.prefix(query.isEmpty ? 8 : Self.limit))197 for note in noteResults where list.count < Self.limit { list.append(note) }198 let previous = selected199 results = list200 selection = keepingSelection ? (previous.flatMap { list.firstIndex(of: $0) } ?? 0) : 0201 }202203 /// For tests: waits for the note search of the current text.204 func settle() async { await search?.value }205}206207extension PaletteCommand {208 /// A note as a command.209 static func note(id: String, title: String, subtitle: String?) -> PaletteCommand {210 PaletteCommand(id: "note:\(id)", title: NoteTitle.display(title), subtitle: subtitle ?? String(localized: "Note"), symbol: "note.text", action: .openNote(id))211 }212}213