/**
 * amis-ui v6.14.0-beta.1
 * Copyright 2018-2025 fex
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var React = require('react');
var ReactDOM = require('react-dom');
var reactColor = require('react-color');
var icons = require('./icons.js');
var amisCore = require('amis-core');
var PopUp = require('./PopUp.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var ColorControl = /** @class */ (function (_super) {
    tslib.__extends(ColorControl, _super);
    function ColorControl(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            isOpened: false,
            isFocused: false,
            inputValue: _this.props.value || '',
            tempValue: _this.props.value || ''
        };
        _this.open = _this.open.bind(_this);
        _this.close = _this.close.bind(_this);
        _this.focus = _this.focus.bind(_this);
        _this.blur = _this.blur.bind(_this);
        _this.handleChange = _this.handleChange.bind(_this);
        _this.handleTempChange = _this.handleTempChange.bind(_this);
        _this.handleConfirm = _this.handleConfirm.bind(_this);
        _this.handleFocus = _this.handleFocus.bind(_this);
        _this.handleBlur = _this.handleBlur.bind(_this);
        _this.clearValue = _this.clearValue.bind(_this);
        _this.handleInputChange = _this.handleInputChange.bind(_this);
        _this.handleClick = _this.handleClick.bind(_this);
        _this.preview = React__default["default"].createRef();
        _this.input = React__default["default"].createRef();
        return _this;
    }
    ColorControl.prototype.componentDidUpdate = function (prevProps) {
        var props = this.props;
        if (prevProps.value !== props.value) {
            this.setState({
                inputValue: props.value || ''
            });
        }
    };
    ColorControl.prototype.handleFocus = function () {
        this.setState({
            isFocused: true
        });
    };
    ColorControl.prototype.handleBlur = function () {
        this.setState({
            isFocused: false,
            inputValue: this.props.value
        });
    };
    ColorControl.prototype.focus = function () {
        this.input.current && this.input.current.focus();
    };
    ColorControl.prototype.blur = function () {
        this.input.current && this.input.current.blur();
    };
    ColorControl.prototype.open = function (fn) {
        if (this.props.disabled) {
            return;
        }
        this.setState({
            isOpened: true
        }, fn);
    };
    ColorControl.prototype.close = function () {
        this.setState({
            isOpened: false
        });
    };
    ColorControl.prototype.clearValue = function () {
        var _a = this.props, onChange = _a.onChange, resetValue = _a.resetValue;
        onChange(resetValue || '');
    };
    ColorControl.prototype.handleClick = function () {
        this.state.isOpened ? this.close() : this.open(this.focus);
    };
    ColorControl.prototype.handleInputChange = function (e) {
        var _this = this;
        if (!this.props.allowCustomColor) {
            return;
        }
        var onChange = this.props.onChange;
        this.setState({
            inputValue: e.currentTarget.value
        }, function () {
            var isValidated = _this.validateColor(_this.state.inputValue);
            if (isValidated) {
                onChange(_this.state.inputValue);
            }
        });
    };
    ColorControl.prototype.validateColor = function (value) {
        if (value === '') {
            return false;
        }
        if (value === 'inherit') {
            return false;
        }
        if (value === 'transparent') {
            return false;
        }
        var image = document.createElement('img');
        image.style.color = 'rgb(0, 0, 0)';
        image.style.color = value;
        if (image.style.color !== 'rgb(0, 0, 0)') {
            return true;
        }
        image.style.color = 'rgb(255, 255, 255)';
        image.style.color = value;
        return image.style.color !== 'rgb(255, 255, 255)';
    };
    ColorControl.prototype.handleChange = function (color) {
        var _a = this.props, onChange = _a.onChange, format = _a.format
        // closeOnSelect
        ;
        if (format === 'rgba') {
            onChange("rgba(".concat(color.rgb.r, ", ").concat(color.rgb.g, ", ").concat(color.rgb.b, ", ").concat(color.rgb.a, ")"));
        }
        else if (format === 'rgb') {
            onChange("rgb(".concat(color.rgb.r, ", ").concat(color.rgb.g, ", ").concat(color.rgb.b, ")"));
        }
        else if (format === 'hexa') {
            onChange(this.rgbaToHex(color.rgb.r, color.rgb.g, color.rgb.b, color.rgb.a));
        }
        else if (format === 'hsl') {
            onChange("hsl(".concat(Math.round(color.hsl.h), ", ").concat(Math.round(color.hsl.s * 100), "%, ").concat(Math.round(color.hsl.l * 100), "%)"));
        }
        else {
            onChange(color.hex);
        }
        // closeOnSelect && this.close();
    };
    ColorControl.prototype.handleTempChange = function (color) {
        var tempValue = this.state.tempValue;
        var format = this.props.format;
        if (format === 'rgba') {
            tempValue = "rgba(".concat(color.rgb.r, ", ").concat(color.rgb.g, ", ").concat(color.rgb.b, ", ").concat(color.rgb.a, ")");
        }
        else if (format === 'rgb') {
            tempValue = "rgb(".concat(color.rgb.r, ", ").concat(color.rgb.g, ", ").concat(color.rgb.b, ")");
        }
        else if (format === 'hexa') {
            tempValue = this.rgbaToHex(color.rgb.r, color.rgb.g, color.rgb.b, color.rgb.a);
        }
        else if (format === 'hsl') {
            tempValue = "hsl(".concat(Math.round(color.hsl.h), ", ").concat(Math.round(color.hsl.s * 100), "%, ").concat(Math.round(color.hsl.l * 100), "%)");
        }
        else {
            tempValue = color.hex;
        }
        this.setState({ tempValue: tempValue });
    };
    ColorControl.prototype.handleConfirm = function () {
        var onChange = this.props.onChange;
        var tempValue = this.state.tempValue;
        onChange(tempValue);
        this.close();
    };
    /**
     * Converts an RGBA color to an 8-digit hex color.
     *
     * @param r - Red component (0-255)
     * @param g - Green component (0-255)
     * @param b - Blue component (0-255)
     * @param a - Alpha component (1-100)
     * @returns The hex color string in the format #RRGGBBAA
     */
    ColorControl.prototype.rgbaToHex = function (r, g, b, a) {
        if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
            return "#00000000";
        }
        if (typeof a === 'undefined' || a > 1) {
            a = 1;
        }
        if (a < 0.01) {
            a = 0;
        }
        var toHex = function (n) { return n.toString(16).padStart(2, '0').toUpperCase(); };
        var alphaHex = toHex(Math.round(a * 255));
        var redHex = toHex(r);
        var greenHex = toHex(g);
        var blueHex = toHex(b);
        return "#".concat(redHex).concat(greenHex).concat(blueHex).concat(alphaHex);
    };
    ColorControl.prototype.render = function () {
        var _this = this;
        var _a = this.props, ns = _a.classPrefix, className = _a.className, popoverClassName = _a.popoverClassName, value = _a.value, placeholder = _a.placeholder, disabled = _a.disabled, popOverContainer = _a.popOverContainer, popOverContainerSelector = _a.popOverContainerSelector, format = _a.format, clearable = _a.clearable, placement = _a.placement, cx = _a.classnames, presetColors = _a.presetColors, allowCustomColor = _a.allowCustomColor, mobileUI = _a.mobileUI;
        var __ = this.props.translate;
        var isOpened = this.state.isOpened;
        var isFocused = this.state.isFocused;
        var tempValue = this.state.tempValue;
        return (_J$X_("div", { className: cx("ColorPicker", {
                'is-disabled': disabled,
                'is-focused': isFocused,
                'is-opened': isOpened
            }, className) },
            _J$X_("span", { onClick: this.handleClick, className: cx('ColorPicker-preview') },
                _J$X_("i", { ref: this.preview, className: "".concat(ns, "ColorPicker-previewIcon"), style: { background: this.state.inputValue || '#ccc' } })),
            _J$X_("input", { ref: this.input, type: "text", autoComplete: "off", size: 10, className: cx('ColorPicker-input'), value: this.state.inputValue || '', placeholder: __(placeholder), disabled: disabled, onChange: this.handleInputChange, onFocus: this.handleFocus, onBlur: this.handleBlur, onClick: this.handleClick, readOnly: mobileUI }),
            clearable && !disabled && value ? (_J$X_("a", { onClick: this.clearValue, className: cx('ColorPicker-clear') },
                _J$X_(icons.Icon, { icon: "input-clear", className: "icon" }))) : null,
            _J$X_("span", { className: cx('ColorPicker-arrow') },
                _J$X_(icons.Icon, { icon: "right-arrow-bold", className: "icon", onClick: this.handleClick })),
            !mobileUI && isOpened ? (_J$X_(amisCore.Overlay, { placement: placement || 'auto', target: function () { return ReactDOM.findDOMNode(_this); }, onHide: this.close, container: popOverContainer || (function () { return ReactDOM.findDOMNode(_this); }), containerSelector: popOverContainerSelector, rootClose: false, show: true },
                _J$X_(amisCore.PopOver, { classPrefix: ns, className: cx('ColorPicker-popover', popoverClassName), onHide: this.close, overlay: true }, allowCustomColor ? (_J$X_(reactColor.SketchPicker, { styles: {}, disableAlpha: !!~['rgb', 'hex'].indexOf(format), color: value, presetColors: presetColors, onChangeComplete: this.handleChange })) : (_J$X_(reactColor.GithubPicker, { color: value, colors: Array.isArray(presetColors)
                        ? presetColors
                            .filter(function (item) { return typeof item === 'string' || amisCore.isObject(item); })
                            .map(function (item) {
                            return typeof item === 'string'
                                ? item
                                : amisCore.isObject(item)
                                    ? item === null || item === void 0 ? void 0 : item.color
                                    : item;
                        })
                        : undefined, onChangeComplete: this.handleChange }))))) : null,
            mobileUI && (_J$X_(PopUp["default"], { className: cx("".concat(ns, "ColorPicker-popup")), container: popOverContainer, isShow: isOpened, onHide: this.handleClick, showConfirm: true, onConfirm: this.handleConfirm }, allowCustomColor ? (_J$X_(reactColor.SketchPicker, { styles: {}, disableAlpha: !!~['rgb', 'hex'].indexOf(format), color: tempValue, presetColors: presetColors, onChangeComplete: this.handleTempChange })) : (_J$X_(reactColor.GithubPicker, { color: tempValue, colors: Array.isArray(presetColors)
                    ? presetColors
                        .filter(function (item) { return typeof item === 'string' || amisCore.isObject(item); })
                        .map(function (item) {
                        return typeof item === 'string'
                            ? item
                            : amisCore.isObject(item)
                                ? item === null || item === void 0 ? void 0 : item.color
                                : item;
                    })
                    : undefined, onChangeComplete: this.handleTempChange }))))));
    };
    ColorControl.defaultProps = {
        format: 'hex',
        clearable: true,
        placeholder: 'ColorPicker.placeholder',
        allowCustomColor: true
        // closeOnSelect: true
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [String]),
        tslib.__metadata("design:returntype", void 0)
    ], ColorControl.prototype, "validateColor", null);
    return ColorControl;
}(React__default["default"].PureComponent));
var ColorPicker = amisCore.themeable(amisCore.localeable(amisCore.uncontrollable(ColorControl, {
    value: 'onChange'
})));

exports.ColorControl = ColorControl;
exports["default"] = ColorPicker;
