
function getCaretPosition(element: HTMLInputElement | HTMLTextAreaElement, x: number, y: number) {  
  const text = element.childNodes[0]
  const range = element.ownerDocument.createRange();  
  const start = 0;  
  const end = element.value.length;  
  let caretPosition = start;  

  range.setStart(text, 0);  
  range.setEnd(text, end);  

  range.setStart(text, 0);  
  for (let i = start; i <= end; i++) {  
    range.setEnd(text, i);  
    console.log(range.getBoundingClientRect())
    if (range.getBoundingClientRect().left >= x && range.getBoundingClientRect().top >= y) {  
      caretPosition = i;  
      break;  
    }  
  }  

  return caretPosition;  
}  

function setCaretPosition(element: any, position: number) {  
  element.focus();  
  if (element.setSelectionRange) {  
    element.setSelectionRange(position, position);  
  } else if (element.createTextRange) {  
    const range = element.createTextRange();  
    range.collapse(true);  
    range.moveEnd('character', position);  
    range.moveStart('character', position);  
    range.select();  
  }  
}  

export const focusToMouse = (element: HTMLInputElement | HTMLTextAreaElement, event: MouseEvent) => {
  const caretPosition = getCaretPosition(element, event.clientX, event.clientY);  
  setCaretPosition(element, caretPosition);  
}