@cometchat/chat-uikit-react-native 5.4.0 → 5.5.0

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.
Files changed (72) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatClipboardModule.kt +34 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +605 -6
  3. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +20 -1
  4. package/ios/CometChatClipboardModule.m +5 -0
  5. package/ios/CometChatClipboardModule.swift +22 -0
  6. package/ios/RichTextEditorView.swift +648 -35
  7. package/ios/RichTextEditorViewManager.m +2 -0
  8. package/ios/RichTextEditorViewManager.swift +16 -0
  9. package/package.json +2 -1
  10. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +245 -55
  11. package/src/CometChatCompactMessageComposer/index.ts +2 -0
  12. package/src/CometChatConversations/CometChatConversations.tsx +291 -14
  13. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +181 -12
  14. package/src/CometChatMessageList/CometChatMessageList.tsx +568 -15
  15. package/src/CometChatMessageList/components/MessageModals.tsx +30 -0
  16. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +14 -1
  17. package/src/CometChatMessageList/components/MessageQuickActions.tsx +162 -0
  18. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +940 -0
  19. package/src/CometChatPinnedMessages/index.ts +5 -0
  20. package/src/CometChatPinnedMessages/style.ts +216 -0
  21. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +5 -0
  22. package/src/CometChatRichTextEditor/index.tsx +27 -1
  23. package/src/CometChatRichTextEditor/types.ts +19 -1
  24. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +634 -0
  25. package/src/CometChatSavedMessages/index.ts +5 -0
  26. package/src/CometChatSavedMessages/style.ts +159 -0
  27. package/src/CometChatSearch/CometChatSearch.tsx +47 -340
  28. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +22 -2
  29. package/src/index.ts +60 -0
  30. package/src/shared/CometChatUiKit/CometChatUIKit.ts +16 -0
  31. package/src/shared/base/Types.ts +5 -0
  32. package/src/shared/constants/UIKitConstants.ts +13 -0
  33. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +34 -0
  34. package/src/shared/events/CometChatUIEventHandler/Listener.ts +37 -0
  35. package/src/shared/events/ListenerInitializer.ts +20 -1
  36. package/src/shared/events/messages.ts +18 -0
  37. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +95 -8
  38. package/src/shared/formatters/index.ts +14 -0
  39. package/src/shared/formatters/richTextWireFormat.ts +165 -0
  40. package/src/shared/framework/MessageDataSource.tsx +296 -3
  41. package/src/shared/icons/components/thread-follow.tsx +13 -0
  42. package/src/shared/icons/components/thread-unfollow.tsx +13 -0
  43. package/src/shared/icons/components/unsave.tsx +13 -0
  44. package/src/shared/icons/icon-mapping.tsx +6 -0
  45. package/src/shared/index.ts +37 -0
  46. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +54 -0
  47. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +2 -1
  48. package/src/shared/utils/MarkdownUtils.ts +25 -4
  49. package/src/shared/utils/MessageUtils.tsx +80 -5
  50. package/src/shared/utils/PinConversationHelper.ts +245 -0
  51. package/src/shared/utils/PinSaveFeatureGates.ts +178 -0
  52. package/src/shared/utils/PinSaveHelper.ts +549 -0
  53. package/src/shared/utils/SavedMessagesHelper.ts +231 -0
  54. package/src/shared/utils/ThreadSubscriptionHelper.ts +427 -0
  55. package/src/shared/utils/conversationUtils.ts +8 -1
  56. package/src/shared/utils/elementType.tsx +38 -0
  57. package/src/shared/utils/stripRichText.ts +7 -0
  58. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +21 -0
  59. package/src/shared/views/ClipboardPasteHandler/NativeCometChatClipboardModule.ts +6 -0
  60. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +4 -0
  61. package/src/shared/views/CometChatAvatar/CometChatAvatar.tsx +17 -5
  62. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +28 -14
  63. package/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx +2 -0
  64. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +91 -20
  65. package/src/shared/views/CometChatList/CometChatList.tsx +6 -1
  66. package/src/shared/views/CometChatListItem/CometChatListItem.tsx +4 -0
  67. package/src/shared/views/CometChatRetryButton/CometChatRetryButton.tsx +1 -0
  68. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +4 -0
  69. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +4 -3
  70. package/src/shared/views/ErrorEmptyView/ErrorEmptyView.tsx +4 -1
  71. package/src/theme/default/default.ts +6 -0
  72. package/src/theme/type.ts +4 -0
@@ -31,6 +31,7 @@ import android.view.View
31
31
  import android.view.ViewGroup
32
32
  import android.view.WindowManager
33
33
  import android.view.inputmethod.EditorInfo
34
+ import android.view.inputmethod.InputMethodManager
34
35
  import android.widget.PopupWindow
35
36
  import android.widget.FrameLayout
36
37
  import android.content.res.Configuration
@@ -105,6 +106,38 @@ class MentionSpan(val uid: String, val displayName: String) : CharacterStyle() {
105
106
  }
106
107
  }
107
108
 
