jel/Jel/Views/Library/LibraryDetailView.swift

99 lines
2.6 KiB
Swift

//
// LibraryDetailView.swift
// Jel
//
// Created by zerocool on 12/22/23.
//
import SwiftUI
import JellyfinKit
struct LibraryDetailView: View {
@EnvironmentObject var jellyfinClient: JellyfinClientController
@StateObject var authState: AuthStateController = AuthStateController.shared
@State var library: BaseItemDto
@State var items: [BaseItemDto]? = []
@State var loading: Bool = true
@State var searchText: String = ""
@State var searchResultHints: SearchHintResult?
@State var searchResultItems: [BaseItemDto]?
let columns = [
GridItem(.adaptive(minimum: 150))
]
var body: some View {
if loading {
ProgressView()
.progressViewStyle(.circular)
} else {
EmptyView()
}
ScrollView {
LazyVGrid(columns: columns) {
// uses searchResultItems only if searchText is not empty
ForEach(!searchText.isEmpty ? (searchResultItems ?? items) ?? [] : items ?? []) {item in
NavigationLink {
ItemView(item: item)
} label: {
LibraryIconView(library: item, imageType: "Primary", width: 150)
.showCaption()
.setAspectRatio(item.primaryImageAspectRatio ?? 0.6)
.padding()
}
.buttonStyle(PlainButtonStyle())
}
}
}
.if(!loading) {view in
view.searchable(text: $searchText)
.onChange(of: searchText) {
Task {
let parameters = Paths.GetParameters(
userID: AuthStateController.shared.userId,
searchTerm: searchText.lowercased(),
parentID: library.id
)
searchResultHints = await jellyfinClient.search(parameters: parameters)
searchResultItems = items?.filter { item in
for hint in searchResultHints?.searchHints ?? [] {
if hint.name == item.name {
return true
}
}
return false
}
}
}
}
.navigationTitle(library.name ?? "Unknown")
.onAppear {
Task {
let params = Paths.GetItemsParameters(
userID: authState.userId,
parentID: library.id,
fields: [.primaryImageAspectRatio]
)
let request = Paths.getItems(parameters: params)
do {
let res = try await jellyfinClient.send(request)
items = res.value.items
items?.sort(by: {$0.name?.lowercased() ?? "" < $1.name?.lowercased() ?? ""})
loading = false
} catch {
}
}
}
}
}
//#Preview {
// LibraryDetailView(library: BaseItemDto())
//}