@cometchat/chat-uikit-react-native 5.3.10 → 5.4.1

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 (132) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatClipboardModule.kt +52 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +1 -0
  3. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +95 -8
  4. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +300 -7
  5. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +2 -1
  6. package/android/src/main/java/com/reactnativecometchatuikit/SoundPlayer.java +85 -47
  7. package/ios/CometChatClipboardModule.m +11 -0
  8. package/ios/CometChatClipboardModule.swift +41 -0
  9. package/ios/FileManager.m +201 -39
  10. package/ios/RichTextEditorView.swift +367 -8
  11. package/ios/RichTextEditorViewManager.m +1 -0
  12. package/ios/SoundPlayer.m +18 -6
  13. package/package.json +10 -7
  14. package/react-native-cometchat-ui-kit.podspec +1 -0
  15. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +692 -107
  16. package/src/CometChatConversations/CometChatConversations.tsx +19 -6
  17. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +649 -49
  18. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +23 -4
  19. package/src/CometChatMessageList/CometChatMessageList.tsx +463 -54
  20. package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +313 -0
  21. package/src/CometChatMessageList/components/MessageListItem.tsx +30 -17
  22. package/src/CometChatMessageList/style.ts +33 -5
  23. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +13 -0
  24. package/src/CometChatRichTextEditor/index.tsx +25 -0
  25. package/src/CometChatSearch/CometChatSearch.tsx +296 -154
  26. package/src/calls/CallingExtension.tsx +19 -13
  27. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +20 -1
  28. package/src/extensions/ThumbnailGeneration/ThumbnailGenerationDecorator.tsx +20 -9
  29. package/src/index.ts +39 -0
  30. package/src/shared/CometChatUiKit/CometChatUIKit.ts +40 -34
  31. package/src/shared/base/Types.ts +3 -0
  32. package/src/shared/constants/UIKitConstants.ts +15 -1
  33. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +3 -2
  34. package/src/shared/framework/DataSource.ts +14 -4
  35. package/src/shared/framework/DataSourceDecorator.tsx +17 -8
  36. package/src/shared/framework/MessageDataSource.tsx +307 -60
  37. package/src/shared/helper/useToast.tsx +29 -0
  38. package/src/shared/icons/components/audio-file-type.tsx +11 -22
  39. package/src/shared/icons/components/document-file-type.tsx +11 -24
  40. package/src/shared/icons/components/image-file-type.tsx +12 -21
  41. package/src/shared/icons/components/link-file-type.tsx +25 -0
  42. package/src/shared/icons/components/pdf-file-type.tsx +11 -22
  43. package/src/shared/icons/components/presentation-file-type.tsx +11 -24
  44. package/src/shared/icons/components/spreadsheet-file-type.tsx +11 -24
  45. package/src/shared/icons/components/text-file-type.tsx +11 -21
  46. package/src/shared/icons/components/unknown-file-type.tsx +21 -25
  47. package/src/shared/icons/components/video-file-type.tsx +11 -24
  48. package/src/shared/icons/components/zip-file-type.tsx +11 -24
  49. package/src/shared/icons/icon-mapping.tsx +2 -0
  50. package/src/shared/index.ts +28 -0
  51. package/src/shared/modals/AttachmentPickerConfiguration.ts +13 -0
  52. package/src/shared/modals/SelectedAttachment.ts +65 -0
  53. package/src/shared/modals/UploadState.ts +10 -0
  54. package/src/shared/modals/index.ts +4 -0
  55. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +42 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +42 -1
  57. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +43 -2
  58. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +43 -2
  59. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +43 -2
  60. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +43 -2
  61. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +43 -2
  62. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +43 -2
  63. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +43 -2
  64. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +43 -2
  65. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +43 -2
  66. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +43 -2
  67. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +43 -2
  68. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +43 -2
  69. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +43 -2
  70. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +43 -2
  71. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +43 -2
  72. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +43 -2
  73. package/src/shared/services/UploadQueueService.ts +145 -0
  74. package/src/shared/services/index.ts +2 -0
  75. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +44 -19
  76. package/src/shared/utils/MessageUtils.tsx +13 -4
  77. package/src/shared/utils/attachmentLimits.ts +156 -0
  78. package/src/shared/utils/audioPlaybackCoordinator.ts +28 -0
  79. package/src/shared/utils/batchMediaContext.tsx +30 -0
  80. package/src/shared/utils/conversationUtils.ts +26 -4
  81. package/src/shared/utils/elementType.tsx +38 -0
  82. package/src/shared/utils/groupAttachments.ts +93 -0
  83. package/src/shared/utils/index.ts +8 -0
  84. package/src/shared/utils/openMultiFileChooser.ts +123 -0
  85. package/src/shared/utils/partitionAttachmentsByKind.ts +44 -0
  86. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +28 -0
  87. package/src/shared/views/ClipboardPasteHandler/NativeCometChatClipboardModule.ts +16 -0
  88. package/src/shared/views/ClipboardPasteHandler/index.ts +2 -0
  89. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +1 -0
  90. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.style.ts +32 -0
  91. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.tsx +90 -0
  92. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreviewItem.tsx +276 -0
  93. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +827 -0
  94. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTray.tsx +110 -0
  95. package/src/shared/views/CometChatAttachmentPreview/StagedVideoDurationProbe.tsx +53 -0
  96. package/src/shared/views/CometChatAttachmentPreview/index.ts +8 -0
  97. package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +305 -0
  98. package/src/shared/views/CometChatAttachmentViewer/index.ts +2 -0
  99. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +71 -74
  100. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +587 -0
  101. package/src/shared/views/CometChatAudiosBubble/index.ts +2 -0
  102. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +31 -20
  103. package/src/shared/views/CometChatCaptionText/CometChatCaptionText.tsx +182 -0
  104. package/src/shared/views/CometChatCaptionText/index.ts +2 -0
  105. package/src/shared/views/CometChatComposerErrorBanner.tsx +83 -0
  106. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +141 -0
  107. package/src/shared/views/CometChatConversationStarter/index.ts +2 -0
  108. package/src/shared/views/CometChatConversationSummary/CometChatConversationSummary.tsx +155 -0
  109. package/src/shared/views/CometChatConversationSummary/index.ts +2 -0
  110. package/src/shared/views/CometChatFileBubble/style.ts +6 -4
  111. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +316 -0
  112. package/src/shared/views/CometChatFilesBubble/index.ts +2 -0
  113. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +323 -0
  114. package/src/shared/views/CometChatImagesBubble/index.ts +2 -0
  115. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +425 -0
  116. package/src/shared/views/CometChatMediaViewer/index.ts +2 -0
  117. package/src/shared/views/CometChatMediaViewer/mediaViewerUtils.ts +30 -0
  118. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +14 -4
  119. package/src/shared/views/CometChatSendButtonView/CometChatSendButtonView.tsx +1 -0
  120. package/src/shared/views/CometChatSmartReplies/CometChatSmartReplies.tsx +172 -0
  121. package/src/shared/views/CometChatSmartReplies/index.ts +2 -0
  122. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +4 -3
  123. package/src/shared/views/CometChatVideoBubble/style.ts +3 -3
  124. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +441 -0
  125. package/src/shared/views/CometChatVideosBubble/index.ts +2 -0
  126. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +78 -0
  127. package/src/shared/views/CometChatVoiceNoteBubble/index.ts +2 -0
  128. package/src/shared/views/index.ts +37 -1
  129. package/src/theme/CometChatThemeHelper.ts +8 -0
  130. package/src/theme/default/color/dark.ts +9 -0
  131. package/src/theme/default/color/light.ts +10 -0
  132. package/src/theme/type.ts +73 -0
