import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.array.push.js";
function textNodesUnder(node) {
  // https://stackoverflow.com/a/10730777/3245937
  var all = [];
  for (node = (_node = node) === null || _node === void 0 ? void 0 : _node.firstChild; node; node = node.nextSibling) {
    var _node;
    if (node.nodeType == 3) {
      all.push(node);
    } else {
      all = all.concat(textNodesUnder(node));
    }
  }
  return all;
}
export function setCaretIndex(win, contentEditable, newCaretIndex) {
  var cumulativeIndex = 0;
  var relativeIndex = 0;
  var targetNode = null;
  var textNodes = textNodesUnder(contentEditable);
  for (var i = 0; i < textNodes.length; i++) {
    var _node$textContent, _node$textContent2;
    var node = textNodes[i];
    if (newCaretIndex <= cumulativeIndex + (((_node$textContent = node.textContent) === null || _node$textContent === void 0 ? void 0 : _node$textContent.length) || 0)) {
      targetNode = node;
      relativeIndex = newCaretIndex - cumulativeIndex;
      break;
    }
    cumulativeIndex += ((_node$textContent2 = node.textContent) === null || _node$textContent2 === void 0 ? void 0 : _node$textContent2.length) || 0;
  }
  var range = win.document.createRange();
  range.setStart(targetNode, relativeIndex);
  range.setEnd(targetNode, relativeIndex);
  range.collapse();
  var sel = win.getSelection();
  sel === null || sel === void 0 || sel.removeAllRanges();
  sel === null || sel === void 0 || sel.addRange(range);
}
export function getCaretIndex(win, contentEditable) {
  var index = 0;
  var selection = win.getSelection();
  var textNodes = textNodesUnder(contentEditable);
  for (var i = 0; i < textNodes.length; i++) {
    var node = textNodes[i];
    var isSelectedNode = node === (selection === null || selection === void 0 ? void 0 : selection.focusNode);
    if (isSelectedNode) {
      index += selection.focusOffset;
      break;
    } else {
      var _node$textContent3;
      index += ((_node$textContent3 = node.textContent) === null || _node$textContent3 === void 0 ? void 0 : _node$textContent3.length) || 0;
    }
  }
  return index;
}