"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-child.js
var layout_child_exports = {};
__export(layout_child_exports, {
  default: () => layout_child_default,
  getChildLayoutStyleRules: () => getChildLayoutStyleRules,
  getChildLayoutStyles: () => getChildLayoutStyles,
  getResponsiveChildLayoutStyles: () => getResponsiveChildLayoutStyles
});
module.exports = __toCommonJS(layout_child_exports);
var import_compose = require("@wordpress/compose");
var import_data = require("@wordpress/data");
var import_element = require("@wordpress/element");
var import_store = require("../store/index.cjs");
var import_lock_unlock = require("../lock-unlock.cjs");
var import_utils = require("./utils.cjs");
var import_layout = require("../components/block-list/layout.cjs");
var import_grid = require("../components/grid/index.cjs");
var import_use_block_refs = require("../components/block-list/use-block-props/use-block-refs.cjs");
var import_use_block_visibility = __toESM(require("../components/block-visibility/use-block-visibility.cjs"));
var import_private_keys = require("../store/private-keys.cjs");
var import_constants = require("../components/block-visibility/constants.cjs");
var import_block_style_state = require("./block-style-state.cjs");
var import_jsx_runtime = require("react/jsx-runtime");
var LAYOUT_CHILD_BLOCK_PROPS_REFERENCE = {};
var RESPONSIVE_BREAKPOINTS = {
  "@mobile": "@media (width <= 480px)",
  "@tablet": "@media (480px < width <= 782px)"
};
var FLEX_CHILD_LAYOUT_VALUES = {
  fit: "fit",
  grow: "fill",
  max: "fixed",
  fixed: "fixedNoShrink"
};
var FLEX_SIZE_VALUES = [
  FLEX_CHILD_LAYOUT_VALUES.max,
  FLEX_CHILD_LAYOUT_VALUES.fixed
];
function isFlexSizeValue(value) {
  return FLEX_SIZE_VALUES.includes(value);
}
function serializeRule({ selector, declarations }) {
  return `${selector} {
		${Object.entries(declarations).map(([property, value]) => `${property}: ${value}`).join("; ")};
	}`;
}
function getChildLayoutStyleRules({
  selector,
  layout = {},
  viewportOverrides,
  parentLayout = {},
  includeContainerQuery = true
}) {
  const hasViewportOverrides = viewportOverrides !== void 0;
  const effectiveLayout = hasViewportOverrides ? {
    ...layout,
    ...viewportOverrides
  } : layout;
  const hasViewportOverride = (key) => Object.hasOwn(viewportOverrides || {}, key);
  const {
    selfStretch,
    flexSize,
    columnStart,
    rowStart,
    columnSpan,
    rowSpan
  } = effectiveLayout;
  const baseSelfStretch = layout.selfStretch;
  const { columnCount, minimumColumnWidth } = parentLayout;
  const rules = [];
  const declarations = {};
  if (!hasViewportOverrides || hasViewportOverride("selfStretch") || hasViewportOverride("flexSize")) {
    if (hasViewportOverrides && (selfStretch === FLEX_CHILD_LAYOUT_VALUES.fit || selfStretch === FLEX_CHILD_LAYOUT_VALUES.grow) && isFlexSizeValue(baseSelfStretch) && layout.flexSize) {
      declarations["flex-basis"] = "unset";
      if (baseSelfStretch === FLEX_CHILD_LAYOUT_VALUES.fixed) {
        declarations["flex-shrink"] = "unset";
      }
    }
    if (isFlexSizeValue(selfStretch) && flexSize) {
      declarations["flex-basis"] = flexSize;
      if (selfStretch === FLEX_CHILD_LAYOUT_VALUES.fixed) {
        declarations["flex-shrink"] = "0";
      } else if (hasViewportOverrides && baseSelfStretch === FLEX_CHILD_LAYOUT_VALUES.fixed) {
        declarations["flex-shrink"] = "unset";
      }
      declarations["box-sizing"] = "border-box";
    } else if (selfStretch === FLEX_CHILD_LAYOUT_VALUES.grow) {
      declarations["flex-grow"] = "1";
    }
  }
  if (!hasViewportOverrides || hasViewportOverride("columnStart") || hasViewportOverride("columnSpan")) {
    if (columnStart && columnSpan) {
      declarations["grid-column"] = `${columnStart} / span ${columnSpan}`;
    } else if (columnStart) {
      declarations["grid-column"] = `${columnStart}`;
    } else if (columnSpan) {
      declarations["grid-column"] = `span ${columnSpan}`;
    }
  }
  if (!hasViewportOverrides || hasViewportOverride("rowStart") || hasViewportOverride("rowSpan")) {
    if (rowStart && rowSpan) {
      declarations["grid-row"] = `${rowStart} / span ${rowSpan}`;
    } else if (rowStart) {
      declarations["grid-row"] = `${rowStart}`;
    } else if (rowSpan) {
      declarations["grid-row"] = `span ${rowSpan}`;
    }
  }
  if (Object.keys(declarations).length) {
    rules.push({ selector, declarations });
  }
  if (includeContainerQuery && !hasViewportOverrides) {
    if ((columnSpan || columnStart) && (minimumColumnWidth || !columnCount)) {
      let parentColumnValue = parseFloat(minimumColumnWidth);
      if (isNaN(parentColumnValue)) {
        parentColumnValue = 12;
      }
      let parentColumnUnit = minimumColumnWidth?.replace(
        parentColumnValue,
        ""
      );
      if (!["px", "rem", "em"].includes(parentColumnUnit)) {
        parentColumnUnit = "rem";
      }
      let numColsToBreakAt = 2;
      if (columnSpan && columnStart) {
        numColsToBreakAt = columnSpan + columnStart - 1;
      } else if (columnSpan) {
        numColsToBreakAt = columnSpan;
      } else {
        numColsToBreakAt = columnStart;
      }
      const defaultGapValue = parentColumnUnit === "px" ? 24 : 1.5;
      const containerQueryValue = numColsToBreakAt * parentColumnValue + (numColsToBreakAt - 1) * defaultGapValue;
      const minimumContainerQueryValue = parentColumnValue * 2 + defaultGapValue - 1;
      const gridColumnValue = columnSpan && columnSpan > 1 ? "1/-1" : "auto";
      rules.push({
        rulesGroup: `@container (max-width: ${Math.max(
          containerQueryValue,
          minimumContainerQueryValue
        )}${parentColumnUnit})`,
        selector,
        declarations: {
          "grid-column": gridColumnValue,
          "grid-row": "auto"
        }
      });
    }
  }
  return rules;
}
function getChildLayoutStyles({
  selector,
  layout = {},
  parentLayout = {},
  includeContainerQuery = true
}) {
  return getChildLayoutStyleRules({
    selector,
    layout,
    parentLayout,
    includeContainerQuery
  }).map((rule) => {
    const serializedRule = serializeRule(rule);
    return rule.rulesGroup ? `${rule.rulesGroup} {
				${serializedRule}
			}` : serializedRule;
  }).join("");
}
function getResponsiveChildLayoutStyles({
  style = {},
  selector,
  parentLayout = {}
}) {
  const baseLayout = style?.layout ?? {};
  return Object.entries(RESPONSIVE_BREAKPOINTS).map(([viewport, mediaQuery]) => {
    const viewportLayout = (0, import_block_style_state.getStyleForState)(style, {
      viewport,
      pseudo: import_block_style_state.DEFAULT_BLOCK_STYLE_STATE.pseudo
    })?.layout;
    if (!viewportLayout || !Object.keys(viewportLayout).length) {
      return "";
    }
    const viewportRules = getChildLayoutStyleRules({
      selector,
      layout: baseLayout,
      viewportOverrides: viewportLayout,
      parentLayout,
      includeContainerQuery: false
    });
    const css = viewportRules.map(serializeRule).join("");
    return css ? `${mediaQuery}{${css}}` : "";
  }).filter(Boolean).join("");
}
function useBlockPropsChildLayoutStyles({ style }) {
  const shouldRenderChildLayoutStyles = (0, import_data.useSelect)((select) => {
    return !select(import_store.store).getSettings().disableLayoutStyles;
  });
  const layout = style?.layout ?? {};
  const { columnStart, rowStart, columnSpan, rowSpan } = layout;
  const parentLayout = (0, import_layout.useLayout)() || {};
  const id = (0, import_compose.useInstanceId)(LAYOUT_CHILD_BLOCK_PROPS_REFERENCE);
  const selector = `.wp-container-content-${id}`;
  if (process.env.NODE_ENV === "development") {
    if (columnStart && typeof columnStart !== "number") {
      throw new Error("columnStart must be a number");
    }
    if (rowStart && typeof rowStart !== "number") {
      throw new Error("rowStart must be a number");
    }
    if (columnSpan && typeof columnSpan !== "number") {
      throw new Error("columnSpan must be a number");
    }
    if (rowSpan && typeof rowSpan !== "number") {
      throw new Error("rowSpan must be a number");
    }
  }
  let css = "";
  if (shouldRenderChildLayoutStyles) {
    css = [
      getChildLayoutStyles({
        selector,
        layout,
        parentLayout
      }),
      getResponsiveChildLayoutStyles({
        style,
        selector,
        parentLayout
      })
    ].join("");
  }
  (0, import_utils.useStyleOverride)({ css });
  if (!css) {
    return;
  }
  return { className: `wp-container-content-${id}` };
}
function ChildLayoutControlsPure({ clientId, style, setAttributes }) {
  const parentLayout = (0, import_layout.useLayout)() || {};
  const {
    type: parentLayoutType = "default",
    allowSizingOnChildren = false,
    isManualPlacement
  } = parentLayout;
  if (parentLayoutType !== "grid") {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    GridTools,
    {
      clientId,
      style,
      setAttributes,
      allowSizingOnChildren,
      isManualPlacement,
      parentLayout
    }
  );
}
function GridTools({
  clientId,
  style,
  setAttributes,
  allowSizingOnChildren,
  isManualPlacement,
  parentLayout
}) {
  const {
    rootClientId,
    isVisible,
    parentBlockVisibility,
    blockBlockVisibility,
    deviceType,
    isChildBlockAGrid
  } = (0, import_data.useSelect)(
    (select) => {
      const {
        getBlockRootClientId,
        getBlockEditingMode,
        getTemplateLock,
        getBlockAttributes,
        getSettings
      } = select(import_store.store);
      const _rootClientId = getBlockRootClientId(clientId);
      if (getTemplateLock(_rootClientId) || getBlockEditingMode(_rootClientId) !== "default") {
        return {
          rootClientId: _rootClientId,
          isVisible: false
        };
      }
      const parentAttributes = getBlockAttributes(_rootClientId);
      const blockAttributes = getBlockAttributes(clientId);
      const settings = getSettings();
      const currentDeviceType = settings?.[import_private_keys.deviceTypeKey]?.toLowerCase() || import_constants.BLOCK_VISIBILITY_VIEWPORTS.desktop.key;
      return {
        rootClientId: _rootClientId,
        isVisible: true,
        parentBlockVisibility: parentAttributes?.metadata?.blockVisibility,
        blockBlockVisibility: blockAttributes?.metadata?.blockVisibility,
        deviceType: currentDeviceType,
        // Check if the selected child block is itself a grid.
        isChildBlockAGrid: blockAttributes?.layout?.type === "grid"
      };
    },
    [clientId]
  );
  const blockElement = (0, import_use_block_refs.useBlockElement)(clientId);
  const rawCanvasView = blockElement?.ownerDocument?.defaultView;
  const canvasView = rawCanvasView === null ? void 0 : rawCanvasView;
  const {
    isBlockCurrentlyHidden: isParentBlockCurrentlyHidden,
    currentViewport
  } = (0, import_use_block_visibility.default)({
    blockVisibility: parentBlockVisibility,
    deviceType,
    view: canvasView
  });
  const isAnyAncestorHidden = (0, import_data.useSelect)(
    (select) => {
      if (!rootClientId) {
        return false;
      }
      const { isBlockParentHiddenAtViewport } = (0, import_lock_unlock.unlock)(
        select(import_store.store)
      );
      return isBlockParentHiddenAtViewport(
        rootClientId,
        currentViewport
      );
    },
    [rootClientId, currentViewport]
  );
  const { isBlockCurrentlyHidden: isBlockItselfCurrentlyHidden } = (0, import_use_block_visibility.default)({
    blockVisibility: blockBlockVisibility,
    deviceType,
    view: canvasView
  });
  const [resizerBounds, setResizerBounds] = (0, import_element.useState)();
  const childGridClientId = isChildBlockAGrid ? clientId : void 0;
  if (!isVisible || isParentBlockCurrentlyHidden || isAnyAncestorHidden) {
    return null;
  }
  const showResizer = allowSizingOnChildren && !isBlockItselfCurrentlyHidden;
  function updateLayout(layout) {
    setAttributes({
      style: {
        ...style,
        layout: {
          ...style?.layout,
          ...layout
        }
      }
    });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_grid.GridVisualizer,
      {
        clientId: rootClientId,
        contentRef: setResizerBounds,
        parentLayout,
        childGridClientId
      }
    ),
    showResizer && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_grid.GridItemResizer,
      {
        clientId,
        bounds: resizerBounds,
        onChange: updateLayout,
        parentLayout
      }
    ),
    isManualPlacement && window.__experimentalEnableGridInteractivity && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_grid.GridItemMovers,
      {
        layout: style?.layout,
        parentLayout,
        onChange: updateLayout,
        gridClientId: rootClientId,
        blockClientId: clientId
      }
    )
  ] });
}
var layout_child_default = {
  useBlockProps: useBlockPropsChildLayoutStyles,
  edit: ChildLayoutControlsPure,
  attributeKeys: ["style"],
  hasSupport() {
    return true;
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getChildLayoutStyleRules,
  getChildLayoutStyles,
  getResponsiveChildLayoutStyles
});
//# sourceMappingURL=layout-child.cjs.map