@@ -0,0 +1,52 @@
1
+ package com.reactnativecometchatuikit
2
+
3
+ import android.content.ClipboardManager
4
+ import android.content.Context
5
+ import com.facebook.react.bridge.Promise
6
+ import com.facebook.react.bridge.ReactApplicationContext
7
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
8
+ import com.facebook.react.bridge.ReactMethod
9
+ import com.facebook.react.bridge.WritableNativeMap
10
+ import java.io.File
11
+
12
+ class CometChatClipboardModule(reactContext: ReactApplicationContext)
13
+ : ReactContextBaseJavaModule(reactContext) {
14
+
15
+ override fun getName() = "CometChatClipboardModule"
16
+
17
+ @ReactMethod
18
+ fun hasImageInClipboard(promise: Promise) {
19
+ val cm = reactApplicationContext
20
+ .getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
21
+ val clip = cm.primaryClip
22
+ val hasUri = clip != null && (0 until clip.itemCount).any { i ->
23
+ clip.getItemAt(i)?.uri != null
24
+ }
25
+ promise.resolve(hasUri)
26
+ }
27
+
28
+ @ReactMethod
29
+ fun getClipboardImage(promise: Promise) {
30
+ val cm = reactApplicationContext
31
+ .getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
32
+ val clip = cm.primaryClip
33
+ if (clip == null || clip.itemCount == 0) { promise.resolve(null); return }
34
+ val uri = clip.getItemAt(0)?.uri
35
+ if (uri == null) { promise.resolve(null); return }
36
+ try {
37
+ val inputStream = reactApplicationContext.contentResolver.openInputStream(uri)
38
+ ?: run { promise.resolve(null); return }
39
+ val file = File(reactApplicationContext.cacheDir, "clipboard_paste.jpg")
40
+ inputStream.use { it.copyTo(file.outputStream()) }
41
+ val map = WritableNativeMap().apply {
42
+ putString("uri", "file://${file.absolutePath}")
43
+ putString("mimeType", "image/jpeg")
44
+ putInt("size", file.length().toInt())
45
+ putString("name", "clipboard_paste.jpg")
46
+ }
47
+ promise.resolve(map)
48
+ } catch (e: Exception) {
49
+ promise.reject("ERROR", e.message)
50
+ }
51
+ }
52
+ }
@@ -26,6 +26,7 @@ public class CometchatUiKitPackage implements ReactPackage {
26
26
  modules.add(new WebViewManager(reactContext));
27
27
  modules.add(new TimeZoneCodeManager(reactContext));
28
28
  modules.add(new ProximityModule(reactContext));
29
+ modules.add(new CometChatClipboardModule(reactContext));
29
30
  return modules;
30
31
  }
