"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.ColorPickerDecorator = exports.ColorPickerBase = exports.ColorPicker = void 0;
var _dispatcher = require("@enact/core/dispatcher");
var _handle = require("@enact/core/handle");
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _propTypes = _interopRequireDefault(require("@enact/core/internal/prop-types"));
var _kind = _interopRequireDefault(require("@enact/core/kind"));
var _SpotlightContainerDecorator = _interopRequireDefault(require("@enact/spotlight/SpotlightContainerDecorator"));
var _Changeable = _interopRequireDefault(require("@enact/ui/Changeable"));
var _Group = _interopRequireDefault(require("@enact/ui/Group"));
var _Pure = _interopRequireDefault(require("@enact/ui/internal/Pure"));
var _Layout = require("@enact/ui/Layout");
var _Toggleable = _interopRequireDefault(require("@enact/ui/Toggleable"));
var _Transition = _interopRequireDefault(require("@enact/ui/Transition"));
var _colorConvert = _interopRequireDefault(require("color-convert"));
var _propTypes2 = _interopRequireDefault(require("prop-types"));
var _compose = _interopRequireDefault(require("ramda/src/compose"));
var _react = require("react");
var _$L = _interopRequireDefault(require("../internal/$L"));
var _Skinnable = _interopRequireDefault(require("../Skinnable"));
var _Button = _interopRequireDefault(require("../Button"));
var _Slider = _interopRequireDefault(require("../Slider"));
var _SwatchButton = _interopRequireDefault(require("./SwatchButton"));
var _ColorPickerModule = _interopRequireDefault(require("./ColorPicker.module.css"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["colorPickerRef", "children", "css", "disabled", "onChange", "onClick", "onHueChange", "onSaturationChange", "onLightnessChange", "onToggleExtended", "open", "sliderValues", "transitionContainerClassname", "transitionDirection", "value"];
/**
 * Agate component to allow the user to choose a color.
 *
 * @example
 * <ColorPicker defaultValue="#ffcc00">{['#fff', '#999', '#000']}</ColorPicker>
 *
 * @module agate/ColorPicker
 * @exports ColorPicker
 * @exports ColorPickerBase
 * @exports ColorPickerDecorator
 */
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _objectDestructuringEmpty(t) { if (null == t) throw new TypeError("Cannot destructure " + t); }
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 _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); }
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 _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 _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
var ContainerDiv = (0, _SpotlightContainerDecorator["default"])({
  enterTo: 'last-focused'
}, 'div');

// helper function to convert color hex strings or kewords to hue, saturation, and lightness values
var convertToHSL = function convertToHSL(value) {
  return _colorConvert["default"][value.charAt(0) === '#' ? 'hex' : 'keyword'].hsl(value);
};

/**
 * The color picker base component which sets-up the component's structure.
 *
 * This component is most often not used directly but may be composed within another component as it
 * is within {@link agate/ColorPicker.ColorPicker|ColorPicker}.
 *
 * @class ColorPickerBase
 * @memberof agate/ColorPicker
 * @ui
 * @public
 */
