Impressia/Vernissage/Widgets/ImageCarouselPicture.swift

61 lines
2.3 KiB
Swift
Raw Normal View History

2023-01-26 15:10:47 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
2023-03-28 10:35:38 +02:00
// Licensed under the Apache License 2.0.
2023-01-26 15:10:47 +01:00
//
2023-01-26 15:10:47 +01:00
import SwiftUI
2023-04-07 14:20:12 +02:00
import ClientKit
2023-04-07 14:38:50 +02:00
import ServicesKit
2023-04-07 16:59:18 +02:00
import WidgetsKit
2023-01-26 15:10:47 +01:00
struct ImageCarouselPicture: View {
@ObservedObject public var attachment: AttachmentModel
2023-09-16 10:39:21 +02:00
@State private var blurredImageHeight: Double
@State private var blurredImageWidth: Double
private let onImageDownloaded: (AttachmentModel, Data) -> Void
init(attachment: AttachmentModel, onImageDownloaded: @escaping (_: AttachmentModel, _: Data) -> Void) {
2023-01-26 15:10:47 +01:00
self.attachment = attachment
self.onImageDownloaded = onImageDownloaded
2023-09-16 10:39:21 +02:00
if let size = ImageSizeService.shared.get(for: attachment.url) {
let imageSize = ImageSizeService.shared.calculate(width: size.width, height: size.height)
self.blurredImageHeight = imageSize.height
self.blurredImageWidth = imageSize.width
} else if let imageWidth = attachment.metaImageWidth, let imageHeight = attachment.metaImageHeight {
let imageSize = ImageSizeService.shared.calculate(width: Double(imageWidth), height: Double(imageHeight))
self.blurredImageHeight = imageSize.height
self.blurredImageWidth = imageSize.width
} else {
self.blurredImageHeight = 100.0
self.blurredImageWidth = 100.0
}
2023-01-26 15:10:47 +01:00
}
2023-01-26 15:10:47 +01:00
var body: some View {
if let data = attachment.data, let image = UIImage(data: data) {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
} else {
BlurredImage(blurhash: attachment.blurhash)
2023-09-16 10:39:21 +02:00
.frame(width: self.blurredImageWidth, height: self.blurredImageHeight)
2023-01-26 15:10:47 +01:00
.task {
do {
// Download image and recalculate exif data.
if let imageData = try await RemoteFileService.shared.fetchData(url: attachment.url) {
self.onImageDownloaded(attachment, imageData)
}
} catch {
2023-03-13 13:53:36 +01:00
ErrorService.shared.handle(error, message: "global.error.errorDuringImageDownload")
2023-01-26 15:10:47 +01:00
}
}
}
}
}