| 1 | import Combine |
| 2 | import Foundation |
| 3 | |
| 4 | @MainActor |
| 5 | final class RecentlyViewedStore: ObservableObject { |
| 6 | @Published private(set) var entryIDs: [String] |
| 7 | |
| 8 | private let defaults: UserDefaults |
| 9 | private let storageKey = "klepon.recentlyViewed" |
| 10 | private let limit = 10 |
| 11 | |
| 12 | init(defaults: UserDefaults = .standard) { |
| 13 | self.defaults = defaults |
| 14 | self.entryIDs = defaults.stringArray(forKey: storageKey) ?? [] |
| 15 | } |
| 16 | |
| 17 | func record(_ entryID: String) { |
| 18 | entryIDs.removeAll { $0 == entryID } |
| 19 | entryIDs.insert(entryID, at: 0) |
| 20 | entryIDs = Array(entryIDs.prefix(limit)) |
| 21 | persist() |
| 22 | } |
| 23 | |
| 24 | func clear() { |
| 25 | entryIDs = [] |
| 26 | persist() |
| 27 | } |
| 28 | |
| 29 | private func persist() { |
| 30 | defaults.set(entryIDs, forKey: storageKey) |
| 31 | } |
| 32 | } |