diff options
| author | Christian Cleberg <[email protected]> | 2026-04-02 00:27:34 -0500 |
|---|---|---|
| committer | Christian Cleberg <[email protected]> | 2026-04-02 00:27:34 -0500 |
| commit | f820109a956c627e510880a7cac88cb35032203b (patch) | |
| tree | 942bfad93efbb8a2a98e98b0a9590e2631613b3a /Hutch/Views/Lookup/LookupHistoryStore.swift | |
| parent | 7f79cadf99ecf014834855e2e4a5c7d60dd709ac (diff) | |
| download | hutch-f820109a956c627e510880a7cac88cb35032203b.tar.gz hutch-f820109a956c627e510880a7cac88cb35032203b.tar.bz2 hutch-f820109a956c627e510880a7cac88cb35032203b.zip | |
Implement search history for Look Up page
Diffstat (limited to 'Hutch/Views/Lookup/LookupHistoryStore.swift')
| -rw-r--r-- | Hutch/Views/Lookup/LookupHistoryStore.swift | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/Hutch/Views/Lookup/LookupHistoryStore.swift b/Hutch/Views/Lookup/LookupHistoryStore.swift new file mode 100644 index 0000000..e127970 --- /dev/null +++ b/Hutch/Views/Lookup/LookupHistoryStore.swift @@ -0,0 +1,60 @@ +import Foundation + +struct LookupHistoryEntry: Codable, Hashable, Identifiable, Sendable { + let type: LookupType + let query: String + let createdAt: Date + + var id: String { + "\(type.rawValue):\(query)" + } +} + +enum LookupHistoryStore { + private static let maximumEntries = 20 + + static func load(defaults: UserDefaults = .standard) -> [LookupHistoryEntry] { + guard let data = defaults.data(forKey: AppStorageKeys.lookupHistory) else { + return [] + } + + do { + return try JSONDecoder().decode([LookupHistoryEntry].self, from: data) + } catch { + defaults.removeObject(forKey: AppStorageKeys.lookupHistory) + return [] + } + } + + static func record( + type: LookupType, + query: String, + defaults: UserDefaults = .standard, + now: Date = .now + ) { + let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedQuery.isEmpty else { return } + + var entries = load(defaults: defaults) + entries.removeAll { $0.type == type && $0.query == normalizedQuery } + entries.insert( + LookupHistoryEntry(type: type, query: normalizedQuery, createdAt: now), + at: 0 + ) + + if entries.count > maximumEntries { + entries = Array(entries.prefix(maximumEntries)) + } + + save(entries, defaults: defaults) + } + + static func clear(defaults: UserDefaults = .standard) { + defaults.removeObject(forKey: AppStorageKeys.lookupHistory) + } + + private static func save(_ entries: [LookupHistoryEntry], defaults: UserDefaults) { + guard let data = try? JSONEncoder().encode(entries) else { return } + defaults.set(data, forKey: AppStorageKeys.lookupHistory) + } +} |
