"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.SliderBehaviorDecorator = void 0;
var _handle = require("@enact/core/handle");
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _platform = _interopRequireDefault(require("@enact/core/platform"));
var _Pause = _interopRequireDefault(require("@enact/spotlight/Pause"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _$L = _interopRequireDefault(require("../internal/$L"));
var _utils = 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 useHintOnActive = function useHintOnActive(_ref) {
  var active = _ref.active;
  return {
    useHintText: active
  };
};
var toggleActive = function toggleActive(_ref2) {
  var active = _ref2.active;
  return {
    active: !active
  };
};
var defaultConfig = {
  // FIXME: This is a compromise to maintain a single decorator for Slider and IncrementSlider
  // that handles both a consolidated focus state and spotlight directional event mgmt. When this
  // is unset (for Slider), this decorator will listen to onKeyDown and fire spotlight events.
  // When set (for IncrementSlider), it specifies the event that is passed down to trigger
  // spotlight events and also doesn't remove the spotlight directional callbacks from the props
  // so the Wrapped component can fire them manually or use the callback for the default behavior.
  emitSpotlightEvents: null
};

// Adds agate-specific slider behaviors
// * aria-valuetext handling
//   * use aria-valuetext when set
//   * defaults to current value
//   * onActivate, set to hint text
//   * on value change, reset to value or aria-valuetext
// * Spotlight
//   * Pause Spotlight when dragging to prevent spotlight from leaving when pointer enters another
//     component
//   * Forward directional spotlight events from slider
// * Managing focused state to show/hide tooltip
var SliderBehaviorDecorator = exports.SliderBehaviorDecorator = (0, _hoc["default"])(defaultConfig, function (config, Wrapped) {
  var _Class;
  var emitSpotlightEvents = config.emitSpotlightEvents;
  return _Class = /*#__PURE__*/function (_Component) {
    function _Class(props) {
      var _this;
      _classCallCheck(this, _Class);
      _this = _callSuper(this, _Class, [props]);
      _this.paused = new _Pause["default"]();
      _this.handleActivate = _this.handleActivate.bind(_this);
      _this.handleBlur = _this.handleBlur.bind(_this);
      _this.handleDragEnd = _this.handleDragEnd.bind(_this);
      _this.handleDragStart = _this.handleDragStart.bind(_this);
      _this.handleFocus = _this.handleFocus.bind(_this);
      _this.handleSpotlightEvents = _this.handleSpotlightEvents.bind(_this);
      _this.bounds = {};
      _this.sliderRef = /*#__PURE__*/(0, _react.createRef)();
      _this.state = {
        active: false,
        dragging: false,
        focused: false,
        useHintText: false,
        prevValue: props.value
      };
      return _this;
    }
    _inherits(_Class, _Component);
    return _createClass(_Class, [{
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        this.paused.resume();
      }
    }, {
      key: "getValueText",
      value: function getValueText() {
        var _this$props = this.props,
          ariaValueText = _this$props['aria-valuetext'],
          min = _this$props.min,
          orientation = _this$props.orientation,
          _this$props$value = _this$props.value,
          value = _this$props$value === void 0 ? min : _this$props$value;
        var useHintText = this.state.useHintText;
        var verticalHint = (0, _$L["default"])('change a value with up down button');
        var horizontalHint = (0, _$L["default"])('change a value with left right button');
        if (useHintText) {
          return orientation === 'horizontal' ? horizontalHint : verticalHint;
        }
        if (ariaValueText != null) {
          return ariaValueText;
        }
        return value;
      }
    }, {
      key: "focusSlider",
      value: function focusSlider() {
        var slider = this.sliderRef.current;
        if (slider.getAttribute('role') !== 'slider') {
          slider = slider.querySelector('[role="slider"]');
        }
        slider.focus();
      }
    }, {
      key: "handleActivate",
      value: function handleActivate() {
        (0, _handle.forward)('onActivate', {
          type: 'onActivate'
        }, this.props);
        this.setState(toggleActive);
        this.setState(useHintOnActive);
      }
    }, {
      key: "handleBlur",
      value: function handleBlur(ev) {
        (0, _handle.forward)('onBlur', ev, this.props);
        this.setState({
          focused: false
        });
      }
    }, {
      key: "handleDragStart",
      value: function handleDragStart() {
        // on platforms with a touchscreen, we want to focus slider when dragging begins
        if (_platform["default"].touchScreen) {
          this.focusSlider();
        }
        this.paused.pause();
        this.setState({
          dragging: true
        });
      }
    }, {
      key: "handleDragEnd",
      value: function handleDragEnd() {
        this.paused.resume();
        this.setState({
          dragging: false
        });
      }
    }, {
      key: "handleFocus",
      value: function handleFocus(ev) {
        (0, _handle.forward)('onFocus', ev, this.props);
        this.setState({
          focused: true
        });
      }
    }, {
      key: "handleSpotlightEvents",
      value: function handleSpotlightEvents(ev) {
        if (!emitSpotlightEvents) {
          (0, _handle.forward)('onKeyDown', ev, this.props);
        }
        (0, _utils.forwardSpotlightEvents)(ev, this.props);
      }
    }, {
      key: "render",
      value: function render() {
        var props = Object.assign({}, this.props);
        if (!emitSpotlightEvents) {
          // Remove spotlight props before hitting spottable since we've handled them uniquely
          delete props.onSpotlightLeft;
          delete props.onSpotlightRight;
          delete props.onSpotlightUp;
          delete props.onSpotlightDown;
          props.onKeyDown = this.handleSpotlightEvents;
        } else {
          props[emitSpotlightEvents] = this.handleSpotlightEvents;
        }
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({
          role: "slider"
        }, props), {}, {
          active: this.state.active,
          "aria-valuetext": this.getValueText(),
          focused: this.state.focused || this.state.dragging,
          onActivate: this.handleActivate,
          onBlur: this.handleBlur,
          onDragStart: this.handleDragStart,
          onDragEnd: this.handleDragEnd,
          onFocus: this.handleFocus,
          sliderRef: this.sliderRef
        }));
      }
    }], [{
      key: "getDerivedStateFromProps",
      value: function getDerivedStateFromProps(props, state) {
        if (props.value !== state.prevValue) {
          return {
            useHintText: false,
            prevValue: props.value
          };
        }
        return null;
      }
    }]);
  }(_react.Component), _Class.displayName = 'SliderBehaviorDecorator', _Class.propTypes = {
    'aria-valuetext': _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
    max: _propTypes["default"].number,
    min: _propTypes["default"].number,
    orientation: _propTypes["default"].string,
    value: _propTypes["default"].number
  }, _Class.defaultProps = {
    max: 100,
    min: 0,
    orientation: 'horizontal'
  }, _Class;
});
var _default = exports["default"] = SliderBehaviorDecorator;