ContentView.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. } .contextMenu {
  21. Button(action: { deleteItem(item: item) }) {
  22. Label("Delete", systemImage: "trash")
  23. }
  24. }
  25. }
  26. .onDelete(perform: deleteItems)
  27. }
  28. .navigationSplitViewColumnWidth(min: 180, ideal: 200)
  29. .toolbar {
  30. ToolbarItem {
  31. Button(action: addItem) {
  32. Label("New Category", systemImage: "plus")
  33. }
  34. }
  35. }
  36. } detail: {
  37. Text("Select an item")
  38. }
  39. }
  40. private func addItem() {
  41. withAnimation {
  42. let newItem = Category(timestamp: Date())
  43. let count = items.count(where: { $0.name.starts(with: "New Category") })
  44. if (count > 0) {
  45. newItem.name += " (\(count))"
  46. }
  47. modelContext.insert(newItem)
  48. }
  49. }
  50. private func deleteItem(item: Category) {
  51. withAnimation {
  52. modelContext.delete(item)
  53. }
  54. }
  55. private func deleteItems(offsets: IndexSet) {
  56. withAnimation {
  57. for index in offsets {
  58. modelContext.delete(items[index])
  59. }
  60. }
  61. }
  62. }
  63. #Preview {
  64. ContentView()
  65. .modelContainer(for: Category.self, inMemory: true)
  66. }