@cometchat/chat-uikit-react-native 5.5.4 → 5.7.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 (215) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatKeyboardModule.kt +101 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +1 -0
  3. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +78 -3
  4. package/android/src/main/java/com/reactnativecometchatuikit/KeyboardDirectionWatcher.kt +64 -0
  5. package/android/src/main/java/com/reactnativecometchatuikit/KeyboardLanguageDirection.kt +44 -0
  6. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +287 -49
  7. package/android/src/main/java/com/reactnativecometchatuikit/SafeFileName.java +78 -0
  8. package/ios/CCLocalFileGuard.h +19 -0
  9. package/ios/CCLocalFileGuard.m +34 -0
  10. package/ios/CometChatKeyboardModule.m +9 -0
  11. package/ios/CometChatKeyboardModule.swift +71 -0
  12. package/ios/FileManager.m +70 -6
  13. package/ios/KeyboardLanguageDirection.swift +24 -0
  14. package/ios/RichTextEditorView.swift +253 -51
  15. package/ios/RichTextEditorViewManager.m +1 -0
  16. package/ios/VideoManager.m +1 -1
  17. package/package.json +18 -3
  18. package/src/CometChatAIAssistantChatHistory/CometChatAIAssistantChatHistory.tsx +41 -57
  19. package/src/CometChatAIAssistantChatHistory/Skeleton.tsx +4 -1
  20. package/src/CometChatAIAssistantChatHistory/style.ts +5 -2
  21. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +145 -63
  22. package/src/CometChatCompactMessageComposer/styles.ts +7 -7
  23. package/src/CometChatConversations/CometChatConversations.tsx +276 -147
  24. package/src/CometChatConversations/Skeleton.tsx +4 -1
  25. package/src/CometChatConversations/style.ts +1 -1
  26. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +39 -18
  27. package/src/CometChatGroupMembers/Skeleton.tsx +4 -1
  28. package/src/CometChatGroupMembers/style.ts +6 -4
  29. package/src/CometChatGroups/CometChatGroups.tsx +74 -58
  30. package/src/CometChatGroups/GroupsStyle.ts +1 -1
  31. package/src/CometChatGroups/Skeleton.tsx +4 -1
  32. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +190 -96
  33. package/src/CometChatMessageComposer/styles.tsx +1 -1
  34. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +28 -15
  35. package/src/CometChatMessageHeader/listners.ts +76 -56
  36. package/src/CometChatMessageInformation/CometChatMessageInformation.tsx +8 -1
  37. package/src/CometChatMessageInformation/Skeleton.tsx +4 -1
  38. package/src/CometChatMessageList/CometChatMessageList.tsx +1465 -313
  39. package/src/CometChatMessageList/SwipeToReplyView.tsx +61 -0
  40. package/src/CometChatMessageList/style.ts +32 -32
  41. package/src/CometChatMessageList/swipeToReply.ts +25 -0
  42. package/src/CometChatNotificationFeed/CometChatNotificationFeed.tsx +81 -10
  43. package/src/CometChatNotificationFeed/style.ts +1 -1
  44. package/src/CometChatNotificationFeed/utils.ts +17 -18
  45. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +82 -3
  46. package/src/CometChatPinnedMessages/style.ts +5 -5
  47. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +2 -0
  48. package/src/CometChatRichTextEditor/index.tsx +3 -0
  49. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +83 -15
  50. package/src/CometChatSavedMessages/style.ts +3 -3
  51. package/src/CometChatSearch/CometChatSearch.tsx +391 -136
  52. package/src/CometChatSearch/Skeleton.tsx +4 -1
  53. package/src/CometChatSearch/searchLabels.ts +26 -0
  54. package/src/CometChatSearch/style.ts +7 -7
  55. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +34 -8
  56. package/src/CometChatThreadHeader/Header.tsx +2 -2
  57. package/src/CometChatUsers/CometChatUsers.tsx +10 -1
  58. package/src/CometChatUsers/Skeleton.tsx +4 -1
  59. package/src/CometChatUsers/style.ts +1 -1
  60. package/src/calls/CometChatCallButtons/CometChatCallButtons.tsx +27 -1
  61. package/src/calls/CometChatCallLogs/CometChatCallLogs.tsx +16 -4
  62. package/src/calls/CometChatCallLogs/Skeleton.tsx +4 -1
  63. package/src/calls/CometChatIncomingCall/CometChatIncomingCall.tsx +11 -3
  64. package/src/calls/CometChatOutgoingCall/CometChatOutgoingCall.tsx +10 -2
  65. package/src/extensions/CollaborativeBubble/style.ts +4 -4
  66. package/src/extensions/CollaborativeDocument/CollaborativeDocumentExtensionDecorator.tsx +1 -1
  67. package/src/extensions/CollaborativeWhiteboard/CollaborativeWhiteboardExtensionDecorator.tsx +1 -1
  68. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +11 -6
  69. package/src/extensions/LinkPreview/style.ts +6 -6
  70. package/src/extensions/Polls/Header.tsx +1 -1
  71. package/src/extensions/Polls/Polls.tsx +25 -12
  72. package/src/extensions/Polls/PollsBubble.tsx +10 -6
  73. package/src/extensions/Polls/style.ts +4 -4
  74. package/src/extensions/Stickers/CometChatStickerKeyboard/CometChatStickerKeyboard.tsx +2 -2
  75. package/src/extensions/Stickers/CometChatStickerKeyboard/Skeleton.tsx +1 -1
  76. package/src/extensions/Stickers/CometChatStickerKeyboard/style.ts +1 -1
  77. package/src/extensions/Stickers/StickersExtensionDecorator.tsx +4 -2
  78. package/src/index.ts +11 -1
  79. package/src/shared/CometChatUiKit/CometChatUIKit.ts +102 -2
  80. package/src/shared/CometChatUiKit/UIKitSettings.ts +28 -0
  81. package/src/shared/events/CometChatUIEventHandler/Listener.ts +10 -0
  82. package/src/shared/events/index.ts +4 -0
  83. package/src/shared/events/offline.ts +28 -0
  84. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +18 -13
  85. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +15 -7
  86. package/src/shared/formatters/CometChatTextFormatter.ts +11 -0
  87. package/src/shared/formatters/CometChatUrlsFormatter/index.tsx +7 -4
  88. package/src/shared/framework/MessageDataSource.tsx +51 -108
  89. package/src/shared/helper/LocalizedDateHelper.ts +64 -4
  90. package/src/shared/helper/helperFunctions.ts +71 -4
  91. package/src/shared/helper/keyboardDirection.ts +54 -0
  92. package/src/shared/helper/layoutDirection.ts +205 -0
  93. package/src/shared/helper/pluralRules.ts +67 -0
  94. package/src/shared/helper/textDirection.ts +118 -0
  95. package/src/shared/icons/Icon.tsx +37 -2
  96. package/src/shared/icons/components/format-list-numbered-rtl.tsx +15 -0
  97. package/src/shared/index.ts +2 -0
  98. package/src/shared/offline/OfflineHub.ts +651 -0
  99. package/src/shared/offline/OfflineMediaBubble.tsx +49 -0
  100. package/src/shared/offline/OfflineViews.tsx +222 -0
  101. package/src/shared/offline/conversationPins.ts +137 -0
  102. package/src/shared/offline/conversations.ts +325 -0
  103. package/src/shared/offline/frameProbe.ts +24 -0
  104. package/src/shared/offline/gate.ts +94 -0
  105. package/src/shared/offline/groupActions.ts +81 -0
  106. package/src/shared/offline/identity.ts +162 -0
  107. package/src/shared/offline/index.ts +76 -0
  108. package/src/shared/offline/media.ts +247 -0
  109. package/src/shared/offline/notices.ts +84 -0
  110. package/src/shared/offline/reconcile.ts +296 -0
  111. package/src/shared/offline/searchOutcome.ts +62 -0
  112. package/src/shared/offline/send.ts +430 -0
  113. package/src/shared/offline/stateContract.ts +85 -0
  114. package/src/shared/offline/threadReplies.ts +125 -0
  115. package/src/shared/offline/twoPhase.ts +372 -0
  116. package/src/shared/offline/unsentActions.ts +168 -0
  117. package/src/shared/offline/useOfflineMediaUri.ts +87 -0
  118. package/src/shared/offline/useOfflineReconnect.ts +25 -0
  119. package/src/shared/offline/useOfflineSessionEnded.ts +22 -0
  120. package/src/shared/offline/useOfflineUploadTray.ts +76 -0
  121. package/src/shared/offline/usePresenceHidden.ts +33 -0
  122. package/src/shared/resources/CometChatLocalizeNew/CometChatLocalizationHelper.ts +2 -0
  123. package/src/shared/resources/CometChatLocalizeNew/resources/ar/translation.json +720 -0
  124. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +74 -3
  125. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +75 -4
  126. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +74 -3
  127. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +75 -4
  128. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +74 -3
  129. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +74 -3
  130. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +74 -3
  131. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +74 -3
  132. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +74 -3
  133. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +82 -3
  134. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +74 -3
  135. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +74 -3
  136. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +74 -3
  137. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +90 -3
  138. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +74 -3
  139. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +74 -3
  140. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +74 -3
  141. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +74 -3
  142. package/src/shared/services/UploadQueueService.ts +106 -1
  143. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +13 -12
  144. package/src/shared/utils/CometChatMessagePreview/style.ts +1 -1
  145. package/src/shared/utils/MessageReceiptUtils.ts +8 -0
  146. package/src/shared/utils/MessageUtils.tsx +14 -14
  147. package/src/shared/utils/PermissionUtil.ts +16 -5
  148. package/src/shared/utils/SavedMessagesHelper.ts +18 -1
  149. package/src/shared/utils/attachmentLimits.ts +3 -2
  150. package/src/shared/utils/catchUpCursor.ts +36 -0
  151. package/src/shared/utils/conversationUtils.ts +3 -5
  152. package/src/shared/utils/failedMessageRetry.ts +73 -0
  153. package/src/shared/utils/fileIconFontSize.ts +10 -0
  154. package/src/shared/utils/fileSizeLabel.ts +16 -0
  155. package/src/shared/utils/groupActionText.ts +75 -0
  156. package/src/shared/utils/messageIdentity.ts +38 -0
  157. package/src/shared/views/CometChatAIAssistantMessageBubble/CometChatAIAssistantMessageBubble.tsx +12 -8
  158. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.style.ts +1 -1
  159. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreviewItem.tsx +5 -3
  160. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +22 -17
  161. package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +45 -12
  162. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +16 -10
  163. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +20 -8
  164. package/src/shared/views/CometChatBadge/CometChatBadge.tsx +8 -4
  165. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +6 -2
  166. package/src/shared/views/CometChatComposerErrorBanner.tsx +3 -1
  167. package/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx +8 -3
  168. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +2 -2
  169. package/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx +5 -3
  170. package/src/shared/views/CometChatEmojiKeyboard/emojis.ts +8 -8
  171. package/src/shared/views/CometChatEmojiKeyboard/style.ts +2 -2
  172. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +13 -27
  173. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +65 -15
  174. package/src/shared/views/CometChatImageViewerModal/ImageViewerModal.tsx +7 -3
  175. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +56 -25
  176. package/src/shared/views/CometChatInlineAudioRecorder/CometChatInlineAudioRecorder.tsx +41 -21
  177. package/src/shared/views/CometChatInlineAudioRecorder/useAudioRecorder.ts +7 -3
  178. package/src/shared/views/CometChatLinkConfirmPopup/CometChatLinkConfirmPopup.tsx +7 -3
  179. package/src/shared/views/CometChatList/CometChatList.tsx +478 -21
  180. package/src/shared/views/CometChatList/Header.tsx +5 -2
  181. package/src/shared/views/CometChatList/sectionLetter.ts +44 -0
  182. package/src/shared/views/CometChatList/styles.ts +7 -7
  183. package/src/shared/views/CometChatListItem/CometChatListItem.tsx +6 -4
  184. package/src/shared/views/CometChatMediaRecorder/CometChatAudioPlayer.tsx +16 -10
  185. package/src/shared/views/CometChatMediaRecorder/Timer.tsx +5 -1
  186. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +43 -16
  187. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +24 -4
  188. package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +19 -2
  189. package/src/shared/views/CometChatNewMessageIndicator/CometChatNewMessageIndicator.tsx +3 -2
  190. package/src/shared/views/CometChatReactionList/CometChatReactionList.tsx +59 -12
  191. package/src/shared/views/CometChatReactionList/ReactionListStyle.tsx +2 -2
  192. package/src/shared/views/CometChatReactionList/Skeleton.tsx +4 -1
  193. package/src/shared/views/CometChatReactions/CometChatReactions.tsx +6 -2
  194. package/src/shared/views/CometChatReportDialog/CometChatReportDialog.tsx +7 -3
  195. package/src/shared/views/CometChatReportDialog/style.ts +1 -1
  196. package/src/shared/views/CometChatSmartReplies/CometChatSmartReplies.tsx +1 -1
  197. package/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx +4 -0
  198. package/src/shared/views/CometChatStreamMessageBubble/CometChatStreamMessageBubble.tsx +20 -13
  199. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +3 -2
  200. package/src/shared/views/CometChatSuggestionList/Skeleton.tsx +1 -1
  201. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +29 -3
  202. package/src/shared/views/CometChatTooltipMenu/CometChatTooltipMenu.tsx +20 -30
  203. package/src/shared/views/CometChatTooltipMenu/tooltipPosition.ts +43 -0
  204. package/src/shared/views/CometChatVideoBubble/style.ts +2 -2
  205. package/src/shared/views/CometChatVideoPlayer/CometChatVideoPlayer.tsx +4 -1
  206. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +58 -24
  207. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +24 -12
  208. package/src/shared/views/SenderLabel.tsx +41 -0
  209. package/src/theme/default/default.ts +1 -1
  210. package/src/theme/type.ts +17 -0
  211. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  212. package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
  213. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  214. package/android/.gradle/7.4/gc.properties +0 -0
  215. package/android/.gradle/vcs-1/gc.properties +0 -0
