ContentView.swift 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // ContentView.swift
  3. // Todos
  4. //
  5. // Created by Sam Jaffe on 2/28/26.
  6. //
  7. import SwiftUI
  8. import SwiftData
  9. struct ContentView: View {
  10. @Environment(\.modelContext) private var modelContext
  11. @Query private var items: [Category]
  12. var body: some View {
  13. NavigationSplitView {
  14. List {
  15. ForEach(items) { item in
  16. NavigationLink {
  17. CategoryPanelView(item: item)
  18. } label: {
  19. CategorySidebarView(name: Bindable(item).name)
  20. }
  21. }
  22. .onDelete(perform: deleteItems)
  23. }
  24. .navigationSplitViewColumnWidth(min: 180, ideal: 200)
  25. .toolbar {
  26. ToolbarItem {
  27. Button(action: addItem) {
  28. Label("New Category", systemImage: "plus")
  29. }
  30. }
  31. }
  32. } detail: {
  33. Text("Select an item")
  34. }
  35. }
  36. private func addItem() {
  37. withAnimation {
  38. let newItem = Category(timestamp: Date())
  39. let count = items.count(where: { $0.name.starts(with: "New Category") })
  40. if (count > 0) {
  41. newItem.name += " (\(count))"
  42. }
  43. modelContext.insert(newItem)
  44. }
  45. }
  46. private func deleteItems(offsets: IndexSet) {
  47. withAnimation {
  48. for index in offsets {
  49. modelContext.delete(items[index])
  50. }
  51. }
  52. }
  53. }
  54. #Preview {
  55. ContentView()
  56. .modelContainer(for: Category.self, inMemory: true)
  57. }