diff --git a/Caps/ContentView.swift b/Caps/ContentView.swift index 46d6a4d..55c905b 100644 --- a/Caps/ContentView.swift +++ b/Caps/ContentView.swift @@ -42,6 +42,12 @@ struct ContentView: View { @State var showNewClassifierAlert = false + + @State + var showUpdateCapNameAlert = false + + @State + var updatedCapName = "" @State var isEnteringNewCapName = false @@ -119,6 +125,14 @@ struct ContentView: View { .onTapGesture { didTap(cap: cap) } + .swipeActions() { + Button { + showRenameWindow(for: cap) + } label: { + Label("Rename", systemSymbol: .pencil) + } + .tint(.purple) + } } .refreshable { refresh() @@ -252,6 +266,13 @@ struct ContentView: View { primaryButton: .default(Text("Download"), action: downloadClassifier), secondaryButton: .cancel()) } + .alert("Update name", isPresented: $showUpdateCapNameAlert, actions: { + TextField("Name", text: $updatedCapName) + Button("Update", action: saveNewCapName) + Button("Cancel", role: .cancel, action: {}) + }, message: { + Text("Please enter the new name for the cap") + }) .onChange(of: database.image) { newImage in if newImage != nil { sortType = .id @@ -332,6 +353,30 @@ struct ContentView: View { removeCapturedImage() isEnteringNewCapName = false } + + private func showRenameWindow(for cap: Cap) { + updatedCapName = cap.name + capIdOfNextPhoto = cap.id + showUpdateCapNameAlert = true + } + + private func saveNewCapName() { + defer { + capIdOfNextPhoto = nil + updatedCapName = "" + } + guard let capId = capIdOfNextPhoto else { + return + } + let name = updatedCapName.trimmingCharacters(in: .whitespacesAndNewlines) + guard name != "" else { + return + } + guard database.update(name: name, for: capId) else { + + return + } + } } struct ContentView_Previews: PreviewProvider { diff --git a/Caps/Data/Database.swift b/Caps/Data/Database.swift index af8e5f0..ae9c412 100644 --- a/Caps/Data/Database.swift +++ b/Caps/Data/Database.swift @@ -394,6 +394,17 @@ final class Database: ObservableObject { } return true } + + func update(name: String, for capId: Int) -> Bool { + guard var cap = caps[capId] else { + log("Failed to update name for missing cap \(capId)") + return false + } + cap.name = name + caps[capId] = cap + changedCaps.insert(capId) + return true + } // MARK: Uploads