]> git.r.bdr.sh - rbdr/map/blob - Map/Views/ContentView.swift
Add code for first release
[rbdr/map] / Map / Views / ContentView.swift
1 //
2 // ContentView.swift
3 // Map
4 //
5 // Created by Ruben Beltran del Rio on 2/1/21.
6 //
7
8 import CoreData
9 import SwiftUI
10
11 struct ContentView: View {
12 @Environment(\.managedObjectContext) private var viewContext
13
14 @FetchRequest(
15 sortDescriptors: [NSSortDescriptor(keyPath: \Map.createdAt, ascending: true)],
16 animation: .default)
17 private var maps: FetchedResults<Map>
18
19 var body: some View {
20 NavigationView {
21 List {
22 if maps.count == 0 {
23 DefaultMapView()
24 }
25 ForEach(maps) { map in
26 NavigationLink(destination: MapDetailView(map: map)) {
27 HStack {
28 Text(map.title ?? "Untitled Map")
29 Spacer()
30 Text(mapFormatter.string(from: (map.createdAt ?? Date())))
31 .font(.caption)
32 .padding(.vertical, 2.0)
33 .padding(.horizontal, 4.0)
34 .background(Color.accentColor)
35 .foregroundColor(Color.black)
36 .cornerRadius(2.0)
37 }.padding(.leading, 8.0)
38 }
39 }
40 .onDelete(perform: deleteMaps)
41 }.frame(minWidth: 250.0, alignment: .leading)
42 .toolbar {
43 HStack {
44 Button(action: toggleSidebar) {
45 Label("Toggle Sidebar", systemImage: "sidebar.left")
46 }
47 Button(action: addMap) {
48 Label("Add Map", systemImage: "plus")
49 }
50 }
51 }
52 }
53 }
54
55 private func toggleSidebar() {
56 NSApp.keyWindow?.firstResponder?.tryToPerform(
57 #selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
58 }
59
60 private func addMap() {
61 withAnimation {
62 let newMap = Map(context: viewContext)
63 newMap.uuid = UUID()
64 newMap.createdAt = Date()
65 newMap.title = "Map \(newMap.createdAt!.format())"
66 newMap.content = ""
67
68 do {
69 try viewContext.save()
70 } catch {
71 let nsError = error as NSError
72 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
73 }
74 }
75 }
76
77 private func deleteMaps(offsets: IndexSet) {
78
79 withAnimation {
80 offsets.map { maps[$0] }.forEach(viewContext.delete)
81
82 do {
83 try viewContext.save()
84 } catch {
85 let nsError = error as NSError
86 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
87 }
88 }
89 }
90 }
91
92 private let mapFormatter: DateFormatter = {
93 let formatter = DateFormatter()
94 formatter.dateStyle = .short
95 formatter.timeStyle = .none
96 return formatter
97 }()
98
99 struct ContentView_Previews: PreviewProvider {
100 static var previews: some View {
101 ContentView().environment(
102 \.managedObjectContext, PersistenceController.preview.container.viewContext)
103 }
104 }