import { n as l, C as V } from "../chunks/lib-cortex-element.CVMmyPMC.js";
import { c as S } from "../chunks/component.styles.CRO4Odto.js";
import { c as F } from "../chunks/custom-element.L4WJXn1j.js";
import { d as C } from "../chunks/debounce.DaHuiSGU.js";
import { d as z } from "../chunks/default-value.COZopaet.js";
import { d as y } from "../chunks/drag.DXEXVXPv.js";
import { F as D } from "../chunks/form.Ch1cwYzO.js";
import { L as I } from "../chunks/i18n.BABe9hN4.js";
import { c as u } from "../chunks/math.DqTA6ya4.js";
import { w as k } from "../chunks/watch.BCJD77bD.js";
import { i as E, x as h } from "../chunks/lit-element.jLBm65_O.js";
import { r as g } from "../chunks/state.CSDxrqLd.js";
import { t as H } from "../chunks/event-options.CYHYGOd8.js";
import { e as _ } from "../chunks/query.BBf1UFkC.js";
import { e as b } from "../chunks/class-map.BiVq-cVR.js";
import { o as x } from "../chunks/if-defined.BRoBj_Rp.js";
import { o as f } from "../chunks/style-map.llVFPd__.js";
import { n as d } from "../chunks/when.Dr1es41R.js";
import { C as M } from "../chunks/button.CAa1kvwe.js";
import O from "./button-group.js";
import A from "./dropdown.js";
import B from "./icon.js";
import P from "./input.js";
import L from "./spinner.js";
import N from "./visually-hidden.js";
import { T as w } from "../chunks/index.C1chwzNp.js";
var m = /* @__PURE__ */ ((t) => (t.Hex = "hex", t.Rgb = "rgb", t.Hsl = "hsl", t.Hsv = "hsv", t))(m || {});
const T = E`:host{--grid-width:280px;--grid-height:200px;--grid-handle-size:16px;--slider-height:15px;--slider-handle-size:17px;--swatch-size:25px;--format-button-width:52px;--eye-dropper-button-width:52px;--control-border-color:var(--cx-color-neutral-300);--control-button-color:var(--cx-color-neutral-0);--control-caret-color:var(--cx-color-neutral-800);display:inline-block}.color-picker{width:var(--grid-width);font-family:var(--cx-font-sans);font-size:var(--cx-font-size-medium);font-weight:var(--cx-font-weight-regular);color:var(--color);background-color:var(--cx-panel-background-color);border-radius:var(--cx-border-radius-small);-webkit-user-select:none;user-select:none}.color-picker--inline{border:var(--inline-border,solid var(--cx-panel-border-width) var(--cx-panel-border-color))}.color-picker--inline:focus-visible{outline:var(--cx-focus-ring);outline-offset:var(--cx-focus-ring-offset)}.color-picker__grid{height:var(--grid-height);border-top-left-radius:var(--cx-border-radius-small);border-top-right-radius:var(--cx-border-radius-small);cursor:crosshair;forced-color-adjust:none;background-image:linear-gradient(#0000 0%,#000 100%),linear-gradient(90deg,#fff 0%,#fff0 100%);position:relative}.color-picker__grid-handle{width:var(--grid-handle-size);height:var(--grid-handle-size);margin-top:calc(var(--grid-handle-size) / -2);margin-left:calc(var(--grid-handle-size) / -2);transition:var(--cx-transition-fast) scale;border:2px solid #fff;border-radius:50%;position:absolute;box-shadow:0 0 0 1px #00000040}.color-picker__grid-handle--dragging{cursor:none;scale:1.5}.color-picker__grid-handle:focus-visible{outline:var(--cx-focus-ring)}.color-picker__controls{padding:var(--cx-spacing-small);align-items:center;gap:var(--cx-spacing-small);display:flex}.color-picker__sliders{flex:auto}.color-picker__slider{height:var(--slider-height);border-radius:var(--cx-border-radius-pill);forced-color-adjust:none;position:relative;box-shadow:inset 0 0 0 1px #0003}.color-picker__slider:not(:last-of-type){margin-bottom:var(--cx-spacing-small)}.color-picker__slider-handle{top:calc(50% - var(--slider-handle-size) / 2);width:var(--slider-handle-size);height:var(--slider-handle-size);margin-left:calc(var(--slider-handle-size) / -2);background-color:#fff;border-radius:50%;position:absolute;box-shadow:0 0 0 1px #00000040}.color-picker__slider-handle:focus-visible{outline:var(--cx-focus-ring)}.color-picker__hue{background-image:linear-gradient(90deg,red 0%,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red 100%)}.color-picker__alpha .color-picker__alpha-gradient{border-radius:inherit;width:100%;height:100%;position:absolute;top:0;left:0}.color-picker__preview{border-radius:var(--cx-border-radius-circle);cursor:pointer;forced-color-adjust:none;width:2rem;height:2rem;width:var(--cx-input-height-medium);height:var(--cx-input-height-medium);background:0 0;border:none;flex:none;justify-content:center;align-items:center;display:inline-flex;position:relative}.color-picker__preview--button,.color-picker__preview--button::part(base){border-radius:var(--cx-border-radius-small)}.color-picker__preview:focus-visible{outline:var(--cx-focus-ring);outline-offset:var(--cx-focus-ring-offset)}.color-picker__preview-color{border:1px solid #00000020;width:100%;height:100%;position:absolute;top:0;left:0}.color-picker__preview-color--copied{animation:.75s pulse}.color-picker__preview.color-picker__preview--button{outline:solid 1px var(--control-border-color)}.color-picker__preview--small.color-picker__preview--button{width:var(--cx-toggle-size-small);height:var(--cx-toggle-size-small)}.color-picker__preview--medium.color-picker__preview--button{width:var(--cx-toggle-size-medium);height:var(--cx-toggle-size-medium)}.color-picker__preview--large.color-picker__preview--button{width:var(--cx-toggle-size-large);height:var(--cx-toggle-size-large)}.color-picker__preview:before{content:"";border-radius:inherit;background-color:var(--preview-color,currentColor);width:100%;height:100%;position:absolute;top:0;left:0}.color-picker__preview--empty:before{background-color:#0000}.color-picker__preview__transparent-bg{background-image:linear-gradient(45deg, var(--cx-color-neutral-300) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--cx-color-neutral-300) 75%), linear-gradient(45deg, transparent 75%, var(--cx-color-neutral-300) 75%), linear-gradient(45deg, var(--cx-color-neutral-300) 25%, transparent 25%);background-position:0 0,0 0,-5px -5px,5px 5px;background-size:10px 10px}@keyframes pulse{0%{box-shadow:0 0 0 0 var(--cx-color-primary-500)}70%{box-shadow:0 0 0 .5rem #0000}to{box-shadow:0 0 #0000}}.color-picker__preview__container{align-items:center;gap:var(--cx-spacing-2x-small);display:flex}.color-picker__user-input__container{padding:0 var(--cx-spacing-small) var(--cx-spacing-small) var(--cx-spacing-small);display:flex}.color-picker__input_color{flex:auto;min-width:0}.color-picker__input_opacity{margin-left:var(--cx-spacing-2x-small);width:54px}.color-picker__input_opacity::part(input){padding-left:var(--cx-spacing-x-small);padding-right:var(--cx-spacing-x-small)}.color-picker__user-input__container cx-button-group{margin-left:var(--cx-spacing-2x-small)}.color-picker__user-input__container cx-button{font-size:var(--cx-font-size-medium)}.color-picker__user-input__container cx-button[part=format-button]{min-width:var(--format-button-width);max-width:var(--format-button-width)}.color-picker__user-input__container cx-button[part=eye-dropper-button]{min-width:var(--eye-dropper-button-width);max-width:var(--eye-dropper-button-width)}.color-picker__swatches{grid-gap:.5rem;border-top:solid 1px var(--cx-color-neutral-200);padding:var(--cx-spacing-small);forced-color-adjust:none;grid-template-columns:repeat(8,1fr);justify-items:center;display:grid}.color-picker__customSwatches{grid-gap:.5rem;padding:0 var(--cx-spacing-small) var(--cx-spacing-small) var(--cx-spacing-small);forced-color-adjust:none;grid-template-columns:repeat(8,1fr);justify-items:center;display:grid}.color-picker__customSwatches-label{--cx-button-text-transform:none;padding:var(--cx-spacing-small);justify-content:space-between;align-items:center;width:100%;display:inline-flex}.color-picker__spinner{text-align:center;margin:var(--cx-spacing-small) 0}.color-picker__swatch{width:var(--swatch-size);height:var(--swatch-size);border-radius:var(--cx-border-radius-small);position:relative}.color-picker__swatch .color-picker__swatch-color{border-radius:inherit;cursor:pointer;border:1px solid #00000020;width:100%;height:100%;position:absolute;top:0;left:0}.color-picker__swatch:focus-visible{outline:var(--cx-focus-ring);outline-offset:var(--cx-focus-ring-offset)}.color-picker--disabled{opacity:.5;cursor:default}.color-picker--disabled .color-picker__grid,.color-picker--disabled .color-picker__grid-handle,.color-picker--disabled .color-picker__slider,.color-picker--disabled .color-picker__slider-handle,.color-picker--disabled .color-picker__preview,.color-picker--disabled .color-picker__swatch,.color-picker--disabled .color-picker__swatch-color{pointer-events:none}.color-dropdown::part(panel){background-color:var(--cx-panel-background-color);border:solid var(--cx-panel-border-width) var(--cx-panel-border-color);border-radius:var(--cx-border-radius-small);max-height:none;overflow:visible}.color-dropdown__trigger::part(base){background-color:var(--control-button-color);border-color:var(--control-border-color);border-radius:var(--cx-border-radius-medium);padding-inline-start:var(--cx-spacing-2x-small);padding-inline-end:var(--cx-spacing-2x-small)}.color-dropdown__trigger::part(label){padding-inline-start:var(--cx-spacing-2x-small);padding-inline-end:var(--cx-spacing-2x-small)}.color-dropdown__trigger{cursor:pointer;forced-color-adjust:none;background-color:#0000;border:none;display:inline-block;position:relative}.color-dropdown__trigger:focus-visible{outline:none}.color-dropdown__trigger.color-dropdown__trigger--disabled{opacity:.5;cursor:default}.color-dropdown__trigger-icon{color:var(--control-caret-color);font-size:var(--cx-font-size-large);justify-content:flex-end;align-items:center;width:100%;height:100%;display:flex}cx-tooltip{display:inline-block}`;
var K = Object.defineProperty, j = Object.getOwnPropertyDescriptor, o = (t, e, i, s) => {
  for (var a = s > 1 ? void 0 : s ? j(e, i) : e, c = t.length - 1, p; c >= 0; c--)
    (p = t[c]) && (a = (s ? p(e, i, a) : p(a)) || a);
  return s && a && K(e, i, a), a;
};
const $ = "EyeDropper" in window;
let r = class extends V {
  constructor() {
    super(), this.formControlController = new D(this), this.isSafeValue = !1, this.localize = new I(this), this.hasFocus = !1, this.isDraggingGridHandle = !1, this.isEmpty = !1, this.inputColorValue = "", this.inputOpacityValue = "", this.hue = 0, this.saturation = 100, this.brightness = 100, this.alpha = 100, this.value = "", this.defaultValue = "", this.label = "", this.variant = "default", this.format = m.Hex, this.formats = [
      m.Hex,
      m.Rgb,
      m.Hsl
    ], this.emitFormat = void 0, this.inline = !1, this.size = "medium", this.noFormatToggle = !1, this.name = "", this.disabled = !1, this.hoist = !1, this.opacity = !1, this.uppercase = !1, this.clearable = !1, this.tooltip = "", this.swatches = "", this.customSwatches = "", this.loading = !1, this.creatable = !1, this.form = void 0, this.required = !1, this.emitValue = "", this.handleFocusIn = this.handleFocusIn.bind(this), this.handleFocusOut = this.handleFocusOut.bind(this), this.addEventListener("focusin", this.handleFocusIn), this.addEventListener("focusout", this.handleFocusOut);
  }
  /** Gets the validity state object */
  get validity() {
    return this.input.validity;
  }
  /** Gets the validation message */
  get validationMessage() {
    return this.input.validationMessage;
  }
  runFirstUpdated() {
    this.input.updateComplete.then(() => {
      this.formControlController.updateValidity();
    }), this.value && this.emitFormat !== this.format && this.syncValues();
  }
  handleCopy() {
    this.input.select(), document.execCommand("copy"), this.previewButton.focus(), this.previewButton.classList.add("color-picker__preview-color--copied"), this.previewButton.addEventListener("animationend", () => {
      this.previewButton.classList.remove(
        "color-picker__preview-color--copied"
      );
    });
  }
  handleFocusIn() {
    this.hasFocus = !0, this.emit("cx-focus");
  }
  handleFocusOut() {
    this.hasFocus = !1, this.emit("cx-blur");
  }
  handleFormatToggle() {
    const t = [
      m.Hex,
      m.Rgb,
      m.Hsl,
      m.Hsv
    ].filter((i) => this.formats.includes(i)), e = (t.indexOf(this.format) + 1) % t.length;
    this.format = t[e], this.setColor(this.value), this.emit("cx-change"), this.emit("cx-input");
  }
  handleAlphaDrag(t) {
    const e = this.shadowRoot.querySelector(
      ".color-picker__slider.color-picker__alpha"
    ), i = e.querySelector(
      ".color-picker__slider-handle"
    ), { width: s } = e.getBoundingClientRect();
    let a = this.value, c = this.value;
    i.focus(), t.preventDefault(), y(e, {
      initialEvent: t,
      onMove: (p) => {
        this.alpha = u(p / s * 100, 0, 100), this.syncValues(), this.value !== c && (c = this.value, this.emit("cx-input"));
      },
      onStop: () => {
        this.value !== a && (a = this.value, this.emit("cx-change"));
      }
    });
  }
  handleHueDrag(t) {
    const e = this.shadowRoot.querySelector(
      ".color-picker__slider.color-picker__hue"
    ), i = e.querySelector(
      ".color-picker__slider-handle"
    ), { width: s } = e.getBoundingClientRect();
    let a = this.value, c = this.value;
    i.focus(), t.preventDefault(), y(e, {
      initialEvent: t,
      onMove: (p) => {
        this.hue = u(p / s * 360, 0, 360), this.syncValues(), this.value !== c && (c = this.value, this.emit("cx-input"));
      },
      onStop: () => {
        this.value !== a && (a = this.value, this.emit("cx-change"));
      }
    });
  }
  handleGridDrag(t) {
    const e = this.shadowRoot.querySelector(
      ".color-picker__grid"
    ), i = e.querySelector(
      ".color-picker__grid-handle"
    ), { height: s, width: a } = e.getBoundingClientRect();
    let c = this.value, p = this.value;
    i.focus(), t.preventDefault(), this.isDraggingGridHandle = !0, y(e, {
      initialEvent: t,
      onMove: (v, n) => {
        this.saturation = u(v / a * 100, 0, 100), this.brightness = u(100 - n / s * 100, 0, 100), this.syncValues(), this.value !== p && (p = this.value, this.emit("cx-input"));
      },
      onStop: () => {
        this.isDraggingGridHandle = !1, this.value !== c && (c = this.value, this.emit("cx-change"));
      }
    });
  }
  handleAlphaKeyDown(t) {
    const e = t.shiftKey ? 10 : 1, i = this.value;
    t.key === "ArrowLeft" && (t.preventDefault(), this.alpha = u(this.alpha - e, 0, 100), this.syncValues()), t.key === "ArrowRight" && (t.preventDefault(), this.alpha = u(this.alpha + e, 0, 100), this.syncValues()), t.key === "Home" && (t.preventDefault(), this.alpha = 0, this.syncValues()), t.key === "End" && (t.preventDefault(), this.alpha = 100, this.syncValues()), this.value !== i && (this.emit("cx-change"), this.emit("cx-input"));
  }
  handleHueKeyDown(t) {
    const e = t.shiftKey ? 10 : 1, i = this.value;
    t.key === "ArrowLeft" && (t.preventDefault(), this.hue = u(this.hue - e, 0, 360), this.syncValues()), t.key === "ArrowRight" && (t.preventDefault(), this.hue = u(this.hue + e, 0, 360), this.syncValues()), t.key === "Home" && (t.preventDefault(), this.hue = 0, this.syncValues()), t.key === "End" && (t.preventDefault(), this.hue = 360, this.syncValues()), this.value !== i && (this.emit("cx-change"), this.emit("cx-input"));
  }
  handleGridKeyDown(t) {
    const e = t.shiftKey ? 10 : 1, i = this.value;
    t.key === "ArrowLeft" && (t.preventDefault(), this.saturation = u(this.saturation - e, 0, 100), this.syncValues()), t.key === "ArrowRight" && (t.preventDefault(), this.saturation = u(this.saturation + e, 0, 100), this.syncValues()), t.key === "ArrowUp" && (t.preventDefault(), this.brightness = u(this.brightness + e, 0, 100), this.syncValues()), t.key === "ArrowDown" && (t.preventDefault(), this.brightness = u(this.brightness - e, 0, 100), this.syncValues()), this.value !== i && (this.emit("cx-change"), this.emit("cx-input"));
  }
  handleInputChange(t) {
    const e = t.target, i = this.value, s = this.getFormatFromValue(e.value);
    s && s !== this.format && (this.format = s), t.stopPropagation(), this.input.value ? (this.setColor(e.value), this.syncValues(), this.input.value = this.inputColorValue) : this.value = "", this.value !== i && (this.emit("cx-change"), this.emit("cx-input"));
  }
  handleInputInput(t) {
    this.formControlController.updateValidity(), t.stopPropagation(), this.debouncedSetColor();
  }
  debouncedSetColor() {
    const t = this.getFormatFromValue(this.input.value);
    t && t !== this.format && (this.format = t), this.setColor(this.input.value, !1), this.inputOpacityValue = Math.round(this.alpha).toString();
  }
  handleInputKeyDown(t) {
    if (t.key === "Enter") {
      const e = this.value;
      if (this.input.value) {
        this.setColor(this.input.value);
        const i = this.getFormatFromValue(this.input.value);
        i && i !== this.format && (this.format = i), this.syncValues(), this.input.value = this.inputColorValue, this.value !== e && (this.emit("cx-change"), this.emit("cx-input")), setTimeout(() => this.input.select());
      } else
        this.hue = 0;
    }
  }
  handleInputInvalid(t) {
    this.formControlController.setValidity(!1), this.formControlController.emitInvalidEvent(t);
  }
  handleOpacityInputChange(t) {
    if (t.stopPropagation(), this.opacityInput.value) {
      const e = parseInt(this.opacityInput.value);
      isNaN(e) || (this.alpha = u(e, 0, 100), this.syncValues());
    }
    this.emit("cx-change"), this.emit("cx-input");
  }
  handleOpacityInputInput(t) {
    this.formControlController.updateValidity(), t.stopPropagation(), this.setOpacity();
  }
  setOpacity() {
    if (this.opacityInput.value) {
      const t = parseInt(this.opacityInput.value);
      isNaN(t) || (this.alpha = u(t, 0, 100));
    }
  }
  handleOpacityInputKeyDown(t) {
    if (t.key === "Enter" && this.opacityInput.value) {
      const e = parseInt(this.opacityInput.value);
      isNaN(e) || (this.alpha = u(e, 0, 100), this.syncValues(), this.emit("cx-change"), this.emit("cx-input"), setTimeout(() => this.opacityInput.select()));
    }
  }
  handleTouchMove(t) {
    t.preventDefault();
  }
  handleClear() {
    this.value = "", this.emitValue = "", this.setColor(""), this.emit("cx-change"), this.emit("cx-input"), this.emit("cx-clear");
  }
  parseColor(t) {
    if (!t)
      return null;
    const e = new w(t);
    if (!e.isValid)
      return null;
    const i = e.toHsl(), s = {
      a: i.a,
      h: i.h,
      l: i.l * 100,
      s: i.s * 100
    }, a = e.toRgb(), c = e.toHexString(), p = e.toHex8String(), v = e.toHsv(), n = {
      a: v.a,
      h: v.h,
      s: v.s * 100,
      v: v.v * 100
    };
    return {
      hex: this.setLetterCase(c),
      hexa: this.setLetterCase(p),
      hsl: {
        h: s.h,
        l: s.l,
        s: s.s,
        string: this.setLetterCase(
          `hsl(${Math.round(s.h)}, ${Math.round(s.s)}%, ${Math.round(
            s.l
          )}%)`
        )
      },
      hsla: {
        a: s.a,
        h: s.h,
        l: s.l,
        s: s.s,
        string: this.setLetterCase(
          `hsla(${Math.round(s.h)}, ${Math.round(s.s)}%, ${Math.round(
            s.l
          )}%, ${s.a.toFixed(2).toString()})`
        )
      },
      hsv: {
        h: n.h,
        s: n.s,
        string: this.setLetterCase(
          `hsv(${Math.round(n.h)}, ${Math.round(n.s)}%, ${Math.round(
            n.v
          )}%)`
        ),
        v: n.v
      },
      hsva: {
        a: n.a,
        h: n.h,
        s: n.s,
        string: this.setLetterCase(
          `hsva(${Math.round(n.h)}, ${Math.round(n.s)}%, ${Math.round(
            n.v
          )}%, ${n.a.toFixed(2).toString()})`
        ),
        v: n.v
      },
      rgb: {
        b: a.b,
        g: a.g,
        r: a.r,
        string: this.setLetterCase(
          `rgb(${Math.round(a.r)}, ${Math.round(a.g)}, ${Math.round(
            a.b
          )})`
        )
      },
      rgba: {
        a: a.a,
        b: a.b,
        g: a.g,
        r: a.r,
        string: this.setLetterCase(
          `rgba(${Math.round(a.r)}, ${Math.round(a.g)}, ${Math.round(
            a.b
          )}, ${a.a.toFixed(2).toString()})`
        )
      }
    };
  }
  setColor(t, e = !0) {
    const i = this.parseColor(t);
    return i === null ? !1 : (this.hue = i.hsva.h, this.saturation = i.hsva.s, this.brightness = i.hsva.v, this.alpha = this.opacity ? i.hsva.a * 100 : 100, e && this.syncValues(), !0);
  }
  setLetterCase(t) {
    return typeof t != "string" ? "" : this.uppercase ? t.toUpperCase() : t.toLowerCase();
  }
  async syncValues() {
    const t = this.parseColor(
      `hsva(${this.hue}, ${this.saturation}%, ${this.brightness}%, ${this.alpha / 100})`
    );
    if (t !== null) {
      if (this.emitFormat) {
        const e = `${this.emitFormat}${this.opacity ? "a" : ""}`, i = t[e];
        this.emitFormat === "hex" ? this.emitValue = i : this.emitValue = typeof i == "string" ? i : i.string;
      }
      this.isSafeValue = !0, this.opacity ? (this.format === "hsl" ? this.inputColorValue = t.hsl.string : this.format === "rgb" ? this.inputColorValue = t.rgb.string : this.format === "hsv" ? this.inputColorValue = t.hsv.string : this.inputColorValue = t.hex, this.inputOpacityValue = Math.round(this.alpha).toString(), this.format === "hsl" ? this.value = t.hsla.string : this.format === "rgb" ? this.value = t.rgba.string : this.format === "hsv" ? this.value = t.hsva.string : this.value = t.hexa) : (this.format === "hsl" ? (this.inputColorValue = t.hsl.string, this.value = t.hsl.string) : this.format === "rgb" ? (this.inputColorValue = t.rgb.string, this.value = t.rgb.string) : this.format === "hsv" ? (this.inputColorValue = t.hsv.string, this.value = t.hsv.string) : (this.inputColorValue = t.hex, this.value = t.hex), this.inputOpacityValue = ""), await this.updateComplete, this.isSafeValue = !1;
    }
  }
  handleAfterHide() {
    this.previewButton.classList.remove("color-picker__preview-color--copied");
  }
  handleEyeDropper() {
    if (!$)
      return;
    new EyeDropper().open().then((e) => {
      const i = this.value;
      this.setColor(e.sRGBHex), this.value !== i && (this.emit("cx-change"), this.emit("cx-input"));
    }).catch(() => {
    });
  }
  handleSwatchAdd() {
    this.emit("cx-swatch-add", {
      cancelable: !0,
      detail: {
        color: this.getHexString(
          this.hue,
          this.saturation,
          this.brightness,
          this.alpha
        )
      }
    }).defaultPrevented || (Array.isArray(this.customSwatches) ? this.customSwatches = [...this.customSwatches, this.value] : this.customSwatches = `${this.customSwatches};${this.value}`.trim());
  }
  selectSwatch(t) {
    const e = this.value;
    this.disabled || (this.setColor(t), this.value !== e && (this.emit("cx-change"), this.emit("cx-input")));
  }
  /** Generates a hex string from HSV values. Hue must be 0-360. All other arguments must be 0-100. */
  getHexString(t, e, i, s = 100) {
    const a = new w(
      `hsva(${t}, ${e}%, ${i}%, ${s / 100})`
    );
    return a.isValid ? a.toHex8String() : "";
  }
  /**
   * Extracts the color format from a value string.
   * @param value - The value string to extract the format from.
   * @returns The color format.
   */
  getFormatFromValue(t) {
    const e = new w(t);
    return !e.isValid || !this.formats || this.formats.length === 0 ? null : this.formats.includes(e.format) ? e.format : this.formats[0];
  }
  // Prevents nested components from leaking events
  stopNestedEventPropagation(t) {
    t.stopImmediatePropagation();
  }
  handleFormatChange() {
    this.syncValues();
  }
  handleOpacityChange() {
    this.alpha = 100;
  }
  handleValueChange(t, e) {
    this.isEmpty = !e;
    const i = this.getFormatFromValue(e);
    if (i && i !== this.format && (this.format = i), e || (this.hue = 0, this.saturation = 0, this.brightness = 100, this.alpha = 100), !this.isSafeValue) {
      const s = this.parseColor(e);
      s !== null ? (this.hue = s.hsva.h, this.saturation = s.hsva.s, this.brightness = s.hsva.v, this.alpha = s.hsva.a * 100, this.syncValues()) : (this.inputColorValue = t ?? "", this.inputOpacityValue = "");
    }
  }
  /** Sets focus on the color picker. */
  focus(t) {
    this.inline ? this.base.focus(t) : this.trigger.focus(t);
  }
  /** Removes focus from the color picker. */
  blur() {
    const t = this.inline ? this.base : this.trigger;
    this.hasFocus && (t.focus({ preventScroll: !0 }), t.blur()), this.dropdown?.open && this.dropdown.hide();
  }
  /** Returns the current value as a string in the specified format. */
  getFormattedValue(t = "hex") {
    const e = this.parseColor(
      `hsva(${this.hue}, ${this.saturation}%, ${this.brightness}%, ${this.alpha / 100})`
    );
    if (e === null)
      return "";
    switch (t) {
      case "hex":
        return e.hex;
      case "hexa":
        return e.hexa;
      case "rgb":
        return e.rgb.string;
      case "rgba":
        return e.rgba.string;
      case "hsl":
        return e.hsl.string;
      case "hsla":
        return e.hsla.string;
      case "hsv":
        return e.hsv.string;
      case "hsva":
        return e.hsva.string;
      default:
        return "";
    }
  }
  /** Checks for validity but does not show a validation message. Returns `true` when valid and `false` when invalid. */
  checkValidity() {
    return this.input.checkValidity();
  }
  /** Gets the associated form, if one exists. */
  getForm() {
    return this.formControlController.getForm();
  }
  /** Checks for validity and shows the browser's validation message if the control is invalid. */
  reportValidity() {
    return !this.inline && !this.validity.valid ? (this.dropdown.show(), this.addEventListener(
      "cx-after-show",
      () => this.input.reportValidity(),
      { once: !0 }
    ), this.disabled || this.formControlController.emitInvalidEvent(), !1) : this.input.reportValidity();
  }
  /** Sets a custom validation message. Pass an empty string to restore validity. */
  setCustomValidity(t) {
    this.input.setCustomValidity(t), this.formControlController.updateValidity();
  }
  renderSwatches(t) {
    return t.map((e) => {
      const i = this.parseColor(e);
      if (!i)
        return console.error(`Unable to parse swatch color: "${e}"`, this), "";
      const s = () => this.selectSwatch(e), a = (c) => !this.disabled && c.key === "Enter" && this.setColor(i.hexa);
      return h`<div part="swatch" class="color-picker__swatch color-picker__transparent-bg" tabindex=${x(this.disabled ? void 0 : "0")} role="button" aria-label=${e} @click=${s} @keydown=${a}><div class="color-picker__swatch-color" style=${f({ backgroundColor: i.hexa })}></div></div>`;
    });
  }
  render() {
    const t = this.saturation, e = 100 - this.brightness, i = this.swatches ? Array.isArray(this.swatches) ? this.swatches : this.swatches.split(";").filter((n) => n.trim() !== "") : [], s = this.customSwatches ? Array.isArray(this.customSwatches) ? this.customSwatches : this.customSwatches.split(";").filter((n) => n.trim() !== "") : [], a = this.inputOpacityValue.endsWith("%") ? this.inputOpacityValue : `${this.inputOpacityValue}%`, c = h`<div part="base" class=${b({
      "color-picker": !0,
      "color-picker--disabled": this.disabled,
      "color-picker--focused": this.hasFocus,
      "color-picker--inline": this.inline
    })} aria-disabled=${this.disabled ? "true" : "false"} aria-labelledby="label" tabindex=${this.inline ? "0" : "-1"}>${d(
      this.inline,
      () => h`<cx-visually-hidden id="label"><slot name="label">${this.label}</slot></cx-visually-hidden>`
    )}<div part="grid" class="color-picker__grid" style=${f({
      backgroundColor: this.getHexString(this.hue, 100, 100)
    })} @pointerdown=${this.handleGridDrag} @touchmove=${this.handleTouchMove}><span part="grid-handle" class=${b({
      "color-picker__grid-handle": !0,
      "color-picker__grid-handle--dragging": this.isDraggingGridHandle
    })} style=${f({
      backgroundColor: this.getHexString(
        this.hue,
        this.saturation,
        this.brightness,
        this.alpha
      ),
      left: `${t}%`,
      top: `${e}%`
    })} role="application" aria-label="HSV" tabindex=${x(this.disabled ? void 0 : "0")} @keydown=${this.handleGridKeyDown}></span></div><div class="color-picker__controls"><div class="color-picker__sliders"><div part="slider hue-slider" class="color-picker__hue color-picker__slider" @pointerdown=${this.handleHueDrag} @touchmove=${this.handleTouchMove}><span part="slider-handle hue-slider-handle" class="color-picker__slider-handle" style=${f({
      left: `${this.hue === 0 ? 0 : 100 / (360 / this.hue)}%`
    })} role="slider" aria-label="hue" aria-orientation="horizontal" aria-valuemin="0" aria-valuemax="360" aria-valuenow=${`${Math.round(this.hue)}`} tabindex=${x(this.disabled ? void 0 : "0")} @keydown=${this.handleHueKeyDown}></span></div>${d(
      this.opacity,
      () => h`<div part="slider opacity-slider" class="color-picker__alpha color-picker__slider color-picker__transparent-bg" @pointerdown=${this.handleAlphaDrag} @touchmove=${this.handleTouchMove}><div class="color-picker__alpha-gradient" style=${f({
        backgroundImage: `linear-gradient(
                        to right,
                        ${this.getHexString(
          this.hue,
          this.saturation,
          this.brightness,
          0
        )} 0%,
                        ${this.getHexString(
          this.hue,
          this.saturation,
          this.brightness,
          100
        )} 100%
                      )`
      })}></div><span part="slider-handle opacity-slider-handle" class="color-picker__slider-handle" style=${f({
        left: `${this.alpha}%`
      })} role="slider" aria-label="alpha" aria-orientation="horizontal" aria-valuemin="0" aria-valuemax="100" aria-valuenow=${Math.round(this.alpha)} tabindex=${x(this.disabled ? void 0 : "0")} @keydown=${this.handleAlphaKeyDown}></span></div>`
    )}</div><div class="color-picker__preview__container"><button type="button" part="preview" class=${b({
      "color-picker__preview": !0,
      "color-picker__preview--button": this.variant === "button",
      "color-picker__preview--empty": this.isEmpty,
      "color-picker__preview__transparent-bg": this.isEmpty
    })} aria-label=${this.localize.term("copy")} style=${f({
      "--preview-color": this.getHexString(
        this.hue,
        this.saturation,
        this.brightness,
        this.alpha
      )
    })} @click=${this.handleCopy}></button>${d(
      this.clearable,
      () => h`<cx-button variant="text" class="color-picker__clear-button" part="clear-button" size="small" exportparts="
                    base:clear-button__base,
                    prefix:clear-button__prefix,
                    label:clear-button__label,
                    suffix:clear-button__suffix,
                    caret:clear-button__caret
                  " @click=${this.handleClear} @cx-blur=${this.stopNestedEventPropagation} @cx-focus=${this.stopNestedEventPropagation}><cx-icon class="color-picker__clear-button__icon" name="close"></cx-icon></cx-button>`
    )}</div></div><div class="color-picker__user-input__container" aria-live="polite"><cx-input class="color-picker__input_color" part="input" type="text" name=${this.name} autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" value=${this.isEmpty ? "" : this.inputColorValue} ?required=${this.required} ?disabled=${this.disabled} aria-label=${this.localize.term("currentValue")} @keydown=${this.handleInputKeyDown} @cx-change=${this.handleInputChange} @cx-input=${this.handleInputInput} @cx-invalid=${this.handleInputInvalid} @cx-blur=${this.stopNestedEventPropagation} @cx-focus=${this.stopNestedEventPropagation}></cx-input>${d(
      this.opacity,
      () => h`<cx-input class="color-picker__input_opacity" part="opacity-input" type="text" name=${this.name} .maskBlocks=${{
        num: {
          mask: Number,
          max: 100,
          min: 0,
          scale: 0,
          thousandsSeparator: ""
        }
      }} mask="num%" no-spin-buttons value=${this.isEmpty ? "%" : a} ?required=${this.required} ?disabled=${this.disabled} aria-label=${this.localize.term("opacity")} @keydown=${this.handleOpacityInputKeyDown} @cx-change=${this.handleOpacityInputChange} @cx-input=${this.handleOpacityInputInput} @cx-invalid=${this.handleInputInvalid} @cx-blur=${this.stopNestedEventPropagation} @cx-focus=${this.stopNestedEventPropagation}></cx-input>`
    )}<cx-button-group>${d(
      !this.noFormatToggle,
      () => h`<cx-button part="format-button" aria-label=${this.localize.term("toggleColorFormat")} exportparts="
                    base:format-button__base,
                    prefix:format-button__prefix,
                    label:format-button__label,
                    suffix:format-button__suffix,
                    caret:format-button__caret
                  " @click=${this.handleFormatToggle} @cx-blur=${this.stopNestedEventPropagation} @cx-focus=${this.stopNestedEventPropagation}>${this.setLetterCase(this.format)}</cx-button>`
    )}
            ${d(
      $,
      () => h`<cx-button part="eye-dropper-button" exportparts="
                base:eye-dropper-button__base,
                prefix:eye-dropper-button__prefix,
                label:eye-dropper-button__label,
                suffix:eye-dropper-button__suffix,
                caret:eye-dropper-button__caret
              " @click=${this.handleEyeDropper} @cx-blur=${this.stopNestedEventPropagation} @cx-focus=${this.stopNestedEventPropagation}><cx-icon name="colorize" label=${this.localize.term("selectAColorFromTheScreen")}></cx-icon></cx-button>`
    )}</cx-button-group></div>${d(
      i.length > 0,
      () => h`<div part="swatches" class="color-picker__swatches">${this.renderSwatches(i)}</div>`
    )}
        ${d(
      s.length > 0 || this.creatable,
      () => h`<div class="color-picker__customSwatches-label">${this.localize.term("custom")}
              ${d(
        this.creatable,
        () => h`<cx-button part="swatch-add-button" size="small" @click=${this.handleSwatchAdd}>${this.localize.term("addCurrent")}</cx-button>`
      )}</div>`
    )}
        ${d(
      s.length > 0,
      () => h`<div part="custom-swatches" class="color-picker__customSwatches">${this.renderSwatches(s)}</div>`
    )}
        ${d(
      this.loading,
      () => h`<div part="loading-spinner" class="color-picker__spinner"><cx-spinner></cx-spinner></div>`
    )}</div>`, p = this.variant === "button" ? h`<cx-button part="trigger" class=${b({
      "color-dropdown__trigger": !0,
      "color-dropdown__trigger--focused": this.hasFocus
    })} outline aria-label=${this.label} ?disabled=${this.disabled} type="button" size=${this.size} @cx-blur=${this.stopNestedEventPropagation}><div slot="prefix" part="preview" class=${b({
      "color-picker__preview": !0,
      "color-picker__preview--button": !0,
      "color-picker__preview--empty": this.isEmpty,
      "color-picker__preview--large": this.size === "large",
      "color-picker__preview--medium": this.size === "medium",
      "color-picker__preview--small": this.size === "small",
      "color-picker__preview__transparent-bg": !0
    })} style=${f({
      color: this.getHexString(
        this.hue,
        this.saturation,
        this.brightness,
        this.alpha
      )
    })}></div><slot slot="suffix" name="expand-icon" part="expand-icon" class="color-dropdown__trigger-icon"><cx-icon name="expand_more"></cx-icon></slot><cx-visually-hidden><slot name="label">${this.label}</slot></cx-visually-hidden></cx-button>` : h`<button part="trigger" class=${b({
      "color-picker__preview": !0,
      "color-picker__preview--empty": this.isEmpty,
      "color-picker__preview--large": this.size === "large",
      "color-picker__preview--medium": this.size === "medium",
      "color-picker__preview--small": this.size === "small",
      "color-picker__preview__transparent-bg": !0
    })} style=${f({
      color: this.getHexString(
        this.hue,
        this.saturation,
        this.brightness,
        this.alpha
      )
    })}><cx-visually-hidden><slot name="label">${this.label}</slot></cx-visually-hidden></button>`, v = d(
      this.tooltip,
      () => h`<cx-tooltip content=${this.tooltip}>${p}</cx-tooltip>`,
      () => p
    );
    return this.inline ? c : h`<cx-dropdown aria-disabled=${this.disabled ? "true" : "false"} class=${b({
      "color-dropdown": !0,
      "color-dropdown--opened": !!this.dropdown?.open
    })} .containing-element=${this} ?disabled=${this.disabled} ?hoist=${this.hoist} @cx-after-hide=${this.handleAfterHide}><slot name="trigger" slot="trigger">${v}</slot>${c}</cx-dropdown>`;
  }
};
r.styles = [S, T];
r.dependencies = {
  "cx-button": M,
  "cx-button-group": O,
  "cx-dropdown": A,
  "cx-icon": B,
  "cx-input": P,
  "cx-spinner": L,
  "cx-visually-hidden": N
};
o([
  _('[part~="base"]')
], r.prototype, "base", 2);
o([
  _('[part~="input"]')
], r.prototype, "input", 2);
o([
  _('[part~="opacity-input"]')
], r.prototype, "opacityInput", 2);
o([
  _(".color-dropdown")
], r.prototype, "dropdown", 2);
o([
  _('[part~="preview"]')
], r.prototype, "previewButton", 2);
o([
  _('[part~="trigger"]')
], r.prototype, "trigger", 2);
o([
  g()
], r.prototype, "hasFocus", 2);
o([
  g()
], r.prototype, "isDraggingGridHandle", 2);
o([
  g()
], r.prototype, "isEmpty", 2);
o([
  g()
], r.prototype, "inputColorValue", 2);
o([
  g()
], r.prototype, "inputOpacityValue", 2);
o([
  g()
], r.prototype, "hue", 2);
o([
  g()
], r.prototype, "saturation", 2);
o([
  g()
], r.prototype, "brightness", 2);
o([
  g()
], r.prototype, "alpha", 2);
o([
  l()
], r.prototype, "value", 2);
o([
  z()
], r.prototype, "defaultValue", 2);
o([
  l()
], r.prototype, "label", 2);
o([
  l({ reflect: !0, type: String })
], r.prototype, "variant", 2);
o([
  l()
], r.prototype, "format", 2);
o([
  l({
    attribute: "formats",
    converter: {
      fromAttribute: (t) => t?.split(" ") ?? [],
      toAttribute: (t) => t.join(" ")
    }
  })
], r.prototype, "formats", 2);
o([
  l({ attribute: "emit-format", reflect: !0, type: String })
], r.prototype, "emitFormat", 2);
o([
  l({ reflect: !0, type: Boolean })
], r.prototype, "inline", 2);
o([
  l({ reflect: !0 })
], r.prototype, "size", 2);
o([
  l({ attribute: "no-format-toggle", type: Boolean })
], r.prototype, "noFormatToggle", 2);
o([
  l()
], r.prototype, "name", 2);
o([
  l({ reflect: !0, type: Boolean })
], r.prototype, "disabled", 2);
o([
  l({ type: Boolean })
], r.prototype, "hoist", 2);
o([
  l({ type: Boolean })
], r.prototype, "opacity", 2);
o([
  l({ type: Boolean })
], r.prototype, "uppercase", 2);
o([
  l({ type: Boolean })
], r.prototype, "clearable", 2);
o([
  l({ type: String })
], r.prototype, "tooltip", 2);
o([
  l()
], r.prototype, "swatches", 2);
o([
  l({ attribute: "custom-swatches", reflect: !0 })
], r.prototype, "customSwatches", 2);
o([
  l({ reflect: !0, type: Boolean })
], r.prototype, "loading", 2);
o([
  l({ reflect: !0, type: Boolean })
], r.prototype, "creatable", 2);
o([
  l({ reflect: !1 })
], r.prototype, "form", 2);
o([
  l({ reflect: !0, type: Boolean })
], r.prototype, "required", 2);
o([
  g()
], r.prototype, "emitValue", 2);
o([
  C(300)
], r.prototype, "debouncedSetColor", 1);
o([
  C(300)
], r.prototype, "setOpacity", 1);
o([
  H({ passive: !1 })
], r.prototype, "handleTouchMove", 1);
o([
  k("format", { waitUntilFirstUpdate: !0 })
], r.prototype, "handleFormatChange", 1);
o([
  k("opacity", { waitUntilFirstUpdate: !0 })
], r.prototype, "handleOpacityChange", 1);
o([
  k("value")
], r.prototype, "handleValueChange", 1);
r = o([
  F("cx-color-picker")
], r);
export {
  r as default
};
