use-caret-position
Version:
A custom React hook for grabbing the caret position in an input field
256 lines (202 loc) • 7.88 kB
JavaScript
;
var react = require('react');
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
/**
* returns x, y coordinates for absolute positioning of a span within a given text input
* at a given selection point
* @param {object} input - the input element to obtain coordinates for
* @param {number} selectionPoint - the selection point for the input
*/
var getCaretPosition = function getCaretPosition(input) {
var selection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'selectionStart';
var scrollLeft = input.scrollLeft,
scrollTop = input.scrollTop; // This provides a hook for getSelection to reuse getCaretPosition.
var selectionPoint = input[selection] || input.selectionStart;
var _input$getBoundingCli = input.getBoundingClientRect(),
height = _input$getBoundingCli.height,
width = _input$getBoundingCli.width,
left = _input$getBoundingCli.left,
top = _input$getBoundingCli.top; // create a dummy element that will be a clone of our input
var div = document.createElement('div'); // get the computed style of the input and clone it onto the dummy element
var copyStyle = getComputedStyle(input);
var _iterator = _createForOfIteratorHelper(copyStyle),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var prop = _step.value;
div.style[prop] = copyStyle[prop];
} // we need a character that will replace whitespace when filling our dummy element if it's a single line <input/>
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var swap = '.';
var inputValue = input.tagName === 'INPUT' ? input.value.replace(/ /g, swap) : input.value; // set the div content to that of the textarea up until selection
var textContent = inputValue.substr(0, selectionPoint); // set the text content of the dummy element div
div.textContent = textContent;
if (input.tagName === 'TEXTAREA') div.style.height = 'auto'; // if a single line input then the div needs to be single line and not break out like a text area
if (input.tagName === 'INPUT') div.style.width = 'auto'; // Apply absolute positioning to account for textarea resize, etc.
div.style.position = 'absolute'; // create a marker element to obtain caret position
var span = document.createElement('span'); // give the span the textContent of remaining content so that the recreated dummy element is as close as possible
span.textContent = inputValue.substr(selectionPoint) || '.'; // append the span marker to the div
div.appendChild(span); // append the dummy element to the body
document.body.appendChild(div); // get the marker position, this is the caret position top and left relative to the input
var spanX = span.offsetLeft,
spanY = span.offsetTop; // lastly, remove that dummy element
// NOTE:: can comment this out for debugging purposes if you want to see where that span is rendered
document.body.removeChild(div); // return an object with the x and y of the caret. account for input positioning so that you don't need to wrap the input
var x = left + spanX;
var y = top + spanY;
var lineHeight = copyStyle.lineHeight,
paddingRight = copyStyle.paddingRight;
x = Math.min(x - scrollLeft, left + width - parseInt(paddingRight, 10)); // Need to account for any scroll position for the window.
y = Math.min(y - scrollTop, top + height - parseInt(lineHeight, 10)) + window.scrollY;
return {
x: x,
y: y
};
};
var getSelectionPosition = function getSelectionPosition(input) {
var _getCaretPosition = getCaretPosition(input, 'selectionStart'),
startY = _getCaretPosition.y,
startX = _getCaretPosition.x;
var _getCaretPosition2 = getCaretPosition(input, 'selectionEnd'),
endX = _getCaretPosition2.x; // Gives you a basic left position for where to put it and the starting position.
var x = startX + (endX - startX) / 2;
var y = startY;
return {
x: x,
y: y
};
};
var useCaretPosition = function useCaretPosition(element) {
var _useState = react.useState(null),
_useState2 = _slicedToArray(_useState, 2),
x = _useState2[0],
setX = _useState2[1];
var _useState3 = react.useState(null),
_useState4 = _slicedToArray(_useState3, 2),
y = _useState4[0],
setY = _useState4[1];
var getPosition = function getPosition(element) {
if (element.current) {
var _getCaretPosition3 = getCaretPosition(element.current),
_x = _getCaretPosition3.x,
_y = _getCaretPosition3.y;
setX(_x);
setY(_y);
}
};
var getSelection = function getSelection(element) {
if (element.current) {
var _getSelectionPosition = getSelectionPosition(element.current),
_x2 = _getSelectionPosition.x,
_y2 = _getSelectionPosition.y;
setX(_x2);
setY(_y2);
}
};
return {
x: x,
y: y,
getPosition: getPosition,
getSelection: getSelection
};
};
module.exports = useCaretPosition;