Sources/Orgstar/EditorView.swift

397c9ad69a596cfff75844141c5e537217661eb3
orgstar/Sources/Orgstar/EditorView.swift history · blame · raw

63 lines · 2461 bytes

 1import AppKit
 2import OrgApp
 3import OrgCore
 4import OrgEditorAppKit
 5import SwiftUI
 6
 7/// The TextKit 2 editor for the session's file. A new file gets a new editor, which becomes the
 8/// session's buffer; reveal requests go to the existing one.
 9struct EditorView: NSViewRepresentable {
10    let session: DocumentSession
11    let commands: AppCommands
12    let keymap: Keymap
13    let optionAsMeta: OptionAsMeta
14    let onAppCommand: (String) -> Void
15
16    final class Coordinator {
17        var editor: OrgEditor?
18        var path: String?
19        var revealID = 0
20    }
21
22    func makeCoordinator() -> Coordinator { Coordinator() }
23
24    func makeNSView(context: Context) -> NSView {
25        NSView()
26    }
27
28    func updateNSView(_ container: NSView, context: Context) {
29        let coordinator = context.coordinator
30        if coordinator.path != session.path {
31            coordinator.path = session.path
32            container.subviews.forEach { $0.removeFromSuperview() }
33            coordinator.editor = nil
34            if let document = session.document {
35                let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable)
36                editor.onChange = { [weak session] in session?.bufferChanged() }
37                editor.onMessage = { [weak commands] in commands?.show($0) }
38                editor.onKeysPending = { [weak commands] keys, next in
39                    commands?.pendingKeys = keys
40                    commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) }
41                }
42                editor.onAppCommand = onAppCommand
43                commands.editor = editor
44                let scroll = editor.makeScrollView()
45                scroll.frame = container.bounds
46                scroll.autoresizingMask = [.width, .height]
47                container.addSubview(scroll)
48                container.window?.makeFirstResponder(editor.textView)
49                coordinator.editor = editor
50                session.attach(editor)
51            }
52        }
53        if let editor = coordinator.editor {
54            if editor.keymap != keymap { editor.keymap = keymap }
55            editor.optionAsMeta = optionAsMeta
56        }
57        container.window?.isDocumentEdited = session.isDirty
58        if let request = session.revealRequest, request.id != coordinator.revealID {
59            coordinator.revealID = request.id
60            coordinator.editor?.reveal(request.offset)
61        }
62    }
63}