This repository has been archived on 2020-11-02. You can view files and clone it, but cannot push or open issues or pull requests.
2020-11-01 22:46:04 +00:00

54 lines
2.0 KiB
JavaScript

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function update(el, headToCursor, cursorToTail) {
var curr = el.value; // strA + strB1 + strC
var next = headToCursor + (cursorToTail || ""); // strA + strB2 + strC
var activeElement = document.activeElement;
// Calculate length of strA and strC
var aLength = 0;
var cLength = 0;
while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) {
aLength++;
}
while (curr.length - cLength - 1 >= 0 &&
next.length - cLength - 1 >= 0 &&
curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) {
cLength++;
}
aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength);
// Select strB1
el.setSelectionRange(aLength, curr.length - cLength);
// Get strB2
var strB2 = next.substring(aLength, next.length - cLength);
// Replace strB1 with strB2
el.focus();
if (!document.execCommand("insertText", false, strB2)) {
// Document.execCommand returns false if the command is not supported.
// Firefox and IE returns false in this case.
el.value = next;
// Dispatch input event. Note that `new Event("input")` throws an error on IE11
var event_1 = document.createEvent("Event");
event_1.initEvent("input", true, true);
el.dispatchEvent(event_1);
}
// Move cursor to the end of headToCursor
el.setSelectionRange(headToCursor.length, headToCursor.length);
activeElement.focus();
return el;
}
function wrapCursor(el, before, after) {
var initEnd = el.selectionEnd;
var headToCursor = el.value.substr(0, el.selectionStart) + before;
var cursorToTail = el.value.substring(el.selectionStart, initEnd) + (after || "") + el.value.substr(initEnd);
update(el, headToCursor, cursorToTail);
el.selectionEnd = initEnd + before.length;
return el;
}
exports.update = update;
exports.wrapCursor = wrapCursor;
//# sourceMappingURL=index.js.map