122 lines
3.9 KiB
Swift
122 lines
3.9 KiB
Swift
import SwiftUI
|
|
|
|
struct CapImagesView: View {
|
|
|
|
private let imageSize: CGFloat = 70
|
|
|
|
@Binding
|
|
var cap: Cap?
|
|
|
|
@Binding
|
|
var isPresented: Bool
|
|
|
|
@State
|
|
private var selectedCap: CapImage?
|
|
|
|
|
|
init(cap: Binding<Cap?>, database: Database, isPresented: Binding<Bool>) {
|
|
self.database = database
|
|
self._cap = cap
|
|
self._isPresented = isPresented
|
|
}
|
|
|
|
let database: Database
|
|
|
|
var images: [CapImage] {
|
|
guard let cap else {
|
|
return []
|
|
}
|
|
return (0..<cap.imageCount).map {
|
|
cap.image(version: $0)
|
|
}
|
|
}
|
|
|
|
var title: String {
|
|
guard let cap else {
|
|
return "Images"
|
|
}
|
|
return "Cap \(cap.id)"
|
|
}
|
|
|
|
var body: some View {
|
|
GeometryReader { geo in
|
|
VStack {
|
|
HStack {
|
|
Text(title).font(.title2).bold()
|
|
Spacer()
|
|
Button(action: { isPresented = false }) {
|
|
Image(systemSymbol: .xmarkCircleFill)
|
|
.foregroundColor(.gray)
|
|
.font(.system(size: 26))
|
|
}
|
|
}
|
|
let gridItem = GridItem(.flexible(), spacing: 10, alignment: .leading)
|
|
ScrollView(.vertical) {
|
|
LazyVGrid(columns: [gridItem, gridItem, gridItem, gridItem]) {
|
|
ForEach(images) { item in
|
|
ZStack(alignment: .topLeading) {
|
|
CachedCapImage(
|
|
item,
|
|
check: { database.images.cachedImage(item) },
|
|
fetch: { await database.images.image(item) },
|
|
content: { $0.resizable() },
|
|
placeholder: { ProgressView() })
|
|
.frame(width: imageSize,
|
|
height: imageSize)
|
|
.clipShape(Circle())
|
|
.onLongPressGesture { selectedCap = item }
|
|
if item.version == cap?.mainImage {
|
|
Image(systemSymbol: .checkmarkCircleFill)
|
|
.foregroundColor(.green)
|
|
.background(Color.white)
|
|
.clipShape(Circle())
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|
|
.padding(.horizontal)
|
|
}
|
|
.actionSheet(item: $selectedCap) { item in
|
|
ActionSheet(title: Text("Image \(item.version)"), buttons: [
|
|
.default(Text("Set as main image")) { setMainImage(item) },
|
|
.destructive(Text("Delete image")) { delete(image: item) },
|
|
.cancel()
|
|
])
|
|
}
|
|
}
|
|
|
|
private func delete(image: CapImage) {
|
|
Task {
|
|
guard let cap = await database.setMainImage(image.version, for: image.cap) else {
|
|
return
|
|
}
|
|
DispatchQueue.main.async {
|
|
self.cap = cap
|
|
}
|
|
}
|
|
selectedCap = nil
|
|
}
|
|
|
|
private func setMainImage(_ image: CapImage) {
|
|
Task {
|
|
guard let cap = await database.setMainImage(image.version, for: image.cap) else {
|
|
return
|
|
}
|
|
DispatchQueue.main.async {
|
|
self.cap = cap
|
|
#warning("Update all images and rows with the cap")
|
|
}
|
|
}
|
|
self.selectedCap = nil
|
|
}
|
|
}
|
|
|
|
struct CapImagesView_Previews: PreviewProvider {
|
|
static var previews: some View {
|
|
CapImagesView(cap: .constant(.init(id: 123, name: "Some")), database: .mock, isPresented: .constant(true))
|
|
}
|
|
}
|