Repository navigation
Expand file tree
/
Copy pathNativeTextViewWrapper.swift
More file actions
948 lines (913 loc) · 54.1 KB
/
Copy pathNativeTextViewWrapper.swift
File metadata and controls
948 lines (913 loc) · 54.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//
// NativeTextViewWrapper.swift
// MarkdownEngine
//
// Created by Luca Chen on 18.02.26.
//
// Brings the editor into SwiftUI and wires up the text view with the
// right setup, styling, and callbacks.
//
// Public selection / replacement value types live in
// `NativeTextViewSelectionTypes.swift`.
import SwiftUI
import AppKit
/// SwiftUI bridge for MarkdownEngine's AppKit-backed editor.
///
/// Wraps a TextKit 2 `NSTextView` inside an `NSScrollView` and exposes a
/// SwiftUI-friendly API of bindings (text, link state, replacement requests)
/// and callback closures (link clicks, caret movement, inline-selection and
/// code-block change notifications). All visual styling and external
/// dependencies are routed through ``MarkdownEditorConfiguration``.
///
/// ### Fit-to-content height
///
/// Set ``MarkdownEditorConfiguration/heightBehavior`` to `.fitsContent` to
/// make the editor report its content height to SwiftUI instead of scrolling
/// internally. Wrap the editor in a `ScrollView` so the page scrolls:
///
/// ```swift
/// ScrollView {
/// NativeTextViewWrapper(
/// text: $text,
/// configuration: .init(heightBehavior: .fitsContent)
/// )
/// }
/// ```
///
/// In `.fitsContent` mode the editor grows/shrinks per keystroke, scroll-
/// wheel events pass through to the enclosing scroller, and caret visibility
/// propagates to the enclosing (page-level) scroll view. The reading column
/// (`readingWidth`) composes naturally. See ``MarkdownEditorConfiguration/HeightBehavior``
/// for the full behavior contract and trade-offs.
public struct NativeTextViewWrapper: NSViewRepresentable {
public typealias Coordinator = NativeTextViewCoordinator
public typealias NSViewType = NSScrollView
/// Two-way binding to the document text in storage form
/// (`[[Name|<id>]]` for wiki-links). The engine keeps display and
/// storage forms in sync internally.
@Binding public var text: String
/// Becomes `true` while the caret is inside a `[[Name]]` link's content
/// range, so embedders can show a contextual UI (e.g. a popover).
@Binding public var isWikiLinkActive: Bool
/// Push a replacement into the editor by setting this to a non-nil value;
/// the engine applies it on the next update and then clears the binding.
@Binding public var pendingInlineReplacement: InlineReplacementRequest?
/// The full editor configuration (theme + services + style toggles). Engine
/// embedders construct this themselves and pass it in; the wrapper does
/// not read UserDefaults or know about app-specific colors/services.
public var configuration: MarkdownEditorConfiguration
/// PostScript name of the base font used for body text.
public var fontName: String
/// Base font size in points. Headings, code blocks, and LaTeX are scaled
/// off this value via ``MarkdownEditorConfiguration``.
public var fontSize: CGFloat
/// Opaque document identifier. Each value keeps its own undo stack and
/// per-document editor state across switching away and back; the undo stack is
/// dropped only if the document's text changes while it is switched away. Set a
/// stable, unique value per document so undo/replacements stay scoped.
public var documentId: String
/// Keeps the editor across a removal from the view hierarchy. With a key, the
/// removed editor is parked under it — text view, undo stacks, scroll position —
/// and the next editor created with the same key takes it back, whatever
/// document it opens. AppKit's undo actions belong to the text view instance,
/// so this is what keeps ⌘Z when the embedder routes away from the editor and
/// back. One editor per key; nil (the default) builds a new one every time.
public var parkingKey: String?
/// When `false` the editor renders read-only with no caret.
public var isEditable: Bool
/// Optional two-way focus state. Changes to the binding request or release
/// first responder status; an initial request waits for window attachment.
/// Repeated values (including `.constant(true)`) do not reclaim focus.
/// Focus and blur are written back asynchronously on the main queue, including
/// removal and window closure. Focus means first responder in this editor's
/// own window, not key-window or active-app status.
/// Without a binding, focus remains entirely AppKit-managed.
public var isFocused: Binding<Bool>?
/// Optional paste hook. Return a Markdown image-embed string (e.g.
/// `"![[my-image]]"`) to insert at the caret, or `nil` to fall through
/// to the system's default plain-text paste.
public var onPasteImage: ((NSPasteboard) -> String?)?
/// Files dragged onto the text. Without it the text view keeps AppKit's own
/// drag handling. See `EditorFileDrop`.
public var fileDrop: EditorFileDrop?
/// Fires when the user clicks a `[[Name]]` link. The argument is the
/// resolved opaque identifier (or the display name when no resolver
/// was supplied).
public var onLinkClick: ((String) -> Void)?
/// Fires whenever the caret rect inside an active wiki-link changes,
/// so embedders can position a follow-the-caret UI.
public var onCaretRectChange: ((CGRect) -> Void)?
/// Reports one completed native edit in UTF-16 display-text coordinates.
/// Multi-step smart-input transformations and ambiguous composition
/// batches are omitted so embedders can treat every callback as exact.
public var onTextMutation: ((MarkdownTextMutation) -> Void)?
/// Build the editor's right-click menu (the engine ships no menu). Receives the default
/// NSMenu + the current selection range; return the menu to display (or unchanged).
public var onBuildContextMenu: ((NSMenu, NSRange) -> NSMenu)?
/// Fires when the caret enters or leaves a `[[Name]]` or `![[…]]`
/// token. `nil` means the caret is no longer inside such a token.
public var onInlineSelectionChange: ((InlineSelectionState?) -> Void)?
/// Fires on ↑/↓/Enter/Esc while an inline `[[…]]` preview is open, so the
/// embedder can drive its autocomplete list. Return `true` to consume the key.
public var onInlinePreviewKey: ((InlinePreviewKey) -> Bool)?
/// Fires when the caret's directive-completion context changes — entering
/// a directive name or one of its arguments — and with `nil` to dismiss.
/// The engine supplies the ranked candidates; the embedder draws the list
/// and routes keys back through ``onInlinePreviewKey``.
public var onDirectiveCompletion: ((DirectiveCompletionContext?) -> Void)?
/// Commit a picked directive completion. The engine applies it, places the
/// caret, and clears the binding.
@Binding public var pendingDirectiveCompletion: DirectiveCompletionRequest?
/// Fires when the set of visible code blocks changes, so embedders can
/// overlay copy buttons (see ``CodeBlockButton``).
public var onCodeBlockSelectionChange: (([CodeBlockSelection]) -> Void)?
/// Fires after the user toggles any of the three spell/grammar/auto-correction
/// menu items. Embedders persist the policy and pass it back via
/// ``MarkdownEditorConfiguration/spellChecking`` on next launch.
public var onSpellCheckingPolicyChanged: ((SpellCheckingPolicy) -> Void)?
/// Ghost text shown at the first-line position while the document is empty;
/// the first typed character hides it. Lives inside the scrolled content, so
/// it sits below the header band and tracks its expand/collapse animation.
public var placeholder: NSAttributedString?
/// SwiftUI header hosted above the body and scrolling with it. The engine owns
/// an `NSHostingView`, reserves its (intrinsic) height at the top of the text
/// content, and refreshes the hosted content on every SwiftUI update. The header
/// is a sibling of the text view in the scrolled container, so it is fully
/// interactive. Inject any required SwiftUI environment into this content
/// before passing it in.
public var header: AnyView?
/// Visible header height when collapsed — typically just the top row. Content
/// below this is clipped. The embedder measures and supplies it so the top row
/// stays fully visible while the lower content reveals/hides.
public var headerCollapsedHeight: CGFloat
/// Whether the header is expanded to its full content height or collapsed to
/// ``headerCollapsedHeight``. Toggling animates the reveal.
public var headerExpanded: Bool
/// documentIds whose scroll offset to keep; others are forgotten. `nil` keeps all.
public var retainedScrollDocumentIds: Set<String>?
/// Scroll memory that outlives the editor. The engine's own offsets live on the
/// coordinator, so an embedder that unmounts the editor entirely — routing to a
/// different screen and back — loses them; these hand the offsets somewhere that
/// survives. `persist` is called on switch-away AND on teardown, `restore` when a
/// document becomes current (nil opens at the top). Both are asked at call time,
/// so the embedder's own retention rules can see changes made on the way out.
public var onPersistScrollOffset: ((String, CGFloat) -> Void)?
public var restoreScrollOffset: ((String) -> CGFloat?)?
/// Embedder-supplied predicate that suppresses the I-beam cursor in edit mode.
/// Called on mouse-move with the event location in window coordinates.
/// Return `true` to show the arrow cursor instead of the I-beam.
public var isCursorExcluded: ((CGPoint) -> Bool)?
public init(
text: Binding<String>,
isWikiLinkActive: Binding<Bool> = .constant(false),
pendingInlineReplacement: Binding<InlineReplacementRequest?> = .constant(nil),
configuration: MarkdownEditorConfiguration = .default,
fontName: String = "SF Pro",
fontSize: CGFloat = 16,
documentId: String = "default",
parkingKey: String? = nil,
isEditable: Bool = true,
isFocused: Binding<Bool>? = nil,
onPasteImage: ((NSPasteboard) -> String?)? = nil,
fileDrop: EditorFileDrop? = nil,
onLinkClick: ((String) -> Void)? = nil,
onCaretRectChange: ((CGRect) -> Void)? = nil,
onTextMutation: ((MarkdownTextMutation) -> Void)? = nil,
onBuildContextMenu: ((NSMenu, NSRange) -> NSMenu)? = nil,
onInlineSelectionChange: ((InlineSelectionState?) -> Void)? = nil,
onInlinePreviewKey: ((InlinePreviewKey) -> Bool)? = nil,
onDirectiveCompletion: ((DirectiveCompletionContext?) -> Void)? = nil,
pendingDirectiveCompletion: Binding<DirectiveCompletionRequest?> = .constant(nil),
onCodeBlockSelectionChange: (([CodeBlockSelection]) -> Void)? = nil,
onSpellCheckingPolicyChanged: ((SpellCheckingPolicy) -> Void)? = nil,
placeholder: NSAttributedString? = nil,
header: AnyView? = nil,
headerCollapsedHeight: CGFloat = 0,
headerExpanded: Bool = true,
retainedScrollDocumentIds: Set<String>? = nil,
onPersistScrollOffset: ((String, CGFloat) -> Void)? = nil,
restoreScrollOffset: ((String) -> CGFloat?)? = nil,
isCursorExcluded: ((CGPoint) -> Bool)? = nil
) {
self._text = text
self._isWikiLinkActive = isWikiLinkActive
self._pendingInlineReplacement = pendingInlineReplacement
self.configuration = configuration
self.fontName = fontName
self.fontSize = fontSize
self.documentId = documentId
self.parkingKey = parkingKey
self.isEditable = isEditable
self.isFocused = isFocused
self.onPasteImage = onPasteImage
self.fileDrop = fileDrop
self.onLinkClick = onLinkClick
self.onCaretRectChange = onCaretRectChange
self.onTextMutation = onTextMutation
self.onBuildContextMenu = onBuildContextMenu
self.onInlineSelectionChange = onInlineSelectionChange
self.onInlinePreviewKey = onInlinePreviewKey
self.onDirectiveCompletion = onDirectiveCompletion
self._pendingDirectiveCompletion = pendingDirectiveCompletion
self.onCodeBlockSelectionChange = onCodeBlockSelectionChange
self.onSpellCheckingPolicyChanged = onSpellCheckingPolicyChanged
self.placeholder = placeholder
self.header = header
self.headerCollapsedHeight = headerCollapsedHeight
self.headerExpanded = headerExpanded
self.retainedScrollDocumentIds = retainedScrollDocumentIds
self.onPersistScrollOffset = onPersistScrollOffset
self.restoreScrollOffset = restoreScrollOffset
self.isCursorExcluded = isCursorExcluded
}
public func sizeThatFits(
_ proposal: ProposedViewSize,
nsView: NSScrollView,
context: Context
) -> CGSize? {
guard configuration.heightBehavior == .fitsContent,
let container = nsView.documentView as? NativeTextViewContainer else {
return nil
}
let width = proposal.width ?? nsView.contentView.bounds.width
// Height is taken from the most recent layout pass rather than re-measured
// at `proposal.width`. Re-measuring TextKit content at a speculative width
// inside sizeThatFits risks layout loops (TextKit relayout → frame change →
// sizeThatFits re-entry) and is expensive for large documents. In practice
// SwiftUI calls sizeThatFits after the view has already been laid out at the
// proposed width, and `invalidateIntrinsicContentSize` in
// `applyManagedFrameSize` ensures SwiftUI re-queries after every width-driven
// relayout, so the returned height stays correct.
return CGSize(width: width, height: container.scrollableContentHeight)
}
public func makeNSView(context: Context) -> NSScrollView {
if let parkingKey {
EditorParking.mounted[parkingKey, default: 0] += 1
// `makeCoordinator` already handed this view the parked coordinator; the
// first update pass brings text, configuration and document up to date.
if let parked = EditorParking.parked[parkingKey], parked.coordinator === context.coordinator {
EditorParking.parked[parkingKey] = nil
parked.scrollView.removeFromSuperview()
parked.scrollView.nativeTextView?.returnsFocusAfterParking = true
return parked.scrollView
}
}
let scrollView = ClampedScrollView()
scrollView.fitsContent = configuration.heightBehavior == .fitsContent
scrollView.borderType = .noBorder
scrollView.hasVerticalScroller = configuration.heightBehavior.wantsVerticalScroller(for: configuration.scrollers)
scrollView.hasHorizontalScroller = configuration.scrollers.hasHorizontalScroller
scrollView.autohidesScrollers = configuration.scrollers.autohidesScrollers
scrollView.drawsBackground = false
scrollView.automaticallyAdjustsContentInsets = false
scrollView.contentInsets = NSEdgeInsets(
top: configuration.safeAreaInsets.top,
left: configuration.safeAreaInsets.leading,
bottom: configuration.safeAreaInsets.bottom,
right: configuration.safeAreaInsets.trailing
)
// Let NSTextView auto-initialize its own TextKit 2 stack via init(frame:).
let textView = NativeTextView(frame: .zero)
// Configure the auto-created text container.
guard let textContainer = textView.textContainer,
let textLayoutManager = textView.textLayoutManager else {
fatalError("NSTextView did not create a TextKit 2 stack on this OS version")
}
textContainer.lineFragmentPadding = 0
if let readingWidth = configuration.readingWidth {
// Fix wrap width at readingWidth so text never re-wraps on resize; only the column's position moves.
textContainer.widthTracksTextView = false
textContainer.size = NSSize(width: readingWidth, height: .greatestFiniteMagnitude)
} else {
textContainer.widthTracksTextView = true
}
textView.textContainerInset = NSSize(
width: configuration.textInsets.horizontal,
height: configuration.textInsets.vertical
)
textContainer.heightTracksTextView = false
let layoutDelegate = MarkdownLayoutManagerDelegate()
context.coordinator.layoutDelegate = layoutDelegate
textLayoutManager.delegate = layoutDelegate
textView.configuration = configuration
textView.overscrollPercent = configuration.overscroll.percent
textView.maxOverscrollPoints = configuration.overscroll.maxPoints
textView.minOverscrollPoints = configuration.overscroll.minPoints
context.coordinator.configuration = configuration
textView.insertionPointColor = configuration.theme.bodyText
textView.isEditable = isEditable
textView.isSelectable = true
textView.isRichText = true
let initialState = WikiLinkService.makeDisplayState(from: text) { configuration.services.wikiLinks.name(forID: $0) }
textView.string = initialState.display
textView.delegate = context.coordinator
textView.isVerticallyResizable = true
textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
textView.postsFrameChangedNotifications = true
// Width and origin are driven by the container document view (see below).
textView.autoresizingMask = []
textView.backgroundColor = .clear
// Body compositing for the scroll-away header (clipsToBounds + redraw policy)
// is applied by ScrollingHeaderController when a header is first supplied, so
// header-less embedders keep AppKit's default rendering.
let font = NSFont(name: fontName, size: fontSize) ?? NSFont.systemFont(ofSize: fontSize)
textView.font = font
textView.baseFont = font
textView.allowsUndo = true
textView.isCursorExcluded = isCursorExcluded
textView.isAutomaticSpellingCorrectionEnabled = configuration.spellChecking.automaticSpellingCorrection
textView.isContinuousSpellCheckingEnabled = configuration.spellChecking.continuousSpellChecking
textView.isGrammarCheckingEnabled = configuration.spellChecking.grammarChecking
textView.isAutomaticQuoteSubstitutionEnabled = configuration.spellChecking.automaticQuoteSubstitution
textView.isAutomaticDataDetectionEnabled = true
textView.isAutomaticDashSubstitutionEnabled = false
textView.onPasteImage = onPasteImage
textView.fileDrop = fileDrop
if #available(macOS 15.1, *) {
// Inline: rewrites morph in place. On 15.1–26 the text below a rewrite dims
// for the animation: AppKit's older path wants the text view directly in the
// clip view, ours sits in the container.
textView.writingToolsBehavior = .complete
WritingToolsEditTrackerFix.install()
}
// Create TextKit 2 layout bridge
let bridge = LayoutBridge(textLayoutManager)
context.coordinator.layoutBridge = bridge
textView.layoutBridge = bridge
// The document view is ALWAYS a container (`NativeTextViewContainer`) hosting
// the text view, the optional scroll-away header (a top band stacked ABOVE the
// text view as a sibling — disjoint frames, so body/header overlap is
// geometrically impossible), and, in reading-column mode, the full-width
// wide-table overlays around the centered fixed-width column. The text view
// keeps managing its own height; the container offsets it below the header
// band and sizes itself to the sum.
let vpSize = scrollView.contentView.bounds.size
let container = NativeTextViewContainer(frame: NSRect(origin: .zero, size: vpSize))
container.autoresizingMask = [.width]
container.clipsToBounds = true
container.textView = textView
let initialWidth = configuration.readingWidth != nil ? textView.readingColumnWidth : vpSize.width
textView.frame = NSRect(x: 0, y: 0, width: initialWidth, height: textView.frame.height)
container.addSubview(textView)
scrollView.documentView = container
// Force full-document layout at init so paragraph heights are known
// upfront; otherwise TextKit 2 viewport layout causes scroll drift.
textLayoutManager.ensureLayout(for: textLayoutManager.documentRange)
scrollView.contentView.scroll(to: NSPoint(x: 0, y: -scrollView.contentInsets.top))
scrollView.clampToInsets()
scrollView.reflectScrolledClipView(scrollView.contentView)
context.coordinator.textView = textView
context.coordinator.wikiLinkMetadata = initialState.metadata
context.coordinator.onCaretRectChange = onCaretRectChange
context.coordinator.onTextMutation = onTextMutation
context.coordinator.onBuildContextMenu = onBuildContextMenu
context.coordinator.onInlineSelectionChange = onInlineSelectionChange
context.coordinator.onInlinePreviewKey = onInlinePreviewKey
context.coordinator.onDirectiveCompletion = onDirectiveCompletion
context.coordinator.onCodeBlockSelectionChange = onCodeBlockSelectionChange
context.coordinator.isFocused = isFocused
textView.onFocusChange = { [weak coordinator = context.coordinator] focused in
coordinator?.reportFocusChange(focused)
}
textView.requestedFocus = isFocused?.wrappedValue
textView.recalcOverscroll(for: scrollView)
textView.setPlaceholder(placeholder)
// Initial reading-column centering; the resize observer below handles later changes.
if configuration.readingWidth != nil {
textView.centerReadingColumn(forClipWidth: scrollView.contentView.bounds.width)
}
scrollView.contentView.postsBoundsChangedNotifications = true
var lastObservedViewportWidth = scrollView.contentView.bounds.width
// Weak, so an editor whose observers were not removed is still freed (#227).
context.coordinator.viewportObservers.append(NotificationCenter.default.addObserver(
forName: NSView.frameDidChangeNotification, object: scrollView.contentView, queue: nil
) { [weak scrollView, weak textView, weak coordinator = context.coordinator] _ in
guard let scrollView, let textView, let coordinator else { return }
textView.revealWideTablesNearViewport()
// Refresh code-block overlays only on real viewport width changes, not on TextKit height-only echoes during typing.
let newWidth = scrollView.contentView.bounds.width
if abs(newWidth - lastObservedViewportWidth) > 0.5 {
lastObservedViewportWidth = newWidth
// Re-center the column by position (no redraw) so it stays smooth during live resize.
// Read readingWidth from the live textView.configuration (a class, captured by
// reference) instead of the struct `configuration` captured by value at
// makeNSView time — the embedder may change readingWidth between updates.
if textView.configuration.readingWidth != nil {
textView.centerReadingColumn(forClipWidth: newWidth)
}
coordinator.didEnsureLayoutForCurrentDocument = false
coordinator.updateCodeBlockSelection(textView: textView)
}
// Only react with overscroll recalc when the viewport itself resizes
// (window resize). Without this guard, TextKit-induced frame changes echo
// back here and re-trigger recalcOverscroll, causing a 149pt height
// oscillation after clicks. Compare the CONTAINER (the document view) height
// to the viewport — it tracks the viewport for short docs.
guard let container = scrollView.documentView as? NativeTextViewContainer else { return }
// Read heightBehavior from the live textView.configuration (a class,
// captured by reference) — not the struct `configuration` captured by
// value at makeNSView time. Without this, a runtime .fitsContent→.scrolls
// switch leaves this closure permanently early-returning, so viewport-
// resize-driven recalcOverscroll is skipped → stale overscroll.
if textView.configuration.heightBehavior == .fitsContent {
// In .fitsContent the container is content-tall (not viewport-tall),
// so the container-vs-viewport guard below is always true — which
// would fire recalcOverscroll on every clip-view frame change. Only
// width changes need a re-measure (text re-wraps); height-only
// changes are already handled by the width-change block above.
return
}
guard abs(container.frame.height - scrollView.contentView.bounds.height) > 1 else { return }
textView.recalcOverscroll(for: scrollView)
scrollView.clampToInsets()
})
context.coordinator.viewportObservers.append(NotificationCenter.default.addObserver(
forName: NSView.boundsDidChangeNotification, object: scrollView.contentView, queue: nil
) { [weak scrollView, weak textView, weak coordinator = context.coordinator] _ in
guard let scrollView, let textView, let coordinator else { return }
textView.ensureVisibleLayout()
if coordinator.isWritingToolsActive {
coordinator.fixWritingToolsChildWindowIfNeeded(textView: textView)
}
scrollView.clampToInsets()
textView.revealWideTablesNearViewport()
coordinator.refreshActiveLinkCaretRect()
coordinator.updateCodeBlockSelection(textView: textView)
})
reconcileHeader(textView: textView, context: context)
return scrollView
}
public func updateNSView(_ nsView: NSScrollView, context: Context) {
guard let textView = nsView.nativeTextView else {
return
}
reconcileHeader(textView: textView, context: context)
let isNodeSwitch = context.coordinator.documentId != documentId
context.coordinator.dropStaleScrollRestore()
// Refreshed here, not with the other callbacks at the bottom — teardown has
// to reach the CURRENT closures even when the pass below returns early.
context.coordinator.onPersistScrollOffset = onPersistScrollOffset
context.coordinator.restoreScrollOffset = restoreScrollOffset
context.coordinator.isFocused = isFocused
textView.requestedFocus = isFocused?.wrappedValue
textView.reconcileRequestedFocus()
// Drop remembered offsets for documents no longer retained (always keep
// the current one). Only rebuilds the dict when something must go.
if let retained = retainedScrollDocumentIds {
let needsPrune = context.coordinator.scrollOffsets.keys.contains { key in
key != documentId && !retained.contains(key)
}
if needsPrune {
context.coordinator.scrollOffsets = context.coordinator.scrollOffsets.filter {
$0.key == documentId || retained.contains($0.key)
}
}
// Undo stacks are not pruned here: they follow recency (`retainUndo`),
// since a file leaves the open tabs whenever its tab switches away.
}
let wtActive: Bool = {
if #available(macOS 15.0, *), textView.isWritingToolsActive { return true }
return context.coordinator.isWritingToolsActive
}()
if wtActive && isNodeSwitch {
// Editing the storage while Writing Tools stream makes AppKit throw
// (measured on 27.0.1, popover too): switch once the session has settled.
if #available(macOS 15.2, *), let writingTools = textView.writingToolsCoordinator,
writingTools.state == .interactiveStreaming {
context.coordinator.deferNodeSwitch(until: writingTools) { [weak nsView] in
guard let nsView else { return }
self.updateNSView(nsView, context: context)
}
return
}
// Any other state ends here: left running, the session's end replays its
// ranges into the next document (NSRangeException on 27.0.1), and its
// result is dropped because the coordinator no longer counts it as active.
context.coordinator.cancelDeferredNodeSwitch()
context.coordinator.resetWritingToolsSession()
if #available(macOS 15.2, *) { textView.writingToolsCoordinator?.stopWritingTools() }
textView.endWritingToolsHide()
} else if context.coordinator.isWritingToolsActive {
// Back on the session's document: a deferred switch is void.
context.coordinator.cancelDeferredNodeSwitch()
// WT active on the same node — don't interfere with the session.
// Note: this skips the heightBehavior sync below, so a heightBehavior
// change while Writing Tools is active won't take effect until the
// session ends. WT sessions are transient and height-mode switches
// during one are not a supported use case.
return
}
textView.onPasteImage = onPasteImage
textView.fileDrop = fileDrop
textView.isCursorExcluded = isCursorExcluded
textView.setPlaceholder(placeholder)
// Sync heightBehavior across all three layers (scroll view, text view,
// coordinator) so a runtime switch fully reconfigures.
let heightBehaviorChanged = textView.configuration.heightBehavior != configuration.heightBehavior
if let clamped = nsView as? ClampedScrollView {
clamped.fitsContent = configuration.heightBehavior == .fitsContent
}
textView.configuration.heightBehavior = configuration.heightBehavior
context.coordinator.configuration.heightBehavior = configuration.heightBehavior
let desiredVerticalScroller = configuration.heightBehavior.wantsVerticalScroller(for: configuration.scrollers)
if nsView.hasVerticalScroller != desiredVerticalScroller {
nsView.hasVerticalScroller = desiredVerticalScroller
}
if nsView.hasHorizontalScroller != configuration.scrollers.hasHorizontalScroller {
nsView.hasHorizontalScroller = configuration.scrollers.hasHorizontalScroller
}
if nsView.autohidesScrollers != configuration.scrollers.autohidesScrollers {
nsView.autohidesScrollers = configuration.scrollers.autohidesScrollers
}
// When heightBehavior changes at runtime, re-measure and re-report so the
// view reconfigures immediately (inflation toggles, overscroll zeroing).
if heightBehaviorChanged {
textView.recalcOverscroll(for: nsView)
(nsView as? ClampedScrollView)?.clampToInsets()
nsView.invalidateIntrinsicContentSize()
}
// Sync rawSourceMode; a flip rebuilds in the new presentation. It
// changes display text ([[Name]] ↔ [[Name|UUID]]), so drop the doc's
// undo stack — surviving actions would replay at stale ranges.
let rawSourceModeChanged = context.coordinator.configuration.rawSourceMode != configuration.rawSourceMode
if rawSourceModeChanged {
context.coordinator.configuration.rawSourceMode = configuration.rawSourceMode
textView.configuration.rawSourceMode = configuration.rawSourceMode
textView.breakUndoCoalescing()
context.coordinator.undoManagers[documentId]?.removeAllActions()
context.coordinator.didInitialFormatting = false
// isWikiLinkActive is a SwiftUI binding — defer off the update pass
// to avoid "Modifying state during view update".
let coordinator = context.coordinator
DispatchQueue.main.async { coordinator.isWikiLinkActive = false }
}
// Sync the input-behavior toggles (auto-close pairs, list helpers).
// The keystroke handlers read textView.configuration live, but only
// makeNSView used to write it — an embedder settings change was inert
// until the editor was rebuilt. Plain assignment: a tiny value struct,
// and no rebuild is needed for it to take effect.
textView.configuration.lists = configuration.lists
context.coordinator.configuration.lists = configuration.lists
// Sync registered extensions (inline spans + fenced blocks) and directives. A change alters
// the GRAMMAR (tokens differ under the new registry), so the coordinator's parsed
// cache must drop before the restyle — the parse-layer memos invalidate
// themselves via the registry fingerprint.
//
// The fingerprint covers BOTH seams, so a directive-only change lands in this branch too —
// which means the directive list has to be copied here as well, or the restyle it triggers
// runs against the old one.
let newExtensionFingerprint = configuration.extensionRegistry.fingerprint
if newExtensionFingerprint != context.coordinator.configuration.extensionRegistry.fingerprint {
context.coordinator.configuration.extensions = configuration.extensions
textView.configuration.extensions = configuration.extensions
context.coordinator.configuration.directives = configuration.directives
textView.configuration.directives = configuration.directives
context.coordinator.configuration.directiveSettings = configuration.directiveSettings
textView.configuration.directiveSettings = configuration.directiveSettings
context.coordinator.cachedParsedDocument = nil
let fullRange = NSRange(location: 0, length: (textView.string as NSString).length)
if fullRange.length > 0 {
context.coordinator.restyleParagraphs([fullRange], in: textView)
}
}
// Reading column centers by POSITION (container subview), so the text inset is constant.
let desiredTextInset = NSSize(
width: configuration.textInsets.horizontal,
height: configuration.textInsets.vertical
)
if abs(textView.textContainerInset.width - desiredTextInset.width) > 0.5
|| abs(textView.textContainerInset.height - desiredTextInset.height) > 0.5 {
textView.textContainerInset = desiredTextInset
}
// Refresh services/theme when the embedder hands us a new configuration
// (e.g. when the available wiki-link targets change). Cheap pointer-/
// value-based comparison; full equality isn't required because the
// embedder is the source of truth.
let newImageFingerprint = configuration.services.images.fingerprint()
let newWikiFingerprint = configuration.services.wikiLinks.fingerprint()
let imageChanged = newImageFingerprint != context.coordinator.lastImageFingerprint
let wikiChanged = newWikiFingerprint != context.coordinator.lastWikiFingerprint
if imageChanged || wikiChanged {
context.coordinator.lastImageFingerprint = newImageFingerprint
context.coordinator.lastWikiFingerprint = newWikiFingerprint
context.coordinator.configuration.services = configuration.services
textView.configuration.services = configuration.services
// Only an image change needs a layout re-measure; a wiki-link rename is style-only.
if imageChanged, let tlm = textView.textLayoutManager {
tlm.invalidateLayout(for: tlm.documentRange)
}
// Restyle live tv content — full rebuild would clobber paste-fresh embeds when `text` binding hasn't caught up.
let fullRange = NSRange(location: 0, length: (textView.string as NSString).length)
if fullRange.length > 0 {
context.coordinator.restyleParagraphs([fullRange], in: textView)
}
}
textView.isEditable = isEditable
textView.isSelectable = true
// Keep the caret ink the selection handler resolved (an extension span
// can invert it); a plain bodyText reset here stomps it on every pass.
textView.insertionPointColor = isEditable
? (context.coordinator.resolvedCaretColor ?? context.coordinator.configuration.theme.bodyText)
: .clear
let fontChanged = (context.coordinator.fontName != fontName) || (context.coordinator.fontSize != fontSize)
if let pendingDirectiveCompletion {
if pendingDirectiveCompletion.documentId == documentId,
context.coordinator.lastAppliedDirectiveCompletionID != pendingDirectiveCompletion.id {
context.coordinator.applyDirectiveCompletion(pendingDirectiveCompletion, to: textView)
}
DispatchQueue.main.async {
if self.pendingDirectiveCompletion?.id == pendingDirectiveCompletion.id {
self.pendingDirectiveCompletion = nil
}
}
return
}
if let pendingInlineReplacement {
if pendingInlineReplacement.documentId == documentId,
context.coordinator.lastAppliedInlineReplacementID != pendingInlineReplacement.id {
context.coordinator.applyInlineReplacement(pendingInlineReplacement, to: textView)
}
DispatchQueue.main.async {
if self.pendingInlineReplacement?.id == pendingInlineReplacement.id {
self.pendingInlineReplacement = nil
}
}
return
}
// Never on a switch: two documents can hold the same text (two empty notes),
// and returning here left `documentId` on the old one for the editor's life.
if !isNodeSwitch
&& context.coordinator.didInitialFormatting
&& context.coordinator.lastSyncedText == text
&& !fontChanged {
return
}
if fontChanged {
context.coordinator.didInitialFormatting = false
}
// SwiftUI can hand over the new documentId one pass before its text (Nodes
// loads the file after the switch): this pass then still carries the
// outgoing document's. Read before the rebuild moves `lastSyncedText`.
let carriesOutgoingText = isNodeSwitch && text == context.coordinator.lastSyncedText
if isNodeSwitch {
// Save the outgoing document's scroll position — unless it just left
// the retained set, in which case let it reset to top next time.
if let outgoingId = context.coordinator.documentId {
let offsetY = nsView.contentView.bounds.origin.y
if retainedScrollDocumentIds?.contains(outgoingId) ?? true {
context.coordinator.scrollOffsets[outgoingId] = offsetY
}
// The embedder's store applies its own retention — it is asked live,
// so it can see what the snapshot above was taken too early to know.
onPersistScrollOffset?(outgoingId, offsetY)
}
// Per-document undo: close the OUTGOING document's open coalescing group
// (while its manager is still active), then switch the active documentId so
// `undoManager(for:)` starts vending the INCOMING document's own manager. We
// no longer clear undo here — that `removeAllActions()` is what killed Cmd+Z
// across a file switch.
textView.breakUndoCoalescing()
context.coordinator.noteUndoBaseline(for: context.coordinator.documentId, text: textView.string)
context.coordinator.noteSelection(for: context.coordinator.documentId, in: textView)
context.coordinator.documentId = documentId
context.coordinator.retainUndo(for: documentId)
context.coordinator.armScrollRestore(for: documentId)
// A stack gone stale while switched away is not judged here: this pass
// can carry another document's text or a remount's empty buffer. The
// baseline noted above is checked when the stack is used.
context.coordinator.didInitialFormatting = false
context.coordinator.didEnsureLayoutForCurrentDocument = false
context.coordinator.resetImageEmbedState()
// Drop old document's wide-table overlays synchronously.
textView.removeAllWideTableOverlays()
// And its autocorrection underlines, which AppKit keeps per view.
textView.removeCorrectionUnderlines()
// Park at top during the rebuild; the new document's own saved offset
// (if any) is restored after its height is known (see below).
nsView.contentView.scroll(to: NSPoint(x: 0, y: -nsView.contentInsets.top))
nsView.reflectScrolledClipView(nsView.contentView)
(nsView as? ClampedScrollView)?.clampToInsets()
}
let font = NSFont(name: fontName, size: fontSize) ?? NSFont.systemFont(ofSize: fontSize)
textView.font = font
textView.baseFont = font
// Skip on switch: textView.string still holds the OUTGOING doc here, so the "?"
// tag would force a full ensureLayout of the doc about to be discarded (~274ms /
// 7714 frags @346k). recalcOverscroll#2 after the rebuild measures the new doc;
// scroll is parked at top so clampToInsets below stays in range. Non-switch
// updates (font change, typing) must keep the forced full layout.
if !isNodeSwitch {
textView.recalcOverscroll(for: nsView)
}
(nsView as? ClampedScrollView)?.clampToInsets()
// Sync coordinator's font fields BEFORE the rebuild so the helper
// reads the current values from the View struct.
context.coordinator.fontName = fontName
context.coordinator.fontSize = fontSize
// The binding replaces this document's text from outside (a reload, a
// remount's empty first pass): the stack was recorded on what is shown now.
if !isNodeSwitch {
context.coordinator.noteUndoBaseline(for: documentId, text: textView.string)
}
context.coordinator.rebuildTextStorageAndStyle(
textView,
from: text,
invalidateLayout: isNodeSwitch || rawSourceModeChanged,
restoring: context.coordinator.selectionToRestore(for: documentId, text: text)
)
textView.recalcOverscroll(for: nsView)
(nsView as? ClampedScrollView)?.clampToInsets()
// Height is measured now, so restore the saved offset; clampToInsets keeps
// it in range if the document got shorter. Latched rather than gated on
// `isNodeSwitch`, because a remount is not a switch and its first pass still
// carries the embedder's empty buffer — the clamp would pull it back to top.
if context.coordinator.pendingScrollRestoreDocumentId == documentId {
context.coordinator.pendingScrollRestoreAttempts -= 1
let saved = restoreScrollOffset?(documentId) ?? context.coordinator.scrollOffsets[documentId]
if let savedY = saved {
nsView.contentView.scroll(to: NSPoint(x: nsView.contentView.bounds.origin.x, y: savedY))
nsView.reflectScrolledClipView(nsView.contentView)
(nsView as? ClampedScrollView)?.clampToInsets()
// A zero-height viewport cannot contradict any offset: with no range to
// clamp against the scroll is taken verbatim, so this is true for EVERY
// value — it says the offset was set, not that it survived. Believing it
// retires the latch before the geometry exists; the first real layout
// then clamps the reader back to the top and nothing is left to correct
// it. Measured on a remount after routing away: saved=201 actual=201
// landed=true viewportH=0.
let measured = nsView.contentView.bounds.height > 0
let landed = measured && abs(nsView.contentView.bounds.origin.y - savedY) < 1
// Also give up once the real content has had its chance, landed or
// not: an armed latch outliving the document's arrival lets a much
// later unrelated pass — ⌘+/⌘−, the raw-source toggle, a buffer
// reload — scroll the reader away from wherever they went.
// The "content has arrived" give-up needs the same proof: a non-empty
// buffer laid out into nothing has not had its chance either.
// The outgoing document's text is not this document's chance either:
// clamped against a shorter one, the offset landed short and the
// latch was gone when the document itself arrived.
let contentHadItsChance = !text.isEmpty && !carriesOutgoingText
if !measured {
// No geometry on this tick: hand it to the scroll view, which applies
// it from its own layout. Retiring the latch here is safe because the
// offset is no longer waiting on another update pass — and those stop
// coming (measured: two passes, both viewportH=0, then nothing, with
// the latch left armed forever and teardown refusing to save).
(nsView as? ClampedScrollView)?.armScrollRestore(to: savedY)
context.coordinator.pendingScrollRestoreDocumentId = nil
} else if landed || contentHadItsChance || context.coordinator.pendingScrollRestoreAttempts <= 0 {
context.coordinator.pendingScrollRestoreDocumentId = nil
} else {
// Kept for the pass that brings the document, but not for longer:
// two documents with the same text never send that pass.
context.coordinator.pendingScrollRestoreDeadline = Date(timeIntervalSinceNow: 1)
}
} else {
context.coordinator.pendingScrollRestoreDocumentId = nil
}
}
// Document rebuilds bypass textDidChange — re-derive emptiness here.
textView.refreshPlaceholderVisibility()
DispatchQueue.main.async {
context.coordinator.updateCodeBlockSelection(textView: textView)
}
context.coordinator.onCaretRectChange = onCaretRectChange
context.coordinator.onTextMutation = onTextMutation
context.coordinator.onBuildContextMenu = onBuildContextMenu
context.coordinator.onInlineSelectionChange = onInlineSelectionChange
context.coordinator.onInlinePreviewKey = onInlinePreviewKey
context.coordinator.onDirectiveCompletion = onDirectiveCompletion
context.coordinator.onCodeBlockSelectionChange = onCodeBlockSelectionChange
context.coordinator.didInitialFormatting = true
}
public func makeCoordinator() -> Coordinator {
if let parkingKey, let parked = EditorParking.parked[parkingKey] {
let coordinator = parked.coordinator
coordinator.rebind(text: $text, isWikiLinkActive: $isWikiLinkActive)
// Set at creation only; everything else refreshes on every update pass.
coordinator.onLinkClick = onLinkClick
coordinator.onSpellCheckingPolicyChanged = onSpellCheckingPolicyChanged
// Back on the parked document is not a switch, so nothing else arms this:
// the remount's empty first pass clamps the reader to the top.
coordinator.armScrollRestore(for: documentId)
return coordinator
}
let coordinator = NativeTextViewCoordinator(
text: $text,
fontName: fontName,
fontSize: fontSize,
isWikiLinkActive: $isWikiLinkActive,
onLinkClick: onLinkClick,
onInlineSelectionChange: onInlineSelectionChange
)
coordinator.documentId = documentId
coordinator.retainUndo(for: documentId)
coordinator.onPersistScrollOffset = onPersistScrollOffset
coordinator.onTextMutation = onTextMutation
coordinator.restoreScrollOffset = restoreScrollOffset
// Seeding documentId above means the first update pass is not a switch, so
// arm the restore here or a remount would always open at the top.
coordinator.armScrollRestore(for: documentId)
coordinator.configuration = configuration
coordinator.lastImageFingerprint = configuration.services.images.fingerprint()
coordinator.lastWikiFingerprint = configuration.services.wikiLinks.fingerprint()
coordinator.onCodeBlockSelectionChange = onCodeBlockSelectionChange
coordinator.onInlinePreviewKey = onInlinePreviewKey
coordinator.onDirectiveCompletion = onDirectiveCompletion
coordinator.userPrefersContinuousSpellChecking = configuration.spellChecking.continuousSpellChecking
coordinator.userPrefersGrammarChecking = configuration.spellChecking.grammarChecking
coordinator.userPrefersAutomaticSpellingCorrection = configuration.spellChecking.automaticSpellingCorrection
coordinator.userPrefersAutomaticQuoteSubstitution = configuration.spellChecking.automaticQuoteSubstitution
coordinator.onSpellCheckingPolicyChanged = onSpellCheckingPolicyChanged
coordinator.parkingKey = parkingKey
return coordinator
}
/// The editor can go away without a document switch — an embedder routing to a
/// different screen — and that is the only moment left to record where the
/// reader was; the coordinator's own offsets die with it.
public static func dismantleNSView(_ nsView: NSScrollView, coordinator: Coordinator) {
// A restore still pending means the reader was never put back where they
// were — recording the current offset would overwrite the good one with
// the mid-load position.
coordinator.dropStaleScrollRestore()
if let documentId = coordinator.documentId,
coordinator.pendingScrollRestoreDocumentId == nil {
coordinator.onPersistScrollOffset?(documentId, nsView.contentView.bounds.origin.y)
}
if !park(nsView, coordinator: coordinator) {
coordinator.stopObservingViewport()
}
}
/// Keeps a removed editor for the next one with its `parkingKey`; false when
/// the editor is let go.
private static func park(_ scrollView: NSScrollView, coordinator: Coordinator) -> Bool {
guard let key = coordinator.parkingKey else { return false }
let stillMounted = max(0, (EditorParking.mounted[key] ?? 1) - 1)
EditorParking.mounted[key] = stillMounted
// Another editor with this key is up already: it is the current one, and
// this one would come back with older state.
guard stillMounted == 0, let textView = scrollView.nativeTextView else { return false }
// Nothing may keep running into a view that is off screen.
coordinator.cancelDeferredNodeSwitch()
coordinator.resetWritingToolsSession()
if #available(macOS 15.2, *) { textView.writingToolsCoordinator?.stopWritingTools() }
textView.endWritingToolsHide()
textView.breakUndoCoalescing()
// The embedder may rewrite the file while the editor is away.
coordinator.noteUndoBaseline(for: coordinator.documentId, text: textView.string)
coordinator.noteSelection(for: coordinator.documentId, in: textView)
// An editor parked earlier and never taken back (see makeNSView) is let go here.
if let replaced = EditorParking.parked[key], replaced.coordinator !== coordinator {
replaced.coordinator.stopObservingViewport()
}
EditorParking.parked[key] = (scrollView, coordinator)
return true
}
}
/// Editors kept across a removal, by `NativeTextViewWrapper.parkingKey`.
@MainActor
enum EditorParking {
static var parked: [String: (scrollView: NSScrollView, coordinator: NativeTextViewCoordinator)] = [:]
/// Mounted editors per key: while one is up, a removed one is not kept.
static var mounted: [String: Int] = [:]
}
// MARK: - Scrolling header view
private extension NativeTextViewWrapper {
/// Host the embedder's header above the body, inside the container document
/// view. The hosted content refreshes on every SwiftUI update; build,
/// collapse/expand, and teardown live in `ScrollingHeaderController`.
///
/// **`.fitsContent` note:** The header's band height is included in the
/// reported content height (via `scrollableContentHeight`), so a static
/// header works correctly. The *collapse-on-scroll* animation is driven by
/// the inner scroll offset, which is always zero in `.fitsContent` (no
/// internal scrolling), so the collapse never triggers. Combining a
/// collapsing header with `.fitsContent` is allowed but the collapse
/// behavior is not meaningful.
func reconcileHeader(textView: NSTextView, context: Context) {
let coord = context.coordinator
guard let container = (textView as? NativeTextView)?.superview as? NativeTextViewContainer else { return }
guard let header else {
if let controller = coord.headerController {
controller.remove(from: container)
coord.headerController = nil
}
return
}
let controller = coord.headerController ?? ScrollingHeaderController()
coord.headerController = controller
// A document switch re-lays the header out at the new document's height a few
// milliseconds later. That is not a disclosure and must not be revealed — see
// `snapNextHeightChange`. Read before `updateNSView` advances the coordinator's
// `documentId`, so this is the switch's own pass.
if coord.documentId != documentId {
controller.snapNextHeightChange()
}
controller.reconcile(
header: header,
collapsedHeight: headerCollapsedHeight,
expanded: headerExpanded,
container: container
)
}
}