31
32
 
@@ -47,6 +47,7 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule;
47
47
  import com.facebook.react.bridge.ReactMethod;
48
48
  import com.facebook.react.bridge.ReadableMap;
49
49
  import com.facebook.react.bridge.WritableMap;
50
+ import com.facebook.react.bridge.WritableArray;
50
51
  import com.facebook.react.bridge.WritableNativeMap;
51
52
 
52
53
  import java.io.File;
@@ -81,9 +82,11 @@ public class FileManager extends ReactContextBaseJavaModule {
81
82
  private static final int READ_REQUEST_CODE = 100;
82
83
  private static final int CAPTURE_STILL_IMAGE = 101;
83
84
  private static final int REQUEST_LAUNCH_CAMERA = 1;
85
+ private static final int READ_REQUEST_CODE_MULTI = 102;
84
86
  private static int IMAGE_QUALITY = 20;
85
87
 
86
88
  private Callback callback;
89
+ private Callback multiCallback;
87
90
 
88
91
  private static final String FIELD_URI = "uri";
89
92
  private static final String FIELD_FILE_COPY_URI = "fileCopyUri";
@@ -132,6 +135,10 @@ public class FileManager extends ReactContextBaseJavaModule {
132
135
  private final ActivityEventListener activityEventListener = new BaseActivityEventListener() {
133
136
  @Override
134
137
  public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
138
+ if (requestCode == READ_REQUEST_CODE_MULTI) {
139
+ if (multiCallback != null) onShowActivityResultMulti(resultCode, data, multiCallback);
140
+ return;
141
+ }
135
142
  if (callback == null) {
136
143
  Log.e(NAME, "callback was null in onActivityResult");
137
144
  return;
@@ -319,6 +326,33 @@ public class FileManager extends ReactContextBaseJavaModule {
319
326
  return Uri.fromFile(destFile);
320
327
  }
321
328
 
329
+ private void onShowActivityResultMulti(int resultCode, Intent data, Callback storedCallback) {
330
+ if (resultCode != Activity.RESULT_OK) return;
331
+ List<Uri> uris = new ArrayList<>();
332
+ if (data != null) {
333
+ ClipData clipData = data.getClipData();
334
+ if (clipData != null && clipData.getItemCount() > 0) {
335
+ for (int i = 0; i < clipData.getItemCount(); i++) {
336
+ uris.add(clipData.getItemAt(i).getUri());
337
+ }
338
+ } else if (data.getData() != null) {
339
+ uris.add(data.getData());
340
+ }
341
+ }
342
+ if (uris.isEmpty()) return;
343
+ ExecutorService service = Executors.newSingleThreadExecutor();
344
+ service.execute(new Runnable() {
345
+ @Override
346
+ public void run() {
347
+ WritableArray array = Arguments.createArray();
348
+ for (Uri uri : uris) {
349
+ array.pushMap(getMetadata(uri));
350
+ }
351
+ storedCallback.invoke(array);
352
+ }
353
+ });
354
+ }
355
+
322
356
  private void onShowActivityResult(int resultCode, Intent data, Callback storedPromise) {
323
357
  if (resultCode == Activity.RESULT_OK) {
324
358
  Uri uri = null;
@@ -1669,21 +1703,74 @@ public class FileManager extends ReactContextBaseJavaModule {
1669
1703
  }
1670
1704
  }
1671
1705
 
1706
+ @ReactMethod
1707
+ public void openFileChooserMulti(String fileType, int maxSelection, Callback callback) {
1708
+ try {
1709
+ this.multiCallback = callback;
1710
+ Activity currentActivity = getCurrentActivity();
1711
+ if ("image".equals(fileType)) {
1712
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
1713
+ // Android 13+: system photo picker — no READ_MEDIA_IMAGES permission required
1714
+ Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
1715
+ // Cap selection to the remaining allowance (server count limit − already staged),
1716
+ // clamped to the OS max. cap==1 is valid — the photo picker enters single-select and
1717
+ // returns getData() (handled by onShowActivityResultMulti's data.getData() branch).
1718
+ int cap = Math.min(Math.max(1, maxSelection), MediaStore.getPickImagesMaxLimit());
1719
+ intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, cap);
1720
+ currentActivity.startActivityForResult(intent, READ_REQUEST_CODE_MULTI, Bundle.EMPTY);
1721
+ } else {
1722
+ // Android < 13: open gallery via ACTION_GET_CONTENT with multi-select
1723
+ Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
1724
+ intent.addCategory(Intent.CATEGORY_OPENABLE);
1725
+ intent.setType("image/*");
1726
+ intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, maxSelection != 1); // single-select when the cap is 1
1727
+ currentActivity.startActivityForResult(intent, READ_REQUEST_CODE_MULTI, Bundle.EMPTY);
1728
+ }
1729
+ } else {
1730
+ // Non-image: document picker without createChooser so EXTRA_ALLOW_MULTIPLE works.
1731
+ // Use setType("*/*") + EXTRA_MIME_TYPES rather than setType("audio/*"): a SPECIFIC
1732
+ // top-level type (audio/*, video/*) routes many devices to a single-select media/
1733
+ // music picker that ignores EXTRA_ALLOW_MULTIPLE — which is why documents ("*/*")
1734
+ // allowed multi-select but audio did not. "*/*" forces the multi-select DocumentsUI;
1735
+ // EXTRA_MIME_TYPES keeps it filtered to the requested kind.
1736
+ String mime = getType(fileType);
1737
+ Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
1738
+ intent.addCategory(Intent.CATEGORY_OPENABLE);
1739
+ intent.setType("*/*");
1740
+ if (mime != null && !mime.isEmpty() && !"*/*".equals(mime)) {
1741
+ intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{ mime });
1742
+ }
1743
+ intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, maxSelection != 1); // single-select when the cap is 1
1744
+ currentActivity.startActivityForResult(intent, READ_REQUEST_CODE_MULTI, Bundle.EMPTY);
1745
+ }
1746
+ } catch (ActivityNotFoundException e) {
1747
+ Log.e(TAG, "openFileChooserMulti: " + e.getMessage());
1748
+ } catch (Exception e) {
1749
+ Log.e(TAG, "openFileChooserMulti: " + e.getMessage());
1750
+ }
1751
+ }
1752
+
1672
1753
  @ReactMethod
