@cometchat/chat-uikit-react-native 5.5.1 → 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.
Files changed (61) hide show
  1. package/android/build.gradle +35 -89
  2. package/android/gradle.properties +5 -5
  3. package/android/src/main/java/com/reactnativecometchatuikit/CometChatSoundModule.java +5 -1
  4. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +52 -0
  5. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +235 -4
  6. package/ios/FileManager.m +77 -3
  7. package/ios/RichTextEditorView.swift +234 -24
  8. package/package.json +7 -4
  9. package/react-native-cometchat-ui-kit.podspec +5 -19
  10. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +31 -27
  11. package/src/CometChatConversations/CometChatConversations.tsx +4 -0
  12. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +35 -28
  13. package/src/CometChatMessageList/CometChatMessageList.tsx +20 -18
  14. package/src/CometChatRichTextEditor/index.tsx +2 -1
  15. package/src/CometChatSearch/CometChatSearch.tsx +10 -5
  16. package/src/calls/CometChatOngoingCall/CometChatOngoingCall.tsx +56 -17
  17. package/src/calls/CometChatOutgoingCall/CometChatOutgoingCall.tsx +12 -9
  18. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +13 -10
  19. package/src/extensions/LinkPreview/LinkPreviewExtensionDecorator.tsx +34 -27
  20. package/src/extensions/Polls/Polls.tsx +7 -7
  21. package/src/extensions/Polls/PollsBubble.tsx +2 -2
  22. package/src/globals.d.ts +6 -0
  23. package/src/shared/constants/textPatterns.ts +20 -2
  24. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +22 -11
  25. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +26 -14
  26. package/src/shared/formatters/CometChatUrlsFormatter/index.tsx +8 -0
  27. package/src/shared/formatters/codeElements.ts +21 -0
  28. package/src/shared/helper/types/index.ts +5 -0
  29. package/src/shared/libs/ImageZoom/ReactNativeZoomableView.tsx +4 -4
  30. package/src/shared/libs/ImageZoom/types/index.ts +2 -0
  31. package/src/shared/resources/CometChatSoundManager/sound.js +2 -3
  32. package/src/shared/services/UploadQueueService.ts +7 -0
  33. package/src/shared/utils/CometChatMessageHelper/index.ts +3 -0
  34. package/src/shared/utils/MarkdownUtils.ts +11 -4
  35. package/src/shared/utils/MessageUtils.tsx +7 -5
  36. package/src/shared/utils/groupMemberAddedRows.ts +28 -0
  37. package/src/shared/utils/linkPreviewSelection.ts +109 -0
  38. package/src/shared/utils/mentionTokens.ts +77 -0
  39. package/src/shared/utils/runAfterInteractions.ts +26 -0
  40. package/src/shared/utils/stripRichText.ts +2 -1
  41. package/src/shared/utils/tapGesture.ts +23 -0
  42. package/src/shared/utils/videoThumbnail.ts +74 -0
  43. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +21 -13
  44. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +13 -15
  45. package/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx +1 -1
  46. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +2 -1
  47. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +2 -1
  48. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +3 -26
  49. package/src/shared/views/CometChatInlineAudioRecorder/useAudioRecorder.ts +4 -2
  50. package/src/shared/views/CometChatList/Header.tsx +1 -1
  51. package/src/shared/views/CometChatMediaRecorder/CometChatAudioPreview/CometChatAudioPreview.tsx +2 -1
  52. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +28 -8
  53. package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +3 -4
  54. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +36 -4
  55. package/src/shared/views/CometChatVideoBubble/CometChatVideoBubble.tsx +2 -1
  56. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +57 -30
  57. package/src/CometChatMessageList/PERFORMANCE_ARCHITECTURE.md +0 -478
  58. package/src/CometChatMessageList/SEARCH_NAV_PERF_PLAN.md +0 -613
  59. package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +0 -313
  60. package/src/shared/CometChatUiKit/CometChatUIKit.changes.md +0 -76
  61. package/src/shared/CometChatUiKit/checkAuthSettings-review.md +0 -211
@@ -1,21 +1,19 @@
1
- buildscript {
2
- repositories {
3
- google()
4
- mavenCentral()
5
- }
6
-
7
- dependencies {
8
- classpath 'com.android.tools.build:gradle:4.2.0'
9
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.22"
10
- }
11
- }
1
+ // AGP and the Kotlin Gradle plugin come from the host app's root project (as in every RN
2
+ // template since 0.71). Pinning them here via a `buildscript` block fights the app's own
3
+ // versions — AGP 9 / Gradle 9 (RN 0.87) will not build with the old pins at all.
12
4
 