var ColorPickerBase = exports.ColorPickerBase = (0, _kind["default"])({
  name: 'ColorPicker',
  propTypes: /** @lends agate/ColorPicker.ColorPickerBase.prototype */{
    children: _propTypes2["default"].array,
    /**
     * Called with the reference to the colorPicker node.
     *
     * @type {Object|Function}
     * @public
     */
    colorPickerRef: _propTypes["default"].ref,
    /**
     * Customizes the component by mapping the supplied collection of CSS class names to the
     * corresponding internal elements and states of this component.
     *
     * The following classes are supported:
     *
     * * `colorPicker` - The root class name
     * * `palette` - The drawer that displays all the available options for color.
     *
     * @type {Object}
     * @public
     */
    css: _propTypes2["default"].object,
    // TODO: position `palette` like `Tooltip`
    /**
     * The animation direction of the `palette`.
     *
     * @type {String}
     * @default 'right'
     * @public
     */
    direction: _propTypes2["default"].string,
    /**
     * Disables the `ColorPicker`.
     *
     * @type {Boolean}
     * @public
     */
    disabled: _propTypes2["default"].bool,
    /**
     * Determines whether the extended color controls (sliders) are visible
     *
     * @type {Boolean}
     * @public
     */
    extended: _propTypes2["default"].bool,
    /**
     * Callback method with a payload containing the `color` that was just selected.
     *
     * @type {Function}
     * @public
     */
    onChange: _propTypes2["default"].func,
    /**
     * Callback method passed to the {@link agate/ColorPicker.SwatchButton|SwatchButton} component with a payload containing the `value` that was just selected.
     *
     * @type {Function}
     * @public
     */
    onClick: _propTypes2["default"].func,
    /**
     * Callback method with a payload containing the hue value of the selected `color`.
     *
     * @type {Function}
     * @public
     */
    onHueChange: _propTypes2["default"].func,
    /**
     * Callback method with a payload containing the lightness value of the selected `color`.
     *
     * @type {Function}
     * @public
     */
    onLightnessChange: _propTypes2["default"].func,
    /**
     * Callback method with a payload containing the saturation value of the selected `color`.
     *
     * @type {Function}
     * @public
     */
    onSaturationChange: _propTypes2["default"].func,
    /**
     * Callback method passed to the {@link agate/Button.Button|Button} component as `onTap`. This is used to toggle the visibility of the H/S/L sliders.
     *
     * @type {Function}
     * @public
     */
    onToggleExtended: _propTypes2["default"].func,
    /**
     * Opens ColorPicker with the contents visible.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    open: _propTypes2["default"].bool,
    /**
     * The color value. Setting this directly will not allow interaction with the
     * component. Use `defaultValue` to enable interactive use.
     *
     * The color should take the format of a HEX color. Ex: `#ffcc00` or `#3467af`
     *
     * @type {String}
     * @see {@link ui/Changeable.Changeable}
     * @default '#cccccc'
     * @public
     */
    value: _propTypes2["default"].string
  },
  defaultProps: {
    direction: 'right',
    open: false,
    value: '#cccccc'
  },
  styles: {
    css: _ColorPickerModule["default"],
    className: 'colorPicker',
    publicClassNames: ['colorPicker', 'palette']
  },
  computed: {
    children: function children(_ref) {
      var _children = _ref.children;
      return _children || [];
    },
    className: function className(_ref2) {
      var extended = _ref2.extended,
        styler = _ref2.styler;
      return styler.append({
        extended: extended
      });
    },
    sliderValues: function sliderValues(_ref3) {
      var value = _ref3.value;
      return {
        hsl: convertToHSL(value)
      };
    },
    transitionContainerClassname: function transitionContainerClassname(_ref4) {
      var css = _ref4.css,
        open = _ref4.open,
        styler = _ref4.styler;
      return styler.join(css.transitionContainer, open ? css.openTransitionContainer : null);
    },
    transitionDirection: function transitionDirection(_ref5) {
      var direction = _ref5.direction;
      switch (direction) {
        case 'left':
          return 'right';
        case 'right':
          return 'left';
        case 'up':
          return 'down';
        case 'down':
          return 'up';
      }
    }
  },
  render: function render(_ref6) {
    var colorPickerRef = _ref6.colorPickerRef,
      children = _ref6.children,
      css = _ref6.css,
      disabled = _ref6.disabled,
      onChange = _ref6.onChange,
      onClick = _ref6.onClick,
      onHueChange = _ref6.onHueChange,
      onSaturationChange = _ref6.onSaturationChange,
      onLightnessChange = _ref6.onLightnessChange,
      onToggleExtended = _ref6.onToggleExtended,
      open = _ref6.open,
      sliderValues = _ref6.sliderValues,
      transitionContainerClassname = _ref6.transitionContainerClassname,
      transitionDirection = _ref6.transitionDirection,
      value = _ref6.value,
      rest = _objectWithoutProperties(_ref6, _excluded);
    delete rest.extended;
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", _objectSpread(_objectSpread({
      ref: colorPickerRef
    }, rest), {}, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_SwatchButton["default"], {
        color: value,
        disabled: disabled,
        onClick: onClick
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Transition["default"], {
        className: transitionContainerClassname,
        visible: open,
        direction: transitionDirection,
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(ContainerDiv, {
          className: css.palette,
          spotlightDisabled: !open,
          spotlightRestrict: "self-only",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Group["default"], {
            childComponent: _SwatchButton["default"],
            childProp: "color",
            className: css.group,
            itemProps: {
              size: 'small',
              className: css.swatch
            },
            onSelect: onChange,
            children: children
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
            "aria-label": (0, _$L["default"])('More'),
            css: css,
            icon: "ellipsis",
            size: "small",
            onTap: onToggleExtended,
            className: css.swatch
          }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            className: css.sliders,
            children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_Layout.Row, {
              align: "center",
              children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_Layout.Cell, {
                "aria-label": (0, _$L["default"])('Hue'),
                role: "region",
                children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("label", {
                  children: (0, _$L["default"])('Hue')
                }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Slider["default"], {
                  "aria-label": (0, _$L["default"])('Degree'),
                  css: css,
                  value: sliderValues.hsl[0],
                  min: 0,
                  max: 360,
                  onChange: onHueChange
                })]
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.Cell, {
                component: "label",
                size: "5ex",
                children: sliderValues.hsl[0] + '˚'
              })]
            }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Layout.Row, {
              align: "center",
              children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_Layout.Cell, {
                "aria-label": (0, _$L["default"])('Saturation'),
                role: "region",
                children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("label", {
                  children: (0, _$L["default"])('Saturation')
                }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Slider["default"], {
                  "aria-label": (0, _$L["default"])('Percent'),
                  css: css,
                  value: sliderValues.hsl[1],
                  min: 0,
                  max: 100,
                  onChange: onSaturationChange
                })]
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.Cell, {
                component: "label",
                size: "5ex",
                children: sliderValues.hsl[1] + '%'
              })]
            }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Layout.Row, {
              align: "center",
              children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_Layout.Cell, {
                "aria-label": (0, _$L["default"])('Lightness'),
                role: "region",
                children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("label", {
                  children: (0, _$L["default"])('Lightness')
                }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Slider["default"], {
                  "aria-label": (0, _$L["default"])('Percent'),
                  css: css,
                  value: sliderValues.hsl[2],
                  min: 0,
                  max: 100,
                  onChange: onLightnessChange
                })]
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.Cell, {
                component: "label",
                size: "5ex",
                children: sliderValues.hsl[2] + '%'
              })]
            })]
          })]
        })
      })]
    }));
  }
});
var ColorPickerExtended = (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.buildValue = function () {
        var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref7$h = _ref7.h,
          h = _ref7$h === void 0 ? _this.hsl[0] : _ref7$h,
          _ref7$s = _ref7.s,
          s = _ref7$s === void 0 ? _this.hsl[1] : _ref7$s,
          _ref7$l = _ref7.l,
          l = _ref7$l === void 0 ? _this.hsl[2] : _ref7$l;
        return '#' + _colorConvert["default"].hsl.hex(h, s, l);
      };
      _this.clickedOutsidePalette = function (_ref8) {
        var target = _ref8.target;
        return !_this.colorPickerRef.current.contains(target);
      };
      // This handler is meant to accommodate using `ColorPicker`'s `onChange` prop from
      // `Changeable` as the `onSelect` handler for its `Group` component that lists the set of
      // pre-defined color choices.  `onSelect` sends the chosen value in the `data` prop of its
      // event but `Changeable` expects `value`.  The slider handlers for hue, saturation, and
      // light values in `ColorPickerExtended` use this handler to update the `value` prop via
      // `onChange` as well.
      _this.handleChange = (0, _handle.handle)((0, _handle.adaptEvent)(function (_ref9) {
        var value = _ref9.data;
        return {
          value: value
        };
      }, (0, _handle.forward)('onChange'))).bindAs(_this, 'handleChange');
      // If a click happened outside the component area (and children of us) dismiss the palette by forwarding the onClick from Toggleable.
      _this.handleClick = (0, _handle.handle)(_this.clickedOutsidePalette, (0, _handle.forward)('onClick')).bindAs(_this, 'handleClick');
      _this.handleToggleExtended = function () {
        _this.setState(function (_ref10) {
          var extended = _ref10.extended;
          return {
            extended: !extended
          };
        });
      };
      _this.handleSlider = function (type) {
        return function (_ref11) {
          var sliderValue = _ref11.value;
          _this.hsl['hsl'.indexOf(type)] = sliderValue;
          var value = _this.buildValue();
          _this.handleChange({
            data: value
          });
        };
      };
      _this.hsl = props.value ? convertToHSL(props.value) : [0, 0, 0];
      _this.colorPickerRef = /*#__PURE__*/(0, _react.createRef)();
      _this.state = {
        extended: props.defaultExtended || false
      };
      return _this;
    }
    _inherits(_Class, _Component);
    return _createClass(_Class, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        if (this.props.open) {
          (0, _dispatcher.on)('click', this.handleClick);
        }
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(prevProps) {
        var _this$props = this.props,
          open = _this$props.open,
          value = _this$props.value;
        if (prevProps.value !== value) {
          this.hsl = convertToHSL(value);
        }
        if (!prevProps.open && open) {
          (0, _dispatcher.on)('click', this.handleClick);
        } else if (prevProps.open && !open) {
          (0, _dispatcher.off)('click', this.handleClick);
        }
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        (0, _dispatcher.off)('click', this.handleClick);
      }
    }, {
      key: "render",
      value: function render() {
        var rest = Object.assign({}, (_objectDestructuringEmpty(this.props), this.props));
        delete rest.defaultExtended;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({}, rest), {}, {
          extended: this.state.extended,
          onChange: this.handleChange,
          onToggleExtended: this.handleToggleExtended,
          onHueChange: this.handleSlider('h'),
          onSaturationChange: this.handleSlider('s'),
          onLightnessChange: this.handleSlider('l'),
          colorPickerRef: this.colorPickerRef
        }));
      }
    }]);
  }(_react.Component), _Class.displayName = 'ColorPickerExtended', _Class.propTypes = {
    defaultExtended: _propTypes2["default"].bool,
    onChange: _propTypes2["default"].func,
    open: _propTypes2["default"].bool,
    value: _propTypes2["default"].string
  }, _Class;
});

/**
 * Applies Agate specific behaviors to {@link agate/ColorPicker.ColorPickerBase|ColorPickerBase}.
 *
 * @hoc
 * @memberof agate/ColorPicker
 * @mixes ui/Toggleable.Toggleable
 * @mixes agate/Skinnable.Skinnable
 * @public
 */
var ColorPickerDecorator = exports.ColorPickerDecorator = (0, _compose["default"])(_Pure["default"], _Changeable["default"], (0, _Toggleable["default"])({
  toggle: null,
  prop: 'open',
  toggleProp: 'onClick'
}), ColorPickerExtended, _Skinnable["default"]);

/**
 * A color picker component, ready to use in Agate applications.
 *
 * @class ColorPicker
 * @memberof agate/ColorPicker
 * @extends agate/ColorPicker.ColorPickerBase
 * @mixes agate/ColorPicker.ColorPickerDecorator
 * @ui
 * @public
 */
var ColorPicker = exports.ColorPicker = ColorPickerDecorator(ColorPickerBase);
var _default = exports["default"] = ColorPicker;