@@ -149,6 +149,17 @@ class NoUnderlineURLSpan(url: String) : URLSpan(url) {
149
149
  }
150
150
  }
151
151
 
152
+ /**
153
+ * ENG-57281: a toolbar alignment, kept as the SCREEN side the user picked ("left"/"right"/"center")
154
+ * so it survives the paragraph changing language, like iOS's UserAlignmentKey. Layout only knows
155
+ * NORMAL/OPPOSITE, which follow the paragraph's direction, so [alignment] is that side resolved for
156
+ * the paragraph's current direction; RichTextEditorView.applyUserAlignment re-resolves it (one span
157
+ * per paragraph) on every text change.
158
+ */
159
+ data class ScreenAlignmentSpan(val side: String, private val resolved: Layout.Alignment) : AlignmentSpan {
160
+ override fun getAlignment(): Layout.Alignment = resolved
161
+ }
162
+
152
163
  class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompatEditText(context) {
153
164
 
154
165
  private var placeholder: String = ""
@@ -346,6 +357,81 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
346
357
  * IME only when the resolved value actually changed — i.e. when the caret crosses a
347
358
  * code boundary, never mid-word in prose.
348
359
  */
360
+ /**
361
+ * ENG-57281: empty with no keyboard language, VIEW_START keeps the caret and hint at the kit's
362
+ * start edge (ENG-41384); otherwise TEXT_START aligns each paragraph by its own direction
363
+ * (FIRST_STRONG), so English starts on the left in an RTL composer and Arabic on the right in an
364
+ * LTR one, and a paragraph with no letter falls back to the keyboard's direction. A toolbar
365
+ * AlignmentSpan still wins over all of them.
366
+ */
367
+ private fun applyContentAlignment(s: CharSequence?) {
368
+ val keyboard = keyboardRtl
369
+ // Setters no-op when the raw value is unchanged (the getters return resolved values).
370
+ textAlignment = if (s.isNullOrEmpty() && keyboard == null) View.TEXT_ALIGNMENT_VIEW_START else View.TEXT_ALIGNMENT_TEXT_START
371
+ // ENG-57281: a paragraph with no letter yet (the empty editor, a new empty line) falls back to
372
+ // the keyboard language's direction, so its caret starts on that side: English at the left of
373
+ // an RTL composer, Arabic at the right of an LTR one. No keyboard language, the layout's.
374
+ textDirection = when (keyboard) {
375
+ true -> View.TEXT_DIRECTION_FIRST_STRONG_RTL
376
+ false -> View.TEXT_DIRECTION_FIRST_STRONG_LTR
377
+ null -> View.TEXT_DIRECTION_FIRST_STRONG
378
+ }
379
+ }
380
+
381
+ // ==================== Keyboard language (ENG-57281) ====================
382
+
383
+ /** The keyboard's language. A seam so tests can stand in a keyboard. */
384
+ internal var keyboardLanguage: () -> String? = { KeyboardLanguageDirection.currentLanguage(context) }
385
+
386
+ /** Only while typing here: focused, in the focused window (not backgrounded, not under a dialog). */
387
+ private fun isTypingHere() = hasFocus() && hasWindowFocus()
388
+
389
+ /**
390
+ * Reads the keyboard while typing here; polls while the caret paragraph has no letter yet (the only
391
+ * time the keyboard decides a side). A new language re-aligns.
392
+ */
393
+ private val keyboardWatcher = KeyboardDirectionWatcher(
394
+ post = { task, delay -> postDelayed(task, delay) },
395
+ cancel = { removeCallbacks(it) },
396
+ read = { if (isTypingHere()) KeyboardLanguageDirection.isRtl(keyboardLanguage()) else null },
397
+ shouldPoll = { isTypingHere() && firstStrongRtlAt(selectionStart) == null },
398
+ onChange = {
399
+ applyContentAlignment(text)
400
+ applyUserAlignment(text)
401
+ updatePlaceholderVisibility()
402
+ },
403
+ )
404
+
405
+ /**
406
+ * The keyboard language's direction, last read while focused: true RTL, false LTR, null no language
407
+ * seen yet. Kept on blur, and while a keyboard with no language (emoji, voice) is up, so nothing moves.
408
+ */
409
+ private val keyboardRtl: Boolean? get() = keyboardWatcher.last
410
+
411
+ /** Re-reads the keyboard while typing here and re-aligns when it moved; keeps polling while needed. */
412
+ private fun refreshKeyboardDirection() = keyboardWatcher.refresh()
413
+
414
+ override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
415
+ super.onWindowFocusChanged(hasWindowFocus)
416
+ // Backgrounded or covered: stop reading; back: catch a keyboard switched meanwhile.
417
+ if (hasWindowFocus) refreshKeyboardDirection() else keyboardWatcher.stop()
418
+ }
419
+
420
+ /**
421
+ * The hint keeps the kit's start edge (ENG-41384). Once the keyboard decides the empty editor's
422
+ * side, alignment is TEXT_START and the hint would follow its own letters, so a bidi mark of the
423
+ * layout's direction in front pins its paragraph direction.
424
+ */
425
+ private fun hintText(): String = when (keyboardRtl) {
426
+ null -> placeholder
427
+ else -> (if (layoutDirection == View.LAYOUT_DIRECTION_RTL) "\u200F" else "\u200E") + placeholder
428
+ }
429
+
430
+ override fun onRtlPropertiesChanged(layoutDirection: Int) {
431
+ super.onRtlPropertiesChanged(layoutDirection)
432
+ if (isInitialized) updatePlaceholderVisibility() // the hint's mark follows the layout
433
+ }
434
+
349
435
  private fun applyTypingTraits() {
350
436
  var flags = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
351
437
 
@@ -393,6 +479,14 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
393
479
  setTextColor(Color.BLACK)
394
480
  setHintTextColor(Color.parseColor("#9E9E9E"))
395
481
  gravity = Gravity.TOP or Gravity.START
482
+ // ENG-41384: START above resolves against the text's own direction, so an English hint sat
483
+ // at the left of an RTL composer. VIEW_START uses the view's layout direction, which Fabric
484
+ // sets from Yoga (the kit's layoutDirection / forceRTL). No change in LTR.
485
+ textAlignment = View.TEXT_ALIGNMENT_VIEW_START
486
+ // ENG-57281: once there is text, each paragraph aligns by its own first strong letter
487
+ // (applyContentAlignment); FIRST_STRONG falls back to the layout direction for a paragraph
488
+ // with no letters until the keyboard's language is known (refreshKeyboardDirection).
489
+ textDirection = View.TEXT_DIRECTION_FIRST_STRONG
396
490
  isFocusable = true
397
491
  isFocusableInTouchMode = true
398
492
  applyTypingTraits()
@@ -485,6 +579,10 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
485
579
  }