13
5
  def isNewArchitectureEnabled() {
14
6
  return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
15
7
  }
16
8
 
17
9
  apply plugin: 'com.android.library'
18
- apply plugin: 'kotlin-android'
10
+
11
+ // AGP 9 can compile Kotlin itself ("built-in Kotlin"), and applying kotlin-android on top of
12
+ // that fails. Apply it only when nothing has registered the `kotlin` extension yet, so this
13
+ // works both on AGP 9 and on the AGP 8 apps of older RN versions.
14
+ if (project.extensions.findByName("kotlin") == null) {
15
+ apply plugin: 'org.jetbrains.kotlin.android'
16
+ }
19
17
 
20
18
  if (isNewArchitectureEnabled()) {
21
19
  apply plugin: 'com.facebook.react'
@@ -30,6 +28,7 @@ def getExtOrIntegerDefault(name) {
30
28
  }
31
29
 
32
30
  android {
31
+ namespace "com.reactnativecometchatuikit"
33
32
  compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')
34
33
 
35
34
  defaultConfig {
@@ -37,102 +36,49 @@ android {
37
36
  targetSdkVersion getExtOrIntegerDefault('targetSdkVersion')
38
37
  buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
39
38
  }
39
+
40
+ buildFeatures {
41
+ buildConfig true
42
+ }
43
+
40
44
  buildTypes {
41
45
  release {
42
46
  minifyEnabled false
43
47
  }
44
48
  }
45
49
 
46
- lintOptions {
50
+ lint {
47
51
  disable 'GradleCompatible'
48
52
  }
49
53
 
50
- compileOptions {
51
- sourceCompatibility JavaVersion.VERSION_1_8
52
- targetCompatibility JavaVersion.VERSION_1_8
54
+ // Robolectric needs the merged resources and the real manifest to inflate a view.
55
+ testOptions {
56
+ unitTests.includeAndroidResources = true
53
57
  }
54
58
 
55
-
59
+ compileOptions {
60
+ sourceCompatibility JavaVersion.VERSION_17
61
+ targetCompatibility JavaVersion.VERSION_17
62
+ }
56
63
  }
57
64
 
58
65
  repositories {
59
66
  mavenCentral()
60
67
  google()
61
-
62
- def found = false
63
- def defaultDir = null
64
- def androidSourcesName = 'React Native sources'
65
-
66
- if (rootProject.ext.has('reactNativeAndroidRoot')) {
67
- defaultDir = rootProject.ext.get('reactNativeAndroidRoot')
68
- } else {
69
- defaultDir = new File(
70
- projectDir,
71
- '/../../../node_modules/react-native/android'
72
- )
73
- }
74
-
75
- if (defaultDir.exists()) {
76
- maven {
77
- url defaultDir.toString()
78
- name androidSourcesName
79
- }
80
-
81
- logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}")
82
- found = true
83
- } else {
84
- def parentDir = rootProject.projectDir
85
-
86
- 1.upto(5, {
87
- if (found) return true
88
- parentDir = parentDir.parentFile
89
-
90
- def androidSourcesDir = new File(
91
- parentDir,
92
- 'node_modules/react-native'
93
- )
94
-
95
- def androidPrebuiltBinaryDir = new File(
96
- parentDir,
97
- 'node_modules/react-native/android'
98
- )
99
-
100
- if (androidPrebuiltBinaryDir.exists()) {
101
- maven {
102
- url androidPrebuiltBinaryDir.toString()
103
- name androidSourcesName
104
- }
105
-
106
- logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}")
107
- found = true
108
- } else if (androidSourcesDir.exists()) {
109
- maven {
110
- url androidSourcesDir.toString()
111
- name androidSourcesName
112
- }
113
-
114
- logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}")
115
- found = true
116
- }
117
- })
118
- }
119
-
120
- if (!found) {
121
- throw new GradleException(
122
- "${project.name}: unable to locate React Native android sources. " +
123
- "Ensure you have you installed React Native as a dependency in your project and try again."
124
- )
125
- }
126
68
  }
127
69
 
128
-
129
70
  dependencies {
130
- //noinspection GradleDynamicVersion
131
- implementation "com.facebook.react:react-native:+"
132
- implementation 'androidx.appcompat:appcompat:1.4.1'
133
- implementation 'com.google.android.material:material:1.5.0'
134
- implementation "org.jetbrains.kotlin:kotlin-stdlib:1.9.22"
135
- // From node_modules
71
+ // Version is supplied by the React Native Gradle Plugin of the host app.
72
+ implementation "com.facebook.react:react-android"
73
+ implementation 'androidx.appcompat:appcompat:1.7.1'
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'
136
82
  }
137
83
 
138
84
  if (isNewArchitectureEnabled()) {
@@ -1,5 +1,5 @@
1
- CometchatUiKit_kotlinVersion=1.7.0
2
- CometchatUiKit_minSdkVersion=21
3
- CometchatUiKit_targetSdkVersion=31
4
- CometchatUiKit_compileSdkVersion=31
5
- CometchatUiKit_ndkversion=21.4.7075529
1
+ CometchatUiKit_kotlinVersion=2.2.0
2
+ CometchatUiKit_minSdkVersion=24
3
+ CometchatUiKit_targetSdkVersion=36
4
+ CometchatUiKit_compileSdkVersion=36
5
+ CometchatUiKit_ndkversion=27.1.12297006
@@ -397,8 +397,12 @@ public class CometChatSoundModule
397
397
  }
398
398
  }
