5 // Created by Ruben Beltran del Rio on 2/1/21.
11 struct ContentView: View {
12 @Environment(\.managedObjectContext) private var viewContext
14 @EnvironmentObject var store: AppStore
17 sortDescriptors: [NSSortDescriptor(keyPath: \Map.createdAt, ascending: true)],
19 private var maps: FetchedResults<Map>
27 ForEach(maps) { map in
28 NavigationLink(destination: MapDetailView(map: map)) {
30 Text(map.title ?? "Untitled Map")
32 Text(mapFormatter.string(from: (map.createdAt ?? Date())))
34 .padding(.vertical, 2.0)
35 .padding(.horizontal, 4.0)
36 .background(Color.accentColor)
37 .foregroundColor(Color.black)
39 }.padding(.leading, 8.0)
41 Button(action: { store.send(.deleteMap(map: map))}) {
42 Image(systemName: "trash")
47 .onDelete(perform: deleteMaps)
48 }.frame(minWidth: 250.0, alignment: .leading)
51 Button(action: toggleSidebar) {
52 Label("Toggle Sidebar", systemImage: "sidebar.left")
54 Button(action: addMap) {
55 Label("Add Map", systemImage: "plus")
63 private func toggleSidebar() {
64 NSApp.keyWindow?.firstResponder?.tryToPerform(
65 #selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
68 private func addMap() {
70 let newMap = Map(context: viewContext)
72 newMap.createdAt = Date()
73 newMap.title = "Map \(newMap.createdAt!.format())"
77 try viewContext.save()
79 let nsError = error as NSError
80 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
85 private func deleteMaps(offsets: IndexSet) {
88 offsets.map { maps[$0] }.forEach(viewContext.delete)
91 try viewContext.save()
93 let nsError = error as NSError
94 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
100 private let mapFormatter: DateFormatter = {
101 let formatter = DateFormatter()
102 formatter.dateStyle = .short
103 formatter.timeStyle = .none
107 struct ContentView_Previews: PreviewProvider {
108 static var previews: some View {
109 ContentView().environment(
110 \.managedObjectContext, PersistenceController.preview.container.viewContext)