Branchwell

Jotley / app / macOS / Views / AddTagPopoverView.swift

1import SwiftUI
2import CoreData
3
4// MARK: - Add Tag Popover View
5internal struct AddTagPopoverView: View {
6 @ObservedObject var note: Note
7 @Binding var showPopover: Bool
8 @Binding var newTagText: String
9 @Binding var currentTags: [String]
10 @Binding var isEditingTags: Bool
11 var saveContext: () -> Void
12
13 @Environment(\.managedObjectContext) private var viewContext
14
15 // Helper to get the canonical form of a tag (lowercase, alphanumeric only) for de-duplication
16 private func getCanonicalTag(_ tag: String) -> String {
17 return tag.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
18 }
19
20 // Helper to format a newly entered tag for display and potential storage (mirrors PersistenceController.getFormattedTag)
21 private func getFormattedTagForDisplay(_ tag: String) -> String {
22 let spacesToDashes = tag.replacingOccurrences(of: " ", with: "-")
23 let validCharacters = CharacterSet.letters.union(CharacterSet(charactersIn: "-0123456789"))
24 return spacesToDashes.components(separatedBy: validCharacters.inverted).joined()
25 }
26
27 var body: some View {
28 VStack(spacing: 15) {
29 Text("Add New Tag")
30 .font(.headline)
31 .padding(.top, 5)
32
33 ThemedTextField(
34 text: $newTagText,
35 placeholder: "Enter tag name (letters, numbers, dashes)",
36 font: NSFont.systemFont(ofSize: NSFont.systemFontSize),
37 textColor: NSColor(Color.themeTextPrimary)
38 )
39 .padding(8)
40 .background(Color.themeContentBackground)
41 .cornerRadius(6)
42 .frame(minWidth: 200)
43 .onChange(of: newTagText) { _, newValue in
44 // Sanitize input live: preserve case and dashes, convert spaces, remove invalid chars
45 let formattedForDisplay = getFormattedTagForDisplay(newValue)
46 if newTagText != formattedForDisplay {
47 newTagText = formattedForDisplay
48 }
49 }
50
51 HStack(spacing: 12) {
52 Button {
53 let trimmedTag = newTagText.trimmingCharacters(in: .whitespacesAndNewlines)
54 let formattedTag = getFormattedTagForDisplay(trimmedTag) // Format for display/storage
55 guard !getCanonicalTag(trimmedTag).isEmpty, note.tagSet.count < LocalNoteTags.maximumCount else { return }
56 do {
57 try note.addTagByName(formattedTag, in: viewContext)
58 } catch { return }
59 currentTags = note.tagNames
60 saveContext()
61 newTagText = ""
62 isEditingTags = false
63 showPopover = false
64 } label: {
65 JotleyAccentIconLabel(title: "Add Tag", systemImage: "plus")
66 }
67 .keyboardShortcut(.defaultAction) // This is now the primary action
68 .disabled(getCanonicalTag(newTagText).isEmpty || note.tagSet.count >= LocalNoteTags.maximumCount)
69 }
70 }
71 .buttonStyle(JotleyGlassButtonStyle())
72 .padding([.horizontal, .bottom], 15)
73 .padding(.top, 10)
74 .frame(minWidth: 250, idealWidth: 280)
75 .background(Color.themeContentBackground) // Consistent with other popovers
76 .cornerRadius(8) // Consistent with other popovers
77 }
78}