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)
42 .onDelete(perform: deleteMaps)
43 }.frame(minWidth: 250.0, alignment: .leading)
46 Button(action: toggleSidebar) {
47 Label("Toggle Sidebar", systemImage: "sidebar.left")
49 Button(action: addMap) {
50 Label("Add Map", systemImage: "plus")
57 private func toggleSidebar() {
58 NSApp.keyWindow?.firstResponder?.tryToPerform(
59 #selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
62 private func addMap() {
64 let newMap = Map(context: viewContext)
66 newMap.createdAt = Date()
67 newMap.title = "Map \(newMap.createdAt!.format())"
71 try viewContext.save()
73 let nsError = error as NSError
74 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
79 private func deleteMaps(offsets: IndexSet) {
82 offsets.map { maps[$0] }.forEach(viewContext.delete)
85 try viewContext.save()
87 let nsError = error as NSError
88 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
94 private let mapFormatter: DateFormatter = {
95 let formatter = DateFormatter()
96 formatter.dateStyle = .short
97 formatter.timeStyle = .none
101 struct ContentView_Previews: PreviewProvider {
102 static var previews: some View {
103 ContentView().environment(
104 \.managedObjectContext, PersistenceController.preview.container.viewContext)