Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

32.4 KB
Raw Blame
diff --git a/ios/RNUITextView.mm b/ios/RNUITextView.mm
index d0c31ed20b4865679ec1397543fc74056e47b978..55961f88d6d14f2fc76e8e28c492615d686be07a 100644
--- a/ios/RNUITextView.mm
+++ b/ios/RNUITextView.mm
@@ -1,4 +1,5 @@
 #import "RNUITextView.h"
+#import <os/log.h>
 #import "RNUITextViewShadowNode.h"
 #import "RNUITextViewComponentDescriptor.h"
 #import "RNUITextViewChild.h"
@@ -22,6 +23,36 @@ using namespace facebook::react;
   RNUITextViewShadowNode::ConcreteState::Shared _state;
   UITapGestureRecognizer * _outsideTapRecognizer;
   BOOL _suppressSelectionChange;
+  // Last applied attributed string, compared as the C++ value type. NSAttributedString
+  // equality after RCTNSAttributedStringFromAttributedString conversion is not stable
+  // across RN versions (attribute object identity), which caused spurious re-assigns
+  // (and visible repaint flashes) on RN 0.85.
+  facebook::react::AttributedString _lastAppliedAttributedString;
+  BOOL _hasAppliedText;
+  // Monotonic apply counter: each apply that schedules a deferred onTextLayout
+  // emission (and each recycle) bumps it, so a pending block can tell it has been
+  // superseded even when the newer text happens to have the same length.
+  NSUInteger _textApplyGeneration;
+  // Last user selection range, used to tell which selection edge is being dragged
+  // (drives enclosing-scroll-view auto-scroll while extending a selection).
+  NSRange _lastSelectionRange;
+  // Polls the live selection while one exists: on iOS 26 textViewDidChangeSelection is
+  // NOT called continuously during a handle drag (only sparse settle events), so the
+  // auto-scroll must sample selectedRange per frame instead of reacting to the delegate.
+  CADisplayLink *_selectionDisplayLink;
+  // Pure touch observer (minimumPressDuration=0 long press, cancels nothing): on iOS 26
+  // even selectedRange only commits sporadically during a handle drag, so edge auto-scroll
+  // must be driven by the raw touch location. Engaged only when the touch starts near a
+  // selection edge (i.e. on a handle) while a selection exists.
+  UILongPressGestureRecognizer *_selectionTouchObserver;
+  BOOL _selectionEdgeDragActive;
+  CGPoint _selectionTouchInWindow;
+  // Scroll view we sent scrollViewWillBeginDragging: to for the current handle drag,
+  // so the paired scrollViewDidEndDragging: goes to the same view on any release path.
+  __weak UIScrollView *_selectionDragScrollView;
+  // Title of the custom edit-menu action (menuActionLabel prop). Empty = no item.
+  NSString *_menuActionLabel;
+  NSString *_sideChatMenuActionLabel;
 }
 
 + (ComponentDescriptorProvider)componentDescriptorProvider
@@ -65,6 +96,18 @@ using namespace facebook::react;
                                                                     action:@selector(handleOutsideTap:)];
     _outsideTapRecognizer.cancelsTouchesInView = NO;
     _outsideTapRecognizer.delegate = self;
+
+    _lastSelectionRange = NSMakeRange(NSNotFound, 0);
+
+    _selectionTouchObserver = [[UILongPressGestureRecognizer alloc] initWithTarget:self
+                                                                            action:@selector(handleSelectionTouchObserver:)];
+    _selectionTouchObserver.minimumPressDuration = 0;
+    _selectionTouchObserver.allowableMovement = CGFLOAT_MAX;
+    _selectionTouchObserver.cancelsTouchesInView = NO;
+    _selectionTouchObserver.delaysTouchesBegan = NO;
+    _selectionTouchObserver.delaysTouchesEnded = NO;
+    _selectionTouchObserver.delegate = self;
+    [_textView addGestureRecognizer:_selectionTouchObserver];
   }
 
   return self;
@@ -77,6 +120,7 @@ using namespace facebook::react;
     [self.window addGestureRecognizer:_outsideTapRecognizer];
   } else {
     [_outsideTapRecognizer.view removeGestureRecognizer:_outsideTapRecognizer];
+    [self invalidateSelectionDisplayLink];
   }
 }
 
