Impressia/Vernissage/Widgets/UserAvatar.swift

81 lines
2.5 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.
2023-03-28 10:35:38 +02:00
// Licensed under the Apache License 2.0.
2023-01-06 13:05:21 +01:00
//
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-03-25 11:37:02 +01:00
case mini, list, comment, profile, large
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)
2023-03-25 11:37:02 +01:00
case .large:
return .init(width: 120, height: 120)
2023-01-24 20:38:21 +01:00
}
}
}
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 {
2023-01-28 21:09:31 +01:00
if let cachedAvatar = CacheImageService.shared.get(for: accountAvatar) {
2023-01-25 15:39:04 +01:00
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
.resizable()
2023-01-25 15:39:04 +01:00
.aspectRatio(contentMode: .fit)
.clipShape(applicationState.avatarShape.shape())
2023-01-25 15:39:04 +01:00
} else if state.isLoading {
placeholderView
} else {
placeholderView
}
}
.priority(.high)
2023-01-26 15:10:47 +01:00
.task {
2023-01-28 21:09:31 +01:00
await CacheImageService.shared.download(url: accountAvatar)
2023-01-26 15:10:47 +01:00
}
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
}