import { defineComponent, ref, reactive, computed, nextTick, onMounted, watch, provide, openBlock, createBlock, unref, withCtx, withDirectives, createElementBlock, createElementVNode, normalizeClass, createVNode, createCommentVNode, withModifiers, withKeys, normalizeStyle, vShow } from 'vue';
import { debounce } from 'lodash-unified';
import { ElRadioGroup, ElRadioButton } from '../../radio/index.mjs';
import { ElIcon } from '../../icon/index.mjs';
import '../../../directives/index.mjs';
import { ElTooltip } from '../../tooltip/index.mjs';
import { ElInput } from '../../input/index.mjs';
import '../../../hooks/index.mjs';
import '../../../constants/index.mjs';
import '../../../utils/index.mjs';
import { EditPen, ArrowDown, Close } from '@element-plus/icons-vue';
import AlphaSlider from './components/alpha-slider.mjs';
import HueSlider from './components/hue-slider.mjs';
import Predefine from './components/predefine.mjs';
import SvPanel from './components/sv-panel.mjs';
import Color from './utils/color.mjs';
import { colorPickerProps, colorPickerEmits, colorPickerContextKey } from './color-picker.mjs';
import { useEyeDropper } from '@vueuse/core';
import _export_sfc from '../../../_virtual/plugin-vue_export-helper.mjs';
import { useLocale } from '../../../hooks/use-locale/index.mjs';
import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
import { useFormItem, useFormItemInputId } from '../../../hooks/use-form-item/index.mjs';
import { useSize, useDisabled } from '../../../hooks/use-common-props/index.mjs';
import { UPDATE_MODEL_EVENT } from '../../../constants/event.mjs';
import { debugWarn } from '../../../utils/error.mjs';
import ClickOutside from '../../../directives/click-outside/index.mjs';

