yattee/Apple TV/SearchView.swift

71 lines
2.0 KiB
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-07-07 22:39:18 +00:00
@Default(.searchQuery) private var queryText
@Default(.searchSortOrder) private var searchSortOrder
@Default(.searchDate) private var searchDate
@Default(.searchDuration) private var searchDuration
2021-06-11 21:11:59 +00:00
2021-06-28 10:43:07 +00:00
@ObservedObject private var store = Store<[Video]>()
2021-07-07 22:39:18 +00:00
@ObservedObject private var query = SearchQuery()
2021-06-28 10:43:07 +00:00
2021-06-11 12:36:26 +00:00
var body: some View {
2021-07-07 22:39:18 +00:00
VStack {
if !store.collection.isEmpty {
VideosView(videos: store.collection)
2021-06-28 15:02:13 +00:00
}
2021-07-07 22:39:18 +00:00
if store.collection.isEmpty && !resource.isLoading {
Text("No results")
if searchFiltersActive {
Button("Reset search filters") {
Defaults.reset(.searchDate, .searchDuration)
}
}
Spacer()
2021-06-28 10:43:07 +00:00
}
2021-07-07 22:39:18 +00:00
}
.searchable(text: $queryText)
.onAppear {
changeQuery {
query.query = queryText
query.sortBy = searchSortOrder
query.date = searchDate
query.duration = searchDuration
}
}
.onChange(of: queryText) { queryText in
changeQuery { query.query = queryText }
}
.onChange(of: searchSortOrder) { order in
changeQuery { query.sortBy = order }
}
.onChange(of: searchDate) { date in
changeQuery { query.date = date }
}
.onChange(of: searchDuration) { duration in
changeQuery { query.duration = duration }
}
2021-06-11 12:36:26 +00:00
}
2021-06-11 21:54:00 +00:00
2021-07-07 22:39:18 +00:00
func changeQuery(_ change: @escaping () -> Void = {}) {
resource.removeObservers(ownedBy: store)
change()
2021-06-28 10:43:07 +00:00
resource.addObserver(store)
resource.loadIfNeeded()
}
2021-06-11 12:36:26 +00:00
2021-07-07 22:39:18 +00:00
var resource: Resource {
2021-06-28 10:43:07 +00:00
InvidiousAPI.shared.search(query)
2021-06-11 12:36:26 +00:00
}
2021-07-07 22:39:18 +00:00
var searchFiltersActive: Bool {
searchDate != nil || searchDuration != nil
}
2021-06-11 12:36:26 +00:00
}