"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// packages/block-editor/src/hooks/style.js
var style_exports = {};
__export(style_exports, {
  addSaveProps: () => addSaveProps,
  default: () => style_default,
  getBlockStateStylesCSS: () => getBlockStateStylesCSS,
  getCanvasStateStyleValue: () => getCanvasStateStyleValue,
  getInlineStyles: () => getInlineStyles,
  getResponsiveStateCSSRules: () => getResponsiveStateCSSRules,
  getStateStylesCSS: () => getStateStylesCSS,
  omitStyle: () => omitStyle
});
module.exports = __toCommonJS(style_exports);
var import_element = require("@wordpress/element");
var import_hooks = require("@wordpress/hooks");
var import_data = require("@wordpress/data");
var import_global_styles_engine = require("@wordpress/global-styles-engine");
var import_blocks = require("@wordpress/blocks");
var import_compose = require("@wordpress/compose");
var import_style_engine = require("@wordpress/style-engine");
var import_background = require("./background.cjs");
var import_border = require("./border.cjs");
var import_color = require("./color.cjs");
var import_elements = require("./elements.cjs");
var import_typography = require("./typography.cjs");
var import_dimensions = require("./dimensions.cjs");
var import_utils = require("./utils.cjs");
var import_block_style_state = require("./block-style-state.cjs");
var import_states = require("./states.cjs");
var import_state_utils = require("./state-utils.cjs");
var import_utils2 = require("../components/global-styles/utils.cjs");
var import_block_editing_mode = require("../components/block-editing-mode/index.cjs");
var import_store = require("../store/index.cjs");
var import_private_keys = require("../store/private-keys.cjs");
var import_lock_unlock = require("../lock-unlock.cjs");
var import_jsx_runtime = require("react/jsx-runtime");
var BORDER_SIDES = ["Top", "Right", "Bottom", "Left"];
var RESPONSIVE_BREAKPOINTS = {
  "@mobile": "@media (width <= 480px)",
  "@tablet": "@media (480px < width <= 782px)"
};
var styleSupportKeys = [
  ...import_typography.TYPOGRAPHY_SUPPORT_KEYS,
  import_border.BORDER_SUPPORT_KEY,
  import_color.COLOR_SUPPORT_KEY,
  import_dimensions.DIMENSIONS_SUPPORT_KEY,
  import_background.BACKGROUND_SUPPORT_KEY,
  import_dimensions.SPACING_SUPPORT_KEY,
  import_border.SHADOW_SUPPORT_KEY
];
var hasStyleSupport = (nameOrType) => styleSupportKeys.some((key) => (0, import_blocks.hasBlockSupport)(nameOrType, key));
function getInlineStyles(styles = {}) {
  const output = {};
  (0, import_style_engine.getCSSRules)(styles).forEach((rule) => {
    output[rule.key] = rule.value;
  });
  return output;
}
function getStateFallbackBorderStyles(stateStyles) {
  const border = stateStyles?.border;
  if (!border) {
    return void 0;
  }
  const hasBorderStyle = !!border.style;
  const hasBorderColor = !!border.color;
  const hasBorderWidth = !!border.width;
  const fallbackBorder = {};
  if (!hasBorderStyle && (hasBorderColor || hasBorderWidth)) {
    fallbackBorder.style = "solid";
  }
  BORDER_SIDES.forEach((side) => {
    const sideKey = side.toLowerCase();
    const sideBorder = border[sideKey];
    const hasSideStyle = !!sideBorder?.style;
    const hasSideColor = !!sideBorder?.color;
    const hasSideWidth = !!sideBorder?.width;
    if (!hasBorderStyle && !hasSideStyle && (hasSideColor || hasSideWidth)) {
      fallbackBorder[sideKey] = { style: "solid" };
    }
  });
  return (0, import_utils.cleanEmptyObject)({ border: (0, import_utils.cleanEmptyObject)(fallbackBorder) });
}
function getStateBackgroundResetCSS(stateStyles, selector) {
  const hasSolidBackground = !!stateStyles?.color?.background;
  if (!hasSolidBackground) {
    return void 0;
  }
  const hasColorGradient = !!stateStyles?.color?.gradient;
  const hasBackgroundGradient = !!stateStyles?.background?.gradient || !!stateStyles?.background?.backgroundImage;
  if (hasColorGradient || hasBackgroundGradient) {
    return void 0;
  }
  const declaration = "background-image: unset !important";
  return selector ? `${selector} { ${declaration}; }` : `${declaration};`;
}
function getStateFallbackDimensionStyles(stateStyles) {
  const dimensions = stateStyles?.dimensions;
  if (!dimensions) {
    return void 0;
  }
  if ((0, import_dimensions.isExplicitAspectRatio)(dimensions.aspectRatio)) {
    return {
      dimensions: {
        minHeight: "unset",
        height: "unset"
      }
    };
  }
  if (dimensions.minHeight || dimensions.height) {
    return {
      dimensions: {
        aspectRatio: "unset"
      }
    };
  }
}
function getStateStylesCSS(stateStyles, selector) {
  const fallbackDimensionStyles = getStateFallbackDimensionStyles(stateStyles);
  const stylesWithDimensionFallbacks = fallbackDimensionStyles ? mergeStyleObjects(stateStyles, fallbackDimensionStyles) : stateStyles;
  const css = (0, import_style_engine.compileCSS)(stylesWithDimensionFallbacks, { selector });
  const importantCSS = css ? css.replace(/;/g, " !important;") : void 0;
  const fallbackBorderStyles = getStateFallbackBorderStyles(stateStyles);
  const fallbackCSS = fallbackBorderStyles ? (0, import_style_engine.compileCSS)(fallbackBorderStyles, { selector }) : void 0;
  const backgroundResetCSS = getStateBackgroundResetCSS(
    stateStyles,
    selector
  );
  return [importantCSS, fallbackCSS, backgroundResetCSS].filter(Boolean).join("\n");
}
function isPlainObject(value) {
  return !!value && typeof value === "object" && !Array.isArray(value);
}
function mergeStyleObjects(target = {}, source = {}) {
  const merged = { ...target };
  Object.entries(source).forEach(([key, value]) => {
    merged[key] = isPlainObject(value) && isPlainObject(merged[key]) ? mergeStyleObjects(merged[key], value) : value;
  });
  return merged;
}
function addStyleGroup(groups, selector, style) {
  const key = selector || "";
  const existing = groups.get(key) || { selector, style: {} };
  groups.set(key, {
    selector,
    style: mergeStyleObjects(existing.style, style)
  });
}
function getStateStyleGroups(stateStyles, name) {
  const blockSelectors = (0, import_blocks.getBlockType)(name)?.selectors || {};
  const groups = /* @__PURE__ */ new Map();
  Object.entries(stateStyles || {}).forEach(
    ([feature, featureStyles]) => {
      const featureSelectors = blockSelectors[feature];
      if (typeof featureSelectors === "string") {
        addStyleGroup(groups, featureSelectors, {
          [feature]: featureStyles
        });
        return;
      }
      if (isPlainObject(featureSelectors) && isPlainObject(featureStyles)) {
        const remainingStyles = { ...featureStyles };
        Object.entries(featureSelectors).forEach(
          ([subfeature, subfeatureSelector]) => {
            if (subfeature === "root" || typeof subfeatureSelector !== "string" || !Object.hasOwn(featureStyles, subfeature)) {
              return;
            }
            addStyleGroup(groups, subfeatureSelector, {
              [feature]: {
                [subfeature]: featureStyles[subfeature]
              }
            });
            delete remainingStyles[subfeature];
          }
        );
        if (Object.keys(remainingStyles).length) {
          addStyleGroup(
            groups,
            featureSelectors.root || blockSelectors.root,
            {
              [feature]: remainingStyles
            }
          );
        }
        return;
      }
      addStyleGroup(groups, blockSelectors.root, {
        [feature]: featureStyles
      });
    }
  );
  return Array.from(groups.values());
}
function getBlockStateStylesCSS(stateStyles, options) {
  const { name, baseSelector, state = "" } = options;
  const rules = getStateStyleGroups(stateStyles, name).map(
    ({ selector: blockSelector, style }) => getStateStylesCSS(
      style,
      (0, import_state_utils.buildScopedBlockSelector)(baseSelector, blockSelector, state)
    )
  ).filter(Boolean);
  return rules.length ? rules.join("\n") : void 0;
}
function getRootStateStyles(stateStyles, nestedKeys) {
  if (!stateStyles) {
    return stateStyles;
  }
  const rootStyles = { ...stateStyles };
  nestedKeys.forEach((key) => {
    delete rootStyles[key];
  });
  return rootStyles;
}
function getPseudoStateCSSRules(style, name, baseSelector) {
  const validPseudoStates = import_states.VALID_BLOCK_PSEUDO_STATES[name];
  if (!validPseudoStates) {
    return [];
  }
  const cssRules = [];
  validPseudoStates.forEach((pseudoState) => {
    const stateStyles = style?.[pseudoState];
    if (stateStyles) {
      const css = getBlockStateStylesCSS(stateStyles, {
        name,
        baseSelector,
        state: pseudoState
      });
      if (css) {
        cssRules.push(css);
      }
    }
  });
  return cssRules;
}
function getResponsiveStateCSSRules(style, name, baseSelector) {
  const cssRules = [];
  const validPseudoStates = import_states.VALID_BLOCK_PSEUDO_STATES[name] ?? [];
  const nestedStateKeys = ["elements", ...validPseudoStates];
  Object.entries(RESPONSIVE_BREAKPOINTS).forEach(
    ([viewport, mediaQuery]) => {
      const viewportStyles = (0, import_block_style_state.getStyleForState)(style, {
        viewport,
        pseudo: import_block_style_state.DEFAULT_BLOCK_STYLE_STATE.pseudo
      });
      if (!viewportStyles) {
        return;
      }
      const viewportCSSRules = [];
      const rootCSS = getBlockStateStylesCSS(
        getRootStateStyles(viewportStyles, nestedStateKeys),
        {
          name,
          baseSelector
        }
      );
      if (rootCSS) {
        viewportCSSRules.push(rootCSS);
      }
      const elementCSS = getElementCSSRules(
        viewportStyles.elements,
        name,
        baseSelector
      );
      if (elementCSS) {
        viewportCSSRules.push(elementCSS);
      }
      viewportCSSRules.push(
        ...getPseudoStateCSSRules(viewportStyles, name, baseSelector)
      );
      if (viewportCSSRules.length) {
        cssRules.push(
          `${mediaQuery}{${viewportCSSRules.join("")}}`
        );
      }
    }
  );
  return cssRules;
}
function getCanvasStateStyleValue(style, selectedState) {
  const stateValue = (0, import_block_style_state.getStyleForState)(style, selectedState);
  if (!(0, import_block_style_state.hasViewportBlockStyleState)(selectedState)) {
    return stateValue;
  }
  const defaultViewportState = {
    ...selectedState,
    viewport: import_block_style_state.DEFAULT_BLOCK_STYLE_STATE.viewport
  };
  const defaultViewportStateValue = (0, import_block_style_state.getStyleForState)(
    style,
    defaultViewportState
  );
  if (defaultViewportStateValue && stateValue) {
    return (0, import_global_styles_engine.mergeGlobalStyles)(defaultViewportStateValue, stateValue);
  }
  return stateValue || defaultViewportStateValue;
}
function addAttribute(settings) {
  if (!hasStyleSupport(settings) && !(0, import_blocks.hasBlockSupport)(settings, "customCSS", true)) {
    return settings;
  }
  if (!settings.attributes.style) {
    Object.assign(settings.attributes, {
      style: {
        type: "object"
      }
    });
  }
  return settings;
}
var skipSerializationPathsEdit = {
  [`${import_border.BORDER_SUPPORT_KEY}.__experimentalSkipSerialization`]: ["border"],
  [`${import_color.COLOR_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    import_color.COLOR_SUPPORT_KEY
  ],
  [`${import_typography.TYPOGRAPHY_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    import_typography.TYPOGRAPHY_SUPPORT_KEY
  ],
  [`${import_dimensions.DIMENSIONS_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    import_dimensions.DIMENSIONS_SUPPORT_KEY
  ],
  [`${import_dimensions.SPACING_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    import_dimensions.SPACING_SUPPORT_KEY
  ],
  [`${import_border.SHADOW_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    import_border.SHADOW_SUPPORT_KEY
  ]
};
var skipSerializationPathsSave = {
  ...skipSerializationPathsEdit,
  [`${import_dimensions.DIMENSIONS_SUPPORT_KEY}.aspectRatio`]: [
    `${import_dimensions.DIMENSIONS_SUPPORT_KEY}.aspectRatio`
  ],
  // Skip serialization of aspect ratio in save mode.
  [`${import_background.BACKGROUND_SUPPORT_KEY}`]: [import_background.BACKGROUND_SUPPORT_KEY]
  // Skip serialization of background support in save mode.
};
var skipSerializationPathsSaveChecks = {
  [`${import_dimensions.DIMENSIONS_SUPPORT_KEY}.aspectRatio`]: true,
  [`${import_background.BACKGROUND_SUPPORT_KEY}`]: true
};
var renamedFeatures = { gradients: "gradient" };
function omitStyle(style, paths, preserveReference = false) {
  if (!style) {
    return style;
  }
  let newStyle = style;
  if (!preserveReference) {
    newStyle = JSON.parse(JSON.stringify(style));
  }
  if (!Array.isArray(paths)) {
    paths = [paths];
  }
  paths.forEach((path) => {
    if (!Array.isArray(path)) {
      path = path.split(".");
    }
    if (path.length > 1) {
      const [firstSubpath, ...restPath] = path;
      omitStyle(newStyle[firstSubpath], [restPath], true);
    } else if (path.length === 1) {
      delete newStyle[path[0]];
    }
  });
  return newStyle;
}
function addSaveProps(props, blockNameOrType, attributes, skipPaths = skipSerializationPathsSave) {
  if (!hasStyleSupport(blockNameOrType)) {
    return props;
  }
  let { style } = attributes;
  Object.entries(skipPaths).forEach(([indicator, path]) => {
    const skipSerialization = skipSerializationPathsSaveChecks[indicator] || (0, import_blocks.getBlockSupport)(blockNameOrType, indicator);
    if (skipSerialization === true) {
      style = omitStyle(style, path);
    }
    if (Array.isArray(skipSerialization)) {
      skipSerialization.forEach((featureName) => {
        const feature = renamedFeatures[featureName] || featureName;
        style = omitStyle(style, [[...path, feature]]);
      });
    }
  });
  props.style = {
    ...getInlineStyles(style),
    ...props.style
  };
  return props;
}
function BlockStyleControls({
  clientId,
  name,
  setAttributes,
  style,
  __unstableParentLayout
}) {
  const settings = (0, import_utils.useBlockSettings)(name, __unstableParentLayout);
  const blockEditingMode = (0, import_block_editing_mode.useBlockEditingMode)();
  const { globalBlockStyles, selectedState, showStateOnCanvas } = (0, import_data.useSelect)(
    (select) => {
      const blockEditorSelect = select(import_store.store);
      const {
        getSelectedBlockStyleState,
        isSelectedBlockStyleStateShownOnCanvas
      } = (0, import_lock_unlock.unlock)(blockEditorSelect);
      const editorSettings = blockEditorSelect.getSettings();
      return {
        globalBlockStyles: editorSettings?.[import_private_keys.globalStylesDataKey]?.blocks?.[name],
        selectedState: getSelectedBlockStyleState(clientId),
        showStateOnCanvas: isSelectedBlockStyleStateShownOnCanvas(clientId)
      };
    },
    [clientId, name]
  );
  const isPseudoSelectorState = (0, import_block_style_state.hasPseudoBlockStyleState)(selectedState);
  const canvasStateCSS = (0, import_element.useMemo)(() => {
    if (!showStateOnCanvas || !isPseudoSelectorState) {
      return void 0;
    }
    const globalStateValue = getCanvasStateStyleValue(
      globalBlockStyles,
      selectedState
    );
    const instanceStateValue = getCanvasStateStyleValue(
      style,
      selectedState
    );
    let stateValue;
    if (globalStateValue && instanceStateValue) {
      stateValue = (0, import_global_styles_engine.mergeGlobalStyles)(
        globalStateValue,
        instanceStateValue
      );
    } else if (instanceStateValue) {
      stateValue = instanceStateValue;
    } else if (globalStateValue) {
      stateValue = globalStateValue;
    } else {
      return void 0;
    }
    return getBlockStateStylesCSS(stateValue, {
      name,
      baseSelector: `[data-block="${clientId}"]`
    });
  }, [
    showStateOnCanvas,
    isPseudoSelectorState,
    globalBlockStyles,
    style,
    selectedState,
    clientId,
    name
  ]);
  (0, import_utils.useStyleOverride)({ css: canvasStateCSS });
  if (blockEditingMode !== "default") {
    return null;
  }
  const panelSettings = {
    ...settings,
    typography: {
      ...settings.typography,
      // The text alignment UI for individual blocks is rendered in
      // the block toolbar, so disable it here.
      textAlign: false
    }
  };
  const passedProps = {
    clientId,
    name,
    setAttributes,
    settings: panelSettings
  };
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_block_style_state.BlockStyleStateProvider, { value: selectedState, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_elements.ElementsEdit, { ...passedProps }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_background.BackgroundImagePanel, { ...passedProps }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_typography.TypographyPanel, { ...passedProps }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_border.BorderPanel, { ...passedProps }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_dimensions.DimensionsPanel, { ...passedProps })
  ] });
}
var style_default = {
  edit: BlockStyleControls,
  hasSupport: hasStyleSupport,
  addSaveProps,
  attributeKeys: ["style"],
  useBlockProps
};
var elementTypes = [
  { elementType: "button" },
  { elementType: "link", pseudo: [":hover"] },
  {
    elementType: "heading",
    elements: ["h1", "h2", "h3", "h4", "h5", "h6"]
  }
];
var STYLE_BLOCK_PROPS_REFERENCE = {};
function getElementCSSRules(blockElementStyles, blockName, baseSelector) {
  if (!blockElementStyles) {
    return;
  }
  const rules = [];
  elementTypes.forEach(({ elementType, pseudo, elements }) => {
    const skipSerialization = (0, import_utils.shouldSkipSerialization)(
      blockName,
      import_color.COLOR_SUPPORT_KEY,
      elementType
    );
    if (skipSerialization) {
      return;
    }
    const elementStyles = blockElementStyles?.[elementType];
    if (elementStyles) {
      const selector = (0, import_utils2.scopeSelector)(
        baseSelector,
        import_blocks.__EXPERIMENTAL_ELEMENTS[elementType]
      );
      rules.push((0, import_style_engine.compileCSS)(elementStyles, { selector }));
      if (pseudo) {
        pseudo.forEach((pseudoSelector) => {
          if (elementStyles[pseudoSelector]) {
            rules.push(
              (0, import_style_engine.compileCSS)(elementStyles[pseudoSelector], {
                selector: (0, import_utils2.scopeSelector)(
                  baseSelector,
                  `${import_blocks.__EXPERIMENTAL_ELEMENTS[elementType]}${pseudoSelector}`
                )
              })
            );
          }
        });
      }
    }
    if (elements) {
      elements.forEach((element) => {
        if (blockElementStyles[element]) {
          rules.push(
            (0, import_style_engine.compileCSS)(blockElementStyles[element], {
              selector: (0, import_utils2.scopeSelector)(
                baseSelector,
                import_blocks.__EXPERIMENTAL_ELEMENTS[element]
              )
            })
          );
        }
      });
    }
  });
  return rules.length > 0 ? rules.join("") : void 0;
}
function useBlockProps({ name, style }) {
  const blockElementsContainerIdentifier = (0, import_compose.useInstanceId)(
    STYLE_BLOCK_PROPS_REFERENCE,
    "wp-elements"
  );
  const baseElementSelector = `.${blockElementsContainerIdentifier}`;
  const blockElementStyles = style?.elements;
  const styles = (0, import_element.useMemo)(() => {
    const cssRules = [];
    const elementCSS = getElementCSSRules(
      blockElementStyles,
      name,
      baseElementSelector
    );
    if (elementCSS) {
      cssRules.push(elementCSS);
    }
    cssRules.push(
      ...getPseudoStateCSSRules(style, name, baseElementSelector)
    );
    cssRules.push(
      ...getResponsiveStateCSSRules(style, name, baseElementSelector)
    );
    return cssRules.length > 0 ? cssRules.join("") : void 0;
  }, [baseElementSelector, blockElementStyles, name, style]);
  (0, import_utils.useStyleOverride)({ css: styles });
  return addSaveProps(
    { className: blockElementsContainerIdentifier },
    name,
    { style },
    skipSerializationPathsEdit
  );
}
(0, import_hooks.addFilter)(
  "blocks.registerBlockType",
  "core/style/addAttribute",
  addAttribute
);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  addSaveProps,
  getBlockStateStylesCSS,
  getCanvasStateStyleValue,
  getInlineStyles,
  getResponsiveStateCSSRules,
  getStateStylesCSS,
  omitStyle
});
//# sourceMappingURL=style.cjs.map
