'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
require('../../../../utils/index.cjs');
var log = require('../../../../utils/log.cjs');

function useCursor(inputRef, focused) {
  const selectionRef = vue.ref(null);
  function recordCursor() {
    try {
      const { selectionStart: start, selectionEnd: end, value } = inputRef.value;
      const beforeTxt = value.substring(0, start);
      const afterTxt = value.substring(end);
      selectionRef.value = {
        start,
        end,
        value,
        beforeTxt,
        afterTxt
      };
    } catch (e) {
    }
  }
  function restoreCursor() {
    if (inputRef.value && selectionRef.value && focused.value) {
      try {
        const { value } = inputRef.value;
        const { beforeTxt, afterTxt, start } = selectionRef.value;
        let startPos = value.length;
        if (value.endsWith(afterTxt)) {
          startPos = value.length - selectionRef.value.afterTxt.length;
        } else if (value.startsWith(beforeTxt)) {
          startPos = beforeTxt.length;
        } else {
          const beforeLastChar = beforeTxt[start - 1];
          const newIndex = value.indexOf(beforeLastChar, start - 1);
          if (newIndex !== -1)
            startPos = newIndex + 1;
        }
        inputRef.value.setSelectionRange(startPos, startPos);
      } catch (e) {
        log.warning(
          false,
          `Something warning of cursor restore. Please fire issue about this: ${e.message}`
        );
      }
    }
  }
  return [recordCursor, restoreCursor];
}

exports.default = useCursor;
//# sourceMappingURL=useCursor.cjs.map
