aboutsummaryrefslogtreecommitdiff
path: root/Map/Views/MapTextEditor.swift
blob: 7251c59460d8b4c6fe306c688cc5d70796edc033 (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
import Cocoa
import SwiftUI

class MapTextEditorController: NSViewController {

  @Binding var text: String

  init(text: Binding<String>) {
    self._text = text
    super.init(nibName: nil, bundle: nil)
  }

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

  override func loadView() {
    let scrollView = NSTextView.scrollableTextView()
    let textView = scrollView.documentView as! NSTextView

    scrollView.translatesAutoresizingMaskIntoConstraints = false

    textView.delegate = self
    textView.string = self.text
    textView.isEditable = true
    textView.font = .monospacedSystemFont(ofSize: 16.0, weight: .regular)
    self.view = scrollView
  }

  override func viewDidAppear() {
    self.view.window?.makeFirstResponder(self.view)
  }
}

extension MapTextEditorController: NSTextViewDelegate {

  func textDidChange(_ obj: Notification) {
    if let textField = obj.object as? NSTextView {
      self.text = textField.string
    }
  }

  func textView(_ view: NSTextView, shouldChangeTextIn: NSRange, replacementString: String?) -> Bool
  {
    let range = Range(shouldChangeTextIn, in: view.string)
    let target = view.string[range!]

    if target == "--" {
      return false
    }

    return true
  }
}

struct MapTextEditor: NSViewControllerRepresentable {

  @Binding var text: String

  func makeNSViewController(
    context: NSViewControllerRepresentableContext<MapTextEditor>
  ) -> MapTextEditorController {
    return MapTextEditorController(text: $text)
  }

  func updateNSViewController(
    _ nsViewController: MapTextEditorController,
    context: NSViewControllerRepresentableContext<MapTextEditor>
  ) {
  }
}