"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/block-editor/src/hooks/duotone.js
var duotone_exports = {};
__export(duotone_exports, {
  default: () => duotone_default,
  getColorsFromDuotonePreset: () => getColorsFromDuotonePreset,
  getDuotonePresetFromColors: () => getDuotonePresetFromColors
});
module.exports = __toCommonJS(duotone_exports);
var import_colord = require("colord");
var import_names = __toESM(require("colord/plugins/names"));
var import_blocks = require("@wordpress/blocks");
var import_compose = require("@wordpress/compose");
var import_hooks = require("@wordpress/hooks");
var import_element = require("@wordpress/element");
var import_global_styles_engine = require("@wordpress/global-styles-engine");
var import_components = require("../components");
var import_utils = require("../components/duotone/utils");
var import_utils2 = require("../components/global-styles/utils");
var import_utils3 = require("./utils");
var import_filters_panel = __toESM(require("../components/global-styles/filters-panel"));
var import_block_editing_mode = require("../components/block-editing-mode");
var import_use_block_refs = require("../components/block-list/use-block-props/use-block-refs");
var import_jsx_runtime = require("react/jsx-runtime");
var EMPTY_ARRAY = [];
var isSafari = window?.navigator.userAgent && window.navigator.userAgent.includes("Safari") && !window.navigator.userAgent.includes("Chrome") && !window.navigator.userAgent.includes("Chromium");
(0, import_colord.extend)([import_names.default]);
function useMultiOriginPresets({ presetSetting, defaultSetting }) {
  const [enableDefault, userPresets, themePresets, defaultPresets] = (0, import_components.useSettings)(
    defaultSetting,
    `${presetSetting}.custom`,
    `${presetSetting}.theme`,
    `${presetSetting}.default`
  );
  return (0, import_element.useMemo)(
    () => [
      ...userPresets || EMPTY_ARRAY,
      ...themePresets || EMPTY_ARRAY,
      ...enableDefault && defaultPresets || EMPTY_ARRAY
    ],
    [enableDefault, userPresets, themePresets, defaultPresets]
  );
}
function getColorsFromDuotonePreset(duotone, duotonePalette) {
  if (!duotone) {
    return;
  }
  const preset = duotonePalette?.find(({ slug }) => {
    return duotone === `var:preset|duotone|${slug}`;
  });
  return preset ? preset.colors : void 0;
}
function getDuotonePresetFromColors(colors, duotonePalette) {
  if (!colors || !Array.isArray(colors)) {
    return;
  }
  const preset = duotonePalette?.find((duotonePreset) => {
    return duotonePreset?.colors?.every(
      (val, index) => val === colors[index]
    );
  });
  return preset ? `var:preset|duotone|${preset.slug}` : void 0;
}
function DuotonePanelPure({ style, setAttributes, name }) {
  const duotoneStyle = style?.color?.duotone;
  const settings = (0, import_utils3.useBlockSettings)(name);
  const blockEditingMode = (0, import_block_editing_mode.useBlockEditingMode)();
  const duotonePalette = useMultiOriginPresets({
    presetSetting: "color.duotone",
    defaultSetting: "color.defaultDuotone"
  });
  const colorPalette = useMultiOriginPresets({
    presetSetting: "color.palette",
    defaultSetting: "color.defaultPalette"
  });
  const [enableCustomColors, enableCustomDuotone] = (0, import_components.useSettings)(
    "color.custom",
    "color.customDuotone"
  );
  const disableCustomColors = !enableCustomColors;
  const disableCustomDuotone = !enableCustomDuotone || colorPalette?.length === 0 && disableCustomColors;
  if (duotonePalette?.length === 0 && disableCustomDuotone) {
    return null;
  }
  if (blockEditingMode !== "default") {
    return null;
  }
  const duotonePresetOrColors = duotoneStyle === "unset" || Array.isArray(duotoneStyle) ? duotoneStyle : getColorsFromDuotonePreset(duotoneStyle, duotonePalette);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.InspectorControls, { group: "filter", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_filters_panel.default,
      {
        value: { filter: { duotone: duotonePresetOrColors } },
        onChange: (newDuotone) => {
          const newStyle = {
            ...style,
            color: {
              ...newDuotone?.filter
            }
          };
          setAttributes({
            style: (0, import_utils3.cleanEmptyObject)(newStyle)
          });
        },
        settings
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.BlockControls, { group: "block", __experimentalShareWithChildBlocks: true, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_components.__experimentalDuotoneControl,
      {
        duotonePalette,
        colorPalette,
        disableCustomDuotone,
        disableCustomColors,
        value: duotonePresetOrColors,
        onChange: (newDuotone) => {
          const maybePreset = getDuotonePresetFromColors(
            newDuotone,
            duotonePalette
          );
          const newStyle = {
            ...style,
            color: {
              ...style?.color,
              duotone: maybePreset ?? newDuotone
              // use preset or fallback to custom colors.
            }
          };
          setAttributes({
            style: (0, import_utils3.cleanEmptyObject)(newStyle)
          });
        },
        settings
      }
    ) })
  ] });
}
var duotone_default = {
  shareWithChildBlocks: true,
  edit: DuotonePanelPure,
  useBlockProps,
  attributeKeys: ["style"],
  hasSupport(name) {
    return (0, import_blocks.hasBlockSupport)(name, "filter.duotone");
  }
};
function addDuotoneAttributes(settings) {
  if (!(0, import_blocks.hasBlockSupport)(settings, "filter.duotone")) {
    return settings;
  }
  if (!settings.attributes.style) {
    Object.assign(settings.attributes, {
      style: {
        type: "object"
      }
    });
  }
  return settings;
}
function useDuotoneStyles({
  clientId,
  id: filterId,
  selector: duotoneSelector,
  attribute: duotoneAttr
}) {
  const duotonePalette = useMultiOriginPresets({
    presetSetting: "color.duotone",
    defaultSetting: "color.defaultDuotone"
  });
  const isCustom = Array.isArray(duotoneAttr);
  const duotonePreset = isCustom ? void 0 : getColorsFromDuotonePreset(duotoneAttr, duotonePalette);
  const isPreset = typeof duotoneAttr === "string" && duotonePreset;
  const isCSS = typeof duotoneAttr === "string" && !isPreset;
  let colors = null;
  if (isPreset) {
    colors = duotonePreset;
  } else if (isCSS) {
    colors = duotoneAttr;
  } else if (isCustom) {
    colors = duotoneAttr;
  }
  const selectors = duotoneSelector.split(",");
  const selectorsScoped = selectors.map((selectorPart) => {
    return `.${filterId}${selectorPart.trim()}`;
  });
  const selector = selectorsScoped.join(", ");
  const isValidFilter = Array.isArray(colors) || colors === "unset";
  (0, import_utils3.usePrivateStyleOverride)(
    isValidFilter ? {
      css: colors !== "unset" ? (0, import_utils.getDuotoneStylesheet)(selector, filterId) : (0, import_utils.getDuotoneUnsetStylesheet)(selector),
      __unstableType: "presets"
    } : void 0
  );
  (0, import_utils3.usePrivateStyleOverride)(
    isValidFilter ? {
      assets: colors !== "unset" ? (0, import_utils.getDuotoneFilter)(filterId, colors) : "",
      __unstableType: "svgs"
    } : void 0
  );
  const blockElement = (0, import_use_block_refs.useBlockElement)(clientId);
  (0, import_element.useEffect)(() => {
    if (!isValidFilter) {
      return;
    }
    if (blockElement && isSafari) {
      const display = blockElement.style.display;
      blockElement.style.setProperty("display", "inline-block");
      blockElement.offsetHeight;
      blockElement.style.setProperty("display", display);
    }
  }, [isValidFilter, blockElement, colors]);
}
var DUOTONE_BLOCK_PROPS_REFERENCE = {};
function useBlockProps({ clientId, name, style }) {
  const id = (0, import_compose.useInstanceId)(DUOTONE_BLOCK_PROPS_REFERENCE);
  const selector = (0, import_element.useMemo)(() => {
    const blockType = (0, import_blocks.getBlockType)(name);
    if (blockType) {
      const duotoneSupport = (0, import_blocks.getBlockSupport)(
        blockType,
        "filter.duotone",
        false
      );
      if (!duotoneSupport) {
        return null;
      }
      const experimentalDuotone = (0, import_blocks.getBlockSupport)(
        blockType,
        "color.__experimentalDuotone",
        false
      );
      if (experimentalDuotone) {
        const rootSelector = (0, import_global_styles_engine.getBlockSelector)(blockType);
        return typeof experimentalDuotone === "string" ? (0, import_utils2.scopeSelector)(rootSelector, experimentalDuotone) : rootSelector;
      }
      return (0, import_global_styles_engine.getBlockSelector)(blockType, "filter.duotone", {
        fallback: true
      });
    }
  }, [name]);
  const attribute = style?.color?.duotone;
  const filterClass = `wp-duotone-${id}`;
  const shouldRender = selector && attribute;
  useDuotoneStyles({
    clientId,
    id: filterClass,
    selector,
    attribute
  });
  return {
    className: shouldRender ? filterClass : ""
  };
}
(0, import_hooks.addFilter)(
  "blocks.registerBlockType",
  "core/editor/duotone/add-attributes",
  addDuotoneAttributes
);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getColorsFromDuotonePreset,
  getDuotonePresetFromColors
});
//# sourceMappingURL=duotone.js.map
