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>
25 ForEach(maps) { map in
26 NavigationLink(destination: MapDetailView(map: map)) {
28 Text(map.title ?? "Untitled Map")
30 Text(mapFormatter.string(from: (map.createdAt ?? Date())))
32 .padding(.vertical, 2.0)
33 .padding(.horizontal, 4.0)
34 .background(Color.accentColor)
35 .foregroundColor(Color.black)
37 }.padding(.leading, 8.0)
40 .onDelete(perform: deleteMaps)
41 }.frame(minWidth: 250.0, alignment: .leading)
44 Button(action: toggleSidebar) {
45 Label("Toggle Sidebar", systemImage: "sidebar.left")
47 Button(action: addMap) {
48 Label("Add Map", systemImage: "plus")
55 private func toggleSidebar() {
56 NSApp.keyWindow?.firstResponder?.tryToPerform(
57 #selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
60 private func addMap() {
62 let newMap = Map(context: viewContext)
64 newMap.createdAt = Date()
65 newMap.title = "Map \(newMap.createdAt!.format())"
69 try viewContext.save()
71 let nsError = error as NSError
72 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
77 private func deleteMaps(offsets: IndexSet) {
80 offsets.map { maps[$0] }.forEach(viewContext.delete)
83 try viewContext.save()
85 let nsError = error as NSError
86 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
92 private let mapFormatter: DateFormatter = {
93 let formatter = DateFormatter()
94 formatter.dateStyle = .short
95 formatter.timeStyle = .none
99 struct ContentView_Previews: PreviewProvider {
100 static var previews: some View {
101 ContentView().environment(
102 \.managedObjectContext, PersistenceController.preview.container.viewContext)