5 // Created by Ruben Beltran del Rio on 2/1/21.
11 struct ContentView: View {
12 @Environment(\.managedObjectContext) private var viewContext
15 sortDescriptors: [NSSortDescriptor(keyPath: \Map.createdAt, ascending: true)],
17 private var maps: FetchedResults<Map>
22 ForEach(maps) { map in
23 NavigationLink(destination: MapDetailView(map: map)) {
25 Text(map.title ?? "Untitled Map")
26 Text(map.createdAt!.format())
28 .foregroundColor(Color.accentColor)
32 .onDelete(perform: deleteMaps)
36 Button(action: toggleSidebar) {
37 Label("Toggle Sidebar", systemImage: "sidebar.left")
39 Button(action: addMap) {
40 Label("Add Map", systemImage: "plus")
47 private func toggleSidebar() {
48 NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
51 private func addMap() {
53 let newMap = Map(context: viewContext)
55 newMap.createdAt = Date()
56 newMap.title = "Map \(newMap.createdAt!.format())"
60 try viewContext.save()
62 // Replace this implementation with code to handle the error appropriately.
63 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
64 let nsError = error as NSError
65 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
70 private func deleteMaps(offsets: IndexSet) {
72 offsets.map { maps[$0] }.forEach(viewContext.delete)
75 try viewContext.save()
77 // Replace this implementation with code to handle the error appropriately.
78 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
79 let nsError = error as NSError
80 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
86 private let mapFormatter: DateFormatter = {
87 let formatter = DateFormatter()
88 formatter.dateStyle = .short
89 formatter.timeStyle = .medium
93 struct ContentView_Previews: PreviewProvider {
94 static var previews: some View {
95 ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)