"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.ArcSliderBehaviorDecorator = void 0;
var _handle = require("@enact/core/handle");
var _keymap = require("@enact/core/keymap");
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _util = require("@enact/core/util");
var _validators = require("@enact/ui/internal/validators");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _utils = require("../Arc/utils");
var _utils2 = require("./utils");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var isDown = (0, _keymap.is)('down');
var isUp = (0, _keymap.is)('up');
var validateValueRange = (0, _validators.validateRangeOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator'
});
var validateAngleRange = (0, _validators.validateRangeOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator',
  minName: 'startAngle',
  maxName: 'endAngle'
});
var validateStepValue = (0, _validators.validateSteppedOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator'
});
var validateStepMax = (0, _validators.validateSteppedOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator',
  valueName: 'max'
});

/**
 * Adds agate-specific arcSlider behaviors.
 *
 * @class ArcSliderBehaviorDecorator
 * @memberof agate/ArcSlider
 * @hoc
 * @public
 */
var ArcSliderBehaviorDecorator = exports.ArcSliderBehaviorDecorator = (0, _hoc["default"])(function (config, Wrapped) {
  var _Class;
  return _Class = /*#__PURE__*/function (_Component) {
    function _Class(props) {
      var _this;
      _classCallCheck(this, _Class);
      _this = _callSuper(this, _Class, [props]);
      _this.handleDown = function (_ref) {
        var clientX = _ref.clientX,
          clientY = _ref.clientY;
        var params = {
          x: clientX,
          y: clientY
        };
        (0, _handle.forward)('onDown', params, _this.props);
        if (clientX != null && clientY != null) {
          _this.emitChangeForPosition(params);
        }
      };
      _this.handleDragStart = function (ev) {
        (0, _handle.forward)('onDragStart', ev, _this.props);
        _this.emitChangeForPosition(ev);
      };
      _this.handleDrag = function (ev) {
        (0, _handle.forward)('onDrag', ev, _this.props);
        _this.emitChangeForPosition(ev);
      };
      // Calculates the new SVG value based on the mouse cursor coordinates and sets the new value into the state
      _this.emitChangeForPosition = function (ev) {
        var componentRef = _this.componentRef.current;
        if (!componentRef) {
          return;
        }
        var _this$props = _this.props,
          endAngle = _this$props.endAngle,
          max = _this$props.max,
          min = _this$props.min,
          radius = _this$props.radius,
          startAngle = _this$props.startAngle,
          step = _this$props.step,
          strokeWidth = _this$props.strokeWidth;
        // Find the coordinates with respect to the SVG
        var svgPoint = componentRef.createSVGPoint();
        svgPoint.x = ev.x;
        svgPoint.y = ev.y;
        var coordsInSvg = svgPoint.matrixTransform(componentRef.getScreenCTM().inverse());
        var angle = (0, _utils.positionToAngle)(coordsInSvg, radius * 2 - strokeWidth);
        // get the value based on the angle, min and max
        var value = (0, _utils2.angleToValue)(angle, min, Math.max(min, max), startAngle, endAngle);

        // adjust value based on the step
        if (step) {
          var delta = (value - min) % step;
          if (delta < step / 2) {
            value -= delta;
          } else {
            value += step - delta;
          }
        }
        _this.handleChange(ev, value);
      };
      _this.handleChange = function (ev, value) {
        if (value !== _this.state.value) {
          _this.setState(function () {
            return {
              value: value
            };
          }, function () {
            (0, _handle.forward)('onChange', {
              type: 'onChange',
              value: value
            }, _this.props);
          });
        }
        if (ev && ev.stopPropagation) {
          ev.stopPropagation();
        }
      };
      _this.handleBlur = function () {
        _this.setState({
          isFocused: false
        });
      };
      _this.handleFocus = function () {
        _this.setState({
          isFocused: true
        });
      };
      _this.handleKeyDown = function (ev) {
        var _this$props2 = _this.props,
          disabled = _this$props2.disabled,
          max = _this$props2.max,
          min = _this$props2.min,
          step = _this$props2.step;
        var value = _this.state.value;
        (0, _handle.forward)('onKeyDown', ev, _this.props);
        if (!disabled) {
          if (isDown(ev.keyCode)) {
            _this.handleChange(ev, Math.max(value - step, min));
          } else if (isUp(ev.keyCode)) {
            _this.handleChange(ev, Math.min(value + step, max));
          }
        }
      };
      _this.componentRef = /*#__PURE__*/(0, _react.createRef)();
      _this.state = {
        isFocused: false,
        value: props.value ? props.value : props.min
      };
      return _this;
    }
    _inherits(_Class, _Component);
    return _createClass(_Class, [{
      key: "componentDidUpdate",
      value: function componentDidUpdate(prevProps) {
        if (this.props.max !== prevProps.max || this.props.min !== prevProps.min) {
          this.handleChange(null, (0, _util.clamp)(this.props.min, this.props.max, this.state.value));
        }
      }
    }, {
      key: "render",
      value: function render() {
        if (process.env.NODE_ENV !== "production") {
          var _this$props3 = this.props,
            endAngle = _this$props3.endAngle,
            max = _this$props3.max,
            min = _this$props3.min,
            startAngle = _this$props3.startAngle,
            step = _this$props3.step;
          var valueProps = {
            min: min,
            value: this.state.value,
            max: max,
            step: step
          };
          var angleProps = {
            startAngle: startAngle,
            endAngle: endAngle
          };
          validateValueRange(valueProps);
          validateAngleRange(angleProps);
          validateStepValue(valueProps);
          validateStepMax(valueProps);
        }
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({}, this.props), {}, {
          componentRef: this.componentRef,
          isFocused: this.state.isFocused,
          onBlur: this.handleBlur,
          onChange: this.handleChange,
          onDown: this.handleDown,
          onDrag: this.handleDrag,
          onDragStart: this.handleDragStart,
          onFocus: this.handleFocus,
          onKeyDown: this.handleKeyDown,
          value: this.state.value
        }));
      }
    }]);
  }(_react.Component), _Class.displayName = 'ArcSliderBehaviorDecorator', _Class.propTypes = /** @lends agate/ArcSlider.ArcSliderBehaviorDecorator.prototype */{
    /**
     * Whether or not the component is in a disabled state.
     *
     * @type {Boolean}
     * @public
     */
    disabled: _propTypes["default"].bool,
    /**
     * The end angle(in degrees) of the arc slider.
     *
     * The value should be between 0 and 360 and should be greater than startAngle.
     *
     * @type {Number}
     * @default 250
     * @public
     */
    endAngle: _propTypes["default"].number,
    /**
     * The maximum value of the slider and should be greater than min.
     *
     * @type {Number}
     * @default 100
     * @public
     */
    max: _propTypes["default"].number,
    /**
     * The minimum value of the slider.
     *
     * @type {Number}
     * @default 0
     * @public
     */
    min: _propTypes["default"].number,
    /**
     * Called when value is changed.
     *
     * @type {Function}
     * @public
     */
    onChange: _propTypes["default"].func,
    /**
     * The radius of the arc circle.
     *
     * @type {Number}
     * @default 150
     * @public
     */
    radius: _propTypes["default"].number,
    /**
     * The start angle(in degrees) of the arc slider.
     *
     * The value should be between 0 and 360.
     *
     * @type {Number}
     * @default 30
     * @public
     */
    startAngle: _propTypes["default"].number,
    /**
     * The amount to increment or decrement the value.
     *
     * @type {Number}
     * @default 1
     * @public
     */
    step: _propTypes["default"].number,
    /**
     * The stroke width of the arc slider.
     *
     * @type {Number}
     * @default 6
     * @public
     */
    strokeWidth: _propTypes["default"].number,
    /**
     * The value of the slider.
     *
     * Defaults to the value of `min`.
     *
     * @type {Number}
     * @public
     */
    value: _propTypes["default"].number
  }, _Class.defaultProps = {
    endAngle: 250,
    max: 100,
    min: 0,
    radius: 150,
    startAngle: 30,
    step: 1,
    strokeWidth: 6
  }, _Class;
});
var _default = exports["default"] = ArcSliderBehaviorDecorator;