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