yattee/Shared/Videos/ThumbnailView.swift

71 lines
1.9 KiB
Swift
Raw Normal View History

2022-12-16 21:37:30 +00:00
import CachedAsyncImage
2022-12-10 23:51:21 +00:00
import SDWebImageSwiftUI
import SwiftUI
struct ThumbnailView: View {
var url: URL?
private let thumbnails = ThumbnailsModel.shared
2022-12-10 23:51:21 +00:00
var body: some View {
2022-12-17 13:38:21 +00:00
if url != nil {
viewForThumbnailExtension
2022-12-21 20:17:02 +00:00
} else {
placeholder
2022-12-17 13:38:21 +00:00
}
2022-12-16 21:37:30 +00:00
}
var thumbnailExtension: String? {
2022-12-17 13:38:21 +00:00
guard let url,
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }
let pathComponents = urlComponents.path.components(separatedBy: ".")
guard pathComponents.count > 1 else { return nil }
return pathComponents.last
2022-12-16 21:37:30 +00:00
}
@ViewBuilder var viewForThumbnailExtension: some View {
2022-12-22 18:37:05 +00:00
if AccountsModel.shared.app != .piped, thumbnailExtension != nil {
2022-12-16 21:37:30 +00:00
if thumbnailExtension == "webp" {
webImage
} else {
asyncImageIfAvailable
}
} else {
2022-12-17 13:38:21 +00:00
webImage
2022-12-16 21:37:30 +00:00
}
}
var webImage: some View {
2022-12-11 13:00:46 +00:00
WebImage(url: url)
.resizable()
.onFailure { _ in
if let url {
thumbnails.insertUnloadable(url)
}
2022-12-10 23:51:21 +00:00
}
2022-12-16 21:37:30 +00:00
.placeholder { placeholder }
}
@ViewBuilder var asyncImageIfAvailable: some View {
2023-07-01 16:38:11 +00:00
CachedAsyncImage(url: url, urlCache: BaseCacheModel.imageCache, transaction: Transaction(animation: .default)) { phase in
switch phase {
case let .success(image):
image
.resizable()
case .failure:
placeholder.onAppear {
guard let url else { return }
thumbnails.insertUnloadable(url)
2022-12-16 21:37:30 +00:00
}
2023-07-01 16:38:11 +00:00
default:
placeholder
}
2022-12-16 21:37:30 +00:00
}
}
var placeholder: some View {
Rectangle().fill(Color("PlaceholderColor"))
2022-12-10 23:51:21 +00:00
}
}