Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Command/CommandRegistry.swift3// Description: The command registry of the command centre (⌘K): the app and the screens register their commands and4// remove them with the token they got back; the palette lists them through the fuzzy ranking and remembers5// the recently used ones on the device. Same semantics as the web registry (`registerCommands`): a6// registration with an existing id replaces the command, and removing the older registration does not7// remove the newer one.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import Observation1314/// One command of the palette.15public struct FeatureCommand: Identifiable {16 /// Stable, namespaced: `nav.tasks`, `page.export.md`…17 public var id: String18 public var title: String19 /// Smaller text next to the title.20 public var subtitle: String?21 /// Extra search terms (synonyms, the English name…).22 public var keywords: String23 public var systemImage: String?24 /// Group heading in the palette: « Aller à », « Créer », « Page »…25 public var section: String26 /// Shortcut hint shown on the right (« ⌘⇧N »). Display only: the app owns the real key equivalents.27 public var shortcut: String?28 /// Higher = earlier among equal scores.29 public var priority: Int30 /// Hidden while it returns false (evaluated at each listing).31 public var isEnabled: @MainActor () -> Bool32 public var action: @MainActor () async -> Void3334 public init(id: String, title: String, subtitle: String? = nil, keywords: String = "", systemImage: String? = nil, section: String, shortcut: String? = nil,35 priority: Int = 0, isEnabled: @escaping @MainActor () -> Bool = { true }, action: @escaping @MainActor () async -> Void) {36 self.id = id37 self.title = title38 self.subtitle = subtitle39 self.keywords = keywords40 self.systemImage = systemImage41 self.section = section42 self.shortcut = shortcut43 self.priority = priority44 self.isEnabled = isEnabled45 self.action = action46 }47}4849/// Where the recents are kept.50@MainActor51public protocol CommandRecentsStore: AnyObject {52 func load() -> [CommandRecent]53 func save(_ recents: [CommandRecent])54}5556/// Recents in `UserDefaults` (device-local, as the web keeps them in `localStorage`).57@MainActor58public final class UserDefaultsCommandRecents: CommandRecentsStore {59 private let defaults: UserDefaults60 private let key: String61 public init(defaults: UserDefaults = .standard, key: String = "spn.command.recents") {62 self.defaults = defaults63 self.key = key64 }65 public func load() -> [CommandRecent] {66 guard let data = defaults.data(forKey: key) else { return [] }67 return (try? JSONDecoder().decode([CommandRecent].self, from: data)) ?? []68 }69 public func save(_ recents: [CommandRecent]) {70 if let data = try? JSONEncoder().encode(recents) { defaults.set(data, forKey: key) }71 }72}7374/// Recents kept in memory (tests, previews, the catalogue).75@MainActor76public final class InMemoryCommandRecents: CommandRecentsStore {77 private var recents: [CommandRecent]78 public init(_ recents: [CommandRecent] = []) { self.recents = recents }79 public func load() -> [CommandRecent] { recents }80 public func save(_ recents: [CommandRecent]) { self.recents = recents }81}8283@Observable @MainActor84public final class CommandRegistry {85 /// What `register` gives back, to remove exactly that registration.86 public struct Token: Hashable, Sendable {87 let value: Int88 }8990 private struct Entry {91 var command: FeatureCommand92 var token: Token93 var owner: String?94 var order: Int95 }9697 private var entries: [String: Entry] = [:]98 private var nextToken = 099 private var nextOrder = 0100 public private(set) var recents: [CommandRecent]101 @ObservationIgnored private let recentsStore: any CommandRecentsStore102 @ObservationIgnored private let now: @Sendable () -> Date103104 public init(recents: (any CommandRecentsStore)? = nil, now: @escaping @Sendable () -> Date = { Date() }) {105 let store = recents ?? UserDefaultsCommandRecents()106 recentsStore = store107 self.recents = store.load()108 self.now = now109 }110111 /// Registers (or replaces, by id) commands. `owner` lets a screen remove everything it registered at once.112 @discardableResult113 public func register(_ commands: [FeatureCommand], owner: String? = nil) -> Token {114 nextToken += 1115 let token = Token(value: nextToken)116 for command in commands {117 // A replaced command keeps its place in the list.118 let order = entries[command.id]?.order ?? { nextOrder += 1; return nextOrder }()119 entries[command.id] = Entry(command: command, token: token, owner: owner, order: order)120 }121 return token122 }123124 /// Removes exactly the commands of that registration (not a command that replaced one of them since).125 public func unregister(_ token: Token) {126 entries = entries.filter { $0.value.token != token }127 }128129 public func unregister(owner: String) {130 entries = entries.filter { $0.value.owner != owner }131 }132133 /// Every registered command, in registration order.134 public var commands: [FeatureCommand] { entries.values.sorted { $0.order < $1.order }.map(\.command) }135 /// The commands that can run now.136 public var available: [FeatureCommand] { commands.filter { $0.isEnabled() } }137 public func command(id: String) -> FeatureCommand? { entries[id]?.command }138139 /// Runs a command by id and remembers it. False when unknown or currently unavailable.140 @discardableResult141 public func run(id: String) async -> Bool {142 guard let command = entries[id]?.command, command.isEnabled() else { return false }143 remember(CommandRecent(kind: .command, id: id, at: now()))144 await command.action()145 return true146 }147148 public func remember(_ entry: CommandRecent) {149 recents = CommandRecents.push(recents, entry)150 recentsStore.save(recents)151 }152153 public func clearRecents() {154 recents = []155 recentsStore.save([])156 }157158 /// The available commands ranked for a query, as the web palette does: keywords = keywords + section, boost =159 /// priority + recency.160 public func ranked(_ query: String, limit: Int = 60) -> [FuzzyRanked<FeatureCommand>] {161 let recents = recents162 return Fuzzy.rank(query, available, title: { $0.title }, keywords: { $0.keywords + " " + $0.section },163 boost: { $0.priority + CommandRecents.boost(recents, kind: .command, id: $0.id) }, limit: limit)164 }165}166