@wordpress/global-styles-ui
Version:
Global Styles UI components for WordPress.
179 lines (178 loc) • 7.96 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_element = require("@wordpress/element");
let _wordpress_data = require("@wordpress/data");
let _wordpress_core_data = require("@wordpress/core-data");
let _wordpress_i18n = require("@wordpress/i18n");
let _wordpress_global_styles_engine = require("@wordpress/global-styles-engine");
let __context_ts = require("./context.cjs");
let __utils_ts = require("./utils.cjs");
// packages/global-styles-ui/src/hooks.ts
/**
* Hook to get and set style values with memoization.
*
* @param path The path to the style value.
* @param blockName The name of the block, if applicable.
* @param readFrom Which source to read from: "base" (theme), "user" (customizations), or "merged" (final result). Defaults to "merged".
* @param shouldDecodeEncode Whether to decode and encode the style value.
* @param state Optional style state path. Supports viewport states (e.g. `@mobile`),
* pseudo-selector states (e.g. `:hover`) or both (e.g. `@mobile.:hover`).
* Pseudo selectors are always read/written as nested keys.
* @return An array containing the style value and a function to set the style
* value.
*
* @example
* const [ color, setColor ] = useStyle<string>( 'color.text', 'core/button', 'merged' );
* const [ hoverColor, setHoverColor ] = useStyle<string>( 'color.text', 'core/button', 'user', true, ':hover' );
*/
function useStyle(path, blockName, readFrom = "merged", shouldDecodeEncode = true, state) {
const { user, base, merged, onChange } = (0, _wordpress_element.useContext)(__context_ts.GlobalStylesContext);
const statePathParts = state?.split(".").filter(Boolean) ?? [];
const pseudoSelectorState = statePathParts.find((value) => value.startsWith(":"));
const stylePath = [path, statePathParts.filter((value) => !value.startsWith(":")).join(".")].filter(Boolean).join(".");
let sourceValue = merged;
if (readFrom === "base") sourceValue = base;
else if (readFrom === "user") sourceValue = user;
return [(0, _wordpress_element.useMemo)(() => {
const rawValue = (0, _wordpress_global_styles_engine.getStyle)(sourceValue, stylePath, blockName, shouldDecodeEncode);
if (pseudoSelectorState) return rawValue?.[pseudoSelectorState] ?? {};
return rawValue;
}, [
sourceValue,
stylePath,
blockName,
shouldDecodeEncode,
pseudoSelectorState
]), (0, _wordpress_element.useCallback)((newValue) => {
let valueToSet = newValue;
if (pseudoSelectorState) valueToSet = {
...(0, _wordpress_global_styles_engine.getStyle)(user, stylePath, blockName, false),
[pseudoSelectorState]: newValue
};
const newGlobalStyles = (0, _wordpress_global_styles_engine.setStyle)(user, stylePath, valueToSet, blockName);
onChange(newGlobalStyles);
}, [
user,
onChange,
stylePath,
blockName,
pseudoSelectorState
])];
}
/**
* Hook to get and set setting values with memoization.
*
* @param path The path to the setting value.
* @param blockName The name of the block, if applicable.
* @param readFrom Which source to read from: "base" (theme), "user" (customizations), or "merged" (final result). Defaults to "merged".
* @return An array containing the setting value and a function to set the
* setting value.
*
* @example
* const [ fontSize, setFontSize ] = useSetting<string>( 'fontSize', 'core/button', 'merged' );
*/
function useSetting(path, blockName, readFrom = "merged") {
const { user, base, merged, onChange } = (0, _wordpress_element.useContext)(__context_ts.GlobalStylesContext);
let sourceValue = merged;
if (readFrom === "base") sourceValue = base;
else if (readFrom === "user") sourceValue = user;
return [(0, _wordpress_element.useMemo)(() => (0, _wordpress_global_styles_engine.getSetting)(sourceValue, path, blockName), [
sourceValue,
path,
blockName
]), (0, _wordpress_element.useCallback)((newValue) => {
const newGlobalStyles = (0, _wordpress_global_styles_engine.setSetting)(user, path, newValue, blockName);
onChange(newGlobalStyles);
}, [
user,
onChange,
path,
blockName
])];
}
const EMPTY_ARRAY = [];
/**
* Checks whether a style variation is empty.
* @param root0
* @param root0.title
* @param root0.settings
* @param root0.styles
*/
function hasThemeVariation({ title, settings, styles }) {
return title === (0, _wordpress_i18n.__)("Default") || Object.keys(settings || {}).length > 0 || Object.keys(styles || {}).length > 0;
}
/**
* Fetches the current theme style variations that contain only the specified properties
* and merges them with the user config.
* @param properties
*/
function useCurrentMergeThemeStyleVariationsWithUserConfig(properties = []) {
const { variationsFromTheme } = (0, _wordpress_data.useSelect)((select) => {
return { variationsFromTheme: select(_wordpress_core_data.store).__experimentalGetCurrentThemeGlobalStylesVariations?.() || EMPTY_ARRAY };
}, []);
const { user: userVariation } = (0, _wordpress_element.useContext)(__context_ts.GlobalStylesContext);
return (0, _wordpress_element.useMemo)(() => {
const clonedUserVariation = structuredClone(userVariation);
const userVariationWithoutProperties = (0, __utils_ts.removePropertiesFromObject)(clonedUserVariation, properties);
userVariationWithoutProperties.title = (0, _wordpress_i18n.__)("Default");
const variationsByProperties = [userVariationWithoutProperties, ...variationsFromTheme.filter((variation) => {
return (0, __utils_ts.isVariationWithProperties)(variation, properties);
}).map((variation) => {
return (0, _wordpress_global_styles_engine.mergeGlobalStyles)(userVariationWithoutProperties, variation);
})];
return variationsByProperties?.length ? variationsByProperties.filter(hasThemeVariation) : [];
}, [
properties,
userVariation,
variationsFromTheme
]);
}
/**
* Resolves `ref` pointers and theme-relative (`file:./…`) URLs in a style
* object's `background` sub-tree, for display. The Global Styles screens
* render inside the package's own public `BlockEditorProvider`, which strips
* the Symbol-keyed settings the background panel would otherwise resolve
* these against, so the screens resolve them before passing styles down.
*
* @param style A style object whose `background` values may contain `ref`
* pointers or theme-relative URLs.
* @return The style object with its `background` values resolved.
*/
function useStyleWithResolvedBackground(style) {
const { merged } = (0, _wordpress_element.useContext)(__context_ts.GlobalStylesContext);
return (0, _wordpress_element.useMemo)(() => {
if (!style?.background) return style;
const tree = {
styles: merged?.styles,
_links: merged?._links
};
const background = {};
for (const [key, value] of Object.entries(style.background)) background[key] = (0, _wordpress_global_styles_engine.getResolvedValue)(value && typeof value === "object" ? { ...value } : value, tree);
return {
...style,
background
};
}, [style, merged]);
}
/**
* Whether the current user may edit custom CSS in Global Styles.
*
* The capability is reported as a link on the global styles record rather
* than as a user capability.
*/
function useCanEditCSS() {
return (0, _wordpress_data.useSelect)((select) => {
const { getEntityRecord, __experimentalGetCurrentGlobalStylesId } = select(_wordpress_core_data.store);
const globalStylesId = __experimentalGetCurrentGlobalStylesId();
return !!(globalStylesId ? getEntityRecord("root", "globalStyles", globalStylesId) : void 0)?._links?.["wp:action-edit-css"];
}, []);
}
exports.useCanEditCSS = useCanEditCSS;
exports.useCurrentMergeThemeStyleVariationsWithUserConfig = useCurrentMergeThemeStyleVariationsWithUserConfig;
exports.useSetting = useSetting;
exports.useStyle = useStyle;
exports.useStyleWithResolvedBackground = useStyleWithResolvedBackground;
//# sourceMappingURL=hooks.cjs.map