hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
| 1 | import Foundation |
| 2 | |
| 3 | /// What you open, how often, how lately. Paths only. Drives the empty Find screen and ranking. |
| 4 | @MainActor |
| 5 | final class Recents { |
| 6 | static let shared = Recents() |
| 7 | struct Entry: Codable { var path: String; var machine: String?; var count: Int; var last: Date } |
| 8 | private(set) var entries: [String: Entry] = [:] |
| 9 | private var file: URL { HopConfig.dir.appendingPathComponent("recents.json") } |
| 10 | |
| 11 | private init() { |
| 12 | if let d = try? Data(contentsOf: file), let v = try? JSONDecoder().decode([String: Entry].self, from: d) { entries = v } |
| 13 | } |
| 14 | private static func key(_ path: String, _ machine: String?) -> String { (machine ?? "Mac") + ":" + path } |
| 15 | |
| 16 | func record(_ hit: FileIndex.Hit) { |
| 17 | let k = Self.key(hit.path, hit.machine) |
| 18 | var e = entries[k] ?? Entry(path: hit.path, machine: hit.machine, count: 0, last: Date()) |
| 19 | e.count += 1; e.last = Date(); entries[k] = e |
| 20 | if entries.count > 500, let old = entries.min(by: { score($0.value) < score($1.value) })?.key { entries[old] = nil } |
| 21 | if let d = try? JSONEncoder().encode(entries) { try? d.write(to: file, options: .atomic) } |
| 22 | } |
| 23 | |
| 24 | func forget(_ hit: FileIndex.Hit) { |
| 25 | entries[Self.key(hit.path, hit.machine)] = nil |
| 26 | if let d = try? JSONEncoder().encode(entries) { try? d.write(to: file, options: .atomic) } |
| 27 | } |
| 28 | |
| 29 | /// Frecency: opens count more when recent (halves every 3 days). |
| 30 | private func score(_ e: Entry) -> Double { |
| 31 | Double(e.count) * pow(0.5, Date().timeIntervalSince(e.last) / (3 * 86400)) |
| 32 | } |
| 33 | func boost(_ hit: FileIndex.Hit) -> Int { |
| 34 | guard let e = entries[Self.key(hit.path, hit.machine)] else { return 0 } |
| 35 | return Int(min(80, 25 * log2(1 + score(e)) + 10)) |
| 36 | } |
| 37 | func top(_ n: Int) -> [FileIndex.Hit] { |
| 38 | entries.values.sorted { score($0) > score($1) }.prefix(n).compactMap { e in |
| 39 | if let m = e.machine { return FileIndex.Hit(path: e.path, machine: m, score: 0) } |
| 40 | return FileManager.default.fileExists(atPath: e.path) ? FileIndex.Hit(id: e.path, score: 0) : nil |
| 41 | } |
| 42 | } |
| 43 | } |