@@ -94,21 +138,27 @@ using namespace facebook::react;
   // Reset the frame to zero so that when it properly lays out on the next use
   _textView.frame = CGRectZero;
   _textView.attributedText = nil;
+  _lastAppliedAttributedString = facebook::react::AttributedString{};
+  _hasAppliedText = NO;
+  _textApplyGeneration += 1;
+  [self invalidateSelectionDisplayLink];
 }
 
 - (void)layoutSubviews
 {
   [super layoutSubviews];
-  // _textView's frame is assigned inside drawRect, which only fires when
-  // state changes. Trigger a redraw whenever the host frame moves out from
-  // under it (rotation, parent relayout) so the text view resizes and
-  // onTextLayout re-fires with the new line wrapping.
-  if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
-    [self setNeedsDisplay];
-  }
+  // Apply synchronously whenever the host frame moves out from under the text
+  // view (rotation, parent relayout) so it resizes and onTextLayout re-fires.
+  [self applyStateIfNeeded];
 }
 
-- (void)drawRect:(CGRect)rect
+// Applies the current Fabric state to the backing UITextView synchronously.
+// Called from finalizeUpdates (inside the mount transaction) and layoutSubviews,
+// instead of the previous setNeedsDisplay/drawRect indirection: waiting for the
+// display pass left a window where a recycled/remounted view was on screen with
+// its text cleared, which showed up as full-screen white flashes in long lists
+// on RN 0.85.
+- (void)applyStateIfNeeded
 {
   if (!_state) {
     return;
@@ -116,19 +166,23 @@ using namespace facebook::react;
 
   const auto &props = *std::static_pointer_cast<RNUITextViewProps const>(_props);
 
-  const auto attrString = _state->getData().attributedString;
-  const auto convertedAttrString = RCTNSAttributedStringFromAttributedString(attrString);
+  const auto &attrString = _state->getData().attributedString;
 
   // Setting attributedText clears any active text selection, and re-assigning
   // the frame triggers a layout flush that has the same effect. Bail out
   // entirely when nothing actually changed so a JS-side state update made in
   // response to onSelectionChange doesn't deselect what the user is selecting.
-  const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
+  // Compare as the C++ value type (see ivar comment) — NSAttributedString
+  // equality after conversion is not reliable across RN versions.
+  const BOOL textChanged = !_hasAppliedText || !(_lastAppliedAttributedString == attrString);
   const BOOL frameChanged = !CGRectEqualToRect(_textView.frame, _view.frame);
   if (!textChanged && !frameChanged) {
     return;
   }
+  const auto convertedAttrString = RCTNSAttributedStringFromAttributedString(attrString);
   if (textChanged) {
+    _lastAppliedAttributedString = attrString;
+    _hasAppliedText = YES;
     // Reassigning attributedText clears any active selection. Save it and
     // restore after, while suppressing the synthetic textViewDidChangeSelection
     // events the clear-then-restore would otherwise produce — those would
@@ -145,27 +199,56 @@ using namespace facebook::react;
     _textView.frame = _view.frame;
   }
 
-  __block std::vector<std::string> lines;
+  os_log_debug(OS_LOG_DEFAULT, "[RNUITextView] apply tag=%ld len=%lu textChanged=%d frameChanged=%d",
+               (long)self.tag, (unsigned long)convertedAttrString.length, textChanged, frameChanged);
+
+  // onTextLayout line enumeration forces a FULL synchronous glyph layout of the whole
+  // string on the main thread. Doing that inside the mount transaction for every apply
+  // is the dominant cost for long texts (visible as blank frames while scrolling through
+  // large messages). Defer it past the current transaction; consumers get the event one
+  // frame later, which matches the old drawRect timing anyway.
+  const auto textLength = convertedAttrString.string.length;
   const int maxLines = props.numberOfLines;
-  [_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
-                                                                                              CGRect usedRect,
-                                                                                              NSTextContainer * _Nonnull textContainer,
-                                                                                              NSRange glyphRange,
-                                                                                              BOOL * _Nonnull stop) {
-    const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
-    const auto line = [self->_textView.text substringWithRange:charRange];
-    lines.push_back(line.UTF8String);
-    // enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
-    // 18, so cap explicitly.
-    if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
-      *stop = YES;
+  _textApplyGeneration += 1;
+  const NSUInteger applyGeneration = _textApplyGeneration;
+  dispatch_async(dispatch_get_main_queue(), ^{
+    if (self->_eventEmitter == nullptr) {
+      return;
     }
-  }];
-
-  if (_eventEmitter != nullptr) {
-    std::dynamic_pointer_cast<const facebook::react::RNUITextViewEventEmitter>(_eventEmitter)
-    ->onTextLayout(facebook::react::RNUITextViewEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
-  };
+    // Staleness guard (review P1): by the time this deferred block runs, the same view may
+    // have been re-applied (streaming update) or recycled. The generation counter marks the
+    // block as superseded even when the newer text has the same length (same-length rewrites
+    // would otherwise emit twice per frame); only the block from the latest apply survives.
+    if (self->_textApplyGeneration != applyGeneration) {
+      return;
+    }
+    // Belt-and-braces vs out-of-bounds: any text mutation path that bypassed the counter
+    // (e.g. library code touching the UITextView directly) would still make
+    // NSMakeRange(0, textLength) unsafe against the current layout manager.
+    if (self->_textView.attributedText.length != textLength) {
+      return;
+    }
+    __block std::vector<std::string> lines;
+    [self->_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, textLength) usingBlock:^(CGRect rect,
+                                                                                                CGRect usedRect,
+                                                                                                NSTextContainer * _Nonnull textContainer,
+                                                                                                NSRange glyphRange,
+                                                                                                BOOL * _Nonnull stop) {
+      const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
+      const auto line = [self->_textView.text substringWithRange:charRange];
+      lines.push_back(line.UTF8String);
+      // enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
+      // 18, so cap explicitly.
+      if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
+        *stop = YES;
+      }
+    }];
+
+    if (self->_eventEmitter != nullptr) {
+      std::dynamic_pointer_cast<const facebook::react::RNUITextViewEventEmitter>(self->_eventEmitter)
+      ->onTextLayout(facebook::react::RNUITextViewEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
+    };
+  });
 }
 
 - (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
@@ -181,6 +264,14 @@ using namespace facebook::react;
     _textView.selectable = newViewProps.selectable;
   }
 
