@point-api/dropdown-react
Version:
HOC to add a Point API autocomplete dropdown
72 lines • 2.45 kB
JavaScript
import getCaretCoordinates from "textarea-caret";
import { getLineHeight } from "./Utils";
/*
NOTE: for inputs, only <input type="text|search|password|tel|url">
are permmitted by big goog to get cursor position
*/
class TextAreaAdapter {
/**
* Expose EditableAdapter API functions for a TextArea or Input element
* @param el - TextArea or Input element to wrap
*/
constructor(el, supportsAutoInsert) {
if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {
throw new Error("Attempted to create TextAreaAdapter with non-input/textarea element");
}
this.el = el;
this.supportsAutoInsert = supportsAutoInsert !== undefined ? supportsAutoInsert : true;
}
get text() {
return this.el.value;
}
insertText(text) {
if (!this.supportsAutoInsert) {
return;
}
text = this.stripRichText(text);
const cusrorIndex = this.getCursorIndex();
if (cusrorIndex === null)
return;
const curText = this.text;
this.el.value =
curText.slice(0, cusrorIndex) +
text +
curText.slice(cusrorIndex);
this.setCursorIndex(cusrorIndex + text.length);
}
stripRichText(text) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = text.replace(/<br>/g, '\n');
return tempDiv.innerText;
}
replaceText(match, newText) {
newText = this.stripRichText(newText);
const curText = this.text;
this.el.value =
curText.slice(0, match.index) +
newText +
curText.slice(match.index + match[0].length);
this.setCursorIndex(match.index + newText.length);
}
getCursorIndex() {
return this.el.selectionStart;
}
setCursorIndex(index) {
this.el.focus();
this.el.setSelectionRange(index, index);
}
getCaretPos() {
const { el } = this;
if (!el.selectionEnd)
return null;
const { top, left } = getCaretCoordinates(el, el.selectionEnd);
const elPos = el.getBoundingClientRect();
const adjustedTop = elPos.top + top + getLineHeight(el) / 2 - el.scrollTop;
return {
top: adjustedTop,
left: elPos.left + left
};
}
}
export default TextAreaAdapter;
//# sourceMappingURL=TextAreaAdapter.js.map