@@ -13,7 +13,7 @@ private struct ComposerTokenPayload: Decodable {
1313 let end : Int
1414}
1515
16- private struct ComposerSelectionPayload : Decodable {
16+ private struct ComposerSelectionPayload : Decodable , Equatable {
1717 let start : Int
1818 let end : Int
1919}
@@ -449,6 +449,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
449449 private var tokensNeedRebuild = false
450450 private var chipsNeedMeasuredWidth = false
451451 private var hasDeferredForcedRebuild = false
452+ private var pendingContentOffset : CGPoint ?
453+ private var needsSelectionReveal = false
454+ private var selectionBeforeFocusingTap : ( selection : ComposerSelectionPayload , value : String ) ?
452455
453456 let onComposerChange = EventDispatcher ( )
454457 let onComposerSelectionChange = EventDispatcher ( )
@@ -464,7 +467,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
464467 public required init ( appContext : AppContext ? = nil ) {
465468 super . init ( appContext : appContext )
466469
467- clipsToBounds = false
470+ clipsToBounds = true
471+ textView . clipsToBounds = true
468472 textView . delegate = self
469473 textView . textDropDelegate = self
470474 textView . backgroundColor = . clear
@@ -520,6 +524,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
520524 @ objc private func openContext ( _ recognizer : UITapGestureRecognizer ) {
521525 guard let ( index , attachment ) = contextAttachment ( at : recognizer . location ( in : textView ) ) else {
522526 textView . becomeFirstResponder ( )
527+ if selectionBeforeFocusingTap != nil {
528+ // UIKit places the caret from its own tap recognizer during this same touch.
529+ DispatchQueue . main . async { [ weak self ] in
530+ self ? . restoreSelectionBeforeFocusingTap ( )
531+ }
532+ }
523533 return
524534 }
525535 openContext ( index : index , attachment : attachment )
@@ -558,7 +568,11 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
558568 }
559569
560570 public func gestureRecognizer ( _ gestureRecognizer : UIGestureRecognizer , shouldReceive touch : UITouch ) -> Bool {
561- true
571+ // The collapsed editor only shows the draft's first line, so a tap that expands an
572+ // overflowing draft returns to the caret it was left at instead of moving it there.
573+ let collapsedOverflow = ! textView . isFirstResponder && ! textView . isScrollEnabled && draftOverflowsBounds ( )
574+ selectionBeforeFocusingTap = collapsedOverflow ? ( sourceSelection ( ) , value ) : nil
575+ return true
562576 }
563577
564578 public func gestureRecognizer ( _ gestureRecognizer : UIGestureRecognizer , shouldRecognizeSimultaneouslyWith otherGestureRecognizer : UIGestureRecognizer ) -> Bool {
@@ -583,11 +597,27 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
583597
584598 public override func layoutSubviews ( ) {
585599 super . layoutSubviews ( )
600+ let previousSize = textView . bounds . size
586601 textView . frame = bounds
587602 if chipsNeedMeasuredWidth , bounds . width > 0 {
588603 chipsNeedMeasuredWidth = false
589604 applyControlledDocument ( force : true )
590605 }
606+ if textView . isScrollEnabled , bounds . width > 0 , bounds . height > 0 {
607+ textView . layoutIfNeeded ( )
608+ if let offset = pendingContentOffset {
609+ let minY = - textView . adjustedContentInset . top
610+ let maxY = max ( minY , textView . contentSize . height - bounds . height + textView . adjustedContentInset . bottom )
611+ textView . setContentOffset ( CGPoint ( x : offset . x , y : min ( maxY , max ( minY , offset . y ) ) ) , animated : false )
612+ pendingContentOffset = nil
613+ }
614+ if needsSelectionReveal || ( previousSize != bounds . size && textView . isFirstResponder ) {
615+ needsSelectionReveal = false
616+ if let selection = textView . selectedTextRange {
617+ textView . scrollRectToVisible ( textView . caretRect ( for : selection . end ) , animated : false )
618+ }
619+ }
620+ }
591621 let placeholderX = textView . textContainerInset . left + textView . textContainer . lineFragmentPadding
592622 let placeholderY = textView . textContainerInset . top
593623 let placeholderWidth = max (
@@ -632,10 +662,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
632662 tokens = decode ( [ ComposerTokenPayload ] . self , from : document . tokensJson ) ?? [ ]
633663 tokensNeedRebuild = true
634664 }
665+ let previousSelection = sourceSelection ( )
635666 value = document . value
636667 requestedSelection = document . selection
637668 applyControlledDocument ( force : tokensNeedRebuild )
638669 applyRequestedSelection ( )
670+ cancelFocusingTapRestoreIfSelectionMoved ( from : previousSelection )
639671 if tokensMatchCurrentValue ( ) {
640672 tokensNeedRebuild = false
641673 }
@@ -694,7 +726,16 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
694726 }
695727
696728 func setScrollEnabled ( _ scrollEnabled : Bool ) {
729+ guard textView . isScrollEnabled != scrollEnabled else { return }
730+ if ! scrollEnabled {
731+ // Disabling scrolling discards UITextView's offset. Restore it after
732+ // expansion has laid out the text, regardless of prop update order.
733+ pendingContentOffset = pendingContentOffset ?? textView . contentOffset
734+ }
697735 textView . isScrollEnabled = scrollEnabled
736+ if scrollEnabled {
737+ revealSelectionAfterLayout ( )
738+ }
698739 }
699740
700741 func setAutoFocus ( _ autoFocus : Bool ) {
@@ -738,8 +779,10 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
738779 }
739780
740781 func setSelection ( start : Int , end : Int ) {
782+ let previousSelection = sourceSelection ( )
741783 requestedSelection = ComposerSelectionPayload ( start : start , end : end )
742784 applyRequestedSelection ( )
785+ cancelFocusingTapRestoreIfSelectionMoved ( from : previousSelection )
743786 }
744787
745788 public func textViewDidChange ( _ textView : UITextView ) {
@@ -811,6 +854,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
811854 }
812855
813856 public func textViewDidBeginEditing ( _ textView : UITextView ) {
857+ revealSelectionAfterLayout ( )
814858 onComposerFocus ( )
815859 }
816860
@@ -836,13 +880,21 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
836880 hasDeferredForcedRebuild = false
837881
838882 let previousSelection = sourceSelection ( )
883+ if textView . isScrollEnabled {
884+ pendingContentOffset = pendingContentOffset ?? textView . contentOffset
885+ }
839886 isApplyingControlledValue = true
840887 textView . attributedText = makeAttributedDocument ( )
841888 let targetSelection = requestedSelection ?? previousSelection
842889 requestedSelection = nil
843890 textView . selectedRange = displayRange ( for : targetSelection )
844891 restoreBaseTypingAttributes ( )
845892 isApplyingControlledValue = false
893+ if currentSource != value || previousSelection . start != targetSelection . start || previousSelection . end != targetSelection . end {
894+ revealSelectionAfterLayout ( )
895+ } else {
896+ setNeedsLayout ( )
897+ }
846898 updatePlaceholderVisibility ( )
847899 emitContentSizeIfNeeded ( )
848900 }
@@ -1053,6 +1105,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
10531105 return
10541106 }
10551107 value = textView . serializedText ( )
1108+ revealSelectionAfterLayout ( )
10561109 let selection = sourceSelection ( )
10571110 nativeEventCount += 1
10581111 onComposerChange ( [
@@ -1122,35 +1175,57 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
11221175 isApplyingControlledValue = true
11231176 textView . selectedRange = nextRange
11241177 isApplyingControlledValue = false
1178+ revealSelectionAfterLayout ( )
1179+ }
1180+
1181+ private func restoreSelectionBeforeFocusingTap ( ) {
1182+ guard let snapshot = selectionBeforeFocusingTap else {
1183+ return
1184+ }
1185+ selectionBeforeFocusingTap = nil
1186+ // A draft that changed during the touch, such as a transcript landing, owns the caret now.
1187+ guard textView . isFirstResponder , textView . markedTextRange == nil , value == snapshot . value else {
1188+ return
1189+ }
1190+ let range = displayRange ( for : snapshot . selection )
1191+ guard ! NSEqualRanges ( range , textView . selectedRange ) else {
1192+ return
1193+ }
1194+ textView . selectedRange = range
1195+ revealSelectionAfterLayout ( )
1196+ }
1197+
1198+ private func cancelFocusingTapRestoreIfSelectionMoved ( from previousSelection : ComposerSelectionPayload ) {
1199+ if sourceSelection ( ) != previousSelection {
1200+ selectionBeforeFocusingTap = nil
1201+ }
1202+ }
1203+
1204+ private func draftOverflowsBounds ( ) -> Bool {
1205+ let size = textView . sizeThatFits ( CGSize ( width : textView . bounds . width , height : . greatestFiniteMagnitude ) )
1206+ return size . height > textView . bounds . height + 1
1207+ }
1208+
1209+ private func revealSelectionAfterLayout ( ) {
1210+ needsSelectionReveal = true
1211+ setNeedsLayout ( )
11251212 }
11261213
11271214 private func updatePlaceholderVisibility ( ) {
11281215 placeholderLabel . isHidden = ! value . isEmpty
11291216 }
11301217
11311218 private func emitContentSizeIfNeeded ( ) {
1132- // The laid-out text without insets. A one-line draft reports its natural width, so
1133- // JS can tell whether it fits a narrower row than the one it is laid out in; past
1134- // one line only the height matters, so layout stops at the second line. The width
1135- // comes from the line fragment because usedRect spans the container once the view
1136- // scrolls. A trailing newline's empty line only exists as the extra fragment.
1137- let layout = textView . layoutManager
1138- let container = textView . textContainer
1139- var lines = 0
1140- var width : CGFloat = 0
1141- var height : CGFloat = 0
1142- let glyphs = NSRange ( location : 0 , length : layout . numberOfGlyphs )
1143- layout . enumerateLineFragments ( forGlyphRange : glyphs ) { _ , used , _ , _ , stop in
1144- lines += 1
1145- width = used . width
1146- height = used . maxY
1147- if lines > 1 { stop . pointee = true }
1148- }
1149- if lines < 2 , layout . extraLineFragmentTextContainer === container {
1150- lines += 1
1151- height = max ( height , layout . extraLineFragmentUsedRect . maxY )
1152- }
1153- let nextSize = CGSize ( width : lines == 1 ? ceil ( width ) : 0 , height : ceil ( height ) )
1219+ guard bounds . width > 0 else { return }
1220+ // Fit independently of the animated viewport: when scrolling is disabled,
1221+ // its current height can clip TextKit's laid-out line fragments.
1222+ let fittedHeight = textView . sizeThatFits ( CGSize ( width : bounds . width , height : . greatestFiniteMagnitude ) ) . height
1223+ - textView . textContainerInset . top - textView . textContainerInset . bottom
1224+ let measuredHeight = min ( lineHeight * 4 , fittedHeight )
1225+ let width = fittedHeight <= lineHeight + 0.5
1226+ ? textView . layoutManager . usedRect ( for : textView . textContainer ) . width
1227+ : 0
1228+ let nextSize = CGSize ( width : ceil ( width ) , height : ceil ( measuredHeight ) )
11541229 guard abs ( nextSize . width - lastContentSize . width ) > 0.5 ||
11551230 abs ( nextSize . height - lastContentSize . height ) > 0.5 else {
11561231 return
0 commit comments