@cometchat/chat-uikit-react-native 5.5.2 → 5.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51,6 +51,11 @@ android {
51
51
  disable 'GradleCompatible'
52
52
  }
53
53
 
54
+ // Robolectric needs the merged resources and the real manifest to inflate a view.
55
+ testOptions {
56
+ unitTests.includeAndroidResources = true
57
+ }
58
+
54
59
  compileOptions {
55
60
  sourceCompatibility JavaVersion.VERSION_17
56
61
  targetCompatibility JavaVersion.VERSION_17
@@ -67,6 +72,13 @@ dependencies {
67
72
  implementation "com.facebook.react:react-android"
68
73
  implementation 'androidx.appcompat:appcompat:1.7.1'
69
74
  implementation 'com.google.android.material:material:1.12.0'
75
+
76
+ // Unit tests for the native editor. Robolectric runs real Android framework code off-device,
77
+ // which is the only way to assert on spans: the inline-style rules live in a TextWatcher and
78
+ // their result is a set of spans on an Editable, which no JS-level test can see.
79
+ testImplementation 'junit:junit:4.13.2'
80
+ testImplementation 'org.robolectric:robolectric:4.17'
81
+ testImplementation 'androidx.test:core:1.7.0'
70
82
  }
71
83
 
72
84
  if (isNewArchitectureEnabled()) {
@@ -228,6 +228,48 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
228
228
  // pendingStyles (rather than as independent fields) so they inherit its existing
229
229
  // caret-moved/cleared invalidation instead of needing a parallel copy of it.
230
230
  private var pendingExternalColor: Int? = null
231
+
232
+ /**
233
+ * Inline formatting carried over when the keyboard REPLACES a run of text — accepting a
234
+ * suggestion, autocorrect on space, or swapping a whole word. The styles are read from the
235
+ * first character of the run being replaced, before the text changes, and re-applied to
236
+ * whatever is inserted in its place.
237
+ *
238
+ * Without this the formatting dies with the text it was anchored to: a span records a
239
+ * character range, not the user's intent, so replacing those characters drops it.
240
+ */
241
+ private data class InlineStyleSnapshot(
242
+ val bold: Boolean,
243
+ val italic: Boolean,
244
+ val underline: Boolean,
245
+ val strikethrough: Boolean,
246
+ val externalColor: Int?,
247
+ val externalBackgroundColor: Int?,
248
+ ) {
249
+ val isEmpty: Boolean
250
+ get() = !bold && !italic && !underline && !strikethrough &&
251
+ externalColor == null && externalBackgroundColor == null
252
+
253
+ /**
254
+ * Drops whatever the user has explicitly switched off at the cursor.
255
+ *
256
+ * An explicit "off" outranks inheritance. Without this, clearing a colour and then
257
+ * letting the keyboard replace the word resurrects the colour from the replaced run —
258
+ * the opposite of what the user just asked for. The newly-typed path already honours
259
+ * [explicitlyOffStyles]; the replacement path has to as well.
260
+ */
261
+ fun minus(off: Set<String>): InlineStyleSnapshot = copy(
262
+ bold = bold && !off.contains("bold"),
263
+ italic = italic && !off.contains("italic"),
264
+ underline = underline && !off.contains("underline"),
265
+ strikethrough = strikethrough && !off.contains("strikethrough"),
266
+ externalColor = externalColor.takeIf { !off.contains("externalColor") },
267
+ externalBackgroundColor =
268
+ externalBackgroundColor.takeIf { !off.contains("externalBackgroundColor") },
269
+ )
270
+ }
271
+
272
+ private var inheritedStyles: InlineStyleSnapshot? = null
231
273
  private var pendingExternalBackgroundColor: Int? = null
232
274
 
233
275
  // Store selection for toolbar actions (selection might be lost when clicking toolbar)
@@ -387,6 +429,14 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
387
429
  // the user had exactly that text highlighted. Keyboards also replace text while typing
388
430
  // (rewriting "www" -> "Www.", autocorrect) but with a bare cursor, and those must not
389
431
  // become links. No clipboard read here: Android 12+ toasts on every read.
432
+ // A replacement is about to happen: remember the formatting of the text being
433
+ // replaced so the incoming text can inherit it (see InlineStyleSnapshot).
434
+ inheritedStyles = if (count > 0 && after > 0 && s != null && start < s.length) {
435
+ captureInlineStylesAt(s, start)
436
+ } else {
437
+ null
438
+ }
439
+
390
440
  val selStart = minOf(selectionStart, selectionEnd)
391
441
  val selEnd = maxOf(selectionStart, selectionEnd)
392
442
  if (count > 0 && after > 0 && s != null && start + count <= s.length &&
@@ -465,6 +515,39 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
465
515
  }
466
516
  }
467
517
 
518
+ // The keyboard replaced a run of text (suggestion, autocorrect, word swap).
519
+ // Give the incoming text the formatting the replaced text had, so the colour
520
+ // follows the user's intent rather than the character range it was pinned to.
521
+ if (removedCount > 0 && addedCount > 0 && s != null) {
522
+ inheritedStyles?.let { captured ->
523
+ // Anything the user explicitly switched off wins over what the
524
+ // replaced run happened to carry.
525
+ var snapshot = captured.minus(explicitlyOffStyles)
526
+ // A colour ARMED at the caret is the user's newest intent, so it
527
+ // outranks the colour of the text being replaced. Without this the
528
+ // replaced run won: arm red over a blue word, accept a suggestion, and
529
+ // the replacement came back blue while the armed red survived to
530
+ // colour the next character — two colours in one word. The typed-text
531
+ // path below already defers to pendingStyles; this one has to as well.
532
+ if (pendingStyles.contains("externalColor")) {
533
+ snapshot = snapshot.copy(externalColor = pendingExternalColor)
534
+ }
535
+ if (pendingStyles.contains("externalBackgroundColor")) {
536
+ snapshot = snapshot.copy(
537
+ externalBackgroundColor = pendingExternalBackgroundColor
538
+ )
539
+ }
540
+ val spanStart = changeStart
541
+ val spanEnd = changeStart + addedCount
542
+ if (!snapshot.isEmpty && spanStart < spanEnd && spanEnd <= s.length) {
543
+ isInternalChange = true
544
+ applyInlineStyleSnapshot(s, snapshot, spanStart, spanEnd)
545
+ isInternalChange = false
546
+ }
547
+ }
548
+ inheritedStyles = null
549
+ }
550
+
468
551
  // Apply pending styles to newly typed text
469
552
  if (addedCount > 0 && removedCount == 0 && s != null) {
470
553
  val spanStart = changeStart
@@ -537,6 +620,78 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
537
620
  }
538
621
  }