const _hoisted_1 = ["id", "aria-label", "aria-labelledby", "aria-description", "tabindex", "onKeydown"];
const __default__ = defineComponent({
  name: "ElColorPicker"
});
const _sfc_main = /* @__PURE__ */ defineComponent({
  ...__default__,
  props: colorPickerProps,
  emits: colorPickerEmits,
  setup(__props, { expose, emit }) {
    var _a, _b;
    const props = __props;
    const { isSupported, open, sRGBHex } = useEyeDropper();
    const { t } = useLocale();
    const ns = useNamespace("color");
    const { formItem } = useFormItem();
    const colorSize = useSize();
    const colorDisabled = useDisabled();
    const { inputId: buttonId, isLabeledByFormItem } = useFormItemInputId(props, {
      formItemContext: formItem
    });
    const hue = ref();
    const sv = ref();
    const alpha = ref();
    const popper = ref();
    let shouldActiveChange = true;
    const color = reactive(new Color({
      enableAlpha: props.showAlpha,
      format: props.colorFormat || ((_a = props.modelValue) == null ? void 0 : _a.startsWith("#")) ? "hex" : "rgb",
      value: props.modelValue
    }));
    const showPicker = ref(false);
    const showPanelColor = ref(false);
    const customInput = ref("");
    const displayedColor = computed(() => {
      if (!props.modelValue && !showPanelColor.value) {
        return "transparent";
      }
      return displayedRgb(color, props.showAlpha);
    });
    const computdTriggerWidth = computed(() => {
      return colorSize.value === "large" ? props.triggerWidth + 18 : props.triggerWidth;
    });
    const computdTriggeIconWidth = computed(() => {
      return colorSize.value === "large" ? computdTriggerWidth.value * 2 - 70 : computdTriggerWidth.value * 2 - 60;
    });
    const getEyeDropper = () => {
      if (!isSupported)
        return;
      open();
    };
    const colorMode = ref(((_b = props.modelValue) == null ? void 0 : _b.startsWith("#")) ? "HEX" : "RGB");
    const currentColor = computed(() => {
      return !props.modelValue && !showPanelColor.value ? "" : color.value;
    });
    const modeChange = (val) => {
      color.format = val.toLowerCase();
      handleConfirm();
      customInput.value = color.value;
    };
    function customInputChange() {
      handleConfirm();
      customInput.value = color.value;
      confirmValue();
    }
    const buttonAriaLabel = computed(() => {
      return !isLabeledByFormItem.value ? props.label || t("el.colorpicker.defaultLabel") : void 0;
    });
    const buttonAriaLabelledby = computed(() => {
      return isLabeledByFormItem.value ? formItem == null ? void 0 : formItem.labelId : void 0;
    });
    const btnKls = computed(() => {
      return [
        ns.b("picker"),
        ns.is("disabled", colorDisabled.value),
        ns.is("custom", props.isCustom),
        ns.is("effect", props.effect === "dark"),
        ns.bm("picker", colorSize.value)
      ];
    });
    function displayedRgb(color2, showAlpha) {
      if (!(color2 instanceof Color)) {
        throw new TypeError("color should be instance of _color Class");
      }
      const { r, g, b } = color2.toRgb();
      return showAlpha ? `rgba(${r}, ${g}, ${b}, ${color2.get("alpha") / 100})` : `rgb(${r}, ${g}, ${b})`;
    }
    function setShowPicker(value) {
      showPicker.value = value;
    }
    const debounceSetShowPicker = debounce(setShowPicker, 100);
    function show() {
      setTimeout(() => {
        if (colorDisabled.value)
          return;
        setShowPicker(true);
      }, 100);
    }
    function hide() {
      debounceSetShowPicker(false);
      resetColor();
    }
    function resetColor() {
      nextTick(() => {
        if (props.modelValue) {
          color.fromString(props.modelValue);
        } else {
          color.value = "";
          nextTick(() => {
            showPanelColor.value = false;
          });
        }
      });
    }
    function handleTrigger() {
      if (colorDisabled.value)
        return;
      debounceSetShowPicker(!showPicker.value);
    }
    function handleConfirm() {
      color.fromString(customInput.value);
    }
    function confirmValue() {
      const value = color.value;
      emit(UPDATE_MODEL_EVENT, value);
      showPicker.value && emit("change", value);
      if (props.validateEvent) {
        formItem == null ? void 0 : formItem.validate("change").catch((err) => debugWarn(err));
      }
      nextTick(() => {
        const newColor = new Color({
          enableAlpha: props.showAlpha,
          format: props.colorFormat || "",
          value: props.modelValue
        });
        if (!color.compare(newColor)) {
          resetColor();
        }
      });
    }
    function clear() {
      debounceSetShowPicker(false);
      emit(UPDATE_MODEL_EVENT, null);
      emit("change", null);
      if (props.modelValue !== null && props.validateEvent) {
        formItem == null ? void 0 : formItem.validate("change").catch((err) => debugWarn(err));
      }
      resetColor();
    }
    onMounted(() => {
      if (props.modelValue) {
        customInput.value = currentColor.value;
      }
    });
    watch(() => props.modelValue, (newVal) => {
      if (!newVal) {
        showPanelColor.value = false;
      } else if (newVal && newVal !== color.value) {
        shouldActiveChange = false;
        color.fromString(newVal);
      }
    });
    watch(sRGBHex, (newValue) => {
      color.fromString(newValue);
      customInput.value = color.value;
    });
    watch(() => customInput.value, (newValue, oldValue) => {
      if (newValue !== oldValue) {
        confirmValue();
      }
    });
    watch(() => currentColor.value, (val) => {
      customInput.value = val;
      shouldActiveChange && emit("activeChange", val);
      shouldActiveChange = true;
    });
    watch(() => color.value, () => {
      if (!props.modelValue && !showPanelColor.value) {
        showPanelColor.value = true;
      }
    });
    watch(() => showPicker.value, () => {
      nextTick(() => {
        var _a2, _b2, _c;
        (_a2 = hue.value) == null ? void 0 : _a2.update();
        (_b2 = sv.value) == null ? void 0 : _b2.update();
        (_c = alpha.value) == null ? void 0 : _c.update();
      });
    });
    provide(colorPickerContextKey, {
      currentColor
    });
    expose({
      color,
      show,
      hide
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(ElTooltip), {
        ref_key: "popper",
        ref: popper,
        visible: showPicker.value,
        "show-arrow": false,
        "fallback-placements": ["bottom", "top", "right", "left"],
        offset: 0,
        "gpu-acceleration": false,
        "popper-class": [unref(ns).be("picker", "panel"), unref(ns).b("dropdown"), _ctx.popperClass],
        "stop-popper-mouse-event": false,
        effect: _ctx.effect,
        trigger: "click",
        transition: `${unref(ns).namespace.value}-zoom-in-top`,
        persistent: ""
      }, {
        content: withCtx(() => [
          withDirectives((openBlock(), createElementBlock("div", null, [
            createElementVNode("div", {
              class: normalizeClass(unref(ns).be("dropdown", "main-wrapper"))
            }, [
              createVNode(HueSlider, {
                ref_key: "hue",
                ref: hue,
                class: "hue-slider",
                color: unref(color),
                vertical: ""
              }, null, 8, ["color"]),
              createVNode(SvPanel, {
                ref_key: "sv",
                ref: sv,
                color: unref(color)
              }, null, 8, ["color"])
            ], 2),
            _ctx.showAlpha ? (openBlock(), createBlock(AlphaSlider, {
              key: 0,
              ref_key: "alpha",
              ref: alpha,
              color: unref(color)
            }, null, 8, ["color"])) : createCommentVNode("v-if", true),
            _ctx.predefine ? (openBlock(), createBlock(Predefine, {
              key: 1,
              ref: "predefine",
              color: unref(color),
              colors: _ctx.predefine
            }, null, 8, ["color", "colors"])) : createCommentVNode("v-if", true),
            createElementVNode("div", {
              onClick: _cache[4] || (_cache[4] = withModifiers(() => {
              }, ["stop"])),
              class: normalizeClass(unref(ns).be("dropdown", "btns"))
            }, [
              createElementVNode("span", {
                class: normalizeClass(unref(ns).be("dropdown", "value"))
              }, [
                createVNode(unref(ElInput), {
                  modelValue: customInput.value,
                  "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => customInput.value = $event),
                  onKeydown: _cache[1] || (_cache[1] = withModifiers(() => {
                  }, ["stop"])),
                  onKeyup: [
                    _cache[2] || (_cache[2] = withModifiers(() => {
                    }, ["stop"])),
                    withKeys(handleConfirm, ["enter"])
                  ],
                  "validate-event": false,
                  size: "small",
                  onBlur: customInputChange
                }, null, 8, ["modelValue", "onKeyup"])
              ], 2),
              createVNode(unref(ElIcon), {
                onClick: withModifiers(getEyeDropper, ["stop"])
              }, {
                default: withCtx(() => [
                  createVNode(unref(EditPen))
                ]),
                _: 1
              }, 8, ["onClick"]),
              createVNode(unref(ElRadioGroup), {
                onChange: modeChange,
                modelValue: colorMode.value,
                "onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => colorMode.value = $event),
                size: "small"
              }, {
                default: withCtx(() => [
                  createVNode(unref(ElRadioButton), { label: "HEX" }),
                  createVNode(unref(ElRadioButton), { label: "RGB" })
                ]),
                _: 1
              }, 8, ["modelValue"]),
              createCommentVNode(` <el-button
            :class="ns.be('dropdown', 'link-btn')"
            text
            size="small"
            @click="clear"
          >
            {{ t('el.colorpicker.clear') }}
          </el-button>
          <el-button
            plain
            size="small"
            :class="ns.be('dropdown', 'btn')"
            @click="confirmValue"
          >
            {{ t('el.colorpicker.confirm') }}
          </el-button> `)
            ], 2)
          ])), [
            [unref(ClickOutside), hide]
          ])
        ]),
        default: withCtx(() => [
          createElementVNode("div", {
            id: unref(buttonId),
            class: normalizeClass(unref(btnKls)),
            role: "button",
            "aria-label": unref(buttonAriaLabel),
            "aria-labelledby": unref(buttonAriaLabelledby),
            "aria-description": unref(t)("el.colorpicker.description", { color: _ctx.modelValue || "" }),
            tabindex: _ctx.tabindex,
            onKeydown: withKeys(handleTrigger, ["enter"])
          }, [
            unref(colorDisabled) ? (openBlock(), createElementBlock("div", {
              key: 0,
              class: normalizeClass(unref(ns).be("picker", "mask"))
            }, null, 2)) : createCommentVNode("v-if", true),
            createElementVNode("div", {
              style: normalizeStyle(_ctx.isCustom ? { width: unref(computdTriggerWidth) ? unref(computdTriggerWidth) + "px" : "auto" } : {}),
              class: normalizeClass(unref(ns).be("picker", "trigger")),
              onClick: handleTrigger
            }, [
              createElementVNode("span", {
                class: normalizeClass([unref(ns).be("picker", "color"), unref(ns).is("alpha", _ctx.showAlpha)])
              }, [
                createElementVNode("span", {
                  class: normalizeClass(unref(ns).be("picker", "color-inner")),
                  style: normalizeStyle({
                    backgroundColor: unref(displayedColor)
                  })
                }, [
                  withDirectives(createVNode(unref(ElIcon), {
                    style: normalizeStyle(_ctx.isCustom ? { marginLeft: unref(computdTriggerWidth) ? unref(computdTriggeIconWidth) + "px" : "auto" } : {}),
                    class: normalizeClass([unref(ns).be("picker", "icon"), unref(ns).is("icon-arrow-down")])
                  }, {
                    default: withCtx(() => [
                      createVNode(unref(ArrowDown))
                    ]),
                    _: 1
                  }, 8, ["style", "class"]), [
                    [vShow, _ctx.modelValue || showPanelColor.value]
                  ]),
                  !_ctx.modelValue && !showPanelColor.value ? (openBlock(), createBlock(unref(ElIcon), {
                    key: 0,
                    class: normalizeClass([unref(ns).be("picker", "empty"), unref(ns).is("icon-close")])
                  }, {
                    default: withCtx(() => [
                      createVNode(unref(Close))
                    ]),
                    _: 1
                  }, 8, ["class"])) : createCommentVNode("v-if", true)
                ], 6)
              ], 2)
            ], 6)
          ], 42, _hoisted_1)
        ]),
        _: 1
      }, 8, ["visible", "popper-class", "effect", "transition"]);
    };
  }
});
var ColorPicker = /* @__PURE__ */ _export_sfc(_sfc_main, [["__file", "/Users/st/Desktop/vue/nxx-ui/packages/components/color-picker/src/color-picker.vue"]]);

export { ColorPicker as default };
//# sourceMappingURL=color-picker2.mjs.map
