UNPKG

@wordpress/global-styles-ui

Version:
170 lines (169 loc) • 7.05 kB
import { useCallback, useContext, useMemo } from "@wordpress/element"; import { useSelect } from "@wordpress/data"; import { store } from "@wordpress/core-data"; import { __ } from "@wordpress/i18n"; import { getResolvedValue, getSetting, getStyle, mergeGlobalStyles, setSetting, setStyle } from "@wordpress/global-styles-engine"; import { GlobalStylesContext } from "./context.mjs"; import { isVariationWithProperties, removePropertiesFromObject } from "./utils.mjs"; // 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 } = useContext(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 [useMemo(() => { const rawValue = getStyle(sourceValue, stylePath, blockName, shouldDecodeEncode); if (pseudoSelectorState) return rawValue?.[pseudoSelectorState] ?? {}; return rawValue; }, [ sourceValue, stylePath, blockName, shouldDecodeEncode, pseudoSelectorState ]), useCallback((newValue) => { let valueToSet = newValue; if (pseudoSelectorState) valueToSet = { ...getStyle(user, stylePath, blockName, false), [pseudoSelectorState]: newValue }; const newGlobalStyles = 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 } = useContext(GlobalStylesContext); let sourceValue = merged; if (readFrom === "base") sourceValue = base; else if (readFrom === "user") sourceValue = user; return [useMemo(() => getSetting(sourceValue, path, blockName), [ sourceValue, path, blockName ]), useCallback((newValue) => { const newGlobalStyles = 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 === __("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 } = useSelect((select) => { return { variationsFromTheme: select(store).__experimentalGetCurrentThemeGlobalStylesVariations?.() || EMPTY_ARRAY }; }, []); const { user: userVariation } = useContext(GlobalStylesContext); return useMemo(() => { const clonedUserVariation = structuredClone(userVariation); const userVariationWithoutProperties = removePropertiesFromObject(clonedUserVariation, properties); userVariationWithoutProperties.title = __("Default"); const variationsByProperties = [userVariationWithoutProperties, ...variationsFromTheme.filter((variation) => { return isVariationWithProperties(variation, properties); }).map((variation) => { return 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 } = useContext(GlobalStylesContext); return 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] = 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 useSelect((select) => { const { getEntityRecord, __experimentalGetCurrentGlobalStylesId } = select(store); const globalStylesId = __experimentalGetCurrentGlobalStylesId(); return !!(globalStylesId ? getEntityRecord("root", "globalStyles", globalStylesId) : void 0)?._links?.["wp:action-edit-css"]; }, []); } export { useCanEditCSS, useCurrentMergeThemeStyleVariationsWithUserConfig, useSetting, useStyle, useStyleWithResolvedBackground }; //# sourceMappingURL=hooks.mjs.map