TagBarView.swift 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //
  2. // TagBarView.swift
  3. // Todos
  4. //
  5. // Created by Sam Jaffe on 2/28/26.
  6. //
  7. import SwiftUI
  8. import SwiftData
  9. struct TagBarView: View {
  10. @Environment(\.modelContext) private var modelContext
  11. @Binding var task: Task
  12. @AppStorage(UserDefaultsKeys.UrlHints) var allHints = CodableArray<URLHint>()
  13. @State private var active: String = ""
  14. @FocusState private var isFocused: Bool
  15. var body: some View {
  16. HStack {
  17. ForEach($task.tags) { tag in
  18. let url = allHints.filter({ $0.matches(tag.wrappedValue) })
  19. .first?.url(tag.wrappedValue)
  20. if url != nil {
  21. Link(destination: url!) {
  22. Label("", systemImage: "link")
  23. }
  24. .padding(.leading, -8)
  25. .padding(.trailing, -10)
  26. }
  27. TextField("", text: tag.id)
  28. .focused($isFocused)
  29. .onChange(of: isFocused) {
  30. task.tags.removeAll(where: { $0.id.isEmpty })
  31. }
  32. }
  33. .scaledToFit()
  34. TextField("Tag", text: $active)
  35. .onSubmit(addItem)
  36. }
  37. }
  38. private func addItem() {
  39. if !active.isEmpty && !task.tags.contains(where: { $0.like(active) }) {
  40. let newTag = Tag(id: active, parent: task)
  41. modelContext.insert(newTag)
  42. task.tags.append(newTag)
  43. }
  44. active = ""
  45. }
  46. }
  47. #Preview {
  48. @Previewable @State var task = Task()
  49. TagBarView(task: $task)
  50. }