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
29 destination: MapDetailView(map: map, title: map.title ?? "", content: map.content ?? "")
32 Text(map.title ?? "Untitled Map")
34 Text(mapFormatter.string(from: (map.createdAt ?? Date())))
36 .padding(.vertical, 2.0)
37 .padding(.horizontal, 4.0)
38 .background(Color.accentColor)
39 .foregroundColor(Color.black)
41 }.padding(.leading, 8.0)
44 action: { store.send(.deleteMap(map: map)) },
46 Image(systemName: "trash")
51 .onDelete(perform: deleteMaps)
52 }.frame(minWidth: 250.0, alignment: .leading)
55 Button(action: toggleSidebar) {
56 Label("Toggle Sidebar", systemImage: "sidebar.left")
58 Button(action: addMap) {
59 Label("Add Map", systemImage: "plus")
67 private func toggleSidebar() {
68 NSApp.keyWindow?.firstResponder?.tryToPerform(
69 #selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
72 private func addMap() {
74 let newMap = Map(context: viewContext)
76 newMap.createdAt = Date()
77 newMap.title = "Map \(newMap.createdAt!.format())"
81 try viewContext.save()
83 let nsError = error as NSError
84 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
89 private func deleteMaps(offsets: IndexSet) {
92 offsets.map { maps[$0] }.forEach(viewContext.delete)
95 try viewContext.save()
97 let nsError = error as NSError
98 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
104 private let mapFormatter: DateFormatter = {
105 let formatter = DateFormatter()
106 formatter.dateStyle = .short
107 formatter.timeStyle = .none
111 struct ContentView_Previews: PreviewProvider {
112 static var previews: some View {
113 ContentView().environment(
114 \.managedObjectContext, PersistenceController.preview.container.viewContext)