486
580
 
487
581
  override fun afterTextChanged(s: Editable?) {
582
+ applyContentAlignment(s)
583
+ applyUserAlignment(s)
584
+ // The keyboard decides only a paragraph with no letter; typing letters reads nothing.
585
+ if (firstStrongRtlAt(selectionStart) == null) refreshKeyboardDirection() else keyboardWatcher.stop()
488
586
  if (!isInternalChange) {
489
587
  // enterKeyBehavior="sendMessage": intercept Enter key press.
490
588
  // When a single newline is inserted (not part of a paste or list continuation),
@@ -1090,8 +1188,10 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1090
1188
 
1091
1189
  setOnFocusChangeListener { _, hasFocus ->
1092
1190
  if (hasFocus) {
1191
+ refreshKeyboardDirection() // ENG-57281: an empty composer's caret on the keyboard's side
1093
1192
  sendEvent("onEditorFocus", Arguments.createMap())
1094
1193
  } else {
1194
+ keyboardWatcher.stop()
1095
1195
  hideToolbar()
1096
1196
  sendEvent("onEditorBlur", Arguments.createMap())
1097
1197
  }
@@ -1416,6 +1516,8 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1416
1516
  // Skip if not initialized yet (during construction)
1417
1517
  if (!isInitialized) return
1418
1518
 
1519
+ keyboardWatcher.schedule() // ENG-57281: the caret may have moved onto an empty line
1520
+
1419
1521
  // How many characters landed since the last selection change, measured against the length
1420
1522
  // recorded here rather than previousText. A keyboard (Gboard, composing mid-word) can run
1421
1523
  // afterTextChanged — which refreshes previousText — before this callback, so measuring
@@ -1748,38 +1850,11 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1748
1850
  }
1749
1851
 
1750
1852
  // Draw blockquote vertical bars (continuous bar for merged adjacent quote lines)
1751
- // Same pattern as iOS: ▎ character is made invisible, bar is custom-drawn
1853
+ // Same pattern as iOS: ▎ character is made invisible, bar is custom-drawn.
1854
+ // RTL: each bar sits at its paragraph's start edge (right for Arabic), see quoteBarRects.
1752
1855
  if (textLayout != null) {
1753
- val plainText = text?.toString() ?: ""
1754
- val lines = plainText.split("\n")
1755
- // Merge adjacent quote lines into regions (startOffset, endOffset)
1756
- val quoteRegions = mutableListOf<Pair<Int, Int>>()
1757
- var offset = 0
1758
- for (line in lines) {
1759
- val lineEnd = offset + line.length
1760
- if (line.startsWith("▎")) {
1761
- if (quoteRegions.isNotEmpty() && offset <= quoteRegions.last().second + 1) {
1762
- quoteRegions[quoteRegions.lastIndex] = Pair(quoteRegions.last().first, lineEnd)
1763
- } else {
1764
- quoteRegions.add(Pair(offset, lineEnd))
1765
- }
1766
- }
1767
- offset = lineEnd + 1 // +1 for the \n
1768
- }
1769
-
1770
- for ((regionStart, regionEnd) in quoteRegions) {
1771
- val clampedEnd = regionEnd.coerceAtMost((text?.length ?: 0) - 1).coerceAtLeast(regionStart)
1772
- val firstLine = textLayout.getLineForOffset(regionStart)
1773
- val lastLine = textLayout.getLineForOffset(clampedEnd)
1774
-
1775
- val topY = textLayout.getLineTop(firstLine).toFloat() + textBaseY
1776
- val bottomY = textLayout.getLineBottom(lastLine).toFloat() + textBaseY
1777
-
1778
- val barWidth = 3f * density
1779
- val barX = paddingLeft.toFloat() + 1f
1780
- val barRadius = barWidth / 2f
1781
-
1782
- val barRect = android.graphics.RectF(barX, topY, barX + barWidth, bottomY)
1856
+ val barRadius = QUOTE_BAR_WIDTH_DP * density / 2f
1857
+ for (barRect in quoteBarRects(textLayout, textBaseY)) {
1783
1858
  codeBlockPaint.isAntiAlias = true
1784
1859
  codeBlockPaint.style = Paint.Style.FILL
1785
1860
  codeBlockPaint.strokeWidth = 0f
@@ -1798,6 +1873,60 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1798
1873
  }
1799
1874
  }
1800
1875
 
1876
+ /**
1877
+ * The blockquote bars onDraw paints, in view coordinates: one per run of adjacent quote lines
1878
+ * of the same direction. Each paragraph's direction is its own (TEXT_DIRECTION_FIRST_STRONG,
1879
+ * ENG-57281), and the layout puts the hidden "▎ " and its LeadingMarginSpan at that
1880
+ * paragraph's start edge, so the side is read from the same layout: right for RTL.
1881
+ */
1882
+ internal fun quoteBarRects(textLayout: Layout, textBaseY: Float): List<android.graphics.RectF> {
1883
+ val barWidth = QUOTE_BAR_WIDTH_DP * density
1884
+ val lastIndex = (text?.length ?: 0) - 1
1885
+ val isRtlAt = { offset: Int ->
1886
+ textLayout.getParagraphDirection(textLayout.getLineForOffset(offset)) == Layout.DIR_RIGHT_TO_LEFT
1887
+ }
1888
+ return quoteBarRegions(text?.toString() ?: "", isRtlAt).map { region ->
1889
+ val clampedEnd = region.end.coerceAtMost(lastIndex).coerceAtLeast(region.start)
1890
+ val topY = textLayout.getLineTop(textLayout.getLineForOffset(region.start)).toFloat() + textBaseY
1891
+ val bottomY = textLayout.getLineBottom(textLayout.getLineForOffset(clampedEnd)).toFloat() + textBaseY
1892
+ val barX = quoteBarX(region.rtl, width, paddingLeft, paddingRight, barWidth)
1893
+ android.graphics.RectF(barX, topY, barX + barWidth, bottomY)
1894
+ }
1895
+ }
1896
+
1897
+ internal data class QuoteBarRegion(val start: Int, val end: Int, val rtl: Boolean)
1898
+
1899
+ companion object {
1900
+ internal const val QUOTE_BAR_WIDTH_DP = 3f
1901
+
1902
+ /**
1903
+ * Runs of adjacent "▎" lines, as [start, end] offsets (end = the last line's end, before its
1904
+ * \n). Adjacent lines merge into one bar only when [isRtlAt] gives them the same direction.
1905
+ */
1906
+ internal fun quoteBarRegions(text: String, isRtlAt: (Int) -> Boolean): List<QuoteBarRegion> {
1907
+ val regions = mutableListOf<QuoteBarRegion>()
1908
+ var offset = 0
1909
+ for (line in text.split("\n")) {
1910
+ val lineEnd = offset + line.length
1911
+ if (line.startsWith("▎")) {
1912
+ val rtl = isRtlAt(offset)
1913
+ val last = regions.lastOrNull()
1914
+ if (last != null && offset <= last.end + 1 && last.rtl == rtl) {
1915
+ regions[regions.lastIndex] = last.copy(end = lineEnd)
1916
+ } else {
1917
+ regions.add(QuoteBarRegion(offset, lineEnd, rtl))
1918
+ }
1919
+ }
1920
+ offset = lineEnd + 1 // +1 for the \n
1921
+ }
1922
+ return regions
1923
+ }
1924
+
1925
+ /** The bar's left x: just inside the paragraph's start edge (the right one for RTL). */
1926
+ internal fun quoteBarX(rtl: Boolean, viewWidth: Int, paddingLeft: Int, paddingRight: Int, barWidth: Float): Float =
1927
+ if (rtl) viewWidth - paddingRight - barWidth - 1f else paddingLeft + 1f
1928
+ }
1929
+
1801
1930
  // Synchronous style detection - emits current active styles to JS
1802
1931
  /** Inline formatting present at [pos] — used to let replacement text inherit it. */
1803
1932
  private fun captureInlineStylesAt(s: CharSequence, pos: Int): InlineStyleSnapshot? {
@@ -1923,13 +2052,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1923
2052
  }
1924
2053
 
1925
2054
  // Check alignment
1926
- spannable.getSpans(checkStart, checkEnd, AlignmentSpan.Standard::class.java).firstOrNull()?.let { span ->
1927
- alignment = when (span.alignment) {
1928
- Layout.Alignment.ALIGN_CENTER -> "center"
1929
- Layout.Alignment.ALIGN_OPPOSITE -> "right"
1930
- else -> "left"
1931
- }
1932
- }
2055
+ alignmentSideAt(checkStart, checkEnd)?.let { alignment = it }
1933
2056
  } // end else (textLen > 0)
1934
2057
  }
1935
2058
 
@@ -2105,13 +2228,13 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
2105
2228
  var alignCenter = false
2106
2229
  var alignRight = false
2107
2230
 
2108
- spannable.getSpans(start, end, AlignmentSpan.Standard::class.java).firstOrNull()?.let { span ->
2109
- when (span.alignment) {
2110
- Layout.Alignment.ALIGN_CENTER -> {
2231
+ alignmentSideAt(start, end)?.let { side ->
2232
+ when (side) {
2233
+ "center" -> {
2111
2234
  alignLeft = false
2112
2235
  alignCenter = true
2113
2236
  }
2114
- Layout.Alignment.ALIGN_OPPOSITE -> {
2237
+ "right" -> {
2115
2238
  alignLeft = false
2116
2239
  alignRight = true
2117
2240
  }
@@ -3565,7 +3688,8 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
3565
3688
  private fun updatePlaceholderVisibility() {
3566
3689
  val empty = isEffectivelyEmpty()
3567
3690
  // Restore or clear hint to control visibility
3568
- hint = if (empty && placeholder.isNotEmpty()) placeholder else null
3691
+ val wanted = if (empty && placeholder.isNotEmpty()) hintText() else null
3692
+ if (hint?.toString() != wanted) hint = wanted
3569
3693
  }
3570
3694
 
3571
3695
  fun setVariant(value: String) {
@@ -4575,16 +4699,112 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
4575
4699
  outdent()
4576
4700
  }
4577
4701
 
4702
+ // ENG-57281: Left/Right are the screen's sides, kept per paragraph (ScreenAlignmentSpan).
4578
4703
  fun onAlignLeftClick() {
4579
- setAlignment(Layout.Alignment.ALIGN_NORMAL)
4704
+ setAlignment("left")
4580
4705
  }
4581
4706
 
4582
4707
  fun onAlignCenterClick() {
4583
- setAlignment(Layout.Alignment.ALIGN_CENTER)
4708
+ setAlignment("center")
4584
4709
  }
4585
4710
 
4586
4711
  fun onAlignRightClick() {
4587
- setAlignment(Layout.Alignment.ALIGN_OPPOSITE)
4712
+ setAlignment("right")
4713
+ }
4714
+
4715
+ /** ENG-57281: the Layout alignment that shows screen [side] in the paragraph at [pos]. */
4716
+ private fun resolveSide(side: String, pos: Int): Layout.Alignment = when (side) {
4717
+ "center" -> Layout.Alignment.ALIGN_CENTER
4718
+ "right" -> if (isRtlParagraphAt(pos)) Layout.Alignment.ALIGN_NORMAL else Layout.Alignment.ALIGN_OPPOSITE
4719
+ else -> if (isRtlParagraphAt(pos)) Layout.Alignment.ALIGN_OPPOSITE else Layout.Alignment.ALIGN_NORMAL
4720
+ }
4721
+
4722
+ /**
4723
+ * ENG-57281: one ScreenAlignmentSpan per aligned paragraph, covering it exactly and resolved for
4724
+ * its current direction. Typing Arabic into a Right line flips its direction, so OPPOSITE would
4725
+ * now show on the left; Enter inside an aligned paragraph stretches its span over two
4726
+ * paragraphs (both keep the choice, as before, but each needs its own resolution); a
4727
+ * backspace-merge leaves two spans in one paragraph (the earlier one wins, as on iOS).
4728
+ */
4729
+ private fun applyUserAlignment(s: Editable?) {
4730
+ s ?: return
4731
+ val spans = s.getSpans(0, s.length, ScreenAlignmentSpan::class.java)
4732
+ if (spans.isEmpty()) return
4733
+ data class Placed(val start: Int, val end: Int, val span: ScreenAlignmentSpan)
4734
+ val current = spans.map { Placed(s.getSpanStart(it), s.getSpanEnd(it), it) }.sortedBy { it.start }
4735
+ val wanted = mutableListOf<Placed>()
4736
+ var start = 0
4737
+ while (true) {
4738
+ val nl = android.text.TextUtils.indexOf(s, '\n', start)
4739
+ val end = if (nl < 0) s.length else nl
4740
+ // An empty paragraph keeps its choice on its own "\n" (see placeAlignment).
4741
+ val (from, to) = if (end > start) start to end else if (nl >= 0) nl to nl + 1 else -1 to -1
4742
+ if (from >= 0) {
4743
+ current.filter { it.start < to && it.end > from }.minByOrNull { it.start }?.let {
4744
+ wanted.add(Placed(from, to, ScreenAlignmentSpan(it.span.side, resolveSide(it.span.side, start))))
4745
+ }
4746
+ }
4747
+ if (nl < 0) break
4748
+ start = nl + 1
4749
+ }
4750
+ // Layout reads the alignment once per span change, so a stale span is replaced, never mutated.
4751
+ if (wanted == current) return
4752
+ current.forEach { s.removeSpan(it.span) }
4753
+ wanted.forEach { placeAlignment(s, it.span, it.start, it.end) }
4754
+ }
4755
+
4756
+ /**
4757
+ * ENG-57281: sets an alignment span on one paragraph. A paragraph with text gets a span over its
4758
+ * text. An EMPTY paragraph has no text to hold a span (Android drops a zero-length
4759
+ * EXCLUSIVE_EXCLUSIVE one), so its span covers its own terminating "\n" with an inclusive start:
4760
+ * text typed into the empty line lands inside it and keeps the choice, while Enter at the end of
4761
+ * the line above inserts at THAT line's "\n", before this span, so the new line stays unaligned.
4762
+ * Layout reads a paragraph's spans from [paraStart, paraEnd incl. its "\n"), so the span shows
4763
+ * on the empty line only.
4764
+ */
4765
+ private fun placeAlignment(s: Editable, span: ScreenAlignmentSpan, from: Int, to: Int) {
4766
+ val holdsOnlyItsNewline = to - from == 1 && s[from] == '\n'
4767
+ s.setSpan(span, from, to, if (holdsOnlyItsNewline) Spanned.SPAN_INCLUSIVE_EXCLUSIVE else Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
4768
+ }
4769
+
4770
+ /**
4771
+ * ENG-57281: whether the paragraph at [pos] is right-to-left, the way the editor's FIRST_STRONG
4772
+ * text direction resolves it: its first strong letter, else the keyboard language's direction,
4773
+ * else the view's layout direction (applyContentAlignment).
4774
+ */
4775
+ private fun isRtlParagraphAt(pos: Int): Boolean =
4776
+ firstStrongRtlAt(pos) ?: keyboardRtl ?: (layoutDirection == View.LAYOUT_DIRECTION_RTL)
4777
+
4778
+ /** ENG-57281: the first strong letter of the paragraph at [pos]: true RTL, false LTR, null none yet. */
4779
+ private fun firstStrongRtlAt(pos: Int): Boolean? {
4780
+ val t = text ?: return null
4781
+ val p = pos.coerceIn(0, t.length)
4782
+ var start = p
4783
+ while (start > 0 && t[start - 1] != '\n') start--
4784
+ var i = start
4785
+ while (i < t.length && t[i] != '\n') {
4786
+ when (Character.getDirectionality(t[i])) {
4787
+ Character.DIRECTIONALITY_RIGHT_TO_LEFT, Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC -> return true
4788
+ Character.DIRECTIONALITY_LEFT_TO_RIGHT -> return false
4789
+ }
4790
+ i++
4791
+ }
4792
+ return null
4793
+ }
4794
+
4795
+ /** The toolbar alignment ("left"/"right"/"center") of the text in [from, to], or null if unaligned. */
4796
+ internal fun alignmentSideAt(from: Int, to: Int): String? {
4797
+ val spannable = text as? Spanned ?: return null
4798
+ val span = spannable.getSpans(from, to, AlignmentSpan::class.java).firstOrNull() ?: return null
4799
+ // The user's own choice; a plain AlignmentSpan (e.g. pasted in) is read for this paragraph.
4800
+ return (span as? ScreenAlignmentSpan)?.side ?: screenSide(span.alignment, from)
4801
+ }
4802
+
4803
+ /** ENG-57281: the screen side ("left"/"right"/"center") an AlignmentSpan shows at [pos]. */
4804
+ private fun screenSide(alignment: Layout.Alignment, pos: Int): String = when (alignment) {
4805
+ Layout.Alignment.ALIGN_CENTER -> "center"
4806
+ Layout.Alignment.ALIGN_OPPOSITE -> if (isRtlParagraphAt(pos)) "left" else "right"
4807
+ else -> if (isRtlParagraphAt(pos)) "right" else "left"
4588
4808
  }
4589
4809
 
4590
4810
  // ==================== Helper Methods ====================
@@ -5972,16 +6192,33 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
5972
6192
  sendContentChange()
5973
6193
  }
5974
6194
 
5975
- fun setAlignment(alignment: Layout.Alignment) {
6195
+ /** ENG-57281: [side] is the screen side ("left"/"right"/"center"), set on each selected paragraph. */
6196
+ fun setAlignment(side: String) {
5976
6197
  val (lineStart, lineEnd) = getLineRange()
5977
6198
  val spannable = text as? Editable ?: return
5978
6199
 
5979
6200
  isInternalChange = true
5980
6201
  // Remove existing alignment spans
5981
- spannable.getSpans(lineStart, lineEnd, AlignmentSpan.Standard::class.java)
6202
+ spannable.getSpans(lineStart, lineEnd, AlignmentSpan::class.java)
5982
6203
  .forEach { spannable.removeSpan(it) }
5983
6204
 
5984
- spannable.setSpan(AlignmentSpan.Standard(alignment), lineStart, lineEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
6205
+ // One span per paragraph, each resolved for its own direction: a single span over an
6206
+ // English and an Arabic line would show OPPOSITE on opposite sides.
6207
+ var start = lineStart
6208
+ while (start <= lineEnd) {
6209
+ val nl = android.text.TextUtils.indexOf(spannable, '\n', start, lineEnd)
6210
+ val end = if (nl < 0) lineEnd else nl
6211
+ val span = ScreenAlignmentSpan(side, resolveSide(side, start))
6212
+ if (end > start) {
6213
+ placeAlignment(spannable, span, start, end)
6214
+ } else if (nl >= 0) {
6215
+ // An empty line inside the selection: typing into it later keeps the choice, as the
6216
+ // single span over the whole selection did before.
6217
+ placeAlignment(spannable, span, nl, nl + 1)
6218
+ }
6219
+ if (nl < 0) break
6220
+ start = nl + 1
6221
+ }
5985
6222
  isInternalChange = false
5986
6223
  sendContentChange()
5987
6224
  updateToolbarButtonStates()
@@ -6506,6 +6743,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
6506
6743
 
6507
6744
  override fun onDetachedFromWindow() {
6508
6745
  super.onDetachedFromWindow()
6746
+ keyboardWatcher.stop()
6509
6747
  hideToolbar()
6510
6748
  toolbarPopup = null
6511
6749
  }
@@ -0,0 +1,78 @@
1
+ package com.reactnativecometchatuikit;
2
+
3
+ import java.io.File;
4
+ import java.net.URI;
5
+
6
+ /**
7
+ * Checks for the native copy and download code, kept free of Android classes so they can be unit
8
+ * tested on the JVM. A destination name keeps only its base name, as the Android UI Kit's share copy
9
+ * does (MediaViewerSource.copyForShare uses File(displayName).name). A local source must also lie
10
+ * inside the offline media cache ({@link #confinedLocalFile}), which is stricter than the Android
11
+ * UI Kit's MediaViewerSource.localFile (it only checks that the file exists).
12
+ */
13
+ final class SafeFileName {
14
+
15
+ private SafeFileName() {}
16
+
17
+ /**
18
+ * The base name of [name], so a `..` or a path separator can never leave the destination
19
+ * folder, or null when there is no usable name (empty, `.`, `..`, or a NUL character).
20
+ */
21
+ static String of(String name) {
22
+ if (name == null || name.indexOf('\0') >= 0) return null;
23
+ String base = new File(name).getName();
24
+ if (base.isEmpty() || base.equals(".") || base.equals("..")) return null;
25
+ return base;
26
+ }
27
+
28
+ /** The path behind a `file://` [uri], or null for any other scheme or an empty path. */
29
+ static String localPath(String uri) {
30
+ if (uri == null) return null;
31
+ try {
32
+ URI parsed = new URI(uri);
33
+ if (!"file".equalsIgnoreCase(parsed.getScheme())) return null;
34
+ String path = parsed.getPath();
35
+ return path == null || path.isEmpty() ? null : path;
36
+ } catch (Exception e) {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ /** True when [file] is an existing regular file that can be read. */
42
+ static boolean isReadableLocalFile(File file) {
43
+ return file != null && file.isFile() && file.canRead();
44
+ }
45
+
46
+ /** True when [uri] has the `file` scheme, in any letter case. */
47
+ static boolean isFileUri(String uri) {
48
+ return uri != null && uri.length() > 5 && uri.regionMatches(true, 0, "file:", 0, 5);
49
+ }
50
+
51
+ /**
52
+ * The file behind a `file://` [uri] when it may be copied out of the app: after `..` and every
53
+ * symlink are resolved, it is a readable regular file strictly inside one of [roots] (the offline
54
+ * media cache). Anything else is null, so a message cannot name a private file of the app (its
55
+ * database, its storage, `/etc/hosts`) and have it copied into public storage or shared.
56
+ *
57
+ * The Android UI Kit's MediaViewerSource.localFile only checks that the file exists, so it is not
58
+ * the model here. The returned file is the resolved one: the caller reads exactly what was checked.
59
+ */
60
+ static File confinedLocalFile(String uri, File... roots) {
61
+ String path = localPath(uri);
62
+ if (path == null || roots == null) return null;
63
+ try {
64
+ File source = new File(path).getCanonicalFile();
65
+ if (!isReadableLocalFile(source)) return null;
66
+ String resolved = source.getPath();
67
+ for (File root : roots) {
68
+ if (root == null) continue;
69
+ String base = root.getCanonicalPath();
70
+ if (base.isEmpty() || base.equals(File.separator)) continue;
71
+ if (resolved.startsWith(base + File.separator)) return source;
72
+ }
73
+ } catch (Exception e) {
74
+ return null;
75
+ }
76
+ return null;
77
+ }
78
+ }
@@ -0,0 +1,19 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ NS_ASSUME_NONNULL_BEGIN
4
+
5
+ /// True when `url` has the `file` scheme, in any letter case.
6
+ FOUNDATION_EXPORT BOOL CCUIKitIsFileURL(NSURL *_Nullable url);
7
+
8
+ /// Where the offline Chat SDK keeps media: `<Documents>/cometchat/media` (its MediaFileStore root,
9
+ /// under react-native-fs's DocumentDirectoryPath).
10
+ FOUNDATION_EXPORT NSArray<NSString *> *CCUIKitOfflineMediaRoots(void);
11
+
12
+ /// The resolved path of the file behind a `file://` `url` when it may be copied out of the app: after
13
+ /// `..` and every symlink are resolved, it is a regular file strictly inside one of `roots` (the offline
14
+ /// media cache). Anything else is nil, so a message cannot name a private file of the app (its database,
15
+ /// its storage, any other file) and have it saved or shared. The caller copies the returned path, i.e.
16
+ /// exactly what was checked.
17
+ FOUNDATION_EXPORT NSString *_Nullable CCUIKitConfinedLocalFilePath(NSURL *_Nullable url, NSArray<NSString *> *roots);
18
+
19
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,34 @@
1
+ #import "CCLocalFileGuard.h"
2
+ #include <limits.h>
3
+ #include <stdlib.h>
4
+
5
+ BOOL CCUIKitIsFileURL(NSURL *url) {
6
+ return url != nil && url.scheme != nil && [url.scheme caseInsensitiveCompare:@"file"] == NSOrderedSame;
7
+ }
8
+
9
+ NSArray<NSString *> *CCUIKitOfflineMediaRoots(void) {
10
+ NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
11
+ return documents.length > 0 ? @[[documents stringByAppendingPathComponent:@"cometchat/media"]] : @[];
12
+ }
13
+
14
+ // realpath(3): `..` and every symlink resolved, or nil when the path does not exist.
15
+ static NSString *CCUIKitResolvedPath(NSString *path) {
16
+ if (path.length == 0) return nil;
17
+ char resolved[PATH_MAX];
18
+ if (realpath(path.fileSystemRepresentation, resolved) == NULL) return nil;
19
+ return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:resolved length:strlen(resolved)];
20
+ }
21
+
22
+ NSString *CCUIKitConfinedLocalFilePath(NSURL *url, NSArray<NSString *> *roots) {
23
+ if (!CCUIKitIsFileURL(url)) return nil;
24
+ NSString *source = CCUIKitResolvedPath(url.path);
25
+ if (source == nil) return nil;
26
+ BOOL isDir = YES;
27
+ if (![[NSFileManager defaultManager] fileExistsAtPath:source isDirectory:&isDir] || isDir) return nil;
28
+ for (NSString *root in roots) {
29
+ NSString *base = CCUIKitResolvedPath(root);
30
+ if (base.length <= 1) continue; // a missing root, or "/", allows nothing
31
+ if ([source hasPrefix:[base stringByAppendingString:@"/"]]) return source;
32
+ }
33
+ return nil;
34
+ }
@@ -0,0 +1,9 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTEventEmitter.h>
3
+
4
+ @interface RCT_EXTERN_MODULE(CometChatKeyboardModule, RCTEventEmitter)
5
+
6
+ RCT_EXTERN_METHOD(getKeyboardDirection:(RCTPromiseResolveBlock)resolve
7
+ reject:(RCTPromiseRejectBlock)reject)
8
+
9
+ @end
@@ -0,0 +1,71 @@
1
+ import Foundation
2
+ import React
3
+ import UIKit
4
+
5
+ /// The responder found by `sendAction(_:to: nil, …)`: UIKit delivers an untargeted action to the
6
+ /// first responder, which is the only responder whose `textInputMode` is the keyboard on screen.
7
+ private weak var cometChatFoundFirstResponder: UIResponder?
8
+
9
+ extension UIResponder {
10
+ @objc fileprivate func cometChatReportFirstResponder(_ sender: Any?) {
11
+ cometChatFoundFirstResponder = self
12
+ }
13
+ }
14
+
15
+ /// ENG-57281: the direction of the current keyboard's language, for the standard composer (a React
16
+ /// Native TextInput), which cannot see the keyboard from JS. The compact composer reads its own
17
+ /// keyboard (RichTextEditorView). Events go out only while JS listens (startObserving).
18
+ @objc(CometChatKeyboardModule)
19
+ class CometChatKeyboardModule: RCTEventEmitter {
20
+
21
+ static let directionChangeEvent = "keyboardDirectionChange"
22
+ /// Set in start/stopObserving, so nothing is sent with no JS listener (as SoundPlayer.m does).
23
+ private var hasListeners = false
24
+
25
+ override class func requiresMainQueueSetup() -> Bool { return false }
26
+
27
+ override func supportedEvents() -> [String]! { return [Self.directionChangeEvent] }
28
+
29
+ override func startObserving() {
30
+ hasListeners = true
31
+ NotificationCenter.default.addObserver(
32
+ self, selector: #selector(inputModeDidChange),
33
+ name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
34
+ }
35
+
36
+ override func stopObserving() {
37
+ hasListeners = false
38
+ NotificationCenter.default.removeObserver(
39
+ self, name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
40
+ }
41
+
42
+ @objc func getKeyboardDirection(
43
+ _ resolve: @escaping RCTPromiseResolveBlock,
44
+ reject: @escaping RCTPromiseRejectBlock
45
+ ) {
46
+ DispatchQueue.main.async { resolve(Self.currentDirection()) }
47
+ }
48
+
49
+ @objc private func inputModeDidChange() {
50
+ // The first responder may report the new mode a moment after the notification. A keyboard
51
+ // with no language (emoji panel, dictation) sends nothing, so the composer keeps its side.
52
+ DispatchQueue.main.async { [weak self] in
53
+ guard let self = self, self.hasListeners, let direction = Self.currentDirection() else { return }
54
+ self.sendEvent(withName: Self.directionChangeEvent, body: ["direction": direction])
55
+ }
56
+ }
57
+
58
+ /// "ltr" / "rtl" for the focused input's keyboard; nil with nothing focused or no language.
59
+ private static func currentDirection() -> String? {
60
+ cometChatFoundFirstResponder = nil
61
+ UIApplication.shared.sendAction(
62
+ #selector(UIResponder.cometChatReportFirstResponder(_:)), to: nil, from: nil, for: nil)
63
+ let language = cometChatFoundFirstResponder?.textInputMode?.primaryLanguage
64
+ cometChatFoundFirstResponder = nil
65
+ switch KeyboardLanguageDirection.of(language) {
66
+ case .rightToLeft?: return "rtl"
67
+ case .leftToRight?: return "ltr"
68
+ default: return nil
69
+ }
70
+ }
71
+ }