@walkover/autosuggest-custom
Advanced tools
Comparing version 0.1.4 to 0.1.5
{ | ||
"name": "@walkover/autosuggest-custom", | ||
"version": "0.1.4", | ||
"version": "0.1.5", | ||
"author": "walkover-web", | ||
@@ -5,0 +5,0 @@ "main": "build/index.js", |
@@ -9,2 +9,3 @@ import React, { useState, useRef, useEffect } from 'react'; | ||
const editableDivRef = useRef(); | ||
const parentDivRef = useRef(); | ||
const [filteredSuggestions, setFilteredSuggestions] = useState([]); | ||
@@ -15,2 +16,30 @@ const [selectedSuggestionIndex, setSelectedSuggestionIndex] = useState(-1); | ||
const handleGetCaretCoordinates = () => { | ||
const parentDiv = parentDivRef.current; | ||
const editableDiv = editableDivRef.current; | ||
const selection = window.getSelection(); | ||
const range = document.createRange(); | ||
// Set the range to the editable div's contents | ||
range.selectNodeContents(editableDiv); | ||
// Set the range's end to the current selection | ||
range.setEnd(selection.anchorNode, selection.anchorOffset); | ||
// Calculate the caret position | ||
const caretRange = range.cloneRange(); | ||
caretRange.collapse(false); | ||
const caretRect = caretRange.getBoundingClientRect(); | ||
const parentRect = parentDiv.getBoundingClientRect(); | ||
const caretCoordinates = { | ||
left: caretRect.left - parentRect.left, | ||
top: caretRect.top - parentRect.top, | ||
}; | ||
return caretCoordinates; | ||
}; | ||
const getInputValueWithContent = () => { | ||
@@ -70,3 +99,3 @@ let htmlCode = editableDivRef.current.innerHTML; | ||
var words = currentNode.trim(); | ||
const caretPosition = getCaretPosition(); | ||
const caretPosition = handleGetCaretCoordinates(); | ||
setSuggestionPosition(caretPosition); | ||
@@ -85,12 +114,2 @@ | ||
const getCaretPosition = () => { | ||
const selection = window.getSelection(); | ||
if (selection.rangeCount > 0) { | ||
const range = selection.getRangeAt(0); | ||
const rect = range.getBoundingClientRect(); | ||
return { left: rect.left, top: rect.top + rect.height }; | ||
} | ||
return { left: 0, top: 0 }; | ||
}; | ||
function setCursorPosition(element, offset) { | ||
@@ -144,3 +163,3 @@ const range = document.createRange(); | ||
return ( | ||
<div className="suggestionMainContainer"> | ||
<div ref={parentDivRef} className="suggestionMainContainer" style={{position:"relative"}}> | ||
<div contentEditable={true} ref={editableDivRef} onKeyDown={handleKeyDown} onInput={(e) => { handleInputChange(e); }} className={editableDivClass || 'editable-div'} suppressContentEditableWarning={true} /> | ||
@@ -147,0 +166,0 @@ |
44470
253