+  if (oldViewProps.menuActionLabel != newViewProps.menuActionLabel) {
+    _menuActionLabel = [NSString stringWithUTF8String:newViewProps.menuActionLabel.c_str()];
+  }
+
+  if (oldViewProps.sideChatMenuActionLabel != newViewProps.sideChatMenuActionLabel) {
+    _sideChatMenuActionLabel = [NSString stringWithUTF8String:newViewProps.sideChatMenuActionLabel.c_str()];
+  }
+
   if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
     if (@available(iOS 11.0, *)) {
       _textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
@@ -215,7 +306,15 @@ using namespace facebook::react;
 - (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
 {
   _state = std::static_pointer_cast<const RNUITextViewShadowNode::ConcreteState>(state);
-  [self setNeedsDisplay];
+}
+
+- (void)finalizeUpdates:(RNComponentViewUpdateMask)updateMask
+{
+  [super finalizeUpdates:updateMask];
+  // Runs inside the mount transaction after props/state/layout metrics are all
+  // in place: text lands on the UITextView before the frame is committed to
+  // screen, so a recycled view never renders a blank frame first.
+  [self applyStateIfNeeded];
 }
 
 // MARK: - UIGestureRecognizerDelegate
@@ -297,4 +396,10 @@ using namespace facebook::react;
 - (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
 {
+  // Long presses also report movement and release. Dispatch the action only
+  // once, when recognition begins, without changing native text selection.
+  if (sender.state != UIGestureRecognizerStateBegan) {
+    return;
+  }
+
   const auto location = [self getLocationOfPress:sender];
   const auto child = [self getTouchChild:location];
@@ -328,6 +433,248 @@ using namespace facebook::react;
       static_cast<int>(selectedRange.location),
       static_cast<int>(selectedRange.location + selectedRange.length),
     });
+
+}
+
+// MARK: - Custom edit menu action (chat-text-quote)
+
+// Inserts a custom action (menuActionLabel prop) in FRONT of the system edit
+// menu items (Copy / Look Up / ...) shown for a text selection. Emits
+// onMenuAction with the selected range at tap time, then clears the selection
+// (deferred past menu dismissal). iOS 16+ only; earlier systems keep the plain
+// system menu.
+- (UIMenu *)textView:(UITextView *)textView
+  editMenuForTextInRange:(NSRange)range
+        suggestedActions:(NSArray<UIMenuElement *> *)suggestedActions API_AVAILABLE(ios(16.0))
+{
+  if (range.length == 0) {
+    return [UIMenu menuWithChildren:suggestedActions];
+  }
+  __weak RNUITextView *weakSelf = self;
+  void (^performAction)(BOOL) = ^(BOOL sideChat) {
+    RNUITextView *strongSelf = weakSelf;
+    if (strongSelf == nil || strongSelf->_eventEmitter == nullptr) {
+      return;
+    }
+    // Use the live range after any handle adjustment, not the menu's original range.
+    const NSRange selection = strongSelf->_textView.selectedRange;
+    if (selection.location == NSNotFound || selection.length == 0 ||
+        NSMaxRange(selection) > strongSelf->_textView.text.length) {
+      return;
+    }
+    auto emitter = std::dynamic_pointer_cast<const facebook::react::RNUITextViewEventEmitter>(strongSelf->_eventEmitter);
+    if (sideChat) {
+      emitter->onSideChatMenuAction(facebook::react::RNUITextViewEventEmitter::OnSideChatMenuAction{
+        static_cast<int>(strongSelf.tag),
+        static_cast<int>(selection.location),
+        static_cast<int>(NSMaxRange(selection)),
+      });
+    } else {
+      emitter->onMenuAction(facebook::react::RNUITextViewEventEmitter::OnMenuAction{
+        static_cast<int>(strongSelf.tag),
+        static_cast<int>(selection.location),
+        static_cast<int>(NSMaxRange(selection)),
+      });
+    }
+    // Clear after dismissal so the system teardown never races a selection mutation.
+    UITextView *innerTextView = strongSelf->_textView;
+    dispatch_async(dispatch_get_main_queue(), ^{
+      innerTextView.selectedTextRange = nil;
+    });
+  };
+  NSMutableArray<UIMenuElement *> *children = [NSMutableArray array];
+  if (_menuActionLabel.length > 0) {
+    [children addObject:[UIAction actionWithTitle:_menuActionLabel image:nil identifier:nil
+      handler:^(__kindof UIAction *action) { performAction(NO); }]];
+  }
+  if (_sideChatMenuActionLabel.length > 0) {
+    [children addObject:[UIAction actionWithTitle:_sideChatMenuActionLabel image:nil identifier:nil
+      handler:^(__kindof UIAction *action) { performAction(YES); }]];
+  }
+  [children addObjectsFromArray:suggestedActions];
+  return [UIMenu menuWithChildren:children];
+}
+
+// MARK: - Selection auto-scroll (frame-driven)
+
+- (void)ensureSelectionDisplayLink
+{
+  if (_selectionDisplayLink != nil) {
+    return;
+  }
+  _selectionDisplayLink = [CADisplayLink displayLinkWithTarget:self
+                                                      selector:@selector(selectionDisplayLinkTick:)];
+  [_selectionDisplayLink addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
+  os_log_debug(OS_LOG_DEFAULT, "[RNUITextView-sel] tag=%ld displaylink armed", (long)self.tag);
+}
+
+- (void)invalidateSelectionDisplayLink
+{
+  if (_selectionDisplayLink == nil) {
+    return;
+  }
+  [_selectionDisplayLink invalidate];
+  _selectionDisplayLink = nil;
+  _lastSelectionRange = NSMakeRange(NSNotFound, 0);
+  _selectionEdgeDragActive = NO;
+  [self notifySelectionDragEnded];
+  os_log_debug(OS_LOG_DEFAULT, "[RNUITextView-sel] tag=%ld displaylink disarmed", (long)self.tag);
+}
+
+// Route the handle-drag lifecycle through the enclosing scroll view's user-drag
+// delegate path (review P2): the auto-scroll below moves contentOffset directly,
+// which never fires JS onScrollBeginDrag — the path where the list owner releases
+// bottom-stickiness. Without this, a streaming content growth during an active
+// selection would treat the list as still stuck-to-bottom and yank the viewport
+// back down, disrupting the selection. Calling the delegate methods makes JS see
+// exactly what a finger drag emits; no new native->JS API surface is needed.
+- (void)notifySelectionDragBegan
+{
+  UIScrollView *scrollView = [self enclosingScrollView];
+  if (scrollView == nil) {
+    return;
+  }
+  _selectionDragScrollView = scrollView;
+  id<UIScrollViewDelegate> delegate = scrollView.delegate;
+  if ([delegate respondsToSelector:@selector(scrollViewWillBeginDragging:)]) {
+    [delegate scrollViewWillBeginDragging:scrollView];
+  }
+}
+
+- (void)notifySelectionDragEnded
+{
+  UIScrollView *scrollView = _selectionDragScrollView;
+  _selectionDragScrollView = nil;
+  if (scrollView == nil) {
+    return;
+  }
+  id<UIScrollViewDelegate> delegate = scrollView.delegate;
+  if ([delegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)]) {
+    [delegate scrollViewDidEndDragging:scrollView willDecelerate:NO];
+  }
+}
+
+- (void)selectionDisplayLinkTick:(CADisplayLink *)link
+{
+  // 护航模式生命周期:视图离屏 / 手指抬起即停(tick 内自检,兼作 CADisplayLink 持有 self 的释放出口)。
+  if (self.window == nil || _textView.window == nil || !_selectionEdgeDragActive) {
+    [self invalidateSelectionDisplayLink];
+    return;
+  }
+  [self autoScrollForTouchAtWindowPoint:_selectionTouchInWindow];
+}
+
+- (void)handleSelectionTouchObserver:(UILongPressGestureRecognizer *)sender
+{
+  switch (sender.state) {
+    case UIGestureRecognizerStateBegan: {
+      const NSRange range = _textView.selectedRange;
+      if (range.length == 0 || range.location == NSNotFound) {
+        return;
+      }
+      const CGPoint location = [sender locationInView:_textView];
+      if (![self isPoint:location nearSelectionEdge:range]) {
+        return;
+      }
+      _selectionEdgeDragActive = YES;
+      _selectionTouchInWindow = [sender locationInView:nil];
+      os_log_debug(OS_LOG_DEFAULT, "[RNUITextView-sel] tag=%ld edge-drag engaged", (long)self.tag);
+      [self ensureSelectionDisplayLink];
+      [self notifySelectionDragBegan];
+      break;
+    }
+    case UIGestureRecognizerStateChanged:
+      if (_selectionEdgeDragActive) {
+        _selectionTouchInWindow = [sender locationInView:nil];
+      }
+      break;
+    default:
+      if (_selectionEdgeDragActive) {
+        os_log_debug(OS_LOG_DEFAULT, "[RNUITextView-sel] tag=%ld edge-drag released", (long)self.tag);
+      }
+      _selectionEdgeDragActive = NO;
+      [self notifySelectionDragEnded];
+      break;
+  }
+}
+
+// 触点是否贴近选区两端(=手柄位置)。普通滚动/点按不从手柄起步,不会误入护航模式。
+- (BOOL)isPoint:(CGPoint)point nearSelectionEdge:(NSRange)range
+{
+  UITextPosition *startPos = [_textView positionFromPosition:_textView.beginningOfDocument
+                                                      offset:(NSInteger)range.location];
+  UITextPosition *endPos = [_textView positionFromPosition:_textView.beginningOfDocument
+                                                    offset:(NSInteger)NSMaxRange(range)];
+  const CGFloat threshold = 44.0;
+  for (UITextPosition *pos in @[startPos ?: (UITextPosition *)NSNull.null,
+                                endPos ?: (UITextPosition *)NSNull.null]) {
+    if ([pos isKindOfClass:NSNull.class]) {
+      continue;
+    }
+    const CGRect caret = [_textView caretRectForPosition:(UITextPosition *)pos];
+    if (CGRectIsNull(caret) || CGRectIsInfinite(caret)) {
+      continue;
+    }
+    const CGRect hitArea = CGRectInset(caret, -threshold, -threshold);
+    if (CGRectContainsPoint(hitArea, point)) {
+      return YES;
+    }
+  }
+  return NO;
+}
+
+// 手指在外层滚动视图可视区边缘 → 连续平滑滚动(速度随贴边深度加速)。
+- (void)autoScrollForTouchAtWindowPoint:(CGPoint)touchInWindow
+{
+  UIScrollView *scrollView = [self enclosingScrollView];
+  if (scrollView == nil) {
+    return;
+  }
+  const CGPoint touchInScroll = [scrollView convertPoint:touchInWindow fromView:nil];
+  const UIEdgeInsets inset = scrollView.adjustedContentInset;
+  const CGFloat visibleTop = scrollView.contentOffset.y + inset.top;
+  const CGFloat visibleBottom = scrollView.contentOffset.y + scrollView.bounds.size.height - inset.bottom;
+  const CGFloat topEdge = 88.0;
+  // 底部放宽:半透明 composer 悬浮在列表底部,insets 不描述它。
+  const CGFloat bottomEdge = 160.0;
+  const CGFloat maxStepPerFrame = 10.0;
+
+  CGFloat step = 0;
+  if (touchInScroll.y > visibleBottom - bottomEdge) {
+    const CGFloat depth = MIN(1.0, (touchInScroll.y - (visibleBottom - bottomEdge)) / bottomEdge);
+    step = maxStepPerFrame * depth;
+  } else if (touchInScroll.y < visibleTop + topEdge) {
+    const CGFloat depth = MIN(1.0, ((visibleTop + topEdge) - touchInScroll.y) / topEdge);
+    step = -maxStepPerFrame * depth;
+  }
+  if (step == 0) {
+    return;
+  }
+  const CGFloat minOffset = -inset.top;
+  const CGFloat maxOffset = MAX(minOffset,
+      scrollView.contentSize.height + inset.bottom - scrollView.bounds.size.height);
+  CGFloat target = scrollView.contentOffset.y + step;
+  target = MIN(MAX(target, minOffset), maxOffset);
+  if (fabs(target - scrollView.contentOffset.y) < 0.1) {
+    return;
+  }
+  [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, target) animated:NO];
+}
+
+- (UIScrollView *)enclosingScrollView
+{
+  UIView *ancestor = self.superview;
+  while (ancestor != nil) {
+    if ([ancestor isKindOfClass:UIScrollView.class]) {
+      UIScrollView *candidate = (UIScrollView *)ancestor;
+      if (candidate.scrollEnabled &&
+          candidate.contentSize.height > candidate.bounds.size.height + 1) {
+        return candidate;
+      }
+    }
+    ancestor = ancestor.superview;
+  }
+  return nil;
 }
 
 Class<RCTComponentViewProtocol> RNUITextViewCls(void)
