Sources/OrgApp/CommandRanking.swift
138 lines · 8839 bytes
13 symbols in this file
1import Foundation
2import OrgCore
3
4/// The commands run from the command palette: the last ten, most recent first, and how often
5/// each was run, kept in `UserDefaults` by command id.
6public final class CommandUsage: Sendable {
7 public static let shared = CommandUsage()
8 /// The recents the palette lists for an empty query.
9 public static let recentLimit = 10
10 /// Uses past this count add nothing more to a command's rank.
11 public static let usesCounted = 20
12
13 private nonisolated(unsafe) let defaults: UserDefaults
14 private static let recentKey = "commandRecents"
15 private static let countsKey = "commandUseCounts"
16
17 public init(defaults: UserDefaults = .standard) {
18 self.defaults = defaults
19 }
20
21 /// Command ids, most recent first.
22 public var recent: [String] { defaults.stringArray(forKey: Self.recentKey) ?? [] }
23
24 public func uses(of id: String) -> Int {
25 (defaults.dictionary(forKey: Self.countsKey)?[id] as? Int) ?? 0
26 }
27
28 public func record(_ id: String) {
29 defaults.set(Array(([id] + recent.filter { $0 != id }).prefix(Self.recentLimit)), forKey: Self.recentKey)
30 var counts = defaults.dictionary(forKey: Self.countsKey) ?? [:]
31 counts[id] = ((counts[id] as? Int) ?? 0) + 1
32 defaults.set(counts, forKey: Self.countsKey)
33 }
34
35 /// What frequent use adds to a `FuzzyMatch.score`: at most one word-start match, so a
36 /// frequent command wins a tie and never beats a clearly better match.
37 public func bonus(for id: String) -> Int {
38 min(uses(of: id), Self.usesCounted) * FuzzyMatch.wordStartBonus * 100 / Self.usesCounted
39 }
40}
41
42/// The command palette's order, on the Mac and on iOS.
43public enum CommandRanking {
44 /// For an empty query, the recent commands among `items` and then the rest by title; for a
45 /// query, no recents and the matches best first, frequent use breaking near ties.
46 public static func rank<Item>(_ items: [Item], query: String, usage: CommandUsage = .shared,
47 id: (Item) -> String, titles: (Item) -> [String]) -> (recent: [Item], rest: [Item]) {
48 func title(_ item: Item) -> String { titles(item).first ?? id(item) }
49 if query.allSatisfy(\.isWhitespace) {
50 let recentIDs = usage.recent
51 let recent = recentIDs.compactMap { wanted in items.first { id($0) == wanted } }
52 let rest = items.filter { !recentIDs.contains(id($0)) }
53 .sorted { title($0).localizedStandardCompare(title($1)) == .orderedAscending }
54 return (recent, rest)
55 }
56 let scored: [(item: Item, score: Int)] = items.compactMap { item in
57 guard let score = titles(item).compactMap({ FuzzyMatch.score(query, $0) }).max() else { return nil }
58 return (item, score + usage.bonus(for: id(item)))
59 }
60 let ranked = scored.sorted { a, b in
61 a.score != b.score ? a.score > b.score : title(a.item).localizedStandardCompare(title(b.item)) == .orderedAscending
62 }
63 return ([], ranked.map(\.item))
64 }
65}
66
67/// Commands by subject: the Org menu's submenus on the Mac and iPad, and the sections of the
68/// iOS Commands list.
69public enum CommandGroups {
70 public struct Group: Sendable {
71 public let title: String
72 /// A command belongs to the first group with a prefix its id starts with.
73 public let prefixes: [String]
74 }
75
76 /// The Org menu's submenus, in menu order.
77 public static let orgMenu: [Group] = [
78 Group(title: String(localized: "Visibility", comment: "Org menu submenu"), prefixes: ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
79 Group(title: String(localized: "Headings", comment: "Org menu submenu"), prefixes: ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
80 Group(title: String(localized: "TODO and Tags", comment: "Org menu submenu"), prefixes: ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
81 Group(title: String(localized: "Properties and Columns", comment: "Org menu submenu"), prefixes: ["org.property.", "org.columns", "org.drawer."]),
82 Group(title: String(localized: "Dates and Timers", comment: "Org menu submenu"), prefixes: ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
83 Group(title: String(localized: "Lists", comment: "Org menu submenu"), prefixes: ["org.item.", "org.checkbox."]),
84 Group(title: String(localized: "Tables", comment: "Org menu submenu"), prefixes: ["org.table", "app.table-", "app.plot"]),
85 Group(title: String(localized: "Links and Footnotes", comment: "Org menu submenu"), prefixes: ["org.link.", "org.id.", "org.footnote."]),
86 Group(title: String(localized: "Blocks", comment: "Org menu submenu"), prefixes: ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
87 Group(title: String(localized: "Text", comment: "Org menu submenu"), prefixes: ["org.emphasize", "org.fill-", "org.snippet"]),
88 Group(title: String(localized: "Attachments", comment: "Org menu submenu"), prefixes: ["app.attach."]),
89 Group(title: String(localized: "Notes", comment: "Org menu submenu"), prefixes: ["app.dailies.", "app.node.", "app.backlinks"]),
90 Group(title: String(localized: "Encryption", comment: "Org menu submenu"), prefixes: ["app.crypt."]),
91 ]
92
93 /// The Org menu's groups and the app's commands outside the Org menu.
94 public static let commandList: [Group] = orgMenu + [
95 Group(title: String(localized: "Clock", comment: "Commands list section"), prefixes: ["app.clock."]),
96 Group(title: String(localized: "Export", comment: "Commands list section"), prefixes: ["app.export", "app.copy-rich-text", "app.publish", "app.share-subtree"]),
97 Group(title: String(localized: "File", comment: "Commands list section"), prefixes: ["app.save", "app.word-count", "app.recovery", "app.sync-conflicts", "app.lint", "app.working-copy"]),
98 Group(title: String(localized: "Edit", comment: "Commands list section"), prefixes: ["edit.", "macro."]),
99 Group(title: String(localized: "View", comment: "Commands list section"), prefixes: ["app.toggle-markup", "editor.", "app.split-", "app.pane-"]),
100 ]
101
102 /// The index in `groups` of the group `id` belongs to, or nil for none.
103 public static func group(of id: String, in groups: [Group] = orgMenu) -> Int? {
104 groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
105 }
106}
107
108/// Why a command doesn't apply at the caret, for a list that shows it greyed: what it needs
109/// that the caret isn't in, or that there is nothing for it to do there.
110public enum CommandReason {
111 public static func reason(for id: String, in context: EditContext) -> String {
112 func starts(_ prefixes: String...) -> Bool { prefixes.contains { id.hasPrefix($0) } }
113 if starts("org.table", "app.table-export", "app.plot"), !KeyContext.holds("table", in: context) {
114 return String(localized: "No table at point")
115 }
116 if starts("org.item.", "org.checkbox."), !KeyContext.holds("item", in: context) {
117 return String(localized: "Not in a list", comment: "Why a command is greyed in the Commands list")
118 }
119 if starts("org.babel."), !KeyContext.holds("src", in: context) {
120 return String(localized: "Not in a code block", comment: "Why a command is greyed in the Commands list")
121 }
122 if starts("org.link.open"), !OpenLinkAtPoint().applies(in: context) {
123 return String(localized: "Not on a link", comment: "Why a command is greyed in the Commands list")
124 }
125 if starts("org.timestamp.up", "org.timestamp.down", "org.timestamp.day-", "org.timestamp.evaluate-range"), !KeyContext.holds("timestamp", in: context) {
126 return String(localized: "Not on a timestamp", comment: "Why a command is greyed in the Commands list")
127 }
128 if starts("app.crypt.open-entry", "app.crypt.decrypt-entry"), OrgCrypt.encryptedRange(context.text, at: context.caret) == nil {
129 return String(localized: "Not an encrypted entry")
130 }
131 if starts("org.heading.", "org.subtree.", "org.todo.", "org.priority.", "org.tags.", "org.property.", "org.effort.",
132 "org.schedule", "org.deadline", "org.archive.", "app.refile", "app.archive", "app.crypt.encrypt-entry"),
133 context.tree.root.child(containing: context.caret)?.kind != .section {
134 return String(localized: "Not in a subtree")
135 }
136 return String(localized: "Nothing to do here", comment: "Why a command is greyed in the Commands list")
137 }
138}