Repository Public License
1import Foundation2import NavigatorCore34/// Result of matching a query against one string.5public struct FuzzyMatch: Sendable, Equatable {6 /// Higher is better. Comparable only between matches of the same query.7 public var score: Double8 /// Offsets (in `Character`s of the candidate) of the matched characters, ascending — for highlighting.9 public var matchedOffsets: [Int]10}1112/// Subsequence matcher used by the orbital view search and the command palette.13///14/// Every character of the query must appear in the candidate, in order, compared without case or diacritics15/// ("resume" finds "Résumé"). Spaces in the query separate terms that must all match, in any order. The score16/// rewards consecutive characters, matches at the start of a word and at the start of the string, and17/// penalises gaps and long candidates. Deterministic, no locale-dependent behaviour.18public enum FuzzyMatcher {19 static func fold(_ text: String) -> [Character] {20 Array(text.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive],21 locale: Locale(identifier: "en_US_POSIX")))22 }2324 private static func isBoundary(_ characters: [Character], _ index: Int) -> Bool {25 guard index > 0 else { return true }26 let previous = characters[index - 1]27 return !(previous.isLetter || previous.isNumber)28 }2930 public static func match(_ query: String, in candidate: String) -> FuzzyMatch? {31 let terms = query.split(whereSeparator: \.isWhitespace).map(String.init)32 guard !terms.isEmpty else { return nil }33 // Folding can change the number of characters ("ß" → "ss"); offsets then refer to the folded text,34 // which is still the right place to highlight for all but those rare characters.35 let haystack = fold(candidate)36 var total = 0.037 var offsets = Set<Int>()38 for term in terms {39 guard let result = matchTerm(fold(term), in: haystack) else { return nil }40 total += result.score41 offsets.formUnion(result.matchedOffsets)42 }43 return FuzzyMatch(score: total / Double(terms.count), matchedOffsets: offsets.sorted())44 }4546 /// Best alignment of one term by dynamic programming: `best[i][j]` is the best score of matching the47 /// first `i + 1` query characters with the `i`-th one placed on haystack position `j`.48 private static func matchTerm(_ needle: [Character], in haystack: [Character]) -> FuzzyMatch? {49 let n = needle.count, m = haystack.count50 guard n > 0, n <= m, m <= 2_048 else { return nil }51 let unreachable = -Double.infinity52 var best = [[Double]](repeating: [Double](repeating: unreachable, count: m), count: n)53 var from = [[Int]](repeating: [Int](repeating: -1, count: m), count: n)5455 func bonus(at j: Int) -> Double {56 var value = 1.057 if j == 0 { value += 2.0 } else if isBoundary(haystack, j) { value += 1.2 }58 return value59 }60 for j in 0..<m where haystack[j] == needle[0] {61 best[0][j] = bonus(at: j) - Double(j) * 0.0262 }63 for i in 1..<max(n, 1) {64 var runningBest = unreachable // best of best[i-1][k] - gap penalty, for k < j - 165 var runningIndex = -166 for j in i..<m {67 if j >= 2, best[i - 1][j - 2] > unreachable {68 // Entering the window of non-adjacent predecessors.69 let candidate = best[i - 1][j - 2] + Double(j - 2) * 0.0570 if candidate > runningBest { runningBest = candidate; runningIndex = j - 2 }71 }72 guard haystack[j] == needle[i] else { continue }73 var score = unreachable74 var source = -175 if best[i - 1][j - 1] > unreachable {76 score = best[i - 1][j - 1] + 1.5 // consecutive characters77 source = j - 178 }79 if runningIndex >= 0 {80 // Gap penalty grows with the distance: (j - k) * 0.05 = j*0.05 - k*0.05.81 let gapped = runningBest - Double(j) * 0.0582 if gapped > score { score = gapped; source = runningIndex }83 }84 guard source >= 0 else { continue }85 best[i][j] = score + bonus(at: j)86 from[i][j] = source87 }88 }89 var end = -190 for j in 0..<m where best[n - 1][j] > unreachable && (end < 0 || best[n - 1][j] > best[n - 1][end]) { end = j }91 guard end >= 0 else { return nil }92 var offsets = [Int](repeating: 0, count: n)93 var j = end94 for i in stride(from: n - 1, through: 0, by: -1) {95 offsets[i] = j96 j = from[i][j]97 }98 // Normalise by the query length and prefer shorter candidates among equals.99 var score = best[n - 1][end] / Double(n) - Double(m - n) * 0.002100 if n == m { score += 1 } // exact match (modulo case and diacritics)101 return FuzzyMatch(score: score, matchedOffsets: offsets)102 }103}104105/// One hit of a search across spaces and tabs.106public struct OrbitSearchResult: Sendable, Equatable, Identifiable {107 public enum Item: Sendable, Equatable {108 case space(OrbitSpace)109 case tab(Tab)110 }111 public enum Field: String, Sendable, Codable { case name, title, url }112113 public var item: Item114 public var score: Double115 /// Which text matched, and where (character offsets in that text).116 public var field: Field117 public var matchedOffsets: [Int]118119 public var id: String {120 switch item {121 case .space(let space): "space-\(space.id.string)"122 case .tab(let tab): "tab-\(tab.id.string)"123 }124 }125}126127public enum OrbitSearch {128 /// Text of a URL that is worth matching: host and path, without scheme, `www.`, query or fragment129 /// (queries often carry tokens and make noisy matches).130 static func searchableText(of url: URL) -> String {131 var host = url.host(percentEncoded: false) ?? ""132 if host.hasPrefix("www.") { host.removeFirst(4) }133 let path = url.path(percentEncoded: false)134 return path == "/" ? host : host + path135 }136137 /// Ranks spaces and tabs against `query`. Archived spaces and closed tabs are searched only when present138 /// in the input: the caller decides the scope. Ties are broken by recency (tabs) then id, so the list is139 /// stable while the user types.140 public static func search(_ query: String, spaces: [OrbitSpace], tabs: [Tab], limit: Int = 50) -> [OrbitSearchResult] {141 guard !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, limit > 0 else { return [] }142 var results: [OrbitSearchResult] = []143 for space in spaces {144 if let match = FuzzyMatcher.match(query, in: space.name) {145 // A space is a destination of its own: a small boost keeps it above tabs of equal quality.146 results.append(OrbitSearchResult(item: .space(space), score: match.score + 0.25, field: .name,147 matchedOffsets: match.matchedOffsets))148 }149 }150 for tab in tabs {151 let title = FuzzyMatcher.match(query, in: tab.title)152 let url = tab.url.flatMap { FuzzyMatcher.match(query, in: searchableText(of: $0)) }153 switch (title, url) {154 case (let title?, let url?) where url.score > title.score:155 results.append(OrbitSearchResult(item: .tab(tab), score: url.score, field: .url, matchedOffsets: url.matchedOffsets))156 case (let title?, _):157 results.append(OrbitSearchResult(item: .tab(tab), score: title.score, field: .title, matchedOffsets: title.matchedOffsets))158 case (nil, let url?):159 results.append(OrbitSearchResult(item: .tab(tab), score: url.score, field: .url, matchedOffsets: url.matchedOffsets))160 case (nil, nil):161 break162 }163 }164 func recency(_ result: OrbitSearchResult) -> Date {165 if case .tab(let tab) = result.item { return tab.lastActiveAt }166 return .distantPast167 }168 results.sort { lhs, rhs in169 if lhs.score != rhs.score { return lhs.score > rhs.score }170 if recency(lhs) != recency(rhs) { return recency(lhs) > recency(rhs) }171 return lhs.id < rhs.id172 }173 return Array(results.prefix(limit))174 }175}176