Open History to see the last commit
1import SwiftUI
2import UIKit
3import UniformTypeIdentifiers
4import Observation
5
6/// The composer's text entry is a UIKit text view because SwiftUI's text
7/// inputs expose no paste hook on iOS: the long-press Paste menu can never
8/// offer an image. Bridging `UITextView` buys the native paste menu, image
9/// paste, and internal scrolling once the draft outgrows its viewport cap.
10struct FeatureComposerTextInput: UIViewRepresentable {
11 @Binding var text: String
12 // A plain binding, not `FocusState`: SwiftUI ignores writes to a
13 // `FocusState` that no `.focused()` view registers with, and a
14 // representable cannot register. The UIKit responder state is the source
15 // of truth and this binding mirrors it for the hosts.
16 @Binding var focused: Bool
17 let placeholder: String
18 let acceptsImages: Bool
19 let isReadOnly: Bool
20 let selectionRequest: FeatureComposerTextSelectionRequest?
21 let onSelectionChange: (NSRange) -> Void
22 let onPasteImages: ([NSItemProvider]) -> Void
23 let onDismissKeyboard: (() -> Void)?
24
25 func makeCoordinator() -> Coordinator {
26 Coordinator(self)
27 }
28
29 func makeUIView(context: Context) -> FeatureComposerUITextView {
30 let textView = FeatureComposerUITextView()
31 textView.delegate = context.coordinator
32 textView.acceptsImages = acceptsImages
33 textView.isReadOnly = isReadOnly
34 textView.onPasteImages = onPasteImages
35 textView.onDismissKeyboard = onDismissKeyboard
36 if onDismissKeyboard != nil {
37 textView.installDismissPanRecognizer()
38 }
39 textView.backgroundColor = .clear
40 textView.textColor = T3Colors.uiTextPrimary
41 textView.tintColor = T3Colors.uiAccent
42 textView.font = UIFont.preferredFont(forTextStyle: .body)
43 textView.adjustsFontForContentSizeCategory = true
44 textView.smartQuotesType = .no
45 textView.smartDashesType = .no
46 // Outer padding belongs to SwiftUI. The bottom inset keeps the final
47 // insertion point above the composer controls.
48 textView.configureComposerViewport()
49 textView.textContainer.lineFragmentPadding = 0
50 textView.isScrollEnabled = true
51 // Deliberately not `keyboardDismissMode = .interactive`: the capped
52 // input sits directly above the keyboard, so scrolling up through a
53 // long draft drags into the keyboard's frame and yanks it around.
54 // Dismissal belongs to the pan recognizer below, which only fires
55 // for a drag that begins with the draft at its top.
56 textView.accessibilityIdentifier = "message-composer"
57 updateAccessibility(textView)
58 return textView
59 }
60
61 func updateUIView(_ textView: FeatureComposerUITextView, context: Context) {
62 context.coordinator.parent = self
63 textView.acceptsImages = acceptsImages
64 textView.onPasteImages = onPasteImages
65 textView.onDismissKeyboard = onDismissKeyboard
66 textView.isReadOnly = isReadOnly
67
68 let shouldApplySelection = selectionRequest.map {
69 context.coordinator.lastAppliedSelectionRequestID != $0.id
70 } ?? false
71 context.coordinator.isApplyingProgrammaticUpdate = true
72 defer {
73 context.coordinator.isApplyingProgrammaticUpdate = false
74 onSelectionChange(textView.selectedRange)
75 }
76 if textView.text != text {
77 let previousText = textView.text ?? ""
78 let selectedRange = textView.selectedRange
79 textView.text = text
80 if !shouldApplySelection {
81 let location = FeatureComposerTextSelectionPolicy.cursorLocationAfterBindingUpdate(
82 previousText: previousText,
83 newText: text,
84 selectedLocation: selectedRange.location
85 )
86 let length = previousText.isEmpty
87 ? 0
88 : min(selectedRange.length, text.utf16.count - location)
89 textView.selectedRange = NSRange(location: location, length: length)
90 textView.scrollSelectionIntoView()
91 }
92 }
93 if shouldApplySelection, let selectionRequest {
94 let location = min(selectionRequest.location, textView.text.utf16.count)
95 textView.selectedRange = NSRange(location: location, length: 0)
96 textView.scrollSelectionIntoView()
97 context.coordinator.lastAppliedSelectionRequestID = selectionRequest.id
98 }
99 updateAccessibility(textView)
100
101 if context.coordinator.lastAppliedFocus != focused {
102 context.coordinator.lastAppliedFocus = focused
103 if focused, !textView.isFirstResponder {
104 textView.becomeFirstResponderWhenAttached()
105 } else if !focused {
106 textView.cancelPendingFirstResponder()
107 if textView.isFirstResponder {
108 textView.resignFirstResponder()
109 }
110 }
111 }
112 }
113
114 func sizeThatFits(
115 _ proposal: ProposedViewSize,
116 uiView: FeatureComposerUITextView,
117 context: Context
118 ) -> CGSize? {
119 guard let width = proposal.width, width.isFinite else { return nil }
120 let fittingSize = uiView.sizeThatFits(
121 CGSize(width: width, height: .greatestFiniteMagnitude)
122 )
123 return CGSize(
124 width: width,
125 height: FeatureComposerTextInputSizing.height(
126 fittingHeight: fittingSize.height,
127 lineHeight: uiView.font?.lineHeight ?? 22,
128 availableHeight: proposal.height
129 )
130 )
131 }
132
133 private func updateAccessibility(_ textView: FeatureComposerUITextView) {
134 textView.accessibilityLabel = "Message agent"
135 textView.accessibilityHint = acceptsImages
136 ? "Enter a message or paste images"
137 : "Enter a message"
138 textView.accessibilityValue = text.isEmpty ? placeholder : text
139 }
140
141 final class Coordinator: NSObject, UITextViewDelegate {
142 var parent: FeatureComposerTextInput
143 var lastAppliedFocus: Bool?
144 var lastAppliedSelectionRequestID: UUID?
145 var isApplyingProgrammaticUpdate = false
146
147 init(_ parent: FeatureComposerTextInput) {
148 self.parent = parent
149 }
150
151 func textView(
152 _ textView: UITextView,
153 shouldChangeTextIn range: NSRange,
154 replacementText text: String
155 ) -> Bool {
156 !parent.isReadOnly
157 }
158
159 func textViewDidChange(_ textView: UITextView) {
160 guard !isApplyingProgrammaticUpdate else { return }
161 guard parent.text != textView.text else { return }
162 parent.text = textView.text
163 (textView as? FeatureComposerUITextView)?.scrollSelectionIntoView()
164 }
165
166 func textViewDidChangeSelection(_ textView: UITextView) {
167 guard !isApplyingProgrammaticUpdate else { return }
168 parent.onSelectionChange(textView.selectedRange)
169 }
170
171 func textViewDidBeginEditing(_ textView: UITextView) {
172 lastAppliedFocus = true
173 if !parent.focused {
174 parent.focused = true
175 }
176 }
177
178 func textViewDidEndEditing(_ textView: UITextView) {
179 lastAppliedFocus = false
180 if parent.focused {
181 parent.focused = false
182 }
183 }
184 }
185}
186
187/// Advertises image support to the paste menu and routes image pastes out to
188/// the attachment pipeline. Text-only pastes fall through to UIKit untouched.
189final class FeatureComposerUITextView: UITextView {
190 private static let bottomEditingInset: CGFloat = 10
191 private var lastLaidOutBoundsSize = CGSize.zero
192
193 // Changing isEditable can dismiss an open keyboard. During voice input,
194 // keep the responder and reject user edits without changing isEditable.
195 var isReadOnly = false
196
197 override var canBecomeFirstResponder: Bool {
198 (!isReadOnly || isFirstResponder) && super.canBecomeFirstResponder
199 }
200
201 override func insertText(_ text: String) {
202 guard !isReadOnly else { return }
203 super.insertText(text)
204 }
205
206 override func deleteBackward() {
207 guard !isReadOnly else { return }
208 super.deleteBackward()
209 }
210
211 override func cut(_ sender: Any?) {
212 guard !isReadOnly else { return }
213 super.cut(sender)
214 }
215
216 func configureComposerViewport() {
217 clipsToBounds = true
218 textContainerInset = UIEdgeInsets(
219 top: 0,
220 left: 0,
221 bottom: Self.bottomEditingInset,
222 right: 0
223 )
224 }
225
226 func scrollSelectionIntoView() {
227 guard bounds.width > 0, bounds.height > 0 else { return }
228 scrollRangeToVisible(selectedRange)
229 guard let selection = selectedTextRange else { return }
230
231 let caret = caretRect(for: selection.end)
232 let visibleBottom = contentOffset.y + bounds.height - Self.bottomEditingInset
233 guard caret.maxY > visibleBottom else { return }
234
235 let maximumOffset = max(
236 -adjustedContentInset.top,
237 contentSize.height + adjustedContentInset.bottom - bounds.height
238 )
239 let requestedOffset = caret.maxY + Self.bottomEditingInset - bounds.height
240 let pixelScale = traitCollection.displayScale > 0 ? traitCollection.displayScale : 1
241 let alignedOffset = ceil(requestedOffset * pixelScale) / pixelScale
242 setContentOffset(
243 CGPoint(x: contentOffset.x, y: min(maximumOffset, alignedOffset)),
244 animated: false
245 )
246 }
247
248 var acceptsImages = false {
249 didSet {
250 guard oldValue != acceptsImages else { return }
251 pasteConfiguration = acceptsImages
252 ? UIPasteConfiguration(
253 acceptableTypeIdentifiers: [
254 UTType.image.identifier,
255 UTType.text.identifier,
256 ]
257 )
258 : nil
259 }
260 }
261 var onPasteImages: (([NSItemProvider]) -> Void)?
262 var onDismissKeyboard: (() -> Void)?
263 private var wantsFirstResponderOnAttach = false
264
265 /// Programmatic focus can arrive before the view joins a window (a host
266 /// refocusing right as the composer expands); retry once attached. The
267 /// pending request is cancelled if focus clears again before the view
268 /// attaches, so a stale request can never raise the keyboard.
269 func becomeFirstResponderWhenAttached() {
270 if window != nil {
271 becomeFirstResponder()
272 } else {
273 wantsFirstResponderOnAttach = true
274 }
275 }
276
277 func cancelPendingFirstResponder() {
278 wantsFirstResponderOnAttach = false
279 }
280
281 override func didMoveToWindow() {
282 super.didMoveToWindow()
283 if window != nil, wantsFirstResponderOnAttach {
284 wantsFirstResponderOnAttach = false
285 becomeFirstResponder()
286 }
287 }
288
289 // A SwiftUI drag gesture on the composer never sees drags that start
290 // inside this view: the text interaction's own recognizers claim them at
291 // the UIKit level. This observing pan reproduces the host's
292 // drag-to-dismiss there: it recognizes alongside everything, cancels
293 // nothing, and dismisses a scrollable draft only when the drag begins at
294 // its top.
295 private let dismissPanDelegate = FeatureComposerDismissPanDelegate()
296
297 func installDismissPanRecognizer() {
298 let pan = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan))
299 pan.cancelsTouchesInView = false
300 pan.delegate = dismissPanDelegate
301 addGestureRecognizer(pan)
302 }
303
304 private var dismissPanBeganAtTop = false
305
306 @objc private func handleDismissPan(_ recognizer: UIPanGestureRecognizer) {
307 // A fast flick can jump straight from .began to .ended without a
308 // .changed in between, so the end state is evaluated too. The at-top
309 // check is latched at .began: a drag that merely reaches the top
310 // mid-scroll only rubber-bands, instead of yanking the keyboard away
311 // the moment the offset crosses zero.
312 switch recognizer.state {
313 case .began:
314 dismissPanBeganAtTop = contentOffset.y <= 0
315 return
316 case .changed, .ended: break
317 default: return
318 }
319 guard isFirstResponder else { return }
320 let translation = recognizer.translation(in: self)
321 guard FeatureComposerDragDismissPolicy.shouldDismiss(
322 translationX: translation.x,
323 translationY: translation.y,
324 isScrollable: contentOverflows,
325 isAtTop: dismissPanBeganAtTop
326 ) else { return }
327 onDismissKeyboard?()
328 }
329
330 // Scrolling stays enabled at every size: toggling `isScrollEnabled` off
331 // stops UITextView from maintaining `contentSize` on some OS versions,
332 // which left long drafts unscrollable on device. Overflow is computed
333 // fresh wherever it matters instead. A stale offset from a mid-resize
334 // selection change is still reset; with nothing to scroll, any offset
335 // clips the first line under the padding.
336 var contentOverflows: Bool {
337 contentSize.height > bounds.height + 0.5
338 }
339
340 override func layoutSubviews() {
341 let viewportChanged = lastLaidOutBoundsSize != bounds.size
342 lastLaidOutBoundsSize = bounds.size
343 super.layoutSubviews()
344 if !contentOverflows, contentOffset.y != 0 {
345 contentOffset.y = 0
346 } else if viewportChanged, isFirstResponder {
347 // `sizeThatFits` receives a proposal. The final UIKit viewport can
348 // still differ after the footer and attachments take their space.
349 // Recheck the caret against these actual bounds once per resize.
350 scrollSelectionIntoView()
351 }
352 }
353
354 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
355 if isReadOnly, action == #selector(paste(_:)) || action == #selector(cut(_:)) {
356 return false
357 }
358 if action == #selector(paste(_:)),
359 acceptsImages,
360 FeatureComposerPasteboardPolicy.containsImage(in: UIPasteboard.general) {
361 return true
362 }
363 return super.canPerformAction(action, withSender: sender)
364 }
365
366 // Drops are the other client of the paste configuration: while editing,
367 // UIKit offers the text view any drag it says it can paste. Declining
368 // image drags leaves them to the composer surface, so one target owns
369 // the session and the highlight; when the text view wins instead, the
370 // image vanishes into UITextView's text-only default and the surface's
371 // highlight never hears that the session ended.
372 override func canPaste(_ itemProviders: [NSItemProvider]) -> Bool {
373 guard !isReadOnly else { return false }
374 let holdsImage = itemProviders.contains {
375 $0.hasItemConformingToTypeIdentifier(UTType.image.identifier)
376 }
377 return holdsImage ? false : super.canPaste(itemProviders)
378 }
379
380 // When the pasteboard holds images, only the images attach. Any text
381 // riding along (a copied web image usually brings its URL) is dropped on
382 // purpose: Slack and X do the same, and inserting a stray URL next to an
383 // attached screenshot reads as a bug.
384 override func paste(_ sender: Any?) {
385 guard !isReadOnly else { return }
386 guard acceptsImages else {
387 super.paste(sender)
388 return
389 }
390 let imageProviders = UIPasteboard.general.itemProviders.filter {
391 $0.hasItemConformingToTypeIdentifier(UTType.image.identifier)
392 }
393 guard !imageProviders.isEmpty else {
394 super.paste(sender)
395 return
396 }
397 onPasteImages?(imageProviders)
398 }
399}
400
401/// A standalone delegate (rather than the text view itself, whose scroll-view
402/// superclass already takes part in gesture delegation) so the observing pan
403/// reliably recognizes alongside the text interaction's own recognizers
404/// instead of being cancelled by them.
405private final class FeatureComposerDismissPanDelegate: NSObject, UIGestureRecognizerDelegate {
406 func gestureRecognizer(
407 _ gestureRecognizer: UIGestureRecognizer,
408 shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
409 ) -> Bool {
410 true
411 }
412}
413
414/// Mirrors the thread view's composer drag-to-dismiss thresholds: a clearly
415/// vertical downward drag. While the draft is scrollable, scrolling back
416/// through it never drops the keyboard mid-read, but a drag that *begins*
417/// with the draft at its top only rubber-bands, which is unambiguous
418/// dismissal intent (and the composer's only escape hatch once it and the
419/// keyboard cover the transcript). `isAtTop` is the position at drag start,
420/// so a scroll that reaches the top never dismisses mid-gesture.
421enum FeatureComposerDragDismissPolicy {
422 static func shouldDismiss(
423 translationX: CGFloat,
424 translationY: CGFloat,
425 isScrollable: Bool,
426 isAtTop: Bool
427 ) -> Bool {
428 (!isScrollable || isAtTop)
429 && translationY > 8
430 && translationY > abs(translationX)
431 }
432}
433
434enum FeatureComposerPasteboardPolicy {
435 /// `UIPasteboard.hasImages` misses formats that merely conform to image
436 /// (HEIC screenshots among them), so detection goes through UTType
437 /// conformance instead.
438 static func containsImage(in pasteboard: UIPasteboard) -> Bool {
439 pasteboard.itemProviders.contains {
440 $0.hasItemConformingToTypeIdentifier(UTType.image.identifier)
441 }
442 }
443}
444
445/// A one-shot caret placement, applied by the text input exactly once per
446/// request `id`. Command completion issues one so the caret lands after the
447/// inserted text instead of wherever UIKit leaves it after a programmatic
448/// text replacement.
449struct FeatureComposerTextSelectionRequest: Equatable {
450 let id = UUID()
451 let location: Int
452}
453
454/// Selection changes come from `updateUIView` and UIKit delegate callbacks.
455/// Keeping this value outside Observation avoids synchronous SwiftUI state
456/// writes while the representable is updating.
457@MainActor
458@Observable
459final class FeatureComposerTextObservation {
460 @ObservationIgnored var selection = NSRange(location: 0, length: 0)
461}
462
463enum FeatureComposerTextSelectionPolicy {
464 /// UTF-16 caret location after `range` (character indices, as produced by
465 /// the trigger parser) is replaced with `replacement`.
466 static func cursorLocation(
467 afterReplacing range: Range<Int>,
468 in text: String,
469 with replacement: String
470 ) -> Int {
471 let lower = min(max(range.lowerBound, 0), text.count)
472 let lowerIndex = text.index(text.startIndex, offsetBy: lower)
473 return text[..<lowerIndex].utf16.count + replacement.utf16.count
474 }
475
476 /// Caret location after the binding changed underneath the text view. A
477 /// restored draft (previous text empty) puts the caret at the end; any
478 /// other external rewrite keeps the caret where it was, clamped into the
479 /// new text.
480 static func cursorLocationAfterBindingUpdate(
481 previousText: String,
482 newText: String,
483 selectedLocation: Int
484 ) -> Int {
485 previousText.isEmpty ? newText.utf16.count : min(selectedLocation, newText.utf16.count)
486 }
487}
488
489/// The editor grows with its content, then scrolls when it reaches the line
490/// cap or the space above the composer controls. A finite SwiftUI proposal is
491/// a hard bound. Returning a larger minimum makes the parent clip the editor
492/// under its fixed footer.
493enum FeatureComposerTextInputSizing {
494 static let maximumLines: CGFloat = 12
495
496 static func height(
497 fittingHeight: CGFloat,
498 lineHeight: CGFloat,
499 availableHeight: CGFloat? = nil
500 ) -> CGFloat {
501 let maximumHeight = max(0, lineHeight * maximumLines)
502 let contentHeight = max(0, fittingHeight)
503 guard let availableHeight, availableHeight.isFinite else {
504 return min(contentHeight, maximumHeight)
505 }
506 return min(contentHeight, maximumHeight, max(0, availableHeight))
507 }
508}