'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var isNum = _interopDefault(require('./isNum'));
var isHTMLElement = _interopDefault(require('./isHTMLElement'));

/**
 * 设置输入框光标位置或定位光标到未尾
 * @param {Element} element 元素
 * @param {number} position 位置，不传默认到未尾
 *
 * @example
 * <input onfocus="setCursorPosition(e.target)" />
 */
function setCursorPosition(element, position) {
  if (isHTMLElement(element) && element.focus) {
    setTimeout(function () {
      if (!isNum(position)) {
        position = (element.value || '').length;
      }

      if (element.setSelectionRange) {
        element.focus();
        element.setSelectionRange(position, position);
      } else if (element.createTextRange) {
        var range = element.createTextRange();
        range.collapse(true);
        range.moveEnd('character', position);
        range.moveStart('character', position);
        range.select();
      }
    });
  }
}

module.exports = setCursorPosition;
