Impressia/Vernissage/Widgets/UserAvatar.swift

75 lines
2.3 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 {
case list, comment, profile
public var size: CGSize {
switch self {
case .list:
return .init(width: 48, height: 48)
case .comment:
return .init(width: 32, height: 32)
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-24 20:38:21 +01:00
Group {
if let accountAvatar {
if let cachedAvatar = CacheImageService.shared.getImage(for: accountAvatar) {
cachedAvatar
2023-01-18 18:41:42 +01:00
.resizable()
2023-01-24 12:22:53 +01:00
.clipShape(applicationState.avatarShape.shape())
2023-01-18 18:41:42 +01:00
.aspectRatio(contentMode: .fit)
2023-01-24 20:38:21 +01:00
.frame(width: size.size.width, height: size.size.height)
2023-01-18 18:41:42 +01:00
} else {
2023-01-24 20:38:21 +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)
.frame(width: size.size.width, height: size.size.height)
2023-01-18 18:41:42 +01:00
}
2023-01-24 20:38:21 +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
}