Sources/Orgstar/EditorView.swift
66 lines · 2637 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 options: EditingOptions
15 let onAppCommand: (String) -> Void
16
17 final class Coordinator {
18 var editor: OrgEditor?
19 var path: String?
20 var revealID = 0
21 }
22
23 func makeCoordinator() -> Coordinator { Coordinator() }
24
25 func makeNSView(context: Context) -> NSView {
26 NSView()
27 }
28
29 func updateNSView(_ container: NSView, context: Context) {
30 let coordinator = context.coordinator
31 if coordinator.path != session.path {
32 coordinator.path = session.path
33 container.subviews.forEach { $0.removeFromSuperview() }
34 coordinator.editor = nil
35 if let document = session.document {
36 let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable)
37 editor.onChange = { [weak session] in session?.bufferChanged() }
38 editor.onMessage = { [weak commands] in commands?.show($0) }
39 editor.onKeysPending = { [weak commands] keys, next in
40 commands?.pendingKeys = keys
41 commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) }
42 }
43 editor.onAppCommand = onAppCommand
44 editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) }
45 commands.editor = editor
46 let scroll = editor.makeScrollView()
47 scroll.frame = container.bounds
48 scroll.autoresizingMask = [.width, .height]
49 container.addSubview(scroll)
50 container.window?.makeFirstResponder(editor.textView)
51 coordinator.editor = editor
52 session.attach(editor)
53 }
54 }
55 if let editor = coordinator.editor {
56 if editor.keymap != keymap { editor.keymap = keymap }
57 editor.optionAsMeta = optionAsMeta
58 editor.options = options
59 }
60 container.window?.isDocumentEdited = session.isDirty
61 if let request = session.revealRequest, request.id != coordinator.revealID {
62 coordinator.revealID = request.id
63 coordinator.editor?.reveal(request.offset)
64 }
65 }
66}