@wordpress/global-styles-ui
Version:
Global Styles UI components for WordPress.
339 lines (338 loc) • 11.5 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_global_styles_engine = require("@wordpress/global-styles-engine");
let _wordpress_i18n = require("@wordpress/i18n");
// packages/global-styles-ui/src/utils.ts
const { getViewportBreakpoints, resolveStyle } = (0, require("./lock-unlock.cjs").unlock)(_wordpress_global_styles_engine.privateApis);
/**
* Valid states for elements with their labels.
* This mirrors the PHP constant in lib/class-wp-theme-json-gutenberg.php
*/
const VALID_ELEMENT_STATES = {
link: [
{
value: ":link",
label: (0, _wordpress_i18n.__)("Link")
},
{
value: ":any-link",
label: (0, _wordpress_i18n.__)("Any Link")
},
{
value: ":visited",
label: (0, _wordpress_i18n.__)("Visited")
},
{
value: ":hover",
label: (0, _wordpress_i18n.__)("Hover")
},
{
value: ":focus",
label: (0, _wordpress_i18n.__)("Focus")
},
{
value: ":focus-visible",
label: (0, _wordpress_i18n.__)("Focus-visible")
},
{
value: ":active",
label: (0, _wordpress_i18n.__)("Active")
}
],
button: [
{
value: ":link",
label: (0, _wordpress_i18n.__)("Link")
},
{
value: ":any-link",
label: (0, _wordpress_i18n.__)("Any Link")
},
{
value: ":visited",
label: (0, _wordpress_i18n.__)("Visited")
},
{
value: ":hover",
label: (0, _wordpress_i18n.__)("Hover")
},
{
value: ":focus",
label: (0, _wordpress_i18n.__)("Focus")
},
{
value: ":focus-visible",
label: (0, _wordpress_i18n.__)("Focus-visible")
},
{
value: ":active",
label: (0, _wordpress_i18n.__)("Active")
}
]
};
/**
* Valid states for blocks with their labels.
* This mirrors the PHP constant in lib/class-wp-theme-json-gutenberg.php
*/
const VALID_BLOCK_STATES = {
"core/button": [
{
value: ":hover",
label: (0, _wordpress_i18n.__)("Hover")
},
{
value: ":focus",
label: (0, _wordpress_i18n.__)("Focus")
},
{
value: ":focus-visible",
label: (0, _wordpress_i18n.__)("Focus-visible")
},
{
value: ":active",
label: (0, _wordpress_i18n.__)("Active")
}
],
"core/navigation-link": [
{
value: ":hover",
label: (0, _wordpress_i18n.__)("Hover")
},
{
value: ":focus",
label: (0, _wordpress_i18n.__)("Focus")
},
{
value: ":focus-visible",
label: (0, _wordpress_i18n.__)("Focus-visible")
},
{
value: ":active",
label: (0, _wordpress_i18n.__)("Active")
}
]
};
/**
* Responsive breakpoint states available for all blocks.
* These map to CSS media queries wrapping the block's styles.
*/
const RESPONSIVE_STATES = [{
value: "@tablet",
label: (0, _wordpress_i18n.__)("Tablet")
}, {
value: "@mobile",
label: (0, _wordpress_i18n.__)("Mobile")
}];
/**
* Get the valid pseudo states for a given block or element.
*
* @param name The block name (e.g., 'core/button') or element name (e.g., 'button')
* @return Array of valid pseudo state definitions, or empty array if none
*/
function getValidPseudoStates(name) {
if (VALID_BLOCK_STATES[name]) return VALID_BLOCK_STATES[name] ?? [];
if (VALID_ELEMENT_STATES[name]) return VALID_ELEMENT_STATES[name];
return [];
}
/**
* Get the valid viewport state definitions.
*
* @param viewportSettings
* @return Array of valid viewport state definitions.
*/
function getValidViewportStates(viewportSettings) {
const breakpoints = getViewportBreakpoints(viewportSettings);
return RESPONSIVE_STATES.filter((state) => (state.value !== "@tablet" || breakpoints.tablet !== void 0) && (state.value !== "@mobile" || breakpoints.mobile !== void 0));
}
/**
* Removes all instances of properties from an object.
*
* @param object The object to remove the properties from.
* @param properties The properties to remove.
* @return The modified object.
*/
function removePropertiesFromObject(object, properties) {
if (!properties?.length) return object;
if (typeof object !== "object" || !object || !Object.keys(object).length) return object;
for (const key in object) if (properties.includes(key)) delete object[key];
else if (typeof object[key] === "object") removePropertiesFromObject(object[key], properties);
return object;
}
/**
* Returns a new object, with properties specified in `properties` array.,
* maintain the original object tree structure.
* The function is recursive, so it will perform a deep search for the given properties.
* E.g., the function will return `{ a: { b: { c: { test: 1 } } } }` if the properties are `[ 'test' ]`.
*
* @param object The object to filter
* @param properties The properties to filter by
* @return The merged object.
*/
const filterObjectByProperties = (object, properties) => {
if (!object || !properties?.length) return {};
const newObject = {};
Object.keys(object).forEach((key) => {
if (properties.includes(key)) newObject[key] = object[key];
else if (typeof object[key] === "object") {
const newFilter = filterObjectByProperties(object[key], properties);
if (Object.keys(newFilter).length) newObject[key] = newFilter;
}
});
return newObject;
};
/**
* Compares a style variation to the same variation filtered by the specified properties.
* Returns true if the variation contains only the properties specified.
*
* @param variation The variation to compare.
* @param properties The properties to compare.
* @return Whether the variation contains only the specified properties.
*/
function isVariationWithProperties(variation, properties) {
const variationWithProperties = filterObjectByProperties(structuredClone(variation), properties);
return (0, _wordpress_global_styles_engine.areGlobalStylesEqual)(variationWithProperties, variation);
}
function getFontFamilyFromSetting(fontFamilies, setting) {
if (!Array.isArray(fontFamilies) || !setting) return null;
const fontFamilySlug = setting.replace("var(", "").replace(")", "")?.split("--").slice(-1)[0];
return fontFamilies.find((fontFamily) => fontFamily.slug === fontFamilySlug);
}
/**
* Extracts font families from a theme JSON configuration.
*
* @param themeJson The theme JSON configuration
* @return Array containing [bodyFontFamily, headingFontFamily]
*/
function getFontFamilies(themeJson) {
const themeFontFamilies = themeJson?.settings?.typography?.fontFamilies?.theme;
const customFontFamilies = themeJson?.settings?.typography?.fontFamilies?.custom;
let fontFamilies = [];
if (themeFontFamilies && customFontFamilies) fontFamilies = [...themeFontFamilies, ...customFontFamilies];
else if (themeFontFamilies) fontFamilies = themeFontFamilies;
else if (customFontFamilies) fontFamilies = customFontFamilies;
const bodyFontFamilySetting = themeJson?.styles?.typography?.fontFamily;
const bodyFontFamily = getFontFamilyFromSetting(fontFamilies, bodyFontFamilySetting);
const headingFontFamilySetting = themeJson?.styles?.elements?.heading?.typography?.fontFamily;
let headingFontFamily;
if (!headingFontFamilySetting) headingFontFamily = bodyFontFamily;
else headingFontFamily = getFontFamilyFromSetting(fontFamilies, themeJson?.styles?.elements?.heading?.typography?.fontFamily);
return [bodyFontFamily, headingFontFamily];
}
/**
* Iterates through the presets array and searches for slugs that start with the specified
* slugPrefix followed by a numerical suffix. It identifies the highest numerical suffix found
* and returns one greater than the highest found suffix, ensuring that the new index is unique.
*
* @param presets The array of preset objects, each potentially containing a slug property.
* @param slugPrefix The prefix to look for in the preset slugs.
*
* @return The next available index for a preset with the specified slug prefix, or 1 if no matching slugs are found.
*/
/**
* Gets the variation class name for a block style variation.
*
* @param variation The variation name.
* @return The variation class name.
*/
function getVariationClassName(variation) {
if (!variation) return "";
return `is-style-${variation}`;
}
function getNewIndexFromPresets(presets, slugPrefix) {
const nameRegex = new RegExp(`^${slugPrefix}([\\d]+)$`);
return presets.reduce((currentHighest, preset) => {
if (typeof preset?.slug === "string") {
const matches = preset?.slug.match(nameRegex);
if (matches) {
const id = parseInt(matches[1], 10);
if (id > currentHighest) return id;
}
}
return currentHighest;
}, 0) + 1;
}
const HEADING_ELEMENTS = [
"heading",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6"
];
const ELEMENT_ONLY_BLOCK_NAME = "core/__element-only";
function getElementKeys(element) {
return HEADING_ELEMENTS.includes(element) ? HEADING_ELEMENTS : [element];
}
function isOwnStylePath(path) {
return !path.startsWith(":") && !path.startsWith("@");
}
const BOX_SIDES = [
"top",
"right",
"bottom",
"left"
];
const SHORTHAND_LONGHANDS = {
"border.color": BOX_SIDES.map((side) => `border.${side}.color`),
"border.style": BOX_SIDES.map((side) => `border.${side}.style`),
"border.width": BOX_SIDES.map((side) => `border.${side}.width`),
"color.gradient": [
"color.background",
"background.backgroundImage",
"background.backgroundPosition",
"background.backgroundRepeat",
"background.backgroundSize",
"background.backgroundAttachment",
"background.backgroundClip"
]
};
function isSameOrNestedPath(path, otherPath) {
return path === otherPath || path.startsWith(`${otherPath}.`) || otherPath.startsWith(`${path}.`);
}
function setsSameProperty(path, otherPath) {
const longhands = SHORTHAND_LONGHANDS[path] ?? [path];
const otherLonghands = SHORTHAND_LONGHANDS[otherPath] ?? [otherPath];
return longhands.some((longhand) => otherLonghands.some((otherLonghand) => isSameOrNestedPath(longhand, otherLonghand)));
}
/**
* The block types an element paints whose own Global Styles beat the element
* for at least one property it sets. Block style variations are not counted.
*
* @param config Merged Global Styles config.
* @param element Element key, e.g. `heading`, `h2` or `button`.
* @param blockNames Block types that paint the element.
* @return Block names, in the given order.
*/
function getOverridingBlockTypes(config, element, blockNames) {
if (!blockNames.length || !config?.styles) return [];
const elements = getElementKeys(element);
const { sources: elementSources } = resolveStyle(config, {
blockName: ELEMENT_ONLY_BLOCK_NAME,
elements
});
const elementPaths = Object.keys(elementSources).filter((path) => elementSources[path].layer === "element");
return blockNames.filter((blockName) => {
const { sources } = resolveStyle(config, {
blockName,
elements
});
return Object.keys(sources).some((path) => isOwnStylePath(path) && sources[path].layer === "block" && elementPaths.some((elementPath) => setsSameProperty(path, elementPath)));
});
}
exports.RESPONSIVE_STATES = RESPONSIVE_STATES;
exports.VALID_BLOCK_STATES = VALID_BLOCK_STATES;
exports.VALID_ELEMENT_STATES = VALID_ELEMENT_STATES;
exports.filterObjectByProperties = filterObjectByProperties;
exports.getFontFamilies = getFontFamilies;
exports.getNewIndexFromPresets = getNewIndexFromPresets;
exports.getOverridingBlockTypes = getOverridingBlockTypes;
exports.getValidPseudoStates = getValidPseudoStates;
exports.getValidViewportStates = getValidViewportStates;
exports.getVariationClassName = getVariationClassName;
exports.isVariationWithProperties = isVariationWithProperties;
exports.removePropertiesFromObject = removePropertiesFromObject;
//# sourceMappingURL=utils.cjs.map