109
+ /**
110
+ * Foreground colour applied by a consumer formatter via applyInlineStyle().
111
+ *
112
+ * Deliberately NOT a `ForegroundColorSpan` subclass. Two reasons:
113
+ * 1. 17 sites in this file sweep `ForegroundColorSpan` indiscriminately (they own the
114
+ * inline-code purple, link blue, code-block grey, transparent quote prefix and mention
115
+ * purple). A subclass would be silently clobbered by every one of them; a sibling type
116
+ * is invisible to all of them by construction.
117
+ * 2. `ForegroundColorSpan` is a `ParcelableSpan`; a subclass reports the *parent's* span
118
+ * type id, so clipboard / saved-instance-state round-trips would downgrade this marker
119
+ * into a plain colour span, indistinguishable from the editor's own colour plumbing.
120
+ *
121
+ * It actually paints, so it implements `UpdateAppearance` to make repaints correct.
122
+ */
123
+ class ExternalForegroundColorSpan(val color: Int) : CharacterStyle(), UpdateAppearance {
124
+ override fun updateDrawState(tp: android.text.TextPaint?) {
125
+ tp?.color = color
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Background colour applied by a consumer formatter. A sibling type for the same reasons as
131
+ * [ExternalForegroundColorSpan] — 12 sites sweep `BackgroundColorSpan` indiscriminately (mention
132
+ * background, highlight, inline code, code block). Setting `TextPaint.bgColor` is exactly how
133
+ * `BackgroundColorSpan` itself renders, so this paints identically without being caught by them.
134
+ */
135
+ class ExternalBackgroundColorSpan(val color: Int) : CharacterStyle(), UpdateAppearance {
136
+ override fun updateDrawState(tp: android.text.TextPaint?) {
137
+ tp?.bgColor = color
138
+ }
139
+ }
140
+
108
141
  /**
109
142
  * Custom URLSpan that suppresses the default underline drawn by ClickableSpan.
110
143
  * Links are visually distinguished by ForegroundColorSpan (blue) only, matching iOS parity.
@@ -165,6 +198,10 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
165
198
  /// Produces a stable map key for an IntRange.
166
199
  private fun rangeKey(range: IntRange): String = "${range.first}_${range.last}"
167
200
 
201
+ /// Formats a colour int as the lowercase `#rrggbb` string the JS wire format expects.
202
+ /// Alpha is intentionally dropped — the wire contract is `#rrggbb` only.
203
+ private fun hexOf(color: Int): String = String.format("#%06x", color and 0xFFFFFF)
204
+
168
205
  // Theme-derived colors for inline code container drawing (set via React props)
169
206
  var inlineCodeBackgroundColor: Int? = null
170
207
  var inlineCodeBorderColor: Int? = null
@@ -187,6 +224,11 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
187
224
  private val pendingStyles = mutableSetOf<String>()
188
225
  private val explicitlyOffStyles = mutableSetOf<String>() // Styles user explicitly turned off at cursor
189
226
  private var pendingStylesInsertPos = -1
227
+ // Colour values for the "externalColor"/"externalBackgroundColor" pending styles. Kept beside
228
+ // pendingStyles (rather than as independent fields) so they inherit its existing
229
+ // caret-moved/cleared invalidation instead of needing a parallel copy of it.
230
+ private var pendingExternalColor: Int? = null
231
+ private var pendingExternalBackgroundColor: Int? = null
190
232
 
191
233
  // Store selection for toolbar actions (selection might be lost when clicking toolbar)
192
234
  private var savedSelectionStart: Int = 0
@@ -236,6 +278,62 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
236
278
  }
237
279
  })
238
280
 
281
+ // ── Typing traits (autocorrect / autocapitalize / spellcheck) ────────────────
282
+ //
283
+ // Autocorrect / sentence capitalization / suggestions are never pinned to a fixed
284
+ // value. In prose the editor asks for exactly the flags RN's own
285
+ // ReactTextInputManager emits for a plain TextInput, so the IME's language and the
286
+ // user's keyboard settings decide; on top of that the editor drops all of them by
287
+ // itself while the caret sits in code (see [isCodeContext]), so autocorrect never
288
+ // rewrites a code sample.
289
+
290
+ /** True while the caret/selection sits inside a code block or an inline code span. */
291
+ private var isCodeContext = false
292
+
293
+ /** Called on every selection/style update with the resolved code state. */
294
+ private fun setCodeContext(inCode: Boolean) {
295
+ if (inCode == isCodeContext) return
296
+ isCodeContext = inCode
297
+ applyTypingTraits()
298
+ }
299
+
300
+ /**
301
+ * Resolves inputType for the caret's current context and applies it, restarting the
302
+ * IME only when the resolved value actually changed — i.e. when the caret crosses a
303
+ * code boundary, never mid-word in prose.
304
+ */
305
+ private fun applyTypingTraits() {
306
+ var flags = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
307
+
308
+ flags = flags or if (isCodeContext) {
309
+ // Capitalizing `teh` to `Teh` inside a code block corrupts the snippet the
310
+ // user is typing, so code always opts out.
311
+ EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS
312
+ } else {
313
+ // The RN TextInput defaults: autoCapitalize="sentences" + autoCorrect=true.
314
+ EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES or EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT
315
+ }
316
+
317
+ if (inputType == flags) return
318
+
319
+ // setInputType() rebuilds the key listener; it only rewrites text/typeface for
320
+ // password variations (never our case), but the caret is restored defensively.
321
+ val selStart = selectionStart
322
+ val selEnd = selectionEnd
323
+ inputType = flags
324
+ if (selStart in 0..length() && selEnd in 0..length() &&
325
+ (selectionStart != selStart || selectionEnd != selEnd)
326
+ ) {
327
+ setSelection(selStart, selEnd)
328
+ }
329
+
330
+ // The IME reads the flags when input starts, so a keyboard already up needs a restart.
331
+ if (hasFocus()) {
332
+ (context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)
333
+ ?.restartInput(this)
334
+ }
335
+ }
336
+
239
337
  init {
240
338
  density = context.resources.displayMetrics.density
241
339
  minHeightPx = 64 * density
@@ -253,7 +351,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
253
351
  gravity = Gravity.TOP or Gravity.START
254
352
  isFocusable = true
255
353
  isFocusableInTouchMode = true
256
- inputType = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
354
+ applyTypingTraits()
257
355
 
258
356
  // Disable vertical scrolling by default
259
357
  isVerticalScrollBarEnabled = false
@@ -377,6 +475,19 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
377
475
  "italic" -> s.setSpan(StyleSpan(Typeface.ITALIC), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
378
476
  "underline" -> s.setSpan(UnderlineSpan(), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
379
477
  "strikethrough" -> s.setSpan(StrikethroughSpan(), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
478
+ // These spans are EXCLUSIVE_INCLUSIVE so a colour keeps
479
+ // applying as the user types. That also means an OLDER
480
+ // colour span grows over text typed after a new colour was
481
+ // armed, leaving two colours on the same characters. Cut
482
+ // the previous colour back to where this one starts.
483
+ "externalColor" -> pendingExternalColor?.let {
484
+ clearInlineStyleSpans(s, "color", spanStart, spanEnd, keepColor = it)
485
+ s.setSpan(ExternalForegroundColorSpan(it), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
486
+ }
487
+ "externalBackgroundColor" -> pendingExternalBackgroundColor?.let {
488
+ clearInlineStyleSpans(s, "backgroundColor", spanStart, spanEnd, keepColor = it)
489
+ s.setSpan(ExternalBackgroundColorSpan(it), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
490
+ }
380
491
  "code" -> {
381
492
  val fontSize = inlineCodeFontSize ?: 12f
382
493
  s.setSpan(AbsoluteSizeSpan(fontSize.toInt(), true), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
@@ -501,7 +612,14 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
501
612
  if (addedCount > 1 && removedCount == 0 && s != null) {
502
613
  val insertedStart = changeStart
503
614
  val insertedEnd = (changeStart + addedCount).coerceAtMost(s.length)
504
- val insertedText = s.subSequence(insertedStart, insertedEnd).toString()
615
+ // A copy from CometChat puts the PLAIN text on the clipboard (so `<color=…>`
616
+ // can never leak into another app) and the wire form in a private clip
617
+ // extra. Nothing read that extra back, so a copy/paste inside CometChat
618
+ // always arrived stripped of its colour — `markdownToSpannable` below
619
+ // handles `<color=…>` fine, it was simply never given it (ENG-38253).
620
+ val insertedText = richTextForPaste(
621
+ s.subSequence(insertedStart, insertedEnd).toString()
622
+ )
505
623
  if (looksLikeMarkdown(insertedText)) {
506
624
  // Check that the inserted text doesn't already have styled spans
507
625
  // (would mean it came through onTextContextMenuItem or blocksToSpannable)
@@ -627,6 +745,13 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
627
745
  s.removeSpan(span)
628
746
  }
629
747
  }
748
+ // Consumer colours are applied SPAN_EXCLUSIVE_INCLUSIVE while typing, so a
749
+ // zero-length ghost would resurrect the colour after the text is deleted.
750
+ s.getSpans(cursorPos, cursorPos, ExternalForegroundColorSpan::class.java).forEach { span ->
751
+ if (s.getSpanStart(span) == s.getSpanEnd(span)) {
752
+ s.removeSpan(span)
753
+ }
754
+ }
630
755
  }
631
756
 
632
757
  // Detect markdown shortcuts (e.g., **text** → bold) and convert to
@@ -1577,6 +1702,11 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1577
1702
  }
1578
1703
  }
1579
1704
  val codeBlockActive = hasCodeBlock || pendingStyles.contains("codeBlock")
1705
+
1706
+ // Autocorrect/autocapitalize/spellcheck follow the caret: off in code, platform
1707
+ // default everywhere else.
1708
+ setCodeContext(codeActive || codeBlockActive)
1709
+
1580
1710
  map.putBoolean("code", codeActive)
1581
1711
  map.putBoolean("codeBlock", codeBlockActive)
1582
1712
  map.putBoolean("highlight", hasHighlight)
@@ -2241,6 +2371,29 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2241
2371
  val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
2242
2372
  val clip = clipboard?.primaryClip
2243
2373
 
2374
+ // 0. Our own rich-text wire format, carried in the clip's extras. Checked before
2375
+ // HTML because a CometChat copy sets plain text only — the colour lives here,
2376
+ // and the plain-text type is deliberately clean so other apps never see markup.
2377
+ val wireText = clip?.description?.extras
2378
+ ?.getString(CometChatClipboardModule.EXTRA_RICH_TEXT)
2379
+ if (!wireText.isNullOrEmpty()) {
2380
+ val s = text as? Editable
2381
+ if (s != null) {
2382
+ val start = selectionStart
2383
+ val end = selectionEnd
2384
+ isInternalChange = true
2385
+ s.replace(
2386
+ start.coerceAtMost(end),
2387
+ start.coerceAtLeast(end),
2388
+ markdownToSpannable(wireText)
2389
+ )
2390
+ isInternalChange = false
2391
+ sendContentChangeWithDelta()
2392
+ saveToUndoStack()
2393
+ return true
2394
+ }
2395
+ }
2396
+
2244
2397
  // 1. Check for HTML rich content first (Req 18.2)
2245
2398
  if (clip != null && clip.description.hasMimeType("text/html")) {
2246
2399
  val htmlText = clip.getItemAt(0)?.htmlText
@@ -2533,6 +2686,8 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2533
2686
 
2534
2687
  /** Returns true if the string contains markdown syntax that should be parsed into rich text. */
2535
2688
  private fun looksLikeMarkdown(str: String): Boolean {
2689
+ // Rich-text wire format — only ever reaches here from our own clipboard extra.
2690
+ if (str.contains("<color=", ignoreCase = true)) return true
2536
2691
  if (str.contains("[") && str.contains("](")) return true
2537
2692
  if (str.contains("**")) return true
2538
2693
  if (str.contains("~~")) return true
@@ -2543,6 +2698,28 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2543
2698
  return false
2544
2699
  }
2545
2700
 
2701
+ /**
2702
+ * The rich-text WIRE form of [inserted] when this paste came from a CometChat copy, else
2703
+ * [inserted] unchanged.
2704
+ *
2705
+ * The match is on the clipboard's own plain text: only a paste of exactly what we copied may be
2706
+ * swapped for the wire form. A partial paste, or a clipboard that has moved on since, falls
2707
+ * through untouched rather than pasting the wrong message's markup.
2708
+ */
2709
+ private fun richTextForPaste(inserted: String): String {
2710
+ return try {
2711
+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
2712
+ ?: return inserted
2713
+ val clip = cm.primaryClip ?: return inserted
2714
+ val wire = clip.description?.extras
2715
+ ?.getString(CometChatClipboardModule.EXTRA_RICH_TEXT) ?: return inserted
2716
+ val plain = clip.getItemAt(0)?.text?.toString() ?: return inserted
2717
+ if (inserted == plain) wire else inserted
2718
+ } catch (e: Exception) {
2719
+ inserted
2720
+ }
2721
+ }
2722
+
2546
2723
  /** Normalizes a URL by prepending https:// if no recognized scheme is present. */
2547
2724
  private fun normalizeURL(url: String): String {
2548
2725
  val lower = url.lowercase()
@@ -2567,6 +2744,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2567
2744
 
2568
2745
  // Active style state
2569
2746
  var isBold = false
2747
+ var activePasteColor: Int? = null
2570
2748
  var isItalic = false
2571
2749
  var isUnderline = false
2572
2750
  var isStrikethrough = false
@@ -2596,10 +2774,41 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2596
2774
  val codeColor = if (isDarkMode()) Color.parseColor("#E0E0E0") else Color.parseColor("#333333")
2597
2775
  result.setSpan(ForegroundColorSpan(codeColor), segStart, segEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
2598
2776
  }
2777
+ // A pasted colour behaves like any other consumer-applied colour once inserted — and it
2778
+ // wins over inline code's own foreground, so this goes in AFTER the code span. Two
2779
+ // foreground spans over one range are applied in the order they were added, so while the
2780
+ // colour was set first the code colour painted straight over it and a copied coloured
2781
+ // message pasted back uniformly grey (ENG-38253). iOS had the same defect in mirror image.
2782
+ activePasteColor?.let {
2783
+ result.setSpan(ExternalForegroundColorSpan(it), segStart, segEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
2784
+ }
2599
2785
  currentText.clear()
2600
2786
  }
2601
2787
 
2602
2788
  while (i < len) {
2789
+ // <color=#rrggbb> … </color> — same grammar the formatter renders.
2790
+ if (chars[i] == '<') {
2791
+ val rest = markdown.substring(i)
2792
+ if (rest.startsWith("</color>", ignoreCase = true)) {
2793
+ flush()
2794
+ activePasteColor = null
2795
+ i += 8
2796
+ continue
2797
+ }
2798
+ if (rest.startsWith("<color=", ignoreCase = true)) {
2799
+ val close = rest.indexOf('>')
2800
+ if (close > 0) {
2801
+ val hex = rest.substring(7, close).trim()
2802
+ val parsed = try { Color.parseColor(hex) } catch (e: Exception) { null }
2803
+ if (parsed != null) {
2804
+ flush()
2805
+ activePasteColor = parsed
2806
+ i += close + 1
2807
+ continue
2808
+ }
2809
+ }
2810
+ }
2811
+ }
2603
2812
  // Markdown link: [text](url)
2604
2813
  if (chars[i] == '[') {
2605
2814
  val linkResult = parseLinkAt(chars, i)
@@ -3032,6 +3241,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3032
3241
  map.putString("text", (text?.toString() ?: "").replace("\u200B", ""))
3033
3242
  // Serialize blocks to JSON string (codegen doesn't support nested arrays)
3034
3243
  map.putString("blocksJson", getBlocksJsonString())
3244
+ map.putString("mentionRangesJson", currentMentionRangesJson())
3035
3245
 
3036
3246
  // Include delta information if available
3037
3247
  if (delta != null) {
@@ -3241,6 +3451,15 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3241
3451
  spannable.setSpan(ForegroundColorSpan(codeColor), absoluteStart, absoluteEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
3242
3452
  }
3243
3453
  "highlight" -> spannable.setSpan(BackgroundColorSpan(Color.parseColor("#80FFFF00")), absoluteStart, absoluteEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
3454
+ "textColor" -> {
3455
+ // Edit round-trip: restore a consumer colour from the wire format so the
3456
+ // composer shows the colour rather than raw <color=…> text.
3457
+ val hex = styleInfo["color"] as? String
3458
+ val parsed = try { hex?.let { Color.parseColor(it) } } catch (e: Exception) { null }
3459
+ if (parsed != null) {
3460
+ spannable.setSpan(ExternalForegroundColorSpan(parsed), absoluteStart, absoluteEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
3461
+ }
3462
+ }
3244
3463
  "link" -> {
3245
3464
  val url = styleInfo["url"] as? String ?: ""
3246
3465
  if (url.isNotEmpty()) {
@@ -3292,6 +3511,52 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3292
3511
  pendingStyles.add("codeBlock")
3293
3512
  pendingStylesInsertPos = endPos
3294
3513
  }
3514
+
3515
+ // Arm the INLINE styles the caret lands in, so typing CONTINUES the run the message
3516
+ // ended with. iOS gets this for free — UITextView derives its typingAttributes from
3517
+ // the character before the insertion point — but here every span above is
3518
+ // SPAN_EXCLUSIVE_EXCLUSIVE, so text appended at the end extends none of them and
3519
+ // only `codeBlock` was ever armed. Opening a message that ended in inline code and
3520
+ // typing therefore dropped straight out of the code (and its colour) mid-word, while
3521
+ // the same edit on iOS carried both (ENG-38253).
3522
+ //
3523
+ // `pendingStyles` is the established mechanism: the TextWatcher applies each armed
3524
+ // style over the inserted range as SPAN_EXCLUSIVE_INCLUSIVE, which is exactly the
3525
+ // "keep applying as the user types" behaviour wanted here.
3526
+ var armedInline = false
3527
+ if (spannable.getSpans(checkPos, checkPos + 1, InlineCodeSpan::class.java).isNotEmpty()) {
3528
+ pendingStyles.add("code")
3529
+ armedInline = true
3530
+ }
3531
+ spannable.getSpans(checkPos, checkPos + 1, StyleSpan::class.java).forEach { span ->
3532
+ // BOLD_ITALIC is a bitmask, not a third case — test the bits, don't match values.
3533
+ if (span.style and Typeface.BOLD != 0) {
3534
+ pendingStyles.add("bold")
3535
+ armedInline = true
3536
+ }
3537
+ if (span.style and Typeface.ITALIC != 0) {
3538
+ pendingStyles.add("italic")
3539
+ armedInline = true
3540
+ }
3541
+ }
3542
+ if (spannable.getSpans(checkPos, checkPos + 1, UnderlineSpan::class.java).isNotEmpty()) {
3543
+ pendingStyles.add("underline")
3544
+ armedInline = true
3545
+ }
3546
+ if (spannable.getSpans(checkPos, checkPos + 1, StrikethroughSpan::class.java).isNotEmpty()) {
3547
+ pendingStyles.add("strikethrough")
3548
+ armedInline = true
3549
+ }
3550
+ spannable.getSpans(checkPos, checkPos + 1, ExternalForegroundColorSpan::class.java)
3551
+ .firstOrNull()?.let { span ->
3552
+ // The consumer colour rides its own pending slot, not `pendingStyles` alone.
3553
+ pendingExternalColor = span.color
3554
+ pendingStyles.add("externalColor")
3555
+ armedInline = true
3556
+ }
3557
+ if (armedInline) {
3558
+ pendingStylesInsertPos = endPos
3559
+ }
3295
3560
  }
3296
3561
  }
3297
3562
 
@@ -3369,6 +3634,24 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3369
3634
  styles.add(mapOf("style" to "code", "start" to start, "end" to end))
3370
3635
  }
3371
3636
 
3637
+ // Consumer inline colour. Offsets are already relative to the block prefix
3638
+ // (`• `/`▎ `/`1. ` and ZWS are stripped by the callers before extraction), so a colour
3639
+ // range can never cover a list/quote glyph.
3640
+ spannable.getSpans(lineStart, lineEnd, ExternalForegroundColorSpan::class.java).forEach { span ->
3641
+ val start = (spannable.getSpanStart(span) - lineStart).coerceAtLeast(0)
3642
+ val end = (spannable.getSpanEnd(span) - lineStart).coerceAtMost(lineEnd - lineStart)
3643
+ if (end > start) {
3644
+ styles.add(
3645
+ mapOf(
3646
+ "style" to "textColor",
3647
+ "start" to start,
3648
+ "end" to end,
3649
+ "color" to hexOf(span.color)
3650
+ )
3651
+ )
3652
+ }
3653
+ }
3654
+
3372
3655
  spannable.getSpans(lineStart, lineEnd, BackgroundColorSpan::class.java).filter {
3373
3656
  val color = it.backgroundColor
3374
3657
  color == Color.parseColor("#80FFFF00") || color == Color.YELLOW
@@ -3459,6 +3742,8 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3459
3742
  styleMap.putInt("end", style["end"] as Int)
3460
3743
  val url = style["url"] as? String
3461
3744
  if (url != null) styleMap.putString("url", url)
3745
+ val color = style["color"] as? String
3746
+ if (color != null) styleMap.putString("color", color)
3462
3747
  stylesArray.pushMap(styleMap)
3463
3748
  }
3464
3749
  block.putArray("styles", stylesArray)
@@ -3523,6 +3808,10 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3523
3808
  styleObj.put("end", style["end"])
3524
3809
  val url = style["url"] as? String
3525
3810
  if (url != null) styleObj.put("url", url)
3811
+ // textColor is value-carrying: without the hex the JS side sees a colour range it
3812
+ // cannot render, and drops it — colour shows in the composer but not in the bubble.
3813
+ val color = style["color"] as? String
3814
+ if (color != null) styleObj.put("color", color)
3526
3815
  stylesJson.put(styleObj)
3527
3816
  }
3528
3817
  block.put("styles", stylesJson)
@@ -3705,6 +3994,211 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3705
3994
  updateToolbarButtonStates()
3706
3995
  }
3707
3996
 
3997
+ /**
3998
+ * Selection to style: the live selection, falling back to the saved one because tapping a
3999
+ * toolbar button can clear it. Returns null when there is nothing to style.
4000
+ */
4001
+ private fun styleTargetRange(): Pair<Int, Int>? {
4002
+ var start = selectionStart
4003
+ var end = selectionEnd
4004
+ if (start >= end && savedSelectionStart < savedSelectionEnd) {
4005
+ start = savedSelectionStart
4006
+ end = savedSelectionEnd
4007
+ }
4008
+ val textLength = text?.length ?: 0
4009
+ start = start.coerceIn(0, textLength)
4010
+ end = end.coerceIn(start, textLength)
4011
+ return if (start < end) Pair(start, end) else null
4012
+ }
4013
+
4014
+ /**
4015
+ * Drops consumer-applied [key] spans inside [start]..[end], preserving the parts that fall
4016
+ * outside it. getSpans() also returns spans that merely OVERLAP the range, so removing them
4017
+ * outright would clear colour beyond it; the outside parts are re-applied instead. This is
4018
+ * what iOS gets implicitly, since an attributed-string attribute is per-character.
4019
+ */
4020
+ private fun clearInlineStyleSpans(
4021
+ spannable: Editable,
4022
+ key: String,
4023
+ start: Int,
4024
+ end: Int,
4025
+ keepColor: Int? = null,
4026
+ ) {
4027
+ val spans: Array<out Any> = when (key) {
4028
+ "color" -> spannable.getSpans(start, end, ExternalForegroundColorSpan::class.java)
4029
+ "backgroundColor" -> spannable.getSpans(start, end, ExternalBackgroundColorSpan::class.java)
4030
+ else -> return
4031
+ }
4032
+ spans.forEach { span ->
4033
+ val spanStart = spannable.getSpanStart(span)
4034
+ val spanEnd = spannable.getSpanEnd(span)
4035
+ val color = when (span) {
4036
+ is ExternalForegroundColorSpan -> span.color
4037
+ is ExternalBackgroundColorSpan -> span.color
4038
+ else -> return@forEach
4039
+ }
4040
+ // Leave a span that already carries the colour being applied. Trimming and re-setting
4041
+ // it per keystroke would shatter one run into a chain of one-character spans, each
4042
+ // emitting its own <color=…> tag.
4043
+ if (keepColor != null && color == keepColor) return@forEach
4044
+ spannable.removeSpan(span)
4045
+ if (spanStart < start) {
4046
+ spannable.setSpan(
4047
+ if (key == "color") ExternalForegroundColorSpan(color) else ExternalBackgroundColorSpan(color),
4048
+ spanStart, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
4049
+ )
4050
+ }
4051
+ if (spanEnd > end) {
4052
+ spannable.setSpan(
4053
+ if (key == "color") ExternalForegroundColorSpan(color) else ExternalBackgroundColorSpan(color),
4054
+ end, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
4055
+ )
4056
+ }
4057
+ }
4058
+ }
4059
+
4060
+ /**
4061
+ * Applies an arbitrary inline style to the current selection, skipping mentions so a
4062
+ * consumer's formatter cannot recolour a mention (§8.2 S4). [color] is an ARGB int from
4063
+ * RN's processColor(). Styles of *different* kinds compose (S3), but a second colour
4064
+ * replaces the first — a character has exactly one foreground colour.
4065
+ *
4066
+ * ponytail: colours are the only inline style a trailing-button formatter needs today —
4067
+ * widen the `when` if fonts/spacing ever follow.
4068
+ */
4069
+ fun applyInlineStyle(key: String, color: Int) {
4070
+ if (key != "color" && key != "backgroundColor") return
4071
+
4072
+ // No selection: style what gets typed next, matching the built-in bold/italic/code
4073
+ // type-ahead rather than silently doing nothing.
4074
+ val target = styleTargetRange()
4075
+ if (target == null) {
4076
+ if (key == "color") {
4077
+ pendingExternalColor = color
4078
+ pendingStyles.add("externalColor")
4079
+ } else {
4080
+ pendingExternalBackgroundColor = color
4081
+ pendingStyles.add("externalBackgroundColor")
4082
+ }
4083
+ pendingStylesInsertPos = selectionStart
4084
+ return
4085
+ }
4086
+
4087
+ val (start, end) = target
4088
+ val spannable = text as? Editable ?: return
4089
+
4090
+ isInternalChange = true
4091
+ nonMentionRanges(start, end, spannable).forEach { range ->
4092
+ val rangeStart = range.first
4093
+ val rangeEnd = range.last + 1
4094
+ // Recolouring must REPLACE, not stack. Leaving the old span underneath makes
4095
+ // extraction report two overlapping textColor ranges for the same characters, and the
4096
+ // JS side keeps whichever it sees first — so the earlier colour wins in the sent
4097
+ // message even though the newer one is what the composer paints.
4098
+ clearInlineStyleSpans(spannable, key, rangeStart, rangeEnd)
4099
+ val span: Any =
4100
+ if (key == "color") ExternalForegroundColorSpan(color)
4101
+ else ExternalBackgroundColorSpan(color)
4102
+ spannable.setSpan(span, rangeStart, rangeEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
4103
+ }
4104
+ setSelection(start, end)
4105
+ isInternalChange = false
4106
+ invalidate()
4107
+ sendContentChange()
4108
+ }
4109
+
4110
+ /**
4111
+ * Removes a previously applied inline style from the current selection. Only consumer-applied
4112
+ * spans are removed — mention/link/code colouring is left intact.
4113
+ */
4114
+ fun removeInlineStyle(key: String) {
4115
+ // No selection: cancel the pending type-ahead style instead of no-oping.
4116
+ val target = styleTargetRange()
4117
+ if (target == null) {
4118
+ if (key == "color") {
4119
+ pendingExternalColor = null
4120
+ pendingStyles.remove("externalColor")
4121
+ } else {
4122
+ pendingExternalBackgroundColor = null
4123
+ pendingStyles.remove("externalBackgroundColor")
4124
+ }
4125
+ // Clearing the pending colour is not enough. A colour span applied by type-ahead is
4126
+ // SPAN_EXCLUSIVE_INCLUSIVE so it grows with typing — a span ending exactly at the cursor
4127
+ // would keep swallowing everything typed after the user asked for NO colour. Pin it shut
4128
+ // by re-applying it as EXCLUSIVE_EXCLUSIVE.
4129
+ (text as? Editable)?.let { s ->
4130
+ val cursor = selectionStart.coerceIn(0, s.length)
4131
+ val spans: Array<out Any> =
4132
+ if (key == "color") s.getSpans(cursor, cursor, ExternalForegroundColorSpan::class.java)
4133
+ else s.getSpans(cursor, cursor, ExternalBackgroundColorSpan::class.java)
4134
+ spans.forEach { span ->
4135
+ val spanStart = s.getSpanStart(span)
4136
+ val spanEnd = s.getSpanEnd(span)
4137
+ if (spanEnd != cursor || spanStart >= spanEnd) return@forEach
4138
+ val colour = when (span) {
4139
+ is ExternalForegroundColorSpan -> span.color
4140
+ is ExternalBackgroundColorSpan -> span.color
4141
+ else -> return@forEach
4142
+ }
4143
+ isInternalChange = true
4144
+ s.removeSpan(span)
4145
+ s.setSpan(
4146
+ if (key == "color") ExternalForegroundColorSpan(colour)
4147
+ else ExternalBackgroundColorSpan(colour),
4148
+ spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
4149
+ )
4150
+ isInternalChange = false
4151
+ }
4152
+ }
4153
+ return
4154
+ }
4155
+
4156
+ val (start, end) = target
4157
+ val spannable = text as? Editable ?: return
4158
+
4159
+ val spans: Array<out Any> = when (key) {
4160
+ "color" -> spannable.getSpans(start, end, ExternalForegroundColorSpan::class.java)
4161
+ "backgroundColor" -> spannable.getSpans(start, end, ExternalBackgroundColorSpan::class.java)
4162
+ else -> return
4163
+ }
4164
+ if (spans.isEmpty()) return
4165
+
4166
+ isInternalChange = true
4167
+ clearInlineStyleSpans(spannable, key, start, end)
4168
+ setSelection(start, end)
4169
+ isInternalChange = false
4170
+ invalidate()
4171
+ sendContentChange()
4172
+ }
4173
+
4174
+ /**
4175
+ * Current mention ranges in "clean" (ZWS-stripped) coordinates — the same space
4176
+ * setMentionRanges() accepts and JS works in. Emitted on every content change so a consumer
4177
+ * formatter can read back where mentions ended up after edits (§8.2 S4).
4178
+ */
4179
+ private fun currentMentionRangesJson(): String {
4180
+ val spannable = text as? Spanned ?: return "[]"
4181
+ val spans = spannable.getSpans(0, spannable.length, MentionSpan::class.java)
4182
+ if (spans.isEmpty()) return "[]"
4183
+
4184
+ val raw = spannable.toString()
4185
+ val rawToClean = IntArray(raw.length + 1)
4186
+ var clean = 0
4187
+ for (i in raw.indices) {
4188
+ rawToClean[i] = clean
4189
+ if (raw[i] != '\u200B') clean++
4190
+ }
4191
+ rawToClean[raw.length] = clean
4192
+
4193
+ return spans
4194
+ .map { Pair(spannable.getSpanStart(it), spannable.getSpanEnd(it)) }
4195
+ .filter { it.first >= 0 && it.second in (it.first + 1)..raw.length }
4196
+ .sortedBy { it.first }
4197
+ .joinToString(",", "[", "]") {
4198
+ """{"start":${rawToClean[it.first]},"end":${rawToClean[it.second]}}"""
4199
+ }
4200
+ }
4201
+
3708
4202
  fun onHighlightClick() {
3709
4203
  // Use saved selection if current selection is empty
3710
4204
  var start = selectionStart
@@ -4110,6 +4604,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4110
4604
 
4111
4605
  // Snapshot mention spans before text modification (Req 5.1, 5.2, 5.7)
4112
4606
  val mentionSnapshots = snapshotMentionSpans(lineStart, lineEnd)
4607
+ val colorSnapshots = snapshotInlineColorSpans(lineStart, lineEnd)
4113
4608
 
4114
4609
  isInternalChange = true
4115
4610
  val editable = text ?: return
@@ -4120,6 +4615,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4120
4615
  val offsetDelta = newText.length - (lineEnd - lineStart)
4121
4616
  restoreMentionSpans(editable, mentionSnapshots, offsetDelta)
4122
4617
  }
4618
+ restoreInlineColorSpans(editable, colorSnapshots, lineStart, selectedText, newText)
4123
4619
 
4124
4620
  setSelection(lineStart + newText.length)
4125
4621
  renumberNumberedLists()
@@ -4211,6 +4707,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4211
4707
 
4212
4708
  // Snapshot mention spans before text modification (Req 5.1, 5.2, 5.7)
4213
4709
  val mentionSnapshots = snapshotMentionSpans(lineStart, lineEnd)
4710
+ val colorSnapshots = snapshotInlineColorSpans(lineStart, lineEnd)
4214
4711
 
4215
4712
  isInternalChange = true
4216
4713
  val editable = text ?: return
@@ -4221,6 +4718,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4221
4718
  val offsetDelta = newText.length - (lineEnd - lineStart)
4222
4719
  restoreMentionSpans(editable, mentionSnapshots, offsetDelta)
4223
4720
  }
4721
+ restoreInlineColorSpans(editable, colorSnapshots, lineStart, selectedText, newText)
4224
4722
 
4225
4723
  setSelection(lineStart + newText.length)
4226
4724
  renumberNumberedLists()
@@ -4569,6 +5067,79 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4569
5067
  }
4570
5068
  }
4571
5069
 
5070
+ /** A consumer colour span captured before a block-prefix rewrite. */
5071
+ private class ColorSnapshot(val start: Int, val end: Int, val color: Int, val isBackground: Boolean)
5072
+
5073
+ private fun snapshotInlineColorSpans(start: Int, end: Int): List<ColorSnapshot> {
5074
+ val s = text as? Spanned ?: return emptyList()
5075
+ val out = ArrayList<ColorSnapshot>()
5076
+ s.getSpans(start, end, ExternalForegroundColorSpan::class.java).forEach {
5077
+ out.add(ColorSnapshot(s.getSpanStart(it), s.getSpanEnd(it), it.color, false))
5078
+ }
5079
+ s.getSpans(start, end, ExternalBackgroundColorSpan::class.java).forEach {
5080
+ out.add(ColorSnapshot(s.getSpanStart(it), s.getSpanEnd(it), it.color, true))
5081
+ }
5082
+ return out
5083
+ }
5084
+
5085
+ /**
5086
+ * Re-applies snapshotted consumer colours after a block-prefix rewrite. replace() drops every
5087
+ * span in the replaced range, so without this the user's colour disappears the moment the line
5088
+ * becomes a list item / quote / checklist.
5089
+ *
5090
+ * Positions cannot shift by one uniform delta the way restoreMentionSpans() assumes: each line's
5091
+ * prefix can grow or shrink by a different amount (`• ` → `1. `, quote kept, empty lines
5092
+ * untouched). The prefix rewrite never touches the line's *content*, so the common suffix of the
5093
+ * old and new line is that content — which gives each line's prefix length on both sides, and
5094
+ * with it an exact content-character mapping.
5095
+ */
5096
+ private fun restoreInlineColorSpans(
5097
+ editable: Editable,
5098
+ snapshots: List<ColorSnapshot>,
5099
+ lineStart: Int,
5100
+ oldRangeText: String,
5101
+ newRangeText: String,
5102
+ ) {
5103
+ if (snapshots.isEmpty()) return
5104
+ val oldLines = oldRangeText.split("\n")
5105
+ val newLines = newRangeText.split("\n")
5106
+
5107
+ // old absolute offset -> new absolute offset, for content characters only
5108
+ val map = HashMap<Int, Int>()
5109
+ var oldPos = lineStart
5110
+ var newPos = lineStart
5111
+ for (i in oldLines.indices) {
5112
+ val oldLine = oldLines[i]
5113
+ val newLine = newLines.getOrElse(i) { oldLine }
5114
+ var contentLen = 0
5115
+ while (contentLen < oldLine.length && contentLen < newLine.length &&
5116
+ oldLine[oldLine.length - 1 - contentLen] == newLine[newLine.length - 1 - contentLen]
5117
+ ) {
5118
+ contentLen++
5119
+ }
5120
+ val oldPrefix = oldLine.length - contentLen
5121
+ val newPrefix = newLine.length - contentLen
5122
+ for (c in 0..contentLen) map[oldPos + oldPrefix + c] = newPos + newPrefix + c
5123
+ oldPos += oldLine.length + 1
5124
+ newPos += newLine.length + 1
5125
+ }
5126
+
5127
+ val oldRangeEnd = lineStart + oldRangeText.length
5128
+ for (snap in snapshots) {
5129
+ // getSpans() also returns spans overhanging the rewritten range; only the part inside
5130
+ // it was destroyed, so clamp and restore just that.
5131
+ val newStart = map[snap.start.coerceIn(lineStart, oldRangeEnd)] ?: continue
5132
+ val newEnd = map[snap.end.coerceIn(lineStart, oldRangeEnd)] ?: continue
5133
+ if (newEnd > newStart && newStart >= 0 && newEnd <= editable.length) {
5134
+ editable.setSpan(
5135
+ if (snap.isBackground) ExternalBackgroundColorSpan(snap.color)
5136
+ else ExternalForegroundColorSpan(snap.color),
5137
+ newStart, newEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
5138
+ )
5139
+ }
5140
+ }
5141
+ }
5142
+
4572
5143
  private fun toggleQuote() {
4573
5144
  val (lineStart, lineEnd) = getLineRange()
4574
5145
  val currentText = text?.toString() ?: return
@@ -4624,6 +5195,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4624
5195
 
4625
5196
  // Snapshot mention spans before text modification (Req 5.1, 5.3, 5.7)
4626
5197
  val mentionSnapshots = snapshotMentionSpans(lineStart, lineEnd)
5198
+ val colorSnapshots = snapshotInlineColorSpans(lineStart, lineEnd)
4627
5199
 
4628
5200
  isInternalChange = true
4629
5201
  val editable = text ?: return
@@ -4636,15 +5208,18 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4636
5208
  if (mentionSnapshots.isNotEmpty()) {
4637
5209
  restoreMentionSpans(editable, mentionSnapshots, -quotePrefix.length)
4638
5210
  }
5211
+ restoreInlineColorSpans(editable, colorSnapshots, lineStart, lineText, unquoted)
4639
5212
  } else {
4640
5213
  // Add quote prefix — preserve existing list prefix
4641
- editable.replace(lineStart, lineEnd, "$quotePrefix$lineText")
5214
+ val quoted = "$quotePrefix$lineText"
5215
+ editable.replace(lineStart, lineEnd, quoted)
4642
5216
  // Make ▎ invisible — bar is custom-drawn in onDraw()
4643
5217
  editable.setSpan(ForegroundColorSpan(Color.TRANSPARENT), lineStart, lineStart + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
4644
5218
  // Restore mention spans shifted forward by prefix length
4645
5219
  if (mentionSnapshots.isNotEmpty()) {
4646
5220
  restoreMentionSpans(editable, mentionSnapshots, quotePrefix.length)
4647
5221
  }
5222
+ restoreInlineColorSpans(editable, colorSnapshots, lineStart, lineText, quoted)
4648
5223
  }
4649
5224
  isInternalChange = false
4650
5225
  applyListIndentation()
@@ -4713,9 +5288,13 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4713
5288
  editable.delete(lineStart, lineStart + 2)
4714
5289
  }
4715
5290
  else -> {
4716
- // Add checklist
5291
+ // Add checklist. Only this branch needs colour re-applied — delete() above shifts
5292
+ // spans rather than dropping them.
4717
5293
  val cleanLine = removeExistingPrefix(lineText)
4718
- editable.replace(lineStart, lineEnd, "☐ $cleanLine")
5294
+ val checked = "☐ $cleanLine"
5295
+ val colorSnapshots = snapshotInlineColorSpans(lineStart, lineEnd)
5296
+ editable.replace(lineStart, lineEnd, checked)
5297
+ restoreInlineColorSpans(editable, colorSnapshots, lineStart, lineText, checked)
4719
5298
  }
4720
5299
  }
4721
5300
  isInternalChange = false
@@ -5217,6 +5796,12 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
5217
5796
  pendingStyles.remove("code")
5218
5797
  explicitlyOffStyles.remove("code")
5219
5798
  explicitlyOffStyles.remove(key)
5799
+ // Drop an armed consumer colour, or the first character typed into the empty block
5800
+ // comes out coloured instead of the code block default (matches iOS).
5801
+ pendingExternalColor = null
5802
+ pendingExternalBackgroundColor = null
5803
+ pendingStyles.remove("externalColor")
5804
+ pendingStyles.remove("externalBackgroundColor")
5220
5805
  // Insert ZWS with code block spans for immediate container
5221
5806
  val zws = "\u200B"
5222
5807
  val insertPos = selectionStart.coerceIn(0, s.length)
@@ -5332,6 +5917,18 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
5332
5917
  .forEach { s.removeSpan(it) }
5333
5918
  s.getSpans(lineStart, lineEnd, ForegroundColorSpan::class.java)
5334
5919
  .forEach { s.removeSpan(it) }
5920
+ // Consumer colour is a bare CharacterStyle, so the ForegroundColorSpan sweep above does
5921
+ // NOT catch it. Without this the span merely sits under the code block's own colour and
5922
+ // paints again the moment the block is toggled off — iOS drops it for good, and a code
5923
+ // block is destructive to every other inline style here too.
5924
+ s.getSpans(lineStart, lineEnd, ExternalForegroundColorSpan::class.java)
5925
+ .forEach { s.removeSpan(it) }
5926
+ s.getSpans(lineStart, lineEnd, ExternalBackgroundColorSpan::class.java)
5927
+ .forEach { s.removeSpan(it) }
5928
+ pendingExternalColor = null
5929
+ pendingExternalBackgroundColor = null
5930
+ pendingStyles.remove("externalColor")
5931
+ pendingStyles.remove("externalBackgroundColor")
5335
5932
  s.getSpans(lineStart, lineEnd, AbsoluteSizeSpan::class.java)
5336
5933
  .filter { s.getSpanStart(it) >= lineStart && s.getSpanEnd(it) <= lineEnd }
5337
5934
  .forEach { s.removeSpan(it) }
@@ -5560,7 +6157,9 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
5560
6157
  spannable.getSpans(msStart, msEnd, android.text.style.StyleSpan::class.java)
5561
6158
  .filter { it.style == android.graphics.Typeface.BOLD }
5562
6159
  .forEach { spannable.removeSpan(it) }
5563
- // Remove ForegroundColorSpan and BackgroundColorSpan on this mention range
6160
+ // Remove ForegroundColorSpan and BackgroundColorSpan on this mention range.
6161
+ // Consumer-applied colours are sibling types, not subclasses, so they are invisible
6162
+ // to these sweeps by construction — no filter needed.
5564
6163
  spannable.getSpans(msStart, msEnd, android.text.style.ForegroundColorSpan::class.java)
5565
6164
  .forEach { spannable.removeSpan(it) }
5566
6165
  spannable.getSpans(msStart, msEnd, android.text.style.BackgroundColorSpan::class.java)