// packages/block-library/src/query/utils.js
import { useSelect } from "@wordpress/data";
import { useMemo } from "@wordpress/element";
import { store as coreStore } from "@wordpress/core-data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { decodeEntities } from "@wordpress/html-entities";
import { __ } from "@wordpress/i18n";
import {
  cloneBlock,
  getBlockSupport,
  store as blocksStore
} from "@wordpress/blocks";
var getEntitiesInfo = (entities) => {
  const mapping = entities?.reduce(
    (accumulator, entity) => {
      const { mapById, mapByName, names } = accumulator;
      mapById[entity.id] = entity;
      mapByName[entity.name] = entity;
      names.push(entity.name);
      return accumulator;
    },
    { mapById: {}, mapByName: {}, names: [] }
  );
  return {
    entities,
    ...mapping
  };
};
var getValueFromObjectPath = (object, path) => {
  const normalizedPath = path.split(".");
  let value = object;
  normalizedPath.forEach((fieldName) => {
    value = value?.[fieldName];
  });
  return value;
};
var mapToIHasNameAndId = (entities, path) => {
  return (entities || []).map((entity) => ({
    ...entity,
    name: decodeEntities(getValueFromObjectPath(entity, path))
  }));
};
var usePostTypes = () => {
  const postTypes = useSelect((select) => {
    const { getPostTypes } = select(coreStore);
    const excludedPostTypes = ["attachment"];
    const filteredPostTypes = getPostTypes({ per_page: -1 })?.filter(
      ({ viewable, slug }) => viewable && !excludedPostTypes.includes(slug)
    );
    return filteredPostTypes;
  }, []);
  const postTypesTaxonomiesMap = useMemo(() => {
    if (!postTypes?.length) {
      return;
    }
    return postTypes.reduce((accumulator, type) => {
      accumulator[type.slug] = type.taxonomies;
      return accumulator;
    }, {});
  }, [postTypes]);
  const postTypesSelectOptions = useMemo(
    () => (postTypes || []).map(({ labels, slug }) => ({
      label: labels.singular_name,
      value: slug
    })),
    [postTypes]
  );
  const postTypeFormatSupportMap = useMemo(() => {
    if (!postTypes?.length) {
      return {};
    }
    return postTypes.reduce((accumulator, type) => {
      accumulator[type.slug] = type.supports?.["post-formats"] || false;
      return accumulator;
    }, {});
  }, [postTypes]);
  return {
    postTypesTaxonomiesMap,
    postTypesSelectOptions,
    postTypeFormatSupportMap
  };
};
var useTaxonomies = (postType) => {
  const taxonomies = useSelect(
    (select) => {
      const { getTaxonomies, getPostType } = select(coreStore);
      if (getPostType(postType)?.taxonomies?.length > 0) {
        return getTaxonomies({
          type: postType,
          per_page: -1
        });
      }
      return [];
    },
    [postType]
  );
  return useMemo(() => {
    return taxonomies?.filter(
      ({ visibility }) => !!visibility?.publicly_queryable
    );
  }, [taxonomies]);
};
function useIsPostTypeHierarchical(postType) {
  return useSelect(
    (select) => {
      const type = select(coreStore).getPostType(postType);
      return type?.viewable && type?.hierarchical;
    },
    [postType]
  );
}
function useOrderByOptions(postType) {
  const supportsCustomOrder = useSelect(
    (select) => {
      const type = select(coreStore).getPostType(postType);
      return !!type?.supports?.["page-attributes"];
    },
    [postType]
  );
  return useMemo(() => {
    const orderByOptions = [
      {
        label: __("Newest to oldest"),
        value: "date/desc"
      },
      {
        label: __("Oldest to newest"),
        value: "date/asc"
      },
      {
        /* translators: Label for ordering posts by title in ascending order. */
        label: __("A \u2192 Z"),
        value: "title/asc"
      },
      {
        /* translators: Label for ordering posts by title in descending order. */
        label: __("Z \u2192 A"),
        value: "title/desc"
      }
    ];
    if (supportsCustomOrder) {
      orderByOptions.push(
        {
          /* translators: Label for ordering posts by ascending menu order. */
          label: __("Ascending by order"),
          value: "menu_order/asc"
        },
        {
          /* translators: Label for ordering posts by descending menu order. */
          label: __("Descending by order"),
          value: "menu_order/desc"
        }
      );
    }
    return orderByOptions;
  }, [supportsCustomOrder]);
}
function useAllowedControls(attributes) {
  return useSelect(
    (select) => select(blocksStore).getActiveBlockVariation(
      "core/query",
      attributes
    )?.allowedControls,
    [attributes]
  );
}
function isControlAllowed(allowedControls, key) {
  if (!allowedControls) {
    return true;
  }
  return allowedControls.includes(key);
}
var getTransformedBlocksFromPattern = (blocks, queryBlockAttributes) => {
  const {
    query: { postType, inherit },
    namespace
  } = queryBlockAttributes;
  const clonedBlocks = blocks.map((block) => cloneBlock(block));
  const queryClientIds = [];
  const blocksQueue = [...clonedBlocks];
  while (blocksQueue.length > 0) {
    const block = blocksQueue.shift();
    if (block.name === "core/query") {
      block.attributes.query = {
        ...block.attributes.query,
        postType,
        inherit
      };
      if (namespace) {
        block.attributes.namespace = namespace;
      }
      queryClientIds.push(block.clientId);
    }
    block.innerBlocks?.forEach((innerBlock) => {
      blocksQueue.push(innerBlock);
    });
  }
  return { newBlocks: clonedBlocks, queryClientIds };
};
function useBlockNameForPatterns(clientId, attributes) {
  return useSelect(
    (select) => {
      const activeVariationName = select(
        blocksStore
      ).getActiveBlockVariation("core/query", attributes)?.name;
      if (!activeVariationName) {
        return "core/query";
      }
      const { getBlockRootClientId, getPatternsByBlockTypes } = select(blockEditorStore);
      const rootClientId = getBlockRootClientId(clientId);
      const activePatterns = getPatternsByBlockTypes(
        `core/query/${activeVariationName}`,
        rootClientId
      );
      return activePatterns.length > 0 ? `core/query/${activeVariationName}` : "core/query";
    },
    [clientId, attributes]
  );
}
function useScopedBlockVariations(attributes) {
  const { activeVariationName, blockVariations } = useSelect(
    (select) => {
      const { getActiveBlockVariation, getBlockVariations } = select(blocksStore);
      return {
        activeVariationName: getActiveBlockVariation(
          "core/query",
          attributes
        )?.name,
        blockVariations: getBlockVariations("core/query", "block")
      };
    },
    [attributes]
  );
  const variations = useMemo(() => {
    const isNotConnected = (variation) => !variation.attributes?.namespace;
    if (!activeVariationName) {
      return blockVariations.filter(isNotConnected);
    }
    const connectedVariations = blockVariations.filter(
      (variation) => variation.attributes?.namespace?.includes(activeVariationName)
    );
    if (!!connectedVariations.length) {
      return connectedVariations;
    }
    return blockVariations.filter(isNotConnected);
  }, [activeVariationName, blockVariations]);
  return variations;
}
var usePatterns = (clientId, name) => {
  return useSelect(
    (select) => {
      const { getBlockRootClientId, getPatternsByBlockTypes } = select(blockEditorStore);
      const rootClientId = getBlockRootClientId(clientId);
      return getPatternsByBlockTypes(name, rootClientId);
    },
    [name, clientId]
  );
};
var useUnsupportedBlocks = (clientId) => {
  return useSelect(
    (select) => {
      const { getClientIdsOfDescendants, getBlockName } = select(blockEditorStore);
      return getClientIdsOfDescendants(clientId).some(
        (descendantClientId) => {
          const blockName = getBlockName(descendantClientId);
          const blockSupportsInteractivity = Object.is(
            getBlockSupport(blockName, "interactivity"),
            true
          );
          const blockSupportsInteractivityClientNavigation = getBlockSupport(
            blockName,
            "interactivity.clientNavigation"
          );
          return !blockSupportsInteractivity && !blockSupportsInteractivityClientNavigation;
        }
      );
    },
    [clientId]
  );
};
function getQueryContextFromTemplate(templateSlug) {
  if (!templateSlug) {
    return { isSingular: true };
  }
  let isSingular = false;
  let templateType = templateSlug === "wp" ? "custom" : templateSlug;
  const singularTemplates = ["404", "blank", "single", "page", "custom"];
  const templateTypeFromSlug = templateSlug.includes("-") ? templateSlug.split("-", 1)[0] : templateSlug;
  const queryFromTemplateSlug = templateSlug.includes("-") ? templateSlug.split("-").slice(1).join("-") : "";
  if (queryFromTemplateSlug) {
    templateType = templateTypeFromSlug;
  }
  isSingular = singularTemplates.includes(templateType);
  return { isSingular, templateType };
}
export {
  getEntitiesInfo,
  getQueryContextFromTemplate,
  getTransformedBlocksFromPattern,
  getValueFromObjectPath,
  isControlAllowed,
  mapToIHasNameAndId,
  useAllowedControls,
  useBlockNameForPatterns,
  useIsPostTypeHierarchical,
  useOrderByOptions,
  usePatterns,
  usePostTypes,
  useScopedBlockVariations,
  useTaxonomies,
  useUnsupportedBlocks
};
//# sourceMappingURL=utils.js.map
