// packages/block-editor/src/hooks/style.js
import { useMemo } from "@wordpress/element";
import { addFilter } from "@wordpress/hooks";
import { useSelect } from "@wordpress/data";
import { mergeGlobalStyles } from "@wordpress/global-styles-engine";
import {
  getBlockSupport,
  getBlockType,
  hasBlockSupport,
  __EXPERIMENTAL_ELEMENTS as ELEMENTS
} from "@wordpress/blocks";
import { useInstanceId } from "@wordpress/compose";
import { getCSSRules, compileCSS } from "@wordpress/style-engine";
import { BACKGROUND_SUPPORT_KEY, BackgroundImagePanel } from "./background.mjs";
import { BORDER_SUPPORT_KEY, BorderPanel, SHADOW_SUPPORT_KEY } from "./border.mjs";
import { COLOR_SUPPORT_KEY } from "./color.mjs";
import { ElementsEdit } from "./elements.mjs";
import {
  TypographyPanel,
  TYPOGRAPHY_SUPPORT_KEY,
  TYPOGRAPHY_SUPPORT_KEYS
} from "./typography.mjs";
import {
  DIMENSIONS_SUPPORT_KEY,
  SPACING_SUPPORT_KEY,
  DimensionsPanel,
  isExplicitAspectRatio
} from "./dimensions.mjs";
import {
  cleanEmptyObject,
  shouldSkipSerialization,
  useStyleOverride,
  useBlockSettings
} from "./utils.mjs";
import {
  BlockStyleStateProvider,
  DEFAULT_BLOCK_STYLE_STATE,
  getStyleForState,
  hasViewportBlockStyleState,
  hasPseudoBlockStyleState
} from "./block-style-state.mjs";
import { VALID_BLOCK_PSEUDO_STATES } from "./states.mjs";
import { buildScopedBlockSelector } from "./state-utils.mjs";
import { scopeSelector } from "../components/global-styles/utils.mjs";
import { useBlockEditingMode } from "../components/block-editing-mode/index.mjs";
import { store as blockEditorStore } from "../store/index.mjs";
import { globalStylesDataKey } from "../store/private-keys.mjs";
import { unlock } from "../lock-unlock.mjs";
import { jsx, jsxs } from "react/jsx-runtime";
var BORDER_SIDES = ["Top", "Right", "Bottom", "Left"];
var RESPONSIVE_BREAKPOINTS = {
  "@mobile": "@media (width <= 480px)",
  "@tablet": "@media (480px < width <= 782px)"
};
var styleSupportKeys = [
  ...TYPOGRAPHY_SUPPORT_KEYS,
  BORDER_SUPPORT_KEY,
  COLOR_SUPPORT_KEY,
  DIMENSIONS_SUPPORT_KEY,
  BACKGROUND_SUPPORT_KEY,
  SPACING_SUPPORT_KEY,
  SHADOW_SUPPORT_KEY
];
var hasStyleSupport = (nameOrType) => styleSupportKeys.some((key) => hasBlockSupport(nameOrType, key));
function getInlineStyles(styles = {}) {
  const output = {};
  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 cleanEmptyObject({ border: 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 (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 = compileCSS(stylesWithDimensionFallbacks, { selector });
  const importantCSS = css ? css.replace(/;/g, " !important;") : void 0;
  const fallbackBorderStyles = getStateFallbackBorderStyles(stateStyles);
  const fallbackCSS = fallbackBorderStyles ? 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 = 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,
      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 = 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 = VALID_BLOCK_PSEUDO_STATES[name] ?? [];
  const nestedStateKeys = ["elements", ...validPseudoStates];
  Object.entries(RESPONSIVE_BREAKPOINTS).forEach(
    ([viewport, mediaQuery]) => {
      const viewportStyles = getStyleForState(style, {
        viewport,
        pseudo: 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 = getStyleForState(style, selectedState);
  if (!hasViewportBlockStyleState(selectedState)) {
    return stateValue;
  }
  const defaultViewportState = {
    ...selectedState,
    viewport: DEFAULT_BLOCK_STYLE_STATE.viewport
  };
  const defaultViewportStateValue = getStyleForState(
    style,
    defaultViewportState
  );
  if (defaultViewportStateValue && stateValue) {
    return mergeGlobalStyles(defaultViewportStateValue, stateValue);
  }
  return stateValue || defaultViewportStateValue;
}
function addAttribute(settings) {
  if (!hasStyleSupport(settings) && !hasBlockSupport(settings, "customCSS", true)) {
    return settings;
  }
  if (!settings.attributes.style) {
    Object.assign(settings.attributes, {
      style: {
        type: "object"
      }
    });
  }
  return settings;
}
var skipSerializationPathsEdit = {
  [`${BORDER_SUPPORT_KEY}.__experimentalSkipSerialization`]: ["border"],
  [`${COLOR_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    COLOR_SUPPORT_KEY
  ],
  [`${TYPOGRAPHY_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    TYPOGRAPHY_SUPPORT_KEY
  ],
  [`${DIMENSIONS_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    DIMENSIONS_SUPPORT_KEY
  ],
  [`${SPACING_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    SPACING_SUPPORT_KEY
  ],
  [`${SHADOW_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
    SHADOW_SUPPORT_KEY
  ]
};
var skipSerializationPathsSave = {
  ...skipSerializationPathsEdit,
  [`${DIMENSIONS_SUPPORT_KEY}.aspectRatio`]: [
    `${DIMENSIONS_SUPPORT_KEY}.aspectRatio`
  ],
  // Skip serialization of aspect ratio in save mode.
  [`${BACKGROUND_SUPPORT_KEY}`]: [BACKGROUND_SUPPORT_KEY]
  // Skip serialization of background support in save mode.
};
var skipSerializationPathsSaveChecks = {
  [`${DIMENSIONS_SUPPORT_KEY}.aspectRatio`]: true,
  [`${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] || 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 = useBlockSettings(name, __unstableParentLayout);
  const blockEditingMode = useBlockEditingMode();
  const { globalBlockStyles, selectedState, showStateOnCanvas } = useSelect(
    (select) => {
      const blockEditorSelect = select(blockEditorStore);
      const {
        getSelectedBlockStyleState,
        isSelectedBlockStyleStateShownOnCanvas
      } = unlock(blockEditorSelect);
      const editorSettings = blockEditorSelect.getSettings();
      return {
        globalBlockStyles: editorSettings?.[globalStylesDataKey]?.blocks?.[name],
        selectedState: getSelectedBlockStyleState(clientId),
        showStateOnCanvas: isSelectedBlockStyleStateShownOnCanvas(clientId)
      };
    },
    [clientId, name]
  );
  const isPseudoSelectorState = hasPseudoBlockStyleState(selectedState);
  const canvasStateCSS = useMemo(() => {
    if (!showStateOnCanvas || !isPseudoSelectorState) {
      return void 0;
    }
    const globalStateValue = getCanvasStateStyleValue(
      globalBlockStyles,
      selectedState
    );
    const instanceStateValue = getCanvasStateStyleValue(
      style,
      selectedState
    );
    let stateValue;
    if (globalStateValue && instanceStateValue) {
      stateValue = 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
  ]);
  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__ */ jsxs(BlockStyleStateProvider, { value: selectedState, children: [
    /* @__PURE__ */ jsx(ElementsEdit, { ...passedProps }),
    /* @__PURE__ */ jsx(BackgroundImagePanel, { ...passedProps }),
    /* @__PURE__ */ jsx(TypographyPanel, { ...passedProps }),
    /* @__PURE__ */ jsx(BorderPanel, { ...passedProps }),
    /* @__PURE__ */ jsx(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 = shouldSkipSerialization(
      blockName,
      COLOR_SUPPORT_KEY,
      elementType
    );
    if (skipSerialization) {
      return;
    }
    const elementStyles = blockElementStyles?.[elementType];
    if (elementStyles) {
      const selector = scopeSelector(
        baseSelector,
        ELEMENTS[elementType]
      );
      rules.push(compileCSS(elementStyles, { selector }));
      if (pseudo) {
        pseudo.forEach((pseudoSelector) => {
          if (elementStyles[pseudoSelector]) {
            rules.push(
              compileCSS(elementStyles[pseudoSelector], {
                selector: scopeSelector(
                  baseSelector,
                  `${ELEMENTS[elementType]}${pseudoSelector}`
                )
              })
            );
          }
        });
      }
    }
    if (elements) {
      elements.forEach((element) => {
        if (blockElementStyles[element]) {
          rules.push(
            compileCSS(blockElementStyles[element], {
              selector: scopeSelector(
                baseSelector,
                ELEMENTS[element]
              )
            })
          );
        }
      });
    }
  });
  return rules.length > 0 ? rules.join("") : void 0;
}
function useBlockProps({ name, style }) {
  const blockElementsContainerIdentifier = useInstanceId(
    STYLE_BLOCK_PROPS_REFERENCE,
    "wp-elements"
  );
  const baseElementSelector = `.${blockElementsContainerIdentifier}`;
  const blockElementStyles = style?.elements;
  const styles = 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]);
  useStyleOverride({ css: styles });
  return addSaveProps(
    { className: blockElementsContainerIdentifier },
    name,
    { style },
    skipSerializationPathsEdit
  );
}
addFilter(
  "blocks.registerBlockType",
  "core/style/addAttribute",
  addAttribute
);
export {
  addSaveProps,
  style_default as default,
  getBlockStateStylesCSS,
  getCanvasStateStyleValue,
  getInlineStyles,
  getResponsiveStateCSSRules,
  getStateStylesCSS,
  omitStyle
};
//# sourceMappingURL=style.mjs.map
