]> git.r.bdr.sh - rbdr/map/blame_incremental - Map/Views/MapDetail.swift
Fix performance and undo
[rbdr/map] / Map / Views / MapDetail.swift
... / ...
CommitLineData
1//
2// ContentView.swift
3// Map
4//
5// Created by Ruben Beltran del Rio on 2/1/21.
6//
7
8import Combine
9import CoreData
10import SwiftUI
11
12class SaveTimer {
13 let currentTimePublisher = Timer.TimerPublisher(interval: 1, runLoop: .main, mode: .default)
14 let cancellable: AnyCancellable?
15
16 init() {
17 self.cancellable = currentTimePublisher.connect() as? AnyCancellable
18 }
19
20 deinit {
21 self.cancellable?.cancel()
22 }
23}
24
25let timer = SaveTimer()
26
27struct MapDetailView: View {
28 @Environment(\.managedObjectContext) private var viewContext
29 @Environment(\.colorScheme) var colorScheme
30
31 @EnvironmentObject var store: AppStore
32
33 @ObservedObject var map: Map
34
35 private var mapColor: MapColor {
36 MapColor.colorForScheme(colorScheme)
37 }
38
39 @State var title: String
40 @State var content: String
41
42 var body: some View {
43 if map.uuid != nil {
44 VSplitView {
45 VStack {
46 HStack {
47 TextField(
48 "Title", text: $title
49 ).font(.title2).textFieldStyle(PlainTextFieldStyle()).padding(.vertical, 4.0).padding(
50 .leading, 4.0)
51 Button(action: saveText) {
52 Image(systemName: "doc.text")
53 }.padding(.vertical, 4.0).padding(.leading, 4.0)
54 Button(action: saveImage) {
55 Image(systemName: "photo")
56 }.padding(.vertical, 4.0).padding(.leading, 4.0).padding(.trailing, 8.0)
57 }
58 EvolutionPicker()
59
60 ZStack(alignment: .topLeading) {
61 MapTextEditor(text: $content, colorScheme: colorScheme)
62 .background(mapColor.background)
63 .foregroundColor(mapColor.foreground)
64 .frame(minHeight: 96.0)
65 }.padding(.top, 8.0).padding(.leading, 8.0).background(mapColor.background).cornerRadius(
66 5.0)
67 }.padding(.horizontal, 8.0)
68 ScrollView([.horizontal, .vertical]) {
69 SlowMapRender(
70 content: content, evolution: Stage.stages(store.state.selectedEvolution),
71 colorScheme: colorScheme)
72 }.background(mapColor.background)
73 }.onReceive(timer.currentTimePublisher) { _ in
74 saveModel()
75 }.onDisappear {
76 saveModel()
77 }
78 } else {
79 DefaultMapView()
80 }
81 }
82
83 private func saveModel() {
84 map.content = content
85 map.title = title
86 try? viewContext.save()
87 }
88
89 private func saveText() {
90 store.send(.exportMapAsText(map: map))
91 }
92
93 private func saveImage() {
94 store.send(.exportMapAsImage(map: map))
95 }
96}
97
98struct MapDetailView_Previews: PreviewProvider {
99 static var previews: some View {
100 MapDetailView(map: Map(), title: "", content: "").environment(
101 \.managedObjectContext, PersistenceController.preview.container.viewContext)
102 }
103}