Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FeatureComposerTextInput.swift

835 lines33.6 KB

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 skills: [FeatureProviderSkill]
21 let selectionRequest: FeatureComposerTextSelectionRequest?
22 let onSelectionChange: (NSRange) -> Void
23 let onPasteImages: ([NSItemProvider]) -> Void
24 let onDismissKeyboard: (() -> Void)?
25 var maximumPastedTextBytes: Int? = nil
26 var onPasteTextAttachment: ((String, @escaping @MainActor () -> Bool) -> Void)? = nil
27 var onPasteTextError: ((String) -> Void)? = nil
28 var draftOwnerID: String = ""
29 var onCopyContext: ((String) throws -> Bool)? = nil
30 var onPasteContext: ((ComposerContextClipboard.Content, String, NSRange) -> Void)? = nil
31​
32 func makeCoordinator() -> Coordinator {
33 Coordinator(self)
34 }
35​
36 func makeUIView(context: Context) -> FeatureComposerUITextView {
37 let textView = FeatureComposerUITextView()
38 textView.delegate = context.coordinator
39 textView.acceptsImages = acceptsImages
40 textView.isReadOnly = isReadOnly
41 textView.onPasteImages = onPasteImages
42 textView.onDismissKeyboard = onDismissKeyboard
43 textView.maximumPastedTextBytes = maximumPastedTextBytes
44 textView.onPasteTextAttachment = onPasteTextAttachment
45 textView.draftOwnerID = draftOwnerID
46 textView.onPasteTextError = onPasteTextError
47 textView.onCopySelection = { selected in
48 try onCopyContext?(FeatureInlineSkillProjection.plainText(from: selected)) ?? false
49 }
50 textView.onCopyError = onPasteTextError
51 textView.onPasteContext = onPasteContext
52 if onDismissKeyboard != nil {
53 textView.installDismissPanRecognizer()
54 }
55 textView.backgroundColor = .clear
56 textView.textColor = T3Colors.uiTextPrimary
57 textView.tintColor = T3Colors.uiAccent
58 textView.font = UIFont.preferredFont(forTextStyle: .body)
59 textView.adjustsFontForContentSizeCategory = true
60 textView.smartQuotesType = .no
61 textView.smartDashesType = .no
62 // Outer padding belongs to SwiftUI. The bottom inset keeps the final
63 // insertion point above the composer controls.
64 textView.configureComposerViewport()
65 textView.textContainer.lineFragmentPadding = 0
66 textView.isScrollEnabled = true
67 // Deliberately not `keyboardDismissMode = .interactive`: the capped
68 // input sits directly above the keyboard, so scrolling up through a
69 // long draft drags into the keyboard's frame and yanks it around.
70 // Dismissal belongs to the pan recognizer below, which only fires
71 // for a drag that begins with the draft at its top.
72 textView.accessibilityIdentifier = "message-composer"
73 updateAccessibility(textView)
74 return textView
75 }
76​
77 func updateUIView(_ textView: FeatureComposerUITextView, context: Context) {
78 context.coordinator.parent = self
79 textView.acceptsImages = acceptsImages
80 textView.onPasteImages = onPasteImages
81 textView.onDismissKeyboard = onDismissKeyboard
82 textView.maximumPastedTextBytes = maximumPastedTextBytes
83 textView.onPasteTextAttachment = onPasteTextAttachment
84 textView.draftOwnerID = draftOwnerID
85 textView.onPasteTextError = onPasteTextError
86 textView.onCopySelection = { selected in
87 try onCopyContext?(FeatureInlineSkillProjection.plainText(from: selected)) ?? false
88 }
89 textView.onCopyError = onPasteTextError
90 textView.onPasteContext = onPasteContext
91 textView.isReadOnly = isReadOnly
92​
93 let previousAttributedText = textView.attributedText ?? NSAttributedString()
94 let previousText = FeatureInlineSkillProjection.plainText(from: previousAttributedText)
95 let previousSelection = FeatureInlineSkillProjection.plainRange(
96 for: textView.selectedRange,
97 in: previousAttributedText
98 )
99 let shouldApplySelection = selectionRequest.map {
100 context.coordinator.lastAppliedSelectionRequestID != $0.id
101 } ?? false
102 context.coordinator.isApplyingProgrammaticUpdate = true
103 defer {
104 context.coordinator.isApplyingProgrammaticUpdate = false
105 onSelectionChange(FeatureInlineSkillProjection.plainRange(
106 for: textView.selectedRange,
107 in: textView.attributedText
108 ))
109 }
110 let targetSelection: NSRange
111 if shouldApplySelection, let selectionRequest {
112 targetSelection = NSRange(
113 location: min(selectionRequest.location, text.utf16.count),
114 length: 0
115 )
116 } else if previousText != text {
117 let location = FeatureComposerTextSelectionPolicy.cursorLocationAfterBindingUpdate(
118 previousText: previousText,
119 newText: text,
120 selectedLocation: previousSelection.location
121 )
122 let length = previousText.isEmpty
123 ? 0
124 : min(previousSelection.length, text.utf16.count - location)
125 targetSelection = NSRange(location: location, length: length)
126 } else {
127 targetSelection = previousSelection
128 }
129​
130 let rebuiltText = context.coordinator.synchronizeInlineSkills(
131 in: textView,
132 source: text,
133 selection: targetSelection
134 )
135 if shouldApplySelection, let selectionRequest {
136 textView.selectedRange = FeatureInlineSkillProjection.displayRange(
137 for: targetSelection,
138 in: textView.attributedText
139 )
140 textView.scrollSelectionIntoView()
141 context.coordinator.lastAppliedSelectionRequestID = selectionRequest.id
142 } else if rebuiltText {
143 textView.scrollSelectionIntoView()
144 }
145 updateAccessibility(textView)
146​
147 if context.coordinator.lastAppliedFocus != focused {
148 context.coordinator.lastAppliedFocus = focused
149 if focused, !textView.isFirstResponder {
150 textView.becomeFirstResponderWhenAttached()
151 } else if !focused {
152 textView.cancelPendingFirstResponder()
153 if textView.isFirstResponder {
154 textView.resignFirstResponder()
155 }
156 }
157 }
158 }
159​
160 func sizeThatFits(
161 _ proposal: ProposedViewSize,
162 uiView: FeatureComposerUITextView,
163 context: Context
164 ) -> CGSize? {
165 guard let width = proposal.width, width.isFinite else { return nil }
166 let fittingSize = uiView.sizeThatFits(
167 CGSize(width: width, height: .greatestFiniteMagnitude)
168 )
169 return CGSize(
170 width: width,
171 height: FeatureComposerTextInputSizing.height(
172 fittingHeight: fittingSize.height,
173 lineHeight: uiView.font?.lineHeight ?? 22,
174 availableHeight: proposal.height
175 )
176 )
177 }
178​
179 private func updateAccessibility(_ textView: FeatureComposerUITextView) {
180 textView.accessibilityLabel = "Message agent"
181 textView.accessibilityHint = acceptsImages
182 ? "Enter a message or paste images"
183 : "Enter a message"
184 textView.accessibilityValue = text.isEmpty ? placeholder : text
185 }
186​
187 final class Coordinator: NSObject, UITextViewDelegate {
188 private struct UndoSnapshot: Equatable {
189 let source: String
190 let selection: NSRange
191 let trailingSkill: FeatureInlineSkillDescriptor?
192 }
193​
194 var parent: FeatureComposerTextInput
195 var lastAppliedFocus: Bool?
196 var lastAppliedSelectionRequestID: UUID?
197 var isApplyingProgrammaticUpdate = false
198 private var isSynchronizingInlineSkills = false
199 private var pendingUndoSnapshot: UndoSnapshot?
200 private weak var disabledUndoManager: UndoManager?
201​
202 init(_ parent: FeatureComposerTextInput) {
203 self.parent = parent
204 }
205​
206 func textView(
207 _ textView: UITextView,
208 shouldChangeTextIn range: NSRange,
209 replacementText text: String
210 ) -> Bool {
211 guard !parent.isReadOnly else { return false }
212 guard !isApplyingProgrammaticUpdate, !isSynchronizingInlineSkills else {
213 return true
214 }
215 if pendingUndoSnapshot == nil {
216 pendingUndoSnapshot = undoSnapshot(in: textView)
217 }
218 if disabledUndoManager == nil,
219 let undoManager = textView.undoManager,
220 undoManager.isUndoRegistrationEnabled {
221 undoManager.disableUndoRegistration()
222 disabledUndoManager = undoManager
223 }
224 return true
225 }
226​
227 func textViewDidChange(_ textView: UITextView) {
228 restoreUndoRegistration()
229 guard !isApplyingProgrammaticUpdate else { return }
230 guard !isSynchronizingInlineSkills else { return }
231 let source = FeatureInlineSkillProjection.plainText(from: textView.attributedText)
232 if parent.text != source {
233 parent.text = source
234 }
235 guard textView.markedTextRange == nil,
236 let composerTextView = textView as? FeatureComposerUITextView else {
237 return
238 }
239 let selection = FeatureInlineSkillProjection.plainRange(
240 for: textView.selectedRange,
241 in: textView.attributedText
242 )
243 _ = synchronizeInlineSkills(
244 in: composerTextView,
245 source: source,
246 selection: selection
247 )
248 let updatedSnapshot = undoSnapshot(in: textView)
249 if let pendingUndoSnapshot, pendingUndoSnapshot != updatedSnapshot {
250 registerUndo(
251 restoring: pendingUndoSnapshot,
252 inverse: updatedSnapshot,
253 in: composerTextView
254 )
255 }
256 pendingUndoSnapshot = nil
257 composerTextView.scrollSelectionIntoView()
258 }
259​
260 @discardableResult
261 func synchronizeInlineSkills(
262 in textView: FeatureComposerUITextView,
263 source: String,
264 selection: NSRange,
265 preservingTrailing restoredTrailingSkill: FeatureInlineSkillDescriptor? = nil
266 ) -> Bool {
267 // Replacing attributed text would commit or discard active IME composition.
268 guard textView.markedTextRange == nil else { return false }
269 let currentText = textView.attributedText ?? NSAttributedString()
270 let currentSource = FeatureInlineSkillProjection.plainText(from: currentText)
271 let currentSignatures = FeatureInlineSkillProjection.signatures(in: currentText)
272 let preservedTrailing = restoredTrailingSkill ?? (
273 currentSource == source ? currentSignatures.last?.descriptor : nil
274 )
275 let descriptors = FeatureInlineSkillParser.descriptors(
276 in: source,
277 skills: parent.skills,
278 allowsEndBoundary: false,
279 preservingTrailing: preservedTrailing
280 )
281 let font = textView.font ?? UIFont.preferredFont(forTextStyle: .body)
282 let desiredSignatures = FeatureInlineSkillPillRenderer.signatures(
283 for: descriptors,
284 font: font,
285 traits: textView.traitCollection
286 )
287 guard currentSource != source || currentSignatures != desiredSignatures else {
288 return false
289 }
290​
291 let baseAttributes: [NSAttributedString.Key: Any] = [
292 .font: font,
293 .foregroundColor: T3Colors.uiTextPrimary,
294 ]
295 let attributedText = FeatureInlineSkillPillRenderer.attributedText(
296 source: source,
297 descriptors: descriptors,
298 baseAttributes: baseAttributes,
299 font: font,
300 traits: textView.traitCollection
301 )
302 isSynchronizingInlineSkills = true
303 textView.attributedText = attributedText
304 textView.selectedRange = FeatureInlineSkillProjection.displayRange(
305 for: selection,
306 in: attributedText
307 )
308 textView.typingAttributes = baseAttributes
309 isSynchronizingInlineSkills = false
310 return true
311 }
312​
313 func textViewDidChangeSelection(_ textView: UITextView) {
314 guard !isApplyingProgrammaticUpdate, !isSynchronizingInlineSkills else { return }
315 let selection = FeatureInlineSkillProjection.plainRange(
316 for: textView.selectedRange,
317 in: textView.attributedText
318 )
319 parent.onSelectionChange(selection)
320 }
321​
322 func textView(
323 _ textView: UITextView,
324 editMenuForTextIn range: NSRange,
325 suggestedActions: [UIMenuElement]
326 ) -> UIMenu? {
327 guard !parent.isReadOnly, UIPasteboard.general.hasStrings,
328 let composerTextView = textView as? FeatureComposerUITextView else {
329 return UIMenu(children: suggestedActions)
330 }
331 let pasteAsText = UIAction(title: "Paste as Text") { [weak composerTextView] _ in
332 composerTextView?.pasteAsText(nil)
333 }
334 return UIMenu(children: suggestedActions + [pasteAsText])
335 }
336​
337 func textViewDidBeginEditing(_ textView: UITextView) {
338 lastAppliedFocus = true
339 if !parent.focused {
340 parent.focused = true
341 }
342 }
343​
344 func textViewDidEndEditing(_ textView: UITextView) {
345 restoreUndoRegistration()
346 pendingUndoSnapshot = nil
347 lastAppliedFocus = false
348 if parent.focused {
349 parent.focused = false
350 }
351 }
352​
353 private func undoSnapshot(in textView: UITextView) -> UndoSnapshot {
354 let source = FeatureInlineSkillProjection.plainText(from: textView.attributedText)
355 let trailingSkill = FeatureInlineSkillProjection.signatures(in: textView.attributedText)
356 .last?.descriptor
357 return UndoSnapshot(
358 source: source,
359 selection: FeatureInlineSkillProjection.plainRange(
360 for: textView.selectedRange,
361 in: textView.attributedText
362 ),
363 trailingSkill: trailingSkill.flatMap {
364 NSMaxRange($0.range) == source.utf16.count ? $0 : nil
365 }
366 )
367 }
368​
369 private func restoreUndoRegistration() {
370 if let disabledUndoManager,
371 !disabledUndoManager.isUndoRegistrationEnabled {
372 disabledUndoManager.enableUndoRegistration()
373 }
374 disabledUndoManager = nil
375 }
376​
377 private func registerUndo(
378 restoring snapshot: UndoSnapshot,
379 inverse: UndoSnapshot,
380 in textView: FeatureComposerUITextView
381 ) {
382 guard let undoManager = textView.undoManager else { return }
383 let opensUndoGroup = undoManager.groupingLevel == 0
384 if opensUndoGroup {
385 undoManager.beginUndoGrouping()
386 }
387 undoManager.registerUndo(withTarget: self) { [weak textView] coordinator in
388 guard let textView else { return }
389 coordinator.restore(
390 snapshot,
391 inverse: inverse,
392 in: textView
393 )
394 }
395 undoManager.setActionName("Typing")
396 if opensUndoGroup {
397 undoManager.endUndoGrouping()
398 }
399 }
400​
401 private func restore(
402 _ snapshot: UndoSnapshot,
403 inverse: UndoSnapshot,
404 in textView: FeatureComposerUITextView
405 ) {
406 registerUndo(restoring: inverse, inverse: snapshot, in: textView)
407 isApplyingProgrammaticUpdate = true
408 _ = synchronizeInlineSkills(
409 in: textView,
410 source: snapshot.source,
411 selection: snapshot.selection,
412 preservingTrailing: snapshot.trailingSkill
413 )
414 parent.text = snapshot.source
415 parent.onSelectionChange(snapshot.selection)
416 isApplyingProgrammaticUpdate = false
417 textView.scrollSelectionIntoView()
418 }
419 }
421​
422/// Routes images and large text pastes to attachments. Ordinary text keeps
423/// UIKit's native paste behavior.
424final class FeatureComposerUITextView: FeatureInlineSkillTextView {
425 private static let bottomEditingInset: CGFloat = 10
426 private var lastLaidOutBoundsSize = CGSize.zero
427​
428 // Changing isEditable can dismiss an open keyboard. During voice input,
429 // keep the responder and reject user edits without changing isEditable.
430 var isReadOnly = false
431​
432 override var canBecomeFirstResponder: Bool {
433 (!isReadOnly || isFirstResponder) && super.canBecomeFirstResponder
434 }
435​
436 override func insertText(_ text: String) {
437 guard !isReadOnly else { return }
438 super.insertText(text)
439 }
440​
441 override func deleteBackward() {
442 guard !isReadOnly else { return }
443 super.deleteBackward()
444 }
445​
446 override func cut(_ sender: Any?) {
447 guard !isReadOnly else { return }
448 super.cut(sender)
449 }
450​
451 func configureComposerViewport() {
452 clipsToBounds = true
453 textContainerInset = UIEdgeInsets(
454 top: 0,
455 left: 0,
456 bottom: Self.bottomEditingInset,
457 right: 0
458 )
459 }
460​
461 func scrollSelectionIntoView() {
462 guard bounds.width > 0, bounds.height > 0 else { return }
463 scrollRangeToVisible(selectedRange)
464 guard let selection = selectedTextRange else { return }
465​
466 let caret = caretRect(for: selection.end)
467 let visibleBottom = contentOffset.y + bounds.height - Self.bottomEditingInset
468 guard caret.maxY > visibleBottom else { return }
469​
470 let maximumOffset = max(
471 -adjustedContentInset.top,
472 contentSize.height + adjustedContentInset.bottom - bounds.height
473 )
474 let requestedOffset = caret.maxY + Self.bottomEditingInset - bounds.height
475 let pixelScale = traitCollection.displayScale > 0 ? traitCollection.displayScale : 1
476 let alignedOffset = ceil(requestedOffset * pixelScale) / pixelScale
477 setContentOffset(
478 CGPoint(x: contentOffset.x, y: min(maximumOffset, alignedOffset)),
479 animated: false
480 )
481 }
482​
483 var acceptsImages = false {
484 didSet {
485 guard oldValue != acceptsImages else { return }
486 pasteConfiguration = acceptsImages
487 ? UIPasteConfiguration(
488 acceptableTypeIdentifiers: [
489 UTType.image.identifier,
490 UTType.text.identifier,
491 ]
492 )
493 : nil
494 }
495 }
496 var onPasteImages: (([NSItemProvider]) -> Void)?
497 var onDismissKeyboard: (() -> Void)?
498 var maximumPastedTextBytes: Int?
499 var onPasteTextAttachment: ((String, @escaping @MainActor () -> Bool) -> Void)?
500 var draftOwnerID = ""
501 private var pastedTextRequestID = UUID()
502 var onPasteTextError: ((String) -> Void)?
503 var onPasteContext: ((ComposerContextClipboard.Content, String, NSRange) -> Void)?
504 private var wantsFirstResponderOnAttach = false
505​
506 override var keyCommands: [UIKeyCommand]? {
507 let pasteAsTextCommand = UIKeyCommand(
508 input: "v",
509 modifierFlags: [.command, .shift],
510 action: #selector(pasteAsText(_:))
511 )
512 pasteAsTextCommand.discoverabilityTitle = "Paste as Text"
513 pasteAsTextCommand.wantsPriorityOverSystemBehavior = true
514 return (super.keyCommands ?? []) + [pasteAsTextCommand]
515 }
516​
517 /// Programmatic focus can arrive before the view joins a window (a host
518 /// refocusing right as the composer expands); retry once attached. The
519 /// pending request is cancelled if focus clears again before the view
520 /// attaches, so a stale request can never raise the keyboard.
521 func becomeFirstResponderWhenAttached() {
522 if window != nil {
523 becomeFirstResponder()
524 } else {
525 wantsFirstResponderOnAttach = true
526 }
527 }
528​
529 func cancelPendingFirstResponder() {
530 wantsFirstResponderOnAttach = false
531 }
532​
533 override func didMoveToWindow() {
534 super.didMoveToWindow()
535 if window != nil, wantsFirstResponderOnAttach {
536 wantsFirstResponderOnAttach = false
537 becomeFirstResponder()
538 }
539 }
540​
541 // A SwiftUI drag gesture on the composer never sees drags that start
542 // inside this view: the text interaction's own recognizers claim them at
543 // the UIKit level. This observing pan reproduces the host's
544 // drag-to-dismiss there: it recognizes alongside everything, cancels
545 // nothing, and dismisses a scrollable draft only when the drag begins at
546 // its top.
547 private let dismissPanDelegate = FeatureComposerDismissPanDelegate()
548​
549 func installDismissPanRecognizer() {
550 let pan = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan))
551 pan.cancelsTouchesInView = false
552 pan.delegate = dismissPanDelegate
553 addGestureRecognizer(pan)
554 }
555​
556 private var dismissPanBeganAtTop = false
557​
558 @objc private func handleDismissPan(_ recognizer: UIPanGestureRecognizer) {
559 // A fast flick can jump straight from .began to .ended without a
560 // .changed in between, so the end state is evaluated too. The at-top
561 // check is latched at .began: a drag that merely reaches the top
562 // mid-scroll only rubber-bands, instead of yanking the keyboard away
563 // the moment the offset crosses zero.
564 switch recognizer.state {
565 case .began:
566 dismissPanBeganAtTop = contentOffset.y <= 0
567 return
568 case .changed, .ended: break
569 default: return
570 }
571 guard isFirstResponder else { return }
572 let translation = recognizer.translation(in: self)
573 guard FeatureComposerDragDismissPolicy.shouldDismiss(
574 translationX: translation.x,
575 translationY: translation.y,
576 isScrollable: contentOverflows,
577 isAtTop: dismissPanBeganAtTop
578 ) else { return }
579 onDismissKeyboard?()
580 }
581​
582 // Scrolling stays enabled at every size: toggling `isScrollEnabled` off
583 // stops UITextView from maintaining `contentSize` on some OS versions,
584 // which left long drafts unscrollable on device. Overflow is computed
585 // fresh wherever it matters instead. A stale offset from a mid-resize
586 // selection change is still reset; with nothing to scroll, any offset
587 // clips the first line under the padding.
588 var contentOverflows: Bool {
589 contentSize.height > bounds.height + 0.5
590 }
591​
592 override func layoutSubviews() {
593 let viewportChanged = lastLaidOutBoundsSize != bounds.size
594 lastLaidOutBoundsSize = bounds.size
595 super.layoutSubviews()
596 if !contentOverflows, contentOffset.y != 0 {
597 contentOffset.y = 0
598 } else if viewportChanged, isFirstResponder {
599 // `sizeThatFits` receives a proposal. The final UIKit viewport can
600 // still differ after the footer and attachments take their space.
601 // Recheck the caret against these actual bounds once per resize.
602 scrollSelectionIntoView()
603 }
604 }
605​
606 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
607 if action == #selector(pasteAsText(_:)) {
608 return !isReadOnly && UIPasteboard.general.hasStrings
609 }
610 if isReadOnly, action == #selector(paste(_:)) || action == #selector(cut(_:)) {
611 return false
612 }
613 if action == #selector(paste(_:)),
614 acceptsImages,
615 FeatureComposerPasteboardPolicy.containsImage(in: UIPasteboard.general) {
616 return true
617 }
618 return super.canPerformAction(action, withSender: sender)
619 }
620​
621 // Drops are the other client of the paste configuration: while editing,
622 // UIKit offers the text view any drag it says it can paste. Declining
623 // image drags leaves them to the composer surface, so one target owns
624 // the session and the highlight; when the text view wins instead, the
625 // image vanishes into UITextView's text-only default and the surface's
626 // highlight never hears that the session ended.
627 override func canPaste(_ itemProviders: [NSItemProvider]) -> Bool {
628 guard !isReadOnly else { return false }
629 let holdsImage = itemProviders.contains {
630 $0.hasItemConformingToTypeIdentifier(UTType.image.identifier)
631 }
632 return holdsImage ? false : super.canPaste(itemProviders)
633 }
634​
635 // When the pasteboard holds images, only the images attach. Any text
636 // riding along (a copied web image usually brings its URL) is dropped on
637 // purpose: Slack and X do the same, and inserting a stray URL next to an
638 // attached screenshot reads as a bug.
639 override func paste(_ sender: Any?) {
640 guard !isReadOnly else { return }
641 do {
642 if let content = try FeatureContextClipboard.read() {
643 guard let onPasteContext, markedTextRange == nil else {
644 throw ComposerContextClipboardError.draftChanged
645 }
646 onPasteContext(
647 content,
648 FeatureInlineSkillProjection.plainText(from: attributedText),
649 FeatureInlineSkillProjection.plainRange(for: selectedRange, in: attributedText)
650 )
651 return
652 }
653 } catch {
654 onPasteTextError?(error.localizedDescription)
655 return
656 }
657 if acceptsImages {
658 let imageProviders = UIPasteboard.general.itemProviders.filter {
659 $0.hasItemConformingToTypeIdentifier(UTType.image.identifier)
660 }
661 if !imageProviders.isEmpty {
662 onPasteImages?(imageProviders)
663 return
664 }
665 }
666 if let pastedText = UIPasteboard.general.string, foldPastedText(pastedText) {
667 return
668 }
669 super.paste(sender)
670 }
671​
672 var readClipboardText: () -> String? = { UIPasteboard.general.string }
673​
674 @objc func pasteAsText(_ sender: Any?) {
675 guard !isReadOnly, let pastedText = readClipboardText() else { return }
676 if !foldPastedText(pastedText, bypassAutoAttachment: true) {
677 insertText(pastedText)
678 }
679 }
680​
681 /// Returning false leaves the paste to UIKit. A rejected fold must not
682 /// replace selected draft text with an empty string.
683 func foldPastedText(_ pastedText: String, bypassAutoAttachment: Bool = false) -> Bool {
684 guard !isReadOnly else { return true }
685 let source = FeatureInlineSkillProjection.plainText(from: attributedText)
686 let selection = FeatureInlineSkillProjection.plainRange(
687 for: selectedRange,
688 in: attributedText
689 )
690 switch FeaturePastedText.disposition(
691 text: pastedText,
692 currentTextLength: source.utf16.count,
693 selection: selection,
694 maximumAttachmentBytes: maximumPastedTextBytes,
695 bypassAutoAttachment: bypassAutoAttachment
696 ) {
697 case .inline:
698 return false
699 case .rejected:
700 onPasteTextError?(
701 "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
702 )
703 case .attachment:
704 guard markedTextRange == nil, let onPasteTextAttachment else {
705 onPasteTextError?("Could not attach pasted text. Your draft has not changed.")
706 return true
707 }
708 let requestID = UUID()
709 pastedTextRequestID = requestID
710 let ownerID = draftOwnerID
711 onPasteTextAttachment(pastedText) { [weak self] in
712 guard let self, self.pastedTextRequestID == requestID,
713 self.draftOwnerID == ownerID, !self.isReadOnly, self.markedTextRange == nil,
714 FeatureInlineSkillProjection.plainText(from: self.attributedText) == source,
715 FeatureInlineSkillProjection.plainRange(for: self.selectedRange, in: self.attributedText) == selection else {
716 return false
717 }
718 if self.selectedRange.length > 0 { self.insertText("") }
719 self.scrollSelectionIntoView()
720 self.pastedTextRequestID = UUID()
721 return true
722 }
723 }
724 return true
725 }
727​
728/// A standalone delegate (rather than the text view itself, whose scroll-view
729/// superclass already takes part in gesture delegation) so the observing pan
730/// reliably recognizes alongside the text interaction's own recognizers
731/// instead of being cancelled by them.
732private final class FeatureComposerDismissPanDelegate: NSObject, UIGestureRecognizerDelegate {
733 func gestureRecognizer(
734 _ gestureRecognizer: UIGestureRecognizer,
735 shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
736 ) -> Bool {
737 true
738 }
740​
741/// Mirrors the thread view's composer drag-to-dismiss thresholds: a clearly
742/// vertical downward drag. While the draft is scrollable, scrolling back
743/// through it never drops the keyboard mid-read, but a drag that *begins*
744/// with the draft at its top only rubber-bands, which is unambiguous
745/// dismissal intent (and the composer's only escape hatch once it and the
746/// keyboard cover the transcript). `isAtTop` is the position at drag start,
747/// so a scroll that reaches the top never dismisses mid-gesture.
748enum FeatureComposerDragDismissPolicy {
749 static func shouldDismiss(
750 translationX: CGFloat,
751 translationY: CGFloat,
752 isScrollable: Bool,
753 isAtTop: Bool
754 ) -> Bool {
755 (!isScrollable || isAtTop)
756 && translationY > 8
757 && translationY > abs(translationX)
758 }
760​
761enum FeatureComposerPasteboardPolicy {
762 /// `UIPasteboard.hasImages` misses formats that merely conform to image
763 /// (HEIC screenshots among them), so detection goes through UTType
764 /// conformance instead.
765 static func containsImage(in pasteboard: UIPasteboard) -> Bool {
766 pasteboard.itemProviders.contains {
767 $0.hasItemConformingToTypeIdentifier(UTType.image.identifier)
768 }
769 }
771​
772/// A one-shot caret placement, applied by the text input exactly once per
773/// request `id`. Command completion issues one so the caret lands after the
774/// inserted text instead of wherever UIKit leaves it after a programmatic
775/// text replacement.
776struct FeatureComposerTextSelectionRequest: Equatable {
777 let id = UUID()
778 let location: Int
780​
781/// Selection changes come from `updateUIView` and UIKit delegate callbacks.
782/// Keeping this value outside Observation avoids synchronous SwiftUI state
783/// writes while the representable is updating.
784@MainActor
785@Observable
786final class FeatureComposerTextObservation {
787 @ObservationIgnored var selection = NSRange(location: 0, length: 0)
789​
790enum FeatureComposerTextSelectionPolicy {
791 /// UTF-16 caret location after `range` (character indices, as produced by
792 /// the trigger parser) is replaced with `replacement`.
793 static func cursorLocation(
794 afterReplacing range: Range<Int>,
795 in text: String,
796 with replacement: String
797 ) -> Int {
798 let lower = min(max(range.lowerBound, 0), text.count)
799 let lowerIndex = text.index(text.startIndex, offsetBy: lower)
800 return text[..<lowerIndex].utf16.count + replacement.utf16.count
801 }
802​
803 /// Caret location after the binding changed underneath the text view. A
804 /// restored draft (previous text empty) puts the caret at the end; any
805 /// other external rewrite keeps the caret where it was, clamped into the
806 /// new text.
807 static func cursorLocationAfterBindingUpdate(
808 previousText: String,
809 newText: String,
810 selectedLocation: Int
811 ) -> Int {
812 previousText.isEmpty ? newText.utf16.count : min(selectedLocation, newText.utf16.count)
813 }
815​
816/// The editor grows with its content, then scrolls when it reaches the line
817/// cap or the space above the composer controls. A finite SwiftUI proposal is
818/// a hard bound. Returning a larger minimum makes the parent clip the editor
819/// under its fixed footer.
820enum FeatureComposerTextInputSizing {
821 static let maximumLines: CGFloat = 12
822​
823 static func height(
824 fittingHeight: CGFloat,
825 lineHeight: CGFloat,
826 availableHeight: CGFloat? = nil
827 ) -> CGFloat {
828 let maximumHeight = max(0, lineHeight * maximumLines)
829 let contentHeight = max(0, fittingHeight)
830 guard let availableHeight, availableHeight.isFinite else {
831 return min(contentHeight, maximumHeight)
832 }
833 return min(contentHeight, maximumHeight, max(0, availableHeight))
834 }