Repository navigation
Expand file tree
/
Copy pathNativeTextViewContainer.swift
More file actions
247 lines (217 loc) · 11.2 KB
/
Copy pathNativeTextViewContainer.swift
File metadata and controls
247 lines (217 loc) · 11.2 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
//
// NativeTextViewContainer.swift
// MarkdownEngine
//
// Document view of the editor's scroll view. Hosts the `NativeTextView` plus two
// optional siblings: the scroll-away header (a top band, stacked ABOVE the text view
// with a disjoint frame) and, in reading-column mode, the full-width wide-table
// overlays around the centered fixed-width column.
//
// The header is a sibling rather than a subview of the text view because a subview
// (reserving space via a `textContainerOrigin` shift) cannot be composited reliably:
// during a responsive-scroll blit the cached body bitmap and the header's own
// `NSHostingView` layer advance against slightly different origins, so the body
// drifts up over the header's lower rows. No compositing fix can unify them
// (NSHostingView always forces its own layer); with disjoint sibling frames the
// overlap is geometrically impossible.
//
// The text view sits at the container's ORIGIN; the header band and the reading
// column's offset are the container's bounds origin (#205). AppKit's Writing Tools
// overlay draws in text-view coordinates against the container's origin, so a text
// view offset inside it got its proofreading words drawn that far up and left.
// Auto Layout ignores the bounds origin, so the header clip's constraints carry it.
//
import AppKit
final class NativeTextViewContainer: NSView {
/// The body. Sizes its OWN height (content + overscroll); the container only shows
/// it below the header band and sizes itself to the sum.
weak var textView: NativeTextView? {
didSet { updateFileDropRegistration() }
}
// MARK: - File drops beside the text
/// With an `EditorFileDrop`, the whole document takes file drops: over the margins
/// beside the reading column or the header band, the drag goes to the text view,
/// which places the insertion point at the nearest text. File drop types only, so a
/// drag of text still has the text view alone.
func updateFileDropRegistration() {
let types = textView?.fileDrop != nil ? NativeTextView.fileDropTypes : []
for view in [self, headerDropCatcher].compactMap({ $0 }) {
if types.isEmpty { view.unregisterDraggedTypes() } else { view.registerForDraggedTypes(types) }
}
}
/// In front of the header band: AppKit gives a drag to the frontmost registered view,
/// and the hosted header's own (an editing title's field editor) took a dropped file
/// as its path, renaming the node. Clicks go through it (`hitTest` nil).
private final class HeaderDropCatcher: NSView {
weak var container: NativeTextViewContainer?
override func hitTest(_ point: NSPoint) -> NSView? { nil }
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { container?.draggingEntered(sender) ?? [] }
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { container?.draggingUpdated(sender) ?? [] }
override func draggingExited(_ sender: NSDraggingInfo?) { container?.draggingExited(sender) }
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { container?.prepareForDragOperation(sender) ?? false }
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { container?.performDragOperation(sender) ?? false }
override func concludeDragOperation(_ sender: NSDraggingInfo?) { container?.concludeDragOperation(sender) }
override func draggingEnded(_ sender: NSDraggingInfo) { container?.draggingEnded(sender) }
}
private var headerDropCatcher: HeaderDropCatcher?
private func installHeaderDropCatcher(over clip: NSView) {
headerDropCatcher?.removeFromSuperview()
let catcher = HeaderDropCatcher()
catcher.container = self
catcher.translatesAutoresizingMaskIntoConstraints = false
addSubview(catcher, positioned: .above, relativeTo: clip)
NSLayoutConstraint.activate([
catcher.topAnchor.constraint(equalTo: clip.topAnchor),
catcher.bottomAnchor.constraint(equalTo: clip.bottomAnchor),
catcher.leadingAnchor.constraint(equalTo: clip.leadingAnchor),
catcher.trailingAnchor.constraint(equalTo: clip.trailingAnchor),
])
headerDropCatcher = catcher
updateFileDropRegistration()
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
textView?.draggingEntered(sender) ?? []
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
textView?.draggingUpdated(sender) ?? []
}
override func draggingExited(_ sender: NSDraggingInfo?) {
textView?.draggingExited(sender)
}
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
textView?.prepareForDragOperation(sender) ?? false
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
textView?.performDragOperation(sender) ?? false
}
override func concludeDragOperation(_ sender: NSDraggingInfo?) {
textView?.concludeDragOperation(sender)
}
override func draggingEnded(_ sender: NSDraggingInfo) {
textView?.draggingEnded(sender)
}
/// Reserved header band height (mirrors the clip's resolved height). Sole driver of
/// the vertical stack: the text view shows at `y = headerHeight`.
var headerHeight: CGFloat = 0 {
didSet {
guard abs(headerHeight - oldValue) > 0.01 else { return }
if let textView {
// Band height feeds the overscroll activation — re-run the policy
// first (no re-measure; skipped when detached, e.g. teardown).
if let scrollView = enclosingScrollView {
textView.reapplyOverscrollPolicy(for: scrollView)
}
// The viewport-fill inflation depends on the band height
// (header + text view ≥ viewport); re-apply before the restack so a
// short doc never grows a phantom scroll range.
textView.applyManagedFrameSize(width: textView.frame.width)
}
restack(propagateWidth: false)
}
}
private var isRestacking = false
/// Where the reading column shows, from the container's left edge (0 in full width).
private(set) var columnOriginX: CGFloat = 0
/// The header clip's position constraints, which carry the bounds origin.
private var headerPins: (top: NSLayoutConstraint, left: NSLayoutConstraint,
right: NSLayoutConstraint)?
private weak var headerClip: NSView?
func pinHeader(_ clip: NSView, top: NSLayoutConstraint, left: NSLayoutConstraint,
right: NSLayoutConstraint) {
headerClip = clip
headerPins = (top, left, right)
applyBoundsOrigin()
installHeaderDropCatcher(over: clip)
}
func unpinHeader() {
headerClip = nil
headerPins = nil
headerDropCatcher?.removeFromSuperview()
headerDropCatcher = nil
}
func setColumnOriginX(_ x: CGFloat) {
guard x != columnOriginX else { return }
columnOriginX = x
applyBoundsOrigin()
}
/// Shows the text view at `(columnOriginX, headerHeight)` while it stays at (0, 0).
private func applyBoundsOrigin() {
let origin = NSPoint(x: -columnOriginX, y: -headerHeight)
if bounds.origin != origin {
setBoundsOrigin(origin)
// The band moves the page under a viewport that did not scroll.
textView?.revealWideTablesNearViewport()
}
guard let headerPins else { return }
headerPins.top.constant = origin.y
headerPins.left.constant = origin.x
headerPins.right.constant = origin.x
// Placed now as well: the next layout pass would leave it one frame behind the band.
headerClip?.setFrameOrigin(origin)
}
/// Flipped (top-left origin) to match `NSTextView`, so the header band is the
/// negative bounds origin above it and the text view's local space IS the
/// container's. A non-flipped container would invert the stack and break every
/// `convert(_:to:)`-based coordinate path.
override var isFlipped: Bool { true }
/// Real scrollable height = header band + the text view's real content (no
/// min-viewport inflation), so the scroll view can't scroll past actual content.
var scrollableContentHeight: CGFloat {
headerHeight + (textView?.scrollableContentHeight ?? 0)
}
/// Single layout method. Shows the text view below the header (bounds origin only —
/// never `setFrameSize`, so the text view's self-measure isn't re-triggered) and sizes the
/// container to `headerHeight + textViewHeight` (min the viewport). The header clip
/// keeps its own height; its position follows the bounds origin through its pins.
func restack(propagateWidth: Bool) {
guard !isRestacking, let textView else { return }
isRestacking = true
defer { isRestacking = false }
let w = bounds.width
// Width propagation happens ONLY from the scroll-view-driven path; a height-only
// restack must never resize the text view (that would re-measure → loop).
if propagateWidth {
if textView.configuration.readingWidth != nil {
// Reading column: the column keeps its fixed width; re-center its X
// (and shift the wide-table overlay insets) instead of resizing.
textView.centerReadingColumn(forClipWidth: w)
} else if textView.frame.width != w {
textView.setFrameSize(NSSize(width: w, height: textView.frame.height))
}
}
// Below the header band and at the column's X, through the bounds origin.
if textView.frame.origin != .zero { textView.setFrameOrigin(.zero) }
if textView.configuration.readingWidth == nil { columnOriginX = 0 }
applyBoundsOrigin()
let viewportH = enclosingScrollView?.contentView.bounds.height ?? 0
let stacked = headerHeight + textView.frame.height
let totalH = (textView.configuration.heightBehavior == .fitsContent) ? stacked
: max(stacked, viewportH)
if abs(frame.height - totalH) > 0.5 {
setFrameSize(NSSize(width: w, height: totalH))
}
}
/// The text view calls this after it self-resizes its height.
func textViewDidResize() {
guard !isRestacking else { return }
restack(propagateWidth: false)
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
// Width came from the scroll view's clip view (autoresizing); propagate it.
restack(propagateWidth: true)
}
}
extension NSScrollView {
/// Editor text view inside the container document view.
var nativeTextView: NativeTextView? {
(documentView as? NativeTextViewContainer)?.textView
}
}
extension NSView {
/// `rect` in the enclosing clip view's space, the one scroll offsets are in.
func rectInClipView(_ rect: NSRect) -> NSRect {
guard let clip = enclosingScrollView?.contentView else { return rect }
return convert(rect, to: clip)
}
}