399
399
 
400
+ // `invalidate()`, not the deprecated onCatalystInstanceDestroy(): bridgeless RN (0.82+ is
401
+ // New-Architecture-only) tears modules down through invalidate(), so the old hook can be
402
+ // skipped and every pooled MediaPlayer would leak.
400
403
  @Override
401
- public void onCatalystInstanceDestroy() {
404
+ public void invalidate() {
405
+ super.invalidate();
402
406
  java.util.Iterator it = this.playerPool.entrySet().iterator();
403
407
  while (it.hasNext()) {
404
408
  Map.Entry entry = (Map.Entry) it.next();
@@ -18,6 +18,7 @@ import android.graphics.Bitmap;
18
18
  import android.graphics.BitmapFactory;
19
19
  import android.graphics.Matrix;
20
20
  import android.media.ExifInterface;
21
+ import android.media.MediaMetadataRetriever;
21
22
  import android.media.MediaPlayer;
22
23
  import android.media.MediaRecorder;
23
24
  import android.net.Uri;
@@ -725,6 +726,57 @@ public class FileManager extends ReactContextBaseJavaModule {
725
726
  }
726
727
  }
727
728
 
729
+ // Small JPEG of a local video's first frame, so a picked/sent video has a thumbnail without waiting
730
+ // for the server's thumbnail-generation extension (which publishes its URL before the image exists).
731
+ // Cached in cacheDir by source uri, so repeat calls for the same file are instant.
732
+ @ReactMethod
733
+ public void getVideoThumbnail(String uri, double maxSize, Promise promise) {
734
+ Executors.newSingleThreadExecutor().execute(() -> {
735
+ MediaMetadataRetriever retriever = new MediaMetadataRetriever();
736
+ try {
737
+ int side = maxSize > 0 ? (int) maxSize : 320;
738
+ File dir = new File(getReactApplicationContext().getCacheDir(), "cometchat-video-thumbnails");
739
+ if (!dir.exists()) dir.mkdirs();
740
+ File thumb = new File(dir, Integer.toHexString(uri.hashCode()) + "_" + uri.length() + "_" + side + ".jpg");
741
+ if (thumb.exists()) {
742
+ promise.resolve(Uri.fromFile(thumb).toString());
743
+ return;
744
+ }
745
+
746
+ Uri source = uri.startsWith("/") ? Uri.fromFile(new File(uri)) : Uri.parse(uri);
747
+ retriever.setDataSource(getReactApplicationContext(), source);
748
+ Bitmap frame;
749
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
750
+ frame = retriever.getScaledFrameAtTime(100_000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC, side, side);
751
+ } else {
752
+ Bitmap full = retriever.getFrameAtTime(100_000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
753
+ frame = full == null ? null : scaleToFit(full, side);
754
+ }
755
+ if (frame == null) {
756
+ promise.reject("thumbnail_failed", "Could not read a video frame");
757
+ return;
758
+ }
759
+ try (FileOutputStream out = new FileOutputStream(thumb)) {
760
+ frame.compress(Bitmap.CompressFormat.JPEG, 80, out);
761
+ }
762
+ frame.recycle();
763
+ promise.resolve(Uri.fromFile(thumb).toString());
764
+ } catch (Exception e) {
765
+ promise.reject("thumbnail_failed", e.getMessage(), e);
766
+ } finally {
767
+ try { retriever.release(); } catch (Exception ignored) { }
768
+ }
769
+ });
770
+ }
771
+
772
+ private static Bitmap scaleToFit(Bitmap source, int side) {
773
+ float scale = Math.min(1f, side / (float) Math.max(source.getWidth(), source.getHeight()));
774
+ if (scale >= 1f) return source;
775
+ Bitmap scaled = Bitmap.createScaledBitmap(source, Math.round(source.getWidth() * scale), Math.round(source.getHeight() * scale), true);
776
+ source.recycle();
777
+ return scaled;
778
+ }
779
+
728
780
  @ReactMethod
729
781
  public void pauseRecording(Promise promise) {
730
782
  if (audioRecorder != null) {
@@ -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)
@@ -383,9 +425,22 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
383
425
  changeStart = start
384
426
  removedCount = count
385
427
  addedCount = after
386
- // Save selected text for URL-paste-over-selection detection.
387
- // When count > 0 and after > 0, it's a replace (paste over selection).
388
- if (count > 0 && after > 0 && s != null && start + count <= s.length) {
428
+ // Save selected text for URL-paste-over-selection detection: a replace counts only when
429
+ // the user had exactly that text highlighted. Keyboards also replace text while typing
430
+ // (rewriting "www" -> "Www.", autocorrect) but with a bare cursor, and those must not
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
+
440
+ val selStart = minOf(selectionStart, selectionEnd)
441
+ val selEnd = maxOf(selectionStart, selectionEnd)
442
+ if (count > 0 && after > 0 && s != null && start + count <= s.length &&
443
+ selStart != selEnd && selStart == start && selEnd == start + count) {
389
444
  savedSelectedTextForPaste = s.subSequence(start, start + count).toString()
390
445
  } else {
391
446
  savedSelectedTextForPaste = null
@@ -460,6 +515,39 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
460
515
  }
461
516
  }
462
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
+
463
551
  // Apply pending styles to newly typed text
464
552
  if (addedCount > 0 && removedCount == 0 && s != null) {
465
553
  val spanStart = changeStart
@@ -532,6 +620,78 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
532
620
  }
533
621
  }
534
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
+
535
695
  // Remove explicitly-off styles from newly typed text
536
696
  if (explicitlyOffStyles.isNotEmpty()) {
537
697
  for (offStyle in explicitlyOffStyles) {
@@ -1596,6 +1756,55 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1596
1756
  }
1597
1757
 
1598
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
+
1599
1808
  private fun emitActiveStyles() {
1600
1809
  val start = selectionStart
1601
1810
  val end = selectionEnd
@@ -2924,8 +3133,16 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2924
3133
  if (j >= chars.size) return null
2925
3134
  if (j + 1 >= chars.size || chars[j + 1] != '(') return null
2926
3135
  val urlStart = j + 2
3136
+ // Balanced: `(planet)` inside the address is kept and only an unmatched `)` closes the
3137
+ // link. Stopping at the first `)` turned a pasted [Mercury](…/Mercury_(planet)) into
3138
+ // "Mercury" linking to …/Mercury_(planet plus a stray ")".
2927
3139
  var k = urlStart
2928
- while (k < chars.size && chars[k] != ')') k++
3140
+ var depth = 0
3141
+ while (k < chars.size) {
3142
+ if (chars[k] == '(') depth++
3143
+ else if (chars[k] == ')') { if (depth == 0) break; depth-- }
3144
+ k++
3145
+ }
2929
3146
  if (k >= chars.size) return null
2930
3147
  val linkText = String(chars, from + 1, j - from - 1)
2931
3148
  val linkURL = String(chars, urlStart, k - urlStart)
@@ -4076,9 +4293,11 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4076
4293
  if (key == "color") {
4077
4294
  pendingExternalColor = color
4078
4295
  pendingStyles.add("externalColor")
4296
+ explicitlyOffStyles.remove("externalColor")
4079
4297
  } else {
4080
4298
  pendingExternalBackgroundColor = color
4081
4299
  pendingStyles.add("externalBackgroundColor")
4300
+ explicitlyOffStyles.remove("externalBackgroundColor")
4082
4301
  }
4083
4302
  pendingStylesInsertPos = selectionStart
4084
4303
  return
@@ -4115,13 +4334,25 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4115
4334
  // No selection: cancel the pending type-ahead style instead of no-oping.
4116
4335
  val target = styleTargetRange()
4117
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.
4118
4344
  if (key == "color") {
4119
4345
  pendingExternalColor = null
4120
4346
  pendingStyles.remove("externalColor")
4347
+ explicitlyOffStyles.add("externalColor")
4121
4348
  } else {
4122
4349
  pendingExternalBackgroundColor = null
4123
4350
  pendingStyles.remove("externalBackgroundColor")
4351
+ explicitlyOffStyles.add("externalBackgroundColor")
4124
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
4125
4356
  // Clearing the pending colour is not enough. A colour span applied by type-ahead is
4126
4357
  // SPAN_EXCLUSIVE_INCLUSIVE so it grows with typing — a span ending exactly at the cursor
4127
4358
  // would keep swallowing everything typed after the user asked for NO colour. Pin it shut