1673
1754
  public void checkAndDownload(String url, String name, Callback callback) {
1674
- Long downloadId = downloadFile(name, url);
1675
1755
  try {
1756
+ if (fileExists(name)) {
1757
+ // Already downloaded — open it and report done
1758
+ openFileWithOption(name, ignored -> {});
1759
+ callback.invoke("{\"success\": true, \"alreadyExists\": true}");
1760
+ return;
1761
+ }
1762
+ Long downloadId = downloadFile(name, url);
1676
1763
  if (downloadId == null) {
1677
- callback.invoke("Download failed: ID is null");
1764
+ callback.invoke("{\"success\": false, \"error\": \"Download could not be started\"}");
1678
1765
  return;
1679
1766
  }
1680
-
1681
- obj = new JSONObject();
1682
- obj.put("downloadId", downloadId.longValue());
1683
- } catch (JSONException e) {
1684
- e.printStackTrace();
1767
+ JSONObject result = new JSONObject();
1768
+ result.put("success", true);
1769
+ result.put("downloadId", downloadId.longValue());
1770
+ callback.invoke(result.toString());
1771
+ } catch (Exception e) {
1772
+ callback.invoke("{\"success\": false, \"error\": \"" + e.getMessage() + "\"}");
1685
1773
  }
1686
- callback.invoke(obj.toString());
1687
1774
  }
1688
1775
 
1689
1776
  @ReactMethod
@@ -2,7 +2,15 @@ package com.reactnativecometchatuikit
2
2
 
3
3
  import android.content.ClipboardManager
4
4
  import android.content.ClipData
5
+ import android.content.ContentResolver
5
6
  import android.content.Context
7
+ import android.net.Uri
8
+ import android.provider.OpenableColumns
9
+ import android.webkit.MimeTypeMap
10
+ import androidx.core.view.ContentInfoCompat
11
+ import androidx.core.view.OnReceiveContentListener
12
+ import androidx.core.view.ViewCompat
13
+ import java.io.File
6
14
  import android.graphics.Canvas
7
15
  import android.graphics.Color
8
16
  import android.graphics.Paint
@@ -23,6 +31,7 @@ import android.view.View
23
31
  import android.view.ViewGroup
24
32
  import android.view.WindowManager
25
33
  import android.view.inputmethod.EditorInfo
34
+ import android.view.inputmethod.InputMethodManager
26
35
  import android.widget.PopupWindow
27
36
  import android.widget.FrameLayout
28
37
  import android.content.res.Configuration
@@ -228,6 +237,62 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
228
237
  }
