import { useCallback } from 'react';
import { isValueValid } from './validation';

/**
 * Given some text that is being entered in an input, work out what the
 * new value will be based on the cursor position ond selection.
 */
function getNewInputValue(input, newText) {
  var textBeforeSelection = input.value.substring(0, input.selectionStart || 0);
  var textAfterSelection = input.value.substring(input.selectionEnd || 0);
  return "".concat(textBeforeSelection).concat(newText).concat(textAfterSelection);
}
export function useEarlyValidation(isNegativeAllowed) {
  /**
   * Block invalid pastes before the DOM is updated (to
   * avoid the cursor jumping).
   *
   * Only needed for Firefox and IE.
   */
  var handlePaste = useCallback(function (event) {
    var pastedText = event.clipboardData.getData('text');
    var newValue = getNewInputValue(event.currentTarget, pastedText);
    if (!isValueValid(newValue, isNegativeAllowed)) {
      event.preventDefault();
      event.stopPropagation();
    }
  }, [isNegativeAllowed]);

  /**
   * Block invalid input before the DOM is updated where possible (to
   * avoid the cursor jumping).
   *
   * Note: React simulates this event using other native events.
   */
  var handleBeforeInput = useCallback(function (event) {
    // Unfortunately, the event seems to be typed incorrectly at present
    // (without the data property)
    if (!('data' in event)) {
      return;
    }

    // data could contain a single character, or something longer
    // in case of pasting. The text could be an insertion or a
    // replacement (if existing text was selected).
    var data = event.data;
    var newValue = getNewInputValue(event.currentTarget, data);
    if (!isValueValid(newValue, isNegativeAllowed)) {
      event.preventDefault();
      event.stopPropagation();
    }
  }, [isNegativeAllowed]);
  return {
    handleBeforeInput: handleBeforeInput,
    handlePaste: handlePaste
  };
}