Skip to content

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

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

Merged
Changes from 2 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
35 changes: 34 additions & 1 deletion src/hooks/useHtmlPaste/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,46 @@ import type UseHtmlPaste from './types';
const useHtmlPaste: UseHtmlPaste = (textInputRef, preHtmlPasteCallback, removeListenerOnScreenBlur = false) => {
const navigation = useNavigation();

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

function insertAtCaret(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 input event to trigger Markdown Input to parse the new text
(textInputRef.current as HTMLElement)?.dispatchEvent(
new Event('input', {
bubbles: true,
}),
);
} else {
insertByCommand(text);
}
}

/**
* Set pasted text to clipboard
* @param {String} text
*/
const paste = useCallback((text: string) => {
try {
document.execCommand('insertText', false, text);
if ((textInputRef.current as HTMLElement)?.hasAttribute('contenteditable')) {
insertAtCaret(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