Sources/Orgstar/EditorView.swift

923f63b7fcb447d5753267b1cf81e58da6449ee6
orgstar/Sources/Orgstar/EditorView.swift history · blame · raw

45 lines · 1617 bytes

 1import AppKit
 2import OrgApp
 3import OrgEditorAppKit
 4import SwiftUI
 5
 6/// The read-only TextKit 2 editor for the session's file. A new file gets a new editor; reveal
 7/// requests and changes on disk go to the existing one, so folds survive a reload.
 8struct EditorView: NSViewRepresentable {
 9    let session: DocumentSession
10
11    final class Coordinator {
12        var editor: OrgEditor?
13        var path: String?
14        var revealID = 0
15    }
16
17    func makeCoordinator() -> Coordinator { Coordinator() }
18
19    func makeNSView(context: Context) -> NSView {
20        NSView()
21    }
22
23    func updateNSView(_ container: NSView, context: Context) {
24        let coordinator = context.coordinator
25        if coordinator.path != session.path {
26            coordinator.path = session.path
27            container.subviews.forEach { $0.removeFromSuperview() }
28            coordinator.editor = nil
29            if let document = session.document {
30                let editor = OrgEditor(document: document, frame: container.bounds, editable: false)
31                let scroll = editor.makeScrollView()
32                scroll.frame = container.bounds
33                scroll.autoresizingMask = [.width, .height]
34                container.addSubview(scroll)
35                container.window?.makeFirstResponder(editor.textView)
36                coordinator.editor = editor
37                session.attach(editor)
38            }
39        }
40        if let request = session.revealRequest, request.id != coordinator.revealID {
41            coordinator.revealID = request.id
42            coordinator.editor?.reveal(request.offset)
43        }
44    }
45}