@@ -3,6 +3,33 @@ import ExpensiMark from 'expensify-common/lib/ExpensiMark';
3
3
import { useCallback , useEffect } from 'react' ;
4
4
import type UseHtmlPaste from './types' ;
5
5
6
+ const insertByCommand = ( text : string ) => {
7
+ document . execCommand ( 'insertText' , false , text ) ;
8
+ } ;
9
+
10
+ const insertAtCaret = ( target : HTMLElement , text : string ) => {
11
+ const selection = window . getSelection ( ) ;
12
+ if ( selection ?. rangeCount ) {
13
+ const range = selection . getRangeAt ( 0 ) ;
14
+ range . deleteContents ( ) ;
15
+ const node = document . createTextNode ( text ) ;
16
+ range . insertNode ( node ) ;
17
+
18
+ // Move caret to the end of the newly inserted text node.
19
+ range . setStart ( node , node . length ) ;
20
+ range . setEnd ( node , node . length ) ;
21
+ selection . removeAllRanges ( ) ;
22
+ selection . addRange ( range ) ;
23
+
24
+ // Dispatch paste event to simulate real browser behavior
25
+ target . dispatchEvent ( new Event ( 'paste' , { bubbles : true } ) ) ;
26
+ // Dispatch input event to trigger Markdown Input to parse the new text
27
+ target . dispatchEvent ( new Event ( 'input' , { bubbles : true } ) ) ;
28
+ } else {
29
+ insertByCommand ( text ) ;
30
+ }
31
+ } ;
32
+
6
33
const useHtmlPaste : UseHtmlPaste = ( textInputRef , preHtmlPasteCallback , removeListenerOnScreenBlur = false ) => {
7
34
const navigation = useNavigation ( ) ;
8
35
@@ -12,7 +39,12 @@ const useHtmlPaste: UseHtmlPaste = (textInputRef, preHtmlPasteCallback, removeLi
12
39
*/
13
40
const paste = useCallback ( ( text : string ) => {
14
41
try {
15
- document . execCommand ( 'insertText' , false , text ) ;
42
+ const textInputHTMLElement = textInputRef . current as HTMLElement ;
43
+ if ( textInputHTMLElement ?. hasAttribute ( 'contenteditable' ) ) {
44
+ insertAtCaret ( textInputHTMLElement , text ) ;
45
+ } else {
46
+ insertByCommand ( text ) ;
47
+ }
16
48
17
49
// Pointer will go out of sight when a large paragraph is pasted on the web. Refocusing the input keeps the cursor in view.
18
50
textInputRef . current ?. blur ( ) ;
0 commit comments