"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/layout.js
var layout_exports = {};
__export(layout_exports, {
  addAttribute: () => addAttribute,
  default: () => layout_default,
  getResetLayout: () => getResetLayout,
  getResponsiveLayoutStyles: () => getResponsiveLayoutStyles,
  useLayoutClasses: () => useLayoutClasses,
  useLayoutStyles: () => useLayoutStyles,
  withLayoutStyles: () => withLayoutStyles
});
module.exports = __toCommonJS(layout_exports);
var import_clsx = __toESM(require("clsx"));
var import_compose = require("@wordpress/compose");
var import_hooks = require("@wordpress/hooks");
var import_element = require("@wordpress/element");
var import_blocks = require("@wordpress/blocks");
var import_data = require("@wordpress/data");
var import_components = require("@wordpress/components");
var import_i18n = require("@wordpress/i18n");
var import_store = require("../store/index.cjs");
var import_components2 = require("../components/index.cjs");
var import_use_settings = require("../components/use-settings/index.cjs");
var import_layouts = require("../layouts/index.cjs");
var import_block_editing_mode = require("../components/block-editing-mode/index.cjs");
var import_definitions = require("../layouts/definitions.cjs");
var import_utils = require("./utils.cjs");
var import_lock_unlock = require("../lock-unlock.cjs");
var import_private_keys = require("../store/private-keys.cjs");
var import_block_style_variation = require("./block-style-variation.cjs");
var import_block_style_state = require("./block-style-state.cjs");
var import_jsx_runtime = require("react/jsx-runtime");
var VARIATION_PREFIX = "is-style-";
var layoutBlockSupportKey = "layout";
var RESPONSIVE_BREAKPOINTS = {
  "@mobile": "@media (width <= 480px)",
  "@tablet": "@media (480px < width <= 782px)"
};
var CHILD_LAYOUT_KEYS = [
  "selfStretch",
  "flexSize",
  "columnStart",
  "columnSpan",
  "rowStart",
  "rowSpan"
];
var { kebabCase } = (0, import_lock_unlock.unlock)(import_components.privateApis);
function getDefaultLayout(layoutBlockSupport = {}, blockVariation) {
  const defaultBlockLayout = layoutBlockSupport?.default;
  return blockVariation?.attributes?.layout ?? defaultBlockLayout;
}
function getResetLayout(layoutBlockSupport = {}, blockVariation) {
  return (0, import_utils.cleanEmptyObject)({
    ...getDefaultLayout(layoutBlockSupport, blockVariation)
  });
}
function getLayoutStateOverrides(layout = {}, baseLayout = {}, existingLayout = {}) {
  const overrides = {};
  const childLayoutValues = Object.fromEntries(
    CHILD_LAYOUT_KEYS.filter(
      (key) => Object.hasOwn(existingLayout || {}, key)
    ).map((key) => [key, existingLayout[key]])
  );
  Object.entries(layout || {}).forEach(([key, value]) => {
    if (!CHILD_LAYOUT_KEYS.includes(key) && value !== baseLayout?.[key]) {
      overrides[key] = value;
    }
  });
  return (0, import_utils.cleanEmptyObject)({
    ...childLayoutValues,
    ...overrides
  });
}
function getLayoutContainerValues(layout = {}) {
  return Object.fromEntries(
    Object.entries(layout || {}).filter(
      ([key]) => !CHILD_LAYOUT_KEYS.includes(key)
    )
  );
}
function hasLayoutBlockSupport(blockName) {
  return (0, import_blocks.hasBlockSupport)(blockName, "layout") || (0, import_blocks.hasBlockSupport)(blockName, "__experimentalLayout");
}
function useLayoutClasses(blockAttributes = {}, blockName = "") {
  const { layout } = blockAttributes;
  const { default: defaultBlockLayout } = (0, import_blocks.getBlockSupport)(blockName, layoutBlockSupportKey) || {};
  const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || defaultBlockLayout || {};
  const layoutClassnames = [];
  if (import_definitions.LAYOUT_DEFINITIONS[usedLayout?.type || "default"]?.className) {
    const baseClassName = import_definitions.LAYOUT_DEFINITIONS[usedLayout?.type || "default"]?.className;
    const splitBlockName = blockName.split("/");
    const fullBlockName = splitBlockName[0] === "core" ? splitBlockName.pop() : splitBlockName.join("-");
    const compoundClassName = `wp-block-${fullBlockName}-${baseClassName}`;
    layoutClassnames.push(baseClassName, compoundClassName);
  }
  const hasGlobalPadding = (0, import_data.useSelect)(
    (select) => {
      if (!usedLayout?.inherit && !usedLayout?.contentSize && usedLayout?.type !== "constrained") {
        return false;
      }
      return select(import_store.store).getSettings().__experimentalFeatures?.useRootPaddingAwareAlignments;
    },
    [usedLayout?.contentSize, usedLayout?.inherit, usedLayout?.type]
  );
  if (hasGlobalPadding) {
    layoutClassnames.push("has-global-padding");
  }
  if (usedLayout?.orientation) {
    layoutClassnames.push(`is-${kebabCase(usedLayout.orientation)}`);
  }
  if (usedLayout?.justifyContent) {
    layoutClassnames.push(
      `is-content-justification-${kebabCase(
        usedLayout.justifyContent
      )}`
    );
  }
  if (usedLayout?.flexWrap && usedLayout.flexWrap === "nowrap") {
    layoutClassnames.push("is-nowrap");
  }
  return layoutClassnames;
}
function useLayoutStyles(blockAttributes = {}, blockName, selector) {
  const { layout = {}, style = {} } = blockAttributes;
  const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || {};
  const fullLayoutType = (0, import_layouts.getLayoutType)(usedLayout?.type || "default");
  const [blockGapSupport] = (0, import_use_settings.useSettings)("spacing.blockGap");
  const hasBlockGapSupport = blockGapSupport !== null;
  return fullLayoutType?.getLayoutStyle?.({
    blockName,
    selector,
    layout,
    style,
    hasBlockGapSupport
  });
}
function getResponsiveLayoutStyles({
  attributes = {},
  blockName,
  selector,
  layout = {},
  hasBlockGapSupport,
  globalBlockGapValue
}) {
  return Object.entries(RESPONSIVE_BREAKPOINTS).map(([viewport, mediaQuery]) => {
    const viewportStyle = (0, import_block_style_state.getStyleForState)(attributes?.style, {
      viewport,
      pseudo: import_block_style_state.DEFAULT_BLOCK_STYLE_STATE.pseudo
    });
    const viewportLayout = getLayoutContainerValues(
      viewportStyle?.layout
    );
    const hasViewportLayout = Object.keys(viewportLayout).length > 0;
    const hasViewportBlockGap = viewportStyle?.spacing && Object.hasOwn(viewportStyle.spacing, "blockGap");
    const hasViewportPadding = viewportStyle?.spacing && Object.hasOwn(viewportStyle.spacing, "padding");
    if (!hasViewportLayout && !hasViewportBlockGap && !hasViewportPadding) {
      return "";
    }
    const layoutType = (0, import_layouts.getLayoutType)(layout?.type || "default");
    const viewportCSS = layoutType?.getLayoutStyle?.({
      blockName,
      selector,
      layout,
      viewportOverrides: viewportLayout,
      style: viewportStyle,
      hasBlockGapSupport,
      globalBlockGapValue
    });
    return viewportCSS ? `${mediaQuery}{${viewportCSS}}` : "";
  }).filter(Boolean).join("");
}
function LayoutPanelPure({
  layout,
  style,
  setAttributes,
  name: blockName,
  clientId
}) {
  const settings = (0, import_utils.useBlockSettings)(blockName);
  const { layout: layoutSettings } = settings;
  const { themeSupportsLayout, activeBlockVariation, selectedState } = (0, import_data.useSelect)(
    (select) => {
      const blockEditorSelect = select(import_store.store);
      const { getBlockAttributes, getSettings } = blockEditorSelect;
      const { getSelectedBlockStyleState } = (0, import_lock_unlock.unlock)(blockEditorSelect);
      return {
        activeBlockVariation: select(
          import_blocks.store
        ).getActiveBlockVariation(
          blockName,
          getBlockAttributes(clientId) || {},
          "block"
        ),
        themeSupportsLayout: getSettings().supportsLayout,
        selectedState: getSelectedBlockStyleState?.(clientId) ?? import_block_style_state.DEFAULT_BLOCK_STYLE_STATE
      };
    },
    [blockName, clientId]
  );
  const blockEditingMode = (0, import_block_editing_mode.useBlockEditingMode)();
  const isViewportLayoutState = (0, import_block_style_state.hasViewportBlockStyleState)(selectedState) && !(0, import_block_style_state.hasPseudoBlockStyleState)(selectedState);
  const resetLayoutFilter = (0, import_element.useCallback)(
    (...resetArgs) => {
      const attributes = resetArgs[0] || {};
      const context = resetArgs[1] || {};
      if (isViewportLayoutState) {
        const existingStateStyle = (0, import_block_style_state.getStyleForState)(
          attributes.style ?? style,
          selectedState
        ) || {};
        const nextStateStyle = (0, import_utils.cleanEmptyObject)({
          ...existingStateStyle,
          layout: void 0
        });
        return {
          style: (0, import_block_style_state.setStyleForState)(
            attributes.style ?? style,
            selectedState,
            nextStateStyle
          )
        };
      }
      const resetBlockName = context.name || blockName;
      const resetLayoutBlockSupport = (0, import_blocks.getBlockSupport)(
        resetBlockName,
        layoutBlockSupportKey,
        {}
      );
      return {
        layout: getResetLayout(
          resetLayoutBlockSupport,
          activeBlockVariation
        )
      };
    },
    [
      blockName,
      activeBlockVariation,
      isViewportLayoutState,
      selectedState,
      style
    ]
  );
  if (blockEditingMode !== "default") {
    return null;
  }
  const layoutBlockSupport = (0, import_blocks.getBlockSupport)(
    blockName,
    layoutBlockSupportKey,
    {}
  );
  const blockSupportAndThemeSettings = {
    ...layoutSettings,
    ...layoutBlockSupport
  };
  const {
    allowSwitching,
    allowEditing = true,
    allowInheriting = true,
    default: defaultBlockLayout
  } = blockSupportAndThemeSettings;
  if (!allowEditing) {
    return null;
  }
  const baseLayout = layout || defaultBlockLayout || {};
  const stateStyle = isViewportLayoutState ? (0, import_block_style_state.getStyleForState)(style, selectedState) : void 0;
  const stateLayout = stateStyle?.layout;
  const usedLayout = isViewportLayoutState ? (0, import_utils.cleanEmptyObject)({
    ...baseLayout,
    ...stateLayout
  }) || {} : baseLayout;
  const resetLayoutDefaults = isViewportLayoutState ? baseLayout : getResetLayout(layoutBlockSupport, activeBlockVariation);
  const blockSupportAndLayout = {
    ...layoutBlockSupport,
    ...usedLayout
  };
  const { type, default: { type: defaultType = "default" } = {} } = blockSupportAndLayout;
  const blockLayoutType = type || defaultType;
  const showInheritToggle = !!(allowInheriting && (!blockLayoutType || blockLayoutType === "default" || blockLayoutType === "constrained" || blockSupportAndLayout.inherit));
  const { inherit = false, contentSize = null } = usedLayout;
  if ((blockLayoutType === "default" || blockLayoutType === "constrained") && !themeSupportsLayout) {
    return null;
  }
  const layoutType = (0, import_layouts.getLayoutType)(blockLayoutType);
  const constrainedType = (0, import_layouts.getLayoutType)("constrained");
  const displayControlsForLegacyLayouts = !usedLayout.type && (contentSize || inherit);
  const hasContentSizeOrLegacySettings = !!inherit || !!contentSize;
  const showLayoutTypeSwitcher = (0, import_block_style_state.isDefaultBlockStyleState)(selectedState) && !inherit && allowSwitching;
  const onChangeLayout = (newLayout) => {
    if (isViewportLayoutState) {
      const nextStateStyle = (0, import_utils.cleanEmptyObject)({
        ...stateStyle,
        layout: getLayoutStateOverrides(
          (0, import_utils.cleanEmptyObject)(newLayout),
          baseLayout,
          stateStyle?.layout
        )
      });
      setAttributes({
        style: (0, import_block_style_state.setStyleForState)(style, selectedState, nextStateStyle)
      });
      return;
    }
    setAttributes({ layout: (0, import_utils.cleanEmptyObject)(newLayout) });
  };
  const onChangeType = (newType) => onChangeLayout({ type: newType });
  const resetLayout = () => onChangeLayout(resetLayoutDefaults);
  const resetInheritToggle = () => onChangeLayout({ type: "default" });
  const isUsingContentWidth = () => layoutType?.name === "constrained" || hasContentSizeOrLegacySettings;
  const hasInheritToggleValue = () => isViewportLayoutState ? (usedLayout?.type ?? "default") !== (resetLayoutDefaults?.type ?? "default") : layout?.type === "constrained";
  const hasLayoutTypeValue = () => (usedLayout?.type ?? "default") !== (resetLayoutDefaults?.type ?? "default");
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
      import_components2.InspectorControls,
      {
        group: "layout",
        resetAllFilter: resetLayoutFilter,
        children: [
          showInheritToggle && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_components.__experimentalToolsPanelItem,
            {
              label: (0, import_i18n.__)("Use content width"),
              hasValue: hasInheritToggleValue,
              onDeselect: resetInheritToggle,
              isShownByDefault: true,
              panelId: clientId,
              children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                import_components.ToggleControl,
                {
                  label: (0, import_i18n.__)("Inner blocks use content width"),
                  checked: isUsingContentWidth(),
                  onChange: () => onChangeLayout({
                    type: isUsingContentWidth() ? "default" : "constrained"
                  }),
                  help: isUsingContentWidth() ? (0, import_i18n.__)(
                    "Nested blocks use content width with options for full and wide widths."
                  ) : (0, import_i18n.__)(
                    "Nested blocks will fill the width of this container."
                  )
                }
              )
            }
          ),
          showLayoutTypeSwitcher && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_components.__experimentalToolsPanelItem,
            {
              label: (0, import_i18n.__)("Layout type"),
              hasValue: hasLayoutTypeValue,
              onDeselect: resetLayout,
              isShownByDefault: true,
              panelId: clientId,
              children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                LayoutTypeSwitcher,
                {
                  type: blockLayoutType,
                  onChange: onChangeType
                }
              )
            }
          ),
          layoutType && layoutType.name !== "default" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            layoutType.inspectorControls,
            {
              layout: usedLayout,
              value: layout,
              onChange: onChangeLayout,
              layoutBlockSupport: blockSupportAndThemeSettings,
              resetLayout: resetLayoutDefaults,
              name: blockName,
              clientId
            }
          ),
          constrainedType && displayControlsForLegacyLayouts && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            constrainedType.inspectorControls,
            {
              layout: usedLayout,
              value: layout,
              onChange: onChangeLayout,
              layoutBlockSupport: blockSupportAndThemeSettings,
              resetLayout: resetLayoutDefaults,
              name: blockName,
              clientId
            }
          )
        ]
      }
    ),
    !inherit && layoutType && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      layoutType.toolBarControls,
      {
        layout: usedLayout,
        onChange: onChangeLayout,
        layoutBlockSupport,
        name: blockName,
        clientId
      }
    )
  ] });
}
var layout_default = {
  shareWithChildBlocks: true,
  edit: LayoutPanelPure,
  attributeKeys: ["layout", "style"],
  hasSupport(name) {
    return hasLayoutBlockSupport(name);
  }
};
function LayoutTypeSwitcher({ type, onChange }) {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    import_components.__experimentalToggleGroupControl,
    {
      __next40pxDefaultSize: true,
      isBlock: true,
      label: (0, import_i18n.__)("Layout type"),
      hideLabelFromVision: true,
      isAdaptiveWidth: true,
      value: type,
      onChange,
      children: (0, import_layouts.getLayoutTypes)().map(({ name, label }) => {
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
          import_components.__experimentalToggleGroupControlOption,
          {
            value: name,
            label
          },
          name
        );
      })
    }
  );
}
function addAttribute(settings) {
  if ("type" in (settings.attributes?.layout ?? {})) {
    return settings;
  }
  if (hasLayoutBlockSupport(settings)) {
    settings.attributes = {
      ...settings.attributes,
      layout: {
        type: "object"
      }
    };
  }
  return settings;
}
function BlockWithLayoutStyles({
  block: BlockListBlock,
  props,
  blockGapSupport,
  globalBlockGapValue,
  layoutClasses
}) {
  const { name, attributes } = props;
  const id = (0, import_compose.useInstanceId)(BlockListBlock);
  const { layout } = attributes;
  const { default: defaultBlockLayout } = (0, import_blocks.getBlockSupport)(name, layoutBlockSupportKey) || {};
  const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || defaultBlockLayout || {};
  const selectorPrefix = `wp-container-${kebabCase(name)}-is-layout-`;
  const selector = `.${selectorPrefix}${id}`;
  const hasBlockGapSupport = blockGapSupport !== null;
  const fullLayoutType = (0, import_layouts.getLayoutType)(usedLayout?.type || "default");
  const baseLayoutCSS = fullLayoutType?.getLayoutStyle?.({
    blockName: name,
    selector,
    layout: usedLayout,
    style: attributes?.style,
    hasBlockGapSupport,
    globalBlockGapValue
  });
  const responsiveLayoutCSS = getResponsiveLayoutStyles({
    attributes,
    blockName: name,
    selector,
    layout: usedLayout,
    hasBlockGapSupport,
    globalBlockGapValue
  });
  const css = [baseLayoutCSS, responsiveLayoutCSS].filter(Boolean).join("");
  const layoutClassNames = (0, import_clsx.default)(
    {
      [`${selectorPrefix}${id}`]: !!css
      // Only attach a container class if there is generated CSS to be attached.
    },
    layoutClasses
  );
  (0, import_utils.useStyleOverride)({ css });
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    BlockListBlock,
    {
      ...props,
      __unstableLayoutClassNames: layoutClassNames
    }
  );
}
var withLayoutStyles = (0, import_compose.createHigherOrderComponent)(
  (BlockListBlock) => function WithLayoutStyles(props) {
    const { clientId, name, attributes } = props;
    const blockSupportsLayout = hasLayoutBlockSupport(name);
    const layoutClasses = useLayoutClasses(attributes, name);
    const extraProps = (0, import_data.useSelect)(
      (select) => {
        if (!blockSupportsLayout) {
          return;
        }
        const { getSettings, getBlockSettings } = (0, import_lock_unlock.unlock)(
          select(import_store.store)
        );
        const settings = getSettings();
        const { disableLayoutStyles } = settings;
        if (disableLayoutStyles) {
          return;
        }
        const [blockGapSupport] = getBlockSettings(
          clientId,
          "spacing.blockGap"
        );
        const globalStyles = settings[import_private_keys.globalStylesDataKey];
        let variationBlockGapValue;
        const className = attributes?.className;
        if (className?.includes(VARIATION_PREFIX)) {
          const { getBlockStyles } = select(import_blocks.store);
          const registeredStyles = getBlockStyles(name);
          const variationName = (0, import_block_style_variation.getVariationNameFromClass)(
            className,
            registeredStyles
          );
          variationBlockGapValue = variationName ? globalStyles?.blocks?.[name]?.variations?.[variationName]?.spacing?.blockGap : void 0;
        }
        const globalBlockGapValue = variationBlockGapValue ?? globalStyles?.blocks?.[name]?.spacing?.blockGap ?? globalStyles?.spacing?.blockGap;
        return { blockGapSupport, globalBlockGapValue };
      },
      [blockSupportsLayout, clientId, attributes?.className, name]
    );
    if (!extraProps) {
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        BlockListBlock,
        {
          ...props,
          __unstableLayoutClassNames: blockSupportsLayout ? layoutClasses : void 0
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      BlockWithLayoutStyles,
      {
        block: BlockListBlock,
        props,
        layoutClasses,
        ...extraProps
      }
    );
  },
  "withLayoutStyles"
);
(0, import_hooks.addFilter)(
  "blocks.registerBlockType",
  "core/layout/addAttribute",
  addAttribute
);
(0, import_hooks.addFilter)(
  "editor.BlockListBlock",
  "core/editor/layout/with-layout-styles",
  withLayoutStyles
);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  addAttribute,
  getResetLayout,
  getResponsiveLayoutStyles,
  useLayoutClasses,
  useLayoutStyles,
  withLayoutStyles
});
//# sourceMappingURL=layout.cjs.map
