// packages/block-editor/src/hooks/layout.js
import clsx from "clsx";
import { createHigherOrderComponent, useInstanceId } from "@wordpress/compose";
import { addFilter } from "@wordpress/hooks";
import { useCallback } from "@wordpress/element";
import {
  getBlockSupport,
  hasBlockSupport,
  store as blocksStore
} from "@wordpress/blocks";
import { useSelect } from "@wordpress/data";
import {
  __experimentalToggleGroupControl as ToggleGroupControl,
  __experimentalToggleGroupControlOption as ToggleGroupControlOption,
  ToggleControl,
  __experimentalToolsPanelItem as ToolsPanelItem,
  privateApis as componentsPrivateApis
} from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { store as blockEditorStore } from "../store/index.mjs";
import { InspectorControls } from "../components/index.mjs";
import { useSettings } from "../components/use-settings/index.mjs";
import { getLayoutType, getLayoutTypes } from "../layouts/index.mjs";
import { useBlockEditingMode } from "../components/block-editing-mode/index.mjs";
import { LAYOUT_DEFINITIONS } from "../layouts/definitions.mjs";
import { cleanEmptyObject, useBlockSettings, useStyleOverride } from "./utils.mjs";
import { unlock } from "../lock-unlock.mjs";
import { globalStylesDataKey } from "../store/private-keys.mjs";
import { getVariationNameFromClass } from "./block-style-variation.mjs";
import {
  DEFAULT_BLOCK_STYLE_STATE,
  getStyleForState,
  hasPseudoBlockStyleState,
  hasViewportBlockStyleState,
  isDefaultBlockStyleState,
  setStyleForState
} from "./block-style-state.mjs";
import { Fragment, jsx, jsxs } from "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 } = unlock(componentsPrivateApis);
function getDefaultLayout(layoutBlockSupport = {}, blockVariation) {
  const defaultBlockLayout = layoutBlockSupport?.default;
  return blockVariation?.attributes?.layout ?? defaultBlockLayout;
}
function getResetLayout(layoutBlockSupport = {}, blockVariation) {
  return 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 cleanEmptyObject({
    ...childLayoutValues,
    ...overrides
  });
}
function getLayoutContainerValues(layout = {}) {
  return Object.fromEntries(
    Object.entries(layout || {}).filter(
      ([key]) => !CHILD_LAYOUT_KEYS.includes(key)
    )
  );
}
function hasLayoutBlockSupport(blockName) {
  return hasBlockSupport(blockName, "layout") || hasBlockSupport(blockName, "__experimentalLayout");
}
function useLayoutClasses(blockAttributes = {}, blockName = "") {
  const { layout } = blockAttributes;
  const { default: defaultBlockLayout } = getBlockSupport(blockName, layoutBlockSupportKey) || {};
  const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || defaultBlockLayout || {};
  const layoutClassnames = [];
  if (LAYOUT_DEFINITIONS[usedLayout?.type || "default"]?.className) {
    const baseClassName = 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 = useSelect(
    (select) => {
      if (!usedLayout?.inherit && !usedLayout?.contentSize && usedLayout?.type !== "constrained") {
        return false;
      }
      return select(blockEditorStore).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 = getLayoutType(usedLayout?.type || "default");
  const [blockGapSupport] = 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 = getStyleForState(attributes?.style, {
      viewport,
      pseudo: 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 = 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 = useBlockSettings(blockName);
  const { layout: layoutSettings } = settings;
  const { themeSupportsLayout, activeBlockVariation, selectedState } = useSelect(
    (select) => {
      const blockEditorSelect = select(blockEditorStore);
      const { getBlockAttributes, getSettings } = blockEditorSelect;
      const { getSelectedBlockStyleState } = unlock(blockEditorSelect);
      return {
        activeBlockVariation: select(
          blocksStore
        ).getActiveBlockVariation(
          blockName,
          getBlockAttributes(clientId) || {},
          "block"
        ),
        themeSupportsLayout: getSettings().supportsLayout,
        selectedState: getSelectedBlockStyleState?.(clientId) ?? DEFAULT_BLOCK_STYLE_STATE
      };
    },
    [blockName, clientId]
  );
  const blockEditingMode = useBlockEditingMode();
  const isViewportLayoutState = hasViewportBlockStyleState(selectedState) && !hasPseudoBlockStyleState(selectedState);
  const resetLayoutFilter = useCallback(
    (...resetArgs) => {
      const attributes = resetArgs[0] || {};
      const context = resetArgs[1] || {};
      if (isViewportLayoutState) {
        const existingStateStyle = getStyleForState(
          attributes.style ?? style,
          selectedState
        ) || {};
        const nextStateStyle = cleanEmptyObject({
          ...existingStateStyle,
          layout: void 0
        });
        return {
          style: setStyleForState(
            attributes.style ?? style,
            selectedState,
            nextStateStyle
          )
        };
      }
      const resetBlockName = context.name || blockName;
      const resetLayoutBlockSupport = getBlockSupport(
        resetBlockName,
        layoutBlockSupportKey,
        {}
      );
      return {
        layout: getResetLayout(
          resetLayoutBlockSupport,
          activeBlockVariation
        )
      };
    },
    [
      blockName,
      activeBlockVariation,
      isViewportLayoutState,
      selectedState,
      style
    ]
  );
  if (blockEditingMode !== "default") {
    return null;
  }
  const layoutBlockSupport = 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 ? getStyleForState(style, selectedState) : void 0;
  const stateLayout = stateStyle?.layout;
  const usedLayout = isViewportLayoutState ? 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 = getLayoutType(blockLayoutType);
  const constrainedType = getLayoutType("constrained");
  const displayControlsForLegacyLayouts = !usedLayout.type && (contentSize || inherit);
  const hasContentSizeOrLegacySettings = !!inherit || !!contentSize;
  const showLayoutTypeSwitcher = isDefaultBlockStyleState(selectedState) && !inherit && allowSwitching;
  const onChangeLayout = (newLayout) => {
    if (isViewportLayoutState) {
      const nextStateStyle = cleanEmptyObject({
        ...stateStyle,
        layout: getLayoutStateOverrides(
          cleanEmptyObject(newLayout),
          baseLayout,
          stateStyle?.layout
        )
      });
      setAttributes({
        style: setStyleForState(style, selectedState, nextStateStyle)
      });
      return;
    }
    setAttributes({ layout: 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__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(
      InspectorControls,
      {
        group: "layout",
        resetAllFilter: resetLayoutFilter,
        children: [
          showInheritToggle && /* @__PURE__ */ jsx(
            ToolsPanelItem,
            {
              label: __("Use content width"),
              hasValue: hasInheritToggleValue,
              onDeselect: resetInheritToggle,
              isShownByDefault: true,
              panelId: clientId,
              children: /* @__PURE__ */ jsx(
                ToggleControl,
                {
                  label: __("Inner blocks use content width"),
                  checked: isUsingContentWidth(),
                  onChange: () => onChangeLayout({
                    type: isUsingContentWidth() ? "default" : "constrained"
                  }),
                  help: isUsingContentWidth() ? __(
                    "Nested blocks use content width with options for full and wide widths."
                  ) : __(
                    "Nested blocks will fill the width of this container."
                  )
                }
              )
            }
          ),
          showLayoutTypeSwitcher && /* @__PURE__ */ jsx(
            ToolsPanelItem,
            {
              label: __("Layout type"),
              hasValue: hasLayoutTypeValue,
              onDeselect: resetLayout,
              isShownByDefault: true,
              panelId: clientId,
              children: /* @__PURE__ */ jsx(
                LayoutTypeSwitcher,
                {
                  type: blockLayoutType,
                  onChange: onChangeType
                }
              )
            }
          ),
          layoutType && layoutType.name !== "default" && /* @__PURE__ */ jsx(
            layoutType.inspectorControls,
            {
              layout: usedLayout,
              value: layout,
              onChange: onChangeLayout,
              layoutBlockSupport: blockSupportAndThemeSettings,
              resetLayout: resetLayoutDefaults,
              name: blockName,
              clientId
            }
          ),
          constrainedType && displayControlsForLegacyLayouts && /* @__PURE__ */ jsx(
            constrainedType.inspectorControls,
            {
              layout: usedLayout,
              value: layout,
              onChange: onChangeLayout,
              layoutBlockSupport: blockSupportAndThemeSettings,
              resetLayout: resetLayoutDefaults,
              name: blockName,
              clientId
            }
          )
        ]
      }
    ),
    !inherit && layoutType && /* @__PURE__ */ 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__ */ jsx(
    ToggleGroupControl,
    {
      __next40pxDefaultSize: true,
      isBlock: true,
      label: __("Layout type"),
      hideLabelFromVision: true,
      isAdaptiveWidth: true,
      value: type,
      onChange,
      children: getLayoutTypes().map(({ name, label }) => {
        return /* @__PURE__ */ jsx(
          ToggleGroupControlOption,
          {
            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 = useInstanceId(BlockListBlock);
  const { layout } = attributes;
  const { default: defaultBlockLayout } = 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 = 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 = clsx(
    {
      [`${selectorPrefix}${id}`]: !!css
      // Only attach a container class if there is generated CSS to be attached.
    },
    layoutClasses
  );
  useStyleOverride({ css });
  return /* @__PURE__ */ jsx(
    BlockListBlock,
    {
      ...props,
      __unstableLayoutClassNames: layoutClassNames
    }
  );
}
var withLayoutStyles = createHigherOrderComponent(
  (BlockListBlock) => function WithLayoutStyles(props) {
    const { clientId, name, attributes } = props;
    const blockSupportsLayout = hasLayoutBlockSupport(name);
    const layoutClasses = useLayoutClasses(attributes, name);
    const extraProps = useSelect(
      (select) => {
        if (!blockSupportsLayout) {
          return;
        }
        const { getSettings, getBlockSettings } = unlock(
          select(blockEditorStore)
        );
        const settings = getSettings();
        const { disableLayoutStyles } = settings;
        if (disableLayoutStyles) {
          return;
        }
        const [blockGapSupport] = getBlockSettings(
          clientId,
          "spacing.blockGap"
        );
        const globalStyles = settings[globalStylesDataKey];
        let variationBlockGapValue;
        const className = attributes?.className;
        if (className?.includes(VARIATION_PREFIX)) {
          const { getBlockStyles } = select(blocksStore);
          const registeredStyles = getBlockStyles(name);
          const variationName = 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__ */ jsx(
        BlockListBlock,
        {
          ...props,
          __unstableLayoutClassNames: blockSupportsLayout ? layoutClasses : void 0
        }
      );
    }
    return /* @__PURE__ */ jsx(
      BlockWithLayoutStyles,
      {
        block: BlockListBlock,
        props,
        layoutClasses,
        ...extraProps
      }
    );
  },
  "withLayoutStyles"
);
addFilter(
  "blocks.registerBlockType",
  "core/layout/addAttribute",
  addAttribute
);
addFilter(
  "editor.BlockListBlock",
  "core/editor/layout/with-layout-styles",
  withLayoutStyles
);
export {
  addAttribute,
  layout_default as default,
  getResetLayout,
  getResponsiveLayoutStyles,
  useLayoutClasses,
  useLayoutStyles,
  withLayoutStyles
};
//# sourceMappingURL=layout.mjs.map
