// packages/block-editor/src/utils/block-bindings.js
import { useDispatch, useRegistry } from "@wordpress/data";
import { store as blockEditorStore } from "../store";
import { useBlockEditContext } from "../components/block-edit";
var DEFAULT_ATTRIBUTE = "__default";
var PATTERN_OVERRIDES_SOURCE = "core/pattern-overrides";
function isObjectEmpty(object) {
  return !object || Object.keys(object).length === 0;
}
function hasPatternOverridesDefaultBinding(bindings) {
  return bindings?.[DEFAULT_ATTRIBUTE]?.source === PATTERN_OVERRIDES_SOURCE;
}
function replacePatternOverridesDefaultBinding(bindings, supportedAttributes) {
  if (hasPatternOverridesDefaultBinding(bindings)) {
    const bindingsWithDefaults = {};
    for (const attributeName of supportedAttributes) {
      const bindingSource = bindings[attributeName] ? bindings[attributeName] : { source: PATTERN_OVERRIDES_SOURCE };
      bindingsWithDefaults[attributeName] = bindingSource;
    }
    return bindingsWithDefaults;
  }
  return bindings;
}
function useBlockBindingsUtils(clientId) {
  const { clientId: contextClientId } = useBlockEditContext();
  const blockClientId = clientId || contextClientId;
  const { updateBlockAttributes } = useDispatch(blockEditorStore);
  const { getBlockAttributes } = useRegistry().select(blockEditorStore);
  const updateBlockBindings = (bindings) => {
    const { metadata: { bindings: currentBindings, ...metadata } = {} } = getBlockAttributes(blockClientId);
    const newBindings = { ...currentBindings };
    Object.entries(bindings).forEach(([attribute, binding]) => {
      if (!binding && newBindings[attribute]) {
        delete newBindings[attribute];
        return;
      }
      newBindings[attribute] = binding;
    });
    const newMetadata = {
      ...metadata,
      bindings: newBindings
    };
    if (isObjectEmpty(newMetadata.bindings)) {
      delete newMetadata.bindings;
    }
    updateBlockAttributes(blockClientId, {
      metadata: isObjectEmpty(newMetadata) ? void 0 : newMetadata
    });
  };
  const removeAllBlockBindings = () => {
    const { metadata: { bindings, ...metadata } = {} } = getBlockAttributes(blockClientId);
    updateBlockAttributes(blockClientId, {
      metadata: isObjectEmpty(metadata) ? void 0 : metadata
    });
  };
  return { updateBlockBindings, removeAllBlockBindings };
}
export {
  hasPatternOverridesDefaultBinding,
  replacePatternOverridesDefaultBinding,
  useBlockBindingsUtils
};
//# sourceMappingURL=block-bindings.js.map
