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