"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// packages/components/src/custom-gradient-picker/gradient-bar/control-points.tsx
var control_points_exports = {};
__export(control_points_exports, {
  default: () => control_points_default
});
module.exports = __toCommonJS(control_points_exports);
var import_clsx = __toESM(require("clsx"), 1);
var import_colord = require("colord");
var import_compose = require("@wordpress/compose");
var import_element = require("@wordpress/element");
var import_i18n = require("@wordpress/i18n");
var import_icons = require("@wordpress/icons");
var import_button = __toESM(require("../../button/index.cjs"), 1);
var import_h_stack = require("../../h-stack/index.cjs");
var import_color_picker = require("../../color-picker/index.cjs");
var import_visually_hidden = require("../../visually-hidden/index.cjs");
var import_color_palette = require("../../color-palette/index.cjs");
var import_utils = require("./utils.cjs");
var import_constants = require("./constants.cjs");
var import_dropdown_content_wrapper = __toESM(require("../../dropdown/dropdown-content-wrapper.cjs"), 1);
var import_jsx_runtime = require("react/jsx-runtime");
function ControlPointButton({
  isOpen,
  position,
  color,
  ...additionalProps
}) {
  const instanceId = (0, import_compose.useInstanceId)(ControlPointButton);
  const descriptionId = `components-custom-gradient-picker__control-point-button-description-${instanceId}`;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, {
    children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_button.default, {
      "aria-label": (0, import_i18n.sprintf)(
        // translators: 1: gradient position e.g: 70. 2: gradient color code e.g: rgb(52,121,151).
        (0, import_i18n.__)("Gradient control point at position %1$d%% with color code %2$s."),
        position,
        color
      ),
      "aria-describedby": descriptionId,
      "aria-haspopup": "true",
      "aria-expanded": isOpen,
      __next40pxDefaultSize: true,
      className: (0, import_clsx.default)("components-custom-gradient-picker__control-point-button", {
        "is-active": isOpen
      }),
      ...additionalProps
    }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_visually_hidden.VisuallyHidden, {
      id: descriptionId,
      children: (0, import_i18n.__)("Use your left or right arrow keys or drag and drop with the mouse to change the gradient position. Press the button to change the color or remove the control point.")
    })]
  });
}
function GradientColorPickerDropdown({
  isRenderedInSidebar,
  className,
  ...props
}) {
  const popoverProps = (0, import_element.useMemo)(() => ({
    placement: "bottom",
    offset: 8,
    // Disabling resize as it would otherwise cause the popover to show
    // scrollbars while dragging the color picker's handle close to the
    // popover edge.
    resize: false
  }), []);
  const mergedClassName = (0, import_clsx.default)("components-custom-gradient-picker__control-point-dropdown", className);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_color_palette.CustomColorPickerDropdown, {
    isRenderedInSidebar,
    popoverProps,
    className: mergedClassName,
    ...props
  });
}
function ControlPoints({
  disableRemove,
  disableAlpha,
  gradientPickerDomRef,
  ignoreMarkerPosition,
  value: controlPoints,
  onChange,
  onStartControlPointChange,
  onStopControlPointChange,
  __experimentalIsRenderedInSidebar
}) {
  const controlPointMoveStateRef = (0, import_element.useRef)();
  const onMouseMove = (event) => {
    if (controlPointMoveStateRef.current === void 0 || gradientPickerDomRef.current === null) {
      return;
    }
    const relativePosition = (0, import_utils.getHorizontalRelativeGradientPosition)(event.clientX, gradientPickerDomRef.current);
    const {
      initialPosition,
      index,
      significantMoveHappened
    } = controlPointMoveStateRef.current;
    if (!significantMoveHappened && Math.abs(initialPosition - relativePosition) >= import_constants.MINIMUM_SIGNIFICANT_MOVE) {
      controlPointMoveStateRef.current.significantMoveHappened = true;
    }
    onChange((0, import_utils.updateControlPointPosition)(controlPoints, index, relativePosition));
  };
  const cleanEventListeners = () => {
    if (window && window.removeEventListener && controlPointMoveStateRef.current && controlPointMoveStateRef.current.listenersActivated) {
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("mouseup", cleanEventListeners);
      onStopControlPointChange();
      controlPointMoveStateRef.current.listenersActivated = false;
    }
  };
  const cleanEventListenersRef = (0, import_element.useRef)();
  cleanEventListenersRef.current = cleanEventListeners;
  (0, import_element.useEffect)(() => {
    return () => {
      cleanEventListenersRef.current?.();
    };
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, {
    children: controlPoints.map((point, index) => {
      const initialPosition = point?.position;
      return ignoreMarkerPosition !== initialPosition && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(GradientColorPickerDropdown, {
        isRenderedInSidebar: __experimentalIsRenderedInSidebar,
        onClose: onStopControlPointChange,
        renderToggle: ({
          isOpen,
          onToggle
        }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ControlPointButton, {
          onClick: () => {
            if (controlPointMoveStateRef.current && controlPointMoveStateRef.current.significantMoveHappened) {
              return;
            }
            if (isOpen) {
              onStopControlPointChange();
            } else {
              onStartControlPointChange();
            }
            onToggle();
          },
          onMouseDown: () => {
            if (window && window.addEventListener) {
              controlPointMoveStateRef.current = {
                initialPosition,
                index,
                significantMoveHappened: false,
                listenersActivated: true
              };
              onStartControlPointChange();
              window.addEventListener("mousemove", onMouseMove);
              window.addEventListener("mouseup", cleanEventListeners);
            }
          },
          onKeyDown: (event) => {
            if (event.code === "ArrowLeft") {
              event.stopPropagation();
              onChange((0, import_utils.updateControlPointPosition)(controlPoints, index, (0, import_utils.clampPercent)(point.position - import_constants.KEYBOARD_CONTROL_POINT_VARIATION)));
            } else if (event.code === "ArrowRight") {
              event.stopPropagation();
              onChange((0, import_utils.updateControlPointPosition)(controlPoints, index, (0, import_utils.clampPercent)(point.position + import_constants.KEYBOARD_CONTROL_POINT_VARIATION)));
            }
          },
          isOpen,
          position: point.position,
          color: point.color
        }, index),
        renderContent: ({
          onClose
        }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_dropdown_content_wrapper.default, {
          paddingSize: "none",
          children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_color_picker.ColorPicker, {
            enableAlpha: !disableAlpha,
            color: point.color,
            onChange: (color) => {
              onChange((0, import_utils.updateControlPointColor)(controlPoints, index, (0, import_colord.colord)(color).toRgbString()));
            }
          }), !disableRemove && controlPoints.length > 2 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_h_stack.HStack, {
            className: "components-custom-gradient-picker__remove-control-point-wrapper",
            alignment: "center",
            children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_button.default, {
              onClick: () => {
                onChange((0, import_utils.removeControlPoint)(controlPoints, index));
                onClose();
              },
              variant: "link",
              children: (0, import_i18n.__)("Remove Control Point")
            })
          })]
        }),
        style: {
          left: `${point.position}%`,
          transform: "translateX( -50% )"
        }
      }, index);
    })
  });
}
function InsertPoint({
  value: controlPoints,
  onChange,
  onOpenInserter,
  onCloseInserter,
  insertPosition,
  disableAlpha,
  __experimentalIsRenderedInSidebar
}) {
  const [alreadyInsertedPoint, setAlreadyInsertedPoint] = (0, import_element.useState)(false);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(GradientColorPickerDropdown, {
    isRenderedInSidebar: __experimentalIsRenderedInSidebar,
    className: "components-custom-gradient-picker__inserter",
    onClose: () => {
      onCloseInserter();
    },
    renderToggle: ({
      isOpen,
      onToggle
    }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_button.default, {
      __next40pxDefaultSize: true,
      "aria-expanded": isOpen,
      "aria-haspopup": "true",
      onClick: () => {
        if (isOpen) {
          onCloseInserter();
        } else {
          setAlreadyInsertedPoint(false);
          onOpenInserter();
        }
        onToggle();
      },
      className: "components-custom-gradient-picker__insert-point-dropdown",
      icon: import_icons.plus
    }),
    renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_dropdown_content_wrapper.default, {
      paddingSize: "none",
      children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_color_picker.ColorPicker, {
        enableAlpha: !disableAlpha,
        onChange: (color) => {
          if (!alreadyInsertedPoint) {
            onChange((0, import_utils.addControlPoint)(controlPoints, insertPosition, (0, import_colord.colord)(color).toRgbString()));
            setAlreadyInsertedPoint(true);
          } else {
            onChange((0, import_utils.updateControlPointColorByPosition)(controlPoints, insertPosition, (0, import_colord.colord)(color).toRgbString()));
          }
        }
      })
    }),
    style: insertPosition !== null ? {
      left: `${insertPosition}%`,
      transform: "translateX( -50% )"
    } : void 0
  });
}
ControlPoints.InsertPoint = InsertPoint;
var control_points_default = ControlPoints;
//# sourceMappingURL=control-points.cjs.map
