Impressia/Vernissage/Widgets/UserAvatar.swift

78 lines
2.4 KiB
Swift
Raw Normal View History

2023-01-06 13:05:21 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
// Licensed under the MIT License.
//
import SwiftUI
2023-01-24 20:38:21 +01:00
import NukeUI
2023-01-06 13:05:21 +01:00
struct UserAvatar: View {
2023-01-24 12:22:53 +01:00
@EnvironmentObject var applicationState: ApplicationState
2023-01-24 20:38:21 +01:00
public enum Size {
2023-01-26 15:10:47 +01:00
case mini, list, comment, profile
2023-01-24 20:38:21 +01:00
public var size: CGSize {
switch self {
2023-01-26 15:10:47 +01:00
case .mini:
return .init(width: 20, height: 20)
2023-01-24 20:38:21 +01:00
case .comment:
return .init(width: 32, height: 32)
2023-01-26 15:10:47 +01:00
case .list:
return .init(width: 48, height: 48)
2023-01-24 20:38:21 +01:00
case .profile:
return .init(width: 96, height: 96)
}
}
}
public let accountAvatar: URL?
public let size: Size
public init(accountAvatar: URL?, size: Size = .list) {
self.accountAvatar = accountAvatar
self.size = size
}
2023-01-06 13:05:21 +01:00
var body: some View {
2023-01-25 15:39:04 +01:00
if let accountAvatar {
if let cachedAvatar = CacheImageService.shared.getImage(for: accountAvatar) {
cachedAvatar
.resizable()
.clipShape(applicationState.avatarShape.shape())
.aspectRatio(contentMode: .fit)
2023-01-24 20:38:21 +01:00
.frame(width: size.size.width, height: size.size.height)
} else {
2023-01-25 15:39:04 +01:00
LazyImage(url: accountAvatar) { state in
if let image = state.image {
image
.clipShape(applicationState.avatarShape.shape())
.aspectRatio(contentMode: .fit)
} else if state.isLoading {
placeholderView
} else {
placeholderView
}
}
.priority(.high)
2023-01-26 15:10:47 +01:00
.task {
await CacheImageService.shared.downloadImage(url: accountAvatar)
}
2023-01-25 15:39:04 +01:00
.frame(width: size.size.width, height: size.size.height)
2023-01-06 13:05:21 +01:00
}
2023-01-25 15:39:04 +01:00
} else {
placeholderView
.frame(width: size.size.width, height: size.size.height)
2023-01-06 13:05:21 +01:00
}
}
2023-01-24 20:38:21 +01:00
@ViewBuilder private var placeholderView: some View {
Image("Avatar")
.resizable()
.clipShape(applicationState.avatarShape.shape())
.aspectRatio(contentMode: .fit)
}
2023-01-06 13:05:21 +01:00
}