aboutsummaryrefslogtreecommitdiff
path: root/Map/Views/SlowMapRender.swift
blob: b7cd8423bcf0a5786bc2de3a79157ead7509e177 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import Cocoa
import SwiftUI

class SlowMapRenderController: NSViewController {

  var content: String
  private var contentBinding: Binding<String> {
    Binding(
      get: { self.content },
      set: { content in
        self.content = content
      }
    )
  }

  var evolution: Stage
  private var evolutionBinding: Binding<Stage> {
    Binding(
      get: { self.evolution },
      set: { evolution in
        self.evolution = evolution
      }
    )
  }
  private var colorSchemeEnvironment: ObservableColorSchemeEnvironment

  private let debouncer: Debouncer = Debouncer(seconds: 0.1)

  init(content: String, evolution: Stage, colorScheme: ColorScheme) {

    self.content = content
    self.evolution = evolution
    self.colorSchemeEnvironment = ObservableColorSchemeEnvironment(colorScheme: colorScheme)
    super.init(nibName: nil, bundle: nil)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override func loadView() {

    let renderView = MapRenderView(content: self.contentBinding, evolution: self.evolutionBinding)
      .environmentObject(self.colorSchemeEnvironment)
    let hostingView = NSHostingView(rootView: renderView)

    self.view = hostingView
  }

  func update(content: String, evolution: Stage, colorScheme: ColorScheme) {
    self.debouncer.debounce {
      DispatchQueue.main.async {
        print("Updating: START")
        self.content = content
        self.evolution = evolution
        self.colorSchemeEnvironment.colorScheme = colorScheme
        print("Updating: END")
      }
    }
  }

  private class ObservableColorSchemeEnvironment: ObservableObject {
    @Published var colorScheme: ColorScheme

    init(colorScheme: ColorScheme) {
      self.colorScheme = colorScheme
    }
  }
}

struct SlowMapRender: NSViewControllerRepresentable {

  var content: String
  var evolution: Stage
  let colorScheme: ColorScheme

  func makeNSViewController(
    context: NSViewControllerRepresentableContext<SlowMapRender>
  ) -> SlowMapRenderController {
    return SlowMapRenderController(content: content, evolution: evolution, colorScheme: colorScheme)
  }

  func updateNSViewController(
    _ nsViewController: SlowMapRenderController,
    context: NSViewControllerRepresentableContext<SlowMapRender>
  ) {
    nsViewController.update(
      content: content, evolution: evolution, colorScheme: context.environment.colorScheme)
  }
}