Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CP Stag] Fix pasting text into main composer #39177

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/hooks/useHtmlPaste/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,33 @@ import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import {useCallback, useEffect} from 'react';
import type UseHtmlPaste from './types';

const insertByCommand = (text: string) => {
document.execCommand('insertText', false, text);
};

const insertAtCaret = (target: HTMLElement, text: string) => {
const selection = window.getSelection();
if (selection?.rangeCount) {
const range = selection.getRangeAt(0);
range.deleteContents();
const node = document.createTextNode(text);
range.insertNode(node);

// Move caret to the end of the newly inserted text node.
range.setStart(node, node.length);
range.setEnd(node, node.length);
selection.removeAllRanges();
selection.addRange(range);

// Dispatch paste event to simulate real browser behavior
target.dispatchEvent(new Event('paste', {bubbles: true}));
// Dispatch input event to trigger Markdown Input to parse the new text
target.dispatchEvent(new Event('input', {bubbles: true}));
} else {
insertByCommand(text);
}
};

const useHtmlPaste: UseHtmlPaste = (textInputRef, preHtmlPasteCallback, removeListenerOnScreenBlur = false) => {
const navigation = useNavigation();

Expand All @@ -12,7 +39,12 @@ const useHtmlPaste: UseHtmlPaste = (textInputRef, preHtmlPasteCallback, removeLi
*/
const paste = useCallback((text: string) => {
try {
document.execCommand('insertText', false, text);
const textInputHTMLElement = textInputRef.current as HTMLElement;
if (textInputHTMLElement?.hasAttribute('contenteditable')) {
insertAtCaret(textInputHTMLElement, text);
} else {
insertByCommand(text);
}

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