diff --git a/ios/RNUITextViewShadowNode.cpp b/ios/RNUITextViewShadowNode.cpp
index 8b39111b9b945527e48ab3d93e5619427385e4ac..f563211079e2924490482f8144ffc9314a22a343 100644
--- a/ios/RNUITextViewShadowNode.cpp
+++ b/ios/RNUITextViewShadowNode.cpp
@@ -28,15 +28,32 @@ Size RNUITextViewShadowNode::measureContent(
       paragraphAttributes.ellipsizeMode = EllipsizeMode::Clip;
     }
 
-    auto baseTextAttributes = TextAttributes::defaultTextAttributes();
-    baseTextAttributes.backgroundColor = baseProps.backgroundColor;
-    baseTextAttributes.allowFontScaling = baseProps.allowFontScaling;
-    
     Float fontSizeMultiplier = 1.0;
-    if (baseTextAttributes.allowFontScaling) {
+    if (baseProps.allowFontScaling) {
       fontSizeMultiplier = layoutContext.fontSizeMultiplier;
     }
+
+    _attributedString = buildAttributedString(fontSizeMultiplier);
     
+    TextLayoutContext textLayoutContext{};
+    textLayoutContext.pointScaleFactor = layoutContext.pointScaleFactor;
+    const auto textLayoutManager = std::make_shared<const TextLayoutManager>(getContextContainer());
+        
+    return textLayoutManager->measure(
+      AttributedStringBox{_attributedString},
+      paragraphAttributes,
+      textLayoutContext,
+      layoutConstraints
+    ).size;
+}
+
+// Builds the attributed string from the current child shadow nodes. Called from BOTH
+// measureContent and layout(): layout() must not rely on _attributedString being fresh —
+// Yoga can skip measureContent (measurement cache) and shadow-node clones don't inherit
+// the field, so the old code could push an EMPTY string into state, permanently wiping
+// already-mounted text (rendered as giant blank bubbles in long lists).
+AttributedString RNUITextViewShadowNode::buildAttributedString(Float fontSizeMultiplier) const {
+    const auto &baseProps = getConcreteProps();
     auto baseAttributedString = AttributedString{};
     const auto &children = getChildren();
     for (size_t i = 0; i < children.size(); i++) {
@@ -119,24 +136,27 @@ Size RNUITextViewShadowNode::measureContent(
       }
     }
     
-    _attributedString = baseAttributedString;
-    
-    TextLayoutContext textLayoutContext{};
-    textLayoutContext.pointScaleFactor = layoutContext.pointScaleFactor;
-    const auto textLayoutManager = std::make_shared<const TextLayoutManager>(getContextContainer());
-        
-    return textLayoutManager->measure(
-      AttributedStringBox{baseAttributedString},
-      paragraphAttributes,
-      textLayoutContext,
-      layoutConstraints
-    ).size;
+    return baseAttributedString;
 }
 
 void RNUITextViewShadowNode::layout(LayoutContext layoutContext) {
   ensureUnsealed();
+  Float fontSizeMultiplier = 1.0;
+  if (getConcreteProps().allowFontScaling) {
+    fontSizeMultiplier = layoutContext.fontSizeMultiplier;
+  }
+  // Rebuild from the current children instead of trusting _attributedString (see
+  // buildAttributedString comment), then only push a new state when the content
+  // actually changed. layout() runs on every Yoga pass over this subtree (any
+  // ancestor relayout, scroll-driven container updates, etc.); unconditionally
+  // calling setStateData used to fan a state update out to EVERY mounted text
+  // view per commit, which on RN 0.85 caused visible full-screen repaint flashes.
+  auto attributedString = buildAttributedString(fontSizeMultiplier);
+  if (getStateData().attributedString == attributedString) {
+    return;
+  }
   setStateData(RNUITextViewStateReal{
-    _attributedString
+    std::move(attributedString)
   });
 }
 }
