@wordpress/block-library
Version:
Block library for the WordPress editor.
383 lines (382 loc) • 15.7 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_data = require("@wordpress/data");
let _wordpress_element = require("@wordpress/element");
let _wordpress_core_data = require("@wordpress/core-data");
let _wordpress_block_editor = require("@wordpress/block-editor");
let _wordpress_html_entities = require("@wordpress/html-entities");
let _wordpress_i18n = require("@wordpress/i18n");
let _wordpress_blocks = require("@wordpress/blocks");
// packages/block-library/src/query/utils.js
/** @typedef {import('@wordpress/blocks').WPBlockVariation} WPBlockVariation */
/** @typedef {import('@wordpress/components/build-types/query-controls/types').OrderByOption} OrderByOption */
/**
* @typedef IHasNameAndId
* @property {string|number} id The entity's id.
* @property {string} name The entity's name.
*/
/**
* The object used in Query block that contains info and helper mappings
* from an array of IHasNameAndId objects.
*
* @typedef {Object} QueryEntitiesInfo
* @property {IHasNameAndId[]} entities The array of entities.
* @property {Object<string, IHasNameAndId>} mapById Object mapping with the id as key and the entity as value.
* @property {Object<string, IHasNameAndId>} mapByName Object mapping with the name as key and the entity as value.
* @property {string[]} names Array with the entities' names.
*/
/**
* Returns a helper object with mapping from Objects that implement
* the `IHasNameAndId` interface. The returned object is used for
* integration with `FormTokenField` component.
*
* @param {IHasNameAndId[]} entities The entities to extract of helper object.
* @return {QueryEntitiesInfo} The object with the entities information.
*/
const getEntitiesInfo = (entities) => {
return {
entities,
...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: []
})
};
};
/**
* Helper util to return a value from a certain path of the object.
* Path is specified as a string of properties, separated by dots,
* for example: "parent.child".
*
* @param {Object} object Input object.
* @param {string} path Path to the object property.
* @return {*} Value of the object property at the specified path.
*/
const getValueFromObjectPath = (object, path) => {
const normalizedPath = path.split(".");
let value = object;
normalizedPath.forEach((fieldName) => {
value = value?.[fieldName];
});
return value;
};
/**
* Helper util to map records to add a `name` prop from a
* provided path, in order to handle all entities in the same
* fashion(implementing`IHasNameAndId` interface).
*
* @param {Object[]} entities The array of entities.
* @param {string} path The path to map a `name` property from the entity.
* @return {IHasNameAndId[]} An array of entities that now implement the `IHasNameAndId` interface.
*/
const mapToIHasNameAndId = (entities, path) => {
return (entities || []).map((entity) => ({
...entity,
name: (0, _wordpress_html_entities.decodeEntities)(getValueFromObjectPath(entity, path))
}));
};
/**
* Returns a helper object that contains:
* 1. An `options` object from the available post types, to be passed to a `SelectControl`.
* 2. A helper map with available taxonomies per post type.
* 3. A helper map with post format support per post type.
*
* @return {Object} The helper object related to post types.
*/
const usePostTypes = () => {
const postTypes = (0, _wordpress_data.useSelect)((select) => {
const { getPostTypes } = select(_wordpress_core_data.store);
const excludedPostTypes = ["attachment"];
return getPostTypes({ per_page: -1 })?.filter(({ viewable, slug }) => viewable && !excludedPostTypes.includes(slug));
}, []);
return {
postTypesTaxonomiesMap: (0, _wordpress_element.useMemo)(() => {
if (!postTypes?.length) return;
return postTypes.reduce((accumulator, type) => {
accumulator[type.slug] = type.taxonomies;
return accumulator;
}, {});
}, [postTypes]),
postTypesSelectOptions: (0, _wordpress_element.useMemo)(() => (postTypes || []).map(({ labels, slug }) => ({
label: labels.singular_name,
value: slug
})), [postTypes]),
postTypeFormatSupportMap: (0, _wordpress_element.useMemo)(() => {
if (!postTypes?.length) return {};
return postTypes.reduce((accumulator, type) => {
accumulator[type.slug] = type.supports?.["post-formats"] || false;
return accumulator;
}, {});
}, [postTypes])
};
};
/**
* Hook that returns the taxonomies associated with a specific post type.
*
* @param {string} postType The post type from which to retrieve the associated taxonomies.
* @return {Object[]} An array of the associated taxonomies.
*/
const useTaxonomies = (postType) => {
const taxonomies = (0, _wordpress_data.useSelect)((select) => {
const { getTaxonomies, getPostType } = select(_wordpress_core_data.store);
if (getPostType(postType)?.taxonomies?.length > 0) return getTaxonomies({
type: postType,
per_page: -1
});
return [];
}, [postType]);
return (0, _wordpress_element.useMemo)(() => {
return taxonomies?.filter(({ visibility }) => !!visibility?.publicly_queryable);
}, [taxonomies]);
};
/**
* Hook that returns whether a specific post type is hierarchical.
*
* @param {string} postType The post type to check.
* @return {boolean} Whether a specific post type is hierarchical.
*/
function useIsPostTypeHierarchical(postType) {
return (0, _wordpress_data.useSelect)((select) => {
const type = select(_wordpress_core_data.store).getPostType(postType);
return type?.viewable && type?.hierarchical;
}, [postType]);
}
/**
* List of available options to order by.
*
* @param {string} postType The post type to check.
* @return {OrderByOption[]} List of order options.
*/
function useOrderByOptions(postType) {
const supportsCustomOrder = (0, _wordpress_data.useSelect)((select) => {
return !!select(_wordpress_core_data.store).getPostType(postType)?.supports?.["page-attributes"];
}, [postType]);
return (0, _wordpress_element.useMemo)(() => {
const orderByOptions = [
{
label: (0, _wordpress_i18n.__)("Newest to oldest"),
value: "date/desc"
},
{
label: (0, _wordpress_i18n.__)("Oldest to newest"),
value: "date/asc"
},
{
label: (0, _wordpress_i18n.__)("A → Z"),
value: "title/asc"
},
{
label: (0, _wordpress_i18n.__)("Z → A"),
value: "title/desc"
}
];
if (supportsCustomOrder) orderByOptions.push({
label: (0, _wordpress_i18n.__)("Ascending by order"),
value: "menu_order/asc"
}, {
label: (0, _wordpress_i18n.__)("Descending by order"),
value: "menu_order/desc"
});
return orderByOptions;
}, [supportsCustomOrder]);
}
/**
* Hook that returns the query properties' names defined by the active
* block variation, to determine which block's filters to show.
*
* @param {Object} attributes Block attributes.
* @return {string[]} An array of the query attributes.
*/
function useAllowedControls(attributes) {
return (0, _wordpress_data.useSelect)((select) => select(_wordpress_blocks.store).getActiveBlockVariation("core/query", attributes)?.allowedControls, [attributes]);
}
function isControlAllowed(allowedControls, key) {
if (!allowedControls) return true;
return allowedControls.includes(key);
}
/**
* Clones a pattern's blocks and then recurses over that list of blocks,
* transforming them to retain some `query` attribute properties.
* For now we retain the `postType` and `inherit` properties as they are
* fundamental for the expected functionality of the block and don't affect
* its design and presentation.
*
* Returns the cloned/transformed blocks and array of existing Query Loop
* client ids for further manipulation, in order to avoid multiple recursions.
*
* @param {WPBlock[]} blocks The list of blocks to look through and transform(mutate).
* @param {Record<string,*>} queryBlockAttributes The existing Query Loop's attributes.
* @return {{ newBlocks: WPBlock[], queryClientIds: string[] }} An object with the cloned/transformed blocks and all the Query Loop clients from these blocks.
*/
const getTransformedBlocksFromPattern = (blocks, queryBlockAttributes) => {
const { query: { postType, inherit }, namespace } = queryBlockAttributes;
const clonedBlocks = blocks.map((block) => (0, _wordpress_blocks.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
};
};
/**
* Helper hook that determines if there is an active variation of the block
* and if there are available specific patterns for this variation.
* If there are, these patterns are going to be the only ones suggested to
* the user in setup and replace flow, without including the default ones
* for Query Loop.
*
* If there are no such patterns, the default ones for Query Loop are going
* to be suggested.
*
* @param {string} clientId The block's client ID.
* @param {Object} attributes The block's attributes.
* @return {string} The block name to be used in the patterns suggestions.
*/
function useBlockNameForPatterns(clientId, attributes) {
return (0, _wordpress_data.useSelect)((select) => {
const activeVariationName = select(_wordpress_blocks.store).getActiveBlockVariation("core/query", attributes)?.name;
if (!activeVariationName) return "core/query";
const { getBlockRootClientId, getPatternsByBlockTypes } = select(_wordpress_block_editor.store);
const rootClientId = getBlockRootClientId(clientId);
return getPatternsByBlockTypes(`core/query/${activeVariationName}`, rootClientId).length > 0 ? `core/query/${activeVariationName}` : "core/query";
}, [clientId, attributes]);
}
/**
* Helper hook that determines if there is an active variation of the block
* and if there are available specific scoped `block` variations connected with
* this variation.
*
* If there are, these variations are going to be the only ones suggested
* to the user in setup flow when clicking to `start blank`, without including
* the default ones for Query Loop.
*
* If there are no such scoped `block` variations, the default ones for Query
* Loop are going to be suggested.
*
* The way we determine such variations is with the convention that they have the `namespace`
* attribute defined as an array. This array should contain the names(`name` property) of any
* variations they want to be connected to.
* For example, if we have a `Query Loop` scoped `inserter` variation with the name `products`,
* we can connect a scoped `block` variation by setting its `namespace` attribute to `['products']`.
* If the user selects this variation, the `namespace` attribute will be overridden by the
* main `inserter` variation.
*
* @param {Object} attributes The block's attributes.
* @return {WPBlockVariation[]} The block variations to be suggested in setup flow, when clicking to `start blank`.
*/
function useScopedBlockVariations(attributes) {
const { activeVariationName, blockVariations } = (0, _wordpress_data.useSelect)((select) => {
const { getActiveBlockVariation, getBlockVariations } = select(_wordpress_blocks.store);
return {
activeVariationName: getActiveBlockVariation("core/query", attributes)?.name,
blockVariations: getBlockVariations("core/query", "block")
};
}, [attributes]);
return (0, _wordpress_element.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]);
}
/**
* Hook that returns the block patterns for a specific block type.
*
* @param {string} clientId The block's client ID.
* @param {string} name The block type name.
* @return {Object[]} An array of valid block patterns.
*/
const usePatterns = (clientId, name) => {
return (0, _wordpress_data.useSelect)((select) => {
const { getBlockRootClientId, getPatternsByBlockTypes } = select(_wordpress_block_editor.store);
return getPatternsByBlockTypes(name, getBlockRootClientId(clientId));
}, [name, clientId]);
};
/**
* Hook that, given a block clientId, returns the titles of the unsupported
* blocks it contains, without duplicates.
*
* @param {string} clientId The block's client ID.
* @return {string[]} The titles of the unsupported blocks.
*/
const useUnsupportedBlocks = (clientId) => {
return (0, _wordpress_data.useSelect)((select) => {
const { getClientIdsOfDescendants, getBlockName } = select(_wordpress_block_editor.store);
const { getBlockSupport, getBlockType } = select(_wordpress_blocks.store);
const blockTitles = /* @__PURE__ */ new Set();
getClientIdsOfDescendants(clientId).forEach((descendantClientId) => {
const blockName = getBlockName(descendantClientId);
const blockSupportsInteractivity = Object.is(getBlockSupport(blockName, "interactivity"), true);
const blockSupportsInteractivityClientNavigation = getBlockSupport(blockName, "interactivity.clientNavigation");
if (!blockSupportsInteractivity && !blockSupportsInteractivityClientNavigation) blockTitles.add(getBlockType(blockName)?.title || blockName);
});
return [...blockTitles];
}, [clientId]);
};
/**
* Helper function that returns the query context from the editor based on the
* available template slug.
*
* @param {string} templateSlug Current template slug based on context.
* @return {Object} An object with isSingular and templateType properties.
*/
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;
if (templateSlug.includes("-") ? templateSlug.split("-").slice(1).join("-") : "") templateType = templateTypeFromSlug;
isSingular = singularTemplates.includes(templateType);
return {
isSingular,
templateType
};
}
exports.getEntitiesInfo = getEntitiesInfo;
exports.getQueryContextFromTemplate = getQueryContextFromTemplate;
exports.getTransformedBlocksFromPattern = getTransformedBlocksFromPattern;
exports.getValueFromObjectPath = getValueFromObjectPath;
exports.isControlAllowed = isControlAllowed;
exports.mapToIHasNameAndId = mapToIHasNameAndId;
exports.useAllowedControls = useAllowedControls;
exports.useBlockNameForPatterns = useBlockNameForPatterns;
exports.useIsPostTypeHierarchical = useIsPostTypeHierarchical;
exports.useOrderByOptions = useOrderByOptions;
exports.usePatterns = usePatterns;
exports.usePostTypes = usePostTypes;
exports.useScopedBlockVariations = useScopedBlockVariations;
exports.useTaxonomies = useTaxonomies;
exports.useUnsupportedBlocks = useUnsupportedBlocks;
//# sourceMappingURL=utils.cjs.map