]> git.r.bdr.sh - rbdr/map/blame_incremental - Map/State/AppState.swift
Make delete a context action
[rbdr/map] / Map / State / AppState.swift
... / ...
CommitLineData
1import Cocoa
2import Foundation
3import SwiftUI
4
5struct AppState {
6 var selectedEvolution: StageType = .general
7}
8
9enum AppAction {
10 case selectEvolution(evolution: StageType)
11 case exportMapAsImage(map: Map)
12 case exportMapAsText(map: Map)
13 case deleteMap(map: Map)
14}
15
16func appStateReducer(state: inout AppState, action: AppAction) {
17
18 switch action {
19
20 case .selectEvolution(let evolution):
21 state.selectedEvolution = evolution
22
23 case .exportMapAsImage(let map):
24 let window = NSWindow(
25 contentRect: .init(
26 origin: .zero,
27 size: .init(
28 width: NSScreen.main!.frame.width,
29 height: NSScreen.main!.frame.height)),
30 styleMask: [.closable],
31 backing: .buffered,
32 defer: false)
33
34 window.title = map.title ?? "Untitled Map"
35 window.isOpaque = true
36 window.center()
37 window.isMovableByWindowBackground = true
38 window.makeKeyAndOrderFront(nil)
39
40 let renderView = MapRenderView(
41 content: map.content ?? "", evolution: Stage.stages(state.selectedEvolution))
42
43 let view = NSHostingView(rootView: renderView)
44 window.contentView = view
45
46 let imageRepresentation = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
47 view.cacheDisplay(in: view.bounds, to: imageRepresentation)
48 let image = NSImage(cgImage: imageRepresentation.cgImage!, size: view.bounds.size)
49
50 let dialog = NSSavePanel()
51
52 dialog.title = "Save Map"
53 dialog.showsResizeIndicator = false
54 dialog.canCreateDirectories = true
55 dialog.showsHiddenFiles = false
56 dialog.allowedFileTypes = ["png"]
57 dialog.nameFieldStringValue = map.title ?? "Untitled Map"
58
59 if dialog.runModal() == NSApplication.ModalResponse.OK {
60 let result = dialog.url
61
62 if result != nil {
63
64 image.writePNG(toURL: result!)
65 print("saved at \(result!)")
66 }
67 } else {
68 print("Cancel")
69 }
70 window.orderOut(nil)
71
72 case .exportMapAsText(let map):
73 let dialog = NSSavePanel()
74
75 dialog.title = "Save Map Text"
76 dialog.showsResizeIndicator = false
77 dialog.canCreateDirectories = true
78 dialog.showsHiddenFiles = false
79 dialog.allowedFileTypes = ["txt"]
80 dialog.nameFieldStringValue = map.title ?? "Untitled Map"
81
82 if let content = map.content {
83
84 if dialog.runModal() == NSApplication.ModalResponse.OK {
85 let result = dialog.url
86
87 if let result = result {
88 try? content.write(to: result, atomically: true, encoding: String.Encoding.utf8)
89 }
90 } else {
91 print("Cancel")
92 }
93 }
94 case .deleteMap(map: let map):
95 let context = PersistenceController.shared.container.viewContext
96 context.delete(map)
97
98 try? context.save()
99 }
100}
101
102typealias AppStore = Store<AppState, AppAction>