"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ColorPickerDecorator = exports.ColorPickerBase = exports.ColorPicker = exports["default"] = void 0;

var _jsxRuntime = require("react/jsx-runtime");

var _dispatcher = require("@enact/core/dispatcher");

var _handle = require("@enact/core/handle");

var _hoc = _interopRequireDefault(require("@enact/core/hoc"));

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 _propTypes = _interopRequireDefault(require("prop-types"));

var _compose = _interopRequireDefault(require("ramda/src/compose"));

var _react = require("react");

var _reactDom = _interopRequireDefault(require("react-dom"));

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"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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 [ColorPicker]{@link agate/ColorPicker.ColorPicker}.
 *
 * @class ColorPickerBase
 * @memberof agate/ColorPicker
 * @ui
 * @public
 */


var ColorPickerBase = (0, _kind["default"])({
  name: 'ColorPicker',
  propTypes:
  /** @lends agate/ColorPicker.ColorPickerBase.prototype */
  {
    children: _propTypes["default"].array,

    /**
     * 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: _propTypes["default"].object,
    // TODO: position `palette` like `Tooltip`

    /**
     * The animation direction of the `palette`.
     *
     * @type {String}
     * @default 'right'
     * @public
     */
    direction: _propTypes["default"].string,

    /**
     * Disables the `ColorPicker`.
     *
     * @type {Boolean}
     * @public
     */
    disabled: _propTypes["default"].bool,

    /**
     * Determines whether the extended color controls (sliders) are visible
     *
     * @type {Boolean}
     * @public
     */
    extended: _propTypes["default"].bool,

    /**
     * Callback method with a payload containing the `color` that was just selected.
     *
     * @type {Function}
     * @public
     */
    onChange: _propTypes["default"].func,

    /**
     * Callback method passed to the [SwatchButton]{@link agate/ColorPicker.SwatchButton} component with a payload containing the `value` that was just selected.
     *
     * @type {Function}
     * @public
     */
    onClick: _propTypes["default"].func,

    /**
     * Callback method with a payload containing the hue value of the selected `color`.
     *
     * @type {Function}
     * @public
     */
    onHueChange: _propTypes["default"].func,

    /**
     * Callback method with a payload containing the lightness value of the selected `color`.
     *
     * @type {Function}
     * @public
     */
    onLightnessChange: _propTypes["default"].func,

    /**
     * Callback method with a payload containing the saturation value of the selected `color`.
     *
     * @type {Function}
     * @public
     */
    onSaturationChange: _propTypes["default"].func,

    /**
     * Callback method passed to the [Button]{@link agate/Button.Button} component as `onTap`. This is used to toggle the visibility of the H/S/L sliders.
     *
     * @type {Function}
     * @public
     */
    onToggleExtended: _propTypes["default"].func,

    /**
     * Opens ColorPicker with the contents visible.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    open: _propTypes["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: _propTypes["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 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, ["children", "css", "disabled", "onChange", "onClick", "onHueChange", "onSaturationChange", "onLightnessChange", "onToggleExtended", "open", "sliderValues", "transitionContainerClassname", "transitionDirection", "value"]);

    delete rest.extended;
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", _objectSpread(_objectSpread({}, 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'),
            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'),
                  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'),
                  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'),
                  value: sliderValues.hsl[2],
                  min: 0,
                  max: 100,
                  onChange: onLightnessChange
                })]
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.Cell, {
                component: "label",
                size: "5ex",
                children: sliderValues.hsl[2] + '%'
              })]
            })]
          })]
        })
      })]
    }));
  }
});
exports.ColorPickerBase = ColorPickerBase;
var ColorPickerExtended = (0, _hoc["default"])(function (config, Wrapped) {
  var _class, _temp;

  return _temp = _class = /*#__PURE__*/function (_Component) {
    _inherits(_class, _Component);

    var _super = _createSuper(_class);

    function _class(props) {
      var _this;

      _classCallCheck(this, _class);

      _this = _super.call(this, 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.node.contains(target);
      };

      _this.handleChange = (0, _handle.handle)((0, _handle.adaptEvent)(function (_ref9) {
        var value = _ref9.data;
        return {
          value: value
        };
      }, (0, _handle.forward)('onChange'))).bindAs(_assertThisInitialized(_this), 'handleChange');
      _this.handleClick = (0, _handle.handle)(_this.clickedOutsidePalette, (0, _handle.forward)('onClick')).bindAs(_assertThisInitialized(_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.state = {
        extended: props.defaultExtended || false
      };
      return _this;
    }

    _createClass(_class, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        // TODO: change to using ref/forwardRef/something else?
        // eslint-disable-next-line react/no-find-dom-node
        this.node = _reactDom["default"].findDOMNode(this);

        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({}, 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')
        }));
      }
    }]);

    return _class;
  }(_react.Component), _class.displayName = 'ColorPickerExtended', _class.propTypes = {
    defaultExtended: _propTypes["default"].bool,
    onChange: _propTypes["default"].func,
    open: _propTypes["default"].bool,
    value: _propTypes["default"].string
  }, _temp;
});
/**
 * Applies Agate specific behaviors to [ColorPickerBase]{@link agate/ColorPicker.ColorPickerBase}.
 *
 * @hoc
 * @memberof agate/ColorPicker
 * @mixes ui/Toggleable.Toggleable
 * @mixes agate/Skinnable.Skinnable
 * @public
 */

var 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
 */

exports.ColorPickerDecorator = ColorPickerDecorator;
var ColorPicker = ColorPickerDecorator(ColorPickerBase);
exports.ColorPicker = ColorPicker;
var _default = ColorPicker;
exports["default"] = _default;