539
622
 
623
+ // --- Insertion inherits from the character before the caret ---
624
+ //
625
+ // A colour applied over a SELECTION is frozen to that range, so text
626
+ // typed straight after it does not join the run. That is what makes
627
+ // "colour Hello, delete two characters, type p" come out as
628
+ // <color>Hel</color>p. Inherit the colour from the preceding character
629
+ // instead of relying on the span to grow.
630
+ //
631
+ // This covers the character styles too, not only the colours. The
632
+ // earlier scoping to colours was wrong: pendingStyles carries a style
633
+ // the user ARMED at the caret, but a style applied over a SELECTION
634
+ // exists only as a frozen span and is in no Set, so typing on dropped
635
+ // it. Measured on a Pixel: strike through "Doe", colour it, then let
636
+ // the keyboard append the "s" of "Does" — the s came out coloured but
637
+ // not struck, because only the colour was carried here (ENG-40419).
638
+ //
639
+ // pendingStyles wins (the user just picked a colour) and
640
+ // explicitlyOffStyles wins (the user just cleared one); this only fills
641
+ // the gap where neither has an opinion. At position 0, or with the
642
+ // field empty, there is nothing to inherit and the text stays plain.
643
+ //
644
+ // Code is skipped wholesale: inline code and a code block own their
645
+ // own foreground, so inheriting a consumer colour from the character
646
+ // before the caret would paint over the code styling the user just
647
+ // armed.
648
+ val codeArmed = pendingStyles.contains("code") ||
649
+ pendingStyles.contains("codeBlock")
650
+ if (changeStart > 0 && !codeArmed) {
651
+ val neighbour = captureInlineStylesAt(s, changeStart - 1)
652
+ if (!pendingStyles.contains("externalColor") &&
653
+ !explicitlyOffStyles.contains("externalColor")
654
+ ) {
655
+ neighbour?.externalColor?.let { inherited ->
656
+ clearInlineStyleSpans(s, "color", spanStart, spanEnd, keepColor = inherited)
657
+ s.setSpan(
658
+ ExternalForegroundColorSpan(inherited),
659
+ spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
660
+ )
661
+ }
662
+ }
663
+ if (!pendingStyles.contains("externalBackgroundColor") &&
664
+ !explicitlyOffStyles.contains("externalBackgroundColor")
665
+ ) {
666
+ neighbour?.externalBackgroundColor?.let { inherited ->
667
+ clearInlineStyleSpans(s, "backgroundColor", spanStart, spanEnd, keepColor = inherited)
668
+ s.setSpan(
669
+ ExternalBackgroundColorSpan(inherited),
670
+ spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
671
+ )
672
+ }
673
+ }
674
+
675
+ // Carry bold/italic/underline/strikethrough the same way. Skipped
676
+ // when the style is already armed — the pendingStyles block above
677
+ // has applied it, and setting a second span over the same range
678
+ // would leave two identical spans to no purpose. (Not a wire-format
679
+ // problem: spannedToMarkdown segments by span boundary and
680
+ // de-duplicates per segment, so a duplicate emits one tag.)
681
+ if (neighbour != null) {
682
+ fun carry(key: String, present: Boolean, makeSpan: () -> Any) {
683
+ if (!present) return
684
+ if (pendingStyles.contains(key)) return
685
+ if (explicitlyOffStyles.contains(key)) return
686
+ s.setSpan(makeSpan(), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
687
+ }
688
+ carry("bold", neighbour.bold) { StyleSpan(Typeface.BOLD) }
689
+ carry("italic", neighbour.italic) { StyleSpan(Typeface.ITALIC) }
690
+ carry("underline", neighbour.underline) { UnderlineSpan() }
691
+ carry("strikethrough", neighbour.strikethrough) { StrikethroughSpan() }
692
+ }
693
+ }
694
+
540
695
  // Remove explicitly-off styles from newly typed text
541
696
  if (explicitlyOffStyles.isNotEmpty()) {
542
697
  for (offStyle in explicitlyOffStyles) {
@@ -1601,6 +1756,55 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1601
1756
  }
1602
1757
 
1603
1758
  // Synchronous style detection - emits current active styles to JS
1759
+ /** Inline formatting present at [pos] — used to let replacement text inherit it. */
1760
+ private fun captureInlineStylesAt(s: CharSequence, pos: Int): InlineStyleSnapshot? {
1761
+ val spanned = s as? Spanned ?: return null
1762
+ if (pos < 0 || pos >= spanned.length) return null
1763
+ val end = pos + 1
1764
+
1765
+ var bold = false
1766
+ var italic = false
1767
+ spanned.getSpans(pos, end, StyleSpan::class.java).forEach {
1768
+ when (it.style) {
1769
+ Typeface.BOLD -> bold = true
1770
+ Typeface.ITALIC -> italic = true
1771
+ Typeface.BOLD_ITALIC -> { bold = true; italic = true }
1772
+ }
1773
+ }
1774
+
1775
+ return InlineStyleSnapshot(
1776
+ bold = bold,
1777
+ italic = italic,
1778
+ underline = spanned.getSpans(pos, end, UnderlineSpan::class.java).isNotEmpty(),
1779
+ strikethrough = spanned.getSpans(pos, end, StrikethroughSpan::class.java).isNotEmpty(),
1780
+ externalColor = spanned.getSpans(pos, end, ExternalForegroundColorSpan::class.java)
1781
+ .firstOrNull()?.color,
1782
+ externalBackgroundColor = spanned.getSpans(pos, end, ExternalBackgroundColorSpan::class.java)
1783
+ .firstOrNull()?.color,
1784
+ )
1785
+ }
1786
+
1787
+ /** Re-applies [snapshot] over [start, end). Caller owns the isInternalChange guard. */
1788
+ private fun applyInlineStyleSnapshot(
1789
+ s: Editable,
1790
+ snapshot: InlineStyleSnapshot,
1791
+ start: Int,
1792
+ end: Int,
1793
+ ) {
1794
+ if (snapshot.bold) s.setSpan(StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
1795
+ if (snapshot.italic) s.setSpan(StyleSpan(Typeface.ITALIC), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
1796
+ if (snapshot.underline) s.setSpan(UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
1797
+ if (snapshot.strikethrough) s.setSpan(StrikethroughSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
1798
+ snapshot.externalColor?.let {
1799
+ clearInlineStyleSpans(s, "color", start, end, keepColor = it)
1800
+ s.setSpan(ExternalForegroundColorSpan(it), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
1801
+ }
1802
+ snapshot.externalBackgroundColor?.let {
1803
+ clearInlineStyleSpans(s, "backgroundColor", start, end, keepColor = it)
1804
+ s.setSpan(ExternalBackgroundColorSpan(it), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
1805
+ }
1806
+ }
1807
+
1604
1808
  private fun emitActiveStyles() {
1605
1809
  val start = selectionStart
1606
1810
  val end = selectionEnd
@@ -4089,9 +4293,11 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4089
4293
  if (key == "color") {
4090
4294
  pendingExternalColor = color
4091
4295
  pendingStyles.add("externalColor")
4296
+ explicitlyOffStyles.remove("externalColor")
4092
4297
  } else {
4093
4298
  pendingExternalBackgroundColor = color
4094
4299
  pendingStyles.add("externalBackgroundColor")
4300
+ explicitlyOffStyles.remove("externalBackgroundColor")
4095
4301
  }
4096
4302
  pendingStylesInsertPos = selectionStart
4097
4303
  return
@@ -4128,13 +4334,25 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4128
4334
  // No selection: cancel the pending type-ahead style instead of no-oping.
4129
4335
  val target = styleTargetRange()
4130
4336
  if (target == null) {
4337
+ // Record the clear in explicitlyOffStyles, not just by dropping the pending value.
4338
+ // Both inheritance rules ask that set whether the user has switched a style off, and
4339
+ // until this line nothing ever put a colour key in it — so `minus(explicitlyOffStyles)`
4340
+ // and the rule-2 guard were dead for colours and an explicit clear was ignored.
4341
+ // Measured on a Pixel 9 Pro XL: colour "Doe", clear at the caret, type "s", and the
4342
+ // "s" came out red. Using the existing set rather than a new flag also means the clear
4343
+ // expires on a caret move for free, through the invalidation in onSelectionChanged.
4131
4344
  if (key == "color") {
4132
4345
  pendingExternalColor = null
4133
4346
  pendingStyles.remove("externalColor")
4347
+ explicitlyOffStyles.add("externalColor")
4134
4348
  } else {
4135
4349
  pendingExternalBackgroundColor = null
4136
4350
  pendingStyles.remove("externalBackgroundColor")
4351
+ explicitlyOffStyles.add("externalBackgroundColor")
4137
4352
  }
4353
+ // That invalidation is gated on an anchor being set, so a clear has to set one too —
4354
+ // otherwise the "off" would outlive the caret and silence colours elsewhere.
4355
+ pendingStylesInsertPos = selectionStart
4138
4356
  // Clearing the pending colour is not enough. A colour span applied by type-ahead is
4139
4357
  // SPAN_EXCLUSIVE_INCLUSIVE so it grows with typing — a span ending exactly at the cursor
4140
4358
  // would keep swallowing everything typed after the user asked for NO colour. Pin it shut
@@ -1197,6 +1197,20 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
1197
1197
  /// True when the colour was cleared with the caret parked, so the next typed character is
1198
1198
  /// `UIColor.label` rather than inheriting a neighbouring colour.
1199
1199
  private var pendingExternalForegroundCleared: Bool = false
1200
+ /// The background equivalent. removeInlineStyle strips the background straight out of
1201
+ /// typingAttributes rather than arming a pending value, so there is no sentinel in
1202
+ /// `pendingStyles` to read — without this flag a keyboard replacing the word would lift the
1203
+ /// background back off the run it replaced and undo the clear. Reset wherever
1204
+ /// `pendingExternalForegroundCleared` is reset, so both decisions expire together.
1205
+ private var pendingExternalBackgroundCleared: Bool = false
1206
+
1207
+ /// Colour to re-apply to text a keyboard just inserted, with the range it landed in.
1208
+ /// Set in shouldChangeTextIn (before the text changes, while the old run is still
1209
+ /// readable) and consumed in textViewDidChange. Going through typingAttributes does not
1210
+ /// survive — many later sites in this file overwrite it before UIKit inserts.
1211
+ private var pendingInheritColour: UIColor? = nil
1212
+ private var pendingInheritBackground: UIColor? = nil
1213
+ private var pendingInheritRange: NSRange? = nil
1200
1214
 
1201
1215
  /// Typing attributes to forcefully restore after all processing (including async
1202
1216
  /// JS bridge callbacks like syncMentionRanges) completes. Set by autoContinueListOnEnter
@@ -1245,7 +1259,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
1245
1259
  return
1246
1260
  }
1247
1261
  pendingExternalForeground = color
1248
- pendingExternalForegroundCleared = false
1262
+ pendingExternalForegroundCleared = false; pendingExternalBackgroundCleared = false
1249
1263
  pendingStyles.insert(ExternalColorPendingKey)
1250
1264
  }
1251
1265
 
@@ -1475,6 +1489,92 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
1475
1489
  return true
1476
1490
  }
1477
1491
 
1492
+ /// Drops every armed, cleared or deferred inline-style decision and returns typingAttributes
1493
+ /// to plain. The composer is empty, so none of it has anything left to apply to.
1494
+ ///
1495
+ /// Called from two places, and it has to be: `textDidChange` runs only for edits the USER
1496
+ /// made, because UIKit does not post `textDidChangeNotification` for a programmatic
1497
+ /// assignment. Clearing the composer after a send is programmatic — `setTextContent("")` —
1498
+ /// so relying on the notification left the colour armed and the NEXT message came out
1499
+ /// coloured without the user asking. Android resets here because its `setText` does run its
1500
+ /// TextWatcher; this is what gives iOS the same behaviour.
1501
+ private func resetInlineStateForEmptyComposer() {
1502
+ pendingStyles.removeAll()
1503
+ explicitlyOffStyles.removeAll()
1504
+ pendingStylesInsertPos = -1
1505
+ lastKnownTextLength = 0
1506
+ pendingExternalForeground = nil
1507
+ pendingExternalForegroundCleared = false
1508
+ pendingExternalBackgroundCleared = false
1509
+ deferredTypingAttrs = nil
1510
+ // A captured inheritance would otherwise be painted onto the first character of the
1511
+ // next message, which is the same leak by a different route.
1512
+ clearPendingInherit()
1513
+ // Reset typingAttributes to plain so next typed text has no ghost formatting
1514
+ let paragraphStyle = NSMutableParagraphStyle()
1515
+ paragraphStyle.lineHeightMultiple = RichTextEditorView.defaultLineHeightMultiple
1516
+ textView.typingAttributes = [
1517
+ .font: UIFont.systemFont(ofSize: 16),
1518
+ .foregroundColor: UIColor.label,
1519
+ .paragraphStyle: paragraphStyle
1520
+ ]
1521
+ }
1522
+
1523
+ private func clearPendingInherit() {
1524
+ pendingInheritColour = nil
1525
+ pendingInheritBackground = nil
1526
+ pendingInheritRange = nil
1527
+ }
1528
+
1529
+ /// Paints the colour captured in shouldChangeTextIn onto the text the keyboard just inserted.
1530
+ ///
1531
+ /// Called from textDidChange rather than from a textViewDidChange delegate method. Two reasons,
1532
+ /// both learned the hard way:
1533
+ ///
1534
+ /// - textView.insertText (list continuation) fires the delegate synchronously from inside an
1535
+ /// isInternalChange window, so a delegate implementation re-enters mid-edit and, by resetting
1536
+ /// the flag, makes the rest of that edit look like user typing. textDidChange already guards
1537
+ /// on isInternalChange, so it is re-entrancy-safe.
1538
+ /// - textDidChange owns saveToUndoStack and sendContentChange. Mutating here, ahead of both,
1539
+ /// means the inherited colour is in the text before it is emitted to JS or snapshotted for
1540
+ /// undo, rather than depending on UIKit's delegate/notification ordering.
1541
+ private func applyPendingInheritedColour() {
1542
+ guard let range = pendingInheritRange,
1543
+ let attrText = textView.attributedText,
1544
+ range.location >= 0, range.location + range.length <= attrText.length,
1545
+ range.length > 0,
1546
+ pendingInheritColour != nil || pendingInheritBackground != nil else {
1547
+ clearPendingInherit()
1548
+ return
1549
+ }
1550
+
1551
+ // Add the attributes in place rather than assigning `textView.attributedText`.
1552
+ //
1553
+ // Assigning attributedText replaces the whole string, and UITextView ends any marked text
1554
+ // when it does — marked text being the uncommitted, underlined run an input method shows
1555
+ // while a word is still being composed. This method runs on every keystroke that inherits
1556
+ // a colour, so with a Japanese, Chinese or Korean keyboard the composition was torn down
1557
+ // character by character and the word could not be typed at all. Mutating textStorage
1558
+ // leaves the string, the composition and the caret untouched, so none of that arises and
1559
+ // the caret no longer has to be saved and restored either.
1560
+ let storage = textView.textStorage
1561
+ let wasInternal = isInternalChange
1562
+ isInternalChange = true
1563
+ storage.beginEditing()
1564
+ if let colour = pendingInheritColour {
1565
+ storage.addAttribute(ExternalForegroundKey, value: colour, range: range)
1566
+ storage.addAttribute(.foregroundColor, value: colour, range: range)
1567
+ }
1568
+ if let background = pendingInheritBackground {
1569
+ storage.addAttribute(ExternalBackgroundKey, value: background, range: range)
1570
+ storage.addAttribute(.backgroundColor, value: background, range: range)
1571
+ }
1572
+ storage.endEditing()
1573
+ isInternalChange = wasInternal
1574
+
1575
+ clearPendingInherit()
1576
+ }
1577
+
1478
1578
  func textViewDidChangeSelection(_ textView: UITextView) {
1479
1579
  let range = textView.selectedRange
1480
1580
  if range.length > 0 {
@@ -1498,8 +1598,12 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
1498
1598
  // to avoid emitting stale style state before typingAttributes are restored.
1499
1599
  guard !isInternalChange else { return }
1500
1600
 
1501
- // Invalidate pending styles if cursor moved away from insert position
1502
- if pendingStylesInsertPos >= 0 && (!pendingStyles.isEmpty || !explicitlyOffStyles.isEmpty) {
1601
+ // Invalidate pending styles if cursor moved away from insert position.
1602
+ // The cleared-colour flags count as pending decisions in their own right: a background
1603
+ // clear arms no sentinel and leaves both Sets empty, so without them in this condition it
1604
+ // would never expire.
1605
+ if pendingStylesInsertPos >= 0 && (!pendingStyles.isEmpty || !explicitlyOffStyles.isEmpty
1606
+ || pendingExternalForegroundCleared || pendingExternalBackgroundCleared) {
1503
1607
  // Typing advances the caret by however many characters actually landed: one for a plain
1504
1608
  // keystroke, but several for autocorrect replacing a word, predictive text, a multi-scalar
1505
1609
  // emoji, a paste, or an IME commit. Comparing against a hardcoded +1 classified all of
@@ -1516,7 +1620,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
1516
1620
  // Drop the caret-armed colour too — otherwise it leaks onto text typed at the
1517
1621
  // new cursor position (the removeAll() above only drops the sentinel).
1518
1622
  pendingExternalForeground = nil
1519
- pendingExternalForegroundCleared = false
1623
+ pendingExternalForegroundCleared = false; pendingExternalBackgroundCleared = false
1520
1624
  if hadCodeBlock {
1521
1625
  pendingStyles.insert("codeBlock")
1522
1626
  pendingStylesInsertPos = range.location
@@ -1773,6 +1877,93 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
1773
1877
 
1774
1878
  func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
1775
1879
 
1880
+ // --- Inline formatting follows the user's intent, not the character range ---
1881
+ //
1882
+ // Measured on iOS 26: accepting a suggestion arrives as ONE replacement —
1883
+ // loc=0 len=3 text='Respect' (after typing "Res")
1884
+ // so the styled characters are destroyed in a single call and the replacement is
1885
+ // styled from typingAttributes, which knows nothing about them.
1886
+ //
1887
+ // This MUST run before the early returns further down (list prefixes, code blocks,
1888
+ // blockquotes). Placed at the end it never executed, which is why the colour was lost
1889
+ // even with the rules in place.
1890
+ if !isInternalChange, let attrText = textView.attributedText {
1891
+ // Reset first, unconditionally. Every `return false` path below handles its own text
1892
+ // and suppresses UIKit's insertion, so textDidChange never runs and never consumes
1893
+ // what we set here. Without this reset that stale range outlives the change and gets
1894
+ // painted onto whatever text later occupies it.
1895
+ clearPendingInherit()
1896
+
1897
+ var typing = textView.typingAttributes
1898
+ var inheritFrom: [NSAttributedString.Key: Any]? = nil
1899
+
1900
+ // Inline code and a code block own their own foreground, so a consumer colour
1901
+ // inherited from the neighbouring character would paint over the code styling the
1902
+ // user just armed. Android skips the same way.
1903
+ let codeArmed = pendingStyles.contains("code") || pendingStyles.contains("codeBlock")
1904
+
1905
+ if codeArmed {
1906
+ inheritFrom = nil
1907
+ } else if range.length > 0, !text.isEmpty, range.location < attrText.length {
1908
+ // A replacement: inherit from the run being replaced, read before it is gone.
1909
+ inheritFrom = attrText.attributes(at: range.location, effectiveRange: nil)
1910
+ } else if range.length == 0, !text.isEmpty, range.location > 0,
1911
+ range.location - 1 < attrText.length,
1912
+ !pendingStyles.contains(ExternalColorPendingKey),
1913
+ !pendingExternalForegroundCleared {
1914
+ // A plain insertion: inherit from the character before the caret, so text typed
1915
+ // after a frozen run joins it. An armed or just-cleared colour wins over this.
1916
+ inheritFrom = attrText.attributes(at: range.location - 1, effectiveRange: nil)
1917
+ }
1918
+
1919
+ if let src = inheritFrom {
1920
+ // An explicit CLEAR outranks inheritance on both rules: the user turned the
1921
+ // colour off, so a keyboard replacing that word must not resurrect it.
1922
+ //
1923
+ // Only the clear, deliberately — not an armed colour. pendingStyles carries the
1924
+ // sentinel for armed and cleared alike, so testing it here also suppressed
1925
+ // inheritance while a colour was armed, and the armed colour alone does not
1926
+ // survive a replacement: typingAttributes is overwritten before UIKit inserts,
1927
+ // which is the whole reason this pendingInherit path exists. Measured on an
1928
+ // iPhone 17 Pro: colour "Doe", accept the "Doesn't" suggestion, and the word
1929
+ // came through black. explicitlyOffStyles is not consulted either — on iOS it
1930
+ // only ever holds bold/italic/underline/strikethrough/code.
1931
+ let colourCleared = pendingExternalForegroundCleared
1932
+ let backgroundCleared = pendingExternalBackgroundCleared
1933
+
1934
+ // Remember where the incoming text will land so textDidChange can style it.
1935
+ //
1936
+ // An ARMED colour beats the replaced run's: it is the user's newest intent. Before
1937
+ // this the run won, so arming red over a blue word and then accepting a suggestion
1938
+ // gave a blue replacement, while the armed red survived to colour the next
1939
+ // character — two colours in one word. Android has the same precedence at
1940
+ // RichTextEditorView.kt:525.
1941
+ pendingInheritColour = colourCleared
1942
+ ? nil
1943
+ : (pendingExternalForeground ?? src[ExternalForegroundKey] as? UIColor)
1944
+ pendingInheritBackground = backgroundCleared ? nil : src[ExternalBackgroundKey] as? UIColor
1945
+ pendingInheritRange = (pendingInheritColour != nil || pendingInheritBackground != nil)
1946
+ ? NSRange(location: range.location, length: (text as NSString).length)
1947
+ : nil
1948
+
1949
+ var changed = false
1950
+ // Marker and paint move together: the marker is what the serializer reads.
1951
+ // Read the already-filtered pending values, not `src`, so a cleared colour is not
1952
+ // re-armed here after being suppressed above.
1953
+ if let colour = pendingInheritColour {
1954
+ typing[ExternalForegroundKey] = colour
1955
+ typing[.foregroundColor] = colour
1956
+ changed = true
1957
+ }
1958
+ if let background = pendingInheritBackground {
1959
+ typing[ExternalBackgroundKey] = background
1960
+ typing[.backgroundColor] = background
1961
+ changed = true
1962
+ }
1963
+ if changed { textView.typingAttributes = typing }
1964
+ }
1965
+ }
1966
+
1776
1967
  // --- Mention bleed-through prevention (iOS equivalent of Android SPAN_EXCLUSIVE_EXCLUSIVE) ---
1777
1968
  // Check if typingAttributes carry mention styling and strip it before insertion.
1778
1969
  do {
@@ -2431,6 +2622,10 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
2431
2622
  }
2432
2623
 
2433
2624
  if !isInternalChange {
2625
+ // Before anything reads or snapshots the text: give the characters the keyboard just
2626
+ // inserted the formatting they inherited (see applyPendingInheritedColour).
2627
+ applyPendingInheritedColour()
2628
+
2434
2629
  // Clear pending styles after text was typed (typingAttributes already applied them).
2435
2630
  // Preserve inline styles (bold, italic, underline, strikethrough) — they persist
2436
2631
  // until the cursor moves to a different position (matching Android behavior where
@@ -2483,21 +2678,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
2483
2678
 
2484
2679
  // Reset pending styles and typingAttributes when text becomes empty
2485
2680
  if textView.text.isEmpty {
2486
- pendingStyles.removeAll()
2487
- explicitlyOffStyles.removeAll()
2488
- pendingStylesInsertPos = -1
2489
- lastKnownTextLength = 0
2490
- pendingExternalForeground = nil
2491
- pendingExternalForegroundCleared = false
2492
- deferredTypingAttrs = nil
2493
- // Reset typingAttributes to plain so next typed text has no ghost formatting
2494
- let paragraphStyle = NSMutableParagraphStyle()
2495
- paragraphStyle.lineHeightMultiple = RichTextEditorView.defaultLineHeightMultiple
2496
- textView.typingAttributes = [
2497
- .font: UIFont.systemFont(ofSize: 16),
2498
- .foregroundColor: UIColor.label,
2499
- .paragraphStyle: paragraphStyle
2500
- ]
2681
+ resetInlineStateForEmptyComposer()
2501
2682
  }
2502
2683
 
2503
2684
  // Skip applyListIndentation/renumberNumberedLists during internal changes
@@ -3795,7 +3976,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
3795
3976
  return
3796
3977
  }
3797
3978
  pendingExternalForeground = color
3798
- pendingExternalForegroundCleared = false
3979
+ pendingExternalForegroundCleared = false; pendingExternalBackgroundCleared = false
3799
3980
  pendingStyles.insert(ExternalColorPendingKey)
3800
3981
  pendingStylesInsertPos = range.location
3801
3982
  applyPendingStylesToTypingAttributes()
@@ -3825,6 +4006,18 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
3825
4006
  guard attribute == .foregroundColor else {
3826
4007
  textView.typingAttributes.removeValue(forKey: marker)
3827
4008
  textView.typingAttributes.removeValue(forKey: attribute)
4009
+ // Stripping typingAttributes stops the next TYPED character carrying the
4010
+ // background, but a keyboard replacement reads the run it replaces, not
4011
+ // typingAttributes — so record the decision for the inheritance rules too.
4012
+ //
4013
+ // The anchor goes in with it. The caret-move invalidation needs one to compare
4014
+ // against, and this branch arms no sentinel, so without it a background-only
4015
+ // clear never expired: clear after one highlighted word, tap into another, accept
4016
+ // a suggestion there, and that second word silently lost its highlight.
4017
+ if attribute == .backgroundColor {
4018
+ pendingExternalBackgroundCleared = true
4019
+ pendingStylesInsertPos = range.location
4020
+ }
3828
4021
  return
3829
4022
  }
3830
4023
  pendingExternalForeground = nil
@@ -4681,7 +4874,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
4681
4874
  // inline style, so the consumer colour goes with them rather than surviving alone.
4682
4875
  pendingStyles.remove(ExternalColorPendingKey)
4683
4876
  pendingExternalForeground = nil
4684
- pendingExternalForegroundCleared = false
4877
+ pendingExternalForegroundCleared = false; pendingExternalBackgroundCleared = false
4685
4878
  explicitlyOffStyles.removeAll()
4686
4879
  // Reset typingAttributes to plain so list prefix doesn't inherit code block styling
4687
4880
  let plainParaStyle = NSMutableParagraphStyle()
@@ -5438,7 +5631,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
5438
5631
  // Drop an armed consumer colour, or the first character typed into the empty block
5439
5632
  // would come out coloured instead of the code block default.
5440
5633
  pendingExternalForeground = nil
5441
- pendingExternalForegroundCleared = false
5634
+ pendingExternalForegroundCleared = false; pendingExternalBackgroundCleared = false
5442
5635
  pendingStyles.remove(ExternalColorPendingKey)
5443
5636
  pendingStylesInsertPos = textView.selectedRange.location
5444
5637
  isInternalChange = false
@@ -5507,7 +5700,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
5507
5700
  // A colour armed for type-ahead would otherwise colour the next character typed
5508
5701
  // inside the block.
5509
5702
  pendingExternalForeground = nil
5510
- pendingExternalForegroundCleared = false
5703
+ pendingExternalForegroundCleared = false; pendingExternalBackgroundCleared = false
5511
5704
  pendingStyles.remove(ExternalColorPendingKey)
5512
5705
  // Set pendingStyles + typingAttributes so newly typed characters
5513
5706
  // inherit code block mode (matches empty-line activation path)
@@ -5670,6 +5863,15 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
5670
5863
 
5671
5864
  placeholderLabel.isHidden = !text.isEmpty
5672
5865
  isInternalChange = false
5866
+
5867
+ // The composer just became empty programmatically — a send, or a clear from JS. UIKit
5868
+ // posts no change notification for that, so textDidChange never runs and the reset it
5869
+ // owns would never happen: the colour stayed armed and the next message came out
5870
+ // coloured on its own. Reset here instead, matching Android.
5871
+ if (textView.text ?? "").isEmpty {
5872
+ resetInlineStateForEmptyComposer()
5873
+ }
5874
+
5673
5875
  updateContentSize()
5674
5876
  if force {
5675
5877
  sendContentChange()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cometchat/chat-uikit-react-native",
3
- "version": "5.5.2",
3
+ "version": "5.5.3",
4
4
  "description": "Ready-to-use Chat UI Components for React Native",
5
5
  "main": "src/index",
6
6
  "module": "src/index",
@@ -16,6 +16,7 @@
16
16
  "react-native-cometchat-ui-kit.podspec",
17
17
  "!lib/typescript/example",
18
18
  "!android/build",
19
+ "!android/src/test",
19
20
  "!ios/build",
20
21
  "!**/__tests__",
21
22
  "!**/__fixtures__",
@@ -23,6 +24,8 @@
23
24
  ],
24
25
  "scripts": {
25
26
  "test": "jest",
27
+ "test:native:android": "cd ../../examples/masterapp/android && ./gradlew :cometchat_chat-uikit-react-native:testDebugUnitTest",
28
+ "test:native:ios": "cd ios-tests && UDID=$(xcrun simctl list devices available | grep -m1 iPhone | grep -oE '[0-9A-F-]{36}'); if [ -z \"$UDID\" ]; then echo \"No iPhone simulator is available. Install one via Xcode > Settings > Components.\" >&2; exit 1; fi; xcodebuild test -scheme RichTextEditorKit-Package -destination \"platform=iOS Simulator,id=$UDID\"",
26
29
  "typescript": "tsc --noEmit",
27
30
  "lint": "eslint \"**/*.{js,ts,tsx}\"",
28
31
  "release": "release-it",
File without changes
File without changes