MCPcopy Index your code
hub / github.com/uiwjs/react-md-editor / insertTextAtPosition

Function insertTextAtPosition

core/src/utils/InsertTextAtPosition.ts:30–124  ·  view source on GitHub ↗
(input: HTMLTextAreaElement | HTMLInputElement, text: string)

Source from the content-addressed store, hash-verified

28 * @returns {void}
29 */
30export function insertTextAtPosition(input: HTMLTextAreaElement | HTMLInputElement, text: string): void {
31 // Most of the used APIs only work with the field selected
32 input.focus();
33
34 // IE 8-10
35 if ((document as any).selection) {
36 const ieRange = (document as any).selection.createRange();
37 ieRange.text = text;
38
39 // Move cursor after the inserted text
40 ieRange.collapse(false /* to the end */);
41 ieRange.select();
42
43 return;
44 }
45
46 // Webkit + Edge
47 let isSuccess = false;
48 if (text !== '') {
49 isSuccess = document.execCommand && document.execCommand('insertText', false, text);
50 } else {
51 isSuccess = document.execCommand && document.execCommand('delete', false);
52 }
53
54 if (!isSuccess) {
55 const start = input.selectionStart!;
56 const end = input.selectionEnd!;
57 // Firefox (non-standard method)
58 if (typeof input.setRangeText === 'function') {
59 input.setRangeText(text);
60 } else {
61 // To make a change we just need a Range, not a Selection
62 const range = document.createRange();
63 const textNode = document.createTextNode(text);
64
65 if (canManipulateViaTextNodes(input)) {
66 let node = input.firstChild;
67
68 // If textarea is empty, just insert the text
69 if (!node) {
70 input.appendChild(textNode);
71 } else {
72 // Otherwise we need to find a nodes for start and end
73 let offset = 0;
74 let startNode = null;
75 let endNode = null;
76
77 while (node && (startNode === null || endNode === null)) {
78 const nodeLength = node.nodeValue!.length;
79
80 // if start of the selection falls into current node
81 if (start >= offset && start <= offset + nodeLength) {
82 range.setStart((startNode = node), start - offset);
83 }
84
85 // if end of the selection falls into current node
86 if (end >= offset && end <= offset + nodeLength) {
87 range.setEnd((endNode = node), end - offset);

Callers 3

handleLineMoveFunction · 0.90
handleKeyDownFunction · 0.90
replaceSelectionMethod · 0.90

Calls 2

setSelectionRangeMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…