Skip to content

Commit 93e9719

Browse files
authored
Merge pull request #39177 from software-mansion-labs/@Skalakid/fix-pasting-to-composer
Fix pasting text into main composer
2 parents b4912ff + e6c9f06 commit 93e9719

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/hooks/useHtmlPaste/index.ts

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,33 @@ import ExpensiMark from 'expensify-common/lib/ExpensiMark';
33
import {useCallback, useEffect} from 'react';
44
import type UseHtmlPaste from './types';
55

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+
633
const useHtmlPaste: UseHtmlPaste = (textInputRef, preHtmlPasteCallback, removeListenerOnScreenBlur = false) => {
734
const navigation = useNavigation();
835

@@ -12,7 +39,12 @@ const useHtmlPaste: UseHtmlPaste = (textInputRef, preHtmlPasteCallback, removeLi
1239
*/
1340
const paste = useCallback((text: string) => {
1441
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+
}
1648

1749
// Pointer will go out of sight when a large paragraph is pasted on the web. Refocusing the input keeps the cursor in view.
1850
textInputRef.current?.blur();

0 commit comments

Comments
 (0)