Bookmarks Refactor

- Don't do async loading stuff
- Move bookmarkmanager to damus state
- Remove bookmarks update notififcation and switch to observed object
- Switch api to use events explicitly instead of strings
This commit is contained in:
William Casarin
2023-03-03 11:57:18 -05:00
parent 5423704980
commit b58baca227
12 changed files with 76 additions and 60 deletions

View File

@@ -7,44 +7,65 @@
import Foundation
class BookmarksManager {
fileprivate func get_bookmarks_key(pubkey: String) -> String {
pk_setting_key(pubkey, key: "bookmarks")
}
func load_bookmarks(pubkey: String) -> [NostrEvent] {
let key = get_bookmarks_key(pubkey: pubkey)
return (UserDefaults.standard.stringArray(forKey: key) ?? []).compactMap {
event_from_json(dat: $0)
}
}
func save_bookmarks(pubkey: String, current_value: [NostrEvent], value: [NostrEvent]) -> Bool {
let uniq_bookmarks = Array(Set(value))
if uniq_bookmarks != current_value {
let encoded = uniq_bookmarks.map(event_to_json)
UserDefaults.standard.set(encoded, forKey: get_bookmarks_key(pubkey: pubkey))
return true
}
return false
}
class BookmarksManager: ObservableObject {
private let userDefaults = UserDefaults.standard
private let pubkey: String
init(pubkey: String) {
self.pubkey = pubkey
}
var bookmarks: [String] {
private var _bookmarks: [NostrEvent]
var bookmarks: [NostrEvent] {
get {
return userDefaults.stringArray(forKey: storageKey()) ?? []
return _bookmarks
}
set {
let uniqueBookmarks = Array(Set(newValue))
if uniqueBookmarks != bookmarks {
userDefaults.set(uniqueBookmarks, forKey: storageKey())
if save_bookmarks(pubkey: pubkey, current_value: _bookmarks, value: newValue) {
self._bookmarks = newValue
self.objectWillChange.send()
}
}
}
func isBookmarked(_ string: String) -> Bool {
return bookmarks.contains(string)
init(pubkey: String) {
self._bookmarks = load_bookmarks(pubkey: pubkey)
self.pubkey = pubkey
}
func updateBookmark(_ string: String) {
if isBookmarked(string) {
bookmarks = bookmarks.filter { $0 != string }
func isBookmarked(_ ev: NostrEvent) -> Bool {
return bookmarks.contains(ev)
}
func updateBookmark(_ ev: NostrEvent) {
if isBookmarked(ev) {
bookmarks = bookmarks.filter { $0 != ev }
} else {
bookmarks.append(string)
bookmarks.append(ev)
}
}
func clearAll() {
bookmarks = []
}
private func storageKey() -> String {
pk_setting_key(pubkey, key: "bookmarks")
}
}