Sources/Orgstar/EditorView.swift

c857dec17c1cf7a45952149fa2e48b69fad2ae25
orgstar/Sources/Orgstar/EditorView.swift history · blame · raw

102 lines · 4420 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import OrgEditorAppKit
  5import OrgPresentation
  6import OrgHighlight
  7import SwiftUI
  8
  9/// The TextKit 2 editors for the session's buffers: one per open file, kept while another
 10/// shows so its caret, folds and undo stay. An editor becomes its buffer's live state; reveal
 11/// requests go to the one showing.
 12struct EditorView: NSViewRepresentable {
 13    /// One highlighter for every editor: it caches compiled grammars and results.
 14    static let highlighter = TreeSitterHighlighter()
 15
 16    let session: DocumentSession
 17    let commands: AppCommands
 18    let keymap: Keymap
 19    let modal: Bool
 20    let optionAsMeta: OptionAsMeta
 21    let options: EditingOptions
 22    let showMarkup: Bool
 23    let showLineNumbers: Bool
 24    let theme: ThemeSpec
 25    let onAppCommand: (String) -> Void
 26    let onExternal: (ExternalRequest) -> Void
 27
 28    final class Coordinator {
 29        var editor: OrgEditor?
 30        var path: String?
 31        var revealID = 0
 32        /// Editors of open buffers, with their scroll views.
 33        var editors: [String: (editor: OrgEditor, scroll: NSScrollView)] = [:]
 34    }
 35
 36    func makeCoordinator() -> Coordinator { Coordinator() }
 37
 38    func makeNSView(context: Context) -> NSView {
 39        NSView()
 40    }
 41
 42    func updateNSView(_ container: NSView, context: Context) {
 43        let coordinator = context.coordinator
 44        // Buffers that were killed take their editors with them.
 45        for path in coordinator.editors.keys where !session.openPaths.contains(path) {
 46            coordinator.editors[path]?.scroll.removeFromSuperview()
 47            coordinator.editors[path] = nil
 48        }
 49        if coordinator.path != session.path {
 50            coordinator.path = session.path
 51            container.subviews.forEach { $0.removeFromSuperview() }
 52            coordinator.editor = nil
 53            if let path = session.path, let shown = coordinator.editors[path] ?? makeEditor(container) {
 54                coordinator.editors[path] = shown
 55                shown.scroll.frame = container.bounds
 56                container.addSubview(shown.scroll)
 57                container.window?.makeFirstResponder(shown.editor.textView)
 58                coordinator.editor = shown.editor
 59                commands.editor = shown.editor
 60                session.attach(shown.editor)
 61            } else {
 62                commands.editor = nil
 63            }
 64        }
 65        if let editor = coordinator.editor {
 66            if editor.keymap != keymap { editor.keymap = keymap }
 67            editor.modal = modal
 68            editor.optionAsMeta = optionAsMeta
 69            editor.options = options
 70            editor.showMarkup = showMarkup
 71            editor.showLineNumbers = showLineNumbers
 72            editor.themeSpec = theme
 73        }
 74        container.window?.isDocumentEdited = !session.dirtyPaths.isEmpty
 75        if let request = session.revealRequest, request.id != coordinator.revealID {
 76            coordinator.revealID = request.id
 77            coordinator.editor?.reveal(request.offset)
 78        }
 79    }
 80
 81    /// An editor for the current buffer, which becomes the buffer's live state.
 82    private func makeEditor(_ container: NSView) -> (editor: OrgEditor, scroll: NSScrollView)? {
 83        guard let document = session.document else { return nil }
 84        let mode: OrgEditor.Mode = session.isOrg ? .org : .plain(language: session.path.flatMap(FileTypes.language))
 85        let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable, highlighter: Self.highlighter, mode: mode)
 86        let path = session.path ?? ""
 87        editor.onChange = { [weak session] in session?.bufferChanged(path) }
 88        editor.onMessage = { [weak commands] in commands?.show($0) }
 89        editor.onKeysPending = { [weak commands] keys, next in
 90            commands?.pendingKeys = keys
 91            commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) }
 92        }
 93        editor.onModeChange = { [weak commands] in commands?.editorState = $0 }
 94        editor.onSelectionChange = { [weak commands] in commands?.selection = $0 }
 95        editor.onAppCommand = onAppCommand
 96        editor.onExternal = onExternal
 97        editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) }
 98        let scroll = editor.makeScrollView()
 99        scroll.autoresizingMask = [.width, .height]
100        return (editor, scroll)
101    }
102}