diff --git a/ios/RNUITextViewShadowNode.h b/ios/RNUITextViewShadowNode.h
index 27797444bfb990b51c5d63d170d362596a384415..9b1e7bfa57f9fb41f51e561d8b1d3c9b894d3961 100644
--- a/ios/RNUITextViewShadowNode.h
+++ b/ios/RNUITextViewShadowNode.h
@@ -43,6 +43,8 @@ public:
       const LayoutConstraints& layoutConstraints) const override;
 
 private:
+  AttributedString buildAttributedString(Float fontSizeMultiplier) const;
+
   mutable AttributedString _attributedString;
 };
 } // namespace facebook::React
diff --git a/lib/commonjs/RNUITextViewNativeComponent.ts b/lib/commonjs/RNUITextViewNativeComponent.ts
index 1c571b4ac58cf8155769e789d103f99b6146b6dd..9c800ec8aac9f00ba55103b8da738dfd40a13efa 100644
--- a/lib/commonjs/RNUITextViewNativeComponent.ts
+++ b/lib/commonjs/RNUITextViewNativeComponent.ts
@@ -32,6 +32,14 @@ interface NativeProps extends ViewProps {
   allowFontScaling?: WithDefault<boolean, true>
   ellipsizeMode?: WithDefault<EllipsizeMode, 'tail'>
   selectable?: boolean
+  /**
+   * Title of a custom action inserted into the iOS edit menu (the system
+   * Copy / Look Up / Translate menu shown for a text selection). Empty or
+   * unset renders no custom item. iOS 16+ only (editMenuForTextInRange).
+   */
+  menuActionLabel?: string
+  /** Optional second action, placed after menuActionLabel. */
+  sideChatMenuActionLabel?: string
   onTextLayout?: BubblingEventHandler<TextLayoutEvent>
   /**
    * Callback fired when the text selection changes.
@@ -48,6 +56,13 @@ interface NativeProps extends ViewProps {
    * ```
    */
   onSelectionChange?: BubblingEventHandler<SelectionChangeEvent>
+  /**
+   * Fired when the user taps the custom edit-menu action (menuActionLabel).
+   * Payload carries the selected range at tap time; the native side clears
+   * the selection after emitting.
+   */
+  onMenuAction?: BubblingEventHandler<SelectionChangeEvent>
+  onSideChatMenuAction?: BubblingEventHandler<SelectionChangeEvent>
 }
 
 export default codegenNativeComponent<NativeProps>('RNUITextView', {
diff --git a/lib/module/RNUITextViewNativeComponent.ts b/lib/module/RNUITextViewNativeComponent.ts
index 1c571b4ac58cf8155769e789d103f99b6146b6dd..9c800ec8aac9f00ba55103b8da738dfd40a13efa 100644
--- a/lib/module/RNUITextViewNativeComponent.ts
+++ b/lib/module/RNUITextViewNativeComponent.ts
@@ -32,6 +32,14 @@ interface NativeProps extends ViewProps {
   allowFontScaling?: WithDefault<boolean, true>
   ellipsizeMode?: WithDefault<EllipsizeMode, 'tail'>
   selectable?: boolean
+  /**
+   * Title of a custom action inserted into the iOS edit menu (the system
+   * Copy / Look Up / Translate menu shown for a text selection). Empty or
+   * unset renders no custom item. iOS 16+ only (editMenuForTextInRange).
+   */
+  menuActionLabel?: string
+  /** Optional second action, placed after menuActionLabel. */
+  sideChatMenuActionLabel?: string
   onTextLayout?: BubblingEventHandler<TextLayoutEvent>
   /**
    * Callback fired when the text selection changes.
@@ -48,6 +56,13 @@ interface NativeProps extends ViewProps {
    * ```
    */
   onSelectionChange?: BubblingEventHandler<SelectionChangeEvent>
+  /**
+   * Fired when the user taps the custom edit-menu action (menuActionLabel).
+   * Payload carries the selected range at tap time; the native side clears
+   * the selection after emitting.
+   */
+  onMenuAction?: BubblingEventHandler<SelectionChangeEvent>
+  onSideChatMenuAction?: BubblingEventHandler<SelectionChangeEvent>
 }
 
 export default codegenNativeComponent<NativeProps>('RNUITextView', {
diff --git a/src/RNUITextViewNativeComponent.ts b/src/RNUITextViewNativeComponent.ts
index 1c571b4ac58cf8155769e789d103f99b6146b6dd..9c800ec8aac9f00ba55103b8da738dfd40a13efa 100644
--- a/src/RNUITextViewNativeComponent.ts
+++ b/src/RNUITextViewNativeComponent.ts
@@ -32,6 +32,14 @@ interface NativeProps extends ViewProps {
   allowFontScaling?: WithDefault<boolean, true>
   ellipsizeMode?: WithDefault<EllipsizeMode, 'tail'>
   selectable?: boolean
+  /**
+   * Title of a custom action inserted into the iOS edit menu (the system
+   * Copy / Look Up / Translate menu shown for a text selection). Empty or
+   * unset renders no custom item. iOS 16+ only (editMenuForTextInRange).
+   */
+  menuActionLabel?: string
+  /** Optional second action, placed after menuActionLabel. */
+  sideChatMenuActionLabel?: string
   onTextLayout?: BubblingEventHandler<TextLayoutEvent>
   /**
    * Callback fired when the text selection changes.
@@ -48,6 +56,13 @@ interface NativeProps extends ViewProps {
    * ```
    */
   onSelectionChange?: BubblingEventHandler<SelectionChangeEvent>
+  /**
+   * Fired when the user taps the custom edit-menu action (menuActionLabel).
+   * Payload carries the selected range at tap time; the native side clears
+   * the selection after emitting.
+   */
+  onMenuAction?: BubblingEventHandler<SelectionChangeEvent>
+  onSideChatMenuAction?: BubblingEventHandler<SelectionChangeEvent>
 }
 
 export default codegenNativeComponent<NativeProps>('RNUITextView', {
diff --git a/src/Text.tsx b/src/Text.tsx
index 840d76af5a001021b23fb83de18899f8156e1001..fc87b8324ab00bb4067be6943cf81979e35e326f 100644
--- a/src/Text.tsx
+++ b/src/Text.tsx
@@ -39,6 +39,18 @@ type UITextViewProps = TextProps & {
    * off this event should debounce.
    */
   onSelectionChange?: (event: SelectionChangeEvent) => void
+  /**
+   * Title of a custom action inserted into the iOS system edit menu for a
+   * text selection (iOS 16+). Empty/unset renders no custom item.
+   */
+  menuActionLabel?: string
+  sideChatMenuActionLabel?: string
+  /**
+   * Fired when the user taps the custom edit-menu action. Payload carries the
+   * selected range at tap time; the native side clears the selection after.
+   */
+  onMenuAction?: (event: SelectionChangeEvent) => void
+  onSideChatMenuAction?: (event: SelectionChangeEvent) => void
 }
 
 function UITextViewChild({style, children, ...rest}: UITextViewProps) {