229
238
  })
230
239
 
240
+ // ── Typing traits (autocorrect / autocapitalize / spellcheck) ────────────────
241
+ //
242
+ // Autocorrect / sentence capitalization / suggestions are never pinned to a fixed
243
+ // value. In prose the editor asks for exactly the flags RN's own
244
+ // ReactTextInputManager emits for a plain TextInput, so the IME's language and the
245
+ // user's keyboard settings decide; on top of that the editor drops all of them by
246
+ // itself while the caret sits in code (see [isCodeContext]), so autocorrect never
247
+ // rewrites a code sample.
248
+
249
+ /** True while the caret/selection sits inside a code block or an inline code span. */
250
+ private var isCodeContext = false
251
+
252
+ /** Called on every selection/style update with the resolved code state. */
253
+ private fun setCodeContext(inCode: Boolean) {
254
+ if (inCode == isCodeContext) return
255
+ isCodeContext = inCode
256
+ applyTypingTraits()
257
+ }
258
+
259
+ /**
260
+ * Resolves inputType for the caret's current context and applies it, restarting the
261
+ * IME only when the resolved value actually changed — i.e. when the caret crosses a
262
+ * code boundary, never mid-word in prose.
263
+ */
264
+ private fun applyTypingTraits() {
265
+ var flags = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
266
+
267
+ flags = flags or if (isCodeContext) {
268
+ // Capitalizing `teh` to `Teh` inside a code block corrupts the snippet the
269
+ // user is typing, so code always opts out.
270
+ EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS
271
+ } else {
272
+ // The RN TextInput defaults: autoCapitalize="sentences" + autoCorrect=true.
273
+ EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES or EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT
274
+ }
275
+
276
+ if (inputType == flags) return
277
+
278
+ // setInputType() rebuilds the key listener; it only rewrites text/typeface for
279
+ // password variations (never our case), but the caret is restored defensively.
280
+ val selStart = selectionStart
281
+ val selEnd = selectionEnd
282
+ inputType = flags
283
+ if (selStart in 0..length() && selEnd in 0..length() &&
284
+ (selectionStart != selStart || selectionEnd != selEnd)
285
+ ) {
286
+ setSelection(selStart, selEnd)
287
+ }
288
+
289
+ // The IME reads the flags when input starts, so a keyboard already up needs a restart.
290
+ if (hasFocus()) {
291
+ (context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)
292
+ ?.restartInput(this)
293
+ }
294
+ }
295
+
231
296
  init {
232
297
  density = context.resources.displayMetrics.density
233
298
  minHeightPx = 64 * density
@@ -245,7 +310,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
245
310
  gravity = Gravity.TOP or Gravity.START
246
311
  isFocusable = true
247
312
  isFocusableInTouchMode = true
248
- inputType = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
313
+ applyTypingTraits()
249
314
 
250
315
  // Disable vertical scrolling by default
251
316
  isVerticalScrollBarEnabled = false
@@ -377,10 +442,20 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
377
442
  s.setSpan(ForegroundColorSpan(codeColor), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
378
443
  }
379
444
  "codeBlock" -> {
380
- s.setSpan(TypefaceSpan("monospace"), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
381
- // Apply dark-mode-aware text color for readability
382
- val cbTextColor = if (isDarkMode()) Color.parseColor("#E0E0E0") else Color.parseColor("#333333")
383
- s.setSpan(ForegroundColorSpan(cbTextColor), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
445
+ // Only apply TypefaceSpan/ForegroundColorSpan if not already covered
446
+ // by an existing auto-extended span. Redundant overlapping spans cause
447
+ // Android's DynamicLayout to re-measure text multiple times (perf kill).
448
+ val existingMono = s.getSpans(spanStart, spanEnd, TypefaceSpan::class.java)
449
+ .any { it.family == "monospace" && s.getSpanStart(it) <= spanStart && s.getSpanEnd(it) >= spanEnd }
450
+ if (!existingMono) {
451
+ s.setSpan(TypefaceSpan("monospace"), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
452
+ }
453
+ val existingColor = s.getSpans(spanStart, spanEnd, ForegroundColorSpan::class.java)
454
+ .any { s.getSpanStart(it) <= spanStart && s.getSpanEnd(it) >= spanEnd }
455
+ if (!existingColor) {
456
+ val cbTextColor = if (isDarkMode()) Color.parseColor("#E0E0E0") else Color.parseColor("#333333")
457
+ s.setSpan(ForegroundColorSpan(cbTextColor), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
458
+ }
384
459
  // Extend existing CodeBlockBorderSpan or create new one
385
460
  val existingBorderSpans = s.getSpans(0, s.length, CodeBlockBorderSpan::class.java)
386
461
  var extended = false
@@ -566,8 +641,10 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
566
641
  renumberNumberedLists()
567
642
  isInternalChange = false
568
643
  }
644
+
569
645
  // Apply hanging indent for lines with list/blockquote prefixes (ENG-31433)
570
646
  applyListIndentation()
647
+
571
648
  // Issue 1: When text becomes empty, reset all pending/explicit style toggles
572
649
  if (s != null && s.isEmpty()) {
573
650
  pendingStyles.clear()
@@ -733,6 +810,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
733
810
 
734
811
  sendContentChangeWithDelta()
735
812
  saveToUndoStack()
813
+
736
814
  pendingDelta = null
737
815
  }
738
816
  previousText = s?.toString() ?: ""
@@ -740,6 +818,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
740
818
  post {
741
819
  updateContentSize()
742
820
  invalidate()
821
+
743
822
  // If line count changed (soft-wrap), schedule another redraw
744
823
  // after the framework's layout pass to ensure onDraw sees
745
824
  // the updated Layout with correct line positions.
@@ -764,9 +843,194 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
764
843
  // Install text selection context menu (conditionally adds Bold/Italic/Underline/Strikethrough)
765
844
  updateSelectionActionModeCallback()
766
845
 
846
+ // Install the OnReceiveContentListener so pasted rich content (images / files
847
+ // from Photos, file explorers, other apps) is intercepted, extracted to temp
848
+ // files, and surfaced to JS via the onPasteMedia event. Plain text pastes are
849
+ // returned unchanged so normal text-paste behavior is preserved.
850
+ installOnReceiveContentListener()
851
+
767
852
  isInitialized = true
768
853
  }
769
854
 
855
+ /**
856
+ * Registers a [OnReceiveContentListener] on this EditText via [ViewCompat] so that
857
+ * pasted (and drag-and-dropped) rich content is intercepted before the platform
858
+ * inserts it as text. This is the modern, backwards-compatible API (androidx.core);
859
+ * on API 31+ it is backed by the platform ON_RECEIVE_CONTENT infrastructure, and on
860
+ * older API levels androidx routes clipboard pastes through the same callback.
861
+ *
862
+ * Media (image, video, audio and application MIME types) is copied to a temp file in
863
+ * cacheDir and emitted to JS; plain text (and anything else) is passed through
864
+ * unchanged so the default paste/insert behavior is untouched.
865
+ */
866
+ private fun installOnReceiveContentListener() {
867
+ // Register the concrete top-level MIME types we want a shot at. Android's
868
+ // setOnReceiveContentListener FORBIDS a "*/*" wildcard (the top-level type must be
869
+ // concrete — it throws IllegalArgumentException otherwise); the subtype "/*"
870
+ // wildcard is allowed. These cover images, video, audio, and every file kind
871
+ // (application/*, text/*). We still decide per-item below whether to consume
872
+ // (URI-backed media/files) or pass through (plain text has no URI).
873
+ val mimeTypes = arrayOf("image/*", "video/*", "audio/*", "application/*", "text/*")
874
+ val listener = OnReceiveContentListener { _, payload ->
875
+ handleReceivedContent(payload)
876
+ }
877
+ ViewCompat.setOnReceiveContentListener(this, mimeTypes, listener)
878
+ }
879
+
880
+ /**
881
+ * Splits the incoming [ContentInfoCompat] payload into a media part (content:// URIs
882
+ * we extract) and a remaining part (text / anything else) that we hand back to the
883
+ * platform so normal paste continues. Returns the remaining payload, or null if we
884
+ * consumed everything.
885
+ */
886
+ private fun handleReceivedContent(payload: ContentInfoCompat): ContentInfoCompat? {
887
+ // Partition the clip: URIs (potential media) vs. everything else (text, etc.).
888
+ val split = payload.partition { item -> item.uri != null }
889
+ val uriPayload: ContentInfoCompat? = split.first
890
+ val remaining: ContentInfoCompat? = split.second
891
+
892
+ if (uriPayload == null) {
893
+ // No URI content — this is a plain text (or other) paste. Pass through
894
+ // unchanged so normal text paste proceeds. Do NOT emit.
895
+ return payload
896
+ }
897
+
898
+ val emitted = try {
899
+ extractAndEmitMedia(uriPayload.clip)
900
+ } catch (e: Exception) {
901
+ e.printStackTrace()
902
+ false
903
+ }
904
+
905
+ // If we could not extract anything usable from the URIs (e.g. resolver returned
906
+ // no stream), fall back to letting the platform handle the whole payload so we
907
+ // never silently swallow a paste.
908
+ return if (emitted) remaining else payload
909
+ }
910
+
911
+ /**
912
+ * Iterates over each item in the pasted [ClipData], copies content:// (or file://)
913
+ * media to a temp file in cacheDir, and emits a single onPasteMedia event with an
914
+ * `items` array. Each item: { uri, mimeType, name, size }. Returns true if at least
915
+ * one item was successfully extracted and the event was emitted.
916
+ */
917
+ private fun extractAndEmitMedia(clip: ClipData): Boolean {
918
+ val resolver = context.contentResolver
919
+ val items: WritableArray = Arguments.createArray()
920
+
921
+ for (i in 0 until clip.itemCount) {
922
+ val uri = clip.getItemAt(i)?.uri ?: continue
923
+ try {
924
+ val itemMap = copyUriToTempFileMap(resolver, uri) ?: continue
925
+ items.pushMap(itemMap)
926
+ } catch (e: Exception) {
927
+ // Skip items that fail; never crash on a single bad clipboard entry.
928
+ e.printStackTrace()
929
+ }
930
+ }
931
+
932
+ if (items.size() == 0) return false
933
+
934
+ val payload = Arguments.createMap()
935
+ payload.putArray("items", items)
936
+ sendEvent("onPasteMedia", payload)
937
+ return true
938
+ }
939
+
940
+ /**
941
+ * Copies a single content:// / file:// [uri] to a temp file in cacheDir and returns
942
+ * a WritableMap of { uri (file://), mimeType (REAL type), name (with extension),
943
+ * size (bytes) }. Returns null if the URI could not be read.
944
+ */
945
+ private fun copyUriToTempFileMap(resolver: ContentResolver, uri: Uri): WritableMap? {
946
+ // Resolve the REAL mime type via the content resolver (do NOT hardcode).
947
+ val mimeType = resolver.getType(uri)
948
+ ?: MimeTypeMap.getSingleton()
949
+ .getMimeTypeFromExtension(
950
+ MimeTypeMap.getFileExtensionFromUrl(uri.toString()).lowercase()
951
+ )
952
+ ?: "application/octet-stream"
953
+
954
+ // Resolve a display name + size from the resolver where possible.
955
+ val (resolvedName, resolvedSize) = queryNameAndSize(resolver, uri)
956
+
957
+ // Derive an extension: prefer the one on the resolved name, else map from mime.
958
+ val extFromMime = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)
959
+ val hasExt = resolvedName?.substringAfterLast('.', "")?.isNotEmpty() == true
960
+ val baseName = when {
961
+ !resolvedName.isNullOrBlank() && hasExt -> resolvedName
962
+ !resolvedName.isNullOrBlank() -> {
963
+ if (!extFromMime.isNullOrBlank()) "$resolvedName.$extFromMime" else resolvedName
964
+ }
965
+ else -> {
966
+ val ext = if (!extFromMime.isNullOrBlank()) ".$extFromMime" else ""
967
+ "pasted_media_${System.currentTimeMillis()}$ext"
968
+ }
969
+ }
970
+ // Guard against illegal filename characters when building the temp file.
971
+ val safeName = baseName.replace(Regex("[^A-Za-z0-9._-]"), "_")
972
+
973
+ // Copy the stream to a uniquely-named temp file so multiple pastes don't collide.
974
+ val tempFile = File.createTempFile(
975
+ "paste_${System.currentTimeMillis()}_",
976
+ "_$safeName",
977
+ context.cacheDir
978
+ )
979
+
980
+ val copied = resolver.openInputStream(uri)?.use { input ->
981
+ tempFile.outputStream().use { output ->
982
+ input.copyTo(output)
983
+ }
984
+ true
985
+ } ?: false
986
+
987
+ if (!copied || !tempFile.exists() || tempFile.length() == 0L) {
988
+ tempFile.delete()
989
+ return null
990
+ }
991
+
992
+ val size = if (resolvedSize > 0L) resolvedSize else tempFile.length()
993
+
994
+ return Arguments.createMap().apply {
995
+ putString("uri", "file://${tempFile.absolutePath}")
996
+ putString("mimeType", mimeType)
997
+ putString("name", safeName)
998
+ // size is bytes; use double to avoid Int overflow for large files (>2GB safe).
999
+ putDouble("size", size.toDouble())
1000
+ }
1001
+ }
1002
+
1003
+ /**
1004
+ * Queries the content resolver for a display name and size. Returns Pair(name?, size).
1005
+ * Size is -1 when unknown. Falls back gracefully for file:// URIs.
1006
+ */
1007
+ private fun queryNameAndSize(resolver: ContentResolver, uri: Uri): Pair<String?, Long> {
1008
+ var name: String? = null
1009
+ var size = -1L
1010
+ if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
1011
+ try {
1012
+ resolver.query(uri, null, null, null, null)?.use { cursor ->
1013
+ if (cursor.moveToFirst()) {
1014
+ val nameIdx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
1015
+ if (nameIdx >= 0 && !cursor.isNull(nameIdx)) {
1016
+ name = cursor.getString(nameIdx)
1017
+ }
1018
+ val sizeIdx = cursor.getColumnIndex(OpenableColumns.SIZE)
1019
+ if (sizeIdx >= 0 && !cursor.isNull(sizeIdx)) {
1020
+ size = cursor.getLong(sizeIdx)
1021
+ }
1022
+ }
1023
+ }
1024
+ } catch (e: Exception) {
1025
+ e.printStackTrace()
1026
+ }
1027
+ } else {
1028
+ // file:// or other — derive name from the last path segment.
1029
+ name = uri.lastPathSegment
1030
+ }
1031
+ return Pair(name, size)
1032
+ }
1033
+
770
1034
  private fun setupToolbar() {
771
1035
  toolbarPopup = PopupWindow(context).apply {
772
1036
  width = WindowManager.LayoutParams.WRAP_CONTENT
@@ -789,12 +1053,34 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
789
1053
  }
790
1054
 
791
1055
  override fun onPrepareActionMode(mode: android.view.ActionMode?, menu: android.view.Menu?): Boolean {
1056
+ // Insertion action mode = long-press / cursor tap with NO selection (e.g. an
1057
+ // empty composer). Rebuild the menu so the system "Paste" bubble is available
1058
+ // — this is what lets the user paste an image/file into an empty composer.
1059
+ // (Previously the menu was cleared and left empty, so no Paste ever appeared.)
1060
+ // Paste is offered only when the clipboard has content; "Select all" is added
1061
+ // when there is text to select.
792
1062
  menu?.clear()
1063
+ val clipboard =
1064
+ context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
1065
+ if (clipboard?.hasPrimaryClip() == true) {
1066
+ menu?.add(0, android.R.id.paste, 0, android.R.string.paste)
1067
+ }
1068
+ if ((text?.length ?: 0) > 0) {
1069
+ menu?.add(0, android.R.id.selectAll, 1, android.R.string.selectAll)
1070
+ }
793
1071
  return true
794
1072
  }
795
1073
 
796
1074
  override fun onActionItemClicked(mode: android.view.ActionMode?, item: android.view.MenuItem?): Boolean {
797
- return false
1075
+ return when (item?.itemId) {
1076
+ android.R.id.paste -> {
1077
+ onTextContextMenuItem(android.R.id.paste); mode?.finish(); true
1078
+ }
1079
+ android.R.id.selectAll -> {
1080
+ onTextContextMenuItem(android.R.id.selectAll); true
1081
+ }
1082
+ else -> false
1083
+ }
798
1084
  }
799
1085
 
800
1086
  override fun onDestroyActionMode(mode: android.view.ActionMode?) {}
@@ -999,7 +1285,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
999
1285
  val textBaseY = paddingTop + gravityOffsetY
1000
1286
 
1001
1287
  // ── Code block containers (unified rect per region, matching iOS) ──
1002
- val spannable = text as? Spanned
1288
+ val spannable = text as? Spanned ?: run { super.onDraw(canvas); return }
1003
1289
  if (spannable != null && textLayout != null) {
1004
1290
  // 1. Find all code block regions by merging overlapping CodeBlockBorderSpan ranges.
1005
1291
  // Only merge spans that truly overlap or are directly adjacent within the
@@ -1348,6 +1634,11 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1348
1634
  }
1349
1635
  }
1350
1636
  val codeBlockActive = hasCodeBlock || pendingStyles.contains("codeBlock")
1637
+
1638
+ // Autocorrect/autocapitalize/spellcheck follow the caret: off in code, platform
1639
+ // default everywhere else.
1640
+ setCodeContext(codeActive || codeBlockActive)
1641
+
1351
1642
  map.putBoolean("code", codeActive)
1352
1643
  map.putBoolean("codeBlock", codeBlockActive)
1353
1644
  map.putBoolean("highlight", hasHighlight)
@@ -2742,6 +3033,8 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2742
3033
  "onSizeChange" -> "topSizeChange"
2743
3034
  "onActiveStylesChange" -> "topActiveStylesChange"
2744
3035
  "onLinkTap" -> "topLinkTap"
3036
+ "onSendRequest" -> "topSendRequest"
3037
+ "onPasteMedia" -> "topPasteMedia"
2745
3038
  else -> eventName
2746
3039
  }
2747
3040
 
@@ -446,7 +446,8 @@ class RichTextEditorViewManager : SimpleViewManager<LinearLayout>() {
446
446
  "topSizeChange" to mapOf("registrationName" to "onSizeChange"),
447
447
  "topActiveStylesChange" to mapOf("registrationName" to "onActiveStylesChange"),
448
448
  "topLinkTap" to mapOf("registrationName" to "onLinkTap"),
449
- "topSendRequest" to mapOf("registrationName" to "onSendRequest")
449
+ "topSendRequest" to mapOf("registrationName" to "onSendRequest"),
450
+ "topPasteMedia" to mapOf("registrationName" to "onPasteMedia")
450
451
  )
451
452
  }
452
453
  }