yattee/Apple TV/SearchView.swift

36 lines
884 B
Swift
Raw Normal View History

2021-06-28 15:02:13 +00:00
import Defaults
2021-06-28 10:43:07 +00:00
import Siesta
2021-06-11 12:36:26 +00:00
import SwiftUI
struct SearchView: View {
2021-06-28 15:02:13 +00:00
@Default(.searchQuery) var query
2021-06-11 21:11:59 +00:00
2021-06-28 10:43:07 +00:00
@ObservedObject private var store = Store<[Video]>()
2021-06-11 12:36:26 +00:00
var body: some View {
2021-06-28 10:43:07 +00:00
VideosView(videos: store.collection)
2021-06-11 21:11:59 +00:00
.searchable(text: $query)
2021-06-28 15:02:13 +00:00
.onAppear {
queryChanged(new: query)
}
2021-06-28 10:43:07 +00:00
.onChange(of: query) { newQuery in
2021-06-28 15:02:13 +00:00
queryChanged(old: query, new: newQuery)
2021-06-28 10:43:07 +00:00
}
2021-06-11 12:36:26 +00:00
}
2021-06-11 21:54:00 +00:00
2021-06-28 15:02:13 +00:00
func queryChanged(old: String? = nil, new: String) {
if old != nil {
let oldResource = resource(old!)
oldResource.removeObservers(ownedBy: store)
}
2021-06-28 10:43:07 +00:00
let resource = resource(new)
resource.addObserver(store)
resource.loadIfNeeded()
}
2021-06-11 12:36:26 +00:00
2021-06-28 10:43:07 +00:00
func resource(_ query: String) -> Resource {
InvidiousAPI.shared.search(query)
2021-06-11 12:36:26 +00:00
}
}