"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/utils.js
var utils_exports = {};
__export(utils_exports, {
  cleanEmptyObject: () => cleanEmptyObject,
  createBlockEditFilter: () => createBlockEditFilter,
  createBlockListBlockFilter: () => createBlockListBlockFilter,
  createBlockSaveFilter: () => createBlockSaveFilter,
  shouldSkipSerialization: () => shouldSkipSerialization,
  transformStyles: () => transformStyles,
  useBlockSettings: () => useBlockSettings,
  usePrivateStyleOverride: () => usePrivateStyleOverride,
  useStyleOverride: () => useStyleOverride
});
module.exports = __toCommonJS(utils_exports);
var import_clsx = __toESM(require("clsx"));
var import_blocks = require("@wordpress/blocks");
var import_element = require("@wordpress/element");
var import_data = require("@wordpress/data");
var import_compose = require("@wordpress/compose");
var import_hooks = require("@wordpress/hooks");
var import_context = require("../components/block-edit/context.cjs");
var import_components = require("../components/index.cjs");
var import_hooks2 = require("../components/global-styles/hooks.cjs");
var import_object = require("../utils/object.cjs");
var import_store = require("../store/index.cjs");
var import_lock_unlock = require("../lock-unlock.cjs");
var import_jsx_runtime = require("react/jsx-runtime");
var cleanEmptyObject = (object) => {
  if (object === null || typeof object !== "object" || Array.isArray(object)) {
    return object;
  }
  const cleanedNestedObjects = Object.entries(object).map(([key, value]) => [key, cleanEmptyObject(value)]).filter(([, value]) => value !== void 0);
  return !cleanedNestedObjects.length ? void 0 : Object.fromEntries(cleanedNestedObjects);
};
function transformStyles(activeSupports, migrationPaths, result, source, index, results) {
  if (Object.values(activeSupports ?? {}).every(
    (isActive) => !isActive
  )) {
    return result;
  }
  if (results.length === 1 && result.innerBlocks.length === source.length) {
    return result;
  }
  let referenceBlockAttributes = source[0]?.attributes;
  if (results.length > 1 && source.length > 1) {
    if (source[index]) {
      referenceBlockAttributes = source[index]?.attributes;
    } else {
      return result;
    }
  }
  let returnBlock = result;
  Object.entries(activeSupports).forEach(([support, isActive]) => {
    if (isActive) {
      migrationPaths[support].forEach((path) => {
        const styleValue = (0, import_object.getValueFromObjectPath)(
          referenceBlockAttributes,
          path
        );
        if (styleValue) {
          returnBlock = {
            ...returnBlock,
            attributes: (0, import_object.setImmutably)(
              returnBlock.attributes,
              path,
              styleValue
            )
          };
        }
      });
    }
  });
  return returnBlock;
}
function shouldSkipSerialization(blockNameOrType, featureSet, feature) {
  const support = (0, import_blocks.getBlockSupport)(blockNameOrType, featureSet);
  const skipSerialization = support?.__experimentalSkipSerialization;
  if (Array.isArray(skipSerialization)) {
    return skipSerialization.includes(feature);
  }
  return skipSerialization;
}
var pendingStyleOverrides = /* @__PURE__ */ new WeakMap();
function useStyleOverride({ id, css }) {
  return usePrivateStyleOverride({ id, css });
}
function usePrivateStyleOverride({
  id,
  css,
  assets,
  __unstableType,
  variation,
  clientId
} = {}) {
  const { setStyleOverride, deleteStyleOverride } = (0, import_lock_unlock.unlock)(
    (0, import_data.useDispatch)(import_store.store)
  );
  const registry = (0, import_data.useRegistry)();
  const fallbackId = (0, import_element.useId)();
  (0, import_element.useEffect)(() => {
    if (!css && !assets) {
      return;
    }
    const _id = id || fallbackId;
    const override = {
      id,
      css,
      assets,
      __unstableType,
      variation,
      clientId
    };
    if (!pendingStyleOverrides.get(registry)) {
      pendingStyleOverrides.set(registry, []);
    }
    pendingStyleOverrides.get(registry).push([_id, override]);
    window.queueMicrotask(() => {
      if (pendingStyleOverrides.get(registry)?.length) {
        registry.batch(() => {
          pendingStyleOverrides.get(registry).forEach((args) => {
            setStyleOverride(...args);
          });
          pendingStyleOverrides.set(registry, []);
        });
      }
    });
    return () => {
      const isPending = pendingStyleOverrides.get(registry)?.find(([currentId]) => currentId === _id);
      if (isPending) {
        pendingStyleOverrides.set(
          registry,
          pendingStyleOverrides.get(registry).filter(([currentId]) => currentId !== _id)
        );
      } else {
        deleteStyleOverride(_id);
      }
    };
  }, [
    id,
    css,
    clientId,
    assets,
    __unstableType,
    fallbackId,
    setStyleOverride,
    deleteStyleOverride,
    registry,
    variation
  ]);
}
function useBlockSettings(name, parentLayout) {
  const [
    backgroundImage,
    backgroundSize,
    customFontFamilies,
    defaultFontFamilies,
    themeFontFamilies,
    defaultFontSizesEnabled,
    customFontSizes,
    defaultFontSizes,
    themeFontSizes,
    customFontSize,
    fontStyle,
    fontWeight,
    lineHeight,
    textAlign,
    textColumns,
    textDecoration,
    writingMode,
    textTransform,
    letterSpacing,
    padding,
    margin,
    blockGap,
    defaultSpacingSizesEnabled,
    customSpacingSize,
    userSpacingSizes,
    defaultSpacingSizes,
    themeSpacingSizes,
    units,
    aspectRatio,
    height,
    minHeight,
    width,
    dimensionSizes,
    layout,
    borderColor,
    borderRadius,
    borderStyle,
    borderWidth,
    borderRadiusSizes,
    customColorsEnabled,
    customColors,
    customDuotone,
    themeColors,
    defaultColors,
    defaultPalette,
    defaultDuotone,
    userDuotonePalette,
    themeDuotonePalette,
    defaultDuotonePalette,
    userGradientPalette,
    themeGradientPalette,
    defaultGradientPalette,
    defaultGradients,
    areCustomGradientsEnabled,
    isBackgroundEnabled,
    isLinkEnabled,
    isTextEnabled,
    isHeadingEnabled,
    isButtonEnabled,
    shadow
  ] = (0, import_components.useSettings)(
    "background.backgroundImage",
    "background.backgroundSize",
    "typography.fontFamilies.custom",
    "typography.fontFamilies.default",
    "typography.fontFamilies.theme",
    "typography.defaultFontSizes",
    "typography.fontSizes.custom",
    "typography.fontSizes.default",
    "typography.fontSizes.theme",
    "typography.customFontSize",
    "typography.fontStyle",
    "typography.fontWeight",
    "typography.lineHeight",
    "typography.textAlign",
    "typography.textColumns",
    "typography.textDecoration",
    "typography.writingMode",
    "typography.textTransform",
    "typography.letterSpacing",
    "spacing.padding",
    "spacing.margin",
    "spacing.blockGap",
    "spacing.defaultSpacingSizes",
    "spacing.customSpacingSize",
    "spacing.spacingSizes.custom",
    "spacing.spacingSizes.default",
    "spacing.spacingSizes.theme",
    "spacing.units",
    "dimensions.aspectRatio",
    "dimensions.height",
    "dimensions.minHeight",
    "dimensions.width",
    "dimensions.dimensionSizes",
    "layout",
    "border.color",
    "border.radius",
    "border.style",
    "border.width",
    "border.radiusSizes",
    "color.custom",
    "color.palette.custom",
    "color.customDuotone",
    "color.palette.theme",
    "color.palette.default",
    "color.defaultPalette",
    "color.defaultDuotone",
    "color.duotone.custom",
    "color.duotone.theme",
    "color.duotone.default",
    "color.gradients.custom",
    "color.gradients.theme",
    "color.gradients.default",
    "color.defaultGradients",
    "color.customGradient",
    "color.background",
    "color.link",
    "color.text",
    "color.heading",
    "color.button",
    "shadow"
  );
  const rawSettings = (0, import_element.useMemo)(() => {
    return {
      background: {
        backgroundImage,
        backgroundSize
      },
      color: {
        palette: {
          custom: customColors,
          theme: themeColors,
          default: defaultColors
        },
        gradients: {
          custom: userGradientPalette,
          theme: themeGradientPalette,
          default: defaultGradientPalette
        },
        duotone: {
          custom: userDuotonePalette,
          theme: themeDuotonePalette,
          default: defaultDuotonePalette
        },
        defaultGradients,
        defaultPalette,
        defaultDuotone,
        custom: customColorsEnabled,
        customGradient: areCustomGradientsEnabled,
        customDuotone,
        background: isBackgroundEnabled,
        link: isLinkEnabled,
        heading: isHeadingEnabled,
        button: isButtonEnabled,
        text: isTextEnabled
      },
      typography: {
        fontFamilies: {
          custom: customFontFamilies,
          default: defaultFontFamilies,
          theme: themeFontFamilies
        },
        fontSizes: {
          custom: customFontSizes,
          default: defaultFontSizes,
          theme: themeFontSizes
        },
        customFontSize,
        defaultFontSizes: defaultFontSizesEnabled,
        fontStyle,
        fontWeight,
        lineHeight,
        textAlign,
        textColumns,
        textDecoration,
        textTransform,
        letterSpacing,
        writingMode
      },
      spacing: {
        spacingSizes: {
          custom: userSpacingSizes,
          default: defaultSpacingSizes,
          theme: themeSpacingSizes
        },
        customSpacingSize,
        defaultSpacingSizes: defaultSpacingSizesEnabled,
        padding,
        margin,
        blockGap,
        units
      },
      border: {
        color: borderColor,
        radius: borderRadius,
        style: borderStyle,
        width: borderWidth,
        radiusSizes: borderRadiusSizes
      },
      dimensions: {
        aspectRatio,
        height,
        minHeight,
        width,
        dimensionSizes
      },
      layout,
      parentLayout,
      shadow
    };
  }, [
    backgroundImage,
    backgroundSize,
    customFontFamilies,
    defaultFontFamilies,
    themeFontFamilies,
    defaultFontSizesEnabled,
    customFontSizes,
    defaultFontSizes,
    themeFontSizes,
    customFontSize,
    fontStyle,
    fontWeight,
    lineHeight,
    textAlign,
    textColumns,
    textDecoration,
    textTransform,
    letterSpacing,
    writingMode,
    padding,
    margin,
    blockGap,
    defaultSpacingSizesEnabled,
    customSpacingSize,
    userSpacingSizes,
    defaultSpacingSizes,
    themeSpacingSizes,
    units,
    aspectRatio,
    height,
    minHeight,
    width,
    dimensionSizes,
    layout,
    parentLayout,
    borderColor,
    borderRadius,
    borderStyle,
    borderWidth,
    borderRadiusSizes,
    customColorsEnabled,
    customColors,
    customDuotone,
    themeColors,
    defaultColors,
    defaultPalette,
    defaultDuotone,
    userDuotonePalette,
    themeDuotonePalette,
    defaultDuotonePalette,
    userGradientPalette,
    themeGradientPalette,
    defaultGradientPalette,
    defaultGradients,
    areCustomGradientsEnabled,
    isBackgroundEnabled,
    isLinkEnabled,
    isTextEnabled,
    isHeadingEnabled,
    isButtonEnabled,
    shadow
  ]);
  return (0, import_hooks2.useSettingsForBlockElement)(rawSettings, name);
}
function createBlockEditFilter(features) {
  features = features.map((settings) => {
    return { ...settings, Edit: (0, import_element.memo)(settings.edit) };
  });
  const withBlockEditHooks = (0, import_compose.createHigherOrderComponent)(
    (OriginalBlockEdit) => (props) => {
      const context = (0, import_context.useBlockEditContext)();
      return [
        ...features.map((feature, i) => {
          const {
            Edit,
            hasSupport,
            attributeKeys = [],
            shareWithChildBlocks
          } = feature;
          const shouldDisplayControls = context[import_context.mayDisplayControlsKey] || context[import_context.mayDisplayParentControlsKey] && shareWithChildBlocks;
          if (!shouldDisplayControls || !hasSupport(props.name)) {
            return null;
          }
          const neededProps = {};
          for (const key of attributeKeys) {
            if (props.attributes[key]) {
              neededProps[key] = props.attributes[key];
            }
          }
          return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            Edit,
            {
              name: props.name,
              isSelected: props.isSelected,
              clientId: props.clientId,
              setAttributes: props.setAttributes,
              __unstableParentLayout: props.__unstableParentLayout,
              ...neededProps
            },
            i
          );
        }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(OriginalBlockEdit, { ...props }, "edit")
      ];
    },
    "withBlockEditHooks"
  );
  (0, import_hooks.addFilter)("editor.BlockEdit", "core/editor/hooks", withBlockEditHooks);
}
function BlockProps({
  index,
  useBlockProps: hook,
  setAllWrapperProps,
  ...props
}) {
  const wrapperProps = hook(props);
  const setWrapperProps = (next) => setAllWrapperProps((prev) => {
    const nextAll = [...prev];
    nextAll[index] = next;
    return nextAll;
  });
  (0, import_element.useEffect)(() => {
    setWrapperProps(wrapperProps);
    return () => {
      setWrapperProps(void 0);
    };
  });
  return null;
}
var BlockPropsPure = (0, import_element.memo)(BlockProps);
function createBlockListBlockFilter(features) {
  const withBlockListBlockHooks = (0, import_compose.createHigherOrderComponent)(
    (BlockListBlock) => (props) => {
      const [allWrapperProps, setAllWrapperProps] = (0, import_element.useState)(
        Array(features.length).fill(void 0)
      );
      return [
        ...features.map((feature, i) => {
          const {
            hasSupport,
            attributeKeys = [],
            useBlockProps,
            isMatch
          } = feature;
          const neededProps = {};
          for (const key of attributeKeys) {
            if (props.attributes[key]) {
              neededProps[key] = props.attributes[key];
            }
          }
          if (
            // Skip rendering if none of the needed attributes are
            // set.
            !Object.keys(neededProps).length || !hasSupport(props.name) || isMatch && !isMatch(neededProps)
          ) {
            return null;
          }
          return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            BlockPropsPure,
            {
              index: i,
              useBlockProps,
              setAllWrapperProps,
              name: props.name,
              clientId: props.clientId,
              ...neededProps
            },
            i
          );
        }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
          BlockListBlock,
          {
            ...props,
            wrapperProps: allWrapperProps.filter(Boolean).reduce((acc, wrapperProps) => {
              return {
                ...acc,
                ...wrapperProps,
                className: (0, import_clsx.default)(
                  acc.className,
                  wrapperProps.className
                ),
                style: {
                  ...acc.style,
                  ...wrapperProps.style
                }
              };
            }, props.wrapperProps || {})
          },
          "edit"
        )
      ];
    },
    "withBlockListBlockHooks"
  );
  (0, import_hooks.addFilter)(
    "editor.BlockListBlock",
    "core/editor/hooks",
    withBlockListBlockHooks
  );
}
function createBlockSaveFilter(features) {
  function extraPropsFromHooks(props, name, attributes) {
    return features.reduce((accu, feature) => {
      const { hasSupport, attributeKeys = [], addSaveProps } = feature;
      const neededAttributes = {};
      for (const key of attributeKeys) {
        if (attributes[key]) {
          neededAttributes[key] = attributes[key];
        }
      }
      if (
        // Skip rendering if none of the needed attributes are
        // set.
        !Object.keys(neededAttributes).length || !hasSupport(name)
      ) {
        return accu;
      }
      return addSaveProps(accu, name, neededAttributes);
    }, props);
  }
  (0, import_hooks.addFilter)(
    "blocks.getSaveContent.extraProps",
    "core/editor/hooks",
    extraPropsFromHooks,
    0
  );
  (0, import_hooks.addFilter)(
    "blocks.getSaveContent.extraProps",
    "core/editor/hooks",
    (props) => {
      if (props.hasOwnProperty("className") && !props.className) {
        delete props.className;
      }
      return props;
    }
  );
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  cleanEmptyObject,
  createBlockEditFilter,
  createBlockListBlockFilter,
  createBlockSaveFilter,
  shouldSkipSerialization,
  transformStyles,
  useBlockSettings,
  usePrivateStyleOverride,
  useStyleOverride
});
//# sourceMappingURL=utils.cjs.map
