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